diff --git a/C/7z.h b/C/7z.h index 304f75ff..9e27c015 100644 --- a/C/7z.h +++ b/C/7z.h @@ -1,8 +1,8 @@ /* 7z.h -- 7z interface -2018-07-02 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_H -#define __7Z_H +#ifndef ZIP7_INC_7Z_H +#define ZIP7_INC_7Z_H #include "7zTypes.h" @@ -98,7 +98,7 @@ typedef struct UInt64 SzAr_GetFolderUnpackSize(const CSzAr *p, UInt32 folderIndex); SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, - ILookInStream *stream, UInt64 startPos, + ILookInStreamPtr stream, UInt64 startPos, Byte *outBuffer, size_t outSize, ISzAllocPtr allocMain); @@ -174,7 +174,7 @@ UInt16 *SzArEx_GetFullNameUtf16_Back(const CSzArEx *p, size_t fileIndex, UInt16 SRes SzArEx_Extract( const CSzArEx *db, - ILookInStream *inStream, + ILookInStreamPtr inStream, UInt32 fileIndex, /* index of file */ UInt32 *blockIndex, /* index of solid block */ Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */ @@ -196,7 +196,7 @@ SZ_ERROR_INPUT_EOF SZ_ERROR_FAIL */ -SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, +SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp); EXTERN_C_END diff --git a/C/7zAlloc.c b/C/7zAlloc.c index c924a529..2f0659af 100644 --- a/C/7zAlloc.c +++ b/C/7zAlloc.c @@ -1,5 +1,5 @@ -/* 7zAlloc.c -- Allocation functions -2017-04-03 : Igor Pavlov : Public domain */ +/* 7zAlloc.c -- Allocation functions for 7z processing +2023-03-04 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -7,74 +7,83 @@ #include "7zAlloc.h" -/* #define _SZ_ALLOC_DEBUG */ -/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ +/* #define SZ_ALLOC_DEBUG */ +/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ -#ifdef _SZ_ALLOC_DEBUG +#ifdef SZ_ALLOC_DEBUG +/* #ifdef _WIN32 -#include +#include "7zWindows.h" #endif +*/ #include -int g_allocCount = 0; -int g_allocCountTemp = 0; +static int g_allocCount = 0; +static int g_allocCountTemp = 0; +static void Print_Alloc(const char *s, size_t size, int *counter) +{ + const unsigned size2 = (unsigned)size; + fprintf(stderr, "\n%s count = %10d : %10u bytes; ", s, *counter, size2); + (*counter)++; +} +static void Print_Free(const char *s, int *counter) +{ + (*counter)--; + fprintf(stderr, "\n%s count = %10d", s, *counter); +} #endif void *SzAlloc(ISzAllocPtr p, size_t size) { - UNUSED_VAR(p); + UNUSED_VAR(p) if (size == 0) return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc %10u bytes; count = %10d", (unsigned)size, g_allocCount); - g_allocCount++; + #ifdef SZ_ALLOC_DEBUG + Print_Alloc("Alloc", size, &g_allocCount); #endif return malloc(size); } void SzFree(ISzAllocPtr p, void *address) { - UNUSED_VAR(p); - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - { - g_allocCount--; - fprintf(stderr, "\nFree; count = %10d", g_allocCount); - } + UNUSED_VAR(p) + #ifdef SZ_ALLOC_DEBUG + if (address) + Print_Free("Free ", &g_allocCount); #endif free(address); } void *SzAllocTemp(ISzAllocPtr p, size_t size) { - UNUSED_VAR(p); + UNUSED_VAR(p) if (size == 0) return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc_temp %10u bytes; count = %10d", (unsigned)size, g_allocCountTemp); - g_allocCountTemp++; + #ifdef SZ_ALLOC_DEBUG + Print_Alloc("Alloc_temp", size, &g_allocCountTemp); + /* #ifdef _WIN32 return HeapAlloc(GetProcessHeap(), 0, size); #endif + */ #endif return malloc(size); } void SzFreeTemp(ISzAllocPtr p, void *address) { - UNUSED_VAR(p); - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - { - g_allocCountTemp--; - fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp); - } + UNUSED_VAR(p) + #ifdef SZ_ALLOC_DEBUG + if (address) + Print_Free("Free_temp ", &g_allocCountTemp); + /* #ifdef _WIN32 HeapFree(GetProcessHeap(), 0, address); return; #endif + */ #endif free(address); } diff --git a/C/7zAlloc.h b/C/7zAlloc.h index 44778f9b..b2b8b0cd 100644 --- a/C/7zAlloc.h +++ b/C/7zAlloc.h @@ -1,8 +1,8 @@ /* 7zAlloc.h -- Allocation functions -2017-04-03 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __7Z_ALLOC_H -#define __7Z_ALLOC_H +#ifndef ZIP7_INC_7Z_ALLOC_H +#define ZIP7_INC_7Z_ALLOC_H #include "7zTypes.h" diff --git a/C/7zArcIn.c b/C/7zArcIn.c index 0d9dec41..43fa7c21 100644 --- a/C/7zArcIn.c +++ b/C/7zArcIn.c @@ -1,5 +1,5 @@ /* 7zArcIn.c -- 7z Input functions -2021-02-09 : Igor Pavlov : Public domain */ +2023-05-11 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -10,10 +10,11 @@ #include "7zCrc.h" #include "CpuArch.h" -#define MY_ALLOC(T, p, size, alloc) { \ - if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } +#define MY_ALLOC(T, p, size, alloc) \ + { if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } -#define MY_ALLOC_ZE(T, p, size, alloc) { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } +#define MY_ALLOC_ZE(T, p, size, alloc) \ + { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } #define MY_ALLOC_AND_CPY(to, size, from, alloc) \ { MY_ALLOC(Byte, to, size, alloc); memcpy(to, from, size); } @@ -58,7 +59,7 @@ enum EIdEnum const Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; -#define SzBitUi32s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } +#define SzBitUi32s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) { @@ -69,8 +70,8 @@ static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) } else { - MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc); - MY_ALLOC(UInt32, p->Vals, num, alloc); + MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc) + MY_ALLOC(UInt32, p->Vals, num, alloc) } return SZ_OK; } @@ -81,7 +82,7 @@ static void SzBitUi32s_Free(CSzBitUi32s *p, ISzAllocPtr alloc) ISzAlloc_Free(alloc, p->Vals); p->Vals = NULL; } -#define SzBitUi64s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } +#define SzBitUi64s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; } static void SzBitUi64s_Free(CSzBitUi64s *p, ISzAllocPtr alloc) { @@ -96,7 +97,7 @@ static void SzAr_Init(CSzAr *p) p->NumFolders = 0; p->PackPositions = NULL; - SzBitUi32s_Init(&p->FolderCRCs); + SzBitUi32s_INIT(&p->FolderCRCs) p->FoCodersOffsets = NULL; p->FoStartPackStreamIndex = NULL; @@ -142,11 +143,11 @@ void SzArEx_Init(CSzArEx *p) p->FileNameOffsets = NULL; p->FileNames = NULL; - SzBitUi32s_Init(&p->CRCs); - SzBitUi32s_Init(&p->Attribs); - // SzBitUi32s_Init(&p->Parents); - SzBitUi64s_Init(&p->MTime); - SzBitUi64s_Init(&p->CTime); + SzBitUi32s_INIT(&p->CRCs) + SzBitUi32s_INIT(&p->Attribs) + // SzBitUi32s_INIT(&p->Parents) + SzBitUi64s_INIT(&p->MTime) + SzBitUi64s_INIT(&p->CTime) } void SzArEx_Free(CSzArEx *p, ISzAllocPtr alloc) @@ -180,11 +181,20 @@ static int TestSignatureCandidate(const Byte *testBytes) return 1; } -#define SzData_Clear(p) { (p)->Data = NULL; (p)->Size = 0; } +#define SzData_CLEAR(p) { (p)->Data = NULL; (p)->Size = 0; } + +#define SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) \ + (_sd_)->Size--; dest = *(_sd_)->Data++; + +#define SZ_READ_BYTE_SD(_sd_, dest) \ + if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; \ + SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) -#define SZ_READ_BYTE_SD(_sd_, dest) if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; (_sd_)->Size--; dest = *(_sd_)->Data++; #define SZ_READ_BYTE(dest) SZ_READ_BYTE_SD(sd, dest) -#define SZ_READ_BYTE_2(dest) if (sd.Size == 0) return SZ_ERROR_ARCHIVE; sd.Size--; dest = *sd.Data++; + +#define SZ_READ_BYTE_2(dest) \ + if (sd.Size == 0) return SZ_ERROR_ARCHIVE; \ + sd.Size--; dest = *sd.Data++; #define SKIP_DATA(sd, size) { sd->Size -= (size_t)(size); sd->Data += (size_t)(size); } #define SKIP_DATA2(sd, size) { sd.Size -= (size_t)(size); sd.Data += (size_t)(size); } @@ -192,25 +202,25 @@ static int TestSignatureCandidate(const Byte *testBytes) #define SZ_READ_32(dest) if (sd.Size < 4) return SZ_ERROR_ARCHIVE; \ dest = GetUi32(sd.Data); SKIP_DATA2(sd, 4); -static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) +static Z7_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) { Byte firstByte, mask; unsigned i; UInt32 v; - SZ_READ_BYTE(firstByte); + SZ_READ_BYTE(firstByte) if ((firstByte & 0x80) == 0) { *value = firstByte; return SZ_OK; } - SZ_READ_BYTE(v); + SZ_READ_BYTE(v) if ((firstByte & 0x40) == 0) { *value = (((UInt32)firstByte & 0x3F) << 8) | v; return SZ_OK; } - SZ_READ_BYTE(mask); + SZ_READ_BYTE(mask) *value = v | ((UInt32)mask << 8); mask = 0x20; for (i = 2; i < 8; i++) @@ -218,11 +228,11 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) Byte b; if ((firstByte & mask) == 0) { - UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); + const UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); *value |= (highPart << (8 * i)); return SZ_OK; } - SZ_READ_BYTE(b); + SZ_READ_BYTE(b) *value |= ((UInt64)b << (8 * i)); mask >>= 1; } @@ -230,7 +240,7 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) } -static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) +static Z7_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) { Byte firstByte; UInt64 value64; @@ -244,7 +254,7 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) sd->Size--; return SZ_OK; } - RINOK(ReadNumber(sd, &value64)); + RINOK(ReadNumber(sd, &value64)) if (value64 >= (UInt32)0x80000000 - 1) return SZ_ERROR_UNSUPPORTED; if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 4))) @@ -258,10 +268,10 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) static SRes SkipData(CSzData *sd) { UInt64 size; - RINOK(ReadNumber(sd, &size)); + RINOK(ReadNumber(sd, &size)) if (size > sd->Size) return SZ_ERROR_ARCHIVE; - SKIP_DATA(sd, size); + SKIP_DATA(sd, size) return SZ_OK; } @@ -270,22 +280,22 @@ static SRes WaitId(CSzData *sd, UInt32 id) for (;;) { UInt64 type; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == id) return SZ_OK; if (type == k7zIdEnd) return SZ_ERROR_ARCHIVE; - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } } static SRes RememberBitVector(CSzData *sd, UInt32 numItems, const Byte **v) { - UInt32 numBytes = (numItems + 7) >> 3; + const UInt32 numBytes = (numItems + 7) >> 3; if (numBytes > sd->Size) return SZ_ERROR_ARCHIVE; *v = sd->Data; - SKIP_DATA(sd, numBytes); + SKIP_DATA(sd, numBytes) return SZ_OK; } @@ -307,48 +317,48 @@ static UInt32 CountDefinedBits(const Byte *bits, UInt32 numItems) return sum; } -static MY_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) +static Z7_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) { Byte allAreDefined; Byte *v2; - UInt32 numBytes = (numItems + 7) >> 3; + const UInt32 numBytes = (numItems + 7) >> 3; *v = NULL; - SZ_READ_BYTE(allAreDefined); + SZ_READ_BYTE(allAreDefined) if (numBytes == 0) return SZ_OK; if (allAreDefined == 0) { if (numBytes > sd->Size) return SZ_ERROR_ARCHIVE; - MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc); - SKIP_DATA(sd, numBytes); + MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc) + SKIP_DATA(sd, numBytes) return SZ_OK; } - MY_ALLOC(Byte, *v, numBytes, alloc); + MY_ALLOC(Byte, *v, numBytes, alloc) v2 = *v; memset(v2, 0xFF, (size_t)numBytes); { - unsigned numBits = (unsigned)numItems & 7; + const unsigned numBits = (unsigned)numItems & 7; if (numBits != 0) v2[(size_t)numBytes - 1] = (Byte)((((UInt32)1 << numBits) - 1) << (8 - numBits)); } return SZ_OK; } -static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) +static Z7_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) { UInt32 i; CSzData sd; UInt32 *vals; const Byte *defs; - MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc); + MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc) sd = *sd2; defs = crcs->Defs; vals = crcs->Vals; for (i = 0; i < numItems; i++) if (SzBitArray_Check(defs, i)) { - SZ_READ_32(vals[i]); + SZ_READ_32(vals[i]) } else vals[i] = 0; @@ -359,7 +369,7 @@ static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *c static SRes ReadBitUi32s(CSzData *sd, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) { SzBitUi32s_Free(crcs, alloc); - RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)); + RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)) return ReadUi32s(sd, numItems, crcs, alloc); } @@ -367,36 +377,36 @@ static SRes SkipBitUi32s(CSzData *sd, UInt32 numItems) { Byte allAreDefined; UInt32 numDefined = numItems; - SZ_READ_BYTE(allAreDefined); + SZ_READ_BYTE(allAreDefined) if (!allAreDefined) { - size_t numBytes = (numItems + 7) >> 3; + const size_t numBytes = (numItems + 7) >> 3; if (numBytes > sd->Size) return SZ_ERROR_ARCHIVE; numDefined = CountDefinedBits(sd->Data, numItems); - SKIP_DATA(sd, numBytes); + SKIP_DATA(sd, numBytes) } if (numDefined > (sd->Size >> 2)) return SZ_ERROR_ARCHIVE; - SKIP_DATA(sd, (size_t)numDefined * 4); + SKIP_DATA(sd, (size_t)numDefined * 4) return SZ_OK; } static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) { - RINOK(SzReadNumber32(sd, &p->NumPackStreams)); + RINOK(SzReadNumber32(sd, &p->NumPackStreams)) - RINOK(WaitId(sd, k7zIdSize)); - MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc); + RINOK(WaitId(sd, k7zIdSize)) + MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc) { UInt64 sum = 0; UInt32 i; - UInt32 numPackStreams = p->NumPackStreams; + const UInt32 numPackStreams = p->NumPackStreams; for (i = 0; i < numPackStreams; i++) { UInt64 packSize; p->PackPositions[i] = sum; - RINOK(ReadNumber(sd, &packSize)); + RINOK(ReadNumber(sd, &packSize)) sum += packSize; if (sum < packSize) return SZ_ERROR_ARCHIVE; @@ -407,16 +417,16 @@ static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) for (;;) { UInt64 type; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdEnd) return SZ_OK; if (type == k7zIdCRC) { /* CRC of packed streams is unused now */ - RINOK(SkipBitUi32s(sd, p->NumPackStreams)); + RINOK(SkipBitUi32s(sd, p->NumPackStreams)) continue; } - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } } @@ -442,7 +452,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) f->NumPackStreams = 0; f->UnpackStream = 0; - RINOK(SzReadNumber32(sd, &numCoders)); + RINOK(SzReadNumber32(sd, &numCoders)) if (numCoders == 0 || numCoders > SZ_NUM_CODERS_IN_FOLDER_MAX) return SZ_ERROR_UNSUPPORTED; @@ -453,7 +463,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) unsigned idSize, j; UInt64 id; - SZ_READ_BYTE(mainByte); + SZ_READ_BYTE(mainByte) if ((mainByte & 0xC0) != 0) return SZ_ERROR_UNSUPPORTED; @@ -481,12 +491,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) { UInt32 numStreams; - RINOK(SzReadNumber32(sd, &numStreams)); + RINOK(SzReadNumber32(sd, &numStreams)) if (numStreams > k_NumCodersStreams_in_Folder_MAX) return SZ_ERROR_UNSUPPORTED; coder->NumStreams = (Byte)numStreams; - RINOK(SzReadNumber32(sd, &numStreams)); + RINOK(SzReadNumber32(sd, &numStreams)) if (numStreams != 1) return SZ_ERROR_UNSUPPORTED; } @@ -499,7 +509,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) if ((mainByte & 0x20) != 0) { UInt32 propsSize = 0; - RINOK(SzReadNumber32(sd, &propsSize)); + RINOK(SzReadNumber32(sd, &propsSize)) if (propsSize > sd->Size) return SZ_ERROR_ARCHIVE; if (propsSize >= 0x80) @@ -549,12 +559,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) { CSzBond *bp = f->Bonds + i; - RINOK(SzReadNumber32(sd, &bp->InIndex)); + RINOK(SzReadNumber32(sd, &bp->InIndex)) if (bp->InIndex >= numInStreams || streamUsed[bp->InIndex]) return SZ_ERROR_ARCHIVE; streamUsed[bp->InIndex] = 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 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) for (i = 0; i < numPackStreams; i++) { UInt32 index; - RINOK(SzReadNumber32(sd, &index)); + RINOK(SzReadNumber32(sd, &index)) if (index >= numInStreams || streamUsed[index]) return SZ_ERROR_ARCHIVE; streamUsed[index] = True; @@ -598,7 +608,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd) } -static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) +static Z7_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) { CSzData sd; sd = *sd2; @@ -606,7 +616,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) { Byte firstByte, mask; unsigned i; - SZ_READ_BYTE_2(firstByte); + SZ_READ_BYTE_2(firstByte) if ((firstByte & 0x80) == 0) continue; if ((firstByte & 0x40) == 0) @@ -622,7 +632,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) mask >>= 1; if (i > sd.Size) return SZ_ERROR_ARCHIVE; - SKIP_DATA2(sd, i); + SKIP_DATA2(sd, i) } *sd2 = sd; return SZ_OK; @@ -645,30 +655,30 @@ static SRes ReadUnpackInfo(CSzAr *p, const Byte *startBufPtr; Byte external; - RINOK(WaitId(sd2, k7zIdFolder)); + RINOK(WaitId(sd2, k7zIdFolder)) - RINOK(SzReadNumber32(sd2, &numFolders)); + RINOK(SzReadNumber32(sd2, &numFolders)) if (numFolders > numFoldersMax) return SZ_ERROR_UNSUPPORTED; p->NumFolders = numFolders; - SZ_READ_BYTE_SD(sd2, external); + SZ_READ_BYTE_SD(sd2, external) if (external == 0) sd = *sd2; else { UInt32 index; - RINOK(SzReadNumber32(sd2, &index)); + RINOK(SzReadNumber32(sd2, &index)) if (index >= numTempBufs) return SZ_ERROR_ARCHIVE; sd.Data = tempBufs[index].data; sd.Size = tempBufs[index].size; } - MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc); - MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc); - MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc); - MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc); + MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc) + MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc) + MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc) + MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc) startBufPtr = sd.Data; @@ -681,7 +691,7 @@ static SRes ReadUnpackInfo(CSzAr *p, p->FoCodersOffsets[fo] = (size_t)(sd.Data - startBufPtr); - RINOK(SzReadNumber32(&sd, &numCoders)); + RINOK(SzReadNumber32(&sd, &numCoders)) if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) return SZ_ERROR_UNSUPPORTED; @@ -691,7 +701,7 @@ static SRes ReadUnpackInfo(CSzAr *p, unsigned idSize; UInt32 coderInStreams; - SZ_READ_BYTE_2(mainByte); + SZ_READ_BYTE_2(mainByte) if ((mainByte & 0xC0) != 0) return SZ_ERROR_UNSUPPORTED; idSize = (mainByte & 0xF); @@ -699,15 +709,15 @@ static SRes ReadUnpackInfo(CSzAr *p, return SZ_ERROR_UNSUPPORTED; if (idSize > sd.Size) return SZ_ERROR_ARCHIVE; - SKIP_DATA2(sd, idSize); + SKIP_DATA2(sd, idSize) coderInStreams = 1; if ((mainByte & 0x10) != 0) { UInt32 coderOutStreams; - RINOK(SzReadNumber32(&sd, &coderInStreams)); - RINOK(SzReadNumber32(&sd, &coderOutStreams)); + RINOK(SzReadNumber32(&sd, &coderInStreams)) + RINOK(SzReadNumber32(&sd, &coderOutStreams)) if (coderInStreams > k_Scan_NumCodersStreams_in_Folder_MAX || coderOutStreams != 1) return SZ_ERROR_UNSUPPORTED; } @@ -717,10 +727,10 @@ static SRes ReadUnpackInfo(CSzAr *p, if ((mainByte & 0x20) != 0) { UInt32 propsSize; - RINOK(SzReadNumber32(&sd, &propsSize)); + RINOK(SzReadNumber32(&sd, &propsSize)) if (propsSize > sd.Size) return SZ_ERROR_ARCHIVE; - SKIP_DATA2(sd, propsSize); + SKIP_DATA2(sd, propsSize) } } @@ -734,7 +744,7 @@ static SRes ReadUnpackInfo(CSzAr *p, Byte coderUsed[k_Scan_NumCoders_MAX]; UInt32 i; - UInt32 numBonds = numCoders - 1; + const UInt32 numBonds = numCoders - 1; if (numInStreams < numBonds) return SZ_ERROR_ARCHIVE; @@ -750,12 +760,12 @@ static SRes ReadUnpackInfo(CSzAr *p, { UInt32 index; - RINOK(SzReadNumber32(&sd, &index)); + RINOK(SzReadNumber32(&sd, &index)) if (index >= numInStreams || streamUsed[index]) return SZ_ERROR_ARCHIVE; streamUsed[index] = 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 @@ static SRes ReadUnpackInfo(CSzAr *p, for (i = 0; i < numPackStreams; i++) { UInt32 index; - RINOK(SzReadNumber32(&sd, &index)); + RINOK(SzReadNumber32(&sd, &index)) if (index >= numInStreams || streamUsed[index]) return SZ_ERROR_ARCHIVE; streamUsed[index] = True; @@ -802,7 +812,7 @@ static SRes ReadUnpackInfo(CSzAr *p, const size_t dataSize = (size_t)(sd.Data - startBufPtr); p->FoStartPackStreamIndex[fo] = packStreamIndex; p->FoCodersOffsets[fo] = dataSize; - MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc); + MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc) } if (external != 0) @@ -812,21 +822,21 @@ static SRes ReadUnpackInfo(CSzAr *p, sd = *sd2; } - RINOK(WaitId(&sd, k7zIdCodersUnpackSize)); + RINOK(WaitId(&sd, k7zIdCodersUnpackSize)) - MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc); + MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc) { UInt32 i; for (i = 0; i < numCodersOutStreams; i++) { - RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)); + RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)) } } for (;;) { UInt64 type; - RINOK(ReadID(&sd, &type)); + RINOK(ReadID(&sd, &type)) if (type == k7zIdEnd) { *sd2 = sd; @@ -834,10 +844,10 @@ static SRes ReadUnpackInfo(CSzAr *p, } if (type == k7zIdCRC) { - RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)); + RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)) continue; } - RINOK(SkipData(&sd)); + RINOK(SkipData(&sd)) } } @@ -862,13 +872,13 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) { UInt64 type = 0; UInt32 numSubDigests = 0; - UInt32 numFolders = p->NumFolders; + const UInt32 numFolders = p->NumFolders; UInt32 numUnpackStreams = numFolders; UInt32 numUnpackSizesInData = 0; for (;;) { - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdNumUnpackStream) { UInt32 i; @@ -878,7 +888,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) for (i = 0; i < numFolders; i++) { UInt32 numStreams; - RINOK(SzReadNumber32(sd, &numStreams)); + RINOK(SzReadNumber32(sd, &numStreams)) if (numUnpackStreams > numUnpackStreams + numStreams) return SZ_ERROR_UNSUPPORTED; numUnpackStreams += numStreams; @@ -892,7 +902,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) } if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd) break; - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } if (!ssi->sdNumSubStreams.Data) @@ -908,9 +918,9 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) if (type == k7zIdSize) { ssi->sdSizes.Data = sd->Data; - RINOK(SkipNumbers(sd, numUnpackSizesInData)); + RINOK(SkipNumbers(sd, numUnpackSizesInData)) ssi->sdSizes.Size = (size_t)(sd->Data - ssi->sdSizes.Data); - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } for (;;) @@ -920,14 +930,14 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi) if (type == k7zIdCRC) { ssi->sdCRCs.Data = sd->Data; - RINOK(SkipBitUi32s(sd, numSubDigests)); + RINOK(SkipBitUi32s(sd, numSubDigests)) ssi->sdCRCs.Size = (size_t)(sd->Data - ssi->sdCRCs.Data); } else { - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } } @@ -940,31 +950,31 @@ static SRes SzReadStreamsInfo(CSzAr *p, { UInt64 type; - SzData_Clear(&ssi->sdSizes); - SzData_Clear(&ssi->sdCRCs); - SzData_Clear(&ssi->sdNumSubStreams); + SzData_CLEAR(&ssi->sdSizes) + SzData_CLEAR(&ssi->sdCRCs) + SzData_CLEAR(&ssi->sdNumSubStreams) *dataOffset = 0; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdPackInfo) { - RINOK(ReadNumber(sd, dataOffset)); + RINOK(ReadNumber(sd, dataOffset)) if (*dataOffset > p->RangeLimit) return SZ_ERROR_ARCHIVE; - RINOK(ReadPackInfo(p, sd, alloc)); + RINOK(ReadPackInfo(p, sd, alloc)) if (p->PackPositions[p->NumPackStreams] > p->RangeLimit - *dataOffset) return SZ_ERROR_ARCHIVE; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } if (type == k7zIdUnpackInfo) { - RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)); - RINOK(ReadID(sd, &type)); + RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)) + RINOK(ReadID(sd, &type)) } if (type == k7zIdSubStreamsInfo) { - RINOK(ReadSubStreamsInfo(p, sd, ssi)); - RINOK(ReadID(sd, &type)); + RINOK(ReadSubStreamsInfo(p, sd, ssi)) + RINOK(ReadID(sd, &type)) } else { @@ -976,7 +986,7 @@ static SRes SzReadStreamsInfo(CSzAr *p, } static SRes SzReadAndDecodePackedStreams( - ILookInStream *inStream, + ILookInStreamPtr inStream, CSzData *sd, CBuf *tempBufs, UInt32 numFoldersMax, @@ -988,7 +998,7 @@ static SRes SzReadAndDecodePackedStreams( UInt32 fo; CSubStreamInfo ssi; - RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)); + RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)) dataStartPos += baseOffset; if (p->NumFolders == 0) @@ -1000,7 +1010,7 @@ static SRes SzReadAndDecodePackedStreams( for (fo = 0; fo < p->NumFolders; fo++) { CBuf *tempBuf = tempBufs + fo; - UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); + const UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); if ((size_t)unpackSize != unpackSize) return SZ_ERROR_MEM; if (!Buf_Create(tempBuf, (size_t)unpackSize, allocTemp)) @@ -1010,8 +1020,8 @@ static SRes SzReadAndDecodePackedStreams( for (fo = 0; fo < p->NumFolders; fo++) { const CBuf *tempBuf = tempBufs + fo; - RINOK(LookInStream_SeekTo(inStream, dataStartPos)); - RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)); + RINOK(LookInStream_SeekTo(inStream, dataStartPos)) + RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)) } return SZ_OK; @@ -1046,7 +1056,7 @@ static SRes SzReadFileNames(const Byte *data, size_t size, UInt32 numFiles, size return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; } -static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, +static Z7_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, CSzData *sd2, const CBuf *tempBufs, UInt32 numTempBufs, ISzAllocPtr alloc) @@ -1057,22 +1067,22 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, Byte *defs; Byte external; - RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)); + RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)) - SZ_READ_BYTE_SD(sd2, external); + SZ_READ_BYTE_SD(sd2, external) if (external == 0) sd = *sd2; else { UInt32 index; - RINOK(SzReadNumber32(sd2, &index)); + RINOK(SzReadNumber32(sd2, &index)) if (index >= numTempBufs) return SZ_ERROR_ARCHIVE; sd.Data = tempBufs[index].data; sd.Size = tempBufs[index].size; } - MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc); + MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc) vals = p->Vals; defs = p->Defs; for (i = 0; i < num; i++) @@ -1082,7 +1092,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, return SZ_ERROR_ARCHIVE; vals[i].Low = GetUi32(sd.Data); vals[i].High = GetUi32(sd.Data + 4); - SKIP_DATA2(sd, 8); + SKIP_DATA2(sd, 8) } else vals[i].High = vals[i].Low = 0; @@ -1100,7 +1110,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, static SRes SzReadHeader2( CSzArEx *p, /* allocMain */ CSzData *sd, - ILookInStream *inStream, + ILookInStreamPtr inStream, CBuf *tempBufs, UInt32 *numTempBufs, ISzAllocPtr allocMain, ISzAllocPtr allocTemp @@ -1111,26 +1121,26 @@ static SRes SzReadHeader2( { UInt64 type; - SzData_Clear(&ssi.sdSizes); - SzData_Clear(&ssi.sdCRCs); - SzData_Clear(&ssi.sdNumSubStreams); + SzData_CLEAR(&ssi.sdSizes) + SzData_CLEAR(&ssi.sdCRCs) + SzData_CLEAR(&ssi.sdNumSubStreams) ssi.NumSubDigests = 0; ssi.NumTotalSubStreams = 0; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdArchiveProperties) { for (;;) { UInt64 type2; - RINOK(ReadID(sd, &type2)); + RINOK(ReadID(sd, &type2)) if (type2 == k7zIdEnd) break; - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } if (type == k7zIdAdditionalStreamsInfo) @@ -1148,15 +1158,15 @@ static SRes SzReadHeader2( if (res != SZ_OK) return res; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } if (type == k7zIdMainStreamsInfo) { RINOK(SzReadStreamsInfo(&p->db, sd, (UInt32)1 << 30, tempBufs, *numTempBufs, - &p->dataPos, &ssi, allocMain)); + &p->dataPos, &ssi, allocMain)) p->dataPos += p->startPosAfterHeader; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) } if (type == k7zIdEnd) @@ -1174,23 +1184,23 @@ static SRes SzReadHeader2( const Byte *emptyStreams = NULL; const Byte *emptyFiles = NULL; - RINOK(SzReadNumber32(sd, &numFiles)); + RINOK(SzReadNumber32(sd, &numFiles)) p->NumFiles = numFiles; for (;;) { UInt64 type; UInt64 size; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdEnd) break; - RINOK(ReadNumber(sd, &size)); + RINOK(ReadNumber(sd, &size)) if (size > sd->Size) return SZ_ERROR_ARCHIVE; if (type >= ((UInt32)1 << 8)) { - SKIP_DATA(sd, size); + SKIP_DATA(sd, size) } else switch ((unsigned)type) { @@ -1200,7 +1210,7 @@ static SRes SzReadHeader2( const Byte *namesData; Byte external; - SZ_READ_BYTE(external); + SZ_READ_BYTE(external) if (external == 0) { namesSize = (size_t)size - 1; @@ -1209,7 +1219,7 @@ static SRes SzReadHeader2( else { UInt32 index; - RINOK(SzReadNumber32(sd, &index)); + RINOK(SzReadNumber32(sd, &index)) if (index >= *numTempBufs) return SZ_ERROR_ARCHIVE; namesData = (tempBufs)[index].data; @@ -1218,25 +1228,25 @@ static SRes SzReadHeader2( if ((namesSize & 1) != 0) return SZ_ERROR_ARCHIVE; - MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain); - MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain); + MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain) + MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain) RINOK(SzReadFileNames(p->FileNames, namesSize, numFiles, p->FileNameOffsets)) if (external == 0) { - SKIP_DATA(sd, namesSize); + SKIP_DATA(sd, namesSize) } break; } case k7zIdEmptyStream: { - RINOK(RememberBitVector(sd, numFiles, &emptyStreams)); + RINOK(RememberBitVector(sd, numFiles, &emptyStreams)) numEmptyStreams = CountDefinedBits(emptyStreams, numFiles); emptyFiles = NULL; break; } case k7zIdEmptyFile: { - RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)); + RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)) break; } case k7zIdWinAttrib: @@ -1245,22 +1255,22 @@ static SRes SzReadHeader2( CSzData sdSwitch; CSzData *sdPtr; SzBitUi32s_Free(&p->Attribs, allocMain); - RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)); + RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)) - SZ_READ_BYTE(external); + SZ_READ_BYTE(external) if (external == 0) sdPtr = sd; else { UInt32 index; - RINOK(SzReadNumber32(sd, &index)); + RINOK(SzReadNumber32(sd, &index)) if (index >= *numTempBufs) return SZ_ERROR_ARCHIVE; sdSwitch.Data = (tempBufs)[index].data; sdSwitch.Size = (tempBufs)[index].size; sdPtr = &sdSwitch; } - RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)); + RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)) break; } /* @@ -1273,11 +1283,11 @@ static SRes SzReadHeader2( break; } */ - case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; - case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; + case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; + case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break; default: { - SKIP_DATA(sd, size); + SKIP_DATA(sd, size) } } } @@ -1288,10 +1298,10 @@ static SRes SzReadHeader2( for (;;) { UInt64 type; - RINOK(ReadID(sd, &type)); + RINOK(ReadID(sd, &type)) if (type == k7zIdEnd) break; - RINOK(SkipData(sd)); + RINOK(SkipData(sd)) } { @@ -1303,40 +1313,37 @@ static SRes SzReadHeader2( UInt64 unpackPos = 0; const Byte *digestsDefs = NULL; const Byte *digestsVals = NULL; - UInt32 digestsValsIndex = 0; - UInt32 digestIndex; - Byte allDigestsDefined = 0; + UInt32 digestIndex = 0; Byte isDirMask = 0; Byte crcMask = 0; Byte mask = 0x80; - MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain); - MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain); - MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain); - MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain); + MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain) + MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain) + MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain) + MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain) - RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)); + RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)) if (ssi.sdCRCs.Size != 0) { - SZ_READ_BYTE_SD(&ssi.sdCRCs, allDigestsDefined); + Byte allDigestsDefined = 0; + SZ_READ_BYTE_SD_NOCHECK(&ssi.sdCRCs, allDigestsDefined) if (allDigestsDefined) digestsVals = ssi.sdCRCs.Data; else { - size_t numBytes = (ssi.NumSubDigests + 7) >> 3; + const size_t numBytes = (ssi.NumSubDigests + 7) >> 3; digestsDefs = ssi.sdCRCs.Data; digestsVals = digestsDefs + numBytes; } } - digestIndex = 0; - for (i = 0; i < numFiles; i++, mask >>= 1) { if (mask == 0) { - UInt32 byteIndex = (i - 1) >> 3; + const UInt32 byteIndex = (i - 1) >> 3; p->IsDirs[byteIndex] = isDirMask; p->CRCs.Defs[byteIndex] = crcMask; isDirMask = 0; @@ -1374,18 +1381,17 @@ static SRes SzReadHeader2( numSubStreams = 1; if (ssi.sdNumSubStreams.Data) { - RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); + RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) } remSubStreams = numSubStreams; if (numSubStreams != 0) break; { - UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); + const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); unpackPos += folderUnpackSize; if (unpackPos < folderUnpackSize) return SZ_ERROR_ARCHIVE; } - folderIndex++; } } @@ -1397,47 +1403,44 @@ static SRes SzReadHeader2( if (--remSubStreams == 0) { - UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); - UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; + const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); + const UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; if (folderUnpackSize < unpackPos - startFolderUnpackPos) return SZ_ERROR_ARCHIVE; unpackPos = startFolderUnpackPos + folderUnpackSize; if (unpackPos < folderUnpackSize) return SZ_ERROR_ARCHIVE; - if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, i)) + if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, folderIndex)) { p->CRCs.Vals[i] = p->db.FolderCRCs.Vals[folderIndex]; crcMask |= mask; } - else if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) - { - p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); - digestsValsIndex++; - crcMask |= mask; - } - folderIndex++; } else { UInt64 v; - RINOK(ReadNumber(&ssi.sdSizes, &v)); + RINOK(ReadNumber(&ssi.sdSizes, &v)) unpackPos += v; if (unpackPos < v) return SZ_ERROR_ARCHIVE; - if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) + } + if ((crcMask & mask) == 0 && digestsVals) + { + if (!digestsDefs || SzBitArray_Check(digestsDefs, digestIndex)) { - p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); - digestsValsIndex++; + p->CRCs.Vals[i] = GetUi32(digestsVals); + digestsVals += 4; crcMask |= mask; } + digestIndex++; } } if (mask != 0x80) { - UInt32 byteIndex = (i - 1) >> 3; + const UInt32 byteIndex = (i - 1) >> 3; p->IsDirs[byteIndex] = isDirMask; p->CRCs.Defs[byteIndex] = crcMask; } @@ -1454,7 +1457,7 @@ static SRes SzReadHeader2( break; if (!ssi.sdNumSubStreams.Data) return SZ_ERROR_ARCHIVE; - RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); + RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)) if (numSubStreams != 0) return SZ_ERROR_ARCHIVE; /* @@ -1479,7 +1482,7 @@ static SRes SzReadHeader2( static SRes SzReadHeader( CSzArEx *p, CSzData *sd, - ILookInStream *inStream, + ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { @@ -1498,7 +1501,7 @@ static SRes SzReadHeader( for (i = 0; i < NUM_ADDITIONAL_STREAMS_MAX; i++) Buf_Free(tempBufs + i, allocTemp); - RINOK(res); + RINOK(res) if (sd->Size != 0) return SZ_ERROR_FAIL; @@ -1508,7 +1511,7 @@ static SRes SzReadHeader( static SRes SzArEx_Open2( CSzArEx *p, - ILookInStream *inStream, + ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { @@ -1521,9 +1524,9 @@ static SRes SzArEx_Open2( SRes res; startArcPos = 0; - RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)); + RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)) - RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)); + RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)) if (!TestSignatureCandidate(header)) return SZ_ERROR_NO_ARCHIVE; @@ -1552,14 +1555,14 @@ static SRes SzArEx_Open2( { Int64 pos = 0; - RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)); + RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)) if ((UInt64)pos < (UInt64)startArcPos + nextHeaderOffset || (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset || (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize) return SZ_ERROR_INPUT_EOF; } - RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)); + RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)) if (!Buf_Create(&buf, nextHeaderSizeT, allocTemp)) return SZ_ERROR_MEM; @@ -1634,10 +1637,10 @@ static SRes SzArEx_Open2( } -SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, +SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream, ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { - SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); + const SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); if (res != SZ_OK) SzArEx_Free(p, allocMain); return res; @@ -1646,7 +1649,7 @@ SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, SRes SzArEx_Extract( const CSzArEx *p, - ILookInStream *inStream, + ILookInStreamPtr inStream, UInt32 fileIndex, UInt32 *blockIndex, Byte **tempBuf, @@ -1656,7 +1659,7 @@ SRes SzArEx_Extract( ISzAllocPtr allocMain, ISzAllocPtr allocTemp) { - UInt32 folderIndex = p->FileToFolder[fileIndex]; + const UInt32 folderIndex = p->FileToFolder[fileIndex]; SRes res = SZ_OK; *offset = 0; @@ -1673,13 +1676,13 @@ SRes SzArEx_Extract( if (*tempBuf == NULL || *blockIndex != folderIndex) { - UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); + const UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); /* UInt64 unpackSizeSpec = p->UnpackPositions[p->FolderToFile[(size_t)folderIndex + 1]] - p->UnpackPositions[p->FolderToFile[folderIndex]]; */ - size_t unpackSize = (size_t)unpackSizeSpec; + const size_t unpackSize = (size_t)unpackSizeSpec; if (unpackSize != unpackSizeSpec) return SZ_ERROR_MEM; @@ -1707,7 +1710,7 @@ SRes SzArEx_Extract( if (res == SZ_OK) { - UInt64 unpackPos = p->UnpackPositions[fileIndex]; + const UInt64 unpackPos = p->UnpackPositions[fileIndex]; *offset = (size_t)(unpackPos - p->UnpackPositions[p->FolderToFile[folderIndex]]); *outSizeProcessed = (size_t)(p->UnpackPositions[(size_t)fileIndex + 1] - unpackPos); if (*offset + *outSizeProcessed > *outBufferSize) @@ -1723,8 +1726,8 @@ SRes SzArEx_Extract( size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest) { - size_t offs = p->FileNameOffsets[fileIndex]; - size_t len = p->FileNameOffsets[fileIndex + 1] - offs; + const size_t offs = p->FileNameOffsets[fileIndex]; + const size_t len = p->FileNameOffsets[fileIndex + 1] - offs; if (dest != 0) { size_t i; diff --git a/C/7zBuf.h b/C/7zBuf.h index 81d1b5b6..c0ba8a7b 100644 --- a/C/7zBuf.h +++ b/C/7zBuf.h @@ -1,8 +1,8 @@ /* 7zBuf.h -- Byte Buffer -2017-04-03 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __7Z_BUF_H -#define __7Z_BUF_H +#ifndef ZIP7_INC_7Z_BUF_H +#define ZIP7_INC_7Z_BUF_H #include "7zTypes.h" diff --git a/C/7zCrc.c b/C/7zCrc.c index f186324d..c995a8be 100644 --- a/C/7zCrc.c +++ b/C/7zCrc.c @@ -1,5 +1,5 @@ -/* 7zCrc.c -- CRC32 init -2021-04-01 : Igor Pavlov : Public domain */ +/* 7zCrc.c -- CRC32 calculation and init +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -13,22 +13,20 @@ #else #define CRC_NUM_TABLES 9 - #define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) - - UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); - UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); + UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table); + UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table); #endif #ifndef MY_CPU_BE - UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); - UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); + UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); + UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); #endif -typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); - +/* extern CRC_FUNC g_CrcUpdateT4; CRC_FUNC g_CrcUpdateT4; +*/ extern CRC_FUNC g_CrcUpdateT8; CRC_FUNC g_CrcUpdateT8; @@ -44,20 +42,22 @@ CRC_FUNC g_CrcUpdate; UInt32 g_CrcTable[256 * CRC_NUM_TABLES]; -UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) +UInt32 Z7_FASTCALL CrcUpdate(UInt32 v, const void *data, size_t size) { return g_CrcUpdate(v, data, size, g_CrcTable); } -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) +UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size) { return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL; } +#if CRC_NUM_TABLES < 4 \ + || (CRC_NUM_TABLES == 4 && defined(MY_CPU_BE)) \ + || (!defined(MY_CPU_LE) && !defined(MY_CPU_BE)) #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - -UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); -UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); +UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; const Byte *pEnd = p + size; @@ -65,7 +65,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U v = CRC_UPDATE_BYTE_2(v, *p); return v; } - +#endif /* ---------- hardware CRC ---------- */ @@ -78,16 +78,29 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U #if defined(_MSC_VER) #if defined(MY_CPU_ARM64) #if (_MSC_VER >= 1910) + #ifndef __clang__ #define USE_ARM64_CRC + #include + #endif #endif #endif #elif (defined(__clang__) && (__clang_major__ >= 3)) \ || (defined(__GNUC__) && (__GNUC__ > 4)) #if !defined(__ARM_FEATURE_CRC32) #define __ARM_FEATURE_CRC32 1 - #if (!defined(__clang__) || (__clang_major__ > 3)) // fix these numbers + #if defined(__clang__) + #if defined(MY_CPU_ARM64) + #define ATTRIB_CRC __attribute__((__target__("crc"))) + #else + #define ATTRIB_CRC __attribute__((__target__("armv8-a,crc"))) + #endif + #else + #if defined(MY_CPU_ARM64) + #define ATTRIB_CRC __attribute__((__target__("+crc"))) + #else #define ATTRIB_CRC __attribute__((__target__("arch=armv8-a+crc"))) #endif + #endif #endif #if defined(__ARM_FEATURE_CRC32) #define USE_ARM64_CRC @@ -105,7 +118,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U #pragma message("ARM64 CRC emulation") -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 __crc32b(UInt32 v, UInt32 data) { const UInt32 *table = g_CrcTable; @@ -113,7 +126,7 @@ UInt32 __crc32b(UInt32 v, UInt32 data) return v; } -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 __crc32w(UInt32 v, UInt32 data) { const UInt32 *table = g_CrcTable; @@ -124,7 +137,7 @@ UInt32 __crc32w(UInt32 v, UInt32 data) return v; } -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 __crc32d(UInt32 v, UInt64 data) { const UInt32 *table = g_CrcTable; @@ -156,9 +169,9 @@ UInt32 __crc32d(UInt32 v, UInt64 data) // #pragma message("USE ARM HW CRC") ATTRIB_CRC -UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); +UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); ATTRIB_CRC -UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; UNUSED_VAR(table); @@ -188,9 +201,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, cons } ATTRIB_CRC -UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); +UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); ATTRIB_CRC -UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; UNUSED_VAR(table); @@ -219,6 +232,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons return v; } +#undef T0_32_UNROLL_BYTES +#undef T0_64_UNROLL_BYTES + #endif // defined(USE_ARM64_CRC) || defined(USE_CRC_EMU) #endif // MY_CPU_LE @@ -226,7 +242,7 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons -void MY_FAST_CALL CrcGenerateTable() +void Z7_FASTCALL CrcGenerateTable(void) { UInt32 i; for (i = 0; i < 256; i++) @@ -239,64 +255,62 @@ void MY_FAST_CALL CrcGenerateTable() } for (i = 256; i < 256 * CRC_NUM_TABLES; i++) { - UInt32 r = g_CrcTable[(size_t)i - 256]; + const UInt32 r = g_CrcTable[(size_t)i - 256]; g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8); } #if CRC_NUM_TABLES < 4 - - g_CrcUpdate = CrcUpdateT1; - - #else - - #ifdef MY_CPU_LE - - g_CrcUpdateT4 = CrcUpdateT4; - g_CrcUpdate = CrcUpdateT4; - - #if CRC_NUM_TABLES >= 8 + g_CrcUpdate = CrcUpdateT1; + #elif defined(MY_CPU_LE) + // g_CrcUpdateT4 = CrcUpdateT4; + #if CRC_NUM_TABLES < 8 + g_CrcUpdate = CrcUpdateT4; + #else // CRC_NUM_TABLES >= 8 g_CrcUpdateT8 = CrcUpdateT8; - + /* #ifdef MY_CPU_X86_OR_AMD64 if (!CPU_Is_InOrder()) #endif - g_CrcUpdate = CrcUpdateT8; + */ + g_CrcUpdate = CrcUpdateT8; #endif - #else { - #ifndef MY_CPU_BE + #ifndef MY_CPU_BE UInt32 k = 0x01020304; const Byte *p = (const Byte *)&k; if (p[0] == 4 && p[1] == 3) { - g_CrcUpdateT4 = CrcUpdateT4; - g_CrcUpdate = CrcUpdateT4; - #if CRC_NUM_TABLES >= 8 - g_CrcUpdateT8 = CrcUpdateT8; - g_CrcUpdate = CrcUpdateT8; + #if CRC_NUM_TABLES < 8 + // g_CrcUpdateT4 = CrcUpdateT4; + g_CrcUpdate = CrcUpdateT4; + #else // CRC_NUM_TABLES >= 8 + g_CrcUpdateT8 = CrcUpdateT8; + g_CrcUpdate = CrcUpdateT8; #endif } else if (p[0] != 1 || p[1] != 2) g_CrcUpdate = CrcUpdateT1; else - #endif + #endif // MY_CPU_BE { for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--) { - UInt32 x = g_CrcTable[(size_t)i - 256]; - g_CrcTable[i] = CRC_UINT32_SWAP(x); + const UInt32 x = g_CrcTable[(size_t)i - 256]; + g_CrcTable[i] = Z7_BSWAP32(x); } - g_CrcUpdateT4 = CrcUpdateT1_BeT4; - g_CrcUpdate = CrcUpdateT1_BeT4; - #if CRC_NUM_TABLES >= 8 - g_CrcUpdateT8 = CrcUpdateT1_BeT8; - g_CrcUpdate = CrcUpdateT1_BeT8; + #if CRC_NUM_TABLES <= 4 + g_CrcUpdate = CrcUpdateT1; + #elif CRC_NUM_TABLES <= 8 + // g_CrcUpdateT4 = CrcUpdateT1_BeT4; + g_CrcUpdate = CrcUpdateT1_BeT4; + #else // CRC_NUM_TABLES > 8 + g_CrcUpdateT8 = CrcUpdateT1_BeT8; + g_CrcUpdate = CrcUpdateT1_BeT8; #endif } } - #endif - #endif + #endif // CRC_NUM_TABLES < 4 #ifdef MY_CPU_LE #ifdef USE_ARM64_CRC @@ -320,3 +334,7 @@ void MY_FAST_CALL CrcGenerateTable() #endif #endif } + +#undef kCrcPoly +#undef CRC64_NUM_TABLES +#undef CRC_UPDATE_BYTE_2 diff --git a/C/7zCrc.h b/C/7zCrc.h index 8fd57958..4afaeae4 100644 --- a/C/7zCrc.h +++ b/C/7zCrc.h @@ -1,8 +1,8 @@ /* 7zCrc.h -- CRC32 calculation -2013-01-18 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_CRC_H -#define __7Z_CRC_H +#ifndef ZIP7_INC_7Z_CRC_H +#define ZIP7_INC_7Z_CRC_H #include "7zTypes.h" @@ -11,14 +11,16 @@ EXTERN_C_BEGIN extern UInt32 g_CrcTable[]; /* Call CrcGenerateTable one time before other CRC functions */ -void MY_FAST_CALL CrcGenerateTable(void); +void Z7_FASTCALL CrcGenerateTable(void); #define CRC_INIT_VAL 0xFFFFFFFF #define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL) #define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) -UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); +UInt32 Z7_FASTCALL CrcUpdate(UInt32 crc, const void *data, size_t size); +UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size); + +typedef UInt32 (Z7_FASTCALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); EXTERN_C_END diff --git a/C/7zCrcOpt.c b/C/7zCrcOpt.c index 69fad9ca..9c649290 100644 --- a/C/7zCrcOpt.c +++ b/C/7zCrcOpt.c @@ -1,5 +1,5 @@ /* 7zCrcOpt.c -- CRC32 calculation -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -9,8 +9,8 @@ #define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) -UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); -UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); +UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) @@ -29,8 +29,8 @@ UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const U return v; } -UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); -UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); +UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; for (; size > 0 && ((unsigned)(ptrdiff_t)p & 7) != 0; size--, p++) @@ -61,11 +61,11 @@ UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const U #ifndef MY_CPU_LE -#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) +#define CRC_UINT32_SWAP(v) Z7_BSWAP32(v) #define CRC_UPDATE_BYTE_2_BE(crc, b) (table[(((crc) >> 24) ^ (b))] ^ ((crc) << 8)) -UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; table += 0x100; @@ -86,7 +86,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, co return CRC_UINT32_SWAP(v); } -UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) +UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) { const Byte *p = (const Byte *)data; table += 0x100; diff --git a/C/7zDec.c b/C/7zDec.c index fbfd016e..96c60359 100644 --- a/C/7zDec.c +++ b/C/7zDec.c @@ -1,11 +1,11 @@ /* 7zDec.c -- Decoding from 7z folder -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" #include -/* #define _7ZIP_PPMD_SUPPPORT */ +/* #define Z7_PPMD_SUPPORT */ #include "7z.h" #include "7zCrc.h" @@ -16,27 +16,49 @@ #include "Delta.h" #include "LzmaDec.h" #include "Lzma2Dec.h" -#ifdef _7ZIP_PPMD_SUPPPORT +#ifdef Z7_PPMD_SUPPORT #include "Ppmd7.h" #endif #define k_Copy 0 -#ifndef _7Z_NO_METHOD_LZMA2 +#ifndef Z7_NO_METHOD_LZMA2 #define k_LZMA2 0x21 #endif #define k_LZMA 0x30101 #define k_BCJ2 0x303011B -#ifndef _7Z_NO_METHODS_FILTERS + +#if !defined(Z7_NO_METHODS_FILTERS) +#define Z7_USE_BRANCH_FILTER +#endif + +#if !defined(Z7_NO_METHODS_FILTERS) || \ + defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARM64) +#define Z7_USE_FILTER_ARM64 +#ifndef Z7_USE_BRANCH_FILTER +#define Z7_USE_BRANCH_FILTER +#endif +#define k_ARM64 0xa +#endif + +#if !defined(Z7_NO_METHODS_FILTERS) || \ + defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARMT) +#define Z7_USE_FILTER_ARMT +#ifndef Z7_USE_BRANCH_FILTER +#define Z7_USE_BRANCH_FILTER +#endif +#define k_ARMT 0x3030701 +#endif + +#ifndef Z7_NO_METHODS_FILTERS #define k_Delta 3 #define k_BCJ 0x3030103 #define k_PPC 0x3030205 #define k_IA64 0x3030401 #define k_ARM 0x3030501 -#define k_ARMT 0x3030701 #define k_SPARC 0x3030805 #endif -#ifdef _7ZIP_PPMD_SUPPPORT +#ifdef Z7_PPMD_SUPPORT #define k_PPMD 0x30401 @@ -49,12 +71,12 @@ typedef struct UInt64 processed; BoolInt extra; SRes res; - const ILookInStream *inStream; + ILookInStreamPtr inStream; } CByteInToLook; -static Byte ReadByte(const IByteIn *pp) +static Byte ReadByte(IByteInPtr pp) { - CByteInToLook *p = CONTAINER_FROM_VTBL(pp, CByteInToLook, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInToLook) if (p->cur != p->end) return *p->cur++; if (p->res == SZ_OK) @@ -67,13 +89,13 @@ static Byte ReadByte(const IByteIn *pp) p->cur = p->begin; p->end = p->begin + size; if (size != 0) - return *p->cur++;; + return *p->cur++; } p->extra = 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 @@ static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, c #endif -static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, +static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) { CLzmaDec state; SRes res = SZ_OK; - LzmaDec_Construct(&state); - RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)); + LzmaDec_CONSTRUCT(&state) + RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)) state.dic = outBuffer; state.dicBufSize = outSize; LzmaDec_Init(&state); @@ -196,18 +218,18 @@ static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, I } -#ifndef _7Z_NO_METHOD_LZMA2 +#ifndef Z7_NO_METHOD_LZMA2 -static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, +static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) { CLzma2Dec state; SRes res = SZ_OK; - Lzma2Dec_Construct(&state); + Lzma2Dec_CONSTRUCT(&state) if (propsSize != 1) return SZ_ERROR_DATA; - RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)); + RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)) state.decoder.dic = outBuffer; state.decoder.dicBufSize = outSize; Lzma2Dec_Init(&state); @@ -257,7 +279,7 @@ static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, #endif -static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer) +static SRes SzDecodeCopy(UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer) { while (inSize > 0) { @@ -265,13 +287,13 @@ static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer size_t curSize = (1 << 18); if (curSize > inSize) curSize = (size_t)inSize; - RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)); + RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)) if (curSize == 0) return SZ_ERROR_INPUT_EOF; memcpy(outBuffer, inBuf, curSize); outBuffer += curSize; inSize -= curSize; - RINOK(ILookInStream_Skip(inStream, curSize)); + RINOK(ILookInStream_Skip(inStream, curSize)) } return SZ_OK; } @@ -282,12 +304,12 @@ static BoolInt IS_MAIN_METHOD(UInt32 m) { case k_Copy: case k_LZMA: - #ifndef _7Z_NO_METHOD_LZMA2 + #ifndef Z7_NO_METHOD_LZMA2 case k_LZMA2: - #endif - #ifdef _7ZIP_PPMD_SUPPPORT + #endif + #ifdef Z7_PPMD_SUPPORT case k_PPMD: - #endif + #endif return True; } return False; @@ -317,7 +339,7 @@ static SRes CheckSupportedFolder(const CSzFolder *f) } - #ifndef _7Z_NO_METHODS_FILTERS + #if defined(Z7_USE_BRANCH_FILTER) if (f->NumCoders == 2) { @@ -333,13 +355,20 @@ static SRes CheckSupportedFolder(const CSzFolder *f) return SZ_ERROR_UNSUPPORTED; switch ((UInt32)c->MethodID) { + #if !defined(Z7_NO_METHODS_FILTERS) case k_Delta: case k_BCJ: case k_PPC: case k_IA64: case k_SPARC: case k_ARM: + #endif + #ifdef Z7_USE_FILTER_ARM64 + case k_ARM64: + #endif + #ifdef Z7_USE_FILTER_ARMT case k_ARMT: + #endif break; default: return SZ_ERROR_UNSUPPORTED; @@ -372,15 +401,16 @@ static SRes CheckSupportedFolder(const CSzFolder *f) return SZ_ERROR_UNSUPPORTED; } -#ifndef _7Z_NO_METHODS_FILTERS -#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break; -#endif + + + + static SRes SzFolder_Decode2(const CSzFolder *folder, const Byte *propsData, const UInt64 *unpackSizes, const UInt64 *packPositions, - ILookInStream *inStream, UInt64 startPos, + ILookInStreamPtr inStream, UInt64 startPos, Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain, Byte *tempBuf[]) { @@ -389,7 +419,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, SizeT tempSize3 = 0; Byte *tempBuf3 = 0; - RINOK(CheckSupportedFolder(folder)); + RINOK(CheckSupportedFolder(folder)) for (ci = 0; ci < folder->NumCoders; ci++) { @@ -404,8 +434,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, SizeT outSizeCur = outSize; if (folder->NumCoders == 4) { - UInt32 indices[] = { 3, 2, 0 }; - UInt64 unpackSize = unpackSizes[ci]; + const UInt32 indices[] = { 3, 2, 0 }; + const UInt64 unpackSize = unpackSizes[ci]; si = indices[ci]; if (ci < 2) { @@ -431,37 +461,37 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, } offset = packPositions[si]; inSize = packPositions[(size_t)si + 1] - offset; - RINOK(LookInStream_SeekTo(inStream, startPos + offset)); + RINOK(LookInStream_SeekTo(inStream, startPos + offset)) if (coder->MethodID == k_Copy) { if (inSize != outSizeCur) /* check it */ return SZ_ERROR_DATA; - RINOK(SzDecodeCopy(inSize, inStream, outBufCur)); + RINOK(SzDecodeCopy(inSize, inStream, outBufCur)) } else if (coder->MethodID == k_LZMA) { - RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); + RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) } - #ifndef _7Z_NO_METHOD_LZMA2 + #ifndef Z7_NO_METHOD_LZMA2 else if (coder->MethodID == k_LZMA2) { - RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); + RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) } - #endif - #ifdef _7ZIP_PPMD_SUPPPORT + #endif + #ifdef Z7_PPMD_SUPPORT else if (coder->MethodID == k_PPMD) { - RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); + RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)) } - #endif + #endif else return SZ_ERROR_UNSUPPORTED; } else if (coder->MethodID == k_BCJ2) { - UInt64 offset = packPositions[1]; - UInt64 s3Size = packPositions[2] - offset; + const UInt64 offset = packPositions[1]; + const UInt64 s3Size = packPositions[2] - offset; if (ci != 3) return SZ_ERROR_UNSUPPORTED; @@ -473,8 +503,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, if (!tempBuf[2] && tempSizes[2] != 0) return SZ_ERROR_MEM; - RINOK(LookInStream_SeekTo(inStream, startPos + offset)); - RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])); + RINOK(LookInStream_SeekTo(inStream, startPos + offset)) + RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])) if ((tempSizes[0] & 3) != 0 || (tempSizes[1] & 3) != 0 || @@ -493,26 +523,22 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, p.destLim = outBuffer + outSize; Bcj2Dec_Init(&p); - RINOK(Bcj2Dec_Decode(&p)); + RINOK(Bcj2Dec_Decode(&p)) { unsigned i; for (i = 0; i < 4; i++) if (p.bufs[i] != p.lims[i]) return SZ_ERROR_DATA; - - if (!Bcj2Dec_IsFinished(&p)) - return SZ_ERROR_DATA; - - if (p.dest != p.destLim - || p.state != BCJ2_STREAM_MAIN) + if (p.dest != p.destLim || !Bcj2Dec_IsMaybeFinished(&p)) return SZ_ERROR_DATA; } } } - #ifndef _7Z_NO_METHODS_FILTERS + #if defined(Z7_USE_BRANCH_FILTER) else if (ci == 1) { + #if !defined(Z7_NO_METHODS_FILTERS) if (coder->MethodID == k_Delta) { if (coder->PropsSize != 1) @@ -522,31 +548,53 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, Delta_Init(state); Delta_Decode(state, (unsigned)(propsData[coder->PropsOffset]) + 1, outBuffer, outSize); } + continue; } - else + #endif + + #ifdef Z7_USE_FILTER_ARM64 + if (coder->MethodID == k_ARM64) + { + UInt32 pc = 0; + if (coder->PropsSize == 4) + pc = GetUi32(propsData + coder->PropsOffset); + else if (coder->PropsSize != 0) + return SZ_ERROR_UNSUPPORTED; + z7_BranchConv_ARM64_Dec(outBuffer, outSize, pc); + continue; + } + #endif + + #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) { if (coder->PropsSize != 0) return SZ_ERROR_UNSUPPORTED; + #define CASE_BRA_CONV(isa) case k_ ## isa: Z7_BRANCH_CONV_DEC(isa)(outBuffer, outSize, 0); break; // pc = 0; switch (coder->MethodID) { + #if !defined(Z7_NO_METHODS_FILTERS) case k_BCJ: { - UInt32 state; - x86_Convert_Init(state); - x86_Convert(outBuffer, outSize, 0, &state, 0); + UInt32 state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; + z7_BranchConvSt_X86_Dec(outBuffer, outSize, 0, &state); // pc = 0 break; } CASE_BRA_CONV(PPC) CASE_BRA_CONV(IA64) CASE_BRA_CONV(SPARC) CASE_BRA_CONV(ARM) + #endif + #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT) CASE_BRA_CONV(ARMT) + #endif default: return SZ_ERROR_UNSUPPORTED; } + continue; } - } - #endif + #endif + } // (c == 1) + #endif else return SZ_ERROR_UNSUPPORTED; } @@ -556,7 +604,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, - ILookInStream *inStream, UInt64 startPos, + ILookInStreamPtr inStream, UInt64 startPos, Byte *outBuffer, size_t outSize, ISzAllocPtr allocMain) { diff --git a/C/7zFile.c b/C/7zFile.c index 13d2efa4..ba5daa13 100644 --- a/C/7zFile.c +++ b/C/7zFile.c @@ -1,5 +1,5 @@ /* 7zFile.c -- File IO -2021-04-29 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -268,7 +268,7 @@ WRes File_Write(CSzFile *p, const void *data, size_t *size) return errno; if (processed == 0) break; - data = (void *)((Byte *)data + (size_t)processed); + data = (const void *)((const Byte *)data + (size_t)processed); originalSize -= (size_t)processed; *size += (size_t)processed; } @@ -287,7 +287,8 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) DWORD moveMethod; UInt32 low = (UInt32)*pos; LONG high = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */ - switch (origin) + // (int) to eliminate clang warning + switch ((int)origin) { case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break; case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break; @@ -308,7 +309,7 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin) int moveMethod; // = origin; - switch (origin) + switch ((int)origin) { case SZ_SEEK_SET: moveMethod = SEEK_SET; break; case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break; @@ -387,10 +388,10 @@ WRes File_GetLength(CSzFile *p, UInt64 *length) /* ---------- FileSeqInStream ---------- */ -static SRes FileSeqInStream_Read(const ISeqInStream *pp, void *buf, size_t *size) +static SRes FileSeqInStream_Read(ISeqInStreamPtr pp, void *buf, size_t *size) { - CFileSeqInStream *p = CONTAINER_FROM_VTBL(pp, CFileSeqInStream, vt); - WRes wres = File_Read(&p->file, buf, size); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileSeqInStream) + const WRes wres = File_Read(&p->file, buf, size); p->wres = wres; return (wres == 0) ? SZ_OK : SZ_ERROR_READ; } @@ -403,18 +404,18 @@ void FileSeqInStream_CreateVTable(CFileSeqInStream *p) /* ---------- FileInStream ---------- */ -static SRes FileInStream_Read(const ISeekInStream *pp, void *buf, size_t *size) +static SRes FileInStream_Read(ISeekInStreamPtr pp, void *buf, size_t *size) { - CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); - WRes wres = File_Read(&p->file, buf, size); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) + const WRes wres = File_Read(&p->file, buf, size); p->wres = wres; return (wres == 0) ? SZ_OK : SZ_ERROR_READ; } -static SRes FileInStream_Seek(const ISeekInStream *pp, Int64 *pos, ESzSeek origin) +static SRes FileInStream_Seek(ISeekInStreamPtr pp, Int64 *pos, ESzSeek origin) { - CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); - WRes wres = File_Seek(&p->file, pos, origin); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream) + const WRes wres = File_Seek(&p->file, pos, origin); p->wres = wres; return (wres == 0) ? SZ_OK : SZ_ERROR_READ; } @@ -428,10 +429,10 @@ void FileInStream_CreateVTable(CFileInStream *p) /* ---------- FileOutStream ---------- */ -static size_t FileOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) +static size_t FileOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) { - CFileOutStream *p = CONTAINER_FROM_VTBL(pp, CFileOutStream, vt); - WRes wres = File_Write(&p->file, data, &size); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileOutStream) + const WRes wres = File_Write(&p->file, data, &size); p->wres = wres; return size; } diff --git a/C/7zFile.h b/C/7zFile.h index 788abb6b..f5069cd9 100644 --- a/C/7zFile.h +++ b/C/7zFile.h @@ -1,8 +1,8 @@ /* 7zFile.h -- File IO -2021-02-15 : Igor Pavlov : Public domain */ +2023-03-05 : Igor Pavlov : Public domain */ -#ifndef __7Z_FILE_H -#define __7Z_FILE_H +#ifndef ZIP7_INC_FILE_H +#define ZIP7_INC_FILE_H #ifdef _WIN32 #define USE_WINDOWS_FILE @@ -10,7 +10,8 @@ #endif #ifdef USE_WINDOWS_FILE -#include +#include "7zWindows.h" + #else // note: USE_FOPEN mode is limited to 32-bit file size // #define USE_FOPEN diff --git a/C/7zStream.c b/C/7zStream.c index 28a14604..74e75b65 100644 --- a/C/7zStream.c +++ b/C/7zStream.c @@ -1,5 +1,5 @@ /* 7zStream.c -- 7z Stream functions -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -7,12 +7,33 @@ #include "7zTypes.h" -SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType) + +SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize) +{ + size_t size = *processedSize; + *processedSize = 0; + while (size != 0) + { + size_t cur = size; + const SRes res = ISeqInStream_Read(stream, buf, &cur); + *processedSize += cur; + buf = (void *)((Byte *)buf + cur); + size -= cur; + if (res != SZ_OK) + return res; + if (cur == 0) + return SZ_OK; + } + return SZ_OK; +} + +/* +SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType) { while (size != 0) { size_t processed = size; - RINOK(ISeqInStream_Read(stream, buf, &processed)); + RINOK(ISeqInStream_Read(stream, buf, &processed)) if (processed == 0) return errorType; buf = (void *)((Byte *)buf + processed); @@ -21,42 +42,44 @@ SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes return SZ_OK; } -SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size) +SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size) { return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); } +*/ + -SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf) +SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf) { size_t processed = 1; - RINOK(ISeqInStream_Read(stream, buf, &processed)); + RINOK(ISeqInStream_Read(stream, buf, &processed)) return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF; } -SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset) +SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset) { Int64 t = (Int64)offset; return ILookInStream_Seek(stream, &t, SZ_SEEK_SET); } -SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size) +SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size) { const void *lookBuf; if (*size == 0) return SZ_OK; - RINOK(ILookInStream_Look(stream, &lookBuf, size)); + RINOK(ILookInStream_Look(stream, &lookBuf, size)) memcpy(buf, lookBuf, *size); return ILookInStream_Skip(stream, *size); } -SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType) +SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType) { while (size != 0) { size_t processed = size; - RINOK(ILookInStream_Read(stream, buf, &processed)); + RINOK(ILookInStream_Read(stream, buf, &processed)) if (processed == 0) return errorType; buf = (void *)((Byte *)buf + processed); @@ -65,16 +88,16 @@ SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRe return SZ_OK; } -SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size) +SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size) { return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); } -#define GET_LookToRead2 CLookToRead2 *p = CONTAINER_FROM_VTBL(pp, CLookToRead2, vt); +#define GET_LookToRead2 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLookToRead2) -static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf, size_t *size) +static SRes LookToRead2_Look_Lookahead(ILookInStreamPtr pp, const void **buf, size_t *size) { SRes res = SZ_OK; GET_LookToRead2 @@ -93,7 +116,7 @@ static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf return res; } -static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, size_t *size) +static SRes LookToRead2_Look_Exact(ILookInStreamPtr pp, const void **buf, size_t *size) { SRes res = SZ_OK; GET_LookToRead2 @@ -113,14 +136,14 @@ static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, si return res; } -static SRes LookToRead2_Skip(const ILookInStream *pp, size_t offset) +static SRes LookToRead2_Skip(ILookInStreamPtr pp, size_t offset) { GET_LookToRead2 p->pos += offset; return SZ_OK; } -static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) +static SRes LookToRead2_Read(ILookInStreamPtr pp, void *buf, size_t *size) { GET_LookToRead2 size_t rem = p->size - p->pos; @@ -134,7 +157,7 @@ static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) return SZ_OK; } -static SRes LookToRead2_Seek(const ILookInStream *pp, Int64 *pos, ESzSeek origin) +static SRes LookToRead2_Seek(ILookInStreamPtr pp, Int64 *pos, ESzSeek origin) { GET_LookToRead2 p->pos = p->size = 0; @@ -153,9 +176,9 @@ void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead) -static SRes SecToLook_Read(const ISeqInStream *pp, void *buf, size_t *size) +static SRes SecToLook_Read(ISeqInStreamPtr pp, void *buf, size_t *size) { - CSecToLook *p = CONTAINER_FROM_VTBL(pp, CSecToLook, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToLook) return LookInStream_LookRead(p->realStream, buf, size); } @@ -164,9 +187,9 @@ void SecToLook_CreateVTable(CSecToLook *p) p->vt.Read = SecToLook_Read; } -static SRes SecToRead_Read(const ISeqInStream *pp, void *buf, size_t *size) +static SRes SecToRead_Read(ISeqInStreamPtr pp, void *buf, size_t *size) { - CSecToRead *p = CONTAINER_FROM_VTBL(pp, CSecToRead, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToRead) return ILookInStream_Read(p->realStream, buf, size); } diff --git a/C/7zTypes.h b/C/7zTypes.h index f7d70718..1fcb2473 100644 --- a/C/7zTypes.h +++ b/C/7zTypes.h @@ -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 @@ typedef int SRes; #define MY_ALIGN(n) #endif #else + /* + // C11/C++11: + #include + #define MY_ALIGN(n) alignas(n) + */ #define MY_ALIGN(n) __attribute__ ((aligned(n))) #endif @@ -62,7 +67,7 @@ typedef int SRes; typedef unsigned WRes; #define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) -// #define MY_HRES_ERROR__INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) +// #define MY_HRES_ERROR_INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) #else // _WIN32 @@ -70,13 +75,13 @@ typedef unsigned WRes; typedef int WRes; // (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT -#define MY__FACILITY_ERRNO 0x800 -#define MY__FACILITY_WIN32 7 -#define MY__FACILITY__WRes MY__FACILITY_ERRNO +#define MY_FACILITY_ERRNO 0x800 +#define MY_FACILITY_WIN32 7 +#define MY_FACILITY_WRes MY_FACILITY_ERRNO #define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \ ( (HRESULT)(x) & 0x0000FFFF) \ - | (MY__FACILITY__WRes << 16) \ + | (MY_FACILITY_WRes << 16) \ | (HRESULT)0x80000000 )) #define MY_SRes_HRESULT_FROM_WRes(x) \ @@ -120,17 +125,17 @@ typedef int WRes; #define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L) #define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L) -// if (MY__FACILITY__WRes != FACILITY_WIN32), +// if (MY_FACILITY_WRes != FACILITY_WIN32), // we use FACILITY_WIN32 for COM errors: #define E_OUTOFMEMORY ((HRESULT)0x8007000EL) #define E_INVALIDARG ((HRESULT)0x80070057L) -#define MY__E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) +#define MY_E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) /* // we can use FACILITY_ERRNO for some COM errors, that have errno equivalents: #define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM) #define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) -#define MY__E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) +#define MY_E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) */ #define TEXT(quote) quote @@ -156,18 +161,18 @@ typedef int WRes; #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 @@ typedef size_t SIZE_T; #endif // _WIN32 -#define MY_HRES_ERROR__INTERNAL_ERROR ((HRESULT)0x8007054FL) +#define MY_HRES_ERROR_INTERNAL_ERROR ((HRESULT)0x8007054FL) -#ifdef _SZ_NO_INT_64 - -/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. - NOTES: Some code will work incorrectly in that case! */ +#ifdef Z7_DECL_Int64_AS_long typedef long Int64; typedef unsigned long UInt64; #else -#if defined(_MSC_VER) || defined(__BORLANDC__) +#if (defined(_MSC_VER) || defined(__BORLANDC__)) && !defined(__clang__) typedef __int64 Int64; typedef unsigned __int64 UInt64; -#define UINT64_CONST(n) n +#else +#if defined(__clang__) || defined(__GNUC__) +#include +typedef int64_t Int64; +typedef uint64_t UInt64; #else typedef long long int Int64; typedef unsigned long long int UInt64; -#define UINT64_CONST(n) n ## ULL +// #define UINT64_CONST(n) n ## ULL +#endif #endif #endif -#ifdef _LZMA_NO_SYSTEM_SIZE_T -typedef UInt32 SizeT; +#define UINT64_CONST(n) n + + +#ifdef Z7_DECL_SizeT_AS_unsigned_int +typedef unsigned int SizeT; #else typedef size_t SizeT; #endif +/* +#if (defined(_MSC_VER) && _MSC_VER <= 1200) +typedef size_t MY_uintptr_t; +#else +#include +typedef uintptr_t MY_uintptr_t; +#endif +*/ + typedef int BoolInt; /* typedef BoolInt Bool; */ #define True 1 @@ -244,23 +263,23 @@ typedef int BoolInt; #ifdef _WIN32 -#define MY_STD_CALL __stdcall +#define Z7_STDCALL __stdcall #else -#define MY_STD_CALL +#define Z7_STDCALL #endif #ifdef _MSC_VER #if _MSC_VER >= 1300 -#define MY_NO_INLINE __declspec(noinline) +#define Z7_NO_INLINE __declspec(noinline) #else -#define MY_NO_INLINE +#define Z7_NO_INLINE #endif -#define MY_FORCE_INLINE __forceinline +#define Z7_FORCE_INLINE __forceinline -#define MY_CDECL __cdecl -#define MY_FAST_CALL __fastcall +#define Z7_CDECL __cdecl +#define Z7_FASTCALL __fastcall #else // _MSC_VER @@ -268,27 +287,25 @@ typedef int BoolInt; || (defined(__clang__) && (__clang_major__ >= 4)) \ || defined(__INTEL_COMPILER) \ || defined(__xlC__) -#define MY_NO_INLINE __attribute__((noinline)) -// #define MY_FORCE_INLINE __attribute__((always_inline)) inline +#define Z7_NO_INLINE __attribute__((noinline)) +#define Z7_FORCE_INLINE __attribute__((always_inline)) inline #else -#define MY_NO_INLINE +#define Z7_NO_INLINE +#define Z7_FORCE_INLINE #endif -#define MY_FORCE_INLINE - - -#define MY_CDECL +#define Z7_CDECL #if defined(_M_IX86) \ || defined(__i386__) -// #define MY_FAST_CALL __attribute__((fastcall)) -// #define MY_FAST_CALL __attribute__((cdecl)) -#define MY_FAST_CALL +// #define Z7_FASTCALL __attribute__((fastcall)) +// #define Z7_FASTCALL __attribute__((cdecl)) +#define Z7_FASTCALL #elif defined(MY_CPU_AMD64) -// #define MY_FAST_CALL __attribute__((ms_abi)) -#define MY_FAST_CALL +// #define Z7_FASTCALL __attribute__((ms_abi)) +#define Z7_FASTCALL #else -#define MY_FAST_CALL +#define Z7_FASTCALL #endif #endif // _MSC_VER @@ -296,41 +313,49 @@ typedef int BoolInt; /* The following interfaces use first parameter as pointer to structure */ -typedef struct IByteIn IByteIn; -struct IByteIn +// #define Z7_C_IFACE_CONST_QUAL +#define Z7_C_IFACE_CONST_QUAL const + +#define Z7_C_IFACE_DECL(a) \ + struct a ## _; \ + typedef Z7_C_IFACE_CONST_QUAL struct a ## _ * a ## Ptr; \ + typedef struct a ## _ a; \ + struct a ## _ + + +Z7_C_IFACE_DECL (IByteIn) { - Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */ + Byte (*Read)(IByteInPtr p); /* reads one byte, returns 0 in case of EOF or error */ }; #define IByteIn_Read(p) (p)->Read(p) -typedef struct IByteOut IByteOut; -struct IByteOut +Z7_C_IFACE_DECL (IByteOut) { - void (*Write)(const IByteOut *p, Byte b); + void (*Write)(IByteOutPtr p, Byte b); }; #define IByteOut_Write(p, b) (p)->Write(p, b) -typedef struct ISeqInStream ISeqInStream; -struct ISeqInStream +Z7_C_IFACE_DECL (ISeqInStream) { - SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size); + SRes (*Read)(ISeqInStreamPtr p, void *buf, size_t *size); /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. (output(*size) < input(*size)) is allowed */ }; #define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) +/* try to read as much as avail in stream and limited by (*processedSize) */ +SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize); /* it can return SZ_ERROR_INPUT_EOF */ -SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size); -SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType); -SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf); +// SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size); +// SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType); +SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf); -typedef struct ISeqOutStream ISeqOutStream; -struct ISeqOutStream +Z7_C_IFACE_DECL (ISeqOutStream) { - size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size); + size_t (*Write)(ISeqOutStreamPtr p, const void *buf, size_t size); /* Returns: result - the number of actually written bytes. (result < size) means error */ }; @@ -344,29 +369,26 @@ typedef enum } ESzSeek; -typedef struct ISeekInStream ISeekInStream; -struct ISeekInStream +Z7_C_IFACE_DECL (ISeekInStream) { - SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ - SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin); + SRes (*Read)(ISeekInStreamPtr p, void *buf, size_t *size); /* same as ISeqInStream::Read */ + SRes (*Seek)(ISeekInStreamPtr p, Int64 *pos, ESzSeek origin); }; #define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) #define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) -typedef struct ILookInStream ILookInStream; -struct ILookInStream +Z7_C_IFACE_DECL (ILookInStream) { - SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size); + SRes (*Look)(ILookInStreamPtr p, const void **buf, size_t *size); /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. (output(*size) > input(*size)) is not allowed (output(*size) < input(*size)) is allowed */ - SRes (*Skip)(const ILookInStream *p, size_t offset); + SRes (*Skip)(ILookInStreamPtr p, size_t offset); /* offset must be <= output(*size) of Look */ - - SRes (*Read)(const ILookInStream *p, void *buf, size_t *size); + SRes (*Read)(ILookInStreamPtr p, void *buf, size_t *size); /* reads directly (without buffer). It's same as ISeqInStream::Read */ - SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin); + SRes (*Seek)(ILookInStreamPtr p, Int64 *pos, ESzSeek origin); }; #define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) @@ -375,19 +397,18 @@ struct ILookInStream #define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) -SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size); -SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset); +SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size); +SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset); /* reads via ILookInStream::Read */ -SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType); -SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size); - +SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType); +SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size); typedef struct { ILookInStream vt; - const ISeekInStream *realStream; + ISeekInStreamPtr realStream; size_t pos; size_t size; /* it's data size */ @@ -399,13 +420,13 @@ typedef struct void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); -#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } +#define LookToRead2_INIT(p) { (p)->pos = (p)->size = 0; } typedef struct { ISeqInStream vt; - const ILookInStream *realStream; + ILookInStreamPtr realStream; } CSecToLook; void SecToLook_CreateVTable(CSecToLook *p); @@ -415,20 +436,19 @@ void SecToLook_CreateVTable(CSecToLook *p); typedef struct { ISeqInStream vt; - const ILookInStream *realStream; + ILookInStreamPtr realStream; } CSecToRead; void SecToRead_CreateVTable(CSecToRead *p); -typedef struct ICompressProgress ICompressProgress; - -struct ICompressProgress +Z7_C_IFACE_DECL (ICompressProgress) { - SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize); + SRes (*Progress)(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize); /* Returns: result. (result != SZ_OK) means break. Value (UInt64)(Int64)-1 for size means unknown value. */ }; + #define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) @@ -466,13 +486,13 @@ struct ISzAlloc -#ifndef MY_container_of +#ifndef Z7_container_of /* -#define MY_container_of(ptr, type, m) container_of(ptr, type, m) -#define MY_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) -#define MY_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) -#define MY_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) +#define Z7_container_of(ptr, type, m) container_of(ptr, type, m) +#define Z7_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) +#define Z7_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) +#define Z7_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) */ /* @@ -481,24 +501,64 @@ struct ISzAlloc GCC 4.8.1 : classes with non-public variable members" */ -#define MY_container_of(ptr, type, m) ((type *)(void *)((char *)(void *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) +#define Z7_container_of(ptr, type, m) \ + ((type *)(void *)((char *)(void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) -#endif - -#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) +#define Z7_container_of_CONST(ptr, type, m) \ + ((const type *)(const void *)((const char *)(const void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) /* -#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) +#define Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) \ + ((type *)(void *)(const void *)((const char *)(const void *) \ + (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m))) */ -#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) -#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) +#endif + +#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) + +// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) +#define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of(ptr, type, m) +// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) + +#define Z7_CONTAINER_FROM_VTBL_CONST(ptr, type, m) Z7_container_of_CONST(ptr, type, m) + +#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) /* -#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m) +#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL(ptr, type, m) */ +#if defined (__clang__) || defined(__GNUC__) +#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL \ + _Pragma("GCC diagnostic pop") +#else +#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL +#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL +#endif + +#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(ptr, type, m, p) \ + Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \ + type *p = Z7_CONTAINER_FROM_VTBL(ptr, type, m); \ + Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL + +#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(type) \ + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(pp, type, vt, p) -#define MY_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) +// #define ZIP7_DECLARE_HANDLE(name) typedef void *name; +#define Z7_DECLARE_HANDLE(name) struct name##_dummy{int unused;}; typedef struct name##_dummy *name; + + +#define Z7_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) + +#ifndef Z7_ARRAY_SIZE +#define Z7_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#endif + #ifdef _WIN32 @@ -527,3 +587,11 @@ struct ISzAlloc EXTERN_C_END #endif + +/* +#ifndef Z7_ST +#ifdef _7ZIP_ST +#define Z7_ST +#endif +#endif +*/ diff --git a/C/7zVersion.h b/C/7zVersion.h index 4f6a8842..ff6f808e 100644 --- a/C/7zVersion.h +++ b/C/7zVersion.h @@ -1,7 +1,7 @@ #define MY_VER_MAJOR 22 #define MY_VER_MINOR 01 #define MY_VER_BUILD 06 -#define MY_VERSION_NUMBERS "22.01 ZS v1.5.5 R3" +#define MY_VERSION_NUMBERS "23.01 ZS v1.5.5 R1" #define MY_VERSION MY_VERSION_NUMBERS #ifdef MY_CPU_NAME @@ -10,12 +10,12 @@ #define MY_VERSION_CPU MY_VERSION #endif -#define MY_DATE "2023-06-18" +#define MY_DATE "2023-10-21" #undef MY_COPYRIGHT #undef MY_VERSION_COPYRIGHT_DATE #define MY_AUTHOR_NAME "Igor Pavlov, Tino Reichardt" #define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" -#define MY_COPYRIGHT_CR "Copyright (c) 1999-2022 Igor Pavlov, 2016-2023 Tino Reichardt" +#define MY_COPYRIGHT_CR "Copyright (c) 1999-2023 Igor Pavlov, 2016-2023 Tino Reichardt" #ifdef USE_COPYRIGHT_CR #define MY_COPYRIGHT MY_COPYRIGHT_CR diff --git a/C/7zWindows.h b/C/7zWindows.h new file mode 100644 index 00000000..42c6db8b --- /dev/null +++ b/C/7zWindows.h @@ -0,0 +1,101 @@ +/* 7zWindows.h -- StdAfx +2023-04-02 : Igor Pavlov : Public domain */ + +#ifndef ZIP7_INC_7Z_WINDOWS_H +#define ZIP7_INC_7Z_WINDOWS_H + +#ifdef _WIN32 + +#if defined(__clang__) +# pragma clang diagnostic push +#endif + +#if defined(_MSC_VER) + +#pragma warning(push) +#pragma warning(disable : 4668) // '_WIN32_WINNT' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' + +#if _MSC_VER == 1900 +// for old kit10 versions +// #pragma warning(disable : 4255) // winuser.h(13979): warning C4255: 'GetThreadDpiAwarenessContext': +#endif +// win10 Windows Kit: +#endif // _MSC_VER + +#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) +// for msvc6 without sdk2003 +#define RPC_NO_WINDOWS_H +#endif + +#if defined(__MINGW32__) || defined(__MINGW64__) +// #if defined(__GNUC__) && !defined(__clang__) +#include +#else +#include +#endif +// #include +// #include + +// but if precompiled with clang-cl then we need +// #include +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(__clang__) +# pragma clang diagnostic pop +#endif + +#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64) +#ifndef _W64 + +typedef long LONG_PTR, *PLONG_PTR; +typedef unsigned long ULONG_PTR, *PULONG_PTR; +typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR; + +#define Z7_OLD_WIN_SDK +#endif // _W64 +#endif // _MSC_VER == 1200 + +#ifdef Z7_OLD_WIN_SDK + +#ifndef INVALID_FILE_ATTRIBUTES +#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) +#endif +#ifndef INVALID_SET_FILE_POINTER +#define INVALID_SET_FILE_POINTER ((DWORD)-1) +#endif +#ifndef FILE_SPECIAL_ACCESS +#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS) +#endif + +// ShlObj.h: +// #define BIF_NEWDIALOGSTYLE 0x0040 + +#pragma warning(disable : 4201) +// #pragma warning(disable : 4115) + +#undef VARIANT_TRUE +#define VARIANT_TRUE ((VARIANT_BOOL)-1) +#endif + +#endif // Z7_OLD_WIN_SDK + +#ifdef UNDER_CE +#undef VARIANT_TRUE +#define VARIANT_TRUE ((VARIANT_BOOL)-1) +#endif + + +#if defined(_MSC_VER) +#if _MSC_VER >= 1400 && _MSC_VER <= 1600 + // BaseTsd.h(148) : 'HandleToULong' : unreferenced inline function has been removed + // string.h + // #pragma warning(disable : 4514) +#endif +#endif + + +/* #include "7zTypes.h" */ + +#endif diff --git a/C/7zip_gcc_c.mak b/C/7zip_gcc_c.mak index 24505f37..f19a99ba 100644 --- a/C/7zip_gcc_c.mak +++ b/C/7zip_gcc_c.mak @@ -4,15 +4,28 @@ MY_ARCH_2 = $(MY_ARCH) 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 @@ DEL_OBJ_EXE = -$(RM) $(O)\*.o $(O)\$(PROG).exe $(O)\$(PROG).dll 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 @@ else 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 @@ DEL_OBJ_EXE = -$(RM) $(PROGPATH) $(PROGPATH_STATIC) $(OBJS) endif - -CFLAGS = $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ - - ifdef IS_X64 AFLAGS_ABI = -elf64 -DABI_LINUX else @@ -129,12 +138,9 @@ AFLAGS_ABI = -elf -DABI_LINUX -DABI_CDECL 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 @@ all: $(O) $(PROGPATH) $(STATIC_TARGET) $(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 @@ $O/Sha256.o: ../../../C/Sha256.c $(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 @@ $O/LzmaDecOpt.o: ../../../Asm/arm64/LzmaDecOpt.S ../../../Asm/arm64/7zAsm.S endif $O/LzmaDec.o: ../../LzmaDec.c - $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< + $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $< else @@ -321,22 +344,16 @@ endif -$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 --git a/C/Aes.c b/C/Aes.c index 27e32e62..bcaafab1 100644 --- a/C/Aes.c +++ b/C/Aes.c @@ -1,5 +1,5 @@ /* Aes.c -- AES encryption / decryption -2021-05-13 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -7,7 +7,7 @@ #include "Aes.h" AES_CODE_FUNC g_AesCbc_Decode; -#ifndef _SFX +#ifndef Z7_SFX AES_CODE_FUNC g_AesCbc_Encode; AES_CODE_FUNC g_AesCtr_Code; UInt32 g_Aes_SupportedFunctions_Flags; @@ -51,7 +51,7 @@ static Byte InvS[256]; #define DD(x) (D + (x << 8)) -// #define _SHOW_AES_STATUS +// #define Z7_SHOW_AES_STATUS #ifdef MY_CPU_X86_OR_AMD64 #define USE_HW_AES @@ -72,11 +72,11 @@ static Byte InvS[256]; #endif #ifdef USE_HW_AES -#ifdef _SHOW_AES_STATUS +#ifdef Z7_SHOW_AES_STATUS #include -#define _PRF(x) x +#define PRF(x) x #else -#define _PRF(x) +#define PRF(x) #endif #endif @@ -90,23 +90,23 @@ void AesGenTables(void) for (i = 0; i < 256; i++) { { - UInt32 a1 = Sbox[i]; - UInt32 a2 = xtime(a1); - UInt32 a3 = a2 ^ a1; + const UInt32 a1 = Sbox[i]; + const UInt32 a2 = xtime(a1); + const UInt32 a3 = a2 ^ a1; TT(0)[i] = Ui32(a2, a1, a1, a3); TT(1)[i] = Ui32(a3, a2, a1, a1); TT(2)[i] = Ui32(a1, a3, a2, a1); TT(3)[i] = Ui32(a1, a1, a3, a2); } { - UInt32 a1 = InvS[i]; - UInt32 a2 = xtime(a1); - UInt32 a4 = xtime(a2); - UInt32 a8 = xtime(a4); - UInt32 a9 = a8 ^ a1; - UInt32 aB = a8 ^ a2 ^ a1; - UInt32 aD = a8 ^ a4 ^ a1; - UInt32 aE = a8 ^ a4 ^ a2; + const UInt32 a1 = InvS[i]; + const UInt32 a2 = xtime(a1); + const UInt32 a4 = xtime(a2); + const UInt32 a8 = xtime(a4); + const UInt32 a9 = a8 ^ a1; + const UInt32 aB = a8 ^ a2 ^ a1; + const UInt32 aD = a8 ^ a4 ^ a1; + const UInt32 aE = a8 ^ a4 ^ a2; DD(0)[i] = Ui32(aE, a9, aD, aB); DD(1)[i] = Ui32(aB, aE, a9, aD); DD(2)[i] = Ui32(aD, aB, aE, a9); @@ -116,7 +116,7 @@ void AesGenTables(void) { AES_CODE_FUNC d = AesCbc_Decode; - #ifndef _SFX + #ifndef Z7_SFX AES_CODE_FUNC e = AesCbc_Encode; AES_CODE_FUNC c = AesCtr_Code; UInt32 flags = 0; @@ -126,10 +126,10 @@ void AesGenTables(void) if (CPU_IsSupported_AES()) { // #pragma message ("AES HW") - _PRF(printf("\n===AES HW\n")); + PRF(printf("\n===AES HW\n")); d = AesCbc_Decode_HW; - #ifndef _SFX + #ifndef Z7_SFX e = AesCbc_Encode_HW; c = AesCtr_Code_HW; flags = k_Aes_SupportedFunctions_HW; @@ -138,9 +138,9 @@ void AesGenTables(void) #ifdef MY_CPU_X86_OR_AMD64 if (CPU_IsSupported_VAES_AVX2()) { - _PRF(printf("\n===vaes avx2\n")); + PRF(printf("\n===vaes avx2\n")); d = AesCbc_Decode_HW_256; - #ifndef _SFX + #ifndef Z7_SFX c = AesCtr_Code_HW_256; flags |= k_Aes_SupportedFunctions_HW_256; #endif @@ -150,7 +150,7 @@ void AesGenTables(void) #endif g_AesCbc_Decode = d; - #ifndef _SFX + #ifndef Z7_SFX g_AesCbc_Encode = e; g_AesCtr_Code = c; g_Aes_SupportedFunctions_Flags = flags; @@ -194,7 +194,7 @@ void AesGenTables(void) #define FD(i, x) InvS[gb(x, m[(i - x) & 3])] #define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; -void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) +void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) { unsigned i, m; const UInt32 *wLim; @@ -230,7 +230,7 @@ void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) while (++w != wLim); } -void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) +void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) { unsigned i, num; Aes_SetKey_Enc(w, key, keySize); @@ -251,7 +251,7 @@ void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) src and dest are pointers to 4 UInt32 words. src and dest can point to same block */ -// MY_FORCE_INLINE +// Z7_FORCE_INLINE static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) { UInt32 s[4]; @@ -265,17 +265,20 @@ static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) w += 4; for (;;) { - HT16(m, s, 0); + HT16(m, s, 0) if (--numRounds2 == 0) break; - HT16(s, m, 4); + HT16(s, m, 4) w += 8; } w += 4; - FT4(0); FT4(1); FT4(2); FT4(3); + FT4(0) + FT4(1) + FT4(2) + FT4(3) } -MY_FORCE_INLINE +Z7_FORCE_INLINE static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) { UInt32 s[4]; @@ -289,12 +292,15 @@ static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) for (;;) { w -= 8; - HD16(m, s, 4); + HD16(m, s, 4) if (--numRounds2 == 0) break; - HD16(s, m, 0); + HD16(s, m, 0) } - FD4(0); FD4(1); FD4(2); FD4(3); + FD4(0) + FD4(1) + FD4(2) + FD4(3) } void AesCbc_Init(UInt32 *p, const Byte *iv) @@ -304,7 +310,7 @@ void AesCbc_Init(UInt32 *p, const Byte *iv) p[i] = GetUi32(iv + i * 4); } -void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) +void Z7_FASTCALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) { for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) { @@ -315,14 +321,14 @@ void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) Aes_Encode(p + 4, p, p); - SetUi32(data, p[0]); - SetUi32(data + 4, p[1]); - SetUi32(data + 8, p[2]); - SetUi32(data + 12, p[3]); + SetUi32(data, p[0]) + SetUi32(data + 4, p[1]) + SetUi32(data + 8, p[2]) + SetUi32(data + 12, p[3]) } } -void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) +void Z7_FASTCALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) { UInt32 in[4], out[4]; for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) @@ -334,10 +340,10 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) Aes_Decode(p + 4, out, in); - SetUi32(data, p[0] ^ out[0]); - SetUi32(data + 4, p[1] ^ out[1]); - SetUi32(data + 8, p[2] ^ out[2]); - SetUi32(data + 12, p[3] ^ out[3]); + SetUi32(data, p[0] ^ out[0]) + SetUi32(data + 4, p[1] ^ out[1]) + SetUi32(data + 8, p[2] ^ out[2]) + SetUi32(data + 12, p[3] ^ out[3]) p[0] = in[0]; p[1] = in[1]; @@ -346,7 +352,7 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) } } -void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) +void Z7_FASTCALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) { for (; numBlocks != 0; numBlocks--) { @@ -360,7 +366,7 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) for (i = 0; i < 4; i++, data += 4) { - UInt32 t = temp[i]; + const UInt32 t = temp[i]; #ifdef MY_CPU_LE_UNALIGN *((UInt32 *)(void *)data) ^= t; @@ -373,3 +379,15 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) } } } + +#undef xtime +#undef Ui32 +#undef gb0 +#undef gb1 +#undef gb2 +#undef gb3 +#undef gb +#undef TT +#undef DD +#undef USE_HW_AES +#undef PRF diff --git a/C/Aes.h b/C/Aes.h index 2aa22564..7f0182ac 100644 --- a/C/Aes.h +++ b/C/Aes.h @@ -1,8 +1,8 @@ /* Aes.h -- AES encryption / decryption -2018-04-28 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __AES_H -#define __AES_H +#ifndef ZIP7_INC_AES_H +#define ZIP7_INC_AES_H #include "7zTypes.h" @@ -20,19 +20,19 @@ void AesGenTables(void); /* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */ /* keySize = 16 or 24 or 32 (bytes) */ -typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); -void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); -void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); +typedef void (Z7_FASTCALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); +void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); +void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); /* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */ void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ /* data - 16-byte aligned pointer to data */ /* numBlocks - the number of 16-byte blocks in data array */ -typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); +typedef void (Z7_FASTCALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); extern AES_CODE_FUNC g_AesCbc_Decode; -#ifndef _SFX +#ifndef Z7_SFX extern AES_CODE_FUNC g_AesCbc_Encode; extern AES_CODE_FUNC g_AesCtr_Code; #define k_Aes_SupportedFunctions_HW (1 << 2) @@ -41,19 +41,19 @@ extern UInt32 g_Aes_SupportedFunctions_Flags; #endif -#define DECLARE__AES_CODE_FUNC(funcName) \ - void MY_FAST_CALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); +#define Z7_DECLARE_AES_CODE_FUNC(funcName) \ + void Z7_FASTCALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); -DECLARE__AES_CODE_FUNC (AesCbc_Encode) -DECLARE__AES_CODE_FUNC (AesCbc_Decode) -DECLARE__AES_CODE_FUNC (AesCtr_Code) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode) +Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code) -DECLARE__AES_CODE_FUNC (AesCbc_Encode_HW) -DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW) -DECLARE__AES_CODE_FUNC (AesCtr_Code_HW) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode_HW) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW) +Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW) -DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW_256) -DECLARE__AES_CODE_FUNC (AesCtr_Code_HW_256) +Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW_256) +Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW_256) EXTERN_C_END diff --git a/C/AesOpt.c b/C/AesOpt.c index 8be8ff69..cfa6413f 100644 --- a/C/AesOpt.c +++ b/C/AesOpt.c @@ -1,39 +1,33 @@ /* AesOpt.c -- AES optimized code for x86 AES hardware instructions -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" +#include "Aes.h" #include "CpuArch.h" #ifdef MY_CPU_X86_OR_AMD64 - #if defined(__clang__) - #if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 8) - #define USE_INTEL_AES - #define ATTRIB_AES __attribute__((__target__("aes"))) - #if (__clang_major__ >= 8) - #define USE_INTEL_VAES - #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) - #endif - #endif - #elif defined(__GNUC__) - #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) - #define USE_INTEL_AES - #ifndef __AES__ - #define ATTRIB_AES __attribute__((__target__("aes"))) - #endif - #if (__GNUC__ >= 8) - #define USE_INTEL_VAES - #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2"))) - #endif - #endif - #elif defined(__INTEL_COMPILER) + #if defined(__INTEL_COMPILER) #if (__INTEL_COMPILER >= 1110) #define USE_INTEL_AES #if (__INTEL_COMPILER >= 1900) #define USE_INTEL_VAES #endif #endif + #elif defined(__clang__) && (__clang_major__ > 3 || __clang_major__ == 3 && __clang_minor__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4) + #define USE_INTEL_AES + #if !defined(__AES__) + #define ATTRIB_AES __attribute__((__target__("aes"))) + #endif + #if defined(__clang__) && (__clang_major__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ >= 8) + #define USE_INTEL_VAES + #if !defined(__AES__) || !defined(__VAES__) || !defined(__AVX__) || !defined(__AVX2__) + #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx,avx2"))) + #endif + #endif #elif defined(_MSC_VER) #if (_MSC_VER > 1500) || (_MSC_FULL_VER >= 150030729) #define USE_INTEL_AES @@ -56,12 +50,15 @@ #include #ifndef USE_INTEL_VAES -#define AES_TYPE_keys __m128i -#define AES_TYPE_data __m128i +#define AES_TYPE_keys UInt32 +#define AES_TYPE_data Byte +// #define AES_TYPE_keys __m128i +// #define AES_TYPE_data __m128i #endif #define AES_FUNC_START(name) \ - void MY_FAST_CALL name(__m128i *p, __m128i *data, size_t numBlocks) + void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) + // void Z7_FASTCALL name(__m128i *p, __m128i *data, size_t numBlocks) #define AES_FUNC_START2(name) \ AES_FUNC_START (name); \ @@ -69,14 +66,16 @@ ATTRIB_AES \ AES_FUNC_START (name) #define MM_OP(op, dest, src) dest = op(dest, src); -#define MM_OP_m(op, src) MM_OP(op, m, src); +#define MM_OP_m(op, src) MM_OP(op, m, src) -#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src); -#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src); +#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src) +#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src) AES_FUNC_START2 (AesCbc_Encode_HW) { + __m128i *p = (__m128i *)(void *)ivAes; + __m128i *data = (__m128i *)(void *)data8; __m128i m = *p; const __m128i k0 = p[2]; const __m128i k1 = p[3]; @@ -86,17 +85,17 @@ AES_FUNC_START2 (AesCbc_Encode_HW) UInt32 r = numRounds2; const __m128i *w = p + 4; __m128i temp = *data; - MM_XOR (temp, k0); - MM_XOR (m, temp); - MM_OP_m (_mm_aesenc_si128, k1); + MM_XOR (temp, k0) + MM_XOR (m, temp) + MM_OP_m (_mm_aesenc_si128, k1) do { - MM_OP_m (_mm_aesenc_si128, w[0]); - MM_OP_m (_mm_aesenc_si128, w[1]); + MM_OP_m (_mm_aesenc_si128, w[0]) + MM_OP_m (_mm_aesenc_si128, w[1]) w += 2; } while (--r); - MM_OP_m (_mm_aesenclast_si128, w[0]); + MM_OP_m (_mm_aesenclast_si128, w[0]) *data = m; } *p = m; @@ -104,14 +103,14 @@ AES_FUNC_START2 (AesCbc_Encode_HW) #define WOP_1(op) -#define WOP_2(op) WOP_1 (op) op (m1, 1); -#define WOP_3(op) WOP_2 (op) op (m2, 2); -#define WOP_4(op) WOP_3 (op) op (m3, 3); +#define WOP_2(op) WOP_1 (op) op (m1, 1) +#define WOP_3(op) WOP_2 (op) op (m2, 2) +#define WOP_4(op) WOP_3 (op) op (m3, 3) #ifdef MY_CPU_AMD64 -#define WOP_5(op) WOP_4 (op) op (m4, 4); -#define WOP_6(op) WOP_5 (op) op (m5, 5); -#define WOP_7(op) WOP_6 (op) op (m6, 6); -#define WOP_8(op) WOP_7 (op) op (m7, 7); +#define WOP_5(op) WOP_4 (op) op (m4, 4) +#define WOP_6(op) WOP_5 (op) op (m5, 5) +#define WOP_7(op) WOP_6 (op) op (m6, 6) +#define WOP_8(op) WOP_7 (op) op (m7, 7) #endif /* #define WOP_9(op) WOP_8 (op) op (m8, 8); @@ -130,20 +129,20 @@ AES_FUNC_START2 (AesCbc_Encode_HW) #define WOP_M1 WOP_4 #endif -#define WOP(op) op (m0, 0); WOP_M1(op) +#define WOP(op) op (m0, 0) WOP_M1(op) -#define DECLARE_VAR(reg, ii) __m128i reg +#define DECLARE_VAR(reg, ii) __m128i reg; #define LOAD_data( reg, ii) reg = data[ii]; #define STORE_data( reg, ii) data[ii] = reg; #if (NUM_WAYS > 1) -#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); +#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) #endif -#define AVX__DECLARE_VAR(reg, ii) __m256i reg -#define AVX__LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; -#define AVX__STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; -#define AVX__XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])); +#define AVX_DECLARE_VAR(reg, ii) __m256i reg; +#define AVX_LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; +#define AVX_STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; +#define AVX_XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])) #define MM_OP_key(op, reg) MM_OP(op, reg, key); @@ -154,23 +153,23 @@ AES_FUNC_START2 (AesCbc_Encode_HW) #define AES_XOR( reg, ii) MM_OP_key (_mm_xor_si128, reg) -#define AVX__AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) -#define AVX__AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) -#define AVX__AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) -#define AVX__AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) -#define AVX__AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) +#define AVX_AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) +#define AVX_AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) +#define AVX_AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) +#define AVX_AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) +#define AVX_AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) -#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one); reg = ctr; -#define CTR_END( reg, ii) MM_XOR (data[ii], reg); +#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one) reg = ctr; +#define CTR_END( reg, ii) MM_XOR (data[ii], reg) -#define AVX__CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two); reg = _mm256_xor_si256(ctr2, key); -#define AVX__CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg); +#define AVX_CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two) reg = _mm256_xor_si256(ctr2, key); +#define AVX_CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg) #define WOP_KEY(op, n) { \ const __m128i key = w[n]; \ WOP(op); } -#define AVX__WOP_KEY(op, n) { \ +#define AVX_WOP_KEY(op, n) { \ const __m256i key = w[n]; \ WOP(op); } @@ -218,6 +217,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) AES_FUNC_START2 (AesCbc_Decode_HW) { + __m128i *p = (__m128i *)(void *)ivAes; + __m128i *data = (__m128i *)(void *)data8; __m128i iv = *p; const __m128i *wStart = p + *(const UInt32 *)(p + 1) * 2 + 2 - 1; const __m128i *dataEnd; @@ -228,7 +229,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) const __m128i *w = wStart; WOP (DECLARE_VAR) - WOP (LOAD_data); + WOP (LOAD_data) WOP_KEY (AES_XOR, 1) do @@ -239,10 +240,10 @@ AES_FUNC_START2 (AesCbc_Decode_HW) while (w != p); WOP_KEY (AES_DEC_LAST, 0) - MM_XOR (m0, iv); + MM_XOR (m0, iv) WOP_M1 (XOR_data_M1) iv = data[NUM_WAYS - 1]; - WOP (STORE_data); + WOP (STORE_data) } WIDE_LOOP_END @@ -252,15 +253,15 @@ AES_FUNC_START2 (AesCbc_Decode_HW) __m128i m = _mm_xor_si128 (w[2], *data); do { - MM_OP_m (_mm_aesdec_si128, w[1]); - MM_OP_m (_mm_aesdec_si128, w[0]); + MM_OP_m (_mm_aesdec_si128, w[1]) + MM_OP_m (_mm_aesdec_si128, w[0]) w -= 2; } while (w != p); - MM_OP_m (_mm_aesdec_si128, w[1]); - MM_OP_m (_mm_aesdeclast_si128, w[0]); + MM_OP_m (_mm_aesdec_si128, w[1]) + MM_OP_m (_mm_aesdeclast_si128, w[0]) - MM_XOR (m, iv); + MM_XOR (m, iv) iv = *data; *data = m; } @@ -271,6 +272,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) AES_FUNC_START2 (AesCtr_Code_HW) { + __m128i *p = (__m128i *)(void *)ivAes; + __m128i *data = (__m128i *)(void *)data8; __m128i ctr = *p; UInt32 numRoundsMinus2 = *(const UInt32 *)(p + 1) * 2 - 1; const __m128i *dataEnd; @@ -283,7 +286,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) const __m128i *w = p; UInt32 r = numRoundsMinus2; WOP (DECLARE_VAR) - WOP (CTR_START); + WOP (CTR_START) WOP_KEY (AES_XOR, 0) w += 1; do @@ -294,7 +297,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) while (--r); WOP_KEY (AES_ENC_LAST, 0) - WOP (CTR_END); + WOP (CTR_END) } WIDE_LOOP_END @@ -303,19 +306,19 @@ AES_FUNC_START2 (AesCtr_Code_HW) UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; const __m128i *w = p; __m128i m; - MM_OP (_mm_add_epi64, ctr, one); + MM_OP (_mm_add_epi64, ctr, one) m = _mm_xor_si128 (ctr, p[0]); w += 1; do { - MM_OP_m (_mm_aesenc_si128, w[0]); - MM_OP_m (_mm_aesenc_si128, w[1]); + MM_OP_m (_mm_aesenc_si128, w[0]) + MM_OP_m (_mm_aesenc_si128, w[1]) w += 2; } while (--numRounds2); - MM_OP_m (_mm_aesenc_si128, w[0]); - MM_OP_m (_mm_aesenclast_si128, w[1]); - MM_XOR (*data, m); + MM_OP_m (_mm_aesenc_si128, w[0]) + MM_OP_m (_mm_aesenclast_si128, w[1]) + MM_XOR (*data, m) } p[-2] = ctr; @@ -325,17 +328,58 @@ AES_FUNC_START2 (AesCtr_Code_HW) #ifdef USE_INTEL_VAES +/* +GCC before 2013-Jun: + : + #ifdef __AVX__ + #include + #endif +GCC after 2013-Jun: + : + #include +CLANG 3.8+: +{ + : + #if !defined(_MSC_VER) || defined(__AVX__) + #include + #endif + + if (the compiler is clang for Windows and if global arch is not set for __AVX__) + [ if (defined(_MSC_VER) && !defined(__AVX__)) ] + { + doesn't include + and we have 2 ways to fix it: + 1) we can define required __AVX__ before + or + 2) we can include after + } +} + +If we include manually for GCC/CLANG, it's +required that must be included before . +*/ + +/* #if defined(__clang__) && defined(_MSC_VER) -#define __SSE4_2__ -#define __AES__ #define __AVX__ #define __AVX2__ #define __VAES__ -#define __AVX512F__ -#define __AVX512VL__ #endif +*/ #include +#if defined(__clang__) && defined(_MSC_VER) + #if !defined(__AVX__) + #include + #endif + #if !defined(__AVX2__) + #include + #endif + #if !defined(__VAES__) + #include + #endif +#endif // __clang__ && _MSC_VER + #define VAES_FUNC_START2(name) \ AES_FUNC_START (name); \ @@ -344,6 +388,8 @@ AES_FUNC_START (name) VAES_FUNC_START2 (AesCbc_Decode_HW_256) { + __m128i *p = (__m128i *)(void *)ivAes; + __m128i *data = (__m128i *)(void *)data8; __m128i iv = *p; const __m128i *dataEnd; UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; @@ -353,22 +399,22 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) { const __m256i *w = keys + numRounds - 2; - WOP (AVX__DECLARE_VAR) - WOP (AVX__LOAD_data); - AVX__WOP_KEY (AVX__AES_XOR, 1) + WOP (AVX_DECLARE_VAR) + WOP (AVX_LOAD_data) + AVX_WOP_KEY (AVX_AES_XOR, 1) do { - AVX__WOP_KEY (AVX__AES_DEC, 0) + AVX_WOP_KEY (AVX_AES_DEC, 0) w--; } while (w != keys); - AVX__WOP_KEY (AVX__AES_DEC_LAST, 0) + AVX_WOP_KEY (AVX_AES_DEC_LAST, 0) - AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])); - WOP_M1 (AVX__XOR_data_M1) + AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])) + WOP_M1 (AVX_XOR_data_M1) iv = data[NUM_WAYS * 2 - 1]; - WOP (AVX__STORE_data); + WOP (AVX_STORE_data) } WIDE_LOOP_END_AVX(;) @@ -378,15 +424,15 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256) __m128i m = _mm_xor_si128 (w[2], *data); do { - MM_OP_m (_mm_aesdec_si128, w[1]); - MM_OP_m (_mm_aesdec_si128, w[0]); + MM_OP_m (_mm_aesdec_si128, w[1]) + MM_OP_m (_mm_aesdec_si128, w[0]) w -= 2; } while (w != p); - MM_OP_m (_mm_aesdec_si128, w[1]); - MM_OP_m (_mm_aesdeclast_si128, w[0]); + MM_OP_m (_mm_aesdec_si128, w[1]) + MM_OP_m (_mm_aesdeclast_si128, w[0]) - MM_XOR (m, iv); + MM_XOR (m, iv) iv = *data; *data = m; } @@ -403,18 +449,20 @@ AVX2: _mm256_add_epi64 : vpaddq ymm, ymm, ymm _mm256_broadcastsi128_si256 : vbroadcasti128 */ -#define AVX__CTR_LOOP_START \ +#define AVX_CTR_LOOP_START \ ctr2 = _mm256_setr_m128i(_mm_sub_epi64(ctr, one), ctr); \ two = _mm256_setr_m128i(one, one); \ two = _mm256_add_epi64(two, two); \ // two = _mm256_setr_epi64x(2, 0, 2, 0); -#define AVX__CTR_LOOP_ENC \ +#define AVX_CTR_LOOP_ENC \ ctr = _mm256_extracti128_si256 (ctr2, 1); \ VAES_FUNC_START2 (AesCtr_Code_HW_256) { + __m128i *p = (__m128i *)(void *)ivAes; + __m128i *data = (__m128i *)(void *)data8; __m128i ctr = *p; UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; const __m128i *dataEnd; @@ -422,44 +470,44 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) __m256i ctr2, two; p += 2; - WIDE_LOOP_START_AVX (AVX__CTR_LOOP_START) + WIDE_LOOP_START_AVX (AVX_CTR_LOOP_START) { const __m256i *w = keys; UInt32 r = numRounds - 2; - WOP (AVX__DECLARE_VAR) - AVX__WOP_KEY (AVX__CTR_START, 0); + WOP (AVX_DECLARE_VAR) + AVX_WOP_KEY (AVX_CTR_START, 0) w += 1; do { - AVX__WOP_KEY (AVX__AES_ENC, 0) + AVX_WOP_KEY (AVX_AES_ENC, 0) w += 1; } while (--r); - AVX__WOP_KEY (AVX__AES_ENC_LAST, 0) + AVX_WOP_KEY (AVX_AES_ENC_LAST, 0) - WOP (AVX__CTR_END); + WOP (AVX_CTR_END) } - WIDE_LOOP_END_AVX (AVX__CTR_LOOP_ENC) + WIDE_LOOP_END_AVX (AVX_CTR_LOOP_ENC) SINGLE_LOOP { UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; const __m128i *w = p; __m128i m; - MM_OP (_mm_add_epi64, ctr, one); + MM_OP (_mm_add_epi64, ctr, one) m = _mm_xor_si128 (ctr, p[0]); w += 1; do { - MM_OP_m (_mm_aesenc_si128, w[0]); - MM_OP_m (_mm_aesenc_si128, w[1]); + MM_OP_m (_mm_aesenc_si128, w[0]) + MM_OP_m (_mm_aesenc_si128, w[1]) w += 2; } while (--numRounds2); - MM_OP_m (_mm_aesenc_si128, w[0]); - MM_OP_m (_mm_aesenclast_si128, w[1]); - MM_XOR (*data, m); + MM_OP_m (_mm_aesenc_si128, w[0]) + MM_OP_m (_mm_aesenclast_si128, w[1]) + MM_XOR (*data, m) } p[-2] = ctr; @@ -477,7 +525,7 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256) #define AES_TYPE_data Byte #define AES_FUNC_START(name) \ - void MY_FAST_CALL name(UInt32 *p, Byte *data, size_t numBlocks) \ + void Z7_FASTCALL name(UInt32 *p, Byte *data, size_t numBlocks) \ #define AES_COMPAT_STUB(name) \ AES_FUNC_START(name); \ @@ -496,8 +544,8 @@ AES_COMPAT_STUB (AesCtr_Code) #pragma message("VAES HW_SW stub was used") #define VAES_COMPAT_STUB(name) \ - void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ - void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ + void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ + void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ { name((AES_TYPE_keys *)(void *)p, (AES_TYPE_data *)(void *)data, numBlocks); } VAES_COMPAT_STUB (AesCbc_Decode_HW) @@ -551,7 +599,8 @@ VAES_COMPAT_STUB (AesCtr_Code_HW) typedef uint8x16_t v128; #define AES_FUNC_START(name) \ - void MY_FAST_CALL name(v128 *p, v128 *data, size_t numBlocks) + void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks) + // void Z7_FASTCALL name(v128 *p, v128 *data, size_t numBlocks) #define AES_FUNC_START2(name) \ AES_FUNC_START (name); \ @@ -559,18 +608,20 @@ ATTRIB_AES \ AES_FUNC_START (name) #define MM_OP(op, dest, src) dest = op(dest, src); -#define MM_OP_m(op, src) MM_OP(op, m, src); +#define MM_OP_m(op, src) MM_OP(op, m, src) #define MM_OP1_m(op) m = op(m); -#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src); -#define MM_XOR_m( src) MM_XOR(m, src); +#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src) +#define MM_XOR_m( src) MM_XOR(m, src) -#define AES_E_m(k) MM_OP_m (vaeseq_u8, k); -#define AES_E_MC_m(k) AES_E_m (k); MM_OP1_m(vaesmcq_u8); +#define AES_E_m(k) MM_OP_m (vaeseq_u8, k) +#define AES_E_MC_m(k) AES_E_m (k) MM_OP1_m(vaesmcq_u8) AES_FUNC_START2 (AesCbc_Encode_HW) { + v128 *p = (v128*)(void*)ivAes; + v128 *data = (v128*)(void*)data8; v128 m = *p; const v128 k0 = p[2]; const v128 k1 = p[3]; @@ -608,7 +659,7 @@ AES_FUNC_START2 (AesCbc_Encode_HW) AES_E_MC_m (p[14]) } } - AES_E_m (k_z1); + AES_E_m (k_z1) MM_XOR_m (k_z0); *data = m; } @@ -617,44 +668,44 @@ AES_FUNC_START2 (AesCbc_Encode_HW) #define WOP_1(op) -#define WOP_2(op) WOP_1 (op) op (m1, 1); -#define WOP_3(op) WOP_2 (op) op (m2, 2); -#define WOP_4(op) WOP_3 (op) op (m3, 3); -#define WOP_5(op) WOP_4 (op) op (m4, 4); -#define WOP_6(op) WOP_5 (op) op (m5, 5); -#define WOP_7(op) WOP_6 (op) op (m6, 6); -#define WOP_8(op) WOP_7 (op) op (m7, 7); +#define WOP_2(op) WOP_1 (op) op (m1, 1) +#define WOP_3(op) WOP_2 (op) op (m2, 2) +#define WOP_4(op) WOP_3 (op) op (m3, 3) +#define WOP_5(op) WOP_4 (op) op (m4, 4) +#define WOP_6(op) WOP_5 (op) op (m5, 5) +#define WOP_7(op) WOP_6 (op) op (m6, 6) +#define WOP_8(op) WOP_7 (op) op (m7, 7) #define NUM_WAYS 8 #define WOP_M1 WOP_8 -#define WOP(op) op (m0, 0); WOP_M1(op) +#define WOP(op) op (m0, 0) WOP_M1(op) -#define DECLARE_VAR(reg, ii) v128 reg +#define DECLARE_VAR(reg, ii) v128 reg; #define LOAD_data( reg, ii) reg = data[ii]; #define STORE_data( reg, ii) data[ii] = reg; #if (NUM_WAYS > 1) -#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); +#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]) #endif -#define MM_OP_key(op, reg) MM_OP (op, reg, key); +#define MM_OP_key(op, reg) MM_OP (op, reg, key) -#define AES_D_m(k) MM_OP_m (vaesdq_u8, k); -#define AES_D_IMC_m(k) AES_D_m (k); MM_OP1_m (vaesimcq_u8); +#define AES_D_m(k) MM_OP_m (vaesdq_u8, k) +#define AES_D_IMC_m(k) AES_D_m (k) MM_OP1_m (vaesimcq_u8) #define AES_XOR( reg, ii) MM_OP_key (veorq_u8, reg) #define AES_D( reg, ii) MM_OP_key (vaesdq_u8, reg) #define AES_E( reg, ii) MM_OP_key (vaeseq_u8, reg) -#define AES_D_IMC( reg, ii) AES_D (reg, ii); reg = vaesimcq_u8(reg) -#define AES_E_MC( reg, ii) AES_E (reg, ii); reg = vaesmcq_u8(reg) +#define AES_D_IMC( reg, ii) AES_D (reg, ii) reg = vaesimcq_u8(reg); +#define AES_E_MC( reg, ii) AES_E (reg, ii) reg = vaesmcq_u8(reg); -#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one); reg = vreinterpretq_u8_u64(ctr); -#define CTR_END( reg, ii) MM_XOR (data[ii], reg); +#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one) reg = vreinterpretq_u8_u64(ctr); +#define CTR_END( reg, ii) MM_XOR (data[ii], reg) #define WOP_KEY(op, n) { \ const v128 key = w[n]; \ - WOP(op); } + WOP(op) } #define WIDE_LOOP_START \ dataEnd = data + numBlocks; \ @@ -672,6 +723,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW) AES_FUNC_START2 (AesCbc_Decode_HW) { + v128 *p = (v128*)(void*)ivAes; + v128 *data = (v128*)(void*)data8; v128 iv = *p; const v128 *wStart = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; const v128 *dataEnd; @@ -681,7 +734,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) { const v128 *w = wStart; WOP (DECLARE_VAR) - WOP (LOAD_data); + WOP (LOAD_data) WOP_KEY (AES_D_IMC, 2) do { @@ -695,7 +748,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW) MM_XOR (m0, iv); WOP_M1 (XOR_data_M1) iv = data[NUM_WAYS - 1]; - WOP (STORE_data); + WOP (STORE_data) } WIDE_LOOP_END @@ -724,6 +777,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW) AES_FUNC_START2 (AesCtr_Code_HW) { + v128 *p = (v128*)(void*)ivAes; + v128 *data = (v128*)(void*)data8; uint64x2_t ctr = vreinterpretq_u64_u8(*p); const v128 *wEnd = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; const v128 *dataEnd; @@ -735,7 +790,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) { const v128 *w = p; WOP (DECLARE_VAR) - WOP (CTR_START); + WOP (CTR_START) do { WOP_KEY (AES_E_MC, 0) @@ -746,7 +801,7 @@ AES_FUNC_START2 (AesCtr_Code_HW) WOP_KEY (AES_E_MC, 0) WOP_KEY (AES_E, 1) WOP_KEY (AES_XOR, 2) - WOP (CTR_END); + WOP (CTR_END) } WIDE_LOOP_END @@ -762,10 +817,10 @@ AES_FUNC_START2 (AesCtr_Code_HW) w += 2; } while (w != wEnd); - AES_E_MC_m (w[0]); - AES_E_m (w[1]); - MM_XOR_m (w[2]); - CTR_END (m, 0); + AES_E_MC_m (w[0]) + AES_E_m (w[1]) + MM_XOR_m (w[2]) + CTR_END (m, 0) } p[-2] = vreinterpretq_u8_u64(ctr); @@ -774,3 +829,12 @@ AES_FUNC_START2 (AesCtr_Code_HW) #endif // USE_HW_AES #endif // MY_CPU_ARM_OR_ARM64 + +#undef NUM_WAYS +#undef WOP_M1 +#undef WOP +#undef DECLARE_VAR +#undef LOAD_data +#undef STORE_data +#undef USE_INTEL_AES +#undef USE_HW_AES diff --git a/C/Alloc.c b/C/Alloc.c index d1af76c5..d841bf20 100644 --- a/C/Alloc.c +++ b/C/Alloc.c @@ -1,38 +1,54 @@ /* Alloc.c -- Memory allocation functions -2021-07-13 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" -#include - #ifdef _WIN32 -#include +#include "7zWindows.h" #endif #include #include "Alloc.h" -/* #define _SZ_ALLOC_DEBUG */ +#ifdef _WIN32 +#ifdef Z7_LARGE_PAGES +#if defined(__clang__) || defined(__GNUC__) +typedef void (*Z7_voidFunction)(void); +#define MY_CAST_FUNC (Z7_voidFunction) +#elif defined(_MSC_VER) && _MSC_VER > 1920 +#define MY_CAST_FUNC (void *) +// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()' +#else +#define MY_CAST_FUNC +#endif +#endif // Z7_LARGE_PAGES +#endif // _WIN32 + +// #define SZ_ALLOC_DEBUG +/* #define SZ_ALLOC_DEBUG */ -/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ -#ifdef _SZ_ALLOC_DEBUG +/* use SZ_ALLOC_DEBUG to debug alloc/free operations */ +#ifdef SZ_ALLOC_DEBUG +#include #include -int g_allocCount = 0; -int g_allocCountMid = 0; -int g_allocCountBig = 0; +static int g_allocCount = 0; +#ifdef _WIN32 +static int g_allocCountMid = 0; +static int g_allocCountBig = 0; +#endif #define CONVERT_INT_TO_STR(charType, tempSize) \ - unsigned char temp[tempSize]; unsigned i = 0; \ - while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \ + char temp[tempSize]; unsigned i = 0; \ + while (val >= 10) { temp[i++] = (char)('0' + (unsigned)(val % 10)); val /= 10; } \ *s++ = (charType)('0' + (unsigned)val); \ while (i != 0) { i--; *s++ = temp[i]; } \ *s = 0; static void ConvertUInt64ToString(UInt64 val, char *s) { - CONVERT_INT_TO_STR(char, 24); + CONVERT_INT_TO_STR(char, 24) } #define GET_HEX_CHAR(t) ((char)(((t < 10) ? ('0' + t) : ('A' + (t - 10))))) @@ -77,7 +93,7 @@ static void PrintAligned(const char *s, size_t align) Print(s); } -static void PrintLn() +static void PrintLn(void) { Print("\n"); } @@ -89,10 +105,10 @@ static void PrintHex(UInt64 v, size_t align) PrintAligned(s, align); } -static void PrintDec(UInt64 v, size_t align) +static void PrintDec(int v, size_t align) { char s[32]; - ConvertUInt64ToString(v, s); + ConvertUInt64ToString((unsigned)v, s); PrintAligned(s, align); } @@ -102,12 +118,19 @@ static void PrintAddr(void *p) } -#define PRINT_ALLOC(name, cnt, size, ptr) \ +#define PRINT_REALLOC(name, cnt, size, ptr) { \ + Print(name " "); \ + if (!ptr) PrintDec(cnt++, 10); \ + PrintHex(size, 10); \ + PrintAddr(ptr); \ + PrintLn(); } + +#define PRINT_ALLOC(name, cnt, size, ptr) { \ Print(name " "); \ PrintDec(cnt++, 10); \ PrintHex(size, 10); \ PrintAddr(ptr); \ - PrintLn(); + PrintLn(); } #define PRINT_FREE(name, cnt, ptr) if (ptr) { \ Print(name " "); \ @@ -117,7 +140,9 @@ static void PrintAddr(void *p) #else +#ifdef _WIN32 #define PRINT_ALLOC(name, cnt, size, ptr) +#endif #define PRINT_FREE(name, cnt, ptr) #define Print(s) #define PrintLn() @@ -127,16 +152,31 @@ static void PrintAddr(void *p) #endif +/* +by specification: + malloc(non_NULL, 0) : returns NULL or a unique pointer value that can later be successfully passed to free() + realloc(NULL, size) : the call is equivalent to malloc(size) + realloc(non_NULL, 0) : the call is equivalent to free(ptr) + +in main compilers: + malloc(0) : returns non_NULL + realloc(NULL, 0) : returns non_NULL + realloc(non_NULL, 0) : returns NULL +*/ + void *MyAlloc(size_t size) { if (size == 0) return NULL; - PRINT_ALLOC("Alloc ", g_allocCount, size, NULL); - #ifdef _SZ_ALLOC_DEBUG + // PRINT_ALLOC("Alloc ", g_allocCount, size, NULL) + #ifdef SZ_ALLOC_DEBUG { void *p = malloc(size); - // PRINT_ALLOC("Alloc ", g_allocCount, size, p); + if (p) + { + PRINT_ALLOC("Alloc ", g_allocCount, size, p) + } return p; } #else @@ -146,33 +186,64 @@ void *MyAlloc(size_t size) void MyFree(void *address) { - PRINT_FREE("Free ", g_allocCount, address); + PRINT_FREE("Free ", g_allocCount, address) free(address); } +void *MyRealloc(void *address, size_t size) +{ + if (size == 0) + { + MyFree(address); + return NULL; + } + // PRINT_REALLOC("Realloc ", g_allocCount, size, address) + #ifdef SZ_ALLOC_DEBUG + { + void *p = realloc(address, size); + if (p) + { + PRINT_REALLOC("Realloc ", g_allocCount, size, address) + } + return p; + } + #else + return realloc(address, size); + #endif +} + + #ifdef _WIN32 void *MidAlloc(size_t size) { if (size == 0) return NULL; - - PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, NULL); - + #ifdef SZ_ALLOC_DEBUG + { + void *p = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); + if (p) + { + PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, p) + } + return p; + } + #else return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); + #endif } void MidFree(void *address) { - PRINT_FREE("Free-Mid", g_allocCountMid, address); + PRINT_FREE("Free-Mid", g_allocCountMid, address) if (!address) return; VirtualFree(address, 0, MEM_RELEASE); } -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES #ifdef MEM_LARGE_PAGES #define MY__MEM_LARGE_PAGES MEM_LARGE_PAGES @@ -183,34 +254,35 @@ void MidFree(void *address) extern SIZE_T g_LargePageSize; SIZE_T g_LargePageSize = 0; -typedef SIZE_T (WINAPI *GetLargePageMinimumP)(VOID); +typedef SIZE_T (WINAPI *Func_GetLargePageMinimum)(VOID); -#endif // _7ZIP_LARGE_PAGES - -void SetLargePageSize() +void SetLargePageSize(void) { - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES SIZE_T size; - GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) - GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); - if (!largePageMinimum) + const + Func_GetLargePageMinimum fn = + (Func_GetLargePageMinimum) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), + "GetLargePageMinimum"); + if (!fn) return; - size = largePageMinimum(); + size = fn(); if (size == 0 || (size & (size - 1)) != 0) return; g_LargePageSize = size; #endif } +#endif // Z7_LARGE_PAGES void *BigAlloc(size_t size) { if (size == 0) return NULL; - PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL); - - #ifdef _7ZIP_LARGE_PAGES + PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL) + + #ifdef Z7_LARGE_PAGES { SIZE_T ps = g_LargePageSize; if (ps != 0 && ps <= (1 << 30) && size > (ps / 2)) @@ -220,38 +292,38 @@ void *BigAlloc(size_t size) size2 = (size + ps) & ~ps; if (size2 >= size) { - void *res = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); - if (res) - return res; + void *p = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); + if (p) + { + PRINT_ALLOC("Alloc-BM ", g_allocCountMid, size2, p) + return p; + } } } } #endif - return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); + return MidAlloc(size); } void BigFree(void *address) { - PRINT_FREE("Free-Big", g_allocCountBig, address); - - if (!address) - return; - VirtualFree(address, 0, MEM_RELEASE); + PRINT_FREE("Free-Big", g_allocCountBig, address) + MidFree(address); } -#endif +#endif // _WIN32 -static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MyAlloc(size); } -static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MyFree(address); } +static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MyAlloc(size); } +static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MyFree(address); } const ISzAlloc g_Alloc = { SzAlloc, SzFree }; #ifdef _WIN32 -static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MidAlloc(size); } -static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MidFree(address); } -static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return BigAlloc(size); } -static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); BigFree(address); } +static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MidAlloc(size); } +static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MidFree(address); } +static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return BigAlloc(size); } +static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) BigFree(address); } const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree }; const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; #endif @@ -334,7 +406,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) void *p; void *pAligned; size_t newSize; - UNUSED_VAR(pp); + UNUSED_VAR(pp) /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned block to prevent cache line sharing with another allocated blocks */ @@ -362,7 +434,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) #else void *p; - UNUSED_VAR(pp); + UNUSED_VAR(pp) if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size)) return NULL; @@ -377,7 +449,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) static void SzAlignedFree(ISzAllocPtr pp, void *address) { - UNUSED_VAR(pp); + UNUSED_VAR(pp) #ifndef USE_posix_memalign if (address) MyFree(((void **)address)[-1]); @@ -401,7 +473,7 @@ const ISzAlloc g_AlignedAlloc = { SzAlignedAlloc, SzAlignedFree }; static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size) { - CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); + const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); void *adr; void *pAligned; size_t newSize; @@ -447,7 +519,7 @@ static void AlignOffsetAlloc_Free(ISzAllocPtr pp, void *address) { if (address) { - CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); + const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt); PrintLn(); Print("- Aligned Free: "); PrintLn(); diff --git a/C/Alloc.h b/C/Alloc.h index 3be2041e..fac5b62f 100644 --- a/C/Alloc.h +++ b/C/Alloc.h @@ -1,19 +1,32 @@ /* Alloc.h -- Memory allocation functions -2021-07-13 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __COMMON_ALLOC_H -#define __COMMON_ALLOC_H +#ifndef ZIP7_INC_ALLOC_H +#define ZIP7_INC_ALLOC_H #include "7zTypes.h" EXTERN_C_BEGIN +/* + MyFree(NULL) : is allowed, as free(NULL) + MyAlloc(0) : returns NULL : but malloc(0) is allowed to return NULL or non_NULL + MyRealloc(NULL, 0) : returns NULL : but realloc(NULL, 0) is allowed to return NULL or non_NULL +MyRealloc() is similar to realloc() for the following cases: + MyRealloc(non_NULL, 0) : returns NULL and always calls MyFree(ptr) + MyRealloc(NULL, non_ZERO) : returns NULL, if allocation failed + MyRealloc(non_NULL, non_ZERO) : returns NULL, if reallocation failed +*/ + void *MyAlloc(size_t size); void MyFree(void *address); +void *MyRealloc(void *address, size_t size); #ifdef _WIN32 +#ifdef Z7_LARGE_PAGES void SetLargePageSize(void); +#endif void *MidAlloc(size_t size); void MidFree(void *address); diff --git a/C/Bcj2.c b/C/Bcj2.c index c7b95670..7cb57ad6 100644 --- a/C/Bcj2.c +++ b/C/Bcj2.c @@ -1,29 +1,24 @@ /* Bcj2.c -- BCJ2 Decoder (Converter for x86 code) -2021-02-09 : Igor Pavlov : Public domain */ +2023-03-01 : Igor Pavlov : Public domain */ #include "Precomp.h" #include "Bcj2.h" #include "CpuArch.h" -#define CProb UInt16 - #define kTopValue ((UInt32)1 << 24) -#define kNumModelBits 11 -#define kBitModelTotal (1 << kNumModelBits) +#define kNumBitModelTotalBits 11 +#define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 -#define _IF_BIT_0 ttt = *prob; bound = (p->range >> kNumModelBits) * ttt; if (p->code < bound) -#define _UPDATE_0 p->range = bound; *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -#define _UPDATE_1 p->range -= bound; p->code -= bound; *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); +// UInt32 bcj2_stats[256 + 2][2]; void Bcj2Dec_Init(CBcj2Dec *p) { unsigned i; - - p->state = BCJ2_DEC_STATE_OK; + p->state = BCJ2_STREAM_RC; // BCJ2_DEC_STATE_OK; p->ip = 0; - p->temp[3] = 0; + p->temp = 0; p->range = 0; p->code = 0; for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) @@ -32,217 +27,248 @@ void Bcj2Dec_Init(CBcj2Dec *p) SRes Bcj2Dec_Decode(CBcj2Dec *p) { + UInt32 v = p->temp; + // const Byte *src; if (p->range <= 5) { - p->state = BCJ2_DEC_STATE_OK; + UInt32 code = p->code; + p->state = BCJ2_DEC_STATE_ERROR; /* for case if we return SZ_ERROR_DATA; */ for (; p->range != 5; p->range++) { - if (p->range == 1 && p->code != 0) + if (p->range == 1 && code != 0) return SZ_ERROR_DATA; - if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) { p->state = BCJ2_STREAM_RC; return SZ_OK; } - - p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; + code = (code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; + p->code = code; } - - if (p->code == 0xFFFFFFFF) + if (code == 0xffffffff) return SZ_ERROR_DATA; - - p->range = 0xFFFFFFFF; + p->range = 0xffffffff; } - else if (p->state >= BCJ2_DEC_STATE_ORIG_0) + // else { - while (p->state <= BCJ2_DEC_STATE_ORIG_3) + unsigned state = p->state; + // we check BCJ2_IS_32BIT_STREAM() here instead of check in the main loop + if (BCJ2_IS_32BIT_STREAM(state)) { - Byte *dest = p->dest; - if (dest == p->destLim) + const Byte *cur = p->bufs[state]; + if (cur == p->lims[state]) return SZ_OK; - *dest = p->temp[(size_t)p->state - BCJ2_DEC_STATE_ORIG_0]; - p->state++; - p->dest = dest + 1; + p->bufs[state] = cur + 4; + { + const UInt32 ip = p->ip + 4; + v = GetBe32a(cur) - ip; + p->ip = ip; + } + state = BCJ2_DEC_STATE_ORIG_0; } - } - - /* - if (BCJ2_IS_32BIT_STREAM(p->state)) - { - const Byte *cur = p->bufs[p->state]; - if (cur == p->lims[p->state]) - return SZ_OK; - p->bufs[p->state] = cur + 4; - + if ((unsigned)(state - BCJ2_DEC_STATE_ORIG_0) < 4) { - UInt32 val; - Byte *dest; - SizeT rem; - - p->ip += 4; - val = GetBe32(cur) - p->ip; - dest = p->dest; - rem = p->destLim - dest; - if (rem < 4) + Byte *dest = p->dest; + for (;;) { - SizeT i; - SetUi32(p->temp, val); - for (i = 0; i < rem; i++) - dest[i] = p->temp[i]; - p->dest = dest + rem; - p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; - return SZ_OK; + if (dest == p->destLim) + { + p->state = state; + p->temp = v; + return SZ_OK; + } + *dest++ = (Byte)v; + p->dest = dest; + if (++state == BCJ2_DEC_STATE_ORIG_3 + 1) + break; + v >>= 8; } - SetUi32(dest, val); - p->temp[3] = (Byte)(val >> 24); - p->dest = dest + 4; - p->state = BCJ2_DEC_STATE_OK; } } - */ + // src = p->bufs[BCJ2_STREAM_MAIN]; for (;;) { + /* if (BCJ2_IS_32BIT_STREAM(p->state)) p->state = BCJ2_DEC_STATE_OK; else + */ { if (p->range < kTopValue) { if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) { p->state = BCJ2_STREAM_RC; + p->temp = v; return SZ_OK; } p->range <<= 8; p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; } - { const Byte *src = p->bufs[BCJ2_STREAM_MAIN]; const Byte *srcLim; - Byte *dest; - SizeT num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); - - if (num == 0) + Byte *dest = p->dest; { - p->state = BCJ2_STREAM_MAIN; - return SZ_OK; + const SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src); + SizeT num = (SizeT)(p->destLim - dest); + if (num >= rem) + num = rem; + #define NUM_ITERS 4 + #if (NUM_ITERS & (NUM_ITERS - 1)) == 0 + num &= ~((SizeT)NUM_ITERS - 1); // if (NUM_ITERS == (1 << x)) + #else + num -= num % NUM_ITERS; // if (NUM_ITERS != (1 << x)) + #endif + srcLim = src + num; } - - dest = p->dest; - if (num > (SizeT)(p->destLim - dest)) + + #define NUM_SHIFT_BITS 24 + #define ONE_ITER(indx) { \ + const unsigned b = src[indx]; \ + *dest++ = (Byte)b; \ + v = (v << NUM_SHIFT_BITS) | b; \ + if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ + if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ + ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ + /* ++dest */; /* v = b; */ } + + if (src != srcLim) + for (;;) { - num = (SizeT)(p->destLim - dest); - if (num == 0) - { - p->state = BCJ2_DEC_STATE_ORIG; - return SZ_OK; - } + /* The dependency chain of 2-cycle for (v) calculation is not big problem here. + But we can remove dependency chain with v = b in the end of loop. */ + ONE_ITER(0) + #if (NUM_ITERS > 1) + ONE_ITER(1) + #if (NUM_ITERS > 2) + ONE_ITER(2) + #if (NUM_ITERS > 3) + ONE_ITER(3) + #if (NUM_ITERS > 4) + ONE_ITER(4) + #if (NUM_ITERS > 5) + ONE_ITER(5) + #if (NUM_ITERS > 6) + ONE_ITER(6) + #if (NUM_ITERS > 7) + ONE_ITER(7) + #endif + #endif + #endif + #endif + #endif + #endif + #endif + + src += NUM_ITERS; + if (src == srcLim) + break; } - - srcLim = src + num; - if (p->temp[3] == 0x0F && (src[0] & 0xF0) == 0x80) - *dest = src[0]; - else for (;;) + if (src == srcLim) + #if (NUM_ITERS > 1) + for (;;) + #endif { - Byte b = *src; - *dest = b; - if (b != 0x0F) + #if (NUM_ITERS > 1) + if (src == p->lims[BCJ2_STREAM_MAIN] || dest == p->destLim) + #endif { - if ((b & 0xFE) == 0xE8) - break; - dest++; - if (++src != srcLim) - continue; - break; + const SizeT num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); + p->bufs[BCJ2_STREAM_MAIN] = src; + p->dest = dest; + p->ip += (UInt32)num; + /* state BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ + p->state = + src == p->lims[BCJ2_STREAM_MAIN] ? + (unsigned)BCJ2_STREAM_MAIN : + (unsigned)BCJ2_DEC_STATE_ORIG; + p->temp = v; + return SZ_OK; } - dest++; - if (++src == srcLim) - break; - if ((*src & 0xF0) != 0x80) - continue; - *dest = *src; - break; + #if (NUM_ITERS > 1) + ONE_ITER(0) + src++; + #endif } - - num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]); - - if (src == srcLim) + { - p->temp[3] = src[-1]; - p->bufs[BCJ2_STREAM_MAIN] = src; + const SizeT num = (SizeT)(dest - p->dest); + p->dest = dest; // p->dest += num; + p->bufs[BCJ2_STREAM_MAIN] += num; // = src; p->ip += (UInt32)num; - p->dest += num; - p->state = - p->bufs[BCJ2_STREAM_MAIN] == - p->lims[BCJ2_STREAM_MAIN] ? - (unsigned)BCJ2_STREAM_MAIN : - (unsigned)BCJ2_DEC_STATE_ORIG; - return SZ_OK; } - { UInt32 bound, ttt; - CProb *prob; - Byte b = src[0]; - Byte prev = (Byte)(num == 0 ? p->temp[3] : src[-1]); - - p->temp[3] = b; - p->bufs[BCJ2_STREAM_MAIN] = src + 1; - num++; - p->ip += (UInt32)num; - p->dest += num; - - prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)prev : (b == 0xE9 ? 1 : 0)); - - _IF_BIT_0 + CBcj2Prob *prob; // unsigned index; + /* + prob = p->probs + (unsigned)((Byte)v == 0xe8 ? + 2 + (Byte)(v >> 8) : + ((v >> 5) & 1)); // ((Byte)v < 0xe8 ? 0 : 1)); + */ { - _UPDATE_0 + const unsigned c = ((v + 0x17) >> 6) & 1; + prob = p->probs + (unsigned) + (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1)); + // (Byte) + // 8x->0 : e9->1 : xxe8->xx+2 + // 8x->0x100 : e9->0x101 : xxe8->xx + // (((0x100 - (e & ~v)) & (0x100 | (v >> 8))) + (e & v)); + // (((0x101 + (~e | v)) & (0x100 | (v >> 8))) + (e & v)); + } + ttt = *prob; + bound = (p->range >> kNumBitModelTotalBits) * ttt; + if (p->code < bound) + { + // bcj2_stats[prob - p->probs][0]++; + p->range = bound; + *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); continue; } - _UPDATE_1 - + { + // bcj2_stats[prob - p->probs][1]++; + p->range -= bound; + p->code -= bound; + *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits)); + } } } } - { - UInt32 val; - unsigned cj = (p->temp[3] == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; + /* (v == 0xe8 ? 0 : 1) uses setcc instruction with additional zero register usage in x64 MSVC. */ + // const unsigned cj = ((Byte)v == 0xe8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; + const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL; const Byte *cur = p->bufs[cj]; Byte *dest; SizeT rem; - if (cur == p->lims[cj]) { p->state = cj; break; } - - val = GetBe32(cur); + v = GetBe32a(cur); p->bufs[cj] = cur + 4; - - p->ip += 4; - val -= p->ip; + { + const UInt32 ip = p->ip + 4; + v -= ip; + p->ip = ip; + } dest = p->dest; rem = (SizeT)(p->destLim - dest); - if (rem < 4) { - p->temp[0] = (Byte)val; if (rem > 0) dest[0] = (Byte)val; val >>= 8; - p->temp[1] = (Byte)val; if (rem > 1) dest[1] = (Byte)val; val >>= 8; - p->temp[2] = (Byte)val; if (rem > 2) dest[2] = (Byte)val; val >>= 8; - p->temp[3] = (Byte)val; + if ((unsigned)rem > 0) { dest[0] = (Byte)v; v >>= 8; + if ((unsigned)rem > 1) { dest[1] = (Byte)v; v >>= 8; + if ((unsigned)rem > 2) { dest[2] = (Byte)v; v >>= 8; }}} + p->temp = v; p->dest = dest + rem; p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; break; } - - SetUi32(dest, val); - p->temp[3] = (Byte)(val >> 24); + SetUi32(dest, v) + v >>= 24; p->dest = dest + 4; } } @@ -252,6 +278,13 @@ SRes Bcj2Dec_Decode(CBcj2Dec *p) p->range <<= 8; p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; } - return SZ_OK; } + +#undef NUM_ITERS +#undef ONE_ITER +#undef NUM_SHIFT_BITS +#undef kTopValue +#undef kNumBitModelTotalBits +#undef kBitModelTotal +#undef kNumMoveBits diff --git a/C/Bcj2.h b/C/Bcj2.h index 8824080a..4575545b 100644 --- a/C/Bcj2.h +++ b/C/Bcj2.h @@ -1,8 +1,8 @@ -/* Bcj2.h -- BCJ2 Converter for x86 code -2014-11-10 : Igor Pavlov : Public domain */ +/* Bcj2.h -- BCJ2 converter for x86 code (Branch CALL/JUMP variant2) +2023-03-02 : Igor Pavlov : Public domain */ -#ifndef __BCJ2_H -#define __BCJ2_H +#ifndef ZIP7_INC_BCJ2_H +#define ZIP7_INC_BCJ2_H #include "7zTypes.h" @@ -26,37 +26,68 @@ enum BCJ2_DEC_STATE_ORIG_3, BCJ2_DEC_STATE_ORIG, - BCJ2_DEC_STATE_OK + BCJ2_DEC_STATE_ERROR /* after detected data error */ }; enum { BCJ2_ENC_STATE_ORIG = BCJ2_NUM_STREAMS, - BCJ2_ENC_STATE_OK + BCJ2_ENC_STATE_FINISHED /* it's state after fully encoded stream */ }; -#define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) +/* #define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) */ +#define BCJ2_IS_32BIT_STREAM(s) ((unsigned)((unsigned)(s) - (unsigned)BCJ2_STREAM_CALL) < 2) /* CBcj2Dec / CBcj2Enc bufs sizes: BUF_SIZE(n) = lims[n] - bufs[n] -bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be mutliply of 4: +bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be multiply of 4: (BUF_SIZE(BCJ2_STREAM_CALL) & 3) == 0 (BUF_SIZE(BCJ2_STREAM_JUMP) & 3) == 0 */ +// typedef UInt32 CBcj2Prob; +typedef UInt16 CBcj2Prob; + +/* +BCJ2 encoder / decoder internal requirements: + - If last bytes of stream contain marker (e8/e8/0f8x), then + there is also encoded symbol (0 : no conversion) in RC stream. + - One case of overlapped instructions is supported, + if last byte of converted instruction is (0f) and next byte is (8x): + marker [xx xx xx 0f] 8x + then the pair (0f 8x) is treated as marker. +*/ + +/* ---------- BCJ2 Decoder ---------- */ + /* CBcj2Dec: -dest is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: +(dest) is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: bufs[BCJ2_STREAM_MAIN] >= dest && - bufs[BCJ2_STREAM_MAIN] - dest >= tempReserv + + bufs[BCJ2_STREAM_MAIN] - dest >= BUF_SIZE(BCJ2_STREAM_CALL) + BUF_SIZE(BCJ2_STREAM_JUMP) - tempReserv = 0 : for first call of Bcj2Dec_Decode - tempReserv = 4 : for any other calls of Bcj2Dec_Decode - overlap with offset = 1 is not allowed + reserve = bufs[BCJ2_STREAM_MAIN] - dest - + ( BUF_SIZE(BCJ2_STREAM_CALL) + + BUF_SIZE(BCJ2_STREAM_JUMP) ) + and additional conditions: + if (it's first call of Bcj2Dec_Decode() after Bcj2Dec_Init()) + { + (reserve != 1) : if (ver < v23.00) + } + else // if there are more than one calls of Bcj2Dec_Decode() after Bcj2Dec_Init()) + { + (reserve >= 6) : if (ver < v23.00) + (reserve >= 4) : if (ver >= v23.00) + We need that (reserve) because after first call of Bcj2Dec_Decode(), + CBcj2Dec::temp can contain up to 4 bytes for writing to (dest). + } + (reserve == 0) is allowed, if we decode full stream via single call of Bcj2Dec_Decode(). + (reserve == 0) also is allowed in case of multi-call, if we use fixed buffers, + and (reserve) is calculated from full (final) sizes of all streams before first call. */ typedef struct @@ -68,21 +99,65 @@ typedef struct unsigned state; /* BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ - UInt32 ip; - Byte temp[4]; + UInt32 ip; /* property of starting base for decoding */ + UInt32 temp; /* Byte temp[4]; */ UInt32 range; UInt32 code; - UInt16 probs[2 + 256]; + CBcj2Prob probs[2 + 256]; } CBcj2Dec; + +/* Note: + Bcj2Dec_Init() sets (CBcj2Dec::ip = 0) + if (ip != 0) property is required, the caller must set CBcj2Dec::ip after Bcj2Dec_Init() +*/ void Bcj2Dec_Init(CBcj2Dec *p); -/* Returns: SZ_OK or SZ_ERROR_DATA */ + +/* Bcj2Dec_Decode(): + returns: + SZ_OK + SZ_ERROR_DATA : if data in 5 starting bytes of BCJ2_STREAM_RC stream are not correct +*/ SRes Bcj2Dec_Decode(CBcj2Dec *p); -#define Bcj2Dec_IsFinished(_p_) ((_p_)->code == 0) +/* To check that decoding was finished you can compare + sizes of processed streams with sizes known from another sources. + You must do at least one mandatory check from the two following options: + - the check for size of processed output (ORIG) stream. + - the check for size of processed input (MAIN) stream. + additional optional checks: + - the checks for processed sizes of all input streams (MAIN, CALL, JUMP, RC) + - the checks Bcj2Dec_IsMaybeFinished*() + also before actual decoding you can check that the + following condition is met for stream sizes: + ( size(ORIG) == size(MAIN) + size(CALL) + size(JUMP) ) +*/ +/* (state == BCJ2_STREAM_MAIN) means that decoder is ready for + additional input data in BCJ2_STREAM_MAIN stream. + Note that (state == BCJ2_STREAM_MAIN) is allowed for non-finished decoding. +*/ +#define Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) ((_p_)->state == BCJ2_STREAM_MAIN) +/* if the stream decoding was finished correctly, then range decoder + part of CBcj2Dec also was finished, and then (CBcj2Dec::code == 0). + Note that (CBcj2Dec::code == 0) is allowed for non-finished decoding. +*/ +#define Bcj2Dec_IsMaybeFinished_code(_p_) ((_p_)->code == 0) + +/* use Bcj2Dec_IsMaybeFinished() only as additional check + after at least one mandatory check from the two following options: + - the check for size of processed output (ORIG) stream. + - the check for size of processed input (MAIN) stream. +*/ +#define Bcj2Dec_IsMaybeFinished(_p_) ( \ + Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) && \ + Bcj2Dec_IsMaybeFinished_code(_p_)) + + + +/* ---------- BCJ2 Encoder ---------- */ typedef enum { @@ -91,6 +166,91 @@ typedef enum BCJ2_ENC_FINISH_MODE_END_STREAM } EBcj2Enc_FinishMode; +/* + BCJ2_ENC_FINISH_MODE_CONTINUE: + process non finished encoding. + It notifies the encoder that additional further calls + can provide more input data (src) than provided by current call. + In that case the CBcj2Enc encoder still can move (src) pointer + up to (srcLim), but CBcj2Enc encoder can store some of the last + processed bytes (up to 4 bytes) from src to internal CBcj2Enc::temp[] buffer. + at return: + (CBcj2Enc::src will point to position that includes + processed data and data copied to (temp[]) buffer) + That data from (temp[]) buffer will be used in further calls. + + BCJ2_ENC_FINISH_MODE_END_BLOCK: + finish encoding of current block (ended at srcLim) without RC flushing. + at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_ORIG) && + CBcj2Enc::src == CBcj2Enc::srcLim) + : it shows that block encoding was finished. And the encoder is + ready for new (src) data or for stream finish operation. + finished block means + { + CBcj2Enc has completed block encoding up to (srcLim). + (1 + 4 bytes) or (2 + 4 bytes) CALL/JUMP cortages will + not cross block boundary at (srcLim). + temporary CBcj2Enc buffer for (ORIG) src data is empty. + 3 output uncompressed streams (MAIN, CALL, JUMP) were flushed. + RC stream was not flushed. And RC stream will cross block boundary. + } + Note: some possible implementation of BCJ2 encoder could + write branch marker (e8/e8/0f8x) in one call of Bcj2Enc_Encode(), + and it could calculate symbol for RC in another call of Bcj2Enc_Encode(). + BCJ2 encoder uses ip/fileIp/fileSize/relatLimit values to calculate RC symbol. + And these CBcj2Enc variables can have different values in different Bcj2Enc_Encode() calls. + So caller must finish each block with BCJ2_ENC_FINISH_MODE_END_BLOCK + to ensure that RC symbol is calculated and written in proper block. + + BCJ2_ENC_FINISH_MODE_END_STREAM + finish encoding of stream (ended at srcLim) fully including RC flushing. + at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_FINISHED) + : it shows that stream encoding was finished fully, + and all output streams were flushed fully. + also Bcj2Enc_IsFinished() can be called. +*/ + + +/* + 32-bit relative offset in JUMP/CALL commands is + - (mod 4 GiB) for 32-bit x86 code + - signed Int32 for 64-bit x86-64 code + BCJ2 encoder also does internal relative to absolute address conversions. + And there are 2 possible ways to do it: + before v23: we used 32-bit variables and (mod 4 GiB) conversion + since v23: we use 64-bit variables and (signed Int32 offset) conversion. + The absolute address condition for conversion in v23: + ((UInt64)((Int64)ip64 - (Int64)fileIp64 + 5 + (Int32)offset) < (UInt64)fileSize64) + note that if (fileSize64 > 2 GiB). there is difference between + old (mod 4 GiB) way (v22) and new (signed Int32 offset) way (v23). + And new (v23) way is more suitable to encode 64-bit x86-64 code for (fileSize64 > 2 GiB) cases. +*/ + +/* +// for old (v22) way for conversion: +typedef UInt32 CBcj2Enc_ip_unsigned; +typedef Int32 CBcj2Enc_ip_signed; +#define BCJ2_ENC_FileSize_MAX ((UInt32)1 << 31) +*/ +typedef UInt64 CBcj2Enc_ip_unsigned; +typedef Int64 CBcj2Enc_ip_signed; + +/* maximum size of file that can be used for conversion condition */ +#define BCJ2_ENC_FileSize_MAX ((CBcj2Enc_ip_unsigned)0 - 2) + +/* default value of fileSize64_minus1 variable that means + that absolute address limitation will not be used */ +#define BCJ2_ENC_FileSizeField_UNLIMITED ((CBcj2Enc_ip_unsigned)0 - 1) + +/* calculate value that later can be set to CBcj2Enc::fileSize64_minus1 */ +#define BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize) \ + ((CBcj2Enc_ip_unsigned)(fileSize) - 1) + +/* set CBcj2Enc::fileSize64_minus1 variable from size of file */ +#define Bcj2Enc_SET_FileSize(p, fileSize) \ + (p)->fileSize64_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize); + + typedef struct { Byte *bufs[BCJ2_NUM_STREAMS]; @@ -101,45 +261,71 @@ typedef struct unsigned state; EBcj2Enc_FinishMode finishMode; - Byte prevByte; + Byte context; + Byte flushRem; + Byte isFlushState; Byte cache; UInt32 range; UInt64 low; UInt64 cacheSize; + + // UInt32 context; // for marker version, it can include marker flag. - UInt32 ip; - - /* 32-bit ralative offset in JUMP/CALL commands is - - (mod 4 GB) in 32-bit mode - - signed Int32 in 64-bit mode - We use (mod 4 GB) check for fileSize. - Use fileSize up to 2 GB, if you want to support 32-bit and 64-bit code conversion. */ - UInt32 fileIp; - UInt32 fileSize; /* (fileSize <= ((UInt32)1 << 31)), 0 means no_limit */ - UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)), 0 means desable_conversion */ + /* (ip64) and (fileIp64) correspond to virtual source stream position + that doesn't include data in temp[] */ + CBcj2Enc_ip_unsigned ip64; /* current (ip) position */ + CBcj2Enc_ip_unsigned fileIp64; /* start (ip) position of current file */ + CBcj2Enc_ip_unsigned fileSize64_minus1; /* size of current file (for conversion limitation) */ + UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)) : 0 means disable_conversion */ + // UInt32 relatExcludeBits; UInt32 tempTarget; - unsigned tempPos; - Byte temp[4 * 2]; - - unsigned flushPos; - - UInt16 probs[2 + 256]; + unsigned tempPos; /* the number of bytes that were copied to temp[] buffer + (tempPos <= 4) outside of Bcj2Enc_Encode() */ + // Byte temp[4]; // for marker version + Byte temp[8]; + CBcj2Prob probs[2 + 256]; } CBcj2Enc; void Bcj2Enc_Init(CBcj2Enc *p); -void Bcj2Enc_Encode(CBcj2Enc *p); -#define Bcj2Enc_Get_InputData_Size(p) ((SizeT)((p)->srcLim - (p)->src) + (p)->tempPos) -#define Bcj2Enc_IsFinished(p) ((p)->flushPos == 5) +/* +Bcj2Enc_Encode(): at exit: + p->State < BCJ2_NUM_STREAMS : we need more buffer space for output stream + (bufs[p->State] == lims[p->State]) + p->State == BCJ2_ENC_STATE_ORIG : we need more data in input src stream + (src == srcLim) + p->State == BCJ2_ENC_STATE_FINISHED : after fully encoded stream +*/ +void Bcj2Enc_Encode(CBcj2Enc *p); -#define BCJ2_RELAT_LIMIT_NUM_BITS 26 -#define BCJ2_RELAT_LIMIT ((UInt32)1 << BCJ2_RELAT_LIMIT_NUM_BITS) +/* Bcj2Enc encoder can look ahead for up 4 bytes of source stream. + CBcj2Enc::tempPos : is the number of bytes that were copied from input stream to temp[] buffer. + (CBcj2Enc::src) after Bcj2Enc_Encode() is starting position after + fully processed data and after data copied to temp buffer. + So if the caller needs to get real number of fully processed input + bytes (without look ahead data in temp buffer), + the caller must subtruct (CBcj2Enc::tempPos) value from processed size + value that is calculated based on current (CBcj2Enc::src): + cur_processed_pos = Calc_Big_Processed_Pos(enc.src)) - + Bcj2Enc_Get_AvailInputSize_in_Temp(&enc); +*/ +/* get the size of input data that was stored in temp[] buffer: */ +#define Bcj2Enc_Get_AvailInputSize_in_Temp(p) ((p)->tempPos) -/* limit for CBcj2Enc::fileSize variable */ -#define BCJ2_FileSize_MAX ((UInt32)1 << 31) +#define Bcj2Enc_IsFinished(p) ((p)->flushRem == 0) + +/* Note : the decoder supports overlapping of marker (0f 80). + But we can eliminate such overlapping cases by setting + the limit for relative offset conversion as + CBcj2Enc::relatLimit <= (0x0f << 24) == (240 MiB) +*/ +/* default value for CBcj2Enc::relatLimit */ +#define BCJ2_ENC_RELAT_LIMIT_DEFAULT ((UInt32)0x0f << 24) +#define BCJ2_ENC_RELAT_LIMIT_MAX ((UInt32)1 << 31) +// #define BCJ2_RELAT_EXCLUDE_NUM_BITS 5 EXTERN_C_END diff --git a/C/Bcj2Enc.c b/C/Bcj2Enc.c index 682362a1..79460bb1 100644 --- a/C/Bcj2Enc.c +++ b/C/Bcj2Enc.c @@ -1,60 +1,62 @@ -/* Bcj2Enc.c -- BCJ2 Encoder (Converter for x86 code) -2021-02-09 : Igor Pavlov : Public domain */ +/* Bcj2Enc.c -- BCJ2 Encoder converter for x86 code (Branch CALL/JUMP variant2) +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" /* #define SHOW_STAT */ - #ifdef SHOW_STAT #include -#define PRF(x) x +#define PRF2(s) printf("%s ip=%8x tempPos=%d src= %8x\n", s, (unsigned)p->ip64, p->tempPos, (unsigned)(p->srcLim - p->src)); #else -#define PRF(x) +#define PRF2(s) #endif -#include - #include "Bcj2.h" #include "CpuArch.h" -#define CProb UInt16 - #define kTopValue ((UInt32)1 << 24) -#define kNumModelBits 11 -#define kBitModelTotal (1 << kNumModelBits) +#define kNumBitModelTotalBits 11 +#define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 void Bcj2Enc_Init(CBcj2Enc *p) { unsigned i; - - p->state = BCJ2_ENC_STATE_OK; + p->state = BCJ2_ENC_STATE_ORIG; p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; - - p->prevByte = 0; - + p->context = 0; + p->flushRem = 5; + p->isFlushState = 0; p->cache = 0; - p->range = 0xFFFFFFFF; + p->range = 0xffffffff; p->low = 0; p->cacheSize = 1; - - p->ip = 0; - - p->fileIp = 0; - p->fileSize = 0; - p->relatLimit = BCJ2_RELAT_LIMIT; - + p->ip64 = 0; + p->fileIp64 = 0; + p->fileSize64_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED; + p->relatLimit = BCJ2_ENC_RELAT_LIMIT_DEFAULT; + // p->relatExcludeBits = 0; p->tempPos = 0; - - p->flushPos = 0; - for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) p->probs[i] = kBitModelTotal >> 1; } -static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) +// Z7_NO_INLINE +Z7_FORCE_INLINE +static BoolInt Bcj2_RangeEnc_ShiftLow(CBcj2Enc *p) { - if ((UInt32)p->low < (UInt32)0xFF000000 || (UInt32)(p->low >> 32) != 0) + const UInt32 low = (UInt32)p->low; + const unsigned high = (unsigned) + #if defined(Z7_MSC_VER_ORIGINAL) \ + && defined(MY_CPU_X86) \ + && defined(MY_CPU_LE) \ + && !defined(MY_CPU_64BIT) + // we try to rid of __aullshr() call in MSVS-x86 + (((const UInt32 *)&p->low)[1]); // [1] : for little-endian only + #else + (p->low >> 32); + #endif + if (low < (UInt32)0xff000000 || high != 0) { Byte *buf = p->bufs[BCJ2_STREAM_RC]; do @@ -65,247 +67,440 @@ static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) p->bufs[BCJ2_STREAM_RC] = buf; return 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; - - dest = p->bufs[BCJ2_STREAM_MAIN]; - if (num > (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest)) + /* p->context contains context of previous byte: + bits [0 : 7] : src[-1], if (src) was changed in this call + bits [8 : 31] : are undefined for non-marker version + */ + // v = p->context; + #define NUM_SHIFT_BITS 24 + #define CONV_FLAG ((UInt32)1 << 16) + #define ONE_ITER { \ + b = src[0]; \ + *dest++ = (Byte)b; \ + v = (v << NUM_SHIFT_BITS) | b; \ + if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \ + if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \ + ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \ + src++; if (src == srcLim) { break; } } + + if (src != srcLim) + for (;;) { - num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); - if (num == 0) - { - p->state = BCJ2_STREAM_MAIN; - return; - } + /* clang can generate ineffective code with setne instead of two jcc instructions. + we can use 2 iterations and external (unsigned b) to avoid that ineffective code genaration. */ + unsigned b; + ONE_ITER + ONE_ITER } - - srcLim = src + num; + + ip = p->ip64 + (CBcj2Enc_ip_unsigned)(SizeT)(dest - p->bufs[BCJ2_STREAM_MAIN]); + p->bufs[BCJ2_STREAM_MAIN] = dest; + p->ip64 = ip; - if (p->prevByte == 0x0F && (src[0] & 0xF0) == 0x80) - *dest = src[0]; - else for (;;) + if (src == srcLim) { - Byte b = *src; - *dest = b; - if (b != 0x0F) + WRITE_CONTEXT_AND_SRC + if (src != p->srcLim) { - if ((b & 0xFE) == 0xE8) - break; - dest++; - if (++src != srcLim) - continue; - break; + p->state = BCJ2_STREAM_MAIN; + return; } - dest++; - if (++src == srcLim) - break; - if ((*src & 0xF0) != 0x80) - continue; - *dest = *src; + /* (p->src == p->srcLim) + (p->state == BCJ2_ENC_STATE_ORIG) */ + if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) + return; + /* (p->finishMode == BCJ2_ENC_FINISH_MODE_END_STREAM */ + // (p->flushRem == 5); + p->isFlushState = 1; break; } - - num = (SizeT)(src - p->src); - - if (src == srcLim) - { - p->prevByte = src[-1]; - p->bufs[BCJ2_STREAM_MAIN] = dest; - p->src = src; - p->ip += (UInt32)num; - continue; - } - + src++; + // p->src = src; + } + // ip = p->ip; // for marker version + /* marker was found */ + /* (v) contains marker that was found: + bits [NUM_SHIFT_BITS : NUM_SHIFT_BITS + 7] + : value of src[-2] : xx/xx/0f + bits [0 : 7] : value of src[-1] : e8/e9/8x + */ + { { - Byte context = (Byte)(num == 0 ? p->prevByte : src[-1]); - BoolInt needConvert; - - p->bufs[BCJ2_STREAM_MAIN] = dest + 1; - p->ip += (UInt32)num + 1; - src++; - - needConvert = 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 --git a/C/Blake2.h b/C/Blake2.h index 14f3cb64..72352356 100644 --- a/C/Blake2.h +++ b/C/Blake2.h @@ -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 --git a/C/Blake2s.c b/C/Blake2s.c index 3c56a8b8..2a84b57a 100644 --- a/C/Blake2s.c +++ b/C/Blake2s.c @@ -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 @@ static void Blake2s_Compress(CBlake2s *p) 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 @@ static void Blake2s_Update(CBlake2s *p, const Byte *data, size_t size) } 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 @@ static void Blake2s_Final(CBlake2s *p, Byte *digest) { 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 @@ void Blake2sp_Final(CBlake2sp *p, Byte *digest) Blake2s_Final(&R, digest); } + +#undef rotr32 diff --git a/C/Bra.c b/C/Bra.c index 3b854d9c..22e0e478 100644 --- a/C/Bra.c +++ b/C/Bra.c @@ -1,230 +1,420 @@ -/* Bra.c -- Converters for RISC code -2021-02-09 : Igor Pavlov : Public domain */ +/* Bra.c -- Branch converters for RISC code +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" -#include "CpuArch.h" #include "Bra.h" +#include "CpuArch.h" +#include "RotateDefs.h" + +#if defined(MY_CPU_SIZEOF_POINTER) \ + && ( MY_CPU_SIZEOF_POINTER == 4 \ + || MY_CPU_SIZEOF_POINTER == 8) + #define BR_CONV_USE_OPT_PC_PTR +#endif + +#ifdef BR_CONV_USE_OPT_PC_PTR +#define BR_PC_INIT pc -= (UInt32)(SizeT)p; +#define BR_PC_GET (pc + (UInt32)(SizeT)p) +#else +#define BR_PC_INIT pc += (UInt32)size; +#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) +// #define BR_PC_INIT +// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) +#endif + +#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; +// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; + +#define Z7_BRANCH_CONV(name) z7_BranchConv_ ## name + +#define Z7_BRANCH_FUNC_MAIN(name) \ +static \ +Z7_FORCE_INLINE \ +Z7_ATTRIB_NO_VECTOR \ +Byte *Z7_BRANCH_CONV(name)(Byte *p, SizeT size, UInt32 pc, int encoding) -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +#define Z7_BRANCH_FUNC_IMP(name, m, encoding) \ +Z7_NO_INLINE \ +Z7_ATTRIB_NO_VECTOR \ +Byte *m(name)(Byte *data, SizeT size, UInt32 pc) \ + { return Z7_BRANCH_CONV(name)(data, size, pc, encoding); } \ + +#ifdef Z7_EXTRACT_ONLY +#define Z7_BRANCH_FUNCS_IMP(name) \ + Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) +#else +#define Z7_BRANCH_FUNCS_IMP(name) \ + Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) \ + Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_ENC, 1) +#endif + +#if defined(__clang__) +#define BR_EXTERNAL_FOR +#define BR_NEXT_ITERATION continue; +#else +#define BR_EXTERNAL_FOR for (;;) +#define BR_NEXT_ITERATION break; +#endif + +#if defined(__clang__) && (__clang_major__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ >= 1000) \ + // GCC is not good for __builtin_expect() here + /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ + // #define Z7_unlikely [[unlikely]] + // #define Z7_LIKELY(x) (__builtin_expect((x), 1)) + #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) + // #define Z7_likely [[likely]] +#else + // #define Z7_LIKELY(x) (x) + #define Z7_UNLIKELY(x) (x) + // #define Z7_likely +#endif + + +Z7_BRANCH_FUNC_MAIN(ARM64) { - Byte *p; + // Byte *p = data; const Byte *lim; - size &= ~(size_t)3; - ip += 4; - p = data; - lim = data + size; + const UInt32 flag = (UInt32)1 << (24 - 4); + const UInt32 mask = ((UInt32)1 << 24) - (flag << 1); + size &= ~(SizeT)3; + // if (size == 0) return p; + lim = p + size; + BR_PC_INIT + pc -= 4; // because (p) will point to next instruction + + BR_EXTERNAL_FOR + { + // Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (;;) + { + UInt32 v; + if Z7_UNLIKELY(p == lim) + return p; + v = GetUi32a(p); + p += 4; + if Z7_UNLIKELY(((v - 0x94000000) & 0xfc000000) == 0) + { + UInt32 c = BR_PC_GET >> 2; + BR_CONVERT_VAL(v, c) + v &= 0x03ffffff; + v |= 0x94000000; + SetUi32a(p - 4, v) + BR_NEXT_ITERATION + } + // v = rotlFixed(v, 8); v += (flag << 8) - 0x90; if Z7_UNLIKELY((v & ((mask << 8) + 0x9f)) == 0) + v -= 0x90000000; if Z7_UNLIKELY((v & 0x9f000000) == 0) + { + UInt32 z, c; + // v = rotrFixed(v, 8); + v += flag; if Z7_UNLIKELY(v & mask) continue; + z = (v & 0xffffffe0) | (v >> 26); + c = (BR_PC_GET >> (12 - 3)) & ~(UInt32)7; + BR_CONVERT_VAL(z, c) + v &= 0x1f; + v |= 0x90000000; + v |= z << 26; + v |= 0x00ffffe0 & ((z & (((flag << 1) - 1))) - flag); + SetUi32a(p - 4, v) + } + } + } +} +Z7_BRANCH_FUNCS_IMP(ARM64) - if (encoding) +Z7_BRANCH_FUNC_MAIN(ARM) +{ + // Byte *p = data; + const Byte *lim; + size &= ~(SizeT)3; + lim = p + size; + BR_PC_INIT + /* in ARM: branch offset is relative to the +2 instructions from current instruction. + (p) will point to next instruction */ + pc += 8 - 4; + for (;;) { for (;;) { - if (p >= lim) - return (SizeT)(p - data); - p += 4; - if (p[-1] == 0xEB) - break; + if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; + if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break; } { - UInt32 v = GetUi32(p - 4); - v <<= 2; - v += ip + (UInt32)(p - data); - v >>= 2; - v &= 0x00FFFFFF; - v |= 0xEB000000; - SetUi32(p - 4, v); + UInt32 v = GetUi32a(p - 4); + UInt32 c = BR_PC_GET >> 2; + BR_CONVERT_VAL(v, c) + v &= 0x00ffffff; + v |= 0xeb000000; + SetUi32a(p - 4, v) } } +} +Z7_BRANCH_FUNCS_IMP(ARM) + +Z7_BRANCH_FUNC_MAIN(PPC) +{ + // Byte *p = data; + const Byte *lim; + size &= ~(SizeT)3; + lim = p + size; + BR_PC_INIT + pc -= 4; // because (p) will point to next instruction + for (;;) { + UInt32 v; for (;;) { - if (p >= lim) - return (SizeT)(p - data); + if Z7_UNLIKELY(p == lim) + return p; + // v = GetBe32a(p); + v = *(UInt32 *)(void *)p; p += 4; - if (p[-1] == 0xEB) - break; + // if ((v & 0xfc000003) == 0x48000001) break; + // if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) break; + if Z7_UNLIKELY( + ((v - Z7_CONV_BE_TO_NATIVE_CONST32(0x48000001)) + & Z7_CONV_BE_TO_NATIVE_CONST32(0xfc000003)) == 0) break; } { - UInt32 v = GetUi32(p - 4); - v <<= 2; - v -= ip + (UInt32)(p - data); - v >>= 2; - v &= 0x00FFFFFF; - v |= 0xEB000000; - SetUi32(p - 4, v); + v = Z7_CONV_NATIVE_TO_BE_32(v); + { + UInt32 c = BR_PC_GET; + BR_CONVERT_VAL(v, c) + } + v &= 0x03ffffff; + v |= 0x48000000; + SetBe32a(p - 4, v) } } } +Z7_BRANCH_FUNCS_IMP(PPC) -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +#ifdef Z7_CPU_FAST_ROTATE_SUPPORTED +#define BR_SPARC_USE_ROTATE +#endif + +Z7_BRANCH_FUNC_MAIN(SPARC) { - Byte *p; + // Byte *p = data; const Byte *lim; - size &= ~(size_t)1; - p = data; - lim = data + size - 4; - - if (encoding) - + const UInt32 flag = (UInt32)1 << 22; + size &= ~(SizeT)3; + lim = p + size; + BR_PC_INIT + pc -= 4; // because (p) will point to next instruction for (;;) { - UInt32 b1; + UInt32 v; for (;;) { - UInt32 b3; - if (p > lim) - return (SizeT)(p - data); - b1 = p[1]; - b3 = p[3]; - p += 2; - b1 ^= 8; - if ((b3 & b1) >= 0xF8) + if Z7_UNLIKELY(p == lim) + return p; + /* // the code without GetBe32a(): + { const UInt32 v = GetUi16a(p) & 0xc0ff; p += 4; if (v == 0x40 || v == 0xc07f) break; } + */ + v = GetBe32a(p); + p += 4; + #ifdef BR_SPARC_USE_ROTATE + v = rotlFixed(v, 2); + v += (flag << 2) - 1; + if Z7_UNLIKELY((v & (3 - (flag << 3))) == 0) + #else + v += (UInt32)5 << 29; + v ^= (UInt32)7 << 29; + v += flag; + if Z7_UNLIKELY((v & (0 - (flag << 1))) == 0) + #endif break; } { - UInt32 v = - ((UInt32)b1 << 19) - + (((UInt32)p[1] & 0x7) << 8) - + (((UInt32)p[-2] << 11)) - + (p[0]); - - p += 2; + // UInt32 v = GetBe32a(p - 4); + #ifndef BR_SPARC_USE_ROTATE + v <<= 2; + #endif { - UInt32 cur = (ip + (UInt32)(p - data)) >> 1; - v += cur; + UInt32 c = BR_PC_GET; + BR_CONVERT_VAL(v, c) } - - p[-4] = (Byte)(v >> 11); - p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); - p[-2] = (Byte)v; - p[-1] = (Byte)(0xF8 | (v >> 8)); + v &= (flag << 3) - 1; + #ifdef BR_SPARC_USE_ROTATE + v -= (flag << 2) - 1; + v = rotrFixed(v, 2); + #else + v -= (flag << 2); + v >>= 2; + v |= (UInt32)1 << 30; + #endif + SetBe32a(p - 4, v) } } +} +Z7_BRANCH_FUNCS_IMP(SPARC) + + +Z7_BRANCH_FUNC_MAIN(ARMT) +{ + // Byte *p = data; + Byte *lim; + size &= ~(SizeT)1; + // if (size == 0) return p; + if (size <= 2) return p; + size -= 2; + lim = p + size; + BR_PC_INIT + /* in ARM: branch offset is relative to the +2 instructions from current instruction. + (p) will point to the +2 instructions from current instruction */ + // pc += 4 - 4; + // if (encoding) pc -= 0xf800 << 1; else pc += 0xf800 << 1; + // #define ARMT_TAIL_PROC { goto armt_tail; } + #define ARMT_TAIL_PROC { return p; } - for (;;) + do { - UInt32 b1; + /* in MSVC 32-bit x86 compilers: + UInt32 version : it loads value from memory with movzx + Byte version : it loads value to 8-bit register (AL/CL) + movzx version is slightly faster in some cpus + */ + unsigned b1; + // Byte / unsigned + b1 = p[1]; + // optimized version to reduce one (p >= lim) check: + // unsigned a1 = p[1]; b1 = p[3]; p += 2; if Z7_LIKELY((b1 & (a1 ^ 8)) < 0xf8) for (;;) { - UInt32 b3; - if (p > lim) - return (SizeT)(p - data); - b1 = p[1]; - b3 = p[3]; - p += 2; - b1 ^= 8; - if ((b3 & b1) >= 0xF8) - break; + unsigned b3; // Byte / UInt32 + /* (Byte)(b3) normalization can use low byte computations in MSVC. + It gives smaller code, and no loss of speed in some compilers/cpus. + But new MSVC 32-bit x86 compilers use more slow load + from memory to low byte register in that case. + So we try to use full 32-bit computations for faster code. + */ + // if (p >= lim) { ARMT_TAIL_PROC } b3 = b1 + 8; b1 = p[3]; p += 2; if ((b3 & b1) >= 0xf8) break; + if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b3 = p[3]; p += 2; if Z7_UNLIKELY((b3 & (b1 ^ 8)) >= 0xf8) break; + if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b1 = p[3]; p += 2; if Z7_UNLIKELY((b1 & (b3 ^ 8)) >= 0xf8) break; } { + /* we can adjust pc for (0xf800) to rid of (& 0x7FF) operation. + But gcc/clang for arm64 can use bfi instruction for full code here */ UInt32 v = - ((UInt32)b1 << 19) + ((UInt32)GetUi16a(p - 2) << 11) | + ((UInt32)GetUi16a(p) & 0x7FF); + /* + UInt32 v = + ((UInt32)p[1 - 2] << 19) + (((UInt32)p[1] & 0x7) << 8) + (((UInt32)p[-2] << 11)) + (p[0]); - + */ p += 2; { - UInt32 cur = (ip + (UInt32)(p - data)) >> 1; - v -= cur; + UInt32 c = BR_PC_GET >> 1; + BR_CONVERT_VAL(v, c) } - + SetUi16a(p - 4, (UInt16)(((v >> 11) & 0x7ff) | 0xf000)) + SetUi16a(p - 2, (UInt16)(v | 0xf800)) /* - SetUi16(p - 4, (UInt16)(((v >> 11) & 0x7FF) | 0xF000)); - SetUi16(p - 2, (UInt16)(v | 0xF800)); - */ - p[-4] = (Byte)(v >> 11); - p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); + p[-3] = (Byte)(0xf0 | ((v >> 19) & 0x7)); p[-2] = (Byte)v; - p[-1] = (Byte)(0xF8 | (v >> 8)); + p[-1] = (Byte)(0xf8 | (v >> 8)); + */ } } + while (p < lim); + return p; + // armt_tail: + // if ((Byte)((lim[1] & 0xf8)) != 0xf0) { lim += 2; } return lim; + // return (Byte *)(lim + ((Byte)((lim[1] ^ 0xf0) & 0xf8) == 0 ? 0 : 2)); + // return (Byte *)(lim + (((lim[1] ^ ~0xfu) & ~7u) == 0 ? 0 : 2)); + // return (Byte *)(lim + 2 - (((((unsigned)lim[1] ^ 8) + 8) >> 7) & 2)); } +Z7_BRANCH_FUNCS_IMP(ARMT) -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - Byte *p; - const Byte *lim; - size &= ~(size_t)3; - ip -= 4; - p = data; - lim = data + size; - - for (;;) - { - for (;;) - { - if (p >= lim) - return (SizeT)(p - data); - p += 4; - /* if ((v & 0xFC000003) == 0x48000001) */ - if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) - break; - } - { - UInt32 v = GetBe32(p - 4); - if (encoding) - v += ip + (UInt32)(p - data); - else - v -= ip + (UInt32)(p - data); - v &= 0x03FFFFFF; - v |= 0x48000000; - SetBe32(p - 4, v); - } - } -} - +// #define BR_IA64_NO_INLINE -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) +Z7_BRANCH_FUNC_MAIN(IA64) { - Byte *p; + // Byte *p = data; const Byte *lim; - size &= ~(size_t)3; - ip -= 4; - p = data; - lim = data + size; - + size &= ~(SizeT)15; + lim = p + size; + pc -= 1 << 4; + pc >>= 4 - 1; + // pc -= 1 << 1; + for (;;) { + unsigned m; for (;;) { - if (p >= lim) - return (SizeT)(p - data); - /* - v = GetBe32(p); - p += 4; - m = v + ((UInt32)5 << 29); - m ^= (UInt32)7 << 29; - m += (UInt32)1 << 22; - if ((m & ((UInt32)0x1FF << 23)) == 0) - break; - */ - p += 4; - if ((p[-4] == 0x40 && (p[-3] & 0xC0) == 0) || - (p[-4] == 0x7F && (p[-3] >= 0xC0))) + if Z7_UNLIKELY(p == lim) + return p; + m = (unsigned)((UInt32)0x334b0000 >> (*p & 0x1e)); + p += 16; + pc += 1 << 1; + if (m &= 3) break; } { - UInt32 v = GetBe32(p - 4); - v <<= 2; - if (encoding) - v += ip + (UInt32)(p - data); - else - v -= ip + (UInt32)(p - data); - - v &= 0x01FFFFFF; - v -= (UInt32)1 << 24; - v ^= 0xFF000000; - v >>= 2; - v |= 0x40000000; - SetBe32(p - 4, v); + p += (ptrdiff_t)m * 5 - 20; // negative value is expected here. + do + { + const UInt32 t = + #if defined(MY_CPU_X86_OR_AMD64) + // we use 32-bit load here to reduce code size on x86: + GetUi32(p); + #else + GetUi16(p); + #endif + UInt32 z = GetUi32(p + 1) >> m; + p += 5; + if (((t >> m) & (0x70 << 1)) == 0 + && ((z - (0x5000000 << 1)) & (0xf000000 << 1)) == 0) + { + UInt32 v = (UInt32)((0x8fffff << 1) | 1) & z; + z ^= v; + #ifdef BR_IA64_NO_INLINE + v |= (v & ((UInt32)1 << (23 + 1))) >> 3; + { + UInt32 c = pc; + BR_CONVERT_VAL(v, c) + } + v &= (0x1fffff << 1) | 1; + #else + { + if (encoding) + { + // pc &= ~(0xc00000 << 1); // we just need to clear at least 2 bits + pc &= (0x1fffff << 1) | 1; + v += pc; + } + else + { + // pc |= 0xc00000 << 1; // we need to set at least 2 bits + pc |= ~(UInt32)((0x1fffff << 1) | 1); + v -= pc; + } + } + v &= ~(UInt32)(0x600000 << 1); + #endif + v += (0x700000 << 1); + v &= (0x8fffff << 1) | 1; + z |= v; + z <<= m; + SetUi32(p + 1 - 5, z) + } + m++; + } + while (m &= 3); // while (m < 4); } } } +Z7_BRANCH_FUNCS_IMP(IA64) diff --git a/C/Bra.h b/C/Bra.h index 855e37a6..a4ee568e 100644 --- a/C/Bra.h +++ b/C/Bra.h @@ -1,64 +1,99 @@ /* Bra.h -- Branch converters for executables -2013-01-18 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __BRA_H -#define __BRA_H +#ifndef ZIP7_INC_BRA_H +#define ZIP7_INC_BRA_H #include "7zTypes.h" EXTERN_C_BEGIN +#define Z7_BRANCH_CONV_DEC(name) z7_BranchConv_ ## name ## _Dec +#define Z7_BRANCH_CONV_ENC(name) z7_BranchConv_ ## name ## _Enc +#define Z7_BRANCH_CONV_ST_DEC(name) z7_BranchConvSt_ ## name ## _Dec +#define Z7_BRANCH_CONV_ST_ENC(name) z7_BranchConvSt_ ## name ## _Enc + +#define Z7_BRANCH_CONV_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc) +#define Z7_BRANCH_CONV_ST_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc, UInt32 *state) + +typedef Z7_BRANCH_CONV_DECL( (*z7_Func_BranchConv)); +typedef Z7_BRANCH_CONV_ST_DECL((*z7_Func_BranchConvSt)); + +#define Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL 0 +Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_DEC(X86)); +Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_ENC(X86)); + +#define Z7_BRANCH_FUNCS_DECL(name) \ +Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_DEC(name)); \ +Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_ENC(name)); + +Z7_BRANCH_FUNCS_DECL(ARM64) +Z7_BRANCH_FUNCS_DECL(ARM) +Z7_BRANCH_FUNCS_DECL(ARMT) +Z7_BRANCH_FUNCS_DECL(PPC) +Z7_BRANCH_FUNCS_DECL(SPARC) +Z7_BRANCH_FUNCS_DECL(IA64) + /* -These functions convert relative addresses to absolute addresses -in CALL instructions to increase the compression ratio. - - In: - data - data buffer - size - size of data - ip - current virtual Instruction Pinter (IP) value - state - state variable for x86 converter - encoding - 0 (for decoding), 1 (for encoding) - - Out: - state - state variable for x86 converter +These functions convert data that contain CPU instructions. +Each such function converts relative addresses to absolute addresses in some +branch instructions: CALL (in all converters) and JUMP (X86 converter only). +Such conversion allows to increase compression ratio, if we compress that data. + +There are 2 types of converters: + Byte * Conv_RISC (Byte *data, SizeT size, UInt32 pc); + Byte * ConvSt_X86(Byte *data, SizeT size, UInt32 pc, UInt32 *state); +Each Converter supports 2 versions: one for encoding +and one for decoding (_Enc/_Dec postfixes in function name). - Returns: - The number of processed bytes. If you call these functions with multiple calls, - you must start next call with first byte after block of processed bytes. +In params: + data : data buffer + size : size of data + pc : current virtual Program Counter (Instruction Pinter) value +In/Out param: + state : pointer to state variable (for X86 converter only) + +Return: + The pointer to position in (data) buffer after last byte that was processed. + If the caller calls converter again, it must call it starting with that position. + But the caller is allowed to move data in buffer. so pointer to + current processed position also will be changed for next call. + Also the caller must increase internal (pc) value for next call. +Each converter has some characteristics: Endian, Alignment, LookAhead. Type Endian Alignment LookAhead - x86 little 1 4 + X86 little 1 4 ARMT little 2 2 ARM little 4 0 + ARM64 little 4 0 PPC big 4 0 SPARC big 4 0 IA64 little 16 0 - size must be >= Alignment + LookAhead, if it's not last block. - If (size < Alignment + LookAhead), converter returns 0. - - Example: + (data) must be aligned for (Alignment). + processed size can be calculated as: + SizeT processed = Conv(data, size, pc) - data; + if (processed == 0) + it means that converter needs more data for processing. + If (size < Alignment + LookAhead) + then (processed == 0) is allowed. - UInt32 ip = 0; - for () - { - ; size must be >= Alignment + LookAhead, if it's not last block - SizeT processed = Convert(data, size, ip, 1); - data += processed; - size -= processed; - ip += processed; - } +Example code for conversion in loop: + UInt32 pc = 0; + size = 0; + for (;;) + { + size += Load_more_input_data(data + size); + SizeT processed = Conv(data, size, pc) - data; + if (processed == 0 && no_more_input_data_after_size) + break; // we stop convert loop + data += processed; + size -= processed; + pc += processed; + } */ -#define x86_Convert_Init(state) { state = 0; } -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); - EXTERN_C_END #endif diff --git a/C/Bra86.c b/C/Bra86.c index 10a0fbd1..d81f392a 100644 --- a/C/Bra86.c +++ b/C/Bra86.c @@ -1,82 +1,187 @@ -/* Bra86.c -- Converter for x86 code (BCJ) -2021-02-09 : Igor Pavlov : Public domain */ +/* Bra86.c -- Branch converter for X86 code (BCJ) +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" #include "Bra.h" +#include "CpuArch.h" -#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0) -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) +#if defined(MY_CPU_SIZEOF_POINTER) \ + && ( MY_CPU_SIZEOF_POINTER == 4 \ + || MY_CPU_SIZEOF_POINTER == 8) + #define BR_CONV_USE_OPT_PC_PTR +#endif + +#ifdef BR_CONV_USE_OPT_PC_PTR +#define BR_PC_INIT pc -= (UInt32)(SizeT)p; // (MY_uintptr_t) +#define BR_PC_GET (pc + (UInt32)(SizeT)p) +#else +#define BR_PC_INIT pc += (UInt32)size; +#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p)) +// #define BR_PC_INIT +// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data)) +#endif + +#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c; +// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c; + +#define Z7_BRANCH_CONV_ST(name) z7_BranchConvSt_ ## name + +#define BR86_NEED_CONV_FOR_MS_BYTE(b) ((((b) + 1) & 0xfe) == 0) + +#ifdef MY_CPU_LE_UNALIGN + #define BR86_PREPARE_BCJ_SCAN const UInt32 v = GetUi32(p) ^ 0xe8e8e8e8; + #define BR86_IS_BCJ_BYTE(n) ((v & ((UInt32)0xfe << (n) * 8)) == 0) +#else + #define BR86_PREPARE_BCJ_SCAN + // bad for MSVC X86 (partial write to byte reg): + #define BR86_IS_BCJ_BYTE(n) ((p[n - 4] & 0xfe) == 0xe8) + // bad for old MSVC (partial write to byte reg): + // #define BR86_IS_BCJ_BYTE(n) (((*p ^ 0xe8) & 0xfe) == 0) +#endif + +static +Z7_FORCE_INLINE +Z7_ATTRIB_NO_VECTOR +Byte *Z7_BRANCH_CONV_ST(X86)(Byte *p, SizeT size, UInt32 pc, UInt32 *state, int encoding) { - SizeT pos = 0; - UInt32 mask = *state & 7; if (size < 5) - return 0; - size -= 4; - ip += 5; + return p; + { + // Byte *p = data; + const Byte *lim = p + size - 4; + unsigned mask = (unsigned)*state; // & 7; +#ifdef BR_CONV_USE_OPT_PC_PTR + /* if BR_CONV_USE_OPT_PC_PTR is defined: we need to adjust (pc) for (+4), + because call/jump offset is relative to the next instruction. + if BR_CONV_USE_OPT_PC_PTR is not defined : we don't need to adjust (pc) for (+4), + because BR_PC_GET uses (pc - (lim - p)), and lim was adjusted for (-4) before. + */ + pc += 4; +#endif + BR_PC_INIT + goto start; - for (;;) + for (;; mask |= 4) { - Byte *p = data + pos; - const Byte *limit = data + size; - for (; p < limit; p++) - if ((*p & 0xFE) == 0xE8) - break; - + // cont: mask |= 4; + start: + if (p >= lim) + goto fin; { - SizeT d = (SizeT)(p - data) - pos; - pos = (SizeT)(p - data); - if (p >= limit) - { - *state = (d > 2 ? 0 : mask >> (unsigned)d); - return pos; - } - if (d > 2) - mask = 0; - else - { - mask >>= (unsigned)d; - if (mask != 0 && (mask > 4 || mask == 3 || Test86MSByte(p[(size_t)(mask >> 1) + 1]))) - { - mask = (mask >> 1) | 4; - pos++; - continue; - } - } + BR86_PREPARE_BCJ_SCAN + p += 4; + if (BR86_IS_BCJ_BYTE(0)) { goto m0; } mask >>= 1; + if (BR86_IS_BCJ_BYTE(1)) { goto m1; } mask >>= 1; + if (BR86_IS_BCJ_BYTE(2)) { goto m2; } mask = 0; + if (BR86_IS_BCJ_BYTE(3)) { goto a3; } } + goto main_loop; - if (Test86MSByte(p[4])) + m0: p--; + m1: p--; + m2: p--; + if (mask == 0) + goto a3; + if (p > lim) + goto fin_p; + + // if (((0x17u >> mask) & 1) == 0) + if (mask > 4 || mask == 3) + { + mask >>= 1; + continue; // goto cont; + } + mask >>= 1; + if (BR86_NEED_CONV_FOR_MS_BYTE(p[mask])) + continue; // goto cont; + // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; { - UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); - UInt32 cur = ip + (UInt32)pos; - pos += 5; - if (encoding) - v += cur; - else - v -= cur; - if (mask != 0) + UInt32 v = GetUi32(p); + UInt32 c; + v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; + c = BR_PC_GET; + BR_CONVERT_VAL(v, c) { - unsigned sh = (mask & 6) << 2; - if (Test86MSByte((Byte)(v >> sh))) + mask <<= 3; + if (BR86_NEED_CONV_FOR_MS_BYTE(v >> mask)) { - v ^= (((UInt32)0x100 << sh) - 1); - if (encoding) - v += cur; - else - v -= cur; + v ^= (((UInt32)0x100 << mask) - 1); + #ifdef MY_CPU_X86 + // for X86 : we can recalculate (c) to reduce register pressure + c = BR_PC_GET; + #endif + BR_CONVERT_VAL(v, c) } mask = 0; } - p[1] = (Byte)v; - p[2] = (Byte)(v >> 8); - p[3] = (Byte)(v >> 16); - p[4] = (Byte)(0 - ((v >> 24) & 1)); + // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); + v &= (1 << 25) - 1; v -= (1 << 24); + SetUi32(p, v) + p += 4; + goto main_loop; } - else + + main_loop: + if (p >= lim) + goto fin; + for (;;) { - mask = (mask >> 1) | 4; - pos++; + BR86_PREPARE_BCJ_SCAN + p += 4; + if (BR86_IS_BCJ_BYTE(0)) { goto a0; } + if (BR86_IS_BCJ_BYTE(1)) { goto a1; } + if (BR86_IS_BCJ_BYTE(2)) { goto a2; } + if (BR86_IS_BCJ_BYTE(3)) { goto a3; } + if (p >= lim) + goto fin; + } + + a0: p--; + a1: p--; + a2: p--; + a3: + if (p > lim) + goto fin_p; + // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont; + { + UInt32 v = GetUi32(p); + UInt32 c; + v += (1 << 24); if (v & 0xfe000000) continue; // goto cont; + c = BR_PC_GET; + BR_CONVERT_VAL(v, c) + // v = (v & ((1 << 24) - 1)) - (v & (1 << 24)); + v &= (1 << 25) - 1; v -= (1 << 24); + SetUi32(p, v) + p += 4; + goto main_loop; } } + +fin_p: + p--; +fin: + // the following processing for tail is optional and can be commented + /* + lim += 4; + for (; p < lim; p++, mask >>= 1) + if ((*p & 0xfe) == 0xe8) + break; + */ + *state = (UInt32)mask; + return p; + } } + + +#define Z7_BRANCH_CONV_ST_FUNC_IMP(name, m, encoding) \ +Z7_NO_INLINE \ +Z7_ATTRIB_NO_VECTOR \ +Byte *m(name)(Byte *data, SizeT size, UInt32 pc, UInt32 *state) \ + { return Z7_BRANCH_CONV_ST(name)(data, size, pc, state, encoding); } + +Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_DEC, 0) +#ifndef Z7_EXTRACT_ONLY +Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_ENC, 1) +#endif diff --git a/C/BraIA64.c b/C/BraIA64.c index d1dbc62c..9dfe3e28 100644 --- a/C/BraIA64.c +++ b/C/BraIA64.c @@ -1,53 +1,14 @@ /* BraIA64.c -- Converter for IA-64 code -2017-01-26 : Igor Pavlov : Public domain */ +2023-02-20 : Igor Pavlov : Public domain */ #include "Precomp.h" -#include "CpuArch.h" -#include "Bra.h" +// the code was moved to Bra.c -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 16) - return 0; - size -= 16; - i = 0; - do - { - unsigned m = ((UInt32)0x334B0000 >> (data[i] & 0x1E)) & 3; - if (m) - { - m++; - do - { - Byte *p = data + (i + (size_t)m * 5 - 8); - if (((p[3] >> m) & 15) == 5 - && (((p[-1] | ((UInt32)p[0] << 8)) >> m) & 0x70) == 0) - { - unsigned raw = GetUi32(p); - unsigned v = raw >> m; - v = (v & 0xFFFFF) | ((v & (1 << 23)) >> 3); - - v <<= 4; - if (encoding) - v += ip + (UInt32)i; - else - v -= ip + (UInt32)i; - v >>= 4; - - v &= 0x1FFFFF; - v += 0x700000; - v &= 0x8FFFFF; - raw &= ~((UInt32)0x8FFFFF << m); - raw |= (v << m); - SetUi32(p, raw); - } - } - while (++m <= 4); - } - i += 16; - } - while (i <= size); - return i; -} +#ifdef _MSC_VER +#pragma warning(disable : 4206) // nonstandard extension used : translation unit is empty +#endif + +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Wempty-translation-unit" +#endif diff --git a/C/BwtSort.c b/C/BwtSort.c index 3eb57efa..05ad6de8 100644 --- a/C/BwtSort.c +++ b/C/BwtSort.c @@ -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 @@ SortGroup - is recursive Range-Sort function with HeapSort optimization for smal 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 @@ static UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt3 { /* #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetFinishedGroupSize(ind2, 1); + SetFinishedGroupSize(ind2, 1) #endif */ return 0; @@ -463,7 +464,7 @@ UInt32 BlockSort(UInt32 *Indices, const Byte *data, UInt32 blockSize) 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 --git a/C/BwtSort.h b/C/BwtSort.h index 7e989a99..a34b243a 100644 --- a/C/BwtSort.h +++ b/C/BwtSort.h @@ -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 --git a/C/Compiler.h b/C/Compiler.h index a9816fa5..185a52de 100644 --- a/C/Compiler.h +++ b/C/Compiler.h @@ -1,12 +1,37 @@ -/* Compiler.h -2021-01-05 : Igor Pavlov : Public domain */ +/* Compiler.h : Compiler specific defines and pragmas +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_COMPILER_H -#define __7Z_COMPILER_H +#ifndef ZIP7_INC_COMPILER_H +#define ZIP7_INC_COMPILER_H + +#if defined(__clang__) +# define Z7_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) +#endif +#if defined(__clang__) && defined(__apple_build_version__) +# define Z7_APPLE_CLANG_VERSION Z7_CLANG_VERSION +#elif defined(__clang__) +# define Z7_LLVM_CLANG_VERSION Z7_CLANG_VERSION +#elif defined(__GNUC__) +# define Z7_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif + +#ifdef _MSC_VER +#if !defined(__clang__) && !defined(__GNUC__) +#define Z7_MSC_VER_ORIGINAL _MSC_VER +#endif +#endif + +#if defined(__MINGW32__) || defined(__MINGW64__) +#define Z7_MINGW +#endif + +// #pragma GCC diagnostic ignored "-Wunknown-pragmas" + +#ifdef __clang__ +// padding size of '' with 4 bytes to alignment boundary +#pragma GCC diagnostic ignored "-Wpadded" +#endif - #ifdef __clang__ - #pragma clang diagnostic ignored "-Wunused-private-field" - #endif #ifdef _MSC_VER @@ -17,24 +42,115 @@ #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int #endif - #if _MSC_VER >= 1300 - #pragma warning(disable : 4996) // This function or variable may be unsafe - #else - #pragma warning(disable : 4511) // copy constructor could not be generated - #pragma warning(disable : 4512) // assignment operator could not be generated - #pragma warning(disable : 4514) // unreferenced inline function has been removed - #pragma warning(disable : 4702) // unreachable code - #pragma warning(disable : 4710) // not inlined - #pragma warning(disable : 4714) // function marked as __forceinline not inlined - #pragma warning(disable : 4786) // identifier was truncated to '255' characters in the debug information - #endif +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#pragma warning(disable : 4464) // relative include path contains '..' +#endif + +// == 1200 : -O1 : for __forceinline +// >= 1900 : -O1 : for printf +#pragma warning(disable : 4710) // function not inlined + +#if _MSC_VER < 1900 +// winnt.h: 'Int64ShllMod32' +#pragma warning(disable : 4514) // unreferenced inline function has been removed +#endif + +#if _MSC_VER < 1300 +// #pragma warning(disable : 4702) // unreachable code +// Bra.c : -O1: +#pragma warning(disable : 4714) // function marked as __forceinline not inlined +#endif + +/* +#if _MSC_VER > 1400 && _MSC_VER <= 1900 +// strcat: This function or variable may be unsafe +// sysinfoapi.h: kit10: GetVersion was declared deprecated +#pragma warning(disable : 4996) +#endif +*/ + +#if _MSC_VER > 1200 +// -Wall warnings + +#pragma warning(disable : 4711) // function selected for automatic inline expansion +#pragma warning(disable : 4820) // '2' bytes padding added after data member + +#if _MSC_VER >= 1400 && _MSC_VER < 1920 +// 1400: string.h: _DBG_MEMCPY_INLINE_ +// 1600 - 191x : smmintrin.h __cplusplus' +// is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' +#pragma warning(disable : 4668) + +// 1400 - 1600 : WinDef.h : 'FARPROC' : +// 1900 - 191x : immintrin.h: _readfsbase_u32 +// no function prototype given : converting '()' to '(void)' +#pragma warning(disable : 4255) +#endif + +#if _MSC_VER >= 1914 +// Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified +#pragma warning(disable : 5045) +#endif + +#endif // _MSC_VER > 1200 +#endif // _MSC_VER + + +#if defined(__clang__) && (__clang_major__ >= 4) + #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ + _Pragma("clang loop unroll(disable)") \ + _Pragma("clang loop vectorize(disable)") + #define Z7_ATTRIB_NO_VECTORIZE +#elif defined(__GNUC__) && (__GNUC__ >= 5) + #define Z7_ATTRIB_NO_VECTORIZE __attribute__((optimize("no-tree-vectorize"))) + // __attribute__((optimize("no-unroll-loops"))); + #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE +#elif defined(_MSC_VER) && (_MSC_VER >= 1920) + #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \ + _Pragma("loop( no_vector )") + #define Z7_ATTRIB_NO_VECTORIZE +#else + #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + #define Z7_ATTRIB_NO_VECTORIZE +#endif + +#if defined(MY_CPU_X86_OR_AMD64) && ( \ + defined(__clang__) && (__clang_major__ >= 4) \ + || defined(__GNUC__) && (__GNUC__ >= 5)) + #define Z7_ATTRIB_NO_SSE __attribute__((__target__("no-sse"))) +#else + #define Z7_ATTRIB_NO_SSE +#endif + +#define Z7_ATTRIB_NO_VECTOR \ + Z7_ATTRIB_NO_VECTORIZE \ + Z7_ATTRIB_NO_SSE + + +#if defined(__clang__) && (__clang_major__ >= 8) \ + || defined(__GNUC__) && (__GNUC__ >= 1000) \ + /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */ + // GCC is not good for __builtin_expect() + #define Z7_LIKELY(x) (__builtin_expect((x), 1)) + #define Z7_UNLIKELY(x) (__builtin_expect((x), 0)) + // #define Z7_unlikely [[unlikely]] + // #define Z7_likely [[likely]] +#else + #define Z7_LIKELY(x) (x) + #define Z7_UNLIKELY(x) (x) + // #define Z7_likely +#endif - #ifdef __clang__ - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #pragma clang diagnostic ignored "-Wmicrosoft-exception-spec" - // #pragma clang diagnostic ignored "-Wreserved-id-macro" - #endif +#if (defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 36000)) +#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wreserved-macro-identifier\"") +#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER \ + _Pragma("GCC diagnostic pop") +#else +#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER +#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER #endif #define UNUSED_VAR(x) (void)x; diff --git a/C/CpuArch.c b/C/CpuArch.c index fa9afe39..33f8a3ab 100644 --- a/C/CpuArch.c +++ b/C/CpuArch.c @@ -1,187 +1,318 @@ /* CpuArch.c -- CPU specific code -2021-07-13 : Igor Pavlov : Public domain */ +2023-05-18 : Igor Pavlov : Public domain */ #include "Precomp.h" +// #include + #include "CpuArch.h" #ifdef MY_CPU_X86_OR_AMD64 -#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__) -#define USE_ASM +#undef NEED_CHECK_FOR_CPUID +#if !defined(MY_CPU_AMD64) +#define NEED_CHECK_FOR_CPUID #endif -#if !defined(USE_ASM) && _MSC_VER >= 1500 -#include +/* + cpuid instruction supports (subFunction) parameter in ECX, + that is used only with some specific (function) parameter values. + But we always use only (subFunction==0). +*/ +/* + __cpuid(): MSVC and GCC/CLANG use same function/macro name + but parameters are different. + We use MSVC __cpuid() parameters style for our z7_x86_cpuid() function. +*/ + +#if defined(__GNUC__) /* && (__GNUC__ >= 10) */ \ + || defined(__clang__) /* && (__clang_major__ >= 10) */ + +/* there was some CLANG/GCC compilers that have issues with + rbx(ebx) handling in asm blocks in -fPIC mode (__PIC__ is defined). + compiler's contains the macro __cpuid() that is similar to our code. + The history of __cpuid() changes in CLANG/GCC: + GCC: + 2007: it preserved ebx for (__PIC__ && __i386__) + 2013: it preserved rbx and ebx for __PIC__ + 2014: it doesn't preserves rbx and ebx anymore + we suppose that (__GNUC__ >= 5) fixed that __PIC__ ebx/rbx problem. + CLANG: + 2014+: it preserves rbx, but only for 64-bit code. No __PIC__ check. + Why CLANG cares about 64-bit mode only, and doesn't care about ebx (in 32-bit)? + Do we need __PIC__ test for CLANG or we must care about rbx even if + __PIC__ is not defined? +*/ + +#define ASM_LN "\n" + +#if defined(MY_CPU_AMD64) && defined(__PIC__) \ + && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) + +#define x86_cpuid_MACRO(p, func) { \ + __asm__ __volatile__ ( \ + ASM_LN "mov %%rbx, %q1" \ + ASM_LN "cpuid" \ + ASM_LN "xchg %%rbx, %q1" \ + : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } + + /* "=&r" selects free register. It can select even rbx, if that register is free. + "=&D" for (RDI) also works, but the code can be larger with "=&D" + "2"(0) means (subFunction = 0), + 2 is (zero-based) index in the output constraint list "=c" (ECX). */ + +#elif defined(MY_CPU_X86) && defined(__PIC__) \ + && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__)) + +#define x86_cpuid_MACRO(p, func) { \ + __asm__ __volatile__ ( \ + ASM_LN "mov %%ebx, %k1" \ + ASM_LN "cpuid" \ + ASM_LN "xchg %%ebx, %k1" \ + : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } + +#else + +#define x86_cpuid_MACRO(p, func) { \ + __asm__ __volatile__ ( \ + ASM_LN "cpuid" \ + : "=a" ((p)[0]), "=b" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); } + #endif -#if defined(USE_ASM) && !defined(MY_CPU_AMD64) -static UInt32 CheckFlag(UInt32 flag) -{ - #ifdef _MSC_VER - __asm pushfd; - __asm pop EAX; - __asm mov EDX, EAX; - __asm xor EAX, flag; - __asm push EAX; - __asm popfd; - __asm pushfd; - __asm pop EAX; - __asm xor EAX, EDX; - __asm push EDX; - __asm popfd; - __asm and flag, EAX; - #else + +void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) +{ + x86_cpuid_MACRO(p, func) +} + + +Z7_NO_INLINE +UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) +{ + #if defined(NEED_CHECK_FOR_CPUID) + #define EFALGS_CPUID_BIT 21 + UInt32 a; __asm__ __volatile__ ( - "pushf\n\t" - "pop %%EAX\n\t" - "movl %%EAX,%%EDX\n\t" - "xorl %0,%%EAX\n\t" - "push %%EAX\n\t" - "popf\n\t" - "pushf\n\t" - "pop %%EAX\n\t" - "xorl %%EDX,%%EAX\n\t" - "push %%EDX\n\t" - "popf\n\t" - "andl %%EAX, %0\n\t": - "=c" (flag) : "c" (flag) : - "%eax", "%edx"); + ASM_LN "pushf" + ASM_LN "pushf" + ASM_LN "pop %0" + // ASM_LN "movl %0, %1" + // ASM_LN "xorl $0x200000, %0" + ASM_LN "btc %1, %0" + ASM_LN "push %0" + ASM_LN "popf" + ASM_LN "pushf" + ASM_LN "pop %0" + ASM_LN "xorl (%%esp), %0" + + ASM_LN "popf" + ASM_LN + : "=&r" (a) // "=a" + : "i" (EFALGS_CPUID_BIT) + ); + if ((a & (1 << EFALGS_CPUID_BIT)) == 0) + return 0; + #endif + { + UInt32 p[4]; + x86_cpuid_MACRO(p, 0) + return p[0]; + } +} + +#undef ASM_LN + +#elif !defined(_MSC_VER) + +/* +// for gcc/clang and other: we can try to use __cpuid macro: +#include +void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) +{ + __cpuid(func, p[0], p[1], p[2], p[3]); +} +UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) +{ + return (UInt32)__get_cpuid_max(0, NULL); +} +*/ +// for unsupported cpuid: +void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func) +{ + UNUSED_VAR(func) + p[0] = p[1] = p[2] = p[3] = 0; +} +UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) +{ + return 0; +} + +#else // _MSC_VER + +#if !defined(MY_CPU_AMD64) + +UInt32 __declspec(naked) Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void) +{ + #if defined(NEED_CHECK_FOR_CPUID) + #define EFALGS_CPUID_BIT 21 + __asm pushfd + __asm pushfd + /* + __asm pop eax + // __asm mov edx, eax + __asm btc eax, EFALGS_CPUID_BIT + __asm push eax + */ + __asm btc dword ptr [esp], EFALGS_CPUID_BIT + __asm popfd + __asm pushfd + __asm pop eax + // __asm xor eax, edx + __asm xor eax, [esp] + // __asm push edx + __asm popfd + __asm and eax, (1 shl EFALGS_CPUID_BIT) + __asm jz end_func + #endif + __asm push ebx + __asm xor eax, eax // func + __asm xor ecx, ecx // subFunction (optional) for (func == 0) + __asm cpuid + __asm pop ebx + #if defined(NEED_CHECK_FOR_CPUID) + end_func: #endif - return flag; + __asm ret 0 } -#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return 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} + { 0x756E6547 }, // , 0x49656E69, 0x6C65746E }, + { 0x68747541 }, // , 0x69746E65, 0x444D4163 }, + { 0x746E6543 } // , 0x48727561, 0x736C7561 } }; +*/ + +/* +typedef struct +{ + UInt32 maxFunc; + UInt32 vendor[3]; + UInt32 ver; + UInt32 b; + UInt32 c; + UInt32 d; +} Cx86cpuid; + +enum +{ + CPU_FIRM_INTEL, + CPU_FIRM_AMD, + CPU_FIRM_VIA +}; +int x86cpuid_GetFirm(const Cx86cpuid *p); +#define x86cpuid_ver_GetFamily(ver) (((ver >> 16) & 0xff0) | ((ver >> 8) & 0xf)) +#define x86cpuid_ver_GetModel(ver) (((ver >> 12) & 0xf0) | ((ver >> 4) & 0xf)) +#define x86cpuid_ver_GetStepping(ver) (ver & 0xf) int x86cpuid_GetFirm(const Cx86cpuid *p) { unsigned i; - for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++) + for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[0]); i++) { const UInt32 *v = kVendors[i]; - if (v[0] == p->vendor[0] && - v[1] == p->vendor[1] && - v[2] == p->vendor[2]) + if (v[0] == p->vendor[0] + // && v[1] == p->vendor[1] + // && v[2] == p->vendor[2] + ) return (int)i; } return -1; @@ -190,41 +321,55 @@ int x86cpuid_GetFirm(const Cx86cpuid *p) BoolInt CPU_Is_InOrder() { Cx86cpuid p; - int firm; UInt32 family, model; if (!x86cpuid_CheckAndRead(&p)) return 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 @@ static BoolInt CPU_Sys_Is_SSE_Supported() #endif -static UInt32 X86_CPUID_ECX_Get_Flags() +#if !defined(MY_CPU_AMD64) + +BoolInt CPU_IsSupported_CMOV(void) { - Cx86cpuid p; + UInt32 a[4]; + if (!x86cpuid_Func_1(&a[0])) + return 0; + return (a[3] >> 15) & 1; +} + +BoolInt CPU_IsSupported_SSE(void) +{ + UInt32 a[4]; CHECK_SYS_SSE_SUPPORT - if (!x86cpuid_CheckAndRead(&p)) + if (!x86cpuid_Func_1(&a[0])) + return 0; + return (a[3] >> 25) & 1; +} + +BoolInt CPU_IsSupported_SSE2(void) +{ + UInt32 a[4]; + CHECK_SYS_SSE_SUPPORT + if (!x86cpuid_Func_1(&a[0])) + return 0; + return (a[3] >> 26) & 1; +} + +#endif + + +static UInt32 x86cpuid_Func_1_ECX(void) +{ + UInt32 a[4]; + CHECK_SYS_SSE_SUPPORT + if (!x86cpuid_Func_1(&a[0])) return 0; - return p.c; + return a[2]; } -BoolInt CPU_IsSupported_AES() +BoolInt CPU_IsSupported_AES(void) { - return (X86_CPUID_ECX_Get_Flags() >> 25) & 1; + return (x86cpuid_Func_1_ECX() >> 25) & 1; } -BoolInt CPU_IsSupported_SSSE3() +BoolInt CPU_IsSupported_SSSE3(void) { - return (X86_CPUID_ECX_Get_Flags() >> 9) & 1; + return (x86cpuid_Func_1_ECX() >> 9) & 1; } -BoolInt CPU_IsSupported_SSE41() +BoolInt CPU_IsSupported_SSE41(void) { - return (X86_CPUID_ECX_Get_Flags() >> 19) & 1; + return (x86cpuid_Func_1_ECX() >> 19) & 1; } -BoolInt CPU_IsSupported_SHA() +BoolInt CPU_IsSupported_SHA(void) { - Cx86cpuid p; CHECK_SYS_SSE_SUPPORT - if (!x86cpuid_CheckAndRead(&p)) - return 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 + +#if defined(ATTRIB_XGETBV) +#include #endif -BoolInt CPU_IsSupported_AVX2() + +// XFEATURE_ENABLED_MASK/XCR0 +#define MY_XCR_XFEATURE_ENABLED_MASK 0 + +#if defined(ATTRIB_XGETBV) +ATTRIB_XGETBV +#endif +static UInt64 x86_xgetbv_0(UInt32 num) { - Cx86cpuid p; - CHECK_SYS_SSE_SUPPORT +#if defined(ATTRIB_XGETBV) + { + return + #if (defined(_MSC_VER)) + _xgetbv(num); + #else + __builtin_ia32_xgetbv( + #if !defined(__clang__) + (int) + #endif + num); + #endif + } + +#elif defined(__GNUC__) || defined(__clang__) || defined(__SUNPRO_CC) + + UInt32 a, d; + #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) + __asm__ + ( + "xgetbv" + : "=a"(a), "=d"(d) : "c"(num) : "cc" + ); + #else // is old gcc + __asm__ + ( + ".byte 0x0f, 0x01, 0xd0" "\n\t" + : "=a"(a), "=d"(d) : "c"(num) : "cc" + ); + #endif + return ((UInt64)d << 32) | a; + // return a; + +#elif defined(_MSC_VER) && !defined(MY_CPU_AMD64) + + UInt32 a, d; + __asm { + push eax + push edx + push ecx + mov ecx, num; + // xor ecx, ecx // = MY_XCR_XFEATURE_ENABLED_MASK + _emit 0x0f + _emit 0x01 + _emit 0xd0 + mov a, eax + mov d, edx + pop ecx + pop edx + pop eax + } + return ((UInt64)d << 32) | a; + // return a; + +#else // it's unknown compiler + // #error "Need xgetbv function" + UNUSED_VAR(num) + // for MSVC-X64 we could call external function from external file. + /* Actually we had checked OSXSAVE/AVX in cpuid before. + So it's expected that OS supports at least AVX and below. */ + // if (num != MY_XCR_XFEATURE_ENABLED_MASK) return 0; // if not XCR0 + return + // (1 << 0) | // x87 + (1 << 1) // SSE + | (1 << 2); // AVX + +#endif +} +#ifdef _WIN32 +/* + Windows versions do not know about new ISA extensions that + can be introduced. But we still can use new extensions, + even if Windows doesn't report about supporting them, + But we can use new extensions, only if Windows knows about new ISA extension + that changes the number or size of registers: SSE, AVX/XSAVE, AVX512 + So it's enough to check + MY_PF_AVX_INSTRUCTIONS_AVAILABLE + instead of + MY_PF_AVX2_INSTRUCTIONS_AVAILABLE +*/ +#define MY_PF_XSAVE_ENABLED 17 +// #define MY_PF_SSSE3_INSTRUCTIONS_AVAILABLE 36 +// #define MY_PF_SSE4_1_INSTRUCTIONS_AVAILABLE 37 +// #define MY_PF_SSE4_2_INSTRUCTIONS_AVAILABLE 38 +// #define MY_PF_AVX_INSTRUCTIONS_AVAILABLE 39 +// #define MY_PF_AVX2_INSTRUCTIONS_AVAILABLE 40 +// #define MY_PF_AVX512F_INSTRUCTIONS_AVAILABLE 41 +#endif + +BoolInt CPU_IsSupported_AVX(void) +{ #ifdef _WIN32 - #define MY__PF_XSAVE_ENABLED 17 - if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED)) + if (!IsProcessorFeaturePresent(MY_PF_XSAVE_ENABLED)) return 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_VAES_AVX2() } } -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 @@ BoolInt CPU_IsSupported_PageGB() #ifdef _WIN32 -#include +#include "7zWindows.h" -BoolInt CPU_IsSupported_CRC32() { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } -BoolInt CPU_IsSupported_CRYPTO() { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } -BoolInt CPU_IsSupported_NEON() { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } +BoolInt CPU_IsSupported_CRC32(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } +BoolInt CPU_IsSupported_CRYPTO(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } +BoolInt CPU_IsSupported_NEON(void) { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } #else @@ -378,28 +724,27 @@ static void Print_sysctlbyname(const char *name) } } */ +/* + Print_sysctlbyname("hw.pagesize"); + Print_sysctlbyname("machdep.cpu.brand_string"); +*/ -static BoolInt My_sysctlbyname_Get_BoolInt(const char *name) +static BoolInt z7_sysctlbyname_Get_BoolInt(const char *name) { UInt32 val = 0; - if (My_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) + if (z7_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) return 1; return 0; } - /* - Print_sysctlbyname("hw.pagesize"); - Print_sysctlbyname("machdep.cpu.brand_string"); - */ - BoolInt CPU_IsSupported_CRC32(void) { - return My_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); + return z7_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); } BoolInt CPU_IsSupported_NEON(void) { - return My_sysctlbyname_Get_BoolInt("hw.optional.neon"); + return z7_sysctlbyname_Get_BoolInt("hw.optional.neon"); } #ifdef MY_CPU_ARM64 @@ -461,15 +806,15 @@ MY_HWCAP_CHECK_FUNC (AES) #include -int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) +int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) { return sysctlbyname(name, buf, bufSize, NULL, 0); } -int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) +int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) { size_t bufSize = sizeof(*val); - int res = My_sysctlbyname_Get(name, val, &bufSize); + const int res = z7_sysctlbyname_Get(name, val, &bufSize); if (res == 0 && bufSize != sizeof(*val)) return EFAULT; return res; diff --git a/C/CpuArch.h b/C/CpuArch.h index 4856fbb1..8e5d8a54 100644 --- a/C/CpuArch.h +++ b/C/CpuArch.h @@ -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 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. || defined(__AARCH64EB__) \ || defined(__aarch64__) #define MY_CPU_ARM64 - #define MY_CPU_NAME "arm64" + #ifdef __ILP32__ + #define MY_CPU_NAME "arm64-32" + #define MY_CPU_SIZEOF_POINTER 4 + #else + #define MY_CPU_NAME "arm64" + #define MY_CPU_SIZEOF_POINTER 8 + #endif #define MY_CPU_64BIT #endif @@ -68,8 +74,10 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. #define MY_CPU_ARM #if defined(__thumb__) || defined(__THUMBEL__) || defined(_M_ARMT) + #define MY_CPU_ARMT #define MY_CPU_NAME "armt" #else + #define MY_CPU_ARM32 #define MY_CPU_NAME "arm" #endif /* #define MY_CPU_32BIT */ @@ -103,6 +111,8 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. || defined(__PPC__) \ || defined(_POWER) +#define MY_CPU_PPC_OR_PPC64 + #if defined(__ppc64__) \ || defined(__powerpc64__) \ || defined(_LP64) \ @@ -197,6 +207,9 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. #error Stop_Compiling_Bad_Endian #endif +#if !defined(MY_CPU_LE) && !defined(MY_CPU_BE) + #error Stop_Compiling_CPU_ENDIAN_must_be_detected_at_compile_time +#endif #if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) #error Stop_Compiling_Bad_32_64_BIT @@ -253,6 +266,67 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. +#ifdef __has_builtin + #define Z7_has_builtin(x) __has_builtin(x) +#else + #define Z7_has_builtin(x) 0 +#endif + + +#define Z7_BSWAP32_CONST(v) \ + ( (((UInt32)(v) << 24) ) \ + | (((UInt32)(v) << 8) & (UInt32)0xff0000) \ + | (((UInt32)(v) >> 8) & (UInt32)0xff00 ) \ + | (((UInt32)(v) >> 24) )) + + +#if defined(_MSC_VER) && (_MSC_VER >= 1300) + +#include + +/* Note: these macros will use bswap instruction (486), that is unsupported in 386 cpu */ + +#pragma intrinsic(_byteswap_ushort) +#pragma intrinsic(_byteswap_ulong) +#pragma intrinsic(_byteswap_uint64) + +#define Z7_BSWAP16(v) _byteswap_ushort(v) +#define Z7_BSWAP32(v) _byteswap_ulong (v) +#define Z7_BSWAP64(v) _byteswap_uint64(v) +#define Z7_CPU_FAST_BSWAP_SUPPORTED + +#elif (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ + || (defined(__clang__) && Z7_has_builtin(__builtin_bswap16)) + +#define Z7_BSWAP16(v) __builtin_bswap16(v) +#define Z7_BSWAP32(v) __builtin_bswap32(v) +#define Z7_BSWAP64(v) __builtin_bswap64(v) +#define Z7_CPU_FAST_BSWAP_SUPPORTED + +#else + +#define Z7_BSWAP16(v) ((UInt16) \ + ( ((UInt32)(v) << 8) \ + | ((UInt32)(v) >> 8) \ + )) + +#define Z7_BSWAP32(v) Z7_BSWAP32_CONST(v) + +#define Z7_BSWAP64(v) \ + ( ( ( (UInt64)(v) ) << 8 * 7 ) \ + | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 1) ) << 8 * 5 ) \ + | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 2) ) << 8 * 3 ) \ + | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 3) ) << 8 * 1 ) \ + | ( ( (UInt64)(v) >> 8 * 1 ) & ((UInt32)0xff << 8 * 3) ) \ + | ( ( (UInt64)(v) >> 8 * 3 ) & ((UInt32)0xff << 8 * 2) ) \ + | ( ( (UInt64)(v) >> 8 * 5 ) & ((UInt32)0xff << 8 * 1) ) \ + | ( ( (UInt64)(v) >> 8 * 7 ) ) \ + ) + +#endif + + + #ifdef MY_CPU_LE #if defined(MY_CPU_X86_OR_AMD64) \ || defined(MY_CPU_ARM64) @@ -272,13 +346,11 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. #define GetUi32(p) (*(const UInt32 *)(const void *)(p)) #ifdef MY_CPU_LE_UNALIGN_64 #define GetUi64(p) (*(const UInt64 *)(const void *)(p)) +#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } #endif #define SetUi16(p, v) { *(UInt16 *)(void *)(p) = (v); } #define SetUi32(p, v) { *(UInt32 *)(void *)(p) = (v); } -#ifdef MY_CPU_LE_UNALIGN_64 -#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); } -#endif #else @@ -305,51 +377,26 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. #endif -#ifndef MY_CPU_LE_UNALIGN_64 - +#ifndef GetUi64 #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) +#endif +#ifndef SetUi64 #define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ - SetUi32(_ppp2_ , (UInt32)_vvv2_); \ - SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } - + SetUi32(_ppp2_ , (UInt32)_vvv2_) \ + SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)) } #endif +#if defined(MY_CPU_LE_UNALIGN) && defined(Z7_CPU_FAST_BSWAP_SUPPORTED) +#define GetBe32(p) Z7_BSWAP32 (*(const UInt32 *)(const void *)(p)) +#define SetBe32(p, v) { (*(UInt32 *)(void *)(p)) = Z7_BSWAP32(v); } -#ifdef __has_builtin - #define MY__has_builtin(x) __has_builtin(x) -#else - #define MY__has_builtin(x) 0 +#if defined(MY_CPU_LE_UNALIGN_64) +#define GetBe64(p) Z7_BSWAP64 (*(const UInt64 *)(const void *)(p)) #endif -#if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ defined(_MSC_VER) && (_MSC_VER >= 1300) - -/* Note: we use bswap instruction, that is unsupported in 386 cpu */ - -#include - -#pragma intrinsic(_byteswap_ushort) -#pragma intrinsic(_byteswap_ulong) -#pragma intrinsic(_byteswap_uint64) - -/* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */ -#define GetBe32(p) _byteswap_ulong (*(const UInt32 *)(const void *)(p)) -#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const void *)(p)) - -#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) - -#elif defined(MY_CPU_LE_UNALIGN) && ( \ - (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ - || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) ) - -/* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const void *)(p)) */ -#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const void *)(p)) -#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const void *)(p)) - -#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) - #else #define GetBe32(p) ( \ @@ -358,8 +405,6 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. ((UInt32)((const Byte *)(p))[2] << 8) | \ ((const Byte *)(p))[3] ) -#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) - #define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ _ppp_[0] = (Byte)(_vvv_ >> 24); \ _ppp_[1] = (Byte)(_vvv_ >> 16); \ @@ -368,50 +413,83 @@ MY_CPU_64BIT means that processor can work with 64-bit registers. #endif +#ifndef GetBe64 +#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) +#endif #ifndef GetBe16 - #define GetBe16(p) ( (UInt16) ( \ ((UInt16)((const Byte *)(p))[0] << 8) | \ ((const Byte *)(p))[1] )) +#endif + +#if defined(MY_CPU_BE) +#define Z7_CONV_BE_TO_NATIVE_CONST32(v) (v) +#define Z7_CONV_LE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) +#define Z7_CONV_NATIVE_TO_BE_32(v) (v) +#elif defined(MY_CPU_LE) +#define Z7_CONV_BE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v) +#define Z7_CONV_LE_TO_NATIVE_CONST32(v) (v) +#define Z7_CONV_NATIVE_TO_BE_32(v) Z7_BSWAP32(v) +#else +#error Stop_Compiling_Unknown_Endian_CONV #endif +#if defined(MY_CPU_BE) -#ifdef MY_CPU_X86_OR_AMD64 +#define GetBe32a(p) (*(const UInt32 *)(const void *)(p)) +#define GetBe16a(p) (*(const UInt16 *)(const void *)(p)) +#define SetBe32a(p, v) { *(UInt32 *)(void *)(p) = (v); } +#define SetBe16a(p, v) { *(UInt16 *)(void *)(p) = (v); } + +#define GetUi32a(p) GetUi32(p) +#define GetUi16a(p) GetUi16(p) +#define SetUi32a(p, v) SetUi32(p, v) +#define SetUi16a(p, v) SetUi16(p, v) + +#elif defined(MY_CPU_LE) -typedef struct -{ - UInt32 maxFunc; - UInt32 vendor[3]; - UInt32 ver; - UInt32 b; - UInt32 c; - UInt32 d; -} Cx86cpuid; +#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); } -enum -{ - CPU_FIRM_INTEL, - CPU_FIRM_AMD, - CPU_FIRM_VIA -}; +#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 -void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); -BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); -int x86cpuid_GetFirm(const Cx86cpuid *p); +#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 -#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) -BoolInt CPU_Is_InOrder(void); +#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 @@ BoolInt CPU_IsSupported_AES(void); #endif #if defined(__APPLE__) -int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); -int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); +int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); +int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); #endif EXTERN_C_END diff --git a/C/Delta.h b/C/Delta.h index 2fa54ad6..70609541 100644 --- a/C/Delta.h +++ b/C/Delta.h @@ -1,8 +1,8 @@ /* Delta.h -- Delta converter -2013-01-18 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ -#ifndef __DELTA_H -#define __DELTA_H +#ifndef ZIP7_INC_DELTA_H +#define ZIP7_INC_DELTA_H #include "7zTypes.h" diff --git a/C/DllSecur.c b/C/DllSecur.c index dce0c96c..02a0f977 100644 --- a/C/DllSecur.c +++ b/C/DllSecur.c @@ -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 @@ typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags); #define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400 #define MY_LOAD_LIBRARY_SEARCH_SYSTEM32 0x800 +#define DELIM "\0" + static const char * const g_Dlls = + "userenv" + DELIM "setupapi" + DELIM "apphelp" + DELIM "propsys" + DELIM "dwmapi" + DELIM "cryptbase" + DELIM "oleacc" + DELIM "clbcatq" + DELIM "version" #ifndef _CONSOLE - "UXTHEME\0" + DELIM "uxtheme" #endif - "USERENV\0" - "SETUPAPI\0" - "APPHELP\0" - "PROPSYS\0" - "DWMAPI\0" - "CRYPTBASE\0" - "OLEACC\0" - "CLBCATQ\0" - "VERSION\0" - ; + DELIM; #endif -// #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 --git a/C/DllSecur.h b/C/DllSecur.h index 64ff26cd..9fa41538 100644 --- a/C/DllSecur.h +++ b/C/DllSecur.h @@ -1,8 +1,8 @@ /* DllSecur.h -- DLL loading for security -2018-02-19 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ -#ifndef __DLL_SECUR_H -#define __DLL_SECUR_H +#ifndef ZIP7_INC_DLL_SECUR_H +#define ZIP7_INC_DLL_SECUR_H #include "7zTypes.h" diff --git a/C/HuffEnc.c b/C/HuffEnc.c index f3c2996d..3dc1e392 100644 --- a/C/HuffEnc.c +++ b/C/HuffEnc.c @@ -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 @@ void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymb 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 @@ void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymb } } } + +#undef kMaxLen +#undef NUM_BITS +#undef MASK +#undef NUM_COUNTERS +#undef HUFFMAN_SPEED_OPT diff --git a/C/HuffEnc.h b/C/HuffEnc.h index 92b6878d..cbc5d11f 100644 --- a/C/HuffEnc.h +++ b/C/HuffEnc.h @@ -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 --git a/C/LzFind.c b/C/LzFind.c index 1b73c284..0fbd5aae 100644 --- a/C/LzFind.c +++ b/C/LzFind.c @@ -1,5 +1,5 @@ /* LzFind.c -- Match finder for LZ algorithms -2021-11-29 : Igor Pavlov : Public domain */ +2023-03-14 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -17,7 +17,7 @@ #define kEmptyHashValue 0 #define kMaxValForNormalize ((UInt32)0) -// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xFFF) // for debug +// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xfff) // for debug // #define kNormalizeAlign (1 << 7) // alignment for speculated accesses @@ -67,10 +67,10 @@ static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc) { - if (!p->directInput) + // if (!p->directInput) { - ISzAlloc_Free(alloc, p->bufferBase); - p->bufferBase = NULL; + ISzAlloc_Free(alloc, p->bufBase); + p->bufBase = NULL; } } @@ -79,7 +79,7 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all { if (blockSize == 0) return 0; - if (!p->bufferBase || p->blockSize != blockSize) + if (!p->bufBase || p->blockSize != blockSize) { // size_t blockSizeT; LzInWindow_Free(p, alloc); @@ -101,11 +101,11 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all #endif */ - p->bufferBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); - // printf("\nbufferBase = %p\n", p->bufferBase); + p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); + // printf("\nbufferBase = %p\n", p->bufBase); // return 0; // for debug } - return (p->bufferBase != NULL); + return (p->bufBase != NULL); } static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } @@ -113,7 +113,7 @@ static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return GET_AVAIL_BYTES(p); } -MY_NO_INLINE +Z7_NO_INLINE static void MatchFinder_ReadBlock(CMatchFinder *p) { if (p->streamEndWasReached || p->result != SZ_OK) @@ -127,8 +127,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) UInt32 curSize = 0xFFFFFFFF - GET_AVAIL_BYTES(p); if (curSize > p->directInputRem) curSize = (UInt32)p->directInputRem; - p->directInputRem -= curSize; p->streamPos += curSize; + p->directInputRem -= curSize; if (p->directInputRem == 0) p->streamEndWasReached = 1; return; @@ -136,8 +136,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) for (;;) { - Byte *dest = p->buffer + GET_AVAIL_BYTES(p); - size_t size = (size_t)(p->bufferBase + p->blockSize - dest); + const Byte *dest = p->buffer + GET_AVAIL_BYTES(p); + size_t size = (size_t)(p->bufBase + p->blockSize - dest); if (size == 0) { /* we call ReadBlock() after NeedMove() and MoveBlock(). @@ -153,7 +153,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) // #define kRead 3 // if (size > kRead) size = kRead; // for debug - p->result = ISeqInStream_Read(p->stream, dest, &size); + /* + // we need cast (Byte *)dest. + #ifdef __clang__ + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + */ + p->result = ISeqInStream_Read(p->stream, + p->bufBase + (dest - p->bufBase), &size); if (p->result != SZ_OK) return; if (size == 0) @@ -173,14 +180,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p) -MY_NO_INLINE +Z7_NO_INLINE void MatchFinder_MoveBlock(CMatchFinder *p) { - const size_t offset = (size_t)(p->buffer - p->bufferBase) - p->keepSizeBefore; + const size_t offset = (size_t)(p->buffer - p->bufBase) - p->keepSizeBefore; const size_t keepBefore = (offset & (kBlockMoveAlign - 1)) + p->keepSizeBefore; - p->buffer = p->bufferBase + keepBefore; - memmove(p->bufferBase, - p->bufferBase + (offset & ~((size_t)kBlockMoveAlign - 1)), + p->buffer = p->bufBase + keepBefore; + memmove(p->bufBase, + p->bufBase + (offset & ~((size_t)kBlockMoveAlign - 1)), keepBefore + (size_t)GET_AVAIL_BYTES(p)); } @@ -198,7 +205,7 @@ int MatchFinder_NeedMove(CMatchFinder *p) return 0; if (p->streamEndWasReached || p->result != SZ_OK) return 0; - return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); + return ((size_t)(p->bufBase + p->blockSize - p->buffer) <= p->keepSizeAfter); } void MatchFinder_ReadIfRequired(CMatchFinder *p) @@ -214,6 +221,8 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) p->cutValue = 32; p->btMode = 1; p->numHashBytes = 4; + p->numHashBytes_Min = 2; + p->numHashOutBits = 0; p->bigHash = 0; } @@ -222,8 +231,10 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p) void MatchFinder_Construct(CMatchFinder *p) { unsigned i; - p->bufferBase = NULL; + p->buffer = NULL; + p->bufBase = NULL; p->directInput = 0; + p->stream = NULL; p->hash = NULL; p->expectedDataSize = (UInt64)(Int64)-1; MatchFinder_SetDefaultSettings(p); @@ -238,6 +249,8 @@ void MatchFinder_Construct(CMatchFinder *p) } } +#undef kCrcPoly + static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) { ISzAlloc_Free(alloc, p->hash); @@ -252,7 +265,7 @@ void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc) static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) { - size_t sizeInBytes = (size_t)num * sizeof(CLzRef); + const size_t sizeInBytes = (size_t)num * sizeof(CLzRef); if (sizeInBytes / sizeof(CLzRef) != num) return NULL; return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); @@ -298,6 +311,62 @@ static UInt32 GetBlockSize(CMatchFinder *p, UInt32 historySize) } +// input is historySize +static UInt32 MatchFinder_GetHashMask2(CMatchFinder *p, UInt32 hs) +{ + if (p->numHashBytes == 2) + return (1 << 16) - 1; + if (hs != 0) + hs--; + hs |= (hs >> 1); + hs |= (hs >> 2); + hs |= (hs >> 4); + hs |= (hs >> 8); + // we propagated 16 bits in (hs). Low 16 bits must be set later + if (hs >= (1 << 24)) + { + if (p->numHashBytes == 3) + hs = (1 << 24) - 1; + /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ + } + // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) + hs |= (1 << 16) - 1; /* don't change it! */ + // bt5: we adjust the size with recommended minimum size + if (p->numHashBytes >= 5) + hs |= (256 << kLzHash_CrcShift_2) - 1; + return hs; +} + +// input is historySize +static UInt32 MatchFinder_GetHashMask(CMatchFinder *p, UInt32 hs) +{ + if (p->numHashBytes == 2) + return (1 << 16) - 1; + if (hs != 0) + hs--; + hs |= (hs >> 1); + hs |= (hs >> 2); + hs |= (hs >> 4); + hs |= (hs >> 8); + // we propagated 16 bits in (hs). Low 16 bits must be set later + hs >>= 1; + if (hs >= (1 << 24)) + { + if (p->numHashBytes == 3) + hs = (1 << 24) - 1; + else + hs >>= 1; + /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ + } + // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) + hs |= (1 << 16) - 1; /* don't change it! */ + // bt5: we adjust the size with recommended minimum size + if (p->numHashBytes >= 5) + hs |= (256 << kLzHash_CrcShift_2) - 1; + return hs; +} + + int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAllocPtr alloc) @@ -318,78 +387,91 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, p->blockSize = 0; if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc)) { - const UInt32 newCyclicBufferSize = historySize + 1; // do not change it - UInt32 hs; - p->matchMaxLen = matchMaxLen; + size_t hashSizeSum; { - // UInt32 hs4; - p->fixedHashSize = 0; - hs = (1 << 16) - 1; - if (p->numHashBytes != 2) + UInt32 hs; + UInt32 hsCur; + + if (p->numHashOutBits != 0) { - hs = historySize; - if (hs > p->expectedDataSize) - hs = (UInt32)p->expectedDataSize; - if (hs != 0) - hs--; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - // we propagated 16 bits in (hs). Low 16 bits must be set later - hs >>= 1; - if (hs >= (1 << 24)) - { - if (p->numHashBytes == 3) - hs = (1 << 24) - 1; - else - hs >>= 1; - /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ - } - - // hs = ((UInt32)1 << 25) - 1; // for test - + unsigned numBits = p->numHashOutBits; + const unsigned nbMax = + (p->numHashBytes == 2 ? 16 : + (p->numHashBytes == 3 ? 24 : 32)); + if (numBits > nbMax) + numBits = nbMax; + if (numBits >= 32) + hs = (UInt32)0 - 1; + else + hs = ((UInt32)1 << numBits) - 1; // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) hs |= (1 << 16) - 1; /* don't change it! */ - - // bt5: we adjust the size with recommended minimum size if (p->numHashBytes >= 5) hs |= (256 << kLzHash_CrcShift_2) - 1; + { + const UInt32 hs2 = MatchFinder_GetHashMask2(p, historySize); + if (hs > hs2) + hs = hs2; + } + hsCur = hs; + if (p->expectedDataSize < historySize) + { + const UInt32 hs2 = MatchFinder_GetHashMask2(p, (UInt32)p->expectedDataSize); + if (hsCur > hs2) + hsCur = hs2; + } } - p->hashMask = hs; - hs++; - - /* - hs4 = (1 << 20); - if (hs4 > hs) - hs4 = hs; - // hs4 = (1 << 16); // for test - p->hash4Mask = hs4 - 1; - */ + else + { + hs = MatchFinder_GetHashMask(p, historySize); + hsCur = hs; + if (p->expectedDataSize < historySize) + { + hsCur = MatchFinder_GetHashMask(p, (UInt32)p->expectedDataSize); + if (hsCur > hs) // is it possible? + hsCur = hs; + } + } + + p->hashMask = hsCur; - if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; - if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; - // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; - hs += p->fixedHashSize; + hashSizeSum = hs; + hashSizeSum++; + if (hashSizeSum < hs) + return 0; + { + UInt32 fixedHashSize = 0; + if (p->numHashBytes > 2 && p->numHashBytes_Min <= 2) fixedHashSize += kHash2Size; + if (p->numHashBytes > 3 && p->numHashBytes_Min <= 3) fixedHashSize += kHash3Size; + // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; + hashSizeSum += fixedHashSize; + p->fixedHashSize = fixedHashSize; + } } + p->matchMaxLen = matchMaxLen; + { size_t newSize; size_t numSons; + const UInt32 newCyclicBufferSize = historySize + 1; // do not change it p->historySize = historySize; - p->hashSizeSum = hs; p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1) numSons = newCyclicBufferSize; if (p->btMode) numSons <<= 1; - newSize = hs + numSons; + newSize = hashSizeSum + numSons; + + if (numSons < newCyclicBufferSize || newSize < numSons) + return 0; // aligned size is not required here, but it can be better for some loops #define NUM_REFS_ALIGN_MASK 0xF newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK; - if (p->hash && p->numRefs == newSize) + // 22.02: we don't reallocate buffer, if old size is enough + if (p->hash && p->numRefs >= newSize) return 1; MatchFinder_FreeThisClassMemory(p, alloc); @@ -398,7 +480,7 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, if (p->hash) { - p->son = p->hash + p->hashSizeSum; + p->son = p->hash + hashSizeSum; return 1; } } @@ -470,7 +552,8 @@ void MatchFinder_Init_HighHash(CMatchFinder *p) void MatchFinder_Init_4(CMatchFinder *p) { - p->buffer = p->bufferBase; + if (!p->directInput) + p->buffer = p->bufBase; { /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker. the code in CMatchFinderMt expects (pos = 1) */ @@ -507,20 +590,20 @@ void MatchFinder_Init(CMatchFinder *p) #ifdef MY_CPU_X86_OR_AMD64 - #if defined(__clang__) && (__clang_major__ >= 8) \ - || defined(__GNUC__) && (__GNUC__ >= 8) \ - || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) - #define USE_SATUR_SUB_128 - #define USE_AVX2 - #define ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) - #define ATTRIB_AVX2 __attribute__((__target__("avx2"))) + #if defined(__clang__) && (__clang_major__ >= 4) \ + || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701) + // || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) + + #define USE_LZFIND_SATUR_SUB_128 + #define USE_LZFIND_SATUR_SUB_256 + #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) + #define LZFIND_ATTRIB_AVX2 __attribute__((__target__("avx2"))) #elif defined(_MSC_VER) #if (_MSC_VER >= 1600) - #define USE_SATUR_SUB_128 - #if (_MSC_VER >= 1900) - #define USE_AVX2 - #include // avx - #endif + #define USE_LZFIND_SATUR_SUB_128 + #endif + #if (_MSC_VER >= 1900) + #define USE_LZFIND_SATUR_SUB_256 #endif #endif @@ -529,16 +612,16 @@ void MatchFinder_Init(CMatchFinder *p) #if defined(__clang__) && (__clang_major__ >= 8) \ || defined(__GNUC__) && (__GNUC__ >= 8) - #define USE_SATUR_SUB_128 + #define USE_LZFIND_SATUR_SUB_128 #ifdef MY_CPU_ARM64 - // #define ATTRIB_SSE41 __attribute__((__target__(""))) + // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__(""))) #else - // #define ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) + // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) #endif #elif defined(_MSC_VER) #if (_MSC_VER >= 1910) - #define USE_SATUR_SUB_128 + #define USE_LZFIND_SATUR_SUB_128 #endif #endif @@ -550,121 +633,130 @@ void MatchFinder_Init(CMatchFinder *p) #endif -/* -#ifndef ATTRIB_SSE41 - #define ATTRIB_SSE41 -#endif -#ifndef ATTRIB_AVX2 - #define ATTRIB_AVX2 -#endif -*/ -#ifdef USE_SATUR_SUB_128 +#ifdef USE_LZFIND_SATUR_SUB_128 -// #define _SHOW_HW_STATUS +// #define Z7_SHOW_HW_STATUS -#ifdef _SHOW_HW_STATUS +#ifdef Z7_SHOW_HW_STATUS #include -#define _PRF(x) x -_PRF(;) +#define PRF(x) x +PRF(;) #else -#define _PRF(x) +#define PRF(x) #endif + #ifdef MY_CPU_ARM_OR_ARM64 #ifdef MY_CPU_ARM64 -// #define FORCE_SATUR_SUB_128 +// #define FORCE_LZFIND_SATUR_SUB_128 #endif +typedef uint32x4_t LzFind_v128; +#define SASUB_128_V(v, s) \ + vsubq_u32(vmaxq_u32(v, s), s) -typedef uint32x4_t v128; -#define SASUB_128(i) \ - *(v128 *)(void *)(items + (i) * 4) = \ - vsubq_u32(vmaxq_u32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); - -#else +#else // MY_CPU_ARM_OR_ARM64 #include // sse4.1 -typedef __m128i v128; -#define SASUB_128(i) \ - *(v128 *)(void *)(items + (i) * 4) = \ - _mm_sub_epi32(_mm_max_epu32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); // SSE 4.1 +typedef __m128i LzFind_v128; +// SSE 4.1 +#define SASUB_128_V(v, s) \ + _mm_sub_epi32(_mm_max_epu32(v, s), s) -#endif +#endif // MY_CPU_ARM_OR_ARM64 +#define SASUB_128(i) \ + *( LzFind_v128 *)( void *)(items + (i) * 4) = SASUB_128_V( \ + *(const LzFind_v128 *)(const void *)(items + (i) * 4), sub2); + -MY_NO_INLINE +Z7_NO_INLINE static -#ifdef ATTRIB_SSE41 -ATTRIB_SSE41 +#ifdef LZFIND_ATTRIB_SSE41 +LZFIND_ATTRIB_SSE41 #endif void -MY_FAST_CALL +Z7_FASTCALL LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim) { - v128 sub2 = + const LzFind_v128 sub2 = #ifdef MY_CPU_ARM_OR_ARM64 vdupq_n_u32(subValue); #else _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); #endif + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { - SASUB_128(0) - SASUB_128(1) - SASUB_128(2) - SASUB_128(3) - items += 4 * 4; + SASUB_128(0) SASUB_128(1) items += 2 * 4; + SASUB_128(0) SASUB_128(1) items += 2 * 4; } while (items != lim); } -#ifdef USE_AVX2 +#ifdef USE_LZFIND_SATUR_SUB_256 #include // avx +/* +clang :immintrin.h uses +#if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ + defined(__AVX2__) +#include +#endif +so we need for clang-cl */ -#define SASUB_256(i) *(__m256i *)(void *)(items + (i) * 8) = _mm256_sub_epi32(_mm256_max_epu32(*(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); // AVX2 +#if defined(__clang__) +#include +#include +#endif -MY_NO_INLINE +// AVX2: +#define SASUB_256(i) \ + *( __m256i *)( void *)(items + (i) * 8) = \ + _mm256_sub_epi32(_mm256_max_epu32( \ + *(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2); + +Z7_NO_INLINE static -#ifdef ATTRIB_AVX2 -ATTRIB_AVX2 +#ifdef LZFIND_ATTRIB_AVX2 +LZFIND_ATTRIB_AVX2 #endif void -MY_FAST_CALL +Z7_FASTCALL LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim) { - __m256i sub2 = _mm256_set_epi32( + const __m256i sub2 = _mm256_set_epi32( (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { - SASUB_256(0) - SASUB_256(1) - items += 2 * 8; + SASUB_256(0) SASUB_256(1) items += 2 * 8; + SASUB_256(0) SASUB_256(1) items += 2 * 8; } while (items != lim); } -#endif // USE_AVX2 +#endif // USE_LZFIND_SATUR_SUB_256 -#ifndef FORCE_SATUR_SUB_128 -typedef void (MY_FAST_CALL *LZFIND_SATUR_SUB_CODE_FUNC)( +#ifndef FORCE_LZFIND_SATUR_SUB_128 +typedef void (Z7_FASTCALL *LZFIND_SATUR_SUB_CODE_FUNC)( UInt32 subValue, CLzRef *items, const CLzRef *lim); static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; -#endif // FORCE_SATUR_SUB_128 +#endif // FORCE_LZFIND_SATUR_SUB_128 -#endif // USE_SATUR_SUB_128 +#endif // USE_LZFIND_SATUR_SUB_128 // kEmptyHashValue must be zero -// #define SASUB_32(i) v = items[i]; m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; -#define SASUB_32(i) v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; +// #define SASUB_32(i) { UInt32 v = items[i]; UInt32 m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; } +#define SASUB_32(i) { UInt32 v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; } -#ifdef FORCE_SATUR_SUB_128 +#ifdef FORCE_LZFIND_SATUR_SUB_128 #define DEFAULT_SaturSub LzFind_SaturSub_128 @@ -672,24 +764,19 @@ static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; #define DEFAULT_SaturSub LzFind_SaturSub_32 -MY_NO_INLINE +Z7_NO_INLINE static void -MY_FAST_CALL +Z7_FASTCALL LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) { + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE do { - UInt32 v; - SASUB_32(0) - SASUB_32(1) - SASUB_32(2) - SASUB_32(3) - SASUB_32(4) - SASUB_32(5) - SASUB_32(6) - SASUB_32(7) - items += 8; + SASUB_32(0) SASUB_32(1) items += 2; + SASUB_32(0) SASUB_32(1) items += 2; + SASUB_32(0) SASUB_32(1) items += 2; + SASUB_32(0) SASUB_32(1) items += 2; } while (items != lim); } @@ -697,27 +784,23 @@ LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) #endif -MY_NO_INLINE +Z7_NO_INLINE void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) { - #define K_NORM_ALIGN_BLOCK_SIZE (1 << 6) - - CLzRef *lim; - - for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (K_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) + #define LZFIND_NORM_ALIGN_BLOCK_SIZE (1 << 7) + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE + for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (LZFIND_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--) { - UInt32 v; - SASUB_32(0); + SASUB_32(0) items++; } - { - #define K_NORM_ALIGN_MASK (K_NORM_ALIGN_BLOCK_SIZE / 4 - 1) - lim = items + (numItems & ~(size_t)K_NORM_ALIGN_MASK); - numItems &= K_NORM_ALIGN_MASK; + const size_t k_Align_Mask = (LZFIND_NORM_ALIGN_BLOCK_SIZE / 4 - 1); + CLzRef *lim = items + (numItems & ~(size_t)k_Align_Mask); + numItems &= k_Align_Mask; if (items != lim) { - #if defined(USE_SATUR_SUB_128) && !defined(FORCE_SATUR_SUB_128) + #if defined(USE_LZFIND_SATUR_SUB_128) && !defined(FORCE_LZFIND_SATUR_SUB_128) if (g_LzFind_SaturSub) g_LzFind_SaturSub(subValue, items, lim); else @@ -726,12 +809,10 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) } items = lim; } - - + Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE for (; numItems != 0; numItems--) { - UInt32 v; - SASUB_32(0); + SASUB_32(0) items++; } } @@ -740,7 +821,7 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) // call MatchFinder_CheckLimits() only after (p->pos++) update -MY_NO_INLINE +Z7_NO_INLINE static void MatchFinder_CheckLimits(CMatchFinder *p) { if (// !p->streamEndWasReached && p->result == SZ_OK && @@ -768,11 +849,14 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */; // const UInt32 subValue = (1 << 15); // for debug // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue); - size_t numSonRefs = p->cyclicBufferSize; - if (p->btMode) - numSonRefs <<= 1; - Inline_MatchFinder_ReduceOffsets(p, subValue); - MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashSizeSum + numSonRefs); + MatchFinder_REDUCE_OFFSETS(p, subValue) + MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashMask + 1 + p->fixedHashSize); + { + size_t numSonRefs = p->cyclicBufferSize; + if (p->btMode) + numSonRefs <<= 1; + MatchFinder_Normalize3(subValue, p->son, numSonRefs); + } } if (p->cyclicBufferPos == p->cyclicBufferSize) @@ -785,7 +869,7 @@ static void MatchFinder_CheckLimits(CMatchFinder *p) /* (lenLimit > maxLen) */ -MY_FORCE_INLINE +Z7_FORCE_INLINE static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, UInt32 *d, unsigned maxLen) @@ -867,7 +951,7 @@ static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, } -MY_FORCE_INLINE +Z7_FORCE_INLINE UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, UInt32 *d, UInt32 maxLen) @@ -1004,7 +1088,7 @@ static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const #define MOVE_POS_RET MOVE_POS return distances; -MY_NO_INLINE +Z7_NO_INLINE static void MatchFinder_MovePos(CMatchFinder *p) { /* we go here at the end of stream data, when (avail < num_hash_bytes) @@ -1015,11 +1099,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) if (p->btMode) p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue */ - MOVE_POS; + MOVE_POS } #define GET_MATCHES_HEADER2(minLen, ret_op) \ - unsigned lenLimit; UInt32 hv; Byte *cur; UInt32 curMatch; \ + unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \ lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ cur = p->buffer; @@ -1028,11 +1112,11 @@ static void MatchFinder_MovePos(CMatchFinder *p) #define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue -#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS; } while (--num); +#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS } while (--num); #define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \ distances = func(MF_PARAMS(p), \ - distances, (UInt32)_maxLen_); MOVE_POS_RET; + distances, (UInt32)_maxLen_); MOVE_POS_RET #define GET_MATCHES_FOOTER_BT(_maxLen_) \ GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1) @@ -1052,7 +1136,7 @@ static void MatchFinder_MovePos(CMatchFinder *p) static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(2) - HASH2_CALC; + HASH2_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_BT(1) @@ -1061,7 +1145,7 @@ static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_BT(2) @@ -1082,7 +1166,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32 *hash; GET_MATCHES_HEADER(3) - HASH3_CALC; + HASH3_CALC hash = p->hash; pos = p->pos; @@ -1107,7 +1191,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); - MOVE_POS_RET; + MOVE_POS_RET } } @@ -1123,7 +1207,7 @@ static UInt32* Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32 *hash; GET_MATCHES_HEADER(4) - HASH4_CALC; + HASH4_CALC hash = p->hash; pos = p->pos; @@ -1190,7 +1274,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32 *hash; GET_MATCHES_HEADER(5) - HASH5_CALC; + HASH5_CALC hash = p->hash; pos = p->pos; @@ -1246,7 +1330,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) if (maxLen == lenLimit) { SkipMatchesSpec(MF_PARAMS(p)); - MOVE_POS_RET; + MOVE_POS_RET } break; } @@ -1263,7 +1347,7 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32 *hash; GET_MATCHES_HEADER(4) - HASH4_CALC; + HASH4_CALC hash = p->hash; pos = p->pos; @@ -1314,12 +1398,12 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS_RET; + MOVE_POS_RET } break; } - GET_MATCHES_FOOTER_HC(maxLen); + GET_MATCHES_FOOTER_HC(maxLen) } @@ -1330,7 +1414,7 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) UInt32 *hash; GET_MATCHES_HEADER(5) - HASH5_CALC; + HASH5_CALC hash = p->hash; pos = p->pos; @@ -1386,19 +1470,19 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS_RET; + MOVE_POS_RET } break; } - GET_MATCHES_FOOTER_HC(maxLen); + GET_MATCHES_FOOTER_HC(maxLen) } UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) { GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; GET_MATCHES_FOOTER_HC(2) @@ -1409,7 +1493,7 @@ static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(2) { - HASH2_CALC; + HASH2_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } @@ -1420,7 +1504,7 @@ void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { SKIP_HEADER(3) { - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = p->hash[hv]; p->hash[hv] = p->pos; } @@ -1433,7 +1517,7 @@ static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { UInt32 h2; UInt32 *hash; - HASH3_CALC; + HASH3_CALC hash = p->hash; curMatch = (hash + kFix3HashSize)[hv]; hash[h2] = @@ -1448,7 +1532,7 @@ static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { UInt32 h2, h3; UInt32 *hash; - HASH4_CALC; + HASH4_CALC hash = p->hash; curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = @@ -1464,7 +1548,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { UInt32 h2, h3; UInt32 *hash; - HASH5_CALC; + HASH5_CALC hash = p->hash; curMatch = (hash + kFix5HashSize)[hv]; hash [h2] = @@ -1478,7 +1562,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) #define HC_SKIP_HEADER(minLen) \ do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \ - Byte *cur; \ + const Byte *cur; \ UInt32 *hash; \ UInt32 *son; \ UInt32 pos = p->pos; \ @@ -1510,7 +1594,7 @@ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) HC_SKIP_HEADER(4) UInt32 h2, h3; - HASH4_CALC; + HASH4_CALC curMatch = (hash + kFix4HashSize)[hv]; hash [h2] = (hash + kFix3HashSize)[h3] = @@ -1540,7 +1624,7 @@ void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { HC_SKIP_HEADER(3) - HASH_ZIP_CALC; + HASH_ZIP_CALC curMatch = hash[hv]; hash[hv] = pos; @@ -1590,17 +1674,17 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder2 *vTable) -void LzFindPrepare() +void LzFindPrepare(void) { - #ifndef FORCE_SATUR_SUB_128 - #ifdef USE_SATUR_SUB_128 + #ifndef FORCE_LZFIND_SATUR_SUB_128 + #ifdef USE_LZFIND_SATUR_SUB_128 LZFIND_SATUR_SUB_CODE_FUNC f = NULL; #ifdef MY_CPU_ARM_OR_ARM64 { if (CPU_IsSupported_NEON()) { // #pragma message ("=== LzFind NEON") - _PRF(printf("\n=== LzFind NEON\n")); + PRF(printf("\n=== LzFind NEON\n")); f = LzFind_SaturSub_128; } // f = 0; // for debug @@ -1609,20 +1693,25 @@ void LzFindPrepare() if (CPU_IsSupported_SSE41()) { // #pragma message ("=== LzFind SSE41") - _PRF(printf("\n=== LzFind SSE41\n")); + PRF(printf("\n=== LzFind SSE41\n")); f = LzFind_SaturSub_128; - #ifdef USE_AVX2 + #ifdef USE_LZFIND_SATUR_SUB_256 if (CPU_IsSupported_AVX2()) { // #pragma message ("=== LzFind AVX2") - _PRF(printf("\n=== LzFind AVX2\n")); + PRF(printf("\n=== LzFind AVX2\n")); f = LzFind_SaturSub_256; } #endif } #endif // MY_CPU_ARM_OR_ARM64 g_LzFind_SaturSub = f; - #endif // USE_SATUR_SUB_128 - #endif // FORCE_SATUR_SUB_128 + #endif // USE_LZFIND_SATUR_SUB_128 + #endif // FORCE_LZFIND_SATUR_SUB_128 } + + +#undef MOVE_POS +#undef MOVE_POS_RET +#undef PRF diff --git a/C/LzFind.h b/C/LzFind.h index eea873ff..a3f72c98 100644 --- a/C/LzFind.h +++ b/C/LzFind.h @@ -1,8 +1,8 @@ /* LzFind.h -- Match finder for LZ algorithms -2021-07-13 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ -#ifndef __LZ_FIND_H -#define __LZ_FIND_H +#ifndef ZIP7_INC_LZ_FIND_H +#define ZIP7_INC_LZ_FIND_H #include "7zTypes.h" @@ -10,9 +10,9 @@ EXTERN_C_BEGIN typedef UInt32 CLzRef; -typedef struct _CMatchFinder +typedef struct { - Byte *buffer; + const Byte *buffer; UInt32 pos; UInt32 posLimit; UInt32 streamPos; /* wrap over Zero is allowed (streamPos < pos). Use (UInt32)(streamPos - pos) */ @@ -32,8 +32,8 @@ typedef struct _CMatchFinder UInt32 hashMask; UInt32 cutValue; - Byte *bufferBase; - ISeqInStream *stream; + Byte *bufBase; + ISeqInStreamPtr stream; UInt32 blockSize; UInt32 keepSizeBefore; @@ -43,7 +43,9 @@ typedef struct _CMatchFinder size_t directInputRem; UInt32 historySize; UInt32 fixedHashSize; - UInt32 hashSizeSum; + Byte numHashBytes_Min; + Byte numHashOutBits; + Byte _pad2_[2]; SRes result; UInt32 crc[256]; size_t numRefs; @@ -69,24 +71,45 @@ void MatchFinder_ReadIfRequired(CMatchFinder *p); void MatchFinder_Construct(CMatchFinder *p); -/* Conditions: - historySize <= 3 GB - keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB +/* (directInput = 0) is default value. + It's required to provide correct (directInput) value + before calling MatchFinder_Create(). + You can set (directInput) by any of the following calls: + - MatchFinder_SET_DIRECT_INPUT_BUF() + - MatchFinder_SET_STREAM() + - MatchFinder_SET_STREAM_MODE() */ + +#define MatchFinder_SET_DIRECT_INPUT_BUF(p, _src_, _srcLen_) { \ + (p)->stream = NULL; \ + (p)->directInput = 1; \ + (p)->buffer = (_src_); \ + (p)->directInputRem = (_srcLen_); } + +/* +#define MatchFinder_SET_STREAM_MODE(p) { \ + (p)->directInput = 0; } +*/ + +#define MatchFinder_SET_STREAM(p, _stream_) { \ + (p)->stream = _stream_; \ + (p)->directInput = 0; } + + int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAllocPtr alloc); void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc); void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems); -// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); /* -#define Inline_MatchFinder_InitPos(p, val) \ +#define MatchFinder_INIT_POS(p, val) \ (p)->pos = (val); \ (p)->streamPos = (val); */ -#define Inline_MatchFinder_ReduceOffsets(p, subValue) \ +// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); +#define MatchFinder_REDUCE_OFFSETS(p, subValue) \ (p)->pos -= (subValue); \ (p)->streamPos -= (subValue); @@ -107,7 +130,7 @@ typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); typedef UInt32 * (*Mf_GetMatches_Func)(void *object, UInt32 *distances); typedef void (*Mf_Skip_Func)(void *object, UInt32); -typedef struct _IMatchFinder +typedef struct { Mf_Init_Func Init; Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; diff --git a/C/LzFindMt.c b/C/LzFindMt.c index 4e67fc3f..5253e6eb 100644 --- a/C/LzFindMt.c +++ b/C/LzFindMt.c @@ -1,5 +1,5 @@ /* LzFindMt.c -- multithreaded Match finder for LZ algorithms -2021-12-21 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -69,7 +69,7 @@ extern UInt64 g_NumIters_Bytes; UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } -#define __MT_HASH4_CALC { \ +#define MT_HASH4_CALC { \ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ temp ^= ((UInt32)cur[2] << 8); \ @@ -79,14 +79,14 @@ extern UInt64 g_NumIters_Bytes; */ -MY_NO_INLINE +Z7_NO_INLINE static void MtSync_Construct(CMtSync *p) { p->affinity = 0; p->wasCreated = 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 @@ static void MtSync_Construct(CMtSync *p) (p)->csWasEntered = False; } -MY_NO_INLINE +Z7_NO_INLINE static UInt32 MtSync_GetNextBlock(CMtSync *p) { UInt32 numBlocks = 0; @@ -140,14 +140,14 @@ static UInt32 MtSync_GetNextBlock(CMtSync *p) // buffer is UNLOCKED here Semaphore_Wait(&p->filledSemaphore); - LOCK_BUFFER(p); + LOCK_BUFFER(p) return numBlocks; } /* if Writing (Processing) thread was started, we must call MtSync_StopWriting() */ -MY_NO_INLINE +Z7_NO_INLINE static void MtSync_StopWriting(CMtSync *p) { if (!Thread_WasCreated(&p->thread) || p->needStart) @@ -185,7 +185,7 @@ static void MtSync_StopWriting(CMtSync *p) } -MY_NO_INLINE +Z7_NO_INLINE static void MtSync_Destruct(CMtSync *p) { PRF(printf("\nMtSync_Destruct %p\n", p)); @@ -220,11 +220,11 @@ static void MtSync_Destruct(CMtSync *p) // #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } // we want to get real system error codes here instead of SZ_ERROR_THREAD -#define RINOK_THREAD(x) RINOK(x) +#define RINOK_THREAD(x) RINOK_WRes(x) // call it before each new file (when new starting is required): -MY_NO_INLINE +Z7_NO_INLINE static SRes MtSync_Init(CMtSync *p, UInt32 numBlocks) { WRes wres; @@ -245,12 +245,12 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * if (p->wasCreated) return SZ_OK; - RINOK_THREAD(CriticalSection_Init(&p->cs)); + RINOK_THREAD(CriticalSection_Init(&p->cs)) p->csWasInitialized = 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 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void * else wres = Thread_Create(&p->thread, startAddress, obj); - RINOK_THREAD(wres); + RINOK_THREAD(wres) p->wasCreated = 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 @@ static void HashThreadFunc(CMatchFinderMt *mt) if (mf->pos > (UInt32)kMtMaxValForNormalize - num) { const UInt32 subValue = (mf->pos - mf->historySize - 1); // & ~(UInt32)(kNormalizeAlign - 1); - Inline_MatchFinder_ReduceOffsets(mf, subValue); + MatchFinder_REDUCE_OFFSETS(mf, subValue) MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, (size_t)mf->hashMask + 1); } @@ -560,7 +560,7 @@ static void HashThreadFunc(CMatchFinderMt *mt) */ -UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, +UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 *posRes); @@ -749,7 +749,7 @@ static void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) } -MY_NO_INLINE +Z7_NO_INLINE static void BtThreadFunc(CMatchFinderMt *mt) { CMtSync *p = &mt->btSync; @@ -864,15 +864,15 @@ SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddB if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) return SZ_ERROR_MEM; - RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)); - RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)); + RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)) + RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)) return SZ_OK; } SRes MatchFinderMt_InitMt(CMatchFinderMt *p) { - RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)); + RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)) return MtSync_Init(&p->btSync, kMtBtNumBlocks); } @@ -941,7 +941,7 @@ void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) } -MY_NO_INLINE +Z7_NO_INLINE static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) { if (p->failure_LZ_BT) @@ -1163,7 +1163,7 @@ UInt32* MatchFinderMt_GetMatches_Bt4(CMatchFinderMt *p, UInt32 *d) */ -static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) +static UInt32 * MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) { UInt32 h2, h3, /* h4, */ c2, c3 /* , c4 */; UInt32 *hash = p->hash; @@ -1179,9 +1179,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) (hash + kFix3HashSize)[h3] = m; // (hash + kFix4HashSize)[h4] = m; - #define _USE_H2 - - #ifdef _USE_H2 + // #define BT5_USE_H2 + // #ifdef BT5_USE_H2 if (c2 >= matchMinPos && cur[(ptrdiff_t)c2 - (ptrdiff_t)m] == cur[0]) { d[1] = m - c2 - 1; @@ -1197,8 +1196,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) } d[0] = 3; d += 2; - - #ifdef _USE_H4 + + #ifdef BT5_USE_H4 if (c4 >= matchMinPos) if ( cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && @@ -1214,7 +1213,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) d[0] = 2; d += 2; } - #endif + // #endif if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0]) { @@ -1228,7 +1227,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) d += 2; } - #ifdef _USE_H4 + #ifdef BT5_USE_H4 if (c4 >= matchMinPos) if ( cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && @@ -1244,7 +1243,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) } -static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) +static UInt32 * MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) { const UInt32 *bt = p->btBufPos; const UInt32 len = *bt++; @@ -1268,7 +1267,7 @@ static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) -static UInt32* MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) +static UInt32 * MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) { const UInt32 *bt = p->btBufPos; UInt32 len = *bt++; @@ -1398,3 +1397,10 @@ void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder2 *vTable) break; } } + +#undef RINOK_THREAD +#undef PRF +#undef MF +#undef GetUi24hi_from32 +#undef LOCK_BUFFER +#undef UNLOCK_BUFFER diff --git a/C/LzFindMt.h b/C/LzFindMt.h index 660b7244..db5923ea 100644 --- a/C/LzFindMt.h +++ b/C/LzFindMt.h @@ -1,15 +1,15 @@ /* LzFindMt.h -- multithreaded Match finder for LZ algorithms -2021-07-12 : Igor Pavlov : Public domain */ +2023-03-05 : Igor Pavlov : Public domain */ -#ifndef __LZ_FIND_MT_H -#define __LZ_FIND_MT_H +#ifndef ZIP7_INC_LZ_FIND_MT_H +#define ZIP7_INC_LZ_FIND_MT_H #include "LzFind.h" #include "Threads.h" EXTERN_C_BEGIN -typedef struct _CMtSync +typedef struct { UInt32 numProcessedBlocks; CThread thread; @@ -39,7 +39,7 @@ typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distance typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); -typedef struct _CMatchFinderMt +typedef struct { /* LZ */ const Byte *pointerToCurPos; diff --git a/C/LzFindOpt.c b/C/LzFindOpt.c index 8ff006e0..85bdc136 100644 --- a/C/LzFindOpt.c +++ b/C/LzFindOpt.c @@ -1,5 +1,5 @@ /* LzFindOpt.c -- multithreaded Match finder for LZ algorithms -2021-07-13 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -41,8 +41,8 @@ UInt64 g_NumIters_Bytes; // #define CYC_TO_POS_OFFSET 1 // for debug /* -MY_NO_INLINE -UInt32 * MY_FAST_CALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, +Z7_NO_INLINE +UInt32 * Z7_FASTCALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, UInt32 *posRes) { do @@ -214,13 +214,13 @@ else to eliminate "movsx" BUG in old MSVC x64 compiler. */ -UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, +UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 *posRes); -MY_NO_INLINE -UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, +Z7_NO_INLINE +UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 *posRes) @@ -404,7 +404,7 @@ else /* typedef UInt32 uint32plus; // size_t -UInt32 * MY_FAST_CALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, +UInt32 * Z7_FASTCALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, UInt32 _cutValue, UInt32 *d, uint32plus _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 *posRes) diff --git a/C/LzHash.h b/C/LzHash.h index 77b898cf..2b6290b6 100644 --- a/C/LzHash.h +++ b/C/LzHash.h @@ -1,8 +1,8 @@ -/* LzHash.h -- HASH functions for LZ algorithms -2019-10-30 : Igor Pavlov : Public domain */ +/* LzHash.h -- HASH constants for LZ algorithms +2023-03-05 : Igor Pavlov : Public domain */ -#ifndef __LZ_HASH_H -#define __LZ_HASH_H +#ifndef ZIP7_INC_LZ_HASH_H +#define ZIP7_INC_LZ_HASH_H /* (kHash2Size >= (1 << 8)) : Required diff --git a/C/Lzma2Dec.c b/C/Lzma2Dec.c index ac970a84..388cbc71 100644 --- a/C/Lzma2Dec.c +++ b/C/Lzma2Dec.c @@ -1,5 +1,5 @@ /* Lzma2Dec.c -- LZMA2 Decoder -2021-02-09 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ /* #define SHOW_DEBUG_INFO */ @@ -71,14 +71,14 @@ static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props) SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) { Byte props[LZMA_PROPS_SIZE]; - RINOK(Lzma2Dec_GetOldProps(prop, props)); + RINOK(Lzma2Dec_GetOldProps(prop, props)) return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc); } SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) { Byte props[LZMA_PROPS_SIZE]; - RINOK(Lzma2Dec_GetOldProps(prop, props)); + RINOK(Lzma2Dec_GetOldProps(prop, props)) return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc); } @@ -474,8 +474,8 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, SizeT outSize = *destLen, inSize = *srcLen; *destLen = *srcLen = 0; *status = LZMA_STATUS_NOT_SPECIFIED; - Lzma2Dec_Construct(&p); - RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)); + Lzma2Dec_CONSTRUCT(&p) + RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)) p.decoder.dic = dest; p.decoder.dicBufSize = outSize; Lzma2Dec_Init(&p); @@ -487,3 +487,5 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, Lzma2Dec_FreeProbs(&p, alloc); return res; } + +#undef PRF diff --git a/C/Lzma2Dec.h b/C/Lzma2Dec.h index b8ddeac8..1f5233a7 100644 --- a/C/Lzma2Dec.h +++ b/C/Lzma2Dec.h @@ -1,8 +1,8 @@ /* Lzma2Dec.h -- LZMA2 Decoder -2018-02-19 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ -#ifndef __LZMA2_DEC_H -#define __LZMA2_DEC_H +#ifndef ZIP7_INC_LZMA2_DEC_H +#define ZIP7_INC_LZMA2_DEC_H #include "LzmaDec.h" @@ -22,9 +22,10 @@ typedef struct CLzmaDec decoder; } CLzma2Dec; -#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder) -#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) -#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) +#define Lzma2Dec_CONSTRUCT(p) LzmaDec_CONSTRUCT(&(p)->decoder) +#define Lzma2Dec_Construct(p) Lzma2Dec_CONSTRUCT(p) +#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) +#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); @@ -90,7 +91,7 @@ Lzma2Dec_GetUnpackExtra() returns the value that shows at current input positon. */ -#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0); +#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0) /* ---------- One Call Interface ---------- */ diff --git a/C/Lzma2DecMt.c b/C/Lzma2DecMt.c index 9f1dc52b..4bc4ddeb 100644 --- a/C/Lzma2DecMt.c +++ b/C/Lzma2DecMt.c @@ -1,44 +1,44 @@ /* Lzma2DecMt.c -- LZMA2 Decoder Multi-thread -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ #include "Precomp.h" // #define SHOW_DEBUG_INFO - -// #define _7ZIP_ST +// #define Z7_ST #ifdef SHOW_DEBUG_INFO #include #endif -#ifndef _7ZIP_ST -#ifdef SHOW_DEBUG_INFO -#define PRF(x) x -#else -#define PRF(x) -#endif -#define PRF_STR(s) PRF(printf("\n" s "\n")) -#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2)) -#endif - #include "Alloc.h" #include "Lzma2Dec.h" #include "Lzma2DecMt.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "MtDec.h" #define LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT (1 << 28) #endif +#ifndef Z7_ST +#ifdef SHOW_DEBUG_INFO +#define PRF(x) x +#else +#define PRF(x) +#endif +#define PRF_STR(s) PRF(printf("\n" s "\n");) +#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2);) +#endif + + void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) { p->inBufSize_ST = 1 << 20; p->outStep_ST = 1 << 20; - #ifndef _7ZIP_ST + #ifndef Z7_ST p->numThreads = 1; p->inBufSize_MT = 1 << 18; p->outBlockMax = LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT; @@ -48,7 +48,7 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) -#ifndef _7ZIP_ST +#ifndef Z7_ST /* ---------- CLzma2DecMtThread ---------- */ @@ -81,7 +81,7 @@ typedef struct /* ---------- CLzma2DecMt ---------- */ -typedef struct +struct CLzma2DecMt { // ISzAllocPtr alloc; ISzAllocPtr allocMid; @@ -90,9 +90,9 @@ typedef struct CLzma2DecMtProps props; Byte prop; - ISeqInStream *inStream; - ISeqOutStream *outStream; - ICompressProgress *progress; + ISeqInStreamPtr inStream; + ISeqOutStreamPtr outStream; + ICompressProgressPtr progress; BoolInt finishMode; BoolInt outSize_Defined; @@ -111,14 +111,13 @@ typedef struct size_t inPos; size_t inLim; - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt64 outProcessed_Parse; BoolInt mtc_WasConstructed; CMtDec mtc; - CLzma2DecMtThread coders[MTDEC__THREADS_MAX]; + CLzma2DecMtThread coders[MTDEC_THREADS_MAX]; #endif - -} CLzma2DecMt; +}; @@ -142,11 +141,11 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) // Lzma2DecMtProps_Init(&p->props); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtc_WasConstructed = 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 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) } #endif - return p; + return (CLzma2DecMtHandle)(void *)p; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static void Lzma2DecMt_FreeOutBufs(CLzma2DecMt *p) { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CLzma2DecMtThread *t = &p->coders[i]; if (t->outBuf) @@ -196,13 +195,15 @@ static void Lzma2DecMt_FreeSt(CLzma2DecMt *p) } -void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) +// #define GET_CLzma2DecMt_p CLzma2DecMt *p = (CLzma2DecMt *)(void *)pp; + +void Lzma2DecMt_Destroy(CLzma2DecMtHandle p) { - CLzma2DecMt *p = (CLzma2DecMt *)pp; + // GET_CLzma2DecMt_p Lzma2DecMt_FreeSt(p); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtc_WasConstructed) { @@ -211,7 +212,7 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) } { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CLzma2DecMtThread *t = &p->coders[i]; if (t->dec_created) @@ -226,19 +227,19 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) #endif - ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); + ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); } -#ifndef _7ZIP_ST +#ifndef Z7_ST static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) { CLzma2DecMt *me = (CLzma2DecMt *)obj; CLzma2DecMtThread *t = &me->coders[coderIndex]; - PRF_STR_INT_2("Parse", coderIndex, cc->srcSize); + PRF_STR_INT_2("Parse", coderIndex, cc->srcSize) cc->state = MTDEC_PARSE_CONTINUE; @@ -246,7 +247,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa { if (!t->dec_created) { - Lzma2Dec_Construct(&t->dec); + Lzma2Dec_CONSTRUCT(&t->dec) t->dec_created = True; AlignOffsetAlloc_CreateVTable(&t->alloc); { @@ -297,7 +298,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa // that must be finished at position <= outBlockMax. { - const SizeT srcOrig = cc->srcSize; + const size_t srcOrig = cc->srcSize; SizeT srcSize_Point = 0; SizeT dicPos_Point = 0; @@ -306,10 +307,10 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa for (;;) { - SizeT srcCur = srcOrig - cc->srcSize; + SizeT srcCur = (SizeT)(srcOrig - cc->srcSize); status = Lzma2Dec_Parse(&t->dec, - limit - t->dec.decoder.dicPos, + (SizeT)limit - t->dec.decoder.dicPos, cc->src + cc->srcSize, &srcCur, checkFinishBlock); @@ -333,7 +334,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa if (t->dec.decoder.dicPos >= (1 << 14)) break; dicPos_Point = t->dec.decoder.dicPos; - srcSize_Point = cc->srcSize; + srcSize_Point = (SizeT)cc->srcSize; continue; } @@ -391,7 +392,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa if (unpackRem != 0) { /* we also reserve space for max possible number of output bytes of current LZMA chunk */ - SizeT rem = limit - dicPos; + size_t rem = limit - dicPos; if (rem > unpackRem) rem = unpackRem; dicPos += rem; @@ -444,7 +445,7 @@ static SRes Lzma2DecMt_MtCallback_PreCode(void *pp, unsigned coderIndex) } t->dec.decoder.dic = dest; - t->dec.decoder.dicBufSize = t->outPreSize; + t->dec.decoder.dicBufSize = (SizeT)t->outPreSize; t->needInit = True; @@ -462,7 +463,7 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, UNUSED_VAR(srcFinished) - PRF_STR_INT_2("Code", coderIndex, srcSize); + PRF_STR_INT_2("Code", coderIndex, srcSize) *inCodePos = t->inCodeSize; *outCodePos = 0; @@ -476,13 +477,13 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex, { ELzmaStatus status; - size_t srcProcessed = srcSize; + SizeT srcProcessed = (SizeT)srcSize; BoolInt blockWasFinished = ((int)t->parseStatus == LZMA_STATUS_FINISHED_WITH_MARK || t->parseStatus == LZMA2_PARSE_STATUS_NEW_BLOCK); SRes res = Lzma2Dec_DecodeToDic(&t->dec, - t->outPreSize, + (SizeT)t->outPreSize, src, &srcProcessed, blockWasFinished ? LZMA_FINISH_END : LZMA_FINISH_ANY, &status); @@ -540,7 +541,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, UNUSED_VAR(srcSize) UNUSED_VAR(isCross) - PRF_STR_INT_2("Write", coderIndex, srcSize); + PRF_STR_INT_2("Write", coderIndex, srcSize) *needContinue = False; *canRecode = True; @@ -588,7 +589,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex, *needContinue = needContinue2; return SZ_OK; } - RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)); + RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)) } } @@ -611,11 +612,11 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p) { if (!p->dec_created) { - Lzma2Dec_Construct(&p->dec); + Lzma2Dec_CONSTRUCT(&p->dec) p->dec_created = 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_Prepare_ST(CLzma2DecMt *p) static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p - #ifndef _7ZIP_ST + #ifndef Z7_ST , BoolInt tMode #endif ) @@ -646,7 +647,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p CLzma2Dec *dec; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { Lzma2DecMt_FreeOutBufs(p); @@ -654,7 +655,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p } #endif - RINOK(Lzma2Dec_Prepare_ST(p)); + RINOK(Lzma2Dec_Prepare_ST(p)) dec = &p->dec; @@ -681,7 +682,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p if (inPos == inLim) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { inData = MtDec_Read(&p->mtc, &inLim); @@ -710,7 +711,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p { SizeT next = dec->decoder.dicBufSize; if (next - wrPos > p->props.outStep_ST) - next = wrPos + p->props.outStep_ST; + next = wrPos + (SizeT)p->props.outStep_ST; size = next - dicPos; } @@ -726,7 +727,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p } } - inProcessed = inLim - inPos; + inProcessed = (SizeT)(inLim - inPos); res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status); @@ -755,7 +756,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p dec->decoder.dicPos = 0; wrPos = dec->decoder.dicPos; - RINOK(res2); + RINOK(res2) if (needStop) { @@ -788,7 +789,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p UInt64 outDelta = p->outProcessed - outPrev; if (inDelta >= (1 << 22) || outDelta >= (1 << 22)) { - RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)); + RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)) inPrev = p->inProcessed; outPrev = p->outProcessed; } @@ -798,20 +799,20 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p -SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, +SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, Byte prop, const CLzma2DecMtProps *props, - ISeqOutStream *outStream, const UInt64 *outDataSize, int finishMode, + ISeqOutStreamPtr outStream, const UInt64 *outDataSize, int finishMode, // Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, // const Byte *inData, size_t inDataSize, UInt64 *inProcessed, // UInt64 *outProcessed, int *isMT, - ICompressProgress *progress) + ICompressProgressPtr progress) { - CLzma2DecMt *p = (CLzma2DecMt *)pp; - #ifndef _7ZIP_ST + // GET_CLzma2DecMt_p + #ifndef Z7_ST BoolInt tMode; #endif @@ -845,7 +846,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, *isMT = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST tMode = False; @@ -939,7 +940,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, p->readWasFinished = p->mtc.readWasFinished; p->inProcessed = p->mtc.inProcessed; - PRF_STR("----- decoding ST -----"); + PRF_STR("----- decoding ST -----") } } @@ -950,7 +951,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, { SRes res = Lzma2Dec_Decode_ST(p - #ifndef _7ZIP_ST + #ifndef Z7_ST , tMode #endif ); @@ -967,7 +968,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, res = p->readRes; /* - #ifndef _7ZIP_ST + #ifndef Z7_ST if (res == SZ_OK && tMode && p->mtc.parseRes != SZ_OK) res = p->mtc.parseRes; #endif @@ -980,13 +981,13 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ -SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, +SRes Lzma2DecMt_Init(CLzma2DecMtHandle p, Byte prop, const CLzma2DecMtProps *props, const UInt64 *outDataSize, int finishMode, - ISeqInStream *inStream) + ISeqInStreamPtr inStream) { - CLzma2DecMt *p = (CLzma2DecMt *)pp; + // GET_CLzma2DecMt_p if (prop > 40) return SZ_ERROR_UNSUPPORTED; @@ -1015,11 +1016,11 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, } -SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, +SRes Lzma2DecMt_Read(CLzma2DecMtHandle p, Byte *data, size_t *outSize, UInt64 *inStreamProcessed) { - CLzma2DecMt *p = (CLzma2DecMt *)pp; + // GET_CLzma2DecMt_p ELzmaFinishMode finishMode; SRes readRes; size_t size = *outSize; @@ -1055,8 +1056,8 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, readRes = ISeqInStream_Read(p->inStream, p->inBuf, &p->inLim); } - inCur = p->inLim - p->inPos; - outCur = size; + inCur = (SizeT)(p->inLim - p->inPos); + outCur = (SizeT)size; res = Lzma2Dec_DecodeToBuf(&p->dec, data, &outCur, p->inBuf + p->inPos, &inCur, finishMode, &status); @@ -1088,3 +1089,7 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, return readRes; } } + +#undef PRF +#undef PRF_STR +#undef PRF_STR_INT_2 diff --git a/C/Lzma2DecMt.h b/C/Lzma2DecMt.h index 7791c310..93a5cd59 100644 --- a/C/Lzma2DecMt.h +++ b/C/Lzma2DecMt.h @@ -1,8 +1,8 @@ /* Lzma2DecMt.h -- LZMA2 Decoder Multi-thread -2018-02-17 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __LZMA2_DEC_MT_H -#define __LZMA2_DEC_MT_H +#ifndef ZIP7_INC_LZMA2_DEC_MT_H +#define ZIP7_INC_LZMA2_DEC_MT_H #include "7zTypes.h" @@ -13,7 +13,7 @@ typedef struct size_t inBufSize_ST; size_t outStep_ST; - #ifndef _7ZIP_ST + #ifndef Z7_ST unsigned numThreads; size_t inBufSize_MT; size_t outBlockMax; @@ -38,7 +38,9 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p); SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) */ -typedef void * CLzma2DecMtHandle; +typedef struct CLzma2DecMt CLzma2DecMt; +typedef CLzma2DecMt * CLzma2DecMtHandle; +// Z7_DECLARE_HANDLE(CLzma2DecMtHandle) CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid); void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); @@ -46,11 +48,11 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, Byte prop, const CLzma2DecMtProps *props, - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, const UInt64 *outDataSize, // NULL means undefined int finishMode, // 0 - partial unpacking is allowed, 1 - if lzma2 stream must be finished // Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, // const Byte *inData, size_t inDataSize, // out variables: @@ -58,7 +60,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, int *isMT, /* out: (*isMT == 0), if single thread decoding was used */ // UInt64 *outProcessed, - ICompressProgress *progress); + ICompressProgressPtr progress); /* ---------- Read from CLzma2DecMtHandle Interface ---------- */ @@ -67,7 +69,7 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, Byte prop, const CLzma2DecMtProps *props, const UInt64 *outDataSize, int finishMode, - ISeqInStream *inStream); + ISeqInStreamPtr inStream); SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, Byte *data, size_t *outSize, diff --git a/C/Lzma2Enc.c b/C/Lzma2Enc.c index e61a5dfe..703e146b 100644 --- a/C/Lzma2Enc.c +++ b/C/Lzma2Enc.c @@ -1,18 +1,18 @@ /* Lzma2Enc.c -- LZMA2 Encoder -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ #include "Precomp.h" #include -/* #define _7ZIP_ST */ +/* #define Z7_ST */ #include "Lzma2Enc.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "MtCoder.h" #else -#define MTCODER__THREADS_MAX 1 +#define MTCODER_THREADS_MAX 1 #endif #define LZMA2_CONTROL_LZMA (1 << 7) @@ -40,7 +40,7 @@ typedef struct { ISeqInStream vt; - ISeqInStream *realStream; + ISeqInStreamPtr realStream; UInt64 limit; UInt64 processed; int finished; @@ -53,15 +53,15 @@ static void LimitedSeqInStream_Init(CLimitedSeqInStream *p) p->finished = 0; } -static SRes LimitedSeqInStream_Read(const ISeqInStream *pp, void *data, size_t *size) +static SRes LimitedSeqInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) { - CLimitedSeqInStream *p = CONTAINER_FROM_VTBL(pp, CLimitedSeqInStream, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLimitedSeqInStream) size_t size2 = *size; SRes res = SZ_OK; if (p->limit != (UInt64)(Int64)-1) { - UInt64 rem = p->limit - p->processed; + const UInt64 rem = p->limit - p->processed; if (size2 > rem) size2 = (size_t)rem; } @@ -95,8 +95,8 @@ static SRes Lzma2EncInt_InitStream(CLzma2EncInt *p, const CLzma2EncProps *props) { SizeT propsSize = LZMA_PROPS_SIZE; Byte propsEncoded[LZMA_PROPS_SIZE]; - RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)); - RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)); + RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)) + RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)) p->propsByte = propsEncoded[0]; p->propsAreSet = True; } @@ -111,23 +111,23 @@ static void Lzma2EncInt_InitBlock(CLzma2EncInt *p) } -SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, +SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); -SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, +SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); -SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, +SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit, Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); -const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); -void LzmaEnc_Finish(CLzmaEncHandle pp); -void LzmaEnc_SaveState(CLzmaEncHandle pp); -void LzmaEnc_RestoreState(CLzmaEncHandle pp); +const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p); +void LzmaEnc_Finish(CLzmaEncHandle p); +void LzmaEnc_SaveState(CLzmaEncHandle p); +void LzmaEnc_RestoreState(CLzmaEncHandle p); /* -UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp); +UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p); */ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, - size_t *packSizeRes, ISeqOutStream *outStream) + size_t *packSizeRes, ISeqOutStreamPtr outStream) { size_t packSizeLimit = *packSizeRes; size_t packSize = packSizeLimit; @@ -167,7 +167,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, while (unpackSize > 0) { - UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; + const UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; if (packSizeLimit - destPos < u + 3) return SZ_ERROR_OUTPUT_EOF; outBuf[destPos++] = (Byte)(p->srcPos == 0 ? LZMA2_CONTROL_COPY_RESET_DIC : LZMA2_CONTROL_COPY_NO_RESET); @@ -196,9 +196,9 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, { size_t destPos = 0; - UInt32 u = unpackSize - 1; - UInt32 pm = (UInt32)(packSize - 1); - unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); + const UInt32 u = unpackSize - 1; + const UInt32 pm = (UInt32)(packSize - 1); + const unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); PRF(printf(" ")); @@ -231,7 +231,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, void Lzma2EncProps_Init(CLzma2EncProps *p) { LzmaEncProps_Init(&p->lzmaProps); - p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO; + p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO; p->numBlockThreads_Reduced = -1; p->numBlockThreads_Max = -1; p->numTotalThreads = -1; @@ -251,8 +251,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) t2 = p->numBlockThreads_Max; t3 = p->numTotalThreads; - if (t2 > MTCODER__THREADS_MAX) - t2 = MTCODER__THREADS_MAX; + if (t2 > MTCODER_THREADS_MAX) + t2 = MTCODER_THREADS_MAX; if (t3 <= 0) { @@ -268,8 +268,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) t1 = 1; t2 = t3; } - if (t2 > MTCODER__THREADS_MAX) - t2 = MTCODER__THREADS_MAX; + if (t2 > MTCODER_THREADS_MAX) + t2 = MTCODER_THREADS_MAX; } else if (t1 <= 0) { @@ -286,8 +286,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) fileSize = p->lzmaProps.reduceSize; - if ( p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID - && p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO + if ( p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID + && p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO && (p->blockSize < fileSize || fileSize == (UInt64)(Int64)-1)) p->lzmaProps.reduceSize = p->blockSize; @@ -297,19 +297,19 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) t1 = p->lzmaProps.numThreads; - if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) + if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) { t2r = t2 = 1; t3 = t1; } - else if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO && t2 <= 1) + else if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO && t2 <= 1) { /* if there is no block multi-threading, we use SOLID block */ - p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; + p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; } else { - if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) + if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) { const UInt32 kMinSize = (UInt32)1 << 20; const UInt32 kMaxSize = (UInt32)1 << 28; @@ -344,7 +344,7 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p) } -static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) +static SRes Progress(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize) { return (p && ICompressProgress_Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK; } @@ -352,7 +352,7 @@ static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) /* ---------- Lzma2 ---------- */ -typedef struct +struct CLzma2Enc { Byte propEncoded; CLzma2EncProps props; @@ -363,23 +363,22 @@ typedef struct ISzAllocPtr alloc; ISzAllocPtr allocBig; - CLzma2EncInt coders[MTCODER__THREADS_MAX]; + CLzma2EncInt coders[MTCODER_THREADS_MAX]; - #ifndef _7ZIP_ST + #ifndef Z7_ST - ISeqOutStream *outStream; + ISeqOutStreamPtr outStream; Byte *outBuf; size_t outBuf_Rem; /* remainder in outBuf */ size_t outBufSize; /* size of allocated outBufs[i] */ - size_t outBufsDataSizes[MTCODER__BLOCKS_MAX]; + size_t outBufsDataSizes[MTCODER_BLOCKS_MAX]; BoolInt mtCoder_WasConstructed; CMtCoder mtCoder; - Byte *outBufs[MTCODER__BLOCKS_MAX]; + Byte *outBufs[MTCODER_BLOCKS_MAX]; #endif - -} CLzma2Enc; +}; @@ -396,30 +395,30 @@ CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) p->allocBig = allocBig; { unsigned i; - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) p->coders[i].enc = NULL; } - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtCoder_WasConstructed = 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 @@ static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) #endif +// #define GET_CLzma2Enc_p CLzma2Enc *p = (CLzma2Enc *)(void *)p; -void Lzma2Enc_Destroy(CLzma2EncHandle pp) +void Lzma2Enc_Destroy(CLzma2EncHandle p) { - CLzma2Enc *p = (CLzma2Enc *)pp; + // GET_CLzma2Enc_p unsigned i; - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) { CLzma2EncInt *t = &p->coders[i]; if (t->enc) @@ -446,7 +446,7 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtCoder_WasConstructed) { MtCoder_Destruct(&p->mtCoder); @@ -458,13 +458,13 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp) ISzAlloc_Free(p->alloc, p->tempBufLzma); p->tempBufLzma = NULL; - ISzAlloc_Free(p->alloc, pp); + ISzAlloc_Free(p->alloc, p); } -SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) +SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props) { - CLzma2Enc *p = (CLzma2Enc *)pp; + // GET_CLzma2Enc_p CLzmaEncProps lzmaProps = props->lzmaProps; LzmaEncProps_Normalize(&lzmaProps); if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX) @@ -475,16 +475,16 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) } -void Lzma2Enc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) +void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize) { - CLzma2Enc *p = (CLzma2Enc *)pp; + // GET_CLzma2Enc_p p->expectedDataSize = expectedDataSiize; } -Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) +Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p) { - CLzma2Enc *p = (CLzma2Enc *)pp; + // GET_CLzma2Enc_p unsigned i; UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps); for (i = 0; i < 40; i++) @@ -497,12 +497,12 @@ Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) static SRes Lzma2Enc_EncodeMt1( CLzma2Enc *me, CLzma2EncInt *p, - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, const Byte *inData, size_t inDataSize, int finished, - ICompressProgress *progress) + ICompressProgressPtr progress) { UInt64 unpackTotal = 0; UInt64 packTotal = 0; @@ -540,12 +540,12 @@ static SRes Lzma2Enc_EncodeMt1( } } - RINOK(Lzma2EncInt_InitStream(p, &me->props)); + RINOK(Lzma2EncInt_InitStream(p, &me->props)) for (;;) { SRes res = SZ_OK; - size_t inSizeCur = 0; + SizeT inSizeCur = 0; Lzma2EncInt_InitBlock(p); @@ -559,7 +559,7 @@ static SRes Lzma2Enc_EncodeMt1( if (me->expectedDataSize != (UInt64)(Int64)-1 && me->expectedDataSize >= unpackTotal) expected = me->expectedDataSize - unpackTotal; - if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID + if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID && expected > me->props.blockSize) expected = (size_t)me->props.blockSize; @@ -569,14 +569,14 @@ static SRes Lzma2Enc_EncodeMt1( &limitedInStream.vt, LZMA2_KEEP_WINDOW_SIZE, me->alloc, - me->allocBig)); + me->allocBig)) } else { - inSizeCur = inDataSize - (size_t)unpackTotal; - if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID + inSizeCur = (SizeT)(inDataSize - (size_t)unpackTotal); + if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID && inSizeCur > me->props.blockSize) - inSizeCur = (size_t)me->props.blockSize; + inSizeCur = (SizeT)(size_t)me->props.blockSize; // LzmaEnc_SetDataSize(p->enc, inSizeCur); @@ -584,7 +584,7 @@ static SRes Lzma2Enc_EncodeMt1( inData + (size_t)unpackTotal, inSizeCur, LZMA2_KEEP_WINDOW_SIZE, me->alloc, - me->allocBig)); + me->allocBig)) } for (;;) @@ -621,7 +621,7 @@ static SRes Lzma2Enc_EncodeMt1( unpackTotal += p->srcPos; - RINOK(res); + RINOK(res) if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur)) return SZ_ERROR_FAIL; @@ -652,12 +652,12 @@ static SRes Lzma2Enc_EncodeMt1( -#ifndef _7ZIP_ST +#ifndef Z7_ST -static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, +static SRes Lzma2Enc_MtCallback_Code(void *p, unsigned coderIndex, unsigned outBufIndex, const Byte *src, size_t srcSize, int finished) { - CLzma2Enc *me = (CLzma2Enc *)pp; + CLzma2Enc *me = (CLzma2Enc *)p; size_t destSize = me->outBufSize; SRes res; CMtProgressThunk progressThunk; @@ -692,9 +692,9 @@ static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned out } -static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) +static SRes Lzma2Enc_MtCallback_Write(void *p, unsigned outBufIndex) { - CLzma2Enc *me = (CLzma2Enc *)pp; + CLzma2Enc *me = (CLzma2Enc *)p; size_t size = me->outBufsDataSizes[outBufIndex]; const Byte *data = me->outBufs[outBufIndex]; @@ -713,14 +713,14 @@ static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) -SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, - ISeqOutStream *outStream, +SRes Lzma2Enc_Encode2(CLzma2EncHandle p, + ISeqOutStreamPtr outStream, Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, const Byte *inData, size_t inDataSize, - ICompressProgress *progress) + ICompressProgressPtr progress) { - CLzma2Enc *p = (CLzma2Enc *)pp; + // GET_CLzma2Enc_p if (inStream && inData) return SZ_ERROR_PARAM; @@ -730,11 +730,11 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, { unsigned i; - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) p->coders[i].propsAreSet = False; } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->props.numBlockThreads_Reduced > 1) { @@ -772,7 +772,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, return SZ_ERROR_PARAM; /* SZ_ERROR_MEM */ { - size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; + const size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; if (destBlockSize < p->mtCoder.blockSize) return SZ_ERROR_PARAM; if (p->outBufSize != destBlockSize) @@ -784,7 +784,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, p->mtCoder.expectedDataSize = p->expectedDataSize; { - SRes res = MtCoder_Code(&p->mtCoder); + const SRes res = MtCoder_Code(&p->mtCoder); if (!outStream) *outBufSize = (size_t)(p->outBuf - outBuf); return res; @@ -801,3 +801,5 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, True, /* finished */ progress); } + +#undef PRF diff --git a/C/Lzma2Enc.h b/C/Lzma2Enc.h index 6a6110ff..cb25275c 100644 --- a/C/Lzma2Enc.h +++ b/C/Lzma2Enc.h @@ -1,15 +1,15 @@ /* Lzma2Enc.h -- LZMA2 Encoder -2017-07-27 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __LZMA2_ENC_H -#define __LZMA2_ENC_H +#ifndef ZIP7_INC_LZMA2_ENC_H +#define ZIP7_INC_LZMA2_ENC_H #include "LzmaEnc.h" EXTERN_C_BEGIN -#define LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 0 -#define LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ((UInt64)(Int64)-1) +#define LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO 0 +#define LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ((UInt64)(Int64)-1) typedef struct { @@ -36,7 +36,9 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p); SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) */ -typedef void * CLzma2EncHandle; +typedef struct CLzma2Enc CLzma2Enc; +typedef CLzma2Enc * CLzma2EncHandle; +// Z7_DECLARE_HANDLE(CLzma2EncHandle) CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); void Lzma2Enc_Destroy(CLzma2EncHandle p); @@ -44,11 +46,11 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props); void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize); Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p); SRes Lzma2Enc_Encode2(CLzma2EncHandle p, - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, const Byte *inData, size_t inDataSize, - ICompressProgress *progress); + ICompressProgressPtr progress); EXTERN_C_END diff --git a/C/Lzma86.h b/C/Lzma86.h index bebed5cb..e7707e2c 100644 --- a/C/Lzma86.h +++ b/C/Lzma86.h @@ -1,8 +1,8 @@ /* Lzma86.h -- LZMA + x86 (BCJ) Filter -2013-01-18 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ -#ifndef __LZMA86_H -#define __LZMA86_H +#ifndef ZIP7_INC_LZMA86_H +#define ZIP7_INC_LZMA86_H #include "7zTypes.h" diff --git a/C/Lzma86Dec.c b/C/Lzma86Dec.c index 21031745..f094d4c3 100644 --- a/C/Lzma86Dec.c +++ b/C/Lzma86Dec.c @@ -1,5 +1,5 @@ /* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder -2016-05-16 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -46,9 +46,8 @@ SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen) return res; if (useFilter == 1) { - UInt32 x86State; - x86_Convert_Init(x86State); - x86_Convert(dest, *destLen, 0, &x86State, 0); + UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; + z7_BranchConvSt_X86_Dec(dest, *destLen, 0, &x86State); } return SZ_OK; } diff --git a/C/Lzma86Enc.c b/C/Lzma86Enc.c index 14fcd65c..0cdde1c9 100644 --- a/C/Lzma86Enc.c +++ b/C/Lzma86Enc.c @@ -1,5 +1,5 @@ /* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder -2018-07-04 : Igor Pavlov : Public domain */ +2023-03-03 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -46,9 +46,8 @@ int Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen, memcpy(filteredStream, src, srcLen); } { - UInt32 x86State; - x86_Convert_Init(x86State); - x86_Convert(filteredStream, srcLen, 0, &x86State, 1); + UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; + z7_BranchConvSt_X86_Enc(filteredStream, srcLen, 0, &x86State); } } diff --git a/C/LzmaDec.c b/C/LzmaDec.c index d6742e5a..69bb8bba 100644 --- a/C/LzmaDec.c +++ b/C/LzmaDec.c @@ -1,5 +1,5 @@ /* LzmaDec.c -- LZMA Decoder -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-07 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -8,15 +8,15 @@ /* #include "CpuArch.h" */ #include "LzmaDec.h" -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) +// #define kNumTopBits 24 +#define kTopValue ((UInt32)1 << 24) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) #define RC_INIT_SIZE 5 -#ifndef _LZMA_DEC_OPT +#ifndef Z7_LZMA_DEC_OPT #define kNumMoveBits 5 #define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } @@ -25,14 +25,14 @@ #define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); #define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); #define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ - { UPDATE_0(p); i = (i + i); A0; } else \ - { UPDATE_1(p); i = (i + i) + 1; A1; } + { UPDATE_0(p) i = (i + i); A0; } else \ + { UPDATE_1(p) i = (i + i) + 1; A1; } #define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } #define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ - { UPDATE_0(p + i); A0; } else \ - { UPDATE_1(p + i); A1; } + { UPDATE_0(p + i) A0; } else \ + { UPDATE_1(p + i) A1; } #define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) #define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) #define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) @@ -40,19 +40,19 @@ #define TREE_DECODE(probs, limit, i) \ { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } -/* #define _LZMA_SIZE_OPT */ +/* #define Z7_LZMA_SIZE_OPT */ -#ifdef _LZMA_SIZE_OPT +#ifdef Z7_LZMA_SIZE_OPT #define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) #else #define TREE_6_DECODE(probs, i) \ { i = 1; \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ + TREE_GET_BIT(probs, i) \ i -= 0x40; } #endif @@ -64,25 +64,25 @@ probLit = prob + (offs + bit + symbol); \ GET_BIT2(probLit, symbol, offs ^= bit; , ;) -#endif // _LZMA_DEC_OPT +#endif // Z7_LZMA_DEC_OPT #define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); } -#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) #define UPDATE_0_CHECK range = bound; #define UPDATE_1_CHECK range -= bound; code -= bound; #define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ - { UPDATE_0_CHECK; i = (i + i); A0; } else \ - { UPDATE_1_CHECK; i = (i + i) + 1; A1; } + { UPDATE_0_CHECK i = (i + i); A0; } else \ + { UPDATE_1_CHECK i = (i + i) + 1; A1; } #define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) #define TREE_DECODE_CHECK(probs, limit, i) \ { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } #define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ - { UPDATE_0_CHECK; i += m; m += m; } else \ - { UPDATE_1_CHECK; m += m; i += m; } + { UPDATE_0_CHECK i += m; m += m; } else \ + { UPDATE_1_CHECK m += m; i += m; } #define kNumPosBitsMax 4 @@ -224,14 +224,14 @@ LZMA_DECODE_REAL() */ -#ifdef _LZMA_DEC_OPT +#ifdef Z7_LZMA_DEC_OPT -int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); +int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); #else static -int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) { CLzmaProb *probs = GET_PROBS; unsigned state = (unsigned)p->state; @@ -263,7 +263,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit IF_BIT_0(prob) { unsigned symbol; - UPDATE_0(prob); + UPDATE_0(prob) prob = probs + Literal; if (processedPos != 0 || checkDicSize != 0) prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); @@ -273,7 +273,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit { state -= (state < 4) ? state : 3; symbol = 1; - #ifdef _LZMA_SIZE_OPT + #ifdef Z7_LZMA_SIZE_OPT do { NORMAL_LITER_DEC } while (symbol < 0x100); #else NORMAL_LITER_DEC @@ -292,7 +292,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit unsigned offs = 0x100; state -= (state < 10) ? 3 : 6; symbol = 1; - #ifdef _LZMA_SIZE_OPT + #ifdef Z7_LZMA_SIZE_OPT do { unsigned bit; @@ -321,25 +321,25 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit } { - UPDATE_1(prob); + UPDATE_1(prob) prob = probs + IsRep + state; IF_BIT_0(prob) { - UPDATE_0(prob); + UPDATE_0(prob) state += kNumStates; prob = probs + LenCoder; } else { - UPDATE_1(prob); + UPDATE_1(prob) prob = probs + IsRepG0 + state; IF_BIT_0(prob) { - UPDATE_0(prob); + UPDATE_0(prob) prob = probs + IsRep0Long + COMBINED_PS_STATE; IF_BIT_0(prob) { - UPDATE_0(prob); + UPDATE_0(prob) // that case was checked before with kBadRepCode // if (checkDicSize == 0 && processedPos == 0) { len = kMatchSpecLen_Error_Data + 1; break; } @@ -353,30 +353,30 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit state = state < kNumLitStates ? 9 : 11; continue; } - UPDATE_1(prob); + UPDATE_1(prob) } else { UInt32 distance; - UPDATE_1(prob); + UPDATE_1(prob) prob = probs + IsRepG1 + state; IF_BIT_0(prob) { - UPDATE_0(prob); + UPDATE_0(prob) distance = rep1; } else { - UPDATE_1(prob); + UPDATE_1(prob) prob = probs + IsRepG2 + state; IF_BIT_0(prob) { - UPDATE_0(prob); + UPDATE_0(prob) distance = rep2; } else { - UPDATE_1(prob); + UPDATE_1(prob) distance = rep3; rep3 = rep2; } @@ -389,37 +389,37 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit prob = probs + RepLenCoder; } - #ifdef _LZMA_SIZE_OPT + #ifdef Z7_LZMA_SIZE_OPT { unsigned lim, offset; CLzmaProb *probLen = prob + LenChoice; IF_BIT_0(probLen) { - UPDATE_0(probLen); + UPDATE_0(probLen) probLen = prob + LenLow + GET_LEN_STATE; offset = 0; lim = (1 << kLenNumLowBits); } else { - UPDATE_1(probLen); + UPDATE_1(probLen) probLen = prob + LenChoice2; IF_BIT_0(probLen) { - UPDATE_0(probLen); + UPDATE_0(probLen) probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); offset = kLenNumLowSymbols; lim = (1 << kLenNumLowBits); } else { - UPDATE_1(probLen); + UPDATE_1(probLen) probLen = prob + LenHigh; offset = kLenNumLowSymbols * 2; lim = (1 << kLenNumHighBits); } } - TREE_DECODE(probLen, lim, len); + TREE_DECODE(probLen, lim, len) len += offset; } #else @@ -427,32 +427,32 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit CLzmaProb *probLen = prob + LenChoice; IF_BIT_0(probLen) { - UPDATE_0(probLen); + UPDATE_0(probLen) probLen = prob + LenLow + GET_LEN_STATE; len = 1; - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) len -= 8; } else { - UPDATE_1(probLen); + UPDATE_1(probLen) probLen = prob + LenChoice2; IF_BIT_0(probLen) { - UPDATE_0(probLen); + UPDATE_0(probLen) probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); len = 1; - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) + TREE_GET_BIT(probLen, len) } else { - UPDATE_1(probLen); + UPDATE_1(probLen) probLen = prob + LenHigh; - TREE_DECODE(probLen, (1 << kLenNumHighBits), len); + TREE_DECODE(probLen, (1 << kLenNumHighBits), len) len += kLenNumLowSymbols * 2; } } @@ -464,7 +464,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit UInt32 distance; prob = probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_6_DECODE(prob, distance); + TREE_6_DECODE(prob, distance) if (distance >= kStartPosModelIndex) { unsigned posSlot = (unsigned)distance; @@ -479,7 +479,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit distance++; do { - REV_BIT_VAR(prob, distance, m); + REV_BIT_VAR(prob, distance, m) } while (--numDirectBits); distance -= m; @@ -514,10 +514,10 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit distance <<= kNumAlignBits; { unsigned i = 1; - REV_BIT_CONST(prob, i, 1); - REV_BIT_CONST(prob, i, 2); - REV_BIT_CONST(prob, i, 4); - REV_BIT_LAST (prob, i, 8); + REV_BIT_CONST(prob, i, 1) + REV_BIT_CONST(prob, i, 2) + REV_BIT_CONST(prob, i, 4) + REV_BIT_LAST (prob, i, 8) distance |= i; } if (distance == (UInt32)0xFFFFFFFF) @@ -592,7 +592,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit } while (dicPos < limit && buf < bufLimit); - NORMALIZE; + NORMALIZE p->buf = buf; p->range = range; @@ -613,7 +613,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit -static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) +static void Z7_FASTCALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) { unsigned len = (unsigned)p->remainLen; if (len == 0 /* || len >= kMatchSpecLenStart */) @@ -683,7 +683,7 @@ and we support the following state of (p->checkDicSize): (p->checkDicSize == p->prop.dicSize) */ -static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +static int Z7_FASTCALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) { if (p->checkDicSize == 0) { @@ -767,54 +767,54 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt else { unsigned len; - UPDATE_1_CHECK; + UPDATE_1_CHECK prob = probs + IsRep + state; IF_BIT_0_CHECK(prob) { - UPDATE_0_CHECK; + UPDATE_0_CHECK state = 0; prob = probs + LenCoder; res = DUMMY_MATCH; } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK res = DUMMY_REP; prob = probs + IsRepG0 + state; IF_BIT_0_CHECK(prob) { - UPDATE_0_CHECK; + UPDATE_0_CHECK prob = probs + IsRep0Long + COMBINED_PS_STATE; IF_BIT_0_CHECK(prob) { - UPDATE_0_CHECK; + UPDATE_0_CHECK break; } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK } } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK prob = probs + IsRepG1 + state; IF_BIT_0_CHECK(prob) { - UPDATE_0_CHECK; + UPDATE_0_CHECK } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK prob = probs + IsRepG2 + state; IF_BIT_0_CHECK(prob) { - UPDATE_0_CHECK; + UPDATE_0_CHECK } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK } } } @@ -826,31 +826,31 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt const CLzmaProb *probLen = prob + LenChoice; IF_BIT_0_CHECK(probLen) { - UPDATE_0_CHECK; + UPDATE_0_CHECK probLen = prob + LenLow + GET_LEN_STATE; offset = 0; limit = 1 << kLenNumLowBits; } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK probLen = prob + LenChoice2; IF_BIT_0_CHECK(probLen) { - UPDATE_0_CHECK; + UPDATE_0_CHECK probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); offset = kLenNumLowSymbols; limit = 1 << kLenNumLowBits; } else { - UPDATE_1_CHECK; + UPDATE_1_CHECK probLen = prob + LenHigh; offset = kLenNumLowSymbols * 2; limit = 1 << kLenNumHighBits; } } - TREE_DECODE_CHECK(probLen, limit, len); + TREE_DECODE_CHECK(probLen, limit, len) len += offset; } @@ -860,7 +860,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt prob = probs + PosSlot + ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot) if (posSlot >= kStartPosModelIndex) { unsigned numDirectBits = ((posSlot >> 1) - 1); @@ -888,7 +888,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt unsigned m = 1; do { - REV_BIT_CHECK(prob, i, m); + REV_BIT_CHECK(prob, i, m) } while (--numDirectBits); } @@ -897,7 +897,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt } break; } - NORMALIZE_CHECK; + NORMALIZE_CHECK *bufOut = buf; return res; @@ -943,7 +943,7 @@ When the decoder lookahead, and the lookahead symbol is not end_marker, we have */ -#define RETURN__NOT_FINISHED__FOR_FINISH \ +#define RETURN_NOT_FINISHED_FOR_FINISH \ *status = LZMA_STATUS_NOT_FINISHED; \ return SZ_ERROR_DATA; // for strict mode // return SZ_OK; // for relaxed mode @@ -1029,7 +1029,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr } if (p->remainLen != 0) { - RETURN__NOT_FINISHED__FOR_FINISH; + RETURN_NOT_FINISHED_FOR_FINISH } checkEndMarkNow = 1; } @@ -1072,7 +1072,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr for (i = 0; i < (unsigned)dummyProcessed; i++) p->tempBuf[i] = src[i]; // p->remainLen = kMatchSpecLen_Error_Data; - RETURN__NOT_FINISHED__FOR_FINISH; + RETURN_NOT_FINISHED_FOR_FINISH } bufLimit = src; @@ -1150,7 +1150,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize; p->tempBufSize = (unsigned)dummyProcessed; // p->remainLen = kMatchSpecLen_Error_Data; - RETURN__NOT_FINISHED__FOR_FINISH; + RETURN_NOT_FINISHED_FOR_FINISH } } @@ -1299,8 +1299,8 @@ static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAl SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) { CLzmaProps propNew; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); + RINOK(LzmaProps_Decode(&propNew, props, propsSize)) + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) p->prop = propNew; return SZ_OK; } @@ -1309,14 +1309,14 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll { CLzmaProps propNew; SizeT dicBufSize; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); + RINOK(LzmaProps_Decode(&propNew, props, propsSize)) + RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)) { UInt32 dictSize = propNew.dicSize; SizeT mask = ((UInt32)1 << 12) - 1; if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; - else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;; + else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1; dicBufSize = ((SizeT)dictSize + mask) & ~mask; if (dicBufSize < dictSize) dicBufSize = dictSize; @@ -1348,8 +1348,8 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, *status = LZMA_STATUS_NOT_SPECIFIED; if (inSize < RC_INIT_SIZE) return SZ_ERROR_INPUT_EOF; - LzmaDec_Construct(&p); - RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)); + LzmaDec_CONSTRUCT(&p) + RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)) p.dic = dest; p.dicBufSize = outSize; LzmaDec_Init(&p); diff --git a/C/LzmaDec.h b/C/LzmaDec.h index 6f129625..b0ce28fa 100644 --- a/C/LzmaDec.h +++ b/C/LzmaDec.h @@ -1,19 +1,19 @@ /* LzmaDec.h -- LZMA Decoder -2020-03-19 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __LZMA_DEC_H -#define __LZMA_DEC_H +#ifndef ZIP7_INC_LZMA_DEC_H +#define ZIP7_INC_LZMA_DEC_H #include "7zTypes.h" EXTERN_C_BEGIN -/* #define _LZMA_PROB32 */ -/* _LZMA_PROB32 can increase the speed on some CPUs, +/* #define Z7_LZMA_PROB32 */ +/* Z7_LZMA_PROB32 can increase the speed on some CPUs, but memory usage for CLzmaDec::probs will be doubled in that case */ typedef -#ifdef _LZMA_PROB32 +#ifdef Z7_LZMA_PROB32 UInt32 #else UInt16 @@ -25,7 +25,7 @@ typedef #define LZMA_PROPS_SIZE 5 -typedef struct _CLzmaProps +typedef struct { Byte lc; Byte lp; @@ -73,7 +73,8 @@ typedef struct Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; } CLzmaDec; -#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } +#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; } +#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p) void LzmaDec_Init(CLzmaDec *p); diff --git a/C/LzmaEnc.c b/C/LzmaEnc.c index c8b31a19..6d13cac8 100644 --- a/C/LzmaEnc.c +++ b/C/LzmaEnc.c @@ -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 @@ static unsigned g_STAT_OFFSET = 0; /* for good normalization speed we still reserve 256 MB before 4 GB range */ #define kLzmaMaxHistorySize ((UInt32)15 << 28) -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) +// #define kNumTopBits 24 +#define kTopValue ((UInt32)1 << 24) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) @@ -60,6 +60,7 @@ void LzmaEncProps_Init(CLzmaEncProps *p) p->dictSize = p->mc = 0; p->reduceSize = (UInt64)(Int64)-1; p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; + p->numHashOutBits = 0; p->writeEndMark = 0; p->affinity = 0; } @@ -99,7 +100,7 @@ void LzmaEncProps_Normalize(CLzmaEncProps *p) if (p->numThreads < 0) p->numThreads = - #ifndef _7ZIP_ST + #ifndef Z7_ST ((p->btMode && p->algo) ? 2 : 1); #else 1; @@ -293,7 +294,7 @@ typedef struct #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) typedef -#ifdef _LZMA_PROB32 +#ifdef Z7_LZMA_PROB32 UInt32 #else UInt16 @@ -350,7 +351,7 @@ typedef struct Byte *buf; Byte *bufLim; Byte *bufBase; - ISeqOutStream *outStream; + ISeqOutStreamPtr outStream; UInt64 processed; SRes res; } CRangeEnc; @@ -383,7 +384,7 @@ typedef struct typedef UInt32 CProbPrice; -typedef struct +struct CLzmaEnc { void *matchFinderObj; IMatchFinder2 matchFinder; @@ -426,7 +427,7 @@ typedef struct UInt32 dictSize; SRes result; - #ifndef _7ZIP_ST + #ifndef Z7_ST BoolInt mtMode; // begin of CMatchFinderMt is used in LZ thread CMatchFinderMt matchFinderMt; @@ -439,7 +440,7 @@ typedef struct // we suppose that we have 8-bytes alignment after CMatchFinder - #ifndef _7ZIP_ST + #ifndef Z7_ST Byte pad[128]; #endif @@ -479,77 +480,59 @@ typedef struct CSaveState saveState; // BoolInt mf_Failure; - #ifndef _7ZIP_ST + #ifndef Z7_ST Byte pad2[128]; #endif -} CLzmaEnc; +}; #define MFB (p->matchFinderBase) /* -#ifndef _7ZIP_ST +#ifndef Z7_ST #define MFB (p->matchFinderMt.MatchFinder) #endif */ -#define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr)); - -void LzmaEnc_SaveState(CLzmaEncHandle pp) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - CSaveState *dest = &p->saveState; - - dest->state = p->state; - - dest->lenProbs = p->lenProbs; - dest->repLenProbs = p->repLenProbs; - - COPY_ARR(dest, p, reps); - - COPY_ARR(dest, p, posAlignEncoder); - COPY_ARR(dest, p, isRep); - COPY_ARR(dest, p, isRepG0); - COPY_ARR(dest, p, isRepG1); - COPY_ARR(dest, p, isRepG2); - COPY_ARR(dest, p, isMatch); - COPY_ARR(dest, p, isRep0Long); - COPY_ARR(dest, p, posSlotEncoder); - COPY_ARR(dest, p, posEncoders); - - memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb)); +// #define GET_CLzmaEnc_p CLzmaEnc *p = (CLzmaEnc*)(void *)p; +// #define GET_const_CLzmaEnc_p const CLzmaEnc *p = (const CLzmaEnc*)(const void *)p; + +#define COPY_ARR(dest, src, arr) memcpy((dest)->arr, (src)->arr, sizeof((src)->arr)); + +#define COPY_LZMA_ENC_STATE(d, s, p) \ + (d)->state = (s)->state; \ + COPY_ARR(d, s, reps) \ + COPY_ARR(d, s, posAlignEncoder) \ + COPY_ARR(d, s, isRep) \ + COPY_ARR(d, s, isRepG0) \ + COPY_ARR(d, s, isRepG1) \ + COPY_ARR(d, s, isRepG2) \ + COPY_ARR(d, s, isMatch) \ + COPY_ARR(d, s, isRep0Long) \ + COPY_ARR(d, s, posSlotEncoder) \ + COPY_ARR(d, s, posEncoders) \ + (d)->lenProbs = (s)->lenProbs; \ + (d)->repLenProbs = (s)->repLenProbs; \ + memcpy((d)->litProbs, (s)->litProbs, ((UInt32)0x300 << (p)->lclp) * sizeof(CLzmaProb)); + +void LzmaEnc_SaveState(CLzmaEncHandle p) +{ + // GET_CLzmaEnc_p + CSaveState *v = &p->saveState; + COPY_LZMA_ENC_STATE(v, p, p) } - -void LzmaEnc_RestoreState(CLzmaEncHandle pp) +void LzmaEnc_RestoreState(CLzmaEncHandle p) { - CLzmaEnc *dest = (CLzmaEnc *)pp; - const CSaveState *p = &dest->saveState; - - dest->state = p->state; - - dest->lenProbs = p->lenProbs; - dest->repLenProbs = p->repLenProbs; - - COPY_ARR(dest, p, reps); - - COPY_ARR(dest, p, posAlignEncoder); - COPY_ARR(dest, p, isRep); - COPY_ARR(dest, p, isRepG0); - COPY_ARR(dest, p, isRepG1); - COPY_ARR(dest, p, isRepG2); - COPY_ARR(dest, p, isMatch); - COPY_ARR(dest, p, isRep0Long); - COPY_ARR(dest, p, posSlotEncoder); - COPY_ARR(dest, p, posEncoders); - - memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb)); + // GET_CLzmaEnc_p + const CSaveState *v = &p->saveState; + COPY_LZMA_ENC_STATE(p, v, p) } - -SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) +Z7_NO_INLINE +SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props2) { - CLzmaEnc *p = (CLzmaEnc *)pp; + // GET_CLzmaEnc_p CLzmaEncProps props = *props2; LzmaEncProps_Normalize(&props); @@ -585,6 +568,7 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) p->fastMode = (props.algo == 0); // p->_maxMode = True; MFB.btMode = (Byte)(props.btMode ? 1 : 0); + // MFB.btMode = (Byte)(props.btMode); { unsigned numHashBytes = 4; if (props.btMode) @@ -595,13 +579,15 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) if (props.numHashBytes >= 5) numHashBytes = 5; MFB.numHashBytes = numHashBytes; + // MFB.numHashBytes_Min = 2; + MFB.numHashOutBits = (Byte)props.numHashOutBits; } MFB.cutValue = props.mc; p->writeEndMark = (BoolInt)props.writeEndMark; - #ifndef _7ZIP_ST + #ifndef Z7_ST /* if (newMultiThread != _multiThread) { @@ -618,9 +604,9 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) } -void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) +void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize) { - CLzmaEnc *p = (CLzmaEnc *)pp; + // GET_CLzmaEnc_p MFB.expectedDataSize = expectedDataSiize; } @@ -684,7 +670,7 @@ static void RangeEnc_Init(CRangeEnc *p) p->res = SZ_OK; } -MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) +Z7_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) { const size_t num = (size_t)(p->buf - p->bufBase); if (p->res == SZ_OK) @@ -696,7 +682,7 @@ MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) p->buf = p->bufBase; } -MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) +Z7_NO_INLINE static void Z7_FASTCALL RangeEnc_ShiftLow(CRangeEnc *p) { UInt32 low = (UInt32)p->low; unsigned high = (unsigned)(p->low >> 32); @@ -741,9 +727,9 @@ static void RangeEnc_FlushData(CRangeEnc *p) ttt = *(prob); \ newBound = (range >> kNumBitModelTotalBits) * ttt; -// #define _LZMA_ENC_USE_BRANCH +// #define Z7_LZMA_ENC_USE_BRANCH -#ifdef _LZMA_ENC_USE_BRANCH +#ifdef Z7_LZMA_ENC_USE_BRANCH #define RC_BIT(p, prob, bit) { \ RC_BIT_PRE(p, prob) \ @@ -811,7 +797,7 @@ static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym) CLzmaProb *prob = probs + (sym >> 8); UInt32 bit = (sym >> 7) & 1; sym <<= 1; - RC_BIT(p, prob, bit); + RC_BIT(p, prob, bit) } while (sym < 0x10000); p->range = range; @@ -833,7 +819,7 @@ static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UIn bit = (sym >> 7) & 1; sym <<= 1; offs &= ~(matchByte ^ sym); - RC_BIT(p, prob, bit); + RC_BIT(p, prob, bit) } while (sym < 0x10000); p->range = range; @@ -867,10 +853,10 @@ static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices) #define GET_PRICE(prob, bit) \ - p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; + p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] #define GET_PRICEa(prob, bit) \ - ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; + ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits] #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] @@ -921,7 +907,7 @@ static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, unsigned numBi unsigned bit = sym & 1; // RangeEnc_EncodeBit(rc, probs + m, bit); sym >>= 1; - RC_BIT(rc, probs + m, bit); + RC_BIT(rc, probs + m, bit) m = (m << 1) | bit; } while (--numBits); @@ -944,15 +930,15 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS UInt32 range, ttt, newBound; CLzmaProb *probs = p->low; range = rc->range; - RC_BIT_PRE(rc, probs); + RC_BIT_PRE(rc, probs) if (sym >= kLenNumLowSymbols) { - RC_BIT_1(rc, probs); + RC_BIT_1(rc, probs) probs += kLenNumLowSymbols; - RC_BIT_PRE(rc, probs); + RC_BIT_PRE(rc, probs) if (sym >= kLenNumLowSymbols * 2) { - RC_BIT_1(rc, probs); + RC_BIT_1(rc, probs) rc->range = range; // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2); LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2); @@ -965,11 +951,11 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS { unsigned m; unsigned bit; - RC_BIT_0(rc, probs); + RC_BIT_0(rc, probs) probs += (posState << (1 + kLenNumLowBits)); - bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit; - bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit; - bit = sym & 1; RC_BIT(rc, probs + m, bit); + bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit) m = (1 << 1) + bit; + bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit) m = (m << 1) + bit; + bit = sym & 1; RC_BIT(rc, probs + m, bit) rc->range = range; } } @@ -990,7 +976,7 @@ static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *price } -MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables( +Z7_NO_INLINE static void Z7_FASTCALL LenPriceEnc_UpdateTables( CLenPriceEnc *p, unsigned numPosStates, const CLenEnc *enc, @@ -1152,7 +1138,7 @@ static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes) + GET_PRICE_1(p->isRep[state]) \ + GET_PRICE_0(p->isRepG0[state]) -MY_FORCE_INLINE +Z7_FORCE_INLINE static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState) { UInt32 price; @@ -1331,7 +1317,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) LitEnc_GetPrice(probs, curByte, p->ProbPrices)); } - MakeAs_Lit(&p->opt[1]); + MakeAs_Lit(&p->opt[1]) matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); @@ -1343,7 +1329,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) if (shortRepPrice < p->opt[1].price) { p->opt[1].price = shortRepPrice; - MakeAs_ShortRep(&p->opt[1]); + MakeAs_ShortRep(&p->opt[1]) } if (last < 2) { @@ -1410,7 +1396,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) else { unsigned slot; - GetPosSlot2(dist, slot); + GetPosSlot2(dist, slot) price += p->alignPrices[dist & kAlignMask]; price += p->posSlotPrices[lenToPosState][slot]; } @@ -1486,7 +1472,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) unsigned delta = best - cur; if (delta != 0) { - MOVE_POS(p, delta); + MOVE_POS(p, delta) } } cur = best; @@ -1633,7 +1619,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) { nextOpt->price = litPrice; nextOpt->len = 1; - MakeAs_Lit(nextOpt); + MakeAs_Lit(nextOpt) nextIsLit = True; } } @@ -1667,7 +1653,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) { nextOpt->price = shortRepPrice; nextOpt->len = 1; - MakeAs_ShortRep(nextOpt); + MakeAs_ShortRep(nextOpt) nextIsLit = False; } } @@ -1871,7 +1857,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) dist = MATCHES[(size_t)offs + 1]; // if (dist >= kNumFullDistances) - GetPosSlot2(dist, posSlot); + GetPosSlot2(dist, posSlot) for (len = /*2*/ startLen; ; len++) { @@ -1962,7 +1948,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position) break; dist = MATCHES[(size_t)offs + 1]; // if (dist >= kNumFullDistances) - GetPosSlot2(dist, posSlot); + GetPosSlot2(dist, posSlot) } } } @@ -2138,7 +2124,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) { UInt32 ttt, newBound; RC_BIT_PRE(p, probs + m) - RC_BIT_1(&p->rc, probs + m); + RC_BIT_1(&p->rc, probs + m) m = (m << 1) + 1; } while (m < (1 << kNumPosSlotBits)); @@ -2163,7 +2149,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState) { UInt32 ttt, newBound; RC_BIT_PRE(p, probs + m) - RC_BIT_1(&p->rc, probs + m); + RC_BIT_1(&p->rc, probs + m) m = (m << 1) + 1; } while (m < kAlignTableSize); @@ -2179,7 +2165,7 @@ static SRes CheckErrors(CLzmaEnc *p) if (p->rc.res != SZ_OK) p->result = SZ_ERROR_WRITE; - #ifndef _7ZIP_ST + #ifndef Z7_ST if ( // p->mf_Failure || (p->mtMode && @@ -2187,7 +2173,7 @@ static SRes CheckErrors(CLzmaEnc *p) p->matchFinderMt.failure_LZ_BT)) ) { - p->result = MY_HRES_ERROR__INTERNAL_ERROR; + p->result = MY_HRES_ERROR_INTERNAL_ERROR; // printf("\nCheckErrors p->matchFinderMt.failureLZ\n"); } #endif @@ -2201,7 +2187,7 @@ static SRes CheckErrors(CLzmaEnc *p) } -MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) +Z7_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) { /* ReleaseMFStream(); */ p->finished = True; @@ -2213,7 +2199,7 @@ MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) } -MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) +Z7_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) { unsigned i; const CProbPrice *ProbPrices = p->ProbPrices; @@ -2237,7 +2223,7 @@ MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) } -MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) +Z7_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) { // int y; for (y = 0; y < 100; y++) { @@ -2337,7 +2323,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) RangeEnc_Construct(&p->rc); MatchFinder_Construct(&MFB); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->matchFinderMt.MatchFinder = &MFB; MatchFinderMt_Construct(&p->matchFinderMt); #endif @@ -2345,7 +2331,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p) { CLzmaEncProps props; LzmaEncProps_Init(&props); - LzmaEnc_SetProps(p, &props); + LzmaEnc_SetProps((CLzmaEncHandle)(void *)p, &props); } #ifndef LZMA_LOG_BSR @@ -2376,7 +2362,7 @@ static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc) static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig) { - #ifndef _7ZIP_ST + #ifndef Z7_ST MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); #endif @@ -2387,21 +2373,22 @@ static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBi void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig) { - LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); + // GET_CLzmaEnc_p + LzmaEnc_Destruct(p, alloc, allocBig); ISzAlloc_Free(alloc, p); } -MY_NO_INLINE +Z7_NO_INLINE static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize) { UInt32 nowPos32, startPos32; if (p->needInit) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtMode) { - RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)); + RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)) } #endif p->matchFinder.Init(p->matchFinderObj); @@ -2410,7 +2397,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa if (p->finished) return p->result; - RINOK(CheckErrors(p)); + RINOK(CheckErrors(p)) nowPos32 = (UInt32)p->nowPos64; startPos32 = nowPos32; @@ -2473,7 +2460,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa const Byte *data; unsigned state; - RC_BIT_0(&p->rc, probs); + RC_BIT_0(&p->rc, probs) p->rc.range = range; data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; probs = LIT_PROBS(nowPos32, *(data - 1)); @@ -2487,53 +2474,53 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa } else { - RC_BIT_1(&p->rc, probs); + RC_BIT_1(&p->rc, probs) probs = &p->isRep[p->state]; RC_BIT_PRE(&p->rc, probs) if (dist < LZMA_NUM_REPS) { - RC_BIT_1(&p->rc, probs); + RC_BIT_1(&p->rc, probs) probs = &p->isRepG0[p->state]; RC_BIT_PRE(&p->rc, probs) if (dist == 0) { - RC_BIT_0(&p->rc, probs); + RC_BIT_0(&p->rc, probs) probs = &p->isRep0Long[p->state][posState]; RC_BIT_PRE(&p->rc, probs) if (len != 1) { - RC_BIT_1_BASE(&p->rc, probs); + RC_BIT_1_BASE(&p->rc, probs) } else { - RC_BIT_0_BASE(&p->rc, probs); + RC_BIT_0_BASE(&p->rc, probs) p->state = kShortRepNextStates[p->state]; } } else { - RC_BIT_1(&p->rc, probs); + RC_BIT_1(&p->rc, probs) probs = &p->isRepG1[p->state]; RC_BIT_PRE(&p->rc, probs) if (dist == 1) { - RC_BIT_0_BASE(&p->rc, probs); + RC_BIT_0_BASE(&p->rc, probs) dist = p->reps[1]; } else { - RC_BIT_1(&p->rc, probs); + RC_BIT_1(&p->rc, probs) probs = &p->isRepG2[p->state]; RC_BIT_PRE(&p->rc, probs) if (dist == 2) { - RC_BIT_0_BASE(&p->rc, probs); + RC_BIT_0_BASE(&p->rc, probs) dist = p->reps[2]; } else { - RC_BIT_1_BASE(&p->rc, probs); + RC_BIT_1_BASE(&p->rc, probs) dist = p->reps[3]; p->reps[3] = p->reps[2]; } @@ -2557,7 +2544,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa else { unsigned posSlot; - RC_BIT_0(&p->rc, probs); + RC_BIT_0(&p->rc, probs) p->rc.range = range; p->state = kMatchNextStates[p->state]; @@ -2571,7 +2558,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa p->reps[0] = dist + 1; p->matchPriceCount++; - GetPosSlot(dist, posSlot); + GetPosSlot(dist, posSlot) // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot); { UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits); @@ -2582,7 +2569,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa CLzmaProb *prob = probs + (sym >> kNumPosSlotBits); UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1; sym <<= 1; - RC_BIT(&p->rc, prob, bit); + RC_BIT(&p->rc, prob, bit) } while (sym < (1 << kNumPosSlotBits * 2)); p->rc.range = range; @@ -2626,10 +2613,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa { unsigned m = 1; unsigned bit; - bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; - bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; - bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; - bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); + bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; + bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; + bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit; + bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) p->rc.range = range; // p->alignPriceCount++; } @@ -2704,7 +2691,7 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, if (!RangeEnc_Alloc(&p->rc, alloc)) return SZ_ERROR_MEM; - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtMode = (p->multiThread && !p->fastMode && (MFB.btMode != 0)); #endif @@ -2748,15 +2735,14 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, (numFastBytes + LZMA_MATCH_LEN_MAX + 1) */ - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtMode) { RINOK(MatchFinderMt_Create(&p->matchFinderMt, dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX + 1 /* 18.04 */ - , allocBig)); + , allocBig)) p->matchFinderObj = &p->matchFinderMt; - MFB.bigHash = (Byte)( - (p->dictSize > kBigHashDicLimit && MFB.hashMask >= 0xFFFFFF) ? 1 : 0); + MFB.bigHash = (Byte)(MFB.hashMask >= 0xFFFFFF ? 1 : 0); MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); } else @@ -2872,59 +2858,53 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr p->finished = 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 @@ typedef struct { ISeqOutStream vt; Byte *data; - SizeT rem; + size_t rem; BoolInt overflow; } CLzmaEnc_SeqOutStreamBuf; -static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size) +static size_t SeqOutStreamBuf_Write(ISeqOutStreamPtr pp, const void *data, size_t size) { - CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLzmaEnc_SeqOutStreamBuf) if (p->rem < size) { size = p->rem; @@ -2956,25 +2936,25 @@ static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, s /* -UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) +UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p) { - const CLzmaEnc *p = (CLzmaEnc *)pp; + GET_const_CLzmaEnc_p return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); } */ -const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) +const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p) { - const CLzmaEnc *p = (CLzmaEnc *)pp; + // GET_const_CLzmaEnc_p return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; } // (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 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, } -MY_NO_INLINE -static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) +Z7_NO_INLINE +static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgressPtr progress) { SRes res = SZ_OK; - #ifndef _7ZIP_ST + #ifndef Z7_ST Byte allocaDummy[0x300]; allocaDummy[0] = 0; allocaDummy[1] = allocaDummy[0]; @@ -3033,7 +3013,7 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) } } - LzmaEnc_Finish(p); + LzmaEnc_Finish((CLzmaEncHandle)(void *)p); /* if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB)) @@ -3045,21 +3025,22 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) } -SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, +SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) { - RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig)); - return LzmaEnc_Encode2((CLzmaEnc *)pp, progress); + // GET_CLzmaEnc_p + RINOK(LzmaEnc_Prepare(p, outStream, inStream, alloc, allocBig)) + return LzmaEnc_Encode2(p, progress); } -SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) +SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *props, SizeT *size) { if (*size < LZMA_PROPS_SIZE) return SZ_ERROR_PARAM; *size = LZMA_PROPS_SIZE; { - const CLzmaEnc *p = (const CLzmaEnc *)pp; + // GET_CLzmaEnc_p const UInt32 dictSize = p->dictSize; UInt32 v; props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); @@ -3083,23 +3064,24 @@ SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) while (v < dictSize); } - SetUi32(props + 1, v); + SetUi32(props + 1, v) return SZ_OK; } } -unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp) +unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p) { - return (unsigned)((CLzmaEnc *)pp)->writeEndMark; + // GET_CLzmaEnc_p + return (unsigned)p->writeEndMark; } -SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) +SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, + int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) { SRes res; - CLzmaEnc *p = (CLzmaEnc *)pp; + // GET_CLzmaEnc_p CLzmaEnc_SeqOutStreamBuf outStream; @@ -3111,7 +3093,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte p->writeEndMark = writeEndMark; p->rc.outStream = &outStream.vt; - res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig); + res = LzmaEnc_MemPrepare(p, src, srcLen, 0, alloc, allocBig); if (res == SZ_OK) { @@ -3120,7 +3102,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte res = SZ_ERROR_FAIL; } - *destLen -= outStream.rem; + *destLen -= (SizeT)outStream.rem; if (outStream.overflow) return SZ_ERROR_OUTPUT_EOF; return res; @@ -3129,9 +3111,9 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) + ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) { - CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); + CLzmaEncHandle p = LzmaEnc_Create(alloc); SRes res; if (!p) return SZ_ERROR_MEM; @@ -3151,10 +3133,10 @@ SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, /* -#ifndef _7ZIP_ST -void LzmaEnc_GetLzThreads(CLzmaEncHandle pp, HANDLE lz_threads[2]) +#ifndef Z7_ST +void LzmaEnc_GetLzThreads(CLzmaEncHandle p, HANDLE lz_threads[2]) { - const CLzmaEnc *p = (CLzmaEnc *)pp; + GET_const_CLzmaEnc_p lz_threads[0] = p->matchFinderMt.hashSync.thread; lz_threads[1] = p->matchFinderMt.btSync.thread; } diff --git a/C/LzmaEnc.h b/C/LzmaEnc.h index bc2ed504..9f8039a1 100644 --- a/C/LzmaEnc.h +++ b/C/LzmaEnc.h @@ -1,8 +1,8 @@ /* LzmaEnc.h -- LZMA Encoder -2019-10-30 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __LZMA_ENC_H -#define __LZMA_ENC_H +#ifndef ZIP7_INC_LZMA_ENC_H +#define ZIP7_INC_LZMA_ENC_H #include "7zTypes.h" @@ -10,7 +10,7 @@ EXTERN_C_BEGIN #define LZMA_PROPS_SIZE 5 -typedef struct _CLzmaEncProps +typedef struct { int level; /* 0 <= level <= 9 */ UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version @@ -23,10 +23,13 @@ typedef struct _CLzmaEncProps int fb; /* 5 <= fb <= 273, default = 32 */ int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */ int numHashBytes; /* 2, 3 or 4, default = 4 */ + unsigned numHashOutBits; /* default = ? */ UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */ unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */ int numThreads; /* 1 or 2, default = 2 */ + // int _pad; + UInt64 reduceSize; /* estimated size of data that will be compressed. default = (UInt64)(Int64)-1. Encoder uses this value to reduce dictionary size */ @@ -51,7 +54,9 @@ UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2); SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) */ -typedef void * CLzmaEncHandle; +typedef struct CLzmaEnc CLzmaEnc; +typedef CLzmaEnc * CLzmaEncHandle; +// Z7_DECLARE_HANDLE(CLzmaEncHandle) CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc); void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig); @@ -61,17 +66,17 @@ void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize); SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p); -SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, - ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); +SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, + ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); + int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); /* ---------- One Call Interface ---------- */ SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); + ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); EXTERN_C_END diff --git a/C/LzmaLib.c b/C/LzmaLib.c index 706e9e58..785e8848 100644 --- a/C/LzmaLib.c +++ b/C/LzmaLib.c @@ -1,12 +1,14 @@ /* LzmaLib.c -- LZMA library wrapper -2015-06-13 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ + +#include "Precomp.h" #include "Alloc.h" #include "LzmaDec.h" #include "LzmaEnc.h" #include "LzmaLib.h" -MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, +Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProps, size_t *outPropsSize, int level, /* 0 <= level <= 9, default = 5 */ unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */ @@ -32,7 +34,7 @@ MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char } -MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, +Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, const unsigned char *props, size_t propsSize) { ELzmaStatus status; diff --git a/C/LzmaLib.h b/C/LzmaLib.h index c343a859..d7c0724d 100644 --- a/C/LzmaLib.h +++ b/C/LzmaLib.h @@ -1,14 +1,14 @@ /* LzmaLib.h -- LZMA library interface -2021-04-03 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __LZMA_LIB_H -#define __LZMA_LIB_H +#ifndef ZIP7_INC_LZMA_LIB_H +#define ZIP7_INC_LZMA_LIB_H #include "7zTypes.h" EXTERN_C_BEGIN -#define MY_STDAPI int MY_STD_CALL +#define Z7_STDAPI int Z7_STDCALL #define LZMA_PROPS_SIZE 5 @@ -100,7 +100,7 @@ numThreads - The number of thereads. 1 or 2. The default value is 2. SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) */ -MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, +Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */ int level, /* 0 <= level <= 9, default = 5 */ unsigned dictSize, /* default = (1 << 24) */ @@ -130,7 +130,7 @@ LzmaUncompress SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer (src) */ -MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, +Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, const unsigned char *props, size_t propsSize); EXTERN_C_END diff --git a/C/MtCoder.c b/C/MtCoder.c index 99dc9090..6f58abb2 100644 --- a/C/MtCoder.c +++ b/C/MtCoder.c @@ -1,28 +1,28 @@ /* MtCoder.c -- Multi-thread Coder -2021-12-21 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ #include "Precomp.h" #include "MtCoder.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST -static SRes MtProgressThunk_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) +static SRes MtProgressThunk_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) { - CMtProgressThunk *thunk = CONTAINER_FROM_VTBL(pp, CMtProgressThunk, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CMtProgressThunk) UInt64 inSize2 = 0; UInt64 outSize2 = 0; if (inSize != (UInt64)(Int64)-1) { - inSize2 = inSize - thunk->inSize; - thunk->inSize = inSize; + inSize2 = inSize - p->inSize; + p->inSize = inSize; } if (outSize != (UInt64)(Int64)-1) { - outSize2 = outSize - thunk->outSize; - thunk->outSize = outSize; + outSize2 = outSize - p->outSize; + p->outSize = outSize; } - return MtProgress_ProgressAdd(thunk->mtProgress, inSize2, outSize2); + return MtProgress_ProgressAdd(p->mtProgress, inSize2, outSize2); } @@ -36,20 +36,12 @@ void MtProgressThunk_CreateVTable(CMtProgressThunk *p) #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } -static WRes ArEvent_OptCreate_And_Reset(CEvent *p) -{ - if (Event_IsCreated(p)) - return Event_Reset(p); - return AutoResetEvent_CreateNotSignaled(p); -} - - static THREAD_FUNC_DECL ThreadFunc(void *pp); static SRes MtCoderThread_CreateAndStart(CMtCoderThread *t) { - WRes wres = ArEvent_OptCreate_And_Reset(&t->startEvent); + WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->startEvent); if (wres == 0) { t->stop = False; @@ -84,24 +76,6 @@ static void MtCoderThread_Destruct(CMtCoderThread *t) -static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) -{ - size_t size = *processedSize; - *processedSize = 0; - while (size != 0) - { - size_t cur = size; - SRes res = ISeqInStream_Read(stream, data, &cur); - *processedSize += cur; - data += cur; - size -= cur; - RINOK(res); - if (cur == 0) - return SZ_OK; - } - return SZ_OK; -} - /* ThreadFunc2() returns: @@ -152,7 +126,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) } if (res == SZ_OK) { - res = FullRead(mtc->inStream, t->inBuf, &size); + res = SeqInStream_ReadMax(mtc->inStream, t->inBuf, &size); readProcessed = mtc->readProcessed + size; mtc->readProcessed = readProcessed; } @@ -253,7 +227,7 @@ static SRes ThreadFunc2(CMtCoderThread *t) block->finished = finished; } - #ifdef MTCODER__USE_WRITE_THREAD + #ifdef MTCODER_USE_WRITE_THREAD RINOK_THREAD(Event_Set(&mtc->writeEvents[bi])) #else { @@ -352,7 +326,7 @@ static THREAD_FUNC_DECL ThreadFunc(void *pp) MtProgress_SetError(&mtc->mtProgress, res); } - #ifndef MTCODER__USE_WRITE_THREAD + #ifndef MTCODER_USE_WRITE_THREAD { unsigned numFinished = (unsigned)InterlockedIncrement(&mtc->numFinishedThreads); if (numFinished == mtc->numStartedThreads) @@ -389,7 +363,7 @@ void MtCoder_Construct(CMtCoder *p) Event_Construct(&p->readEvent); Semaphore_Construct(&p->blocksSemaphore); - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) { CMtCoderThread *t = &p->threads[i]; t->mtCoder = p; @@ -397,11 +371,11 @@ void MtCoder_Construct(CMtCoder *p) t->inBuf = NULL; t->stop = 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 @@ static void MtCoder_Free(CMtCoder *p) Event_Set(&p->readEvent); */ - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) MtCoderThread_Destruct(&p->threads[i]); Event_Close(&p->readEvent); Semaphore_Close(&p->blocksSemaphore); - #ifdef MTCODER__USE_WRITE_THREAD - for (i = 0; i < MTCODER__BLOCKS_MAX; i++) + #ifdef MTCODER_USE_WRITE_THREAD + for (i = 0; i < MTCODER_BLOCKS_MAX; i++) Event_Close(&p->writeEvents[i]); #else Event_Close(&p->finishedEvent); @@ -455,20 +429,20 @@ SRes MtCoder_Code(CMtCoder *p) unsigned i; SRes res = SZ_OK; - if (numThreads > MTCODER__THREADS_MAX) - numThreads = MTCODER__THREADS_MAX; - numBlocksMax = MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads); + if (numThreads > MTCODER_THREADS_MAX) + numThreads = MTCODER_THREADS_MAX; + numBlocksMax = MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads); if (p->blockSize < ((UInt32)1 << 26)) numBlocksMax++; if (p->blockSize < ((UInt32)1 << 24)) numBlocksMax++; if (p->blockSize < ((UInt32)1 << 22)) numBlocksMax++; - if (numBlocksMax > MTCODER__BLOCKS_MAX) - numBlocksMax = MTCODER__BLOCKS_MAX; + if (numBlocksMax > MTCODER_BLOCKS_MAX) + numBlocksMax = MTCODER_BLOCKS_MAX; if (p->blockSize != p->allocatedBufsSize) { - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) { CMtCoderThread *t = &p->threads[i]; if (t->inBuf) @@ -484,23 +458,23 @@ SRes MtCoder_Code(CMtCoder *p) MtProgress_Init(&p->mtProgress, p->progress); - #ifdef MTCODER__USE_WRITE_THREAD + #ifdef MTCODER_USE_WRITE_THREAD for (i = 0; i < numBlocksMax; i++) { - RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->writeEvents[i])); + RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->writeEvents[i])) } #else - RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); + RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) #endif { - RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->readEvent)); - RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)); + RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->readEvent)) + RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)) } - for (i = 0; i < MTCODER__BLOCKS_MAX - 1; i++) + for (i = 0; i < MTCODER_BLOCKS_MAX - 1; i++) p->freeBlockList[i] = i + 1; - p->freeBlockList[MTCODER__BLOCKS_MAX - 1] = (unsigned)(int)-1; + p->freeBlockList[MTCODER_BLOCKS_MAX - 1] = (unsigned)(int)-1; p->freeBlockHead = 0; p->readProcessed = 0; @@ -508,10 +482,10 @@ SRes MtCoder_Code(CMtCoder *p) p->numBlocksMax = numBlocksMax; p->stopReading = 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 @@ SRes MtCoder_Code(CMtCoder *p) // for (i = 0; i < numThreads; i++) { CMtCoderThread *nextThread = &p->threads[p->numStartedThreads++]; - RINOK(MtCoderThread_CreateAndStart(nextThread)); + RINOK(MtCoderThread_CreateAndStart(nextThread)) } RINOK_THREAD(Event_Set(&p->readEvent)) - #ifdef MTCODER__USE_WRITE_THREAD + #ifdef MTCODER_USE_WRITE_THREAD { unsigned bi = 0; @@ -582,7 +556,7 @@ SRes MtCoder_Code(CMtCoder *p) if (res == SZ_OK) res = p->mtProgress.res; - #ifndef MTCODER__USE_WRITE_THREAD + #ifndef MTCODER_USE_WRITE_THREAD if (res == SZ_OK) res = p->writeRes; #endif @@ -593,3 +567,5 @@ SRes MtCoder_Code(CMtCoder *p) } #endif + +#undef RINOK_THREAD diff --git a/C/MtCoder.h b/C/MtCoder.h index 5a5f4d11..1231d3c2 100644 --- a/C/MtCoder.h +++ b/C/MtCoder.h @@ -1,30 +1,30 @@ /* MtCoder.h -- Multi-thread Coder -2018-07-04 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __MT_CODER_H -#define __MT_CODER_H +#ifndef ZIP7_INC_MT_CODER_H +#define ZIP7_INC_MT_CODER_H #include "MtDec.h" EXTERN_C_BEGIN /* - if ( defined MTCODER__USE_WRITE_THREAD) : main thread writes all data blocks to output stream - if (not defined MTCODER__USE_WRITE_THREAD) : any coder thread can write data blocks to output stream + if ( defined MTCODER_USE_WRITE_THREAD) : main thread writes all data blocks to output stream + if (not defined MTCODER_USE_WRITE_THREAD) : any coder thread can write data blocks to output stream */ -/* #define MTCODER__USE_WRITE_THREAD */ +/* #define MTCODER_USE_WRITE_THREAD */ -#ifndef _7ZIP_ST - #define MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) - #define MTCODER__THREADS_MAX 64 - #define MTCODER__BLOCKS_MAX (MTCODER__GET_NUM_BLOCKS_FROM_THREADS(MTCODER__THREADS_MAX) + 3) +#ifndef Z7_ST + #define MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) + #define MTCODER_THREADS_MAX 64 + #define MTCODER_BLOCKS_MAX (MTCODER_GET_NUM_BLOCKS_FROM_THREADS(MTCODER_THREADS_MAX) + 3) #else - #define MTCODER__THREADS_MAX 1 - #define MTCODER__BLOCKS_MAX 1 + #define MTCODER_THREADS_MAX 1 + #define MTCODER_BLOCKS_MAX 1 #endif -#ifndef _7ZIP_ST +#ifndef Z7_ST typedef struct @@ -37,15 +37,15 @@ typedef struct void MtProgressThunk_CreateVTable(CMtProgressThunk *p); -#define MtProgressThunk_Init(p) { (p)->inSize = 0; (p)->outSize = 0; } +#define MtProgressThunk_INIT(p) { (p)->inSize = 0; (p)->outSize = 0; } -struct _CMtCoder; +struct CMtCoder_; typedef struct { - struct _CMtCoder *mtCoder; + struct CMtCoder_ *mtCoder; unsigned index; int stop; Byte *inBuf; @@ -71,7 +71,7 @@ typedef struct } CMtCoderBlock; -typedef struct _CMtCoder +typedef struct CMtCoder_ { /* input variables */ @@ -79,11 +79,11 @@ typedef struct _CMtCoder unsigned numThreadsMax; UInt64 expectedDataSize; - ISeqInStream *inStream; + ISeqInStreamPtr inStream; const Byte *inData; size_t inDataSize; - ICompressProgress *progress; + ICompressProgressPtr progress; ISzAllocPtr allocBig; IMtCoderCallback2 *mtCallback; @@ -100,13 +100,13 @@ typedef struct _CMtCoder BoolInt stopReading; SRes readRes; - #ifdef MTCODER__USE_WRITE_THREAD - CAutoResetEvent writeEvents[MTCODER__BLOCKS_MAX]; + #ifdef MTCODER_USE_WRITE_THREAD + CAutoResetEvent writeEvents[MTCODER_BLOCKS_MAX]; #else CAutoResetEvent finishedEvent; SRes writeRes; unsigned writeIndex; - Byte ReadyBlocks[MTCODER__BLOCKS_MAX]; + Byte ReadyBlocks[MTCODER_BLOCKS_MAX]; LONG numFinishedThreads; #endif @@ -120,11 +120,11 @@ typedef struct _CMtCoder CCriticalSection cs; unsigned freeBlockHead; - unsigned freeBlockList[MTCODER__BLOCKS_MAX]; + unsigned freeBlockList[MTCODER_BLOCKS_MAX]; CMtProgress mtProgress; - CMtCoderBlock blocks[MTCODER__BLOCKS_MAX]; - CMtCoderThread threads[MTCODER__THREADS_MAX]; + CMtCoderBlock blocks[MTCODER_BLOCKS_MAX]; + CMtCoderThread threads[MTCODER_THREADS_MAX]; } CMtCoder; diff --git a/C/MtDec.c b/C/MtDec.c index 6ca5c27f..78206992 100644 --- a/C/MtDec.c +++ b/C/MtDec.c @@ -1,5 +1,5 @@ /* MtDec.c -- Multi-thread Decoder -2021-12-21 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -14,7 +14,7 @@ #include "MtDec.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #ifdef SHOW_DEBUG_INFO #define PRF(x) x @@ -24,7 +24,7 @@ #define PRF_STR_INT(s, d) PRF(printf("\n" s " %d\n", (unsigned)d)) -void MtProgress_Init(CMtProgress *p, ICompressProgress *progress) +void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress) { p->progress = progress; p->res = SZ_OK; @@ -81,36 +81,28 @@ void MtProgress_SetError(CMtProgress *p, SRes res) #define RINOK_THREAD(x) RINOK_WRes(x) -static WRes ArEvent_OptCreate_And_Reset(CEvent *p) +struct CMtDecBufLink_ { - if (Event_IsCreated(p)) - return Event_Reset(p); - return AutoResetEvent_CreateNotSignaled(p); -} - - -struct __CMtDecBufLink -{ - struct __CMtDecBufLink *next; + struct CMtDecBufLink_ *next; void *pad[3]; }; -typedef struct __CMtDecBufLink CMtDecBufLink; +typedef struct CMtDecBufLink_ CMtDecBufLink; #define MTDEC__LINK_DATA_OFFSET sizeof(CMtDecBufLink) #define MTDEC__DATA_PTR_FROM_LINK(link) ((Byte *)(link) + MTDEC__LINK_DATA_OFFSET) -static MY_NO_INLINE THREAD_FUNC_DECL ThreadFunc(void *pp); +static THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp); static WRes MtDecThread_CreateEvents(CMtDecThread *t) { - WRes wres = ArEvent_OptCreate_And_Reset(&t->canWrite); + WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->canWrite); if (wres == 0) { - wres = ArEvent_OptCreate_And_Reset(&t->canRead); + wres = AutoResetEvent_OptCreate_And_Reset(&t->canRead); if (wres == 0) return SZ_OK; } @@ -126,7 +118,7 @@ static SRes MtDecThread_CreateAndStart(CMtDecThread *t) { if (Thread_WasCreated(&t->thread)) return SZ_OK; - wres = Thread_Create(&t->thread, ThreadFunc, t); + wres = Thread_Create(&t->thread, MtDec_ThreadFunc, t); if (wres == 0) return SZ_OK; } @@ -167,7 +159,7 @@ static void MtDecThread_CloseThread(CMtDecThread *t) static void MtDec_CloseThreads(CMtDec *p) { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) MtDecThread_CloseThread(&p->threads[i]); } @@ -179,25 +171,6 @@ static void MtDecThread_Destruct(CMtDecThread *t) -static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize) -{ - size_t size = *processedSize; - *processedSize = 0; - while (size != 0) - { - size_t cur = size; - SRes res = ISeqInStream_Read(stream, data, &cur); - *processedSize += cur; - data += cur; - size -= cur; - RINOK(res); - if (cur == 0) - return SZ_OK; - } - return SZ_OK; -} - - static SRes MtDec_GetError_Spec(CMtDec *p, UInt64 interruptIndex, BoolInt *wasInterrupted) { SRes res; @@ -253,7 +226,7 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) /* - ThreadFunc2() returns: + MtDec_ThreadFunc2() returns: 0 - in all normal cases (even for stream error or memory allocation error) (!= 0) - WRes error return by system threading function */ @@ -261,11 +234,11 @@ Byte *MtDec_GetCrossBuff(CMtDec *p) // #define MTDEC_ProgessStep (1 << 22) #define MTDEC_ProgessStep (1 << 0) -static WRes ThreadFunc2(CMtDecThread *t) +static WRes MtDec_ThreadFunc2(CMtDecThread *t) { CMtDec *p = t->mtDec; - PRF_STR_INT("ThreadFunc2", t->index); + PRF_STR_INT("MtDec_ThreadFunc2", t->index) // SetThreadAffinityMask(GetCurrentThread(), 1 << t->index); @@ -295,13 +268,13 @@ static WRes ThreadFunc2(CMtDecThread *t) // CMtDecCallbackInfo parse; CMtDecThread *nextThread; - PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index); + PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index) - RINOK_THREAD(Event_Wait(&t->canRead)); + RINOK_THREAD(Event_Wait(&t->canRead)) if (p->exitThread) return 0; - PRF_STR_INT("after Event_Wait(&t->canRead)", t->index); + PRF_STR_INT("after Event_Wait(&t->canRead)", t->index) // if (t->index == 3) return 19; // for test @@ -373,7 +346,7 @@ static WRes ThreadFunc2(CMtDecThread *t) { size = p->inBufSize; - res = FullRead(p->inStream, data, &size); + res = SeqInStream_ReadMax(p->inStream, data, &size); // size = 10; // test @@ -615,7 +588,7 @@ static WRes ThreadFunc2(CMtDecThread *t) // if ( !finish ) we must call Event_Set(&nextThread->canWrite) in any case // if ( finish ) we switch to single-thread mode and there are 2 ways at the end of current iteration (current block): // - if (needContinue) after Write(&needContinue), we restore decoding with new iteration - // - otherwise we stop decoding and exit from ThreadFunc2() + // - otherwise we stop decoding and exit from MtDec_ThreadFunc2() // Don't change (finish) variable in the further code @@ -688,7 +661,7 @@ static WRes ThreadFunc2(CMtDecThread *t) // ---------- WRITE ---------- - RINOK_THREAD(Event_Wait(&t->canWrite)); + RINOK_THREAD(Event_Wait(&t->canWrite)) { BoolInt isErrorMode = False; @@ -801,14 +774,14 @@ static WRes ThreadFunc2(CMtDecThread *t) if (!finish) { - RINOK_THREAD(Event_Set(&nextThread->canWrite)); + RINOK_THREAD(Event_Set(&nextThread->canWrite)) } else { if (needContinue) { // we restore decoding with new iteration - RINOK_THREAD(Event_Set(&p->threads[0].canWrite)); + RINOK_THREAD(Event_Set(&p->threads[0].canWrite)) } else { @@ -817,7 +790,7 @@ static WRes ThreadFunc2(CMtDecThread *t) return SZ_OK; p->exitThread = True; } - RINOK_THREAD(Event_Set(&p->threads[0].canRead)); + RINOK_THREAD(Event_Set(&p->threads[0].canRead)) } } } @@ -836,7 +809,7 @@ static WRes ThreadFunc2(CMtDecThread *t) #endif -static THREAD_FUNC_DECL ThreadFunc1(void *pp) +static THREAD_FUNC_DECL MtDec_ThreadFunc1(void *pp) { WRes res; @@ -845,7 +818,7 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) // fprintf(stdout, "\n%d = %p\n", t->index, &t); - res = ThreadFunc2(t); + res = MtDec_ThreadFunc2(t); p = t->mtDec; if (res == 0) return (THREAD_FUNC_RET_TYPE)(UINT_PTR)p->exitThreadWRes; @@ -862,14 +835,14 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp) return (THREAD_FUNC_RET_TYPE)(UINT_PTR)res; } -static MY_NO_INLINE THREAD_FUNC_DECL ThreadFunc(void *pp) +static Z7_NO_INLINE THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp) { #ifdef USE_ALLOCA CMtDecThread *t = (CMtDecThread *)pp; // fprintf(stderr, "\n%d = %p - before", t->index, &t); t->allocaPtr = alloca(t->index * 128); #endif - return ThreadFunc1(pp); + return MtDec_ThreadFunc1(pp); } @@ -883,7 +856,7 @@ int MtDec_PrepareRead(CMtDec *p) { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) if (i > p->numStartedThreads || p->numFilledThreads <= (i >= p->filledThreadStart ? @@ -987,7 +960,7 @@ void MtDec_Construct(CMtDec *p) p->allocatedBufsSize = 0; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CMtDecThread *t = &p->threads[i]; t->mtDec = p; @@ -995,7 +968,7 @@ void MtDec_Construct(CMtDec *p) t->inBuf = NULL; Event_Construct(&t->canRead); Event_Construct(&t->canWrite); - Thread_Construct(&t->thread); + Thread_CONSTRUCT(&t->thread) } // Event_Construct(&p->finishedEvent); @@ -1010,7 +983,7 @@ static void MtDec_Free(CMtDec *p) p->exitThread = 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 @@ SRes MtDec_Code(CMtDec *p) { unsigned numThreads = p->numThreadsMax; - if (numThreads > MTDEC__THREADS_MAX) - numThreads = MTDEC__THREADS_MAX; + if (numThreads > MTDEC_THREADS_MAX) + numThreads = MTDEC_THREADS_MAX; p->numStartedThreads_Limit = numThreads; p->numStartedThreads = 0; } if (p->inBufSize != p->allocatedBufsSize) { - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CMtDecThread *t = &p->threads[i]; if (t->inBuf) @@ -1086,7 +1059,7 @@ SRes MtDec_Code(CMtDec *p) MtProgress_Init(&p->mtProgress, p->progress); - // RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); + // RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent)) p->exitThread = False; p->exitThreadWRes = 0; @@ -1098,7 +1071,7 @@ SRes MtDec_Code(CMtDec *p) wres = MtDecThread_CreateEvents(nextThread); if (wres == 0) { wres = Event_Set(&nextThread->canWrite); if (wres == 0) { wres = Event_Set(&nextThread->canRead); - if (wres == 0) { THREAD_FUNC_RET_TYPE res = ThreadFunc(nextThread); + if (wres == 0) { THREAD_FUNC_RET_TYPE res = MtDec_ThreadFunc(nextThread); wres = (WRes)(UINT_PTR)res; if (wres != 0) { @@ -1137,3 +1110,5 @@ SRes MtDec_Code(CMtDec *p) } #endif + +#undef PRF diff --git a/C/MtDec.h b/C/MtDec.h index c2da46ae..c28e8d9a 100644 --- a/C/MtDec.h +++ b/C/MtDec.h @@ -1,46 +1,46 @@ /* MtDec.h -- Multi-thread Decoder -2020-03-05 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __MT_DEC_H -#define __MT_DEC_H +#ifndef ZIP7_INC_MT_DEC_H +#define ZIP7_INC_MT_DEC_H #include "7zTypes.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "Threads.h" #endif EXTERN_C_BEGIN -#ifndef _7ZIP_ST +#ifndef Z7_ST -#ifndef _7ZIP_ST - #define MTDEC__THREADS_MAX 32 +#ifndef Z7_ST + #define MTDEC_THREADS_MAX 32 #else - #define MTDEC__THREADS_MAX 1 + #define MTDEC_THREADS_MAX 1 #endif typedef struct { - ICompressProgress *progress; + ICompressProgressPtr progress; SRes res; UInt64 totalInSize; UInt64 totalOutSize; CCriticalSection cs; } CMtProgress; -void MtProgress_Init(CMtProgress *p, ICompressProgress *progress); +void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress); SRes MtProgress_Progress_ST(CMtProgress *p); SRes MtProgress_ProgressAdd(CMtProgress *p, UInt64 inSize, UInt64 outSize); SRes MtProgress_GetError(CMtProgress *p); void MtProgress_SetError(CMtProgress *p, SRes res); -struct _CMtDec; +struct CMtDec; typedef struct { - struct _CMtDec *mtDec; + struct CMtDec_ *mtDec; unsigned index; void *inBuf; @@ -117,7 +117,7 @@ typedef struct -typedef struct _CMtDec +typedef struct CMtDec_ { /* input variables */ @@ -126,11 +126,11 @@ typedef struct _CMtDec // size_t inBlockMax; unsigned numThreadsMax_2; - ISeqInStream *inStream; + ISeqInStreamPtr inStream; // const Byte *inData; // size_t inDataSize; - ICompressProgress *progress; + ICompressProgressPtr progress; ISzAllocPtr alloc; IMtDecCallback2 *mtCallback; @@ -171,11 +171,11 @@ typedef struct _CMtDec unsigned filledThreadStart; unsigned numFilledThreads; - #ifndef _7ZIP_ST + #ifndef Z7_ST BoolInt needInterrupt; UInt64 interruptIndex; CMtProgress mtProgress; - CMtDecThread threads[MTDEC__THREADS_MAX]; + CMtDecThread threads[MTDEC_THREADS_MAX]; #endif } CMtDec; diff --git a/C/Ppmd.h b/C/Ppmd.h index b1987920..66b26266 100644 --- a/C/Ppmd.h +++ b/C/Ppmd.h @@ -1,9 +1,9 @@ /* Ppmd.h -- PPMD codec common code -2021-04-13 : Igor Pavlov : Public domain +2023-03-05 : Igor Pavlov : Public domain This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ -#ifndef __PPMD_H -#define __PPMD_H +#ifndef ZIP7_INC_PPMD_H +#define ZIP7_INC_PPMD_H #include "CpuArch.h" @@ -48,8 +48,10 @@ typedef struct Byte Count; /* Count to next change of Shift */ } CPpmd_See; -#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ - { (p)->Summ = (UInt16)((p)->Summ << 1); (p)->Count = (Byte)(3 << (p)->Shift++); } +#define Ppmd_See_UPDATE(p) \ + { if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ + { (p)->Summ = (UInt16)((p)->Summ << 1); \ + (p)->Count = (Byte)(3 << (p)->Shift++); }} typedef struct diff --git a/C/Ppmd7.c b/C/Ppmd7.c index cf401cb3..6e1307e2 100644 --- a/C/Ppmd7.c +++ b/C/Ppmd7.c @@ -1,5 +1,5 @@ /* Ppmd7.c -- PPMdH codec -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ #include "Precomp.h" @@ -14,7 +14,7 @@ This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ MY_ALIGN(16) static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; MY_ALIGN(16) -static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; +static const UInt16 PPMD7_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; #define MAX_FREQ 124 #define UNIT_SIZE 12 @@ -33,7 +33,7 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x #define ONE_STATE(ctx) Ppmd7Context_OneState(ctx) #define SUFFIX(ctx) CTX((ctx)->Suffix) -typedef CPpmd7_Context * CTX_PTR; +typedef CPpmd7_Context * PPMD7_CTX_PTR; struct CPpmd7_Node_; @@ -107,14 +107,14 @@ BoolInt Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAllocPtr alloc) // ---------- Internal Memory Allocator ---------- /* We can use CPpmd7_Node in list of free units (as in Ppmd8) - But we still need one additional list walk pass in GlueFreeBlocks(). - So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in InsertNode() / RemoveNode() + But we still need one additional list walk pass in Ppmd7_GlueFreeBlocks(). + So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in Ppmd7_InsertNode() / Ppmd7_RemoveNode() */ #define EMPTY_NODE 0 -static void InsertNode(CPpmd7 *p, void *node, unsigned indx) +static void Ppmd7_InsertNode(CPpmd7 *p, void *node, unsigned indx) { *((CPpmd_Void_Ref *)node) = p->FreeList[indx]; // ((CPpmd7_Node *)node)->Next = (CPpmd7_Node_Ref)p->FreeList[indx]; @@ -124,7 +124,7 @@ static void InsertNode(CPpmd7 *p, void *node, unsigned indx) } -static void *RemoveNode(CPpmd7 *p, unsigned indx) +static void *Ppmd7_RemoveNode(CPpmd7 *p, unsigned indx) { CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]); p->FreeList[indx] = *node; @@ -134,32 +134,32 @@ static void *RemoveNode(CPpmd7 *p, unsigned indx) } -static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) +static void Ppmd7_SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) { unsigned i, nu = I2U(oldIndx) - I2U(newIndx); ptr = (Byte *)ptr + U2B(I2U(newIndx)); if (I2U(i = U2I(nu)) != nu) { unsigned k = I2U(--i); - InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); + Ppmd7_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); } - InsertNode(p, ptr, i); + Ppmd7_InsertNode(p, ptr, i); } /* we use CPpmd7_Node_Union union to solve XLC -O2 strict pointer aliasing problem */ -typedef union _CPpmd7_Node_Union +typedef union { CPpmd7_Node Node; CPpmd7_Node_Ref NextRef; } CPpmd7_Node_Union; -/* Original PPmdH (Ppmd7) code uses doubly linked list in GlueFreeBlocks() +/* Original PPmdH (Ppmd7) code uses doubly linked list in Ppmd7_GlueFreeBlocks() we use single linked list similar to Ppmd8 code */ -static void GlueFreeBlocks(CPpmd7 *p) +static void Ppmd7_GlueFreeBlocks(CPpmd7 *p) { /* we use first UInt16 field of 12-bytes UNITs as record type stamp @@ -239,27 +239,27 @@ static void GlueFreeBlocks(CPpmd7 *p) if (nu == 0) continue; for (; nu > 128; nu -= 128, node += 128) - InsertNode(p, node, PPMD_NUM_INDEXES - 1); + Ppmd7_InsertNode(p, node, PPMD_NUM_INDEXES - 1); if (I2U(i = U2I(nu)) != nu) { unsigned k = I2U(--i); - InsertNode(p, node + k, (unsigned)nu - k - 1); + Ppmd7_InsertNode(p, node + k, (unsigned)nu - k - 1); } - InsertNode(p, node, i); + Ppmd7_InsertNode(p, node, i); } } -MY_NO_INLINE -static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) +Z7_NO_INLINE +static void *Ppmd7_AllocUnitsRare(CPpmd7 *p, unsigned indx) { unsigned i; if (p->GlueCount == 0) { - GlueFreeBlocks(p); + Ppmd7_GlueFreeBlocks(p); if (p->FreeList[indx] != 0) - return RemoveNode(p, indx); + return Ppmd7_RemoveNode(p, indx); } i = indx; @@ -277,17 +277,17 @@ static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) while (p->FreeList[i] == 0); { - void *block = RemoveNode(p, i); - SplitBlock(p, block, i, indx); + void *block = Ppmd7_RemoveNode(p, i); + Ppmd7_SplitBlock(p, block, i, indx); return block; } } -static void *AllocUnits(CPpmd7 *p, unsigned indx) +static void *Ppmd7_AllocUnits(CPpmd7 *p, unsigned indx) { if (p->FreeList[indx] != 0) - return RemoveNode(p, indx); + return Ppmd7_RemoveNode(p, indx); { UInt32 numBytes = U2B(I2U(indx)); Byte *lo = p->LoUnit; @@ -297,11 +297,11 @@ static void *AllocUnits(CPpmd7 *p, unsigned indx) return lo; } } - return AllocUnitsRare(p, indx); + return Ppmd7_AllocUnitsRare(p, indx); } -#define MyMem12Cpy(dest, src, num) \ +#define MEM_12_CPY(dest, src, num) \ { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } @@ -315,12 +315,12 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU return oldPtr; if (p->FreeList[i1] != 0) { - void *ptr = RemoveNode(p, i1); - MyMem12Cpy(ptr, oldPtr, newNU); - InsertNode(p, oldPtr, i0); + void *ptr = Ppmd7_RemoveNode(p, i1); + MEM_12_CPY(ptr, oldPtr, newNU) + Ppmd7_InsertNode(p, oldPtr, i0); return ptr; } - SplitBlock(p, oldPtr, i0, i1); + Ppmd7_SplitBlock(p, oldPtr, i0, i1); return oldPtr; } */ @@ -329,14 +329,14 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) { - Ppmd_SET_SUCCESSOR(p, v); + Ppmd_SET_SUCCESSOR(p, v) } -MY_NO_INLINE +Z7_NO_INLINE static -void RestartModel(CPpmd7 *p) +void Ppmd7_RestartModel(CPpmd7 *p) { unsigned i, k; @@ -352,8 +352,8 @@ void RestartModel(CPpmd7 *p) p->PrevSuccess = 0; { - CPpmd7_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ - CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ + CPpmd7_Context *mc = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ + CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd7_AllocUnits(p, PPMD_NUM_INDEXES - 1); */ p->LoUnit += U2B(256 / 2); p->MaxContext = p->MinContext = mc; @@ -391,7 +391,7 @@ void RestartModel(CPpmd7 *p) { unsigned m; UInt16 *dest = p->BinSumm[i] + k; - UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2)); + const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD7_kInitBinEsc[k] / (i + 2)); for (m = 0; m < 64; m += 8) dest[m] = val; } @@ -423,13 +423,13 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) { p->MaxOrder = maxOrder; - RestartModel(p); + Ppmd7_RestartModel(p); } /* - CreateSuccessors() + Ppmd7_CreateSuccessors() It's called when (FoundState->Successor) is RAW-Successor, that is the link to position in Raw text. So we create Context records and write the links to @@ -445,10 +445,10 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder) also it can return pointer to real context of same order, */ -MY_NO_INLINE -static CTX_PTR CreateSuccessors(CPpmd7 *p) +Z7_NO_INLINE +static PPMD7_CTX_PTR Ppmd7_CreateSuccessors(CPpmd7 *p) { - CTX_PTR c = p->MinContext; + PPMD7_CTX_PTR c = p->MinContext; CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); Byte newSym, newFreq; unsigned numPs = 0; @@ -522,15 +522,15 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) do { - CTX_PTR c1; + PPMD7_CTX_PTR c1; /* = AllocContext(p); */ if (p->HiUnit != p->LoUnit) - c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); + c1 = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); else if (p->FreeList[0] != 0) - c1 = (CTX_PTR)RemoveNode(p, 0); + c1 = (PPMD7_CTX_PTR)Ppmd7_RemoveNode(p, 0); else { - c1 = (CTX_PTR)AllocUnitsRare(p, 0); + c1 = (PPMD7_CTX_PTR)Ppmd7_AllocUnitsRare(p, 0); if (!c1) return NULL; } @@ -550,16 +550,16 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p) -#define SwapStates(s) \ +#define SWAP_STATES(s) \ { CPpmd_State tmp = s[0]; s[0] = s[-1]; s[-1] = tmp; } void Ppmd7_UpdateModel(CPpmd7 *p); -MY_NO_INLINE +Z7_NO_INLINE void Ppmd7_UpdateModel(CPpmd7 *p) { CPpmd_Void_Ref maxSuccessor, minSuccessor; - CTX_PTR c, mc; + PPMD7_CTX_PTR c, mc; unsigned s0, ns; @@ -592,7 +592,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) if (s[0].Freq >= s[-1].Freq) { - SwapStates(s); + SWAP_STATES(s) s--; } } @@ -610,10 +610,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) { /* MAX ORDER context */ /* (FoundState->Successor) is RAW-Successor. */ - p->MaxContext = p->MinContext = CreateSuccessors(p); + p->MaxContext = p->MinContext = Ppmd7_CreateSuccessors(p); if (!p->MinContext) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } SetSuccessor(p->FoundState, REF(p->MinContext)); @@ -629,7 +629,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p) p->Text = text; if (text >= p->UnitsStart) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } maxSuccessor = REF(text); @@ -645,10 +645,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) if (minSuccessor <= maxSuccessor) { // minSuccessor is RAW-Successor. So we will create real contexts records: - CTX_PTR cs = CreateSuccessors(p); + PPMD7_CTX_PTR cs = Ppmd7_CreateSuccessors(p); if (!cs) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } minSuccessor = REF(cs); @@ -715,16 +715,16 @@ void Ppmd7_UpdateModel(CPpmd7 *p) unsigned i = U2I(oldNU); if (i != U2I((size_t)oldNU + 1)) { - void *ptr = AllocUnits(p, i + 1); + void *ptr = Ppmd7_AllocUnits(p, i + 1); void *oldPtr; if (!ptr) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } oldPtr = STATS(c); - MyMem12Cpy(ptr, oldPtr, oldNU); - InsertNode(p, oldPtr, i); + MEM_12_CPY(ptr, oldPtr, oldNU) + Ppmd7_InsertNode(p, oldPtr, i); c->Union4.Stats = STATS_REF(ptr); } } @@ -739,10 +739,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p) else { // instead of One-symbol context we create 2-symbol context - CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); + CPpmd_State *s = (CPpmd_State*)Ppmd7_AllocUnits(p, 0); if (!s) { - RestartModel(p); + Ppmd7_RestartModel(p); return; } { @@ -795,8 +795,8 @@ void Ppmd7_UpdateModel(CPpmd7 *p) -MY_NO_INLINE -static void Rescale(CPpmd7 *p) +Z7_NO_INLINE +static void Ppmd7_Rescale(CPpmd7 *p) { unsigned i, adder, sumFreq, escFreq; CPpmd_State *stats = STATS(p->MinContext); @@ -885,7 +885,7 @@ static void Rescale(CPpmd7 *p) *s = *stats; s->Freq = (Byte)freq; // (freq <= 260 / 4) p->FoundState = s; - InsertNode(p, stats, U2I(n0)); + Ppmd7_InsertNode(p, stats, U2I(n0)); return; } @@ -899,13 +899,13 @@ static void Rescale(CPpmd7 *p) { if (p->FreeList[i1] != 0) { - void *ptr = RemoveNode(p, i1); + void *ptr = Ppmd7_RemoveNode(p, i1); p->MinContext->Union4.Stats = STATS_REF(ptr); - MyMem12Cpy(ptr, (const void *)stats, n1); - InsertNode(p, stats, i0); + MEM_12_CPY(ptr, (const void *)stats, n1) + Ppmd7_InsertNode(p, stats, i0); } else - SplitBlock(p, stats, i0, i1); + Ppmd7_SplitBlock(p, stats, i0, i1); } } } @@ -948,9 +948,9 @@ CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq) } -static void NextContext(CPpmd7 *p) +static void Ppmd7_NextContext(CPpmd7 *p) { - CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); + PPMD7_CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); if (p->OrderFall == 0 && (const Byte *)c > p->Text) p->MaxContext = p->MinContext = c; else @@ -967,12 +967,12 @@ void Ppmd7_Update1(CPpmd7 *p) s->Freq = (Byte)freq; if (freq > s[-1].Freq) { - SwapStates(s); + SWAP_STATES(s) p->FoundState = --s; if (freq > MAX_FREQ) - Rescale(p); + Ppmd7_Rescale(p); } - NextContext(p); + Ppmd7_NextContext(p); } @@ -988,8 +988,8 @@ void Ppmd7_Update1_0(CPpmd7 *p) freq += 4; s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); - NextContext(p); + Ppmd7_Rescale(p); + Ppmd7_NextContext(p); } @@ -1000,7 +1000,7 @@ void Ppmd7_UpdateBin(CPpmd7 *p) p->FoundState->Freq = (Byte)(freq + (freq < 128)); p->PrevSuccess = 1; p->RunLength++; - NextContext(p); + Ppmd7_NextContext(p); } */ @@ -1013,7 +1013,7 @@ void Ppmd7_Update2(CPpmd7 *p) p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); + Ppmd7_Rescale(p); Ppmd7_UpdateModel(p); } @@ -1042,8 +1042,8 @@ Last UNIT of array at offset (Size - 12) is root order-0 CPpmd7_Context record. The code can free UNITs memory blocks that were allocated to store CPpmd_State vectors. The code doesn't free UNITs allocated for CPpmd7_Context records. -The code calls RestartModel(), when there is no free memory for allocation. -And RestartModel() changes the state to orignal start state, with full free block. +The code calls Ppmd7_RestartModel(), when there is no free memory for allocation. +And Ppmd7_RestartModel() changes the state to orignal start state, with full free block. The code allocates UNITs with the following order: @@ -1051,14 +1051,14 @@ The code allocates UNITs with the following order: Allocation of 1 UNIT for Context record - from free space (HiUnit) down to (LoUnit) - from FreeList[0] - - AllocUnitsRare() + - Ppmd7_AllocUnitsRare() -AllocUnits() for CPpmd_State vectors: +Ppmd7_AllocUnits() for CPpmd_State vectors: - from FreeList[i] - from free space (LoUnit) up to (HiUnit) - - AllocUnitsRare() + - Ppmd7_AllocUnitsRare() -AllocUnitsRare() +Ppmd7_AllocUnitsRare() - if (GlueCount == 0) { Glue lists, GlueCount = 255, allocate from FreeList[i]] } - loop for all higher sized FreeList[...] lists @@ -1093,8 +1093,8 @@ The PPMd code tries to fulfill the condition: We have (Sum(Stats[].Freq) <= 256 * 124), because of (MAX_FREQ = 124) So (4 = 128 - 124) is average reserve for Escape_Freq for each symbol. If (CPpmd_State::Freq) is not aligned for 4, the reserve can be 5, 6 or 7. -SummFreq and Escape_Freq can be changed in Rescale() and *Update*() functions. -Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Rescale() for +SummFreq and Escape_Freq can be changed in Ppmd7_Rescale() and *Update*() functions. +Ppmd7_Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Ppmd7_Rescale() for max-order context. When the PPMd code still break (Total <= RC::Range) condition in range coder, @@ -1102,3 +1102,21 @@ we have two ways to resolve that problem: 1) we can report error, if we want to keep compatibility with original PPMd code that has no fix for such cases. 2) we can reduce (Total) value to (RC::Range) by reducing (Escape_Freq) part of (Total) value. */ + +#undef MAX_FREQ +#undef UNIT_SIZE +#undef U2B +#undef U2I +#undef I2U +#undef I2U_UInt16 +#undef REF +#undef STATS_REF +#undef CTX +#undef STATS +#undef ONE_STATE +#undef SUFFIX +#undef NODE +#undef EMPTY_NODE +#undef MEM_12_CPY +#undef SUCCESSOR +#undef SWAP_STATES diff --git a/C/Ppmd7.h b/C/Ppmd7.h index d31809ae..d9eb326d 100644 --- a/C/Ppmd7.h +++ b/C/Ppmd7.h @@ -1,11 +1,11 @@ /* Ppmd7.h -- Ppmd7 (PPMdH) compression codec -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.H (2001): Dmitry Shkarin : Public domain */ -#ifndef __PPMD7_H -#define __PPMD7_H +#ifndef ZIP7_INC_PPMD7_H +#define ZIP7_INC_PPMD7_H #include "Ppmd.h" @@ -55,7 +55,7 @@ typedef struct UInt32 Range; UInt32 Code; UInt32 Low; - IByteIn *Stream; + IByteInPtr Stream; } CPpmd7_RangeDec; @@ -66,7 +66,7 @@ typedef struct // Byte _dummy_[3]; UInt64 Low; UInt64 CacheSize; - IByteOut *Stream; + IByteOutPtr Stream; } CPpmd7z_RangeEnc; diff --git a/C/Ppmd7Dec.c b/C/Ppmd7Dec.c index 55d74ff9..83238282 100644 --- a/C/Ppmd7Dec.c +++ b/C/Ppmd7Dec.c @@ -1,5 +1,5 @@ /* Ppmd7Dec.c -- Ppmd7z (PPMdH with 7z Range Coder) Decoder -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.H (2001): Dmitry Shkarin : Public domain */ @@ -8,7 +8,7 @@ This code is based on: #include "Ppmd7.h" -#define kTopValue (1 << 24) +#define kTopValue ((UInt32)1 << 24) #define READ_BYTE(p) IByteIn_Read((p)->Stream) @@ -37,9 +37,9 @@ BoolInt Ppmd7z_RangeDec_Init(CPpmd7_RangeDec *p) #define R (&p->rc.dec) -MY_FORCE_INLINE -// MY_NO_INLINE -static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) +Z7_FORCE_INLINE +// Z7_NO_INLINE +static void Ppmd7z_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size) { @@ -48,18 +48,18 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) RC_NORM_LOCAL(R) } -#define RC_Decode(start, size) RangeDec_Decode(p, start, size); -#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) -#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) +#define RC_Decode(start, size) Ppmd7z_RD_Decode(p, start, size); +#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) +#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) -typedef CPpmd7_Context * CTX_PTR; +// typedef CPpmd7_Context * CTX_PTR; #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) void Ppmd7_UpdateModel(CPpmd7 *p); #define MASK(sym) ((unsigned char *)charMask)[sym] -// MY_FORCE_INLINE +// Z7_FORCE_INLINE // static int Ppmd7z_DecodeSymbol(CPpmd7 *p) { @@ -70,7 +70,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); unsigned i; UInt32 count, hiCnt; - UInt32 summFreq = p->MinContext->Union2.SummFreq; + const UInt32 summFreq = p->MinContext->Union2.SummFreq; @@ -81,7 +81,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) if ((Int32)(count -= s->Freq) < 0) { Byte sym; - RC_DecodeFinal(0, s->Freq); + RC_DecodeFinal(0, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd7_Update1_0(p); @@ -96,7 +96,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) if ((Int32)(count -= (++s)->Freq) < 0) { Byte sym; - RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); + RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd7_Update1(p); @@ -109,10 +109,10 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) return PPMD7_SYM_ERROR; hiCnt -= count; - RC_Decode(hiCnt, summFreq - hiCnt); + RC_Decode(hiCnt, summFreq - hiCnt) p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) // i = p->MinContext->NumStats - 1; // do { MASK((--s)->Symbol) = 0; } while (--i); { @@ -152,7 +152,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) // Ppmd7_UpdateBin(p); { unsigned freq = s->Freq; - CTX_PTR c = CTX(SUCCESSOR(s)); + CPpmd7_Context *c = CTX(SUCCESSOR(s)); sym = s->Symbol; p->FoundState = s; p->PrevSuccess = 1; @@ -176,7 +176,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) R->Range -= size0; RC_NORM_LOCAL(R) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; p->PrevSuccess = 0; } @@ -245,13 +245,13 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) { count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; - }; + } } s--; - RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); + RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) // new (see->Summ) value can overflow over 16-bits in some rare cases - Ppmd_See_Update(see); + Ppmd_See_UPDATE(see) p->FoundState = s; sym = s->Symbol; Ppmd7_Update2(p); @@ -261,7 +261,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p) if (count >= freqSum) return PPMD7_SYM_ERROR; - RC_Decode(hiCnt, freqSum - hiCnt); + RC_Decode(hiCnt, freqSum - hiCnt) // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. // new (see->Summ) value can overflow over 16-bits in some rare cases @@ -295,3 +295,18 @@ Byte *Ppmd7z_DecodeSymbols(CPpmd7 *p, Byte *buf, const Byte *lim) return buf; } */ + +#undef kTopValue +#undef READ_BYTE +#undef RC_NORM_BASE +#undef RC_NORM_1 +#undef RC_NORM +#undef RC_NORM_LOCAL +#undef RC_NORM_REMOTE +#undef R +#undef RC_Decode +#undef RC_DecodeFinal +#undef RC_GetThreshold +#undef CTX +#undef SUCCESSOR +#undef MASK diff --git a/C/Ppmd7Enc.c b/C/Ppmd7Enc.c index 62139c5b..41106bab 100644 --- a/C/Ppmd7Enc.c +++ b/C/Ppmd7Enc.c @@ -1,5 +1,5 @@ /* Ppmd7Enc.c -- Ppmd7z (PPMdH with 7z Range Coder) Encoder -2021-04-13 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on: PPMd var.H (2001): Dmitry Shkarin : Public domain */ @@ -8,7 +8,7 @@ This code is based on: #include "Ppmd7.h" -#define kTopValue (1 << 24) +#define kTopValue ((UInt32)1 << 24) #define R (&p->rc.enc) @@ -20,8 +20,8 @@ void Ppmd7z_Init_RangeEnc(CPpmd7 *p) R->CacheSize = 1; } -MY_NO_INLINE -static void RangeEnc_ShiftLow(CPpmd7 *p) +Z7_NO_INLINE +static void Ppmd7z_RangeEnc_ShiftLow(CPpmd7 *p) { if ((UInt32)R->Low < (UInt32)0xFF000000 || (unsigned)(R->Low >> 32) != 0) { @@ -38,53 +38,53 @@ static void RangeEnc_ShiftLow(CPpmd7 *p) R->Low = (UInt32)((UInt32)R->Low << 8); } -#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; RangeEnc_ShiftLow(p); -#define RC_NORM_1(p) RC_NORM_BASE(p) } -#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} +#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; Ppmd7z_RangeEnc_ShiftLow(p); +#define RC_NORM_1(p) RC_NORM_BASE(p) } +#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} // we must use only one type of Normalization from two: LOCAL or REMOTE #define RC_NORM_LOCAL(p) // RC_NORM(p) #define RC_NORM_REMOTE(p) RC_NORM(p) /* -#define RangeEnc_Encode(p, start, _size_) \ +#define Ppmd7z_RangeEnc_Encode(p, start, _size_) \ { UInt32 size = _size_; \ R->Low += start * R->Range; \ R->Range *= size; \ RC_NORM_LOCAL(p); } */ -MY_FORCE_INLINE -// MY_NO_INLINE -static void RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) +Z7_FORCE_INLINE +// Z7_NO_INLINE +static void Ppmd7z_RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) { R->Low += start * R->Range; R->Range *= size; - RC_NORM_LOCAL(p); + RC_NORM_LOCAL(p) } void Ppmd7z_Flush_RangeEnc(CPpmd7 *p) { unsigned i; for (i = 0; i < 5; i++) - RangeEnc_ShiftLow(p); + Ppmd7z_RangeEnc_ShiftLow(p); } -#define RC_Encode(start, size) RangeEnc_Encode(p, start, size); -#define RC_EncodeFinal(start, size) RC_Encode(start, size); RC_NORM_REMOTE(p); +#define RC_Encode(start, size) Ppmd7z_RangeEnc_Encode(p, start, size); +#define RC_EncodeFinal(start, size) RC_Encode(start, size) RC_NORM_REMOTE(p) #define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) #define SUFFIX(ctx) CTX((ctx)->Suffix) -typedef CPpmd7_Context * CTX_PTR; +// typedef CPpmd7_Context * CTX_PTR; #define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) void Ppmd7_UpdateModel(CPpmd7 *p); #define MASK(sym) ((unsigned char *)charMask)[sym] -MY_FORCE_INLINE +Z7_FORCE_INLINE static void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) { @@ -104,7 +104,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) if (s->Symbol == symbol) { // R->Range /= p->MinContext->Union2.SummFreq; - RC_EncodeFinal(0, s->Freq); + RC_EncodeFinal(0, s->Freq) p->FoundState = s; Ppmd7_Update1_0(p); return; @@ -117,7 +117,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) if ((++s)->Symbol == symbol) { // R->Range /= p->MinContext->Union2.SummFreq; - RC_EncodeFinal(sum, s->Freq); + RC_EncodeFinal(sum, s->Freq) p->FoundState = s; Ppmd7_Update1(p); return; @@ -127,10 +127,10 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) while (--i); // R->Range /= p->MinContext->Union2.SummFreq; - RC_Encode(sum, p->MinContext->Union2.SummFreq - sum); + RC_Encode(sum, p->MinContext->Union2.SummFreq - sum) p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) // MASK(s->Symbol) = 0; // i = p->MinContext->NumStats - 1; // do { MASK((--s)->Symbol) = 0; } while (--i); @@ -153,20 +153,20 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) UInt16 *prob = Ppmd7_GetBinSumm(p); CPpmd_State *s = Ppmd7Context_OneState(p->MinContext); UInt32 pr = *prob; - UInt32 bound = (R->Range >> 14) * pr; + const UInt32 bound = (R->Range >> 14) * pr; pr = PPMD_UPDATE_PROB_1(pr); if (s->Symbol == symbol) { *prob = (UInt16)(pr + (1 << PPMD_INT_BITS)); // RangeEnc_EncodeBit_0(p, bound); R->Range = bound; - RC_NORM_1(p); + RC_NORM_1(p) // p->FoundState = s; // Ppmd7_UpdateBin(p); { - unsigned freq = s->Freq; - CTX_PTR c = CTX(SUCCESSOR(s)); + const unsigned freq = s->Freq; + CPpmd7_Context *c = CTX(SUCCESSOR(s)); p->FoundState = s; p->PrevSuccess = 1; p->RunLength++; @@ -187,7 +187,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) R->Range -= bound; RC_NORM_LOCAL(p) - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) MASK(s->Symbol) = 0; p->PrevSuccess = 0; } @@ -248,14 +248,14 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) do { - unsigned cur = s->Symbol; + const unsigned cur = s->Symbol; if ((int)cur == symbol) { - UInt32 low = sum; - UInt32 freq = s->Freq; + const UInt32 low = sum; + const UInt32 freq = s->Freq; unsigned num2; - Ppmd_See_Update(see); + Ppmd_See_UPDATE(see) p->FoundState = s; sum += escFreq; @@ -279,7 +279,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) R->Range /= sum; - RC_EncodeFinal(low, freq); + RC_EncodeFinal(low, freq) Ppmd7_Update2(p); return; } @@ -289,21 +289,21 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) while (--i); { - UInt32 total = sum + escFreq; + const UInt32 total = sum + escFreq; see->Summ = (UInt16)(see->Summ + total); R->Range /= total; - RC_Encode(sum, escFreq); + RC_Encode(sum, escFreq) } { - CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); + const CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); s--; MASK(s->Symbol) = 0; do { - unsigned sym0 = s2[0].Symbol; - unsigned sym1 = s2[1].Symbol; + const unsigned sym0 = s2[0].Symbol; + const unsigned sym1 = s2[1].Symbol; s2 += 2; MASK(sym0) = 0; MASK(sym1) = 0; @@ -321,3 +321,18 @@ void Ppmd7z_EncodeSymbols(CPpmd7 *p, const Byte *buf, const Byte *lim) Ppmd7z_EncodeSymbol(p, *buf); } } + +#undef kTopValue +#undef WRITE_BYTE +#undef RC_NORM_BASE +#undef RC_NORM_1 +#undef RC_NORM +#undef RC_NORM_LOCAL +#undef RC_NORM_REMOTE +#undef R +#undef RC_Encode +#undef RC_EncodeFinal +#undef SUFFIX +#undef CTX +#undef SUCCESSOR +#undef MASK diff --git a/C/Ppmd7aDec.c b/C/Ppmd7aDec.c index c4245784..55e164e1 100644 --- a/C/Ppmd7aDec.c +++ b/C/Ppmd7aDec.c @@ -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 @@ This code is based on: #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 @@ BoolInt Ppmd7a_RangeDec_Init(CPpmd7_RangeDec *p) #define R (&p->rc.dec) -MY_FORCE_INLINE -// MY_NO_INLINE -static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) +Z7_FORCE_INLINE +// Z7_NO_INLINE +static void Ppmd7a_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size) { start *= R->Range; R->Low += start; @@ -48,9 +48,9 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) RC_NORM_LOCAL(R) } -#define RC_Decode(start, size) RangeDec_Decode(p, start, size); -#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) -#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) +#define RC_Decode(start, size) 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 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); unsigned i; UInt32 count, hiCnt; - UInt32 summFreq = p->MinContext->Union2.SummFreq; + const UInt32 summFreq = p->MinContext->Union2.SummFreq; if (summFreq > R->Range) return PPMD7_SYM_ERROR; @@ -81,7 +81,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) if ((Int32)(count -= s->Freq) < 0) { Byte sym; - RC_DecodeFinal(0, s->Freq); + RC_DecodeFinal(0, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd7_Update1_0(p); @@ -96,7 +96,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) if ((Int32)(count -= (++s)->Freq) < 0) { Byte sym; - RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); + RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd7_Update1(p); @@ -109,10 +109,10 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) return PPMD7_SYM_ERROR; hiCnt -= count; - RC_Decode(hiCnt, summFreq - hiCnt); + RC_Decode(hiCnt, summFreq - hiCnt) p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); - PPMD_SetAllBitsIn256Bytes(charMask); + PPMD_SetAllBitsIn256Bytes(charMask) // i = p->MinContext->NumStats - 1; // do { MASK((--s)->Symbol) = 0; } while (--i); { @@ -176,7 +176,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) 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 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) { count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; - }; + } } s--; - RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); + RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) // new (see->Summ) value can overflow over 16-bits in some rare cases - Ppmd_See_Update(see); + Ppmd_See_UPDATE(see) p->FoundState = s; sym = s->Symbol; Ppmd7_Update2(p); @@ -261,7 +261,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) if (count >= freqSum) return PPMD7_SYM_ERROR; - RC_Decode(hiCnt, freqSum - hiCnt); + RC_Decode(hiCnt, freqSum - hiCnt) // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. // new (see->Summ) value can overflow over 16-bits in some rare cases @@ -277,3 +277,19 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p) 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 --git a/C/Ppmd8.c b/C/Ppmd8.c index fda8b88a..28abf279 100644 --- a/C/Ppmd8.c +++ b/C/Ppmd8.c @@ -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 @@ This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */ 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 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x #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 @@ BoolInt Ppmd8_Alloc(CPpmd8 *p, UInt32 size, ISzAllocPtr alloc) #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 InsertNode(CPpmd8 *p, void *node, unsigned indx) } -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 *RemoveNode(CPpmd8 *p, unsigned indx) } -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 SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx) -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 @@ static void GlueFreeBlocks(CPpmd8 *p) 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 @@ static void *AllocUnitsRare(CPpmd8 *p, unsigned indx) 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 @@ static void *AllocUnits(CPpmd8 *p, unsigned indx) 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 @@ static void *ShrinkUnits(CPpmd8 *p, void *oldPtr, unsigned oldNU, unsigned newNU return oldPtr; if (p->FreeList[i1] != 0) { - void *ptr = RemoveNode(p, i1); - MyMem12Cpy(ptr, oldPtr, newNU); - InsertNode(p, oldPtr, i0); + void *ptr = 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 @@ static void *MoveUnitsUp(CPpmd8 *p, void *oldPtr, unsigned nu) 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 @@ static void ExpandTextArea(CPpmd8 *p) #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 @@ void RestartModel(CPpmd8 *p) 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 @@ void RestartModel(CPpmd8 *p) { s->Symbol = (Byte)i; s->Freq = 1; - SetSuccessor(s, 0); + Ppmd8State_SetSuccessor(s, 0); } } @@ -475,7 +475,7 @@ void RestartModel(CPpmd8 *p) { 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 @@ void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod) { p->MaxOrder = maxOrder; p->RestoreMethod = restoreMethod; - RestartModel(p); + Ppmd8_RestartModel(p); } @@ -531,7 +531,7 @@ Refresh() is called when we remove some symbols (successors) in context. 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 Refresh(CPpmd8 *p, CTX_PTR ctx, unsigned oldNU, unsigned scale) } -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 @@ CutOff() reduces contexts: 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 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) 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 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) 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 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) } 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 @@ RemoveBinContexts() 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 @@ static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order) 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 @@ static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order) { 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 @@ static UInt32 GetUsedMemory(const CPpmd8 *p) #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 @@ static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError 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 @@ static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError -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 @@ static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PT 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 @@ static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PT 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 CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PT } -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 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) ps[numPs++] = p->FoundState; #endif - SetSuccessor(p->FoundState, upBranch); + Ppmd8State_SetSuccessor(p->FoundState, upBranch); p->OrderFall++; for (;;) @@ -985,8 +985,8 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) #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 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) #ifdef PPMD8_FREEZE_SUPPORT ps[numPs++] = s; #endif - SetSuccessor(s, upBranch); + Ppmd8State_SetSuccessor(s, upBranch); p->OrderFall++; } @@ -1022,8 +1022,8 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) 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 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) #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 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) 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 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) if (s[0].Freq >= s[-1].Freq) { - SwapStates(&s[0], &s[-1]); + SWAP_STATES(&s[0], &s[-1]); s--; } } @@ -1112,14 +1112,14 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) } 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) { maxSuccessor = minSuccessor; - RESET_TEXT(0); + RESET_TEXT(0) p->OrderFall = 0; } #endif @@ -1219,7 +1219,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) 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 @@ void Ppmd8_UpdateModel(CPpmd8 *p) -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 @@ static void Rescale(CPpmd8 *p) *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 @@ CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked1, UInt32 *escFreq) } -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 @@ void Ppmd8_Update1(CPpmd8 *p) 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 @@ void Ppmd8_Update1_0(CPpmd8 *p) freq += 4; s->Freq = (Byte)freq; if (freq > MAX_FREQ) - Rescale(p); - NextContext(p); + Ppmd8_Rescale(p); + Ppmd8_NextContext(p); } @@ -1504,7 +1504,7 @@ void Ppmd8_UpdateBin(CPpmd8 *p) p->FoundState->Freq = (Byte)(freq + (freq < 196)); // Ppmd8 (196) p->PrevSuccess = 1; p->RunLength++; - NextContext(p); + Ppmd8_NextContext(p); } */ @@ -1517,7 +1517,7 @@ void Ppmd8_Update2(CPpmd8 *p) 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 @@ void Ppmd8_Update2(CPpmd8 *p) 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 @@ void Ppmd8_Update2(CPpmd8 *p) (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 --git a/C/Ppmd8.h b/C/Ppmd8.h index fe93fe7c..d5bb57e1 100644 --- a/C/Ppmd8.h +++ b/C/Ppmd8.h @@ -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 @@ typedef struct UInt32 Low; union { - IByteIn *In; - IByteOut *Out; + IByteInPtr In; + IByteOutPtr Out; } Stream; Byte Indx2Units[PPMD_NUM_INDEXES + 2]; // +2 for alignment diff --git a/C/Ppmd8Dec.c b/C/Ppmd8Dec.c index d205de28..72d3626e 100644 --- a/C/Ppmd8Dec.c +++ b/C/Ppmd8Dec.c @@ -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 @@ This code is based on: #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 @@ BoolInt Ppmd8_Init_RangeDec(CPpmd8 *p) #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 @@ static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size) RC_NORM_LOCAL(R) } -#define RC_Decode(start, size) RangeDec_Decode(p, start, size); -#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) -#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) +#define RC_Decode(start, size) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) if ((Int32)(count -= s->Freq) < 0) { Byte sym; - RC_DecodeFinal(0, s->Freq); + RC_DecodeFinal(0, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd8_Update1_0(p); @@ -96,7 +96,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) if ((Int32)(count -= (++s)->Freq) < 0) { Byte sym; - RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); + RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq) p->FoundState = s; sym = s->Symbol; Ppmd8_Update1(p); @@ -109,10 +109,10 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) // 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) } } 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p) 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 --git a/C/Ppmd8Enc.c b/C/Ppmd8Enc.c index 32ff8052..9e29ef71 100644 --- a/C/Ppmd8Enc.c +++ b/C/Ppmd8Enc.c @@ -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 @@ This code is based on: #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 @@ void Ppmd8_Flush_RangeEnc(CPpmd8 *p) -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 @@ static void RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total) -#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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) do { - unsigned cur = s->Symbol; + const unsigned cur = s->Symbol; if ((int)cur == symbol) { - UInt32 low = sum; - UInt32 freq = s->Freq; + const UInt32 low = sum; + const UInt32 freq = s->Freq; unsigned num2; - Ppmd_See_Update(see); + Ppmd_See_UPDATE(see) p->FoundState = s; sum += escFreq; @@ -277,9 +277,9 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) } } - 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) { 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 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) } } } + + + + + + + + + +#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 --git a/C/Precomp.h b/C/Precomp.h index e8ff8b40..69afb2ff 100644 --- a/C/Precomp.h +++ b/C/Precomp.h @@ -1,8 +1,8 @@ /* Precomp.h -- StdAfx -2013-11-12 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_PRECOMP_H -#define __7Z_PRECOMP_H +#ifndef ZIP7_INC_PRECOMP_H +#define ZIP7_INC_PRECOMP_H #include "Compiler.h" /* #include "7zTypes.h" */ diff --git a/C/RotateDefs.h b/C/RotateDefs.h index 8f01d1a6..c16b4f8e 100644 --- a/C/RotateDefs.h +++ b/C/RotateDefs.h @@ -1,14 +1,14 @@ /* RotateDefs.h -- Rotate functions -2015-03-25 : Igor Pavlov : Public domain */ +2023-06-18 : Igor Pavlov : Public domain */ -#ifndef __ROTATE_DEFS_H -#define __ROTATE_DEFS_H +#ifndef ZIP7_INC_ROTATE_DEFS_H +#define ZIP7_INC_ROTATE_DEFS_H #ifdef _MSC_VER #include -/* don't use _rotl with MINGW. It can insert slow call to function. */ +/* don't use _rotl with old MINGW. It can insert slow call to function. */ /* #if (_MSC_VER >= 1200) */ #pragma intrinsic(_rotl) @@ -18,12 +18,32 @@ #define rotlFixed(x, n) _rotl((x), (n)) #define rotrFixed(x, n) _rotr((x), (n)) +#if (_MSC_VER >= 1300) +#define Z7_ROTL64(x, n) _rotl64((x), (n)) +#define Z7_ROTR64(x, n) _rotr64((x), (n)) +#else +#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) +#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) +#endif + #else /* new compilers can translate these macros to fast commands. */ +#if defined(__clang__) && (__clang_major__ >= 4) \ + || defined(__GNUC__) && (__GNUC__ >= 5) +/* GCC 4.9.0 and clang 3.5 can recognize more correct version: */ +#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (-(n) & 31))) +#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (-(n) & 31))) +#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (-(n) & 63))) +#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (-(n) & 63))) +#else +/* for old GCC / clang: */ #define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) #define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) +#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) +#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) +#endif #endif diff --git a/C/Sha1.c b/C/Sha1.c index 9665b5b5..fd6c018c 100644 --- a/C/Sha1.c +++ b/C/Sha1.c @@ -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 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l #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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) { 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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) /* 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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) */ #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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) #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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) #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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) #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 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo) #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_InitState(CSha1 *p) 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 @@ void Sha1_Init(CSha1 *p) } -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 @@ void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t nu #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 @@ void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t nu } -#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 @@ void Sha1_Update(CSha1 *p, const Byte *data, size_t size) } { 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 @@ void Sha1_Final(CSha1 *p, Byte *digest) 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_Final(CSha1 *p, Byte *digest) 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 @@ void Sha1_GetBlockDigest(const CSha1 *p, const Byte *data, Byte *destDigest) 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 @@ void Sha1Prepare() 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 --git a/C/Sha1.h b/C/Sha1.h index 345a816a..fecd9d31 100644 --- a/C/Sha1.h +++ b/C/Sha1.h @@ -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 @@ EXTERN_C_BEGIN #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 @@ typedef struct { 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_Final(CSha1 *p, Byte *digest); 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 --git a/C/Sha1Opt.c b/C/Sha1Opt.c index 63132da3..27796aa4 100644 --- a/C/Sha1Opt.c +++ b/C/Sha1Opt.c @@ -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 @@ SHA1 uses: _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 @@ SHA1 uses: #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 @@ SHA1 uses: 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 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t 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 @@ typedef uint32x4_t v128; #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 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t // #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 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t } #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 --git a/C/Sha256.c b/C/Sha256.c index 8b3983ea..018cf6f4 100644 --- a/C/Sha256.c +++ b/C/Sha256.c @@ -1,5 +1,5 @@ /* Sha256.c -- SHA-256 Hash -2021-04-01 : Igor Pavlov : Public domain +2023-04-02 : Igor Pavlov : Public domain This code is based on public domain code from Wei Dai's Crypto++ library. */ #include "Precomp.h" @@ -17,48 +17,48 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */ #ifdef MY_CPU_X86_OR_AMD64 #ifdef _MSC_VER #if _MSC_VER >= 1200 - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #elif defined(__clang__) #if (__clang_major__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #elif defined(__GNUC__) #if (__GNUC__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #elif defined(__INTEL_COMPILER) #if (__INTEL_COMPILER >= 1800) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #endif #elif defined(MY_CPU_ARM_OR_ARM64) #ifdef _MSC_VER #if _MSC_VER >= 1910 - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #elif defined(__clang__) #if (__clang_major__ >= 8) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #elif defined(__GNUC__) #if (__GNUC__ >= 6) // fix that check - #define _SHA_SUPPORTED + #define Z7_COMPILER_SHA256_SUPPORTED #endif #endif #endif -void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); -#ifdef _SHA_SUPPORTED - void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +#ifdef Z7_COMPILER_SHA256_SUPPORTED + void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); - static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; - static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; + static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; + static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS_HW; - #define UPDATE_BLOCKS(p) p->func_UpdateBlocks + #define SHA256_UPDATE_BLOCKS(p) p->func_UpdateBlocks #else - #define UPDATE_BLOCKS(p) Sha256_UpdateBlocks + #define SHA256_UPDATE_BLOCKS(p) Sha256_UpdateBlocks #endif @@ -66,16 +66,16 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) { SHA256_FUNC_UPDATE_BLOCKS func = Sha256_UpdateBlocks; - #ifdef _SHA_SUPPORTED + #ifdef Z7_COMPILER_SHA256_SUPPORTED if (algo != SHA256_ALGO_SW) { if (algo == SHA256_ALGO_DEFAULT) - func = g_FUNC_UPDATE_BLOCKS; + func = g_SHA256_FUNC_UPDATE_BLOCKS; else { if (algo != SHA256_ALGO_HW) return False; - func = g_FUNC_UPDATE_BLOCKS_HW; + func = g_SHA256_FUNC_UPDATE_BLOCKS_HW; if (!func) return False; } @@ -92,17 +92,18 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo) /* define it for speed optimization */ -#ifdef _SFX +#ifdef Z7_SFX #define STEP_PRE 1 #define STEP_MAIN 1 #else #define STEP_PRE 2 #define STEP_MAIN 4 - // #define _SHA256_UNROLL + // #define Z7_SHA256_UNROLL #endif +#undef Z7_SHA256_BIG_W #if STEP_MAIN != 16 - #define _SHA256_BIG_W + #define Z7_SHA256_BIG_W #endif @@ -124,8 +125,8 @@ void Sha256_InitState(CSha256 *p) void Sha256_Init(CSha256 *p) { p->func_UpdateBlocks = - #ifdef _SHA_SUPPORTED - g_FUNC_UPDATE_BLOCKS; + #ifdef Z7_COMPILER_SHA256_SUPPORTED + g_SHA256_FUNC_UPDATE_BLOCKS; #else NULL; #endif @@ -145,7 +146,7 @@ void Sha256_Init(CSha256 *p) #define blk2_main(j, i) s1(w(j, (i)-2)) + w(j, (i)-7) + s0(w(j, (i)-15)) -#ifdef _SHA256_BIG_W +#ifdef Z7_SHA256_BIG_W // we use +i instead of +(i) to change the order to solve CLANG compiler warning for signed/unsigned. #define w(j, i) W[(size_t)(j) + i] #define blk2(j, i) (w(j, i) = w(j, (i)-16) + blk2_main(j, i)) @@ -176,7 +177,7 @@ void Sha256_Init(CSha256 *p) #define R1_PRE(i) T1( W_PRE, i) #define R1_MAIN(i) T1( W_MAIN, i) -#if (!defined(_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) +#if (!defined(Z7_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) #define R2_MAIN(i) \ R1_MAIN(i) \ R1_MAIN(i + 1) \ @@ -185,7 +186,7 @@ void Sha256_Init(CSha256 *p) -#if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 +#if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 #define T4( a,b,c,d,e,f,g,h, wx, i) \ h += S1(e) + Ch(e,f,g) + K[(i)+(size_t)(j)] + wx(i); \ @@ -223,7 +224,7 @@ void Sha256_Init(CSha256 *p) #endif -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); // static extern MY_ALIGN(64) @@ -252,11 +253,11 @@ const UInt32 SHA256_K_ARRAY[64] = { #define K SHA256_K_ARRAY -MY_NO_INLINE -void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) +Z7_NO_INLINE +void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) { UInt32 W - #ifdef _SHA256_BIG_W + #ifdef Z7_SHA256_BIG_W [64]; #else [16]; @@ -266,7 +267,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t UInt32 a,b,c,d,e,f,g,h; - #if !defined(_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) + #if !defined(Z7_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) UInt32 tmp; #endif @@ -297,12 +298,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t #else - R1_PRE(0); + R1_PRE(0) #if STEP_PRE >= 2 - R1_PRE(1); + R1_PRE(1) #if STEP_PRE >= 4 - R1_PRE(2); - R1_PRE(3); + R1_PRE(2) + R1_PRE(3) #endif #endif @@ -311,32 +312,32 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t for (j = 16; j < 64; j += STEP_MAIN) { - #if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 + #if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8 #if STEP_MAIN < 8 - R4_MAIN(0); + R4_MAIN(0) #else - R8_MAIN(0); + R8_MAIN(0) #if STEP_MAIN == 16 - R8_MAIN(8); + R8_MAIN(8) #endif #endif #else - R1_MAIN(0); + R1_MAIN(0) #if STEP_MAIN >= 2 - R1_MAIN(1); + R1_MAIN(1) #if STEP_MAIN >= 4 - R2_MAIN(2); + R2_MAIN(2) #if STEP_MAIN >= 8 - R2_MAIN(4); - R2_MAIN(6); + R2_MAIN(4) + R2_MAIN(6) #if STEP_MAIN >= 16 - R2_MAIN(8); - R2_MAIN(10); - R2_MAIN(12); - R2_MAIN(14); + R2_MAIN(8) + R2_MAIN(10) + R2_MAIN(12) + R2_MAIN(14) #endif #endif #endif @@ -367,7 +368,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t #undef s1 #undef K -#define Sha256_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) +#define Sha256_UpdateBlock(p) SHA256_UPDATE_BLOCKS(p)(p->state, p->buffer, 1) void Sha256_Update(CSha256 *p, const Byte *data, size_t size) { @@ -397,7 +398,7 @@ void Sha256_Update(CSha256 *p, const Byte *data, size_t size) } { size_t numBlocks = size >> 6; - UPDATE_BLOCKS(p)(p->state, data, numBlocks); + SHA256_UPDATE_BLOCKS(p)(p->state, data, numBlocks); size &= 0x3F; if (size == 0) return; @@ -441,8 +442,8 @@ void Sha256_Final(CSha256 *p, Byte *digest) { UInt64 numBits = (p->count << 3); - SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); - SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); + SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)) + SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)) } Sha256_UpdateBlock(p); @@ -451,8 +452,8 @@ void Sha256_Final(CSha256 *p, Byte *digest) { UInt32 v0 = p->state[i]; UInt32 v1 = p->state[(size_t)i + 1]; - SetBe32(digest , v0); - SetBe32(digest + 4, v1); + SetBe32(digest , v0) + SetBe32(digest + 4, v1) digest += 8; } @@ -460,9 +461,9 @@ void Sha256_Final(CSha256 *p, Byte *digest) } -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 @@ void Sha256Prepare() // printf("\n========== HW SHA256 ======== \n"); f = f_hw = Sha256_UpdateBlocks_HW; } - g_FUNC_UPDATE_BLOCKS = f; - g_FUNC_UPDATE_BLOCKS_HW = f_hw; + g_SHA256_FUNC_UPDATE_BLOCKS = f; + g_SHA256_FUNC_UPDATE_BLOCKS_HW = f_hw; #endif } + +#undef S0 +#undef S1 +#undef s0 +#undef s1 +#undef Ch +#undef Maj +#undef W_MAIN +#undef W_PRE +#undef w +#undef blk2_main +#undef blk2 +#undef T1 +#undef T4 +#undef T8 +#undef R1_PRE +#undef R1_MAIN +#undef R2_MAIN +#undef R4 +#undef R4_PRE +#undef R4_MAIN +#undef R8 +#undef R8_PRE +#undef R8_MAIN +#undef STEP_PRE +#undef STEP_MAIN +#undef Z7_SHA256_BIG_W +#undef Z7_SHA256_UNROLL +#undef Z7_COMPILER_SHA256_SUPPORTED diff --git a/C/Sha256.h b/C/Sha256.h index aa38501e..9e042232 100644 --- a/C/Sha256.h +++ b/C/Sha256.h @@ -1,8 +1,8 @@ /* Sha256.h -- SHA-256 Hash -2021-01-01 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_SHA256_H -#define __7Z_SHA256_H +#ifndef ZIP7_INC_SHA256_H +#define ZIP7_INC_SHA256_H #include "7zTypes.h" @@ -14,7 +14,7 @@ EXTERN_C_BEGIN #define SHA256_BLOCK_SIZE (SHA256_NUM_BLOCK_WORDS * 4) #define SHA256_DIGEST_SIZE (SHA256_NUM_DIGEST_WORDS * 4) -typedef void (MY_FAST_CALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); +typedef void (Z7_FASTCALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); /* if (the system supports different SHA256 code implementations) @@ -34,7 +34,7 @@ typedef struct { SHA256_FUNC_UPDATE_BLOCKS func_UpdateBlocks; UInt64 count; - UInt64 __pad_2[2]; + UInt64 _pad_2[2]; UInt32 state[SHA256_NUM_DIGEST_WORDS]; Byte buffer[SHA256_BLOCK_SIZE]; @@ -62,7 +62,7 @@ void Sha256_Final(CSha256 *p, Byte *digest); -// void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); +// void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); /* call Sha256Prepare() once at program start. diff --git a/C/Sha256Opt.c b/C/Sha256Opt.c index decc1382..e4465e3e 100644 --- a/C/Sha256Opt.c +++ b/C/Sha256Opt.c @@ -1,7 +1,9 @@ /* Sha256Opt.c -- SHA-256 optimized code for SHA-256 hardware instructions -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" +#include "Compiler.h" +#include "CpuArch.h" #if defined(_MSC_VER) #if (_MSC_VER < 1900) && (_MSC_VER >= 1200) @@ -9,41 +11,26 @@ #endif #endif -#include "CpuArch.h" - #ifdef MY_CPU_X86_OR_AMD64 - #if defined(__clang__) - #if (__clang_major__ >= 8) // fix that check + #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1600) // fix that check #define USE_HW_SHA - #ifndef __SHA__ - #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) - #if defined(_MSC_VER) - // SSSE3: for clang-cl: - #include - #define __SHA__ - #endif - #endif - - #endif - #elif defined(__GNUC__) - #if (__GNUC__ >= 8) // fix that check + #elif defined(Z7_LLVM_CLANG_VERSION) && (Z7_LLVM_CLANG_VERSION >= 30800) \ + || defined(Z7_APPLE_CLANG_VERSION) && (Z7_APPLE_CLANG_VERSION >= 50100) \ + || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40900) #define USE_HW_SHA - #ifndef __SHA__ + #if !defined(_INTEL_COMPILER) + // icc defines __GNUC__, but icc doesn't support __attribute__(__target__) + #if !defined(__SHA__) || !defined(__SSSE3__) #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) - // #pragma GCC target("sha,ssse3") #endif - #endif - #elif defined(__INTEL_COMPILER) - #if (__INTEL_COMPILER >= 1800) // fix that check - #define USE_HW_SHA - #endif + #endif #elif defined(_MSC_VER) #ifdef USE_MY_MM #define USE_VER_MIN 1300 #else - #define USE_VER_MIN 1910 + #define USE_VER_MIN 1900 #endif - #if _MSC_VER >= USE_VER_MIN + #if (_MSC_VER >= USE_VER_MIN) #define USE_HW_SHA #endif #endif @@ -52,16 +39,19 @@ #ifdef USE_HW_SHA // #pragma message("Sha256 HW") -// #include -#if !defined(_MSC_VER) || (_MSC_VER >= 1900) +// sse/sse2/ssse3: +#include +// sha*: #include -#else -#include -#if defined(_MSC_VER) && (_MSC_VER >= 1600) -// #include -#endif +#if defined (__clang__) && defined(_MSC_VER) + // #if !defined(__SSSE3__) + // #endif + #if !defined(__SHA__) + #include + #endif +#else #ifdef USE_MY_MM #include "My_mm.h" @@ -98,9 +88,9 @@ const UInt32 SHA256_K_ARRAY[64]; #define K SHA256_K_ARRAY -#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); -#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); -#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); +#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); +#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); +#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); #define LOAD_SHUFFLE(m, k) \ @@ -112,7 +102,7 @@ const UInt32 SHA256_K_ARRAY[64]; #define SM2(g0, g1, g2, g3) \ tmp = _mm_alignr_epi8(g1, g0, 4); \ - ADD_EPI32(g2, tmp); \ + ADD_EPI32(g2, tmp) \ SHA25G_MSG2(g2, g1); \ // #define LS0(k, g0, g1, g2, g3) LOAD_SHUFFLE(g0, k) @@ -138,16 +128,16 @@ const UInt32 SHA256_K_ARRAY[64]; // We use scheme with 3 rounds ahead for SHA256_MSG1 / 2 rounds ahead for SHA256_MSG2 #define R4(k, g0, g1, g2, g3, OP0, OP1) \ - RND2_0(g0, k); \ - OP0(g0, g1, g2, g3); \ - RND2_1; \ - OP1(g0, g1, g2, g3); \ + RND2_0(g0, k) \ + OP0(g0, g1, g2, g3) \ + RND2_1 \ + OP1(g0, g1, g2, g3) \ #define R16(k, OP0, OP1, OP2, OP3, OP4, OP5, OP6, OP7) \ - R4 ( (k)*4+0, m0, m1, m2, m3, OP0, OP1 ) \ - R4 ( (k)*4+1, m1, m2, m3, m0, OP2, OP3 ) \ - R4 ( (k)*4+2, m2, m3, m0, m1, OP4, OP5 ) \ - R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ + R4 ( (k)*4+0, m0,m1,m2,m3, OP0, OP1 ) \ + R4 ( (k)*4+1, m1,m2,m3,m0, OP2, OP3 ) \ + R4 ( (k)*4+2, m2,m3,m0,m1, OP4, OP5 ) \ + R4 ( (k)*4+3, m3,m0,m1,m2, OP6, OP7 ) \ #define PREPARE_STATE \ tmp = _mm_shuffle_epi32(state0, 0x1B); /* abcd */ \ @@ -157,11 +147,11 @@ const UInt32 SHA256_K_ARRAY[64]; state1 = _mm_unpackhi_epi64(state1, tmp); /* abef */ \ -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); #ifdef ATTRIB_SHA ATTRIB_SHA #endif -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) { const __m128i mask = _mm_set_epi32(0x0c0d0e0f, 0x08090a0b, 0x04050607, 0x00010203); __m128i tmp; @@ -192,13 +182,13 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size - R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ); - R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); - R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); - R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ); + R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ) + R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) + R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ) + R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ) - ADD_EPI32(state0, state0_save); - ADD_EPI32(state1, state1_save); + ADD_EPI32(state0, state0_save) + ADD_EPI32(state1, state1_save) data += 64; } @@ -298,11 +288,11 @@ const UInt32 SHA256_K_ARRAY[64]; R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); #ifdef ATTRIB_SHA ATTRIB_SHA #endif -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) { v128 state0, state1; @@ -353,12 +343,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size // #include // #include "Sha256.h" -void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); #pragma message("Sha256 HW-SW stub was used") -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); -void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); +void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) { Sha256_UpdateBlocks(state, data, numBlocks); /* @@ -371,3 +361,26 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size } #endif + + + +#undef K +#undef RND2 +#undef RND2_0 +#undef RND2_1 + +#undef MY_rev32_for_LE +#undef NNN +#undef LOAD_128 +#undef STORE_128 +#undef LOAD_SHUFFLE +#undef SM1 +#undef SM2 + +#undef NNN +#undef R4 +#undef R16 +#undef PREPARE_STATE +#undef USE_HW_SHA +#undef ATTRIB_SHA +#undef USE_VER_MIN diff --git a/C/Sort.h b/C/Sort.h index 2e2963a2..1817b652 100644 --- a/C/Sort.h +++ b/C/Sort.h @@ -1,8 +1,8 @@ /* Sort.h -- Sort functions -2014-04-05 : Igor Pavlov : Public domain */ +2023-03-05 : Igor Pavlov : Public domain */ -#ifndef __7Z_SORT_H -#define __7Z_SORT_H +#ifndef ZIP7_INC_SORT_H +#define ZIP7_INC_SORT_H #include "7zTypes.h" diff --git a/C/SwapBytes.c b/C/SwapBytes.c new file mode 100644 index 00000000..7901bbaa --- /dev/null +++ b/C/SwapBytes.c @@ -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 --git a/C/SwapBytes.h b/C/SwapBytes.h new file mode 100644 index 00000000..d4424673 --- /dev/null +++ b/C/SwapBytes.h @@ -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 --git a/C/Threads.c b/C/Threads.c index 58eb90ff..cf52bd30 100644 --- a/C/Threads.c +++ b/C/Threads.c @@ -1,5 +1,5 @@ /* Threads.c -- multithreading library -2021-12-21 : Igor Pavlov : Public domain */ +2023-03-04 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -11,9 +11,9 @@ #include "Threads.h" -static WRes GetError() +static WRes GetError(void) { - DWORD res = GetLastError(); + const DWORD res = GetLastError(); return res ? (WRes)res : 1; } @@ -173,6 +173,9 @@ WRes CriticalSection_Init(CCriticalSection *p) Windows XP, 2003 : can raise a STATUS_NO_MEMORY exception Windows Vista+ : no exceptions */ #ifdef _MSC_VER + #ifdef __clang__ + #pragma GCC diagnostic ignored "-Wlanguage-extension-token" + #endif __try #endif { @@ -193,18 +196,26 @@ WRes CriticalSection_Init(CCriticalSection *p) // ---------- POSIX ---------- #ifndef __APPLE__ -#ifndef _7ZIP_AFFINITY_DISABLE +#ifndef Z7_AFFINITY_DISABLE // _GNU_SOURCE can be required for pthread_setaffinity_np() / CPU_ZERO / CPU_SET +// clang < 3.6 : unknown warning group '-Wreserved-id-macro' +// clang 3.6 - 12.01 : gives warning "macro name is a reserved identifier" +// clang >= 13 : do not give warning +#if !defined(_GNU_SOURCE) + #if defined(__clang__) && (__clang_major__ >= 4) && (__clang_major__ <= 12) + #pragma GCC diagnostic ignored "-Wreserved-id-macro" + #endif #define _GNU_SOURCE -#endif -#endif +#endif // !defined(_GNU_SOURCE) +#endif // Z7_AFFINITY_DISABLE +#endif // __APPLE__ #include "Threads.h" #include #include #include -#ifdef _7ZIP_AFFINITY_SUPPORTED +#ifdef Z7_AFFINITY_SUPPORTED // #include #endif @@ -212,15 +223,12 @@ WRes CriticalSection_Init(CCriticalSection *p) // #include // #define PRF(p) p #define PRF(p) - -#define Print(s) PRF(printf("\n%s\n", s)) - -// #include +#define Print(s) PRF(printf("\n%s\n", s);) WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, const CCpuSet *cpuSet) { // new thread in Posix probably inherits affinity from parrent thread - Print("Thread_Create_With_CpuSet"); + Print("Thread_Create_With_CpuSet") pthread_attr_t attr; int ret; @@ -228,7 +236,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, p->_created = 0; - RINOK(pthread_attr_init(&attr)); + RINOK(pthread_attr_init(&attr)) ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); @@ -236,7 +244,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, { if (cpuSet) { - #ifdef _7ZIP_AFFINITY_SUPPORTED + #ifdef Z7_AFFINITY_SUPPORTED /* printf("\n affinity :"); @@ -292,7 +300,7 @@ WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param) WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, CAffinityMask affinity) { - Print("Thread_Create_WithAffinity"); + Print("Thread_Create_WithAffinity") CCpuSet cs; unsigned i; CpuSet_Zero(&cs); @@ -312,7 +320,7 @@ WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param WRes Thread_Close(CThread *p) { - // Print("Thread_Close"); + // Print("Thread_Close") int ret; if (!p->_created) return 0; @@ -326,7 +334,7 @@ WRes Thread_Close(CThread *p) WRes Thread_Wait_Close(CThread *p) { - // Print("Thread_Wait_Close"); + // Print("Thread_Wait_Close") void *thread_return; int ret; if (!p->_created) @@ -343,8 +351,8 @@ WRes Thread_Wait_Close(CThread *p) static WRes Event_Create(CEvent *p, int manualReset, int signaled) { - RINOK(pthread_mutex_init(&p->_mutex, NULL)); - RINOK(pthread_cond_init(&p->_cond, NULL)); + RINOK(pthread_mutex_init(&p->_mutex, NULL)) + RINOK(pthread_cond_init(&p->_cond, NULL)) p->_manual_reset = manualReset; p->_state = (signaled ? True : False); p->_created = 1; @@ -363,7 +371,7 @@ WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) WRes Event_Set(CEvent *p) { - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) p->_state = True; int res1 = pthread_cond_broadcast(&p->_cond); int res2 = pthread_mutex_unlock(&p->_mutex); @@ -372,14 +380,14 @@ WRes Event_Set(CEvent *p) WRes Event_Reset(CEvent *p) { - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) p->_state = 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 @@ WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount) { if (initCount > maxCount || maxCount < 1) return EINVAL; - RINOK(pthread_mutex_init(&p->_mutex, NULL)); - RINOK(pthread_cond_init(&p->_cond, NULL)); + RINOK(pthread_mutex_init(&p->_mutex, NULL)) + RINOK(pthread_cond_init(&p->_cond, NULL)) p->_count = initCount; p->_maxCount = maxCount; p->_created = 1; @@ -448,7 +456,7 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) if (releaseCount < 1) return EINVAL; - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) newCount = p->_count + releaseCount; if (newCount > p->_maxCount) @@ -458,13 +466,13 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) p->_count = newCount; ret = pthread_cond_broadcast(&p->_cond); } - RINOK(pthread_mutex_unlock(&p->_mutex)); + RINOK(pthread_mutex_unlock(&p->_mutex)) return ret; } WRes Semaphore_Wait(CSemaphore *p) { - RINOK(pthread_mutex_lock(&p->_mutex)); + RINOK(pthread_mutex_lock(&p->_mutex)) while (p->_count < 1) { pthread_cond_wait(&p->_cond, &p->_mutex); @@ -489,7 +497,7 @@ WRes Semaphore_Close(CSemaphore *p) WRes CriticalSection_Init(CCriticalSection *p) { - // Print("CriticalSection_Init"); + // Print("CriticalSection_Init") if (!p) return EINTR; return pthread_mutex_init(&p->_mutex, NULL); @@ -497,7 +505,7 @@ WRes CriticalSection_Init(CCriticalSection *p) void CriticalSection_Enter(CCriticalSection *p) { - // Print("CriticalSection_Enter"); + // Print("CriticalSection_Enter") if (p) { // int ret = @@ -507,7 +515,7 @@ void CriticalSection_Enter(CCriticalSection *p) void CriticalSection_Leave(CCriticalSection *p) { - // Print("CriticalSection_Leave"); + // Print("CriticalSection_Leave") if (p) { // int ret = @@ -517,7 +525,7 @@ void CriticalSection_Leave(CCriticalSection *p) void CriticalSection_Delete(CCriticalSection *p) { - // Print("CriticalSection_Delete"); + // Print("CriticalSection_Delete") if (p) { // int ret = @@ -527,14 +535,28 @@ void CriticalSection_Delete(CCriticalSection *p) LONG InterlockedIncrement(LONG volatile *addend) { - // Print("InterlockedIncrement"); + // Print("InterlockedIncrement") #ifdef USE_HACK_UNSAFE_ATOMIC LONG val = *addend + 1; *addend = val; return val; #else + + #if defined(__clang__) && (__clang_major__ >= 8) + #pragma GCC diagnostic ignored "-Watomic-implicit-seq-cst" + #endif return __sync_add_and_fetch(addend, 1); #endif } #endif // _WIN32 + +WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p) +{ + if (Event_IsCreated(p)) + return Event_Reset(p); + return AutoResetEvent_CreateNotSignaled(p); +} + +#undef PRF +#undef Print diff --git a/C/Threads.h b/C/Threads.h index 89ecb92b..4028464a 100644 --- a/C/Threads.h +++ b/C/Threads.h @@ -1,18 +1,19 @@ /* Threads.h -- multithreading library -2021-12-21 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __7Z_THREADS_H -#define __7Z_THREADS_H +#ifndef ZIP7_INC_THREADS_H +#define ZIP7_INC_THREADS_H #ifdef _WIN32 -#include +#include "7zWindows.h" + #else #if defined(__linux__) #if !defined(__APPLE__) && !defined(_AIX) && !defined(__ANDROID__) -#ifndef _7ZIP_AFFINITY_DISABLE -#define _7ZIP_AFFINITY_SUPPORTED -// #pragma message(" ==== _7ZIP_AFFINITY_SUPPORTED") +#ifndef Z7_AFFINITY_DISABLE +#define Z7_AFFINITY_SUPPORTED +// #pragma message(" ==== Z7_AFFINITY_SUPPORTED") // #define _GNU_SOURCE #endif #endif @@ -33,7 +34,7 @@ WRes Handle_WaitObject(HANDLE h); typedef HANDLE CThread; -#define Thread_Construct(p) { *(p) = NULL; } +#define Thread_CONSTRUCT(p) { *(p) = NULL; } #define Thread_WasCreated(p) (*(p) != NULL) #define Thread_Close(p) HandlePtr_Close(p) // #define Thread_Wait(p) Handle_WaitObject(*(p)) @@ -52,42 +53,46 @@ typedef #endif THREAD_FUNC_RET_TYPE; +#define THREAD_FUNC_RET_ZERO 0 + typedef DWORD_PTR CAffinityMask; typedef DWORD_PTR CCpuSet; -#define CpuSet_Zero(p) { *(p) = 0; } -#define CpuSet_Set(p, cpu) { *(p) |= ((DWORD_PTR)1 << (cpu)); } +#define CpuSet_Zero(p) *(p) = (0) +#define CpuSet_Set(p, cpu) *(p) |= ((DWORD_PTR)1 << (cpu)) #else // _WIN32 -typedef struct _CThread +typedef struct { pthread_t _tid; int _created; } CThread; -#define Thread_Construct(p) { (p)->_tid = 0; (p)->_created = 0; } -#define Thread_WasCreated(p) ((p)->_created != 0) +#define Thread_CONSTRUCT(p) { (p)->_tid = 0; (p)->_created = 0; } +#define Thread_WasCreated(p) ((p)->_created != 0) WRes Thread_Close(CThread *p); // #define Thread_Wait Thread_Wait_Close typedef void * THREAD_FUNC_RET_TYPE; +#define THREAD_FUNC_RET_ZERO NULL + typedef UInt64 CAffinityMask; -#ifdef _7ZIP_AFFINITY_SUPPORTED +#ifdef Z7_AFFINITY_SUPPORTED typedef cpu_set_t CCpuSet; -#define CpuSet_Zero(p) CPU_ZERO(p) -#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) -#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) +#define CpuSet_Zero(p) CPU_ZERO(p) +#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) +#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) #else typedef UInt64 CCpuSet; -#define CpuSet_Zero(p) { *(p) = 0; } -#define CpuSet_Set(p, cpu) { *(p) |= ((UInt64)1 << (cpu)); } -#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) +#define CpuSet_Zero(p) *(p) = (0) +#define CpuSet_Set(p, cpu) *(p) |= ((UInt64)1 << (cpu)) +#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) #endif @@ -95,7 +100,7 @@ typedef UInt64 CCpuSet; #endif // _WIN32 -#define THREAD_FUNC_CALL_TYPE MY_STD_CALL +#define THREAD_FUNC_CALL_TYPE Z7_STDCALL #if defined(_WIN32) && defined(__GNUC__) /* GCC compiler for x86 32-bit uses the rule: @@ -187,6 +192,7 @@ WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled); WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p); WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled); WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p); + WRes Event_Set(CEvent *p); WRes Event_Reset(CEvent *p); WRes Event_Wait(CEvent *p); @@ -227,6 +233,8 @@ LONG InterlockedIncrement(LONG volatile *addend); #endif // _WIN32 +WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p); + EXTERN_C_END #endif diff --git a/C/Util/7z/7z.dsp b/C/Util/7z/7z.dsp index be0f0a74..11e1b03e 100644 --- a/C/Util/7z/7z.dsp +++ b/C/Util/7z/7z.dsp @@ -42,7 +42,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\7zTypes.h # 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 --git a/C/Util/7z/7zMain.c b/C/Util/7z/7zMain.c index 9d555098..547920ac 100644 --- a/C/Util/7z/7zMain.c +++ b/C/Util/7z/7zMain.c @@ -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 @@ static int Buf_EnsureSize(CBuf *dest, size_t size) } #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 @@ static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim) if (val < 0x80) continue; - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { size++; continue; @@ -90,7 +90,7 @@ static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim) if (val >= 0xD800 && val < 0xDC00 && src != srcLim) { - UInt32 c2 = *src; + const UInt32 c2 = *src; if (c2 >= 0xDC00 && c2 < 0xE000) { src++; @@ -119,33 +119,33 @@ static Byte *Utf16_To_Utf8(Byte *dest, const UInt16 *src, const UInt16 *srcLim) 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 @@ static SRes Utf16_To_Utf8Buf(CBuf *dest, const UInt16 *src, size_t srcLen) #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 @@ static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s 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 @@ static WRes MyCreateDir(const UInt16 *name) 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 @@ static WRes OutFile_OpenUtf16(CSzFile *p, const UInt16 *name) 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 @@ static SRes PrintString(const UInt16 *s) 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 @@ typedef struct _FILETIME 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 @@ static BOOL WINAPI FileTimeToLocalFileTime(const FILETIME *fileTime, FILETIME *l { 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 const UInt64 kUnixTimeOffset = 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 @@ static void FILETIME_To_timespec(const FILETIME *ft, struct MY_ST_TIMESPEC *ts) 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 @@ static WRes Set_File_FILETIME(const UInt16 *name, const FILETIME *mTime) 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 @@ static void ConvertFileTimeToString(const CNtfsFileTime *nTime, char *s) 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 @@ static void ConvertFileTimeToString(const CNtfsFileTime *nTime, char *s) UIntToStr_2(s, sec); s[2] = 0; } -static void PrintLF() +static void PrintLF(void) { Print("\n"); } @@ -541,7 +541,7 @@ static void GetAttribString(UInt32 wa, BoolInt isDir, char *s) // #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 @@ int MY_CDECL main(int numargs, char *args[]) allocImp = g_Alloc; allocTempImp = g_Alloc; + // allocTempImp = g_Alloc_temp; { WRes wres = @@ -611,7 +612,7 @@ int MY_CDECL main(int numargs, char *args[]) { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -767,7 +768,7 @@ int MY_CDECL main(int numargs, char *args[]) } 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 @@ int MY_CDECL main(int numargs, char *args[]) 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 @@ int MY_CDECL main(int numargs, char *args[]) #endif { - WRes wres = File_Close(&outFile); + const WRes wres = File_Close(&outFile); if (wres != 0) { PrintError_WRes("cannot close output file", wres); diff --git a/C/Util/7z/Precomp.h b/C/Util/7z/Precomp.h index 588a66f7..bc8fa219 100644 --- a/C/Util/7z/Precomp.h +++ b/C/Util/7z/Precomp.h @@ -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 --git a/C/Util/7z/makefile b/C/Util/7z/makefile index 9a49fd51..dfc560e9 100644 --- a/C/Util/7z/makefile +++ b/C/Util/7z/makefile @@ -1,4 +1,4 @@ -CFLAGS = $(CFLAGS) -D_7ZIP_PPMD_SUPPPORT +CFLAGS = $(CFLAGS) -DZ7_PPMD_SUPPORT -DZ7_EXTRACT_ONLY PROG = 7zDec.exe diff --git a/C/Util/7z/makefile.gcc b/C/Util/7z/makefile.gcc index 4263d675..f48d3621 100644 --- a/C/Util/7z/makefile.gcc +++ b/C/Util/7z/makefile.gcc @@ -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 @@ OBJS = \ $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 --git a/C/Util/7zipInstall/7zipInstall.c b/C/Util/7zipInstall/7zipInstall.c index 8c383573..e1092f5b 100644 --- a/C/Util/7zipInstall/7zipInstall.c +++ b/C/Util/7zipInstall/7zipInstall.c @@ -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 Z7_7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR) +#define Z7_7ZIP_DLL_VER_COMPAT ((16 << 16) | 3) -#define _7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR) -#define _7ZIP_DLL_VER_COMPAT ((16 << 16) | 3) - -static LPCSTR const k_7zip = "7-Zip-Zstandard"; +static LPCSTR const k_7zip = "7-Zip"; static LPCWSTR const k_Reg_Software_7zip = L"Software\\7-Zip-Zstandard"; -// #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 ZS " LLL(MY_VERSION) +#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_7zip_Setup = k_7zip_with_Ver L" Setup"; 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 @@ -103,7 +124,7 @@ static LPCWSTR const k_Reg_Path32 = L"Path" #define k_Reg_WOW_Flag_32 0 #endif -#define k_7zip_CLSID L"{23170F69-20BB-278A-1000-000100020000}" +#define k_7zip_CLSID L"{23170F69-40C1-278A-1000-000100020000}" static LPCWSTR const k_Reg_CLSID_7zip = L"CLSID\\" k_7zip_CLSID; static LPCWSTR const k_Reg_CLSID_7zip_Inproc = L"CLSID\\" k_7zip_CLSID L"\\InprocServer32"; @@ -126,8 +147,6 @@ static WCHAR cmdError[MAX_PATH + 4]; 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 @@ static DWORD GetFileVersion(LPCWSTR s) 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 int ReverseFind_PathSepar(const wchar_t *s) } } -static WRes CreateComplexDir() +static WRes CreateComplexDir(void) { WCHAR s[MAX_PATH + 10]; @@ -287,7 +309,7 @@ static WRes CreateComplexDir() { 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 @@ static WRes CreateComplexDir() if (len == 1) return 0; s[pos] = 0; - len = pos; + len = (unsigned)pos; } } @@ -309,7 +331,7 @@ static WRes CreateComplexDir() 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 @@ static WRes CreateComplexDir() 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 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest) { 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_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest) 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 @@ static void NormalizePrefix(WCHAR *s) for (;; i++) { - wchar_t c = s[i]; + const wchar_t c = s[i]; if (c == 0) break; if (c == '/') @@ -587,7 +609,7 @@ static LPCWSTR FindSubString(LPCWSTR s1, const char *s2) 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)) @@ -602,15 +624,15 @@ static LPCWSTR FindSubString(LPCWSTR s1, const char *s2) static void Set7zipPostfix(WCHAR *s) { NormalizePrefix(s); - if (FindSubString(s, "7-Zip-Zstandard")) + if (FindSubString(s, "7-Zip")) return; - CatAscii(s, "7-Zip-Zstandard\\"); + CatAscii(s, "7-Zip\\"); } static int Install(void); -static void OnClose() +static void OnClose(void) { if (g_Install_was_Pressed && !g_Finished) { @@ -624,7 +646,13 @@ static void OnClose() 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 @@ static LONG SetRegKey_Path2(HKEY parentKey) return res; } -static void SetRegKey_Path() +static void SetRegKey_Path(void) { SetRegKey_Path2(HKEY_CURRENT_USER); SetRegKey_Path2(HKEY_LOCAL_MACHINE); @@ -803,7 +831,7 @@ static void SetShellProgramsGroup(HWND hwndOwner) for (k = 0; k < 2; k++) { CpyAscii(link + baseLen, k == 0 ? - "7-Zip ZS File Manager.lnk" : + "7-Zip File Manager.lnk" : "7-Zip Help.lnk" ); wcscpy(destPath, path); @@ -828,7 +856,7 @@ static void SetShellProgramsGroup(HWND hwndOwner) 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 @@ static LPCSTR const k_ShellEx_Items[] = , "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-Zstandard"); @@ -968,7 +996,7 @@ static const wchar_t *GetCmdParam(const wchar_t *s) 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, for (;;) { { - wchar_t c = *s; + const wchar_t c = *s; if (c == 0) break; if (c == ' ') @@ -1070,11 +1098,12 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, } } - #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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, { 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 @@ static int Install(void) 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 @@ if (res == SZ_OK) for (;;) { - wchar_t c = path[i++]; + const wchar_t c = path[i++]; if (c == 0) break; if (c != ' ') @@ -1318,7 +1347,7 @@ if (res == SZ_OK) { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -1372,7 +1401,7 @@ if (res == SZ_OK) } { - 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 @@ if (res == SZ_OK) #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 @@ if (res == SZ_OK) #endif { - SRes winRes2 = File_Close(&outFile); + const WRes winRes2 = File_Close(&outFile); if (res != SZ_OK) break; if (winRes2 != 0) diff --git a/C/Util/7zipInstall/7zipInstall.dsp b/C/Util/7zipInstall/7zipInstall.dsp index d3b5c4c9..4c6ea4d8 100644 --- a/C/Util/7zipInstall/7zipInstall.dsp +++ b/C/Util/7zipInstall/7zipInstall.dsp @@ -152,6 +152,10 @@ SOURCE=..\..\7zVersion.h # 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 @@ SOURCE=..\..\LzmaDec.h # 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 --git a/C/Util/7zipInstall/Precomp.h b/C/Util/7zipInstall/Precomp.h index 4c90d479..bc8fa219 100644 --- a/C/Util/7zipInstall/Precomp.h +++ b/C/Util/7zipInstall/Precomp.h @@ -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 --git a/C/Util/7zipInstall/makefile b/C/Util/7zipInstall/makefile index ab8893a9..18e27830 100644 --- a/C/Util/7zipInstall/makefile +++ b/C/Util/7zipInstall/makefile @@ -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 @@ C_OBJS = \ $O\7zDec.obj \ $O\7zStream.obj \ $O\Bcj2.obj \ + $O\Bra.obj \ $O\CpuArch.obj \ $O\DllSecur.obj \ $O\LzmaDec.obj \ diff --git a/C/Util/7zipUninstall/7zipUninstall.c b/C/Util/7zipUninstall/7zipUninstall.c index 7f56e0b1..1ceb3217 100644 --- a/C/Util/7zipUninstall/7zipUninstall.c +++ b/C/Util/7zipUninstall/7zipUninstall.c @@ -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-Zstandard"; +// 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 ZS " LLL(MY_VERSION) +#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_Software_7zip = L"Software\\7-Zip-Zstandard"; 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 @@ -83,7 +107,7 @@ static LPCWSTR const k_Reg_Path32 = L"Path" #define k_Reg_WOW_Flag_32 0 #endif -#define k_7zip_CLSID L"{23170F69-20BB-278A-1000-000100020000}" +#define k_7zip_CLSID L"{23170F69-40C1-278A-1000-000100020000}" static LPCWSTR const k_Reg_CLSID_7zip = L"CLSID\\" k_7zip_CLSID; static LPCWSTR const k_Reg_CLSID_7zip_Inproc = L"CLSID\\" k_7zip_CLSID L"\\InprocServer32"; @@ -116,14 +140,14 @@ static WCHAR copyPath[MAX_PATH * 2 + 40]; 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 @@ static BoolInt IsString1PrefixedByString2_NoCase(const wchar_t *s1, const wchar_ 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 BoolInt IsString1PrefixedByString2_NoCase(const wchar_t *s1, const wchar_ 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 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest) { 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_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest) 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 LONG MyRegistry_DeleteKey(HKEY parentKey, LPCWSTR name) 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 MyReg_DeleteVal_Path_if_Equal(HKEY hKey, LPCWSTR name) 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_Path2(HKEY parentKey) } } -static void SetRegKey_Path() +static void SetRegKey_Path(void) { SetRegKey_Path2(HKEY_CURRENT_USER); SetRegKey_Path2(HKEY_LOCAL_MACHINE); @@ -356,7 +380,7 @@ static void SetShellProgramsGroup(HWND hwndOwner) continue; NormalizePrefix(link); - CatAscii(link, "7-Zip-Zstandard\\"); + CatAscii(link, "7-Zip\\"); { const size_t baseLen = wcslen(link); @@ -366,7 +390,7 @@ static void SetShellProgramsGroup(HWND hwndOwner) for (k = 0; k < 2; k++) { CpyAscii(link + baseLen, k == 0 ? - "7-Zip ZS File Manager.lnk" : + "7-Zip File Manager.lnk" : "7-Zip Help.lnk"); wcscpy(destPath, path); CatAscii(destPath, k == 0 ? @@ -405,7 +429,7 @@ static LPCWSTR const k_Shell_Approved = L"Software\\Microsoft\\Windows\\CurrentV static LPCWSTR const k_AppPaths_7zFm = L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\7zFM.exe"; #define k_REG_Uninstall L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" -static LPCWSTR const k_Uninstall_7zip = k_REG_Uninstall L"7-Zip-Zstandard"; +static LPCWSTR const k_Uninstall_7zip = k_REG_Uninstall L"7-Zip"; static void RemoveQuotes(wchar_t *s) @@ -426,7 +450,7 @@ static BoolInt AreEqual_Path_PrefixName(const wchar_t *s, const wchar_t *prefix, return AreStringsEqual_NoCase(s + wcslen(prefix), name); } -static void WriteCLSID() +static void WriteCLSID(void) { WCHAR s[MAX_PATH + 30]; @@ -435,14 +459,14 @@ static void WriteCLSID() 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 @@ static void WriteCLSID() { 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 @@ static void WriteCLSID() 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 @@ static void WriteCLSID() { 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 @@ static const wchar_t *GetCmdParam(const wchar_t *s) 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 @@ static const wchar_t *GetCmdParam(const wchar_t *s) 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 void RemoveQuotes(wchar_t *s) } */ -static BoolInt DoesFileOrDirExist() +static BoolInt DoesFileOrDirExist(void) { return (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES); } @@ -573,7 +597,7 @@ static BOOL RemoveFileAfterReboot2(const WCHAR *s) #endif } -static BOOL RemoveFileAfterReboot() +static BOOL RemoveFileAfterReboot(void) { return RemoveFileAfterReboot2(path); } @@ -584,7 +608,7 @@ static BoolInt IsThereSpace(const wchar_t *s) { for (;;) { - wchar_t c = *s++; + const wchar_t c = *s++; if (c == 0) return False; if (c == ' ') @@ -594,7 +618,7 @@ static BoolInt IsThereSpace(const wchar_t *s) 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 @@ static BoolInt GetErrorMessage(DWORD errorCode, WCHAR *message) 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)) @@ -659,8 +683,6 @@ static const char * const k_Names = " 7z.sfx" " 7zCon.sfx" " 7z.exe" - " 7za.exe" - " 7za.dll" " 7zG.exe" " 7z.dll" " 7zFM.exe" @@ -672,7 +694,7 @@ static const char * const k_Names = -static int Install() +static int Install(void) { SRes res = SZ_OK; WRes winRes = 0; @@ -726,7 +748,7 @@ static int Install() for (;;) { - char c = *curName; + const char c = *curName; if (c == 0) break; curName++; @@ -745,7 +767,7 @@ static int Install() 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) @@ -805,7 +827,7 @@ static int Install() } -static void OnClose() +static void OnClose(void) { if (g_Install_was_Pressed && !g_Finished) { @@ -819,7 +841,13 @@ static void OnClose() 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) @@ -907,7 +935,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, #endif #ifndef UNDER_CE - func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) + func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) MY_CAST_FUNC GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW"); #endif @@ -978,7 +1006,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, { 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; @@ -989,7 +1017,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *s = modulePrefix; for (;;) { - wchar_t c = *s++; + const wchar_t c = *s++; if (c == 0) break; if (c == WCHAR_PATH_SEPARATOR) @@ -1039,7 +1067,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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))); } @@ -1136,7 +1164,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 --git a/C/Util/7zipUninstall/7zipUninstall.dsp b/C/Util/7zipUninstall/7zipUninstall.dsp index cc7b6b6b..bb7473fc 100644 --- a/C/Util/7zipUninstall/7zipUninstall.dsp +++ b/C/Util/7zipUninstall/7zipUninstall.dsp @@ -104,6 +104,14 @@ SOURCE=..\..\7zVersion.h # 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 --git a/C/Util/7zipUninstall/Precomp.h b/C/Util/7zipUninstall/Precomp.h index 4c90d479..bc8fa219 100644 --- a/C/Util/7zipUninstall/Precomp.h +++ b/C/Util/7zipUninstall/Precomp.h @@ -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 --git a/C/Util/7zipUninstall/makefile b/C/Util/7zipUninstall/makefile index 60c2fe20..9d8aafca 100644 --- a/C/Util/7zipUninstall/makefile +++ b/C/Util/7zipUninstall/makefile @@ -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 --git a/C/Util/Lzma/LzmaUtil.c b/C/Util/Lzma/LzmaUtil.c index 62a59079..b9b974bd 100644 --- a/C/Util/Lzma/LzmaUtil.c +++ b/C/Util/Lzma/LzmaUtil.c @@ -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 kCantWriteMessage = "Cannot write output file"; 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 @@ static int PrintUserError(char *buffer) #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 @@ static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inS 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 Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inS } -static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream) +static SRes Decode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream) { UInt64 unpackSize; int i; @@ -137,27 +169,29 @@ static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream) /* 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 SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 file } -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 @@ static int main2(int numArgs, const char *args[], char *rs) 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 @@ static int main2(int numArgs, const char *args[], char *rs) 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 @@ static int main2(int numArgs, const char *args[], char *rs) 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 --git a/C/Util/Lzma/LzmaUtil.dsp b/C/Util/Lzma/LzmaUtil.dsp index 4e38e4a6..e2e7d428 100644 --- a/C/Util/Lzma/LzmaUtil.dsp +++ b/C/Util/Lzma/LzmaUtil.dsp @@ -106,6 +106,10 @@ SOURCE=..\..\7zVersion.h # 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 @@ SOURCE=..\..\Alloc.h # 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 @@ SOURCE=.\LzmaUtil.c # 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 --git a/C/Util/Lzma/Precomp.h b/C/Util/Lzma/Precomp.h new file mode 100644 index 00000000..bc8fa219 --- /dev/null +++ b/C/Util/Lzma/Precomp.h @@ -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 --git a/C/Util/LzmaLib/LzmaLib.dsp b/C/Util/LzmaLib/LzmaLib.dsp index 6ce91dcd..bacd9679 100644 --- a/C/Util/LzmaLib/LzmaLib.dsp +++ b/C/Util/LzmaLib/LzmaLib.dsp @@ -101,6 +101,10 @@ SOURCE=.\LzmaLib.def SOURCE=.\LzmaLibExports.c # End Source File +# Begin Source File + +SOURCE=.\Precomp.h +# End Source File # End Group # Begin Source File @@ -108,6 +112,10 @@ SOURCE=..\..\7zTypes.h # 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 @@ SOURCE=..\..\Alloc.h # 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 @@ SOURCE=..\..\LzmaLib.h # 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 --git a/C/Util/LzmaLib/LzmaLibExports.c b/C/Util/LzmaLib/LzmaLibExports.c index 4a28a9a6..a46c9a80 100644 --- a/C/Util/LzmaLib/LzmaLibExports.c +++ b/C/Util/LzmaLib/LzmaLibExports.c @@ -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 --git a/C/Util/LzmaLib/Precomp.c b/C/Util/LzmaLib/Precomp.c new file mode 100644 index 00000000..01605e3c --- /dev/null +++ b/C/Util/LzmaLib/Precomp.c @@ -0,0 +1,4 @@ +/* Precomp.c -- StdAfx +2013-01-21 : Igor Pavlov : Public domain */ + +#include "Precomp.h" diff --git a/C/Util/LzmaLib/Precomp.h b/C/Util/LzmaLib/Precomp.h new file mode 100644 index 00000000..bc8fa219 --- /dev/null +++ b/C/Util/LzmaLib/Precomp.h @@ -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 --git a/C/Util/LzmaLib/makefile b/C/Util/LzmaLib/makefile index b36f1de0..b8e054ef 100644 --- a/C/Util/LzmaLib/makefile +++ b/C/Util/LzmaLib/makefile @@ -21,6 +21,7 @@ C_OBJS = \ $O\Threads.obj \ OBJS = \ + $O\Precomp.obj \ $(LIB_OBJS) \ $(C_OBJS) \ $O\resource.res @@ -30,7 +31,24 @@ OBJS = \ $(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 --git a/C/Util/SfxSetup/Precomp.h b/C/Util/SfxSetup/Precomp.h index 588a66f7..bc8fa219 100644 --- a/C/Util/SfxSetup/Precomp.h +++ b/C/Util/SfxSetup/Precomp.h @@ -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 --git a/C/Util/SfxSetup/SfxSetup.c b/C/Util/SfxSetup/SfxSetup.c index ef19aeac..7304a0be 100644 --- a/C/Util/SfxSetup/SfxSetup.c +++ b/C/Util/SfxSetup/SfxSetup.c @@ -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 @@ static unsigned FindExt(const wchar_t *s, unsigned *extLen) 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 @@ static unsigned FindItem(const char * const *items, unsigned num, const wchar_t 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 @@ static BOOL WINAPI HandlerRoutine(DWORD ctrlType) } #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 @@ static WRes RemoveDirWithSubItems(WCHAR *path) 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 @@ static WRes RemoveDirWithSubItems(WCHAR *path) } #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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) } } @@ -455,11 +471,11 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, #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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 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 --git a/C/Util/SfxSetup/makefile b/C/Util/SfxSetup/makefile index 544da67d..bc0cf8bc 100644 --- a/C/Util/SfxSetup/makefile +++ b/C/Util/SfxSetup/makefile @@ -1,6 +1,9 @@ PROG = 7zS2.sfx MY_FIXED = 1 +CFLAGS = $(CFLAGS) \ + -DZ7_EXTRACT_ONLY \ + C_OBJS = \ $O\7zAlloc.obj \ $O\7zArcIn.obj \ diff --git a/C/Util/SfxSetup/makefile_con b/C/Util/SfxSetup/makefile_con index d0f83525..9f4b9166 100644 --- a/C/Util/SfxSetup/makefile_con +++ b/C/Util/SfxSetup/makefile_con @@ -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 --git a/C/Xz.c b/C/Xz.c index 7c53b600..4ad07106 100644 --- a/C/Xz.c +++ b/C/Xz.c @@ -1,5 +1,5 @@ /* Xz.c - Xz -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -70,7 +70,7 @@ int XzCheck_Final(CXzCheck *p, Byte *digest) switch (p->mode) { case XZ_CHECK_CRC32: - SetUi32(digest, CRC_GET_DIGEST(p->crc)); + SetUi32(digest, CRC_GET_DIGEST(p->crc)) break; case XZ_CHECK_CRC64: { diff --git a/C/Xz.h b/C/Xz.h index 849b944b..d5001f6c 100644 --- a/C/Xz.h +++ b/C/Xz.h @@ -1,21 +1,23 @@ /* Xz.h - Xz interface -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __XZ_H -#define __XZ_H +#ifndef ZIP7_INC_XZ_H +#define ZIP7_INC_XZ_H #include "Sha256.h" +#include "Delta.h" EXTERN_C_BEGIN #define XZ_ID_Subblock 1 #define XZ_ID_Delta 3 -#define XZ_ID_X86 4 -#define XZ_ID_PPC 5 -#define XZ_ID_IA64 6 -#define XZ_ID_ARM 7 -#define XZ_ID_ARMT 8 +#define XZ_ID_X86 4 +#define XZ_ID_PPC 5 +#define XZ_ID_IA64 6 +#define XZ_ID_ARM 7 +#define XZ_ID_ARMT 8 #define XZ_ID_SPARC 9 +#define XZ_ID_ARM64 0xa #define XZ_ID_LZMA2 0x21 unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value); @@ -53,7 +55,7 @@ typedef struct #define XzBlock_HasUnsupportedFlags(p) (((p)->flags & ~(XZ_BF_NUM_FILTERS_MASK | XZ_BF_PACK_SIZE | XZ_BF_UNPACK_SIZE)) != 0) SRes XzBlock_Parse(CXzBlock *p, const Byte *header); -SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes); +SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes); /* ---------- xz stream ---------- */ @@ -101,7 +103,7 @@ typedef UInt16 CXzStreamFlags; unsigned XzFlags_GetCheckSize(CXzStreamFlags f); SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf); -SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream); +SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream); typedef struct { @@ -112,6 +114,7 @@ typedef struct typedef struct { CXzStreamFlags flags; + // Byte _pad[6]; size_t numBlocks; CXzBlockSizes *blocks; UInt64 startOffset; @@ -134,7 +137,7 @@ typedef struct void Xzs_Construct(CXzs *p); void Xzs_Free(CXzs *p, ISzAllocPtr alloc); -SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc); +SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr inStream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc); UInt64 Xzs_GetNumBlocks(const CXzs *p); UInt64 Xzs_GetUnpackSize(const CXzs *p); @@ -160,9 +163,9 @@ typedef enum } ECoderFinishMode; -typedef struct _IStateCoder +typedef struct { - void *p; + void *p; // state object; void (*Free)(void *p, ISzAllocPtr alloc); SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAllocPtr alloc); void (*Init)(void *p); @@ -174,6 +177,20 @@ typedef struct _IStateCoder } IStateCoder; +typedef struct +{ + UInt32 methodId; + UInt32 delta; + UInt32 ip; + UInt32 X86_State; + Byte delta_State[DELTA_STATE_SIZE]; +} CXzBcFilterStateBase; + +typedef SizeT (*Xz_Func_BcFilterStateBase_Filter)(CXzBcFilterStateBase *p, Byte *data, SizeT size); + +SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, + Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc); + #define MIXCODER_NUM_FILTERS_MAX 4 @@ -422,7 +439,7 @@ typedef struct size_t outStep_ST; // size of output buffer for Single-Thread decoding BoolInt ignoreErrors; // if set to 1, the decoder can ignore some errors and it skips broken parts of data. - #ifndef _7ZIP_ST + #ifndef Z7_ST unsigned numThreads; // the number of threads for Multi-Thread decoding. if (umThreads == 1) it will use Single-thread decoding size_t inBufSize_MT; // size of small input data buffers for Multi-Thread decoding. Big number of such small buffers can be created size_t memUseMax; // the limit of total memory usage for Multi-Thread decoding. @@ -432,8 +449,9 @@ typedef struct void XzDecMtProps_Init(CXzDecMtProps *p); - -typedef void * CXzDecMtHandle; +typedef struct CXzDecMt CXzDecMt; +typedef CXzDecMt * CXzDecMtHandle; +// Z7_DECLARE_HANDLE(CXzDecMtHandle) /* alloc : XzDecMt uses CAlignOffsetAlloc internally for addresses allocated by (alloc). @@ -503,14 +521,14 @@ SRes XzDecMt_Decode(CXzDecMtHandle p, const CXzDecMtProps *props, const UInt64 *outDataSize, // NULL means undefined int finishMode, // 0 - partial unpacking is allowed, 1 - xz stream(s) must be finished - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, // Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, // const Byte *inData, size_t inDataSize, CXzStatInfo *stat, // out: decoding results and statistics int *isMT, // out: 0 means that ST (Single-Thread) version was used // 1 means that MT (Multi-Thread) version was used - ICompressProgress *progress); + ICompressProgressPtr progress); EXTERN_C_END diff --git a/C/XzCrc64.c b/C/XzCrc64.c index b6d02cbe..c2fad6cd 100644 --- a/C/XzCrc64.c +++ b/C/XzCrc64.c @@ -1,5 +1,5 @@ /* XzCrc64.c -- CRC64 calculation -2017-05-23 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -12,39 +12,30 @@ #define CRC64_NUM_TABLES 4 #else #define CRC64_NUM_TABLES 5 - #define CRC_UINT64_SWAP(v) \ - ((v >> 56) \ - | ((v >> 40) & ((UInt64)0xFF << 8)) \ - | ((v >> 24) & ((UInt64)0xFF << 16)) \ - | ((v >> 8) & ((UInt64)0xFF << 24)) \ - | ((v << 8) & ((UInt64)0xFF << 32)) \ - | ((v << 24) & ((UInt64)0xFF << 40)) \ - | ((v << 40) & ((UInt64)0xFF << 48)) \ - | ((v << 56))) - UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); + UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); #endif #ifndef MY_CPU_BE - UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); + UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); #endif -typedef UInt64 (MY_FAST_CALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); +typedef UInt64 (Z7_FASTCALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); static CRC64_FUNC g_Crc64Update; UInt64 g_Crc64Table[256 * CRC64_NUM_TABLES]; -UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size) +UInt64 Z7_FASTCALL Crc64Update(UInt64 v, const void *data, size_t size) { return g_Crc64Update(v, data, size, g_Crc64Table); } -UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size) +UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size) { return g_Crc64Update(CRC64_INIT_VAL, data, size, g_Crc64Table) ^ CRC64_INIT_VAL; } -void MY_FAST_CALL Crc64GenerateTable() +void Z7_FASTCALL Crc64GenerateTable(void) { UInt32 i; for (i = 0; i < 256; i++) @@ -57,7 +48,7 @@ void MY_FAST_CALL Crc64GenerateTable() } for (i = 256; i < 256 * CRC64_NUM_TABLES; i++) { - UInt64 r = g_Crc64Table[(size_t)i - 256]; + const UInt64 r = g_Crc64Table[(size_t)i - 256]; g_Crc64Table[i] = g_Crc64Table[r & 0xFF] ^ (r >> 8); } @@ -76,11 +67,14 @@ void MY_FAST_CALL Crc64GenerateTable() { for (i = 256 * CRC64_NUM_TABLES - 1; i >= 256; i--) { - UInt64 x = g_Crc64Table[(size_t)i - 256]; - g_Crc64Table[i] = CRC_UINT64_SWAP(x); + const UInt64 x = g_Crc64Table[(size_t)i - 256]; + g_Crc64Table[i] = Z7_BSWAP64(x); } g_Crc64Update = XzCrc64UpdateT1_BeT4; } } #endif } + +#undef kCrc64Poly +#undef CRC64_NUM_TABLES diff --git a/C/XzCrc64.h b/C/XzCrc64.h index 08dbc330..ca46869a 100644 --- a/C/XzCrc64.h +++ b/C/XzCrc64.h @@ -1,8 +1,8 @@ /* XzCrc64.h -- CRC64 calculation -2013-01-18 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ -#ifndef __XZ_CRC64_H -#define __XZ_CRC64_H +#ifndef ZIP7_INC_XZ_CRC64_H +#define ZIP7_INC_XZ_CRC64_H #include @@ -12,14 +12,14 @@ EXTERN_C_BEGIN extern UInt64 g_Crc64Table[]; -void MY_FAST_CALL Crc64GenerateTable(void); +void Z7_FASTCALL Crc64GenerateTable(void); #define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF) #define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL) #define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) -UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size); -UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size); +UInt64 Z7_FASTCALL Crc64Update(UInt64 crc, const void *data, size_t size); +UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size); EXTERN_C_END diff --git a/C/XzCrc64Opt.c b/C/XzCrc64Opt.c index 93a9ffff..d03374c0 100644 --- a/C/XzCrc64Opt.c +++ b/C/XzCrc64Opt.c @@ -1,5 +1,5 @@ /* XzCrc64Opt.c -- CRC64 calculation -2021-02-09 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -9,15 +9,15 @@ #define CRC64_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) -UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) +UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); +UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) { const Byte *p = (const Byte *)data; for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) v = CRC64_UPDATE_BYTE_2(v, *p); for (; size >= 4; size -= 4, p += 4) { - UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; + const UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; v = (v >> 32) ^ (table + 0x300)[((d ) & 0xFF)] ^ (table + 0x200)[((d >> 8) & 0xFF)] @@ -34,29 +34,19 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, con #ifndef MY_CPU_LE -#define CRC_UINT64_SWAP(v) \ - ((v >> 56) \ - | ((v >> 40) & ((UInt64)0xFF << 8)) \ - | ((v >> 24) & ((UInt64)0xFF << 16)) \ - | ((v >> 8) & ((UInt64)0xFF << 24)) \ - | ((v << 8) & ((UInt64)0xFF << 32)) \ - | ((v << 24) & ((UInt64)0xFF << 40)) \ - | ((v << 40) & ((UInt64)0xFF << 48)) \ - | ((v << 56))) - #define CRC64_UPDATE_BYTE_2_BE(crc, b) (table[(Byte)((crc) >> 56) ^ (b)] ^ ((crc) << 8)) -UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); -UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) +UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); +UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) { const Byte *p = (const Byte *)data; table += 0x100; - v = CRC_UINT64_SWAP(v); + v = Z7_BSWAP64(v); for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) v = CRC64_UPDATE_BYTE_2_BE(v, *p); for (; size >= 4; size -= 4, p += 4) { - UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; + const UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; v = (v << 32) ^ (table + 0x000)[((d ) & 0xFF)] ^ (table + 0x100)[((d >> 8) & 0xFF)] @@ -65,7 +55,7 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size } for (; size > 0; size--, p++) v = CRC64_UPDATE_BYTE_2_BE(v, *p); - return CRC_UINT64_SWAP(v); + return Z7_BSWAP64(v); } #endif diff --git a/C/XzDec.c b/C/XzDec.c index 3f96a37f..a5f70396 100644 --- a/C/XzDec.c +++ b/C/XzDec.c @@ -1,5 +1,5 @@ /* XzDec.c -- Xz Decode -2021-09-04 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -67,7 +67,8 @@ unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value) return 0; } -/* ---------- BraState ---------- */ + +/* ---------- XzBcFilterState ---------- */ #define BRA_BUF_SIZE (1 << 14) @@ -76,27 +77,29 @@ typedef struct size_t bufPos; size_t bufConv; size_t bufTotal; + Byte *buf; // must be aligned for 4 bytes + Xz_Func_BcFilterStateBase_Filter filter_func; + // int encodeMode; + CXzBcFilterStateBase base; + // Byte buf[BRA_BUF_SIZE]; +} CXzBcFilterState; - int encodeMode; - - UInt32 methodId; - UInt32 delta; - UInt32 ip; - UInt32 x86State; - Byte deltaState[DELTA_STATE_SIZE]; - Byte buf[BRA_BUF_SIZE]; -} CBraState; - -static void BraState_Free(void *pp, ISzAllocPtr alloc) +static void XzBcFilterState_Free(void *pp, ISzAllocPtr alloc) { - ISzAlloc_Free(alloc, pp); + if (pp) + { + CXzBcFilterState *p = ((CXzBcFilterState *)pp); + ISzAlloc_Free(alloc, p->buf); + ISzAlloc_Free(alloc, pp); + } } -static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) + +static SRes XzBcFilterState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) { - CBraState *p = ((CBraState *)pp); - UNUSED_VAR(alloc); + CXzBcFilterStateBase *p = &((CXzBcFilterState *)pp)->base; + UNUSED_VAR(alloc) p->ip = 0; if (p->methodId == XZ_ID_Delta) { @@ -114,6 +117,7 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA case XZ_ID_PPC: case XZ_ID_ARM: case XZ_ID_SPARC: + case XZ_ID_ARM64: if ((v & 3) != 0) return SZ_ERROR_UNSUPPORTED; break; @@ -134,73 +138,90 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA return SZ_OK; } -static void BraState_Init(void *pp) + +static void XzBcFilterState_Init(void *pp) { - CBraState *p = ((CBraState *)pp); + CXzBcFilterState *p = ((CXzBcFilterState *)pp); p->bufPos = p->bufConv = p->bufTotal = 0; - x86_Convert_Init(p->x86State); - if (p->methodId == XZ_ID_Delta) - Delta_Init(p->deltaState); + p->base.X86_State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL; + if (p->base.methodId == XZ_ID_Delta) + Delta_Init(p->base.delta_State); } -#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: size = isa ## _Convert(data, size, p->ip, p->encodeMode); break; - -static SizeT BraState_Filter(void *pp, Byte *data, SizeT size) +static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Dec[] = +{ + Z7_BRANCH_CONV_DEC(PPC), + Z7_BRANCH_CONV_DEC(IA64), + Z7_BRANCH_CONV_DEC(ARM), + Z7_BRANCH_CONV_DEC(ARMT), + Z7_BRANCH_CONV_DEC(SPARC), + Z7_BRANCH_CONV_DEC(ARM64) +}; + +static SizeT XzBcFilterStateBase_Filter_Dec(CXzBcFilterStateBase *p, Byte *data, SizeT size) { - CBraState *p = ((CBraState *)pp); switch (p->methodId) { case XZ_ID_Delta: - if (p->encodeMode) - Delta_Encode(p->deltaState, p->delta, data, size); - else - Delta_Decode(p->deltaState, p->delta, data, size); + Delta_Decode(p->delta_State, p->delta, data, size); break; case XZ_ID_X86: - size = x86_Convert(data, size, p->ip, &p->x86State, p->encodeMode); + size = (SizeT)(z7_BranchConvSt_X86_Dec(data, size, p->ip, &p->X86_State) - data); + break; + default: + if (p->methodId >= XZ_ID_PPC) + { + const UInt32 i = p->methodId - XZ_ID_PPC; + if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Dec)) + size = (SizeT)(g_Funcs_BranchConv_RISC_Dec[i](data, size, p->ip) - data); + } break; - CASE_BRA_CONV(PPC) - CASE_BRA_CONV(IA64) - CASE_BRA_CONV(ARM) - CASE_BRA_CONV(ARMT) - CASE_BRA_CONV(SPARC) } p->ip += (UInt32)size; return size; } -static SRes BraState_Code2(void *pp, +static SizeT XzBcFilterState_Filter(void *pp, Byte *data, SizeT size) +{ + CXzBcFilterState *p = ((CXzBcFilterState *)pp); + return p->filter_func(&p->base, data, size); +} + + +static SRes XzBcFilterState_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, int srcWasFinished, ECoderFinishMode finishMode, // int *wasFinished ECoderStatus *status) { - CBraState *p = ((CBraState *)pp); + CXzBcFilterState *p = ((CXzBcFilterState *)pp); SizeT destRem = *destLen; SizeT srcRem = *srcLen; - UNUSED_VAR(finishMode); + UNUSED_VAR(finishMode) *destLen = 0; *srcLen = 0; // *wasFinished = 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 @@ static SRes BraState_Code2(void *pp, if (p->bufTotal == 0) break; - p->bufConv = BraState_Filter(pp, p->buf, p->bufTotal); + p->bufConv = p->filter_func(&p->base, p->buf, p->bufTotal); if (p->bufConv == 0) { @@ -240,27 +261,37 @@ static SRes BraState_Code2(void *pp, } -SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); -SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc) +#define XZ_IS_SUPPORTED_FILTER_ID(id) \ + ((id) >= XZ_ID_Delta && (id) <= XZ_ID_ARM64) + +SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id, + Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc) { - CBraState *decoder; - if (id < XZ_ID_Delta || id > XZ_ID_SPARC) + CXzBcFilterState *decoder; + if (!XZ_IS_SUPPORTED_FILTER_ID(id)) return SZ_ERROR_UNSUPPORTED; - decoder = (CBraState *)p->p; + decoder = (CXzBcFilterState *)p->p; if (!decoder) { - decoder = (CBraState *)ISzAlloc_Alloc(alloc, sizeof(CBraState)); + decoder = (CXzBcFilterState *)ISzAlloc_Alloc(alloc, sizeof(CXzBcFilterState)); if (!decoder) return SZ_ERROR_MEM; + decoder->buf = ISzAlloc_Alloc(alloc, BRA_BUF_SIZE); + if (!decoder->buf) + { + ISzAlloc_Free(alloc, decoder); + return SZ_ERROR_MEM; + } p->p = decoder; - p->Free = BraState_Free; - p->SetProps = BraState_SetProps; - p->Init = BraState_Init; - p->Code2 = BraState_Code2; - p->Filter = BraState_Filter; + p->Free = XzBcFilterState_Free; + p->SetProps = XzBcFilterState_SetProps; + p->Init = XzBcFilterState_Init; + p->Code2 = XzBcFilterState_Code2; + p->Filter = XzBcFilterState_Filter; + decoder->filter_func = func; } - decoder->methodId = (UInt32)id; - decoder->encodeMode = encodeMode; + decoder->base.methodId = (UInt32)id; + // decoder->encodeMode = encodeMode; return SZ_OK; } @@ -279,9 +310,9 @@ static void SbState_Free(void *pp, ISzAllocPtr alloc) static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) { - UNUSED_VAR(pp); - UNUSED_VAR(props); - UNUSED_VAR(alloc); + UNUSED_VAR(pp) + UNUSED_VAR(props) + UNUSED_VAR(alloc) return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED; } @@ -297,7 +328,7 @@ static SRes SbState_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *src, { CSbDec *p = (CSbDec *)pp; SRes res; - UNUSED_VAR(srcWasFinished); + UNUSED_VAR(srcWasFinished) p->dest = dest; p->destLen = *destLen; p->src = src; @@ -389,7 +420,7 @@ static SRes Lzma2State_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *s ELzmaStatus status2; /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */ SRes res; - UNUSED_VAR(srcWasFinished); + UNUSED_VAR(srcWasFinished) if (spec->outBufMode) { SizeT dicPos = spec->decoder.decoder.dicPos; @@ -420,7 +451,7 @@ static SRes Lzma2State_SetFromMethod(IStateCoder *p, Byte *outBuf, size_t outBuf p->Init = Lzma2State_Init; p->Code2 = Lzma2State_Code2; p->Filter = NULL; - Lzma2Dec_Construct(&spec->decoder); + Lzma2Dec_CONSTRUCT(&spec->decoder) } spec->outBufMode = False; if (outBuf) @@ -519,7 +550,8 @@ static SRes MixCoder_SetFromMethod(CMixCoder *p, unsigned coderIndex, UInt64 met } if (coderIndex == 0) return SZ_ERROR_UNSUPPORTED; - return BraState_SetFromMethod(sc, methodId, 0, p->alloc); + return Xz_StateCoder_Bc_SetFromMethod_Func(sc, methodId, + XzBcFilterStateBase_Filter_Dec, p->alloc); } @@ -568,7 +600,7 @@ static SRes MixCoder_Code(CMixCoder *p, SizeT destLen2, srcLen2; int wasFinished; - PRF_STR("------- MixCoder Single ----------"); + PRF_STR("------- MixCoder Single ----------") srcLen2 = srcLenOrig; destLen2 = destLenOrig; @@ -615,14 +647,14 @@ static SRes MixCoder_Code(CMixCoder *p, processed = coder->Filter(coder->p, p->outBuf, processed); if (wasFinished || (destFinish && p->outWritten == destLenOrig)) processed = p->outWritten; - PRF_STR_INT("filter", i); + PRF_STR_INT("filter", i) } *destLen = processed; } return res; } - PRF_STR("standard mix"); + PRF_STR("standard mix") if (p->numCoders != 1) { @@ -779,7 +811,7 @@ static BoolInt Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) { - unsigned numFilters = XzBlock_GetNumFilters(p) - 1; + const unsigned numFilters = XzBlock_GetNumFilters(p) - 1; unsigned i; { const CXzFilter *f = &p->filters[numFilters]; @@ -795,8 +827,7 @@ static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) if (f->propsSize != 1) return 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 @@ SRes XzBlock_Parse(CXzBlock *p, const Byte *header) p->packSize = (UInt64)(Int64)-1; if (XzBlock_HasPackSize(p)) { - READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize); + READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize) if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63) return SZ_ERROR_ARCHIVE; } p->unpackSize = (UInt64)(Int64)-1; if (XzBlock_HasUnpackSize(p)) - READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize); + { + READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize) + } numFilters = XzBlock_GetNumFilters(p); for (i = 0; i < numFilters; i++) { CXzFilter *filter = p->filters + i; UInt64 size; - READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id); - READ_VARINT_AND_CHECK(header, pos, headerSize, &size); + READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id) + READ_VARINT_AND_CHECK(header, pos, headerSize, &size) if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX) return SZ_ERROR_ARCHIVE; filter->propsSize = (UInt32)size; @@ -894,20 +927,20 @@ static SRes XzDecMix_Init(CMixCoder *p, const CXzBlock *block, Byte *outBuf, siz MixCoder_Free(p); for (i = 0; i < numFilters; i++) { - RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)); + RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)) } p->numCoders = numFilters; } else { - RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)); + RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)) } for (i = 0; i < numFilters; i++) { const CXzFilter *f = &block->filters[numFilters - 1 - i]; IStateCoder *sc = &p->coders[i]; - RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)); + RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)) } MixCoder_Init(p); @@ -1054,14 +1087,14 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, (*destLen) += destLen2; p->unpackSize += destLen2; - RINOK(res); + RINOK(res) if (*status != CODER_STATUS_FINISHED_WITH_MARK) { if (p->block.packSize == p->packSize && *status == CODER_STATUS_NEEDS_MORE_INPUT) { - PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT"); + PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT") *status = CODER_STATUS_NOT_SPECIFIED; return SZ_ERROR_DATA; } @@ -1078,7 +1111,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, if ((p->block.packSize != (UInt64)(Int64)-1 && p->block.packSize != p->packSize) || (p->block.unpackSize != (UInt64)(Int64)-1 && p->block.unpackSize != p->unpackSize)) { - PRF_STR("ERROR: block.size mismatch"); + PRF_STR("ERROR: block.size mismatch") return SZ_ERROR_DATA; } } @@ -1109,7 +1142,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, } else { - RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)); + RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)) p->numStartedStreams++; p->indexSize = 0; p->numBlocks = 0; @@ -1155,7 +1188,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, } else { - RINOK(XzBlock_Parse(&p->block, p->buf)); + RINOK(XzBlock_Parse(&p->block, p->buf)) if (!XzBlock_AreSupportedFilters(&p->block)) return SZ_ERROR_UNSUPPORTED; p->numTotalBlocks++; @@ -1168,7 +1201,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen, p->headerParsedOk = 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 @@ UInt64 XzUnpacker_GetExtraSize(const CXzUnpacker *p) -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "MtDec.h" #endif @@ -1400,7 +1433,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p) p->outStep_ST = 1 << 20; p->ignoreErrors = 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 @@ void XzDecMtProps_Init(CXzDecMtProps *p) -#ifndef _7ZIP_ST +#ifndef Z7_ST /* ---------- CXzDecMtThread ---------- */ @@ -1448,7 +1481,7 @@ typedef struct /* ---------- CXzDecMt ---------- */ -typedef struct +struct CXzDecMt { CAlignOffsetAlloc alignOffsetAlloc; ISzAllocPtr allocMid; @@ -1456,9 +1489,9 @@ typedef struct CXzDecMtProps props; size_t unpackBlockMaxSize; - ISeqInStream *inStream; - ISeqOutStream *outStream; - ICompressProgress *progress; + ISeqInStreamPtr inStream; + ISeqOutStreamPtr outStream; + ICompressProgressPtr progress; BoolInt finishMode; BoolInt outSize_Defined; @@ -1481,7 +1514,7 @@ typedef struct ECoderStatus status; SRes codeRes; - #ifndef _7ZIP_ST + #ifndef Z7_ST BoolInt mainDecoderWasCalled; // int statErrorDefined; int finishedDecoderIndex; @@ -1504,10 +1537,9 @@ typedef struct BoolInt mtc_WasConstructed; CMtDec mtc; - CXzDecMtThread coders[MTDEC__THREADS_MAX]; + CXzDecMtThread coders[MTDEC_THREADS_MAX]; #endif - -} CXzDecMt; +}; @@ -1535,11 +1567,11 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) XzDecMtProps_Init(&p->props); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtc_WasConstructed = 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 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid) } #endif - return p; + return (CXzDecMtHandle)p; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static void XzDecMt_FreeOutBufs(CXzDecMt *p) { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CXzDecMtThread *coder = &p->coders[i]; if (coder->outBuf) @@ -1595,13 +1627,15 @@ static void XzDecMt_FreeSt(CXzDecMt *p) } -void XzDecMt_Destroy(CXzDecMtHandle pp) +// #define GET_CXzDecMt_p CXzDecMt *p = pp; + +void XzDecMt_Destroy(CXzDecMtHandle p) { - CXzDecMt *p = (CXzDecMt *)pp; + // GET_CXzDecMt_p XzDecMt_FreeSt(p); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtc_WasConstructed) { @@ -1610,7 +1644,7 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) } { unsigned i; - for (i = 0; i < MTDEC__THREADS_MAX; i++) + for (i = 0; i < MTDEC_THREADS_MAX; i++) { CXzDecMtThread *t = &p->coders[i]; if (t->dec_created) @@ -1625,12 +1659,12 @@ void XzDecMt_Destroy(CXzDecMtHandle pp) #endif - ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); + ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p); } -#ifndef _7ZIP_ST +#ifndef Z7_ST static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) { @@ -1696,7 +1730,7 @@ static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbac coder->dec.parseMode = 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 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, } data += cur; size -= cur; - // PRF_STR_INT("Written size =", size); + // PRF_STR_INT("Written size =", size) if (size == 0) break; res = MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0); @@ -2087,7 +2121,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, return res; } - RINOK(res); + RINOK(res) if (coder->inPreSize != coder->inCodeSize || coder->blockPackTotal != coder->inCodeSize) @@ -2106,13 +2140,13 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, // (coder->state == MTDEC_PARSE_END) means that there are no other working threads // so we can use mtc variables without lock - PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed); + PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed) me->mtc.mtProgress.totalInSize = me->mtc.inProcessed; { CXzUnpacker *dec = &me->dec; - PRF_STR_INT("PostSingle", srcSize); + PRF_STR_INT("PostSingle", srcSize) { size_t srcProcessed = srcSize; @@ -2186,7 +2220,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, me->mtc.crossEnd = srcSize; } - PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd); + PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd) return SZ_OK; } @@ -2277,7 +2311,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex, UInt64 inDelta = me->mtc.inProcessed - inProgressPrev; if (inDelta >= (1 << 22)) { - RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)); + RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)) inProgressPrev = me->mtc.inProcessed; } } @@ -2331,7 +2365,7 @@ void XzStatInfo_Clear(CXzStatInfo *p) */ static SRes XzDecMt_Decode_ST(CXzDecMt *p - #ifndef _7ZIP_ST + #ifndef Z7_ST , BoolInt tMode #endif , CXzStatInfo *stat) @@ -2343,7 +2377,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p CXzUnpacker *dec; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { XzDecMt_FreeOutBufs(p); @@ -2400,7 +2434,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p if (inPos == inLim) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (tMode) { inData = MtDec_Read(&p->mtc, &inLim); @@ -2577,19 +2611,19 @@ static void XzStatInfo_SetStat(const CXzUnpacker *dec, -SRes XzDecMt_Decode(CXzDecMtHandle pp, +SRes XzDecMt_Decode(CXzDecMtHandle p, const CXzDecMtProps *props, const UInt64 *outDataSize, int finishMode, - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, // Byte *outBuf, size_t *outBufSize, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, // const Byte *inData, size_t inDataSize, CXzStatInfo *stat, int *isMT, - ICompressProgress *progress) + ICompressProgressPtr progress) { - CXzDecMt *p = (CXzDecMt *)pp; - #ifndef _7ZIP_ST + // GET_CXzDecMt_p + #ifndef Z7_ST BoolInt tMode; #endif @@ -2640,7 +2674,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, */ - #ifndef _7ZIP_ST + #ifndef Z7_ST p->isBlockHeaderState_Parse = False; p->isBlockHeaderState_Write = False; @@ -2782,7 +2816,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, return res; } - PRF_STR("----- decoding ST -----"); + PRF_STR("----- decoding ST -----") } #endif @@ -2792,13 +2826,13 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, { SRes res = XzDecMt_Decode_ST(p - #ifndef _7ZIP_ST + #ifndef Z7_ST , tMode #endif , stat ); - #ifndef _7ZIP_ST + #ifndef Z7_ST // we must set error code from MT decoding at first if (p->mainErrorCode != SZ_OK) stat->DecodeRes = p->mainErrorCode; @@ -2835,3 +2869,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp, return res; } } + +#undef PRF +#undef PRF_STR +#undef PRF_STR_INT_2 diff --git a/C/XzEnc.c b/C/XzEnc.c index be174ccc..22408e26 100644 --- a/C/XzEnc.c +++ b/C/XzEnc.c @@ -1,5 +1,5 @@ /* XzEnc.c -- Xz Encode -2021-04-01 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -18,13 +18,13 @@ #include "XzEnc.h" -// #define _7ZIP_ST +// #define Z7_ST -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "MtCoder.h" #else -#define MTCODER__THREADS_MAX 1 -#define MTCODER__BLOCKS_MAX 1 +#define MTCODER_THREADS_MAX 1 +#define MTCODER_BLOCKS_MAX 1 #endif #define XZ_GET_PAD_SIZE(dataSize) ((4 - ((unsigned)(dataSize) & 3)) & 3) @@ -35,25 +35,25 @@ #define XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(unpackSize) (XZ_BLOCK_HEADER_SIZE_MAX + XZ_GET_MAX_BLOCK_PACK_SIZE(unpackSize)) -#define XzBlock_ClearFlags(p) (p)->flags = 0; -#define XzBlock_SetNumFilters(p, n) (p)->flags = (Byte)((p)->flags | ((n) - 1)); +// #define XzBlock_ClearFlags(p) (p)->flags = 0; +#define XzBlock_ClearFlags_SetNumFilters(p, n) (p)->flags = (Byte)((n) - 1); #define XzBlock_SetHasPackSize(p) (p)->flags |= XZ_BF_PACK_SIZE; #define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE; -static SRes WriteBytes(ISeqOutStream *s, const void *buf, size_t size) +static SRes WriteBytes(ISeqOutStreamPtr s, const void *buf, size_t size) { return (ISeqOutStream_Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE; } -static SRes WriteBytesUpdateCrc(ISeqOutStream *s, const void *buf, size_t size, UInt32 *crc) +static SRes WriteBytes_UpdateCrc(ISeqOutStreamPtr s, const void *buf, size_t size, UInt32 *crc) { *crc = CrcUpdate(*crc, buf, size); return WriteBytes(s, buf, size); } -static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) +static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStreamPtr s) { UInt32 crc; Byte header[XZ_STREAM_HEADER_SIZE]; @@ -61,12 +61,12 @@ static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) header[XZ_SIG_SIZE] = (Byte)(f >> 8); header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF); crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE); - SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc); + SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc) return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE); } -static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) +static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStreamPtr s) { Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; @@ -91,7 +91,7 @@ static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) header[pos++] = 0; header[0] = (Byte)(pos >> 2); - SetUi32(header + pos, CrcCalc(header, pos)); + SetUi32(header + pos, CrcCalc(header, pos)) return WriteBytes(s, header, pos + 4); } @@ -182,7 +182,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 size_t newSize = p->allocated * 2 + 16 * 2; if (newSize < p->size + pos) return SZ_ERROR_MEM; - RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)); + RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)) } memcpy(p->blocks + p->size, buf, pos); p->size += pos; @@ -191,7 +191,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64 } -static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStream *s) +static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStreamPtr s) { Byte buf[32]; UInt64 globalPos; @@ -200,8 +200,8 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I globalPos = pos; buf[0] = 0; - RINOK(WriteBytesUpdateCrc(s, buf, pos, &crc)); - RINOK(WriteBytesUpdateCrc(s, p->blocks, p->size, &crc)); + RINOK(WriteBytes_UpdateCrc(s, buf, pos, &crc)) + RINOK(WriteBytes_UpdateCrc(s, p->blocks, p->size, &crc)) globalPos += p->size; pos = XZ_GET_PAD_SIZE(globalPos); @@ -211,12 +211,12 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I globalPos += pos; crc = CrcUpdate(crc, buf + 4 - pos, pos); - SetUi32(buf + 4, CRC_GET_DIGEST(crc)); + SetUi32(buf + 4, CRC_GET_DIGEST(crc)) - SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)); + SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)) buf[8 + 8] = (Byte)(flags >> 8); buf[8 + 9] = (Byte)(flags & 0xFF); - SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)); + SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)) buf[8 + 10] = XZ_FOOTER_SIG_0; buf[8 + 11] = XZ_FOOTER_SIG_1; @@ -230,7 +230,7 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I typedef struct { ISeqInStream vt; - ISeqInStream *realStream; + ISeqInStreamPtr realStream; const Byte *data; UInt64 limit; UInt64 processed; @@ -251,9 +251,9 @@ static void SeqCheckInStream_GetDigest(CSeqCheckInStream *p, Byte *digest) XzCheck_Final(&p->check, digest); } -static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *size) +static SRes SeqCheckInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) { - CSeqCheckInStream *p = CONTAINER_FROM_VTBL(pp, CSeqCheckInStream, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqCheckInStream) size_t size2 = *size; SRes res = SZ_OK; @@ -285,15 +285,15 @@ static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *si typedef struct { ISeqOutStream vt; - ISeqOutStream *realStream; + ISeqOutStreamPtr realStream; Byte *outBuf; size_t outBufLimit; UInt64 processed; } CSeqSizeOutStream; -static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) +static size_t SeqSizeOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size) { - CSeqSizeOutStream *p = CONTAINER_FROM_VTBL(pp, CSeqSizeOutStream, vt); + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqSizeOutStream) if (p->realStream) size = ISeqOutStream_Write(p->realStream, data, size); else @@ -313,8 +313,8 @@ static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, typedef struct { - ISeqInStream p; - ISeqInStream *realStream; + ISeqInStream vt; + ISeqInStreamPtr realStream; IStateCoder StateCoder; Byte *buf; size_t curPos; @@ -323,7 +323,39 @@ typedef struct } CSeqInFilter; -SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); +static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Enc[] = +{ + Z7_BRANCH_CONV_ENC(PPC), + Z7_BRANCH_CONV_ENC(IA64), + Z7_BRANCH_CONV_ENC(ARM), + Z7_BRANCH_CONV_ENC(ARMT), + Z7_BRANCH_CONV_ENC(SPARC), + Z7_BRANCH_CONV_ENC(ARM64) +}; + +static SizeT XzBcFilterStateBase_Filter_Enc(CXzBcFilterStateBase *p, Byte *data, SizeT size) +{ + switch (p->methodId) + { + case XZ_ID_Delta: + Delta_Encode(p->delta_State, p->delta, data, size); + break; + case XZ_ID_X86: + size = (SizeT)(z7_BranchConvSt_X86_Enc(data, size, p->ip, &p->X86_State) - data); + break; + default: + if (p->methodId >= XZ_ID_PPC) + { + const UInt32 i = p->methodId - XZ_ID_PPC; + if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Enc)) + size = (SizeT)(g_Funcs_BranchConv_RISC_Enc[i](data, size, p->ip) - data); + } + break; + } + p->ip += (UInt32)size; + return size; +} + static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPtr alloc) { @@ -335,17 +367,17 @@ static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPt } p->curPos = p->endPos = 0; p->srcWasFinished = 0; - RINOK(BraState_SetFromMethod(&p->StateCoder, props->id, 1, alloc)); - RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)); + RINOK(Xz_StateCoder_Bc_SetFromMethod_Func(&p->StateCoder, props->id, XzBcFilterStateBase_Filter_Enc, alloc)) + RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)) p->StateCoder.Init(p->StateCoder.p); return SZ_OK; } -static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) +static SRes SeqInFilter_Read(ISeqInStreamPtr pp, void *data, size_t *size) { - CSeqInFilter *p = CONTAINER_FROM_VTBL(pp, CSeqInFilter, p); - size_t sizeOriginal = *size; + Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInFilter) + const size_t sizeOriginal = *size; if (sizeOriginal == 0) return SZ_OK; *size = 0; @@ -356,7 +388,7 @@ static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) { p->curPos = 0; p->endPos = FILTER_BUF_SIZE; - RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)); + RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)) if (p->endPos == 0) p->srcWasFinished = 1; } @@ -381,7 +413,7 @@ static void SeqInFilter_Construct(CSeqInFilter *p) { p->buf = NULL; p->StateCoder.p = NULL; - p->p.Read = SeqInFilter_Read; + p->vt.Read = SeqInFilter_Read; } static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) @@ -406,13 +438,13 @@ static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) typedef struct { ISeqInStream vt; - ISeqInStream *inStream; + ISeqInStreamPtr inStream; CSbEnc enc; } CSbEncInStream; -static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) +static SRes SbEncInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size) { - CSbEncInStream *p = CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); + CSbEncInStream *p = Z7_CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); size_t sizeOriginal = *size; if (sizeOriginal == 0) return SZ_OK; @@ -422,7 +454,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) if (p->enc.needRead && !p->enc.readWasFinished) { size_t processed = p->enc.needReadSizeMax; - RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)); + RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)) p->enc.readPos += processed; if (processed == 0) { @@ -433,7 +465,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) } *size = sizeOriginal; - RINOK(SbEnc_Read(&p->enc, data, size)); + RINOK(SbEnc_Read(&p->enc, data, size)) if (*size != 0 || !p->enc.needRead) return SZ_OK; } @@ -473,7 +505,7 @@ void XzFilterProps_Init(CXzFilterProps *p) void XzProps_Init(CXzProps *p) { p->checkId = XZ_CHECK_CRC32; - p->blockSize = XZ_PROPS__BLOCK_SIZE__AUTO; + p->blockSize = XZ_PROPS_BLOCK_SIZE_AUTO; p->numBlockThreads_Reduced = -1; p->numBlockThreads_Max = -1; p->numTotalThreads = -1; @@ -502,8 +534,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) t2 = p->numBlockThreads_Max; t3 = p->numTotalThreads; - if (t2 > MTCODER__THREADS_MAX) - t2 = MTCODER__THREADS_MAX; + if (t2 > MTCODER_THREADS_MAX) + t2 = MTCODER_THREADS_MAX; if (t3 <= 0) { @@ -519,8 +551,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p) t1 = 1; t2 = t3; } - if (t2 > MTCODER__THREADS_MAX) - t2 = MTCODER__THREADS_MAX; + if (t2 > MTCODER_THREADS_MAX) + t2 = MTCODER_THREADS_MAX; } else if (t1 <= 0) { @@ -571,7 +603,7 @@ static void XzProps_Normalize(CXzProps *p) /* we normalize xzProps properties, but we normalize only some of CXzProps::lzma2Props properties. Lzma2Enc_SetProps() will normalize lzma2Props later. */ - if (p->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID) + if (p->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID) { p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; p->numBlockThreads_Reduced = 1; @@ -583,15 +615,15 @@ static void XzProps_Normalize(CXzProps *p) else { CLzma2EncProps *lzma2 = &p->lzma2Props; - if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) + if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) { // xz-auto p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; - if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) + if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) { // if (xz-auto && lzma2-solid) - we use solid for both - p->blockSize = XZ_PROPS__BLOCK_SIZE__SOLID; + p->blockSize = XZ_PROPS_BLOCK_SIZE_SOLID; p->numBlockThreads_Reduced = 1; p->numBlockThreads_Max = 1; if (p->lzma2Props.numTotalThreads <= 0) @@ -610,9 +642,9 @@ static void XzProps_Normalize(CXzProps *p) p->blockSize = tp.blockSize; // fixed or solid p->numBlockThreads_Reduced = tp.numBlockThreads_Reduced; p->numBlockThreads_Max = tp.numBlockThreads_Max; - if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) - lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID - if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) + if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) + lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID + if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) lzma2->lzmaProps.reduceSize = tp.blockSize; lzma2->numBlockThreads_Reduced = 1; lzma2->numBlockThreads_Max = 1; @@ -631,9 +663,9 @@ static void XzProps_Normalize(CXzProps *p) r = p->blockSize; lzma2->lzmaProps.reduceSize = r; } - if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) - lzma2->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; - else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) + if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO) + lzma2->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID; + else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) lzma2->blockSize = p->blockSize; XzEncProps_Normalize_Fixed(p); @@ -704,17 +736,17 @@ typedef struct static SRes Xz_CompressBlock( CLzma2WithFilters *lzmaf, - ISeqOutStream *outStream, + ISeqOutStreamPtr outStream, Byte *outBufHeader, Byte *outBufData, size_t outBufDataLimit, - ISeqInStream *inStream, + ISeqInStreamPtr inStream, // UInt64 expectedSize, const Byte *inBuf, // used if (!inStream) size_t inBufSize, // used if (!inStream), it's block size, props->blockSize is ignored const CXzProps *props, - ICompressProgress *progress, + ICompressProgressPtr progress, int *inStreamFinished, /* only for inStream version */ CXzEncBlockInfo *blockSizes, ISzAllocPtr alloc, @@ -731,12 +763,12 @@ static SRes Xz_CompressBlock( *inStreamFinished = 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 @@ static SRes Xz_CompressBlock( else if (fp->ipDefined) { Byte *ptr = filter->props; - SetUi32(ptr, fp->ip); + SetUi32(ptr, fp->ip) filter->propsSize = 4; } } @@ -777,13 +809,13 @@ static SRes Xz_CompressBlock( if (props->blockSize != (UInt64)(Int64)-1) if (expectedSize > props->blockSize) block.unpackSize = props->blockSize; - XzBlock_SetHasUnpackSize(&block); + XzBlock_SetHasUnpackSize(&block) } */ if (outStream) { - RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); + RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) } checkInStream.vt.Read = SeqCheckInStream_Read; @@ -801,13 +833,13 @@ static SRes Xz_CompressBlock( if (fp->id == XZ_ID_Subblock) { lzmaf->sb.inStream = &checkInStream.vt; - RINOK(SbEncInStream_Init(&lzmaf->sb)); + RINOK(SbEncInStream_Init(&lzmaf->sb)) } else #endif { lzmaf->filter.realStream = &checkInStream.vt; - RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)); + RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)) } } @@ -841,7 +873,7 @@ static SRes Xz_CompressBlock( #ifdef USE_SUBBLOCK (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.vt: #endif - &lzmaf->filter.p) : + &lzmaf->filter.vt) : &checkInStream.vt) : NULL, useStream ? NULL : inBuf, @@ -852,7 +884,7 @@ static SRes Xz_CompressBlock( if (outBuf) seqSizeOutStream.processed += outSize; - RINOK(res); + RINOK(res) blockSizes->unpackSize = checkInStream.processed; } { @@ -866,7 +898,7 @@ static SRes Xz_CompressBlock( buf[3] = 0; SeqCheckInStream_GetDigest(&checkInStream, buf + 4); - RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))); + RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))) blockSizes->totalSize = seqSizeOutStream.processed - padSize; @@ -877,12 +909,12 @@ static SRes Xz_CompressBlock( seqSizeOutStream.processed = 0; block.unpackSize = blockSizes->unpackSize; - XzBlock_SetHasUnpackSize(&block); + XzBlock_SetHasUnpackSize(&block) block.packSize = packSize; - XzBlock_SetHasPackSize(&block); + XzBlock_SetHasPackSize(&block) - RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); + RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)) blockSizes->headerSize = (size_t)seqSizeOutStream.processed; blockSizes->totalSize += seqSizeOutStream.processed; @@ -906,15 +938,15 @@ static SRes Xz_CompressBlock( typedef struct { ICompressProgress vt; - ICompressProgress *progress; + ICompressProgressPtr progress; UInt64 inOffset; UInt64 outOffset; } CCompressProgress_XzEncOffset; -static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) +static SRes CompressProgress_XzEncOffset_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) { - const CCompressProgress_XzEncOffset *p = CONTAINER_FROM_VTBL(pp, CCompressProgress_XzEncOffset, vt); + const CCompressProgress_XzEncOffset *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CCompressProgress_XzEncOffset, vt); inSize += p->inOffset; outSize += p->outOffset; return ICompressProgress_Progress(p->progress, inSize, outSize); @@ -923,7 +955,7 @@ static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, U -typedef struct +struct CXzEnc { ISzAllocPtr alloc; ISzAllocPtr allocBig; @@ -933,20 +965,19 @@ typedef struct CXzEncIndex xzIndex; - CLzma2WithFilters lzmaf_Items[MTCODER__THREADS_MAX]; + CLzma2WithFilters lzmaf_Items[MTCODER_THREADS_MAX]; size_t outBufSize; /* size of allocated outBufs[i] */ - Byte *outBufs[MTCODER__BLOCKS_MAX]; + Byte *outBufs[MTCODER_BLOCKS_MAX]; - #ifndef _7ZIP_ST + #ifndef Z7_ST unsigned checkType; - ISeqOutStream *outStream; + ISeqOutStreamPtr outStream; BoolInt mtCoder_WasConstructed; CMtCoder mtCoder; - CXzEncBlockInfo EncBlocks[MTCODER__BLOCKS_MAX]; + CXzEncBlockInfo EncBlocks[MTCODER_BLOCKS_MAX]; #endif - -} CXzEnc; +}; static void XzEnc_Construct(CXzEnc *p) @@ -955,13 +986,13 @@ static void XzEnc_Construct(CXzEnc *p) XzEncIndex_Construct(&p->xzIndex); - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) Lzma2WithFilters_Construct(&p->lzmaf_Items[i]); - #ifndef _7ZIP_ST + #ifndef Z7_ST p->mtCoder_WasConstructed = 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_Construct(CXzEnc *p) static void XzEnc_FreeOutBufs(CXzEnc *p) { unsigned i; - for (i = 0; i < MTCODER__BLOCKS_MAX; i++) + for (i = 0; i < MTCODER_BLOCKS_MAX; i++) if (p->outBufs[i]) { ISzAlloc_Free(p->alloc, p->outBufs[i]); @@ -988,10 +1019,10 @@ static void XzEnc_Free(CXzEnc *p, ISzAllocPtr alloc) XzEncIndex_Free(&p->xzIndex, alloc); - for (i = 0; i < MTCODER__THREADS_MAX; i++) + for (i = 0; i < MTCODER_THREADS_MAX; i++) Lzma2WithFilters_Free(&p->lzmaf_Items[i], alloc); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (p->mtCoder_WasConstructed) { MtCoder_Destruct(&p->mtCoder); @@ -1013,37 +1044,38 @@ CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig) p->expectedDataSize = (UInt64)(Int64)-1; p->alloc = alloc; p->allocBig = allocBig; - return p; + return (CXzEncHandle)p; } +// #define GET_CXzEnc_p CXzEnc *p = (CXzEnc *)(void *)pp; -void XzEnc_Destroy(CXzEncHandle pp) +void XzEnc_Destroy(CXzEncHandle p) { - CXzEnc *p = (CXzEnc *)pp; + // GET_CXzEnc_p XzEnc_Free(p, p->alloc); ISzAlloc_Free(p->alloc, p); } -SRes XzEnc_SetProps(CXzEncHandle pp, const CXzProps *props) +SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props) { - CXzEnc *p = (CXzEnc *)pp; + // GET_CXzEnc_p p->xzProps = *props; XzProps_Normalize(&p->xzProps); return SZ_OK; } -void XzEnc_SetDataSize(CXzEncHandle pp, UInt64 expectedDataSiize) +void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize) { - CXzEnc *p = (CXzEnc *)pp; + // GET_CXzEnc_p p->expectedDataSize = expectedDataSiize; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, const Byte *src, size_t srcSize, int finished) @@ -1073,7 +1105,7 @@ static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBuf MtProgressThunk_CreateVTable(&progressThunk); progressThunk.mtProgress = &me->mtCoder.mtProgress; - MtProgressThunk_Init(&progressThunk); + MtProgressThunk_INIT(&progressThunk) { CXzEncBlockInfo blockSizes; @@ -1112,11 +1144,11 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) const CXzEncBlockInfo *bInfo = &me->EncBlocks[outBufIndex]; const Byte *data = me->outBufs[outBufIndex]; - RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)); + RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)) { UInt64 totalPackFull = bInfo->totalSize + XZ_GET_PAD_SIZE(bInfo->totalSize); - RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)); + RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)) } return XzEncIndex_AddIndexRecord(&me->xzIndex, bInfo->unpackSize, bInfo->totalSize, me->alloc); @@ -1126,9 +1158,9 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex) -SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress) +SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress) { - CXzEnc *p = (CXzEnc *)pp; + // GET_CXzEnc_p const CXzProps *props = &p->xzProps; @@ -1137,7 +1169,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr UInt64 numBlocks = 1; UInt64 blockSize = props->blockSize; - if (blockSize != XZ_PROPS__BLOCK_SIZE__SOLID + if (blockSize != XZ_PROPS_BLOCK_SIZE_SOLID && props->reduceSize != (UInt64)(Int64)-1) { numBlocks = props->reduceSize / blockSize; @@ -1147,13 +1179,13 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr else blockSize = (UInt64)1 << 62; - RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)); + RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)) } - RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)); + RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)) - #ifndef _7ZIP_ST + #ifndef Z7_ST if (props->numBlockThreads_Reduced > 1) { IMtCoderCallback2 vt; @@ -1180,8 +1212,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr p->mtCoder.mtCallback = &vt; p->mtCoder.mtCallbackObject = p; - if ( props->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID - || props->blockSize == XZ_PROPS__BLOCK_SIZE__AUTO) + if ( props->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID + || props->blockSize == XZ_PROPS_BLOCK_SIZE_AUTO) return SZ_ERROR_FAIL; p->mtCoder.blockSize = (size_t)props->blockSize; @@ -1200,7 +1232,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr p->mtCoder.numThreadsMax = (unsigned)props->numBlockThreads_Max; p->mtCoder.expectedDataSize = p->expectedDataSize; - RINOK(MtCoder_Code(&p->mtCoder)); + RINOK(MtCoder_Code(&p->mtCoder)) } else #endif @@ -1217,7 +1249,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr writeStartSizes = 0; - if (props->blockSize != XZ_PROPS__BLOCK_SIZE__SOLID) + if (props->blockSize != XZ_PROPS_BLOCK_SIZE_SOLID) { writeStartSizes = (props->forceWriteSizesInHeader > 0); @@ -1274,18 +1306,18 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr &inStreamFinished, &blockSizes, p->alloc, - p->allocBig)); + p->allocBig)) { UInt64 totalPackFull = blockSizes.totalSize + XZ_GET_PAD_SIZE(blockSizes.totalSize); if (writeStartSizes) { - RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)); - RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)); + RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)) + RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)) } - RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)); + RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)) progress2.inOffset += blockSizes.unpackSize; progress2.outOffset += totalPackFull; @@ -1302,8 +1334,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr #include "Alloc.h" -SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, - const CXzProps *props, ICompressProgress *progress) +SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, + const CXzProps *props, ICompressProgressPtr progress) { SRes res; CXzEncHandle xz = XzEnc_Create(&g_Alloc, &g_BigAlloc); @@ -1317,7 +1349,7 @@ SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, } -SRes Xz_EncodeEmpty(ISeqOutStream *outStream) +SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream) { SRes res; CXzEncIndex xzIndex; diff --git a/C/XzEnc.h b/C/XzEnc.h index 0c29e7e1..77b78c01 100644 --- a/C/XzEnc.h +++ b/C/XzEnc.h @@ -1,8 +1,8 @@ /* XzEnc.h -- Xz Encode -2017-06-27 : Igor Pavlov : Public domain */ +2023-04-13 : Igor Pavlov : Public domain */ -#ifndef __XZ_ENC_H -#define __XZ_ENC_H +#ifndef ZIP7_INC_XZ_ENC_H +#define ZIP7_INC_XZ_ENC_H #include "Lzma2Enc.h" @@ -11,8 +11,8 @@ EXTERN_C_BEGIN -#define XZ_PROPS__BLOCK_SIZE__AUTO LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO -#define XZ_PROPS__BLOCK_SIZE__SOLID LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID +#define XZ_PROPS_BLOCK_SIZE_AUTO LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO +#define XZ_PROPS_BLOCK_SIZE_SOLID LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID typedef struct @@ -41,19 +41,20 @@ typedef struct void XzProps_Init(CXzProps *p); - -typedef void * CXzEncHandle; +typedef struct CXzEnc CXzEnc; +typedef CXzEnc * CXzEncHandle; +// Z7_DECLARE_HANDLE(CXzEncHandle) CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); void XzEnc_Destroy(CXzEncHandle p); SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props); void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize); -SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress); +SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress); -SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, - const CXzProps *props, ICompressProgress *progress); +SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, + const CXzProps *props, ICompressProgressPtr progress); -SRes Xz_EncodeEmpty(ISeqOutStream *outStream); +SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream); EXTERN_C_END diff --git a/C/XzIn.c b/C/XzIn.c index 84f868ec..d0fc7636 100644 --- a/C/XzIn.c +++ b/C/XzIn.c @@ -1,5 +1,5 @@ /* XzIn.c - Xz input -2021-09-04 : Igor Pavlov : Public domain */ +2023-04-02 : Igor Pavlov : Public domain */ #include "Precomp.h" @@ -15,11 +15,13 @@ #define XZ_FOOTER_SIG_CHECK(p) ((p)[0] == XZ_FOOTER_SIG_0 && (p)[1] == XZ_FOOTER_SIG_1) -SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) +SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream) { Byte sig[XZ_STREAM_HEADER_SIZE]; - RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE)); - if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) + size_t processedSize = XZ_STREAM_HEADER_SIZE; + RINOK(SeqInStream_ReadMax(inStream, sig, &processedSize)) + if (processedSize != XZ_STREAM_HEADER_SIZE + || memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) return SZ_ERROR_NO_ARCHIVE; return Xz_ParseHeader(p, sig); } @@ -29,12 +31,12 @@ SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) if (s == 0) return SZ_ERROR_ARCHIVE; \ pos += s; } -SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes) +SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes) { Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; unsigned headerSize; *headerSizeRes = 0; - RINOK(SeqInStream_ReadByte(inStream, &header[0])); + RINOK(SeqInStream_ReadByte(inStream, &header[0])) headerSize = (unsigned)header[0]; if (headerSize == 0) { @@ -46,7 +48,12 @@ SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, U *isIndex = 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 Xz_GetUnpackSize(const CXzStream *p) UInt64 size = 0; size_t i; for (i = 0; i < p->numBlocks; i++) - ADD_SIZE_CHECK(size, p->blocks[i].unpackSize); + { + ADD_SIZE_CHECK(size, p->blocks[i].unpackSize) + } return size; } @@ -67,12 +76,14 @@ UInt64 Xz_GetPackSize(const CXzStream *p) UInt64 size = 0; size_t i; for (i = 0; i < p->numBlocks; i++) - ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3); + { + ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3) + } return size; } /* -SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream) +SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStreamPtr inStream) { return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f)); } @@ -93,7 +104,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt { UInt64 numBlocks64; - READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64); + READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64) numBlocks = (size_t)numBlocks64; if (numBlocks != numBlocks64 || numBlocks * 2 > size) return SZ_ERROR_ARCHIVE; @@ -110,8 +121,8 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt for (i = 0; i < numBlocks; i++) { CXzBlockSizes *block = &p->blocks[i]; - READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize); - READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize); + READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize) + READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize) if (block->totalSize == 0) return SZ_ERROR_ARCHIVE; } @@ -122,7 +133,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; } -static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAllocPtr alloc) +static SRes Xz_ReadIndex(CXzStream *p, ILookInStreamPtr stream, UInt64 indexSize, ISzAllocPtr alloc) { SRes res; size_t size; @@ -142,14 +153,14 @@ static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, return res; } -static SRes LookInStream_SeekRead_ForArc(ILookInStream *stream, UInt64 offset, void *buf, size_t size) +static SRes LookInStream_SeekRead_ForArc(ILookInStreamPtr stream, UInt64 offset, void *buf, size_t size) { - RINOK(LookInStream_SeekTo(stream, offset)); + RINOK(LookInStream_SeekTo(stream, offset)) return LookInStream_Read(stream, buf, size); /* return LookInStream_Read2(stream, buf, size, SZ_ERROR_NO_ARCHIVE); */ } -static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAllocPtr alloc) +static SRes Xz_ReadBackward(CXzStream *p, ILookInStreamPtr stream, Int64 *startOffset, ISzAllocPtr alloc) { UInt64 indexSize; Byte buf[XZ_STREAM_FOOTER_SIZE]; @@ -159,7 +170,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff return SZ_ERROR_NO_ARCHIVE; pos -= XZ_STREAM_FOOTER_SIZE; - RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); + RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) if (!XZ_FOOTER_SIG_CHECK(buf + 10)) { @@ -174,7 +185,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff i = (pos > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)pos; pos -= i; - RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)); + RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)) total += (UInt32)i; for (; i != 0; i--) if (temp[i - 1] != 0) @@ -193,7 +204,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff if (pos < XZ_STREAM_FOOTER_SIZE) return SZ_ERROR_NO_ARCHIVE; pos -= XZ_STREAM_FOOTER_SIZE; - RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); + RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)) if (!XZ_FOOTER_SIG_CHECK(buf + 10)) return SZ_ERROR_NO_ARCHIVE; } @@ -217,8 +228,8 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff return SZ_ERROR_ARCHIVE; pos -= indexSize; - RINOK(LookInStream_SeekTo(stream, pos)); - RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)); + RINOK(LookInStream_SeekTo(stream, pos)) + RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)) { UInt64 totalSize = Xz_GetPackSize(p); @@ -227,7 +238,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff || pos < totalSize + XZ_STREAM_HEADER_SIZE) return SZ_ERROR_ARCHIVE; pos -= (totalSize + XZ_STREAM_HEADER_SIZE); - RINOK(LookInStream_SeekTo(stream, pos)); + RINOK(LookInStream_SeekTo(stream, pos)) *startOffset = (Int64)pos; } { @@ -236,7 +247,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff SecToRead_CreateVTable(&secToRead); secToRead.realStream = stream; - RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)); + RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)) return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE; } } @@ -274,7 +285,9 @@ UInt64 Xzs_GetUnpackSize(const CXzs *p) UInt64 size = 0; size_t i; for (i = 0; i < p->num; i++) - ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])); + { + ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])) + } return size; } @@ -284,15 +297,17 @@ UInt64 Xzs_GetPackSize(const CXzs *p) UInt64 size = 0; size_t i; for (i = 0; i < p->num; i++) - ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])); + { + ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])) + } return size; } */ -SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc) +SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr stream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc) { Int64 endOffset = 0; - RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)); + RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)) *startOffset = endOffset; for (;;) { @@ -301,7 +316,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr Xz_Construct(&st); res = Xz_ReadBackward(&st, stream, startOffset, alloc); st.startOffset = (UInt64)*startOffset; - RINOK(res); + RINOK(res) if (p->num == p->numAllocated) { const size_t newNum = p->num + p->num / 4 + 1; @@ -317,7 +332,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr p->streams[p->num++] = st; if (*startOffset == 0) break; - RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)); + RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)) if (progress && ICompressProgress_Progress(progress, (UInt64)(endOffset - *startOffset), (UInt64)(Int64)-1) != SZ_OK) return SZ_ERROR_PROGRESS; } diff --git a/C/brotli/Brotli-Adjust.sh b/C/brotli/Brotli-Adjust.sh old mode 100755 new mode 100644 diff --git a/C/lizard/AdjustLiz.sh b/C/lizard/AdjustLiz.sh old mode 100755 new mode 100644 diff --git a/C/warn_clang.mak b/C/warn_clang.mak index ed4f908f..0d6446d2 100644 --- a/C/warn_clang.mak +++ b/C/warn_clang.mak @@ -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 --git a/C/warn_clang_mac.mak b/C/warn_clang_mac.mak index 41044a2c..44afc537 100644 --- a/C/warn_clang_mac.mak +++ b/C/warn_clang_mac.mak @@ -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 --git a/C/zstd/AdjustZS.sh b/C/zstd/AdjustZS.sh old mode 100755 new mode 100644 diff --git a/CPP/7zip/7zip.mak b/CPP/7zip/7zip.mak index 2db08cea..4612daed 100644 --- a/CPP/7zip/7zip.mak +++ b/CPP/7zip/7zip.mak @@ -5,14 +5,14 @@ OBJS = \ $(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 --git a/CPP/7zip/7zip_gcc.mak b/CPP/7zip/7zip_gcc.mak index f65cff2e..8bf0594e 100644 --- a/CPP/7zip/7zip_gcc.mak +++ b/CPP/7zip/7zip_gcc.mak @@ -12,23 +12,35 @@ ifdef USE_JWASM 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 @@ endif 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 @@ MY_MKDIR=mkdir 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 @@ RM = rm -f 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 @@ endif -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 @@ endif # IS_MINGW ifdef USE_ASM -CONSOLE_ASM_FLAGS=-D_7ZIP_ASM +CONSOLE_ASM_FLAGS=-DZ7_7ZIP_ASM else CONSOLE_ASM_FLAGS= endif @@ -179,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 = $(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 @@ all: $(O) $(PROGPATH) $(STATIC_TARGET) $(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 @@ $(PROGPATH_STATIC): $(OBJS) 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 @@ $O/MethodId.o: ../../Common/MethodId.cpp $(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 @@ $O/Sha256.o: ../../../../C/Sha256.c $(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 @@ $O/LzmaDecOpt.o: ../../../../Asm/arm64/LzmaDecOpt.S ../../../../Asm/arm64/7zAsm. endif $O/LzmaDec.o: ../../../../C/LzmaDec.c - $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< + $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $< else @@ -1227,13 +1269,6 @@ endif -$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 --git a/CPP/7zip/Archive/7z/7z.dsp b/CPP/7zip/Archive/7z/7z.dsp index ffd28721..2c3e1447 100644 --- a/CPP/7zip/Archive/7z/7z.dsp +++ b/CPP/7zip/Archive/7z/7z.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # 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 @@ BSC32=bscmake.exe # 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 @@ LINK32=link.exe # 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 @@ BSC32=bscmake.exe # 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 @@ SOURCE=..\ArchiveExports.cpp # 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 @@ SOURCE=..\..\Common\VirtThread.h # 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 --git a/CPP/7zip/Archive/7z/7zCompressionMode.h b/CPP/7zip/Archive/7z/7zCompressionMode.h index 9e846345..ac1f6ad1 100644 --- a/CPP/7zip/Archive/7z/7zCompressionMode.h +++ b/CPP/7zip/Archive/7z/7zCompressionMode.h @@ -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 @@ struct CCompressionMethodMode 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 @@ struct CCompressionMethodMode 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 @@ struct CCompressionMethodMode , PasswordIsDefined(false) {} +#ifdef Z7_CPP_IS_SUPPORTED_default + CCompressionMethodMode(const CCompressionMethodMode &) = default; + CCompressionMethodMode& operator =(const CCompressionMethodMode &) = default; +#endif ~CCompressionMethodMode() { Password.Wipe_and_Empty(); } }; diff --git a/CPP/7zip/Archive/7z/7zDecode.cpp b/CPP/7zip/Archive/7z/7zDecode.cpp index c27c8fbc..5420dcee 100644 --- a/CPP/7zip/Archive/7z/7zDecode.cpp +++ b/CPP/7zip/Archive/7z/7zDecode.cpp @@ -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 @@ static bool AreBindInfoExEqual(const CBindInfoEx &a1, const CBindInfoEx &a2) } 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 @@ struct CLockedInStream: #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 @@ class CLockedSequentialInStreamMT: _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 @@ STDMETHODIMP CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 * #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 @@ class CLockedSequentialInStreamST: _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 @@ HRESULT CDecoder::Decode( , 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 @@ HRESULT CDecoder::Decode( 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 @@ HRESULT CDecoder::Decode( #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 @@ HRESULT CDecoder::Decode( CCreatedCoder cod; RINOK(CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS - coderInfo.MethodID, false, cod)); + coderInfo.MethodID, false, cod)) if (coderInfo.IsSimpleCoder()) { @@ -333,13 +326,13 @@ HRESULT CDecoder::Decode( // 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 @@ HRESULT CDecoder::Decode( _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 @@ HRESULT CDecoder::Decode( 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 @@ HRESULT CDecoder::Decode( 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 @@ HRESULT CDecoder::Decode( 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 @@ HRESULT CDecoder::Decode( if (folderInfo.PackStreams.Size() == 1) { - RINOK(inStream->Seek((Int64)packPos, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, packPos)) packStream = inStream; } else diff --git a/CPP/7zip/Archive/7z/7zDecode.h b/CPP/7zip/Archive/7z/7zDecode.h index eeb146e3..ee9d9c25 100644 --- a/CPP/7zip/Archive/7z/7zDecode.h +++ b/CPP/7zip/Archive/7z/7zDecode.h @@ -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 @@ struct CBindInfoEx: public NCoderMixer2::CBindInfo 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 @@ class CDecoder , 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 --git a/CPP/7zip/Archive/7z/7zEncode.cpp b/CPP/7zip/Archive/7z/7zEncode.cpp index 83b0f18f..78c91cfa 100644 --- a/CPP/7zip/Archive/7z/7zEncode.cpp +++ b/CPP/7zip/Archive/7z/7zEncode.cpp @@ -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 @@ void CEncoder::InitBindConv() { 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 @@ void CEncoder::InitBindConv() 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 @@ void CEncoder::SetFolder(CFolder &folder) { 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 @@ void CEncoder::SetFolder(CFolder &folder) 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 @@ void CMtEncMultiProgress::Init(ICompressProgressInfo *progress) 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 @@ HRESULT CEncoder::CreateMixerCoder( #endif } - RINOK(_mixer->SetBindInfo(_bindInfo)); + RINOK(_mixer->SetBindInfo(_bindInfo)) FOR_VECTOR (m, _options.Methods) { @@ -158,23 +161,27 @@ HRESULT CEncoder::CreateMixerCoder( { 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 @@ HRESULT CEncoder::CreateMixerCoder( RINOK(setCoderMt->SetNumberOfThreads( /* _options.NumThreads */ methodFull.NumThreads - )); + )) } } #endif - RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon)); + RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon)) /* CMyComPtr resetSalt; @@ -202,13 +209,13 @@ HRESULT CEncoder::CreateMixerCoder( // 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 @@ HRESULT CEncoder::CreateMixerCoder( ((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 @@ HRESULT CEncoder::CreateMixerCoder( -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 @@ HRESULT CEncoder::Encode( 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 @@ HRESULT CEncoder::Encode( */ + /* 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 @@ HRESULT CEncoder::Encode( 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 @@ HRESULT CEncoder::Encode( 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 @@ HRESULT CEncoder::Encode( 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 @@ HRESULT CEncoder::EncoderConstr() 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 --git a/CPP/7zip/Archive/7z/7zEncode.h b/CPP/7zip/Archive/7z/7zEncode.h index 6ea7f276..849ac63b 100644 --- a/CPP/7zip/Archive/7z/7zEncode.h +++ b/CPP/7zip/Archive/7z/7zEncode.h @@ -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 @@ class CMtEncMultiProgress: 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 @@ class CEncoder MY_UNCOPYABLE 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 @@ class CEncoder MY_UNCOPYABLE 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 --git a/CPP/7zip/Archive/7z/7zExtract.cpp b/CPP/7zip/Archive/7z/7zExtract.cpp index 8ca815d4..5498c590 100644 --- a/CPP/7zip/Archive/7z/7zExtract.cpp +++ b/CPP/7zip/Archive/7z/7zExtract.cpp @@ -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 @@ class CFolderOutStream: UInt64 _rem; const UInt32 *_indexes; + // unsigned _startIndex; unsigned _numFiles; unsigned _fileIndex; @@ -40,8 +42,6 @@ class CFolderOutStream: HRESULT ProcessEmptyFiles(); public: - MY_UNKNOWN_IMP1(ISequentialOutStream) - const CDbEx *_db; CMyComPtr ExtractCallback; @@ -52,8 +52,6 @@ class CFolderOutStream: 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 @@ class CFolderOutStream: HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles) { + // _startIndex = startIndex; _fileIndex = startIndex; _indexes = indexes; _numFiles = numFiles; @@ -76,11 +75,10 @@ HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsig 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 @@ HRESULT CFolderOutStream::OpenFile(bool isCorrupted) 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 @@ HRESULT CFolderOutStream::ProcessEmptyFiles() { 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 @@ STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *proc _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 @@ STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *proc // return S_FALSE; return k_My_HRESULT_WritingWasCut; } - RINOK(OpenFile()); + RINOK(OpenFile()) } return S_OK; @@ -204,18 +202,32 @@ HRESULT CFolderOutStream::FlushCorrupted(Int32 callbackOperationResult) { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } - RINOK(extractCallback->SetTotal(importantTotalUnpacked)); + RINOK(extractCallback->SetTotal(importantTotalUnpacked)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -268,8 +280,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, for (UInt32 i = 0;; lps->OutSize += curUnpacked, lps->InSize += curPacked) { - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= numItems) break; @@ -303,7 +315,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } { - 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 --git a/CPP/7zip/Archive/7z/7zFolderInStream.cpp b/CPP/7zip/Archive/7z/7zFolderInStream.cpp index cf50e694..08231893 100644 --- a/CPP/7zip/Archive/7z/7zFolderInStream.cpp +++ b/CPP/7zip/Archive/7z/7zFolderInStream.cpp @@ -15,32 +15,38 @@ void CFolderInStream::Init(IArchiveUpdateCallback *updateCallback, _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 @@ HRESULT CFolderInStream::OpenStream() } } - RINOK(AddFileInfo(result == S_OK)); + RINOK(AddFileInfo(result == S_OK)) } return S_OK; } @@ -117,13 +123,13 @@ HRESULT CFolderInStream::AddFileInfo(bool isProcessed) // 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 @@ HRESULT CFolderInStream::AddFileInfo(bool isProcessed) 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 @@ STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSiz { 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 @@ STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value) 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 --git a/CPP/7zip/Archive/7z/7zFolderInStream.h b/CPP/7zip/Archive/7z/7zFolderInStream.h index f054e681..6447b25c 100644 --- a/CPP/7zip/Archive/7z/7zFolderInStream.h +++ b/CPP/7zip/Archive/7z/7zFolderInStream.h @@ -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 @@ class CFolderInStream: 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 @@ class CFolderInStream: 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 --git a/CPP/7zip/Archive/7z/7zHandler.cpp b/CPP/7zip/Archive/7z/7zHandler.cpp index 4942d232..7f3a4c5d 100644 --- a/CPP/7zip/Archive/7z/7zHandler.cpp +++ b/CPP/7zip/Archive/7z/7zHandler.cpp @@ -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 @@ namespace N7z { 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 void ConvertMethodIdToString(AString &res, UInt64 id) 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 @@ void CHandler::AddMethodName(AString &s, UInt64 id) #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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) GetStringForSizeValue(temp, pm.LzmaDic); s += temp; } + /* + else if (id == k_ZSTD) + { + s += "ZSTD"; + } + */ else AddMethodName(s, id); } @@ -269,7 +274,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } } return prop.Detach(value); - #ifndef _SFX + #ifndef Z7_SFX COM_TRY_END #endif } @@ -285,17 +290,17 @@ bool CHandler::IsFolderEncrypted(CNum folderIndex) const { 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 @@ bool CHandler::IsFolderEncrypted(CNum folderIndex) const 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 @@ STDMETHODIMP CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *par 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 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const { @@ -389,9 +394,9 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 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 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const { 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 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 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); @@ -593,6 +598,16 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 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) @@ -600,8 +615,8 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 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); } } @@ -609,8 +624,8 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 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++; @@ -639,7 +654,7 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const pos -= ConvertMethodIdToString_Back(temp + pos, id64); else { - unsigned len = methodName.Len(); + const unsigned len = methodName.Len(); if (len + 5 > pos) break; pos -= len; @@ -663,9 +678,9 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const #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; @@ -692,7 +707,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val { // prop = ref2.PackSize; { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; + const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; if (folderIndex != kNumNoIndex) { if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2) @@ -733,24 +748,24 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 && @@ -764,7 +779,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val PropVarEm_Set_UInt64(value, 0); } break; - */ + #endif #endif } @@ -773,13 +788,13 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val // 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 @@ -787,31 +802,31 @@ STDMETHODIMP CHandler::Open(IInStream *stream, { 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; } @@ -824,19 +839,19 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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(); @@ -845,10 +860,10 @@ STDMETHODIMP CHandler::Close() 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 @@ -863,19 +878,19 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 --git a/CPP/7zip/Archive/7z/7zHandler.h b/CPP/7zip/Archive/7z/7zHandler.h index 08bd6540..b1c04669 100644 --- a/CPP/7zip/Archive/7z/7zHandler.h +++ b/CPP/7zip/Archive/7z/7zHandler.h @@ -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 NArchive { namespace N7z { -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY class COutHandler: public CMultiMethodProps { @@ -79,73 +79,63 @@ class COutHandler: public CMultiMethodProps #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 @@ class CHandler: #endif bool IsFolderEncrypted(CNum folderIndex) const; - #ifndef _SFX + #ifndef Z7_SFX CRecordVector _fileInfoPopIDs; void FillPopIDs(); @@ -172,6 +162,13 @@ class CHandler: #endif DECL_EXTERNAL_CODECS_VARS + +public: + CHandler(); + ~CHandler() + { + Close(); + } }; }} diff --git a/CPP/7zip/Archive/7z/7zHandlerOut.cpp b/CPP/7zip/Archive/7z/7zHandlerOut.cpp index d364cfd1..54cc4b33 100644 --- a/CPP/7zip/Archive/7z/7zHandlerOut.cpp +++ b/CPP/7zip/Archive/7z/7zHandlerOut.cpp @@ -13,7 +13,7 @@ #include "7zOut.h" #include "7zUpdate.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY using namespace NWindows; @@ -35,7 +35,7 @@ static const UInt32 k_Dictionary_ForHeaders = 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 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 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 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode) SetGlobalLevelTo(oneMethodInfo); - #ifndef _7ZIP_ST + #ifndef Z7_ST const bool numThreads_WasSpecifiedInMethod = (oneMethodInfo.Get_NumThreads() >= 0); if (!numThreads_WasSpecifiedInMethod) { @@ -128,9 +129,9 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode) #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 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode) 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 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode) 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 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode) 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 @@ static HRESULT GetTime(IArchiveUpdateCallback *updateCallback, unsigned index, P // 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 @@ static int AddFolder(CObjectVector &treeFolders, int cur, const USt } */ -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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt db = &volume->Database; } #else - if (_inStream != 0) + if (_inStream) db = &_db; #endif @@ -368,8 +409,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } // 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { NCOM::CPropVariant prop; - RINOK(updateCallback->GetProperty(i, kpidPath, &prop)); + RINOK(updateCallback->GetProperty(i, kpidPath, &prop)) if (prop.vt == VT_EMPTY) { } @@ -492,7 +534,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } #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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { if (_encryptHeadersSpecified) encryptHeaders = _encryptHeaders; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO else encryptHeaders = _passwordIsDefined; #endif @@ -716,13 +759,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt options.MultiThreadMixer = _useMultiThreadMixer; - COutArchive archive; - CArchiveDatabaseOut newDatabase; - - CMyComPtr getPassword; - updateCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getPassword); - /* if (secureBlocks.Sorted.Size() > 1) { @@ -766,9 +804,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } */ - 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ static HRESULT ParseBond(UString &srcString, UInt32 &coder, UInt32 &stream) { 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 @@ static HRESULT ParseBond(UString &srcString, UInt32 &coder, UInt32 &stream) 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 @@ HRESULT COutHandler::SetSolidFromString(const UString &s) 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 @@ HRESULT COutHandler::SetSolidFromPROPVARIANT(const PROPVARIANT &value) 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 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val } 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 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val 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 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR continue; } - RINOK(SetProperty(name, value)); + RINOK(SetProperty(name, value)) } unsigned numEmptyMethods = GetNumEmptyMethods(); diff --git a/CPP/7zip/Archive/7z/7zHeader.cpp b/CPP/7zip/Archive/7z/7zHeader.cpp index acff2fdd..d5f94973 100644 --- a/CPP/7zip/Archive/7z/7zHeader.cpp +++ b/CPP/7zip/Archive/7z/7zHeader.cpp @@ -8,7 +8,7 @@ namespace NArchive { 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 --git a/CPP/7zip/Archive/7z/7zHeader.h b/CPP/7zip/Archive/7z/7zHeader.h index 3a104687..af975852 100644 --- a/CPP/7zip/Archive/7z/7zHeader.h +++ b/CPP/7zip/Archive/7z/7zHeader.h @@ -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 @@ namespace N7z { 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 @@ struct CStartHeader 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 @@ namespace NID const UInt32 k_Copy = 0; const UInt32 k_Delta = 3; +const UInt32 k_ARM64 = 0xa; const UInt32 k_LZMA2 = 0x21; @@ -129,14 +130,17 @@ const UInt32 k_LIZARD= 0x4F71106; 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 --git a/CPP/7zip/Archive/7z/7zIn.cpp b/CPP/7zip/Archive/7z/7zIn.cpp index 7134595c..4defd272 100644 --- a/CPP/7zip/Archive/7z/7zIn.cpp +++ b/CPP/7zip/Archive/7z/7zIn.cpp @@ -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 @@ using namespace NCOM; 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 @@ static void BoolVector_Fill_False(CBoolVector &v, unsigned size) 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 CByteBuffer &byteBuffer) 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 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed) return 0; } - unsigned b = *p++; + const unsigned b = *p++; size--; if ((b & 0x80) == 0) @@ -192,10 +196,10 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed) 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 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed) 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 @@ CNum CInByte2::ReadNum() } } */ - UInt64 value = ReadNumber(); + const UInt64 value = ReadNumber(); if (value > kNumMax) ThrowUnsupported(); return (CNum)value; @@ -249,7 +253,7 @@ UInt32 CInByte2::ReadUInt32() { if (_pos + 4 > _size) ThrowEndOfData(); - UInt32 res = Get32(_buffer + _pos); + const UInt32 res = Get32(_buffer + _pos); _pos += 4; return res; } @@ -258,54 +262,101 @@ UInt64 CInByte2::ReadUInt64() { 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 @@ HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *search } 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) { 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 CInArchive::ReadArchiveProperties(CInArchiveInfo & /* archiveInfo */) 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 @@ void CInByte2::ParseFolder(CFolder &folder) { 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 @@ void CInByte2::ParseFolder(CFolder &folder) 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 @@ void CInByte2::ParseFolder(CFolder &folder) 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 @@ void CInByte2::ParseFolder(CFolder &folder) 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 @@ void CInByte2::ParseFolder(CFolder &folder) 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 CInByte2::ParseFolder(CFolder &folder) 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 @@ void CDatabase::GetPath(unsigned index, UString &path) const 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 @@ HRESULT CDatabase::GetPath_Prop(unsigned index, PROPVARIANT *path) const throw() 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 @@ HRESULT CDatabase::GetPath_Prop(unsigned index, PROPVARIANT *path) const throw() #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 @@ void CInArchive::WaitId(UInt64 id) { for (;;) { - UInt64 type = ReadID(); + const UInt64 type = ReadID(); if (type == id) return; if (type == NID::kEnd) @@ -613,7 +663,7 @@ void CInArchive::WaitId(UInt64 id) 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 @@ void CInArchive::ReadHashDigests(unsigned numItems, CUInt32DefVector &crcs) } -#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 @@ void CInArchive::ReadPackInfo(CFolders &f) 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 @@ void CInArchive::ReadUnpackInfo( CFolders &folders) { WaitId(NID::kFolder); - CNum numFolders = ReadNum(); + const CNum numFolders = ReadNum(); CNum numCodersOutStreams = 0; { @@ -704,18 +751,18 @@ void CInArchive::ReadUnpackInfo( 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 @@ void CInArchive::ReadUnpackInfo( 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 @@ void CInArchive::ReadUnpackInfo( else { UInt32 i; - CNum numBonds = numCoders - 1; + const CNum numBonds = numCoders - 1; if (numInStreams < numBonds) ThrowUnsupported(); @@ -796,7 +843,7 @@ void CInArchive::ReadUnpackInfo( 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 @@ void CInArchive::ReadUnpackInfo( for (;;) { - UInt64 type = ReadID(); + const UInt64 type = ReadID(); if (type == NID::kEnd) return; if (type == NID::kCRC) @@ -882,19 +929,19 @@ void CInArchive::ReadSubStreamsInfo( { // 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 @@ void CInArchive::ReadSubStreamsInfo( { /* 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 @@ void CInArchive::ReadSubStreamsInfo( 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 @@ void CInArchive::ReadSubStreamsInfo( 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 @@ void CInArchive::ReadSubStreamsInfo( 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::ReadBoolVector(unsigned numItems, CBoolVector &v) void CInArchive::ReadBoolVector2(unsigned numItems, CBoolVector &v) { - Byte allAreDefined = ReadByte(); + const Byte allAreDefined = ReadByte(); if (allAreDefined == 0) { ReadBoolVector(numItems, v); @@ -1106,7 +1153,7 @@ HRESULT CInArchive::ReadAndDecodePackedStreams( 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 @@ HRESULT CInArchive::ReadAndDecodePackedStreams( 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::ReadAndDecodePackedStreams( 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 @@ HRESULT CInArchive::ReadHeader( 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 @@ HRESULT CInArchive::ReadHeader( 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 @@ HRESULT CInArchive::ReadHeader( { 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 @@ void CDbEx::FillLinks() 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 @@ void CDbEx::FillLinks() 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 @@ HRESULT CInArchive::ReadDatabase2( 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 @@ HRESULT CInArchive::ReadDatabase2( 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 @@ HRESULT CInArchive::ReadDatabase2( 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 @@ HRESULT CInArchive::ReadDatabase2( 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 @@ HRESULT CInArchive::ReadDatabase2( return ReadHeader( EXTERNAL_CODECS_LOC_VARS db - _7Z_DECODER_CRYPRO_VARS + Z7_7Z_DECODER_CRYPRO_VARS ); } @@ -1680,14 +1727,14 @@ HRESULT CInArchive::ReadDatabase2( 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 --git a/CPP/7zip/Archive/7z/7zIn.h b/CPP/7zip/Archive/7z/7zIn.h index ffa1e4bc..a9c14fb3 100644 --- a/CPP/7zip/Archive/7z/7zIn.h +++ b/CPP/7zip/Archive/7z/7zIn.h @@ -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 @@ namespace N7z { 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 @@ class CInArchive 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 @@ class CInArchive HRESULT ReadDatabase( DECL_EXTERNAL_CODECS_LOC_VARS CDbEx &db - _7Z_DECODER_CRYPRO_VARS_DECL + Z7_7Z_DECODER_CRYPRO_VARS_DECL ); }; diff --git a/CPP/7zip/Archive/7z/7zItem.h b/CPP/7zip/Archive/7z/7zItem.h index 0f9fdada..e8c68bee 100644 --- a/CPP/7zip/Archive/7z/7zItem.h +++ b/CPP/7zip/Archive/7z/7zItem.h @@ -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 CBond struct CFolder { - CLASS_NO_COPY(CFolder) + Z7_CLASS_NO_COPY(CFolder) public: CObjArray2 Coders; CObjArray2 Bonds; @@ -129,6 +129,11 @@ struct CUInt32DefVector 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 --git a/CPP/7zip/Archive/7z/7zOut.cpp b/CPP/7zip/Archive/7z/7zOut.cpp index 2786bf28..7f8fa5b5 100644 --- a/CPP/7zip/Archive/7z/7zOut.cpp +++ b/CPP/7zip/Archive/7z/7zOut.cpp @@ -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 @@ static void SetUInt64(Byte *p, UInt64 d) 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 @@ HRESULT COutArchive::WriteFinishHeader(const CFinishHeader &h) } #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 @@ HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker) 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 @@ HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker) 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 @@ void COutArchive::Close() 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 @@ static unsigned GetBigNumberSize(UInt64 value) 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 @@ HRESULT COutArchive::EncodeStream( 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 @@ HRESULT COutArchive::WriteDatabase( { 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 @@ HRESULT COutArchive::WriteDatabase( RINOK(EncodeStream( EXTERNAL_CODECS_LOC_VARS encoder, buf, - packSizes, folders, outFolders)); + packSizes, folders, outFolders)) _writeToStream = true; @@ -890,11 +882,11 @@ HRESULT COutArchive::WriteDatabase( 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 @@ HRESULT COutArchive::WriteDatabase( } 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 --git a/CPP/7zip/Archive/7z/7zOut.h b/CPP/7zip/Archive/7z/7zOut.h index 1ebad56d..940cafcd 100644 --- a/CPP/7zip/Archive/7z/7zOut.h +++ b/CPP/7zip/Archive/7z/7zOut.h @@ -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 @@ struct CArchiveDatabaseOut: public COutFolders class COutArchive { - UInt64 _prefixHeaderPos; - HRESULT WriteDirect(const void *data, UInt32 size) { return WriteStream(SeqStream, data, size); } UInt64 GetPos() const; @@ -290,44 +290,39 @@ class COutArchive 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 --git a/CPP/7zip/Archive/7z/7zProperties.cpp b/CPP/7zip/Archive/7z/7zProperties.cpp index 4cb5a5e6..d3b3cbe5 100644 --- a/CPP/7zip/Archive/7z/7zProperties.cpp +++ b/CPP/7zip/Archive/7z/7zProperties.cpp @@ -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; }; +// #define STAT_PROP(name, id, vt) { name, id, vt } +#define STAT_PROP(name, id, vt) vt, id + +#define STAT_PROP2(id, vt) STAT_PROP(NULL, id, vt) + +#define k_7z_id_Encrypted 97 +#define k_7z_id_Method 98 +#define k_7z_id_Block 99 + static const CPropMap kPropMap[] = { - { NID::kName, { NULL, kpidPath, VT_BSTR } }, - { NID::kSize, { NULL, kpidSize, VT_UI8 } }, - { NID::kPackInfo, { NULL, kpidPackSize, VT_UI8 } }, + { NID::kName, STAT_PROP2(kpidPath, VT_BSTR) }, + { NID::kSize, STAT_PROP2(kpidSize, VT_UI8) }, + { NID::kPackInfo, STAT_PROP2(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 } }, + #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, { 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 } }, + { 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, { NULL, kpidCRC, VT_UI4 } }, - -// { NID::kIsAux, { NULL, kpidIsAux, VT_BOOL } }, - { NID::kAnti, { NULL, kpidIsAnti, VT_BOOL } } - - #ifndef _SFX - , - { 97, { NULL, kpidEncrypted, VT_BOOL } }, - { 98, { NULL, kpidMethod, VT_BSTR } }, - { 99, { NULL, kpidBlock, VT_UI4 } } + { 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 CopyOneItem(CRecordVector &src, } } -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 RemoveOneItem(CRecordVector &src, UInt32 item) } } -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 @@ void CHandler::FillPopIDs() { _fileInfoPopIDs.Clear(); - #ifdef _7Z_VOL + #ifdef Z7_7Z_VOL if (_volumes.Size() < 1) return; const CVolume &volume = _volumes.Front(); @@ -105,34 +112,31 @@ void CHandler::FillPopIDs() 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 @@ void CHandler::FillPopIDs() #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 --git a/CPP/7zip/Archive/7z/7zProperties.h b/CPP/7zip/Archive/7z/7zProperties.h index 66181795..091c39b4 100644 --- a/CPP/7zip/Archive/7z/7zProperties.h +++ b/CPP/7zip/Archive/7z/7zProperties.h @@ -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 @@ enum kpidPackedSize3, kpidPackedSize4 }; +#endif }} diff --git a/CPP/7zip/Archive/7z/7zRegister.cpp b/CPP/7zip/Archive/7z/7zRegister.cpp index eac8b4f2..1f11079e 100644 --- a/CPP/7zip/Archive/7z/7zRegister.cpp +++ b/CPP/7zip/Archive/7z/7zRegister.cpp @@ -22,6 +22,6 @@ REGISTER_ARC_IO_DECREMENT_SIG( | NArcInfoFlags::kMTime_Default , TIME_PREC_TO_ARC_FLAGS_MASK(NFileTimeType::kWindows) | TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(NFileTimeType::kWindows) - , NULL); + , NULL) }} diff --git a/CPP/7zip/Archive/7z/7zSpecStream.cpp b/CPP/7zip/Archive/7z/7zSpecStream.cpp index 8e45d987..8b531bc7 100644 --- a/CPP/7zip/Archive/7z/7zSpecStream.cpp +++ b/CPP/7zip/Archive/7z/7zSpecStream.cpp @@ -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 --git a/CPP/7zip/Archive/7z/7zSpecStream.h b/CPP/7zip/Archive/7z/7zSpecStream.h index 21155069..78f631e4 100644 --- a/CPP/7zip/Archive/7z/7zSpecStream.h +++ b/CPP/7zip/Archive/7z/7zSpecStream.h @@ -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 --git a/CPP/7zip/Archive/7z/7zUpdate.cpp b/CPP/7zip/Archive/7z/7zUpdate.cpp index 2b8f849a..cc61773b 100644 --- a/CPP/7zip/Archive/7z/7zUpdate.cpp +++ b/CPP/7zip/Archive/7z/7zUpdate.cpp @@ -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 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode) { 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 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode) default: return 0; } + // const UInt32 numSections = GetUi16(p + 2); optHeaderSize = GetUi16(p + 16); if (optHeaderSize > (1 << 10)) return 0; @@ -109,6 +132,63 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode) 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 @@ static int Parse_ELF(const Byte *buf, size_t size, CFilterMode *filterMode) 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 @@ static int Parse_ELF(const Byte *buf, size_t size, CFilterMode *filterMode) #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 @@ static unsigned Parse_MACH(const Byte *buf, size_t size, CFilterMode *filterMode 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 @@ static BoolInt Parse_WAV(const Byte *buf, size_t size, CFilterMode *filterMode) 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 @@ struct CFilterMode2: public CFilterMode 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 @@ static inline bool IsExeFilter(CMethodId m) { switch (m) { + case k_ARM64: case k_BCJ: case k_BCJ2: case k_ARM: @@ -383,8 +498,9 @@ static unsigned Get_FilterGroup_for_Folder( 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 @@ static unsigned Get_FilterGroup_for_Folder( 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 unsigned Get_FilterGroup_for_Folder( 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 @@ UString CUpdateItem::GetExtension() const } */ -#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 @@ struct CRefItem unsigned NamePos; unsigned ExtensionIndex; - CRefItem() {}; + CRefItem() {} CRefItem(UInt32 index, const CUpdateItem &ui, bool sortByType): UpdateItem(&ui), Index(index), @@ -710,16 +829,16 @@ static int CompareUpdateItems(const CRefItem *p1, const CRefItem *p2, void *para // 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 @@ static int CompareUpdateItems(const CRefItem *p1, const CRefItem *p2, void *para } */ // 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 @@ struct CSolidGroup CRecordVector folderRefs; }; -static const char * const g_ExeExts[] = +static const char * const g_Exe_Exts[] = { "dll" , "exe" @@ -787,14 +906,65 @@ static const char * const g_ExeExts[] = , "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 < ARRAY_SIZE(g_ExeExts); i++) - if (StringsAreEqualNoCase_Ascii(ext, g_ExeExts[i])) + 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 < 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 { CMyComPtr Callback; @@ -802,6 +972,8 @@ struct CAnalysis bool ParseWav; bool ParseExe; + bool ParseExeUnix; + bool ParseNoExt; bool ParseAll; /* @@ -811,8 +983,10 @@ struct CAnalysis */ CAnalysis(): - ParseWav(true), + ParseWav(false), ParseExe(false), + ParseExeUnix(false), + ParseNoExt(false), ParseAll(false) /* , Need_ATime(false) @@ -829,32 +1003,46 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo { 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 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo } } - if (IsExeExt(ext)) - { - needReadFile = true; - #ifdef _WIN32 - probablyIsSameIsa = true; - needReadFile = ParseExe; - #endif - } - else if (StringsAreEqualNoCase_Ascii(ext, "wav")) - { - needReadFile = ParseWav; - } - /* - else if (!needReadFile && ParseUnixExt) + if (!needReadFile) { - 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 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo 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 @@ static HRESULT AddBcj2Methods(CCompressionMethodMode &mode) 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 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode, 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 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode, 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 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode, 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 @@ static void UpdateItem_To_FileItem(const CUpdateItem &ui, -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 @@ class CRepackInStreamWithSizes: { _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 @@ class CRepackStreamBase 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 @@ HRESULT CRepackStreamBase::OpenFile() NEventIndexType::kInArcIndex, arcIndex, _needWrite ? NUpdateNotifyOp::kRepack : - NUpdateNotifyOp::kSkip)); + NUpdateNotifyOp::kSkip)) } _crc = CRC_INIT_VAL; @@ -1267,7 +1484,7 @@ HRESULT CRepackStreamBase::CloseFile() { 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 @@ HRESULT CRepackStreamBase::ProcessEmptyFiles() { 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 @@ STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *pro _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 @@ STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *pro 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 @@ class CFolderInStream2: } 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 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi 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 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi 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 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi 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 @@ class CThreadDecoder CThreadDecoder(bool multiThreadMixer): Decoder(multiThreadMixer) { - #ifndef _7ZIP_ST + #ifndef Z7_ST if (multiThreadMixer) { MtMode = false; @@ -1463,7 +1678,7 @@ class CThreadDecoder // send_UnpackSize = false; } - #ifndef _7ZIP_ST + #ifndef Z7_ST bool dataAfterEnd_Error; HRESULT Result; @@ -1479,31 +1694,39 @@ class CThreadDecoder // 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 @@ void CThreadDecoder::Execute() 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 @@ void CThreadDecoder::Execute() #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 @@ HRESULT Update( 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); + Z7_DECL_CMyComPtr_QI_FROM( + IArchiveUpdateCallbackFile, + opCallback, updateCallback) - CMyComPtr extractCallback; - updateCallback->QueryInterface(IID_IArchiveExtractCallbackMessage, (void **)&extractCallback); + 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 @@ HRESULT Update( 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 @@ HRESULT Update( { 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( { 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 @@ HRESULT Update( 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 @@ HRESULT Update( } 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 @@ HRESULT Update( } - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO CCryptoGetTextPassword *getPasswordSpec = NULL; CMyComPtr getTextPassword; @@ -1847,7 +2088,7 @@ HRESULT Update( getPasswordSpec = new CCryptoGetTextPassword; getTextPassword = getPasswordSpec; - #ifndef _7ZIP_ST + #ifndef Z7_ST threadDecoder.getTextPassword = getPasswordSpec; #endif @@ -1855,10 +2096,13 @@ HRESULT Update( 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 @@ HRESULT Update( #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 @@ HRESULT Update( { // ---------- Sort Filters ---------- - FOR_VECTOR (i, filters) { filters[i].GroupIndex = i; @@ -1987,22 +2231,22 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( { RINOK(opCallback->ReportOperation( NEventIndexType::kBlockIndex, (UInt32)folderIndex, - NUpdateNotifyOp::kReplicate)); + NUpdateNotifyOp::kReplicate)) // ---------- Copy old solid block ---------- { @@ -2047,21 +2291,27 @@ HRESULT Update( 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 @@ HRESULT Update( } 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 @@ HRESULT Update( 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 @@ HRESULT Update( unsigned startPackIndex = newDatabase.PackSizes.Size(); UInt64 curUnpackSize; { - CMyComPtr sbInStream; CRepackStreamBase *repackBase; CFolderInStream2 *FosSpec2 = NULL; @@ -2138,13 +2387,13 @@ HRESULT Update( 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 @@ HRESULT Update( sbInStream = FosSpec2; repackBase = FosSpec2; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool isEncrypted = false; bool passwordIsDefined = false; UString password; @@ -2173,7 +2422,7 @@ HRESULT Update( 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 @@ HRESULT Update( &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 @@ HRESULT Update( 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 @@ HRESULT Update( #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 @@ HRESULT Update( 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 @@ HRESULT Update( // 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 @@ HRESULT Update( { 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 @@ HRESULT Update( 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 @@ HRESULT Update( // ---------- 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 @@ HRESULT Update( if (numSubFiles < 1) numSubFiles = 1; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) /* const unsigned folderIndex = newDatabase.NumUnpackStreamsVector.Size(); @@ -2431,31 +2689,45 @@ HRESULT Update( 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 @@ HRESULT Update( // 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 @@ HRESULT Update( 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 @@ HRESULT Update( if (skippedSize != 0 && complexity >= skippedSize) { complexity -= skippedSize; - RINOK(updateCallback->SetTotal(complexity)); + RINOK(updateCallback->SetTotal(complexity)) } /* @@ -2604,7 +2934,7 @@ HRESULT Update( } } - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) /* fileIndexToUpdateIndexMap.ClearAndFree(); @@ -2634,10 +2964,26 @@ HRESULT Update( } } */ + + { + 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 --git a/CPP/7zip/Archive/7z/7zUpdate.h b/CPP/7zip/Archive/7z/7zUpdate.h index e6c48cae..de4117af 100644 --- a/CPP/7zip/Archive/7z/7zUpdate.h +++ b/CPP/7zip/Archive/7z/7zUpdate.h @@ -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 @@ struct CUpdateOptions bool MaxFilter; // use BCJ2 filter instead of BCJ int AnalysisLevel; - CHeaderOptions HeaderOptions; - UInt64 NumSolidFiles; UInt64 NumSolidBytes; bool SolidExtension; @@ -110,6 +107,9 @@ struct CUpdateOptions bool Need_ATime; bool Need_MTime; bool Need_Attrib; + // bool Need_Crc; + + CHeaderOptions HeaderOptions; CUpdateOptions(): Method(NULL), @@ -127,6 +127,7 @@ struct CUpdateOptions Need_ATime(false), Need_MTime(false), Need_Attrib(false) + // , Need_Crc(true) {} }; @@ -134,18 +135,12 @@ HRESULT Update( 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 --git a/CPP/7zip/Archive/7z/StdAfx.h b/CPP/7zip/Archive/7z/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/7z/StdAfx.h +++ b/CPP/7zip/Archive/7z/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/7z/makefile b/CPP/7zip/Archive/7z/makefile index a3b077da..ff60e4d4 100644 --- a/CPP/7zip/Archive/7z/makefile +++ b/CPP/7zip/Archive/7z/makefile @@ -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 @@ COMMON_OBJS = \ $O\Wildcard.obj \ WIN_OBJS = \ - $O\DLL.obj \ $O\FileDir.obj \ $O\FileFind.obj \ $O\FileIO.obj \ @@ -61,6 +60,7 @@ WIN_OBJS = \ COMPRESS_OBJS = \ $O\CopyCoder.obj \ + $O\CodecExports.obj \ AR_COMMON_OBJS = \ $O\CoderMixer2.obj \ diff --git a/CPP/7zip/Archive/ApfsHandler.cpp b/CPP/7zip/Archive/ApfsHandler.cpp index 2c16de15..5fb7e0af 100644 --- a/CPP/7zip/Archive/ApfsHandler.cpp +++ b/CPP/7zip/Archive/ApfsHandler.cpp @@ -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 @@ struct CUuid 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 @@ struct prange_t #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 @@ struct prange_t #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 @@ struct prange_t // #define MAX_CKSUM_SIZE 8 +static const unsigned k_obj_phys_Size = 0x20; + // obj_phys_t struct CPhys { @@ -183,10 +191,10 @@ struct CPhys 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 @@ typedef enum #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 @@ struct CSuperBlock2 { 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 @@ bool CSuperBlock::Parse(const Byte *p) 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 @@ bool CSuperBlock::Parse(const Byte *p) 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 @@ bool CSuperBlock::Parse(const Byte *p) } +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 @@ bool C_omap_phys::Parse(const Byte *p, size_t size, oid_t oid) 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 @@ struct nloc 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 @@ struct kvoff void Parse(const Byte *p) { - G16 (0, k); - G16 (2, v); + G16 (0, k) + G16 (2, v) } }; @@ -551,9 +643,9 @@ struct kvoff #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 @@ static const unsigned k_Toc_offset = 0x38; 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 @@ struct CBTreeNodePhys */ 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 @@ struct CBTreeNodePhys #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 @@ struct btree_info_fixed 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 @@ struct btree_info 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 @@ struct wrapped_meta_crypto_state #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 @@ struct apfs_modified_by_t { 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 @@ struct CApfs // 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 @@ struct CApfs 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 @@ bool CApfs::Parse(const Byte *p, size_t size) 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 @@ bool CApfs::Parse(const Byte *p, size_t size) 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 @@ bool CApfs::Parse(const Byte *p, size_t size) 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 @@ struct j_key_t { 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 @@ struct j_drec_val // 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 @@ struct CItem #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_ACTIVE_FILE_TRIMMED = 0x00000800, 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_CLONED_INTERNAL_FLAGS = \ | INODE_HAS_FINDER_INFO \ | INODE_SNAPSHOT_COW_EXEMPTION), */ -} -j_inode_flags; +// } +// j_inode_flags; /* @@ -1063,24 +1175,24 @@ static const char * const g_INODE_Flags[] = // 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 @@ struct j_dstream 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 @@ struct j_file_extent_val 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 @@ struct CExtent 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 @@ struct CNode // 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 @@ struct CSmallNode { 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 @@ struct CRef #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 CRef2 }; +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 @@ struct CVol 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 @@ struct CVol ThereAreUnlinkedNodes(false), WrongInodeLink(false), UnsupportedFeature(false), + UnsupportedMethod(false), NumItems_In_PrivateDir(0), NumAltStreams(0) {} @@ -1479,7 +1725,7 @@ static void ApfsTimeToFileTime(UInt64 apfsTime, FILETIME &ft, UInt32 &ns100) 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 @@ void CVol::AddComment(UString &s) const 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 @@ void CVol::AddComment(UString &s) const 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 @@ struct omap_key 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 @@ struct omap_key #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 @@ struct omap_val { 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 @@ struct CDatabase bool HeadersError; bool ThereAreAltStreams; bool UnsupportedFeature; + bool UnsupportedMethod; CSuperBlock sb; @@ -1726,8 +2001,9 @@ struct CDatabase void Clear() { HeadersError = false; - UnsupportedFeature = false; ThereAreAltStreams = false; + UnsupportedFeature = false; + UnsupportedMethod = false; ProgressVal_Cur = 0; ProgressVal_Prev = 0; @@ -1742,8 +2018,9 @@ struct CDatabase 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 @@ HRESULT CDatabase::SeekReadBlock_FALSE(UInt64 oid, void *data) { 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 @@ API_FUNC_static_IsArc IsArc_APFS(const Byte *p, size_t size) } +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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) - 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) } 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) 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 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) // 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::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) -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 @@ HRESULT CDatabase::Open2() 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 @@ HRESULT CDatabase::Open2() { 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 @@ HRESULT CDatabase::Open2() 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) if (OpenCallback) { const UInt64 numFiles = ProgressVal_NumFilesTotal + numApfsItems; - RINOK(OpenCallback->SetTotal(&numFiles, NULL)); + RINOK(OpenCallback->SetTotal(&numFiles, NULL)) } } @@ -2165,7 +2607,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) { 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) inode.refcnt_defined = true; if (inode.refcnt != (UInt32)inode.nlink) { + PRF(printf(" refcnt != nlink")); // is it possible ? // return S_FALSE; } @@ -2536,13 +2982,138 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) 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 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) RINOK(OpenCallback->SetCompleted( &ProgressVal_NumFilesTotal, - &ProgressVal_Cur)); + &ProgressVal_Cur)) ProgressVal_Prev = ProgressVal_Cur; } } @@ -2623,7 +3194,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) } else { - vol.UnsupportedFeature = true; + vol.UnsupportedMethod = true; } } } @@ -2635,6 +3206,8 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid) HeadersError = true; if (vol.UnsupportedFeature) UnsupportedFeature = true; + if (vol.UnsupportedMethod) + UnsupportedMethod = true; if (vol.NumAltStreams != 0) ThereAreAltStreams = true; @@ -2863,38 +3436,39 @@ HRESULT CVol::FillRefs() -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 @@ static void ApfsTimeToProp(UInt64 hfsTime, NWindows::NCOM::CPropVariant &prop) } -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *pr } -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::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp } -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 @@ static void AddNodeName(UString &s, const CNode &inode, UInt64 id) 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 @@ void CDatabase::GetItemPath(unsigned index, const CNode *inode, NWindows::NCOM:: -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 @@ UInt64 CDatabase::GetSize(const UInt32 index) const } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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(IInStream *apfsInStream, const CVol &vol, 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 --git a/CPP/7zip/Archive/ApmHandler.cpp b/CPP/7zip/Archive/ApmHandler.cpp index 73e5fcb6..6770301d 100644 --- a/CPP/7zip/Archive/ApmHandler.cpp +++ b/CPP/7zip/Archive/ApmHandler.cpp @@ -71,8 +71,10 @@ struct CItem } }; -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 @@ class CHandler: public CHandlerCont 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 @@ HRESULT CHandler::ReadTables(IInStream *stream) { 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 @@ HRESULT CHandler::ReadTables(IInStream *stream) 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 @@ HRESULT CHandler::ReadTables(IInStream *stream) _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 @@ HRESULT CHandler::ReadTables(IInStream *stream) 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 @@ static AString GetString(const char *s) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } } if (mainIndex >= 0) - prop = (UInt32)mainIndex; + prop = (UInt32)(Int32)mainIndex; break; } case kpidClusterSize: prop = (UInt32)1 << _blockSizeLog; break; @@ -263,13 +262,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val type = "hfs"; if (!type.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += type; } prop = s; @@ -306,7 +305,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val static const Byte k_Signature[] = { kSig0, kSig1 }; REGISTER_ARC_I( - "APM", "apm", 0, 0xD4, + "APM", "apm", NULL, 0xD4, k_Signature, 0, 0, diff --git a/CPP/7zip/Archive/ArHandler.cpp b/CPP/7zip/Archive/ArHandler.cpp index 6cd72bb3..07ecec64 100644 --- a/CPP/7zip/Archive/ArHandler.cpp +++ b/CPP/7zip/Archive/ArHandler.cpp @@ -56,10 +56,8 @@ BSD (Mac OS X) variant: */ 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 @@ class CInArchive 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled) } 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled) 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 @@ class CHandler: unsigned _numLibFiles; AString _errorMessage; bool _isArc; - void UpdateErrorMessage(const char *s); @@ -298,10 +294,6 @@ class CHandler: 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 @@ HRESULT CHandler::ParseLongNames(IInStream *stream) 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 @@ HRESULT CHandler::ParseLongNames(IInStream *stream) { 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 @@ void CHandler::ChangeDuplicateNames() 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 @@ int CHandler::FindItem(UInt32 offset) const 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 @@ int CHandler::FindItem(UInt32 offset) const 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 @@ HRESULT CHandler::AddFunc(UInt32 offset, const Byte *data, size_t size, size_t & 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 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex) 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 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex) 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 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex) 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 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex) 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 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex) 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -672,13 +663,13 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) } REGISTER_ARC_I( - "Ar", "ar a deb udeb lib", 0, 0xEC, + "Ar", "ar a deb udeb lib", NULL, 0xEC, kSignature, 0, 0, diff --git a/CPP/7zip/Archive/Archive.def b/CPP/7zip/Archive/Archive.def index 145516d7..2ed62462 100644 --- a/CPP/7zip/Archive/Archive.def +++ b/CPP/7zip/Archive/Archive.def @@ -10,3 +10,5 @@ EXPORTS SetLargePageMode PRIVATE SetCaseSensitive PRIVATE + + GetModuleProp PRIVATE diff --git a/CPP/7zip/Archive/Archive2.def b/CPP/7zip/Archive/Archive2.def index c7582742..f891ad3b 100644 --- a/CPP/7zip/Archive/Archive2.def +++ b/CPP/7zip/Archive/Archive2.def @@ -17,3 +17,5 @@ EXPORTS SetLargePageMode PRIVATE SetCaseSensitive PRIVATE + + GetModuleProp PRIVATE diff --git a/CPP/7zip/Archive/ArchiveExports.cpp b/CPP/7zip/Archive/ArchiveExports.cpp index a84a3cbb..e922b46f 100644 --- a/CPP/7zip/Archive/ArchiveExports.cpp +++ b/CPP/7zip/Archive/ArchiveExports.cpp @@ -36,7 +36,7 @@ DEFINE_GUID(CLSID_CArchiveHandler, 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 +52,7 @@ static int FindFormatCalssId(const GUID *clsid) 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 +64,11 @@ STDAPI CreateArchiver(const GUID *clsid, const GUID *iid, void **outObject) { 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 --git a/CPP/7zip/Archive/ArjHandler.cpp b/CPP/7zip/Archive/ArjHandler.cpp index 125b9c20..2f982c44 100644 --- a/CPP/7zip/Archive/ArjHandler.cpp +++ b/CPP/7zip/Archive/ArjHandler.cpp @@ -31,10 +31,11 @@ static const unsigned kMatchMinLen = 3; 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 @@ class CCoder: 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 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) 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 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) -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 @@ HRESULT CArcHeader::Parse(const Byte *p, unsigned size) // 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 @@ HRESULT CItem::Parse(const Byte *p, unsigned size) 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 @@ HRESULT CArc::ReadBlock(bool &filled, CExtendedInfo *extendedInfo) 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 @@ HRESULT CArc::SkipExtendedHeaders(CExtendedInfo &extendedInfo) 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 @@ HRESULT CArc::GetNextItem(CItem &item, bool &filled) 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 @@ static void SetUnicodeString(const AString &s, NCOM::CPropVariant &prop) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback) { 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 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback) 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _arc.Close(); _phySize = 0; @@ -849,12 +841,12 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) curUnpacked = item.Size; curPacked = item.PackSize; @@ -930,8 +922,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, opRes = NExtract::NOperationResult::kDataError; else { - RINOK(result); + RINOK(result) opRes = (outStreamSpec->GetCRC() == item.FileCRC) ? NExtract::NOperationResult::kOK: NExtract::NOperationResult::kCRCError; @@ -998,7 +989,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } } @@ -1009,7 +1000,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, static const Byte k_Signature[] = { kSig0, kSig1 }; REGISTER_ARC_I( - "Arj", "arj", 0, 4, + "Arj", "arj", NULL, 4, k_Signature, 0, 0, diff --git a/CPP/7zip/Archive/Base64Handler.cpp b/CPP/7zip/Archive/Base64Handler.cpp index 63b4552e..5b060513 100644 --- a/CPP/7zip/Archive/Base64Handler.cpp +++ b/CPP/7zip/Archive/Base64Handler.cpp @@ -207,7 +207,7 @@ static const Byte *Base64_SkipSpaces(const Byte *p, size_t size) { 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 @@ Byte *Base64ToBin(Byte *dest, const char *src) for (;;) { - UInt32 c = k_Base64Table[(Byte)(*src++)]; + const UInt32 c = k_Base64Table[(Byte)(*src++)]; if (c < 64) { @@ -266,7 +266,7 @@ Byte *Base64ToBin(Byte *dest, const char *src) 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 @@ Byte *Base64ToBin(Byte *dest, const char *src) 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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ static HRESULT ReadStream_OpenProgress(ISequentialInStream *stream, void *data, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb _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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _size = 0; @@ -442,19 +437,16 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (realOutStream) { - RINOK(WriteStream(realOutStream, (const Byte *)_data, _size)); + RINOK(WriteStream(realOutStream, (const Byte *)_data, _size)) realOutStream.Release(); } @@ -492,7 +484,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, opRes = NExtract::NOperationResult::kDataError; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } lps->InSize = _phySize; @@ -503,9 +495,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 --git a/CPP/7zip/Archive/BrotliHandler.cpp b/CPP/7zip/Archive/BrotliHandler.cpp index f513c8cf..cde26bd5 100644 --- a/CPP/7zip/Archive/BrotliHandler.cpp +++ b/CPP/7zip/Archive/BrotliHandler.cpp @@ -22,13 +22,11 @@ using namespace NWindows; namespace NArchive { namespace NBROTLI { -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; @@ -45,19 +43,6 @@ class CHandler: 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[] = @@ -75,18 +60,18 @@ static const Byte kArcProps[] = IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/)) { 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) @@ -108,7 +93,7 @@ API_FUNC_static_IsArc IsArc_Brotli(const Byte *p, size_t size) } #endif -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); @@ -121,7 +106,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -129,7 +114,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _dataAfterEnd = false; @@ -145,8 +130,8 @@ STDMETHODIMP CHandler::Close() 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) @@ -268,14 +253,14 @@ static HRESULT UpdateArchive( return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -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 *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -336,7 +321,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/Bz2Handler.cpp b/CPP/7zip/Archive/Bz2Handler.cpp index c89a53c5..994b1ad0 100644 --- a/CPP/7zip/Archive/Bz2Handler.cpp +++ b/CPP/7zip/Archive/Bz2Handler.cpp @@ -20,13 +20,11 @@ using namespace NWindows; 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 @@ class CHandler: 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 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ API_FUNC_static_IsArc IsArc_BZip2(const Byte *p, size_t size) } } -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::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -160,7 +145,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _needSeekToStart = false; @@ -180,8 +165,8 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _needSeekToStart = true; @@ -216,8 +201,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ static HRESULT UpdateArchive( { { 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 @@ static HRESULT UpdateArchive( 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 @@ static HRESULT UpdateArchive( 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } if (_stream) - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) return NCompress::CopyStream(_stream, outStream, progress); @@ -468,7 +460,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/Cab/CabBlockInStream.cpp b/CPP/7zip/Archive/Cab/CabBlockInStream.cpp index c193434f..dc767a4d 100644 --- a/CPP/7zip/Archive/Cab/CabBlockInStream.cpp +++ b/CPP/7zip/Archive/Cab/CabBlockInStream.cpp @@ -18,7 +18,7 @@ bool CCabBlockInStream::Create() { if (!_buf) _buf = (Byte *)::MyAlloc(kBlockSize); - return _buf != 0; + return _buf != NULL; } CCabBlockInStream::~CCabBlockInStream() @@ -60,7 +60,7 @@ HRESULT CCabBlockInStream::PreRead(ISequentialInStream *stream, UInt32 &packSize 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 @@ HRESULT CCabBlockInStream::PreRead(ISequentialInStream *stream, UInt32 &packSize 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 --git a/CPP/7zip/Archive/Cab/CabBlockInStream.h b/CPP/7zip/Archive/Cab/CabBlockInStream.h index af89abb6..d14fff88 100644 --- a/CPP/7zip/Archive/Cab/CabBlockInStream.h +++ b/CPP/7zip/Archive/Cab/CabBlockInStream.h @@ -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 @@ class CCabBlockInStream: 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 @@ class CCabBlockInStream: UInt32 GetPackSizeAvail() const { return _size - _pos; } const Byte *GetData() const { return _buf + _pos; } - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); }; }} diff --git a/CPP/7zip/Archive/Cab/CabHandler.cpp b/CPP/7zip/Archive/Cab/CabHandler.cpp index 804c921a..f0151459 100644 --- a/CPP/7zip/Archive/Cab/CabHandler.cpp +++ b/CPP/7zip/Archive/Cab/CabHandler.cpp @@ -32,9 +32,9 @@ using namespace NWindows; namespace NArchive { namespace NCab { -// #define _CAB_DETAILS +// #define CAB_DETAILS -#ifdef _CAB_DETAILS +#ifdef CAB_DETAILS enum { kpidBlockReal = kpidUserDefined @@ -49,7 +49,7 @@ static const Byte kProps[] = kpidAttrib, kpidMethod, kpidBlock - #ifdef _CAB_DETAILS + #ifdef CAB_DETAILS , // kpidBlockReal, // L"BlockReal", kpidOffset, @@ -83,7 +83,7 @@ static const unsigned kMethodNameBufSize = 32; // "Quantum:255" 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 @@ static void SetMethodName(char *s, unsigned method, unsigned param) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, if (callback) { - RINOK(callback->SetCompleted(&numItems, NULL)); + RINOK(callback->SetCompleted(&numItems, NULL)) } nextStream = NULL; @@ -471,7 +471,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _errorMessage.Empty(); _isArc = false; @@ -534,15 +534,11 @@ STDMETHODIMP CHandler::Close() 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 @@ HRESULT CFolderOutStream::OpenFile() 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 @@ HRESULT CFolderOutStream::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; - 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 @@ HRESULT CFolderOutStream::WriteEmptyFiles() 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 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed if (m_RemainFileSize == 0) { - RINOK(CloseFile()); + RINOK(CloseFile()) while (NumIdenticalFiles) { @@ -789,14 +785,14 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed 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 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed if (fileOffset == m_PosInFolder) { - RINOK(OpenFile()); + RINOK(OpenFile()) m_FileIsOpen = true; m_CurrentIndex++; m_IsOk = true; @@ -860,11 +856,11 @@ HRESULT CFolderOutStream::FlushCorrupted(unsigned folderIndex) { 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 @@ HRESULT CFolderOutStream::FlushCorrupted(unsigned folderIndex) if (size > remain) size = (UInt32)remain; UInt32 processedSizeLocal = 0; - RINOK(Write(NULL, size, &processedSizeLocal)); + RINOK(Write(NULL, size, &processedSizeLocal)) } } @@ -891,19 +887,18 @@ HRESULT CFolderOutStream::Unsupported() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, lps->OutSize = totalUnPacked2; lps->InSize = totalPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const UInt32 kBlockSizeMax = (1 << 15); @@ -1230,7 +1225,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (res != S_OK) { if (res != S_FALSE) - RINOK(res); + RINOK(res) break; } @@ -1239,13 +1234,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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::Extract(const UInt32 *indices, UInt32 numItems, } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = m_Database.Items.Size(); return S_OK; diff --git a/CPP/7zip/Archive/Cab/CabHandler.h b/CPP/7zip/Archive/Cab/CabHandler.h index 6f44b875..1e1811f8 100644 --- a/CPP/7zip/Archive/Cab/CabHandler.h +++ b/CPP/7zip/Archive/Cab/CabHandler.h @@ -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 --git a/CPP/7zip/Archive/Cab/CabHeader.h b/CPP/7zip/Archive/Cab/CabHeader.h index 2f2bd109..ecb9a87b 100644 --- a/CPP/7zip/Archive/Cab/CabHeader.h +++ b/CPP/7zip/Archive/Cab/CabHeader.h @@ -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 --git a/CPP/7zip/Archive/Cab/CabIn.cpp b/CPP/7zip/Archive/Cab/CabIn.cpp index e11ce9d0..fb696431 100644 --- a/CPP/7zip/Archive/Cab/CabIn.cpp +++ b/CPP/7zip/Archive/Cab/CabIn.cpp @@ -76,9 +76,9 @@ struct CSignatureFinder 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 @@ struct CSignatureFinder 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 @@ HRESULT CSignatureFinder::Find() { 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 @@ HRESULT CSignatureFinder::Find() 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 @@ HRESULT CSignatureFinder::Find() 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 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) 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 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) // 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 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) 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 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) for (;;) { - RINOK(finder.Find()); + RINOK(finder.Find()) if (ai.Parse(finder.Buf + finder.Pos)) { db.StartPosition = finder.Processed + finder.Pos; @@ -311,7 +311,7 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) { // 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 @@ HRESULT CInArchive::Open(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit) -#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 @@ static int CompareMvItems(const CMvItem *p1, const CMvItem *p2, void *param) 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 @@ bool CMvDatabaseEx::AreItemsEqual(unsigned i1, unsigned i2) 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 --git a/CPP/7zip/Archive/Cab/CabIn.h b/CPP/7zip/Archive/Cab/CabIn.h index 39586d12..06aa34c7 100644 --- a/CPP/7zip/Archive/Cab/CabIn.h +++ b/CPP/7zip/Archive/Cab/CabIn.h @@ -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 --git a/CPP/7zip/Archive/Cab/CabItem.h b/CPP/7zip/Archive/Cab/CabItem.h index 9a912d5e..b7e07d1c 100644 --- a/CPP/7zip/Archive/Cab/CabItem.h +++ b/CPP/7zip/Archive/Cab/CabItem.h @@ -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 --git a/CPP/7zip/Archive/Cab/CabRegister.cpp b/CPP/7zip/Archive/Cab/CabRegister.cpp index 0b5cc93a..8f4f323f 100644 --- a/CPP/7zip/Archive/Cab/CabRegister.cpp +++ b/CPP/7zip/Archive/Cab/CabRegister.cpp @@ -10,7 +10,7 @@ namespace NArchive { namespace NCab { REGISTER_ARC_I( - "Cab", "cab", 0, 8, + "Cab", "cab", NULL, 8, NHeader::kMarker, 0, NArcInfoFlags::kFindSignature, diff --git a/CPP/7zip/Archive/Cab/StdAfx.h b/CPP/7zip/Archive/Cab/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Cab/StdAfx.h +++ b/CPP/7zip/Archive/Cab/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/Chm/ChmHandler.cpp b/CPP/7zip/Archive/Chm/ChmHandler.cpp index 03e7ddd2..38e25433 100644 --- a/CPP/7zip/Archive/Chm/ChmHandler.cpp +++ b/CPP/7zip/Archive/Chm/ChmHandler.cpp @@ -27,9 +27,9 @@ using namespace NTime; namespace NArchive { namespace NChm { -// #define _CHM_DETAILS +// #define CHM_DETAILS -#ifdef _CHM_DETAILS +#ifdef CHM_DETAILS enum { @@ -45,7 +45,7 @@ static const Byte kProps[] = kpidMethod, kpidBlock - #ifdef _CHM_DETAILS + #ifdef CHM_DETAILS , L"Section", kpidSection, kpidOffset @@ -63,7 +63,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)) { // COM_TRY_BEGIN NCOM::CPropVariant prop; @@ -97,7 +97,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) // 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, { 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { m_ErrorFlags = 0; m_Database.Clear(); @@ -237,15 +213,22 @@ STDMETHODIMP CHandler::Close() 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 @@ class CChmFolderOutStream: 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 @@ void CChmFolderOutStream::Init( 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 @@ HRESULT CChmFolderOutStream::WriteEmptyFiles() 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 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce 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 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce if (fileOffset == m_PosInSection) { - RINOK(OpenFile()); + RINOK(OpenFile()) m_FileIsOpen = true; m_CurrentIndex++; m_IsOk = true; @@ -406,7 +376,7 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce 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 @@ HRESULT CChmFolderOutStream::FlushCorrupted(UInt64 maxSize) { 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 @@ HRESULT CChmFolderOutStream::FlushCorrupted(UInt64 maxSize) } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } - 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, for (i = 0;;) { - RINOK(extractCallback->SetCompleted(¤tTotalSize)); + RINOK(extractCallback->SetCompleted(¤tTotalSize)) if (i >= numItems) break; @@ -595,10 +565,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } catch(...) { - RINOK(chmFolderOutStream->FlushCorrupted(unPackSize)); + RINOK(chmFolderOutStream->FlushCorrupted(unPackSize)) } currentTotalSize += folderSize; @@ -790,9 +760,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ static const Byte k_Signature[] = { 'I', 'T', 'S', 'F', 3, 0, 0, 0, 0x60, 0, 0, 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 @@ static const Byte k_Signature[] = { 'I', 'T', 'O', 'L', 'I', 'T', 'L', 'S', 1, 0 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 --git a/CPP/7zip/Archive/Chm/ChmHandler.h b/CPP/7zip/Archive/Chm/ChmHandler.h index 884f391b..94821b21 100644 --- a/CPP/7zip/Archive/Chm/ChmHandler.h +++ b/CPP/7zip/Archive/Chm/ChmHandler.h @@ -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 --git a/CPP/7zip/Archive/Chm/ChmIn.cpp b/CPP/7zip/Archive/Chm/ChmIn.cpp index f4916b68..28d512da 100644 --- a/CPP/7zip/Archive/Chm/ChmIn.cpp +++ b/CPP/7zip/Archive/Chm/ChmIn.cpp @@ -10,6 +10,7 @@ #include "../../../Common/UTFConvert.h" #include "../../Common/LimitedStreams.h" +#include "../../Common/StreamUtils.h" #include "ChmIn.h" @@ -217,7 +218,7 @@ void CInArchive::ReadUString(unsigned size, UString &s) 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 @@ HRESULT CInArchive::OpenChm(IInStream *inStream, CDatabase &database) return S_FALSE; if (offset == offsetLimit) break; - RINOK(ReadDirEntry(database)); + RINOK(ReadDirEntry(database)) numItems++; } @@ -570,7 +571,7 @@ HRESULT CInArchive::OpenHelp2(IInStream *inStream, CDatabase &database) } else { - RINOK(ReadDirEntry(database)); + RINOK(ReadDirEntry(database)) } numItems++; } @@ -616,7 +617,7 @@ static AString GetSectionPrefix(const AString &name) 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 @@ static int CompareFiles(const unsigned *p1, const unsigned *p2, void *param) } 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 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) { { // 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 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) 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 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) { // Control Data - RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData)); + RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData)) FOR_VECTOR (mi, section.Methods) { @@ -781,19 +782,19 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) { // 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 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) { // SpanInfo - RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo)); + RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo)) section.UncompressedSize = ReadUInt64(); } @@ -824,7 +825,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database) { // ResetTable; RINOK(DecompressStream(inStream, database, transformPrefix + - method.GetGuidString() + kResetTable)); + method.GetGuidString() + kResetTable)) CResetTable &rt = method.LzxInfo.ResetTable; if (_chunkSize < 4) @@ -906,7 +907,7 @@ HRESULT CInArchive::Open2(IInStream *inStream, 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 @@ HRESULT CInArchive::Open2(IInStream *inStream, } database.StartPosition += _inBuffer.GetProcessedSize() - kSignatureSize; - RINOK(OpenHelp2(inStream, database)); + RINOK(OpenHelp2(inStream, database)) if (database.NewFormat) return S_OK; } @@ -952,7 +953,7 @@ HRESULT CInArchive::Open2(IInStream *inStream, return S_FALSE; if (ReadUInt32() != chmVersion) return S_FALSE; - RINOK(OpenChm(inStream, database)); + RINOK(OpenChm(inStream, database)) } @@ -969,7 +970,7 @@ HRESULT CInArchive::Open2(IInStream *inStream, database.HighLevelClear(); return S_OK; } - RINOK(res); + RINOK(res) if (!database.CheckSectionRefs()) HeadersError = true; database.LowLevel = false; diff --git a/CPP/7zip/Archive/Chm/ChmIn.h b/CPP/7zip/Archive/Chm/ChmIn.h index 2d773667..c01ef4dc 100644 --- a/CPP/7zip/Archive/Chm/ChmIn.h +++ b/CPP/7zip/Archive/Chm/ChmIn.h @@ -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 @@ struct CDatabase { FOR_VECTOR (i, Items) if (Items[i].Name == name) - return i; + return (int)i; return -1; } diff --git a/CPP/7zip/Archive/Chm/StdAfx.h b/CPP/7zip/Archive/Chm/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Chm/StdAfx.h +++ b/CPP/7zip/Archive/Chm/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/ComHandler.cpp b/CPP/7zip/Archive/ComHandler.cpp index a1f643b7..7aabd657 100644 --- a/CPP/7zip/Archive/ComHandler.cpp +++ b/CPP/7zip/Archive/ComHandler.cpp @@ -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 @@ class CDatabase Int32 MainSubfile; UInt64 PhySize; + UInt64 PhySize_Aligned; EType Type; bool IsNotArcType() const @@ -129,10 +130,12 @@ class CDatabase 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 @@ class CDatabase 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 CItem::Parse(const Byte *p, bool mode64bit) void CDatabase::Clear() { PhySize = 0; + PhySize_Aligned = 0; Fat.Free(); MiniSids.Free(); @@ -227,14 +232,14 @@ HRESULT CDatabase::AddNode(int parent, UInt32 did) 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 @@ static UString CompoundNameToFileName(const UString &s) 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 @@ UString CDatabase::GetItemPath(UInt32 index) const 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 @@ HRESULT CDatabase::Update_PhySize_WithItem(unsigned index) 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 @@ HRESULT CDatabase::Update_PhySize_WithItem(unsigned index) { 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 @@ HRESULT CDatabase::Open(IInStream *inStream) 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 @@ HRESULT CDatabase::Open(IInStream *inStream) 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 @@ HRESULT CDatabase::Open(IInStream *inStream) { 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 @@ HRESULT CDatabase::Open(IInStream *inStream) 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 @@ HRESULT CDatabase::Open(IInStream *inStream) 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 @@ HRESULT CDatabase::Open(IInStream *inStream) } } - RINOK(AddNode(-1, root.SonDid)); + RINOK(AddNode(-1, root.SonDid)) unsigned numCabs = 0; @@ -584,7 +595,7 @@ HRESULT CDatabase::Open(IInStream *inStream) ) { numCabs++; - MainSubfile = i; + MainSubfile = (int)i; } } } @@ -598,6 +609,17 @@ HRESULT CDatabase::Open(IInStream *inStream) Update_PhySize_WithItem(t); } } + { + 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) { @@ -634,17 +656,11 @@ HRESULT CDatabase::Open(IInStream *inStream) 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 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!item.IsDir()) totalSize += item.Size; } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 totalPackSize; totalSize = totalPackSize = 0; @@ -762,20 +778,20 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) } 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 --git a/CPP/7zip/Archive/Common/CoderMixer2.cpp b/CPP/7zip/Archive/Common/CoderMixer2.cpp index c8b67bd4..b6ddeb83 100644 --- a/CPP/7zip/Archive/Common/CoderMixer2.cpp +++ b/CPP/7zip/Archive/Common/CoderMixer2.cpp @@ -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 CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 * } -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 @@ STDMETHODIMP COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *pr return result; } -STDMETHODIMP COutStreamCalcSize::OutStreamFinish() +Z7_COM7F_IMF(COutStreamCalcSize::OutStreamFinish()) { HRESULT result = S_OK; if (_stream) @@ -73,7 +73,7 @@ HRESULT CCoder::CheckDataAfterEnd(bool &dataAfterEnd_Error /* , bool &InternalPa 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 @@ HRESULT CCoder::CheckDataAfterEnd(bool &dataAfterEnd_Error /* , bool &InternalPa 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 @@ void CMixerST::AddCoder(const CCreatedCoder &cod) { 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 @@ HRESULT CMixerST::GetInStream2( 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 @@ HRESULT CMixerST::GetInStream2( 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 @@ HRESULT CMixerST::GetInStream2( 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 @@ HRESULT CMixerST::GetInStream( 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 @@ HRESULT CMixerST::GetOutStream( 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 @@ HRESULT CMixerST::GetOutStream( 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 @@ HRESULT CMixerST::GetOutStream( 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 @@ HRESULT CMixerST::GetOutStream( 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 @@ HRESULT CMixerST::FinishStream(UInt32 streamIndex) 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 @@ HRESULT CMixerST::FinishCoder(UInt32 coderIndex) { 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 @@ void CMixerST::SelectMainCoder(bool useFirst) 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 @@ HRESULT CMixerST::Code( 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 @@ HRESULT CMixerST::Code( 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 @@ HRESULT CMixerST::Code( 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 @@ HRESULT CMixerST::GetMainUnpackStream( coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize); if (setOutStreamSize) { - RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer)); + RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer)) } } @@ -919,7 +921,7 @@ HRESULT CMixerMT::SetBindInfo(const CBindInfo &bindInfo) _streamBinders.Clear(); FOR_VECTOR (i, _bi.Bonds) { - // RINOK(_streamBinders.AddNew().CreateEvents()); + // RINOK(_streamBinders.AddNew().CreateEvents()) _streamBinders.AddNew(); } return S_OK; @@ -946,7 +948,7 @@ HRESULT CMixerMT::ReInit2() { FOR_VECTOR (i, _streamBinders) { - RINOK(_streamBinders[i].Create_ReInit()); + RINOK(_streamBinders[i].Create_ReInit()) } return S_OK; } @@ -986,8 +988,8 @@ HRESULT CMixerMT::Init(ISequentialInStream * const *inStreams, ISequentialOutStr 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 @@ HRESULT CMixerMT::Code( 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 @@ HRESULT CMixerMT::Code( return result; } - RINOK(ReturnIfError(S_FALSE)); + RINOK(ReturnIfError(S_FALSE)) for (i = 0; i < _coders.Size(); i++) { @@ -1126,7 +1128,7 @@ HRESULT CMixerMT::Code( 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 --git a/CPP/7zip/Archive/Common/CoderMixer2.h b/CPP/7zip/Archive/Common/CoderMixer2.h index f099ac3e..484a6089 100644 --- a/CPP/7zip/Archive/Common/CoderMixer2.h +++ b/CPP/7zip/Archive/Common/CoderMixer2.h @@ -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 CSequentialInStreamCalcSize: }; -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 @@ struct CBindInfo bool SetUnpackCoder() { bool isOk = false; - FOR_VECTOR(i, Coders) + FOR_VECTOR (i, Coders) { if (FindBond_for_UnpackStream(i) < 0) { @@ -142,7 +132,7 @@ struct CBindInfo 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 @@ struct CBindInfo 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 @@ class CCoder CRecordVector PackSizes; CRecordVector PackSizePointers; - bool Finish; - CCoder(): Finish(false) {} void SetCoderInfo(const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish); @@ -251,7 +240,7 @@ class CMixer // , InternalPackSizeError(false) {} - virtual ~CMixer() {}; + virtual ~CMixer() {} /* Sequence of calling: @@ -323,7 +312,8 @@ class CMixerST: 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 @@ class CMixerST: 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 CMixerST: 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 CCoderMT: public CCoder, public CVirtThread class CReleaser { - CLASS_NO_COPY(CReleaser) + Z7_CLASS_NO_COPY(CReleaser) CCoderMT &_c; public: CReleaser(CCoderMT &c): _c(c) {} @@ -405,7 +393,14 @@ class CCoderMT: public CCoder, public CVirtThread }; 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 @@ class CMixerMT: 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 --git a/CPP/7zip/Archive/Common/DummyOutStream.cpp b/CPP/7zip/Archive/Common/DummyOutStream.cpp index 7c4f5487..f48c32f2 100644 --- a/CPP/7zip/Archive/Common/DummyOutStream.cpp +++ b/CPP/7zip/Archive/Common/DummyOutStream.cpp @@ -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 --git a/CPP/7zip/Archive/Common/DummyOutStream.h b/CPP/7zip/Archive/Common/DummyOutStream.h index b5a51fc0..f884e13c 100644 --- a/CPP/7zip/Archive/Common/DummyOutStream.h +++ b/CPP/7zip/Archive/Common/DummyOutStream.h @@ -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 --git a/CPP/7zip/Archive/Common/FindSignature.cpp b/CPP/7zip/Archive/Common/FindSignature.cpp index fc952fa8..6c6740ff 100644 --- a/CPP/7zip/Archive/Common/FindSignature.cpp +++ b/CPP/7zip/Archive/Common/FindSignature.cpp @@ -16,7 +16,7 @@ HRESULT FindSignatureInStream(ISequentialInStream *stream, { 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 @@ HRESULT FindSignatureInStream(ISequentialInStream *stream, 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 --git a/CPP/7zip/Archive/Common/FindSignature.h b/CPP/7zip/Archive/Common/FindSignature.h index c359b9ed..f0e6cddf 100644 --- a/CPP/7zip/Archive/Common/FindSignature.h +++ b/CPP/7zip/Archive/Common/FindSignature.h @@ -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 --git a/CPP/7zip/Archive/Common/HandlerOut.cpp b/CPP/7zip/Archive/Common/HandlerOut.cpp index aa43f0b0..bab3b06f 100644 --- a/CPP/7zip/Archive/Common/HandlerOut.cpp +++ b/CPP/7zip/Archive/Common/HandlerOut.cpp @@ -88,7 +88,7 @@ bool CCommonMethodProps::SetCommonProperty(const UString &name, const PROPVARIAN 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 @@ bool CCommonMethodProps::SetCommonProperty(const UString &name, const PROPVARIAN } -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY static void SetMethodProp32(CMethodProps &m, PROPID propID, UInt32 value) { @@ -127,7 +127,7 @@ void CMultiMethodProps::SetGlobalLevelTo(COneMethodInfo &oneMethodInfo) const 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 @@ void CMultiMethodProps::SetMethodThreadsTo_Replace(CMethodProps &oneMethodInfo, SetMethodProp32_Replace(oneMethodInfo, NCoderPropID::kNumThreads, numThreads); } -#endif // _7ZIP_ST +#endif // Z7_ST void CMultiMethodProps::InitMulti() @@ -189,7 +189,7 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN { name.Delete(0, 2); UInt32 v = 9; - RINOK(ParsePropToUInt32(name, value, v)); + RINOK(ParsePropToUInt32(name, value, v)) _analysisLevel = (int)v; return S_OK; } @@ -209,13 +209,13 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN } 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) @@ -225,7 +225,7 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN 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); @@ -251,7 +251,7 @@ HRESULT CSingleMethodProps::SetProperty(const wchar_t *name2, const PROPVARIANT 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; @@ -263,7 +263,7 @@ HRESULT CSingleMethodProps::SetProperty(const wchar_t *name2, const PROPVARIANT /* don't return here, since many handlers set common properties (e. g. kNumThreads) with SetCoderProperties, so add it also as prop by its ID from name below */ } - RINOK(ParseMethodFromPROPVARIANT(name, value)); + RINOK(ParseMethodFromPROPVARIANT(name, value)) return S_OK; } @@ -274,7 +274,7 @@ HRESULT CSingleMethodProps::SetProperties(const wchar_t * const *names, const PR for (UInt32 i = 0; i < numProps; i++) { - RINOK(SetProperty(names[i], values[i])); + RINOK(SetProperty(names[i], values[i])) } return S_OK; @@ -285,7 +285,7 @@ HRESULT CSingleMethodProps::SetProperties(const wchar_t * const *names, const PR 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; } @@ -299,7 +299,7 @@ HRESULT CHandlerTimeOptions::Parse(const UString &name, const PROPVARIANT &prop, 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 --git a/CPP/7zip/Archive/Common/HandlerOut.h b/CPP/7zip/Archive/Common/HandlerOut.h index 41ee189d..cfba46e2 100644 --- a/CPP/7zip/Archive/Common/HandlerOut.h +++ b/CPP/7zip/Archive/Common/HandlerOut.h @@ -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 @@ class CCommonMethodProps void InitCommon() { // _Write_MTime = true; - #ifndef _7ZIP_ST + #ifndef Z7_ST _numProcessors = _numThreads = NWindows::NSystem::GetNumberOfProcessors(); _numThreads_WasForced = false; #endif @@ -46,7 +46,7 @@ class CCommonMethodProps } public: - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 _numThreads; UInt32 _numProcessors; bool _numThreads_WasForced; @@ -63,7 +63,7 @@ class CCommonMethodProps }; -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY class CMultiMethodProps: public CCommonMethodProps { @@ -80,7 +80,7 @@ class CMultiMethodProps: public CCommonMethodProps 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 --git a/CPP/7zip/Archive/Common/InStreamWithCRC.cpp b/CPP/7zip/Archive/Common/InStreamWithCRC.cpp index a2d68832..735d5d1e 100644 --- a/CPP/7zip/Archive/Common/InStreamWithCRC.cpp +++ b/CPP/7zip/Archive/Common/InStreamWithCRC.cpp @@ -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 @@ STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSi 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 --git a/CPP/7zip/Archive/Common/InStreamWithCRC.h b/CPP/7zip/Archive/Common/InStreamWithCRC.h index 31b761e4..2a91d767 100644 --- a/CPP/7zip/Archive/Common/InStreamWithCRC.h +++ b/CPP/7zip/Archive/Common/InStreamWithCRC.h @@ -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 @@ class CSequentialInStreamWithCRC: 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 --git a/CPP/7zip/Archive/Common/ItemNameUtils.h b/CPP/7zip/Archive/Common/ItemNameUtils.h index 3f5f4e8a..8ab9b610 100644 --- a/CPP/7zip/Archive/Common/ItemNameUtils.h +++ b/CPP/7zip/Archive/Common/ItemNameUtils.h @@ -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 --git a/CPP/7zip/Archive/Common/MultiStream.cpp b/CPP/7zip/Archive/Common/MultiStream.cpp index 162fc928..5d357af7 100644 --- a/CPP/7zip/Archive/Common/MultiStream.cpp +++ b/CPP/7zip/Archive/Common/MultiStream.cpp @@ -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 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) else if (_pos >= m.GlobalOffset + m.Size) left = mid + 1; else - { - _streamIndex = mid; break; - } mid = (left + right) / 2; } _streamIndex = mid; @@ -36,12 +33,14 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ class COutVolumeStream: public ISequentialOutStream, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_0 + Z7_IFACE_COM7_IMP(ISequentialOutStream) + unsigned _volIndex; UInt64 _volSize; UInt64 _curPos; @@ -80,8 +82,6 @@ class COutVolumeStream: CCRC _crc; public: - MY_UNKNOWN_IMP - CFileItem _file; CUpdateOptions _options; CMyComPtr VolumeCallback; @@ -98,7 +98,6 @@ class COutVolumeStream: } HRESULT Flush(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); }; HRESULT COutVolumeStream::Flush() @@ -107,7 +106,7 @@ HRESULT COutVolumeStream::Flush() { _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 @@ HRESULT COutVolumeStream::Flush() */ /* -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 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce 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 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce 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 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce 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 @@ STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP } 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 --git a/CPP/7zip/Archive/Common/MultiStream.h b/CPP/7zip/Archive/Common/MultiStream.h index c10cd455..e3096f58 100644 --- a/CPP/7zip/Archive/Common/MultiStream.h +++ b/CPP/7zip/Archive/Common/MultiStream.h @@ -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 @@ class CMultiStream: 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 @@ class CMultiStream: { 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 @@ class COutMultiStream: _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 --git a/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp b/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp index f955c225..7dcd44ac 100644 --- a/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp +++ b/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp @@ -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 @@ STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *pro if (_calculate) _crc = CrcUpdate(_crc, data, size); _size += size; - if (processedSize != NULL) + if (processedSize) *processedSize = size; return result; } diff --git a/CPP/7zip/Archive/Common/OutStreamWithCRC.h b/CPP/7zip/Archive/Common/OutStreamWithCRC.h index 09b899bb..845146a1 100644 --- a/CPP/7zip/Archive/Common/OutStreamWithCRC.h +++ b/CPP/7zip/Archive/Common/OutStreamWithCRC.h @@ -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 --git a/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp b/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp index ac26edf7..57c18ecc 100644 --- a/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp +++ b/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp @@ -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 --git a/CPP/7zip/Archive/Common/OutStreamWithSha1.h b/CPP/7zip/Archive/Common/OutStreamWithSha1.h index 5a7bfef3..74bc53cb 100644 --- a/CPP/7zip/Archive/Common/OutStreamWithSha1.h +++ b/CPP/7zip/Archive/Common/OutStreamWithSha1.h @@ -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 --git a/CPP/7zip/Archive/Common/ParseProperties.h b/CPP/7zip/Archive/Common/ParseProperties.h index 1038a8c0..4ec2e48e 100644 --- a/CPP/7zip/Archive/Common/ParseProperties.h +++ b/CPP/7zip/Archive/Common/ParseProperties.h @@ -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 --git a/CPP/7zip/Archive/Common/StdAfx.h b/CPP/7zip/Archive/Common/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Common/StdAfx.h +++ b/CPP/7zip/Archive/Common/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/CpioHandler.cpp b/CPP/7zip/Archive/CpioHandler.cpp index b7e7564f..872cea74 100644 --- a/CPP/7zip/Archive/CpioHandler.cpp +++ b/CPP/7zip/Archive/CpioHandler.cpp @@ -44,41 +44,6 @@ static const unsigned k_HexRecord_Size = 6 + 13 * 8; 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 @@ static const char * const k_Types[] = 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 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 G16(offs, v) v = Get16(p + (offs), be) -#define G32(offs, v) v = Get32(p + (offs), be) +#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 @@ API_FUNC_static_IsArc IsArc_Cpio(const Byte *p, size_t size) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType) 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; - 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) + 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) + + 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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ class COutStreamWithSum: 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 @@ STDMETHODIMP COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *pro 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ static const Byte k_Signature[] = { 2, kMagicBin1, kMagicBin0 }; REGISTER_ARC_I( - "Cpio", "cpio", 0, 0xED, + "Cpio", "cpio", NULL, 0xED, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff --git a/CPP/7zip/Archive/CramfsHandler.cpp b/CPP/7zip/Archive/CramfsHandler.cpp index 0f123321..fd83f711 100644 --- a/CPP/7zip/Archive/CramfsHandler.cpp +++ b/CPP/7zip/Archive/CramfsHandler.cpp @@ -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 @@ static UInt32 GetNameLen(const Byte *p, bool be) 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 @@ struct CHeader 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 @@ struct CHeader 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 @@ class CHandler: 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 @@ class CHandler: } 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 @@ HRESULT CHandler::OpenDir(int parent, UInt32 baseOffset, unsigned level) 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::OpenDir(int parent, UInt32 baseOffset, unsigned level) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) _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 @@ HRESULT CHandler::Open2(IInStream *inStream) _items.ClearAndReserve(_h.NumFiles - 1); } - RINOK(OpenDir(-1, kHeaderSize, 0)); + RINOK(OpenDir(-1, kHeaderSize, 0)) if (!_h.IsVer2()) { @@ -389,22 +385,23 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ AString CHandler::GetPath(int index) const 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 @@ AString CHandler::GetPath(int index) const 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) } _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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) UInt32 offset = GetOffset(p, be); if (offset < kHeaderSize) @@ -705,7 +702,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } } - 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) } REGISTER_ARC_I( - "CramFS", "cramfs", 0, 0xD3, + "CramFS", "cramfs", NULL, 0xD3, kSignature, 16, 0, diff --git a/CPP/7zip/Archive/DeflateProps.h b/CPP/7zip/Archive/DeflateProps.h index 9fd2c2e9..666fb39b 100644 --- a/CPP/7zip/Archive/DeflateProps.h +++ b/CPP/7zip/Archive/DeflateProps.h @@ -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 --git a/CPP/7zip/Archive/DllExports.cpp b/CPP/7zip/Archive/DllExports.cpp index 7aee235e..9def2088 100644 --- a/CPP/7zip/Archive/DllExports.cpp +++ b/CPP/7zip/Archive/DllExports.cpp @@ -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 CreateObject(const GUID *clsid, const GUID *iid, void **outObject) STDAPI SetLargePageMode() { - #if defined(_7ZIP_LARGE_PAGES) + #if defined(Z7_LARGE_PAGES) SetLargePageSize(); #endif return S_OK; @@ -64,7 +66,7 @@ STDAPI SetCaseSensitive(Int32 caseSensitive) return S_OK; } -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; diff --git a/CPP/7zip/Archive/DllExports2.cpp b/CPP/7zip/Archive/DllExports2.cpp index 1f714861..ae8d8acc 100644 --- a/CPP/7zip/Archive/DllExports2.cpp +++ b/CPP/7zip/Archive/DllExports2.cpp @@ -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 @@ BOOL WINAPI DllMain( { // OutputDebugStringA("7z.dll DLL_PROCESS_ATTACH"); g_hInstance = (HINSTANCE)hInstance; - NT_CHECK; + NT_CHECK } /* if (dwReason == DLL_PROCESS_DETACH) @@ -80,7 +80,7 @@ static __attribute__((constructor)) void Init_ForceToUTF8() #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); 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 CreateObject(const GUID *clsid, const GUID *iid, void **outObject) STDAPI SetLargePageMode(); STDAPI SetLargePageMode() { - #if defined(_7ZIP_LARGE_PAGES) + #if defined(Z7_LARGE_PAGES) #ifdef _WIN32 SetLargePageSize(); #endif @@ -143,7 +143,7 @@ STDAPI SetProperty(Int32 id, const PROPVARIANT *value) } */ -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; diff --git a/CPP/7zip/Archive/DmgHandler.cpp b/CPP/7zip/Archive/DmgHandler.cpp index e6166f15..4bcb9043 100644 --- a/CPP/7zip/Archive/DmgHandler.cpp +++ b/CPP/7zip/Archive/DmgHandler.cpp @@ -85,7 +85,7 @@ void CChecksum::Parse(const Byte *p) Type = Get32(p); NumBits = Get32(p + 4); memcpy(Data, p + 8, kChecksumSize_Max); -}; +} struct CFile { @@ -132,11 +132,9 @@ struct CForkPair }; -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 @@ class CHandler: 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 @@ static const CAppleName k_Names[] = { 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 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ static int FindKeyPair(const CXmlItem &item, const char *key, const char *nextTa { 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 const Byte k_Signature[] = { 'k','o','l','y', 0, 0, 0, 4, 0, 0, 2, 0 }; 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 @@ HRESULT CHandler::ReadData(IInStream *stream, const CForkPair &pair, CByteBuffer 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 @@ HRESULT CHandler::Open2(IInStream *stream) */ _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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) #else CByteBuffer blobBuf; #endif - RINOK(ReadData(stream, blobPair, blobBuf)); + RINOK(ReadData(stream, blobPair, blobBuf)) if (!ParseBlob(blobBuf)) _headersError = true; } @@ -704,7 +695,7 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) { 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) if (name) file.Name = *name; } - RINOK(file.Parse(rawBuf, destLen)); + RINOK(file.Parse(rawBuf, destLen)) } } @@ -941,9 +932,9 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _inStream.Release(); @@ -970,7 +961,7 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) #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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } UString name2; ConvertUTF8ToUnicode(subName, name2); - name += '.'; + name.Add_Dot(); name += name2; } else @@ -1111,10 +1102,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 CAdcDecoder: } */ - class CCoderReleaser + class CCoderReleaser Z7_final { CAdcDecoder *m_Coder; public: @@ -1142,18 +1134,12 @@ class CAdcDecoder: 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 @@ STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream, 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 @@ STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream, 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 CAdcDecoder::Code(ISequentialInStream *inStream, -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1480,10 +1466,13 @@ struct CChunk 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 @@ class CInStream: 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 @@ static unsigned FindBlock(const CRecordVector &blocks, UInt64 pos) } } -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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) break; if (i != _chunks.Size()) - _latestChunk = i; + _latestChunk = (int)i; else { const unsigned kNumChunksMax = 128; @@ -1620,7 +1604,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio } 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) } REGISTER_ARC_I( - "Dmg", "dmg", 0, 0xE4, + "Dmg", "dmg", NULL, 0xE4, k_Signature, 0, NArcInfoFlags::kBackwardOpen | diff --git a/CPP/7zip/Archive/ElfHandler.cpp b/CPP/7zip/Archive/ElfHandler.cpp index efcde95d..7e1facc9 100644 --- a/CPP/7zip/Archive/ElfHandler.cpp +++ b/CPP/7zip/Archive/ElfHandler.cpp @@ -156,18 +156,22 @@ bool CHeader::Parse(const Byte *p) #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 @@ static const CUInt32PCharPair g_SectTypes[] = { 16, "PREINIT_ARRAY" }, { 17, "GROUP" }, { 18, "SYMTAB_SHNDX" }, + { 0x6ffffff5, "GNU_ATTRIBUTES" }, { 0x6ffffff6, "GNU_HASH" }, { 0x6ffffffd, "GNU_verdef" }, @@ -654,11 +659,9 @@ static const char * const g_Types[] = -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 @@ class CHandler: 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 @@ void CHandler::GetSectionName(UInt32 index, NCOM::CPropVariant &prop, bool showN 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 @@ static const CStatProp kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::Open2(IInStream *stream) { 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 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 --git a/CPP/7zip/Archive/ExtHandler.cpp b/CPP/7zip/Archive/ExtHandler.cpp index 01e12edc..f3094852 100644 --- a/CPP/7zip/Archive/ExtHandler.cpp +++ b/CPP/7zip/Archive/ExtHandler.cpp @@ -353,7 +353,7 @@ static int inline GetLog(UInt32 num) { for (unsigned i = 0; i < 32; i++) if (((UInt32)1 << i) == num) - return i; + return (int)i; return -1; } @@ -371,8 +371,8 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) // 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 @@ bool CHeader::Parse(const Byte *p) // 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) // 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 @@ bool CHeader::Parse(const Byte *p) // 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 @@ struct CGroupDescriptor 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 @@ struct CExtentTreeHeader 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 @@ struct CExtentIndexNode 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 @@ struct CExtent 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 CExtTime 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 @@ struct CNode ParentNode(-1), ItemIndex(-1), SymLinkIndex(-1), - DirIndex(0), + DirIndex(-1), NumLinksCalced(0) {} @@ -679,18 +679,18 @@ bool CNode::Parse(const Byte *p, const CHeader &_h) 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 @@ bool CNode::Parse(const Byte *p, const CHeader &_h) { 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 @@ bool CNode::Parse(const Byte *p, const CHeader &_h) // 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 @@ bool CNode::Parse(const Byte *p, const CHeader &_h) // 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 @@ struct CItem bool IsDir() const { return Type == k_Type_DIR; } // bool IsNotDir() const { return Type != k_Type_DIR && Type != k_Type_UNKNOWN; } - }; @@ -794,14 +793,12 @@ struct CItem 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 @@ class CHandler: 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) 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 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir) } +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 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co 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 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co } 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 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co return -1; if (iNode == k_INODE_ROOT) return -1; - iNode = node.ParentNode; + iNode = (unsigned)node.ParentNode; continue; } } @@ -1087,6 +1081,7 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co const CUIntVector &dir = _dirs[node.DirIndex]; + /* for (unsigned i = 0;; i++) { if (i >= dir.Size()) @@ -1098,6 +1093,26 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co 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 @@ HRESULT CHandler::SeekAndRead(IInStream *inStream, UInt64 block, Byte *data, siz 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 @@ HRESULT CHandler::Open2(IInStream *inStream) { { 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) // ---------- 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 @@ HRESULT CHandler::Open2(IInStream *inStream) { 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) _refs.Add(-1); } - _refs.Add(_nodes.Add(node)); + _refs.Add((int)_nodes.Add(node)); } @@ -1336,7 +1351,7 @@ HRESULT CHandler::Open2(IInStream *inStream) FOR_VECTOR (i, _refs) { - int nodeIndex = _refs[i]; + const int nodeIndex = _refs[i]; { if (nodeIndex < 0) continue; @@ -1344,7 +1359,7 @@ HRESULT CHandler::Open2(IInStream *inStream) if (!node.IsDir()) continue; } - RINOK(ExtractNode(nodeIndex, dataBuf)); + RINOK(ExtractNode((unsigned)nodeIndex, dataBuf)) if (dataBuf.Size() == 0) { // _headersError = true; @@ -1352,12 +1367,12 @@ HRESULT CHandler::Open2(IInStream *inStream) } 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 @@ HRESULT CHandler::Open2(IInStream *inStream) for (;;) { - int nodeIndex = _refs[c]; + const int nodeIndex = _refs[c]; if (nodeIndex < 0) return S_FALSE; CNode &node = _nodes[nodeIndex]; @@ -1435,12 +1450,12 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 @@ HRESULT CHandler::Open2(IInStream *inStream) } 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 @@ void CHandler::ClearRefs() } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalRead = 0; _totalReadPrev = 0; @@ -1652,7 +1672,7 @@ void CHandler::GetPath(unsigned index, AString &s) const 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 @@ bool CHandler::GetPackSize(unsigned index, UInt64 &totalPack) const } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _items.Size() + _auxItems.Size(); return S_OK; @@ -1797,7 +1817,7 @@ static void UnixTimeToProp(UInt32 val, NCOM::CPropVariant &prop) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ static const Byte kRawProps[] = }; */ -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 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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 @@ static void ExtTimeToProp(const CExtTime &t, NCOM::CPropVariant &prop) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } -class CClusterInStream2: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream(CClusterInStream2 +) UInt64 _virtPos; UInt64 _physPos; UInt32 _curRem; @@ -2150,7 +2168,7 @@ class CClusterInStream2: 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 @@ class CClusterInStream2: } 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 @@ STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedS if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } _curRem = blockSize - offsetInBlock; @@ -2229,7 +2242,7 @@ STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedS 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 @@ STDMETHODIMP CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *ne 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 @@ class CExtInStream: 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 @@ STDMETHODIMP CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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::Read(void *data, UInt32 size, UInt32 *processedSize) } -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 @@ STDMETHODIMP CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosi } 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 @@ HRESULT CHandler::FillFileBlocks2(UInt32 block, unsigned level, unsigned numBloc 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 @@ HRESULT CHandler::FillFileBlocks2(UInt32 block, unsigned level, unsigned numBloc return S_FALSE; } - RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks)); + RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks)) continue; } @@ -2464,7 +2470,7 @@ HRESULT CHandler::FillFileBlocks(const Byte *p, unsigned numBlocks, CRecordVecto return S_FALSE; } - RINOK(FillFileBlocks2(val, level, numBlocks, blocks)); + RINOK(FillFileBlocks2(val, level, numBlocks, blocks)) } return S_OK; @@ -2560,8 +2566,8 @@ HRESULT CHandler::FillExtents(const Byte *p, size_t size, CRecordVector 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 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea 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 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea // return S_FALSE; } - RINOK(streamSpec->StartSeek()); + RINOK(streamSpec->StartSeek()) } else { @@ -2648,7 +2654,7 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea } 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 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea 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 @@ HRESULT CHandler::ExtractNode(unsigned nodeIndex, CByteBuffer &data) 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 @@ HRESULT CHandler::ExtractNode(unsigned nodeIndex, CByteBuffer &data) } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int res = NExtract::NOperationResult::kDataError; { @@ -2792,7 +2798,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } else { - RINOK(hres); + RINOK(hres) { hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); if (hres == S_OK) @@ -2806,12 +2812,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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::Extract(const UInt32 *indices, UInt32 numItems, } -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 @@ API_FUNC_IsArc IsArc_Ext(const Byte *p, size_t size) 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 --git a/CPP/7zip/Archive/FatHandler.cpp b/CPP/7zip/Archive/FatHandler.cpp index 826b4fd1..4a843a8f 100644 --- a/CPP/7zip/Archive/FatHandler.cpp +++ b/CPP/7zip/Archive/FatHandler.cpp @@ -134,15 +134,15 @@ bool CHeader::Parse(const Byte *p) } { { - 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ bool CHeader::Parse(const Byte *p) 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 @@ struct CDatabase UInt64 PhySize; - CDatabase(): Fat(0) {} + CDatabase(): Fat(NULL) {} ~CDatabase() { ClearAndClose(); } void Clear(); @@ -366,7 +369,7 @@ struct CDatabase 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 @@ struct CDatabase 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 @@ void CDatabase::Clear() Items.Clear(); delete []Fat; - Fat = 0; + Fat = NULL; } void CDatabase::ClearAndClose() @@ -409,7 +412,7 @@ HRESULT CDatabase::OpenProgressFat(bool changeTotal) { 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 @@ HRESULT CDatabase::OpenProgress() 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 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level) if (!clusterMode) { blockSize = Header.SectorSize(); - RINOK(SeekToSector(Header.RootDirSector)); + RINOK(SeekToSector(Header.RootDirSector)) } ByteBuf.Alloc(blockSize); @@ -480,7 +483,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level) if ((NumDirClusters & 0xFF) == 0) { - RINOK(OpenProgress()); + RINOK(OpenProgress()) } if (clusterMode) @@ -490,7 +493,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level) 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 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level) 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 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level) 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() i += size; if ((i & 0xFFFFF) == 0) { - RINOK(OpenProgressFat(!numFreeClustersDefined)); + RINOK(OpenProgressFat(!numFreeClustersDefined)) } } } @@ -711,7 +714,7 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() } } - RINOK(OpenProgressFat()); + RINOK(OpenProgressFat()) if ((Fat[0] & 0xFF) != Header.MediaType) { @@ -741,28 +744,27 @@ HRESULT CDatabase::Open() 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ static void StringToProp(const Byte *src, unsigned size, NWindows::NCOM::CPropVa #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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!item.IsDir()) totalSize += item.Size; } - RINOK(extractCallback->SetTotal(totalSize)); + RINOK(extractCallback->SetTotal(totalSize)) UInt64 totalPackSize; totalSize = totalPackSize = 0; @@ -995,23 +997,25 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -1031,22 +1035,22 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 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 --git a/CPP/7zip/Archive/FlvHandler.cpp b/CPP/7zip/Archive/FlvHandler.cpp index 97a7c268..1f746aa9 100644 --- a/CPP/7zip/Archive/FlvHandler.cpp +++ b/CPP/7zip/Archive/FlvHandler.cpp @@ -64,11 +64,10 @@ struct CItem2 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 @@ class CHandler: 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 @@ static const char * const g_Rates[4] = , "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 @@ AString CHandler::GetComment() } */ -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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _stream.Release(); @@ -450,17 +445,17 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 --git a/CPP/7zip/Archive/GptHandler.cpp b/CPP/7zip/Archive/GptHandler.cpp index 0d2caa3d..78c76cf8 100644 --- a/CPP/7zip/Archive/GptHandler.cpp +++ b/CPP/7zip/Archive/GptHandler.cpp @@ -30,10 +30,9 @@ API_FUNC_IsArc IsArc_Fat(const Byte *p, size_t size); 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 @@ struct CPartType 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 const CPartType kPartTypes[] = 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 @@ static void RawLeGuidToString_Upper(const Byte *g, char *s) } -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 @@ class CHandler: public CHandlerCont 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) || 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 @@ HRESULT CHandler::Open2(IInStream *stream) { UInt64 fileEnd; - RINOK(stream->Seek(0, STREAM_SEEK_END, &fileEnd)); + RINOK(InStream_GetSize_SeekToEnd(stream, fileEnd)) if (_totalSize < fileEnd) { @@ -246,7 +244,7 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ static bool IsNtfs(const Byte *p) { 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 @@ static bool IsNtfs(const Byte *p) } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; memset(Guid, 0, sizeof(Guid)); @@ -356,7 +356,7 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } if (!s2.IsEmpty()) { - s += '.'; + s.Add_Dot(); s += s2; } } { - s += '.'; + s.Add_Dot(); s += (item.Ext ? item.Ext : "img"); } prop = s; diff --git a/CPP/7zip/Archive/GzHandler.cpp b/CPP/7zip/Archive/GzHandler.cpp index 35e642ec..ad9a0741 100644 --- a/CPP/7zip/Archive/GzHandler.cpp +++ b/CPP/7zip/Archive/GzHandler.cpp @@ -354,7 +354,7 @@ HRESULT CItem::ReadHeader(NDecoder::CCOMCoder *stream) // 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 @@ HRESULT CItem::ReadHeader(NDecoder::CCOMCoder *stream) 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::ReadHeader(NDecoder::CCOMCoder *stream) 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::ReadFooter1(NDecoder::CCOMCoder *stream) 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 @@ HRESULT CItem::WriteHeader(ISequentialOutStream *stream) 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::WriteHeader(ISequentialOutStream *stream) 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 @@ class CHandler: 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 @@ static const Byte kArcProps[] = 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN 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 CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const /* */ -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { COM_TRY_BEGIN try @@ -656,7 +642,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 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 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _needSeekToStart = false; @@ -687,8 +673,8 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, lps->InSize = packSize; lps->OutSize = unpackedSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CItem item; @@ -954,14 +940,15 @@ static HRESULT UpdateArchive( { 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 @@ static HRESULT UpdateArchive( } 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 @@ static HRESULT UpdateArchive( 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 @@ static HRESULT UpdateArchive( } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType)) { /* if (_item.Time != 0) @@ -1049,24 +1036,29 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR continue; } } - RINOK(_props.SetProperty(name, value)); + RINOK(_props.SetProperty(name, value)) } return S_OK; } diff --git a/CPP/7zip/Archive/HandlerCont.cpp b/CPP/7zip/Archive/HandlerCont.cpp index 3cbfdacd..b4524a44 100644 --- a/CPP/7zip/Archive/HandlerCont.cpp +++ b/CPP/7zip/Archive/HandlerCont.cpp @@ -18,14 +18,14 @@ namespace NExt { 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 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, } 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 @@ CHandlerImg::CHandlerImg() 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 @@ STDMETHODIMP CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosit *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 @@ void CHandlerImg::Clear_HandlerImg_Vars() 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 @@ STDMETHODIMP CHandlerImg::Open(IInStream *stream, 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 CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt6 } -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 @@ STDMETHODIMP CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ HRESULT ReadZeroTail(ISequentialInStream *stream, bool &areThereNonZeros, UInt64 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 --git a/CPP/7zip/Archive/HandlerCont.h b/CPP/7zip/Archive/HandlerCont.h index 3c645929..2dd0529e 100644 --- a/CPP/7zip/Archive/HandlerCont.h +++ b/CPP/7zip/Archive/HandlerCont.h @@ -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 @@ class CHandlerImg: 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 --git a/CPP/7zip/Archive/HfsHandler.cpp b/CPP/7zip/Archive/HfsHandler.cpp index fa96b735..696ecd7b 100644 --- a/CPP/7zip/Archive/HfsHandler.cpp +++ b/CPP/7zip/Archive/HfsHandler.cpp @@ -126,16 +126,16 @@ bool CFork::Check_NumBlocks() const 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 @@ static int FindItemIndex(const CRecordVector &items, UInt32 id) 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 @@ static int Find_in_IdExtents(const CObjectVector &items, UInt32 id) 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_COPY_RSRC = 10; // 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 @@ static const char * const g_Methods[] = , "COPY-rsrc" , "LZFSE-attr" , "LZFSE-rsrc" + , NULL + , "ZBM-rsrc" }; @@ -281,7 +285,9 @@ void CCompressHeader::Parse(const Byte *p, size_t dataSize) 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 @@ void CCompressHeader::MethodToProp(NWindows::NCOM::CPropVariant &prop) const 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 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path) { 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 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path) len += s->Len(); len++; - cur = ref.Parent; - if (cur < 0) + cur = (unsigned)ref.Parent; + if (ref.Parent < 0) break; } @@ -580,7 +586,7 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path) if (len == 0) break; p[--len] = delimChar; - cur = ref.Parent; + cur = (unsigned)ref.Parent; } } @@ -607,10 +613,10 @@ HRESULT CDatabase::ReadFile(const CFork &fork, CByteBuffer &buf, IInStream *inSt 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 @@ HRESULT CDatabase::LoadExtentFile(const CFork &fork, IInStream *inStream, CObjec 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 @@ HRESULT CDatabase::LoadAttrs(const CFork &fork, IInStream *inStream, IArchiveOpe 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 @@ HRESULT CDatabase::LoadAttrs(const CFork &fork, IInStream *inStream, IArchiveOpe 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 @@ bool CDatabase::Parse_decmpgfs(unsigned attrIndex, CItem &item, bool &skip) 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 @@ bool CDatabase::Parse_decmpgfs(unsigned attrIndex, CItem &item, bool &skip) 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 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVectorSetCompleted(&numItems, NULL)); + RINOK(progress->SetCompleted(&numItems, NULL)) } } node = desc.fLink; @@ -1265,7 +1271,7 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVectorSetTotal(&numFiles, NULL)); + RINOK(progress->SetTotal(&numFiles, NULL)) } h.NumFreeBlocks = Get16(p + 0x22); */ @@ -1420,8 +1426,8 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress) 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 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress) 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 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress) 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 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress) -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 @@ static void HfsTimeToProp(UInt32 hfsTime, NWindows::NCOM::CPropVariant &prop) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( 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 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( _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 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( 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 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( 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 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( if ((i & 0xFF) == 0) { const UInt64 progressPos = progressStart + outPos; - RINOK(extractCallback->SetCompleted(&progressPos)); + RINOK(extractCallback->SetCompleted(&progressPos)) } } @@ -1940,7 +1944,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB( /* 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 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( 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 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( 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 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( return S_FALSE; if (outStream) { - RINOK(WriteStream(outStream, buf, blockSize)); + RINOK(WriteStream(outStream, buf + 1, blockSize)) } } else @@ -2039,7 +2043,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( 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 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( if ((i & 0xFF) == 0) { const UInt64 progressPos = progressStart + outPos; - RINOK(extractCallback->SetCompleted(&progressPos)); + RINOK(extractCallback->SetCompleted(&progressPos)) } } @@ -2055,6 +2059,186 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE( } +/* +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 @@ HRESULT CDecoder::Extract( 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 @@ HRESULT CDecoder::Extract( 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 @@ HRESULT CDecoder::Extract( } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, RINOK(WriteStream(realOutStream, // AttrBuf + attr.Pos, attr.Size attr.Data, attr.Data.Size() - )); + )) } } } @@ -2258,7 +2451,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } 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 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream) { - *stream = 0; + *stream = NULL; if (!fork.IsOk(Header.BlockSizeLog)) return S_FALSE; @@ -2354,9 +2547,9 @@ HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream) 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 @@ static const Byte k_Signature[] = { 4, 'H', 'X', 0, 5 }; REGISTER_ARC_I( - "HFS", "hfs hfsx", 0, 0xE3, + "HFS", "hfs hfsx", NULL, 0xE3, k_Signature, kHeaderPadSize, NArcInfoFlags::kMultiSignature, diff --git a/CPP/7zip/Archive/HfsHandler.h b/CPP/7zip/Archive/HfsHandler.h index 2461f6b8..0006e12d 100644 --- a/CPP/7zip/Archive/HfsHandler.h +++ b/CPP/7zip/Archive/HfsHandler.h @@ -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" @@ -67,6 +67,11 @@ class CDecoder UInt64 forkSize, UInt64 unpackSize, UInt64 progressStart, IArchiveExtractCallback *extractCallback); + HRESULT ExtractResourceFork_ZBM( + ISequentialInStream *inStream, ISequentialOutStream *realOutStream, + UInt64 forkSize, UInt64 unpackSize, + UInt64 progressStart, IArchiveExtractCallback *extractCallback); + public: HRESULT Extract( diff --git a/CPP/7zip/Archive/IArchive.h b/CPP/7zip/Archive/IArchive.h index 3862e555..3e68ac30 100644 --- a/CPP/7zip/Archive/IArchive.h +++ b/CPP/7zip/Archive/IArchive.h @@ -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 @@ namespace NArcInfoTimeFlags 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 @@ namespace NArchive kIsNotArc, kHeadersError, kWrongPassword + // , kMemError }; } } @@ -166,14 +174,11 @@ namespace NArchive } } -#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:: @@ -209,7 +214,7 @@ IArchiveExtractCallback::GetStream() if (IProgress::SetTotal() was called) { IProgress::SetCompleted(completeValue) uses - packSize - for some stream formats (xz, gz, bz2, lz, lzma, z, ppmd). + packSize - for some stream formats (xz, gz, bz2, lzma, z, ppmd). unpackSize - for another formats. } else @@ -224,57 +229,49 @@ SetOperationResult() 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) */ +/* +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 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); -}; - +#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) -ARCHIVE_INTERFACE(IInArchiveGetStream, 0x40) -{ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) PURE; -}; +#define Z7_IFACEM_IInArchiveGetStream(x) \ + x(GetStream(UInt32 index, ISequentialInStream **stream)) +Z7_IFACE_CONSTR_ARCHIVE(IInArchiveGetStream, 0x40) -ARCHIVE_INTERFACE(IArchiveOpenSetSubArchiveName, 0x50) -{ - STDMETHOD(SetSubArchiveName)(const wchar_t *name) PURE; -}; +#define Z7_IFACEM_IArchiveOpenSetSubArchiveName(x) \ + x(SetSubArchiveName(const wchar_t *name)) +Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenSetSubArchiveName, 0x50) /* @@ -310,28 +307,25 @@ IInArchive::GetArchiveProperty: 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; \ - -ARCHIVE_INTERFACE(IInArchive, 0x60) -{ - INTERFACE_IInArchive(PURE) -}; +#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)) \ + +Z7_IFACE_CONSTR_ARCHIVE(IInArchive, 0x60) namespace NParentType { @@ -340,7 +334,7 @@ namespace NParentType kDir = 0, kAltStream }; -}; +} namespace NPropDataType { @@ -356,41 +350,36 @@ namespace NPropDataType 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; +#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)) -ARCHIVE_INTERFACE(IArchiveGetRawProps, 0x70) -{ - INTERFACE_IArchiveGetRawProps(PURE) -}; +Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetRawProps, 0x70) -#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_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 @@ const UInt32 kOpenFlags_NoSeek = 1 << 1; 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 @@ SetOperationResult() 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; \ +// 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)) \ -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback, IProgress, 0x80) -{ - INTERFACE_IArchiveUpdateCallback(PURE); -}; +Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveUpdateCallback, IProgress, 0x80) -#define INTERFACE_IArchiveUpdateCallback2(x) \ - INTERFACE_IArchiveUpdateCallback(x) \ - STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size) x; \ - STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream) x; \ +// 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 @@ namespace NUpdateNotifyOp // , kOpFinished // , kNumDefined }; -}; +} /* IArchiveUpdateCallbackFile::ReportOperation @@ -502,36 +483,26 @@ IArchiveUpdateCallbackFile::ReportOperation 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,19 +527,12 @@ UpdateItems() */ -#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) -ARCHIVE_INTERFACE(IMultiVolumeOutArchive, 0xFF) -{ - STDMETHOD(GetMultiArchiveNameFmt)(PROPVARIANT* nameMod, PROPVARIANT* prefix, PROPVARIANT* postfix, BOOL* numberAfterExt, UInt32* digitCount) PURE; -}; /* ISetProperties::SetProperties() @@ -580,31 +544,26 @@ ISetProperties::SetProperties() 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 @@ -620,46 +579,69 @@ namespace NCOM { 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 @@ -675,7 +657,6 @@ extern "C" typedef UInt32 (WINAPI *Func_IsArc)(const Byte *p, size_t size); typedef HRESULT (WINAPI *Func_GetIsArc)(UInt32 formatIndex, Func_IsArc *isArc); - typedef HRESULT (WINAPI *Func_GetFormatLevelMask)(UInt32 formatIndex, UInt32 *mask); typedef HRESULT (WINAPI *Func_GetNumberOfFormats)(UInt32 *numFormats); typedef HRESULT (WINAPI *Func_GetHandlerProperty)(PROPID propID, PROPVARIANT *value); @@ -719,4 +700,5 @@ extern UInt32 g_ClientVersion; NFileTimeType::kWindows)) */ +Z7_PURE_INTERFACES_END #endif diff --git a/CPP/7zip/Archive/IhexHandler.cpp b/CPP/7zip/Archive/IhexHandler.cpp index 05453ee6..badb5593 100644 --- a/CPP/7zip/Archive/IhexHandler.cpp +++ b/CPP/7zip/Archive/IhexHandler.cpp @@ -27,10 +27,9 @@ struct CBlock UInt32 Offset; }; -class CHandler: - public IInArchive, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_0 + bool _isArc; bool _needMoreInput; bool _dataError; @@ -38,9 +37,6 @@ class CHandler: UInt64 _phySize; CObjectVector _blocks; -public: - MY_UNKNOWN_IMP1(IInArchive) - INTERFACE_IInArchive(;) }; static const Byte kProps[] = @@ -53,13 +49,13 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ API_FUNC_static_IsArc IsArc_Ihex(const Byte *p, size_t size) { 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 @@ API_FUNC_static_IsArc IsArc_Ihex(const Byte *p, size_t size) } } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb } _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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb _needMoreInput = true; return S_FALSE; } - int num = Parse(temp); + const int num = Parse(temp); if (num < 0) { _dataError = true; @@ -287,17 +283,17 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; @@ -426,11 +422,11 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // k_Signature: { ':', '1' } REGISTER_ARC_I_NO_SIG( - "IHex", "ihex", 0, 0xCD, + "IHex", "ihex", NULL, 0xCD, 0, NArcInfoFlags::kStartOpen, IsArc_Ihex) diff --git a/CPP/7zip/Archive/Iso/IsoHandler.cpp b/CPP/7zip/Archive/Iso/IsoHandler.cpp index 8588a7c5..0c63c71e 100644 --- a/CPP/7zip/Archive/Iso/IsoHandler.cpp +++ b/CPP/7zip/Archive/Iso/IsoHandler.cpp @@ -8,6 +8,7 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" +#include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" @@ -48,28 +49,28 @@ static const Byte kArcProps[] = 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 @@ static void AddErrorMessage(AString &s, const char *message) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val if (_archive.BootEntries.Size() != 1) { s.Add_UInt32(index + 1); - s += '-'; + s.Add_Minus(); } s += be.GetName(); prop = s; @@ -303,11 +304,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 --git a/CPP/7zip/Archive/Iso/IsoHandler.h b/CPP/7zip/Archive/Iso/IsoHandler.h index 1923784d..507814ac 100644 --- a/CPP/7zip/Archive/Iso/IsoHandler.h +++ b/CPP/7zip/Archive/Iso/IsoHandler.h @@ -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 --git a/CPP/7zip/Archive/Iso/IsoHeader.h b/CPP/7zip/Archive/Iso/IsoHeader.h index e6a4d327..0b14c9fb 100644 --- a/CPP/7zip/Archive/Iso/IsoHeader.h +++ b/CPP/7zip/Archive/Iso/IsoHeader.h @@ -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 --git a/CPP/7zip/Archive/Iso/IsoIn.cpp b/CPP/7zip/Archive/Iso/IsoIn.cpp index 67802359..1d3a42ff 100644 --- a/CPP/7zip/Archive/Iso/IsoIn.cpp +++ b/CPP/7zip/Archive/Iso/IsoIn.cpp @@ -48,9 +48,9 @@ bool CBootInitialEntry::Parse(const Byte *p) 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 @@ AString CBootInitialEntry::GetName() const 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 @@ UInt16 CInArchive::ReadUInt16() { 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 @@ static inline bool CheckSignature(const Byte *sig, const Byte *data) 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 @@ void CInArchive::ReadBootInfo() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ void CInArchive::Clear() 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 --git a/CPP/7zip/Archive/Iso/IsoIn.h b/CPP/7zip/Archive/Iso/IsoIn.h index a705b06a..f3e47513 100644 --- a/CPP/7zip/Archive/Iso/IsoIn.h +++ b/CPP/7zip/Archive/Iso/IsoIn.h @@ -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 @@ struct CDir: public CDirRecord void Clear() { - Parent = 0; + Parent = NULL; _subItems.Clear(); } @@ -133,7 +133,7 @@ struct CDateTime 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 @@ class CInArchive 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 @@ class CInArchive // 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 @@ class CInArchive 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 --git a/CPP/7zip/Archive/Iso/IsoItem.h b/CPP/7zip/Archive/Iso/IsoItem.h index 8c2a7253..95568058 100644 --- a/CPP/7zip/Archive/Iso/IsoItem.h +++ b/CPP/7zip/Archive/Iso/IsoItem.h @@ -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 @@ struct CRecordingDateTime 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 @@ struct CDirRecord { 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 @@ struct CDirRecord } - bool GetSymLink(int skipSize, AString &link) const + bool GetSymLink(unsigned skipSize, AString &link) const { link.Empty(); const Byte *p = NULL; @@ -185,13 +185,13 @@ struct CDirRecord 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 @@ struct CDirRecord } - 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 @@ struct CDirRecord 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 @@ struct CDirRecord 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 --git a/CPP/7zip/Archive/Iso/IsoRegister.cpp b/CPP/7zip/Archive/Iso/IsoRegister.cpp index 0205238d..41b56bac 100644 --- a/CPP/7zip/Archive/Iso/IsoRegister.cpp +++ b/CPP/7zip/Archive/Iso/IsoRegister.cpp @@ -12,7 +12,7 @@ namespace NIso { 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 --git a/CPP/7zip/Archive/Iso/StdAfx.h b/CPP/7zip/Archive/Iso/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Iso/StdAfx.h +++ b/CPP/7zip/Archive/Iso/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/LizardHandler.cpp b/CPP/7zip/Archive/LizardHandler.cpp index 938dd754..a3117a8f 100644 --- a/CPP/7zip/Archive/LizardHandler.cpp +++ b/CPP/7zip/Archive/LizardHandler.cpp @@ -22,13 +22,11 @@ using namespace NWindows; namespace NArchive { namespace NLIZARD { -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; @@ -45,19 +43,6 @@ class CHandler: 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[] = @@ -75,18 +60,18 @@ static const Byte kArcProps[] = IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/)) { 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) @@ -122,7 +107,7 @@ API_FUNC_static_IsArc IsArc_lizard(const Byte *p, size_t size) } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); @@ -140,7 +125,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -148,7 +133,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _dataAfterEnd = false; @@ -164,8 +149,8 @@ STDMETHODIMP CHandler::Close() 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) @@ -281,14 +266,14 @@ static HRESULT UpdateArchive( return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -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 *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -349,7 +334,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/LpHandler.cpp b/CPP/7zip/Archive/LpHandler.cpp index b2720f4b..c1a76b44 100644 --- a/CPP/7zip/Archive/LpHandler.cpp +++ b/CPP/7zip/Archive/LpHandler.cpp @@ -59,9 +59,9 @@ static const unsigned kSectorSizeLog = 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 @@ struct CGeometry 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 @@ struct CDescriptor 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 @@ struct CPartition 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 @@ struct CExtent 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 @@ struct CGroup 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 @@ struct CDevice 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 @@ struct LpMetadataHeader 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 @@ static bool CheckSha256_csOffset(Byte *data, size_t size, unsigned hashOffset) -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _items; CRecordVector Extents; @@ -505,11 +503,6 @@ class CHandler: AString DeviceArcName; HRESULT Open2(IInStream *stream); - -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - INTERFACE_IInArchive(;) - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); }; @@ -533,10 +526,10 @@ static bool IsBufZero(const Byte *data, size_t size) 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 @@ HRESULT CHandler::Open2(IInStream *stream) } 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 @@ HRESULT CHandler::Open2(IInStream *stream) } } - 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 @@ HRESULT CHandler::Open2(IInStream *stream) // 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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::Open(IInStream *stream, } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; // _usedSize = 0; @@ -818,7 +811,7 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { AString s; s.Add_UInt32(Major_version); - s += '.'; + s.Add_Dot(); s.Add_UInt32(Minor_version); prop = s; break; @@ -874,7 +867,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val -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::GetStream(UInt32 index, ISequentialInStream **stream) } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, opRes = NExtract::NOperationResult::kUnexpectedEnd; } outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; diff --git a/CPP/7zip/Archive/Lz4Handler.cpp b/CPP/7zip/Archive/Lz4Handler.cpp index 9984da82..fe39e511 100644 --- a/CPP/7zip/Archive/Lz4Handler.cpp +++ b/CPP/7zip/Archive/Lz4Handler.cpp @@ -22,13 +22,11 @@ using namespace NWindows; namespace NArchive { namespace NLZ4 { -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; @@ -45,19 +43,6 @@ class CHandler: 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[] = @@ -75,18 +60,18 @@ static const Byte kArcProps[] = IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/)) { 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) @@ -122,7 +107,7 @@ API_FUNC_static_IsArc IsArc_lz4(const Byte *p, size_t size) } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); @@ -140,7 +125,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -148,7 +133,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _dataAfterEnd = false; @@ -164,8 +149,8 @@ STDMETHODIMP CHandler::Close() 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) @@ -281,14 +266,14 @@ static HRESULT UpdateArchive( return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -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 *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -349,7 +334,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/Lz5Handler.cpp b/CPP/7zip/Archive/Lz5Handler.cpp index 2ed99fe3..b40f590b 100644 --- a/CPP/7zip/Archive/Lz5Handler.cpp +++ b/CPP/7zip/Archive/Lz5Handler.cpp @@ -22,13 +22,11 @@ using namespace NWindows; namespace NArchive { namespace NLZ5 { -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; @@ -45,19 +43,6 @@ class CHandler: 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[] = @@ -75,18 +60,18 @@ static const Byte kArcProps[] = IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/)) { 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) @@ -122,7 +107,7 @@ API_FUNC_static_IsArc IsArc_lz5(const Byte *p, size_t size) } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); @@ -140,7 +125,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -148,7 +133,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _dataAfterEnd = false; @@ -164,8 +149,8 @@ STDMETHODIMP CHandler::Close() 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) @@ -281,14 +266,14 @@ static HRESULT UpdateArchive( return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -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 *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -349,7 +334,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/LzHandler.cpp b/CPP/7zip/Archive/LzHandler.cpp index 188ecba2..b6f1f401 100644 --- a/CPP/7zip/Archive/LzHandler.cpp +++ b/CPP/7zip/Archive/LzHandler.cpp @@ -75,7 +75,6 @@ struct CTrailer return tmp; } }; - class CDecoder { CMyComPtr _lzmaDecoder; @@ -129,11 +128,10 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream, } -class CHandler: - public IInArchive, - public IArchiveOpenSeq, - public CMyUnknownImp -{ +// IInArchiveGetStream, +Z7_CLASS_IMP_CHandler_IInArchive_1( + IArchiveOpenSeq +) CHeader _header; CMyComPtr _stream; CMyComPtr _seqStream; @@ -152,20 +150,12 @@ class CHandler: UInt64 _packSize; UInt64 _unpackSize; UInt64 _numStreams; - -public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq) - - INTERFACE_IInArchive(;) - STDMETHOD(OpenSeq)(ISequentialInStream *stream); - - CHandler() { } }; 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) @@ -187,13 +177,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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) @@ -229,7 +219,7 @@ bool CHeader::Parse() return (DicSize >= min_dictionary_size && DicSize <= max_dictionary_size); } -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *)) { Close(); @@ -248,7 +238,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal return S_OK; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -256,7 +246,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _packSize_Defined = false; @@ -276,20 +266,17 @@ STDMETHODIMP CHandler::Close() 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) { @@ -300,8 +287,8 @@ STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const 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) diff --git a/CPP/7zip/Archive/LzhHandler.cpp b/CPP/7zip/Archive/LzhHandler.cpp index 6711da60..9239afda 100644 --- a/CPP/7zip/Archive/LzhHandler.cpp +++ b/CPP/7zip/Archive/LzhHandler.cpp @@ -51,9 +51,8 @@ UInt32 LzhCrc16Update(UInt32 crc, const void *data, size_t size) return crc; } -static class CLzhCrc16TableInit +static struct CLzhCrc16TableInit { -public: CLzhCrc16TableInit() { for (UInt32 i = 0; i < 256; i++) @@ -176,7 +175,7 @@ struct CItem { FOR_VECTOR (i, Extensions) if (Extensions[i].Type == type) - return i; + return (int)i; return -1; } @@ -239,10 +238,10 @@ static const Byte *ReadString(const Byte *p, size_t size, AString &s) 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 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite 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 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite 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 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite { 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 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite 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 @@ static const Byte kProps[] = }; -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 @@ class COutStreamWithCRC: 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 @@ struct CItemEx: public CItem }; -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 @@ IMP_IInArchive_ArcProps_NO_Table 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, { _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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, _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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, { 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _phySize = 0; @@ -592,30 +581,28 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) currentItemUnPacked = item.Size; currentItemPacked = item.PackSize; @@ -672,8 +661,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 --git a/CPP/7zip/Archive/LzmaHandler.cpp b/CPP/7zip/Archive/LzmaHandler.cpp index ba547c83..11cb76ed 100644 --- a/CPP/7zip/Archive/LzmaHandler.cpp +++ b/CPP/7zip/Archive/LzmaHandler.cpp @@ -76,7 +76,7 @@ bool CHeader::Parse(const Byte *buf, bool isThereFilter) && CheckDicSize(LzmaProps + 1); } -class CDecoder +class CDecoder Z7_final { CMyComPtr _bcjStream; CFilterCoder *_filterCoder; @@ -112,7 +112,7 @@ HRESULT CDecoder::Create(bool filteredMode, ISequentialInStream *inStream) { _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 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream, 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 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream, res = res2; } - RINOK(res); + RINOK(res) if (header.HasSize()) if (_lzmaDecoderSpec->GetOutputProcessedSize() != header.Size) @@ -167,11 +167,9 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream, } -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 @@ class CHandler: 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; @@ -244,7 +234,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 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 @@ void CHandler::GetMethod(NCOM::CPropVariant &prop) } -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 @@ API_FUNC_static_IsArc IsArc_Lzma86(const Byte *p, size_t size) -STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *)) { Close(); @@ -356,7 +346,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal return S_OK; } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -409,41 +399,38 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 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 @@ STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } if (result == S_FALSE) break; - RINOK(result); + RINOK(result) } if (firstItem) @@ -602,7 +589,7 @@ namespace NLzmaAr { 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 @@ namespace NLzma86Ar { REGISTER_ARC_I_CLS_NO_SIG( CHandler(true), - "lzma86", "lzma86", 0, 0xB, + "lzma86", "lzma86", NULL, 0xB, 0, NArcInfoFlags::kKeepName, IsArc_Lzma86) diff --git a/CPP/7zip/Archive/MachoHandler.cpp b/CPP/7zip/Archive/MachoHandler.cpp index bc8ba223..4920a046 100644 --- a/CPP/7zip/Archive/MachoHandler.cpp +++ b/CPP/7zip/Archive/MachoHandler.cpp @@ -95,6 +95,13 @@ static const char * const g_SectTypes[] = , "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 char * const g_ArcFlags[] = }; -static const CUInt32PCharPair g_Flags[] = +static const CUInt32PCharPair g_SectFlags[] = { { 31, "PURE_INSTRUCTIONS" }, { 30, "NO_TOC" }, @@ -171,25 +178,54 @@ static const CUInt32PCharPair g_Flags[] = { 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 @@ struct CSection }; -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 @@ class CHandler: HRESULT Open2(ISequentialInStream *stream); public: - MY_UNKNOWN_IMP2(IInArchive, IArchiveAllowTail) - INTERFACE_IInArchive(;) - STDMETHOD(AllowTail)(Int32 allowTail); CHandler(): _allowTail(false) {} }; @@ -240,13 +271,14 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val { 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) _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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) _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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) } 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _inStream.Release(); @@ -581,17 +657,17 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ static const Byte k_Signature[] = { 4, 0xFE, 0xED, 0xFA, 0xCF }; REGISTER_ARC_I( - "MachO", "macho", 0, 0xDF, + "MachO", "macho", NULL, 0xDF, k_Signature, 0, NArcInfoFlags::kMultiSignature | diff --git a/CPP/7zip/Archive/MbrHandler.cpp b/CPP/7zip/Archive/MbrHandler.cpp index 026696f3..0d3611b9 100644 --- a/CPP/7zip/Archive/MbrHandler.cpp +++ b/CPP/7zip/Archive/MbrHandler.cpp @@ -54,7 +54,7 @@ struct CChs // 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 @@ void CChs::ToString(NCOM::CPropVariant &prop) const { 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 @@ struct CPartType #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 @@ static const CPartType kPartTypes[] = { 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 @@ struct CItem { 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 @@ class CHandler: public CHandlerCont } 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 @@ HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsi 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 @@ HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsi 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Close() return S_OK; } + enum { kpidPrimary = kpidUserDefined, @@ -347,7 +450,7 @@ static const CStatProp kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val // 2, { 0x55, 0x1FF }, REGISTER_ARC_I_NO_SIG( - "MBR", "mbr", 0, 0xDB, + "MBR", "mbr", NULL, 0xDB, 0, NArcInfoFlags::kPureStartOpen, NULL) diff --git a/CPP/7zip/Archive/MslzHandler.cpp b/CPP/7zip/Archive/MslzHandler.cpp index 6f9057a6..04549f81 100644 --- a/CPP/7zip/Archive/MslzHandler.cpp +++ b/CPP/7zip/Archive/MslzHandler.cpp @@ -21,11 +21,9 @@ namespace NMslz { 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 @@ class CHandler: 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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback) { 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 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback) { 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 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback) _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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPo COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _originalFileSize = 0; _packSize = 0; @@ -276,11 +269,11 @@ static HRESULT MslzDec(CInBuffer &inStream, ISequentialOutStream *outStream, UIn } 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 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { if (!_inStream) return E_FAIL; - RINOK(_inStream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_inStream)) } else _needSeekToStart = true; @@ -388,7 +381,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } REGISTER_ARC_I( - "MsLZ", "mslz", 0, 0xD5, + "MsLZ", "mslz", NULL, 0xD5, kSignature, 0, 0, diff --git a/CPP/7zip/Archive/MubHandler.cpp b/CPP/7zip/Archive/MubHandler.cpp index c790265d..7363b1b3 100644 --- a/CPP/7zip/Archive/MubHandler.cpp +++ b/CPP/7zip/Archive/MubHandler.cpp @@ -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 @@ struct CItem 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 @@ class CHandler: public CHandlerCont 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 kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) (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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _stream.Release(); _numItems = 0; @@ -223,7 +238,7 @@ STDMETHODIMP CHandler::Close() return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _numItems; return S_OK; @@ -236,7 +251,7 @@ static const Byte k_Signature[] = { 4, 0xB9, 0xFA, 0xF1, 0x0E }; REGISTER_ARC_I( - "Mub", "mub", 0, 0xE2, + "Mub", "mub", NULL, 0xE2, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff --git a/CPP/7zip/Archive/Nsis/NsisDecode.cpp b/CPP/7zip/Archive/Nsis/NsisDecode.cpp index e2822184..044de37f 100644 --- a/CPP/7zip/Archive/Nsis/NsisDecode.cpp +++ b/CPP/7zip/Archive/Nsis/NsisDecode.cpp @@ -40,7 +40,7 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) if (!_codecInStream) { - switch (Method) + switch ((int)Method) { // case NMethodType::kCopy: return E_NOTIMPL; case NMethodType::kDeflate: @@ -65,7 +65,7 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) 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 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) { _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 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) { 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 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) _codecInStream.QueryInterface(IID_ICompressSetInStream, &setInStream); if (!setInStream) return E_NOTIMPL; - RINOK(setInStream->SetInStream(inStream)); + RINOK(setInStream->SetInStream(inStream)) } { @@ -106,12 +106,12 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter) _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 @@ HRESULT CDecoder::SetToPos(UInt64 pos, ICompressProgressInfo *progress) 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp { 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp { 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp limitedStreamSpec->Init(size); { bool useFilter; - RINOK(Init(limitedStream, useFilter)); + RINOK(Init(limitedStream, useFilter)) } } @@ -244,7 +244,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp 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 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp unpackSizeRes += (UInt32)size; UInt64 outSize = offset; - RINOK(progress->SetRatioInfo(&inSize, &outSize)); + RINOK(progress->SetRatioInfo(&inSize, &outSize)) if (realOutStream) { res = WriteStream(realOutStream, Buffer, size); diff --git a/CPP/7zip/Archive/Nsis/NsisDecode.h b/CPP/7zip/Archive/Nsis/NsisDecode.h index 2153d785..1d08d018 100644 --- a/CPP/7zip/Archive/Nsis/NsisDecode.h +++ b/CPP/7zip/Archive/Nsis/NsisDecode.h @@ -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 @@ class CDecoder HRESULT Read(void *data, size_t *processedSize) { - return ReadStream(_decoderInStream, data, processedSize);; + return ReadStream(_decoderInStream, data, processedSize); } diff --git a/CPP/7zip/Archive/Nsis/NsisHandler.cpp b/CPP/7zip/Archive/Nsis/NsisHandler.cpp index aa0a9175..7a512b72 100644 --- a/CPP/7zip/Archive/Nsis/NsisHandler.cpp +++ b/CPP/7zip/Archive/Nsis/NsisHandler.cpp @@ -61,22 +61,19 @@ IMP_IInArchive_Props 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 @@ static AString GetMethod(bool useFilter, NMethodType::EEnum method, UInt32 dict) 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 @@ AString CHandler::GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt3 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 @@ AString CHandler::GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt3 } */ -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) if (!_archive.IsInstaller) { if (!s.IsEmpty()) - s += '.'; + s.Add_Dot(); s += "Uninstall"; } #endif @@ -190,7 +187,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPositi 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 @@ bool CHandler::GetUncompressedSize(unsigned index, UInt32 &size) const 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 @@ bool CHandler::GetCompressedSize(unsigned index, UInt32 &size) const } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } -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 @@ static bool UninstallerPatch(const Byte *p, size_t size, CByteBuffer &dest) } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!_archive.IsSolid) { - RINOK(_archive.SeekToNonSolidItem(index)); + RINOK(_archive.SeekToNonSolidItem(index)) } else { @@ -566,10 +568,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } - 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, realOutStream.Release(); RINOK(extractCallback->SetOperationResult(dataError ? NExtract::NOperationResult::kDataError : - NExtract::NOperationResult::kOK)); + NExtract::NOperationResult::kOK)) } return S_OK; COM_TRY_END diff --git a/CPP/7zip/Archive/Nsis/NsisHandler.h b/CPP/7zip/Archive/Nsis/NsisHandler.h index 1eb8b731..bb90bfe0 100644 --- a/CPP/7zip/Archive/Nsis/NsisHandler.h +++ b/CPP/7zip/Archive/Nsis/NsisHandler.h @@ -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 @@ class CHandler: 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 --git a/CPP/7zip/Archive/Nsis/NsisIn.cpp b/CPP/7zip/Archive/Nsis/NsisIn.cpp index 4e2d7a9d..05ebfd0b 100644 --- a/CPP/7zip/Archive/Nsis/NsisIn.cpp +++ b/CPP/7zip/Archive/Nsis/NsisIn.cpp @@ -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 unsigned kCmdSize = 4 + kNumCommandParams * 4; 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 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID) } 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 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID) { 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 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID) else { sz += 2; - UInt32 len = GetUi16Str_Len(sz); + const UInt32 len = GetUi16Str_Len(sz); lic.Size = len * 2; if (isRTF) { @@ -526,6 +525,26 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID) #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 @@ static const char * const kVarStrings[] = , "_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 @@ void CInArchive::AddParam_UInt(UInt32 value) #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 @@ void CInArchive::GetShellString(AString &s, unsigned index1, unsigned index2) } s += '$'; - if (index1 < ARRAY_SIZE(kShellStrings)) + if (index1 < Z7_ARRAY_SIZE(kShellStrings)) { const char *sz = kShellStrings[index1]; if (sz) @@ -747,7 +766,7 @@ void CInArchive::GetShellString(AString &s, unsigned index1, unsigned index2) return; } } - if (index2 < ARRAY_SIZE(kShellStrings)) + if (index2 < Z7_ARRAY_SIZE(kShellStrings)) { const char *sz = kShellStrings[index2]; if (sz) @@ -1151,7 +1170,7 @@ void CInArchive::ReadString2_Raw(UInt32 pos) 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 @@ void CInArchive::ReadString2(AString &s, UInt32 pos) { 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_Leave = (1 << 4); 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 @@ void CInArchive::Add_GotoVar(UInt32 param) { 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 bool NoLabels(const UInt32 *labels, UInt32 num) 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 @@ static const char * const k_MB_Buttons[] = , "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 @@ static const char * const k_MB_Flags[] = // , "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 @@ static const char * const k_Button_IDs[] = 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 @@ void CNsis_CtlColors::Parse(const Byte *p, bool is64) } // 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 @@ void CInArchive::Add_Color(UInt32 v) 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 const char * const kShowWindow_Commands[] = 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 @@ static void Add_ShowWindow_Cmd_2(AString &s, UInt32 cmd) 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 @@ void CInArchive::Add_TypeFromList(const char * const *table, unsigned tableSize, } } -#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 @@ enum 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 @@ void CSection::Parse(const Byte *p) 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 @@ bool CInArchive::PrintSectionBegin(const CSection §, unsigned index) { 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 @@ void CInArchive::MessageBox_MB_Part(UInt32 param) { 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 @@ void CInArchive::MessageBox_MB_Part(UInt32 param) 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 @@ void CInArchive::MessageBox_MB_Part(UInt32 param) 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 @@ AString CInArchive::GetFormatDescription() const if (BadCmd >= 0) { AddString(s, "BadCmd="); - UIntToString(s, BadCmd); + UIntToString(s, (UInt32)BadCmd); } return s; } @@ -2455,7 +2463,7 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p) 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 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p) { if (id == EW_RESERVEDOPCODE) { - BadCmd = id; + BadCmd = (int)id; continue; } } @@ -2474,23 +2482,23 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p) // 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 @@ Int32 CInArchive::GetVarIndex(UInt32 strPos) const 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 @@ static bool IsAbsolutePath(const char *s) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) } */ 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) #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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) altPathOk = AreTwoParamStringsEqual(altParam + additional, params[0]); } - - #ifdef NSIS_SCRIPT - AddParam(params[0]); /* @@ -3640,8 +3647,6 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) AddParam(params[3]); } - #endif - if (!altPathOk) { #ifdef NSIS_SCRIPT @@ -3649,9 +3654,11 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) #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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) case EW_WRITEREG: { - const char *s2 = 0; + const char *s2 = NULL; switch (params[4]) { case 1: s2 = "Str"; break; @@ -4642,20 +4659,42 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) 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 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) case EW_INSTTYPESET: { - int numQwParams = 0; + unsigned numQwParams = 0; const char *s2; if (params[3] == 0) { @@ -4952,7 +4995,18 @@ static int CompareItems(void *const *p1, void *const *p2, void *param) { 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 @@ static int CompareItems(void *const *p1, void *const *p2, void *param) 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 @@ static int CompareItems(void *const *p1, void *const *p2, void *param) 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 @@ HRESULT CInArchive::SortItems() 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 @@ HRESULT CInArchive::SortItems() 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 @@ HRESULT CInArchive::SortItems() 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 @@ HRESULT CInArchive::Parse() 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 @@ HRESULT CInArchive::Parse() 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 @@ HRESULT CInArchive::Parse() 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 @@ HRESULT CInArchive::Parse() } 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 @@ HRESULT CInArchive::Parse() #endif - RINOK(ReadEntries(bhEntries)); + RINOK(ReadEntries(bhEntries)) #ifdef NSIS_SCRIPT @@ -5747,14 +5809,14 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size) 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 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size) 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 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size) } { 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 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size) 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 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size) 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 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio { 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 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio 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 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio 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 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio // 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 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio } */ - 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 --git a/CPP/7zip/Archive/Nsis/NsisIn.h b/CPP/7zip/Archive/Nsis/NsisIn.h index 1d92e12f..bb8de629 100644 --- a/CPP/7zip/Archive/Nsis/NsisIn.h +++ b/CPP/7zip/Archive/Nsis/NsisIn.h @@ -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 CBlockHeader struct CItem { + bool IsEmptyFile; bool IsCompressed; bool Size_Defined; bool CompressedSize_Defined; @@ -77,7 +80,7 @@ struct CItem // bool UseFilter; UInt32 Attrib; - UInt32 Pos; + UInt32 Pos; // = 0, if (IsEmptyFile == true) UInt32 Size; UInt32 CompressedSize; UInt32 EstimatedSize; @@ -89,7 +92,10 @@ struct CItem 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 @@ class CInArchive HRESULT SeekTo(UInt64 pos) { - return _stream->Seek(pos, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(_stream, pos); } HRESULT SeekTo_DataStreamOffset() @@ -433,7 +439,7 @@ class CInArchive 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 --git a/CPP/7zip/Archive/Nsis/NsisRegister.cpp b/CPP/7zip/Archive/Nsis/NsisRegister.cpp index 7230c3c2..a5003817 100644 --- a/CPP/7zip/Archive/Nsis/NsisRegister.cpp +++ b/CPP/7zip/Archive/Nsis/NsisRegister.cpp @@ -10,7 +10,7 @@ namespace NArchive { namespace NNsis { REGISTER_ARC_I( - "Nsis", "nsis", 0, 0x9, + "Nsis", "nsis", NULL, 0x9, kSignature, 4, NArcInfoFlags::kFindSignature | diff --git a/CPP/7zip/Archive/Nsis/StdAfx.h b/CPP/7zip/Archive/Nsis/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Nsis/StdAfx.h +++ b/CPP/7zip/Archive/Nsis/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/NtfsHandler.cpp b/CPP/7zip/Archive/NtfsHandler.cpp index 7d0c6f78..c13e0cad 100644 --- a/CPP/7zip/Archive/NtfsHandler.cpp +++ b/CPP/7zip/Archive/NtfsHandler.cpp @@ -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 @@ bool CHeader::Parse(const Byte *p) 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 @@ struct CMftRef 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 @@ struct CFileNameAttr 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 @@ struct CSiAttr // 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 @@ struct CAttr } }; -#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 @@ static int CompareAttr(void *const *elem1, void *const *elem2, void *) 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 @@ bool CAttr::ParseExtents(CRecordVector &extents, UInt64 numClustersMax, } 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 UInt64 kEmptyTag = (UInt64)(Int64)-1; 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 @@ class CInStream: 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 @@ class CInStream: _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 @@ static size_t Lznt1Dec(Byte *dest, size_t outBufLim, size_t destLen, const Byte 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } UInt64 next = Extents[i + 1].Virt; if (next > virtBlock2End) @@ -870,30 +885,30 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio 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 @@ struct CDataRef 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 @@ struct CMftRec { 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 @@ struct CMftRec { 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 @@ struct CMftRec 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 @@ struct CMftRec 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 @@ void CMftRec::ParseDataNames() 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 @@ HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex, 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 @@ bool CMftRec::Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 r CObjectVector *attrs) { G32(p, Magic); - if (!IsFILE()) - return IsEmpty() || IsBAAD(); - + if (!Is_Magic_FILE()) + return Is_Magic_CanIgnore(); { UInt32 usaOffset; @@ -1228,7 +1271,7 @@ bool CMftRec::Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 r 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 @@ struct CDatabase 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 @@ HRESULT CDatabase::Open() */ { - 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() { 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() return S_FALSE; if (OpenCallback) { - RINOK(OpenCallback->SetTotal(&numFiles, &mftSize)); + RINOK(OpenCallback->SetTotal(&numFiles, &mftSize)) } ByteBuf.Alloc(kBufSize); @@ -1791,9 +1834,9 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() } 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() } 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 @@ HRESULT CDatabase::Open() FOR_VECTOR (di, rec.DataRefs) if (rec.DataAttrs[rec.DataRefs[di].Start].Name.IsEmpty()) { - indexOfUnnamedStream = di; + indexOfUnnamedStream = (int)di; break; } } @@ -1985,14 +2039,14 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() continue; } - numAltStreams++; + // numAltStreams++; ThereAreAltStreams = true; - item.DataIndex = di; + item.DataIndex = (int)di; Items.Add(item); } } @@ -2027,10 +2081,10 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() 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 @@ HRESULT CDatabase::Open() 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 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data 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 @@ static void NtfsTimeToProp(UInt64 t, NCOM::CPropVariant &prop) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { s.Add_Space(); s.Add_UInt32(vi.MajorVer); - s += '.'; + s.Add_Dot(); s.Add_UInt32(vi.MinorVer); } break; @@ -2461,7 +2510,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val { // 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !realOutStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -2745,13 +2794,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 --git a/CPP/7zip/Archive/PeHandler.cpp b/CPP/7zip/Archive/PeHandler.cpp index 34a38acf..9851ed35 100644 --- a/CPP/7zip/Archive/PeHandler.cpp +++ b/CPP/7zip/Archive/PeHandler.cpp @@ -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 @@ static HRESULT CalcCheckSum(ISequentialInStream *stream, UInt32 size, UInt32 exc 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 @@ struct COptHeader 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 @@ bool COptHeader::Parse(const Byte *p, UInt32 size) 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 @@ struct CSection 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 @@ struct CTextFile 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 @@ struct CTextFile } }; -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 @@ struct CStringKeyValue 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 @@ class CHandler: CUsedBitmap _usedRes; // bool _parseResources; bool _checksumError; + bool _sectionsError; bool IsOpt() const { return _header.OptHeaderSize != 0; } @@ -800,11 +802,6 @@ class CHandler: _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 @@ static void TimeToProp(UInt32 unixTime, NCOM::CPropVariant &prop) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) // 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 @@ void CHandler::AddLangPrefix(UString &s, UInt32 lang) const } } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::LoadDebugSections(IInStream *stream, bool &thereIsSection) 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 @@ bool CBitmapInfoHeader::Parse(const Byte *p, size_t size) 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 @@ static UInt32 SetBitmapHeader(Byte *dest, const Byte *src, UInt32 size) 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 @@ static UInt32 SetIconHeader(Byte *dest, const Byte *src, UInt32 size) 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 @@ static UInt32 SetIconHeader(Byte *dest, const Byte *src, UInt32 size) // 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(CTextFile &f, UInt32 ms, UInt32 ls) 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 @@ static int FindKey(CObjectVector &v, const char *key) { FOR_VECTOR (i, v) if (v[i].Key.IsEqualTo(key)) - return i; + return (int)i; return -1; } @@ -1642,7 +1661,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector> 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 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector= size) return -1; if (Get16(p + pos) == 0) - return pos; + return (int)pos; pos += 2; } } @@ -1793,10 +1812,10 @@ bool CVersionBlock::Parse(const Byte *p, UInt32 size) 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 @@ static bool ParseVersion(const Byte *p, UInt32 size, CTextFile &f, CObjectVector { 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi { 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi _usedRes.Alloc(fileSize); CRecordVector specItems; - RINOK(ReadTable(0, specItems)); + RINOK(ReadTable(0, specItems)) _oneLang = true; bool stringsOk = true; @@ -2062,7 +2081,7 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi 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 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi 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 @@ bool CHeader::ParseCoff(const Byte *p) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) } { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) _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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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. */ + 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) + if (i != 0) { - CSection &prev = _sections[i - 1]; - if (prev.Pa < sect.Pa && - prev.Pa + prev.PSize > sect.Pa && - sect.PSize > 0) + const CSection &prev = _sections[i - 1]; + if (prev.Pa < sect.Pa + && prev.Pa + prev.PSize > sect.Pa + && sect.PSize != 0 + && prev.PSize != 0) { - // printf("\n !!!! Section correction: %s\n ", prev.Name); - // fflush(stdout); - prev.PSize = sect.Pa - prev.Pa; + _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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ void CHandler::CloseResources() _versionKeys.Clear(); } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _checksumError = false; + _sectionsError = false; _mainSubfile = -1; _stream.Release(); @@ -2630,17 +2665,17 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 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( 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 @@ static bool FindValue(const CUInt32PCharPair *pairs, unsigned num, UInt32 value) 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 @@ struct CSection } }; -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 @@ class CHandler: 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 @@ static const CStatProp kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _totalSize = 0; _stream.Release(); @@ -3150,17 +3180,17 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail) static const Byte k_Signature[] = { 'V', 'Z' }; REGISTER_ARC_I( - "TE", "te", 0, 0xCF, + "TE", "te", NULL, 0xCF, k_Signature, 0, NArcInfoFlags::kPreArc, diff --git a/CPP/7zip/Archive/PpmdHandler.cpp b/CPP/7zip/Archive/PpmdHandler.cpp index 101bfd98..e5c2f9b3 100644 --- a/CPP/7zip/Archive/PpmdHandler.cpp +++ b/CPP/7zip/Archive/PpmdHandler.cpp @@ -33,13 +33,13 @@ struct CBuf { 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 @@ struct CItem 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 @@ HRESULT CItem::ReadHeader(ISequentialInStream *s, UInt32 &headerSize) 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 @@ class CHandler: 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 @@ void CHandler::GetVersion(NCOM::CPropVariant &prop) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN 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 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; _packSize_Defined = false; @@ -252,7 +250,7 @@ struct CPpmdCpp 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 @@ struct CPpmdCpp }; -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, // 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { lps->InSize = _packSize = inBuf.GetProcessed(); lps->OutSize = outSize; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) size_t i; int sym = 0; @@ -363,7 +361,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, _packSize_Defined = true; if (realOutStream) { - RINOK(WriteStream(realOutStream, outBuf.Buf, i)); + RINOK(WriteStream(realOutStream, outBuf.Buf, i)) } if (inBuf.Extra) @@ -380,7 +378,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } - RINOK(inBuf.Res); + RINOK(inBuf.Res) } realOutStream.Release(); @@ -391,7 +389,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 --git a/CPP/7zip/Archive/QcowHandler.cpp b/CPP/7zip/Archive/QcowHandler.cpp index 4a795eca..5a80daa4 100644 --- a/CPP/7zip/Archive/QcowHandler.cpp +++ b/CPP/7zip/Archive/QcowHandler.cpp @@ -28,9 +28,7 @@ using namespace NWindows; 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 @@ VA to PA maps: 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 @@ class CHandler: public CHandlerImg 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 @@ class CHandler: public CHandlerImg 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) // 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) || _bufOutStreamSpec->GetPos() != clusterSize) res = S_FALSE; - RINOK(res); + RINOK(res) _cacheCluster = cluster; continue; @@ -245,7 +241,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) /* 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _table.Free(); _dir.Free(); @@ -617,7 +613,7 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea } CMyComPtr streamTemp = this; - RINOK(InitAndSeek()); + RINOK(InitAndSeek()) *stream = streamTemp.Detach(); return S_OK; COM_TRY_END diff --git a/CPP/7zip/Archive/Rar/Rar5Handler.cpp b/CPP/7zip/Archive/Rar/Rar5Handler.cpp index 563695f8..87d11e78 100644 --- a/CPP/7zip/Archive/Rar/Rar5Handler.cpp +++ b/CPP/7zip/Archive/Rar/Rar5Handler.cpp @@ -45,9 +45,8 @@ namespace NRar5 { 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 @@ void CItem::PrintInfo(AString &s) const 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 @@ void CItem::PrintInfo(AString &s) const 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 @@ void CItem::PrintInfo(AString &s) const 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_Version(UInt64 &version) const 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 @@ bool CHash::Check(const CItem &item, NCrypto::NRar5::CDecoder *cryptoDecoderSpec } -class COutStreamWithHash: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + COutStreamWithHash + , ISequentialOutStream +) ISequentialOutStream *_stream; UInt64 _pos; UInt64 _size; @@ -495,8 +494,6 @@ class COutStreamWithHash: 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 @@ class COutStreamWithHash: }; -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 @@ class CInArchive 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 @@ class CInArchive 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 @@ bool CInArchive::ReadVar(UInt64 &val) 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 @@ HRESULT CInArchive::ReadBlockHeader(CHeader &h) 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 @@ HRESULT CInArchive::ReadBlockHeader(CHeader &h) 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit, 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit, _stream = stream; CHeader h; - RINOK(ReadBlockHeader(h)); + RINOK(ReadBlockHeader(h)) info.IsEncrypted = false; if (h.Type == NHeaderType::kArcEncrypt) @@ -843,9 +840,9 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit, } 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit, return S_FALSE; } - RINOK(ReadBlockHeader(h)); + RINOK(ReadBlockHeader(h)) } if (h.Type != NHeaderType::kArc) @@ -1052,16 +1049,16 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool 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 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool 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 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool return E_NOTIMPL; } - RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec)); + RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec)) if (!cryptoDecoderSpec->CalcKey_and_CheckPassword()) wrongPassword = True; @@ -1273,7 +1270,7 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS _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 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS 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 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS 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 @@ UInt64 CHandler::GetPackSize(unsigned refIndex) const 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _refs.Size(); return S_OK; @@ -1515,20 +1512,20 @@ static const Byte kRawProps[] = }; -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::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp } -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 @@ static void TimeRecordToProp(const CItem &item, unsigned stampIndex, NCOM::CProp } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ static int FindLink(const CHandler &handler, const CUIntVector &sorted, { 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 @@ HRESULT CHandler::Open2(IInStream *stream, 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 @@ HRESULT CHandler::Open2(IInStream *stream, } 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 @@ HRESULT CHandler::Open2(IInStream *stream, break; } - RINOK(inStream->Seek(arch.Position, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekSet(inStream, arch.Position)) { CInArchive::CHeader h; @@ -2168,11 +2163,11 @@ HRESULT CHandler::Open2(IInStream *stream, { // 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 @@ HRESULT CHandler::Open2(IInStream *stream, && 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 @@ HRESULT CHandler::Open2(IInStream *stream, { if (_acls.IsEmpty() || acl != _acls.Back()) _acls.Add(acl); - mainItem.ACL = _acls.Size() - 1; + mainItem.ACL = (int)_acls.Size() - 1; } } } @@ -2292,7 +2287,7 @@ HRESULT CHandler::Open2(IInStream *stream, if (item.IsNextForItem(prevItem)) { ref2.Last = _items.Size(); - prevItem.NextItem = ref2.Last; + prevItem.NextItem = (int)ref2.Last; needAdd = false; } } @@ -2302,9 +2297,9 @@ HRESULT CHandler::Open2(IInStream *stream, 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 @@ HRESULT CHandler::Open2(IInStream *stream, { 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 @@ HRESULT CHandler::Open2(IInStream *stream, } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { COM_TRY_BEGIN _missingVolName.Empty(); @@ -2380,10 +2375,10 @@ STDMETHODIMP CHandler::Close() } -class CVolsInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CVolsInStream + , ISequentialInStream +) UInt64 _rem; ISequentialInStream *_stream; const CObjectVector *_arcs; @@ -2394,22 +2389,19 @@ class CVolsInStream: 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 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ static int FindLinkBuf(CObjectVector &linkFiles, unsigned index) { 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 @@ static HRESULT CopyData_with_Progress(const Byte *data, size_t size, 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 @@ static HRESULT CopyData_with_Progress(const Byte *data, size_t size, } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (total != 0 || !isThereUndefinedSize) { - RINOK(extractCallback->SetTotal(total)); + RINOK(extractCallback->SetTotal(total)) } } @@ -2745,7 +2736,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, totalPacked += curPackSize; lps->InSize = totalPacked; lps->OutSize = totalUnpacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CMyComPtr realOutStream; @@ -2781,7 +2772,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (needCallback) { - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) } if (bufIndex >= 0) @@ -2889,7 +2880,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, NExtract::NOperationResult::kUnsupportedMethod: NExtract::NOperationResult::kOK; realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) continue; } @@ -2930,7 +2921,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (wrongPassword) { realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword)) continue; } @@ -2955,7 +2946,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, return result; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } { @@ -2973,7 +2964,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, IMPL_ISetCompressCodecsInfo REGISTER_ARC_I( - "Rar5", "rar r00", 0, 0xCC, + "Rar5", "rar r00", NULL, 0xCC, kMarker, 0, NArcInfoFlags::kFindSignature, @@ -2982,31 +2973,27 @@ REGISTER_ARC_I( }} -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 --git a/CPP/7zip/Archive/Rar/Rar5Handler.h b/CPP/7zip/Archive/Rar/Rar5Handler.h index 3b3b940a..72e1efcf 100644 --- a/CPP/7zip/Archive/Rar/Rar5Handler.h +++ b/CPP/7zip/Archive/Rar/Rar5Handler.h @@ -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 @@ struct CArc }; -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 @@ class CHandler: 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 --git a/CPP/7zip/Archive/Rar/RarHandler.cpp b/CPP/7zip/Archive/Rar/RarHandler.cpp index ecadf853..9157accb 100644 --- a/CPP/7zip/Archive/Rar/RarHandler.cpp +++ b/CPP/7zip/Archive/Rar/RarHandler.cpp @@ -44,9 +44,8 @@ using namespace NWindows; 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) { 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) 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 @@ static int ReadTime(const Byte *p, unsigned size, Byte mask, CRarTime &rarTime) 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 @@ bool CInArchive::ReadHeaderReal(const Byte *p, unsigned size, CItem &item) 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass 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 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass 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 @@ bool CHandler::IsSolid(unsigned refIndex) const 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ static void RarTimeToProp(const CRarTime &rarTime, NCOM::CPropVariant &prop) */ } -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 @@ HRESULT CHandler::Open2(IInStream *stream, 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 @@ HRESULT CHandler::Open2(IInStream *stream, 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 @@ HRESULT CHandler::Open2(IInStream *stream, // AddErrorMessage(errorMessageLoc); } - RINOK(result); + RINOK(result) if (!filled) { @@ -1169,11 +1165,11 @@ HRESULT CHandler::Open2(IInStream *stream, /* 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 @@ HRESULT CHandler::Open2(IInStream *stream, { UInt64 numFiles = _items.Size(); UInt64 numBytes = curBytes + item.Position; - RINOK(openCallback->SetCompleted(&numFiles, &numBytes)); + RINOK(openCallback->SetCompleted(&numFiles, &numBytes)) } } @@ -1260,9 +1256,9 @@ HRESULT CHandler::Open2(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { COM_TRY_BEGIN // _errorMessage.Empty(); @@ -1303,10 +1299,10 @@ struct CMethodItem }; -class CVolsInStream: - public ISequentialInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_1( + CVolsInStream + , ISequentialInStream +) UInt64 _rem; ISequentialInStream *_stream; const CObjectVector *_arcs; @@ -1317,10 +1313,6 @@ class CVolsInStream: 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 @@ class CVolsInStream: }; -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 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) // 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 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (importantTotalUnPacked != 0 || !isThereUndefinedSize) { - RINOK(extractCallback->SetTotal(importantTotalUnPacked)); + RINOK(extractCallback->SetTotal(importantTotalUnPacked)) } UInt64 currentImportantTotalUnPacked = 0; @@ -1494,7 +1488,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { lps->InSize = currentImportantTotalPacked; lps->OutSize = currentImportantTotalUnPacked; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) if (i >= importantIndexes.Size()) break; @@ -1528,14 +1522,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, else { outStream.Release(); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); + RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)) continue; } @@ -1621,14 +1615,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, CMyComPtr compressSetDecoderProperties; RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &compressSetDecoderProperties)); + &compressSetDecoderProperties)) Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0); if (solidStart) @@ -1736,14 +1730,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } - 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, else return result; } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1779,7 +1773,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, IMPL_ISetCompressCodecsInfo REGISTER_ARC_I( - "Rar", "rar r00", 0, 3, + "Rar", "rar r00", NULL, 3, kMarker, 0, NArcInfoFlags::kFindSignature, diff --git a/CPP/7zip/Archive/Rar/RarHandler.h b/CPP/7zip/Archive/Rar/RarHandler.h index a62b60cd..c4d8450b 100644 --- a/CPP/7zip/Archive/Rar/RarHandler.h +++ b/CPP/7zip/Archive/Rar/RarHandler.h @@ -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 @@ struct CRefItem 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 @@ class CHandler: 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 --git a/CPP/7zip/Archive/Rar/RarHeader.h b/CPP/7zip/Archive/Rar/RarHeader.h index 30c53ec9..031fea62 100644 --- a/CPP/7zip/Archive/Rar/RarHeader.h +++ b/CPP/7zip/Archive/Rar/RarHeader.h @@ -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 --git a/CPP/7zip/Archive/Rar/RarItem.h b/CPP/7zip/Archive/Rar/RarItem.h index 10e21c57..e1028ba4 100644 --- a/CPP/7zip/Archive/Rar/RarItem.h +++ b/CPP/7zip/Archive/Rar/RarItem.h @@ -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 --git a/CPP/7zip/Archive/Rar/RarVol.h b/CPP/7zip/Archive/Rar/RarVol.h index 2f5bbd37..9ee8e86c 100644 --- a/CPP/7zip/Archive/Rar/RarVol.h +++ b/CPP/7zip/Archive/Rar/RarVol.h @@ -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 @@ class CVolumeName UString _changed; UString _after; public: - CVolumeName(): _needChangeForNext(true) {}; + CVolumeName(): _needChangeForNext(true) {} bool InitName(const UString &name, bool newStyle = true) { @@ -52,7 +52,7 @@ class CVolumeName 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 @@ class CVolumeName _after.Empty(); _before = base; - _before += '.'; + _before.Add_Dot(); _changed = "r00"; _needChangeForNext = false; return true; diff --git a/CPP/7zip/Archive/Rar/StdAfx.h b/CPP/7zip/Archive/Rar/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Rar/StdAfx.h +++ b/CPP/7zip/Archive/Rar/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/RpmHandler.cpp b/CPP/7zip/Archive/RpmHandler.cpp index 366f8efb..e05ac26d 100644 --- a/CPP/7zip/Archive/RpmHandler.cpp +++ b/CPP/7zip/Archive/RpmHandler.cpp @@ -19,7 +19,7 @@ #include "HandlerCont.h" -// #define _SHOW_RPM_METADATA +// #define Z7_RPM_SHOW_METADATA using namespace NWindows; @@ -169,7 +169,7 @@ struct CEntry }; -#ifdef _SHOW_RPM_METADATA +#ifdef Z7_RPM_SHOW_METADATA struct CMetaFile { UInt32 Tag; @@ -178,8 +178,10 @@ struct CMetaFile }; #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 @@ class CHandler: public CHandlerCont CLead _lead; - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA AString _metadata; CRecordVector _metaFiles; #endif @@ -234,15 +236,12 @@ class CHandler: public CHandlerCont 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 @@ static const Byte kArcProps[] = kpidCpu, kpidHostOS, kpidCTime - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA , kpidComment #endif }; @@ -274,7 +273,7 @@ void CHandler::AddCPU(AString &s) const { 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 @@ AString CHandler::GetBaseName() const 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 @@ void CHandler::AddSubFileExtension(AString &res) const res += _format; else res += "cpio"; - res += '.'; + res.Add_Dot(); const char *s; @@ -344,7 +343,7 @@ void CHandler::AddSubFileExtension(AString &res) const 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) break; } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA // case kpidComment: SetStringProp(_metadata, prop); break; #endif @@ -399,7 +398,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val case kpidPath: { AString s (GetBaseName()); - s += '.'; + s.Add_Dot(); AddSubFileExtension(s); SetStringProp(s, prop); break; @@ -432,7 +431,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } */ } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA else { index--; @@ -467,7 +466,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) 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 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) 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 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) } else { - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA { _metadata.Add_UInt32(entry.Tag); _metadata += ": "; @@ -547,7 +546,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) case RPMTAG_PAYLOADCOMPRESSOR: _compressor = s; break; } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA _metadata += s; #endif } @@ -563,7 +562,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) _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 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) #endif } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA else if ( entry.Type == k_EntryType_STRING_ARRAY || @@ -628,7 +627,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader) #endif } - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA CMetaFile meta; meta.Offset = entry.Offset; meta.Tag = entry.Tag; @@ -656,7 +655,7 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) { { 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) 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 @@ HRESULT CHandler::Open2(ISequentialInStream *stream) } -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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _headersSize = 0; _payloadSize = 0; @@ -738,7 +737,7 @@ STDMETHODIMP CHandler::Close() _format.Empty(); _compressor.Empty(); - #ifdef _SHOW_RPM_METADATA + #ifdef Z7_RPM_SHOW_METADATA _metadata.Empty(); _metaFiles.Size(); #endif @@ -747,10 +746,10 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 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 --git a/CPP/7zip/Archive/SparseHandler.cpp b/CPP/7zip/Archive/SparseHandler.cpp index 47e3ed8d..ab76f32a 100644 --- a/CPP/7zip/Archive/SparseHandler.cpp +++ b/CPP/7zip/Archive/SparseHandler.cpp @@ -42,11 +42,11 @@ struct CHeader { // 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 @@ struct CHeader #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 @@ struct CChunk 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 @@ class CHandler: public CHandlerImg 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 @@ class CHandler: public CHandlerImg } // 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 @@ static const Byte kArcProps[] = 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { Chunks.Clear(); _isArc = false; @@ -388,7 +387,7 @@ STDMETHODIMP CHandler::Close() } -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 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &proces } -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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) } 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 --git a/CPP/7zip/Archive/SplitHandler.cpp b/CPP/7zip/Archive/SplitHandler.cpp index 6bddfb83..ae7ca036 100644 --- a/CPP/7zip/Archive/SplitHandler.cpp +++ b/CPP/7zip/Archive/SplitHandler.cpp @@ -9,6 +9,7 @@ #include "../Common/ProgressUtils.h" #include "../Common/RegisterArc.h" +#include "../Common/StreamUtils.h" #include "../Compress/CopyCoder.h" @@ -31,27 +32,22 @@ static const Byte kArcProps[] = 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 @@ struct CSeqName } }; + 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { /* 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) { const UInt64 numFiles = _streams.Size(); - RINOK(callback->SetCompleted(&numFiles, NULL)); + RINOK(callback->SetCompleted(&numFiles, NULL)) } for (;;) @@ -216,30 +213,20 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) } REGISTER_ARC_I_NO_SIG( - "Split", "001", 0, 0xEA, + "Split", "001", NULL, 0xEA, 0, 0, NULL) diff --git a/CPP/7zip/Archive/SquashfsHandler.cpp b/CPP/7zip/Archive/SquashfsHandler.cpp index b682c130..34e0e5d0 100644 --- a/CPP/7zip/Archive/SquashfsHandler.cpp +++ b/CPP/7zip/Archive/SquashfsHandler.cpp @@ -51,13 +51,13 @@ static UInt64 Get64b(const Byte *p, bool be) { return be ? GetBe64(p) : GetUi64( #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 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 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; @@ -837,11 +837,10 @@ struct CFrag UInt32 Size; }; -class CHandler: - public IInArchive, - public IInArchiveGetStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_CHandler_IInArchive_1( + IInArchiveGetStream +) CRecordVector _items; CRecordVector _nodes; CRecordVector _nodesPos; @@ -902,7 +901,7 @@ class CHandler: 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, @@ -915,8 +914,8 @@ class CHandler: 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(); @@ -925,13 +924,10 @@ class CHandler: 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); @@ -1053,7 +1049,7 @@ static HRESULT LzoDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *src } srcRem--; - back = (b >> 2) + (*src++ << 2); + back = (b >> 2) + ((UInt32)*src++ << 2); len = 2; if (mode == 4) { @@ -1095,8 +1091,8 @@ static HRESULT LzoDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *src 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; @@ -1161,16 +1157,16 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool 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; @@ -1186,7 +1182,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool _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; } @@ -1239,7 +1235,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool { if (_inputBuffer.Size() < inSize) _inputBuffer.Alloc(inSize); - RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize)); + RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize)) Byte *dest = outBuf; if (!outBuf) @@ -1253,7 +1249,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool if (method == kMethod_LZO) { - RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen)); + RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen)) } else if (method == kMethod_LZ4) { @@ -1267,7 +1263,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool if (_noPropsLZMA) { props[0] = 0x5D; - SetUi32(&props[1], _h.BlockSize); + SetUi32(&props[1], _h.BlockSize) } else { @@ -1328,7 +1324,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize) 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); @@ -1342,7 +1338,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize) if (isCompressed) { _limitedInStreamSpec->Init(size); - RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize)); + RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize)) } else { @@ -1350,7 +1346,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize) 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; @@ -1369,7 +1365,7 @@ HRESULT CHandler::ReadData(CData &data, UInt64 start, UInt64 end) 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) @@ -1379,7 +1375,7 @@ HRESULT CHandler::ReadData(CData &data, UInt64 start, UInt64 end) 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) @@ -1505,7 +1501,7 @@ HRESULT CHandler::OpenDir(int parent, UInt32 startBlock, UInt32 offset, unsigned UInt64 numFiles = _items.Size(); if ((numFiles & 0xFFFF) == 0) { - RINOK(_openCallback->SetCompleted(&numFiles, NULL)); + RINOK(_openCallback->SetCompleted(&numFiles, NULL)) } } @@ -1560,13 +1556,13 @@ HRESULT CHandler::OpenDir(int parent, UInt32 startBlock, UInt32 offset, unsigned } } - 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; @@ -1578,7 +1574,7 @@ HRESULT CHandler::ReadUids(UInt64 start, UInt32 num, CByteBuffer &ids) ids.Alloc(size); if (num == 0) return S_OK; - RINOK(Seek2(start)); + RINOK(Seek2(start)) return ReadStream_FALSE(_stream, ids, size); } @@ -1586,7 +1582,7 @@ HRESULT CHandler::Open2(IInStream *inStream) { { 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()) @@ -1621,15 +1617,15 @@ HRESULT CHandler::Open2(IInStream *inStream) 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))) @@ -1658,8 +1654,8 @@ HRESULT CHandler::Open2(IInStream *inStream) 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)) @@ -1704,12 +1700,12 @@ HRESULT CHandler::Open2(IInStream *inStream) 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 { @@ -1718,29 +1714,29 @@ HRESULT CHandler::Open2(IInStream *inStream) 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) @@ -1757,23 +1753,24 @@ HRESULT CHandler::Open2(IInStream *inStream) 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; @@ -1782,22 +1779,22 @@ AString CHandler::GetPath(int index) const 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 { @@ -1825,7 +1822,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _openCodePage = CP_UTF8; _sizeCalculated = 0; @@ -1841,8 +1838,8 @@ STDMETHODIMP CHandler::Close() _inodesData.Clear(); _dirs.Clear(); - // _uids.Free(); - // _gids.Free();; + _uids.Free(); + _gids.Free(); _cachedBlock.Free(); ClearCache(); @@ -1850,7 +1847,7 @@ STDMETHODIMP CHandler::Close() 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]; @@ -1859,7 +1856,7 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets) 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) { @@ -1867,7 +1864,7 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets) return true; } - UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h); + const UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h); if (fillOffsets) { @@ -1937,13 +1934,13 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets) } -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; @@ -1960,7 +1957,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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) { @@ -1978,7 +1975,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) res += "-LZMA"; res.Add_Space(); res.Add_UInt32(_h.Major); - res += '.'; + res.Add_Dot(); res.Add_UInt32(_h.Minor); prop = res; break; @@ -2020,7 +2017,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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; @@ -2084,40 +2081,29 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } 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; } /* @@ -2134,7 +2120,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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; }; @@ -2180,7 +2166,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) packBlockSize != _cachedPackBlockSize) { ClearCache(); - RINOK(Seek2(blockOffset)); + RINOK(Seek2(blockOffset)) _limitedInStreamSpec->Init(packBlockSize); if (compressed) @@ -2189,7 +2175,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) bool outBufWasWritten; UInt32 outBufWasWrittenSize; HRESULT res = Decompress(_outStream, _cachedBlock, &outBufWasWritten, &outBufWasWrittenSize, packBlockSize, _h.BlockSize); - RINOK(res); + RINOK(res) if (outBufWasWritten) _cachedUnpackBlockSize = outBufWasWrittenSize; else @@ -2199,7 +2185,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) { if (packBlockSize > _h.BlockSize) return S_FALSE; - RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize)); + RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize)) _cachedUnpackBlockSize = packBlockSize; } _cachedBlockStartPos = blockOffset; @@ -2212,11 +2198,11 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) 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) @@ -2245,21 +2231,21 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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(); @@ -2270,7 +2256,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, if (!testMode && !outStream) continue; - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) int res = NExtract::NOperationResult::kDataError; { @@ -2284,7 +2270,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } else { - RINOK(hres); + RINOK(hres) { hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); if (hres == S_OK) @@ -2298,13 +2284,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } else if (hres != S_FALSE) { - RINOK(hres); + RINOK(hres) } } } } - RINOK(extractCallback->SetOperationResult(res)); + RINOK(extractCallback->SetOperationResult(res)) } return S_OK; @@ -2312,7 +2298,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream)) { COM_TRY_BEGIN @@ -2372,7 +2358,7 @@ static const Byte k_Signature[] = { 4, 'q', 's', 'h', 's' }; REGISTER_ARC_I( - "SquashFS", "squashfs", 0, 0xD2, + "SquashFS", "squashfs", NULL, 0xD2, k_Signature, 0, NArcInfoFlags::kMultiSignature, diff --git a/CPP/7zip/Archive/StdAfx.h b/CPP/7zip/Archive/StdAfx.h index 1cbd7fea..80866550 100644 --- a/CPP/7zip/Archive/StdAfx.h +++ b/CPP/7zip/Archive/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/SwfHandler.cpp b/CPP/7zip/Archive/SwfHandler.cpp index a5ff1877..ab704b67 100644 --- a/CPP/7zip/Archive/SwfHandler.cpp +++ b/CPP/7zip/Archive/SwfHandler.cpp @@ -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 @@ struct CItem 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 @@ struct CItem } }; -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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) return S_OK; } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = 1; return S_OK; @@ -222,7 +222,7 @@ static void DicSizeToString(char *s, UInt32 val) { 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 @@ static void DicSizeToString(char *s, UInt32 val) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN 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 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; _packSizeDefined = false; @@ -302,31 +302,29 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } -#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 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size, */ 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 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size, 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 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size, 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ struct CTag 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 @@ static const Byte kProps[] = 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _tags.Size(); return S_OK; @@ -764,7 +756,7 @@ static const char * const g_TagDesc[92] = , "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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca 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 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca { 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 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca 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 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca 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 @@ HRESULT CHandler::OpenSeq2(ISequentialInStream *stream, IArchiveOpenCallback *ca 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 --git a/CPP/7zip/Archive/Tar/StdAfx.h b/CPP/7zip/Archive/Tar/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Tar/StdAfx.h +++ b/CPP/7zip/Archive/Tar/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/Tar/TarHandler.cpp b/CPP/7zip/Archive/Tar/TarHandler.cpp index bd04bd7d..d7fe1759 100644 --- a/CPP/7zip/Archive/Tar/TarHandler.cpp +++ b/CPP/7zip/Archive/Tar/TarHandler.cpp @@ -67,7 +67,7 @@ static const char *k_Characts_Prefix = "PREFIX"; 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { 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 @@ AString CEncodingCharacts::GetCharactsString() const 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) for (;;) { _arc.NumFiles = _items.Size(); - RINOK(_arc.ReadItem(item)); + RINOK(_arc.ReadItem(item)) if (!_arc.filled) break; @@ -245,7 +244,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) _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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) _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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 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 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; @@ -346,7 +346,7 @@ STDMETHODIMP CHandler::Close() 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 @@ HRESULT CHandler::SkipTo(UInt32 index) 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 @@ HRESULT CHandler::SkipTo(UInt32 index) { _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 @@ void CHandler::TarStringToUnicode(const AString &s, NWindows::NCOM::CPropVariant } +// CPaxTime is defined (NumDigits >= 0) static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop) { UInt64 v; @@ -418,7 +419,7 @@ static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop 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 @@ static void AddSpecBools(AString &s, const char *name, bool b1, bool b2) } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val return E_INVALIDARG; else { - RINOK(SkipTo(index)); + RINOK(SkipTo(index)) item = &_latestItem; } } @@ -665,8 +666,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val } -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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, skipMode = true; askMode = NExtract::NAskMode::kSkip; } - RINOK(extractCallback->PrepareOperation(askMode)); + RINOK(extractCallback->PrepareOperation(askMode)) outStreamSpec->SetStream(realOutStream); realOutStream.Release(); @@ -770,16 +771,16 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, _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 @@ class CSparseStream: 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 @@ class CSparseStream: }; -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 @@ STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos 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 @@ void CHandler::Init() } -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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR { // 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR } */ bool processed = false; - RINOK(_handlerTimeOptions.Parse(name, prop, processed)); + RINOK(_handlerTimeOptions.Parse(name, prop, processed)) if (processed) continue; return E_INVALIDARG; diff --git a/CPP/7zip/Archive/Tar/TarHandler.h b/CPP/7zip/Archive/Tar/TarHandler.h index 44a99809..451c2fdf 100644 --- a/CPP/7zip/Archive/Tar/TarHandler.h +++ b/CPP/7zip/Archive/Tar/TarHandler.h @@ -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 @@ class CHandler: 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 --git a/CPP/7zip/Archive/Tar/TarHandlerOut.cpp b/CPP/7zip/Archive/Tar/TarHandlerOut.cpp index 53255e4c..c93a86eb 100644 --- a/CPP/7zip/Archive/Tar/TarHandlerOut.cpp +++ b/CPP/7zip/Archive/Tar/TarHandlerOut.cpp @@ -20,7 +20,7 @@ using namespace NWindows; 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 @@ HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PROPID pro 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 @@ static HRESULT GetTime(UInt32 i, UInt32 pid, IArchiveUpdateCallback *callback, { 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 @@ static HRESULT GetDevice(IArchiveUpdateCallback *callback, UInt32 i, { 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 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i, 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 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i, } { 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 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i, -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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt /* // 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Archive/Tar/TarHeader.cpp b/CPP/7zip/Archive/Tar/TarHeader.cpp index f1efddb5..deae357e 100644 --- a/CPP/7zip/Archive/Tar/TarHeader.cpp +++ b/CPP/7zip/Archive/Tar/TarHeader.cpp @@ -20,7 +20,7 @@ namespace NFileHeader { // 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 --git a/CPP/7zip/Archive/Tar/TarHeader.h b/CPP/7zip/Archive/Tar/TarHeader.h index 1af30935..aeccd286 100644 --- a/CPP/7zip/Archive/Tar/TarHeader.h +++ b/CPP/7zip/Archive/Tar/TarHeader.h @@ -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 @@ namespace NFileHeader // 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 --git a/CPP/7zip/Archive/Tar/TarIn.cpp b/CPP/7zip/Archive/Tar/TarIn.cpp index 4fd8c5b1..90b6f843 100644 --- a/CPP/7zip/Archive/Tar/TarIn.cpp +++ b/CPP/7zip/Archive/Tar/TarIn.cpp @@ -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 @@ API_FUNC_IsArc IsArc_Tar(const Byte *p2, size_t size) 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 @@ API_FUNC_IsArc IsArc_Tar(const Byte *p2, size_t size) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) thereAreEmptyRecords = true; if (OpenCallback) { - RINOK(Progress(item, 0)); + RINOK(Progress(item, 0)) } } if (thereAreEmptyRecords) @@ -243,19 +243,19 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) */ // 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) if (OpenCallback) { - RINOK(Progress(item, 0)); + RINOK(Progress(item, 0)) } isExtended = (Byte)buf[21 * 24]; @@ -394,8 +394,8 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item) 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 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item, error = k_ErrorType_UnexpectedEnd; return res; } - RINOK(res); + RINOK(res) packSize -= size; @@ -492,7 +492,7 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item, 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 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item, { if (OpenCallback) { - RINOK(Progress(item, pos)); + RINOK(Progress(item, pos)) } unsigned size = kBufSize; @@ -590,8 +590,8 @@ static bool ParsePaxTime(const AString &src, CPaxTime &pt, bool &doubleTagError) 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 @@ static bool ParsePaxTime(const AString &src, CPaxTime &pt, bool &doubleTagError) 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 @@ bool CPaxInfo::ParsePax(const CTempBuffer &tb, bool isFile) 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 @@ HRESULT CArchive::ReadItem2(CItemEx &item) 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 @@ HRESULT CArchive::ReadItem2(CItemEx &item) */ 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 @@ HRESULT CArchive::ReadItem2(CItemEx &item) 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 @@ HRESULT CArchive::ReadItem2(CItemEx &item) } 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 @@ HRESULT CArchive::ReadItem(CItemEx &item) if (error != k_ErrorType_OK) _error = error; - RINOK(res); + RINOK(res) if (filled) { diff --git a/CPP/7zip/Archive/Tar/TarIn.h b/CPP/7zip/Archive/Tar/TarIn.h index e99599a4..8c690574 100644 --- a/CPP/7zip/Archive/Tar/TarIn.h +++ b/CPP/7zip/Archive/Tar/TarIn.h @@ -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 --git a/CPP/7zip/Archive/Tar/TarItem.h b/CPP/7zip/Archive/Tar/TarItem.h index 738618f2..2e12c9d3 100644 --- a/CPP/7zip/Archive/Tar/TarItem.h +++ b/CPP/7zip/Archive/Tar/TarItem.h @@ -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 @@ struct CItem { memcpy(Magic, posixMode ? NFileHeader::NMagic::k_Posix_ustar_00 : - NFileHeader::NMagic::k_GNU_ustar__, + NFileHeader::NMagic::k_GNU_ustar, 8); } @@ -172,7 +172,7 @@ struct CItem 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 @@ struct CItem 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 @@ struct CItem 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 --git a/CPP/7zip/Archive/Tar/TarOut.cpp b/CPP/7zip/Archive/Tar/TarOut.cpp index f73c625b..26d08559 100644 --- a/CPP/7zip/Archive/Tar/TarOut.cpp +++ b/CPP/7zip/Archive/Tar/TarOut.cpp @@ -60,7 +60,7 @@ static void WriteOctal_12(char *s, UInt64 val) } } -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 @@ static void WriteOctal_12_Signed(char *s, Int64 val) 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 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax 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 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax *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 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax if (!isPax && !Prefix.IsEmpty()) { - COPY_STRING_CHECK (cur, Prefix, kPrefixSize); + COPY_STRING_CHECK (cur, Prefix, kPrefixSize) } if (item.Is_Sparse()) @@ -194,7 +194,7 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax 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 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax 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 @@ static void AddPaxLine(AString &s, const char *name, const AString &val) 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 @@ static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt, 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 @@ static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt, 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 @@ HRESULT COutArchive::WriteHeader(const CItem &item) // 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 @@ HRESULT COutArchive::WriteHeader(const CItem &item) 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_AfterDataResidual(UInt64 dataSize) 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 @@ HRESULT COutArchive::WriteFinishHeader() for (unsigned i = 0; i < kNumFinishRecords; i++) { - RINOK(Write_Data(record, kRecordSize)); + RINOK(Write_Data(record, kRecordSize)) } return S_OK; } diff --git a/CPP/7zip/Archive/Tar/TarOut.h b/CPP/7zip/Archive/Tar/TarOut.h index 34af20ac..7b99c268 100644 --- a/CPP/7zip/Archive/Tar/TarOut.h +++ b/CPP/7zip/Archive/Tar/TarOut.h @@ -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 --git a/CPP/7zip/Archive/Tar/TarRegister.cpp b/CPP/7zip/Archive/Tar/TarRegister.cpp index a78c3766..709c1917 100644 --- a/CPP/7zip/Archive/Tar/TarRegister.cpp +++ b/CPP/7zip/Archive/Tar/TarRegister.cpp @@ -12,7 +12,7 @@ namespace NTar { 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 --git a/CPP/7zip/Archive/Tar/TarUpdate.cpp b/CPP/7zip/Archive/Tar/TarUpdate.cpp index caa0a822..0b348e9b 100644 --- a/CPP/7zip/Archive/Tar/TarUpdate.cpp +++ b/CPP/7zip/Archive/Tar/TarUpdate.cpp @@ -8,6 +8,7 @@ #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" +#include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" @@ -44,7 +45,7 @@ HRESULT Prop_To_PaxTime(const NWindows::NCOM::CPropVariant &prop, CPaxTime &pt) 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 @@ static HRESULT GetTime(IStreamGetProp *getProp, UInt32 pid, CPaxTime &pt) { 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 @@ static HRESULT GetUser(IStreamGetProp *getProp, 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 @@ static HRESULT GetUser(IStreamGetProp *getProp, } { 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 @@ static HRESULT GetDevice(IStreamGetProp *getProp, { 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, lps->Init(updateCallback, true); CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStreamLimited(streamSpec); + CMyComPtr inStreamLimited(streamSpec); streamSpec->SetStream(inStream); complexity = 0; @@ -208,10 +209,14 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, needWrite = false; else { - RINOK(res); + RINOK(res) if (!fileInStream) { @@ -295,9 +300,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, } 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, */ 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, { 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, } 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, // 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, { 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, } 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, // 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, complexity += item.PackSize; fileInStream.Release(); - RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } else { @@ -518,7 +524,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream, 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 --git a/CPP/7zip/Archive/Tar/TarUpdate.h b/CPP/7zip/Archive/Tar/TarUpdate.h index ca0976dd..f6c2e779 100644 --- a/CPP/7zip/Archive/Tar/TarUpdate.h +++ b/CPP/7zip/Archive/Tar/TarUpdate.h @@ -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 --git a/CPP/7zip/Archive/Udf/StdAfx.h b/CPP/7zip/Archive/Udf/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Udf/StdAfx.h +++ b/CPP/7zip/Archive/Udf/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/Udf/UdfHandler.cpp b/CPP/7zip/Archive/Udf/UdfHandler.cpp index 691199ea..ae6113f1 100644 --- a/CPP/7zip/Archive/Udf/UdfHandler.cpp +++ b/CPP/7zip/Archive/Udf/UdfHandler.cpp @@ -26,7 +26,7 @@ static void UdfTimeToFileTime(const CTime &t, NWindows::NCOM::CPropVariant &prop 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 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ HRESULT CProgressImp::SetCompleted() 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _inStream.Release(); _archive.Clear(); @@ -217,13 +217,13 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 --git a/CPP/7zip/Archive/Udf/UdfHandler.h b/CPP/7zip/Archive/Udf/UdfHandler.h index 462faeec..5426d064 100644 --- a/CPP/7zip/Archive/Udf/UdfHandler.h +++ b/CPP/7zip/Archive/Udf/UdfHandler.h @@ -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 @@ struct CRef2 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 --git a/CPP/7zip/Archive/Udf/UdfIn.cpp b/CPP/7zip/Archive/Udf/UdfIn.cpp index 70496e4e..13d84e05 100644 --- a/CPP/7zip/Archive/Udf/UdfIn.cpp +++ b/CPP/7zip/Archive/Udf/UdfIn.cpp @@ -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 @@ static const UInt64 kInlineExtentsSizeMax = (UInt64)1 << 33; #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 void MY_FAST_CALL Crc16GenerateTable(void) } } -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 @@ void CRegId::AddUdfVersionTo(UString &s) const char temp[16]; ConvertUInt32ToHex(major, temp); s += temp; - s += '.'; + s.Add_Dot(); ConvertUInt32ToHex8Digits(minor, temp); s += &temp[8 - 2]; } @@ -346,7 +346,7 @@ HRESULT CInArchive::Read(unsigned volIndex, unsigned partitionRef, UInt32 blockP 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 @@ HRESULT CInArchive::ReadFromFile(unsigned volIndex, const CItem &item, CByteBuff { 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 @@ void CItem::Parse(const Byte *p) // 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 @@ struct CFileId 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 @@ size_t CFileId::Parse(const Byte *p, size_t size) 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 @@ size_t CFileId::Parse(const Byte *p, size_t size) -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 @@ HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLon { 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 @@ HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLon // (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 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes 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 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes } } + if (isDir != item.IcbTag.IsDir()) + return S_FALSE; + if (item.IcbTag.IsDir()) { if (fsIndex < 0) @@ -646,7 +668,7 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes 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 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes 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 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes 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 @@ HRESULT CInArchive::FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int n { if ((_numRefs & 0xFFF) == 0) { - RINOK(_progress->SetCompleted()); + RINOK(_progress->SetCompleted()) } if (numRecurseAllowed-- == 0) return S_FALSE; @@ -712,12 +738,12 @@ HRESULT CInArchive::FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int n 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 @@ API_FUNC_IsArc IsArc_Udf(const Byte *p, size_t size) { 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 @@ HRESULT CInArchive::Open2() { 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() } } - RINOK(_progress->SetTotal(totalSize)); + RINOK(_progress->SetTotal(totalSize)) PRF(printf("\n Read files")); @@ -1143,12 +1190,12 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ HRESULT CInArchive::Open2() 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 @@ static const char * const g_OsIds_Unix[] = , "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 @@ static void AddOs_Class_Id(UString &s, const char *p) 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 @@ static void AddOs_Class_Id(UString &s, const char *p) 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 @@ UString CInArchive::GetComment() const 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 @@ UString CInArchive::GetItemPath(unsigned volIndex, unsigned fsIndex, unsigned re // 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 --git a/CPP/7zip/Archive/Udf/UdfIn.h b/CPP/7zip/Archive/Udf/UdfIn.h index d962e7db..9ccbf746 100644 --- a/CPP/7zip/Archive/Udf/UdfIn.h +++ b/CPP/7zip/Archive/Udf/UdfIn.h @@ -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 @@ struct CRegId { 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 @@ struct CIcbTag 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 CLogVol }; - -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 @@ class CInArchive 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 --git a/CPP/7zip/Archive/UefiHandler.cpp b/CPP/7zip/Archive/UefiHandler.cpp index 67fe795a..cd6fcbdf 100644 --- a/CPP/7zip/Archive/UefiHandler.cpp +++ b/CPP/7zip/Archive/UefiHandler.cpp @@ -171,14 +171,14 @@ enum 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 bool AreGuidsEq(const Byte *p1, const Byte *p2) 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 @@ static bool IsFfs(const Byte *p) { 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 @@ static bool ParseDepedencyExpression(const Byte *p, UInt32 size, AString &res) 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 @@ static bool ParseUtf16zString2(const Byte *p, UInt32 size, AString &res) 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 @@ PRF(public:) } }; -#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 @@ struct CItem 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 @@ AString CItem::GetName(int numChildsInParent) const 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 @@ struct CItem2 { 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 @@ class CHandler: 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 @@ class CHandler: 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 @@ static const Byte kArcProps[] = 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 @@ void CHandler::AddCommentString(const char *name, UInt32 pos) _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 @@ static void MyPrint(UInt32 posBase, UInt32 size, unsigned level, const char *nam -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::DecodeLzma(const Byte *data, size_t inputSize) } -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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p } 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p // 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p 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 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p { 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 @@ bool CVolFfsHeader::Parse(const Byte *p) 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 @@ HRESULT CHandler::ParseVolume( 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 @@ HRESULT CHandler::ParseVolume( } 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 @@ HRESULT CHandler::ParseVolume( 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 @@ static const char * const kRegionName[] = 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 @@ HRESULT CHandler::OpenCapsule(IInStream *stream) { 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::OpenCapsule(IInStream *stream) 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 @@ HRESULT CHandler::OpenFv(IInStream *stream, const UInt64 * /* maxCheckStartPosit 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 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, { 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 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, 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 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, 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 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, 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 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _totalBufsSize = 0; @@ -1761,17 +1762,17 @@ STDMETHODIMP CHandler::Close() 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ static const Byte k_Capsule_Signatures[] = REGISTER_ARC_I_CLS( CHandler(true), - "UEFIc", "scap", 0, 0xD0, + "UEFIc", "scap", NULL, 0xD0, k_Capsule_Signatures, 0, NArcInfoFlags::kMultiSignature | @@ -1880,7 +1881,7 @@ static const Byte k_FFS_Signatures[] = REGISTER_ARC_I_CLS( CHandler(false), - "UEFIf", "uefif", 0, 0xD1, + "UEFIf", "uefif", NULL, 0xD1, k_FFS_Signatures, kFfsGuidOffset, NArcInfoFlags::kMultiSignature | diff --git a/CPP/7zip/Archive/VdiHandler.cpp b/CPP/7zip/Archive/VdiHandler.cpp index 7641cdc9..a5a9332b 100644 --- a/CPP/7zip/Archive/VdiHandler.cpp +++ b/CPP/7zip/Archive/VdiHandler.cpp @@ -26,9 +26,7 @@ using namespace NWindows; 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 @@ static bool IsEmptyGuid(const Byte *data) -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { UInt32 _dataOffset; CByteBuffer _table; @@ -99,7 +97,7 @@ class CHandler: public CHandlerImg 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 @@ class CHandler: public CHandlerImg 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) offset += lowBits; if (offset != _posInArc) { - RINOK(Seek2(offset)); + RINOK(Seek2(offset)) } HRESULT res = Stream->Read(data, size, &size); _posInArc += size; @@ -189,7 +187,7 @@ static const Byte kArcProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac { 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac } _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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _table.Free(); _phySize = 0; @@ -416,14 +414,14 @@ STDMETHODIMP CHandler::Close() } -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 --git a/CPP/7zip/Archive/VhdHandler.cpp b/CPP/7zip/Archive/VhdHandler.cpp index 60bc3d30..e5bf997d 100644 --- a/CPP/7zip/Archive/VhdHandler.cpp +++ b/CPP/7zip/Archive/VhdHandler.cpp @@ -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 @@ struct CFooter 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 @@ bool CDynHeader::Parse(const Byte *p) 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 @@ class CHandler: public CHandlerImg _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 @@ class CHandler: public CHandlerImg 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 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size) 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 @@ HRESULT CHandler::Open3() // 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 @@ HRESULT CHandler::Open3() } 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 @@ HRESULT CHandler::Open3() _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 @@ HRESULT CHandler::Open3() _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 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) } 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) { 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) } 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 @@ static void StringToAString(char *dest, UInt32 val) { 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 @@ static void ConvertByteToHex(unsigned value, char *s) } } -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ HRESULT CHandler::Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback 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 @@ HRESULT CHandler::Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback 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 @@ void CHandler::CloseAtError() // _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::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN } -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 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea 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 --git a/CPP/7zip/Archive/VhdxHandler.cpp b/CPP/7zip/Archive/VhdxHandler.cpp index 0fc83ace..e3ddedd5 100644 --- a/CPP/7zip/Archive/VhdxHandler.cpp +++ b/CPP/7zip/Archive/VhdxHandler.cpp @@ -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 @@ EXTERN_C_BEGIN 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 @@ static void MY_FAST_CALL Crc32c_GenerateTable() } } -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 @@ EXTERN_C_END 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 @@ static int DecodeFrom2HexChars(const wchar_t *s) { 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 @@ struct CHeader if (!Guids[i].IsEqualTo(h.Guids[i])) return false; return true; - }; + } bool Parse(Byte *p); }; @@ -195,7 +205,7 @@ bool CHeader::Parse(Byte *p) 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 @@ bool CRegion::Parse(Byte *p) 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 @@ bool CMetaEntry::Parse(const Byte *p) if ((Flags1 & 3) != 0) // Reserved2 return false; return true; -}; +} struct CParentPair @@ -406,7 +416,7 @@ struct CMetaHeader { const CParentPair &pair = ParentPairs[i]; if (pair.Key.IsEqualTo(name)) - return i; + return (int)i; } return -1; } @@ -628,7 +638,7 @@ struct CBat -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { UInt64 _phySize; @@ -657,11 +667,11 @@ class CHandler: public CHandlerImg 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 @@ class CHandler: public CHandlerImg 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 @@ class CHandler: public CHandlerImg HRESULT CHandler::Seek2(UInt64 offset) { - return Stream->Seek(offset, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(Stream, offset); } @@ -833,8 +843,8 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &proces #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 @@ bool CHandler::CheckBat() 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 @@ HRESULT CHandler::Open3() const wchar_t c = Get16(p + i); if (c < 0x20 || c > 0x7F) break; - _Creator += c; + _creator += c; } } @@ -1178,8 +1188,8 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() { 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 @@ HRESULT CHandler::Open3() if (regions[i].Parse(temp)) { if (correctRegionIndex < 0) - correctRegionIndex = i; + correctRegionIndex = (int)i; } else { @@ -1281,8 +1291,8 @@ HRESULT CHandler::Open3() // 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 @@ HRESULT CHandler::Open3() 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 @@ HRESULT CHandler::Open3() { // 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 @@ HRESULT CHandler::Open3() // _posInArc = 0; // Reset_PosInArc(); - // RINOK(Stream->Seek(0, STREAM_SEEK_SET, NULL)); + // RINOK(InStream_SeekToBegin(Stream)) return S_OK; } @@ -1384,7 +1394,7 @@ static struct CCounter { ~CCounter() } } 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ void CHandler::AddComment(UString &s) const -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } case kpidCreatorApp: { - if (!_Creator.IsEmpty()) - prop = _Creator; + if (!_creator.IsEmpty()) + prop = _creator; break; } case kpidId: @@ -1808,7 +1818,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCall if (_level >= (1 << 20)) return S_FALSE; - RINOK(Open3()); + RINOK(Open3()) NumLevels = 1; PackSize_Total = GetPackSize(); @@ -1882,12 +1892,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCall 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 @@ HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_p 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 @@ HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_p { 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 @@ void CHandler::CloseAtError() 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 @@ void CHandler::CloseAtError() _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::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN } -STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) +Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)) { COM_TRY_BEGIN *stream = NULL; diff --git a/CPP/7zip/Archive/VmdkHandler.cpp b/CPP/7zip/Archive/VmdkHandler.cpp index 40f56131..0a6b9670 100644 --- a/CPP/7zip/Archive/VmdkHandler.cpp +++ b/CPP/7zip/Archive/VmdkHandler.cpp @@ -31,14 +31,12 @@ namespace NVmdk { #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 @@ struct CHeader 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 *SkipSpaces(const char *s) 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 *GetNextWord(const char *s, AString &dest) 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 @@ bool CExtentInfo::Parse(const char *s) if (Type.IsEmpty()) return false; - SKIP_SPACES(s); + SKIP_SPACES(s) if (IsType_ZERO()) return (*s == 0); @@ -243,7 +241,7 @@ bool CExtentInfo::Parse(const char *s) FileName.SetFrom(s, (unsigned)(s2 - s)); s = s2 + 1; } - SKIP_SPACES(s); + SKIP_SPACES(s) if (*s == 0) return true; @@ -298,7 +296,7 @@ bool CDescriptor::Parse(const Byte *p, size_t size) for (;;) { - char c = 0; + Byte c = 0; if (size != 0) { size--; @@ -369,7 +367,7 @@ struct CExtent 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 @@ struct CExtent 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 @@ struct CExtent }; -class CHandler: public CHandlerImg +Z7_class_CHandler_final: public CHandlerImg { bool _isArc; bool _unsupported; @@ -461,17 +459,17 @@ class CHandler: public CHandlerImg _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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) _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 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) res = S_FALSE; } - RINOK(res); + RINOK(res) _cacheCluster = cluster; _cacheExtent = extentIndex; @@ -718,7 +716,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 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 kProps[] = static const Byte kArcProps[] = { kpidNumVolumes, + kpidTotalPhySize, kpidMethod, kpidClusterSize, kpidHeadersSize, @@ -774,7 +773,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; @@ -794,6 +793,17 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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 @@ static int inline GetLog(UInt64 num) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) 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 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) stream = nextStream; headerSize = kSectoreSize; - RINOK(ReadStream(stream, buf, &headerSize)); + RINOK(ReadStream(stream, buf, &headerSize)) if (headerSize != kSectoreSize) continue; @@ -1176,7 +1186,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) _needDeflate = false; _clusterBitsMax = 0; - unsigned numOKs = 0; + // unsigned numOKs = 0; unsigned numUnsupported = 0; FOR_VECTOR (i, _extents) @@ -1186,7 +1196,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback) numUnsupported++; if (!e.IsOK) continue; - numOKs++; + // numOKs++; if (e.IsVmdk()) { if (e.NeedDeflate) @@ -1212,7 +1222,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, { // 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, } { - UInt64 overHeadBytes = h.overHead << 9; + const UInt64 overHeadBytes = h.overHead << 9; if (PhySize < overHeadBytes) PhySize = overHeadBytes; } @@ -1290,8 +1300,8 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, } } - 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, { 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, } 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 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback, } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; @@ -1458,10 +1468,10 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea FOR_VECTOR (i, _extents) { - RINOK(_extents[i].InitAndSeek()); + RINOK(_extents[i].InitAndSeek()) } CMyComPtr streamTemp = this; diff --git a/CPP/7zip/Archive/Wim/StdAfx.h b/CPP/7zip/Archive/Wim/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Wim/StdAfx.h +++ b/CPP/7zip/Archive/Wim/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/Wim/WimHandler.cpp b/CPP/7zip/Archive/Wim/WimHandler.cpp index 3b394557..7f96dcc8 100644 --- a/CPP/7zip/Archive/Wim/WimHandler.cpp +++ b/CPP/7zip/Archive/Wim/WimHandler.cpp @@ -95,7 +95,7 @@ static void AddErrorMessage(AString &s, const char *message) } -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) if (h.PartNumber != 1) { s.Add_UInt32(h.PartNumber); - s += '.'; + s.Add_Dot(); } s += "swm"; prop = s; @@ -267,7 +267,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) { 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ static void MethodToProp(int method, int chunksSizeBits, NCOM::CPropVariant &pro { 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 @@ static void MethodToProp(int method, int chunksSizeBits, NCOM::CPropVariant &pro } -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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::GetSecurity(UInt32 realIndex, const void **data, UInt32 *dataS 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 @@ static const Byte kRawProps[] = }; -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 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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 @@ class CVolumeName { 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 @@ class CVolumeName } }; -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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal } } - 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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal _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::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _firstVolumeIndex = -1; _phySize = 0; @@ -1019,11 +1019,11 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return S_OK; @@ -1164,7 +1164,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = _db.SortedItems.Size() + _numXmlItems + @@ -1180,7 +1180,7 @@ CHandler::CHandler() _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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR { // 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR { } 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 --git a/CPP/7zip/Archive/Wim/WimHandler.h b/CPP/7zip/Archive/Wim/WimHandler.h index 3ba88d2b..60bb156b 100644 --- a/CPP/7zip/Archive/Wim/WimHandler.h +++ b/CPP/7zip/Archive/Wim/WimHandler.h @@ -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 @@ namespace NWim { 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 @@ class CHandler: 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 @@ class CHandler: 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 --git a/CPP/7zip/Archive/Wim/WimHandlerOut.cpp b/CPP/7zip/Archive/Wim/WimHandlerOut.cpp index 5e8365a4..5d9dea25 100644 --- a/CPP/7zip/Archive/Wim/WimHandlerOut.cpp +++ b/CPP/7zip/Archive/Wim/WimHandlerOut.cpp @@ -27,8 +27,25 @@ using namespace NWindows; 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 @@ static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const By break; if (i == kHashSize) - return index; + return (int)index; if (h[i] < hash2[i]) right = mid; @@ -50,8 +67,8 @@ static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const By left = mid + 1; } - if (streamIndexForInsert >= 0) - sorted.Insert(left, streamIndexForInsert); + if (streamIndexForInsert != -1) + sorted.Insert(left, (unsigned)streamIndexForInsert); return -1; } @@ -78,13 +95,13 @@ struct CMetaItem 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 @@ struct CMetaItem 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 @@ static int AddToHardLinkList(const CObjectVector &metaItems, unsigned 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 @@ bool CDir::FindDir(const CObjectVector &items, const UString &name, u } -STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) +Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type)) { *type = NFileTimeType::kWindows; return S_OK; @@ -229,8 +253,8 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 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 @@ HRESULT CHandler::GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex { 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 @@ static HRESULT GetRootTime( 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 @@ static HRESULT GetRootTime( } if (arcRoot) { - RINOK(arcRoot->GetRootProp(propID, &prop)); + RINOK(arcRoot->GetRootProp(propID, &prop)) if (prop.vt == VT_FILETIME) { ft = prop.filetime; @@ -285,29 +309,29 @@ static HRESULT GetRootTime( 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 CHeader::WriteTo(Byte *p) const 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 @@ class CInStreamWithSha1: 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 @@ STDMETHODIMP CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedS 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 @@ static size_t WriteItem_Dummy(const CMetaItem &item) // 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 @@ static size_t WriteItem_Dummy(const CMetaItem &item) 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 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte 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 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte 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 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte } 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 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte 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 @@ void CDb::WriteTree(const CDir &tree, Byte *dest, size_t &pos) const 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 @@ void CDb::WriteTree(const CDir &tree, Byte *dest, size_t &pos) const 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 @@ void CDb::WriteOrderList(const CDir &tree) { 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 @@ void CHeader::SetDefaultFields(bool useLZX) 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 @@ static void AddTrees(CObjectVector &trees, CObjectVector &metaI -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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu // 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { if (!isRootImageDir) { - ui.MetaIndex = db.MetaItems.Size(); + ui.MetaIndex = (int)db.MetaItems.Size(); db.MetaItems.AddNew(); } @@ -1166,10 +1187,10 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu if (arcIndex >= 0) { - GetRawProp(arcIndex, kpidNtSecure, &data, &dataSize, &propType); + GetRawProp((UInt32)arcIndex, kpidNtSecure, &data, &dataSize, &propType); } else { @@ -1219,7 +1244,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu if (arcIndex >= 0) { - GetRawProp(arcIndex, kpidNtReparse, &data, &dataSize, &propType); + GetRawProp((UInt32)arcIndex, kpidNtReparse, &data, &dataSize, &propType); } else { @@ -1254,7 +1279,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu curItem->Dirs.InsertNew(indexOfDir).MetaIndex = ui.MetaIndex; } else - curItem->Files.Add(ui.MetaIndex); + curItem->Files.Add((unsigned)ui.MetaIndex); } } @@ -1272,7 +1297,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu complexity += rs.PackSize; } - RINOK(callback->SetTotal(complexity)); + RINOK(callback->SetTotal(complexity)) UInt64 totalComplexity = complexity; NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; @@ -1381,10 +1406,15 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu CMyComPtr inShaStream = inShaStreamSpec; CLimitedSequentialInStream *inStreamLimitedSpec = NULL; - CMyComPtr inStreamLimited; + CMyComPtr inStreamLimited; if (_volumes.Size() == 2) { inStreamLimitedSpec = new CLimitedSequentialInStream; @@ -1403,7 +1433,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } else { - RINOK(res); + RINOK(res) int miIndex = -1; @@ -1581,23 +1611,23 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu else { inShaStreamSpec->SetStream(fileInStream); + + CMyComPtr inSeekStream; + fileInStream.QueryInterface(IID_IInStream, (void **)&inSeekStream); + fileInStream.Release(); inShaStreamSpec->Init(); UInt64 offsetBlockSize = 0; @@ -1670,54 +1704,88 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } } */ + + // 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; - - streams.Add(s); + Byte hash[kHashSize]; + inShaStreamSpec->Final(hash); + + 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { Byte buf[kStreamInfoSize]; streams[i].WriteTo(buf); - RINOK(WriteStream(outStream, buf, kStreamInfoSize)); + RINOK(WriteStream(outStream, buf, kStreamInfoSize)) curPos += kStreamInfoSize; } @@ -1862,7 +1930,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu { 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 --git a/CPP/7zip/Archive/Wim/WimIn.cpp b/CPP/7zip/Archive/Wim/WimIn.cpp index f805521a..ff118d85 100644 --- a/CPP/7zip/Archive/Wim/WimIn.cpp +++ b/CPP/7zip/Archive/Wim/WimIn.cpp @@ -99,7 +99,7 @@ HRESULT CUnpacker::UnpackChunk( 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 @@ HRESULT CUnpacker::UnpackChunk( else { res = lzmsDecoder->Code(packBuf.Data, inSize, unpackBuf.Data, outSize); - unpackedSize = lzmsDecoder->GetUnpackSize();; + unpackedSize = lzmsDecoder->GetUnpackSize(); } } @@ -141,7 +141,7 @@ HRESULT CUnpacker::UnpackChunk( if (outStream) { - RINOK(WriteStream(outStream, unpackBuf.Data, outSize)); + RINOK(WriteStream(outStream, unpackBuf.Data, outSize)) } return res; @@ -168,7 +168,7 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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 @@ HRESULT CUnpacker::Unpack2( 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::GetItemName(unsigned index, NWindows::NCOM::CPropVariant &name) 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 @@ void CDatabase::GetItemPath(unsigned index1, bool showImageNumber, NWindows::NCO else if (needColon) s[0] = L':'; - index = index1; + index = (int)index1; wchar_t separator = 0; for (;;) @@ -597,7 +597,7 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent) 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 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent) 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 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent) 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 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent) 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 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent) if (item.IsDir && subdirOffset != 0) { - RINOK(ParseDirItem((size_t)subdirOffset, prevIndex)); + RINOK(ParseDirItem((size_t)subdirOffset, (int)prevIndex)) } } } @@ -864,7 +865,7 @@ HRESULT CDatabase::ParseImageDirs(CByteBuffer &buf, int parent) 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 @@ HRESULT CHeader::Parse(const Byte *p, UInt64 &phySize) 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 @@ const Byte kSignature[kSignatureSize] = { 'M', 'S', 'W', 'I', 'M', 0, 0, 0 }; 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 @@ static HRESULT ReadStreams(IInStream *inStream, const CHeader &h, CDatabase &db) 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 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems 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 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems 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 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems if (Items.IsEmpty()) Items.ClearAndReserve(numItemsReserve); - RINOK(ParseImageDirs(metadata, -1)); + RINOK(ParseImageDirs(metadata, -1)) if (needBootMetadata) { @@ -1166,12 +1167,12 @@ bool CDatabase::ItemHasStream(const CItem &item) const } -#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 @@ static int FindId(const CStreamInfo *streams, const CUIntVector &sorted, UInt32 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 @@ static int FindHash(const CStreamInfo *streams, const CUIntVector &sorted, const 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 @@ static int CompareItems(const unsigned *a1, const unsigned *a2, void *param) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) 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 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector &volumes) { CItem item; item.Offset = 0; - item.StreamIndex = i; + item.StreamIndex = (int)i; item.ImageIndex = -1; Items.Add(item); ThereAreDeletedStreams = true; @@ -1591,7 +1592,7 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber) if (NumExcludededItems != 0) { - ExludedItem = startItem; + ExludedItem = (int)startItem; startItem += NumExcludededItems; } @@ -1603,7 +1604,7 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber) 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 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber) 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 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector &volumes, 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 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector &volumes, 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 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector &volumes, 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 @@ bool CWimXml::Parse() return false; } - imageInfo.ItemIndexInXml = i; + imageInfo.ItemIndexInXml = (int)i; Images.Add(imageInfo); } diff --git a/CPP/7zip/Archive/Wim/WimIn.h b/CPP/7zip/Archive/Wim/WimIn.h index 9e835b01..3de84562 100644 --- a/CPP/7zip/Archive/Wim/WimIn.h +++ b/CPP/7zip/Archive/Wim/WimIn.h @@ -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 @@ struct CSolid UInt64 UnpackSize; int Method; - int ChunkSizeBits; + unsigned ChunkSizeBits; UInt64 HeadersSize; // size_t NumChunks; @@ -258,8 +258,8 @@ struct CHeader 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 @@ struct CHeader 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 @@ class CDatabase 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 --git a/CPP/7zip/Archive/XarHandler.cpp b/CPP/7zip/Archive/XarHandler.cpp index b5a1972d..c03128f3 100644 --- a/CPP/7zip/Archive/XarHandler.cpp +++ b/CPP/7zip/Archive/XarHandler.cpp @@ -103,11 +103,10 @@ struct CFile } }; -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 @@ class CHandler: 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 @@ static UInt64 ParseTime(const CXmlItem &item, const char *name) 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 int HexToByte(unsigned char c) 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 @@ static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest) 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 @@ static bool AddItem(const CXmlItem &item, CObjectVector &files, int paren { 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 @@ HRESULT CHandler::Open2(IInStream *stream) { 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ HRESULT CHandler::Open2(IInStream *stream) 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _phySize = 0; _inStream.Release(); @@ -412,7 +406,7 @@ STDMETHODIMP CHandler::Close() 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 @@ static void Utf8StringToProp(const AString &s, NCOM::CPropVariant &prop) } } -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val case kpidPath: { AString path; - int cur = index; - do + unsigned cur = index; + for (;;) { const CFile &item2 = _files[cur]; if (!path.IsEmpty()) @@ -496,9 +490,10 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { outStreamSha1Spec->Init(false); outStreamLimSpec->Init(_xmlLen); - RINOK(WriteStream(outStream, _xml, _xmlLen)); + RINOK(WriteStream(outStream, _xml, _xmlLen)) currentPackSize = currentUnpSize = _xmlLen; } else @@ -641,7 +636,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } 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 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 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 --git a/CPP/7zip/Archive/XzHandler.cpp b/CPP/7zip/Archive/XzHandler.cpp index d358ca56..976817c7 100644 --- a/CPP/7zip/Archive/XzHandler.cpp +++ b/CPP/7zip/Archive/XzHandler.cpp @@ -43,24 +43,39 @@ struct CBlockInfo }; -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 EXTRACT_ONLY - public CMultiMethodProps - #else - public CCommonMethodProps - #endif + #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 + 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 @@ class CHandler: AString _methodsString; - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY UInt32 _filterId; UInt64 _numSolidBytes; @@ -89,7 +104,7 @@ class CHandler: void InitXz() { _filterId = 0; - _numSolidBytes = XZ_PROPS__BLOCK_SIZE__AUTO; + _numSolidBytes = XZ_PROPS_BLOCK_SIZE_AUTO; } #endif @@ -97,7 +112,7 @@ class CHandler: void Init() { - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY InitXz(); CMultiMethodProps::Init(); #else @@ -114,7 +129,7 @@ class CHandler: ISequentialOutStream *outStream, ICompressProgressInfo *progress) { - #ifndef _7ZIP_ST + #ifndef Z7_ST decoder._numThreads = _numThreads; #endif decoder._memUsage = _memUsage_Decompress; @@ -140,25 +155,6 @@ class CHandler: } 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 @@ class CHandler: HRESULT SeekToPackPos(UInt64 pos) { - return _stream->Seek((Int64)pos, STREAM_SEEK_SET, NULL); + return InStream_SeekSet(_stream, pos); } }; @@ -181,7 +177,7 @@ CHandler::CHandler(): _blocks(NULL), _blocksArraySize(0) { - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY InitXz(); #endif } @@ -259,13 +255,14 @@ static const CMethodNamePair g_NamePairs[] = { 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 @@ static void AddMethodString(AString &s, const CXzFilter &f) 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 @@ static void AddCheckString(AString &s, const CXzs &xzs) } } -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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ struct COpenCallbackWrap 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 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal } } - 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 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal return E_OUTOFMEMORY; lookStream.realStream = &inStreamImp.vt; - LookToRead2_Init(&lookStream); + LookToRead2_INIT(&lookStream) COpenCallbackWrap openWrap; openWrap.Init(callback); @@ -660,7 +659,7 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal res = SZ_OK; } - RINOK(SRes_to_Open_HRESULT(res)); + RINOK(SRes_to_Open_HRESULT(res)) _stream = inStream; _seqStream = inStream; @@ -670,7 +669,7 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal -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 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal COM_TRY_END } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _seqStream = stream; @@ -689,7 +688,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { XzStatInfo_Clear(&_stat); XzStatInfo_Clear(&_stat2); @@ -738,12 +737,14 @@ CXzUnpackerCPP2::~CXzUnpackerCPP2() } -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 @@ class CInStream: 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 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu, ECoderStatus status; - SRes res = XzUnpacker_Code(&xzu.p, + const SRes res = XzUnpacker_Code(&xzu.p, // dest + outPos, NULL, &outLen, @@ -868,7 +864,7 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu, 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 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu, } -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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) _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::Read(void *data, UInt32 size, UInt32 *processedSize) } -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 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio 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 @@ static Int32 Get_Extract_OperationResult(const NCompress::NXz::CDecoder &decoder -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { if (!_stream) return E_FAIL; - RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(_stream)) } else _needSeekToStart = true; @@ -1085,9 +1081,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, -#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::GetFileTimeType(UInt32 *timeType) } -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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt /* { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value) if (name.IsEmpty()) return E_INVALIDARG; - #ifndef EXTRACT_ONLY + #ifndef Z7_EXTRACT_ONLY if (name[0] == L's') { @@ -1349,7 +1356,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value) } 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 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &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 @@ -1383,15 +1390,15 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR break; } } - if (k == ARRAY_SIZE(g_NamePairs)) + if (k == Z7_ARRAY_SIZE(g_NamePairs)) return E_INVALIDARG; } diff --git a/CPP/7zip/Archive/XzHandler.h b/CPP/7zip/Archive/XzHandler.h index 24e8eeb4..4d099548 100644 --- a/CPP/7zip/Archive/XzHandler.h +++ b/CPP/7zip/Archive/XzHandler.h @@ -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 --git a/CPP/7zip/Archive/ZHandler.cpp b/CPP/7zip/Archive/ZHandler.cpp index 29934367..18e712ac 100644 --- a/CPP/7zip/Archive/ZHandler.cpp +++ b/CPP/7zip/Archive/ZHandler.cpp @@ -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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN } /* -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 @@ API_FUNC_static_IsArc IsArc_Z(const Byte *p, size_t size) } } -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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _packSize = 0; // _unpackSize_Defined = false; @@ -164,8 +158,8 @@ STDMETHODIMP CHandler::Close() } -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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, opRes = NExtract::NOperationResult::kDataError; else { - RINOK(result); + RINOK(result) opRes = NExtract::NOperationResult::kOK; } } diff --git a/CPP/7zip/Archive/Zip/StdAfx.h b/CPP/7zip/Archive/Zip/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Archive/Zip/StdAfx.h +++ b/CPP/7zip/Archive/Zip/StdAfx.h @@ -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 --git a/CPP/7zip/Archive/Zip/ZipAddCommon.cpp b/CPP/7zip/Archive/Zip/ZipAddCommon.cpp index 0dde9639..8d8d7806 100644 --- a/CPP/7zip/Archive/Zip/ZipAddCommon.cpp +++ b/CPP/7zip/Archive/Zip/ZipAddCommon.cpp @@ -31,31 +31,22 @@ namespace NZip { using namespace NFileHeader; -static const UInt32 kLzmaPropsSize = 5; -static const UInt32 kLzmaHeaderSize = 4 + kLzmaPropsSize; - -class CLzmaEncoder: - public ICompressCoder, - public ICompressSetCoderProperties, - public ICompressSetCoderPropertiesOpt, - public CMyUnknownImp -{ +static const unsigned kLzmaPropsSize = 5; +static const unsigned kLzmaHeaderSize = 4 + kLzmaPropsSize; + +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) { @@ -65,8 +56,8 @@ STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPV 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; @@ -76,15 +67,15 @@ STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPV 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); } @@ -121,7 +112,7 @@ HRESULT CAddCommon::CalcStreamCRC(ISequentialInStream *inStream, UInt32 &resultC for (;;) { UInt32 processed; - RINOK(inStream->Read(_buf, kBufSize, &processed)); + RINOK(inStream->Read(_buf, kBufSize, &processed)) if (processed == 0) { resultCRC = CRC_GET_DIGEST(crc); @@ -149,9 +140,9 @@ HRESULT CAddCommon::Set_Pre_CompressionResult(bool inSeqMode, bool outSeqMode, U 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; @@ -161,7 +152,7 @@ HRESULT CAddCommon::Set_Pre_CompressionResult(bool inSeqMode, bool outSeqMode, U opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; opRes.DescriptorMode = outSeqMode; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; if (_options.IsAesMode) @@ -204,10 +195,11 @@ HRESULT CAddCommon::Compress( 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) { @@ -231,9 +223,11 @@ HRESULT CAddCommon::Compress( } 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; @@ -242,7 +236,7 @@ HRESULT CAddCommon::Compress( // 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; @@ -253,28 +247,27 @@ HRESULT CAddCommon::Compress( 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% @@ -283,7 +276,7 @@ HRESULT CAddCommon::Compress( bool needCode = true; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) { opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; @@ -300,9 +293,9 @@ HRESULT CAddCommon::Compress( { _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 { @@ -323,26 +316,26 @@ HRESULT CAddCommon::Compress( { 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; } } @@ -359,11 +352,11 @@ HRESULT CAddCommon::Compress( _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; } @@ -414,7 +407,7 @@ HRESULT CAddCommon::Compress( } RINOK(CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS - methodId, true, _compressEncoder)); + methodId, true, _compressEncoder)) if (!_compressEncoder) return E_NOTIMPL; @@ -436,7 +429,7 @@ HRESULT CAddCommon::Compress( COneMethodInfo *oneMethodMain = &_options._methods[0]; RINOK(oneMethodMain->SetCoderProps(setCoderProps, - _options._dataSizeReduceDefined ? &_options._dataSizeReduce : NULL)); + _options.DataSizeReduce_Defined ? &_options.DataSizeReduce : NULL)) } } } @@ -448,7 +441,7 @@ HRESULT CAddCommon::Compress( opRes.LzmaEos = _isLzmaEos; CMyComPtr outStreamNew; - if (_options.PasswordIsDefined) + if (_options.Password_Defined) outStreamNew = _cryptoStream; else outStreamNew = outStream; @@ -460,41 +453,45 @@ HRESULT CAddCommon::Compress( _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)) @@ -504,8 +501,6 @@ HRESULT CAddCommon::Compress( break; } - - opRes.Method = method; return S_OK; } diff --git a/CPP/7zip/Archive/Zip/ZipAddCommon.h b/CPP/7zip/Archive/Zip/ZipAddCommon.h index 0aa44adf..051915ce 100644 --- a/CPP/7zip/Archive/Zip/ZipAddCommon.h +++ b/CPP/7zip/Archive/Zip/ZipAddCommon.h @@ -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 @@ class CAddCommon MY_UNCOPYABLE 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 --git a/CPP/7zip/Archive/Zip/ZipCompressionMode.h b/CPP/7zip/Archive/Zip/ZipCompressionMode.h index 842991c4..89742615 100644 --- a/CPP/7zip/Archive/Zip/ZipCompressionMode.h +++ b/CPP/7zip/Archive/Zip/ZipCompressionMode.h @@ -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 CBaseProps: public CMultiMethodProps 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 --git a/CPP/7zip/Archive/Zip/ZipHandler.cpp b/CPP/7zip/Archive/Zip/ZipHandler.cpp index 547465e5..5f022cc3 100644 --- a/CPP/7zip/Archive/Zip/ZipHandler.cpp +++ b/CPP/7zip/Archive/Zip/ZipHandler.cpp @@ -19,7 +19,7 @@ #include "../../Compress/CopyCoder.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #ifndef SUPPORT_LZFSE #define SUPPORT_LZFSE #endif @@ -34,7 +34,6 @@ #include "../../Compress/PpmdZip.h" #include "../../Compress/ShrinkDecoder.h" #include "../../Compress/XzDecoder.h" -#include "../../Compress/ZstdDecoder.h" #include "../../Crypto/WzAes.h" #include "../../Crypto/ZipCrypto.h" @@ -93,12 +92,14 @@ const char * const kMethodNames1[kNumMethodNames1] = , "BZip2" , NULL , "LZMA" + /* , NULL , NULL , NULL , NULL , NULL - , "zstd-pk" + , "zstd-pk" // deprecated + */ }; @@ -130,6 +131,7 @@ static const CUInt32PCharPair g_HeaderCharacts[] = { { 0, "Encrypt" }, { 3, "Descriptor" }, + // { 4, "Enhanced" }, // { 5, "Patched" }, { 6, kMethod_StrongCrypto }, { 11, "UTF8" }, @@ -222,7 +224,7 @@ static AString BytesToString(const CByteBuffer &data) 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; @@ -344,7 +346,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) COM_TRY_END } -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = m_Items.Size(); return S_OK; @@ -378,7 +380,7 @@ static bool NtfsUnixTimeToProp(bool fromCentral, } -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; @@ -522,7 +524,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val if (extra.GetWzAes(aesField)) { m += kMethod_AES; - m += '-'; + m.Add_Minus(); m.Add_UInt32(((unsigned)aesField.Strength + 1) * 64); id = aesField.Method; isWzAes = true; @@ -538,7 +540,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ -630,7 +632,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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()) @@ -691,13 +693,13 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val /* -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; @@ -705,7 +707,7 @@ STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 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; @@ -721,7 +723,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp 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); @@ -768,13 +770,16 @@ void CHandler::MarkAltStreams(CObjectVector &items) } */ -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) { @@ -788,59 +793,24 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, COM_TRY_END } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { m_Items.Clear(); m_Archive.Close(); return S_OK; } -class CZstdDecoder: - public ICompressCoder, - public CMyUnknownImp -{ - NCompress::NZSTD::CDecoder *DecoderSpec; - CMyComPtr Decoder; -public: - CZstdDecoder(); - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - MY_UNKNOWN_IMP -}; - -CZstdDecoder::CZstdDecoder() -{ - DecoderSpec = new NCompress::NZSTD::CDecoder; - Decoder = DecoderSpec; -} -HRESULT CZstdDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - return Decoder->Code(inStream, outStream, NULL, outSize, progress); -} - - -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(); }; @@ -852,14 +822,14 @@ CLzmaDecoder::CLzmaDecoder() 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) { @@ -871,13 +841,13 @@ HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream * 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; @@ -915,11 +885,11 @@ class CZipDecoder 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( @@ -928,7 +898,7 @@ class CZipDecoder ISequentialOutStream *realOutStream, IArchiveExtractCallback *extractCallback, ICompressProgressInfo *compressProgress, - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads, UInt64 memUsage, #endif Int32 &res); @@ -946,7 +916,7 @@ static HRESULT SkipStreamData(ISequentialInStream *stream, for (;;) { size_t size = kBufSize; - RINOK(ReadStream(stream, buf, &size)); + RINOK(ReadStream(stream, buf, &size)) if (size == 0) return S_OK; thereAreData = true; @@ -954,25 +924,23 @@ static HRESULT SkipStreamData(ISequentialInStream *stream, 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(); } @@ -989,7 +957,7 @@ class COutStreamWithPadPKCS7: }; -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; @@ -1030,7 +998,7 @@ HRESULT CZipDecoder::Decode( ISequentialOutStream *realOutStream, IArchiveExtractCallback *extractCallback, ICompressProgressInfo *compressProgress, - #ifndef _7ZIP_ST + #ifndef Z7_ST UInt32 numThreads, UInt64 memUsage, #endif Int32 &res) @@ -1101,7 +1069,7 @@ HRESULT CZipDecoder::Decode( 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; @@ -1153,7 +1121,7 @@ HRESULT CZipDecoder::Decode( } CMyComPtr cryptoSetPassword; - RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)); + RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)) if (!cryptoSetPassword) return E_FAIL; @@ -1163,12 +1131,12 @@ HRESULT CZipDecoder::Decode( 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; @@ -1230,10 +1198,6 @@ HRESULT CZipDecoder::Decode( lzmaDecoderSpec = new CLzmaDecoder; mi.Coder = lzmaDecoderSpec; } - else if (id ==NFileHeader::NCompressionMethod::kZstd) - mi.Coder = new CZstdDecoder(); - else if (id ==NFileHeader::NCompressionMethod::kZstdPk) - mi.Coder = new CZstdDecoder(); else if (id == NFileHeader::NCompressionMethod::kXz) mi.Coder = new NCompress::NXz::CComDecoder; else if (id == NFileHeader::NCompressionMethod::kPPMd) @@ -1257,7 +1221,7 @@ HRESULT CZipDecoder::Decode( 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) { @@ -1272,13 +1236,13 @@ HRESULT CZipDecoder::Decode( 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) @@ -1287,7 +1251,7 @@ HRESULT CZipDecoder::Decode( coder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit); if (setMemLimit) { - RINOK(setMemLimit->SetMemLimit(memUsage)); + RINOK(setMemLimit->SetMemLimit(memUsage)) } } #endif @@ -1298,7 +1262,7 @@ HRESULT CZipDecoder::Decode( if (setDecoderProperties) { Byte properties = (Byte)item.Flags; - RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)); + RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)) } } @@ -1394,7 +1358,7 @@ HRESULT CZipDecoder::Decode( coder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); if (setFinishMode) { - RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))); + RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))) } const UInt64 coderPackSize = limitedStreamSpec->GetRem(); @@ -1452,12 +1416,12 @@ HRESULT CZipDecoder::Decode( { 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)); } @@ -1479,7 +1443,7 @@ HRESULT CZipDecoder::Decode( if (getInStreamProcessedSize && setFinishMode) { UInt64 processed; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); + RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)) if (processed != (UInt64)(Int64)-1) { if (pkAesMode) @@ -1505,7 +1469,7 @@ HRESULT CZipDecoder::Decode( UInt32 processedSize = 0; if (readInStream) { - RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize)); + RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize)) } if (processedSize > padSize) dataAfterEnd = true; @@ -1563,7 +1527,7 @@ HRESULT CZipDecoder::Decode( return S_OK; } - RINOK(result); + RINOK(result) } bool crcOK = true; @@ -1631,66 +1595,59 @@ HRESULT CZipDecoder::Decode( } -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) + for (i = 0;; i++, + lps->OutSize += cur_Unpacked, + lps->InSize += cur_Packed) { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); + 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; } @@ -1699,30 +1656,30 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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; } @@ -1730,19 +1687,19 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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) @@ -1751,9 +1708,6 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, RINOK(extractCallback->SetOperationResult(res)) } - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - return lps->SetCur(); COM_TRY_END } diff --git a/CPP/7zip/Archive/Zip/ZipHandler.h b/CPP/7zip/Archive/Zip/ZipHandler.h index d14979e3..a9d798dc 100644 --- a/CPP/7zip/Archive/Zip/ZipHandler.h +++ b/CPP/7zip/Archive/Zip/ZipHandler.h @@ -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 kMethodNames1[kNumMethodNames1]; 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 @@ class CHandler: 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 = true; + _force_SeqOutMode = false; + _force_OpenSeq = false; _forceCodePage = false; _specifiedCodePage = CP_OEMCP; } @@ -85,6 +84,9 @@ class CHandler: // void MarkAltStreams(CObjectVector &items); HRESULT GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value); + +public: + CHandler(); }; }} diff --git a/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp b/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp index 77a71df2..19699b5d 100644 --- a/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp +++ b/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp @@ -28,7 +28,7 @@ using namespace NTime; 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 @@ static HRESULT GetTime(IArchiveUpdateCallback *callback, unsigned index, PROPID { 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 @@ static HRESULT GetTime(IArchiveUpdateCallback *callback, unsigned index, PROPID } -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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } */ - 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt -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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 --git a/CPP/7zip/Archive/Zip/ZipHeader.h b/CPP/7zip/Archive/Zip/ZipHeader.h index 797aa73d..42b0e5c3 100644 --- a/CPP/7zip/Archive/Zip/ZipHeader.h +++ b/CPP/7zip/Archive/Zip/ZipHeader.h @@ -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 --git a/CPP/7zip/Archive/Zip/ZipIn.cpp b/CPP/7zip/Archive/Zip/ZipIn.cpp index f2b69a9c..4236df71 100644 --- a/CPP/7zip/Archive/Zip/ZipIn.cpp +++ b/CPP/7zip/Archive/Zip/ZipIn.cpp @@ -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 @@ HRESULT CInArchive::Seek_SavePos(UInt64 offset) 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 @@ HRESULT CInArchive::SeekToVol(int volIndex, UInt64 offset) 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 @@ API_FUNC_IsArc IsArc_Zip(const Byte *p, size_t size) { 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 @@ static UInt32 IsArc_Zip_2(const Byte *p, size_t size, bool isFinal) -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 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) 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 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) if ( marker == NSignature::kNoSpan || marker == NSignature::kSpan) { - RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)); + RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)) _signature = Get32(startBuf); } @@ -579,16 +652,12 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) 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 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) 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 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) if (!s.Stream) break; - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) InitBuf(); Vols.StreamIndex++; @@ -651,11 +721,15 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) 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 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit) { progressPrev = _cnt; // const UInt64 numFiles64 = 0; - RINOK(Callback->SetCompleted(NULL, &_cnt)); + RINOK(Callback->SetCompleted(NULL, &_cnt)) } } @@ -734,6 +808,8 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished) return S_OK; } + // cache is empty + if (!IsMultiVol) { _cnt += offset; @@ -767,7 +843,7 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished) _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 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished) return S_OK; } Stream = s2.Stream; - RINOK(Seek_SavePos(0)); + RINOK(Seek_SavePos(0)) } } @@ -847,7 +923,7 @@ HRESULT CInArchive::LookAhead(size_t minRequired) if (!s.Stream) return S_OK; - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) Vols.StreamIndex++; _streamPos = 0; @@ -957,7 +1033,7 @@ HRESULT CInArchive::Skip64(UInt64 num, unsigned numFiles) if (Callback) { const UInt64 numFiles64 = numFiles; - RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles64, &_cnt)) } } } @@ -1000,6 +1076,7 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo const UInt32 pair = ReadUInt32(); subBlock.ID = (pair & 0xFFFF); unsigned size = (unsigned)(pair >> 16); + // const unsigned origSize = size; extraSize -= 4; @@ -1068,13 +1145,15 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo } } + // 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 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo { 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 @@ static bool FlagsAreSame(const CItem &i1, const CItem &i2_cd) 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 @@ static bool AreItemsEqual(const CItemEx &localItem, const CItemEx &cdItem) } -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 @@ HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool } } - 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 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles) // size_t processedSize; CanStartNewVol = true; - RINOK(LookAhead(descriptorSize4)); + RINOK(LookAhead(descriptorSize4)) const size_t avail = GetAvail(); if (avail < descriptorSize4) @@ -1429,7 +1509,7 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles) // 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 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles) { progressPrev = _cnt; const UInt64 numFiles64 = numFiles; - RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles64, &_cnt)) } } } @@ -1501,7 +1581,7 @@ HRESULT CInArchive::CheckDescriptor(const CItemEx &item) // 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::CheckDescriptor(const CItemEx &item) } -HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) +HRESULT CInArchive::Read_LocalItem_After_CdItem_Full(CItemEx &item) { if (item.FromLocal) return S_OK; @@ -1556,7 +1636,7 @@ HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) { 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 @@ HRESULT CInArchive::ReadCdItem(CItemEx &item) } +/* +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 @@ HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo) } +/* 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 @@ HRESULT CInArchive::FindCd(bool checkOffsetMode) // 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 @@ HRESULT CInArchive::FindCd(bool checkOffsetMode) 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 @@ HRESULT CInArchive::TryReadCd(CObjectVector &items, const CCdInfo &cdIn // _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 @@ HRESULT CInArchive::TryReadCd(CObjectVector &items, const CCdInfo &cdIn CanStartNewVol = false; { CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); + RINOK(ReadCdItem(cdItem)) /* if (cdItem.Disk < _startLocalFromCd_Disk || @@ -1854,10 +1939,10 @@ HRESULT CInArchive::TryReadCd(CObjectVector &items, const CCdInfo &cdIn 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 @@ HRESULT CInArchive::ReadCd(CObjectVector &items, UInt32 &cdDisk, UInt64 if (!Vols.ecd_wasRead) { - RINOK(FindCd(checkOffsetMode)); + RINOK(FindCd(checkOffsetMode)) } CCdInfo &cdInfo = Vols.ecd; @@ -2004,7 +2089,7 @@ HRESULT CInArchive::ReadLocals(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadLocals(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadLocals(CObjectVector &items) { progressPrev = _cnt; const UInt64 numFiles = items.Size(); - RINOK(Callback->SetCompleted(&numFiles, &_cnt)); + RINOK(Callback->SetCompleted(&numFiles, &_cnt)) } } @@ -2072,7 +2157,7 @@ HRESULT CVols::ParseArcName(IArchiveOpenVolumeCallback *volCallback) 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 @@ HRESULT CInArchive::ReadVols2(IArchiveOpenVolumeCallback *volCallback, } } - 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 @@ HRESULT CInArchive::ReadVols() if (!volCallback) return S_OK; - RINOK(Vols.ParseArcName(volCallback)); + RINOK(Vols.ParseArcName(volCallback)) // const int startZIndex = Vols.StartVolIndex; @@ -2324,7 +2406,7 @@ HRESULT CInArchive::ReadVols() 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 @@ HRESULT CInArchive::ReadVols() { // 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 @@ HRESULT CInArchive::ReadVols() || !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 @@ HRESULT CInArchive::ReadVols() 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 @@ HRESULT CVols::Read(void *data, UInt32 size, UInt32 *processedSize) return S_FALSE; if (NeedSeek) { - RINOK(s.SeekToStart()); + RINOK(s.SeekToStart()) NeedSeek = false; } UInt32 realProcessedSize = 0; @@ -2444,7 +2526,7 @@ HRESULT CVols::Read(void *data, UInt32 size, UInt32 *processedSize) } } -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 @@ STDMETHODIMP CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) else if (res != S_FALSE) return res; } - else + else // (MarkerIsFound && MarkerIsSafe) { // _signature must be kLocalFileHeader or kEcd or kEcd64 @@ -2528,7 +2613,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) return S_FALSE; } - RINOK(Skip64(recordSize - kEcd64_MainSize, 0)); + RINOK(Skip64(recordSize - kEcd64_MainSize, 0)) } ReadSignature(); @@ -2568,7 +2653,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) } } } - } + } // (MarkerIsFound && MarkerIsSafe) +} // (!onlyLocalsMode) CObjectVector cdItems; @@ -2676,17 +2762,20 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) */ 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) { 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) cdInfo.ParseEcd64e(buf); } - RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size())); + RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size())) } @@ -2886,12 +2974,12 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::ReadHeaders(CObjectVector &items) 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, && (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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, 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 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, if (ArcInfo.IsSpanMode && !volWasRequested) { - RINOK(ReadVols()); + RINOK(ReadVols()) if (IsMultiVol && MarkerIsFound && ArcInfo.MarkerVolIndex < 0) ArcInfo.MarkerVolIndex = Vols.StartVolIndex; } @@ -3271,7 +3374,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, Stream = Vols.Streams[(unsigned)Vols.StartVolIndex].Stream; if (Stream) { - RINOK(Seek_SavePos(curPos)); + RINOK(Seek_SavePos(curPos)) } else IsMultiVol = false; @@ -3287,7 +3390,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit, Stream = StartStream; Vols.StreamIndex = -1; InitBuf(); - RINOK(Seek_SavePos(curPos)); + RINOK(Seek_SavePos(curPos)) } ArcInfo.MarkerVolIndex = -1; @@ -3356,7 +3459,7 @@ HRESULT CInArchive::GetItemStream(const CItemEx &item, bool seekPackData, CMyCom 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 @@ HRESULT CInArchive::GetItemStream(const CItemEx &item, bool seekPackData, CMyCom 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 --git a/CPP/7zip/Archive/Zip/ZipIn.h b/CPP/7zip/Archive/Zip/ZipIn.h index 1498afed..bea26dc9 100644 --- a/CPP/7zip/Archive/Zip/ZipIn.h +++ b/CPP/7zip/Archive/Zip/ZipIn.h @@ -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 @@ struct CVols 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 @@ struct CVols }; -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 @@ class CInArchive _cnt += skip; } + HRESULT AllocateBuffer(size_t size); + UInt64 GetVirtStreamPos() { return _streamPos - _bufCached + _bufPos; } bool _inBufMode; @@ -353,12 +352,19 @@ class CInArchive 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 @@ class CInArchive 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 --git a/CPP/7zip/Archive/Zip/ZipItem.cpp b/CPP/7zip/Archive/Zip/ZipItem.cpp index cffbb78a..a77643b3 100644 --- a/CPP/7zip/Archive/Zip/ZipItem.cpp +++ b/CPP/7zip/Archive/Zip/ZipItem.cpp @@ -45,7 +45,7 @@ static const CUInt32PCharPair g_ExtraTypes[] = 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 --git a/CPP/7zip/Archive/Zip/ZipItem.h b/CPP/7zip/Archive/Zip/ZipItem.h index 934d7ecf..4a25de3d 100644 --- a/CPP/7zip/Archive/Zip/ZipItem.h +++ b/CPP/7zip/Archive/Zip/ZipItem.h @@ -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 --git a/CPP/7zip/Archive/Zip/ZipOut.cpp b/CPP/7zip/Archive/Zip/ZipOut.cpp index 8f3f43bf..63f1a716 100644 --- a/CPP/7zip/Archive/Zip/ZipOut.cpp +++ b/CPP/7zip/Archive/Zip/ZipOut.cpp @@ -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 @@ void COutArchive::WriteCommonItemInfo(const CLocalItem &item, bool isZip64) } -#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 @@ void COutArchive::WriteLocalHeader(CItemOut &item, bool needCheck) 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::WriteLocalHeader_Replace(CItemOut &item) 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 @@ void COutArchive::WriteCentralHeader(const CItemOut &item) 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 @@ void COutArchive::WriteCentralHeader(const CItemOut &item) 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 @@ void COutArchive::WriteCentralHeader(const CItemOut &item) 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 @@ void COutArchive::WriteCentralDir(const CObjectVector &items, const CB 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 @@ void COutArchive::WriteCentralDir(const CObjectVector &items, const CB } 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 --git a/CPP/7zip/Archive/Zip/ZipOut.h b/CPP/7zip/Archive/Zip/ZipOut.h index a645d67f..e9b2abbc 100644 --- a/CPP/7zip/Archive/Zip/ZipOut.h +++ b/CPP/7zip/Archive/Zip/ZipOut.h @@ -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 @@ class COutArchive void SeekToCurPos(); public: + CMyComPtr SetRestriction; + + HRESULT ClearRestriction(); + HRESULT SetRestrictionFromCurrent(); HRESULT Create(IOutStream *outStream); UInt64 GetCurPos() const { return m_CurPos; } @@ -88,7 +92,7 @@ class COutArchive 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 --git a/CPP/7zip/Archive/Zip/ZipRegister.cpp b/CPP/7zip/Archive/Zip/ZipRegister.cpp index 3ad47153..c17a1a3d 100644 --- a/CPP/7zip/Archive/Zip/ZipRegister.cpp +++ b/CPP/7zip/Archive/Zip/ZipRegister.cpp @@ -17,7 +17,7 @@ static const Byte k_Signature[] = { 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 --git a/CPP/7zip/Archive/Zip/ZipUpdate.cpp b/CPP/7zip/Archive/Zip/ZipUpdate.cpp index 7f13071a..e6d881c9 100644 --- a/CPP/7zip/Archive/Zip/ZipUpdate.cpp +++ b/CPP/7zip/Archive/Zip/ZipUpdate.cpp @@ -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 @@ static void SetFileHeader( 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 @@ static void SetItemInfoFromCompressingResult(const CCompressingResult &compressi } -#ifndef _7ZIP_ST +#ifndef Z7_ST struct CMtSem { @@ -191,7 +201,7 @@ static THREAD_FUNC_DECL CoderThread(void *threadCoderInfo); struct CThreadInfo { - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL NWindows::CThread Thread; NWindows::NSynchronization::CAutoResetEvent CompressEvent; @@ -211,19 +221,24 @@ struct CThreadInfo 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 @@ void CThreadInfo::WaitAndCode() EXTERNAL_CODECS_LOC_VARS InStream, OutStream, InSeqMode, OutSeqMode, FileTime, ExpectedDataSize, + ExpectedDataSize_IsConfirmed, Progress, CompressingResult); if (Result == S_OK && Progress) @@ -313,7 +329,7 @@ class CMemRefs 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 CMemRefs } }; -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 @@ class CMtProgressMixer2: 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 @@ HRESULT CMtProgressMixer2::SetRatioInfo(unsigned index, const UInt64 *inSize, co 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 @@ HRESULT CMtProgressMixer2::SetRatioInfo(unsigned index, const UInt64 *inSize, co 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 @@ void CMtProgressMixer::Create(IProgress *progress, bool inSizeIsMain) 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 @@ static HRESULT UpdateItemOldData( UInt64 rangeSize; + RINOK(archive.ClearRestriction()) + if (ui.NewProps) { if (item.HasDescriptor()) @@ -456,7 +472,7 @@ static HRESULT UpdateItemOldData( 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 HRESULT UpdateItemOldData( } -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 @@ static void UpdatePropsFromStream( { 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 @@ static HRESULT Update2St( { lps->InSize = unpackSizeTotal; lps->OutSize = packSizeTotal; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) CUpdateItem &ui = updateItems[itemIndex]; CItemEx itemEx; CItemOut item; @@ -623,7 +659,7 @@ static HRESULT Update2St( // 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 @@ static HRESULT Update2St( bool isDir = ui.IsDir; if (isDir) { - WriteDirHeader(archive, options, ui, item); + RINOK(WriteDirHeader(archive, options, ui, item)) } else { @@ -644,10 +680,10 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2St( RINOK(compressor.Set_Pre_CompressionResult( inSeqMode, outSeqMode, ui.Size, - compressingResult)); + compressingResult)) SetFileHeader(*options, ui, compressingResult.DescriptorMode, item); @@ -675,6 +711,7 @@ static HRESULT Update2St( SetItemInfoFromCompressingResult(compressingResult, options->IsRealAesMode(), options->AesKeyMode, item); + RINOK(archive.SetRestrictionFromCurrent()) archive.WriteLocalHeader(item); CMyComPtr outStream; @@ -684,8 +721,9 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2St( 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 @@ static HRESULT Update2( bool unknownComplexity = false; UInt64 complexity = 0; + #ifndef Z7_ST UInt64 numFilesToCompress = 0; UInt64 numBytesToCompress = 0; + #endif unsigned i; @@ -769,8 +933,10 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( } - #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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( } 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 @@ static HRESULT Update2( } } // (oneMethodMain) - if (numThreads > numFilesToCompress) - numThreads = (UInt32)numFilesToCompress; + if (numThreads > numZipThreads_limit) + numThreads = numZipThreads_limit; if (numThreads <= 1) { mtMode = false; @@ -989,13 +1203,15 @@ static HRESULT Update2( ); - #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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( if (isDir) { - WriteDirHeader(archive, &options, ui, item); + RINOK(WriteDirHeader(archive, &options, ui, item)) } else { @@ -1206,12 +1418,21 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( SetItemInfoFromCompressingResult(compressingResult, options.IsRealAesMode(), options.AesKeyMode, item); // file Size can be 64-bit !!! + RINOK(archive.SetRestrictionFromCurrent()) archive.WriteLocalHeader(item); } @@ -1270,7 +1492,7 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( } 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 @@ static HRESULT Update2( 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 @@ static HRESULT Update2( #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 @@ class CCacheOutStream: 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 @@ bool CCacheOutStream::Allocate() 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 @@ HRESULT CCacheOutStream::MyWrite(size_t size) _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 @@ STDMETHODIMP CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP 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 @@ HRESULT Update( 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 @@ HRESULT Update( 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 --git a/CPP/7zip/Archive/Zip/ZipUpdate.h b/CPP/7zip/Archive/Zip/ZipUpdate.h index d1e35347..13ecd9cb 100644 --- a/CPP/7zip/Archive/Zip/ZipUpdate.h +++ b/CPP/7zip/Archive/Zip/ZipUpdate.h @@ -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 @@ struct CUpdateRange 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 @@ struct CUpdateItem bool Write_UnixTime; // bool Write_UnixTime_ATime; bool IsUtf8; + bool Size_WasSetFromStream; // bool IsAltStream; int IndexInArc; unsigned IndexInClient; @@ -57,6 +58,7 @@ struct CUpdateItem Write_UnixTime = false; IsUtf8 = false; + Size_WasSetFromStream = false; // IsAltStream = false; Time = 0; Size = 0; @@ -74,6 +76,7 @@ struct CUpdateItem Write_NtfsTime(false), Write_UnixTime(false), IsUtf8(false), + Size_WasSetFromStream(false), // IsAltStream(false), Time(0), Size(0) diff --git a/CPP/7zip/Archive/ZstdHandler.cpp b/CPP/7zip/Archive/ZstdHandler.cpp index dcdef408..d71d42e2 100644 --- a/CPP/7zip/Archive/ZstdHandler.cpp +++ b/CPP/7zip/Archive/ZstdHandler.cpp @@ -22,13 +22,11 @@ using namespace NWindows; namespace NArchive { namespace NZSTD { -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; @@ -45,19 +43,6 @@ class CHandler: 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[] = @@ -75,18 +60,18 @@ static const Byte kArcProps[] = IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID /*propID*/, PROPVARIANT * /*value*/)) { 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) @@ -132,7 +117,7 @@ API_FUNC_static_IsArc IsArc_zstd(const Byte *p, size_t size) } } -STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) +Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *)) { COM_TRY_BEGIN Close(); @@ -151,7 +136,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb } -STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) +Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream)) { Close(); _isArc = true; @@ -159,7 +144,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) return S_OK; } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { _isArc = false; _dataAfterEnd = false; @@ -175,8 +160,8 @@ STDMETHODIMP CHandler::Close() 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) @@ -296,14 +281,14 @@ static HRESULT UpdateArchive( return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); } -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 *updateCallback) +Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, + IArchiveUpdateCallback *updateCallback)) { COM_TRY_BEGIN @@ -364,7 +349,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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 --git a/CPP/7zip/Bundles/Alone/Alone.dsp b/CPP/7zip/Bundles/Alone/Alone.dsp index 406cb60d..df4451ed 100644 --- a/CPP/7zip/Bundles/Alone/Alone.dsp +++ b/CPP/7zip/Bundles/Alone/Alone.dsp @@ -44,7 +44,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\Common\MethodProps.h # 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 @@ -2315,6 +2323,10 @@ 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)" == "Alone - Win32 Release" @@ -3167,6 +3179,34 @@ SOURCE=..\..\..\..\C\Sort.h # 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 --git a/CPP/7zip/Bundles/Alone/StdAfx.h b/CPP/7zip/Bundles/Alone/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Alone/StdAfx.h +++ b/CPP/7zip/Bundles/Alone/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Alone/makefile b/CPP/7zip/Bundles/Alone/makefile index 87272dd9..b5f85ad2 100644 --- a/CPP/7zip/Bundles/Alone/makefile +++ b/CPP/7zip/Bundles/Alone/makefile @@ -63,6 +63,7 @@ WIN_OBJS = \ $O\MemBlocks.obj \ $O\MethodId.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\OffsetStream.obj \ $O\OutBuffer.obj \ $O\OutMemStream.obj \ @@ -217,6 +218,7 @@ C_OBJS = \ $O\Ppmd8Dec.obj \ $O\Ppmd8Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff --git a/CPP/7zip/Bundles/Alone/makefile.gcc b/CPP/7zip/Bundles/Alone/makefile.gcc index 20d6a86c..cb7e8281 100644 --- a/CPP/7zip/Bundles/Alone/makefile.gcc +++ b/CPP/7zip/Bundles/Alone/makefile.gcc @@ -24,7 +24,7 @@ endif ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -53,9 +53,9 @@ LOCAL_FLAGS_SYS = 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 @@ WIN_OBJS = \ $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 @@ C_OBJS = \ $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 @@ C_OBJS = \ $O/Sha1Opt.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff --git a/CPP/7zip/Bundles/Alone2/StdAfx.h b/CPP/7zip/Bundles/Alone2/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Alone2/StdAfx.h +++ b/CPP/7zip/Bundles/Alone2/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Alone2/makefile b/CPP/7zip/Bundles/Alone2/makefile index 357e78ee..4cb77185 100644 --- a/CPP/7zip/Bundles/Alone2/makefile +++ b/CPP/7zip/Bundles/Alone2/makefile @@ -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 @@ WIN_OBJS = $(WIN_OBJS) \ 7ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ $O\FilePathAutoRename.obj \ $O\FileStreams.obj \ + $O\MultiOutStream.obj \ !include "../../7zip.mak" diff --git a/CPP/7zip/Bundles/Alone2/makefile.gcc b/CPP/7zip/Bundles/Alone2/makefile.gcc index 49f9fd02..f767b0d1 100644 --- a/CPP/7zip/Bundles/Alone2/makefile.gcc +++ b/CPP/7zip/Bundles/Alone2/makefile.gcc @@ -4,7 +4,7 @@ PROG = 7zz # 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 @@ endif 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 @@ WIN_OBJS_2 = \ 7ZIP_COMMON_OBJS_2 = \ $O/FilePathAutoRename.o \ $O/FileStreams.o \ + $O/MultiOutStream.o \ OBJS = \ $(ARC_OBJS) \ diff --git a/CPP/7zip/Bundles/Alone7z/Alone.dsp b/CPP/7zip/Bundles/Alone7z/Alone.dsp index 217e6d68..ef4ec605 100644 --- a/CPP/7zip/Bundles/Alone7z/Alone.dsp +++ b/CPP/7zip/Bundles/Alone7z/Alone.dsp @@ -44,7 +44,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\Common\LzFindPrepare.cpp # 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 @@ SOURCE=..\..\..\Common\MyString.h # 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 @@ SOURCE=..\..\..\Windows\MemoryLock.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 @@ -550,10 +566,6 @@ SOURCE=..\..\..\Windows\Registry.h # 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 @@ SOURCE=..\..\Common\MethodProps.h # 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 @@ SOURCE=..\..\Compress\ByteSwap.cpp # 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 @@ SOURCE=..\..\UI\Common\EnumDirItems.h # 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 @@ SOURCE=..\..\ICoder.h # End Source File # Begin Source File -SOURCE=..\..\IMyUnknown.h +SOURCE=..\..\IDecl.h # End Source File # Begin Source File @@ -1473,6 +1493,10 @@ SOURCE=..\..\..\..\C\7zTypes.h # 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 @@ SOURCE=..\..\..\..\C\BraIA64.c # 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 @@ SOURCE=..\..\..\..\C\MtDec.h # 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 @@ SOURCE=..\..\..\..\C\Sha256Opt.c # 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 --git a/CPP/7zip/Bundles/Alone7z/StdAfx.h b/CPP/7zip/Bundles/Alone7z/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Alone7z/StdAfx.h +++ b/CPP/7zip/Bundles/Alone7z/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Alone7z/makefile b/CPP/7zip/Bundles/Alone7z/makefile index f87684c7..1f857c54 100644 --- a/CPP/7zip/Bundles/Alone7z/makefile +++ b/CPP/7zip/Bundles/Alone7z/makefile @@ -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 @@ WIN_OBJS = \ $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 @@ WIN_OBJS = \ $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 @@ C_OBJS = \ $O\MtCoder.obj \ $O\MtDec.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff --git a/CPP/7zip/Bundles/Alone7z/makefile.gcc b/CPP/7zip/Bundles/Alone7z/makefile.gcc index f11fcde0..6d92c19b 100644 --- a/CPP/7zip/Bundles/Alone7z/makefile.gcc +++ b/CPP/7zip/Bundles/Alone7z/makefile.gcc @@ -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 @@ MT_OBJS = ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -38,7 +38,6 @@ MT_OBJS = \ $O/LzFindMt.o \ $O/LzFindOpt.o \ $O/StreamBinder.o \ - $O/Synchronization.o \ $O/VirtThread.o \ $O/Threads.o \ @@ -53,9 +52,9 @@ LOCAL_FLAGS_SYS = 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 = \ $(LOCAL_FLAGS_ST) \ $(LOCAL_FLAGS_SYS) \ -# -D_LZMA_PROB32 - CONSOLE_OBJS = \ $O/BenchCon.o \ @@ -160,6 +157,7 @@ WIN_OBJS = \ $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 @@ C_OBJS = \ $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 @@ C_OBJS = \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff --git a/CPP/7zip/Bundles/Codec_flzma2/makefile b/CPP/7zip/Bundles/Codec_flzma2/makefile index 891003c6..8aaee2a4 100644 --- a/CPP/7zip/Bundles/Codec_flzma2/makefile +++ b/CPP/7zip/Bundles/Codec_flzma2/makefile @@ -14,6 +14,7 @@ COMPRESS_OBJS = \ $O\DllExportsCompress.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\CpuArch.obj \ $O\Threads.obj \ diff --git a/CPP/7zip/Bundles/Fm/FM.dsp b/CPP/7zip/Bundles/Fm/FM.dsp index 54efba98..402dd2c5 100644 --- a/CPP/7zip/Bundles/Fm/FM.dsp +++ b/CPP/7zip/Bundles/Fm/FM.dsp @@ -45,7 +45,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\Common\MethodProps.h # 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 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c # 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 @@ SOURCE=..\..\..\..\C\Alloc.h # 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 --git a/CPP/7zip/Bundles/Fm/StdAfx.h b/CPP/7zip/Bundles/Fm/StdAfx.h index 15fd136e..4f27255c 100644 --- a/CPP/7zip/Bundles/Fm/StdAfx.h +++ b/CPP/7zip/Bundles/Fm/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Fm/makefile b/CPP/7zip/Bundles/Fm/makefile index 33813e82..33b5320a 100644 --- a/CPP/7zip/Bundles/Fm/makefile +++ b/CPP/7zip/Bundles/Fm/makefile @@ -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 @@ WIN_CTRL_OBJS = \ 7ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ $O\FilePathAutoRename.obj \ $O\FileStreams.obj \ + $O\MultiOutStream.obj \ UI_COMMON_OBJS = \ $O\ArchiveExtractCallback.obj \ diff --git a/CPP/7zip/Bundles/Format7z/StdAfx.h b/CPP/7zip/Bundles/Format7z/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Format7z/StdAfx.h +++ b/CPP/7zip/Bundles/Format7z/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Format7z/makefile b/CPP/7zip/Bundles/Format7z/makefile index e0738a42..26b968ca 100644 --- a/CPP/7zip/Bundles/Format7z/makefile +++ b/CPP/7zip/Bundles/Format7z/makefile @@ -111,6 +111,7 @@ CRYPTO_OBJS = \ $O\RandGen.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bcj2Enc.obj \ @@ -134,6 +135,7 @@ C_OBJS = \ $O\Ppmd7Dec.obj \ $O\Ppmd7Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Aes.mak" diff --git a/CPP/7zip/Bundles/Format7zExtract/StdAfx.h b/CPP/7zip/Bundles/Format7zExtract/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Format7zExtract/StdAfx.h +++ b/CPP/7zip/Bundles/Format7zExtract/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Format7zExtract/makefile b/CPP/7zip/Bundles/Format7zExtract/makefile index 977fed64..08873cac 100644 --- a/CPP/7zip/Bundles/Format7zExtract/makefile +++ b/CPP/7zip/Bundles/Format7zExtract/makefile @@ -1,6 +1,6 @@ PROG = 7zxa.dll DEF_FILE = ../../Archive/Archive2.def -CFLAGS = $(CFLAGS) -DEXTRACT_ONLY \ +CFLAGS = $(CFLAGS) -DZ7_EXTRACT_ONLY COMMON_OBJS = \ $O\CRC.obj \ @@ -90,6 +90,7 @@ CRYPTO_OBJS = \ $O\MyAesReg.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ @@ -103,6 +104,7 @@ C_OBJS = \ $O\MtDec.obj \ $O\Ppmd7.obj \ $O\Ppmd7Dec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ COMPRESS_OBJS = $(COMPRESS_OBJS) \ diff --git a/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h b/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h +++ b/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Format7zExtractR/makefile b/CPP/7zip/Bundles/Format7zExtractR/makefile index 756c8ae6..50b84d87 100644 --- a/CPP/7zip/Bundles/Format7zExtractR/makefile +++ b/CPP/7zip/Bundles/Format7zExtractR/makefile @@ -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 @@ COMPRESS_OBJS = \ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ @@ -88,6 +89,7 @@ C_OBJS = \ $O\Lzma2DecMt.obj \ $O\LzmaDec.obj \ $O\MtDec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Crc.mak" diff --git a/CPP/7zip/Bundles/Format7zF/Arc.mak b/CPP/7zip/Bundles/Format7zF/Arc.mak index f66cfd55..d378a4a4 100644 --- a/CPP/7zip/Bundles/Format7zF/Arc.mak +++ b/CPP/7zip/Bundles/Format7zF/Arc.mak @@ -307,6 +307,7 @@ C_OBJS = \ $O\Ppmd8Dec.obj \ $O\Ppmd8Enc.obj \ $O\Sort.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ $O\Xz.obj \ $O\XzDec.obj \ diff --git a/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak b/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak index 1292dd8d..404d9172 100644 --- a/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak +++ b/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak @@ -14,7 +14,7 @@ endif ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -351,6 +351,7 @@ C_OBJS = \ $O/Sha256Opt.o \ $O/Sha1.o \ $O/Sha1Opt.o \ + $O/SwapBytes.o \ ARC_OBJS = \ $(LZMA_DEC_OPT_OBJS) \ @@ -358,6 +359,7 @@ ARC_OBJS = \ $(MT_OBJS) \ $(COMMON_OBJS) \ $(WIN_OBJS) \ + $(7ZIP_COMMON_OBJS) \ $(AR_OBJS) \ $(AR_COMMON_OBJS) \ $(7Z_OBJS) \ @@ -373,5 +375,5 @@ ARC_OBJS = \ $(ZIP_OBJS) \ $(COMPRESS_OBJS) \ $(CRYPTO_OBJS) \ - $(7ZIP_COMMON_OBJS) \ +# we need empty line after last line above diff --git a/CPP/7zip/Bundles/Format7zF/Format7z.dsp b/CPP/7zip/Bundles/Format7zF/Format7z.dsp index 0ed78be3..e35294f8 100644 --- a/CPP/7zip/Bundles/Format7zF/Format7z.dsp +++ b/CPP/7zip/Bundles/Format7zF/Format7z.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\..\Common\Common.h # 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 @@ 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\Aes.c !IF "$(CFG)" == "7z - Win32 Release" @@ -2214,7 +2226,23 @@ SOURCE=..\..\..\..\C\Sort.h # 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 @@ SOURCE=..\..\IStream.h # 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 @@ SOURCE=..\..\..\Windows\FileName.h # 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 --git a/CPP/7zip/Bundles/Format7zF/StdAfx.h b/CPP/7zip/Bundles/Format7zF/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Format7zF/StdAfx.h +++ b/CPP/7zip/Bundles/Format7zF/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Format7zF/makefile b/CPP/7zip/Bundles/Format7zF/makefile index 15497b97..a1bf77e1 100644 --- a/CPP/7zip/Bundles/Format7zF/makefile +++ b/CPP/7zip/Bundles/Format7zF/makefile @@ -1,9 +1,9 @@ PROG = 7z.dll DEF_FILE = ../../Archive/Archive2.def -CFLAGS = $(CFLAGS) -DEXTERNAL_CODECS -DZSTD_LEGACY_SUPPORT -DZSTD_MULTITHREAD +CFLAGS = $(CFLAGS) -DZ7_EXTERNAL_CODECS -DZSTD_LEGACY_SUPPORT -DZSTD_MULTITHREAD !IFNDEF UNDER_CE -CFLAGS = $(CFLAGS) -D_7ZIP_LARGE_PAGES +CFLAGS = $(CFLAGS) -DZ7_LARGE_PAGES !ENDIF !include "Arc.mak" diff --git a/CPP/7zip/Bundles/Format7zF/makefile.gcc b/CPP/7zip/Bundles/Format7zF/makefile.gcc index e468d7c3..fc657955 100644 --- a/CPP/7zip/Bundles/Format7zF/makefile.gcc +++ b/CPP/7zip/Bundles/Format7zF/makefile.gcc @@ -20,7 +20,7 @@ endif ifdef IS_MINGW LOCAL_FLAGS_WIN = \ - -D_7ZIP_LARGE_PAGES \ + -DZ7_LARGE_PAGES \ $(LOCAL_FLAGS_ST) \ SYS_OBJS = \ @@ -34,7 +34,7 @@ SYS_OBJS = \ endif LOCAL_FLAGS = \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ $(LOCAL_FLAGS_WIN) \ $(LOCAL_FLAGS_ST) \ diff --git a/CPP/7zip/Bundles/Format7zR/StdAfx.h b/CPP/7zip/Bundles/Format7zR/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/Format7zR/StdAfx.h +++ b/CPP/7zip/Bundles/Format7zR/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/Format7zR/makefile b/CPP/7zip/Bundles/Format7zR/makefile index c2237152..24497550 100644 --- a/CPP/7zip/Bundles/Format7zR/makefile +++ b/CPP/7zip/Bundles/Format7zR/makefile @@ -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 @@ COMPRESS_OBJS = \ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bcj2Enc.obj \ @@ -109,6 +110,7 @@ C_OBJS = \ $O\LzmaEnc.obj \ $O\MtCoder.obj \ $O\MtDec.obj \ + $O\SwapBytes.obj \ $O\Threads.obj \ !include "../../Crc.mak" diff --git a/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp b/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp index 71436f65..ac1334f4 100644 --- a/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp +++ b/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp @@ -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 @@ static void PrintHelp() 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 @@ void CProgressPrint::ClosePrint() 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 @@ STDMETHODIMP CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *ou } -MY_ATTR_NORETURN +Z7_ATTR_NORETURN static void IncorrectCommand() { throw "Incorrect command"; @@ -316,7 +314,7 @@ static int Error_HRESULT(const char *s, HRESULT res) else { char temp[32]; - ConvertUInt32ToHex(res, temp); + ConvertUInt32ToHex((UInt32)res, temp); PrintErr("Error code = 0x"); PrintErr_LF(temp); } @@ -357,7 +355,7 @@ static int main2(int numArgs, const char *args[]) 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 @@ static int main2(int numArgs, const char *args[]) UInt32 numThreads = (UInt32)(Int32)-1; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (parser[NKey::kMultiThread].ThereIs) { @@ -676,7 +674,7 @@ static int main2(int numArgs, const char *args[]) 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 @@ static int main2(int numArgs, const char *args[]) 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 @@ static int main2(int numArgs, const char *args[]) return 0; } -int MY_CDECL main(int numArgs, const char *args[]) +int Z7_CDECL main(int numArgs, const char *args[]) { NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter; diff --git a/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp b/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp index d7326efc..5a8911b2 100644 --- a/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp +++ b/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp @@ -132,6 +132,10 @@ SOURCE=..\..\..\Windows\FileIO.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 @@ -148,14 +152,6 @@ SOURCE=..\..\..\Windows\Registry.h # 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 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\Common\LzFindPrepare.cpp # 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 @@ SOURCE=..\..\..\Common\MyString.h # 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\StringToInt.h 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.cpp 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 @@ SOURCE=..\..\..\..\C\7zTypes.h # 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 @@ SOURCE=..\..\..\..\C\Bra86.c # 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.c 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 --git a/CPP/7zip/Bundles/LzmaCon/StdAfx.h b/CPP/7zip/Bundles/LzmaCon/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/LzmaCon/StdAfx.h +++ b/CPP/7zip/Bundles/LzmaCon/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/LzmaCon/makefile b/CPP/7zip/Bundles/LzmaCon/makefile index 5e53327a..f303c31f 100644 --- a/CPP/7zip/Bundles/LzmaCon/makefile +++ b/CPP/7zip/Bundles/LzmaCon/makefile @@ -1,6 +1,9 @@ PROG = lzma.exe MY_CONSOLE = 1 +# CFLAGS = $(CFLAGS) -DZ7_ST + + CURRENT_OBJS = \ $O\LzmaAlone.obj \ @@ -20,6 +23,7 @@ COMMON_OBJS = \ $O\NewHandler.obj \ $O\StringConvert.obj \ $O\StringToInt.obj \ + $O\Wildcard.obj \ WIN_OBJS = \ $O\FileIO.obj \ diff --git a/CPP/7zip/Bundles/LzmaCon/makefile.gcc b/CPP/7zip/Bundles/LzmaCon/makefile.gcc index e45ebb68..dd19a0e6 100644 --- a/CPP/7zip/Bundles/LzmaCon/makefile.gcc +++ b/CPP/7zip/Bundles/LzmaCon/makefile.gcc @@ -21,7 +21,7 @@ endif ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST else @@ -72,6 +72,7 @@ COMMON_OBJS = \ $O/StringConvert.o \ $O/StringToInt.o \ $O/UTFConvert.o \ + $O/Wildcard.o \ WIN_OBJS = \ $O/FileIO.o \ @@ -110,7 +111,7 @@ C_OBJS = \ $O/Lzma86Enc.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff --git a/CPP/7zip/Bundles/SFXCon/SFXCon.dsp b/CPP/7zip/Bundles/SFXCon/SFXCon.dsp index 87e27c4f..1bb063db 100644 --- a/CPP/7zip/Bundles/SFXCon/SFXCon.dsp +++ b/CPP/7zip/Bundles/SFXCon/SFXCon.dsp @@ -42,7 +42,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp # 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 @@ SOURCE=..\..\Compress\BcjCoder.cpp # 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 @@ SOURCE=..\..\Compress\CopyCoder.cpp # 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 @@ SOURCE=..\..\Compress\LzmaDecoder.cpp # 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 @@ SOURCE=..\..\Compress\PpmdDecoder.cpp # 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 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\Common\IntToString.h # 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 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c # 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 @@ SOURCE=..\..\..\..\C\BraIA64.c # 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 @@ SOURCE=..\..\..\..\C\Delta.h # 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.c 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 --git a/CPP/7zip/Bundles/SFXCon/SfxCon.cpp b/CPP/7zip/Bundles/SFXCon/SfxCon.cpp index cfa1ee7c..cfce24d9 100644 --- a/CPP/7zip/Bundles/SFXCon/SfxCon.cpp +++ b/CPP/7zip/Bundles/SFXCon/SfxCon.cpp @@ -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 NDir; 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 @@ static void PrintHelp(void) 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 @@ int Main2( } } - 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 @@ int Main2( CCodecs *codecs = new CCodecs; CMyComPtr< - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS ICompressCodecsInfo #else IUnknown @@ -421,7 +424,7 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( wildcardCensorHead, true, // enableHeaders false, // techMode - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO passwordEnabled, password, #endif numErrors, numWarnings); diff --git a/CPP/7zip/Bundles/SFXCon/StdAfx.h b/CPP/7zip/Bundles/SFXCon/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/Bundles/SFXCon/StdAfx.h +++ b/CPP/7zip/Bundles/SFXCon/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/SFXCon/makefile b/CPP/7zip/Bundles/SFXCon/makefile index 41911462..36bb5253 100644 --- a/CPP/7zip/Bundles/SFXCon/makefile +++ b/CPP/7zip/Bundles/SFXCon/makefile @@ -3,9 +3,9 @@ MY_CONSOLE = 1 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 @@ CRYPTO_OBJS = \ $O\MyAes.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff --git a/CPP/7zip/Bundles/SFXCon/makefile.gcc b/CPP/7zip/Bundles/SFXCon/makefile.gcc index 551b3e17..9278502d 100644 --- a/CPP/7zip/Bundles/SFXCon/makefile.gcc +++ b/CPP/7zip/Bundles/SFXCon/makefile.gcc @@ -22,7 +22,7 @@ endif ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -63,9 +63,9 @@ endif 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 @@ CRYPTO_OBJS = \ $O/MyAes.o \ C_OBJS = \ + $O/7zStream.o \ $O/Alloc.o \ $O/Bcj2.o \ $O/Bra.o \ @@ -179,7 +180,6 @@ C_OBJS = \ $O/BraIA64.o \ $O/CpuArch.o \ $O/Delta.o \ - \ $O/Lzma2Dec.o \ $O/Lzma2DecMt.o \ $O/LzmaDec.o \ @@ -194,7 +194,7 @@ C_OBJS = \ $O/AesOpt.o \ OBJS = \ - $(LZMA_DEC_OPT_OBJS) \ + $(LZMA_DEC_OPT_OBJS) \ $(C_OBJS) \ $(MT_OBJS) \ $(SYS_OBJS) \ diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp index 8eaeabe7..9d632ee0 100644 --- a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp +++ b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp @@ -63,7 +63,7 @@ HRESULT CExtractCallbackImp::Open_Finished() 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 @@ STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) 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 @@ void CExtractCallbackImp::CreateComplexDirectory(const UStringVector &dirPathPar } } -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 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, 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 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, 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 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, _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 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, 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 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResul if (_outFileStream != NULL) { _outFileStreamSpec->SetMTime(&_processedFileInfo.MTime); - RINOK(_outFileStreamSpec->Close()); + RINOK(_outFileStreamSpec->Close()) } _outFileStream.Release(); if (_extractMode) diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h index cfbc5c07..b9377ae6 100644 --- a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h +++ b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h @@ -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 @@ class CExtractCallbackImp: #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 @@ class CExtractCallbackImp: ProgressDialog.Show(SW_SHOWNORMAL); return S_OK; } - virtual ~CExtractCallbackImp() { ProgressDialog.Destroy(); } + ~CExtractCallbackImp() { ProgressDialog.Destroy(); } #endif }; diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp index 71b65c62..73ccff1b 100644 --- a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp +++ b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp @@ -64,18 +64,14 @@ struct CThreadExtracting 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 @@ HRESULT ExtractArchive(CCodecs *codecs, const FString &fileName, const FString & { 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 --git a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h index 295d77b9..b7f79657 100644 --- a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h +++ b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h @@ -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 --git a/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp b/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp index 754cc0e0..cf96460f 100644 --- a/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp +++ b/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp @@ -44,7 +44,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp # 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 @@ SOURCE=..\..\Compress\BcjCoder.cpp # 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 @@ SOURCE=..\..\Compress\CopyCoder.cpp # 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 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\Common\IntToString.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 @@ -464,7 +484,7 @@ SOURCE=..\..\..\Windows\Window.cpp 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 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c # 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 @@ SOURCE=..\..\..\..\C\BraIA64.c # 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.c 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 --git a/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp b/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp index 86b4f0fb..47d7966d 100644 --- a/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp +++ b/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp @@ -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 @@ static bool ReadDataString(CFSTR fileName, LPCSTR startID, 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 bool ReadDataString(CFSTR fileName, LPCSTR startID, 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 @@ struct CInstallIDInit 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, // InitCommonControls(); UString archiveName, switches; - #ifdef _SHELL_EXECUTE + #ifdef MY_SHELL_EXECUTE UString executeFile, executeParameters; #endif NCommandLineParser::SplitCommandLine(GetCommandLineW(), archiveName, switches); @@ -183,23 +184,23 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, { 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, executeParameters += switches; } - CSysString parametersSys (GetSystemString(executeParameters)); + const CSysString parametersSys (GetSystemString(executeParameters)); if (parametersSys.IsEmpty()) execInfo.lpParameters = NULL; else @@ -288,7 +289,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, } 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, ::CloseHandle(processInformation.hThread); hProcess = processInformation.hProcess; } - if (hProcess != 0) + if (hProcess) { WaitForSingleObject(hProcess, INFINITE); ::CloseHandle(hProcess); diff --git a/CPP/7zip/Bundles/SFXSetup/StdAfx.h b/CPP/7zip/Bundles/SFXSetup/StdAfx.h index 37bbd0c3..4f27255c 100644 --- a/CPP/7zip/Bundles/SFXSetup/StdAfx.h +++ b/CPP/7zip/Bundles/SFXSetup/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/SFXSetup/makefile b/CPP/7zip/Bundles/SFXSetup/makefile index 6c71fa40..96546528 100644 --- a/CPP/7zip/Bundles/SFXSetup/makefile +++ b/CPP/7zip/Bundles/SFXSetup/makefile @@ -2,11 +2,11 @@ PROG = 7zS.sfx 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 @@ COMPRESS_OBJS = \ $O\LzmaRegister.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff --git a/CPP/7zip/Bundles/SFXWin/SFXWin.dsp b/CPP/7zip/Bundles/SFXWin/SFXWin.dsp index 8e1a70d2..65cf0bf0 100644 --- a/CPP/7zip/Bundles/SFXWin/SFXWin.dsp +++ b/CPP/7zip/Bundles/SFXWin/SFXWin.dsp @@ -44,7 +44,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp # 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 @@ SOURCE=..\..\Compress\BcjCoder.cpp # 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 @@ SOURCE=..\..\Compress\CopyCoder.cpp # 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 @@ SOURCE=..\..\Compress\PpmdDecoder.cpp # 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 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c # 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 @@ SOURCE=..\..\..\..\C\BraIA64.c # 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.c 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 --git a/CPP/7zip/Bundles/SFXWin/SfxWin.cpp b/CPP/7zip/Bundles/SFXWin/SfxWin.cpp index 23beade2..3e1880ed 100644 --- a/CPP/7zip/Bundles/SFXWin/SfxWin.cpp +++ b/CPP/7zip/Bundles/SFXWin/SfxWin.cpp @@ -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 @@ static DWORD GetDllVersion(LPCTSTR dllName) #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 @@ static int APIENTRY WinMain2() 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 @@ static int APIENTRY WinMain2() CMyComPtr extractCallback = ecs; ecs->Init(); - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO ecs->PasswordIsDefined = !password.IsEmpty(); ecs->Password = password; #endif diff --git a/CPP/7zip/Bundles/SFXWin/StdAfx.h b/CPP/7zip/Bundles/SFXWin/StdAfx.h index 975a17e8..4f27255c 100644 --- a/CPP/7zip/Bundles/SFXWin/StdAfx.h +++ b/CPP/7zip/Bundles/SFXWin/StdAfx.h @@ -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 --git a/CPP/7zip/Bundles/SFXWin/makefile b/CPP/7zip/Bundles/SFXWin/makefile index c8440066..5002e4d9 100644 --- a/CPP/7zip/Bundles/SFXWin/makefile +++ b/CPP/7zip/Bundles/SFXWin/makefile @@ -2,10 +2,10 @@ PROG = 7z.sfx 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 @@ CRYPTO_OBJS = \ $O\MyAes.obj \ C_OBJS = \ + $O\7zStream.obj \ $O\Alloc.obj \ $O\Bcj2.obj \ $O\Bra.obj \ diff --git a/CPP/7zip/Common/CWrappers.cpp b/CPP/7zip/Common/CWrappers.cpp index ee4c36a2..346774e5 100644 --- a/CPP/7zip/Common/CWrappers.cpp +++ b/CPP/7zip/Common/CWrappers.cpp @@ -57,9 +57,9 @@ HRESULT SResToHRESULT(SRes res) throw() #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 @@ void CCompressProgressWrap::Init(ICompressProgressInfo *progress) throw() 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 @@ static SRes MyRead(const ISeqInStream *pp, void *data, size_t *size) throw() 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 @@ void CSeqOutStreamWrap::Init(ISequentialOutStream *stream) throw() } -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 @@ Byte CByteInBufWrap::ReadByteFromNewBlock() throw() 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 @@ bool CLookToSequentialWrap::Alloc(UInt32 size) throw() /* EXTERN_C_BEGIN -void CLookToSequentialWrap_Look(ILookInSeqStream *pp) +void CLookToSequentialWrap_Look(ILookInSeqStreamPtr pp) { CLookToSequentialWrap *p = (CLookToSequentialWrap *)pp->Obj; @@ -281,9 +287,10 @@ HRESULT CByteOutBufWrap::Flush() throw() 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 @@ bool CLookOutWrap::Alloc(size_t size) throw() 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 --git a/CPP/7zip/Common/CWrappers.h b/CPP/7zip/Common/CWrappers.h index e7196a5c..6c10a5c2 100644 --- a/CPP/7zip/Common/CWrappers.h +++ b/CPP/7zip/Common/CWrappers.h @@ -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 @@ struct CByteInBufWrap bool Extra; HRESULT Res; - CByteInBufWrap(); + CByteInBufWrap() throw(); ~CByteInBufWrap() { Free(); } void Free() throw(); bool Alloc(UInt32 size) throw(); diff --git a/CPP/7zip/Common/CreateCoder.cpp b/CPP/7zip/Common/CreateCoder.cpp index 872f17fc..bf7b04e4 100644 --- a/CPP/7zip/Common/CreateCoder.cpp +++ b/CPP/7zip/Common/CreateCoder.cpp @@ -19,11 +19,11 @@ const CCodecInfo *g_Codecs[]; 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 @@ void RegisterHasher(const CHasherInfo *hashInfo) throw() } -#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 ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index 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 @@ HRESULT CExternalCodecs::Load() 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 @@ HRESULT CExternalCodecs::Load() 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 @@ HRESULT CExternalCodecs::Load() { 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 @@ HRESULT CExternalCodecs::Load() 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 @@ int FindMethod_Index( 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 @@ int FindMethod_Index( { 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 @@ static int FindMethod_Index( 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 @@ bool FindMethod( } } - #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 @@ bool FindHashMethod( } } - #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 @@ void GetHashMethods( 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 @@ HRESULT CreateCoder_Index( } } - #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 @@ HRESULT CreateCoder_Index( { 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 @@ HRESULT CreateCoder_Index( { 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 @@ HRESULT CreateCoder_Index( 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 @@ HRESULT CreateCoder_Id( 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 @@ HRESULT CreateCoder_Id( 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 @@ HRESULT CreateCoder_Id( CMyComPtr &coder) { CCreatedCoder cod; - HRESULT res = CreateCoder_Id( + const HRESULT res = CreateCoder_Id( EXTERNAL_CODECS_LOC_VARS methodId, encode, cod); @@ -524,18 +527,18 @@ HRESULT CreateHasher( } } - #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 --git a/CPP/7zip/Common/CreateCoder.h b/CPP/7zip/Common/CreateCoder.h index 24e6b663..709fe83c 100644 --- a/CPP/7zip/Common/CreateCoder.h +++ b/CPP/7zip/Common/CreateCoder.h @@ -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 @@ struct CHasherInfoEx 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 @@ struct CExternalCodecs 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 @@ extern CExternalCodecs g_ExternalCodecs; #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 @@ int FindMethod_Index( const AString &name, bool encode, CMethodId &methodId, - UInt32 &numStreams); + UInt32 &numStreams, + bool &isFilter); bool FindMethod( DECL_EXTERNAL_CODECS_LOC_VARS diff --git a/CPP/7zip/Common/FilePathAutoRename.h b/CPP/7zip/Common/FilePathAutoRename.h index 7b576591..ac368823 100644 --- a/CPP/7zip/Common/FilePathAutoRename.h +++ b/CPP/7zip/Common/FilePathAutoRename.h @@ -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 --git a/CPP/7zip/Common/FileStreams.cpp b/CPP/7zip/Common/FileStreams.cpp index 0349e907..42986363 100644 --- a/CPP/7zip/Common/FileStreams.cpp +++ b/CPP/7zip/Common/FileStreams.cpp @@ -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 @@ static inline HRESULT ConvertBoolToHRESULT(bool result) } -#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(): CInFileStream::~CInFileStream() { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE MidFree(Buf); #endif @@ -81,11 +83,11 @@ CInFileStream::~CInFileStream() 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) { 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) { 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) } 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) if (processedSize) *processedSize = realProcessedSize; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE VirtPos += realProcessedSize; PhyPos += realProcessedSize; #endif @@ -188,7 +190,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) if (result) return S_OK; - #else // USE_WIN_FILE + #else // Z7_FILE_STREAMS_USE_WIN_FILE if (processedSize) *processedSize = 0; @@ -199,7 +201,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) *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 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) } #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 @@ STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSi 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 @@ STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSi #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 @@ STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos 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 @@ STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos #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::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aT } } -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::GetProps2(CStreamFileProps *props) } } -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::GetProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CInFileStream::ReloadProps() #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 @@ STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aT // #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 @@ STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props) 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 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) // 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::GetProperty(PROPID propID, PROPVARIANT *value) } -STDMETHODIMP CInFileStream::ReloadProps() +Z7_COM7F_IMF(CInFileStream::ReloadProps()) { _info_WasLoaded = (File.my_fstat(&_info) == 0); if (!_info_WasLoaded) @@ -653,9 +676,9 @@ HRESULT COutFileStream::Close() 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 @@ STDMETHODIMP COutFileStream::Write(const void *data, UInt32 size, UInt32 *proces #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 @@ STDMETHODIMP COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo #endif } -STDMETHODIMP COutFileStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(COutFileStream::SetSize(UInt64 newSize)) { return ConvertBoolToHRESULT(File.SetLength_KeepPosition(newSize)); } @@ -717,7 +740,7 @@ HRESULT COutFileStream::GetSize(UInt64 *size) #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 @@ STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *pro #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 --git a/CPP/7zip/Common/FileStreams.h b/CPP/7zip/Common/FileStreams.h index f2c19eea..7e1b086b 100644 --- a/CPP/7zip/Common/FileStreams.h +++ b/CPP/7zip/Common/FileStreams.h @@ -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; }; - -class CInFileStream: +Z7_PURE_INTERFACES_END + + +/* +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 @@ class CInFileStream: 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 @@ class CInFileStream: IInFileStream_Callback *Callback; UINT_PTR CallbackRef; - virtual ~CInFileStream(); - CInFileStream(); + ~CInFileStream(); void Set_PreserveATime(bool v) { @@ -89,44 +120,25 @@ class CInFileStream: _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 @@ class COutFileStream: } 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 @@ class COutFileStream: 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 --git a/CPP/7zip/Common/FilterCoder.cpp b/CPP/7zip/Common/FilterCoder.cpp index fb99f610..8d7e0dcc 100644 --- a/CPP/7zip/Common/FilterCoder.cpp +++ b/CPP/7zip/Common/FilterCoder.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +// #include + #include "../../Common/Defs.h" #include "FilterCoder.h" @@ -33,13 +35,17 @@ void CAlignedMidBuffer::AllocAligned(size_t size) 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 @@ HRESULT CFilterCoder::Alloc() 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::Alloc() HRESULT CFilterCoder::Init_and_Alloc() { - RINOK(Filter->Init()); + RINOK(Filter->Init()) return Alloc(); } @@ -72,78 +79,197 @@ CFilterCoder::CFilterCoder(bool encodeMode): _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 (readPos == 0) + return hres; + + /* 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; } - if (pos == 0) - return S_OK; + UInt32 size = filterPos; + if (hres == S_OK) + { + /* 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 filtered = Filter->Filter(_buf, pos); - - if (filtered > pos) { - // AES - if (!inputFinished || filtered > _bufSize) - return E_FAIL; + 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 @@ STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStr // ---------- 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 @@ HRESULT CFilterCoder::Flush2() 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 @@ HRESULT CFilterCoder::Flush2() } 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 @@ HRESULT CFilterCoder::Flush2() 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 @@ STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processe 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 @@ STDMETHODIMP CFilterCoder::OutStreamFinish() _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 @@ STDMETHODIMP CFilterCoder::OutStreamFinish() // ---------- Init functions ---------- -STDMETHODIMP CFilterCoder::InitEncoder() +Z7_COM7F_IMF(CFilterCoder::InitEncoder()) { InitSpecVars(); return Init_and_Alloc(); @@ -297,33 +429,33 @@ HRESULT CFilterCoder::Init_NoSubFilterInit() 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 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) { 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 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) } -#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 +#ifndef Z7_EXTRACT_ONLY + +Z7_COM7F_IMF(CFilterCoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *properties, UInt32 numProperties)) + { return _setCoderProperties->SetCoderProperties(propIDs, properties, numProperties); } -STDMETHODIMP 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); } -STDMETHODIMP 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 --git a/CPP/7zip/Common/FilterCoder.h b/CPP/7zip/Common/FilterCoder.h index 6668fdb3..3a588fd5 100644 --- a/CPP/7zip/Common/FilterCoder.h +++ b/CPP/7zip/Common/FilterCoder.h @@ -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 @@ struct CAlignedMidBuffer void AllocAligned(size_t size); }; -class CFilterCoder: + +class CFilterCoder Z7_final : public ICompressCoder, public ICompressSetOutStreamSize, @@ -41,14 +42,15 @@ class CFilterCoder: 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 @@ class CFilterCoder: UInt32 _outBufSize; bool _encodeMode; - bool _outSizeIsDefined; + bool _outSize_Defined; UInt64 _outSize; UInt64 _nowPos64; @@ -78,7 +80,7 @@ class CFilterCoder: _convPos = 0; _convSize = 0; - _outSizeIsDefined = false; + _outSize_Defined = false; _outSize = 0; _nowPos64 = 0; } @@ -87,117 +89,111 @@ class CFilterCoder: 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 - + Z7_COM_QI_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _setDecoderProperties2) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - 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 EXTRACT_ONLY - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); + #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 - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - +public: + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) HRESULT Init_NoSubFilterInit(); }; diff --git a/CPP/7zip/Common/InBuffer.cpp b/CPP/7zip/Common/InBuffer.cpp index fe6d1490..b0f222c2 100644 --- a/CPP/7zip/Common/InBuffer.cpp +++ b/CPP/7zip/Common/InBuffer.cpp @@ -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 @@ bool CInBuffer::Create(size_t bufSize) throw() 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 @@ void CInBufferBase::Init() throw() _buf = _bufBase; _bufLim = _buf; _wasFinished = false; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif NumExtraBytes = 0; @@ -50,7 +50,7 @@ void CInBufferBase::Init() throw() bool CInBufferBase::ReadBlock() { - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS if (ErrorCode != S_OK) return false; #endif @@ -61,8 +61,8 @@ bool CInBufferBase::ReadBlock() _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 --git a/CPP/7zip/Common/InBuffer.h b/CPP/7zip/Common/InBuffer.h index fa063949..3aaf797a 100644 --- a/CPP/7zip/Common/InBuffer.h +++ b/CPP/7zip/Common/InBuffer.h @@ -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 @@ class CInBufferBase Byte ReadByte_FromNewBlock(); public: - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS HRESULT ErrorCode; #endif UInt32 NumExtraBytes; @@ -60,7 +60,7 @@ class CInBufferBase _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 @@ class CInBufferBase void Init() throw(); - MY_FORCE_INLINE + Z7_FORCE_INLINE bool ReadByte(Byte &b) { if (_buf >= _bufLim) @@ -77,7 +77,7 @@ class CInBufferBase return true; } - MY_FORCE_INLINE + Z7_FORCE_INLINE bool ReadByte_FromBuf(Byte &b) { if (_buf >= _bufLim) @@ -86,7 +86,7 @@ class CInBufferBase return true; } - MY_FORCE_INLINE + Z7_FORCE_INLINE Byte ReadByte() { if (_buf >= _bufLim) diff --git a/CPP/7zip/Common/InOutTempBuffer.cpp b/CPP/7zip/Common/InOutTempBuffer.cpp index cae6b803..3f7272ef 100644 --- a/CPP/7zip/Common/InOutTempBuffer.cpp +++ b/CPP/7zip/Common/InOutTempBuffer.cpp @@ -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() +CInOutTempBuffer::CInOutTempBuffer(): + _size(0), + _bufs(NULL), + _numBufs(0), + _numFilled(0) { - #ifdef USE_InOutTempBuffer_FILE - _bufPos = 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 --git a/CPP/7zip/Common/InOutTempBuffer.h b/CPP/7zip/Common/InOutTempBuffer.h index 755935ea..345c3863 100644 --- a/CPP/7zip/Common/InOutTempBuffer.h +++ b/CPP/7zip/Common/InOutTempBuffer.h @@ -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 --git a/CPP/7zip/Common/LimitedStreams.cpp b/CPP/7zip/Common/LimitedStreams.cpp index 980c795d..664cd0c4 100644 --- a/CPP/7zip/Common/LimitedStreams.cpp +++ b/CPP/7zip/Common/LimitedStreams.cpp @@ -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 @@ STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *p 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 @@ STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSi if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } HRESULT res = _stream->Read(data, size, &size); if (processedSize) @@ -56,7 +56,7 @@ STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSi 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 @@ STDMETHODIMP CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new 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 @@ STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSi if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } _curRem = blockSize - offsetInBlock; @@ -130,7 +130,7 @@ STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSi 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 CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new } -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 @@ STDMETHODIMP CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize 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::Read(void *data, UInt32 size, UInt32 *processedSize } -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 CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo } -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 CLimitedSequentialOutStream::Write(const void *data, UInt32 size, U } -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 @@ STDMETHODIMP CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 @@ STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos 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 @@ STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos _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 @@ STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *proce if (newPos != _physPos) { _physPos = newPos; - RINOK(SeekToPhys()); + RINOK(SeekToPhys()) } res = _stream->Read(data, size, &size); _physPos += size; @@ -340,7 +340,7 @@ STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *proce 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 @@ STDMETHODIMP CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt6 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 @@ STDMETHODIMP CTailOutStream::Write(const void *data, UInt32 size, UInt32 *proces 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 @@ STDMETHODIMP CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo 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 --git a/CPP/7zip/Common/LimitedStreams.h b/CPP/7zip/Common/LimitedStreams.h index 50c7cd85..69fcdcdb 100644 --- a/CPP/7zip/Common/LimitedStreams.h +++ b/CPP/7zip/Common/LimitedStreams.h @@ -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 @@ class CLimitedSequentialInStream: _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 @@ class CLimitedInStream: _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 @@ class CClusterInStream: 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 @@ class CClusterInStream: } 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 @@ struct CSeekExtent 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 CExtentsStream: -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 CLimitedSequentialOutStream: }; -class CTailInStream: - public IInStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_IInStream( + CTailInStream +) UInt64 _virtPos; public: CMyComPtr Stream; @@ -178,19 +157,13 @@ class CTailInStream: { _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 @@ class CLimitedCachedInStream: 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 @@ class CLimitedCachedInStream: 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 --git a/CPP/7zip/Common/LockedStream.h b/CPP/7zip/Common/LockedStream.h index efebf197..99ee8055 100644 --- a/CPP/7zip/Common/LockedStream.h +++ b/CPP/7zip/Common/LockedStream.h @@ -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 --git a/CPP/7zip/Common/MemBlocks.cpp b/CPP/7zip/Common/MemBlocks.cpp index 9b0652c6..aa682448 100644 --- a/CPP/7zip/Common/MemBlocks.cpp +++ b/CPP/7zip/Common/MemBlocks.cpp @@ -34,8 +34,8 @@ bool CMemBlockManager::AllocateSpace_bool(size_t numBlocks) void CMemBlockManager::FreeSpace() { ::MidFree(_data); - _data = 0; - _headFree= 0; + _data = NULL; + _headFree= NULL; } void *CMemBlockManager::AllocateBlock() @@ -157,7 +157,7 @@ HRESULT CMemBlocks::WriteToStream(size_t blockSize, ISequentialOutStream *outStr 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 @@ void CMemLockBlocks::Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManag blocks.Blocks.Add(Blocks[i]); else FreeBlock(i, memManager); - Blocks[i] = 0; + Blocks[i] = NULL; totalSize += blockSize; } blocks.TotalSize = TotalSize; diff --git a/CPP/7zip/Common/MemBlocks.h b/CPP/7zip/Common/MemBlocks.h index 3c9cefdb..7c34f21c 100644 --- a/CPP/7zip/Common/MemBlocks.h +++ b/CPP/7zip/Common/MemBlocks.h @@ -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 @@ class CMemBlockManagerMt: public CMemBlockManager { 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 @@ struct CMemLockBlocks: public CMemBlocks { bool LockMode; - CMemLockBlocks(): LockMode(true) {}; + CMemLockBlocks(): LockMode(true) {} void Free(CMemBlockManagerMt *memManager); void FreeBlock(unsigned index, CMemBlockManagerMt *memManager); // HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager); diff --git a/CPP/7zip/Common/MethodId.h b/CPP/7zip/Common/MethodId.h index 28b615fc..19b1f10d 100644 --- a/CPP/7zip/Common/MethodId.h +++ b/CPP/7zip/Common/MethodId.h @@ -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 --git a/CPP/7zip/Common/MethodProps.cpp b/CPP/7zip/Common/MethodProps.cpp index 8d7e204d..d1aa124d 100644 --- a/CPP/7zip/Common/MethodProps.cpp +++ b/CPP/7zip/Common/MethodProps.cpp @@ -379,14 +379,14 @@ struct CNameToPropID // 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,12 +400,13 @@ static const CNameToPropID g_NameToPropID[] = { 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, "aff" }, - // zstd props + { VT_UI4, "offset" }, + { VT_UI4, "zhb" }, { VT_UI4, "strat" }, { VT_UI4, "fast" }, { VT_UI4, "long" }, @@ -420,16 +421,50 @@ static const CNameToPropID g_NameToPropID[] = { VT_UI4, "ldmslen" }, { VT_UI4, "ldmblog" }, { VT_UI4, "ldmhevery" } + /* + , + // { 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) || (__STDC_VERSION >= 201112L) || (_MSC_VER >= 1900) - static_assert(ARRAY_SIZE(g_NameToPropID) == NCoderPropID::kEndOfProp, +/* +#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; @@ -514,6 +549,10 @@ static bool IsLogSizeProp(PROPID propid) case NCoderPropID::kUsedMemorySize: case NCoderPropID::kBlockSize: case NCoderPropID::kBlockSize2: + /* + case NCoderPropID::kChainSize: + case NCoderPropID::kLdmWindowSize: + */ // case NCoderPropID::kReduceSize: return true; } @@ -524,14 +563,19 @@ HRESULT CMethodProps::SetParam(const UString &name, const UString &value) { 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 { @@ -582,7 +626,7 @@ HRESULT CMethodProps::ParseParamsFromString(const UString &srcString) const UString ¶m = params[i]; UString name, value; SplitParam(param, name, value); - RINOK(SetParam(name, value)); + RINOK(SetParam(name, value)) } return S_OK; } @@ -603,7 +647,7 @@ HRESULT CMethodProps::ParseParamsFromPROPVARIANT(const UString &realName, const } // {realName}=value - int index = FindPropIdExact(realName); + const int index = FindPropIdExact(realName); if (index < 0) return E_INVALIDARG; const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index]; @@ -612,7 +656,7 @@ HRESULT CMethodProps::ParseParamsFromPROPVARIANT(const UString &realName, const if (IsLogSizeProp(prop.Id)) { - RINOK(PROPVARIANT_to_DictSize(value, prop.Value)); + RINOK(PROPVARIANT_to_DictSize(value, prop.Value)) } else { diff --git a/CPP/7zip/Common/MethodProps.h b/CPP/7zip/Common/MethodProps.h index 5b5c96a4..3c332d6a 100644 --- a/CPP/7zip/Common/MethodProps.h +++ b/CPP/7zip/Common/MethodProps.h @@ -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 --git a/CPP/7zip/Common/MultiOutStream.cpp b/CPP/7zip/Common/MultiOutStream.cpp new file mode 100644 index 00000000..8efb977f --- /dev/null +++ b/CPP/7zip/Common/MultiOutStream.cpp @@ -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 --git a/CPP/7zip/Common/MultiOutStream.h b/CPP/7zip/Common/MultiOutStream.h new file mode 100644 index 00000000..2fb78112 --- /dev/null +++ b/CPP/7zip/Common/MultiOutStream.h @@ -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 --git a/CPP/7zip/Common/OffsetStream.cpp b/CPP/7zip/Common/OffsetStream.cpp index b16124c2..a6b005e4 100644 --- a/CPP/7zip/Common/OffsetStream.cpp +++ b/CPP/7zip/Common/OffsetStream.cpp @@ -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 @@ HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset) 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 @@ STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new 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 --git a/CPP/7zip/Common/OffsetStream.h b/CPP/7zip/Common/OffsetStream.h index 9074a24e..9bd554cc 100644 --- a/CPP/7zip/Common/OffsetStream.h +++ b/CPP/7zip/Common/OffsetStream.h @@ -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 --git a/CPP/7zip/Common/OutBuffer.cpp b/CPP/7zip/Common/OutBuffer.cpp index 4ba34a05..197b3767 100644 --- a/CPP/7zip/Common/OutBuffer.cpp +++ b/CPP/7zip/Common/OutBuffer.cpp @@ -11,18 +11,18 @@ bool COutBuffer::Create(UInt32 bufSize) throw() 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 @@ void COutBuffer::Init() throw() _pos = 0; _processedSize = 0; _overDict = false; - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif } @@ -51,17 +51,17 @@ HRESULT COutBuffer::FlushPart() throw() // _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::FlushPart() throw() 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 @@ HRESULT COutBuffer::Flush() throw() 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 --git a/CPP/7zip/Common/OutBuffer.h b/CPP/7zip/Common/OutBuffer.h index d7ca9f6a..cef7d502 100644 --- a/CPP/7zip/Common/OutBuffer.h +++ b/CPP/7zip/Common/OutBuffer.h @@ -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 @@ class COutBuffer 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 --git a/CPP/7zip/Common/OutMemStream.cpp b/CPP/7zip/Common/OutMemStream.cpp index 241589d2..29a23941 100644 --- a/CPP/7zip/Common/OutMemStream.cpp +++ b/CPP/7zip/Common/OutMemStream.cpp @@ -31,13 +31,13 @@ void COutMemStream::DetachData(CMemLockBlocks &blocks) 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 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process 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 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process 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 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process { if (waitResult == WAIT_FAILED) { - DWORD res = ::GetLastError(); + const DWORD res = ::GetLastError(); if (res != 0) return HRESULT_FROM_WIN32(res); } @@ -118,7 +118,7 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process 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 @@ STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos return S_OK; } -STDMETHODIMP COutMemStream::SetSize(UInt64 newSize) +Z7_COM7F_IMF(COutMemStream::SetSize(UInt64 newSize)) { if (_realStreamMode) { diff --git a/CPP/7zip/Common/OutMemStream.h b/CPP/7zip/Common/OutMemStream.h index 873742ed..7fc2dbd9 100644 --- a/CPP/7zip/Common/OutMemStream.h +++ b/CPP/7zip/Common/OutMemStream.h @@ -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 @@ class COutMemStream: 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 @@ class COutMemStream: 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 --git a/CPP/7zip/Common/ProgressMt.cpp b/CPP/7zip/Common/ProgressMt.cpp index c2714a27..ee21ab3e 100644 --- a/CPP/7zip/Common/ProgressMt.cpp +++ b/CPP/7zip/Common/ProgressMt.cpp @@ -31,13 +31,13 @@ HRESULT CMtCompressProgressMixer::SetRatioInfo(unsigned index, const UInt64 *inS 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 @@ HRESULT CMtCompressProgressMixer::SetRatioInfo(unsigned index, const UInt64 *inS } -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 --git a/CPP/7zip/Common/ProgressMt.h b/CPP/7zip/Common/ProgressMt.h index 32da976b..78c806c5 100644 --- a/CPP/7zip/Common/ProgressMt.h +++ b/CPP/7zip/Common/ProgressMt.h @@ -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 @@ class CMtCompressProgressMixer 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 @@ class CMtCompressProgress: _index = index; } void Reinit() { _progress->Reinit(_index); } - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); }; #endif diff --git a/CPP/7zip/Common/ProgressUtils.cpp b/CPP/7zip/Common/ProgressUtils.cpp index 41385ccb..fb81f29b 100644 --- a/CPP/7zip/Common/ProgressUtils.cpp +++ b/CPP/7zip/Common/ProgressUtils.cpp @@ -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 @@ void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain) _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 @@ STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *ou if (SendRatio && _ratioProgress) { - RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2)); + RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2)) } if (SendProgress) diff --git a/CPP/7zip/Common/ProgressUtils.h b/CPP/7zip/Common/ProgressUtils.h index e94265ba..dad5fccf 100644 --- a/CPP/7zip/Common/ProgressUtils.h +++ b/CPP/7zip/Common/ProgressUtils.h @@ -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 --git a/CPP/7zip/Common/PropId.cpp b/CPP/7zip/Common/PropId.cpp index 0e643e85..6117b0e2 100644 --- a/CPP/7zip/Common/PropId.cpp +++ b/CPP/7zip/Common/PropId.cpp @@ -111,5 +111,7 @@ const Byte k7z_PROPID_To_VARTYPE[kpid_NUM_DEFINED] = VT_UI4, VT_UI4, VT_UI4, - VT_UI4 // kpidDeviceMinor + VT_UI4, + VT_UI4, + VT_UI4 // kpidDevMinor }; diff --git a/CPP/7zip/Common/RegisterArc.h b/CPP/7zip/Common/RegisterArc.h index a0384fad..55c1483f 100644 --- a/CPP/7zip/Common/RegisterArc.h +++ b/CPP/7zip/Common/RegisterArc.h @@ -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 @@ void RegisterArc(const CArcInfo *arcInfo) throw(); #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 @@ void RegisterArc(const CArcInfo *arcInfo) throw(); #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 @@ void RegisterArc(const CArcInfo *arcInfo) throw(); #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 --git a/CPP/7zip/Common/RegisterCodec.h b/CPP/7zip/Common/RegisterCodec.h index a942da7a..cf94998a 100644 --- a/CPP/7zip/Common/RegisterCodec.h +++ b/CPP/7zip/Common/RegisterCodec.h @@ -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 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw(); #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 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw(); 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 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw(); 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 @@ void RegisterHasher(const CHasherInfo *hasher) throw(); #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 --git a/CPP/7zip/Common/StdAfx.h b/CPP/7zip/Common/StdAfx.h index 1cbd7fea..80866550 100644 --- a/CPP/7zip/Common/StdAfx.h +++ b/CPP/7zip/Common/StdAfx.h @@ -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 --git a/CPP/7zip/Common/StreamBinder.cpp b/CPP/7zip/Common/StreamBinder.cpp index 6b6e0e58..38334af9 100644 --- a/CPP/7zip/Common/StreamBinder.cpp +++ b/CPP/7zip/Common/StreamBinder.cpp @@ -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 --git a/CPP/7zip/Common/StreamBinder.h b/CPP/7zip/Common/StreamBinder.h index 16c872fb..c0a70793 100644 --- a/CPP/7zip/Common/StreamBinder.h +++ b/CPP/7zip/Common/StreamBinder.h @@ -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 --git a/CPP/7zip/Common/StreamObjects.cpp b/CPP/7zip/Common/StreamObjects.cpp index 2d941df6..b54f4237 100644 --- a/CPP/7zip/Common/StreamObjects.cpp +++ b/CPP/7zip/Common/StreamObjects.cpp @@ -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 @@ STDMETHODIMP CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSiz 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 @@ STDMETHODIMP CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP 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 @@ STDMETHODIMP CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 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 Create_BufInStream_WithNewBuffer(const void *data, size_t size, ISequential void CByteDynBuffer::Free() throw() { - free(_buf); - _buf = 0; + MyFree(_buf); + _buf = NULL; _capacity = 0; } @@ -108,11 +106,10 @@ bool CByteDynBuffer::EnsureCapacity(size_t cap) throw() { 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 @@ void CDynBufSeqOutStream::CopyToBuffer(CByteBuffer &dest) const 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 @@ STDMETHODIMP CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *p 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 @@ STDMETHODIMP CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *p 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 @@ void CCachedInStream::Init(UInt64 size) throw() { _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 @@ STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSiz return S_OK; { - UInt64 rem = _size - _pos; + const UInt64 rem = _size - _pos; if (size > rem) size = (UInt32)rem; } @@ -245,12 +242,12 @@ STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSiz 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::Read(void *data, UInt32 size, UInt32 *processedSiz } -STDMETHODIMP CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) +Z7_COM7F_IMF(CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) { switch (seekOrigin) { diff --git a/CPP/7zip/Common/StreamObjects.h b/CPP/7zip/Common/StreamObjects.h index a8fb229c..2c0ebea9 100644 --- a/CPP/7zip/Common/StreamObjects.h +++ b/CPP/7zip/Common/StreamObjects.h @@ -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 @@ class CBufInStream: } 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 @@ inline void Create_BufInStream_WithNewBuffer(const CByteBuffer &buf, ISequential { 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 CByteDynBuffer }; -class CDynBufSeqOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CDynBufSeqOutStream + , ISequentialOutStream +) CByteDynBuffer _buffer; size_t _size; public: @@ -95,16 +86,13 @@ class CDynBufSeqOutStream: 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 @@ class CBufPtrSeqOutStream: _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 @@ class CCachedInStream: public IInStream, public CMyUnknownImp { + Z7_IFACES_IMP_UNK_2(ISequentialInStream, IInStream) + UInt64 *_tags; Byte *_data; size_t _dataSize; @@ -153,14 +137,10 @@ class CCachedInStream: 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 --git a/CPP/7zip/Common/StreamUtils.cpp b/CPP/7zip/Common/StreamUtils.cpp index 1402f420..24eed36c 100644 --- a/CPP/7zip/Common/StreamUtils.cpp +++ b/CPP/7zip/Common/StreamUtils.cpp @@ -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 @@ HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSiz *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(ISequentialInStream *stream, void *data, size_t *processedSiz 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 WriteStream(ISequentialOutStream *stream, const void *data, size_t size) 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 --git a/CPP/7zip/Common/StreamUtils.h b/CPP/7zip/Common/StreamUtils.h index ae914c00..35a62ed3 100644 --- a/CPP/7zip/Common/StreamUtils.h +++ b/CPP/7zip/Common/StreamUtils.h @@ -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 --git a/CPP/7zip/Common/UniqBlocks.h b/CPP/7zip/Common/UniqBlocks.h index 8479d68c..66c7fa21 100644 --- a/CPP/7zip/Common/UniqBlocks.h +++ b/CPP/7zip/Common/UniqBlocks.h @@ -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 --git a/CPP/7zip/Common/VirtThread.cpp b/CPP/7zip/Common/VirtThread.cpp index bf24bb1c..3cf7296c 100644 --- a/CPP/7zip/Common/VirtThread.cpp +++ b/CPP/7zip/Common/VirtThread.cpp @@ -11,7 +11,7 @@ static THREAD_FUNC_DECL CoderThread(void *p) 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 @@ static THREAD_FUNC_DECL CoderThread(void *p) 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 --git a/CPP/7zip/Common/VirtThread.h b/CPP/7zip/Common/VirtThread.h index b4d8a5a9..809b3568 100644 --- a/CPP/7zip/Common/VirtThread.h +++ b/CPP/7zip/Common/VirtThread.h @@ -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 @@ struct CVirtThread NWindows::CThread Thread; bool Exit; - ~CVirtThread() { WaitThreadFinish(); } + virtual ~CVirtThread() { WaitThreadFinish(); } void WaitThreadFinish(); // call it in destructor of child class ! WRes Create(); WRes Start(); diff --git a/CPP/7zip/Compress/BZip2Const.h b/CPP/7zip/Compress/BZip2Const.h index 7927d018..0dfcfe54 100644 --- a/CPP/7zip/Compress/BZip2Const.h +++ b/CPP/7zip/Compress/BZip2Const.h @@ -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 --git a/CPP/7zip/Compress/BZip2Crc.h b/CPP/7zip/Compress/BZip2Crc.h index 3b16c60b..10e147bc 100644 --- a/CPP/7zip/Compress/BZip2Crc.h +++ b/CPP/7zip/Compress/BZip2Crc.h @@ -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 @@ class CBZip2Crc 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 @@ class CBZip2CombinedCrc { 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 --git a/CPP/7zip/Compress/BZip2Decoder.cpp b/CPP/7zip/Compress/BZip2Decoder.cpp index c09c160e..b28da5fb 100644 --- a/CPP/7zip/Compress/BZip2Decoder.cpp +++ b/CPP/7zip/Compress/BZip2Decoder.cpp @@ -32,7 +32,7 @@ namespace NCompress { 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 @@ enum EState SRes CBitDecoder::ReadByte(int &b) { b = -1; - READ_BITS_8(b, 8); + READ_BITS_8(b, 8) return SZ_OK; } @@ -180,7 +180,7 @@ SRes CBase::ReadStreamSignature2() 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 @@ SRes CBase::ReadBlockSignature2() while (state2 < 10) { unsigned b; - READ_BITS_8(b, 8); + READ_BITS_8(b, 8) temp[state2] = (Byte)b; state2++; } @@ -285,7 +285,7 @@ SRes CBase::ReadBlock2() { if (Props.randMode) { - READ_BIT(Props.randMode); + READ_BIT(Props.randMode) } state = STATE_ORIG_BITS; // g_Tick = GetCpuTicks(); @@ -293,7 +293,7 @@ SRes CBase::ReadBlock2() 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 @@ SRes CBase::ReadBlock2() 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 @@ SRes CBase::ReadBlock2() 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 @@ SRes CBase::ReadBlock2() 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 @@ SRes CBase::ReadBlock2() if (state == STATE_NUM_SELECTORS) { - READ_BITS(numSelectors, kNumSelectorsBits); + READ_BITS(numSelectors, kNumSelectorsBits) state = STATE_SELECTORS; state2 = 0x543210; state3 = 0; @@ -358,7 +358,7 @@ SRes CBase::ReadBlock2() for (;;) { unsigned b; - READ_BIT(b); + READ_BIT(b) if (!b) break; if (++state4 >= numTables) @@ -392,7 +392,7 @@ SRes CBase::ReadBlock2() { if (state3 == 0) { - READ_BITS_8(state3, kNumLevelsBits); + READ_BITS_8(state3, kNumLevelsBits) state4 = 0; state5 = 0; } @@ -407,14 +407,14 @@ SRes CBase::ReadBlock2() 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 @@ SRes CBase::ReadBlock2() // 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 @@ SRes CBase::ReadBlock2() { 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 @@ HRESULT CDecoder::DecodeBlock(const CBlockProps &props) if (processed >= size) { - RINOK(Flush()); + RINOK(Flush()) } if (block.Finished()) @@ -900,7 +900,7 @@ CDecoder::CDecoder(): _inBuf(NULL), _inProcessed(0) { - #ifndef _7ZIP_ST + #ifndef Z7_ST MtMode = false; NeedWaitScout = false; // ScoutRes = S_OK; @@ -912,7 +912,7 @@ CDecoder::~CDecoder() { PRIN("\n~CDecoder()"); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (Thread.IsCreated()) { @@ -966,7 +966,7 @@ HRESULT CDecoder::ReadStreamSignature() { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadStreamSignature2(); if (res != SZ_OK) return S_FALSE; @@ -992,7 +992,7 @@ HRESULT CDecoder::ReadBlockSignature() { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadBlockSignature2(); @@ -1015,7 +1015,7 @@ HRESULT CDecoder::ReadBlock() { for (;;) { - RINOK(ReadInput()); + RINOK(ReadInput()) SRes res = Base.ReadBlock2(); @@ -1036,18 +1036,18 @@ HRESULT CDecoder::ReadBlock() 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 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) 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 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) return nextRes; if ( - #ifndef _7ZIP_ST + #ifndef Z7_ST !useMt && #endif !wasFinished && Base.state == STATE_BLOCK_SIGNATURE) @@ -1125,7 +1125,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) wasFinished = false; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (MtMode) if (props.blockSize != 0) { @@ -1136,7 +1136,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) if (!Thread.IsCreated()) { PRIN("=== MT_MODE"); - RINOK(CreateThread()); + RINOK(CreateThread()) } useMt = true; } @@ -1148,7 +1148,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) { crc = nextCrc; - #ifndef _7ZIP_ST + #ifndef Z7_ST if (useMt) { PRIN("DecoderEvent.Lock()"); @@ -1165,7 +1165,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) crc = _block.Crc; packPos = _block.PackPos; wasFinished = _block.WasFinished; - RINOK(_block.Res); + RINOK(_block.Res) } else #endif @@ -1175,7 +1175,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) TICKS_START Base.Props.randMode = 1; - RINOK(ReadBlock()); + RINOK(ReadBlock()) TICKS_UPDATE(0) props = Base.Props; @@ -1190,7 +1190,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) TICKS_UPDATE(1) } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (useMt && !wasFinished) { /* @@ -1216,7 +1216,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) if (props.blockSize == 0) continue; - RINOK(DecodeBlock(props)); + RINOK(DecodeBlock(props)) if (!_blockFinished) return nextRes; @@ -1278,8 +1278,8 @@ void CDecoder::InitOutSize(const UInt64 *outSize) } -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::Code(ISequentialInStream *inStream, ISequentialOutStream } -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 @@ STDMETHODIMP CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *proc } -#ifndef _7ZIP_ST +#ifndef Z7_ST #define PRIN_MT(s) PRIN(" " s) @@ -1397,9 +1397,9 @@ void CDecoder::RunScout() 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 @@ void CDecoder::RunScout() res = ReadBlock(); - PRIN_MT("-- Base.ReadBlock"); + PRIN_MT("-- Base.ReadBlock") if (res != S_OK) break; block.Props = Base.Props; @@ -1505,13 +1505,13 @@ void CDecoder::RunScout() 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 @@ void CDecoder::RunScout() } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { MtMode = (numThreads > 1); @@ -1538,10 +1538,10 @@ STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) -#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::SetInStream(ISequentialInStream *inStream) } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { Base.InStreamRef.Release(); Base.InStream = NULL; @@ -1558,7 +1558,7 @@ STDMETHODIMP CDecoder::ReleaseInStream() -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { InitOutSize(outSize); @@ -1583,7 +1583,7 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) -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 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) // ---------- NSIS ---------- -STDMETHODIMP CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) +Z7_COM7F_IMF(CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)) { *processedSize = 0; diff --git a/CPP/7zip/Compress/BZip2Decoder.h b/CPP/7zip/Compress/BZip2Decoder.h index 8fe4ef1b..a8ef7009 100644 --- a/CPP/7zip/Compress/BZip2Decoder.h +++ b/CPP/7zip/Compress/BZip2Decoder.h @@ -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 @@ struct CBase: public CBitDecoder ISequentialInStream *InStream; - #ifndef NO_READ_FROM_CODER + #ifndef Z7_NO_READ_FROM_CODER CMyComPtr InStreamRef; #endif @@ -194,24 +194,51 @@ class CSpecState -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 @@ class CDecoder : CSpecState _spec; UInt32 *_counters; - #ifndef _7ZIP_ST + #ifndef Z7_ST struct CBlock { @@ -339,60 +366,20 @@ class CDecoder : 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 --git a/CPP/7zip/Compress/BZip2Encoder.cpp b/CPP/7zip/Compress/BZip2Encoder.cpp index 62c15d67..ef2555a0 100644 --- a/CPP/7zip/Compress/BZip2Encoder.cpp +++ b/CPP/7zip/Compress/BZip2Encoder.cpp @@ -46,7 +46,7 @@ void CThreadInfo::Free() m_Block = NULL; } -#ifndef _7ZIP_ST +#ifndef Z7_ST static THREAD_FUNC_DECL MFThread(void *threadCoderInfo) { @@ -146,14 +146,14 @@ CEncoder::CEncoder() { _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 @@ void CThreadInfo::EncodeBlock(const Byte *block, UInt32 blockSize) { 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 @@ HRESULT CThreadInfo::EncodeBlock3(UInt32 blockSize) 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 @@ HRESULT CThreadInfo::EncodeBlock3(UInt32 blockSize) 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 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * m_OutStream.Init(); CombinedCrc.Init(); - #ifndef _7ZIP_ST + #ifndef Z7_ST NextBlockIndex = 0; StreamWasFinished = false; CloseThreads = false; @@ -799,7 +799,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * WriteByte(kArSig2); WriteByte((Byte)(kArSig3 + _props.BlockSizeMult)); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (MtMode) { @@ -814,7 +814,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * for (t = 0; t < NumThreads; t++) ThreadsInfo[t].WaitingWasStartedEvent.Lock(); CanStartWaitingEvent.Reset(); - RINOK(Result); + RINOK(Result) } else #endif @@ -822,7 +822,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * for (;;) { CThreadInfo &ti = - #ifndef _7ZIP_ST + #ifndef Z7_ST ThreadsInfo[0]; #else ThreadsInfo; @@ -830,12 +830,12 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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 @@ HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *c case NCoderPropID::kLevel: level = (int)v; break; case NCoderPropID::kNumThreads: { - #ifndef _7ZIP_ST + #ifndef Z7_ST SetNumberOfThreads(v); #endif break; @@ -905,8 +905,8 @@ HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *c 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 --git a/CPP/7zip/Compress/BZip2Encoder.h b/CPP/7zip/Compress/BZip2Encoder.h index e2828a92..4a04fbd6 100644 --- a/CPP/7zip/Compress/BZip2Encoder.h +++ b/CPP/7zip/Compress/BZip2Encoder.h @@ -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 @@ class CThreadInfo 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 @@ class CThreadInfo public: bool m_OptimizeNumTables; CEncoder *Encoder; - #ifndef _7ZIP_ST + #ifndef Z7_ST NWindows::CThread Thread; NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent; @@ -129,13 +127,15 @@ class CThreadInfo // 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 @@ struct CEncProps 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 @@ class CEncoder : HRESULT Result; ICompressProgressInfo *Progress; - #else + #else CThreadInfo ThreadsInfo; - #endif + #endif UInt64 NumBlocks; @@ -207,37 +225,21 @@ class CEncoder : // 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 --git a/CPP/7zip/Compress/BZip2Register.cpp b/CPP/7zip/Compress/BZip2Register.cpp index 6e960366..83b911de 100644 --- a/CPP/7zip/Compress/BZip2Register.cpp +++ b/CPP/7zip/Compress/BZip2Register.cpp @@ -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 @@ namespace NBZip2 { 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 --git a/CPP/7zip/Compress/Bcj2Coder.cpp b/CPP/7zip/Compress/Bcj2Coder.cpp index 561fd08b..27e78b00 100644 --- a/CPP/7zip/Compress/Bcj2Coder.cpp +++ b/CPP/7zip/Compress/Bcj2Coder.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +// #include + #include "../../../C/Alloc.h" #include "../Common/StreamUtils.h" @@ -13,42 +15,47 @@ namespace NBcj2 { 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 @@ HRESULT CBaseCoder::Alloc(bool allocForOrig) -#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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA 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 (numBytes_in_ReadBuf != (size_t)(enc.src - _bufs[BCJ2_NUM_STREAMS])) + 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) { - enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; - continue; + 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 (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)); - - // printf("Read %6d bytes\n", curSize); - if (curSize == 0) + if (getSubStreamSize) { - readWasFinished = true; - 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 (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) + } + + 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 CEncoder::Code(ISequentialInStream * const *inStreams, const UInt64 -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; { - for (int i = 0; i < BCJ2_NUM_STREAMS; i++) + 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)) + { + 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 @@ HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * co 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 @@ HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * co 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 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 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 --git a/CPP/7zip/Compress/Bcj2Coder.h b/CPP/7zip/Compress/Bcj2Coder.h index ca6a1e4e..2ab91bc8 100644 --- a/CPP/7zip/Compress/Bcj2Coder.h +++ b/CPP/7zip/Compress/Bcj2Coder.h @@ -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 @@ class CBaseCoder { 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 @@ class CBaseCoder }; -#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 --git a/CPP/7zip/Compress/Bcj2Register.cpp b/CPP/7zip/Compress/Bcj2Register.cpp index 2868f1c9..1ce4decb 100644 --- a/CPP/7zip/Compress/Bcj2Register.cpp +++ b/CPP/7zip/Compress/Bcj2Register.cpp @@ -10,7 +10,7 @@ namespace NCompress { 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 --git a/CPP/7zip/Compress/BcjCoder.cpp b/CPP/7zip/Compress/BcjCoder.cpp index 32aa1762..00478747 100644 --- a/CPP/7zip/Compress/BcjCoder.cpp +++ b/CPP/7zip/Compress/BcjCoder.cpp @@ -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 --git a/CPP/7zip/Compress/BcjCoder.h b/CPP/7zip/Compress/BcjCoder.h index 7883906e..734a2786 100644 --- a/CPP/7zip/Compress/BcjCoder.h +++ b/CPP/7zip/Compress/BcjCoder.h @@ -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 --git a/CPP/7zip/Compress/BcjRegister.cpp b/CPP/7zip/Compress/BcjRegister.cpp index f06dcfe9..0348f641 100644 --- a/CPP/7zip/Compress/BcjRegister.cpp +++ b/CPP/7zip/Compress/BcjRegister.cpp @@ -10,8 +10,8 @@ namespace NCompress { namespace NBcj { REGISTER_FILTER_E(BCJ, - CCoder(false), - CCoder(true), + CCoder2(z7_BranchConvSt_X86_Dec), + CCoder2(z7_BranchConvSt_X86_Enc), 0x3030103, "BCJ") }} diff --git a/CPP/7zip/Compress/BitlDecoder.h b/CPP/7zip/Compress/BitlDecoder.h index 825864d8..789ad1f9 100644 --- a/CPP/7zip/Compress/BitlDecoder.h +++ b/CPP/7zip/Compress/BitlDecoder.h @@ -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 @@ class CBaseDecoder 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 @@ class CDecoder: public CBaseDecoder _normalValue = 0; } - MY_FORCE_INLINE + Z7_FORCE_INLINE void Normalize() { for (; this->_bitPos >= 8; this->_bitPos -= 8) @@ -113,21 +113,21 @@ class CDecoder: public CBaseDecoder } } - 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 @@ class CDecoder: public CBaseDecoder 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 @@ class CDecoder: public CBaseDecoder } // 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 --git a/CPP/7zip/Compress/BitlEncoder.h b/CPP/7zip/Compress/BitlEncoder.h index 9a4612fc..67b14288 100644 --- a/CPP/7zip/Compress/BitlEncoder.h +++ b/CPP/7zip/Compress/BitlEncoder.h @@ -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 --git a/CPP/7zip/Compress/BitmDecoder.h b/CPP/7zip/Compress/BitmDecoder.h index 9ce41bd1..199a2285 100644 --- a/CPP/7zip/Compress/BitmDecoder.h +++ b/CPP/7zip/Compress/BitmDecoder.h @@ -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 @@ class CDecoder 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 @@ class CDecoder void AlignToByte() { MovePos((kNumBigValueBits - _bitPos) & 7); } - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 ReadAlignBits() { return ReadBits((kNumBigValueBits - _bitPos) & 7); } }; diff --git a/CPP/7zip/Compress/BitmEncoder.h b/CPP/7zip/Compress/BitmEncoder.h index 4499c79d..978ee1c0 100644 --- a/CPP/7zip/Compress/BitmEncoder.h +++ b/CPP/7zip/Compress/BitmEncoder.h @@ -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 --git a/CPP/7zip/Compress/BranchMisc.cpp b/CPP/7zip/Compress/BranchMisc.cpp index d0e75e83..d9fec8c5 100644 --- a/CPP/7zip/Compress/BranchMisc.cpp +++ b/CPP/7zip/Compress/BranchMisc.cpp @@ -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 --git a/CPP/7zip/Compress/BranchMisc.h b/CPP/7zip/Compress/BranchMisc.h index 66fc23d2..a5793f72 100644 --- a/CPP/7zip/Compress/BranchMisc.h +++ b/CPP/7zip/Compress/BranchMisc.h @@ -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 --git a/CPP/7zip/Compress/BranchRegister.cpp b/CPP/7zip/Compress/BranchRegister.cpp index 6331c1b9..80fbf60a 100644 --- a/CPP/7zip/Compress/BranchRegister.cpp +++ b/CPP/7zip/Compress/BranchRegister.cpp @@ -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 @@ CREATE_BRA(SPARC) #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_VAR REGISTER_CODECS(Branch) +namespace NArm64 { +REGISTER_FILTER_E(ARM64, + CDecoder(), + CEncoder(), + 0xa, "ARM64") +} + }} diff --git a/CPP/7zip/Compress/BrotliDecoder.cpp b/CPP/7zip/Compress/BrotliDecoder.cpp index 910ec4f7..4f52ebe6 100644 --- a/CPP/7zip/Compress/BrotliDecoder.cpp +++ b/CPP/7zip/Compress/BrotliDecoder.cpp @@ -83,7 +83,7 @@ CDecoder::~CDecoder() { } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size)) { DProps *pProps = (DProps *)prop; @@ -95,7 +95,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) return S_OK; } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = BROTLIMT_THREAD_MAX; if (numThreads < 0) numThreads = 0; @@ -114,7 +114,7 @@ HRESULT CDecoder::SetOutStreamSizeResume(const UInt64 * /*outSize*/) return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 * outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 * outSize)) { _processedIn = 0; RINOK(SetOutStreamSizeResume(outSize)); @@ -162,21 +162,21 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, 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)) { SetOutStreamSize(outSize); return CodeSpec(inStream, outStream, progress); } -#ifndef NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream * inStream) +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream * inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { _inStream.Release(); return S_OK; diff --git a/CPP/7zip/Compress/BrotliDecoder.h b/CPP/7zip/Compress/BrotliDecoder.h index bfe40778..666be740 100644 --- a/CPP/7zip/Compress/BrotliDecoder.h +++ b/CPP/7zip/Compress/BrotliDecoder.h @@ -44,13 +44,16 @@ struct DProps Byte _level; }; -class CDecoder:public ICompressCoder, +class CDecoder Z7_final: + public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetCoderMt, + public ICompressSetInStream, public CMyUnknownImp { CMyComPtr < ISequentialInStream > _inStream; +public: DProps _props; UInt64 _processedIn; @@ -59,31 +62,29 @@ class CDecoder:public ICompressCoder, UInt32 _numThreads; HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); + HRESULT CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress); HRESULT SetOutStreamSizeResume(const UInt64 *outSize); -public: - - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) -#ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetCoderMt) +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM_QI_ENTRY(ICompressSetInStream) #endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_END + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - 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 (SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD (SetNumberOfThreads)(UInt32 numThreads); - -#ifndef NO_READ_FROM_CODER - STDMETHOD (SetInStream)(ISequentialInStream *inStream); - STDMETHOD (ReleaseInStream)(); + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +public: + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); +#ifndef Z7_NO_READ_FROM_CODER + Z7_IFACE_COM7_IMP(ICompressSetInStream) UInt64 GetInputProcessedSize() const { return _processedIn; } #endif - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); +public: CDecoder(); virtual ~CDecoder(); }; diff --git a/CPP/7zip/Compress/BrotliEncoder.cpp b/CPP/7zip/Compress/BrotliEncoder.cpp index 4343a848..f302ea1b 100644 --- a/CPP/7zip/Compress/BrotliEncoder.cpp +++ b/CPP/7zip/Compress/BrotliEncoder.cpp @@ -4,7 +4,7 @@ #include "BrotliEncoder.h" #include "BrotliDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NBROTLI { @@ -27,7 +27,7 @@ CEncoder::~CEncoder() BROTLIMT_freeCCtx(_ctx); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps)) { _props.clear(); @@ -96,14 +96,14 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARI return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream * outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream * outStream)) { return WriteStream(outStream, &_props, sizeof (_props)); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /*inSize*/ , - const UInt64 * /*outSize */, ICompressProgressInfo *progress) + const UInt64 * /*outSize */, ICompressProgressInfo *progress)) { BROTLIMT_RdWr_t rdwr; size_t result; @@ -119,10 +119,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, Rd.processedOut = &_processedOut; struct BrotliStream Wr; -// if (_processedIn == 0) - Wr.progress = progress; -// else -// Wr.progress = 0; + Wr.progress = progress; Wr.inStream = inStream; Wr.outStream = outStream; Wr.processedIn = &_processedIn; @@ -152,7 +149,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, return res; } -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = BROTLIMT_THREAD_MAX; if (numThreads < 0) numThreads = 0; diff --git a/CPP/7zip/Compress/BrotliEncoder.h b/CPP/7zip/Compress/BrotliEncoder.h index c207069a..bfcf42c0 100644 --- a/CPP/7zip/Compress/BrotliEncoder.h +++ b/CPP/7zip/Compress/BrotliEncoder.h @@ -11,7 +11,7 @@ #include "../ICoder.h" #include "../Common/StreamUtils.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NBROTLI { @@ -31,15 +31,15 @@ struct CProps Byte _level; }; -class CEncoder: +class CEncoder Z7_final: public ICompressCoder, + public ICompressWriteCoderProperties, public ICompressSetCoderMt, public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, public CMyUnknownImp { +public: CProps _props; - UInt64 _processedIn; UInt64 _processedOut; UInt32 _inputSize; @@ -47,27 +47,24 @@ class CEncoder: Int32 _Long; Int32 _WindowLog; - - BROTLIMT_CCtx *_ctx; - -public: - UInt64 unpackSize; - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_ENTRY(ICompressWriteCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE + BROTLIMT_CCtx *_ctx; - 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 (SetNumberOfThreads)(UInt32 numThreads); + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressWriteCoderProperties) + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_ENTRY(ICompressSetCoderProperties) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE +public: + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties) + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff --git a/CPP/7zip/Compress/BrotliRegister.cpp b/CPP/7zip/Compress/BrotliRegister.cpp index e64cb6b3..4fe650f0 100644 --- a/CPP/7zip/Compress/BrotliRegister.cpp +++ b/CPP/7zip/Compress/BrotliRegister.cpp @@ -6,7 +6,7 @@ #include "BrotliDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "BrotliEncoder.h" #endif diff --git a/CPP/7zip/Compress/ByteSwap.cpp b/CPP/7zip/Compress/ByteSwap.cpp index 4c11806e..cc28d8b9 100644 --- a/CPP/7zip/Compress/ByteSwap.cpp +++ b/CPP/7zip/Compress/ByteSwap.cpp @@ -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 --git a/CPP/7zip/Compress/Codec.def b/CPP/7zip/Compress/Codec.def index f55b2d57..e2bc0dfd 100644 --- a/CPP/7zip/Compress/Codec.def +++ b/CPP/7zip/Compress/Codec.def @@ -4,3 +4,4 @@ EXPORTS GetMethodProperty PRIVATE CreateDecoder PRIVATE CreateEncoder PRIVATE + GetModuleProp PRIVATE diff --git a/CPP/7zip/Compress/CodecExports.cpp b/CPP/7zip/Compress/CodecExports.cpp index 5bb6ff8d..e37ae143 100644 --- a/CPP/7zip/Compress/CodecExports.cpp +++ b/CPP/7zip/Compress/CodecExports.cpp @@ -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 @@ extern const CHasherInfo *g_Hashers[]; 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 @@ static HRESULT MethodToClassID(UInt16 typeId, CMethodId id, PROPVARIANT *value) 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 @@ static HRESULT FindCodecClassId(const GUID *clsid, bool isCoder2, bool isFilter, 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 @@ static HRESULT FindCodecClassId(const GUID *clsid, bool isCoder2, bool isFilter, if (codec.NumStreams == 1 ? isCoder2 : !isCoder2) return E_NOINTERFACE; - index = i; + index = (int)i; return S_OK; } @@ -169,7 +171,7 @@ STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject) 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 @@ STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject) 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 GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value) } -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 @@ static int FindHasherClassId(const GUID *clsid) throw() 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); 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 @@ STDAPI GetHasherProp(UInt32 codecIndex, PROPID propID, PROPVARIANT *value) 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 @@ STDAPI GetHashers(IHashers **hashers) 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 --git a/CPP/7zip/Compress/CopyCoder.cpp b/CPP/7zip/Compress/CopyCoder.cpp index a49bba8a..b779e08b 100644 --- a/CPP/7zip/Compress/CopyCoder.cpp +++ b/CPP/7zip/Compress/CopyCoder.cpp @@ -15,15 +15,15 @@ CCopyCoder::~CCopyCoder() ::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 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, { 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 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, return E_FAIL; // internal code failure pos += processed; TotalSize += processed; - RINOK(res); + RINOK(res) if (processed == 0) return E_FAIL; } @@ -90,32 +95,32 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, 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 @@ STDMETHODIMP CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize) return res; } -STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value) +Z7_COM7F_IMF(CCopyCoder::GetInStreamProcessedSize(UInt64 *value)) { *value = TotalSize; return S_OK; @@ -141,7 +146,7 @@ HRESULT CopyStream_ExactSize(ISequentialInStream *inStream, ISequentialOutStream { 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 --git a/CPP/7zip/Compress/CopyCoder.h b/CPP/7zip/Compress/CopyCoder.h index a9d0b6db..cb93e4ee 100644 --- a/CPP/7zip/Compress/CopyCoder.h +++ b/CPP/7zip/Compress/CopyCoder.h @@ -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 --git a/CPP/7zip/Compress/Deflate64Register.cpp b/CPP/7zip/Compress/Deflate64Register.cpp index 14d20bb3..7f6bae0e 100644 --- a/CPP/7zip/Compress/Deflate64Register.cpp +++ b/CPP/7zip/Compress/Deflate64Register.cpp @@ -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 @@ namespace NDeflate { 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 --git a/CPP/7zip/Compress/DeflateConst.h b/CPP/7zip/Compress/DeflateConst.h index cfbbf886..a73d8ff0 100644 --- a/CPP/7zip/Compress/DeflateConst.h +++ b/CPP/7zip/Compress/DeflateConst.h @@ -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 --git a/CPP/7zip/Compress/DeflateDecoder.cpp b/CPP/7zip/Compress/DeflateDecoder.cpp index e4f66b7d..017b6944 100644 --- a/CPP/7zip/Compress/DeflateDecoder.cpp +++ b/CPP/7zip/Compress/DeflateDecoder.cpp @@ -83,7 +83,7 @@ bool CCoder::ReadTables(void) 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 @@ bool CCoder::ReadTables(void) } 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 @@ bool CCoder::ReadTables(void) 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 @@ bool CCoder::ReadTables(void) 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 @@ bool CCoder::ReadTables(void) 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 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro 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 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro 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 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro } -#ifdef _NO_EXCEPTIONS +#ifdef Z7_NO_EXCEPTIONS #define DEFLATE_TRY_BEGIN #define DEFLATE_TRY_END(res) @@ -361,7 +361,7 @@ HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo 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 @@ HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo { 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::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo } -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 @@ HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStr } -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::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *proces } -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::SetInStream(ISequentialInStream *inStream) } -STDMETHODIMP CCoder::ReleaseInStream() +Z7_COM7F_IMF(CCoder::ReleaseInStream()) { m_InStreamRef.Release(); return S_OK; @@ -468,7 +468,7 @@ void CCoder::SetOutStreamSizeResume(const UInt64 *outSize) } -STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CCoder::SetOutStreamSize(const UInt64 *outSize)) { /* 18.06: @@ -484,9 +484,9 @@ STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize) } -#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 @@ STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) DEFLATE_TRY_END(res) { - HRESULT res2 = Flush(); + const HRESULT res2 = Flush(); if (res2 != S_OK) res = res2; } diff --git a/CPP/7zip/Compress/DeflateDecoder.h b/CPP/7zip/Compress/DeflateDecoder.h index 141184ef..d31f2995 100644 --- a/CPP/7zip/Compress/DeflateDecoder.h +++ b/CPP/7zip/Compress/DeflateDecoder.h @@ -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 @@ class CCoder: 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 @@ class CCoder: 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 --git a/CPP/7zip/Compress/DeflateEncoder.cpp b/CPP/7zip/Compress/DeflateEncoder.cpp index 8168ec78..e277ad60 100644 --- a/CPP/7zip/Compress/DeflateEncoder.cpp +++ b/CPP/7zip/Compress/DeflateEncoder.cpp @@ -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 @@ CCoder::CCoder(bool deflate64Mode): 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 @@ HRESULT CCoder::Create() { _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 @@ HRESULT CCoder::BaseSetEncoderProperties2(const PROPID *propIDs, const PROPVARIA 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou 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 @@ HRESULT CCoder::BaseCode(ISequentialInStream *inStream, ISequentialOutStream *ou 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 --git a/CPP/7zip/Compress/DeflateEncoder.h b/CPP/7zip/Compress/DeflateEncoder.h index 94d250ec..be181e15 100644 --- a/CPP/7zip/Compress/DeflateEncoder.h +++ b/CPP/7zip/Compress/DeflateEncoder.h @@ -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 CCoder }; -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 --git a/CPP/7zip/Compress/DeflateRegister.cpp b/CPP/7zip/Compress/DeflateRegister.cpp index 387be6ed..eaedb84a 100644 --- a/CPP/7zip/Compress/DeflateRegister.cpp +++ b/CPP/7zip/Compress/DeflateRegister.cpp @@ -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 @@ namespace NDeflate { 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 --git a/CPP/7zip/Compress/DeltaFilter.cpp b/CPP/7zip/Compress/DeltaFilter.cpp index 3986ae4f..35b77ba7 100644 --- a/CPP/7zip/Compress/DeltaFilter.cpp +++ b/CPP/7zip/Compress/DeltaFilter.cpp @@ -23,41 +23,40 @@ struct CDelta }; -#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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA 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 --git a/CPP/7zip/Compress/FastLzma2Register.cpp b/CPP/7zip/Compress/FastLzma2Register.cpp index b1ba9870..80cb0b28 100644 --- a/CPP/7zip/Compress/FastLzma2Register.cpp +++ b/CPP/7zip/Compress/FastLzma2Register.cpp @@ -6,7 +6,7 @@ #include "Lzma2Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "Lzma2Encoder.h" #endif diff --git a/CPP/7zip/Compress/HuffmanDecoder.h b/CPP/7zip/Compress/HuffmanDecoder.h index f0529876..4b8169f5 100644 --- a/CPP/7zip/Compress/HuffmanDecoder.h +++ b/CPP/7zip/Compress/HuffmanDecoder.h @@ -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 @@ class CDecoder template - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 Decode(TBitDecoder *bitStream) const { UInt32 val = bitStream->GetValue(kNumBitsMax); @@ -166,7 +166,7 @@ class CDecoder template - MY_FORCE_INLINE + Z7_FORCE_INLINE UInt32 DecodeFull(TBitDecoder *bitStream) const { UInt32 val = bitStream->GetValue(kNumBitsMax); diff --git a/CPP/7zip/Compress/ImplodeDecoder.cpp b/CPP/7zip/Compress/ImplodeDecoder.cpp index 97a3cdf7..12f2dce5 100644 --- a/CPP/7zip/Compress/ImplodeDecoder.cpp +++ b/CPP/7zip/Compress/ImplodeDecoder.cpp @@ -49,7 +49,7 @@ bool CHuffmanDecoder::Build(const Byte *lens, unsigned numSymbols) throw() 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 @@ bool CHuffmanDecoder::Build(const Byte *lens, unsigned numSymbols) throw() 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 @@ bool CCoder::BuildHuff(CHuffmanDecoder &decoder, unsigned numSymbols) 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou } 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 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou } -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::Code(ISequentialInStream *inStream, ISequentialOutStream *o } -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::SetDecoderProperties2(const Byte *data, UInt32 size) } -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 --git a/CPP/7zip/Compress/ImplodeDecoder.h b/CPP/7zip/Compress/ImplodeDecoder.h index a73c143c..ec700454 100644 --- a/CPP/7zip/Compress/ImplodeDecoder.h +++ b/CPP/7zip/Compress/ImplodeDecoder.h @@ -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 CHuffmanDecoder }; -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 @@ class CCoder: 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 --git a/CPP/7zip/Compress/ImplodeHuffmanDecoder.h b/CPP/7zip/Compress/ImplodeHuffmanDecoder.h index ea25211a..dcf8ac6b 100644 --- a/CPP/7zip/Compress/ImplodeHuffmanDecoder.h +++ b/CPP/7zip/Compress/ImplodeHuffmanDecoder.h @@ -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 --git a/CPP/7zip/Compress/LizardDecoder.cpp b/CPP/7zip/Compress/LizardDecoder.cpp index 2cf59f78..d77c82dc 100644 --- a/CPP/7zip/Compress/LizardDecoder.cpp +++ b/CPP/7zip/Compress/LizardDecoder.cpp @@ -83,7 +83,7 @@ CDecoder::~CDecoder() { } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size)) { DProps *pProps = (DProps *)prop; @@ -95,7 +95,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) return S_OK; } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LIZARDMT_THREAD_MAX; if (numThreads < 1) numThreads = 1; @@ -110,7 +110,7 @@ HRESULT CDecoder::SetOutStreamSizeResume(const UInt64 * /*outSize*/) return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 * outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 * outSize)) { _processedIn = 0; RINOK(SetOutStreamSizeResume(outSize)); @@ -158,21 +158,21 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, 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)) { SetOutStreamSize(outSize); return CodeSpec(inStream, outStream, progress); } -#ifndef NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream * inStream) +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream * inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { _inStream.Release(); return S_OK; diff --git a/CPP/7zip/Compress/LizardDecoder.h b/CPP/7zip/Compress/LizardDecoder.h index 8c3a1b97..bcddd21e 100644 --- a/CPP/7zip/Compress/LizardDecoder.h +++ b/CPP/7zip/Compress/LizardDecoder.h @@ -46,13 +46,15 @@ struct DProps Byte _level; }; -class CDecoder:public ICompressCoder, +class CDecoder Z7_final: + public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetCoderMt, public CMyUnknownImp { CMyComPtr < ISequentialInStream > _inStream; +public: DProps _props; UInt64 _processedIn; @@ -61,31 +63,30 @@ class CDecoder:public ICompressCoder, UInt32 _numThreads; HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); + HRESULT CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress); HRESULT SetOutStreamSizeResume(const UInt64 *outSize); -public: - - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) -#ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) +#ifndef Z7_NO_READ_FROM_CODER + //Z7_COM_QI_ENTRY(ICompressSetInStream) #endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_END + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - 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 (SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD (SetNumberOfThreads)(UInt32 numThreads); - -#ifndef NO_READ_FROM_CODER - STDMETHOD (SetInStream)(ISequentialInStream *inStream); - STDMETHOD (ReleaseInStream)(); + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +public: + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM7F_IMF(SetInStream(ISequentialInStream *inStream)); + Z7_COM7F_IMF(ReleaseInStream()); UInt64 GetInputProcessedSize() const { return _processedIn; } #endif - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); +public: CDecoder(); virtual ~CDecoder(); }; diff --git a/CPP/7zip/Compress/LizardEncoder.cpp b/CPP/7zip/Compress/LizardEncoder.cpp index f5c5ad12..927b59a9 100644 --- a/CPP/7zip/Compress/LizardEncoder.cpp +++ b/CPP/7zip/Compress/LizardEncoder.cpp @@ -4,7 +4,7 @@ #include "LizardEncoder.h" #include "LizardDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLIZARD { @@ -24,7 +24,7 @@ CEncoder::~CEncoder() LIZARDMT_freeCCtx(_ctx); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps)) { _props.clear(); @@ -63,14 +63,14 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARI return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream * outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream * outStream)) { return WriteStream(outStream, &_props, sizeof (_props)); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /*inSize*/ , - const UInt64 * /*outSize */, ICompressProgressInfo *progress) + const UInt64 * /*outSize */, ICompressProgressInfo *progress)) { LIZARDMT_RdWr_t rdwr; size_t result; @@ -115,7 +115,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, return res; } -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LIZARDMT_THREAD_MAX; if (numThreads < 1) numThreads = 1; diff --git a/CPP/7zip/Compress/LizardEncoder.h b/CPP/7zip/Compress/LizardEncoder.h index 541a9130..474187cd 100644 --- a/CPP/7zip/Compress/LizardEncoder.h +++ b/CPP/7zip/Compress/LizardEncoder.h @@ -12,7 +12,7 @@ #include "../ICoder.h" #include "../Common/StreamUtils.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLIZARD { @@ -32,13 +32,14 @@ struct CProps Byte _level; }; -class CEncoder: - public ICompressCoder, - public ICompressSetCoderMt, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_4( + CEncoder, + ICompressCoder, + ICompressSetCoderMt, + ICompressSetCoderProperties, + ICompressWriteCoderProperties +) +public: CProps _props; UInt64 _processedIn; @@ -48,21 +49,8 @@ class CEncoder: LIZARDMT_CCtx *_ctx; -public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_ENTRY(ICompressWriteCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - 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 (SetNumberOfThreads)(UInt32 numThreads); - CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff --git a/CPP/7zip/Compress/LizardRegister.cpp b/CPP/7zip/Compress/LizardRegister.cpp index 836d2703..05996413 100644 --- a/CPP/7zip/Compress/LizardRegister.cpp +++ b/CPP/7zip/Compress/LizardRegister.cpp @@ -6,7 +6,7 @@ #include "LizardDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "LizardEncoder.h" #endif diff --git a/CPP/7zip/Compress/Lz4Decoder.cpp b/CPP/7zip/Compress/Lz4Decoder.cpp index cb88d086..5035be0e 100644 --- a/CPP/7zip/Compress/Lz4Decoder.cpp +++ b/CPP/7zip/Compress/Lz4Decoder.cpp @@ -83,7 +83,7 @@ CDecoder::~CDecoder() { } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size)) { DProps *pProps = (DProps *)prop; @@ -99,7 +99,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) } } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LZ4MT_THREAD_MAX; if (numThreads < 1) numThreads = 1; @@ -114,10 +114,10 @@ HRESULT CDecoder::SetOutStreamSizeResume(const UInt64 * /*outSize*/) return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 * outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 * outSize)) { _processedIn = 0; - RINOK(SetOutStreamSizeResume(outSize)); + RINOK(SetOutStreamSizeResume(outSize)) return S_OK; } @@ -162,21 +162,21 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, 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)) { SetOutStreamSize(outSize); return CodeSpec(inStream, outStream, progress); } -#ifndef NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream * inStream) +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream * inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { _inStream.Release(); return S_OK; @@ -185,7 +185,7 @@ STDMETHODIMP CDecoder::ReleaseInStream() HRESULT CDecoder::CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress) { - RINOK(SetOutStreamSizeResume(outSize)); + RINOK(SetOutStreamSizeResume(outSize)) return CodeSpec(_inStream, outStream, progress); } diff --git a/CPP/7zip/Compress/Lz4Decoder.h b/CPP/7zip/Compress/Lz4Decoder.h index ab55ef3c..cdf635d9 100644 --- a/CPP/7zip/Compress/Lz4Decoder.h +++ b/CPP/7zip/Compress/Lz4Decoder.h @@ -45,13 +45,15 @@ struct DProps Byte _reserved[2]; }; -class CDecoder:public ICompressCoder, +class CDecoder Z7_final: + public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetCoderMt, public CMyUnknownImp { CMyComPtr < ISequentialInStream > _inStream; +public: DProps _props; UInt64 _processedIn; @@ -60,31 +62,27 @@ class CDecoder:public ICompressCoder, UInt32 _numThreads; HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); + HRESULT CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress); HRESULT SetOutStreamSizeResume(const UInt64 *outSize); -public: - - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) -#ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) -#endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_END + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - 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 (SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD (SetNumberOfThreads)(UInt32 numThreads); - -#ifndef NO_READ_FROM_CODER - STDMETHOD (SetInStream)(ISequentialInStream *inStream); - STDMETHOD (ReleaseInStream)(); + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +public: + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM7F_IMF(SetInStream(ISequentialInStream *inStream)); + Z7_COM7F_IMF(ReleaseInStream()); UInt64 GetInputProcessedSize() const { return _processedIn; } #endif - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); +public: CDecoder(); virtual ~CDecoder(); }; diff --git a/CPP/7zip/Compress/Lz4Encoder.cpp b/CPP/7zip/Compress/Lz4Encoder.cpp index 8ef855ce..7bd9a016 100644 --- a/CPP/7zip/Compress/Lz4Encoder.cpp +++ b/CPP/7zip/Compress/Lz4Encoder.cpp @@ -4,7 +4,7 @@ #include "Lz4Encoder.h" #include "Lz4Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLZ4 { @@ -24,7 +24,7 @@ CEncoder::~CEncoder() LZ4MT_freeCCtx(_ctx); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps)) { _props.clear(); @@ -62,14 +62,14 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARI return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream * outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream * outStream)) { return WriteStream(outStream, &_props, sizeof (_props)); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /*inSize*/ , - const UInt64 * /*outSize */, ICompressProgressInfo *progress) + const UInt64 * /*outSize */, ICompressProgressInfo *progress)) { LZ4MT_RdWr_t rdwr; size_t result; @@ -114,7 +114,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, return res; } -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LZ4MT_THREAD_MAX; if (numThreads < 1) numThreads = 1; diff --git a/CPP/7zip/Compress/Lz4Encoder.h b/CPP/7zip/Compress/Lz4Encoder.h index 3b3abfff..95a8050b 100644 --- a/CPP/7zip/Compress/Lz4Encoder.h +++ b/CPP/7zip/Compress/Lz4Encoder.h @@ -11,7 +11,7 @@ #include "../ICoder.h" #include "../Common/StreamUtils.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLZ4 { @@ -32,13 +32,14 @@ struct CProps Byte _reserved[2]; }; -class CEncoder: - public ICompressCoder, - public ICompressSetCoderMt, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_4( + CEncoder, + ICompressCoder, + ICompressSetCoderMt, + ICompressSetCoderProperties, + ICompressWriteCoderProperties +) +public: CProps _props; UInt64 _processedIn; @@ -48,21 +49,8 @@ class CEncoder: LZ4MT_CCtx *_ctx; -public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_ENTRY(ICompressWriteCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - 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 (SetNumberOfThreads)(UInt32 numThreads); - CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff --git a/CPP/7zip/Compress/Lz4Register.cpp b/CPP/7zip/Compress/Lz4Register.cpp index a6c237a8..5fa314eb 100644 --- a/CPP/7zip/Compress/Lz4Register.cpp +++ b/CPP/7zip/Compress/Lz4Register.cpp @@ -5,13 +5,17 @@ #include "../Common/RegisterCodec.h" #include "Lz4Decoder.h" - -#ifndef EXTRACT_ONLY +#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_LZ4_EXTRACT_ONLY) #include "Lz4Encoder.h" #endif +namespace NCompress { +namespace NLZ4 { + REGISTER_CODEC_E( LZ4, NCompress::NLZ4::CDecoder(), NCompress::NLZ4::CEncoder(), 0x4F71104, "LZ4") + +}} diff --git a/CPP/7zip/Compress/Lz5Decoder.cpp b/CPP/7zip/Compress/Lz5Decoder.cpp index 5ec807cb..768174e5 100644 --- a/CPP/7zip/Compress/Lz5Decoder.cpp +++ b/CPP/7zip/Compress/Lz5Decoder.cpp @@ -83,7 +83,7 @@ CDecoder::~CDecoder() { } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size)) { DProps *pProps = (DProps *)prop; @@ -99,7 +99,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) } } -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LZ5MT_THREAD_MAX; if (numThreads < 1) numThreads = 1; @@ -114,7 +114,7 @@ HRESULT CDecoder::SetOutStreamSizeResume(const UInt64 * /*outSize*/) return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 * outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 * outSize)) { _processedIn = 0; RINOK(SetOutStreamSizeResume(outSize)); @@ -162,21 +162,21 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, 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)) { SetOutStreamSize(outSize); return CodeSpec(inStream, outStream, progress); } -#ifndef NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream * inStream) +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream * inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { _inStream.Release(); return S_OK; diff --git a/CPP/7zip/Compress/Lz5Decoder.h b/CPP/7zip/Compress/Lz5Decoder.h index d759877e..57677966 100644 --- a/CPP/7zip/Compress/Lz5Decoder.h +++ b/CPP/7zip/Compress/Lz5Decoder.h @@ -45,13 +45,15 @@ struct DProps Byte _reserved[2]; }; -class CDecoder:public ICompressCoder, +class CDecoder Z7_final: + public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetCoderMt, public CMyUnknownImp { CMyComPtr < ISequentialInStream > _inStream; +public: DProps _props; UInt64 _processedIn; @@ -60,31 +62,30 @@ class CDecoder:public ICompressCoder, UInt32 _numThreads; HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); + HRESULT CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress); HRESULT SetOutStreamSizeResume(const UInt64 *outSize); -public: - - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) -#ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) +#ifndef Z7_NO_READ_FROM_CODER + //Z7_COM_QI_ENTRY(ICompressSetInStream) #endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_END + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE - 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 (SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD (SetNumberOfThreads)(UInt32 numThreads); - -#ifndef NO_READ_FROM_CODER - STDMETHOD (SetInStream)(ISequentialInStream *inStream); - STDMETHOD (ReleaseInStream)(); + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) +public: + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM7F_IMF(SetInStream(ISequentialInStream *inStream)); + Z7_COM7F_IMF(ReleaseInStream()); UInt64 GetInputProcessedSize() const { return _processedIn; } #endif - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); +public: CDecoder(); virtual ~CDecoder(); }; diff --git a/CPP/7zip/Compress/Lz5Encoder.cpp b/CPP/7zip/Compress/Lz5Encoder.cpp index b587aca8..e227e252 100644 --- a/CPP/7zip/Compress/Lz5Encoder.cpp +++ b/CPP/7zip/Compress/Lz5Encoder.cpp @@ -4,7 +4,7 @@ #include "Lz5Encoder.h" #include "Lz5Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLZ5 { @@ -24,7 +24,7 @@ CEncoder::~CEncoder() LZ5MT_freeCCtx(_ctx); } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps)) { _props.clear(); @@ -62,14 +62,14 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARI return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream * outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream * outStream)) { return WriteStream(outStream, &_props, sizeof (_props)); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /*inSize*/ , - const UInt64 * /*outSize */, ICompressProgressInfo *progress) + const UInt64 * /*outSize */, ICompressProgressInfo *progress)) { LZ5MT_RdWr_t rdwr; size_t result; @@ -114,7 +114,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, return res; } -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = LZ5MT_THREAD_MAX; if (numThreads < 1) numThreads = 1; diff --git a/CPP/7zip/Compress/Lz5Encoder.h b/CPP/7zip/Compress/Lz5Encoder.h index a0fec10d..d00ec4fb 100644 --- a/CPP/7zip/Compress/Lz5Encoder.h +++ b/CPP/7zip/Compress/Lz5Encoder.h @@ -11,7 +11,7 @@ #include "../ICoder.h" #include "../Common/StreamUtils.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NLZ5 { @@ -32,13 +32,14 @@ struct CProps Byte _reserved[2]; }; -class CEncoder: - public ICompressCoder, - public ICompressSetCoderMt, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_4( + CEncoder, + ICompressCoder, + ICompressSetCoderMt, + ICompressSetCoderProperties, + ICompressWriteCoderProperties +) +public: CProps _props; UInt64 _processedIn; @@ -48,21 +49,8 @@ class CEncoder: LZ5MT_CCtx *_ctx; -public: - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_ENTRY(ICompressWriteCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - 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 (SetNumberOfThreads)(UInt32 numThreads); - CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff --git a/CPP/7zip/Compress/Lz5Register.cpp b/CPP/7zip/Compress/Lz5Register.cpp index 461fe23d..edab3f62 100644 --- a/CPP/7zip/Compress/Lz5Register.cpp +++ b/CPP/7zip/Compress/Lz5Register.cpp @@ -6,7 +6,7 @@ #include "Lz5Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "Lz5Encoder.h" #endif diff --git a/CPP/7zip/Compress/LzOutWindow.cpp b/CPP/7zip/Compress/LzOutWindow.cpp index eb346407..aae02eb8 100644 --- a/CPP/7zip/Compress/LzOutWindow.cpp +++ b/CPP/7zip/Compress/LzOutWindow.cpp @@ -8,7 +8,7 @@ void CLzOutWindow::Init(bool solid) throw() { if (!solid) COutBuffer::Init(); - #ifdef _NO_EXCEPTIONS + #ifdef Z7_NO_EXCEPTIONS ErrorCode = S_OK; #endif } diff --git a/CPP/7zip/Compress/LzOutWindow.h b/CPP/7zip/Compress/LzOutWindow.h index 30ac334f..599b124e 100644 --- a/CPP/7zip/Compress/LzOutWindow.h +++ b/CPP/7zip/Compress/LzOutWindow.h @@ -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 --git a/CPP/7zip/Compress/LzfseDecoder.cpp b/CPP/7zip/Compress/LzfseDecoder.cpp index 0eb10afa..236d5bd0 100644 --- a/CPP/7zip/Compress/LzfseDecoder.cpp +++ b/CPP/7zip/Compress/LzfseDecoder.cpp @@ -293,7 +293,7 @@ static UInt32 SumFreqs(const UInt16 *freqs, unsigned num) } -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 unsigned CountZeroBits(UInt32 val, UInt32 mask) } -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 @@ typedef struct } 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 @@ static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s, 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 @@ static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s, #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 int FseInStream_Init(CBitStream *s, -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 @@ static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits) 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 @@ static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate, #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 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) 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 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) // 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 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) 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 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) // 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 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version) } -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 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr 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 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr 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 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr 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 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr 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 --git a/CPP/7zip/Compress/LzfseDecoder.h b/CPP/7zip/Compress/LzfseDecoder.h index 401e0bad..b7227dc2 100644 --- a/CPP/7zip/Compress/LzfseDecoder.h +++ b/CPP/7zip/Compress/LzfseDecoder.h @@ -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 @@ class CDecoder: 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 @@ class CDecoder: // 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 --git a/CPP/7zip/Compress/LzhDecoder.cpp b/CPP/7zip/Compress/LzhDecoder.cpp index b0aa7536..064bc556 100644 --- a/CPP/7zip/Compress/LzhDecoder.cpp +++ b/CPP/7zip/Compress/LzhDecoder.cpp @@ -15,7 +15,7 @@ static bool CheckCodeLens(const Byte *lens, unsigned num) 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 @@ bool CCoder::ReadTP(unsigned num, unsigned numBits, int spec) { _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 @@ bool CCoder::ReadTP(unsigned num, unsigned numBits, int spec) do { - UInt32 val = _inBitStream.GetValue(16); + const UInt32 val = _inBitStream.GetValue(16); unsigned c = val >> 13; if (c == 7) @@ -85,8 +86,9 @@ bool CCoder::ReadC() 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 @@ bool CCoder::ReadC() 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 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) 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 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) } -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 @@ STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *o CCoderReleaser coderReleaser(this); - RINOK(CodeReal(*outSize, progress)); + RINOK(CodeReal(*outSize, progress)) coderReleaser.Disable(); return _outWindow.Flush(); diff --git a/CPP/7zip/Compress/LzhDecoder.h b/CPP/7zip/Compress/LzhDecoder.h index 5e13d823..491212e6 100644 --- a/CPP/7zip/Compress/LzhDecoder.h +++ b/CPP/7zip/Compress/LzhDecoder.h @@ -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 NT = (NUM_CODE_BITS + 3); 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 @@ class CCoder: 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 --git a/CPP/7zip/Compress/Lzma2Decoder.cpp b/CPP/7zip/Compress/Lzma2Decoder.cpp index 653fe2de..eab78000 100644 --- a/CPP/7zip/Compress/Lzma2Decoder.cpp +++ b/CPP/7zip/Compress/Lzma2Decoder.cpp @@ -21,7 +21,7 @@ CDecoder::CDecoder(): , _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 @@ CDecoder::~CDecoder() 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::SetDecoderProperties2(const Byte *prop, UInt32 size) } -STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) +Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode)) { _finishMode = (finishMode != 0); return S_OK; @@ -56,7 +56,7 @@ STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) -#ifndef _7ZIP_ST +#ifndef Z7_ST static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize) { @@ -81,8 +81,8 @@ static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize) #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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream UInt64 inProcessed = 0; int isMT = False; - #ifndef _7ZIP_ST + #ifndef Z7_ST isMT = _tryMt; #endif @@ -162,7 +162,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream */ - #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::Code(ISequentialInStream *inStream, ISequentialOutStream } -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 @@ STDMETHODIMP CDecoder::SetMemLimit(UInt64 memUsage) #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 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) _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::SetOutStreamSize(const UInt64 *outSize) } -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 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 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 --git a/CPP/7zip/Compress/Lzma2Decoder.h b/CPP/7zip/Compress/Lzma2Decoder.h index e1414884..7ca717e7 100644 --- a/CPP/7zip/Compress/Lzma2Decoder.h +++ b/CPP/7zip/Compress/Lzma2Decoder.h @@ -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 @@ class CDecoder: 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 --git a/CPP/7zip/Compress/Lzma2Encoder.cpp b/CPP/7zip/Compress/Lzma2Encoder.cpp index 67c26cec..c3302ced 100644 --- a/CPP/7zip/Compress/Lzma2Encoder.cpp +++ b/CPP/7zip/Compress/Lzma2Encoder.cpp @@ -3,7 +3,7 @@ #include "StdAfx.h" #include "../../../C/Alloc.h" - +#include "../../../C/Lzma2Enc.h" #include "../../../C/fast-lzma2/fl2_errors.h" #include "../Common/CWrappers.h" @@ -58,33 +58,33 @@ HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzm 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); @@ -93,9 +93,9 @@ STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, } -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); } @@ -103,8 +103,8 @@ STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) #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; @@ -126,10 +126,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream return SResToHRESULT(res); } - // Fast LZMA2 encoder - - static HRESULT TranslateError(size_t res) { if (FL2_getErrorCode(res) == FL2_error_memory_allocation) @@ -213,7 +210,7 @@ HRESULT CFastEncoder::FastLzma2::SetCoderProperties(const PROPID *propIDs, const CHECK_P(FL2_CCtx_setParameter(fcs, FL2_p_posBits, lzma2Props.lzmaProps.pb)); if (lzma2Props.blockSize == 0) lzma2Props.blockSize = min(max(MIN_BLOCK_SIZE, dictSize * 4U), MAX_BLOCK_SIZE); - else if (lzma2Props.blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) + else if (lzma2Props.blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID) lzma2Props.blockSize = 0; unsigned r = 0; if (lzma2Props.blockSize != 0) { @@ -334,25 +331,14 @@ void CFastEncoder::FastLzma2::Cancel() FL2_cancelCStream(fcs); } -CFastEncoder::CFastEncoder() -{ -} - -CFastEncoder::~CFastEncoder() -{ -} - - -STDMETHODIMP CFastEncoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *coderProps, UInt32 numProps) +Z7_COM7F_IMF(CFastEncoder::SetCoderProperties(const PROPID *propIDs, + const PROPVARIANT *coderProps, UInt32 numProps)) { return _encoder.SetCoderProperties(propIDs, coderProps, numProps); } - #define LZMA2_DIC_SIZE_FROM_PROP(p) (((UInt32)2 | ((p) & 1)) << ((p) / 2 + 11)) - -STDMETHODIMP CFastEncoder::WriteCoderProperties(ISequentialOutStream *outStream) +Z7_COM7F_IMF(CFastEncoder::WriteCoderProperties(ISequentialOutStream *outStream)) { Byte prop; unsigned i; @@ -365,8 +351,8 @@ STDMETHODIMP CFastEncoder::WriteCoderProperties(ISequentialOutStream *outStream) } -STDMETHODIMP CFastEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) +Z7_COM7F_IMF(CFastEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)) { CHECK_H(_encoder.Begin()); size_t inSize; diff --git a/CPP/7zip/Compress/Lzma2Encoder.h b/CPP/7zip/Compress/Lzma2Encoder.h index 3211a1d6..68060ca0 100644 --- a/CPP/7zip/Compress/Lzma2Encoder.h +++ b/CPP/7zip/Compress/Lzma2Encoder.h @@ -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" #include "../../../C/fast-lzma2/fast-lzma2.h" @@ -14,37 +14,36 @@ 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); +public: CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; -class CFastEncoder : +class CFastEncoder Z7_final: public ICompressCoder, public ICompressSetCoderProperties, public ICompressWriteCoderProperties, public CMyUnknownImp { + Z7_COM_UNKNOWN_IMP_3( + ICompressCoder, + ICompressSetCoderProperties, + ICompressWriteCoderProperties) + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetCoderProperties) + Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties) + +public: class FastLzma2 { public: @@ -72,20 +71,6 @@ class CFastEncoder : }; FastLzma2 _encoder; - -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); - - CFastEncoder(); - virtual ~CFastEncoder(); }; }} diff --git a/CPP/7zip/Compress/Lzma2Register.cpp b/CPP/7zip/Compress/Lzma2Register.cpp index 8f279ebf..fe533463 100644 --- a/CPP/7zip/Compress/Lzma2Register.cpp +++ b/CPP/7zip/Compress/Lzma2Register.cpp @@ -6,7 +6,7 @@ #include "Lzma2Decoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "Lzma2Encoder.h" #endif diff --git a/CPP/7zip/Compress/LzmaDecoder.cpp b/CPP/7zip/Compress/LzmaDecoder.cpp index a25d36d1..4f05b483 100644 --- a/CPP/7zip/Compress/LzmaDecoder.cpp +++ b/CPP/7zip/Compress/LzmaDecoder.cpp @@ -25,14 +25,14 @@ namespace NCompress { 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 @@ CDecoder::CDecoder(): _alloc.numAlignBits = 7; _alloc.offset = 0; */ - LzmaDec_Construct(&_state); + LzmaDec_CONSTRUCT(&_state) } CDecoder::~CDecoder() @@ -51,8 +51,10 @@ CDecoder::~CDecoder() 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 @@ HRESULT CDecoder::CreateInputBuffer() } -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 @@ void CDecoder::SetOutStreamSizeResume(const UInt64 *outSize) } -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::SetOutStreamSize(const UInt64 *outSize) } -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 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream * _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 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream } -#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 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 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::CodeResume(ISequentialOutStream *outStream, const UInt64 *outS HRESULT CDecoder::ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize) { - RINOK(CreateInputBuffer()); + RINOK(CreateInputBuffer()) if (processedSize) *processedSize = 0; diff --git a/CPP/7zip/Compress/LzmaDecoder.h b/CPP/7zip/Compress/LzmaDecoder.h index 37dec025..095e76ff 100644 --- a/CPP/7zip/Compress/LzmaDecoder.h +++ b/CPP/7zip/Compress/LzmaDecoder.h @@ -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: + 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: - bool FinishStream; // set it before decoding, if you need to decode full LZMA stream + 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 @@ class CDecoder: 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 --git a/CPP/7zip/Compress/LzmaEncoder.cpp b/CPP/7zip/Compress/LzmaEncoder.cpp index dabd77a0..08e3ba53 100644 --- a/CPP/7zip/Compress/LzmaEncoder.cpp +++ b/CPP/7zip/Compress/LzmaEncoder.cpp @@ -48,12 +48,12 @@ static inline wchar_t GetLowCharFast(wchar_t c) 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 @@ static int ParseMatchFinder(const wchar_t *s, int *btMode, int *numHashBytes) { 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 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep) 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 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep) 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 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep) 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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, 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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, 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::SetCoderPropertiesOpt(const PROPID *propIDs, } -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 @@ static void PrintStat(HANDLE thread, UInt64 totalTime, const CBaseStat *prevStat -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 --git a/CPP/7zip/Compress/LzmaEncoder.h b/CPP/7zip/Compress/LzmaEncoder.h index 7d706ad7..2836d7df 100644 --- a/CPP/7zip/Compress/LzmaEncoder.h +++ b/CPP/7zip/Compress/LzmaEncoder.h @@ -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 --git a/CPP/7zip/Compress/LzmaRegister.cpp b/CPP/7zip/Compress/LzmaRegister.cpp index c802a99f..887f7a2d 100644 --- a/CPP/7zip/Compress/LzmaRegister.cpp +++ b/CPP/7zip/Compress/LzmaRegister.cpp @@ -6,7 +6,7 @@ #include "LzmaDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "LzmaEncoder.h" #endif diff --git a/CPP/7zip/Compress/LzmsDecoder.cpp b/CPP/7zip/Compress/LzmsDecoder.cpp index e27afa3c..38c04081 100644 --- a/CPP/7zip/Compress/LzmsDecoder.cpp +++ b/CPP/7zip/Compress/LzmsDecoder.cpp @@ -77,7 +77,7 @@ static unsigned GetNumPosSlots(size_t size) 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 @@ static void x86_Filter(Byte *data, UInt32 size, Int32 *history) Int32 maxTransOffset = k_x86_TransOffset; - Byte b = p[0]; + const Byte b = p[0]; if (b == 0x48) { @@ -202,8 +202,8 @@ static void x86_Filter(Byte *data, UInt32 size, Int32 *history) 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 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out 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 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out 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 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out } 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 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out 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 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out 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 --git a/CPP/7zip/Compress/LzmsDecoder.h b/CPP/7zip/Compress/LzmsDecoder.h index f0909a1e..e173c975 100644 --- a/CPP/7zip/Compress/LzmsDecoder.h +++ b/CPP/7zip/Compress/LzmsDecoder.h @@ -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 @@ struct CProbEntry 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 --git a/CPP/7zip/Compress/Lzx.h b/CPP/7zip/Compress/Lzx.h index 29ca4cac..2532088f 100644 --- a/CPP/7zip/Compress/Lzx.h +++ b/CPP/7zip/Compress/Lzx.h @@ -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 --git a/CPP/7zip/Compress/LzxDecoder.cpp b/CPP/7zip/Compress/LzxDecoder.cpp index e59cd400..b50d8633 100644 --- a/CPP/7zip/Compress/LzxDecoder.cpp +++ b/CPP/7zip/Compress/LzxDecoder.cpp @@ -27,7 +27,7 @@ static void x86_Filter(Byte *data, UInt32 size, UInt32 processedSize, UInt32 tra 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 @@ static void x86_Filter(Byte *data, UInt32 size, UInt32 processedSize, UInt32 tra if (v >= pos && v < (Int32)translationSize) { v += (v >= 0 ? pos : (Int32)translationSize); - SetUi32(p, (UInt32)v); + SetUi32(p, (UInt32)v) } } } @@ -88,7 +88,7 @@ HRESULT CDecoder::Flush() 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 @@ bool CDecoder::ReadTable(Byte *levels, unsigned numSymbols) 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 @@ bool CDecoder::ReadTable(Byte *levels, unsigned numSymbols) else return false; - unsigned limit = i + num; + const unsigned limit = i + num; if (limit > numSymbols) return false; @@ -188,7 +188,7 @@ bool CDecoder::ReadTables(void) _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 @@ bool CDecoder::ReadTables(void) 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 @@ bool CDecoder::ReadTables(void) _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 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize) 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 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize) 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 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize) 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 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize) } 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 @@ HRESULT CDecoder::Code(const Byte *inData, size_t inSize, UInt32 outSize) _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 @@ HRESULT CDecoder::SetParams2(unsigned numDictBits) _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::SetParams2(unsigned numDictBits) 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 --git a/CPP/7zip/Compress/LzxDecoder.h b/CPP/7zip/Compress/LzxDecoder.h index 4d70b272..ab114e53 100644 --- a/CPP/7zip/Compress/LzxDecoder.h +++ b/CPP/7zip/Compress/LzxDecoder.h @@ -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 CBitDecoder }; -class CDecoder: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CDecoder +) CBitDecoder _bitStream; Byte *_win; UInt32 _pos; @@ -220,8 +219,6 @@ class CDecoder: CDecoder(bool wimMode = false); ~CDecoder(); - MY_UNKNOWN_IMP - HRESULT SetExternalWindow(Byte *win, unsigned numDictBits) { NeedAlloc = false; diff --git a/CPP/7zip/Compress/Mtf8.h b/CPP/7zip/Compress/Mtf8.h index 50a84cee..1b44d00f 100644 --- a/CPP/7zip/Compress/Mtf8.h +++ b/CPP/7zip/Compress/Mtf8.h @@ -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 @@ struct CMtf8Encoder { 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 @@ struct CMtf8Decoder #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 @@ struct CMtf8Decoder { 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 @@ struct CMtf8Decoder 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 --git a/CPP/7zip/Compress/PpmdDecoder.cpp b/CPP/7zip/Compress/PpmdDecoder.cpp index 7f54ec3b..1238df60 100644 --- a/CPP/7zip/Compress/PpmdDecoder.cpp +++ b/CPP/7zip/Compress/PpmdDecoder.cpp @@ -1,5 +1,4 @@ // PpmdDecoder.cpp -// 2020-07-03 : Igor Pavlov : Public domain #include "StdAfx.h" @@ -29,14 +28,13 @@ CDecoder::~CDecoder() 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 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size) 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 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size) 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 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size) 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 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size) */ } - 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 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size) -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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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::Code(ISequentialInStream *inStream, ISequentialOutStream } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize)) { _outSizeDefined = (outSize != NULL); if (_outSizeDefined) @@ -179,37 +177,37 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 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 --git a/CPP/7zip/Compress/PpmdDecoder.h b/CPP/7zip/Compress/PpmdDecoder.h index f1a8ee21..22e5bd49 100644 --- a/CPP/7zip/Compress/PpmdDecoder.h +++ b/CPP/7zip/Compress/PpmdDecoder.h @@ -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 @@ class CDecoder : 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 --git a/CPP/7zip/Compress/PpmdEncoder.cpp b/CPP/7zip/Compress/PpmdEncoder.cpp index d41d2aca..2dfca6df 100644 --- a/CPP/7zip/Compress/PpmdEncoder.cpp +++ b/CPP/7zip/Compress/PpmdEncoder.cpp @@ -24,7 +24,7 @@ void CEncProps::Normalize(int level) 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 @@ CEncoder::~CEncoder() 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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA 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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA 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 @@ HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outS 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 @@ HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outS */ 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 --git a/CPP/7zip/Compress/PpmdEncoder.h b/CPP/7zip/Compress/PpmdEncoder.h index 0104663f..057cccbe 100644 --- a/CPP/7zip/Compress/PpmdEncoder.h +++ b/CPP/7zip/Compress/PpmdEncoder.h @@ -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 @@ struct CEncProps 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 --git a/CPP/7zip/Compress/PpmdRegister.cpp b/CPP/7zip/Compress/PpmdRegister.cpp index a3ebb5f3..fb5619c9 100644 --- a/CPP/7zip/Compress/PpmdRegister.cpp +++ b/CPP/7zip/Compress/PpmdRegister.cpp @@ -6,7 +6,7 @@ #include "PpmdDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "PpmdEncoder.h" #endif diff --git a/CPP/7zip/Compress/PpmdZip.cpp b/CPP/7zip/Compress/PpmdZip.cpp index 434e143b..5039131e 100644 --- a/CPP/7zip/Compress/PpmdZip.cpp +++ b/CPP/7zip/Compress/PpmdZip.cpp @@ -24,8 +24,8 @@ CDecoder::~CDecoder() 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream } 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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::Code(ISequentialInStream *inStream, ISequentialOutStream } -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 @@ CEncoder::~CEncoder() 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 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA } 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 @@ CEncoder::CEncoder() 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 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream _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 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream } 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 --git a/CPP/7zip/Compress/PpmdZip.h b/CPP/7zip/Compress/PpmdZip.h index 9d1fc4bd..a23d0087 100644 --- a/CPP/7zip/Compress/PpmdZip.h +++ b/CPP/7zip/Compress/PpmdZip.h @@ -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 @@ struct CBuf { 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 @@ struct CEncProps 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 --git a/CPP/7zip/Compress/QuantumDecoder.cpp b/CPP/7zip/Compress/QuantumDecoder.cpp index 8c650581..16ef0fc2 100644 --- a/CPP/7zip/Compress/QuantumDecoder.cpp +++ b/CPP/7zip/Compress/QuantumDecoder.cpp @@ -33,12 +33,12 @@ void CModelDecoder::Init(unsigned numItems) 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 @@ unsigned CModelDecoder::Decode(CRangeDecoder *rc) 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 @@ void CDecoder::Init() 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 @@ HRESULT CDecoder::CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize) 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 @@ HRESULT CDecoder::CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize) 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 @@ HRESULT CDecoder::Code(const Byte *inData, size_t inSize, 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 --git a/CPP/7zip/Compress/QuantumDecoder.h b/CPP/7zip/Compress/QuantumDecoder.h index afeba708..925989af 100644 --- a/CPP/7zip/Compress/QuantumDecoder.h +++ b/CPP/7zip/Compress/QuantumDecoder.h @@ -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 CModelDecoder }; -class CDecoder: - public IUnknown, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_0( + CDecoder +) CLzOutWindow _outWindow; unsigned _numDictBits; @@ -157,17 +156,12 @@ class CDecoder: 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 --git a/CPP/7zip/Compress/Rar1Decoder.cpp b/CPP/7zip/Compress/Rar1Decoder.cpp index 510bbd17..050cde21 100644 --- a/CPP/7zip/Compress/Rar1Decoder.cpp +++ b/CPP/7zip/Compress/Rar1Decoder.cpp @@ -39,7 +39,7 @@ static const UInt32 kHistorySize = (1 << 16); CDecoder::CDecoder(): _isSolid(false), _solidAllowed(false) - { } + {} UInt32 CDecoder::ReadBits(unsigned numBits) { return m_InBitStream.ReadBits(numBits); } @@ -73,8 +73,8 @@ UInt32 CDecoder::DecodeNum(const Byte *numTab) for (;;) { - UInt32 num = numTab[i]; - UInt32 cur = num << (kNumBits - i); + const UInt32 num = numTab[i]; + const UInt32 cur = num << (kNumBits - i); if (val < cur) break; i++; @@ -126,7 +126,7 @@ HRESULT CDecoder::ShortLZ() return CopyBlock(dist, len); } - UInt32 saveLen = len; + const UInt32 saveLen = len; dist = m_RepDists[(m_RepDistPtr - (len - 9)) & 3]; len = DecodeNum(PosL1); @@ -342,9 +342,9 @@ HRESULT CDecoder::HuffDecode() void CDecoder::GetFlagsBuf() { UInt32 flags, newFlagsPlace; - UInt32 flagsPlace = DecodeNum(PosHf2); // [0, 256] + const UInt32 flagsPlace = DecodeNum(PosHf2); // [0, 256] - if (flagsPlace >= ARRAY_SIZE(ChSetC)) + if (flagsPlace >= Z7_ARRAY_SIZE(ChSetC)) return; for (;;) @@ -362,15 +362,15 @@ void CDecoder::GetFlagsBuf() } -void CDecoder::CorrHuff(UInt32 *CharSet,UInt32 *NumToPlace) +void CDecoder::CorrHuff(UInt32 *CharSet, UInt32 *NumToPlace) { int i; for (i = 7; i >= 0; i--) - for (int j = 0; j < 32; j++, CharSet++) - *CharSet = (*CharSet & ~0xff) | i; + for (unsigned j = 0; j < 32; j++, CharSet++) + *CharSet = (*CharSet & ~(UInt32)0xff) | (unsigned)i; memset(NumToPlace, 0, sizeof(NToPl)); for (i = 6; i >= 0; i--) - NumToPlace[i] = (7 - i) * 32; + NumToPlace[i] = (7 - (unsigned)i) * 32; } @@ -459,7 +459,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * FlagBuf <<= 1; if (Nlzb > Nhfb) { - RINOK(LongLZ()); + RINOK(LongLZ()) continue; } } @@ -476,7 +476,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * if ((FlagBuf & 0x80) == 0) { FlagBuf <<= 1; - RINOK(ShortLZ()); + RINOK(ShortLZ()) continue; } @@ -484,13 +484,13 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * if (Nlzb <= Nhfb) { - RINOK(LongLZ()); + RINOK(LongLZ()) continue; } } } - RINOK(HuffDecode()); + RINOK(HuffDecode()) } _solidAllowed = true; @@ -498,8 +498,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * } -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; } @@ -507,7 +507,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream catch(...) { return S_FALSE; } } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size < 1) return E_INVALIDARG; diff --git a/CPP/7zip/Compress/Rar1Decoder.h b/CPP/7zip/Compress/Rar1Decoder.h index 52907e5c..6d0e31d8 100644 --- a/CPP/7zip/Compress/Rar1Decoder.h +++ b/CPP/7zip/Compress/Rar1Decoder.h @@ -2,8 +2,8 @@ // According to unRAR license, this code may not be used to develop // a program that creates RAR archives -#ifndef __COMPRESS_RAR1_DECODER_H -#define __COMPRESS_RAR1_DECODER_H +#ifndef ZIP7_INC_COMPRESS_RAR1_DECODER_H +#define ZIP7_INC_COMPRESS_RAR1_DECODER_H #include "../../Common/MyCom.h" @@ -20,11 +20,11 @@ namespace NRar1 { const UInt32 kNumRepDists = 4; -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_2( + CDecoder + , ICompressCoder + , ICompressSetDecoderProperties2 +) CLzOutWindow m_OutWindowStream; NBitm::CDecoder m_InBitStream; @@ -64,14 +64,6 @@ class CDecoder : public: CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - }; }} diff --git a/CPP/7zip/Compress/Rar2Decoder.cpp b/CPP/7zip/Compress/Rar2Decoder.cpp index b1c8c2d4..92404b62 100644 --- a/CPP/7zip/Compress/Rar2Decoder.cpp +++ b/CPP/7zip/Compress/Rar2Decoder.cpp @@ -13,30 +13,32 @@ namespace NRar2 { namespace NMultimedia { +#define my_abs(x) (unsigned)abs(x) + Byte CFilter::Decode(int &channelDelta, Byte deltaByte) { D4 = D3; D3 = D2; D2 = LastDelta - D1; D1 = LastDelta; - int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3); + const int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3); - Byte realValue = (Byte)(predictedValue - deltaByte); + const Byte realValue = (Byte)(predictedValue - deltaByte); { - int i = ((int)(signed char)deltaByte) << 3; - - Dif[0] += abs(i); - Dif[1] += abs(i - D1); - Dif[2] += abs(i + D1); - Dif[3] += abs(i - D2); - Dif[4] += abs(i + D2); - Dif[5] += abs(i - D3); - Dif[6] += abs(i + D3); - Dif[7] += abs(i - D4); - Dif[8] += abs(i + D4); - Dif[9] += abs(i - channelDelta); - Dif[10] += abs(i + channelDelta); + const int i = ((int)(signed char)deltaByte) << 3; + + Dif[0] += my_abs(i); + Dif[1] += my_abs(i - D1); + Dif[2] += my_abs(i + D1); + Dif[3] += my_abs(i - D2); + Dif[4] += my_abs(i + D2); + Dif[5] += my_abs(i - D3); + Dif[6] += my_abs(i + D3); + Dif[7] += my_abs(i - D4); + Dif[8] += my_abs(i + D4); + Dif[9] += my_abs(i - channelDelta); + Dif[10] += my_abs(i + channelDelta); } channelDelta = LastDelta = (signed char)(realValue - LastChar); @@ -48,7 +50,7 @@ Byte CFilter::Decode(int &channelDelta, Byte deltaByte) UInt32 numMinDif = 0; Dif[0] = 0; - for (unsigned i = 1; i < ARRAY_SIZE(Dif); i++) + for (unsigned i = 1; i < Z7_ARRAY_SIZE(Dif); i++) { if (Dif[i] < minDif) { @@ -129,13 +131,13 @@ bool CDecoder::ReadTables(void) unsigned i; for (i = 0; i < kLevelTableSize; i++) levelLevels[i] = (Byte)ReadBits(4); - RIF(m_LevelDecoder.Build(levelLevels)); + RIF(m_LevelDecoder.Build(levelLevels)) i = 0; do { - UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream); + const UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream); if (sym < kTableDirectLevels) { lens[i] = (Byte)((sym + m_LastLevels[i]) & kLevelMask); @@ -154,7 +156,7 @@ bool CDecoder::ReadTables(void) // return false; num = numLevels; // original unRAR } - Byte v = lens[(size_t)i - 1]; + const Byte v = lens[(size_t)i - 1]; do lens[i++] = v; while (i < num); @@ -188,13 +190,13 @@ bool CDecoder::ReadTables(void) if (m_AudioMode) for (i = 0; i < m_NumChannels; i++) { - RIF(m_MMDecoders[i].Build(&lens[i * kMMTableSize])); + RIF(m_MMDecoders[i].Build(&lens[i * kMMTableSize])) } else { - RIF(m_MainDecoder.Build(&lens[0])); - RIF(m_DistDecoder.Build(&lens[kMainTableSize])); - RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize])); + RIF(m_MainDecoder.Build(&lens[0])) + RIF(m_DistDecoder.Build(&lens[kMainTableSize])) + RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize])) } memcpy(m_LastLevels, lens, kMaxTableSize); @@ -214,7 +216,7 @@ bool CDecoder::ReadLastTables() { if (m_AudioMode) { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); + const UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); if (symbol == 256) return ReadTables(); if (symbol >= kMMTableSize) @@ -222,7 +224,7 @@ bool CDecoder::ReadLastTables() } else { - UInt32 sym = m_MainDecoder.Decode(&m_InBitStream); + const UInt32 sym = m_MainDecoder.Decode(&m_InBitStream); if (sym == kReadTableNumber) return ReadTables(); if (sym >= kMainTableSize) @@ -237,7 +239,7 @@ bool CDecoder::DecodeMm(UInt32 pos) { while (pos-- != 0) { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); + const UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); if (m_InBitStream.ExtraBitsWereRead()) return false; if (symbol >= 256) @@ -247,7 +249,7 @@ bool CDecoder::DecodeMm(UInt32 pos) Byte byReal = (Byte)(byPredict - (Byte)symbol); m_Predictor.Update(byReal, byPredict); */ - Byte byReal = m_MmFilter.Decode((Byte)symbol); + const Byte byReal = m_MmFilter.Decode((Byte)symbol); m_OutWindowStream.PutByte(byReal); if (++m_MmFilter.CurrentChannel == m_NumChannels) m_MmFilter.CurrentChannel = 0; @@ -375,7 +377,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * if (!m_TablesOK) return S_FALSE; - UInt64 startPos = m_OutWindowStream.GetProcessedSize(); + const UInt64 startPos = m_OutWindowStream.GetProcessedSize(); while (pos < unPackSize) { UInt32 blockSize = 1 << 20; @@ -396,7 +398,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * if (m_InBitStream.ExtraBitsWereRead()) return S_FALSE; - UInt64 globalPos = m_OutWindowStream.GetProcessedSize(); + const UInt64 globalPos = m_OutWindowStream.GetProcessedSize(); pos = globalPos - blockStartPos; if (pos < blockSize) if (!ReadTables()) @@ -405,7 +407,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * if (progress) { const UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); + RINOK(progress->SetRatioInfo(&packSize, &pos)) } } if (pos > unPackSize) @@ -419,8 +421,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * return m_OutWindowStream.Flush(); } -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; } @@ -428,7 +430,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream catch(...) { return S_FALSE; } } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size < 1) return E_INVALIDARG; diff --git a/CPP/7zip/Compress/Rar2Decoder.h b/CPP/7zip/Compress/Rar2Decoder.h index f42f228d..d77bfc18 100644 --- a/CPP/7zip/Compress/Rar2Decoder.h +++ b/CPP/7zip/Compress/Rar2Decoder.h @@ -2,8 +2,8 @@ // According to unRAR license, this code may not be used to develop // a program that creates RAR archives -#ifndef __COMPRESS_RAR2_DECODER_H -#define __COMPRESS_RAR2_DECODER_H +#ifndef ZIP7_INC_COMPRESS_RAR2_DECODER_H +#define ZIP7_INC_COMPRESS_RAR2_DECODER_H #include "../../Common/MyCom.h" @@ -112,11 +112,11 @@ typedef NBitm::CDecoder CBitDecoder; const unsigned kNumHuffmanBits = 15; -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CDecoder + , ICompressCoder + , ICompressSetDecoderProperties2 +) CLzOutWindow m_OutWindowStream; CBitDecoder m_InBitStream; @@ -157,14 +157,6 @@ class CDecoder : public: CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - }; }} diff --git a/CPP/7zip/Compress/Rar3Decoder.cpp b/CPP/7zip/Compress/Rar3Decoder.cpp index 2271dcc8..a4943ada 100644 --- a/CPP/7zip/Compress/Rar3Decoder.cpp +++ b/CPP/7zip/Compress/Rar3Decoder.cpp @@ -38,15 +38,15 @@ static const UInt32 kVmCodeSizeMax = 1 << 16; extern "C" { -static Byte Wrap_ReadByte(const IByteIn *pp) throw() +static Byte Wrap_ReadByte(IByteInPtr pp) throw() { - CByteIn *p = CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); + CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); return p->BitDecoder.Stream.ReadByte(); } -static Byte Wrap_ReadBits8(const IByteIn *pp) throw() +static Byte Wrap_ReadBits8(IByteInPtr pp) throw() { - CByteIn *p = CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); + CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); return (Byte)p->BitDecoder.ReadByteFromAligned(); } @@ -54,13 +54,13 @@ static Byte Wrap_ReadBits8(const IByteIn *pp) throw() CDecoder::CDecoder(): - _window(0), + _window(NULL), _winPos(0), _wrPtr(0), _lzSize(0), _writtenFileSize(0), - _vmData(0), - _vmCode(0), + _vmData(NULL), + _vmCode(NULL), _isSolid(false), _solidAllowed(false) { @@ -106,7 +106,7 @@ HRESULT CDecoder::WriteArea(UInt32 startPtr, UInt32 endPtr) { if (startPtr <= endPtr) return WriteData(_window + startPtr, endPtr - startPtr); - RINOK(WriteData(_window + startPtr, kWindowSize - startPtr)); + RINOK(WriteData(_window + startPtr, kWindowSize - startPtr)) return WriteData(_window, endPtr); } @@ -146,7 +146,7 @@ HRESULT CDecoder::WriteBuf() { if (writtenBorder != blockStart) { - RINOK(WriteArea(writtenBorder, blockStart)); + RINOK(WriteArea(writtenBorder, blockStart)) writtenBorder = blockStart; writeSize = (_winPos - writtenBorder) & kWindowMask; } @@ -353,26 +353,26 @@ bool CDecoder::ReadVmCodeLZ() bool CDecoder::ReadVmCodePPM() { - int firstByte = DecodePpmSymbol(); + const int firstByte = DecodePpmSymbol(); if (firstByte < 0) return false; UInt32 len = (firstByte & 7) + 1; if (len == 7) { - int b1 = DecodePpmSymbol(); + const int b1 = DecodePpmSymbol(); if (b1 < 0) return false; - len = b1 + 7; + len = (unsigned)b1 + 7; } else if (len == 8) { - int b1 = DecodePpmSymbol(); + const int b1 = DecodePpmSymbol(); if (b1 < 0) return false; - int b2 = DecodePpmSymbol(); + const int b2 = DecodePpmSymbol(); if (b2 < 0) return false; - len = b1 * 256 + b2; + len = (unsigned)b1 * 256 + (unsigned)b2; } if (len > kVmDataSizeMax) return false; @@ -380,12 +380,12 @@ bool CDecoder::ReadVmCodePPM() return false; for (UInt32 i = 0; i < len; i++) { - int b = DecodePpmSymbol(); + const int b = DecodePpmSymbol(); if (b < 0) return false; _vmData[i] = (Byte)b; } - return AddVmCode(firstByte, len); + return AddVmCode((unsigned)firstByte, len); } #define RIF(x) { if (!(x)) return S_FALSE; } @@ -398,7 +398,7 @@ HRESULT CDecoder::InitPPM() { unsigned maxOrder = (unsigned)ReadBits(7); - bool reset = ((maxOrder & 0x20) != 0); + const bool reset = ((maxOrder & 0x20) != 0); UInt32 maxMB = 0; if (reset) maxMB = (Byte)Wrap_ReadBits8(&m_InBitStream.IByteIn_obj); @@ -446,7 +446,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) { if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) { - RINOK(WriteBuf()); + RINOK(WriteBuf()) if (_writtenFileSize > _unpackSize) { keepDecompressing = false; @@ -455,7 +455,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) } if (InputEofError_Fast()) return false; - int c = DecodePpmSymbol(); + const int c = DecodePpmSymbol(); if (c < 0) { PpmError = true; @@ -463,7 +463,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) } if (c == PpmEscChar) { - int nextCh = DecodePpmSymbol(); + const int nextCh = DecodePpmSymbol(); if (nextCh < 0) { PpmError = true; @@ -490,7 +490,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) { for (int i = 0; i < 3; i++) { - int c2 = DecodePpmSymbol(); + const int c2 = DecodePpmSymbol(); if (c2 < 0) { PpmError = true; @@ -501,13 +501,13 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) dist++; len += 28; } - int c2 = DecodePpmSymbol(); + const int c2 = DecodePpmSymbol(); if (c2 < 0) { PpmError = true; return S_FALSE; } - len += c2; + len += (unsigned)c2; if (dist >= _lzSize) return S_FALSE; CopyBlock(dist, len); @@ -552,7 +552,7 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing) for (i = 0; i < kLevelTableSize; i++) { - UInt32 len = ReadBits(4); + const UInt32 len = ReadBits(4); if (len == 15) { UInt32 zeroCount = ReadBits(4); @@ -568,13 +568,13 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing) levelLevels[i] = (Byte)len; } - RIF(m_LevelDecoder.Build(levelLevels)); + RIF(m_LevelDecoder.Build(levelLevels)) i = 0; do { - UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream.BitDecoder); + const UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream.BitDecoder); if (sym < 16) { lens[i] = Byte((sym + m_LastLevels[i]) & 15); @@ -617,10 +617,10 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing) } */ - RIF(m_MainDecoder.Build(&lens[0])); - RIF(m_DistDecoder.Build(&lens[kMainTableSize])); - RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])); - RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])); + RIF(m_MainDecoder.Build(&lens[0])) + RIF(m_DistDecoder.Build(&lens[kMainTableSize])) + RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])) + RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])) memcpy(m_LastLevels, lens, kTablesSizesSum); @@ -667,7 +667,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing) { if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) { - RINOK(WriteBuf()); + RINOK(WriteBuf()) if (_writtenFileSize > _unpackSize) { keepDecompressing = false; @@ -686,7 +686,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing) } else if (sym == kSymbolReadTable) { - RINOK(ReadEndOfBlock(keepDecompressing)); + RINOK(ReadEndOfBlock(keepDecompressing)) break; } else if (sym == 257) @@ -749,7 +749,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing) len = kNormalMatchMinLen + sym; if (sym >= 8) { - unsigned num = (sym >> 2) - 1; + const unsigned num = (sym >> 2) - 1; len = kNormalMatchMinLen + ((4 + (sym & 3)) << num) + m_InBitStream.BitDecoder.ReadBits_upto8(num); } const UInt32 sym2 = m_DistDecoder.Decode(&m_InBitStream.BitDecoder); @@ -833,7 +833,7 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress) if (!_isSolid || !TablesRead) { bool keepDecompressing; - RINOK(ReadTables(keepDecompressing)); + RINOK(ReadTables(keepDecompressing)) if (!keepDecompressing) { _solidAllowed = true; @@ -858,17 +858,17 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress) if (InputEofError()) return S_FALSE; - UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); + const UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); + RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)) if (!keepDecompressing) break; } _solidAllowed = true; - RINOK(WriteBuf()); - UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); + RINOK(WriteBuf()) + const UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); + RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)) if (_writtenFileSize < _unpackSize) return S_FALSE; @@ -878,8 +878,8 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress) return S_OK; } -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 { @@ -924,7 +924,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream // by error in data stream. } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size < 1) return E_INVALIDARG; diff --git a/CPP/7zip/Compress/Rar3Decoder.h b/CPP/7zip/Compress/Rar3Decoder.h index fdecc55f..4711052f 100644 --- a/CPP/7zip/Compress/Rar3Decoder.h +++ b/CPP/7zip/Compress/Rar3Decoder.h @@ -4,8 +4,8 @@ /* This code uses Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ -#ifndef __COMPRESS_RAR3_DECODER_H -#define __COMPRESS_RAR3_DECODER_H +#ifndef ZIP7_INC_COMPRESS_RAR3_DECODER_H +#define ZIP7_INC_COMPRESS_RAR3_DECODER_H #include "../../../C/Ppmd7.h" @@ -156,11 +156,11 @@ struct CTempFilter: public NVm::CProgramInitState const unsigned kNumHuffmanBits = 15; -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CDecoder + , ICompressCoder + , ICompressSetDecoderProperties2 +) CByteIn m_InBitStream; Byte *_window; UInt32 _winPos; @@ -231,17 +231,6 @@ class CDecoder: bool InputEofError() const { return m_InBitStream.BitDecoder.ExtraBitsWereRead(); } bool InputEofError_Fast() const { return (m_InBitStream.BitDecoder.Stream.NumExtraBytes > 2); } -public: - CDecoder(); - ~CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - void CopyBlock(UInt32 dist, UInt32 len) { _lzSize += len; @@ -270,11 +259,15 @@ class CDecoder: void PutByte(Byte b) { - UInt32 wp = _winPos; + const UInt32 wp = _winPos; _window[wp] = b; _winPos = (wp + 1) & kWindowMask; _lzSize++; } + +public: + CDecoder(); + ~CDecoder(); }; }} diff --git a/CPP/7zip/Compress/Rar3Vm.cpp b/CPP/7zip/Compress/Rar3Vm.cpp index 6accd08c..9b728efc 100644 --- a/CPP/7zip/Compress/Rar3Vm.cpp +++ b/CPP/7zip/Compress/Rar3Vm.cpp @@ -29,8 +29,8 @@ UInt32 CMemBitDecoder::ReadBits(unsigned numBits) UInt32 res = 0; for (;;) { - unsigned b = _bitPos < _bitSize ? (unsigned)_data[_bitPos >> 3] : 0; - unsigned avail = (unsigned)(8 - (_bitPos & 7)); + const unsigned b = _bitPos < _bitSize ? (unsigned)_data[_bitPos >> 3] : 0; + const unsigned avail = (unsigned)(8 - (_bitPos & 7)); if (numBits <= avail) { _bitPos += numBits; @@ -46,8 +46,8 @@ UInt32 CMemBitDecoder::ReadBit() { return ReadBits(1); } UInt32 CMemBitDecoder::ReadEncodedUInt32() { - unsigned v = (unsigned)ReadBits(2); - UInt32 res = ReadBits(4 << v); + const unsigned v = (unsigned)ReadBits(2); + UInt32 res = ReadBits(4u << v); if (v == 1 && res < 16) res = 0xFFFFFF00 | (res << 4) | ReadBits(4); return res; @@ -57,7 +57,13 @@ namespace NVm { static const UInt32 kStackRegIndex = kNumRegs - 1; -#ifdef RARVM_VM_ENABLE +#ifdef Z7_RARVM_VM_ENABLE + +#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 static const UInt32 FLAG_C = 1; static const UInt32 FLAG_Z = 2; @@ -144,7 +150,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, R[kNumRegs] = 0; Flags = 0; - UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize); + const UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize); if (globalSize != 0) memcpy(Mem + kGlobalOffset, &initState->GlobalData[0], globalSize); UInt32 staticSize = MyMin((UInt32)prg->StaticData.Size(), kGlobalSize - globalSize); @@ -153,13 +159,13 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, bool res = true; - #ifdef RARVM_STANDARD_FILTERS + #ifdef Z7_RARVM_STANDARD_FILTERS if (prg->StandardFilterIndex >= 0) - res = ExecuteStandardFilter(prg->StandardFilterIndex); + res = ExecuteStandardFilter((unsigned)prg->StandardFilterIndex); else #endif { - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE res = ExecuteCode(prg); if (!res) { @@ -192,7 +198,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, return res; } -#ifdef RARVM_VM_ENABLE +#ifdef Z7_RARVM_VM_ENABLE #define SET_IP(IP) \ if ((IP) >= numCommands) return true; \ @@ -200,7 +206,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, cmd = commands + (IP); #define GET_FLAG_S_B(res) (((res) & 0x80) ? FLAG_S : 0) -#define SET_IP_OP1 { UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val); } +#define SET_IP_OP1 { const UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val) } #define FLAGS_UPDATE_SZ Flags = res == 0 ? FLAG_Z : res & FLAG_S #define FLAGS_UPDATE_SZ_B Flags = (res & 0xFF) == 0 ? FLAG_Z : GET_FLAG_S_B(res) @@ -220,6 +226,7 @@ void CVm::SetOperand32(const COperand *op, UInt32 val) { case OP_TYPE_REG: R[op->Data] = val; return; case OP_TYPE_REGMEM: SetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask], val); return; + default: break; } } @@ -228,7 +235,7 @@ Byte CVm::GetOperand8(const COperand *op) const switch (op->Type) { case OP_TYPE_REG: return (Byte)R[op->Data]; - case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask];; + case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask]; default: return (Byte)op->Data; } } @@ -239,6 +246,7 @@ void CVm::SetOperand8(const COperand *op, Byte val) { case OP_TYPE_REG: R[op->Data] = (R[op->Data] & 0xFFFFFF00) | val; return; case OP_TYPE_REGMEM: Mem[(op->Base + R[op->Data]) & kSpaceMask] = val; return; + default: break; } } @@ -262,7 +270,7 @@ bool CVm::ExecuteCode(const CProgram *prg) Int32 maxOpCount = 25000000; const CCommand *commands = &prg->Commands[0]; const CCommand *cmd = commands; - UInt32 numCommands = prg->Commands.Size(); + const UInt32 numCommands = prg->Commands.Size(); if (numCommands == 0) return false; @@ -278,152 +286,152 @@ bool CVm::ExecuteCode(const CProgram *prg) break; case CMD_CMP: { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); + const UInt32 v1 = GetOperand32(&cmd->Op1); + const UInt32 res = v1 - GetOperand32(&cmd->Op2); Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); } break; case CMD_CMPB: { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = (Byte)((v1 - GetOperand8(&cmd->Op2)) & 0xFF); + const Byte v1 = GetOperand8(&cmd->Op1); + const Byte res = (Byte)((v1 - GetOperand8(&cmd->Op2)) & 0xFF); Flags = res == 0 ? FLAG_Z : (res > v1) | GET_FLAG_S_B(res); } break; case CMD_ADD: { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 + GetOperand32(&cmd->Op2); + const UInt32 v1 = GetOperand32(&cmd->Op1); + const UInt32 res = v1 + GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); Flags = (res < v1) | (res == 0 ? FLAG_Z : (res & FLAG_S)); } break; case CMD_ADDB: { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = (Byte)((v1 + GetOperand8(&cmd->Op2)) & 0xFF); + const Byte v1 = GetOperand8(&cmd->Op1); + const Byte res = (Byte)((v1 + GetOperand8(&cmd->Op2)) & 0xFF); SetOperand8(&cmd->Op1, (Byte)res); Flags = (res < v1) | (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)); } break; case CMD_ADC: { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); + const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); + const UInt32 FC = (Flags & FLAG_C); UInt32 res = v1 + GetOperand(cmd->ByteMode, &cmd->Op2) + FC; if (cmd->ByteMode) res &= 0xFF; SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res < v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); + Flags = (res < v1 || (res == v1 && FC)) | (res == 0 ? FLAG_Z : (res & FLAG_S)); } break; case CMD_SUB: { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); + const UInt32 v1 = GetOperand32(&cmd->Op1); + const UInt32 res = v1 - GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); } break; case CMD_SUBB: { - UInt32 v1 = GetOperand8(&cmd->Op1); - UInt32 res = v1 - GetOperand8(&cmd->Op2); + const UInt32 v1 = GetOperand8(&cmd->Op1); + const UInt32 res = v1 - GetOperand8(&cmd->Op2); SetOperand8(&cmd->Op1, (Byte)res); Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); } break; case CMD_SBB: { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); + const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); + const UInt32 FC = (Flags & FLAG_C); UInt32 res = v1 - GetOperand(cmd->ByteMode, &cmd->Op2) - FC; // Flags = res == 0 ? FLAG_Z : (res > v1 || res == v1 && FC) | (res & FLAG_S); if (cmd->ByteMode) res &= 0xFF; SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res > v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); + Flags = (res > v1 || (res == v1 && FC)) | (res == 0 ? FLAG_Z : (res & FLAG_S)); } break; case CMD_INC: { - UInt32 res = GetOperand32(&cmd->Op1) + 1; + const UInt32 res = GetOperand32(&cmd->Op1) + 1; SetOperand32(&cmd->Op1, res); FLAGS_UPDATE_SZ; } break; case CMD_INCB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) + 1); - SetOperand8(&cmd->Op1, res);; + const Byte res = (Byte)(GetOperand8(&cmd->Op1) + 1); + SetOperand8(&cmd->Op1, res); FLAGS_UPDATE_SZ_B; } break; case CMD_DEC: { - UInt32 res = GetOperand32(&cmd->Op1) - 1; + const UInt32 res = GetOperand32(&cmd->Op1) - 1; SetOperand32(&cmd->Op1, res); FLAGS_UPDATE_SZ; } break; case CMD_DECB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) - 1); - SetOperand8(&cmd->Op1, res);; + const Byte res = (Byte)(GetOperand8(&cmd->Op1) - 1); + SetOperand8(&cmd->Op1, res); FLAGS_UPDATE_SZ_B; } break; case CMD_XOR: { - UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2); + const UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); FLAGS_UPDATE_SZ; } break; case CMD_XORB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2)); + const Byte res = (Byte)(GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2)); SetOperand8(&cmd->Op1, res); FLAGS_UPDATE_SZ_B; } break; case CMD_AND: { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); + const UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); FLAGS_UPDATE_SZ; } break; case CMD_ANDB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); + const Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); SetOperand8(&cmd->Op1, res); FLAGS_UPDATE_SZ_B; } break; case CMD_OR: { - UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2); + const UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); FLAGS_UPDATE_SZ; } break; case CMD_ORB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2)); + const Byte res = (Byte)(GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2)); SetOperand8(&cmd->Op1, res); FLAGS_UPDATE_SZ_B; } break; case CMD_TEST: { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); + const UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); FLAGS_UPDATE_SZ; } break; case CMD_TESTB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); + const Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); FLAGS_UPDATE_SZ_B; } break; @@ -432,14 +440,14 @@ bool CVm::ExecuteCode(const CProgram *prg) break; case CMD_NEG: { - UInt32 res = 0 - GetOperand32(&cmd->Op1); + const UInt32 res = 0 - GetOperand32(&cmd->Op1); SetOperand32(&cmd->Op1, res); Flags = res == 0 ? FLAG_Z : FLAG_C | (res & FLAG_S); } break; case CMD_NEGB: { - Byte res = (Byte)(0 - GetOperand8(&cmd->Op1)); + const Byte res = (Byte)(0 - GetOperand8(&cmd->Op1)); SetOperand8(&cmd->Op1, res); Flags = res == 0 ? FLAG_Z : FLAG_C | GET_FLAG_S_B(res); } @@ -447,115 +455,115 @@ bool CVm::ExecuteCode(const CProgram *prg) case CMD_SHL: { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 << v2; + const UInt32 v1 = GetOperand32(&cmd->Op1); + const int v2 = (int)GetOperand32(&cmd->Op2); + const UInt32 res = v1 << v2; SetOperand32(&cmd->Op1, res); Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 << (v2 - 1)) & 0x80000000 ? FLAG_C : 0); } break; case CMD_SHLB: { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 << v2); + const Byte v1 = GetOperand8(&cmd->Op1); + const int v2 = (int)GetOperand8(&cmd->Op2); + const Byte res = (Byte)(v1 << v2); SetOperand8(&cmd->Op1, res); Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 << (v2 - 1)) & 0x80 ? FLAG_C : 0); } break; case CMD_SHR: { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 >> v2; + const UInt32 v1 = GetOperand32(&cmd->Op1); + const int v2 = (int)GetOperand32(&cmd->Op2); + const UInt32 res = v1 >> v2; SetOperand32(&cmd->Op1, res); Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); } break; case CMD_SHRB: { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 >> v2); + const Byte v1 = GetOperand8(&cmd->Op1); + const int v2 = (int)GetOperand8(&cmd->Op2); + const Byte res = (Byte)(v1 >> v2); SetOperand8(&cmd->Op1, res); Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); } break; case CMD_SAR: { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = UInt32(((Int32)v1) >> v2); + const UInt32 v1 = GetOperand32(&cmd->Op1); + const int v2 = (int)GetOperand32(&cmd->Op2); + const UInt32 res = UInt32(((Int32)v1) >> v2); SetOperand32(&cmd->Op1, res); Flags= (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); } break; case CMD_SARB: { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(((signed char)v1) >> v2); + const Byte v1 = GetOperand8(&cmd->Op1); + const int v2 = (int)GetOperand8(&cmd->Op2); + const Byte res = (Byte)(((signed char)v1) >> v2); SetOperand8(&cmd->Op1, res); Flags= (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); } break; case CMD_JMP: - SET_IP_OP1; + SET_IP_OP1 continue; case CMD_JZ: if ((Flags & FLAG_Z) != 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JNZ: if ((Flags & FLAG_Z) == 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JS: if ((Flags & FLAG_S) != 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JNS: if ((Flags & FLAG_S) == 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JB: if ((Flags & FLAG_C) != 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JBE: if ((Flags & (FLAG_C | FLAG_Z)) != 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JA: if ((Flags & (FLAG_C | FLAG_Z)) == 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; case CMD_JAE: if ((Flags & FLAG_C) == 0) { - SET_IP_OP1; + SET_IP_OP1 continue; } break; @@ -571,7 +579,7 @@ bool CVm::ExecuteCode(const CProgram *prg) case CMD_CALL: R[kStackRegIndex] -= 4; SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], (UInt32)(cmd - commands + 1)); - SET_IP_OP1; + SET_IP_OP1 continue; case CMD_PUSHA: @@ -604,29 +612,29 @@ bool CVm::ExecuteCode(const CProgram *prg) break; case CMD_XCHG: { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); + const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); SetOperand(cmd->ByteMode, &cmd->Op1, GetOperand(cmd->ByteMode, &cmd->Op2)); SetOperand(cmd->ByteMode, &cmd->Op2, v1); } break; case CMD_MUL: { - UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2); + const UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2); SetOperand32(&cmd->Op1, res); } break; case CMD_MULB: { - Byte res = (Byte)(GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2)); + const Byte res = (Byte)(GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2)); SetOperand8(&cmd->Op1, res); } break; case CMD_DIV: { - UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2); + const UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2); if (divider != 0) { - UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider; + const UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider; SetOperand(cmd->ByteMode, &cmd->Op1, res); } } @@ -636,8 +644,8 @@ bool CVm::ExecuteCode(const CProgram *prg) { if (R[kStackRegIndex] >= kSpaceSize) return true; - UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); - SET_IP(ip); + const UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); + SET_IP(ip) R[kStackRegIndex] += 4; continue; } @@ -695,7 +703,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize) if (inp.ReadBit()) { - UInt32 dataSize = inp.ReadEncodedUInt32() + 1; + const UInt32 dataSize = inp.ReadEncodedUInt32() + 1; for (UInt32 i = 0; inp.Avail() && i < dataSize; i++) StaticData.Add((Byte)inp.ReadBits(8)); } @@ -705,28 +713,30 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize) Commands.Add(CCommand()); CCommand *cmd = &Commands.Back(); + unsigned opCode; if (inp.ReadBit() == 0) - cmd->OpCode = (ECommand)inp.ReadBits(3); + opCode = inp.ReadBits(3); else - cmd->OpCode = (ECommand)(8 + inp.ReadBits(5)); - - if (kCmdFlags[(unsigned)cmd->OpCode] & CF_BYTEMODE) + opCode = 8 + inp.ReadBits(5); + cmd->OpCode = (ECommand)opCode; + const unsigned cmdFlags = kCmdFlags[opCode]; + if (cmdFlags & CF_BYTEMODE) cmd->ByteMode = (inp.ReadBit()) ? true : false; else cmd->ByteMode = 0; - int opNum = (kCmdFlags[(unsigned)cmd->OpCode] & CF_OPMASK); + const unsigned opNum = (cmdFlags & CF_OPMASK); - if (opNum > 0) + if (opNum) { DecodeArg(inp, cmd->Op1, cmd->ByteMode); if (opNum == 2) DecodeArg(inp, cmd->Op2, cmd->ByteMode); else { - if (cmd->Op1.Type == OP_TYPE_INT && (kCmdFlags[(unsigned)cmd->OpCode] & (CF_JUMP | CF_PROC))) + if (cmd->Op1.Type == OP_TYPE_INT && (cmdFlags & (CF_JUMP | CF_PROC))) { - int dist = cmd->Op1.Data; + Int32 dist = (Int32)cmd->Op1.Data; if (dist >= 256) dist -= 256; else @@ -739,7 +749,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize) dist -= 16; dist += Commands.Size() - 1; } - cmd->Op1.Data = dist; + cmd->Op1.Data = (UInt32)dist; } } } @@ -763,6 +773,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize) case CMD_SHR: cmd->OpCode = CMD_SHRB; break; case CMD_SAR: cmd->OpCode = CMD_SARB; break; case CMD_MUL: cmd->OpCode = CMD_MULB; break; + default: break; } } } @@ -771,7 +782,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize) #endif -#ifdef RARVM_STANDARD_FILTERS +#ifdef Z7_RARVM_STANDARD_FILTERS enum EStandardFilter { @@ -803,12 +814,13 @@ kStdFilters[]= static int FindStandardFilter(const Byte *code, UInt32 codeSize) { - UInt32 crc = CrcCalc(code, codeSize); - for (unsigned i = 0; i < ARRAY_SIZE(kStdFilters); i++) + // return -1; // for debug VM execution + const UInt32 crc = CrcCalc(code, codeSize); + for (unsigned i = 0; i < Z7_ARRAY_SIZE(kStdFilters); i++) { const CStandardFilterSignature &sfs = kStdFilters[i]; if (sfs.CRC == crc && sfs.Length == codeSize) - return i; + return (int)i; } return -1; } @@ -820,11 +832,11 @@ bool CProgram::PrepareProgram(const Byte *code, UInt32 codeSize) { IsSupported = false; - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE Commands.Clear(); #endif - #ifdef RARVM_STANDARD_FILTERS + #ifdef Z7_RARVM_STANDARD_FILTERS StandardFilterIndex = -1; #endif @@ -838,20 +850,20 @@ bool CProgram::PrepareProgram(const Byte *code, UInt32 codeSize) { IsSupported = true; isOK = true; - #ifdef RARVM_STANDARD_FILTERS + #ifdef Z7_RARVM_STANDARD_FILTERS StandardFilterIndex = FindStandardFilter(code, codeSize); if (StandardFilterIndex >= 0) return true; #endif - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE ReadProgram(code + 1, codeSize - 1); #else IsSupported = false; #endif } - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE Commands.Add(CCommand()); Commands.Back().OpCode = CMD_RET; #endif @@ -865,7 +877,7 @@ void CVm::SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize) memmove(Mem + pos, data, MyMin(dataSize, kSpaceSize - pos)); } -#ifdef RARVM_STANDARD_FILTERS +#ifdef Z7_RARVM_STANDARD_FILTERS static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9) { @@ -873,7 +885,7 @@ static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9) return; dataSize -= 4; const UInt32 kFileSize = 0x1000000; - Byte cmpMask = (Byte)(e9 ? 0xFE : 0xFF); + const Byte cmpMask = (Byte)(e9 ? 0xFE : 0xFF); for (UInt32 curPos = 0; curPos < dataSize;) { curPos++; @@ -921,7 +933,7 @@ static void ItaniumDecode(Byte *data, UInt32 dataSize, UInt32 fileOffset) raw &= ~(kMask << m); raw |= (v << m); // p[0] = (Byte)raw; p[1] = (Byte)(raw >> 8); p[2] = (Byte)(raw >> 16); - SetUi32(p, raw); + SetUi32(p, raw) } } while (++m <= 4); @@ -960,12 +972,12 @@ static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR) predicted = prevByte; else { - unsigned int upperLeftByte = destData[i - width]; - unsigned int upperByte = destData[i - width + 3]; + const unsigned int upperLeftByte = destData[i - width]; + const unsigned int upperByte = destData[i - width + 3]; predicted = prevByte + upperByte - upperLeftByte; - int pa = abs((int)(predicted - prevByte)); - int pb = abs((int)(predicted - upperByte)); - int pc = abs((int)(predicted - upperLeftByte)); + const int pa = abs((int)(predicted - prevByte)); + const int pb = abs((int)(predicted - upperByte)); + const int pc = abs((int)(predicted - upperLeftByte)); if (pa <= pb && pa <= pc) predicted = prevByte; else @@ -982,12 +994,14 @@ static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR) const UInt32 border = dataSize - 2; for (UInt32 i = posR; i < border; i += 3) { - Byte g = destData[i + 1]; + const Byte g = destData[i + 1]; destData[i ] = (Byte)(destData[i ] + g); destData[i + 2] = (Byte)(destData[i + 2] + g); } } +#define my_abs(x) (unsigned)abs(x) + static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels) { Byte *destData = srcData + dataSize; @@ -1001,34 +1015,34 @@ static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels) for (UInt32 i = curChannel, byteCount = 0; i < dataSize; i += numChannels, byteCount++) { D3 = D2; - D2 = prevDelta - D1; - D1 = prevDelta; + D2 = (Int32)prevDelta - D1; + D1 = (Int32)prevDelta; - UInt32 predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; + UInt32 predicted = (UInt32)((Int32)(8 * prevByte) + K1 * D1 + K2 * D2 + K3 * D3); predicted = (predicted >> 3) & 0xFF; - UInt32 curByte = *(srcData++); + const UInt32 curByte = *(srcData++); predicted -= curByte; destData[i] = (Byte)predicted; prevDelta = (UInt32)(Int32)(signed char)(predicted - prevByte); prevByte = predicted; - Int32 D = ((Int32)(signed char)curByte) << 3; + const Int32 D = ((Int32)(signed char)curByte) << 3; - dif[0] += abs(D); - dif[1] += abs(D - D1); - dif[2] += abs(D + D1); - dif[3] += abs(D - D2); - dif[4] += abs(D + D2); - dif[5] += abs(D - D3); - dif[6] += abs(D + D3); + dif[0] += my_abs(D); + dif[1] += my_abs(D - D1); + dif[2] += my_abs(D + D1); + dif[3] += my_abs(D - D2); + dif[4] += my_abs(D + D2); + dif[5] += my_abs(D - D3); + dif[6] += my_abs(D + D3); if ((byteCount & 0x1F) == 0) { UInt32 minDif = dif[0], numMinDif = 0; dif[0] = 0; - for (unsigned j = 1; j < ARRAY_SIZE(dif); j++) + for (unsigned j = 1; j < Z7_ARRAY_SIZE(dif); j++) { if (dif[j] < minDif) { @@ -1068,7 +1082,7 @@ static UInt32 UpCaseDecode(Byte *data, UInt32 dataSize) bool CVm::ExecuteStandardFilter(unsigned filterIndex) { - UInt32 dataSize = R[4]; + const UInt32 dataSize = R[4]; if (dataSize >= kGlobalOffset) return false; EStandardFilter filterType = kStdFilters[filterIndex].Type; @@ -1088,7 +1102,7 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex) { if (dataSize >= kGlobalOffset / 2) return false; - UInt32 numChannels = R[0]; + const UInt32 numChannels = R[0]; if (numChannels == 0 || numChannels > 1024) // unrar 5.5.5 return false; SetBlockPos(dataSize); @@ -1100,8 +1114,8 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex) { if (dataSize >= kGlobalOffset / 2 || dataSize < 3) // unrar 5.5.5 return false; - UInt32 width = R[0]; - UInt32 posR = R[1]; + const UInt32 width = R[0]; + const UInt32 posR = R[1]; if (width < 3 || width - 3 > dataSize || posR > 2) // unrar 5.5.5 return false; SetBlockPos(dataSize); @@ -1113,7 +1127,7 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex) { if (dataSize >= kGlobalOffset / 2) return false; - UInt32 numChannels = R[0]; + const UInt32 numChannels = R[0]; if (numChannels == 0 || numChannels > 128) // unrar 5.5.5 return false; SetBlockPos(dataSize); diff --git a/CPP/7zip/Compress/Rar3Vm.h b/CPP/7zip/Compress/Rar3Vm.h index 3fc51510..fde7e95e 100644 --- a/CPP/7zip/Compress/Rar3Vm.h +++ b/CPP/7zip/Compress/Rar3Vm.h @@ -2,15 +2,15 @@ // According to unRAR license, this code may not be used to develop // a program that creates RAR archives -#ifndef __COMPRESS_RAR3_VM_H -#define __COMPRESS_RAR3_VM_H +#ifndef ZIP7_INC_COMPRESS_RAR3_VM_H +#define ZIP7_INC_COMPRESS_RAR3_VM_H #include "../../../C/CpuArch.h" #include "../../Common/MyVector.h" -#define RARVM_STANDARD_FILTERS -// #define RARVM_VM_ENABLE +#define Z7_RARVM_STANDARD_FILTERS +// #define Z7_RARVM_VM_ENABLE namespace NCompress { namespace NRar3 { @@ -37,7 +37,7 @@ class CMemBitDecoder namespace NVm { inline UInt32 GetValue32(const void *addr) { return GetUi32(addr); } -inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value); } +inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value) } const unsigned kNumRegBits = 3; const UInt32 kNumRegs = 1 << kNumRegBits; @@ -58,7 +58,7 @@ namespace NGlobalOffset } -#ifdef RARVM_VM_ENABLE +#ifdef Z7_RARVM_VM_ENABLE enum ECommand { @@ -104,14 +104,14 @@ struct CBlockRef class CProgram { - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE void ReadProgram(const Byte *code, UInt32 codeSize); public: CRecordVector Commands; #endif public: - #ifdef RARVM_STANDARD_FILTERS + #ifdef Z7_RARVM_STANDARD_FILTERS int StandardFilterIndex; #endif @@ -150,7 +150,7 @@ class CVm if (byteMode) *(Byte *)addr = (Byte)value; else - SetUi32(addr, value); + SetUi32(addr, value) } UInt32 GetFixedGlobalValue32(UInt32 globalOffset) { return GetValue(false, &Mem[kGlobalOffset + globalOffset]); } @@ -162,7 +162,7 @@ class CVm private: - #ifdef RARVM_VM_ENABLE + #ifdef Z7_RARVM_VM_ENABLE UInt32 GetOperand32(const COperand *op) const; void SetOperand32(const COperand *op, UInt32 val); Byte GetOperand8(const COperand *op) const; @@ -172,7 +172,7 @@ class CVm bool ExecuteCode(const CProgram *prg); #endif - #ifdef RARVM_STANDARD_FILTERS + #ifdef Z7_RARVM_STANDARD_FILTERS bool ExecuteStandardFilter(unsigned filterIndex); #endif diff --git a/CPP/7zip/Compress/Rar5Decoder.cpp b/CPP/7zip/Compress/Rar5Decoder.cpp index caabb316..e55d7de3 100644 --- a/CPP/7zip/Compress/Rar5Decoder.cpp +++ b/CPP/7zip/Compress/Rar5Decoder.cpp @@ -21,12 +21,12 @@ void CBitDecoder::Prepare2() throw() if (_buf > _bufLim) return; - size_t rem = _bufLim - _buf; + size_t rem = (size_t)(_bufLim - _buf); if (rem != 0) memmove(_bufBase, _buf, rem); _bufLim = _bufBase + rem; - _processedSize += (_buf - _bufBase); + _processedSize += (size_t)(_buf - _bufBase); _buf = _bufBase; if (!_wasFinished) @@ -42,7 +42,7 @@ void CBitDecoder::Prepare2() throw() } } - rem = _bufLim - _buf; + rem = (size_t)(_bufLim - _buf); _bufCheck = _buf; if (rem < kSize) memset(_bufLim, 0xFF, kSize - rem); @@ -92,7 +92,7 @@ HRESULT CDecoder::WriteData(const Byte *data, size_t size) size_t cur = size; if (_unpackSize_Defined) { - UInt64 rem = _unpackSize - _writtenFileSize; + const UInt64 rem = _unpackSize - _writtenFileSize; if (cur > rem) cur = (size_t)rem; } @@ -122,26 +122,26 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f) if (dataSize > 4) { dataSize -= 4; - UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); + const UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); const UInt32 kFileSize = (UInt32)1 << 24; - Byte cmpMask = (Byte)(f.Type == FILTER_E8 ? 0xFF : 0xFE); + const Byte cmpMask = (Byte)(f.Type == FILTER_E8 ? 0xFF : 0xFE); for (UInt32 curPos = 0; curPos < dataSize;) { curPos++; if (((*data++) & cmpMask) == 0xE8) { - UInt32 offset = (curPos + fileOffset) & (kFileSize - 1); - UInt32 addr = GetUi32(data); + const UInt32 offset = (curPos + fileOffset) & (kFileSize - 1); + const UInt32 addr = GetUi32(data); if (addr < kFileSize) { - SetUi32(data, addr - offset); + SetUi32(data, addr - offset) } else if (addr > ((UInt32)0xFFFFFFFF - offset)) // (addr > ~(offset)) { - SetUi32(data, addr + kFileSize); + SetUi32(data, addr + kFileSize) } data += 4; @@ -157,7 +157,7 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f) if (dataSize >= 4) { dataSize -= 4; - UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); + const UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); for (UInt32 curPos = 0; curPos <= dataSize; curPos += 4) { @@ -183,7 +183,7 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f) return E_OUTOFMEMORY; Byte *dest = _filterDst; - UInt32 numChannels = f.Channels; + const UInt32 numChannels = f.Channels; for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) { @@ -216,27 +216,27 @@ HRESULT CDecoder::WriteBuf() { const CFilter &f = _filters[i]; - UInt64 blockStart = f.Start; + const UInt64 blockStart = f.Start; - size_t lzAvail = (size_t)(_lzSize - _lzWritten); + const size_t lzAvail = (size_t)(_lzSize - _lzWritten); if (lzAvail == 0) break; if (blockStart > _lzWritten) { - UInt64 rem = blockStart - _lzWritten; + const UInt64 rem = blockStart - _lzWritten; size_t size = lzAvail; if (size > rem) size = (size_t)rem; if (size != 0) { - RINOK(WriteData(_window + _winPos - lzAvail, size)); + RINOK(WriteData(_window + _winPos - lzAvail, size)) _lzWritten += size; } continue; } - UInt32 blockSize = f.Size; + const UInt32 blockSize = f.Size; size_t offset = (size_t)(_lzWritten - blockStart); if (offset == 0) { @@ -245,7 +245,7 @@ HRESULT CDecoder::WriteBuf() return E_OUTOFMEMORY; } - size_t blockRem = (size_t)blockSize - offset; + const size_t blockRem = (size_t)blockSize - offset; size_t size = lzAvail; if (size > blockRem) size = blockRem; @@ -256,7 +256,7 @@ HRESULT CDecoder::WriteBuf() return S_OK; _numUnusedFilters = ++i; - RINOK(ExecuteFilter(f)); + RINOK(ExecuteFilter(f)) } DeleteUnusedFilters(); @@ -264,8 +264,8 @@ HRESULT CDecoder::WriteBuf() if (!_filters.IsEmpty()) return S_OK; - size_t lzAvail = (size_t)(_lzSize - _lzWritten); - RINOK(WriteData(_window + _winPos - lzAvail, lzAvail)); + const size_t lzAvail = (size_t)(_lzSize - _lzWritten); + RINOK(WriteData(_window + _winPos - lzAvail, lzAvail)) _lzWritten += lzAvail; return S_OK; } @@ -273,7 +273,7 @@ HRESULT CDecoder::WriteBuf() static UInt32 ReadUInt32(CBitDecoder &bi) { - unsigned numBytes = bi.ReadBits9fix(2) + 1; + const unsigned numBytes = bi.ReadBits9fix(2) + 1; UInt32 v = 0; for (unsigned i = 0; i < numBytes; i++) v += ((UInt32)bi.ReadBits9fix(8) << (i * 8)); @@ -289,7 +289,7 @@ HRESULT CDecoder::AddFilter(CBitDecoder &_bitStream) if (_filters.Size() >= MAX_UNPACK_FILTERS) { - RINOK(WriteBuf()); + RINOK(WriteBuf()) DeleteUnusedFilters(); if (_filters.Size() >= MAX_UNPACK_FILTERS) { @@ -301,7 +301,7 @@ HRESULT CDecoder::AddFilter(CBitDecoder &_bitStream) _bitStream.Prepare(); CFilter f; - UInt32 blockStart = ReadUInt32(_bitStream); + const UInt32 blockStart = ReadUInt32(_bitStream); f.Size = ReadUInt32(_bitStream); if (f.Size > ((UInt32)1 << 22)) @@ -336,17 +336,17 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream) if (_progress) { const UInt64 packSize = _bitStream.GetProcessedSize(); - RINOK(_progress->SetRatioInfo(&packSize, &_writtenFileSize)); + RINOK(_progress->SetRatioInfo(&packSize, &_writtenFileSize)) } _bitStream.AlignToByte(); _bitStream.Prepare(); { - unsigned flags = _bitStream.ReadByteInAligned(); + const unsigned flags = _bitStream.ReadByteInAligned(); unsigned checkSum = _bitStream.ReadByteInAligned(); checkSum ^= flags; - unsigned num = (flags >> 3) & 3; + const unsigned num = (flags >> 3) & 3; if (num == 3) return S_FALSE; UInt32 blockSize = _bitStream.ReadByteInAligned(); @@ -399,7 +399,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream) for (unsigned i = 0; i < kLevelTableSize;) { _bitStream.Prepare(); - unsigned len = (unsigned)_bitStream.ReadBits9fix(4); + const unsigned len = (unsigned)_bitStream.ReadBits9fix(4); if (len == 15) { unsigned num = (unsigned)_bitStream.ReadBits9fix(4); @@ -421,7 +421,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream) if (_bitStream.IsBlockOverRead()) return S_FALSE; - RIF(m_LevelDecoder.Build(lens2)); + RIF(m_LevelDecoder.Build(lens2)) } Byte lens[kTablesSizesSum]; @@ -437,7 +437,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream) return S_FALSE; } - UInt32 sym = m_LevelDecoder.Decode(&_bitStream); + const UInt32 sym = m_LevelDecoder.Decode(&_bitStream); if (sym < 16) lens[i++] = (Byte)sym; @@ -469,10 +469,10 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream) if (_bitStream.InputEofError()) return S_FALSE; - RIF(m_MainDecoder.Build(&lens[0])); - RIF(m_DistDecoder.Build(&lens[kMainTableSize])); - RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])); - RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])); + RIF(m_MainDecoder.Build(&lens[0])) + RIF(m_DistDecoder.Build(&lens[kMainTableSize])) + RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])) + RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])) _useAlignBits = false; // _useAlignBits = true; @@ -492,7 +492,7 @@ static inline unsigned SlotToLen(CBitDecoder &_bitStream, unsigned slot) { if (slot < 8) return slot + 2; - unsigned numBits = (slot >> 2) - 1; + const unsigned numBits = (slot >> 2) - 1; return 2 + ((4 | (slot & 3)) << numBits) + _bitStream.ReadBits9(numBits); } @@ -523,7 +523,7 @@ HRESULT CDecoder::DecodeLZ() { if (_winPos >= limit) { - RINOK(WriteBuf()); + RINOK(WriteBuf()) if (_unpackSize_Defined && _writtenFileSize > _unpackSize) break; // return S_FALSE; @@ -543,7 +543,7 @@ HRESULT CDecoder::DecodeLZ() if (remLen != 0) { size_t winPos = _winPos; - size_t winMask = _winMask; + const size_t winMask = _winMask; size_t pos = (winPos - (size_t)rep0 - 1) & winMask; Byte *win = _window; @@ -570,13 +570,13 @@ HRESULT CDecoder::DecodeLZ() if (_bitStream._buf >= _bitStream._bufCheck) _bitStream.Prepare2(); - UInt64 processed = _bitStream.GetProcessedSize_Round(); + const UInt64 processed = _bitStream.GetProcessedSize_Round(); if (processed >= _bitStream._blockEnd) { if (processed > _bitStream._blockEnd) break; // return S_FALSE; { - unsigned bits7 = _bitStream.GetProcessedBits7(); + const unsigned bits7 = _bitStream.GetProcessedBits7(); if (bits7 > _bitStream._blockEndBits7) break; // return S_FALSE; if (bits7 == _bitStream._blockEndBits7) @@ -597,7 +597,7 @@ HRESULT CDecoder::DecodeLZ() return _bitStream._hres; // break; } - RINOK(ReadTables(_bitStream)); + RINOK(ReadTables(_bitStream)) continue; } } @@ -608,7 +608,7 @@ HRESULT CDecoder::DecodeLZ() break; // return S_FALSE; } - UInt32 sym = m_MainDecoder.Decode(&_bitStream); + const UInt32 sym = m_MainDecoder.Decode(&_bitStream); if (sym < 256) { @@ -654,7 +654,7 @@ HRESULT CDecoder::DecodeLZ() { if (sym == 256) { - RINOK(AddFilter(_bitStream)); + RINOK(AddFilter(_bitStream)) continue; } else // if (sym == 257) @@ -682,7 +682,7 @@ HRESULT CDecoder::DecodeLZ() { if (rep0 >= _numCorrectDistSymbols) break; // return S_FALSE; - unsigned numBits = (rep0 >> 1) - 1; + const unsigned numBits = (rep0 >> 1) - 1; rep0 = (2 | (rep0 & 1)) << numBits; if (numBits < kNumAlignBits) @@ -697,7 +697,7 @@ HRESULT CDecoder::DecodeLZ() { // if (numBits > kNumAlignBits) rep0 += (_bitStream.ReadBits32(numBits - kNumAlignBits) << kNumAlignBits); - UInt32 a = m_AlignDecoder.Decode(&_bitStream); + const UInt32 a = m_AlignDecoder.Decode(&_bitStream); if (a >= kAlignTableSize) break; // return S_FALSE; rep0 += a; @@ -718,7 +718,7 @@ HRESULT CDecoder::DecodeLZ() size_t winPos = _winPos; size_t pos = (winPos - (size_t)rep0 - 1) & _winMask; { - size_t rem = limit - winPos; + const size_t rem = limit - winPos; // size_t rem = _winSize - winPos; if (lenCur > rem) @@ -825,8 +825,8 @@ HRESULT CDecoder::CodeReal() static const unsigned kWinSize_Log_Min = 17; -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 { @@ -850,7 +850,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream memset(_window, 0, _winSize); else { - size_t pos = (size_t)_lzSize & _winSize; + const size_t pos = (size_t)_lzSize & _winSize; size_t rem2 = _winSize - pos; if (rem2 > rem) rem2 = (size_t)rem; @@ -905,10 +905,10 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream // but the original unRAR decoder still supports such grow case. Byte *winOld = _window; - size_t oldSize = _winSize; - size_t newMask = newSize - 1; - size_t oldMask = _winSize - 1; - size_t winPos = _winPos; + const size_t oldSize = _winSize; + const size_t newMask = newSize - 1; + const size_t oldMask = _winSize - 1; + const size_t winPos = _winPos; for (size_t i = 1; i <= oldSize; i++) win[(winPos - i) & newMask] = winOld[(winPos - i) & oldMask]; ::MidFree(_window); @@ -951,7 +951,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream _progress = progress; - HRESULT res = CodeReal(); + const HRESULT res = CodeReal(); if (res != S_OK) return res; @@ -968,7 +968,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream // by error in data stream. } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)) { if (size != 2) return E_NOTIMPL; diff --git a/CPP/7zip/Compress/Rar5Decoder.h b/CPP/7zip/Compress/Rar5Decoder.h index 8174c4af..daf05dd8 100644 --- a/CPP/7zip/Compress/Rar5Decoder.h +++ b/CPP/7zip/Compress/Rar5Decoder.h @@ -2,8 +2,8 @@ // According to unRAR license, this code may not be used to develop // a program that creates RAR archives -#ifndef __COMPRESS_RAR5_DECODER_H -#define __COMPRESS_RAR5_DECODER_H +#ifndef ZIP7_INC_COMPRESS_RAR5_DECODER_H +#define ZIP7_INC_COMPRESS_RAR5_DECODER_H #include "../../../C/CpuArch.h" @@ -19,7 +19,6 @@ namespace NCompress { namespace NRar5 { - /* struct CInBufferException: public CSystemException { @@ -55,7 +54,7 @@ class CBitDecoder _bufCheck2 = _buf; else { - UInt64 delta = _blockEnd - processed; + const UInt64 delta = _blockEnd - processed; if ((size_t)(_bufCheck - _buf) > delta) _bufCheck2 = _buf + (size_t)delta; } @@ -64,7 +63,7 @@ class CBitDecoder bool IsBlockOverRead() const { - UInt64 v = GetProcessedSize_Round(); + const UInt64 v = GetProcessedSize_Round(); if (v < _blockEnd) return false; if (v > _blockEnd) @@ -113,8 +112,8 @@ class CBitDecoder bool InputEofError() const { return ExtraBitsWereRead(); } unsigned GetProcessedBits7() const { return _bitPos; } - UInt64 GetProcessedSize_Round() const { return _processedSize + (_buf - _bufBase); } - UInt64 GetProcessedSize() const { return _processedSize + (_buf - _bufBase) + ((_bitPos + 7) >> 3); } + UInt64 GetProcessedSize_Round() const { return _processedSize + (size_t)(_buf - _bufBase); } + UInt64 GetProcessedSize() const { return _processedSize + (size_t)(_buf - _bufBase) + ((_bitPos + 7) >> 3); } void AlignToByte() { @@ -157,7 +156,7 @@ class CBitDecoder { const Byte *buf = _buf; UInt32 v = ((UInt32)buf[0] << 8) | (UInt32)buf[1]; - UInt32 mask = ((1 << numBits) - 1); + const UInt32 mask = ((1 << numBits) - 1); numBits += _bitPos; v >>= (16 - numBits); _buf = buf + (numBits >> 3); @@ -167,7 +166,7 @@ class CBitDecoder UInt32 ReadBits32(unsigned numBits) { - UInt32 mask = ((1 << numBits) - 1); + const UInt32 mask = ((1 << numBits) - 1); numBits += _bitPos; const Byte *buf = _buf; UInt32 v = GetBe32(buf); @@ -205,11 +204,11 @@ const unsigned kTablesSizesSum = kMainTableSize + kDistTableSize + kAlignTableSi const unsigned kNumHuffmanBits = 15; -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ +Z7_CLASS_IMP_NOQIB_2( + CDecoder + , ICompressCoder + , ICompressSetDecoderProperties2 +) bool _useAlignBits; bool _isLastBlock; bool _unpackSize_Defined; @@ -293,13 +292,6 @@ class CDecoder: public: CDecoder(); ~CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); }; }} diff --git a/CPP/7zip/Compress/ShrinkDecoder.cpp b/CPP/7zip/Compress/ShrinkDecoder.cpp index 22f3844c..c8e2083c 100644 --- a/CPP/7zip/Compress/ShrinkDecoder.cpp +++ b/CPP/7zip/Compress/ShrinkDecoder.cpp @@ -198,7 +198,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * while (i); } - RINOK(outBuffer.Flush()); + RINOK(outBuffer.Flush()) if (res == S_OK) if (_fullStreamMode) @@ -216,8 +216,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * } -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::Code(ISequentialInStream *inStream, ISequentialOutStream } -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 --git a/CPP/7zip/Compress/ShrinkDecoder.h b/CPP/7zip/Compress/ShrinkDecoder.h index b095b5f4..5e7f78f3 100644 --- a/CPP/7zip/Compress/ShrinkDecoder.h +++ b/CPP/7zip/Compress/ShrinkDecoder.h @@ -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 @@ namespace NShrink { 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 @@ class CDecoder : 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 --git a/CPP/7zip/Compress/StdAfx.h b/CPP/7zip/Compress/StdAfx.h index 1cbd7fea..80866550 100644 --- a/CPP/7zip/Compress/StdAfx.h +++ b/CPP/7zip/Compress/StdAfx.h @@ -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 --git a/CPP/7zip/Compress/XpressDecoder.cpp b/CPP/7zip/Compress/XpressDecoder.cpp index a8bbd008..8816a125 100644 --- a/CPP/7zip/Compress/XpressDecoder.cpp +++ b/CPP/7zip/Compress/XpressDecoder.cpp @@ -50,7 +50,7 @@ HRESULT Decode(const Byte *in, size_t inSize, Byte *out, size_t outSize) 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 @@ HRESULT Decode(const Byte *in, size_t inSize, Byte *out, size_t outSize) 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 --git a/CPP/7zip/Compress/XpressDecoder.h b/CPP/7zip/Compress/XpressDecoder.h index cada85bf..aaa5b25b 100644 --- a/CPP/7zip/Compress/XpressDecoder.h +++ b/CPP/7zip/Compress/XpressDecoder.h @@ -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 --git a/CPP/7zip/Compress/XzDecoder.cpp b/CPP/7zip/Compress/XzDecoder.cpp index 0371173c..420bd714 100644 --- a/CPP/7zip/Compress/XzDecoder.cpp +++ b/CPP/7zip/Compress/XzDecoder.cpp @@ -50,10 +50,10 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream 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 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream MainDecodeSRes = res; - #ifndef _7ZIP_ST + #ifndef Z7_ST // _tryMt = isMT; #endif @@ -113,33 +113,33 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream } -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 --git a/CPP/7zip/Compress/XzDecoder.h b/CPP/7zip/Compress/XzDecoder.h index 7ad81f49..40ed4f5c 100644 --- a/CPP/7zip/Compress/XzDecoder.h +++ b/CPP/7zip/Compress/XzDecoder.h @@ -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 @@ struct CDecoder }; -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 --git a/CPP/7zip/Compress/XzEncoder.cpp b/CPP/7zip/Compress/XzEncoder.cpp index d6f42caf..33f0bde4 100644 --- a/CPP/7zip/Compress/XzEncoder.cpp +++ b/CPP/7zip/Compress/XzEncoder.cpp @@ -15,9 +15,7 @@ namespace NCompress { namespace NLzma2 { - HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzma2Props); - } namespace NXz { @@ -63,7 +61,7 @@ static const CMethodNamePair g_NamePairs[] = 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 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop) { 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 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop) } 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 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop) 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 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop) } -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::SetCoderProperties(const PROPID *propIDs, } -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 @@ STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, #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 --git a/CPP/7zip/Compress/XzEncoder.h b/CPP/7zip/Compress/XzEncoder.h index ea5190ee..434f5820 100644 --- a/CPP/7zip/Compress/XzEncoder.h +++ b/CPP/7zip/Compress/XzEncoder.h @@ -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 --git a/CPP/7zip/Compress/ZDecoder.cpp b/CPP/7zip/Compress/ZDecoder.cpp index 06eab00e..07c5fe5f 100644 --- a/CPP/7zip/Compress/ZDecoder.cpp +++ b/CPP/7zip/Compress/ZDecoder.cpp @@ -22,9 +22,9 @@ static const unsigned kNumMaxBits = 16; 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 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * { 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 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream * 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 @@ bool CheckStream(const Byte *data, size_t size) 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 @@ bool CheckStream(const Byte *data, size_t size) { 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 --git a/CPP/7zip/Compress/ZDecoder.h b/CPP/7zip/Compress/ZDecoder.h index 19acd498..390b013d 100644 --- a/CPP/7zip/Compress/ZDecoder.h +++ b/CPP/7zip/Compress/ZDecoder.h @@ -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 @@ namespace NZ { // 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 --git a/CPP/7zip/Compress/ZlibDecoder.cpp b/CPP/7zip/Compress/ZlibDecoder.cpp index 2356c7c5..a0669320 100644 --- a/CPP/7zip/Compress/ZlibDecoder.cpp +++ b/CPP/7zip/Compress/ZlibDecoder.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include "../../../C/CpuArch.h" + #include "../Common/StreamUtils.h" #include "ZlibDecoder.h" @@ -22,7 +24,7 @@ UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size) 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 @@ UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size) 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 @@ STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *p 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream 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 --git a/CPP/7zip/Compress/ZlibDecoder.h b/CPP/7zip/Compress/ZlibDecoder.h index 8c5e73b0..1dc5c67d 100644 --- a/CPP/7zip/Compress/ZlibDecoder.h +++ b/CPP/7zip/Compress/ZlibDecoder.h @@ -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 @@ namespace NZlib { 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 @@ class COutStreamWithAdler: 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 @@ static bool inline IsZlib_3bytes(const Byte *p) { 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 --git a/CPP/7zip/Compress/ZlibEncoder.cpp b/CPP/7zip/Compress/ZlibEncoder.cpp index 09235c33..3670d303 100644 --- a/CPP/7zip/Compress/ZlibEncoder.cpp +++ b/CPP/7zip/Compress/ZlibEncoder.cpp @@ -14,12 +14,12 @@ namespace NZlib { 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 @@ void CEncoder::Create() 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 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream { 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 --git a/CPP/7zip/Compress/ZlibEncoder.h b/CPP/7zip/Compress/ZlibEncoder.h index 621cc1d0..484a307c 100644 --- a/CPP/7zip/Compress/ZlibEncoder.h +++ b/CPP/7zip/Compress/ZlibEncoder.h @@ -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 @@ class CInStreamWithAdler: 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 @@ class CEncoder: 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 --git a/CPP/7zip/Compress/ZstdDecoder.cpp b/CPP/7zip/Compress/ZstdDecoder.cpp index 8c201bf2..9661fe16 100644 --- a/CPP/7zip/Compress/ZstdDecoder.cpp +++ b/CPP/7zip/Compress/ZstdDecoder.cpp @@ -27,7 +27,7 @@ CDecoder::~CDecoder() } } -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size) +Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte * prop, UInt32 size)) { DProps *pProps = (DProps *)prop; @@ -49,10 +49,10 @@ HRESULT CDecoder::SetOutStreamSizeResume(const UInt64 * /*outSize*/) return S_OK; } -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 * outSize) +Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 * outSize)) { _processedIn = 0; - RINOK(SetOutStreamSizeResume(outSize)); + RINOK(SetOutStreamSizeResume(outSize)) return S_OK; } @@ -90,7 +90,7 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, srcBufLen = _srcBufSize; /* read first input block */ - RINOK(ReadStream(inStream, _srcBuf, &srcBufLen)); + RINOK(ReadStream(inStream, _srcBuf, &srcBufLen)) _processedIn += srcBufLen; zIn.src = _srcBuf; @@ -124,11 +124,11 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, /* write decompressed result */ if (zOut.pos) { - RINOK(WriteStream(outStream, _dstBuf, zOut.pos)); + RINOK(WriteStream(outStream, _dstBuf, zOut.pos)) _processedOut += zOut.pos; if (progress) { - RINOK(progress->SetRatioInfo(&_processedIn, &_processedOut)); + RINOK(progress->SetRatioInfo(&_processedIn, &_processedOut)) } } @@ -153,7 +153,7 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, /* read next input */ srcBufLen = _srcBufSize; - RINOK(ReadStream(inStream, _srcBuf, &srcBufLen)); + RINOK(ReadStream(inStream, _srcBuf, &srcBufLen)) _processedIn += srcBufLen; /* finished */ @@ -165,35 +165,35 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream * inStream, } } -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)) { SetOutStreamSize(outSize); return CodeSpec(inStream, outStream, progress); } -#ifndef NO_READ_FROM_CODER -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream * inStream) +#ifndef Z7_NO_READ_FROM_CODER +Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream * inStream)) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() +Z7_COM7F_IMF(CDecoder::ReleaseInStream()) { _inStream.Release(); return S_OK; } #endif -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 /* numThreads */) +Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 /* numThreads */)) { return S_OK; } HRESULT CDecoder::CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress) { - RINOK(SetOutStreamSizeResume(outSize)); + RINOK(SetOutStreamSizeResume(outSize)) return CodeSpec(_inStream, outStream, progress); } diff --git a/CPP/7zip/Compress/ZstdDecoder.h b/CPP/7zip/Compress/ZstdDecoder.h index fe16ebf0..32ea77c7 100644 --- a/CPP/7zip/Compress/ZstdDecoder.h +++ b/CPP/7zip/Compress/ZstdDecoder.h @@ -48,12 +48,15 @@ struct DProps Byte _reserved[2]; }; -class CDecoder:public ICompressCoder, +class CDecoder Z7_final: + public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressSetCoderMt, public CMyUnknownImp { CMyComPtr < ISequentialInStream > _inStream; + +public: DProps _props; ZSTD_DCtx* _ctx; @@ -66,30 +69,28 @@ class CDecoder:public ICompressCoder, UInt64 _processedOut; HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); + HRESULT CodeResume(ISequentialOutStream * outStream, const UInt64 * outSize, ICompressProgressInfo * progress); HRESULT SetOutStreamSizeResume(const UInt64 *outSize); + + Z7_COM_QI_BEGIN2(ICompressCoder) + Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2) + Z7_COM_QI_ENTRY(ICompressSetCoderMt) + Z7_COM_QI_END + Z7_COM_ADDREF_RELEASE + + Z7_IFACE_COM7_IMP(ICompressCoder) + Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2) public: + Z7_IFACE_COM7_IMP(ICompressSetCoderMt) - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) -#ifndef NO_READ_FROM_CODER - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) -#endif - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - 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 (SetOutStreamSize)(const UInt64 *outSize); - STDMETHOD (SetNumberOfThreads)(UInt32 numThreads); - -#ifndef NO_READ_FROM_CODER - STDMETHOD (SetInStream)(ISequentialInStream *inStream); - STDMETHOD (ReleaseInStream)(); + Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize)); +#ifndef Z7_NO_READ_FROM_CODER + Z7_COM7F_IMF(SetInStream(ISequentialInStream *inStream)); + Z7_COM7F_IMF(ReleaseInStream()); UInt64 GetInputProcessedSize() const { return _processedIn; } #endif - HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); +public: CDecoder(); virtual ~CDecoder(); }; diff --git a/CPP/7zip/Compress/ZstdEncoder.cpp b/CPP/7zip/Compress/ZstdEncoder.cpp index dda80153..cefdc5da 100644 --- a/CPP/7zip/Compress/ZstdEncoder.cpp +++ b/CPP/7zip/Compress/ZstdEncoder.cpp @@ -4,7 +4,7 @@ #include "ZstdEncoder.h" #include "ZstdDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NZSTD { @@ -47,7 +47,7 @@ CEncoder::~CEncoder() } } -STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps) +Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARIANT * coderProps, UInt32 numProps)) { _props.clear(); @@ -212,14 +212,14 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID * propIDs, const PROPVARI return S_OK; } -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream * outStream) +Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream * outStream)) { return WriteStream(outStream, &_props, sizeof (_props)); } -STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, +Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /*inSize*/ , - const UInt64 * /*outSize */, ICompressProgressInfo *progress) + const UInt64 * /*outSize */, ICompressProgressInfo *progress)) { ZSTD_EndDirective ZSTD_todo = ZSTD_e_continue; ZSTD_outBuffer outBuff; @@ -349,7 +349,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, /* read input */ srcSize = _srcBufSize; - RINOK(ReadStream(inStream, _srcBuf, &srcSize)); + RINOK(ReadStream(inStream, _srcBuf, &srcSize)) /* eof */ if (srcSize == 0) @@ -393,12 +393,12 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, /* write output */ if (outBuff.pos) { - RINOK(WriteStream(outStream, _dstBuf, outBuff.pos)); + RINOK(WriteStream(outStream, _dstBuf, outBuff.pos)) _processedOut += outBuff.pos; } if (progress) - RINOK(progress->SetRatioInfo(&_processedIn, &_processedOut)); + RINOK(progress->SetRatioInfo(&_processedIn, &_processedOut)) /* done */ if (ZSTD_todo == ZSTD_e_end && err == 0) @@ -411,7 +411,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, } } -STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) +Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads)) { const UInt32 kNumThreadsMax = ZSTD_THREAD_MAX; if (numThreads < 1) numThreads = 1; diff --git a/CPP/7zip/Compress/ZstdEncoder.h b/CPP/7zip/Compress/ZstdEncoder.h index 1b3a61a0..7e9da5d2 100644 --- a/CPP/7zip/Compress/ZstdEncoder.h +++ b/CPP/7zip/Compress/ZstdEncoder.h @@ -10,7 +10,7 @@ #include "../ICoder.h" #include "../Common/StreamUtils.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY namespace NCompress { namespace NZSTD { @@ -31,13 +31,14 @@ struct CProps Byte _reserved[2]; }; -class CEncoder: - public ICompressCoder, - public ICompressSetCoderMt, - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_4( + CEncoder, + ICompressCoder, + ICompressSetCoderMt, + ICompressSetCoderProperties, + ICompressWriteCoderProperties +) +public: CProps _props; ZSTD_CCtx* _ctx; @@ -66,26 +67,12 @@ class CEncoder: Int32 _LdmBucketSizeLog; Int32 _LdmHashRateLog; -public: - int dictIDFlag; int checksumFlag; UInt64 unpackSize; - MY_QUERYINTERFACE_BEGIN2(ICompressCoder) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt) - MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties) - MY_QUERYINTERFACE_ENTRY(ICompressWriteCoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - 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 (SetNumberOfThreads)(UInt32 numThreads); - CEncoder(); - virtual ~CEncoder(); + ~CEncoder(); }; }} diff --git a/CPP/7zip/Compress/ZstdRegister.cpp b/CPP/7zip/Compress/ZstdRegister.cpp index 94abdd74..8eb7f4df 100644 --- a/CPP/7zip/Compress/ZstdRegister.cpp +++ b/CPP/7zip/Compress/ZstdRegister.cpp @@ -6,7 +6,7 @@ #include "ZstdDecoder.h" -#ifndef EXTRACT_ONLY +#ifndef Z7_EXTRACT_ONLY #include "ZstdEncoder.h" #endif diff --git a/CPP/7zip/Crypto/7zAes.cpp b/CPP/7zip/Crypto/7zAes.cpp index 7f34e910..6b1c648d 100644 --- a/CPP/7zip/Crypto/7zAes.cpp +++ b/CPP/7zip/Crypto/7zAes.cpp @@ -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 @@ void CKeyInfo::CalcKey() 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 @@ void CKeyInfoCache::Add(const CKeyInfo &key) 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 @@ void CBase::PrepareKey() 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::ResetSalt() } */ -STDMETHODIMP CEncoder::ResetInitVector() +Z7_COM7F_IMF(CEncoder::ResetInitVector()) { for (unsigned i = 0; i < sizeof(_iv); i++) _iv[i] = 0; @@ -205,7 +205,7 @@ STDMETHODIMP CEncoder::ResetInitVector() 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 @@ CDecoder::CDecoder() _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 CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) } -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 @@ STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) 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 --git a/CPP/7zip/Crypto/7zAes.h b/CPP/7zip/Crypto/7zAes.h index a67ac0b6..8f7bf03e 100644 --- a/CPP/7zip/Crypto/7zAes.h +++ b/CPP/7zip/Crypto/7zAes.h @@ -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 @@ class CKeyInfo 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 @@ class CBaseCoder: 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 --git a/CPP/7zip/Crypto/7zAesRegister.cpp b/CPP/7zip/Crypto/7zAesRegister.cpp index 35605f43..69d0890a 100644 --- a/CPP/7zip/Crypto/7zAesRegister.cpp +++ b/CPP/7zip/Crypto/7zAesRegister.cpp @@ -9,7 +9,7 @@ namespace NCrypto { namespace N7z { -REGISTER_FILTER_E(_7zAES, +REGISTER_FILTER_E(SzAES, CDecoder, CEncoder, 0x6F10701, "7zAES") diff --git a/CPP/7zip/Crypto/HmacSha1.cpp b/CPP/7zip/Crypto/HmacSha1.cpp index d085bb05..30b1a8f6 100644 --- a/CPP/7zip/Crypto/HmacSha1.cpp +++ b/CPP/7zip/Crypto/HmacSha1.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha1.h" diff --git a/CPP/7zip/Crypto/HmacSha1.h b/CPP/7zip/Crypto/HmacSha1.h index d4b21b36..a36c78e1 100644 --- a/CPP/7zip/Crypto/HmacSha1.h +++ b/CPP/7zip/Crypto/HmacSha1.h @@ -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 --git a/CPP/7zip/Crypto/HmacSha256.cpp b/CPP/7zip/Crypto/HmacSha256.cpp index cec5e752..56f8ede1 100644 --- a/CPP/7zip/Crypto/HmacSha256.cpp +++ b/CPP/7zip/Crypto/HmacSha256.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha256.h" diff --git a/CPP/7zip/Crypto/HmacSha256.h b/CPP/7zip/Crypto/HmacSha256.h index d709f43d..4039c0ce 100644 --- a/CPP/7zip/Crypto/HmacSha256.h +++ b/CPP/7zip/Crypto/HmacSha256.h @@ -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 --git a/CPP/7zip/Crypto/MyAes.cpp b/CPP/7zip/Crypto/MyAes.cpp index 5cb7f463..6abc3881 100644 --- a/CPP/7zip/Crypto/MyAes.cpp +++ b/CPP/7zip/Crypto/MyAes.cpp @@ -10,11 +10,16 @@ namespace NCrypto { 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 @@ CAesCoder::CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode): 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 @@ STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size) #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; } + + + +#ifndef Z7_SFX +SET_AES_FUNCS( + CAesCtrCoder, + g_AesCtr_Code, + AesCtr_Code, + AesCtr_Code_HW, + AesCtr_Code_HW_256) #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 - - return false; - - #endif -} - - -#ifndef _SFX - -STDMETHODIMP CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) +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) + +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 @@ STDMETHODIMP CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARI return S_OK; } -#endif +#endif // Z7_EXTRACT_ONLY } diff --git a/CPP/7zip/Crypto/MyAes.h b/CPP/7zip/Crypto/MyAes.h index a60042be..a3c1c27f 100644 --- a/CPP/7zip/Crypto/MyAes.h +++ b/CPP/7zip/Crypto/MyAes.h @@ -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 --git a/CPP/7zip/Crypto/MyAesReg.cpp b/CPP/7zip/Crypto/MyAesReg.cpp index 86bd2547..e2b4f72d 100644 --- a/CPP/7zip/Crypto/MyAesReg.cpp +++ b/CPP/7zip/Crypto/MyAesReg.cpp @@ -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 --git a/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp b/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp index 6b504ee9..3d9e4c1a 100644 --- a/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp +++ b/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +#include + #include "../../../C/CpuArch.h" #include "HmacSha1.h" @@ -28,7 +30,7 @@ void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, 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 @@ void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, 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 --git a/CPP/7zip/Crypto/Pbkdf2HmacSha1.h b/CPP/7zip/Crypto/Pbkdf2HmacSha1.h index e9462e47..89cbe414 100644 --- a/CPP/7zip/Crypto/Pbkdf2HmacSha1.h +++ b/CPP/7zip/Crypto/Pbkdf2HmacSha1.h @@ -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 --git a/CPP/7zip/Crypto/RandGen.cpp b/CPP/7zip/Crypto/RandGen.cpp index 65633fd8..05a6c06d 100644 --- a/CPP/7zip/Crypto/RandGen.cpp +++ b/CPP/7zip/Crypto/RandGen.cpp @@ -6,7 +6,7 @@ #ifndef USE_STATIC_SYSTEM_RAND -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #endif @@ -76,9 +76,9 @@ void CRandomGenerator::Init() #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 @@ void CRandomGenerator::Init() } #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 @@ void CRandomGenerator::Init() #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 @@ void CRandomGenerator::Init() #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 @@ void CRandomGenerator::Init() _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 @@ void CRandomGenerator::Generate(Byte *data, unsigned size) 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 @@ void CRandomGenerator::Generate(Byte *data, unsigned size) } } +MY_ALIGN (16) CRandomGenerator g_RandomGenerator; #endif diff --git a/CPP/7zip/Crypto/RandGen.h b/CPP/7zip/Crypto/RandGen.h index 5122ec4b..3bd69ec2 100644 --- a/CPP/7zip/Crypto/RandGen.h +++ b/CPP/7zip/Crypto/RandGen.h @@ -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 @@ class CRandomGenerator 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 --git a/CPP/7zip/Crypto/Rar20Crypto.cpp b/CPP/7zip/Crypto/Rar20Crypto.cpp index 2bbaa931..8e55763c 100644 --- a/CPP/7zip/Crypto/Rar20Crypto.cpp +++ b/CPP/7zip/Crypto/Rar20Crypto.cpp @@ -54,7 +54,7 @@ void CData::SetPassword(const Byte *data, unsigned size) 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 @@ void CData::CryptBlock(Byte *buf, bool encrypt) 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 --git a/CPP/7zip/Crypto/Rar20Crypto.h b/CPP/7zip/Crypto/Rar20Crypto.h index 596619ce..85507182 100644 --- a/CPP/7zip/Crypto/Rar20Crypto.h +++ b/CPP/7zip/Crypto/Rar20Crypto.h @@ -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 @@ class CData ~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 @@ class CData 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 --git a/CPP/7zip/Crypto/Rar5Aes.cpp b/CPP/7zip/Crypto/Rar5Aes.cpp index 5834bbb7..26c61006 100644 --- a/CPP/7zip/Crypto/Rar5Aes.cpp +++ b/CPP/7zip/Crypto/Rar5Aes.cpp @@ -4,7 +4,7 @@ #include "../../../C/CpuArch.h" -#ifndef _7ZIP_ST +#ifndef Z7_ST #include "../../Windows/Synchronization.h" #endif @@ -129,11 +129,11 @@ void CDecoder::SetPassword(const Byte *data, size_t size) } -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 @@ UInt32 CDecoder::Hmac_Convert_Crc32(UInt32 crc) const 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 @@ UInt32 CDecoder::Hmac_Convert_Crc32(UInt32 crc) const 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 @@ void CDecoder::Hmac_Convert_32Bytes(Byte *data) const 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 --git a/CPP/7zip/Crypto/Rar5Aes.h b/CPP/7zip/Crypto/Rar5Aes.h index e779c17b..3cd79920 100644 --- a/CPP/7zip/Crypto/Rar5Aes.h +++ b/CPP/7zip/Crypto/Rar5Aes.h @@ -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 @@ struct CKey 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 @@ class CDecoder: 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 --git a/CPP/7zip/Crypto/RarAes.cpp b/CPP/7zip/Crypto/RarAes.cpp index aa9444cf..878ea3a5 100644 --- a/CPP/7zip/Crypto/RarAes.cpp +++ b/CPP/7zip/Crypto/RarAes.cpp @@ -78,11 +78,11 @@ void CDecoder::SetPassword(const Byte *data, unsigned size) _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 @@ static void UpdatePswDataSha1(Byte *data) 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 --git a/CPP/7zip/Crypto/RarAes.h b/CPP/7zip/Crypto/RarAes.h index 2bb68667..d3c104c8 100644 --- a/CPP/7zip/Crypto/RarAes.h +++ b/CPP/7zip/Crypto/RarAes.h @@ -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 @@ namespace NRar3 { 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 @@ class CDecoder: 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 --git a/CPP/7zip/Crypto/Sha1Cls.h b/CPP/7zip/Crypto/Sha1Cls.h index 34616782..56ae040d 100644 --- a/CPP/7zip/Crypto/Sha1Cls.h +++ b/CPP/7zip/Crypto/Sha1Cls.h @@ -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 --git a/CPP/7zip/Crypto/StdAfx.h b/CPP/7zip/Crypto/StdAfx.h index 1cbd7fea..80866550 100644 --- a/CPP/7zip/Crypto/StdAfx.h +++ b/CPP/7zip/Crypto/StdAfx.h @@ -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 --git a/CPP/7zip/Crypto/WzAes.cpp b/CPP/7zip/Crypto/WzAes.cpp index b422b501..3f2adab0 100644 --- a/CPP/7zip/Crypto/WzAes.cpp +++ b/CPP/7zip/Crypto/WzAes.cpp @@ -23,7 +23,7 @@ const unsigned kAesKeySizeMax = 32; 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 @@ STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) void CBaseCoder::Init2() { + _hmacOverCalc = 0; const unsigned dkSizeMax32 = (2 * kAesKeySizeMax + kPwdVerifSize + 3) / 4; Byte dk[dkSizeMax32 * 4]; @@ -59,7 +60,7 @@ void CBaseCoder::Init2() if (_aesCoderSpec->Init() != S_OK) throw 3; } -STDMETHODIMP CBaseCoder::Init() +Z7_COM7F_IMF(CBaseCoder::Init()) { return S_OK; } @@ -69,7 +70,7 @@ HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) 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 @@ HRESULT CEncoder::WriteFooter(ISequentialOutStream *outStream) } /* -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 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 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 @@ HRESULT CDecoder::CheckMac(ISequentialInStream *inStream, bool &isOK) 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 @@ void AesCtr2_Code(CAesCtr2 *p, Byte *data, SizeT size) /* (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 @@ STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) 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 --git a/CPP/7zip/Crypto/WzAes.h b/CPP/7zip/Crypto/WzAes.h index fa6221c5..113ec81a 100644 --- a/CPP/7zip/Crypto/WzAes.h +++ b/CPP/7zip/Crypto/WzAes.h @@ -9,8 +9,8 @@ specified in "A Password Based File Encryption Utility": - 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 @@ struct CKeyInfo 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 @@ class CBaseCoder: 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 @@ class CBaseCoder: 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 @@ class CBaseCoder: 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 --git a/CPP/7zip/Crypto/ZipCrypto.cpp b/CPP/7zip/Crypto/ZipCrypto.cpp index 8610297a..047e2bd6 100644 --- a/CPP/7zip/Crypto/ZipCrypto.cpp +++ b/CPP/7zip/Crypto/ZipCrypto.cpp @@ -20,14 +20,14 @@ namespace NZip { #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 @@ STDMETHODIMP CCipher::CryptoSetPassword(const Byte *data, UInt32 size) return S_OK; } -STDMETHODIMP CCipher::Init() +Z7_COM7F_IMF(CCipher::Init()) { return S_OK; } @@ -58,7 +58,7 @@ HRESULT CEncoder::WriteHeader_Check16(ISequentialOutStream *outStream, UInt16 cr 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 @@ STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) 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 @@ void CDecoder::Init_BeforeDecode() 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 @@ STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) { DECRYPT_BYTE_1 Byte b = (Byte)(data[i] ^ DECRYPT_BYTE_2); - UPDATE_KEYS(b); + UPDATE_KEYS(b) data[i] = b; } diff --git a/CPP/7zip/Crypto/ZipCrypto.h b/CPP/7zip/Crypto/ZipCrypto.h index d2fe4c4f..485470ed 100644 --- a/CPP/7zip/Crypto/ZipCrypto.h +++ b/CPP/7zip/Crypto/ZipCrypto.h @@ -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 @@ class CCipher: 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 @@ class CCipher: } public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - STDMETHOD(Init)(); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - virtual ~CCipher() { Key0 = KeyMem0 = @@ -59,18 +59,18 @@ class CCipher: } }; -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 --git a/CPP/7zip/Crypto/ZipStrong.cpp b/CPP/7zip/Crypto/ZipStrong.cpp index 895ce949..59698d8f 100644 --- a/CPP/7zip/Crypto/ZipStrong.cpp +++ b/CPP/7zip/Crypto/ZipStrong.cpp @@ -59,36 +59,51 @@ void CKeyInfo::SetPassword(const Byte *data, UInt32 size) 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 @@ HRESULT CDecoder::Init_and_CheckPassword(bool &passwOK) 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 @@ HRESULT CDecoder::Init_and_CheckPassword(bool &passwOK) 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 --git a/CPP/7zip/Crypto/ZipStrong.h b/CPP/7zip/Crypto/ZipStrong.h index 2b58a5cb..a2b5cddf 100644 --- a/CPP/7zip/Crypto/ZipStrong.h +++ b/CPP/7zip/Crypto/ZipStrong.h @@ -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 @@ struct CKeyInfo 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 @@ class CDecoder: public CBaseCoder // 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 --git a/CPP/7zip/Guid.txt b/CPP/7zip/Guid.txt index 53d65da1..fa16fd24 100644 --- a/CPP/7zip/Guid.txt +++ b/CPP/7zip/Guid.txt @@ -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 --git a/CPP/7zip/ICoder.h b/CPP/7zip/ICoder.h index 65b21a05..4bd629e9 100644 --- a/CPP/7zip/ICoder.h +++ b/CPP/7zip/ICoder.h @@ -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 - (outSize) 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; -}; +#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) -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_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 @@ CODER_INTERFACE(ICompressCoder2, 0x18) { 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 @@ -133,6 +134,34 @@ namespace NCoderPropID kFilter, // VT_BSTR kMemUse, // 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. + */ /* zstd props */ kStrategy, // VT_UI4 1=ZSTD_fast, 2=ZSTD_dfast, 3=ZSTD_greedy, 4=ZSTD_lazy, 5=ZSTD_lazy2, 6=ZSTD_btlazy2, 7=ZSTD_btopt, 8=ZSTD_btultra @@ -149,71 +178,62 @@ namespace NCoderPropID kLdmSearchLength, // 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. - kEndOfProp + 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; -}; +#define Z7_IFACEM_ICompressWriteCoderProperties(x) \ + x(WriteCoderProperties(ISequentialOutStream *outStream)) +Z7_IFACE_CONSTR_CODER(ICompressWriteCoderProperties, 0x23) -CODER_INTERFACE(ICompressSetCoderMt, 0x25) -{ - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE; -}; +#define Z7_IFACEM_ICompressGetInStreamProcessedSize(x) \ + x(GetInStreamProcessedSize(UInt64 *value)) +Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize, 0x24) -CODER_INTERFACE(ICompressSetFinishMode, 0x26) -{ - STDMETHOD(SetFinishMode)(UInt32 finishMode) PURE; +#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; -}; +#define Z7_IFACEM_ICompressGetInStreamProcessedSize2(x) \ + x(GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value)) +Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize2, 0x27) -CODER_INTERFACE(ICompressSetMemLimit, 0x28) -{ - STDMETHOD(SetMemLimit)(UInt64 memUsage) PURE; -}; +#define Z7_IFACEM_ICompressSetMemLimit(x) \ + x(SetMemLimit(UInt64 memUsage)) +Z7_IFACE_CONSTR_CODER(ICompressSetMemLimit, 0x28) /* @@ -225,23 +245,18 @@ CODER_INTERFACE(ICompressSetMemLimit, 0x28) data from the internal buffer. in ReadUnusedFromInBuf(): the Coder is not allowed to use (ISequentialInStream *inStream) object, that was sent to ICoder::Code(). */ - -CODER_INTERFACE(ICompressReadUnusedFromInBuf, 0x29) -{ - STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize) PURE; -}; - +#define Z7_IFACEM_ICompressReadUnusedFromInBuf(x) \ + x(ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize)) +Z7_IFACE_CONSTR_CODER(ICompressReadUnusedFromInBuf, 0x29) -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) @@ -251,74 +266,74 @@ CODER_INTERFACE(ICompressGetSubStreamSize, 0x30) subStream++; } */ -}; -CODER_INTERFACE(ICompressSetInStream, 0x31) -{ - STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE; - STDMETHOD(ReleaseInStream)() PURE; -}; +#define Z7_IFACEM_ICompressSetInStream(x) \ + x(SetInStream(ISequentialInStream *inStream)) \ + x(ReleaseInStream()) +Z7_IFACE_CONSTR_CODER(ICompressSetInStream, 0x31) -CODER_INTERFACE(ICompressSetOutStream, 0x32) -{ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE; - STDMETHOD(ReleaseOutStream)() PURE; -}; +#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: @@ -327,13 +342,28 @@ CODER_INTERFACE(ICompressSetInStreamSize2, 0x39) { 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) - - returns: (outSize): + (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): 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 @@ -342,60 +372,47 @@ CODER_INTERFACE(ICompressSetInStreamSize2, 0x39) (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); -}; +#define Z7_IFACEM_ICompressFilter(x) \ + x(Init()) \ + x##2(UInt32, Filter(Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICompressFilter, 0x40) -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; -}; +#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) -CODER_INTERFACE(ISetCompressCodecsInfo, 0x61) -{ - STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo) PURE; -}; +#define Z7_IFACEM_ISetCompressCodecsInfo(x) \ + x(SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo)) +Z7_IFACE_CONSTR_CODER(ISetCompressCodecsInfo, 0x61) -CODER_INTERFACE(ICryptoProperties, 0x80) -{ - STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE; - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE; -}; +#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; -}; +#define Z7_IFACEM_ICryptoSetPassword(x) \ + x(CryptoSetPassword(const Byte *data, UInt32 size)) +Z7_IFACE_CONSTR_CODER(ICryptoSetPassword, 0x90) -CODER_INTERFACE(ICryptoSetCRC, 0xA0) -{ - STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE; -}; +#define Z7_IFACEM_ICryptoSetCRC(x) \ + x(CryptoSetCRC(UInt32 crc)) +Z7_IFACE_CONSTR_CODER(ICryptoSetCRC, 0xA0) namespace NMethodPropID @@ -416,24 +433,48 @@ namespace NMethodPropID }; } - -#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" { @@ -445,6 +486,8 @@ extern "C" 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 --git a/CPP/7zip/IDecl.h b/CPP/7zip/IDecl.h index f2202e9b..651ec6c0 100644 --- a/CPP/7zip/IDecl.h +++ b/CPP/7zip/IDecl.h @@ -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 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 DECL_INTERFACE(i, groupId, subId) DECL_INTERFACE_SUB(i, IUnknown, groupId, subId) +#define Z7_IFACE_DECL_PURE_(name, baseiface) \ + DECLARE_INTERFACE_(name, baseiface) \ + { Z7_IFACE_PURE(name) }; #endif diff --git a/CPP/7zip/IPassword.h b/CPP/7zip/IPassword.h index 4ccc9ac7..689f08cb 100644 --- a/CPP/7zip/IPassword.h +++ b/CPP/7zip/IPassword.h @@ -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 @@ out: The callee rewrites BSTR variable (*password) with new allocated string poi 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 @@ CryptoGetTextPassword2() 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 --git a/CPP/7zip/IProgress.h b/CPP/7zip/IProgress.h index fac951ec..67149830 100644 --- a/CPP/7zip/IProgress.h +++ b/CPP/7zip/IProgress.h @@ -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; \ +Z7_PURE_INTERFACES_BEGIN -DECL_INTERFACE(IProgress, 0, 5) -{ - INTERFACE_IProgress(PURE) -}; +#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 --git a/CPP/7zip/IStream.h b/CPP/7zip/IStream.h index 2793a1e9..4a58bc97 100644 --- a/CPP/7zip/IStream.h +++ b/CPP/7zip/IStream.h @@ -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 @@ STREAM_INTERFACE(ISequentialInStream, 0x01) 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 @@ STREAM_INTERFACE(ISequentialOutStream, 0x02) 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 @@ STREAM_INTERFACE(ISequentialOutStream, 0x02) #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; -}; +#define Z7_IFACEM_IInStream(x) \ + x(Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) +Z7_IFACE_CONSTR_STREAM_SUB(IInStream, ISequentialInStream, 0x03) -STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; - STDMETHOD(SetSize)(UInt64 newSize) PURE; -}; +#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) -STREAM_INTERFACE(IStreamGetSize, 0x06) -{ - STDMETHOD(GetSize)(UInt64 *size) PURE; -}; +#define Z7_IFACEM_IStreamGetSize(x) \ + x(GetSize(UInt64 *size)) +Z7_IFACE_CONSTR_STREAM(IStreamGetSize, 0x06) -STREAM_INTERFACE(IOutStreamFinish, 0x07) -{ - STDMETHOD(OutStreamFinish)() PURE; -}; +#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 @@ struct CStreamFileProps 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) -STREAM_INTERFACE(IStreamGetProp, 0x0a) -{ - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(ReloadProps)() PURE; -}; +#define Z7_IFACEM_IStreamGetProp(x) \ + x(GetProperty(PROPID propID, PROPVARIANT *value)) \ + x(ReloadProps()) +Z7_IFACE_CONSTR_STREAM(IStreamGetProp, 0x0a) + + +/* +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 --git a/CPP/7zip/LzmaDec.mak b/CPP/7zip/LzmaDec.mak index bed4700a..3beb5052 100644 --- a/CPP/7zip/LzmaDec.mak +++ b/CPP/7zip/LzmaDec.mak @@ -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 --git a/CPP/7zip/MyVersionInfo.rc b/CPP/7zip/MyVersionInfo.rc index fab66860..fc63d798 100644 --- a/CPP/7zip/MyVersionInfo.rc +++ b/CPP/7zip/MyVersionInfo.rc @@ -1,2 +1,2 @@ #include "MyVersion.h" -#include "..\..\C\7zVersion.rc" +#include "../../C/7zVersion.rc" diff --git a/CPP/7zip/PropID.h b/CPP/7zip/PropID.h index 2da636fa..e0747942 100644 --- a/CPP/7zip/PropID.h +++ b/CPP/7zip/PropID.h @@ -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 @@ enum kpidGroupId, kpidDeviceMajor, kpidDeviceMinor, + kpidDevMajor, + kpidDevMinor, kpid_NUM_DEFINED, diff --git a/CPP/7zip/UI/Agent/Agent.cpp b/CPP/7zip/UI/Agent/Agent.cpp index cc20c116..6761b284 100644 --- a/CPP/7zip/UI/Agent/Agent.cpp +++ b/CPP/7zip/UI/Agent/Agent.cpp @@ -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 @@ static const bool k_keepEmptyDirPrefixes = 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 @@ static const bool k_keepEmptyDirPrefixes = 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 @@ void FreeGlobalCodecs() { MT_LOCK - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (g_CodecsObj) { g_CodecsObj->CloseLibs(); @@ -73,7 +77,7 @@ HRESULT LoadGlobalCodecs() 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 @@ HRESULT LoadGlobalCodecs() g_CodecsRef = g_CodecsObj; #endif - RINOK(g_CodecsObj->Load()); + RINOK(g_CodecsObj->Load()) if (g_CodecsObj->Formats.IsEmpty()) { FreeGlobalCodecs(); @@ -91,15 +95,15 @@ HRESULT LoadGlobalCodecs() 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 @@ void CAgentFolder::LoadFolder(unsigned proxyDirIndex) _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 @@ void CAgentFolder::LoadFolder(unsigned proxyDirIndex) } } -STDMETHODIMP CAgentFolder::LoadItems() +Z7_COM7F_IMF(CAgentFolder::LoadItems()) { if (!_agentSpec->_archiveLink.IsOpen) return E_FAIL; @@ -160,7 +164,7 @@ STDMETHODIMP CAgentFolder::LoadItems() return S_OK; } -STDMETHODIMP CAgentFolder::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CAgentFolder::GetNumberOfItems(UInt32 *numItems)) { if (_flatMode) *numItems = _items.Size(); @@ -217,7 +221,7 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const { 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 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const *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 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const { 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 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const *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 @@ UString CAgentFolder::GetFullPrefix(UInt32 index) const 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 @@ STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index) return item.Size; if (!item.IsLeaf()) return 0; - arcIndex = item.ArcIndex; + arcIndex = (unsigned)item.ArcIndex; } else { @@ -309,7 +313,7 @@ STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index) 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 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT // 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 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT { 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 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT } 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 @@ static UInt64 GetUInt64Prop(IInArchive *archive, UInt32 index, PROPID propID) 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::GetItemName(UInt32 index, const wchar_t **name, unsig } } -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 @@ STDMETHODIMP CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, uns 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 @@ static int CompareRawProps(IArchiveGetRawProps *rawProps, int arcIndex1, int arc 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 @@ int CAgentFolder::CompareItems2(UInt32 index1, UInt32 index2, PROPID propID, Int } -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 @@ STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PR 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 @@ STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PR 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 @@ HRESULT CAgentFolder::BindToFolder_Internal(unsigned proxyDirIndex, IFolderFolde 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 @@ STDMETHODIMP CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFold 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 @@ HRESULT CAgentFolder::BindToAltStreams_Internal(unsigned proxyDirIndex, IFolderF 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 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **result } 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 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **result } 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 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder * 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 @@ STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupport *isSupported = BoolToInt(true); return S_OK; } - arcIndex = _proxy2->Dirs[_proxyDirIndex].ArcIndex; + arcIndex = (unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex; } else { @@ -1046,7 +1050,7 @@ STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupport } -STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder) +Z7_COM7F_IMF(CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder)) { COM_TRY_BEGIN /* @@ -1071,15 +1075,15 @@ STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream) 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 @@ struct CArchiveItemPropertyTemp 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 @@ STDMETHODIMP CAgentFolder::GetNumberOfProperties(UInt32 *numProps) 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 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro { *propID = kpidName; *varType = VT_BSTR; - *name = 0; + *name = NULL; return S_OK; } index--; @@ -1190,7 +1195,7 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro 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 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro */ *propID = kProps[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; - *name = 0; + *name = NULL; } return S_OK; COM_TRY_END @@ -1221,7 +1226,7 @@ static const PROPID kFolderProps[] = kpidCRC }; -STDMETHODIMP CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)) { COM_TRY_BEGIN @@ -1284,21 +1289,23 @@ STDMETHODIMP CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CAgentFolder::GetNumRawProps(UInt32 *numProps) 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 @@ STDMETHODIMP CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *prop 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 @@ STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void ** *propType = 0; return S_OK; } - arcIndex = item.ArcIndex; + arcIndex = (unsigned)item.ArcIndex; } else arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; @@ -1352,29 +1359,27 @@ STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void ** 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 @@ int CAgentFolder::GetRealIndex(unsigned index) const 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 @@ int CAgentFolder::GetRealIndex(unsigned index) const return -1; return f.ArcIndex; } - return dir->SubFiles[realIndex - dir->SubDirs.Size()]; + return (int)dir->SubFiles[realIndex - dir->SubDirs.Size()]; } } } @@ -1437,7 +1442,7 @@ void CAgentFolder::GetRealIndices(const UInt32 *indices, UInt32 numItems, bool i 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 @@ void CAgentFolder::GetRealIndices(const UInt32 *indices, UInt32 numItems, bool i 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 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, Int32 testMode, - IFolderArchiveExtractCallback *extractCallback2) + IFolderArchiveExtractCallback *extractCallback2)) { COM_TRY_BEGIN @@ -1492,6 +1497,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, { pathU = us2fs(path); if (!pathU.IsEmpty()) + if (!NFile::NName::IsAltStreamPrefixWithColon(pathU)) { NFile::NName::NormalizeDirPathPrefix(pathU); NFile::NDir::CreateComplexDir(pathU); @@ -1524,7 +1530,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, (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 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, if (!testMode) { - RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices)); + RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices)) } #endif @@ -1592,12 +1598,12 @@ bool CAgent::CanUpdate() const 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 @@ STDMETHODIMP CAgent::Open( 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 @@ STDMETHODIMP CAgent::Open( } CArcInfoEx archiverInfo0, archiverInfo1; - RINOK(LoadGlobalCodecs()); + RINOK(LoadGlobalCodecs()) CObjectVector types; if (!ParseOpenTypes(*g_CodecsObj, arcFormat, types)) @@ -1665,7 +1671,7 @@ STDMETHODIMP CAgent::Open( ArchiveType = GetTypeOfArc(arc); if (archiveType) { - RINOK(StringToBstr(ArchiveType, archiveType)); + RINOK(StringToBstr(ArchiveType, archiveType)) } if (arc.IsHashHandler(options)) @@ -1678,7 +1684,7 @@ STDMETHODIMP CAgent::Open( } -STDMETHODIMP CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback) +Z7_COM7F_IMF(CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback)) { COM_TRY_BEGIN if (_proxy2) @@ -1704,12 +1710,12 @@ STDMETHODIMP CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback) 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::Close() } /* -STDMETHODIMP CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties) +Z7_COM7F_IMF(CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties) { return _archive->EnumProperties(EnumProperties); } @@ -1748,7 +1754,7 @@ HRESULT CAgent::ReadItems() 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 @@ HRESULT CAgent::ReadItems() 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 @@ STDMETHODIMP CAgent::BindToRootFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CAgent::Extract( 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 @@ STDMETHODIMP CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value) 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 --git a/CPP/7zip/UI/Agent/Agent.h b/CPP/7zip/UI/Agent/Agent.h index 8e8a4c7d..ea81aa8a 100644 --- a/CPP/7zip/UI/Agent/Agent.h +++ b/CPP/7zip/UI/Agent/Agent.h @@ -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 @@ void FreeGlobalCodecs(); 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 @@ enum AGENT_OP AGENT_OP_Comment }; -class CAgentFolder: +class CAgentFolder Z7_final: public IFolderFolder, public IFolderAltStreams, public IFolderProperties, @@ -59,65 +60,51 @@ class CAgentFolder: public IArchiveFolderInternal, public IInArchiveGetStream, public IFolderSetZoneIdMode, -#ifdef NEW_FOLDER_INTERFACE public IFolderOperations, public IFolderSetFlatMode, -#endif public CMyUnknownImp { - void LoadFolder(unsigned proxyDirIndex); + 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: - - 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 - 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 @@ class CAgentFolder: 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 @@ class CAgent: 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 @@ class CAgent: 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 @@ class CAgent: 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 @@ class CAgent: } 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 --git a/CPP/7zip/UI/Agent/AgentOut.cpp b/CPP/7zip/UI/Agent/AgentOut.cpp index da8da6cd..b5a25a35 100644 --- a/CPP/7zip/UI/Agent/AgentOut.cpp +++ b/CPP/7zip/UI/Agent/AgentOut.cpp @@ -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 @@ STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder) 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 @@ STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder) 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 @@ static HRESULT EnumerateArchiveItems(CAgent *agent, 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 @@ static HRESULT EnumerateArchiveItems(CAgent *agent, 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 @@ static HRESULT EnumerateArchiveItems2(const CAgent *agent, 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 @@ static void SetInArchiveInterfaces(CAgent *agent, CArchiveUpdateCallback *upd) 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 @@ struct CDirItemsCallback_AgentOut: public IDirItemsCallback 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 @@ STDMETHODIMP CAgent::DoOperation( ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, - IFolderArchiveUpdateCallback *updateCallback100) + IFolderArchiveUpdateCallback *updateCallback100)) { if (!CanUpdate()) return E_NOTIMPL; @@ -226,9 +225,10 @@ STDMETHODIMP CAgent::DoOperation( { 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 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ STDMETHODIMP CAgent::DoOperation( if (updateCallback100) { - RINOK(updateCallback100->SetNumFiles(numFiles)); + RINOK(updateCallback100->SetNumFiles(numFiles)) } CUpdateCallbackAgent updateCallbackAgent; @@ -347,12 +347,14 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ STDMETHODIMP CAgent::DoOperation( { 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 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ STDMETHODIMP CAgent::DoOperation( 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 @@ HRESULT CAgent::CommonUpdate(ISequentialOutStream *outArchiveStream, 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 @@ STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream, realIndices); unsigned curIndex = 0; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) UString deletePath; @@ -460,8 +462,8 @@ STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream, 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 @@ HRESULT CAgent::CreateFolder(ISequentialOutStream *outArchiveStream, 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 @@ HRESULT CAgent::RenameItem(ISequentialOutStream *outArchiveStream, unsigned curIndex = 0; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) for (UInt32 i = 0; i < numItemsInArchive; i++) { @@ -579,15 +581,15 @@ HRESULT CAgent::RenameItem(ISequentialOutStream *outArchiveStream, 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 @@ HRESULT CAgent::CommentItem(ISequentialOutStream *outArchiveStream, return E_NOTIMPL; UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) UString newName = newItemName; @@ -686,7 +688,7 @@ HRESULT CAgent::UpdateOneFile(ISequentialOutStream *outArchiveStream, } UInt32 numItemsInArchive; - RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); + RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)) for (UInt32 i = 0; i < numItemsInArchive; i++) { CUpdatePair2 up2; @@ -710,7 +712,7 @@ HRESULT CAgent::UpdateOneFile(ISequentialOutStream *outArchiveStream, 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 --git a/CPP/7zip/UI/Agent/AgentProxy.cpp b/CPP/7zip/UI/Agent/AgentProxy.cpp index 4c9c386b..df9f3158 100644 --- a/CPP/7zip/UI/Agent/AgentProxy.cpp +++ b/CPP/7zip/UI/Agent/AgentProxy.cpp @@ -39,7 +39,7 @@ int CProxyArc::FindSubDir(unsigned dirIndex, const wchar_t *name, unsigned &inse 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 @@ unsigned CProxyArc::AddDir(unsigned dirIndex, int arcIndex, const UString &name) 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 @@ void CProxyDir::Clear() 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 @@ void CProxyArc::GetDirPathParts(int dirIndex, UStringVector &pathParts) const } } -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 @@ void CProxyArc::AddRealIndices(unsigned dirIndex, CUIntVector &realIndices) cons { 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 @@ int CProxyArc::GetRealIndex(unsigned dirIndex, unsigned index) const 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 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) #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 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) */ bool isDir; - RINOK(Archive_IsItem_Dir(archive, i, isDir)); + RINOK(Archive_IsItem_Dir(archive, i, isDir)) CProxyFile &f = Files[i]; @@ -407,31 +409,32 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress) // ---------- 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 @@ void CProxyArc2::AddRealIndices_of_ArcItem(unsigned arcIndex, bool includeAltStr 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 @@ void CProxyArc2::CalculateSizes(unsigned dirIndex, IInArchive *archive) 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 @@ void CProxyArc2::CalculateSizes(unsigned dirIndex, IInArchive *archive) // 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) if (progress && (i & 0xFFFFF) == 0) { UInt64 currentItemIndex = i; - RINOK(progress->SetCompleted(¤tItemIndex)); + RINOK(progress->SetCompleted(¤tItemIndex)) } CProxyFile2 &file = Files[i]; @@ -625,7 +628,7 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) } 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 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress) 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 @@ int CProxyArc2::FindItem(unsigned dirIndex, const wchar_t *name, bool foldersOnl if (foldersOnly && file.DirIndex == -1) continue; if (CompareFileNames(file.Name, name) == 0) - return i; + return (int)i; } return -1; } diff --git a/CPP/7zip/UI/Agent/AgentProxy.h b/CPP/7zip/UI/Agent/AgentProxy.h index 233174b4..c24dd914 100644 --- a/CPP/7zip/UI/Agent/AgentProxy.h +++ b/CPP/7zip/UI/Agent/AgentProxy.h @@ -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 @@ struct CProxyDir 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 @@ class CProxyArc // 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 @@ struct CProxyFile2 { 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 @@ struct CProxyDir2 UInt32 NumSubDirs; UInt32 NumSubFiles; - CProxyDir2(): ArcIndex(-1) {}; + CProxyDir2(): ArcIndex(-1) {} void AddFileSubItem(UInt32 index, const UString &name); void Clear(); }; @@ -130,7 +130,7 @@ class CProxyArc2 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 --git a/CPP/7zip/UI/Agent/ArchiveFolder.cpp b/CPP/7zip/UI/Agent/ArchiveFolder.cpp index eca02ba1..89b20dcb 100644 --- a/CPP/7zip/UI/Agent/ArchiveFolder.cpp +++ b/CPP/7zip/UI/Agent/ArchiveFolder.cpp @@ -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 @@ STDMETHODIMP CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 CMyComPtr extractCallback2; { CMyComPtr callbackWrap = callback; - RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)); + RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)) } NExtract::NPathMode::EEnum pathMode; if (!_flatMode) diff --git a/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp b/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp index 55457f45..3fa027dd 100644 --- a/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp +++ b/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp @@ -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 @@ STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream, 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 @@ STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream, return res; } - RINOK(agent->BindToRootFolder(resultFolder)); + RINOK(archive->BindToRootFolder(resultFolder)) return res; } @@ -58,7 +128,7 @@ HRESULT CAgent::FolderReOpen( /* -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 @@ static void AddIconExt(const CCodecIcons &lib, UString &dest) } } -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::GetIconPath(const wchar_t *ext, BSTR *iconPa } /* -STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types) +Z7_COM7F_IMF(CArchiveFolderManager::GetTypes(BSTR *types)) { LoadFormats(); UString typesStrings; @@ -146,9 +221,11 @@ STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types) } 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 --git a/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp b/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp index cd18c996..0189224f 100644 --- a/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp +++ b/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp @@ -83,7 +83,7 @@ HRESULT CAgentFolder::CommonUpdateOperation( try { - RINOK(_agentSpec->SetFolder(this)); + RINOK(_agentSpec->SetFolder(this)) // ---------- Save FolderItem ---------- @@ -95,7 +95,7 @@ HRESULT CAgentFolder::CommonUpdateOperation( 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( { 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 CAgentFolder::CommonUpdateOperation( HRESULT result; - switch (operation) + switch ((int)operation) { case AGENT_OP_Delete: result = _agentSpec->DeleteItems(tailStream, indices, numItems, updateCallback100); @@ -149,18 +149,18 @@ HRESULT CAgentFolder::CommonUpdateOperation( 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( // ---------- 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( { 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( } 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 @@ HRESULT CAgentFolder::CommonUpdateOperation( { UString s2 ("Error: "); s2 += s; - RINOK(updateCallback100->UpdateErrorMessage(s2)); + RINOK(updateCallback100->UpdateErrorMessage(s2)) return E_FAIL; } throw; @@ -303,16 +303,15 @@ HRESULT CAgentFolder::CommonUpdateOperation( } - -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 @@ STDMETHODIMP CAgentFolder::CopyFrom(Int32 moveMode, 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 @@ STDMETHODIMP CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPat 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 @@ STDMETHODIMP CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgr 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 @@ STDMETHODIMP CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress 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 @@ STDMETHODIMP CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgres 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 --git a/CPP/7zip/UI/Agent/IFolderArchive.h b/CPP/7zip/UI/Agent/IFolderArchive.h index 92eb6160..55f14234 100644 --- a/CPP/7zip/UI/Agent/IFolderArchive.h +++ b/CPP/7zip/UI/Agent/IFolderArchive.h @@ -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 @@ IArchiveFolder is used by: 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 implemented by CAgent (Agent/Agent.h) 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; \ - -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)( \ + Int32 testMode, IFolderArchiveExtractCallback *extractCallback2)) \ + +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 --git a/CPP/7zip/UI/Agent/StdAfx.h b/CPP/7zip/UI/Agent/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/UI/Agent/StdAfx.h +++ b/CPP/7zip/UI/Agent/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp b/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp index 53a13bb9..8299902d 100644 --- a/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp +++ b/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp @@ -71,12 +71,12 @@ HRESULT CUpdateCallbackAgent::Finalize() 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 @@ HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemErr 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::OpenFileError(const FString &path, DWORD systemErr 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 @@ HRESULT CUpdateCallbackAgent::ReadingFileError(const FString &path, DWORD system 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::ReportUpdateOperation(UInt32 op, const wchar_t *na /* 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 --git a/CPP/7zip/UI/Agent/UpdateCallbackAgent.h b/CPP/7zip/UI/Agent/UpdateCallbackAgent.h index 4da7693c..179ce988 100644 --- a/CPP/7zip/UI/Agent/UpdateCallbackAgent.h +++ b/CPP/7zip/UI/Agent/UpdateCallbackAgent.h @@ -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 --git a/CPP/7zip/UI/Client7z/Client7z.cpp b/CPP/7zip/UI/Client7z/Client7z.cpp index a55fa22d..121a2f10 100644 --- a/CPP/7zip/UI/Client7z/Client7z.cpp +++ b/CPP/7zip/UI/Client7z/Client7z.cpp @@ -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 void PrintError(const char *message, const FString &name) 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 @@ static const wchar_t * const kEmptyFileAlias = L"[Content]"; // 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 @@ class CArchiveOpenCallback: 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 @@ struct CArcTime -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); - - // IArchiveExtractCallback - STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode); - STDMETHOD(PrepareOperation)(Int32 askExtractMode); - STDMETHOD(SetOperationResult)(Int32 resultEOperationResult); + Z7_IFACES_IMP_UNK_2(IArchiveExtractCallback, ICryptoGetTextPassword) + Z7_IFACE_COM7_IMP(IProgress) - // ICryptoGetTextPassword - STDMETHOD(CryptoGetTextPassword)(BSTR *aPassword); - -private: CMyComPtr _archiveHandler; FString _directoryPath; // Output directory UString _filePath; // name inside arcvhive @@ -376,26 +357,26 @@ void CArchiveExtractCallback::Init(IInArchive *archiveHandler, const FString &di 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, { // 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, } } - 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, { // 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, 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 @@ STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) 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 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult) else { char temp[16]; - ConvertUInt32ToString(operationResult, temp); + ConvertUInt32ToString((UInt32)operationResult, temp); Print("Error #"); Print(temp); } @@ -579,7 +560,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult) _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::SetOperationResult(Int32 operationResult) } -STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password)) { if (!PasswordIsDefined) { @@ -617,28 +598,14 @@ struct CDirItem: public NWindows::NFile::NFind::CFileInfoBase {} }; -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 @@ class CArchiveUpdateCallback: } }; -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 @@ STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */, 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 @@ static void GetStream2(const wchar_t *name) 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 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream 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 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream 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 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) 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 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOu 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 @@ STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDef #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 @@ int MY_CDECL main(int numArgs, const char *args[]) 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 @@ int MY_CDECL main(int numArgs, const char *args[]) } 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 @@ int MY_CDECL main(int numArgs, const char *args[]) 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 @@ int MY_CDECL main(int numArgs, const char *args[]) } 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 --git a/CPP/7zip/UI/Client7z/Client7z.dsp b/CPP/7zip/UI/Client7z/Client7z.dsp index b412c8e9..d46300fe 100644 --- a/CPP/7zip/UI/Client7z/Client7z.dsp +++ b/CPP/7zip/UI/Client7z/Client7z.dsp @@ -104,6 +104,10 @@ SOURCE=.\StdAfx.h # 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 @@ SOURCE=..\..\..\Windows\FileName.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 @@ -158,12 +166,24 @@ SOURCE=..\..\..\Windows\PropVariantConv.cpp 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 @@ SOURCE=..\..\..\Common\IntToString.h # 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 @@ SOURCE=..\..\..\Common\MyString.h # 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 @@ SOURCE=..\..\..\Common\MyVector.h # 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.cpp 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 @@ SOURCE=.\Client7z.cpp # End Source File # Begin Source File -SOURCE=..\..\..\..\C\Sort.h +SOURCE=..\..\Archive\IArchive.h # End Source File # End Target # End Project diff --git a/CPP/7zip/UI/Client7z/StdAfx.h b/CPP/7zip/UI/Client7z/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/UI/Client7z/StdAfx.h +++ b/CPP/7zip/UI/Client7z/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Common/ArchiveCommandLine.cpp b/CPP/7zip/UI/Common/ArchiveCommandLine.cpp index ca3eb4c2..ec5e0f39 100644 --- a/CPP/7zip/UI/Common/ArchiveCommandLine.cpp +++ b/CPP/7zip/UI/Common/ArchiveCommandLine.cpp @@ -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 @@ enum Enum kDeleteAfterCompressing, kSetArcMTime - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , kPassword #endif }; @@ -322,7 +322,7 @@ static const CSwitchForm kSwitchForms[] = { "sdel", SWFRM_SIMPLE }, { "stl", SWFRM_SIMPLE } - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO , { "p", SWFRM_STRING } #endif }; @@ -340,7 +340,7 @@ static const char * const kEmptyFilePath = "Empty file path"; bool CArcCommand::IsFromExtractGroup() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kTest: case NCommandType::kExtract: @@ -353,7 +353,7 @@ bool CArcCommand::IsFromExtractGroup() const NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kTest: case NCommandType::kExtractFull: @@ -365,7 +365,7 @@ NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const bool CArcCommand::IsFromUpdateGroup() const { - switch (CommandType) + switch ((int)CommandType) { case NCommandType::kAdd: case NCommandType::kUpdate: @@ -438,7 +438,7 @@ static void AddNameToCensor(NWildcard::CCensor &censor, { bool recursed = false; - switch (nop.RecursedType) + switch ((int)nop.RecursedType) { case NRecursedType::kWildcardOnlyRecursed: recursed = DoesNameContainWildcard(name); @@ -905,7 +905,7 @@ static void SetAddCommandOptions( CUpdateOptions &options) { NUpdateArchive::CActionSet defaultActionSet; - switch (commandType) + switch ((int)commandType) { case NCommandType::kAdd: defaultActionSet = NUpdateArchive::k_ActionSet_Add; @@ -944,8 +944,10 @@ static void SetAddCommandOptions( 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 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings, 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 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings, 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 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings, 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 @@ static const CCodePagePair g_CodePagePairs[] = { "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 @@ static Int32 FindCharset(const NCommandLineParser::CParser &parser, unsigned key 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 @@ void CArcCmdLineParser::Parse2(CArcCmdLineOptions &options) 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 --git a/CPP/7zip/UI/Common/ArchiveCommandLine.h b/CPP/7zip/UI/Common/ArchiveCommandLine.h index 745f999d..9e375b55 100644 --- a/CPP/7zip/UI/Common/ArchiveCommandLine.h +++ b/CPP/7zip/UI/Common/ArchiveCommandLine.h @@ -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 @@ struct CArcCmdLineOptions bool TechMode; bool ShowTime; + CBoolPair NtSecurity; + CBoolPair AltStreams; + CBoolPair HardLinks; + CBoolPair SymLinks; + + CBoolPair StoreOwnerId; + CBoolPair StoreOwnerName; + AString ListFields; int ConsoleCodePage; @@ -75,7 +83,7 @@ struct CArcCmdLineOptions CArcCommand Command; UString ArchiveName; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordEnabled; UString Password; #endif @@ -83,7 +91,7 @@ struct CArcCmdLineOptions UStringVector HashMethods; // UString HashFilePath; - bool AppendName; + // bool AppendName; // UStringVector ArchivePathsSorted; // UStringVector ArchivePathsFullSorted; NWildcard::CCensor arcCensor; @@ -93,14 +101,6 @@ struct CArcCmdLineOptions CExtractOptionsBase ExtractOptions; - CBoolPair NtSecurity; - CBoolPair AltStreams; - CBoolPair HardLinks; - CBoolPair SymLinks; - - CBoolPair StoreOwnerId; - CBoolPair StoreOwnerName; - CUpdateOptions UpdateOptions; CHashOptions HashOptions; UString ArcType; @@ -145,7 +145,7 @@ struct CArcCmdLineOptions LogLevel(0) { - }; + } }; class CArcCmdLineParser diff --git a/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp b/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp index a574f136..4b0cbeda 100644 --- a/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp +++ b/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp @@ -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 kCantCreateHardLink = "Cannot create hard link"; 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 @@ STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *pr return result; } -#endif // _SFX +#endif // Z7_SFX -#ifdef _USE_SECURITY_CODE +#ifdef Z7_USE_SECURITY_CODE bool InitLocalPrivileges(); bool InitLocalPrivileges() { @@ -92,11 +92,11 @@ bool InitLocalPrivileges() 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 @@ static bool FindExt2(const char *p, const UString &name) 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 @@ static const FChar * const k_ZoneId_StreamName = FTEXT(":Zone.Identifier"); void ReadZoneFile_Of_BaseFile(CFSTR fileName2, CByteBuffer &buf) { - FString fileName = fileName2; + FString fileName (fileName2); fileName += k_ZoneId_StreamName; buf.Free(); @@ -188,13 +188,13 @@ static HRESULT Archive_Get_HardLinkNode(IInArchive *archive, UInt32 index, CHard 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 @@ HRESULT CArchiveExtractCallback::PrepareHardLinks(const CRecordVector *r 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 @@ CArchiveExtractCallback::CArchiveExtractCallback(): LocalProgressSpec = new CLocalProgress(); _localProgress = LocalProgressSpec; - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE _saclEnabled = InitLocalPrivileges(); #endif } @@ -325,16 +330,18 @@ void CArchiveExtractCallback::Init( _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 @@ void CArchiveExtractCallback::Init( _removePathParts = removePathParts; _removePartsForAltStreams = removePartsForAltStreams; - #ifndef _SFX + #ifndef Z7_SFX _baseParentFolder = (UInt32)(Int32)-1; _use_baseParentFolder_mode = false; #endif @@ -374,7 +381,7 @@ void CArchiveExtractCallback::Init( } -STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 size) +Z7_COM7F_IMF(CArchiveExtractCallback::SetTotal(UInt64 size)) { COM_TRY_BEGIN _progressTotal = size; @@ -407,7 +414,7 @@ static UInt64 MyMultDiv64(UInt64 unpCur, UInt64 unpTotal, UInt64 packTotal) } -STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue)) { COM_TRY_BEGIN @@ -428,7 +435,7 @@ STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue) } -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 @@ HRESULT CArchiveExtractCallback::GetTime(UInt32 index, PROPID propID, CArcTime & { 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::GetTime(UInt32 index, PROPID propID, CArcTime & 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 @@ HRESULT CArchiveExtractCallback::SendMessageError2(HRESULT errorCode, const char 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 @@ STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value) return Arc->Archive->GetProperty(IndexInArc, propID, value); } -#endif // _SFX +#endif // Z7_SFX #ifdef SUPPORT_LINKS @@ -749,15 +756,15 @@ HRESULT CArchiveExtractCallback::MyCopyFile(ISequentialOutStream *outStream) 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 @@ HRESULT CArchiveExtractCallback::ReadLink() { 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 @@ HRESULT CArchiveExtractCallback::ReadLink() { 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 @@ static HRESULT GetOwner(IInArchive *archive, { { 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 @@ static HRESULT GetOwner(IInArchive *archive, } { 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 @@ HRESULT CArchiveExtractCallback::Read_fi_Props() #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 @@ HRESULT CArchiveExtractCallback::Read_fi_Props() { 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 @@ HRESULT CArchiveExtractCallback::Read_fi_Props() 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 @@ void CArchiveExtractCallback::CreateFolders() // 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 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool 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 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool { if (!AutoRenamePath(fullProcessedPath)) { - RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)); + RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)) return E_FAIL; } _isRenamed = true; @@ -1207,14 +1224,14 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool 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 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool // 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 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool 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 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtrArchive; @@ -1283,7 +1300,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtrIsItem_Anti(index, isAnti)); + RINOK(_arc->IsItem_Anti(index, isAnti)) CorrectPathParts(); UString processedPath (MakePathFromParts(_item.PathParts)); @@ -1333,7 +1350,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(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 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr 0 && _curSize < (1 << 12)) + if (_curSize_Defined && _curSize > 0 && _curSize < (1 << 12)) { if (_fi.IsLinuxSymLink()) { @@ -1451,18 +1468,18 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr (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 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtrSeekToBegin_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 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtrSeek((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::GetExtractStream(CMyComPtrReleaseStream(); _hashStreamWasUsed = false; @@ -1555,8 +1572,8 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre _isSplit = false; _curSize = 0; - _curSizeDefined = false; - _fileLengthWasSet = false; + _curSize_Defined = false; + _fileLength_WasSet = false; _fileLength_that_WasSet = 0; _index = index; @@ -1574,7 +1591,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre _itemFailure = false; #ifdef SUPPORT_LINKS - // _CopyFile_Path.Empty(); + // _copyFile_Path.Empty(); _link.Clear(); #endif @@ -1590,16 +1607,16 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre } #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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre return S_OK; } - #ifndef _SFX + #ifndef Z7_SFX if (_use_baseParentFolder_mode) { if (!pathParts.IsEmpty()) @@ -1651,7 +1668,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre } } else - #endif // _SFX + #endif // Z7_SFX { if (pathParts.IsEmpty()) { @@ -1734,12 +1751,8 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre numRemovePathParts = pathParts.Size() - 1; break; } - /* - case NExtract::NPathMode::kFullPaths: case NExtract::NPathMode::kAbsPaths: - break; - */ - default: + // default: break; } @@ -1747,7 +1760,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre } - #ifndef _SFX + #ifndef Z7_SFX if (ExtractToStreamCallback) { @@ -1772,7 +1785,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre return ExtractToStreamCallback->GetStream7(name, BoolToInt(_item.IsDir), outStream, askExtractMode, GetProp); } - #endif // _SFX + #endif // Z7_SFX CMyComPtr outStreamLoc; @@ -1784,13 +1797,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre _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::GetStream(UInt32 index, ISequentialOutStre -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 @@ STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) 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 CArchiveExtractCallback::CloseFile() 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 @@ HRESULT CArchiveExtractCallback::CloseFile() t.MTime_Defined ? &t.MTime : NULL); // #endif - RINOK(_outFileStreamSpec->Close()); + RINOK(_outFileStreamSpec->Close()) _outFileStream.Release(); return hres; } @@ -1964,7 +1977,7 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath( { 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 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath( { 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 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath( } 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 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath( 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 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath( 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 @@ bool CLinkInfo::Parse(const Byte *data, size_t dataSize, bool isLinuxData) // 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 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile() { repraseMode = true; reparseSize = _bufPtrSeqOutStream_Spec->GetPos(); - if (_curSizeDefined && reparseSize == _outMemBuf.Size()) + if (_curSize_Defined && reparseSize == _outMemBuf.Size()) { /* CReparseAttr reparse; @@ -2181,7 +2194,7 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile() } 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 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile() #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 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile() // 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 @@ void CArchiveExtractCallback::SetAttrib() } -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 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) } #endif - #ifndef _SFX + #ifndef Z7_SFX if (_hashStreamWasUsed) { @@ -2308,16 +2321,16 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) #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 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) } } } - #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 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) if (_needSetAttrib) SetAttrib(); - RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted))); + RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted))) return S_OK; @@ -2373,7 +2386,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) -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 @@ STDMETHODIMP CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt 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::ReportExtractResult(UInt32 indexType, UInt } -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 @@ FString CArchiveExtractCallback::Hash_GetFullFilePath() } -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::GetDiskProperty(UInt32 index, PROPID propI } -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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStre 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 @@ STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStre 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::GetStream2(UInt32 index, ISequentialInStre } -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::SetDirsTimes() HRESULT CArchiveExtractCallback::CloseArc() { HRESULT res = CloseReparseAndFile(); - HRESULT res2 = SetDirsTimes(); + const HRESULT res2 = SetDirsTimes(); if (res == S_OK) res = res2; _arc = NULL; diff --git a/CPP/7zip/UI/Common/ArchiveExtractCallback.h b/CPP/7zip/UI/Common/ArchiveExtractCallback.h index fe70bc92..5ed20f3f 100644 --- a/CPP/7zip/UI/Common/ArchiveExtractCallback.h +++ b/CPP/7zip/UI/Common/ArchiveExtractCallback.h @@ -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 @@ struct CExtractNtOptions } }; -#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 @@ struct COwnerInfo #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 @@ class CArchiveExtractCallback: 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 @@ class CArchiveExtractCallback: } } _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 @@ class CArchiveExtractCallback: 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 @@ class CArchiveExtractCallback: // 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 @@ class CArchiveExtractCallback: 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 @@ class CArchiveExtractCallback: NumFolders = NumFiles = NumAltStreams = UnpackSize = AltStreams_UnpackSize = 0; } - #ifndef _SFX + #ifndef Z7_SFX void SetHashMethods(IHashCalc *hash) { @@ -494,7 +489,7 @@ class CArchiveExtractCallback: 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 @@ class CArchiveExtractCallback: // call it after Init() - #ifndef _SFX + #ifndef Z7_SFX void SetBaseParentFolderIndex(UInt32 indexInArc) { _baseParentFolder = indexInArc; diff --git a/CPP/7zip/UI/Common/ArchiveName.cpp b/CPP/7zip/UI/Common/ArchiveName.cpp index 1baf3e1e..1c0c3a82 100644 --- a/CPP/7zip/UI/Common/ArchiveName.cpp +++ b/CPP/7zip/UI/Common/ArchiveName.cpp @@ -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; - fp = &fi2; + const wchar_t *end; + const UInt32 v = ConvertStringToUInt32(n.Ptr(1), &end); + if (*end != 0) + continue; + 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 --git a/CPP/7zip/UI/Common/ArchiveName.h b/CPP/7zip/UI/Common/ArchiveName.h index 0d32645f..9b6b7fe9 100644 --- a/CPP/7zip/UI/Common/ArchiveName.h +++ b/CPP/7zip/UI/Common/ArchiveName.h @@ -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 --git a/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp b/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp index 64aa9878..4e5f1f56 100644 --- a/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp +++ b/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp @@ -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 @@ STDMETHODIMP COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes 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::SetCompleted(const UInt64 *files, const UInt64 *b } -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 @@ STDMETHODIMP COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre 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 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre 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 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre 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 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre 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 @@ STDMETHODIMP COpenCallbackImp::CryptoGetTextPassword(BSTR *password) 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 --git a/CPP/7zip/UI/Common/ArchiveOpenCallback.h b/CPP/7zip/UI/Common/ArchiveOpenCallback.h index 46b26768..4e44c9dd 100644 --- a/CPP/7zip/UI/Common/ArchiveOpenCallback.h +++ b/CPP/7zip/UI/Common/ArchiveOpenCallback.h @@ -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: - 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 - - STDMETHOD(SetSubArchiveName(const wchar_t *name)) - { - _subArchiveMode = true; - _subArchiveName = name; - // TotalSize = 0; - return S_OK; - } - + Z7_IFACE_COM7_IMP(IArchiveOpenSetSubArchiveName) private: - FString _folderPrefix; - NWindows::NFile::NFind::CFileInfo _fileInfo; + #ifndef Z7_NO_CRYPTO + Z7_IFACE_COM7_IMP(ICryptoGetTextPassword) + #endif + bool _subArchiveMode; - UString _subArchiveName; public: + bool PasswordWasAsked; UStringVector FileNames; CBoolVector FileNames_WasUsed; CRecordVector FileSizes; - - bool PasswordWasAsked; + void AtCloseFile(unsigned fileIndex) + { + 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 ReOpenCallback; + // CMyComPtr Callback_Ref; + +private: + FString _folderPrefix; + UString _subArchiveName; + NWindows::NFile::NFind::CFileInfo _fileInfo; + +public: + CMultiStreams Volumes; + // 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 --git a/CPP/7zip/UI/Common/Bench.cpp b/CPP/7zip/UI/Common/Bench.cpp index cc0cfd0c..5da9783d 100644 --- a/CPP/7zip/UI/Common/Bench.cpp +++ b/CPP/7zip/UI/Common/Bench.cpp @@ -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 @@ class CBaseRandomGenerator 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 @@ class CBaseRandomGenerator }; -MY_NO_INLINE +Z7_NO_INLINE static void RandGen(Byte *buf, size_t size) { CBaseRandomGenerator RG; @@ -143,7 +144,7 @@ static void RandGen(Byte *buf, size_t size) 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 CBenchRandomGenerator: public CMidAlignedBuffer }; -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 @@ class CBenchmarkInStream: 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 @@ STDMETHODIMP CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processed 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 @@ class CBenchmarkOutStream: 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 @@ STDMETHODIMP CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *p } -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 @@ static UInt64 GetTimeCount() #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 @@ static UInt64 GetUserFreq() #endif } -class CBenchProgressStatus +class CBenchProgressStatus Z7_final { - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CCriticalSection CS; #endif public: @@ -541,14 +536,14 @@ class CBenchProgressStatus 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 @@ void CBenchInfoCalc::SetFinishTime(CBenchInfo &dest) 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 @@ UInt64 CBenchInfo::GetSpeed(UInt64 numUnits) const 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 @@ struct CBenchProps 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 @@ void CBenchProps::SetLzmaCompexity() 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 @@ UInt64 CBenchProps::GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt6 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 @@ UInt64 CBenchInfo::GetRating_LzmaEnc(UInt64 dictSize) const { 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 @@ struct CBenchSyncCommon +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 @@ class CEncoderInfo UInt32 EncoderIndex; UInt32 NumEncoderInternalThreads; CAffinityMode AffinityMode; + bool IsGlobalMtMode; // if more than one benchmark encoder threads #endif CMyComPtr _encoder; @@ -1024,14 +1036,17 @@ class CEncoderInfo 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 @@ class CEncoderInfo 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 @@ class CEncoderInfo propStreamSpec(NULL) {} - #ifndef _7ZIP_ST + #ifndef Z7_ST static THREAD_FUNC_DECL EncodeThreadFunction(void *param) { @@ -1115,7 +1132,7 @@ class CEncoderInfo 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 @@ class CEncoderInfo 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 @@ HRESULT CEncoderInfo::Generate() 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 @@ HRESULT CEncoderInfo::Generate() crc = CrcCalc((const Byte *)rg, rg.Size()); uncompressedDataPtr = (const Byte *)rg; } - - if (_encoderFilter) - { - ALLOC_WITH_HRESULT(&rgCopy, kBufferSize); - } - if (!outStream) { @@ -1226,6 +1250,15 @@ HRESULT CEncoderInfo::Generate() 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 @@ HRESULT CEncoderInfo::Generate() /* 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 @@ HRESULT CEncoderInfo::Generate() // 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 @@ HRESULT CEncoderInfo::Generate() coder.QueryInterface(IID_ICompressWriteCoderProperties, &writeCoderProps); if (writeCoderProps) { - RINOK(writeCoderProps->WriteCoderProperties(propStream)); + RINOK(writeCoderProps->WriteCoderProperties(propStream)) } { @@ -1282,7 +1315,7 @@ HRESULT CEncoderInfo::Generate() 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 @@ HRESULT CEncoderInfo::Generate() 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 @@ HRESULT CEncoderInfo::Generate() } -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 @@ HRESULT CEncoderInfo::Encode() { // 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 @@ HRESULT CEncoderInfo::Encode() if (cp) { - RINOK(Set_Key_and_IV(cp)); + RINOK(Set_Key_and_IV(cp)) } compressedSize = 0; @@ -1384,20 +1420,32 @@ HRESULT CEncoderInfo::Encode() // 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 @@ HRESULT CEncoderInfo::Encode() 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 @@ HRESULT CEncoderInfo::Encode() 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 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) 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 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) if (scp) { const UInt64 reduceSize = _uncompressedDataSize; - RINOK(_method.SetCoderProps(scp, &reduceSize)); + RINOK(_method.SetCoderProps(scp, &reduceSize)) } CMyComPtr cp; @@ -1528,7 +1580,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) RINOK(setDecProps->SetDecoderProperties2( /* (const Byte *)*propStreamSpec, */ propsData, - (UInt32)propStreamSpec->GetPos())); + (UInt32)propStreamSpec->GetPos())) } { @@ -1536,7 +1588,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) coder.QueryInterface(IID_ICryptoSetPassword, &sp); if (sp) { - RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))); + RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))) } } @@ -1544,7 +1596,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) if (cp) { - RINOK(Set_Key_and_IV(cp)); + RINOK(Set_Key_and_IV(cp)) } CMyComPtr setFinishMode; @@ -1559,32 +1611,38 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) 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 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) 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 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex) if (getInStreamProcessedSize) { UInt64 processed; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); + RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)) if (processed != compressedSize) return S_FALSE; } @@ -1652,7 +1710,7 @@ static UInt64 GetNumIterations(UInt64 numCommands, UInt64 complexInCommands) -#ifndef _7ZIP_ST +#ifndef Z7_ST // ---------- CBenchThreadsFlusher ---------- @@ -1696,7 +1754,7 @@ WRes CBenchThreadsFlusher::StartAndWait(bool exitMode) return res; } -#endif // _7ZIP_ST +#endif // Z7_ST @@ -1714,7 +1772,7 @@ static void SetPseudoRand(Byte *data, size_t size, UInt32 startValue) 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( UInt32 numEncoderThreads = 1; UInt32 numSubDecoderThreads = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST numEncoderThreads = numThreads; if (oldLzmaBenchMode) @@ -1759,7 +1818,7 @@ static HRESULT MethodBench( } } - bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity(); + const bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity(); #endif @@ -1771,10 +1830,10 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( { 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 @@ static HRESULT MethodBench( { 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 @@ static HRESULT MethodBench( status.Res = S_OK; status.EncodeMode = true; - #ifndef _7ZIP_ST + #ifndef Z7_ST CBenchThreadsFlusher encoderFlusher; if (mtEncMode) { @@ -1853,7 +1925,7 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( bpi->BenchInfo.NumIterations = numEncoderThreads; } - #ifndef _7ZIP_ST + #ifndef Z7_ST if (mtEncMode) { #ifdef USE_ALLOCA @@ -1885,6 +1957,7 @@ static HRESULT MethodBench( #endif encoder.Common = &encoderFlusher.Common; + encoder.IsGlobalMtMode = numEncoderThreads > 1; RINOK(encoder.CreateEncoderThread()) } #endif @@ -1892,35 +1965,35 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( { 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 @@ static HRESULT MethodBench( 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 @@ static HRESULT MethodBench( 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 @@ HRESULT CCrcInfo_Base::CrcProcess(UInt64 numIterations, if (cur - prev >= ((UInt32)1 << 30)) { prev = cur; - RINOK(callback->CheckBreak()); + RINOK(callback->CheckBreak()) } } } @@ -2266,7 +2343,7 @@ static UInt32 CountCpuFreq(UInt32 sum, UInt32 num, UInt32 val) EXTERN_C_END -#ifndef _7ZIP_ST +#ifndef Z7_ST struct CBaseThreadInfo { @@ -2300,12 +2377,12 @@ static THREAD_FUNC_DECL FreqThreadFunction(void *param) { 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 @@ struct CCrcInfo: public CBaseThreadInfo HRESULT Res; UInt32 CheckSum_Res; - #ifndef _7ZIP_ST + #ifndef Z7_ST NSynchronization::CManualResetEvent ReadyEvent; UInt32 ThreadIndex; CBenchSyncCommon *Common; @@ -2433,7 +2510,7 @@ static THREAD_FUNC_DECL CrcThreadFunction(void *param) alloca(p->AllocaSize); #endif p->Process(); - return 0; + return THREAD_FUNC_RET_ZERO; } @@ -2480,7 +2557,7 @@ WRes CCrcThreads::StartAndWait(bool exitMode) 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 @@ struct CBenchMethod { 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 @@ static const CBenchMethod g_Bench[] = // { 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 @@ static const CBenchMethod g_Bench[] = // { 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 @@ struct CBenchHash // #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_RU = 6; 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 @@ AString GetProcessThreadsInfo(const NSystem::CProcessAffinity &ti) } -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES #ifdef _WIN32 extern bool g_LargePagesMode; @@ -2875,7 +2960,7 @@ static void PrintRequirements(IBenchPrintCallback &f, const char *sizeString, f.Print(" ?"); f.Print(" MB"); - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES { AString s; Add_LargePages_String(s); @@ -2890,30 +2975,34 @@ static void PrintRequirements(IBenchPrintCallback &f, const char *sizeString, -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 @@ struct CBenchCallbackToPrint: public IBenchCallback 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::SetFreq(bool showFreq, UInt64 cpuFreq) 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 @@ static const char * const kSep = " | "; 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 @@ static void PrintRight(IBenchPrintCallback &f, const char *s, unsigned size) 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 @@ static HRESULT TotalBench( 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 @@ static HRESULT TotalBench( 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 @@ static HRESULT TotalBench( 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 @@ static HRESULT TotalBench( } else { - RINOK(res); + RINOK(res) } callback->NewLine(); @@ -3080,7 +3189,7 @@ struct CFreqBench {} HRESULT FreqBench(IBenchPrintCallback *_file - #ifndef _7ZIP_ST + #ifndef Z7_ST , const CAffinityMode *affinityMode #endif ); @@ -3088,7 +3197,7 @@ struct CFreqBench HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file - #ifndef _7ZIP_ST + #ifndef Z7_ST , const CAffinityMode *affinityMode #endif ) @@ -3100,7 +3209,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file if (numThreads == 0) numThreads = 1; - #ifdef _7ZIP_ST + #ifdef Z7_ST numThreads = 1; #endif @@ -3117,7 +3226,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file CBenchInfoCalc progressInfoSpec; - #ifndef _7ZIP_ST + #ifndef Z7_ST bool mtMode = (numThreads > 1) || affinityMode->NeedAffinity(); @@ -3150,7 +3259,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file 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 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file sum = CountCpuFreq(sum, numIterations2, g_BenchCpuFreqTemp); if (_file) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } } res += sum; @@ -3172,7 +3281,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file if (res == 0x12345678) if (_file) { - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } CBenchInfo info; @@ -3193,7 +3302,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file 0, // weight rating, showFreq, showFreq ? (specifiedFreq != 0 ? specifiedFreq : CpuFreqRes) : 0, NULL); - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } return S_OK; @@ -3215,7 +3324,7 @@ static HRESULT CrcBench( const UInt32 *checkSum, const COneMethodInfo &method, IBenchPrintCallback *_file, - #ifndef _7ZIP_ST + #ifndef Z7_ST const CAffinityMode *affinityMode, #endif bool showRating, @@ -3225,7 +3334,7 @@ static HRESULT CrcBench( if (numThreads == 0) numThreads = 1; - #ifdef _7ZIP_ST + #ifdef Z7_ST numThreads = 1; #endif @@ -3249,14 +3358,14 @@ static HRESULT CrcBench( */ 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 @@ static HRESULT CrcBench( { 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 @@ static HRESULT CrcBench( 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 @@ static HRESULT CrcBench( 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 @@ static HRESULT CrcBench( { 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 @@ static HRESULT CrcBench( benchWeight, rating, showFreq, cpuFreq, encodeRes); } - RINOK(_file->CheckBreak()); + RINOK(_file->CheckBreak()) } speed = info.GetSpeed(unpSizeThreads); @@ -3395,20 +3504,23 @@ static HRESULT CrcBench( 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 @@ static HRESULT TotalBench_Hash( 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 @@ static HRESULT TotalBench_Hash( (!fileData && bufSize == (1 << kNumHashDictBits)) ? &bench.CheckSum : NULL, method, printCallback, - #ifndef _7ZIP_ST + #ifndef Z7_ST affinityMode, #endif true, // showRating @@ -3441,7 +3553,7 @@ static HRESULT TotalBench_Hash( } else { - RINOK(res); + RINOK(res) } callback->NewLine(); } @@ -3451,7 +3563,8 @@ static HRESULT TotalBench_Hash( 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_Usage_and_Threads(IBenchPrintCallback &f, UInt64 usage, UInt32 } +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 @@ HRESULT Bench( NSystem::CProcessAffinity threadsInfo; threadsInfo.InitST(); - #ifndef _7ZIP_ST + #ifndef Z7_ST if (threadsInfo.Get() && threadsInfo.GetNumProcessThreads() != 0) numCPUs = threadsInfo.GetNumProcessThreads(); @@ -3533,7 +3669,7 @@ HRESULT Bench( UInt64 complexInCommands = kComplexInCommands; UInt32 numThreads_Start = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST CAffinityMode affinityMode; #endif @@ -3597,7 +3733,7 @@ HRESULT Bench( // (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 @@ HRESULT Bench( if (name.IsEqualTo("time")) { - RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); + RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)) needSetComplexity = true; testTimeMs *= 1000; continue; @@ -3624,7 +3760,7 @@ HRESULT Bench( if (name.IsEqualTo("timems")) { - RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); + RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)) needSetComplexity = true; continue; } @@ -3632,7 +3768,7 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( { 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 @@ HRESULT Bench( for (int jj = 0;; jj++) { if (printCallback) - RINOK(printCallback->CheckBreak()); + RINOK(printCallback->CheckBreak()) UInt64 start = ::GetTimeCount(); UInt32 sum = (UInt32)start; @@ -3776,7 +3912,7 @@ HRESULT Bench( } if (freqCallback) { - RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult)); + RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult)) } if (jj >= 1) @@ -3806,7 +3942,7 @@ HRESULT Bench( } if (freqCallback) { - RINOK(freqCallback->FreqsFinished(1)); + RINOK(freqCallback->FreqsFinished(1)) } } @@ -3830,17 +3966,24 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( } // if (jj >= 1) { - bool needStop = (numMilCommands >= (1 << + const bool needStop = (numMilCommands >= (1 << #ifdef _DEBUG 7 #else @@ -3903,7 +4046,7 @@ HRESULT Bench( } if (freqCallback) { - RINOK(freqCallback->FreqsFinished(numThreads)); + RINOK(freqCallback->FreqsFinished(numThreads)) } } @@ -3923,10 +4066,12 @@ HRESULT Bench( 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 @@ HRESULT Bench( return MethodBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, - #ifndef _7ZIP_ST + #ifndef Z7_ST true, numThreadsSpecified, &affinityMode, #endif @@ -3958,13 +4103,28 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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++) + // 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++) { - 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; + 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 @@ HRESULT Bench( } } - CBenchCallbackToPrint callback; - callback.Init(); - callback._file = printCallback; - IBenchPrintCallback &f = *printCallback; if (threadsPassIndex > 0) @@ -4230,7 +4520,7 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( dataSize, (const Byte *)fileDataBuffer, printCallback, &callback); - RINOK(res); + RINOK(res) } { @@ -4418,14 +4708,16 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( { 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( // 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 @@ HRESULT Bench( 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 @@ HRESULT Bench( uncompressedDataSize, (const Byte *)fileDataBuffer, kOldLzmaDictBits, printCallback, &callback, &callback.BenchProps); f.NewLine(); - RINOK(res); + RINOK(res) if (!multiDict) break; } diff --git a/CPP/7zip/UI/Common/Bench.h b/CPP/7zip/UI/Common/Bench.h index ab0c3048..313676dd 100644 --- a/CPP/7zip/UI/Common/Bench.h +++ b/CPP/7zip/UI/Common/Bench.h @@ -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 @@ struct CTotalBenchRes }; +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 GetSysInfo(AString &s1, AString &s2); 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 --git a/CPP/7zip/UI/Common/CompressCall.cpp b/CPP/7zip/UI/Common/CompressCall.cpp index 23fd03f4..c5c16dcd 100644 --- a/CPP/7zip/UI/Common/CompressCall.cpp +++ b/CPP/7zip/UI/Common/CompressCall.cpp @@ -78,7 +78,7 @@ static HRESULT Call7zGui(const UString ¶ms, 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; } @@ -87,7 +87,7 @@ static HRESULT Call7zGui(const UString ¶ms, 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; } @@ -170,7 +170,7 @@ static HRESULT CreateMap(const UStringVector &names, 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; } @@ -215,7 +215,7 @@ HRESULT CompressFiles( CFileMapping fileMapping; NSynchronization::CManualResetEvent event; params += kIncludeSwitch; - RINOK(CreateMap(names, fileMapping, event, params)); + RINOK(CreateMap(names, fileMapping, event, params)) if (!arcType.IsEmpty() && arcType == L"7z") { @@ -410,7 +410,7 @@ void Benchmark(bool totalMode) 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 --git a/CPP/7zip/UI/Common/CompressCall.h b/CPP/7zip/UI/Common/CompressCall.h index 2087e802..ed1248bf 100644 --- a/CPP/7zip/UI/Common/CompressCall.h +++ b/CPP/7zip/UI/Common/CompressCall.h @@ -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 --git a/CPP/7zip/UI/Common/CompressCall2.cpp b/CPP/7zip/UI/Common/CompressCall2.cpp index 3c43c952..9f833864 100644 --- a/CPP/7zip/UI/Common/CompressCall2.cpp +++ b/CPP/7zip/UI/Common/CompressCall2.cpp @@ -2,6 +2,8 @@ #include "StdAfx.h" +#ifndef Z7_EXTERNAL_CODECS + #include "../../../Common/MyException.h" #include "../../UI/Common/EnumDirItems.h" @@ -33,7 +35,7 @@ static void ThrowException_if_Error(HRESULT res) throw CSystemException(res); } -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #define CREATE_CODECS \ CCodecs *codecs = new CCodecs; \ @@ -42,10 +44,10 @@ static void ThrowException_if_Error(HRESULT res) 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 @@ -310,3 +312,5 @@ void Benchmark(bool totalMode) MY_TRY_FINISH } + +#endif diff --git a/CPP/7zip/UI/Common/DefaultName.h b/CPP/7zip/UI/Common/DefaultName.h index df164560..46f6e9e6 100644 --- a/CPP/7zip/UI/Common/DefaultName.h +++ b/CPP/7zip/UI/Common/DefaultName.h @@ -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 --git a/CPP/7zip/UI/Common/DirItem.h b/CPP/7zip/UI/Common/DirItem.h index 86e385fe..ae849376 100644 --- a/CPP/7zip/UI/Common/DirItem.h +++ b/CPP/7zip/UI/Common/DirItem.h @@ -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 @@ struct CDirItemsStat2: public CDirItemsStat }; +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 --git a/CPP/7zip/UI/Common/EnumDirItems.cpp b/CPP/7zip/UI/Common/EnumDirItems.cpp index dab37254..d536c473 100644 --- a/CPP/7zip/UI/Common/EnumDirItems.cpp +++ b/CPP/7zip/UI/Common/EnumDirItems.cpp @@ -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 @@ CDirItems::CDirItems(): , ExcludeDirItems(false) , ExcludeFileItems(false) , ShareForWrite(false) - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE , ReadSecure(false) #endif #ifndef _WIN32 @@ -191,13 +191,13 @@ CDirItems::CDirItems(): #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 @@ HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex) if (res) { if (secureSize != TempSecureBuf.Size()) - errorCode = ERROR_INVALID_FUNCTION;; + errorCode = ERROR_INVALID_FUNCTION; } else errorCode = GetLastError(); @@ -253,7 +253,7 @@ HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex) 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 @@ HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector files; - RINOK(EnumerateOneDir(phyPrefix, files)); + RINOK(EnumerateOneDir(phyPrefix, files)) FOR_VECTOR (i, files) { @@ -361,10 +361,10 @@ HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phy 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 @@ HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phy 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 @@ HRESULT CDirItems::EnumerateItems2( 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 @@ HRESULT CDirItems::EnumerateItems2( 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 @@ HRESULT CDirItems::EnumerateItems2( 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 @@ static HRESULT EnumerateForItem( 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 @@ static HRESULT EnumerateForItem( 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 @@ static HRESULT EnumerateForItem( phyPrefix + fi.Name, // with (fi.Name) newParts, // with (fi.Name) addAllSubStreams, - dirItems)); + dirItems)) } #endif @@ -787,7 +800,7 @@ static HRESULT EnumerateDirItems( enterToSubFolders = true; } - RINOK(dirItems.ScanProgress(phyPrefix)); + RINOK(dirItems.ScanProgress(phyPrefix)) // try direct_names case at first if (addParts.IsEmpty() && !enterToSubFolders) @@ -818,7 +831,7 @@ static HRESULT EnumerateDirItems( bool needAltStreams = true; #endif - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE bool needSecurity = true; #endif @@ -838,7 +851,7 @@ static HRESULT EnumerateDirItems( /* // 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 @@ static HRESULT EnumerateDirItems( #endif if (!FindFile_KeepDots(fi, fullPath FOLLOW_LINK_PARAM2)) { - RINOK(dirItems.AddError(fullPath)); + RINOK(dirItems.AddError(fullPath)) continue; } @@ -884,7 +897,7 @@ static HRESULT EnumerateDirItems( 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 @@ static HRESULT EnumerateDirItems( 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 @@ static HRESULT EnumerateDirItems( #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 @@ static HRESULT EnumerateDirItems( fullPath, // including (name) pathParts, // including (fi.Name) true, /* addAllSubStreams */ - dirItems)); + dirItems)) } #endif // defined(_WIN32) @@ -975,9 +988,9 @@ static HRESULT EnumerateDirItems( } 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 @@ static HRESULT EnumerateDirItems( 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 @@ static HRESULT EnumerateDirItems( { 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 @@ static HRESULT EnumerateDirItems( fi.Name = driveName; RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix, - addParts, dirItems, enterToSubFolders)); + addParts, dirItems, enterToSubFolders)) } return S_OK; } @@ -1088,7 +1104,7 @@ static HRESULT EnumerateDirItems( // 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 @@ static HRESULT EnumerateDirItems( #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 @@ HRESULT EnumerateItems( 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 @@ HRESULT CDirItems::FillFixedReparse() } */ - RINOK(AddError(phyPath)); + RINOK(AddError(phyPath)) continue; } @@ -1485,7 +1501,7 @@ HRESULT EnumerateDirItemsAndSort( { HRESULT res = EnumerateItems(censor, censorPathMode, addPathPrefix, dirItems); st = dirItems.Stat; - RINOK(res); + RINOK(res) } FOR_VECTOR (i, dirItems.Items) diff --git a/CPP/7zip/UI/Common/EnumDirItems.h b/CPP/7zip/UI/Common/EnumDirItems.h index 9b17c600..24f1c8bd 100644 --- a/CPP/7zip/UI/Common/EnumDirItems.h +++ b/CPP/7zip/UI/Common/EnumDirItems.h @@ -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 --git a/CPP/7zip/UI/Common/ExitCode.h b/CPP/7zip/UI/Common/ExitCode.h index b6d7d4df..2d7b0293 100644 --- a/CPP/7zip/UI/Common/ExitCode.h +++ b/CPP/7zip/UI/Common/ExitCode.h @@ -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 --git a/CPP/7zip/UI/Common/Extract.cpp b/CPP/7zip/UI/Common/Extract.cpp index 58f5218b..34b48719 100644 --- a/CPP/7zip/UI/Common/Extract.cpp +++ b/CPP/7zip/UI/Common/Extract.cpp @@ -43,6 +43,7 @@ static HRESULT DecompressArchive( const CExtractOptions &options, bool calcCrc, IExtractCallbackUI *callback, + IFolderArchiveExtractCallback *callbackFAE, CArchiveExtractCallback *ecs, UString &errorMessage, UInt64 &stdInProcessed) @@ -94,7 +95,7 @@ static HRESULT DecompressArchive( if (!options.StdInMode) { UInt32 numItems; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) CReadArcItem item; @@ -105,7 +106,7 @@ static HRESULT DecompressArchive( || 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 @@ static HRESULT DecompressArchive( 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 @@ static HRESULT DecompressArchive( options.NtOptions, options.StdInMode ? &wildcardCensor : NULL, &arc, - callback, + callbackFAE, options.StdOutMode, options.TestMode, outDir, removePathParts, false, @@ -207,14 +208,14 @@ static HRESULT DecompressArchive( !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 @@ static HRESULT DecompressArchive( 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 @@ HRESULT Extract( const CExtractOptions &options, IOpenCallbackUI *openCallback, IExtractCallbackUI *extractCallback, - #ifndef _SFX + IFolderArchiveExtractCallback *faeCallback, + #ifndef Z7_SFX IHashCalc *hash, #endif UString &errorMessage, @@ -323,13 +325,13 @@ HRESULT Extract( 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 @@ HRESULT Extract( } /* - #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 @@ HRESULT Extract( */ COpenOptions op; - #ifndef _SFX + #ifndef Z7_SFX op.props = &options.Properties; #endif op.codecs = codecs; @@ -418,7 +420,7 @@ HRESULT Extract( 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 @@ HRESULT Extract( 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 @@ HRESULT Extract( /* 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 @@ HRESULT Extract( if (newPackSize < 0) newPackSize = 0; totalPackSize = (UInt64)newPackSize; - RINOK(extractCallback->SetTotal(totalPackSize)); + RINOK(faeCallback->SetTotal(totalPackSize)) } } } @@ -498,13 +506,13 @@ HRESULT Extract( /* // 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 @@ HRESULT Extract( UInt64 packProcessed; const bool calcCrc = - #ifndef _SFX + #ifndef Z7_SFX (hash != NULL); #else false; @@ -533,7 +541,8 @@ HRESULT Extract( wildcardCensor, options, calcCrc, - extractCallback, ecs, errorMessage, packProcessed)); + extractCallback, faeCallback, ecs, + errorMessage, packProcessed)) if (!options.StdInMode) packProcessed = fi.Size + arcLink.VolumesSize; @@ -546,8 +555,8 @@ HRESULT Extract( if (multi || thereAreNotOpenArcs) { - RINOK(extractCallback->SetTotal(totalPackSize)); - RINOK(extractCallback->SetCompleted(&totalPackProcessed)); + RINOK(faeCallback->SetTotal(totalPackSize)) + RINOK(faeCallback->SetCompleted(&totalPackProcessed)) } st.NumFolders = ecs->NumFolders; diff --git a/CPP/7zip/UI/Common/Extract.h b/CPP/7zip/UI/Common/Extract.h index f3d1126b..b20f607d 100644 --- a/CPP/7zip/UI/Common/Extract.h +++ b/CPP/7zip/UI/Common/Extract.h @@ -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 @@ struct CExtractOptions: public CExtractOptionsBase // 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 @@ HRESULT Extract( const CExtractOptions &options, IOpenCallbackUI *openCallback, IExtractCallbackUI *extractCallback, - #ifndef _SFX + IFolderArchiveExtractCallback *faeCallback, + #ifndef Z7_SFX IHashCalc *hash, #endif UString &errorMessage, diff --git a/CPP/7zip/UI/Common/ExtractMode.h b/CPP/7zip/UI/Common/ExtractMode.h index 9ad831eb..6e38f260 100644 --- a/CPP/7zip/UI/Common/ExtractMode.h +++ b/CPP/7zip/UI/Common/ExtractMode.h @@ -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 --git a/CPP/7zip/UI/Common/ExtractingFilePath.cpp b/CPP/7zip/UI/Common/ExtractingFilePath.cpp index a1282b72..88da4ad3 100644 --- a/CPP/7zip/UI/Common/ExtractingFilePath.cpp +++ b/CPP/7zip/UI/Common/ExtractingFilePath.cpp @@ -124,7 +124,7 @@ static const char * const g_ReservedNames[] = 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 --git a/CPP/7zip/UI/Common/ExtractingFilePath.h b/CPP/7zip/UI/Common/ExtractingFilePath.h index 8f8f9f1b..bb1732fc 100644 --- a/CPP/7zip/UI/Common/ExtractingFilePath.h +++ b/CPP/7zip/UI/Common/ExtractingFilePath.h @@ -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 --git a/CPP/7zip/UI/Common/HashCalc.cpp b/CPP/7zip/UI/Common/HashCalc.cpp index 5c8ccddc..a7a03a84 100644 --- a/CPP/7zip/UI/Common/HashCalc.cpp +++ b/CPP/7zip/UI/Common/HashCalc.cpp @@ -26,7 +26,7 @@ using namespace NWindows; -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS extern const CExternalCodecs *g_ExternalCodecs_Ptr; #endif @@ -61,7 +61,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto 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; @@ -96,7 +96,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto { 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]; @@ -104,7 +104,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto 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) @@ -334,14 +334,14 @@ static void AddHashResultLine( 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; @@ -471,7 +471,7 @@ HRESULT HashCalc( } else { - RINOK(callback->StartScanning()); + RINOK(callback->StartScanning()) dirItems.SymLinks = options.SymLinks.Val; dirItems.ScanAltStreams = options.AltStreamsMode; @@ -491,12 +491,12 @@ HRESULT HashCalc( 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; @@ -504,12 +504,12 @@ HRESULT HashCalc( 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; @@ -519,7 +519,7 @@ HRESULT HashCalc( UInt64 completeValue = 0; - RINOK(callback->BeforeFirstFile(hb)); + RINOK(callback->BeforeFirstFile(hb)) /* CDynLimBuf hashFileString((size_t)1 << 31); @@ -579,7 +579,7 @@ HRESULT HashCalc( if (curSize > di.Size) { totalSize += curSize - di.Size; - RINOK(callback->SetTotal(totalSize)); + RINOK(callback->SetTotal(totalSize)) // printf("\ntotal = %d MiB\n", (unsigned)(totalSize >> 20)); } } @@ -589,7 +589,7 @@ HRESULT HashCalc( } } - RINOK(callback->GetStream(path, isDir)); + RINOK(callback->GetStream(path, isDir)) UInt64 fileSize = 0; hb.InitForNewFile(); @@ -601,10 +601,10 @@ HRESULT HashCalc( 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); @@ -630,8 +630,8 @@ HRESULT HashCalc( } */ - RINOK(callback->SetOperationResult(fileSize, hb, !isDir)); - RINOK(callback->SetCompleted(&completeValue)); + RINOK(callback->SetOperationResult(fileSize, hb, !isDir)) + RINOK(callback->SetCompleted(&completeValue)) } /* @@ -788,7 +788,7 @@ bool CHashPair::ParseCksum(const char *s) Name = end; Hash.Alloc(4); - SetBe32(Hash, crc); + SetBe32(Hash, crc) Size_from_Arc = size; Size_from_Arc_Defined = true; @@ -827,7 +827,7 @@ static UString GetMethod_from_FileName(const UString &name) } 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) @@ -840,7 +840,7 @@ static UString GetMethod_from_FileName(const UString &name) break; } UString res; - if (i != ARRAY_SIZE(k_CsumMethodNames)) + if (i != Z7_ARRAY_SIZE(k_CsumMethodNames)) res = m; return res; } @@ -1037,27 +1037,27 @@ static const Byte kRawProps[] = }; -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; @@ -1081,7 +1081,7 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data IMP_IInArchive_Props IMP_IInArchive_ArcProps -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) +Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems)) { *numItems = HashPairs.Size(); return S_OK; @@ -1093,7 +1093,7 @@ static void Add_OptSpace_String(UString &dest, const char *src) dest += src; } -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) +Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)) { NWindows::NCOM::CPropVariant prop; switch (propID) @@ -1156,7 +1156,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) } -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; @@ -1210,10 +1210,9 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp { 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); @@ -1222,7 +1221,7 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp 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; @@ -1232,13 +1231,13 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp 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 { @@ -1265,12 +1264,13 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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); } @@ -1380,7 +1380,7 @@ void CHandler::ClearVars() } -STDMETHODIMP CHandler::Close() +Z7_COM7F_IMF(CHandler::Close()) { ClearVars(); _nameExtenstion.Empty(); @@ -1421,8 +1421,8 @@ static void AddDefaultMethod(UStringVector &methods, unsigned size) 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 @@ -1431,8 +1431,8 @@ static void AddDefaultMethod(UStringVector &methods, unsigned size) } -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 @@ -1447,8 +1447,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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; @@ -1476,15 +1476,17 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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; @@ -1497,13 +1499,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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)); } } @@ -1521,7 +1523,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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]; @@ -1533,7 +1535,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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() @@ -1546,7 +1548,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 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 */ @@ -1575,7 +1577,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, methods_loc.Add(UString(hp.Method)); RINOK(hb_Loc.SetMethods( EXTERNAL_CODECS_LOC_VARS - methods_loc)); + methods_loc)) } else res_SetMethods = E_NOTIMPL; @@ -1588,7 +1590,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, hb_Use = &hb_Loc; RINOK(hb_Loc.SetMethods( EXTERNAL_CODECS_LOC_VARS - methods_loc)); + methods_loc)) } } @@ -1601,16 +1603,16 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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; } @@ -1643,7 +1645,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, } } - RINOK(extractCallback->SetOperationResult(opRes)); + RINOK(extractCallback->SetOperationResult(opRes)) } return lps->SetCur(); @@ -1673,7 +1675,7 @@ static HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PRO 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; @@ -1686,15 +1688,15 @@ static HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PRO } -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 @@ -1702,8 +1704,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt return E_NOTIMPL; /* - CMyComPtr reportArcProp; - callback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); + Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, + reportArcProp, callback) */ CObjectVector updateItems; @@ -1721,7 +1723,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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); @@ -1731,7 +1733,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { { 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) @@ -1741,7 +1743,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } RINOK(GetPropString(callback, i, kpidPath, ui.Path, - true)); // convertSlash + true)) // convertSlash /* if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/') ui.Name += '/'; @@ -1751,7 +1753,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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; @@ -1768,11 +1770,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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; @@ -1790,13 +1792,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } 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); @@ -1806,7 +1808,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } } - RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods)); + RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods)) CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; @@ -1839,7 +1841,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt for (i = 0; i < updateItems.Size(); i++) { lps->InSize = complexity; - RINOK(lps->SetCur()); + RINOK(lps->SetCur()) const CUpdateItem &ui = updateItems[i]; @@ -1863,12 +1865,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt 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; @@ -1876,8 +1879,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt currentComplexity = size; } /* - CMyComPtr getProps; - fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); + Z7_DECL_CMyComPtr_QI_FROM( + IStreamGetProps, + getProps, fileInStream) if (getProps) { FILETIME mTime; @@ -1906,11 +1910,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt { 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); @@ -1967,7 +1971,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt } } */ - RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); + RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)) } else { @@ -1992,7 +1996,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt return E_OUTOFMEMORY; } - RINOK(WriteStream(outStream, hashFileString, hashFileString.Len())); + RINOK(WriteStream(outStream, hashFileString, hashFileString.Len())) return S_OK; COM_TRY_END @@ -2045,7 +2049,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &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 @@ -2053,7 +2057,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR 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 --git a/CPP/7zip/UI/Common/HashCalc.h b/CPP/7zip/UI/Common/HashCalc.h index c566caa8..0b527c16 100644 --- a/CPP/7zip/UI/Common/HashCalc.h +++ b/CPP/7zip/UI/Common/HashCalc.h @@ -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 @@ struct CHasherState }; +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 @@ struct IHashCalc 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 @@ struct CHashBundle: public IHashCalc 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; \ - -struct IHashCallbackUI: public IDirItemsCallback -{ - INTERFACE_IHashCallbackUI(=0) -}; +Z7_PURE_INTERFACES_BEGIN + +// 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 @@ struct CHashOptions OpenShareForWrite(false), StdInMode(false), AltStreamsMode(false), - PathMode(NWildcard::k_RelatPath) {}; + PathMode(NWildcard::k_RelatPath) {} }; @@ -213,7 +217,7 @@ HRESULT HashCalc( -#ifndef _SFX +#ifndef Z7_SFX namespace NHash { @@ -264,14 +268,12 @@ struct CHashPair }; -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 @@ class CHandler: 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 --git a/CPP/7zip/UI/Common/IFileExtractCallback.h b/CPP/7zip/UI/Common/IFileExtractCallback.h index e6a85c6d..dd5c0d72 100644 --- a/CPP/7zip/UI/Common/IFileExtractCallback.h +++ b/CPP/7zip/UI/Common/IFileExtractCallback.h @@ -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 @@ IID_IFolderArchiveExtractCallback is requested by: 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 @@ is implemented by 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 --git a/CPP/7zip/UI/Common/LoadCodecs.cpp b/CPP/7zip/UI/Common/LoadCodecs.cpp index 4f15407b..5a65bdce 100644 --- a/CPP/7zip/UI/Common/LoadCodecs.cpp +++ b/CPP/7zip/UI/Common/LoadCodecs.cpp @@ -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 @@ EXTERNAL_CODECS 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 @@ EXPORT_CODECS #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 @@ static const UINT kIconTypesResId = 100; #include "../../../Windows/Registry.h" #endif +using namespace NWindows; using namespace NFile; @@ -119,7 +106,7 @@ static bool ReadPathFromRegistry(HKEY baseKey, LPCWSTR value, FString &path) #endif // _WIN32 -#endif // EXTERNAL_CODECS +#endif // Z7_EXTERNAL_CODECS static const unsigned kNumArcsMax = 72; @@ -133,8 +120,10 @@ void RegisterArc(const CArcInfo *arcInfo) throw() g_Arcs[g_NumArcs] = arcInfo; g_NumArcs++; } + // else throw 1; } +/* static void SplitString(const UString &srcString, UStringVector &destStrings) { destStrings.Clear(); @@ -159,6 +148,7 @@ static void SplitString(const UString &srcString, UStringVector &destStrings) if (!s.IsEmpty()) destStrings.Add(s); } +*/ int CArcInfoEx::FindExtension(const UString &ext) const { @@ -187,7 +177,7 @@ void CArcInfoEx::AddExts(const UString &ext, const UString &addExt) } } -#ifndef _SFX +#ifndef Z7_SFX static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector &signatures) { @@ -205,11 +195,11 @@ static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS static FString GetBaseFolderPrefixFromRegistry() { @@ -238,7 +228,7 @@ static HRESULT GetCoderClass(Func_GetMethodProperty getMethodProperty, UInt32 in { 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 @@ static HRESULT GetMethodBoolProp(Func_GetMethodProperty getMethodProperty, UInt3 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 @@ static HRESULT GetMethodBoolProp(Func_GetMethodProperty getMethodProperty, UInt3 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 @@ static HRESULT GetProp( 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 @@ static HRESULT GetProp_Bool( { 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 @@ static HRESULT GetProp_UInt32( 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 @@ static HRESULT GetProp_String( { 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 @@ static HRESULT GetProp_RawData( { 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,23 +407,22 @@ HRESULT CCodecs::LoadFormats() 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 (getFormatLevelMask, Func_GetFormatLevelMask, lib.GetProc("GetFormatLevelMask")); + 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; } @@ -440,7 +433,7 @@ HRESULT CCodecs::LoadFormats() 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; @@ -455,18 +448,18 @@ HRESULT CCodecs::LoadFormats() } 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); @@ -474,24 +467,24 @@ HRESULT CCodecs::LoadFormats() item.Flags |= kArcFlagsPars[j + 1]; } } - + { 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)); @@ -499,15 +492,12 @@ HRESULT CCodecs::LoadFormats() if (getIsArc) getIsArc(i, &item.IsArcFunc); - if (getFormatLevelMask) - getFormatLevelMask(i, &item.LevelsMask); - Formats.Add(item); } return S_OK; } -#ifdef _7ZIP_LARGE_PAGES +#ifdef Z7_LARGE_PAGES extern "C" { extern SIZE_T g_LargePageSize; @@ -517,12 +507,57 @@ extern "C" 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) @@ -541,7 +576,7 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded // #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(); @@ -562,20 +597,30 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded 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(); @@ -586,10 +631,10 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded } */ - #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(); } @@ -597,14 +642,14 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded 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; @@ -614,7 +659,7 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded */ - 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(); @@ -644,7 +689,8 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded } */ } - else + } + else { AddLastError(dllPath); } @@ -690,7 +736,7 @@ HRESULT CCodecs::LoadDllsFromFolder(const FString &folderPath) continue; #endif - RINOK(LoadDll(folderPrefix + fi.Name, true)); + RINOK(LoadDll(folderPrefix + fi.Name, true)) } return S_OK; } @@ -718,18 +764,20 @@ void CCodecs::CloseLibs() // 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(); @@ -755,7 +803,7 @@ HRESULT CCodecs::Load() item.AddExts(e, ae); } - #ifndef _SFX + #ifndef Z7_SFX item.CreateOutArchive = arc.CreateOutArchive; item.UpdateEnabled = (arc.CreateOutArchive != NULL); @@ -778,16 +826,16 @@ HRESULT CCodecs::Load() // 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; @@ -810,10 +858,10 @@ HRESULT CCodecs::Load() 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)) } } } @@ -825,7 +873,7 @@ HRESULT CCodecs::Load() return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX int CCodecs::FindFormatForArchiveName(const UString &arcPath) const { @@ -891,60 +939,10 @@ bool CCodecs::FindFormatForArchiveType(const UString &arcType, CIntVector &forma 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 @@ -968,24 +966,24 @@ STDAPI GetHasherProp(UInt32 codecIndex, PROPID propID, PROPVARIANT *value); #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 || @@ -1014,14 +1012,14 @@ STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *valu #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) { @@ -1037,14 +1035,14 @@ STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder) #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) { @@ -1061,23 +1059,23 @@ STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder) } -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 @@ -1085,13 +1083,13 @@ STDMETHODIMP CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *va #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 @@ -1106,7 +1104,7 @@ int CCodecs::GetCodec_LibIndex(UInt32 index) const return -1; #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; return (int)ci.LibIndex; #else @@ -1121,7 +1119,7 @@ int CCodecs::GetHasherLibIndex(UInt32 index) return -1; #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; return (int)ci.LibIndex; #else @@ -1144,7 +1142,7 @@ bool CCodecs::GetCodec_DecoderIsAssigned(UInt32 index) const } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return Codecs[index - NUM_EXPORT_CODECS].DecoderIsAssigned; #else return false; @@ -1167,7 +1165,7 @@ bool CCodecs::GetCodec_EncoderIsAssigned(UInt32 index) const } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return Codecs[index - NUM_EXPORT_CODECS].EncoderIsAssigned; #else return false; @@ -1194,7 +1192,7 @@ bool CCodecs::GetCodec_IsFilter(UInt32 index, bool &isAssigned) const } #endif - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { const CDllCodecInfo &c = Codecs[index - NUM_EXPORT_CODECS]; isAssigned = c.IsFilter_Assigned; @@ -1221,7 +1219,7 @@ UInt32 CCodecs::GetCodec_NumStreams(UInt32 index) 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; @@ -1290,9 +1288,9 @@ void CCodecs::GetCodecsErrorMessage(UString &s) } } -#endif // EXTERNAL_CODECS +#endif // Z7_EXTERNAL_CODECS -#ifndef _SFX +#ifndef Z7_SFX extern unsigned g_NumCodecs; extern const CCodecInfo *g_Codecs[]; @@ -1315,7 +1313,7 @@ void CCodecs::Get_CodecsInfoUser_Vector(CObjectVector &v) } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS { UInt32 numMethods; if (GetNumMethods(&numMethods) == S_OK) diff --git a/CPP/7zip/UI/Common/LoadCodecs.h b/CPP/7zip/UI/Common/LoadCodecs.h index 8d838394..8af50057 100644 --- a/CPP/7zip/UI/Common/LoadCodecs.h +++ b/CPP/7zip/UI/Common/LoadCodecs.h @@ -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 @@ CCodecs object, that contains 3 lists of plugins: 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 @@ EXTERNAL_CODECS #include "../../../Common/MyString.h" #include "../../../Common/ComTry.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS #include "../../../Windows/DLL.h" #endif @@ -60,7 +60,7 @@ EXTERNAL_CODECS #include "../../Archive/IArchive.h" -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS struct CDllCodecInfo { @@ -104,19 +104,21 @@ struct CArcInfoEx 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; @@ -125,10 +127,10 @@ struct CArcInfoEx 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; @@ -193,6 +195,7 @@ struct CArcInfoEx 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 @@ -201,7 +204,7 @@ struct CArcInfoEx for (int i = 0; i < Exts.Size(); i++) { if (i > 0) - s += ' '; + s.Add_Space(); s += Exts[i].Ext; } return s; @@ -216,43 +219,24 @@ struct CArcInfoEx 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) , LevelsMask(0xFFFFFFFF) #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; @@ -264,17 +248,23 @@ struct CCodecLib 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) {} }; @@ -303,8 +293,8 @@ struct CCodecInfoUser }; -class CCodecs: - #ifdef EXTERNAL_CODECS +class CCodecs Z7_final: + #ifdef Z7_EXTERNAL_CODECS public ICompressCodecsInfo, public IHashers, #else @@ -312,9 +302,15 @@ class CCodecs: #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; @@ -325,7 +321,7 @@ class CCodecs: 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/ @@ -354,13 +350,15 @@ class CCodecs: #endif + /* #ifdef NEW_FOLDER_INTERFACE CCodecIcons InternalIcons; #endif + */ CObjectVector Formats; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CRecordVector Codecs; CRecordVector Hashers; #endif @@ -369,7 +367,7 @@ class CCodecs: bool CaseSensitive; CCodecs(): - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS NeedSetLibCodecs(true), #endif CaseSensitive_Change(false), @@ -388,34 +386,14 @@ class CCodecs: 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; @@ -437,7 +415,7 @@ class CCodecs: HRESULT CreateInArchive(unsigned formatIndex, CMyComPtr &archive) const { const CArcInfoEx &ai = Formats[formatIndex]; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (ai.LibIndex < 0) #endif { @@ -446,17 +424,17 @@ class CCodecs: 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 { @@ -466,7 +444,7 @@ class CCodecs: COM_TRY_END } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS return CreateArchiveHandler(ai, true, (void **)&archive); #endif } @@ -486,21 +464,21 @@ class CCodecs: 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 --git a/CPP/7zip/UI/Common/OpenArchive.cpp b/CPP/7zip/UI/Common/OpenArchive.cpp index d632b15b..cbe9e677 100644 --- a/CPP/7zip/UI/Common/OpenArchive.cpp +++ b/CPP/7zip/UI/Common/OpenArchive.cpp @@ -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 @@ static const UInt64 kMaxCheckStartPosition = 1 << 23; using namespace NWindows; /* -#ifdef _SFX +#ifdef Z7_SFX #define OPEN_PROPS_PARAM #else #define OPEN_PROPS_PARAM , props @@ -111,7 +111,7 @@ CArc::~CArc() } */ -#ifndef _SFX +#ifndef Z7_SFX namespace NArchive { namespace NParser { @@ -172,23 +172,14 @@ struct CParseItem } }; -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 @@ static const Byte kProps[] = 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 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val 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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, { 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 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, } -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 @@ HRESULT Archive_GetItemBoolProp(IInArchive *arc, UInt32 index, PROPID propID, bo { 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 @@ static HRESULT Archive_GetArcProp_Bool(IInArchive *arc, PROPID propid, bool &res { 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 @@ static HRESULT Archive_GetArcProp_UInt(IInArchive *arc, PROPID propid, UInt64 &r { 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 @@ static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &res { 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 @@ static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &res return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const { @@ -550,14 +541,14 @@ HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &p 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 @@ HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &p 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 @@ HRESULT CArc::GetItem_Path(UInt32 index, UString &result) const { 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 @@ HRESULT CArc::GetItem_DefaultPath(UInt32 index, UString &result) const { 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_DefaultPath(UInt32 index, UString &result) const 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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const 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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const 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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const { 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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const } 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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const #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 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const 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 @@ HRESULT CArc::GetItem_Size(UInt32 index, UInt64 &size, bool &defined) const 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 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const { 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 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const // (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 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const 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 @@ static bool IsPreArcFormat(const CArcInfoEx &ai) { 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[] = @@ -1144,44 +1135,46 @@ static bool IsNewStyleSignature(const CArcInfoEx &ai) // 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) @@ -1191,12 +1184,12 @@ STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password) } #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; @@ -1206,7 +1199,7 @@ STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UIn 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); @@ -1215,7 +1208,7 @@ STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT // 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); @@ -1267,32 +1260,32 @@ HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openR 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) @@ -1303,7 +1296,7 @@ HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openR */ 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); @@ -1339,12 +1332,12 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom // 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]; @@ -1356,14 +1349,14 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom 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]; @@ -1393,14 +1386,14 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom } } */ - 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) { @@ -1408,14 +1401,14 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr 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; @@ -1426,7 +1419,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr 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; @@ -1436,7 +1429,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr { NCOM::CPropVariant prop; - RINOK(archive->GetArchiveProperty(kpidName, &prop)); + RINOK(archive->GetArchiveProperty(kpidName, &prop)) if (prop.vt == VT_BSTR) { pi.Name.SetFromBstr(prop.bstrVal); @@ -1444,7 +1437,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr } else { - RINOK(archive->GetArchiveProperty(kpidExtension, &prop)); + RINOK(archive->GetArchiveProperty(kpidExtension, &prop)) if (prop.vt == VT_BSTR) pi.Extension.SetFromBstr(prop.bstrVal); } @@ -1452,14 +1445,14 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr { 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)); @@ -1500,14 +1493,14 @@ HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset) { 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; @@ -1528,21 +1521,19 @@ HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset) -#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; @@ -1551,17 +1542,17 @@ class CExtractCallback_To_OpenCallback: } }; -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) { @@ -1573,18 +1564,18 @@ STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize 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; } @@ -1598,30 +1589,31 @@ static HRESULT OpenArchiveSpec(IInArchive *archive, bool needPhySize, /* 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")); } } @@ -1664,7 +1656,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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)); } @@ -1672,7 +1664,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) CIntVector orderIndices; bool searchMarkerInHandler = false; - #ifdef _SFX + #ifdef Z7_SFX searchMarkerInHandler = true; #endif @@ -1682,25 +1674,25 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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); @@ -1712,12 +1704,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) else { unsigned numFinded = 0; - #ifndef _SFX + #ifndef Z7_SFX bool isPrearcExt = false; #endif { - #ifndef _SFX + #ifndef Z7_SFX bool isZip = false; bool isRar = false; @@ -1759,13 +1751,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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 @@ -1796,11 +1788,11 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) } */ - #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)) @@ -1809,13 +1801,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) } 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; @@ -1835,7 +1827,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -1871,7 +1863,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) FOR_VECTOR (i, orderIndices) { - int val = orderIndices[i]; + const int val = orderIndices[i]; if (val != -1) orderIndices2.Add(val); } @@ -1880,12 +1872,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; } @@ -1894,7 +1886,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) numMainTypes = numFinded; isUnknownExt = (numMainTypes == 0) || isPrearcExt; - #else // _SFX + #else // Z7_SFX numMainTypes = orderIndices.Size(); @@ -1908,13 +1900,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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()); { @@ -1946,7 +1937,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) bool exactOnly = false; - #ifndef _SFX + #ifndef Z7_SFX const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex]; // OutputDebugStringW(ai.Name); @@ -1964,16 +1955,16 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) // 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; @@ -1992,13 +1983,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -2018,7 +2009,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) // 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; @@ -2027,7 +2018,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) } /* - #ifndef _SFX + #ifndef Z7_SFX if (IsExeExt(extension) || ai.Flags_PreArc()) { // openOnlyFullArc = false; @@ -2040,9 +2031,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) continue; } - RINOK(result); + RINOK(result) - #ifndef _SFX + #ifndef Z7_SFX bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); @@ -2050,7 +2041,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; } @@ -2104,7 +2095,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) - #ifndef _SFX + #ifndef Z7_SFX if (!op.stream) return S_FALSE; @@ -2149,9 +2140,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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) @@ -2233,12 +2224,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -2264,9 +2255,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) // printf(" OpenForSize Error"); continue; } - RINOK(result); + RINOK(result) - RINOK(ReadBasicProps(archive, 0, result)); + RINOK(ReadBasicProps(archive, 0, result)) if (Offset > 0) { @@ -2303,7 +2294,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -2313,7 +2304,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) { if (mode.ZerosTailIsAllowed) { - RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))); + RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))) if (ErrorInfo.IgnoreTail) openCur = true; } @@ -2353,7 +2344,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) continue; // printf("\nAdd offset = %d", (int)pi.Offset); - RINOK(ReadParseItemProps(archive, ai, pi)); + RINOK(ReadParseItemProps(archive, ai, pi)) handlerSpec->AddItem(pi); } } @@ -2452,7 +2443,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) // canReturnTailArc = true; } - RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); + RINOK(InStream_SeekToBegin(op.stream)) CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream; CMyComPtr limitedStream = limitedStreamSpec; @@ -2466,13 +2457,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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); @@ -2510,8 +2501,8 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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) { @@ -2569,7 +2560,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) if (pos >= callbackPrev + (1 << 23)) { - RINOK(openCallback_Offset_Spec->SetCompleted(NULL, NULL)); + RINOK(openCallback_Offset->SetCompleted(NULL, NULL)) callbackPrev = pos; } } @@ -2692,10 +2683,10 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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) @@ -2717,7 +2708,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -2729,12 +2720,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; } @@ -2756,7 +2747,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; @@ -2785,7 +2776,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) continue; } isOpen = true; - RINOK(result); + RINOK(result) PRF(printf(" OK ")); } @@ -2875,7 +2866,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) pos = pi.Offset + pi.Size; - RINOK(ReadParseItemProps(archive, ai, pi)); + RINOK(ReadParseItemProps(archive, ai, pi)) if (pi.Offset < startArcPos && !mode.EachPos /* && phySize_Defined */) { @@ -2904,7 +2895,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) 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; } @@ -3030,7 +3021,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op) HRESULT CArc::OpenStream(const COpenOptions &op) { - RINOK(OpenStream2(op)); + RINOK(OpenStream2(op)) // PrintNumber("op.formatIndex 3", op.formatIndex); if (Archive) @@ -3040,12 +3031,12 @@ HRESULT CArc::OpenStream(const COpenOptions &op) 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; @@ -3075,7 +3066,7 @@ HRESULT CArc::OpenStream(const COpenOptions &op) return S_OK; } -#ifdef _SFX +#ifdef Z7_SFX #ifdef _WIN32 #define k_ExeExt ".exe" @@ -3106,7 +3097,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op) if (!fileStreamSpec->Open(us2fs(Path))) return GetLastError_noZero_HRESULT(); op.stream = fileStream; - #ifdef _SFX + #ifdef Z7_SFX IgnoreSplit = true; #endif } @@ -3115,7 +3106,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op) 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)) } */ @@ -3123,7 +3114,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op) HRESULT res = OpenStream(op); IgnoreSplit = false; - #ifdef _SFX + #ifdef Z7_SFX if (res != S_FALSE || !fileStreamSpec @@ -3142,7 +3133,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op) if (ai.Is_Split()) continue; UString path3 = path2; - path3 += '.'; + path3.Add_Dot(); path3 += ai.GetMainExt(); // "7z" for SFX. Path = path3; Path += ".001"; @@ -3188,7 +3179,7 @@ HRESULT CArchiveLink::Close() for (unsigned i = Arcs.Size(); i != 0;) { i--; - RINOK(Arcs[i].Close()); + RINOK(Arcs[i].Close()) } IsOpen = false; // ErrorsText.Empty(); @@ -3321,13 +3312,13 @@ HRESULT CArchiveLink::Open(COpenOptions &op) 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; } @@ -3346,16 +3337,17 @@ HRESULT CArchiveLink::Open(COpenOptions &op) 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); } @@ -3366,7 +3358,7 @@ HRESULT CArchiveLink::Open(COpenOptions &op) CIntVector excl; COpenOptions op2; - #ifndef _SFX + #ifndef Z7_SFX op2.props = op.props; #endif op2.codecs = op.codecs; @@ -3389,8 +3381,8 @@ HRESULT CArchiveLink::Open(COpenOptions &op) 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(); @@ -3409,7 +3401,7 @@ HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI) if (!op.stream && !op.stdInMode) { NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name); - RINOK(openCallbackSpec->Init2(prefix, name)); + RINOK(openCallbackSpec->Init2(prefix, name)) } else { @@ -3424,7 +3416,7 @@ HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI) PasswordWasAsked = openCallbackSpec->PasswordWasAsked; // Password = openCallbackSpec->Password; - RINOK(res); + RINOK(res) // VolumePaths.Add(fs2us(prefix + name)); FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed) @@ -3447,8 +3439,9 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_ 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; @@ -3463,7 +3456,7 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_ 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 @@ -3476,7 +3469,7 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_ 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; @@ -3489,7 +3482,7 @@ HRESULT CArchiveLink::Open3(COpenOptions &op, IOpenCallbackUI *callbackUI) HRESULT res = Open2(op, callbackUI); if (callbackUI) { - RINOK(callbackUI->Open_Finished()); + RINOK(callbackUI->Open_Finished()) } return res; } @@ -3509,6 +3502,8 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op) 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; @@ -3517,7 +3512,7 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op) { FString dirPrefix, fileName; NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName); - RINOK(openCallbackSpec->Init2(dirPrefix, fileName)); + RINOK(openCallbackSpec->Init2(dirPrefix, fileName)) } @@ -3528,7 +3523,9 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op) 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; @@ -3537,7 +3534,7 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op) return res; } -#ifndef _SFX +#ifndef Z7_SFX bool ParseComplexSize(const wchar_t *s, UInt64 &result); bool ParseComplexSize(const wchar_t *s, UInt64 &result) diff --git a/CPP/7zip/UI/Common/OpenArchive.h b/CPP/7zip/UI/Common/OpenArchive.h index e3220b94..5c3bfe5d 100644 --- a/CPP/7zip/UI/Common/OpenArchive.h +++ b/CPP/7zip/UI/Common/OpenArchive.h @@ -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 @@ struct COptionalOpenProperties }; */ -#ifdef _SFX +#ifdef Z7_SFX #define OPEN_PROPS_DECL #else #define OPEN_PROPS_DECL const CObjectVector *props; @@ -243,7 +243,7 @@ struct CReadArcItem bool MainIsDir; UInt32 ParentIndex; // use it, if IsAltStream - #ifndef _SFX + #ifndef Z7_SFX bool _use_baseParentFolder_mode; int _baseParentFolder; #endif @@ -254,7 +254,7 @@ struct CReadArcItem WriteToAltStreamIfColon = false; #endif - #ifndef _SFX + #ifndef Z7_SFX _use_baseParentFolder_mode = false; _baseParentFolder = -1; #endif @@ -270,7 +270,7 @@ class CArc 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 @@ class CArc 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 @@ class CArc // 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 @@ class CArc // 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 @@ class CArc HRESULT ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes); - // ~CArc(); - HRESULT Close() { InStream.Release(); diff --git a/CPP/7zip/UI/Common/PropIDUtils.cpp b/CPP/7zip/UI/Common/PropIDUtils.cpp index 72384b3e..ee9ff323 100644 --- a/CPP/7zip/UI/Common/PropIDUtils.cpp +++ b/CPP/7zip/UI/Common/PropIDUtils.cpp @@ -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 @@ FILE_ATTRIBUTE_ 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 @@ void ConvertWinAttribToString(char *s, UInt32 wa) throw() 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 @@ void ConvertPropertyToShortString2(char *dest, const PROPVARIANT &prop, PROPID p { 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 @@ void ConvertPropertyToShortString2(char *dest, const PROPVARIANT &prop, PROPID p 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 @@ void ConvertPropertyToString2(UString &dest, const PROPVARIANT &prop, PROPID pro dest = temp; } -#ifndef _SFX +#ifndef Z7_SFX static inline unsigned GetHex(unsigned v) { @@ -387,33 +387,33 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize) 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 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize) 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 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize) } 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 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize) } 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 ParseOwner(AString &s, const Byte *p, UInt32 size, UInt32 pos) 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 @@ static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName 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 @@ static bool CheckSid(const Byte *data, UInt32 size, UInt32 pos) throw() 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 @@ bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s) 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 @@ bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s) s += "..."; break; } - unsigned b = data[i]; + const unsigned b = data[i]; s += (char)GetHex((b >> 4) & 0xF); s += (char)GetHex(b & 0xF); } diff --git a/CPP/7zip/UI/Common/PropIDUtils.h b/CPP/7zip/UI/Common/PropIDUtils.h index 915bfc28..6df1e94c 100644 --- a/CPP/7zip/UI/Common/PropIDUtils.h +++ b/CPP/7zip/UI/Common/PropIDUtils.h @@ -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 @@ void ConvertPropertyToString2(UString &dest, const PROPVARIANT &propVariant, PRO 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 --git a/CPP/7zip/UI/Common/Property.h b/CPP/7zip/UI/Common/Property.h index 8b57a2a6..04628098 100644 --- a/CPP/7zip/UI/Common/Property.h +++ b/CPP/7zip/UI/Common/Property.h @@ -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 --git a/CPP/7zip/UI/Common/SetProperties.cpp b/CPP/7zip/UI/Common/SetProperties.cpp index 4b3037af..5e15d9c0 100644 --- a/CPP/7zip/UI/Common/SetProperties.cpp +++ b/CPP/7zip/UI/Common/SetProperties.cpp @@ -18,7 +18,7 @@ using namespace NCOM; 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 @@ HRESULT SetProperties(IUnknown *unknown, const CObjectVector &propert { 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 @@ HRESULT SetProperties(IUnknown *unknown, const CObjectVector &propert { if (!name.IsEmpty()) { - wchar_t c = name.Back(); + const wchar_t c = name.Back(); if (c == L'-') propVariant = false; else if (c == L'+') diff --git a/CPP/7zip/UI/Common/SetProperties.h b/CPP/7zip/UI/Common/SetProperties.h index 892f1a21..0676c45d 100644 --- a/CPP/7zip/UI/Common/SetProperties.h +++ b/CPP/7zip/UI/Common/SetProperties.h @@ -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 --git a/CPP/7zip/UI/Common/SortUtils.h b/CPP/7zip/UI/Common/SortUtils.h index 8e42e068..07aa24d2 100644 --- a/CPP/7zip/UI/Common/SortUtils.h +++ b/CPP/7zip/UI/Common/SortUtils.h @@ -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 --git a/CPP/7zip/UI/Common/StdAfx.h b/CPP/7zip/UI/Common/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/UI/Common/StdAfx.h +++ b/CPP/7zip/UI/Common/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Common/TempFiles.h b/CPP/7zip/UI/Common/TempFiles.h index 4099e655..dd4ac203 100644 --- a/CPP/7zip/UI/Common/TempFiles.h +++ b/CPP/7zip/UI/Common/TempFiles.h @@ -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 --git a/CPP/7zip/UI/Common/Update.cpp b/CPP/7zip/UI/Common/Update.cpp index 03042a1b..27625aeb 100644 --- a/CPP/7zip/UI/Common/Update.cpp +++ b/CPP/7zip/UI/Common/Update.cpp @@ -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 @@ HRESULT CUpdateErrorInfo::SetFromError_DWORD(const char *message, const FString using namespace NUpdateArchive; -class COutMultiVolStream: - public IOutStream, - public CMyUnknownImp +struct CMultiOutStream_Rec { - 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); + CMultiOutStream *Spec; + CMyComPtr Ref; }; -// static NSynchronization::CCriticalSection g_TempPathsCS; - -HRESULT COutMultiVolStream::Close() -{ - HRESULT res = S_OK; - FOR_VECTOR (i, Streams) - { - COutFileStream *s = Streams[i].StreamSpec; - if (s) - { - HRESULT res2 = s->Close(); - if (res2 != S_OK) - res = res2; - } - } - return res; -} - -bool COutMultiVolStream::SetMTime(const CFiTime *mTime) +struct CMultiOutStream_Bunch { - bool res = true; - FOR_VECTOR (i, Streams) - { - 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) + CObjectVector Items; + + HRESULT Destruct() { - if (_streamIndex >= Streams.Size()) + HRESULT hres = S_OK; + FOR_VECTOR (i, Items) { - 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(); + CMultiOutStream_Rec &rec = Items[i]; + if (rec.Ref) { - // NSynchronization::CCriticalSectionLock lock(g_TempPathsCS); - TempFiles->Paths.Add(name); + const HRESULT hres2 = rec.Spec->Destruct(); + if (hres == S_OK) + hres = hres2; } - - 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) - { - _streamIndex++; - _offsetPos = 0; } - if (realProcessed == 0 && curSize != 0) - return E_FAIL; - break; + Items.Clear(); + return hres; } - 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()) + void DisableDeletion() { - CAltStreamInfo &altStream = Streams[i++]; - if ((UInt64)newSize < altStream.RealSize) + FOR_VECTOR (i, Items) { - RINOK(altStream.Stream->SetSize(newSize)); - altStream.RealSize = newSize; - break; + CMultiOutStream_Rec &rec = Items[i]; + if (rec.Ref) + rec.Spec->NeedDelete = false; } - 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 CArchivePath::GetFinalPath() const UString path = GetPathWithoutExt(); if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += BaseExtension; } return path; @@ -317,7 +160,7 @@ UString CArchivePath::GetFinalVolPath() const // if BaseExtension is empty, we must ignore VolExtension also. if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += VolExtension; } return path; @@ -329,7 +172,7 @@ FString CArchivePath::GetTempPath() const path += us2fs(Name); if (!BaseExtension.IsEmpty()) { - path += '.'; + path.Add_Dot(); path += us2fs(BaseExtension); } path += ".tmp"; @@ -403,7 +246,7 @@ bool CUpdateOptions::SetArcPath(const CCodecs *codecs, const UString &arcPath) } -struct CUpdateProduceCallbackImp: public IUpdateProduceCallback +struct CUpdateProduceCallbackImp Z7_final: public IUpdateProduceCallback { const CObjectVector *_arcItems; CDirItemsStat *_stat; @@ -417,7 +260,7 @@ struct CUpdateProduceCallbackImp: public IUpdateProduceCallback _stat(stat), _callback(callback) {} - virtual HRESULT ShowDeleteFile(unsigned arcIndex); + virtual HRESULT ShowDeleteFile(unsigned arcIndex) Z7_override; }; @@ -499,6 +342,8 @@ bool CRenamePair::GetNewPath(bool isFolder, const UString &src, UString &dest) c int FindAltStreamColon_in_Path(const wchar_t *path); #endif + + static HRESULT Compress( const CUpdateOptions &options, bool isUpdatingItself, @@ -511,6 +356,7 @@ static HRESULT Compress( const CDirItems &dirItems, const CDirItem *parentDirItem, CTempFiles &tempFiles, + CMultiOutStream_Bunch &multiStreams, CUpdateErrorInfo &errorInfo, IUpdateCallbackUI *callback, CFinishArchiveStat &st) @@ -530,15 +376,15 @@ static HRESULT Compress( } 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 @@ static HRESULT Compress( 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,8 +426,8 @@ static HRESULT Compress( */ UInt32 value; - RINOK(outArchive->GetFileTimeType(&value)); - + RINOK(outArchive->GetFileTimeType(&value)) + // we support any future fileType here. fileTimeType = (NFileTimeType::EEnum)value; @@ -676,7 +522,7 @@ static HRESULT Compress( 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 @@ static HRESULT Compress( } } } - RINOK(callback->SetNumItems(stat2)); + RINOK(callback->SetNumItems(stat2)) } CArchiveUpdateCallback *updateCallbackSpec = new CArchiveUpdateCallback; @@ -828,7 +674,7 @@ static HRESULT Compress( COutFileStream *outStreamSpec = NULL; CStdOutFileStream *stdOutFileStreamSpec = NULL; - COutMultiVolStream *volStreamSpec = NULL; + CMultiOutStream *volStreamSpec = NULL; if (options.VolumesSizes.Size() == 0) { @@ -839,7 +685,6 @@ static HRESULT Compress( } else { - single: outStreamSpec = new COutFileStream; outSeekStream = outStreamSpec; outStream = outSeekStream; @@ -882,44 +727,24 @@ static HRESULT Compress( if (arc && arc->GetGlobalOffset() > 0) return E_NOTIMPL; - CMyComPtr multiVolArch; - outArchive->QueryInterface(IID_IMultiVolumeOutArchive, (void**)&multiVolArch); - if (multiVolArch) - { - CPropVariant prefix, postfix, name; - name = archivePath.Name; - BOOL numberAfterExt = FALSE; - UInt32 numberCount = 2; - RINOK(multiVolArch->GetMultiArchiveNameFmt(&name, &prefix, &postfix, &numberAfterExt, &numberCount)); - if (prefix.vt != VT_EMPTY && prefix.vt != VT_BSTR) - return E_FAIL; - if (postfix.vt != VT_EMPTY && postfix.vt != VT_BSTR) - return E_FAIL; - updateCallbackSpec->VolumesSizes = options.VolumesSizes; - if (name.vt == VT_BSTR) - updateCallbackSpec->VolName = archivePath.Prefix + name.bstrVal; - else - updateCallbackSpec->VolName = archivePath.Prefix + archivePath.Name; - updateCallbackSpec->VolNumberAfterExt = numberAfterExt != FALSE; - if (prefix.vt == VT_BSTR) - updateCallbackSpec->VolPrefix.SetFromBstr(prefix.bstrVal); - if (postfix.vt == VT_BSTR) - updateCallbackSpec->VolPostfix.SetFromBstr(postfix.bstrVal); - if (!archivePath.VolExtension.IsEmpty()) - updateCallbackSpec->VolExt = UString('.') + archivePath.VolExtension; - updateCallbackSpec->DigitCount = numberCount; - const_cast&>(options.VolumesSizes).Clear(); - goto single; - } - - 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; + updateCallbackSpec->VolName = archivePath.Prefix + archivePath.Name; + if (!archivePath.VolExtension.IsEmpty()) + updateCallbackSpec->VolExt = UString('.') + archivePath.VolExtension; + */ } if (options.SfxMode) @@ -937,22 +762,22 @@ static HRESULT Compress( { 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()) } } @@ -963,8 +788,8 @@ static HRESULT Compress( 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 @@ -977,10 +802,57 @@ static HRESULT Compress( } } + 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()) { @@ -991,10 +863,6 @@ static HRESULT Compress( if (options.SetArcMTime) { - CFiTime ft; - FiTime_Clear(ft); - bool isDefined = false; - // bool needNormalizeAfterStream; // needParse; /* @@ -1014,40 +882,9 @@ static HRESULT Compress( // 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) @@ -1055,12 +892,14 @@ static HRESULT Compress( */ } // 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); } } @@ -1080,7 +919,10 @@ static HRESULT Compress( if (outStreamSpec) result = outStreamSpec->Close(); else if (volStreamSpec) - result = volStreamSpec->Close(); + { + result = volStreamSpec->FinalFlush_and_CloseFiles(st.NumVolumes); + st.IsMultiVolMode = true; + } RINOK(result) @@ -1145,7 +987,7 @@ static HRESULT EnumerateInArchiveItems( arcItems.Clear(); UInt32 numItems; IInArchive *archive = arc.Archive; - RINOK(archive->GetNumberOfItems(&numItems)); + RINOK(archive->GetNumberOfItems(&numItems)) arcItems.ClearAndReserve(numItems); CReadArcItem item; @@ -1156,7 +998,7 @@ static HRESULT EnumerateInArchiveItems( { CArcItem ai; - RINOK(arc.GetItem(i, item)); + RINOK(arc.GetItem(i, item)) ai.Name = item.Path; ai.IsDir = item.IsDir; ai.IsAltStream = @@ -1176,8 +1018,8 @@ static HRESULT EnumerateInArchiveItems( 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); @@ -1187,10 +1029,73 @@ static HRESULT EnumerateInArchiveItems( #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, @@ -1277,8 +1182,7 @@ HRESULT UpdateArchive( if (!options.VolumesSizes.IsEmpty()) { arcPath = options.ArchivePath.GetFinalVolPath(); - arcPath += '.'; - arcPath += "001"; + arcPath += ".001"; } if (cmdArcPath2.IsEmpty()) @@ -1292,7 +1196,7 @@ HRESULT UpdateArchive( 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)) @@ -1343,7 +1247,7 @@ HRESULT UpdateArchive( CIntVector excl; COpenOptions op; - #ifndef _SFX + #ifndef Z7_SFX op.props = &options.MethodMode.Properties; #endif op.codecs = codecs; @@ -1353,7 +1257,7 @@ HRESULT UpdateArchive( op.stream = NULL; op.filePath = arcPath; - RINOK(callback->StartOpenArchive(arcPath)); + RINOK(callback->StartOpenArchive(arcPath)) HRESULT result = arcLink.Open_Strict(op, openCallback); @@ -1365,8 +1269,8 @@ HRESULT UpdateArchive( if (result == S_FALSE) return E_FAIL; */ - RINOK(res2); - RINOK(result); + RINOK(res2) + RINOK(result) if (arcLink.VolumePaths.Size() > 1) { @@ -1446,7 +1350,7 @@ HRESULT UpdateArchive( if (needScanning) { - RINOK(callback->StartScanning()); + RINOK(callback->StartScanning()) dirItems.SymLinks = options.SymLinks.Val; @@ -1457,7 +1361,7 @@ HRESULT UpdateArchive( dirItems.ScanAltStreams = options.AltStreams.Val; dirItems.ExcludeDirItems = censor.ExcludeDirItems; dirItems.ExcludeFileItems = censor.ExcludeFileItems; - + dirItems.ShareForWrite = options.OpenShareForWrite; #ifndef _WIN32 @@ -1476,7 +1380,7 @@ HRESULT UpdateArchive( 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) @@ -1484,7 +1388,7 @@ HRESULT UpdateArchive( { 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) @@ -1600,7 +1504,7 @@ HRESULT UpdateArchive( { RINOK(EnumerateInArchiveItems( // options.StoreAltStreams, - censor, arcLink.Arcs.Back(), arcItems)); + censor, arcLink.Arcs.Back(), arcItems)) } /* @@ -1619,8 +1523,10 @@ HRESULT UpdateArchive( processedItems[i] = 0; } + CMultiOutStream_Bunch multiStreams; + /* - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO if (arcLink.PasswordWasAsked) { // We set password, if open have requested password @@ -1664,18 +1570,22 @@ HRESULT UpdateArchive( 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) { @@ -1726,6 +1636,19 @@ HRESULT UpdateArchive( 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) @@ -1734,25 +1657,70 @@ HRESULT UpdateArchive( 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; @@ -1803,6 +1771,7 @@ HRESULT UpdateArchive( sendMail((LHANDLE)0, 0, &m, MAPI_DIALOG, 0); } + } } #endif @@ -1851,7 +1820,7 @@ HRESULT UpdateArchive( && 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); } } @@ -1876,12 +1845,12 @@ HRESULT UpdateArchive( 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 --git a/CPP/7zip/UI/Common/Update.h b/CPP/7zip/UI/Common/Update.h index 01fc43e2..a9459ffb 100644 --- a/CPP/7zip/UI/Common/Update.h +++ b/CPP/7zip/UI/Common/Update.h @@ -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 @@ struct CArchivePath 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 CRenamePair 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 @@ struct CUpdateOptions 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 @@ struct CUpdateOptions 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 @@ struct CUpdateOptions c.ActionSet = NUpdateArchive::k_ActionSet_Add; Commands.Add(c); } - - CRecordVector VolumesSizes; }; + struct CUpdateErrorInfo { DWORD SystemError; // it's DWORD (WRes) only; @@ -170,32 +169,40 @@ struct CUpdateErrorInfo 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; \ - -struct IUpdateCallbackUI2: public IUpdateCallbackUI, public IDirItemsCallback +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 \ + +DECLARE_INTERFACE(IUpdateCallbackUI2): + public IUpdateCallbackUI, + public IDirItemsCallback { - INTERFACE_IUpdateCallbackUI2(=0) + Z7_IFACE_PURE(IUpdateCallbackUI2) }; +Z7_PURE_INTERFACES_END HRESULT UpdateArchive( CCodecs *codecs, diff --git a/CPP/7zip/UI/Common/UpdateAction.h b/CPP/7zip/UI/Common/UpdateAction.h index bc53fcdb..6a3565e7 100644 --- a/CPP/7zip/UI/Common/UpdateAction.h +++ b/CPP/7zip/UI/Common/UpdateAction.h @@ -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 --git a/CPP/7zip/UI/Common/UpdateCallback.cpp b/CPP/7zip/UI/Common/UpdateCallback.cpp index 38a205f3..5e2860dd 100644 --- a/CPP/7zip/UI/Common/UpdateCallback.cpp +++ b/CPP/7zip/UI/Common/UpdateCallback.cpp @@ -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,28 +57,11 @@ static NSynchronization::CCriticalSection g_CriticalSection; #endif -#ifdef _USE_SECURITY_CODE +#ifdef Z7_USE_SECURITY_CODE bool InitLocalPrivileges(); #endif CArchiveUpdateCallback::CArchiveUpdateCallback(): - _hardIndex_From((UInt32)(Int32)-1), - - VolNumberAfterExt(false), - DigitCount(2), - - Callback(NULL), - - DirItems(NULL), - ParentDirItem(NULL), - - Arc(NULL), - ArcItems(NULL), - UpdatePairs(NULL), - NewNames(NULL), - CommentIndex(-1), - Comment(NULL), - PreserveATime(false), ShareForWrite(false), StopAfterOpenError(false), @@ -82,7 +71,7 @@ CArchiveUpdateCallback::CArchiveUpdateCallback(): StoreNtSecurity(false), StoreHardLinks(false), StoreSymLinks(false), - + #ifndef _WIN32 StoreOwnerId(false), StoreOwnerName(false), @@ -95,29 +84,42 @@ CArchiveUpdateCallback::CArchiveUpdateCallback(): 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); @@ -138,17 +140,17 @@ static const CStatProp kProps[] = { 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); @@ -162,7 +164,8 @@ STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index, COM_TRY_END } -STDMETHODIMP CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value) + +Z7_COM7F_IMF(CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value)) { NCOM::CPropVariant prop; switch (propID) @@ -178,14 +181,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *val 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) @@ -193,25 +196,27 @@ STDMETHODIMP CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps) 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) @@ -235,12 +240,10 @@ STDMETHODIMP CArchiveUpdateCallback::GetRootRawProp(PROPID 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; @@ -267,7 +270,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, con const CDirItem &di = DirItems->Items[(unsigned)up.DirIndex]; #endif - #ifdef _USE_SECURITY_CODE + #ifdef Z7_USE_SECURITY_CODE if (propID == kpidNtSecure) { if (!StoreNtSecurity) @@ -351,7 +354,7 @@ static UString GetRelativePath(const UString &to, const UString &from) #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]; @@ -387,7 +390,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR 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,7 +487,12 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR #if defined(_WIN32) case kpidIsAltStream: prop = di.IsAltStream; break; // case kpidShortName: prop = di.ShortName; break; - #else + #else + + #if defined(__APPLE__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wsign-conversion" + #endif case kpidDeviceMajor: /* @@ -501,6 +509,10 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR 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; @@ -513,30 +525,30 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR if (di.OwnerGroupIndex >= 0) prop = DirItems->OwnerGroupMap.Strings[(unsigned)di.OwnerGroupIndex]; break; - #endif - } + #endif } + } prop.Detach(value); return S_OK; 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; @@ -544,7 +556,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea if (!up.NewData) return E_FAIL; - RINOK(Callback->CheckBreak()); + RINOK(Callback->CheckBreak()) // RINOK(Callback->Finalize()); bool isDir = IsDir(up); @@ -556,7 +568,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea 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 */ @@ -571,7 +583,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea 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; @@ -642,8 +654,9 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea #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); @@ -657,12 +670,32 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea 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; + } } /* @@ -681,7 +714,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea inStreamSpec->ReloadProps(); } - // #if defined(USE_WIN_FILE) || !defined(_WIN32) + // #if defined(Z7_FILE_STREAMS_USE_WIN_FILE) || !defined(_WIN32) if (StoreHardLinks) { CStreamFileProps props; @@ -693,8 +726,8 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea 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]; @@ -716,14 +749,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea 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, @@ -733,7 +766,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream 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 @@ -772,9 +805,9 @@ STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 in } 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)) } } } @@ -793,7 +826,7 @@ STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 in 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 @@ -827,12 +860,12 @@ STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt3 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)) } } } @@ -850,7 +883,7 @@ STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt3 /* -STDMETHODIMP CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer) +Z7_COM7F_IMF(CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer)) { *answer = 0; if (Need_ArcMTime_Report && propID == kpidComboMTime) @@ -858,7 +891,7 @@ STDMETHODIMP CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer) 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) { @@ -881,19 +914,19 @@ STDMETHODIMP CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index, 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; @@ -903,37 +936,18 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) 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]; ConvertUInt32ToString(index + 1, temp); FString res (temp); - while (res.Len() < DigitCount) + while (res.Len() < 2) res.InsertAtFront(FTEXT('0')); FString fileName = VolName; - if (VolNumberAfterExt) - { - if (!VolPrefix.IsEmpty()) - fileName += VolPrefix; - fileName += VolExt; - if (!VolPostfix.IsEmpty()) - fileName += VolPostfix; - else - fileName += '.'; - fileName += res; - } - else - { - if (!VolPrefix.IsEmpty()) - fileName += VolPrefix; - else - fileName += '.'; - fileName += res; - if (!VolPostfix.IsEmpty()) - fileName += VolPostfix; - fileName += VolExt; - } + fileName.Add_Dot(); + fileName += res; + fileName += VolExt; COutFileStream *streamSpec = new COutFileStream; CMyComPtr streamLoc(streamSpec); if (!streamSpec->Create(fileName, false)) @@ -943,14 +957,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOu 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); @@ -970,7 +984,7 @@ HRESULT CArchiveUpdateCallback::InFileStream_On_Error(UINT_PTR val, DWORD error) { if (_openFiles_Indexes[i] == index) { - RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error)); + RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error)) break; } } diff --git a/CPP/7zip/UI/Common/UpdateCallback.h b/CPP/7zip/UI/Common/UpdateCallback.h index a78a9955..379b8146 100644 --- a/CPP/7zip/UI/Common/UpdateCallback.h +++ b/CPP/7zip/UI/Common/UpdateCallback.h @@ -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 @@ struct CArcToDoStat } }; -#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 @@ struct CKeyKeyValPair }; -class CArchiveUpdateCallback: +class CArchiveUpdateCallback Z7_final: public IArchiveUpdateCallback2, public IArchiveUpdateCallbackFile, // public IArchiveUpdateCallbackArcProp, - public IArchiveExtractCallbackMessage, + public IArchiveExtractCallbackMessage2, public IArchiveGetRawProps, public IArchiveGetRootProps, public ICryptoGetTextPassword2, @@ -87,58 +88,63 @@ class CArchiveUpdateCallback: 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(;) - - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password); - STDMETHOD(CryptoGetTextPassword)(BSTR *password); + bool PreserveATime; + bool ShareForWrite; + bool StopAfterOpenError; + bool StdInMode; + + bool KeepOriginalItemNames; + bool StoreNtSecurity; + bool StoreHardLinks; + bool StoreSymLinks; + + 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 - FString VolPrefix; - FString VolPostfix; - bool VolNumberAfterExt; - UInt32 DigitCount; + 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; @@ -149,36 +155,24 @@ class CArchiveUpdateCallback: 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 @@ -189,6 +183,15 @@ class CArchiveUpdateCallback: 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 --git a/CPP/7zip/UI/Common/UpdatePair.cpp b/CPP/7zip/UI/Common/UpdatePair.cpp index e9a16444..99b0aafb 100644 --- a/CPP/7zip/UI/Common/UpdatePair.cpp +++ b/CPP/7zip/UI/Common/UpdatePair.cpp @@ -103,7 +103,7 @@ static const char * const k_Duplicate_inArc_Message = "Duplicate filename in arc 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 @@ void ThrowError(const char *message, const UString &s1, const UString &s2) 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 @@ static int CompareArcItems(const unsigned *p1, const unsigned *p2, void *param) 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 @@ void GetUpdatePairInfoList( 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 @@ void GetUpdatePairInfoList( { 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 --git a/CPP/7zip/UI/Common/UpdatePair.h b/CPP/7zip/UI/Common/UpdatePair.h index 296d3b09..13228b0e 100644 --- a/CPP/7zip/UI/Common/UpdatePair.h +++ b/CPP/7zip/UI/Common/UpdatePair.h @@ -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 --git a/CPP/7zip/UI/Common/UpdateProduce.h b/CPP/7zip/UI/Common/UpdateProduce.h index 24bb32ec..9db6c1e4 100644 --- a/CPP/7zip/UI/Common/UpdateProduce.h +++ b/CPP/7zip/UI/Common/UpdateProduce.h @@ -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 CUpdatePair2 {} }; -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 --git a/CPP/7zip/UI/Common/WorkDir.cpp b/CPP/7zip/UI/Common/WorkDir.cpp index 1307ceeb..cfec6350 100644 --- a/CPP/7zip/UI/Common/WorkDir.cpp +++ b/CPP/7zip/UI/Common/WorkDir.cpp @@ -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 @@ FString GetWorkDir(const NWorkDir::CInfo &workDirInfo, const FString &path, FStr 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 @@ FString GetWorkDir(const NWorkDir::CInfo &workDirInfo, const FString &path, FStr } #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 @@ HRESULT CWorkDirTempFile::CreateTempFile(const FString &originalPath) 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 --git a/CPP/7zip/UI/Common/WorkDir.h b/CPP/7zip/UI/Common/WorkDir.h index 75850a92..d32ab9d3 100644 --- a/CPP/7zip/UI/Common/WorkDir.h +++ b/CPP/7zip/UI/Common/WorkDir.h @@ -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 --git a/CPP/7zip/UI/Common/ZipRegistry.cpp b/CPP/7zip/UI/Common/ZipRegistry.cpp index d075fdea..fad3f06e 100644 --- a/CPP/7zip/UI/Common/ZipRegistry.cpp +++ b/CPP/7zip/UI/Common/ZipRegistry.cpp @@ -13,6 +13,7 @@ #include "../FileManager/RegistryUtils.h" +// #include "../Explorer/ContextMenuFlags.h" #include "ZipRegistry.h" using namespace NWindows; @@ -197,6 +198,7 @@ static LPCTSTR const kOptionsKeyName = TEXT("Options"); 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"); @@ -280,6 +282,7 @@ void CInfo::Save() const 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); @@ -337,6 +340,7 @@ void CInfo::Load() 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); @@ -560,7 +564,15 @@ void CContextMenuInfo::Load() 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 --git a/CPP/7zip/UI/Common/ZipRegistry.h b/CPP/7zip/UI/Common/ZipRegistry.h index b7075e67..6bc6977b 100644 --- a/CPP/7zip/UI/Common/ZipRegistry.h +++ b/CPP/7zip/UI/Common/ZipRegistry.h @@ -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 @@ namespace NCompression { UInt32 Level; UInt32 Dictionary; + // UInt32 DictionaryChain; UInt32 Order; UInt32 BlockLogSize; UInt32 NumThreads; @@ -116,6 +117,7 @@ namespace NCompression void ResetForLevelChange() { BlockLogSize = NumThreads = Level = Dictionary = Order = (UInt32)(Int32)-1; + // DictionaryChain = (UInt32)(Int32)-1; Method.Empty(); // Options.Empty(); // EncryptionMethod.Empty(); @@ -133,10 +135,6 @@ namespace NCompression UInt32 Level; bool ShowPassword; bool EncryptHeaders; - UString ArcType; - UStringVector ArcPaths; - - CObjectVector Formats; CBoolPair NtSecurity; CBoolPair AltStreams; @@ -145,6 +143,11 @@ namespace NCompression CBoolPair PreserveATime; + UString ArcType; + UStringVector ArcPaths; + + CObjectVector Formats; + void Save() const; void Load(); }; @@ -164,8 +167,8 @@ namespace NWorkDir struct CInfo { NMode::EEnum Mode; - FString Path; bool ForRemovableOnly; + FString Path; void SetForRemovableOnlyDefault() { ForRemovableOnly = true; } void SetDefault() diff --git a/CPP/7zip/UI/Console/BenchCon.cpp b/CPP/7zip/UI/Console/BenchCon.cpp index a7c9e676..113f584a 100644 --- a/CPP/7zip/UI/Console/BenchCon.cpp +++ b/CPP/7zip/UI/Console/BenchCon.cpp @@ -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 --git a/CPP/7zip/UI/Console/BenchCon.h b/CPP/7zip/UI/Console/BenchCon.h index c9da1de3..844cc2a7 100644 --- a/CPP/7zip/UI/Console/BenchCon.h +++ b/CPP/7zip/UI/Console/BenchCon.h @@ -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 --git a/CPP/7zip/UI/Console/Console.dsp b/CPP/7zip/UI/Console/Console.dsp index ea336cf7..26e8c7f0 100644 --- a/CPP/7zip/UI/Console/Console.dsp +++ b/CPP/7zip/UI/Console/Console.dsp @@ -44,7 +44,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\..\..\Common\MyCom.h # 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 @@ SOURCE=..\..\..\Common\MyVector.h # 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 @@ SOURCE=..\..\Common\MethodProps.h # 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 @@ 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 @@ -858,6 +882,10 @@ SOURCE=..\..\..\..\C\Alloc.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 diff --git a/CPP/7zip/UI/Console/Console.mak b/CPP/7zip/UI/Console/Console.mak index bd4c1da4..1a47bfa7 100644 --- a/CPP/7zip/UI/Console/Console.mak +++ b/CPP/7zip/UI/Console/Console.mak @@ -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 @@ UI_COMMON_OBJS = \ C_OBJS = $(C_OBJS) \ $O\DllSecur.obj \ + +# we need empty line after last line above diff --git a/CPP/7zip/UI/Console/Console.manifest b/CPP/7zip/UI/Console/Console.manifest index 58b68ced..c932b28c 100644 --- a/CPP/7zip/UI/Console/Console.manifest +++ b/CPP/7zip/UI/Console/Console.manifest @@ -10,4 +10,7 @@ + + +true \ No newline at end of file diff --git a/CPP/7zip/UI/Console/ConsoleClose.h b/CPP/7zip/UI/Console/ConsoleClose.h index 9c9e035c..25c5d0ca 100644 --- a/CPP/7zip/UI/Console/ConsoleClose.h +++ b/CPP/7zip/UI/Console/ConsoleClose.h @@ -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 @@ inline bool TestBreakSignal() return (g_BreakCounter != 0); } -class CCtrlHandlerSetter +class CCtrlHandlerSetter Z7_final { #ifndef _WIN32 void (*memo_sig_int)(int); @@ -29,7 +29,7 @@ class CCtrlHandlerSetter #endif public: CCtrlHandlerSetter(); - virtual ~CCtrlHandlerSetter(); + ~CCtrlHandlerSetter(); }; #endif diff --git a/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp b/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp index 7f791b00..dd7a2145 100644 --- a/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp +++ b/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp @@ -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 @@ void CExtractScanConsole::PrintStat(const CDirItemsStat &st) -#ifndef _7ZIP_ST +#ifndef Z7_ST static NSynchronization::CCriticalSection g_CriticalSection; #define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); #else @@ -235,7 +235,7 @@ static const char * const k_ErrorFlagsMessages[] = , "CRC Error" }; -STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64 size) +Z7_COM7F_IMF(CExtractCallbackConsole::SetTotal(UInt64 size)) { MT_LOCK @@ -247,7 +247,7 @@ STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64 size) return CheckBreak2(); } -STDMETHODIMP CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -281,14 +281,14 @@ static void PrintFileInfo(CStdOutStream *_so, const wchar_t *path, const FILETIM } } -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 @@ STDMETHODIMP CExtractCallbackConsole::AskOverwrite( 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 @@ STDMETHODIMP CExtractCallbackConsole::AskOverwrite( 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 @@ STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int3 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 @@ STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int3 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 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &dest) } } -STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted) +Z7_COM7F_IMF(CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted)) { MT_LOCK @@ -499,7 +499,7 @@ STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encr 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 @@ STDMETHODIMP CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 enc -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackConsole::SetPassword(const UString &password) { @@ -521,7 +521,7 @@ HRESULT CExtractCallbackConsole::SetPassword(const UString &password) return S_OK; } -STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password) +Z7_COM7F_IMF(CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password)) { COM_TRY_BEGIN MT_LOCK @@ -533,7 +533,7 @@ STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password) HRESULT CExtractCallbackConsole::BeforeOpen(const wchar_t *name, bool testMode) { - RINOK(CheckBreak2()); + RINOK(CheckBreak2()) NumTryArcs++; ThereIsError_in_Current = false; @@ -560,7 +560,7 @@ static AString GetOpenArcErrorMessage(UInt32 errorFlags) { 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 @@ HRESULT CExtractCallbackConsole::OpenResult( { if (_so) { - RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); + RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)) *_so << endl; } } @@ -753,8 +753,8 @@ HRESULT CExtractCallbackConsole::OpenResult( *_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 --git a/CPP/7zip/UI/Console/ExtractCallbackConsole.h b/CPP/7zip/UI/Console/ExtractCallbackConsole.h index 7964813d..478b293e 100644 --- a/CPP/7zip/UI/Console/ExtractCallbackConsole.h +++ b/CPP/7zip/UI/Console/ExtractCallbackConsole.h @@ -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 @@ struct CErrorPathCodes2 }; */ -class CExtractScanConsole: public IDirItemsCallback +class CExtractScanConsole Z7_final: public IDirItemsCallback { + Z7_IFACE_IMP(IDirItemsCallback) + CStdOutStream *_so; CStdOutStream *_se; CPercentPrinter _percent; @@ -54,8 +56,6 @@ class CExtractScanConsole: public IDirItemsCallback public: - virtual ~CExtractScanConsole() {} - void Init(CStdOutStream *outStream, CStdOutStream *errorStream, CStdOutStream *percentStream) { _so = outStream; @@ -67,8 +67,6 @@ class CExtractScanConsole: public IDirItemsCallback void StartScanning(); - INTERFACE_IDirItemsCallback(;) - void CloseScanning() { if (NeedPercents()) @@ -81,16 +79,36 @@ class CExtractScanConsole: public IDirItemsCallback -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 @@ class CExtractCallbackConsole: 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 --git a/CPP/7zip/UI/Console/HashCon.cpp b/CPP/7zip/UI/Console/HashCon.cpp index 5a349765..c0e69e26 100644 --- a/CPP/7zip/UI/Console/HashCon.cpp +++ b/CPP/7zip/UI/Console/HashCon.cpp @@ -99,7 +99,7 @@ HRESULT CHashCallbackConsole::SetCompleted(const UInt64 *completeValue) 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 --git a/CPP/7zip/UI/Console/HashCon.h b/CPP/7zip/UI/Console/HashCon.h index f926d4d3..ebccb6ff 100644 --- a/CPP/7zip/UI/Console/HashCon.h +++ b/CPP/7zip/UI/Console/HashCon.h @@ -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 @@ class CHashCallbackConsole: public IHashCallbackUI, public CCallbackConsoleBase 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 @@ class CHashCallbackConsole: public IHashCallbackUI, public CCallbackConsoleBase // , PrintSize(true), // , PrintNewLine(true) {} - - virtual ~CHashCallbackConsole() {} - - INTERFACE_IHashCallbackUI(;) }; void PrintHashStat(CStdOutStream &so, const CHashBundle &hb); diff --git a/CPP/7zip/UI/Console/List.cpp b/CPP/7zip/UI/Console/List.cpp index f764f07e..46819f18 100644 --- a/CPP/7zip/UI/Console/List.cpp +++ b/CPP/7zip/UI/Console/List.cpp @@ -131,6 +131,8 @@ static const char * const kPropIdToName[] = , "Group ID" , "Device Major" , "Device Minor" + , "Dev Major" + , "Dev Minor" }; static const char kEmptyAttribChar = '.'; @@ -405,13 +407,13 @@ void CFieldPrinter::Init(const CFieldInfoInit *standardFieldTable, unsigned numI 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 @@ void CFieldPrinter::AddProp(const wchar_t *name, PROPID propID, bool isRawProp) 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::AddMainProps(IInArchive *archive) 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 @@ static void PrintTime(char *dest, const CListFileTimeDef &t, bool showNS) ConvertUtcFileTimeToString2(t.FT, t.Ns100, dest, prec); } -#ifndef _SFX +#ifndef Z7_SFX static inline char GetHex(Byte value) { @@ -585,12 +587,12 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st) 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 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st) { 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 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st) 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 @@ static HRESULT GetUInt64Value(IInArchive *archive, UInt32 index, PROPID propID, 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 @@ static HRESULT GetItemMTime(IInArchive *archive, UInt32 index, CListFileTimeDef 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 @@ static void PrintPropName_and_Eq(CStdOutStream &so, PROPID propID) { 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 @@ static void PrintPropVal_MultiLine(CStdOutStream &so, const wchar_t *val) 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 void PrintPropertyPair2(CStdOutStream &so, PROPID propID, const wchar_t * 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 @@ HRESULT Print_OpenArchive_Props(CStdOutStream &so, const CCodecs *codecs, const 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 @@ HRESULT Print_OpenArchive_Props(CStdOutStream &so, const CCodecs *codecs, const 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_Props(CStdOutStream &so, const CCodecs *codecs, const 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 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( CFieldPrinter fp; if (!techMode) - fp.Init(kStandardFieldTable, ARRAY_SIZE(kStandardFieldTable)); + fp.Init(kStandardFieldTable, Z7_ARRAY_SIZE(kStandardFieldTable)); CListStat2 stat2total; @@ -1128,7 +1130,7 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( */ COpenOptions options; - #ifndef _SFX + #ifndef Z7_SFX options.props = props; #endif options.codecs = codecs; @@ -1229,7 +1231,7 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( { if (isAltStream) { - RINOK(arc.GetItem(i, item)); + RINOK(arc.GetItem(i, item)) if (!CensorNode_CheckPath(wildcardCensor, item)) continue; } @@ -1319,9 +1321,9 @@ HRESULT ListArchives( 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 @@ HRESULT ListArchives( if (isAltStream && !showAltStreams) continue; - RINOK(fp.PrintItemInfo(i, st)); + RINOK(fp.PrintItemInfo(i, st)) } UInt64 numStreams = stat2.GetNumStreams(); diff --git a/CPP/7zip/UI/Console/List.h b/CPP/7zip/UI/Console/List.h index 79d2ed48..4969c3e2 100644 --- a/CPP/7zip/UI/Console/List.h +++ b/CPP/7zip/UI/Console/List.h @@ -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 @@ HRESULT ListArchives( 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 --git a/CPP/7zip/UI/Console/Main.cpp b/CPP/7zip/UI/Console/Main.cpp index d01aa4d0..eb9e2a80 100644 --- a/CPP/7zip/UI/Console/Main.cpp +++ b/CPP/7zip/UI/Console/Main.cpp @@ -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 NFile; 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 const CCodecInfo *g_Codecs[]; 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 @@ static const char * const kHelpString = " -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 @@ static const char * const kHelpString = " -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 @@ static const char * const kUnsupportedArcTypeMessage = "Unsupported archive type #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 @@ static void ShowProgInfo(CStdOutStream *so) { 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 @@ static void PrintUInt32(CStdOutStream &so, UInt32 val, unsigned size) 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 @@ static void PrintMemUsage(const char *s, UInt64 val) *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 @@ static void PrintStat() 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 @@ static void PrintStat() #ifndef UNDER_CE if (memDefined) PrintMemUsage("Physical", m.PeakWorkingSetSize); #endif + *g_StdStream << endl; } @@ -603,7 +663,7 @@ static void PrintStat() 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 @@ static void PrintTime(const char *s, UInt64 val, UInt64 total_us, UInt64 kFreq) *g_StdStream << '%'; } -static void PrintStat(UInt64 startTime) +static void PrintStat(const UInt64 startTime) { tms t; /* clock_t res = */ times(&t); @@ -722,9 +782,23 @@ int Main2( #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 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( || 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 @@ int Main2( // 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 @@ int Main2( 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 @@ int Main2( { const CArcInfoEx &arc = codecs->Formats[i]; - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS PrintLibIndex(so, arc.LibIndex); #else so << " "; @@ -1063,10 +1141,10 @@ int Main2( } - #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 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( eo.YesToAll = options.YesToAll; eo.TestMode = options.Command.IsTestCommand(); - #ifndef _SFX + #ifndef Z7_SFX eo.Properties = options.Properties; #endif @@ -1254,7 +1332,9 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( 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 @@ int Main2( 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 --git a/CPP/7zip/UI/Console/MainAr.cpp b/CPP/7zip/UI/Console/MainAr.cpp index 0e45312c..80f84f5e 100644 --- a/CPP/7zip/UI/Console/MainAr.cpp +++ b/CPP/7zip/UI/Console/MainAr.cpp @@ -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 @@ static void PrintError(const char *message) #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 @@ int MY_CDECL main 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 @@ int MY_CDECL main } return (NExitCode::kFatalError); } - catch(NExitCode::EEnum &exitCode) + catch(NExitCode::EEnum exitCode) { FlushStreams(); if (g_ErrStream) diff --git a/CPP/7zip/UI/Console/OpenCallbackConsole.cpp b/CPP/7zip/UI/Console/OpenCallbackConsole.cpp index a074fa1f..1e7adf5d 100644 --- a/CPP/7zip/UI/Console/OpenCallbackConsole.cpp +++ b/CPP/7zip/UI/Console/OpenCallbackConsole.cpp @@ -77,17 +77,17 @@ HRESULT COpenCallbackConsole::Open_Finished() } -#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 --git a/CPP/7zip/UI/Console/OpenCallbackConsole.h b/CPP/7zip/UI/Console/OpenCallbackConsole.h index 075d3741..c5b4b45f 100644 --- a/CPP/7zip/UI/Console/OpenCallbackConsole.h +++ b/CPP/7zip/UI/Console/OpenCallbackConsole.h @@ -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 @@ class COpenCallbackConsole: public IOpenCallbackUI 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 @@ class COpenCallbackConsole: public IOpenCallbackUI } 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 @@ class COpenCallbackConsole: public IOpenCallbackUI _percent._so = percentStream; } - INTERFACE_IOpenCallbackUI(;) + Z7_IFACE_IMP(IOpenCallbackUI) - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordIsDefined; // bool PasswordWasAsked; UString Password; diff --git a/CPP/7zip/UI/Console/PercentPrinter.cpp b/CPP/7zip/UI/Console/PercentPrinter.cpp index 49d03932..9d392abe 100644 --- a/CPP/7zip/UI/Console/PercentPrinter.cpp +++ b/CPP/7zip/UI/Console/PercentPrinter.cpp @@ -79,7 +79,7 @@ void CPercentPrinter::GetPercents() while (size < kPercentsSize) { - _s += ' '; + _s.Add_Space(); size++; } @@ -125,8 +125,8 @@ void CPercentPrinter::Print() 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 @@ void CPercentPrinter::Print() 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 --git a/CPP/7zip/UI/Console/PercentPrinter.h b/CPP/7zip/UI/Console/PercentPrinter.h index 95290b37..4debb3b6 100644 --- a/CPP/7zip/UI/Console/PercentPrinter.h +++ b/CPP/7zip/UI/Console/PercentPrinter.h @@ -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 --git a/CPP/7zip/UI/Console/StdAfx.h b/CPP/7zip/UI/Console/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/UI/Console/StdAfx.h +++ b/CPP/7zip/UI/Console/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp b/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp index 1a6b820c..85496f5b 100644 --- a/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp +++ b/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp @@ -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 @@ HRESULT CUpdateCallbackConsole::OpenResult( { if (_so) { - RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); + RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)) *_so << endl; } } @@ -150,7 +150,7 @@ HRESULT CUpdateCallbackConsole::OpenResult( _se->NormalizePrint_wstr(name); *_se << endl; HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); - RINOK(res); + RINOK(res) _se->Flush(); } } @@ -333,6 +333,12 @@ HRESULT CUpdateCallbackConsole::FinishArchive(const CFinishArchiveStat &st) 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::ReportUpdateOperation(UInt32 op, const wchar_t * /* 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 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword2(Int32 *passwordIsDefined, *password = NULL; - #ifdef _NO_CRYPTO + #ifdef Z7_NO_CRYPTO *passwordIsDefined = false; return S_OK; @@ -711,7 +717,7 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword2(Int32 *passwordIsDefined, { if (AskPassword) { - RINOK(GetPassword_HRESULT(_so, Password)); + RINOK(GetPassword_HRESULT(_so, Password)) PasswordIsDefined = true; } } @@ -729,7 +735,7 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword(BSTR *password) *password = NULL; - #ifdef _NO_CRYPTO + #ifdef Z7_NO_CRYPTO return E_NOTIMPL; diff --git a/CPP/7zip/UI/Console/UpdateCallbackConsole.h b/CPP/7zip/UI/Console/UpdateCallbackConsole.h index b7ffef03..b6c1be4b 100644 --- a/CPP/7zip/UI/Console/UpdateCallbackConsole.h +++ b/CPP/7zip/UI/Console/UpdateCallbackConsole.h @@ -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 @@ struct CErrorPathCodes } }; + class CCallbackConsoleBase { protected: @@ -42,7 +43,7 @@ class CCallbackConsoleBase 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 @@ class CCallbackConsoleBase // 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 @@ class CUpdateCallbackConsole: public IUpdateCallbackUI2, public CCallbackConsole } */ // ~CUpdateCallbackConsole() { if (NeedPercents()) _percent.ClosePrint(); } - INTERFACE_IUpdateCallbackUI2(;) }; #endif diff --git a/CPP/7zip/UI/Console/UserInputUtils.cpp b/CPP/7zip/UI/Console/UserInputUtils.cpp index 93f60eb2..04d675e6 100644 --- a/CPP/7zip/UI/Console/UserInputUtils.cpp +++ b/CPP/7zip/UI/Console/UserInputUtils.cpp @@ -73,19 +73,26 @@ static bool GetPassword(CStdOutStream *outStream, UString &psw) #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 --git a/CPP/7zip/UI/Console/UserInputUtils.h b/CPP/7zip/UI/Console/UserInputUtils.h index 256feafe..695a3e66 100644 --- a/CPP/7zip/UI/Console/UserInputUtils.h +++ b/CPP/7zip/UI/Console/UserInputUtils.h @@ -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 --git a/CPP/7zip/UI/Console/makefile b/CPP/7zip/UI/Console/makefile index acc3f107..a20b0cc0 100644 --- a/CPP/7zip/UI/Console/makefile +++ b/CPP/7zip/UI/Console/makefile @@ -1,6 +1,6 @@ PROG = 7z.exe CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ COMMON_OBJS = \ $O\CommandLineParser.obj \ @@ -42,6 +42,7 @@ WIN_OBJS = \ $O\FilterCoder.obj \ $O\LimitedStreams.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\ProgressUtils.obj \ $O\PropId.obj \ $O\StreamObjects.obj \ diff --git a/CPP/7zip/UI/Console/makefile.gcc b/CPP/7zip/UI/Console/makefile.gcc index d7e44478..8a293d8a 100644 --- a/CPP/7zip/UI/Console/makefile.gcc +++ b/CPP/7zip/UI/Console/makefile.gcc @@ -20,7 +20,7 @@ endif ifdef ST_MODE -LOCAL_FLAGS_ST = -D_7ZIP_ST +LOCAL_FLAGS_ST = -DZ7_ST ifdef IS_MINGW MT_OBJS = \ @@ -43,9 +43,9 @@ LOCAL_FLAGS_WIN= 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 @@ endif LOCAL_FLAGS = \ $(LOCAL_FLAGS_WIN) \ $(LOCAL_FLAGS_ST) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ @@ -147,6 +147,7 @@ WIN_OBJS = \ $O/LimitedStreams.o \ $O/MethodId.o \ $O/MethodProps.o \ + $O/MultiOutStream.o \ $O/OffsetStream.o \ $O/OutBuffer.o \ $O/ProgressUtils.o \ diff --git a/CPP/7zip/UI/Explorer/ContextMenu.cpp b/CPP/7zip/UI/Explorer/ContextMenu.cpp index 98d4bca5..01a1193f 100644 --- a/CPP/7zip/UI/Explorer/ContextMenu.cpp +++ b/CPP/7zip/UI/Explorer/ContextMenu.cpp @@ -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 LONG g_DllRefCount; 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); + 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); +} + +#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 -void Print_Number(UInt32 number, char *s) +static void Print_Ptr(const void *p, const char *s) { - char temp[64]; - ConvertUInt64ToString(number, temp); - AString s2; - s2 += temp; - s2.Add_Space(); - s2 += s; - OutputDebugStringA(s2); + char temp[32]; + sprintf(temp, "%p", (const void *)p); + AString m; + m += temp; + m.Add_Space(); + m += s; + OutputDebugStringA(m); } -#define ODS(sz) Print_Ptr(this, sz) -#define ODS_U(s) OutputDebugStringW(s); -// #define ODS(sz) -// #define ODS_U(s) +static void Print_Number(UInt32 number, const char *s) +{ + AString m; + m.Add_UInt32(number); + m.Add_Space(); + m += s; + OutputDebugStringA(m); +} -#define ODS2(sz) Print_Ptr(this, sz) +#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,102 +172,96 @@ CZipContextMenu::CZipContextMenu(): 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 } ///////////////////////////// // IContextMenu -static LPCSTR const kMainVerb = "SevenZipZS"; -static LPCSTR const kOpenCascadedVerb = "SevenZipZS.OpenWithType."; -static LPCSTR const kCheckSumCascadedVerb = "SevenZipZS.Checksum"; +static LPCSTR const kMainVerb = "SevenZip"; +static LPCSTR const kOpenCascadedVerb = "SevenZip.OpenWithType."; +static LPCSTR const kCheckSumCascadedVerb = "SevenZip.Checksum"; struct CContextMenuCommand { UInt32 flag; - CZipContextMenu::ECommandInternalID CommandInternalID; + CZipContextMenu::enum_CommandInternalID CommandInternalID; LPCSTR Verb; UINT ResourceID; }; @@ -227,7 +286,7 @@ static const CContextMenuCommand g_Commands[] = struct CHashCommand { - CZipContextMenu::ECommandInternalID CommandInternalID; + CZipContextMenu::enum_CommandInternalID CommandInternalID; LPCSTR UserName; LPCSTR MethodName; }; @@ -247,28 +306,28 @@ static const CHashCommand g_HashCommands[] = { CZipContextMenu::kHash_SHA512, "SHA2-512", "SHA512" }, { CZipContextMenu::kHash_BLAKE2sp, "BLAKE2sp", "BLAKE2sp" }, { CZipContextMenu::kHash_BLAKE3, "BLAKE3", "BLAKE3" }, - { CZipContextMenu::kHash_SHA256, "SHA3-256", "SHA3-256" }, - { CZipContextMenu::kHash_SHA384, "SHA3-384", "SHA3-384" }, - { CZipContextMenu::kHash_SHA512, "SHA3-512", "SHA3-512" }, + { CZipContextMenu::kHash_SHA3_256, "SHA3-256", "SHA3-256" }, + { CZipContextMenu::kHash_SHA3_384, "SHA3-384", "SHA3-384" }, + { CZipContextMenu::kHash_SHA3_512, "SHA3-512", "SHA3-512" }, { CZipContextMenu::kHash_All, "*", "*" }, { CZipContextMenu::kHash_Generate_SHA256, "SHA2-256 -> file.sha256", "SHA256" }, { CZipContextMenu::kHash_TestArc, "Checksum : Test", "Hash" } }; -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]; @@ -278,7 +337,6 @@ void CZipContextMenu::FillCommand(ECommandInternalID id, UString &mainString, CC // cmi.HelpString = cmi.Verb; LangString(command.ResourceID, mainString); cmi.UserString = mainString; - // return true; } @@ -291,14 +349,39 @@ static UString LangStringAlt(UInt32 id, const char *altString) } -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; @@ -322,7 +405,7 @@ static void MyInsertMenu(CMenu &menu, int pos, UINT id, const UString &s, HBITMA 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; @@ -355,18 +438,13 @@ static const char * const kArcExts[] = "7z" , "bz2" , "gz" - , "lz" - , "liz" - , "lz4" - , "lz5" , "rar" , "zip" - , "zst" }; 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; @@ -411,8 +489,7 @@ static UString GetQuotedReducedString(const UString &s) UString s2 = s; ReduceString(s2); s2.Replace(L"&", L"&&"); - s2.InsertAtFront(L'"'); s2 += L'"'; // quote without GetQuotedString (because it escapes now) - return s2; + return GetQuotedString(s2); } static void MyFormatNew_ReducedName(UString &s, const UString &name) @@ -462,39 +539,21 @@ static const char * const kOpenTypes[] = , "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. @@ -528,28 +587,24 @@ static HRESULT RETURN_WIN32_LastError_AS_HRESULT() */ - -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); @@ -559,7 +614,6 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, if (commandIDFirst > commandIDLast) return E_INVALIDARG; - UINT currentCommandID = commandIDFirst; if ((flags & 0x000F) != CMF_NORMAL @@ -570,24 +624,33 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, // 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) { @@ -614,7 +677,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, popupMenu.InsertItem(subIndex++, true, mi); } - UInt32 contextMenuFlags = ci.Flags; + const UInt32 contextMenuFlags = ci.Flags; NFind::CFileInfo fi0; FString folderPrefix; @@ -628,7 +691,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, { // 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 "\\"; @@ -648,16 +711,42 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, } } - 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; @@ -676,7 +765,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, _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) @@ -703,29 +792,40 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, } } + 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) { @@ -775,16 +875,46 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, // 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) @@ -812,7 +942,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, // CompressTo7z if (contextMenuFlags & NContextMenuFlags::kCompressTo7z && - !arcName7z.IsEqualTo_NoCase(fs2us(fi0.Name))) + !arcName_7z.IsEqualTo_NoCase(fs2us(fi0.Name))) { CCommandMapItem cmi; UString s; @@ -820,10 +950,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, 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); } @@ -834,10 +964,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, { 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); } @@ -845,7 +975,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, // CompressToZip if (contextMenuFlags & NContextMenuFlags::kCompressToZip && - !arcNameZip.IsEqualTo_NoCase(fs2us(fi0.Name))) + !arcName_zip.IsEqualTo_NoCase(fs2us(fi0.Name))) { CCommandMapItem cmi; UString s; @@ -853,10 +983,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, 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); } @@ -867,16 +997,17 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, { 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 @@ -887,7 +1018,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, CMenu menu; menu.Attach(hMenu); menuDestroyer.Disable(); - MyAddSubMenu(_commandMap, kMainVerb, menu, indexMenu++, currentCommandID++, (UString)"7-Zip ZS", + MyAddSubMenu(_commandMap, kMainVerb, menu, indexMenu++, currentCommandID++, (UString)"7-Zip", popupMenu, // popupMenu.Detach(), bitmap); } @@ -897,6 +1028,8 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, indexMenu = subIndex; } + ODS("### 350") + const bool needCrc = ((contextMenuFlags & (NContextMenuFlags::kCRC | NContextMenuFlags::kCRC_Cascaded)) != 0); @@ -908,7 +1041,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, { CMenu subMenu; // CMenuDestroyer menuDestroyer_CRC; - + UINT subIndex_CRC = 0; if (!hMenu || subMenu.CreatePopup()) @@ -919,7 +1052,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, CMenu menu; { - int indexInParent; + unsigned indexInParent; if (insertHashMenuTo7zipMenu) { indexInParent = subIndex; @@ -931,14 +1064,16 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, menu.Attach(hMenu); // menuDestroyer_CRC.Disable(); } - MyAddSubMenu(_commandMap, kCheckSumCascadedVerb, menu, indexInParent++, currentCommandID++, (UString)"7-Zip ZS Hash", subMenu, + MyAddSubMenu(_commandMap, kCheckSumCascadedVerb, menu, indexInParent++, currentCommandID++, (UString)"CRC SHA", subMenu, /* insertHashMenuTo7zipMenu ? NULL : */ bitmap); _commandMap.Back().CtxCommandType = CtxCommandType_CrcRoot; if (!insertHashMenuTo7zipMenu) 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; @@ -946,13 +1081,13 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, 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; @@ -962,28 +1097,47 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, } 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 = "SHA2-256 -> "; - s += name; + s = "SHA-256 -> "; + 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(); @@ -991,49 +1145,45 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu, } 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; } @@ -1043,66 +1193,16 @@ static UString Get7zFmPath() } -#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); @@ -1112,16 +1212,16 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo) 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); @@ -1138,22 +1238,17 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo) 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); @@ -1163,7 +1258,7 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo) HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) { - const ECommandInternalID cmdID = cmi.CommandInternalID; + const enum_CommandInternalID cmdID = cmi.CommandInternalID; try { @@ -1185,6 +1280,11 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) 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 @@ -1204,44 +1304,53 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) 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 ); break; } - + case kHash_CRC32: case kHash_CRC64: - case kHash_XXH32: - case kHash_XXH64: - case kHash_MD2: - case kHash_MD4: - case kHash_MD5: case kHash_SHA1: case kHash_SHA256: - case kHash_SHA384: - case kHash_SHA512: - case kHash_BLAKE2sp: - case kHash_BLAKE3: - case kHash_SHA3_256: - case kHash_SHA3_384: - case kHash_SHA3_512: case kHash_All: 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) @@ -1253,7 +1362,18 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) } 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; @@ -1267,14 +1387,14 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) } catch(...) { - ::MessageBoxW(0, L"Error", L"7-Zip ZS", 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--; @@ -1283,6 +1403,7 @@ static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UI UString s = src; s.DeleteFrom(size); MyStringCopy((wchar_t *)dest, s); + ODS_U(s) } else { @@ -1293,50 +1414,48 @@ static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UI } -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 @@ -1369,7 +1488,7 @@ static HRESULT WINAPI My_SHStrDupW(LPCWSTR src, LPWSTR *dest) class CCoTaskWSTR { LPWSTR m_str; - CLASS_NO_COPY(CCoTaskWSTR) + Z7_CLASS_NO_COPY(CCoTaskWSTR) public: CCoTaskWSTR(): m_str(NULL) {} ~CCoTaskWSTR() { ::CoTaskMemFree(m_str); } @@ -1410,41 +1529,47 @@ class CCoTaskWSTR */ }; -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, @@ -1454,7 +1579,6 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray) if (FAILED(res)) return /* res */; - CZipExplorerCommand *crcHandler = NULL; CZipExplorerCommand *openHandler = NULL; @@ -1465,7 +1589,6 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray) { const CCommandMapItem &cmi = _commandMap[i]; - if (cmi.IsPopup) if (!cmi.IsSubMenu()) continue; @@ -1489,22 +1612,22 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray) 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) { @@ -1535,9 +1658,9 @@ STDMETHODIMP CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR } -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; @@ -1550,30 +1673,30 @@ STDMETHODIMP CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */, } -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 @@ -1582,16 +1705,17 @@ STDMETHODIMP CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */, -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]); @@ -1599,9 +1723,9 @@ STDMETHODIMP CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx } -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) @@ -1615,7 +1739,7 @@ STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags) // const CCommandMapItem &cmi = ; if (_commandMap_Cur[0].IsSubMenu()) { - // ODS("ECF_HASSUBCOMMANDS"); + // ODS("ECF_HASSUBCOMMANDS") f = ECF_HASSUBCOMMANDS; } } @@ -1626,9 +1750,9 @@ STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags) } -STDMETHODIMP CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) +Z7_COMWF_B CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) { - ODS("- EnumSubCommands()"); + ODS("- EnumSubCommands()") // COM_TRY_BEGIN *ppEnum = NULL; @@ -1653,12 +1777,12 @@ STDMETHODIMP CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) } -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; @@ -1679,7 +1803,7 @@ STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, UL 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; @@ -1687,25 +1811,24 @@ STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, UL } -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 --git a/CPP/7zip/UI/Explorer/ContextMenu.h b/CPP/7zip/UI/Explorer/ContextMenu.h index b45fcedf..6f24c06a 100644 --- a/CPP/7zip/UI/Explorer/ContextMenu.h +++ b/CPP/7zip/UI/Explorer/ContextMenu.h @@ -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, @@ -66,48 +105,22 @@ class CZipContextMenu: 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; @@ -115,7 +128,7 @@ class CZipContextMenu: UString ArcName; UString ArcType; bool IsPopup; - ECtxCommandType CtxCommandType; + enum_CtxCommandType CtxCommandType; CCommandMapItem(): IsPopup(false), @@ -130,33 +143,34 @@ class CZipContextMenu: } }; -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 --git a/CPP/7zip/UI/Explorer/ContextMenuFlags.h b/CPP/7zip/UI/Explorer/ContextMenuFlags.h index 42b25f3a..50c177e9 100644 --- a/CPP/7zip/UI/Explorer/ContextMenuFlags.h +++ b/CPP/7zip/UI/Explorer/ContextMenuFlags.h @@ -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 --git a/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp b/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp index 471c8ba4..66c1b49d 100644 --- a/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp +++ b/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp @@ -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 @@ static LPCTSTR const k_Approved = TEXT("Software\\Microsoft\\Windows\\CurrentVer // {23170F69-40C1-278A-1000-000100020000} static LPCTSTR const k_Clsid = TEXT("{23170F69-20BB-278A-1000-000100020000}"); -DEFINE_GUID(CLSID_CZipContextMenu, +Z7_DEFINE_GUID(CLSID_CZipContextMenu, k_7zip_GUID_Data1, k_7zip_GUID_Data2_ZS, k_7zip_GUID_Data3_Common, @@ -42,11 +56,11 @@ using namespace NWindows; 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 @@ LONG g_DllRefCount = 0; // Reference count of this DLL. // #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 @@ STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, 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 @@ STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) 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 @@ static BOOL RegisterServer() STDAPI DllRegisterServer(void) { - return RegisterServer() ? S_OK: SELFREG_E_CLASS; + return RegisterServer() ? S_OK: SELFREG_E_CLASS; } static BOOL UnregisterServer() diff --git a/CPP/7zip/UI/Explorer/Explorer.dsp b/CPP/7zip/UI/Explorer/Explorer.dsp index e3909176..ff8503ba 100644 --- a/CPP/7zip/UI/Explorer/Explorer.dsp +++ b/CPP/7zip/UI/Explorer/Explorer.dsp @@ -45,7 +45,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\FileManager\LangUtils.h # 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 @@ SOURCE=..\FileManager\RegistryUtils.h # 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 @@ SOURCE=..\..\..\..\C\CpuArch.h # 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 @@ SOURCE=..\..\..\..\C\Threads.h # 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 @@ SOURCE=..\..\..\Common\MyVector.h # 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 @@ SOURCE=..\..\..\Windows\Control\PropertyPage.h # 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=".\7-zip.dll.manifest" SOURCE=.\ContextMenuFlags.h # End Source File +# Begin Source File + +SOURCE=..\FileManager\FM.ico +# End Source File # End Target # End Project diff --git a/CPP/7zip/UI/Explorer/MyExplorerCommand.h b/CPP/7zip/UI/Explorer/MyExplorerCommand.h index 227b9e02..11ac247b 100644 --- a/CPP/7zip/UI/Explorer/MyExplorerCommand.h +++ b/CPP/7zip/UI/Explorer/MyExplorerCommand.h @@ -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 --git a/CPP/7zip/UI/Explorer/MyMessages.cpp b/CPP/7zip/UI/Explorer/MyMessages.cpp index 5edabb68..517d0211 100644 --- a/CPP/7zip/UI/Explorer/MyMessages.cpp +++ b/CPP/7zip/UI/Explorer/MyMessages.cpp @@ -18,12 +18,15 @@ void ShowErrorMessage(HWND window, LPCWSTR message) 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 --git a/CPP/7zip/UI/Explorer/MyMessages.h b/CPP/7zip/UI/Explorer/MyMessages.h index d5822f45..47d10db7 100644 --- a/CPP/7zip/UI/Explorer/MyMessages.h +++ b/CPP/7zip/UI/Explorer/MyMessages.h @@ -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 --git a/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp b/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp index e1d6189a..7d048130 100644 --- a/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp +++ b/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp @@ -67,8 +67,9 @@ static Func_RegDeleteKeyExW func_RegDeleteKeyExW; 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 @@ LONG SetContextMenuHandler(bool setMode, const UString &path, UInt32 wow) 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 --git a/CPP/7zip/UI/Explorer/RegistryContextMenu.h b/CPP/7zip/UI/Explorer/RegistryContextMenu.h index 8c2acc42..bf3bb5b7 100644 --- a/CPP/7zip/UI/Explorer/RegistryContextMenu.h +++ b/CPP/7zip/UI/Explorer/RegistryContextMenu.h @@ -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 --git a/CPP/7zip/UI/Explorer/StdAfx.h b/CPP/7zip/UI/Explorer/StdAfx.h index 5e4dc640..130db8aa 100644 --- a/CPP/7zip/UI/Explorer/StdAfx.h +++ b/CPP/7zip/UI/Explorer/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Explorer/makefile b/CPP/7zip/UI/Explorer/makefile index cab645e5..b9c9abe1 100644 --- a/CPP/7zip/UI/Explorer/makefile +++ b/CPP/7zip/UI/Explorer/makefile @@ -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 = \ @@ -71,6 +71,7 @@ FM_OBJS = \ C_OBJS = \ $O\CpuArch.obj \ + $O\Sort.obj \ $O\Threads.obj \ !include "../../7zip.mak" diff --git a/CPP/7zip/UI/Explorer/resource.h b/CPP/7zip/UI/Explorer/resource.h index 8bb82108..bbb28b16 100644 --- a/CPP/7zip/UI/Explorer/resource.h +++ b/CPP/7zip/UI/Explorer/resource.h @@ -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 --git a/CPP/7zip/UI/Explorer/resource2.rc b/CPP/7zip/UI/Explorer/resource2.rc index c07148fd..de34824b 100644 --- a/CPP/7zip/UI/Explorer/resource2.rc +++ b/CPP/7zip/UI/Explorer/resource2.rc @@ -13,6 +13,7 @@ BEGIN 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 --git a/CPP/7zip/UI/Far/ExtractEngine.cpp b/CPP/7zip/UI/Far/ExtractEngine.cpp index ab5c0def..05e92081 100644 --- a/CPP/7zip/UI/Far/ExtractEngine.cpp +++ b/CPP/7zip/UI/Far/ExtractEngine.cpp @@ -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 @@ static HRESULT CheckBreak2() extern void PrintMessage(const char *message); -CExtractCallbackImp::~CExtractCallbackImp() -{ -} - void CExtractCallbackImp::Init( UINT codePage, CProgressBox *progressBox, @@ -47,7 +43,7 @@ void CExtractCallbackImp::Init( _percent = progressBox; } -STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 size)) { MT_LOCK @@ -59,7 +55,7 @@ STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) return CheckBreak2(); } -STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -72,15 +68,15 @@ STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) 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 @@ STDMETHODIMP CExtractCallbackImp::AskOverwrite( 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 @@ STDMETHODIMP CExtractCallbackImp::AskOverwrite( 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 kExtractString = "Extracting"; 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 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* 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 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* return CheckBreak2(); } -STDMETHODIMP CExtractCallbackImp::MessageError(const wchar_t *message) +Z7_COM7F_IMF(CExtractCallbackImp::MessageError(const wchar_t *message)) { MT_LOCK @@ -199,7 +195,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s) } 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 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s) 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::SetOperationResult(Int32 opRes, Int32 encrypte } -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 @@ STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypt 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 --git a/CPP/7zip/UI/Far/ExtractEngine.h b/CPP/7zip/UI/Far/ExtractEngine.h index 5861d92c..2bee2ee4 100644 --- a/CPP/7zip/UI/Far/ExtractEngine.h +++ b/CPP/7zip/UI/Far/ExtractEngine.h @@ -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 @@ class CExtractCallbackImp: */ void AddErrorMessage(LPCTSTR message); public: - // CExtractCallbackImp() {} - ~CExtractCallbackImp(); void Init(UINT codePage, CProgressBox *progressBox, bool passwordIsDefined, const UString &password); diff --git a/CPP/7zip/UI/Far/Far.cpp b/CPP/7zip/UI/Far/Far.cpp index a9e47916..74d5e60f 100644 --- a/CPP/7zip/UI/Far/Far.cpp +++ b/CPP/7zip/UI/Far/Far.cpp @@ -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 LPCTSTR const kRegisrtryValueNameEnabled = TEXT("UsedByDefault3"); 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 @@ const char *g_PluginName_for_Error = "7-Zip"; BOOL WINAPI DllMain( #ifdef UNDER_CE - HANDLE + HANDLE + #else + HINSTANCE + #endif + hInstance, DWORD dwReason, LPVOID); +BOOL WINAPI DllMain( + #ifdef UNDER_CE + HANDLE #else - HINSTANCE + HINSTANCE #endif hInstance, DWORD dwReason, LPVOID) { @@ -89,7 +95,7 @@ EXTERN_C void WINAPI ExitFAR() 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 @@ EXTERN_C void WINAPI SetStartupInfo(const PluginStartupInfo *info) // 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 @@ class COpenArchiveCallback: 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 @@ class COpenArchiveCallback: 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 @@ void COpenArchiveCallback::ShowMessage() _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 @@ STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 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::SetCompleted(const UInt64 *numFiles, const UI } -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 @@ HRESULT GetPassword(UString &password) { 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 @@ HRESULT GetPassword(UString &password) 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 @@ static HANDLE MyOpenFilePluginW(const wchar_t *name, bool isAbortCodeSupported) } 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 @@ static HANDLE MyOpenFilePluginW(const wchar_t *name, bool isAbortCodeSupported) 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 @@ static HANDLE MyOpenFilePlugin(const char *name, bool isAbortCodeSupported) 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 @@ EXTERN_C HANDLE WINAPI OpenFilePlugin(char *name, const unsigned char * /* data 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 OpenFilePluginW(const wchar_t *name,const unsigned char * EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item) { - MY_TRY_BEGIN; + MY_TRY_BEGIN if (openFrom == OPEN_COMMANDLINE) { @@ -511,13 +432,13 @@ EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item) } 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 void WINAPI ClosePlugin(HANDLE plugin) 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 void WINAPI FreeFindData(HANDLE plugin, struct PluginPanelItem *panelIt 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 @@ EXTERN_C int WINAPI Configure(int /* itemNumber */) { 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 @@ EXTERN_C int WINAPI Configure(int /* itemNumber */) 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 --git a/CPP/7zip/UI/Far/Far.dsp b/CPP/7zip/UI/Far/Far.dsp index bd6d8fd4..823c728d 100644 --- a/CPP/7zip/UI/Far/Far.dsp +++ b/CPP/7zip/UI/Far/Far.dsp @@ -43,7 +43,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=.\StdAfx.h # 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 @@ SOURCE=..\..\..\Common\IntToString.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 @@ -142,6 +150,10 @@ SOURCE=..\..\..\Common\MyString.h # 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 @@ SOURCE=..\..\..\Common\MyVector.h # 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 @@ SOURCE=..\..\..\Windows\FileName.h # 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 @@ SOURCE=..\..\..\Windows\Synchronization.h # 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 @@ SOURCE=..\Agent\ArchiveFolder.cpp # 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 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c # 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 @@ SOURCE=..\..\..\..\C\Alloc.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 diff --git a/CPP/7zip/UI/Far/FarPlugin.h b/CPP/7zip/UI/Far/FarPlugin.h index 859d319f..ad3ed38b 100644 --- a/CPP/7zip/UI/Far/FarPlugin.h +++ b/CPP/7zip/UI/Far/FarPlugin.h @@ -16,8 +16,8 @@ typedef struct _CHAR_INFO { } 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_BEGIN 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 --git a/CPP/7zip/UI/Far/FarUtils.cpp b/CPP/7zip/UI/Far/FarUtils.cpp index 3bdb9895..9fddbc13 100644 --- a/CPP/7zip/UI/Far/FarUtils.cpp +++ b/CPP/7zip/UI/Far/FarUtils.cpp @@ -36,10 +36,10 @@ const char *CStartupInfo::GetMsgString(int messageId) } 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 @@ namespace NMessageID }; } -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 @@ int CStartupInfo::ShowErrorMessage(const char *message) 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 @@ int CStartupInfo::ShowErrorMessage2(const char *m1, const char *m2) 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::ShowMessage(int messageId) } 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 @@ int CStartupInfo::ShowDialog(int sizeX, int sizeY, 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 @@ bool CStartupInfo::ControlClearPanelSelection() 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 CStartupInfo::Menu( 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 @@ int CStartupInfo::Menu( 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 @@ int CStartupInfo::Menu( 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 @@ void CScreenRestorer::Restore() g_StartupInfo.RestoreScreen(m_HANDLE); m_Saved = false; } -}; +} int PrintErrorMessage(const char *message, unsigned code) { @@ -471,7 +474,7 @@ int PrintErrorMessage(const char *message, const wchar_t *name, unsigned maxLen) int ShowSysErrorMessage(DWORD errorCode) { - UString message = NError::MyFormatMessage(errorCode); + const UString message = NError::MyFormatMessage(errorCode); return g_StartupInfo.ShowErrorMessage(UnicodeStringToMultiByte(message, CP_OEMCP)); } diff --git a/CPP/7zip/UI/Far/FarUtils.h b/CPP/7zip/UI/Far/FarUtils.h index 38f64f98..6e6ff3c7 100644 --- a/CPP/7zip/UI/Far/FarUtils.h +++ b/CPP/7zip/UI/Far/FarUtils.h @@ -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 @@ class CStartupInfo 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 @@ class CStartupInfo 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 @@ class CStartupInfo 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 @@ class CStartupInfo 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 @@ class CScreenRestorer bool m_Saved; HANDLE m_HANDLE; public: - CScreenRestorer(): m_Saved(false){}; + CScreenRestorer(): m_Saved(false) {} ~CScreenRestorer(); void Save(); void Restore(); @@ -184,10 +184,16 @@ int PrintErrorMessage(const char *message, const wchar_t *name, unsigned maxLen 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 --git a/CPP/7zip/UI/Far/Messages.h b/CPP/7zip/UI/Far/Messages.h index 4e5ed8d5..f6b20a3d 100644 --- a/CPP/7zip/UI/Far/Messages.h +++ b/CPP/7zip/UI/Far/Messages.h @@ -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 --git a/CPP/7zip/UI/Far/OverwriteDialogFar.cpp b/CPP/7zip/UI/Far/OverwriteDialogFar.cpp index b8fc565f..a45d2b2a 100644 --- a/CPP/7zip/UI/Far/OverwriteDialogFar.cpp +++ b/CPP/7zip/UI/Far/OverwriteDialogFar.cpp @@ -35,7 +35,7 @@ static void SetFileInfoStrings(const CFileInfo &fileInfo, { 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 @@ static void SetFileInfoStrings(const CFileInfo &fileInfo, 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 @@ NResult::EEnum Execute(const CFileInfo &oldFileInfo, const CFileInfo &newFileInf 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 @@ NResult::EEnum Execute(const CFileInfo &oldFileInfo, const CFileInfo &newFileInf { 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 --git a/CPP/7zip/UI/Far/OverwriteDialogFar.h b/CPP/7zip/UI/Far/OverwriteDialogFar.h index 34947436..bc6e92bc 100644 --- a/CPP/7zip/UI/Far/OverwriteDialogFar.h +++ b/CPP/7zip/UI/Far/OverwriteDialogFar.h @@ -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 --git a/CPP/7zip/UI/Far/Plugin.cpp b/CPP/7zip/UI/Far/Plugin.cpp index 8dc1375a..fe6fcce4 100644 --- a/CPP/7zip/UI/Far/Plugin.cpp +++ b/CPP/7zip/UI/Far/Plugin.cpp @@ -20,13 +20,13 @@ using namespace NFile; 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 @@ static void CopyStrLimited(char *dest, const AString &src, unsigned len) 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 @@ int CPlugin::GetFindData(PluginPanelItem **panelItems, int *itemsNumber, int opM 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 @@ int CPlugin::GetFindData(PluginPanelItem **panelItems, int *itemsNumber, int opM delete [](*panelItems); throw; } - *itemsNumber = numItems; + *itemsNumber = (int)numItems; return(TRUE); } @@ -291,7 +291,7 @@ static int FindPropNameID(PROPID propID) { if (propID > NMessageID::k_Last_PropId_supported_by_plugin) return -1; - return NMessageID::kNoProperty + propID; + return NMessageID::kNoProperty + (int)propID; } /* @@ -324,7 +324,7 @@ static CPropertyIDInfo kPropertyIDInfos[] = // { 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 @@ static AString ConvertSizeToString(UInt64 value) 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 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info) 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 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info) 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 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info) //m_InfoLines[1].Separator = 0; info->InfoLines = m_InfoLines; - info->InfoLinesNumber = numItems; + info->InfoLinesNumber = (int)numItems; info->DescrFiles = NULL; @@ -654,19 +654,19 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info) 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; - - info->PanelModesArray = &_PanelMode; + _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->PanelModesNumber = 1; */ @@ -704,18 +704,18 @@ HRESULT CPlugin::ShowAttributesWindow() 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 @@ HRESULT CPlugin::ShowAttributesWindow() { const CArchiveItemProperty &property = properties[i]; - int startY = kStartY + values.Size(); + const int startY = kStartY + (int)values.Size(); { CInitDialogItem idi = @@ -755,7 +755,7 @@ HRESULT CPlugin::ShowAttributesWindow() } 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 @@ HRESULT CPlugin::ShowAttributesWindow() } } - int startY = kStartY + values.Size(); + const int startY = kStartY + (int)values.Size(); { CInitDialogItem idi = @@ -856,14 +856,14 @@ HRESULT CPlugin::ShowAttributesWindow() } } - 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 @@ HRESULT CPlugin::ShowAttributesWindow() 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 @@ int CPlugin::ProcessKey(int key, unsigned int controlState) 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 --git a/CPP/7zip/UI/Far/Plugin.h b/CPP/7zip/UI/Far/Plugin.h index 1fe190e4..00ccc81f 100644 --- a/CPP/7zip/UI/Far/Plugin.h +++ b/CPP/7zip/UI/Far/Plugin.h @@ -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 @@ class CPlugin AString PanelModeColumnTypes; AString PanelModeColumnWidths; - // PanelMode _PanelMode; + // PanelMode _panelMode; void AddColumn(PROPID aPropID); void EnterToDirectory(const UString &dirName); @@ -62,7 +62,7 @@ class CPlugin 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 @@ class CPlugin 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 --git a/CPP/7zip/UI/Far/PluginDelete.cpp b/CPP/7zip/UI/Far/PluginDelete.cpp index 939a3558..fdade1a3 100644 --- a/CPP/7zip/UI/Far/PluginDelete.cpp +++ b/CPP/7zip/UI/Far/PluginDelete.cpp @@ -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 @@ int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode) // 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 @@ int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode) */ CObjArray indices(numItems); - int i; + unsigned i; for (i = 0; i < numItems; i++) indices[i] = (UInt32)panelItems[i].UserData; diff --git a/CPP/7zip/UI/Far/PluginRead.cpp b/CPP/7zip/UI/Far/PluginRead.cpp index 70e7e141..7e81dddb 100644 --- a/CPP/7zip/UI/Far/PluginRead.cpp +++ b/CPP/7zip/UI/Far/PluginRead.cpp @@ -86,14 +86,14 @@ HRESULT CPlugin::ExtractFiles( } 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 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa 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 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa { 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 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa 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 --git a/CPP/7zip/UI/Far/PluginWrite.cpp b/CPP/7zip/UI/Far/PluginWrite.cpp index 8a76bb4e..3f1fba88 100644 --- a/CPP/7zip/UI/Far/PluginWrite.cpp +++ b/CPP/7zip/UI/Far/PluginWrite.cpp @@ -49,7 +49,7 @@ static HRESULT SetOutProperties(IOutFolderArchive *outArchive, UInt32 method) */ 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 @@ HRESULT CPlugin::AfterUpdate(CWorkDirTempFile &tempFile, const UStringVector &pa */ 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 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles( 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 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles( { 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 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles( compressionInfo.Save(); - CWorkDirTempFile tempFile;; + CWorkDirTempFile tempFile; if (tempFile.CreateTempFile(m_FileName) != S_OK) return NFileOperationReturnCode::kError; @@ -337,7 +337,7 @@ void CParsedPath::ParsePath(const UString &path) // 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 @@ static void SetArcName(UString &arcName, const CArcInfoEx &arcInfo) if (dotPos > slashPos + 1) arcName.DeleteFrom(dotPos); } - arcName += '.'; + arcName.Add_Dot(); arcName += arcInfo.GetMainExt(); } @@ -420,9 +420,9 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) { 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) if (askCode == kSelectarchiverButtonIndex) { - CIntVector indices; + CUIntVector indices; AStringVector archiverNames; FOR_VECTOR (k, codecs->Formats) { @@ -561,7 +561,7 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) } } - 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) } } - archiverIndex = indices[index]; + archiverIndex = (int)indices[index]; const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex]; prevFormat = archiverIndex; @@ -612,8 +612,7 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) return E_FAIL; CWorkDirTempFile tempFile; - RINOK(tempFile.CreateTempFile(fullArcName)); - + RINOK(tempFile.CreateTempFile(fullArcName)) CScreenRestorer screenRestorer; CProgressBox progressBox; CProgressBox *progressBoxPointer = NULL; @@ -640,15 +639,15 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) 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 @@ HRESULT CompressFiles(const CObjectVector &pluginPanelItems) updateCallbackSpec->Init(/* archiveHandler, */ progressBoxPointer); - RINOK(SetOutProperties(outArchive, compressionInfo.Level)); + RINOK(SetOutProperties(outArchive, compressionInfo.Level)) // FStringVector requestedPaths; // FStringVector processedPaths; @@ -754,7 +753,7 @@ HRESULT CPlugin::CreateFolder() { 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 --git a/CPP/7zip/UI/Far/ProgressBox.cpp b/CPP/7zip/UI/Far/ProgressBox.cpp index 6efb132a..ab25a104 100644 --- a/CPP/7zip/UI/Far/ProgressBox.cpp +++ b/CPP/7zip/UI/Far/ProgressBox.cpp @@ -67,9 +67,9 @@ static UInt64 MyMultAndDiv(UInt64 mult1, UInt64 mult2, UInt64 divider) 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 @@ static void GetTimeString(UInt64 timeValue, char *s) } 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 @@ void CProgressBox::Print() 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 @@ void CProgressBox::Print() { 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 --git a/CPP/7zip/UI/Far/ProgressBox.h b/CPP/7zip/UI/Far/ProgressBox.h index 54bdb4f1..6e8b487a 100644 --- a/CPP/7zip/UI/Far/ProgressBox.h +++ b/CPP/7zip/UI/Far/ProgressBox.h @@ -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 --git a/CPP/7zip/UI/Far/StdAfx.h b/CPP/7zip/UI/Far/StdAfx.h index 2854ff3e..035267cc 100644 --- a/CPP/7zip/UI/Far/StdAfx.h +++ b/CPP/7zip/UI/Far/StdAfx.h @@ -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 --git a/CPP/7zip/UI/Far/UpdateCallbackFar.cpp b/CPP/7zip/UI/Far/UpdateCallbackFar.cpp index 3f0f206b..94f0a47c 100644 --- a/CPP/7zip/UI/Far/UpdateCallbackFar.cpp +++ b/CPP/7zip/UI/Far/UpdateCallbackFar.cpp @@ -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 @@ static HRESULT CheckBreak2() } -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 @@ STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFi 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::SetNumFiles(UInt64 numFiles) } -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::SetCompleted(const UInt64 * /* files */, con -STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(UInt64 size)) { MT_LOCK @@ -88,7 +88,7 @@ STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue) +Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue)) { MT_LOCK @@ -101,7 +101,7 @@ STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue) return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) +Z7_COM7F_IMF(CUpdateCallback100Imp::CompressOperation(const wchar_t *name)) { MT_LOCK @@ -111,10 +111,10 @@ STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) _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 @@ STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name) _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 @@ STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* opRes */) return CheckBreak2(); } -STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) +Z7_COM7F_IMF(CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message)) { MT_LOCK @@ -147,14 +147,14 @@ STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) 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 @@ STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESUL 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::ReportExtractResult(Int32 opRes, Int32 isEnc } -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 @@ STDMETHODIMP CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar _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 --git a/CPP/7zip/UI/Far/UpdateCallbackFar.h b/CPP/7zip/UI/Far/UpdateCallbackFar.h index d2c2c8ed..4ec5eed2 100644 --- a/CPP/7zip/UI/Far/UpdateCallbackFar.h +++ b/CPP/7zip/UI/Far/UpdateCallbackFar.h @@ -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 --git a/CPP/7zip/UI/Far/makefile b/CPP/7zip/UI/Far/makefile index 0db22749..f3809a88 100644 --- a/CPP/7zip/UI/Far/makefile +++ b/CPP/7zip/UI/Far/makefile @@ -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 @@ WIN_OBJS = \ $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 @@ AGENT_OBJS = \ $O\AgentOut.obj \ $O\AgentProxy.obj \ $O\ArchiveFolder.obj \ - $O\ArchiveFolderOpen.obj \ $O\ArchiveFolderOut.obj \ $O\UpdateCallbackAgent.obj \ diff --git a/CPP/7zip/UI/FileManager/7zFM.exe.manifest b/CPP/7zip/UI/FileManager/7zFM.exe.manifest index 64728882..a3abd6d0 100644 --- a/CPP/7zip/UI/FileManager/7zFM.exe.manifest +++ b/CPP/7zip/UI/FileManager/7zFM.exe.manifest @@ -17,4 +17,7 @@ true + + +true diff --git a/CPP/7zip/UI/FileManager/AboutDialog.cpp b/CPP/7zip/UI/FileManager/AboutDialog.cpp index fe0a4997..6a2896b0 100644 --- a/CPP/7zip/UI/FileManager/AboutDialog.cpp +++ b/CPP/7zip/UI/FileManager/AboutDialog.cpp @@ -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 kHomePageURL2 TEXT("https://github.com/mcmilk/7-Zip-zstd/") @@ -30,7 +32,7 @@ extern CCodecs *g_CodecsObj; bool CAboutDialog::OnInit() { - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS if (g_CodecsObj) { UString s; @@ -40,11 +42,13 @@ bool CAboutDialog::OnInit() } #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(); } @@ -54,7 +58,7 @@ void CAboutDialog::OnHelp() ShowHelpWindow(kHelpTopic); } -bool CAboutDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CAboutDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { LPCTSTR url; switch (buttonID) diff --git a/CPP/7zip/UI/FileManager/AboutDialog.h b/CPP/7zip/UI/FileManager/AboutDialog.h index 39fd3ba7..1d11d749 100644 --- a/CPP/7zip/UI/FileManager/AboutDialog.h +++ b/CPP/7zip/UI/FileManager/AboutDialog.h @@ -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 --git a/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp b/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp index e1c99d3c..b3d354da 100644 --- a/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp +++ b/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp @@ -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 @@ static unsigned GetFsParentPrefixSize(const FString &path) { 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 @@ static unsigned GetFsParentPrefixSize(const FString &path) } 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 @@ HRESULT CAltStreamsFolder::Init(const FString &path /* , IFolderFolder *parentFo return S_OK; } -STDMETHODIMP CAltStreamsFolder::LoadItems() +Z7_COM7F_IMF(CAltStreamsFolder::LoadItems()) { Int32 dummy; WasChanged(&dummy); @@ -152,7 +174,7 @@ STDMETHODIMP CAltStreamsFolder::LoadItems() 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 @@ STDMETHODIMP CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems) #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 @@ STDMETHODIMP CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name, 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 @@ STDMETHODIMP_(UInt64) CAltStreamsFolder::GetItemSize(UInt32 index) #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 @@ STDMETHODIMP CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVAR 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 @@ STDMETHODIMP_(Int32) CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index 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 @@ STDMETHODIMP CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *va COM_TRY_END } -STDMETHODIMP CAltStreamsFolder::WasChanged(Int32 *wasChanged) +Z7_COM7F_IMF(CAltStreamsFolder::WasChanged(Int32 *wasChanged)) { bool wasChangedMain = false; for (;;) @@ -385,7 +401,7 @@ STDMETHODIMP CAltStreamsFolder::WasChanged(Int32 *wasChanged) 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 @@ static HRESULT SendMessageError(IFolderArchiveUpdateCallback *callback, } */ -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 @@ static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR ou { 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 @@ static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR ou 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 @@ STDMETHODIMP CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IPr 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 @@ STDMETHODIMP CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconInde *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 @@ static HRESULT CopyStream( 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 @@ static HRESULT CopyStream( &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 @@ static HRESULT CopyStream( 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 @@ static HRESULT CopyStream( 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 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI { 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 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI 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 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI CFileInfo fi; if (!fi.Find(_pathBaseFile)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); NFsFolder::CCopyStateIO state; state.Progress = callback; @@ -736,21 +849,21 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI 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 @@ STDMETHODIMP CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * / 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 --git a/CPP/7zip/UI/FileManager/AltStreamsFolder.h b/CPP/7zip/UI/FileManager/AltStreamsFolder.h index ccd0a58f..ccb6d6f4 100644 --- a/CPP/7zip/UI/FileManager/AltStreamsFolder.h +++ b/CPP/7zip/UI/FileManager/AltStreamsFolder.h @@ -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 @@ struct CAltStream }; -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 @@ class CAltStreamsFolder: 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 @@ class CAltStreamsFolder: // 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 --git a/CPP/7zip/UI/FileManager/App.cpp b/CPP/7zip/UI/FileManager/App.cpp index 512acc53..3461c922 100644 --- a/CPP/7zip/UI/FileManager/App.cpp +++ b/CPP/7zip/UI/FileManager/App.cpp @@ -49,7 +49,7 @@ void CPanelCallbackImp::OnTab() 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::DragBegin() { _app->DragBegin(_index); } 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 @@ void CApp::SetListSettings() 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 @@ void CApp::SetListSettings() #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 @@ HRESULT CApp::CreateOnePanel(int panelIndex, const UString &mainPath, const UStr 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 bool SetButtonText(int commandID, const CButtonInfo *buttons, unsigned nu 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 @@ static void AddButton( 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 @@ void CApp::ReloadToolbars() 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 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma _commandBar.Create(g_hInstance, hwnd, 1); #endif - MyLoadMenu(); + MyLoadMenu(false); // needResetMenu #ifdef UNDER_CE _commandBar.AutoSize(); @@ -317,7 +317,7 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma 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 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma RINOK(CreateOnePanel(panelIndex, path, arcFormat, isMainPanel && needOpenArc, - *(isMainPanel ? &openRes : &openRes2))); + *(isMainPanel ? &openRes : &openRes2))) if (isMainPanel) { @@ -366,7 +366,7 @@ HRESULT CApp::SwitchOnOffOnePanel() 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 @@ void AddValuePair2(UString &s, UINT resourceID, UInt64 num, UInt64 size) 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 @@ UString CPanel::GetItemsInfoString(const CRecordVector &indices) 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 @@ UString CPanel::GetItemsInfoString(const CRecordVector &indices) { 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 @@ static bool IsFsPath(const FString &path) } */ -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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) { 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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) } else { - srcPanel.GetOperatedIndicesSmart(indices); + srcPanel.Get_ItemIndices_OperSmart(indices); if (indices.Size() == 0) return; destPath = destPanel.GetFsPath(); @@ -607,7 +607,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) 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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) 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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) 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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) 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 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) srcPanel.SetFocusToList(); } -void CApp::OnSetSameFolder(int srcPanelIndex) +void CApp::OnSetSameFolder(unsigned srcPanelIndex) { if (NumPanels <= 1) return; @@ -858,17 +858,17 @@ void CApp::OnSetSameFolder(int srcPanelIndex) 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 @@ void CApp::OnNotify(int /* ctrlID */, LPNMHDR pnmh) 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 @@ void CApp::OnNotify(int /* ctrlID */, LPNMHDR pnmh) 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 --git a/CPP/7zip/UI/FileManager/App.h b/CPP/7zip/UI/FileManager/App.h index 3c3c5ef2..fc54501c 100644 --- a/CPP/7zip/UI/FileManager/App.h +++ b/CPP/7zip/UI/FileManager/App.h @@ -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 @@ enum kMenuCmdID_Toolbar_End }; -class CPanelCallbackImp: public CPanelCallback +class CPanelCallbackImp Z7_final: public CPanelCallback { CApp *_app; unsigned _index; @@ -40,79 +40,26 @@ class CPanelCallbackImp: public CPanelCallback _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 @@ class CApp 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 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 CreateDragTarget(); + void SetFocusedPanel(unsigned index); + void DragBegin(unsigned panelIndex); + void DragEnd(); - void OnCopy(bool move, bool copyToSame, int srcPanelIndex); - void OnSetSameFolder(int srcPanelIndex); - void OnSetSubFolder(int srcPanelIndex); + void OnCopy(bool move, bool copyToSame, unsigned srcPanelIndex); + void OnSetSameFolder(unsigned srcPanelIndex); + void OnSetSubFolder(unsigned 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 @@ class CApp // 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 @@ class CApp 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 --git a/CPP/7zip/UI/FileManager/AppState.h b/CPP/7zip/UI/FileManager/AppState.h index cc887150..6630b962 100644 --- a/CPP/7zip/UI/FileManager/AppState.h +++ b/CPP/7zip/UI/FileManager/AppState.h @@ -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 --git a/CPP/7zip/UI/FileManager/BrowseDialog.cpp b/CPP/7zip/UI/FileManager/BrowseDialog.cpp index 6d2b6b55..5170302c 100644 --- a/CPP/7zip/UI/FileManager/BrowseDialog.cpp +++ b/CPP/7zip/UI/FileManager/BrowseDialog.cpp @@ -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 NFile; 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 @@ extern bool g_LVN_ITEMACTIVATE_Support; 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 @@ class CBrowseDialog: public NControl::CModalDialog 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 @@ class CBrowseDialog: public NControl::CModalDialog 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 @@ bool CBrowseDialog::OnInit() _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 @@ bool CBrowseDialog::OnInit() #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 += ")"; + } + */ + + 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); } - _filterCombo.AddString(s); - _filterCombo.SetCurSel(0); + + if (/* FilterIndex >= 0 && */ (unsigned)FilterIndex < Filters.Size()) + _filterCombo.SetCurSel(FilterIndex); } _list.SetImageList(GetSysImageList(true), LVSIL_SMALL); @@ -261,7 +243,7 @@ bool CBrowseDialog::OnInit() _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 @@ bool CBrowseDialog::OnInit() #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 @@ bool CBrowseDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) 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 @@ bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header) 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::OnNotify(UINT /* controlID */, LPNMHDR header) bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo) { - bool ctrl = IsKeyDown(VK_CONTROL); + const bool ctrl = IsKeyDown(VK_CONTROL); switch (keyDownInfo->wVKey) { @@ -434,7 +434,8 @@ bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo) return false; } -bool CBrowseDialog::OnButtonClicked(int buttonID, HWND buttonHWND) + +bool CBrowseDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -474,21 +475,21 @@ bool CBrowseDialog::GetParentPath(const UString &path, UString &parentPrefix, US 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 int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData) 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 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected 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 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected 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 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected 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(const UString &pathPrefix, const UString &selected 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::OpenParentFolder() 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 @@ void CBrowseDialog::OnCreateDir() { 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::OnCreateDir() 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 @@ void CBrowseDialog::OnItemEnter() 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 @@ void CBrowseDialog::FinishOnOK() 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 @@ bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultP #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 @@ bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultP 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(); + if (message) + s += message; + else + { + char temp[16]; + ConvertUInt32ToHex8Digits(errorCode, temp); + s += "Error #"; + s += temp; + } s.Add_LF(); - s += path; - MessageBox_Error_Global(owner, s); + 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 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result result.Empty(); UString path = path2; + #ifdef _WIN32 path.Replace(L'/', WCHAR_PATH_SEPARATOR); + #endif unsigned start = 0; UString base; @@ -926,9 +991,7 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result return true; } #endif - int pos = GetRootPrefixSize(path); - if (pos > 0) - start = pos; + start = GetRootPrefixSize(path); } else { @@ -973,8 +1036,8 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result { 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 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result result += cur; if (slashPos < 0) break; + start = (unsigned)(slashPos + 1); result.Add_PathSepar(); - start = slashPos + 1; } return true; diff --git a/CPP/7zip/UI/FileManager/BrowseDialog.h b/CPP/7zip/UI/FileManager/BrowseDialog.h index 957af2e2..2ad8d544 100644 --- a/CPP/7zip/UI/FileManager/BrowseDialog.h +++ b/CPP/7zip/UI/FileManager/BrowseDialog.h @@ -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 --git a/CPP/7zip/UI/FileManager/ComboDialog.cpp b/CPP/7zip/UI/FileManager/ComboDialog.cpp index 729743e8..921972ea 100644 --- a/CPP/7zip/UI/FileManager/ComboDialog.cpp +++ b/CPP/7zip/UI/FileManager/ComboDialog.cpp @@ -5,7 +5,7 @@ #include "../../../Windows/Control/Static.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -13,7 +13,7 @@ using namespace NWindows; bool CComboDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG LangSetDlgItems(*this, NULL, 0); #endif _comboBox.Attach(GetItem(IDC_COMBO)); diff --git a/CPP/7zip/UI/FileManager/ComboDialog.h b/CPP/7zip/UI/FileManager/ComboDialog.h index 29b28b5b..bb0fda80 100644 --- a/CPP/7zip/UI/FileManager/ComboDialog.h +++ b/CPP/7zip/UI/FileManager/ComboDialog.h @@ -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 @@ class CComboDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/CopyDialog.cpp b/CPP/7zip/UI/FileManager/CopyDialog.cpp index 4b17110d..9bc01d06 100644 --- a/CPP/7zip/UI/FileManager/CopyDialog.cpp +++ b/CPP/7zip/UI/FileManager/CopyDialog.cpp @@ -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 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) return false; } -bool CCopyDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CCopyDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff --git a/CPP/7zip/UI/FileManager/CopyDialog.h b/CPP/7zip/UI/FileManager/CopyDialog.h index 30fde71f..37824208 100644 --- a/CPP/7zip/UI/FileManager/CopyDialog.h +++ b/CPP/7zip/UI/FileManager/CopyDialog.h @@ -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 @@ const int kCopyDialog_NumInfoLines = 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 @@ class CCopyDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/DialogSize.h b/CPP/7zip/UI/FileManager/DialogSize.h index 504541bd..9f2270bd 100644 --- a/CPP/7zip/UI/FileManager/DialogSize.h +++ b/CPP/7zip/UI/FileManager/DialogSize.h @@ -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 --git a/CPP/7zip/UI/FileManager/EditDialog.cpp b/CPP/7zip/UI/FileManager/EditDialog.cpp index 7f596722..e97d9ea5 100644 --- a/CPP/7zip/UI/FileManager/EditDialog.cpp +++ b/CPP/7zip/UI/FileManager/EditDialog.cpp @@ -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 @@ bool CEditDialog::OnInit() 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 @@ bool CEditDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) */ 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 --git a/CPP/7zip/UI/FileManager/EditDialog.h b/CPP/7zip/UI/FileManager/EditDialog.h index d820516a..6970b14d 100644 --- a/CPP/7zip/UI/FileManager/EditDialog.h +++ b/CPP/7zip/UI/FileManager/EditDialog.h @@ -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 --git a/CPP/7zip/UI/FileManager/EditPage.cpp b/CPP/7zip/UI/FileManager/EditPage.cpp index 0108904d..a2a03215 100644 --- a/CPP/7zip/UI/FileManager/EditPage.cpp +++ b/CPP/7zip/UI/FileManager/EditPage.cpp @@ -12,6 +12,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_EDIT_EDITOR, @@ -22,6 +23,7 @@ static const UInt32 kLangIDs_Colon[] = { IDT_EDIT_VIEWER }; +#endif #define kEditTopic "FM/options.htm#editor" @@ -29,8 +31,10 @@ bool CEditPage::OnInit() { _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 @@ static void Edit_BrowseForFile(NWindows::NControl::CEdit &edit, HWND hwnd) 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 @@ static void Edit_BrowseForFile(NWindows::NControl::CEdit &edit, HWND hwnd) } } -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 @@ bool CEditPage::OnButtonClicked(int buttonID, HWND buttonHWND) 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 --git a/CPP/7zip/UI/FileManager/EditPage.h b/CPP/7zip/UI/FileManager/EditPage.h index 208edd8d..a70fad7f 100644 --- a/CPP/7zip/UI/FileManager/EditPage.h +++ b/CPP/7zip/UI/FileManager/EditPage.h @@ -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 @@ struct CEditPageCtrl { NWindows::NControl::CEdit Edit; bool WasChanged; - int Ctrl; - int Button; + unsigned Ctrl; + unsigned Button; }; class CEditPage: public NWindows::NControl::CPropertyPage @@ -20,11 +20,11 @@ class CEditPage: public NWindows::NControl::CPropertyPage 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 --git a/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp b/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp index 389aa3e8..fc2fd6c4 100644 --- a/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp +++ b/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp @@ -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 @@ CEnumFormatEtc::~CEnumFormatEtc() } } -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 @@ STDMETHODIMP CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pcel 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 @@ STDMETHODIMP CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc) // 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 --git a/CPP/7zip/UI/FileManager/EnumFormatEtc.h b/CPP/7zip/UI/FileManager/EnumFormatEtc.h index 93a53cb3..12df225d 100644 --- a/CPP/7zip/UI/FileManager/EnumFormatEtc.h +++ b/CPP/7zip/UI/FileManager/EnumFormatEtc.h @@ -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 --git a/CPP/7zip/UI/FileManager/ExtractCallback.cpp b/CPP/7zip/UI/FileManager/ExtractCallback.cpp index 232717f8..f6740447 100644 --- a/CPP/7zip/UI/FileManager/ExtractCallback.cpp +++ b/CPP/7zip/UI/FileManager/ExtractCallback.cpp @@ -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 @@ void CExtractCallbackImp::Init() NumArchiveErrors = 0; ThereAreMessageErrors = false; - #ifndef _SFX + #ifndef Z7_SFX NumFolders = NumFiles = 0; NeedAddFile = false; #endif @@ -60,29 +60,27 @@ void CExtractCallbackImp::AddError_Message(LPCWSTR s) 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 @@ HRESULT CExtractCallbackImp::Open_Finished() return ProgressDialog->Sync.CheckStop(); } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackImp::Open_CryptoGetTextPassword(BSTR *password) { @@ -168,8 +166,8 @@ void CExtractCallbackImp::Open_Clear_PasswordWasAsked_Flag() #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 @@ STDMETHODIMP CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt6 #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::SetCompletedFiles(const UInt64 *value) } */ -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::AskOverwrite( } -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 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 is 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 @@ HRESULT CExtractCallbackImp::MessageError(const char *message, const FString &pa 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 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam 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 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam } 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 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam else { s += "Error #"; - s.Add_UInt32(opRes); + s.Add_UInt32((UInt32)opRes); } if (encrypted && opRes != NArchive::NExtract::NOperationResult::kWrongPassword) @@ -354,7 +361,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam } } -STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted) +Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted)) { switch (opRes) { @@ -369,7 +376,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypte } } - #ifndef _SFX + #ifndef Z7_SFX if (_isFolder) NumFolders++; else @@ -380,7 +387,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypte 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 @@ STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypt 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::BeforeOpen(const wchar_t *name, bool /* testMode */ 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 GetOpenArcErrorMessage(UInt32 errorFlags) { 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 @@ HRESULT CExtractCallbackImp::ExtractResult(HRESULT result) return S_OK; } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CExtractCallbackImp::SetPassword(const UString &password) { @@ -658,14 +665,14 @@ HRESULT CExtractCallbackImp::SetPassword(const UString &password) 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 @@ STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) 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 @@ STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) #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 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( { 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 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( 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 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( { 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 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( &destFileInfo.MTime, &destFileInfo.Size, srcPath, srcTime, srcSize, - &overwriteResult)); + &overwriteResult)) switch (overwriteResult) { @@ -763,7 +770,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( { 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 @@ STDMETHODIMP CExtractCallbackImp::AskWrite( 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::AskWrite( } -STDMETHODIMP CExtractCallbackImp::UseExtractToStream(Int32 *res) +Z7_COM7F_IMF(CExtractCallbackImp::UseExtractToStream(Int32 *res)) { *res = BoolToInt(StreamMode); return S_OK; @@ -794,7 +801,7 @@ static HRESULT GetTime(IGetProp *getProp, PROPID propID, FILETIME &ft, bool &ftD { 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 @@ static HRESULT GetItemBoolProp(IGetProp *getProp, PROPID propID, bool &result) { 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 @@ static HRESULT GetItemBoolProp(IGetProp *getProp, PROPID propID, bool &result) } -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 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name, _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 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name, 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 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name, COM_TRY_END } -STDMETHODIMP CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode) +Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode)) { COM_TRY_BEGIN _needUpdateStat = ( @@ -934,21 +941,21 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode) 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 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypt // 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 @@ STDMETHODIMP CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *proce } _fileMode = true; } - RINOK(FlushToDisk(false)); + RINOK(FlushToDisk(false)) return _outFileStream->Write(data, size, processedSize); } @@ -1026,7 +1033,7 @@ HRESULT CVirtFileSystem::FlushToDisk(bool closeLast) // 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 --git a/CPP/7zip/UI/FileManager/ExtractCallback.h b/CPP/7zip/UI/FileManager/ExtractCallback.h index 02578bb4..c2aa4700 100644 --- a/CPP/7zip/UI/FileManager/ExtractCallback.h +++ b/CPP/7zip/UI/FileManager/ExtractCallback.h @@ -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 @@ class CGrowBuf return true; } - CGrowBuf(): _items(0), _size(0) {} + CGrowBuf(): _items(NULL), _size(0) {} ~CGrowBuf() { MyFree(_items); } operator Byte *() { return _items; } @@ -92,10 +92,11 @@ struct CVirtFile IsAltStream(false) {} }; -class CVirtFileSystem: - public ISequentialOutStream, - public CMyUnknownImp -{ + +Z7_CLASS_IMP_NOQIB_1( + CVirtFileSystem, + ISequentialOutStream +) UInt64 _totalAllocSize; size_t _pos; @@ -156,104 +157,86 @@ class CVirtFileSystem: 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 @@ class CExtractCallbackImp: bool StreamMode; CProgressDialog *ProgressDialog; - #ifndef _SFX + #ifndef Z7_SFX UInt64 NumFolders; UInt64 NumFiles; bool NeedAddFile; @@ -272,7 +255,7 @@ class CExtractCallbackImp: bool ThereAreMessageErrors; NExtract::NOverwriteMode::EEnum OverwriteMode; - #ifndef _NO_CRYPTO + #ifndef Z7_NO_CRYPTO bool PasswordIsDefined; bool PasswordWasAsked; UString Password; @@ -290,13 +273,13 @@ class CExtractCallbackImp: 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 @@ class CExtractCallbackImp: ~CExtractCallbackImp(); void Init(); - #ifndef _SFX + #ifndef Z7_SFX void SetHashCalc(IHashCalc *hashCalc) { _hashCalc = hashCalc; } void SetHashMethods(IHashCalc *hash) diff --git a/CPP/7zip/UI/FileManager/FM.cpp b/CPP/7zip/UI/FileManager/FM.cpp index 812eff67..13189a76 100644 --- a/CPP/7zip/UI/FileManager/FM.cpp +++ b/CPP/7zip/UI/FileManager/FM.cpp @@ -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 @@ extern 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 @@ DWORD g_ComCtl32Version; 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 @@ CApp g_App; 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 @@ static BOOL InitInstance(int nCmdShow) 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 @@ static BOOL InitInstance(int nCmdShow) wc.lpszClassName = kWindowClass; - MyRegisterClass(&wc); + if (MyRegisterClass(&wc) == 0) + return FALSE; // RECT rect; // GetClientRect(hWnd, &rect); @@ -305,7 +316,7 @@ static BOOL InitInstance(int nCmdShow) { if (windowPosIsRead) placement.rcNormalPosition = info.rect; - placement.showCmd = nCmdShow; + placement.showCmd = (UINT)nCmdShow; wnd.SetPlacement(&placement); } else @@ -343,6 +354,8 @@ static void GetCommands(const UString &aCommandLine, UString &aCommands) #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 @@ typedef BOOL (WINAPI *Func_IsWow64Process)(HANDLE, PBOOL); 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 @@ bool IsLargePageSupported() #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 @@ bool g_SymLink_Supported = false; 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 const CSwitchForm kSwitchForms[kNumSwitches] = 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 @@ static int WINAPI WinMain2(int nCmdShow) */ NT_CHECK + #ifdef Z7_LARGE_PAGES SetLargePageSize(); + #endif #endif + #ifdef Z7_LANG LoadLangOneTime(); + #endif InitCommonControls(); @@ -516,7 +539,7 @@ static int WINAPI WinMain2(int nCmdShow) // NCOM::CComInitializer comInitializer; UString commandsString; - // MessageBoxW(0, GetCommandLineW(), L"", 0); + // MessageBoxW(NULL, GetCommandLineW(), L"", 0); #ifdef UNDER_CE commandsString = GetCommandLineW(); @@ -577,7 +600,7 @@ static int WINAPI WinMain2(int nCmdShow) 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 @@ static int WINAPI WinMain2(int nCmdShow) Set_SymLink_Supported(); #endif - g_App.ReloadLang(); + g_App.ReloadLangItems(); MSG msg; if (!InitInstance (nCmdShow)) @@ -654,7 +677,7 @@ static int WINAPI WinMain2(int nCmdShow) // 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 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, catch(int v) { AString e ("Error: "); - e.Add_UInt32(v); + e.Add_UInt32((unsigned)v); ErrorMessage(e); return 1; } @@ -748,7 +771,7 @@ static void SaveWindowInfo(HWND aWnd) 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 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) 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 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) 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 @@ void CApp::MoveSubWindows() { HWND hWnd = _window; RECT rect; - if (hWnd == 0) + if (!hWnd) return; ::GetClientRect(hWnd, &rect); int xSize = rect.right; diff --git a/CPP/7zip/UI/FileManager/FM.dsp b/CPP/7zip/UI/FileManager/FM.dsp index a12d3307..1ae054d2 100644 --- a/CPP/7zip/UI/FileManager/FM.dsp +++ b/CPP/7zip/UI/FileManager/FM.dsp @@ -45,7 +45,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ 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 @@ -716,6 +720,10 @@ SOURCE=..\..\..\..\C\Alloc.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 @@ -1112,6 +1120,10 @@ SOURCE=..\..\..\Common\MyCom.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 @@ -1132,6 +1144,10 @@ SOURCE=..\..\..\Common\MyVector.h # 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 @@ SOURCE=..\Explorer\MyExplorerCommand.h # 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 --git a/CPP/7zip/UI/FileManager/FM.mak b/CPP/7zip/UI/FileManager/FM.mak index 8b3d97af..8331285a 100644 --- a/CPP/7zip/UI/FileManager/FM.mak +++ b/CPP/7zip/UI/FileManager/FM.mak @@ -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 @@ FM_OBJS = \ $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 @@ AGENT_OBJS = \ $O\ArchiveFolderOpen.obj \ $O\ArchiveFolderOut.obj \ $O\UpdateCallbackAgent.obj \ + +# we need empty line after last line above diff --git a/CPP/7zip/UI/FileManager/FSDrives.cpp b/CPP/7zip/UI/FileManager/FSDrives.cpp index c563907f..985d7c45 100644 --- a/CPP/7zip/UI/FileManager/FSDrives.cpp +++ b/CPP/7zip/UI/FileManager/FSDrives.cpp @@ -41,7 +41,7 @@ FString CDriveInfo::GetDeviceFileIoName() const struct CPhysTempBuffer { void *buffer; - CPhysTempBuffer(): buffer(0) {} + CPhysTempBuffer(): buffer(NULL) {} ~CPhysTempBuffer() { MidFree(buffer); } }; @@ -50,22 +50,22 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt { 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 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt 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 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt } 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 @@ static const char * const kDriveTypes[] = , "RAM disk" }; -STDMETHODIMP CFSDrives::LoadItems() +Z7_COM7F_IMF(CFSDrives::LoadItems()) { _drives.Clear(); @@ -209,13 +209,13 @@ STDMETHODIMP CFSDrives::LoadItems() 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 @@ STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT 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 @@ STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT 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 @@ HRESULT CFSDrives::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 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::GetFolderProperty(PROPID propID, PROPVARIANT *value) } -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 @@ STDMETHODIMP CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) *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 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num 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 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num } 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 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num 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 --git a/CPP/7zip/UI/FileManager/FSDrives.h b/CPP/7zip/UI/FileManager/FSDrives.h index f12e4da8..8ae831cf 100644 --- a/CPP/7zip/UI/FileManager/FSDrives.h +++ b/CPP/7zip/UI/FileManager/FSDrives.h @@ -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 @@ struct CDriveInfo 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 @@ class CFSDrives: 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 --git a/CPP/7zip/UI/FileManager/FSFolder.cpp b/CPP/7zip/UI/FileManager/FSFolder.cpp index f6030618..06c572d2 100644 --- a/CPP/7zip/UI/FileManager/FSFolder.cpp +++ b/CPP/7zip/UI/FileManager/FSFolder.cpp @@ -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 @@ HRESULT CFSFolder::Init(const FString &path /* , IFolderFolder *parentFolder */) if (!_findChangeNotification.IsHandleAllocated()) { - DWORD lastError = GetLastError(); + const HRESULT lastError = GetLastError_noZero_HRESULT(); CFindFile findFile; CFileInfo fi; FString path2 = _path; @@ -125,7 +134,7 @@ HRESULT CFsFolderStat::Enumerate() { if (Progress) { - RINOK(Progress->SetCompleted(NULL)); + RINOK(Progress->SetCompleted(NULL)) } Path.Add_PathSepar(); const unsigned len = Path.Len(); @@ -139,7 +148,7 @@ HRESULT CFsFolderStat::Enumerate() NumFolders++; Path.DeleteFrom(len); Path += fi.Name; - RINOK(Enumerate()); + RINOK(Enumerate()) } else { @@ -166,7 +175,7 @@ bool MyGetCompressedFileSizeW(CFSTR path, UInt64 &size) return true; } } - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (USE_SUPER_PATH) { UString superPath; @@ -285,16 +294,16 @@ HRESULT CFSFolder::LoadSubItems(int dirItem, const FString &relPrefix) 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 @@ bool CFSFolder::SaveComments() 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 @@ STDMETHODIMP CFSFolder::GetNumberOfItems(UInt32 *numItems) #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 @@ STDMETHODIMP CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsign 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 @@ STDMETHODIMP CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned 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 @@ bool CFSFolder::ReadFileInfo(CDirItem &di) } +EXTERN_C_BEGIN + typedef struct { LARGE_INTEGER CreationTime; @@ -443,37 +454,57 @@ typedef struct 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 @@ void CFSFolder::ReadChangeTime(CDirItem &di) 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 @@ STDMETHODIMP CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *va // ---------- 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 @@ STDMETHODIMP CFSFolder::GetRawProp(UInt32 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 @@ STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPI { 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 @@ STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPI 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 @@ FString CFSFolder::GetRelPath(const CDirItem &item) const 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 @@ STDMETHODIMP CFSFolder::BindToParentFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) COM_TRY_END } -STDMETHODIMP CFSFolder::WasChanged(Int32 *wasChanged) +Z7_COM7F_IMF(CFSFolder::WasChanged(Int32 *wasChanged)) { bool wasChangedMain = false; @@ -961,7 +990,7 @@ STDMETHODIMP CFSFolder::WasChanged(Int32 *wasChanged) 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 @@ STDMETHODIMP CFSFolder::Clone(IFolderFolder **resultFolder) 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 @@ HRESULT CFSFolder::GetItemFullSize(unsigned index, UInt64 &size, IProgress *prog 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::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgr } */ -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 @@ STDMETHODIMP CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress) 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 @@ void CFSFolder::GetAbsPath(const wchar_t *name, FString &absPath) 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 @@ STDMETHODIMP CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress * 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 @@ STDMETHODIMP CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress 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 @@ STDMETHODIMP CFSFolder::SetProperty(UInt32 index, PROPID propID, 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 @@ STDMETHODIMP CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) *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 --git a/CPP/7zip/UI/FileManager/FSFolder.h b/CPP/7zip/UI/FileManager/FSFolder.h index 4f8c3449..fe8538a6 100644 --- a/CPP/7zip/UI/FileManager/FSFolder.h +++ b/CPP/7zip/UI/FileManager/FSFolder.h @@ -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 @@ struct CFsFolderStat HRESULT Enumerate(); }; -class CFSFolder: +class CFSFolder Z7_final: public IFolderFolder, public IArchiveGetRawProps, public IFolderCompare, @@ -95,42 +95,36 @@ class CFSFolder: // 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 @@ class CFSFolder: 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 @@ struct CCopyStateIO 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 --git a/CPP/7zip/UI/FileManager/FSFolderCopy.cpp b/CPP/7zip/UI/FileManager/FSFolderCopy.cpp index 4ca931b3..db4ae0ae 100644 --- a/CPP/7zip/UI/FileManager/FSFolderCopy.cpp +++ b/CPP/7zip/UI/FileManager/FSFolderCopy.cpp @@ -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 @@ using namespace NFind; 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 @@ HRESULT CCopyStateIO::MyCopyFile(CFSTR inPath, CFSTR outPath, DWORD attrib) 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 @@ static DWORD CALLBACK CopyProgressRoutine( 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 @@ struct CCopyState IFolderOperationsExtractCallback *Callback; bool MoveMode; bool UseReadWriteMode; + bool IsAltStreamsDest; Func_CopyFileExW my_CopyFileExW; #ifndef UNDER_CE @@ -248,23 +251,27 @@ void CCopyState::Prepare() 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 @@ bool CCopyState::CopyFile_Sys(CFSTR oldFile, CFSTR newFile) 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 @@ bool CCopyState::MoveFile_Sys(CFSTR oldFile, CFSTR newFile) &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 @@ static HRESULT CopyFile_Ask( state.MoveMode ? "Cannot move file onto itself" : "Cannot copy file onto itself" - , destPath)); + , destPath)) return E_ABORT; } @@ -416,12 +423,12 @@ static HRESULT CopyFile_Ask( &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 @@ static HRESULT CopyFile_Ask( 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 @@ static HRESULT CopyFile_Ask( 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 @@ static HRESULT CopyFile_Ask( 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 @@ static HRESULT CopyFile_Ask( 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 @@ static HRESULT CopyFolder( 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 @@ static HRESULT CopyFolder( state.MoveMode ? "Cannot copy folder onto itself" : "Cannot move folder onto itself" - , destPath)); + , destPath)) return E_ABORT; } @@ -521,7 +529,7 @@ static HRESULT CopyFolder( 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 @@ static HRESULT CopyFolder( } else { - RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2)); + RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2)) } } @@ -555,7 +563,7 @@ static HRESULT CopyFolder( { 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 @@ static HRESULT CopyFolder( 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 @@ STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num 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 @@ STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num 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 --git a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp index a7873fe5..e4e99975 100644 --- a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp +++ b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp @@ -26,8 +26,15 @@ struct CThreadArchiveOpen 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 @@ struct CThreadArchiveOpen 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 int FindPlugin(const CObjectVector &plugins, const UString & 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 @@ static void SplitNameToPureNameAndExtension(const FString &fullName, } else { - pureName.SetFrom(fullName, index); + pureName.SetFrom(fullName, (unsigned)index); extensionDelimiter = '.'; extension = fullName.Ptr((unsigned)index + 1); } @@ -229,16 +236,21 @@ static void GetFolderError(CMyComPtr &folder, UString &open_Error } } +#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 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream, 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 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream, { 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 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream, } return t.Result; - } - - return S_FALSE; + // } } diff --git a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h index a1f2f104..88027659 100644 --- a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h +++ b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h @@ -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 --git a/CPP/7zip/UI/FileManager/FilePlugins.cpp b/CPP/7zip/UI/FileManager/FilePlugins.cpp index 46000301..cf20970f 100644 --- a/CPP/7zip/UI/FileManager/FilePlugins.cpp +++ b/CPP/7zip/UI/FileManager/FilePlugins.cpp @@ -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 @@ void CExtDatabase::Read() 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 --git a/CPP/7zip/UI/FileManager/FilePlugins.h b/CPP/7zip/UI/FileManager/FilePlugins.h index 43b05f92..db8ec396 100644 --- a/CPP/7zip/UI/FileManager/FilePlugins.h +++ b/CPP/7zip/UI/FileManager/FilePlugins.h @@ -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 @@ struct CExtPlugins class CExtDatabase { - int FindExt(const UString &ext); + int FindExt(const UString &ext) const; public: CObjectVector Exts; - CObjectVector Plugins; + // CObjectVector Plugins; void Read(); }; diff --git a/CPP/7zip/UI/FileManager/FoldersPage.cpp b/CPP/7zip/UI/FileManager/FoldersPage.cpp index d019bab8..7e74635b 100644 --- a/CPP/7zip/UI/FileManager/FoldersPage.cpp +++ b/CPP/7zip/UI/FileManager/FoldersPage.cpp @@ -11,6 +11,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDT_FOLDERS_WORKING_FOLDER, @@ -19,8 +20,9 @@ static const UInt32 kLangIDs[] = 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 @@ static const int kWorkModeButtons[] = #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 @@ int CFoldersPage::GetWorkMode() const { for (unsigned i = 0; i < kNumWorkModeButtons; i++) if (IsButtonCheckedBool(kWorkModeButtons[i])) - return i; + return (int)i; throw 0; } @@ -104,7 +110,7 @@ void CFoldersPage::ModifiedEvent() */ } -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 @@ bool CFoldersPage::OnButtonClicked(int buttonID, HWND buttonHWND) 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 --git a/CPP/7zip/UI/FileManager/FoldersPage.h b/CPP/7zip/UI/FileManager/FoldersPage.h index 71c7bfce..09b6cddb 100644 --- a/CPP/7zip/UI/FileManager/FoldersPage.h +++ b/CPP/7zip/UI/FileManager/FoldersPage.h @@ -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 @@ class CFoldersPage : public NWindows::NControl::CPropertyPage 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 --git a/CPP/7zip/UI/FileManager/FormatUtils.h b/CPP/7zip/UI/FileManager/FormatUtils.h index 993e8033..1db08eff 100644 --- a/CPP/7zip/UI/FileManager/FormatUtils.h +++ b/CPP/7zip/UI/FileManager/FormatUtils.h @@ -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 --git a/CPP/7zip/UI/FileManager/HelpUtils.cpp b/CPP/7zip/UI/FileManager/HelpUtils.cpp index 5cb78fc1..d5b6a580 100644 --- a/CPP/7zip/UI/FileManager/HelpUtils.cpp +++ b/CPP/7zip/UI/FileManager/HelpUtils.cpp @@ -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 @@ void ShowHelpWindow(LPCSTR) #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 --git a/CPP/7zip/UI/FileManager/HelpUtils.h b/CPP/7zip/UI/FileManager/HelpUtils.h index 90c5f7d1..d7bdf453 100644 --- a/CPP/7zip/UI/FileManager/HelpUtils.h +++ b/CPP/7zip/UI/FileManager/HelpUtils.h @@ -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 --git a/CPP/7zip/UI/FileManager/IFolder.h b/CPP/7zip/UI/FileManager/IFolder.h index c5cff06e..1ebdf7e5 100644 --- a/CPP/7zip/UI/FileManager/IFolder.h +++ b/CPP/7zip/UI/FileManager/IFolder.h @@ -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 @@ namespace NPlugin }; } -#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; \ - -FOLDER_INTERFACE(IFolderFolder, 0x00) -{ - INTERFACE_FolderFolder(PURE) -}; +#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)) \ + +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; -}; +#define Z7_IFACEM_IFolderGetSystemIconIndex(x) \ + x(GetSystemIconIndex(UInt32 index, Int32 *iconIndex)) +Z7_IFACE_CONSTR_FOLDER(IFolderGetSystemIconIndex, 0x07) -FOLDER_INTERFACE(IFolderGetItemFullSize, 0x08) -{ - STDMETHOD(GetItemFullSize)(UInt32 index, PROPVARIANT *value, IProgress *progress) PURE; -}; +#define Z7_IFACEM_IFolderGetItemFullSize(x) \ + x(GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress)) +Z7_IFACE_CONSTR_FOLDER(IFolderGetItemFullSize, 0x08) -FOLDER_INTERFACE(IFolderCalcItemFullSize, 0x14) -{ - STDMETHOD(CalcItemFullSize)(UInt32 index, IProgress *progress) PURE; -}; +#define Z7_IFACEM_IFolderCalcItemFullSize(x) \ + x(CalcItemFullSize(UInt32 index, IProgress *progress)) +Z7_IFACE_CONSTR_FOLDER(IFolderCalcItemFullSize, 0x14) -FOLDER_INTERFACE(IFolderClone, 0x09) -{ - STDMETHOD(Clone)(IFolderFolder **resultFolder) PURE; -}; +#define Z7_IFACEM_IFolderClone(x) \ + x(Clone(IFolderFolder **resultFolder)) +Z7_IFACE_CONSTR_FOLDER(IFolderClone, 0x09) -FOLDER_INTERFACE(IFolderSetFlatMode, 0x0A) -{ - STDMETHOD(SetFlatMode)(Int32 flatMode) PURE; -}; +#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; \ +#define Z7_IFACEM_IFolderProperties(x) \ + x(GetNumberOfFolderProperties(UInt32 *numProperties)) \ + x(GetFolderPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \ -FOLDER_INTERFACE(IFolderProperties, 0x0E) -{ - INTERFACE_FolderProperties(PURE) -}; +Z7_IFACE_CONSTR_FOLDER(IFolderProperties, 0x0E) -#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; \ +#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)) \ -FOLDER_INTERFACE(IFolderArcProps, 0x10) -{ - INTERFACE_IFolderArcProps(PURE) -}; +Z7_IFACE_CONSTR_FOLDER(IFolderArcProps, 0x10) -FOLDER_INTERFACE(IGetFolderArcProps, 0x11) -{ - STDMETHOD(GetFolderArcProps)(IFolderArcProps **object) PURE; -}; +#define Z7_IFACEM_IGetFolderArcProps(x) \ + x(GetFolderArcProps(IFolderArcProps **object)) +Z7_IFACE_CONSTR_FOLDER(IGetFolderArcProps, 0x11) -FOLDER_INTERFACE(IFolderCompare, 0x15) -{ - STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw) PURE; -}; +#define Z7_IFACEM_IFolderCompare(x) \ + x##2(Int32, CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw)) +Z7_IFACE_CONSTR_FOLDER(IFolderCompare, 0x15) -#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; \ +#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)) \ -FOLDER_INTERFACE(IFolderGetItemName, 0x16) -{ - INTERFACE_IFolderGetItemName(PURE) -}; +Z7_IFACE_CONSTR_FOLDER(IFolderGetItemName, 0x16) -#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_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 --git a/CPP/7zip/UI/FileManager/LangPage.cpp b/CPP/7zip/UI/FileManager/LangPage.cpp index 47e7894c..ec1dd2ef 100644 --- a/CPP/7zip/UI/FileManager/LangPage.cpp +++ b/CPP/7zip/UI/FileManager/LangPage.cpp @@ -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 LangOpen(CLang &lang, CFSTR fileName); 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 @@ bool CLangPage::OnInit() } 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 @@ bool CLangPage::OnInit() 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 @@ void CLangPage::OnNotifyHelp() 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 --git a/CPP/7zip/UI/FileManager/LangPage.h b/CPP/7zip/UI/FileManager/LangPage.h index b8062573..e37ba058 100644 --- a/CPP/7zip/UI/FileManager/LangPage.h +++ b/CPP/7zip/UI/FileManager/LangPage.h @@ -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 --git a/CPP/7zip/UI/FileManager/LangPage.rc b/CPP/7zip/UI/FileManager/LangPage.rc index 164e2d30..506f102d 100644 --- a/CPP/7zip/UI/FileManager/LangPage.rc +++ b/CPP/7zip/UI/FileManager/LangPage.rc @@ -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 @@ IDD_LANG_2 MY_PAGE 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 --git a/CPP/7zip/UI/FileManager/LangPageRes.h b/CPP/7zip/UI/FileManager/LangPageRes.h index d7a39d75..a1ad30fa 100644 --- a/CPP/7zip/UI/FileManager/LangPageRes.h +++ b/CPP/7zip/UI/FileManager/LangPageRes.h @@ -6,3 +6,4 @@ #define IDT_LANG_LANG 2102 #define IDC_LANG_LANG 100 +#define IDT_LANG_INFO 101 diff --git a/CPP/7zip/UI/FileManager/LangUtils.cpp b/CPP/7zip/UI/FileManager/LangUtils.cpp index 83d5aa70..4c9d16fe 100644 --- a/CPP/7zip/UI/FileManager/LangUtils.cpp +++ b/CPP/7zip/UI/FileManager/LangUtils.cpp @@ -19,7 +19,8 @@ extern bool g_IsNT; 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 @@ FString GetLangDirPrefix() return NDLL::GetModuleDirPrefix() + FTEXT("Lang") FSTRING_PATH_SEPARATOR; } +#ifdef Z7_LANG + void LoadLangOneTime() { NSynchronization::CCriticalSectionLock lock(g_CriticalSection); @@ -48,7 +51,7 @@ void LangSetDlgItemText(HWND dialog, UInt32 controlID, UInt32 langID) 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 @@ static const CIDLangPair kLangPairs[] = 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 @@ void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems) for (i = 0; i < numItems; i++) { - UInt32 id = ids[i]; + const UInt32 id = ids[i]; LangSetDlgItemText(dialog, id, id); } } @@ -90,11 +93,11 @@ void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems) { 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_Colon(HWND dialog, const UInt32 *ids, unsigned numItems) } } +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 @@ static struct CC1Lang // 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 @@ static void OpenDefaultLang() 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 @@ void ReloadLang() 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 --git a/CPP/7zip/UI/FileManager/LangUtils.h b/CPP/7zip/UI/FileManager/LangUtils.h index d63a443c..d53d270e 100644 --- a/CPP/7zip/UI/FileManager/LangUtils.h +++ b/CPP/7zip/UI/FileManager/LangUtils.h @@ -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 @@ struct CIDLangPair 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 @@ inline void AddLangString(UString &s, UInt32 langID) { s += NWindows::MyLoadStri #endif +FString GetLangDirPrefix(); +// bool LangOpen(CLang &lang, CFSTR fileName); + +void Lang_GetShortNames_for_DefaultLang(AStringVector &names, unsigned &subLang); + #endif diff --git a/CPP/7zip/UI/FileManager/LinkDialog.cpp b/CPP/7zip/UI/FileManager/LinkDialog.cpp index 07f1f061..0f247617 100644 --- a/CPP/7zip/UI/FileManager/LinkDialog.cpp +++ b/CPP/7zip/UI/FileManager/LinkDialog.cpp @@ -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 @@ extern bool g_SymLink_Supported; using namespace NWindows; using namespace NFile; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDB_LINK_LINK, @@ -73,7 +71,7 @@ static bool GetSymLink(CFSTR path, CReparseAttr &attr, UString &errorMessage) } -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 @@ static const int k_LinkType_Buttons[] = 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 @@ bool CLinkDialog::OnInit() 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 @@ bool CLinkDialog::OnInit() { 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 @@ bool CLinkDialog::OnInit() 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 @@ bool CLinkDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) return false; } -bool CLinkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CLinkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -240,7 +241,7 @@ void CLinkDialog::OnButton_SetPath(bool to) _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 @@ void CLinkDialog::OnButton_Link() 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 CLinkDialog::OnButton_Link() void CApp::Link() { - unsigned srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.IsFSFolder()) { @@ -363,7 +364,7 @@ void CApp::Link() return; } CRecordVector indices; - srcPanel.GetOperatedItemIndices(indices); + srcPanel.Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; if (indices.Size() != 1) @@ -371,14 +372,14 @@ void CApp::Link() 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 --git a/CPP/7zip/UI/FileManager/LinkDialog.h b/CPP/7zip/UI/FileManager/LinkDialog.h index 56deec9d..dd768f7e 100644 --- a/CPP/7zip/UI/FileManager/LinkDialog.h +++ b/CPP/7zip/UI/FileManager/LinkDialog.h @@ -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 @@ class CLinkDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/ListViewDialog.cpp b/CPP/7zip/UI/FileManager/ListViewDialog.cpp index a42e790b..6767e4c0 100644 --- a/CPP/7zip/UI/FileManager/ListViewDialog.cpp +++ b/CPP/7zip/UI/FileManager/ListViewDialog.cpp @@ -8,7 +8,7 @@ #include "ListViewDialog.h" #include "RegistryUtils.h" -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -26,14 +26,14 @@ static void ListView_GetSelected(NControl::CListView &listView, CUIntVector &vec 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 @@ void CListViewDialog::DeleteItems() { 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 --git a/CPP/7zip/UI/FileManager/ListViewDialog.h b/CPP/7zip/UI/FileManager/ListViewDialog.h index 00206afd..5f0b66de 100644 --- a/CPP/7zip/UI/FileManager/ListViewDialog.h +++ b/CPP/7zip/UI/FileManager/ListViewDialog.h @@ -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 @@ class CListViewDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/MenuPage.cpp b/CPP/7zip/UI/FileManager/MenuPage.cpp index ef4485f3..8603f325 100644 --- a/CPP/7zip/UI/FileManager/MenuPage.cpp +++ b/CPP/7zip/UI/FileManager/MenuPage.cpp @@ -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 @@ static const UInt32 kLangIDs[] = 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 @@ bool CMenuPage::OnInit() 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 @@ bool CMenuPage::OnInit() 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 @@ bool CMenuPage::OnInit() _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 @@ bool CMenuPage::OnInit() } } - 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 @@ LONG CMenuPage::OnApply() 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 @@ LONG CMenuPage::OnApply() 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 @@ void CMenuPage::OnNotifyHelp() ShowHelpWindow(kMenuTopic); } -bool CMenuPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CMenuPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -392,7 +396,7 @@ bool CMenuPage::OnButtonClicked(int buttonID, HWND buttonHWND) } -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 --git a/CPP/7zip/UI/FileManager/MenuPage.h b/CPP/7zip/UI/FileManager/MenuPage.h index 02aee6d7..3b62a8bd 100644 --- a/CPP/7zip/UI/FileManager/MenuPage.h +++ b/CPP/7zip/UI/FileManager/MenuPage.h @@ -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 @@ struct CShellDll 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 @@ class CMenuPage: public NWindows::NControl::CPropertyPage 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 --git a/CPP/7zip/UI/FileManager/MessagesDialog.cpp b/CPP/7zip/UI/FileManager/MessagesDialog.cpp index 41248277..57e56bcf 100644 --- a/CPP/7zip/UI/FileManager/MessagesDialog.cpp +++ b/CPP/7zip/UI/FileManager/MessagesDialog.cpp @@ -16,9 +16,9 @@ using namespace NWindows; 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 @@ void CMessagesDialog::AddMessage(LPCWSTR message) 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 --git a/CPP/7zip/UI/FileManager/MessagesDialog.h b/CPP/7zip/UI/FileManager/MessagesDialog.h index 5c017eb4..40b0379b 100644 --- a/CPP/7zip/UI/FileManager/MessagesDialog.h +++ b/CPP/7zip/UI/FileManager/MessagesDialog.h @@ -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 @@ class CMessagesDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/MyCom2.h b/CPP/7zip/UI/FileManager/MyCom2.h index 5fe1ef71..d3b49fe8 100644 --- a/CPP/7zip/UI/FileManager/MyCom2.h +++ b/CPP/7zip/UI/FileManager/MyCom2.h @@ -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 --git a/CPP/7zip/UI/FileManager/MyLoadMenu.cpp b/CPP/7zip/UI/FileManager/MyLoadMenu.cpp index c83bccb4..db4a4cfc 100644 --- a/CPP/7zip/UI/FileManager/MyLoadMenu.cpp +++ b/CPP/7zip/UI/FileManager/MyLoadMenu.cpp @@ -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 @@ extern void OptionsDialog(HWND hwndOwner, HINSTANCE hInstance); 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 @@ static int GetSortControlID(PROPID propID) 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 @@ static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex) 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)) + { + // here we try to exclude the case (wID == item.hSubMenu) if (MENU+POPUP) + continue; + } + if (langID == 0) { - MyChangeMenu(item.hSubMenu, level + 1, i); - if (level == 1 && menuIndex == kMenuIndex_View) + 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 @@ static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex) 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 CopyMenu(HMENU srcMenuSpec, HMENU destMenuSpec); 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 @@ static void CopyPopMenu_IfRequired(CMenuItem &item) } } +/* 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 - - HWND hWnd = g_HWND; - HMENU oldMenu = ::GetMenu(hWnd); - ::SetMenu(hWnd, ::LoadMenu(g_hInstance, MAKEINTRESOURCE(IDM_MENU))); - ::DestroyMenu(oldMenu); - baseMenu = ::GetMenu(hWnd); + #else // UNDER_CE + + 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) // 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) } } 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 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 @@ void CFileMenu::Load(HMENU hMenu, unsigned startPos) 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()) @@ -765,7 +850,7 @@ bool OnMenuCommand(HWND hWnd, unsigned id) 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); */ @@ -820,20 +905,19 @@ bool OnMenuCommand(HWND hWnd, unsigned id) } 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 --git a/CPP/7zip/UI/FileManager/MyLoadMenu.h b/CPP/7zip/UI/FileManager/MyLoadMenu.h index 764bf7c7..e71dbbf6 100644 --- a/CPP/7zip/UI/FileManager/MyLoadMenu.h +++ b/CPP/7zip/UI/FileManager/MyLoadMenu.h @@ -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 @@ struct CFileMenu bool isFsFolder; bool allAreFiles; bool isAltStreamsSupported; - int numItems; + unsigned numItems; FString FilePath; diff --git a/CPP/7zip/UI/FileManager/MyWindowsNew.h b/CPP/7zip/UI/FileManager/MyWindowsNew.h index 48a95359..325babcd 100644 --- a/CPP/7zip/UI/FileManager/MyWindowsNew.h +++ b/CPP/7zip/UI/FileManager/MyWindowsNew.h @@ -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 @@ struct ITaskbarList3: public ITaskbarList2 STDMETHOD(SetThumbnailClip)(HWND hwnd, RECT *prcClip) = 0; }; -#endif +#endif // __ITaskbarList3_INTERFACE_DEFINED__ -#endif +#endif // __MINGW* #endif diff --git a/CPP/7zip/UI/FileManager/NetFolder.cpp b/CPP/7zip/UI/FileManager/NetFolder.cpp index a941e73d..879f1dba 100644 --- a/CPP/7zip/UI/FileManager/NetFolder.cpp +++ b/CPP/7zip/UI/FileManager/NetFolder.cpp @@ -55,9 +55,9 @@ void CNetFolder::Init(const UString &path) 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 @@ void CNetFolder::Init(const NWindows::NNet::CResourceW *netResource, IFolderFolder *parentFolder, const UString &path) { _path = path; - if (netResource == 0) - _netResourcePointer = 0; + if (!netResource) + _netResourcePointer = NULL; else { _netResource = *netResource; @@ -86,7 +86,7 @@ void CNetFolder::Init(const NWindows::NNet::CResourceW *netResource, _parentFolder = parentFolder; } -STDMETHODIMP CNetFolder::LoadItems() +Z7_COM7F_IMF(CNetFolder::LoadItems()) { _items.Clear(); CEnum enumerator; @@ -102,35 +102,35 @@ STDMETHODIMP CNetFolder::LoadItems() 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::LoadItems() } -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 @@ STDMETHODIMP CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIAN 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 @@ STDMETHODIMP CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder 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 @@ STDMETHODIMP CNetFolder::BindToParentFolder(IFolderFolder **resultFolder) 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 @@ STDMETHODIMP CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 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 @@ STDMETHODIMP CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) } // *anIconIndex = GetRealIconIndex(0, L"\\\\HOME"); } - return GetLastError(); + return GetLastError_noZero_HRESULT(); } diff --git a/CPP/7zip/UI/FileManager/NetFolder.h b/CPP/7zip/UI/FileManager/NetFolder.h index 151dd096..352f5bd8 100644 --- a/CPP/7zip/UI/FileManager/NetFolder.h +++ b/CPP/7zip/UI/FileManager/NetFolder.h @@ -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 @@ struct CResourceEx: public NWindows::NNet::CResourceW 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 @@ class CNetFolder: 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 --git a/CPP/7zip/UI/FileManager/OpenCallback.cpp b/CPP/7zip/UI/FileManager/OpenCallback.cpp index e2e03f5e..5b6df50a 100644 --- a/CPP/7zip/UI/FileManager/OpenCallback.cpp +++ b/CPP/7zip/UI/FileManager/OpenCallback.cpp @@ -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 @@ STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 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 @@ STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password) NExtract::Save_ShowPassword(dialog.ShowPassword); } return StringToBstr(Password, password); - COM_TRY_END + // COM_TRY_END } +#endif diff --git a/CPP/7zip/UI/FileManager/OpenCallback.h b/CPP/7zip/UI/FileManager/OpenCallback.h index 9aa5d43c..8f4638cf 100644 --- a/CPP/7zip/UI/FileManager/OpenCallback.h +++ b/CPP/7zip/UI/FileManager/OpenCallback.h @@ -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 @@ class COpenArchiveCallback: 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 @@ class COpenArchiveCallback: } */ - 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 --git a/CPP/7zip/UI/FileManager/OptionsDialog.cpp b/CPP/7zip/UI/FileManager/OptionsDialog.cpp index c42e0f87..b71c3233 100644 --- a/CPP/7zip/UI/FileManager/OptionsDialog.cpp +++ b/CPP/7zip/UI/FileManager/OptionsDialog.cpp @@ -51,25 +51,27 @@ void OptionsDialog(HWND hwndOwner, HINSTANCE /* hInstance */) 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 --git a/CPP/7zip/UI/FileManager/OverwriteDialog.cpp b/CPP/7zip/UI/FileManager/OverwriteDialog.cpp index b455b14a..096527cc 100644 --- a/CPP/7zip/UI/FileManager/OverwriteDialog.cpp +++ b/CPP/7zip/UI/FileManager/OverwriteDialog.cpp @@ -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::ReduceString(UString &s) } } -void COverwriteDialog::SetFileInfoControl(int textID, int iconID, +void COverwriteDialog::SetFileInfoControl(unsigned textID, unsigned iconID, const NOverwriteDialog::CFileInfo &fileInfo) { UString sizeString; @@ -96,9 +96,9 @@ void COverwriteDialog::SetFileInfoControl(int textID, int iconID, 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 @@ bool COverwriteDialog::OnInit() return CModalDialog::OnInit(); } -bool COverwriteDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool COverwriteDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -131,7 +131,7 @@ bool COverwriteDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 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 --git a/CPP/7zip/UI/FileManager/OverwriteDialog.h b/CPP/7zip/UI/FileManager/OverwriteDialog.h index 24e56cac..a9ca9915 100644 --- a/CPP/7zip/UI/FileManager/OverwriteDialog.h +++ b/CPP/7zip/UI/FileManager/OverwriteDialog.h @@ -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 @@ class COverwriteDialog: public NWindows::NControl::CModalDialog { 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 @@ class COverwriteDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/Panel.cpp b/CPP/7zip/UI/FileManager/Panel.cpp index f7cdb5b9..72b72c65 100644 --- a/CPP/7zip/UI/FileManager/Panel.cpp +++ b/CPP/7zip/UI/FileManager/Panel.cpp @@ -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 @@ CPanel::~CPanel() 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 @@ HRESULT CPanel::Create(HWND mainWindow, HWND parentWindow, UINT id, 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 @@ LRESULT CMyComboBoxEdit::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) } 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 @@ LRESULT CMyComboBoxEdit::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) 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 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) 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 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) 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 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) _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 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) , 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 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) _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::OnDestroy() void CPanel::ChangeWindowSize(int xSize, int ySize) { - if ((HWND)*this == 0) + if (!(HWND)*this) return; int kHeaderSize; int kStatusBarSize; @@ -601,7 +648,7 @@ void CPanel::ChangeWindowSize(int xSize, int ySize) 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 @@ bool CPanel::OnNotify(UINT /* controlID */, LPNMHDR header, LRESULT &result) 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_Error_2Lines_Message_HRESULT(LPCWSTR message, HRESULT er } 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 @@ void CPanel::SetListViewMode(UInt32 index) { 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::Post_Refresh_StatusBar() 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 @@ static UString GetSubFolderNameForExtract2(const UString &arcPath) 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) + 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++) { - MessageBox_Error_LangID(IDS_SELECT_FILES); - return; + 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 @@ void CPanel::ExtractArchives() 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 @@ void CPanel::ExtractArchives() ci.Load(); ::ExtractArchives(paths, outFolder - , true // showDialog - , false // elimDup + , true // showDialog + , false // elimDup , ci.WriteZone ); } @@ -1047,7 +1108,7 @@ static void AddSizePair(UInt32 langID, UInt64 value, UString &s) void CPanel::TestArchives() { CRecordVector indices; - GetOperatedIndicesSmart(indices); + Get_ItemIndices_OperSmart(indices); CMyComPtr archiveFolder; _folder.QueryInterface(IID_IArchiveFolder, &archiveFolder); if (archiveFolder) @@ -1086,7 +1147,7 @@ void CPanel::TestArchives() 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 @@ void CPanel::TestArchives() return; } UStringVector paths; - GetFilePaths(indices, paths, true); + GetFilePaths(indices, paths); if (paths.IsEmpty()) + { + MessageBox_Error_LangID(IDS_SELECT_FILES); return; + } ::TestArchives(paths); } diff --git a/CPP/7zip/UI/FileManager/Panel.h b/CPP/7zip/UI/FileManager/Panel.h index 4755678e..e512cadf 100644 --- a/CPP/7zip/UI/FileManager/Panel.h +++ b/CPP/7zip/UI/FileManager/Panel.h @@ -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 @@ const UInt32 kParentIndex_UInt32 = (UInt32)(Int32)kParentIndex; #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 @@ struct CPanelCallback virtual void DragEnd() = 0; virtual void RefreshTitle(bool always) = 0; }; +Z7_PURE_INTERFACES_END void PanelCopyItems(); @@ -116,7 +123,7 @@ class CPropColumns: public CObjectVector { FOR_VECTOR (i, (*this)) if ((*this)[i].ID == id) - return i; + return (int)i; return -1; } @@ -194,11 +201,15 @@ UString GetFolderPath(IFolderFolder *folder); 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 @@ struct CSelectedState 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 @@ struct COpenResult -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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 _markDeletedItems(true), PanelCreated(false), - _ListViewMode(3), + _listViewMode(3), _xSize(300), _flatMode(false), @@ -565,6 +595,8 @@ class CPanel: public NWindows::NControl::CWindow2 _dontShowMode(false), + m_DropHighlighted_SelectionIndex(-1), + _needSaveInfo(false), _startGroupSelect(0), _selectionIsDefined(false) @@ -572,7 +604,7 @@ class CPanel: public NWindows::NControl::CWindow2 void SetExtendedStyle() { - if (_listView != 0) + if (_listView) _listView.SetExtendedListViewStyle(_exStyle); } @@ -592,30 +624,38 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 // 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 CPanel: public NWindows::NControl::CWindow2 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 CPanel: public NWindows::NControl::CWindow2 } }; + 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CPanel: public NWindows::NControl::CWindow2 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 @@ class CMyBuffer { 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 @@ class CExitEventLauncher throw 9387173; _needExit = true; _numActiveThreads = 0; - }; + } ~CExitEventLauncher() { Exit(true); } diff --git a/CPP/7zip/UI/FileManager/PanelCopy.cpp b/CPP/7zip/UI/FileManager/PanelCopy.cpp index 2ea3e3bd..de3d7643 100644 --- a/CPP/7zip/UI/FileManager/PanelCopy.cpp +++ b/CPP/7zip/UI/FileManager/PanelCopy.cpp @@ -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 @@ class CPanelCopyThread: public CProgressThreadVirt CPanelCopyThread(): ResultsWereShown(false), - NeedShowRes(false) + NeedShowRes(false), + CopyFrom_Paths(NULL) // , Result2(E_FAIL) {} }; @@ -72,23 +73,32 @@ HRESULT CPanelCopyThread::ProcessVirt() 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 @@ HRESULT CPanelCopyThread::ProcessVirt() /* -#ifdef EXTERNAL_CODECS +#ifdef Z7_EXTERNAL_CODECS static void ThrowException_if_Error(HRESULT res) { @@ -133,9 +143,11 @@ static void ThrowException_if_Error(HRESULT res) #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 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector &ind 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 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector &ind { /* - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS CExternalCodecs g_ExternalCodecs; #endif */ @@ -203,7 +216,7 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector &ind 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 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector &ind 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 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri 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 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri { 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 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri 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 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri return res; } -void CPanel::CopyFromNoAsk(const UStringVector &filePaths) +void CPanel::CopyFromNoAsk(bool moveMode, const UStringVector &filePaths) { CDisableTimerProcessing disableTimerProcessing(*this); @@ -396,7 +416,7 @@ void CPanel::CopyFromNoAsk(const UStringVector &filePaths) 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 @@ void CPanel::CopyFromNoAsk(const UStringVector &filePaths) 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 --git a/CPP/7zip/UI/FileManager/PanelCrc.cpp b/CPP/7zip/UI/FileManager/PanelCrc.cpp index 32948d85..df0b7338 100644 --- a/CPP/7zip/UI/FileManager/PanelCrc.cpp +++ b/CPP/7zip/UI/FileManager/PanelCrc.cpp @@ -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 @@ struct CDirEnumerator 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 @@ void CDirEnumerator::Init() 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 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r 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 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r #endif if (!fi.Find(BasePrefix + path)) { - DWORD error = GetNormalizedError(); + const DWORD error = GetNormalizedError(); resPath = path; return error; } @@ -110,7 +110,7 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r } else { - DWORD error = GetNormalizedError(); + const DWORD error = GetNormalizedError(); resPath = Prefixes.Back(); Enumerators.DeleteBack(); Prefixes.DeleteBack(); @@ -142,8 +142,8 @@ class CThreadCrc: public CProgressThreadVirt 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::ProcessWasFinished_GuiVirt() 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 @@ HRESULT CThreadCrc::ProcessVirt() 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 @@ HRESULT CThreadCrc::ProcessVirt() */ 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 @@ HRESULT CThreadCrc::ProcessVirt() 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 @@ HRESULT CApp::CalculateCrc2(const UString &methodName) CPanel &srcPanel = Panels[srcPanelIndex]; CRecordVector indices; - srcPanel.GetOperatedIndicesSmart(indices); + srcPanel.Get_ItemIndices_OperSmart(indices); if (indices.IsEmpty()) return S_OK; @@ -357,7 +357,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName) return srcPanel.CopyTo(options, indices, &messages); } - #ifdef EXTERNAL_CODECS + #ifdef Z7_EXTERNAL_CODECS LoadGlobalCodecs(); @@ -369,7 +369,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName) { 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 @@ HRESULT CApp::CalculateCrc2(const UString &methodName) 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 @@ HRESULT CApp::CalculateCrc2(const UString &methodName) 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 --git a/CPP/7zip/UI/FileManager/PanelDrag.cpp b/CPP/7zip/UI/FileManager/PanelDrag.cpp index af8799ca..040444cb 100644 --- a/CPP/7zip/UI/FileManager/PanelDrag.cpp +++ b/CPP/7zip/UI/FileManager/PanelDrag.cpp @@ -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,219 +41,1386 @@ using namespace NDir; 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); + } + + 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 ---- -class CDataObject: +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) { - for (size_t i = 0; i < size; i++) + 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) + { + 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) { - void *dest = GlobalLock(destGlobal); - if (!dest) + void *dest = GlobalLock(destGlobal); + if (!dest) + { + GlobalFree(destGlobal); + destGlobal = NULL; + } + else + { + memcpy(dest, src, size); + GlobalUnlock(destGlobal); + } + } + GlobalUnlock(srcGlobal); + return destGlobal; +} + + +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) +{ + 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) { - GlobalFree(destGlobal); - destGlobal = 0; + transfer.Flags |= k_SourceFlags_SetTargetFolder; } - else + if (!DestDirPrefix_FromTarget.IsEmpty()) { - memcpy(dest, src, size); - GlobalUnlock(destGlobal); + transfer.Flags |= k_SourceFlags_SetTargetFolder_NonEmpty; } - } - GlobalUnlock(srcGlobal); - return destGlobal; -} + 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; -STDMETHODIMP CDataObject::GetData(LPFORMATETC etc, LPSTGMEDIUM medium) -{ - RINOK(QueryGetData(etc)); + 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; - - CDropSource(): m_Effect(DROPEFFECT_NONE), Panel(NULL), NeedPostCopy(false), Result(S_OK) {} + HRESULT DragProcessing_HRESULT; + bool DragProcessing_WasFinished; + + 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()) - { - needExtract = false; - NeedPostCopy = true; - } - if (needExtract) - { - CCopyToOptions options; - options.folder = Folder; + // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) == 0"); + g_Debug = true; + } + else + { + // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0"); + } + */ - // 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); + 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; + } - /* HWND oldHwnd = */ SetCapture(*Panel); + if (DragProcessing_WasFinished) + return DragProcessing_HRESULT; - Result = Panel->CopyTo(options, Indices, &Messages); + if ((keyState & MK_RBUTTON) != 0) + { + if (!DataObjectSpec->IsRightButton) + { + DragProcessing_WasFinished = true; + DragProcessing_HRESULT = DRAGDROP_S_CANCEL; + return DRAGDROP_S_CANCEL; + } + return S_OK; + } + + if ((keyState & MK_LBUTTON) != 0) + { + if (DataObjectSpec->IsRightButton) + { + 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() */ - // 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 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na 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 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na 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 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na 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 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) // 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) */ 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) /* 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) 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 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) 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 @@ bool CDropTarget::IsItSameDrive() const 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 @@ bool CDropTarget::IsItSameDrive() const 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 @@ bool CDropTarget::IsItSameDrive() const 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) { - if (needDrop) + opEffect = DROPEFFECT_NONE; + cmdEffect = DROPEFFECT_NONE; + } + else + { + 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 --git a/CPP/7zip/UI/FileManager/PanelFolderChange.cpp b/CPP/7zip/UI/FileManager/PanelFolderChange.cpp index b91195f4..a13b88d0 100644 --- a/CPP/7zip/UI/FileManager/PanelFolderChange.cpp +++ b/CPP/7zip/UI/FileManager/PanelFolderChange.cpp @@ -133,8 +133,9 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO 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 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO 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 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO 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 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO _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 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO 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 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO 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 @@ bool CPanel::OnComboBoxCommand(UINT code, LPARAM /* param */, LRESULT &result) 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 @@ void CPanel::FoldersHistory() 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 @@ void CPanel::OpenParentFolder() 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 @@ void CPanel::OpenDrivesFolder() RefreshListCtrl(); } -void CPanel::OpenFolder(int index) +void CPanel::OpenFolder(unsigned index) { if (index == kParentIndex) { @@ -820,7 +854,7 @@ void CPanel::OpenFolder(int index) 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::OpenFolder(int index) 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 @@ void CPanel::OpenAltStreams() #if defined(_WIN32) && !defined(UNDER_CE) UString path; if (realIndex >= 0) - path = GetItemFullPath(realIndex); + path = GetItemFullPath((UInt32)realIndex); else { path = GetFsPath(); diff --git a/CPP/7zip/UI/FileManager/PanelItemOpen.cpp b/CPP/7zip/UI/FileManager/PanelItemOpen.cpp index 77b129ac..86b7f10f 100644 --- a/CPP/7zip/UI/FileManager/PanelItemOpen.cpp +++ b/CPP/7zip/UI/FileManager/PanelItemOpen.cpp @@ -7,6 +7,7 @@ #include #include "../../../Common/IntToString.h" +#include "../../../Common/MyString.h" #include "../../../Common/AutoPtr.h" #include "../../../Common/StringConvert.h" @@ -68,7 +69,7 @@ class CProcessSnapshot { HANDLE _handle; public: - CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {}; + CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {} ~CProcessSnapshot() { Close(); } bool Close() @@ -136,7 +137,7 @@ class CPossibleProgs 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 +221,25 @@ static void My_GetProcessFileName(HANDLE hProcess, UString &path) 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 +322,13 @@ class CChildProcesses 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 +468,7 @@ HRESULT CPanel::OpenAsArc(IInStream *inStream, 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 +477,14 @@ HRESULT CPanel::OpenAsArc(IInStream *inStream, 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 +577,7 @@ HRESULT CPanel::OpenAsArc_Name(const UString &relPath, const UString &arcFormat } -HRESULT CPanel::OpenAsArc_Index(int index, const wchar_t *type +HRESULT CPanel::OpenAsArc_Index(unsigned index, const wchar_t *type // , bool showErrorMessage ) { @@ -653,36 +659,13 @@ static const char * const kStartExtensions = " 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); } void SplitCmdLineSmart(const UString &cmd, UString &prg, UString ¶ms); @@ -751,10 +734,10 @@ static HRESULT StartEditApplication(const UString &path, bool useEditor, HWND wi 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); } @@ -769,7 +752,7 @@ void CApp::DiffFiles() } CRecordVector indices; - panel.GetSelectedItemsIndices(indices); + panel.Get_ItemIndices_Selected(indices); UString path1, path2; if (indices.Size() == 2) @@ -789,7 +772,7 @@ void CApp::DiffFiles() 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 @@ -817,19 +800,19 @@ void CApp::DiffFiles(const UString &path1, const UString &path2) 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) @@ -841,7 +824,7 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi int dot = path2.ReverseFind_Dot(); int separ = path2.ReverseFind_PathSepar(); if (dot < 0 || dot < separ) - path2 += '.'; + path2.Add_Dot(); } #endif @@ -859,12 +842,15 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi 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); } @@ -892,7 +878,7 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi #endif ; execInfo.nShow = SW_SHOWNORMAL; - execInfo.hProcess = 0; + execInfo.hProcess = NULL; ::ShellExecuteEx(&execInfo); result = (UINT32)(UINT_PTR)execInfo.hInstApp; process.Attach(execInfo.hProcess); @@ -924,7 +910,7 @@ static void StartApplicationDontWait(const UString &dir, const UString &path, HW StartApplication(dir, path, window, process); } -void CPanel::EditItem(int index, bool useEditor) +void CPanel::EditItem(unsigned index, bool useEditor) { if (!_parentFolders.IsEmpty()) { @@ -936,7 +922,7 @@ void CPanel::EditItem(int index, bool useEditor) } -void CPanel::OpenFolderExternal(int index) +void CPanel::OpenFolderExternal(unsigned index) { UString prefix = GetFsPath(); UString path = prefix; @@ -1007,9 +993,10 @@ bool CPanel::IsVirus_Message(const UString &name) } if (i != name2.Len()) { + CStringFinder finder; UString name3 = name2; name3.DeleteFrom(i); - if (FindExt(kExeExtensions, name3)) + if (FindExt(kExeExtensions, name3, finder)) isVirus = true; } } @@ -1022,13 +1009,13 @@ bool CPanel::IsVirus_Message(const UString &name) 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); } @@ -1047,10 +1034,10 @@ bool CPanel::IsVirus_Message(const UString &name) } -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)) @@ -1093,7 +1080,7 @@ void CPanel::OpenItem(int index, bool tryInternal, bool tryExternal, const wchar class CThreadCopyFrom: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: UString FullPath; UInt32 ItemIndex; @@ -1130,7 +1117,7 @@ HRESULT CPanel::OnOpenItemChanged(UInt32 index, const wchar_t *fullFilePath, t.UpdateCallbackSpec->Password = password; - RINOK(t.Create(GetItemName(index), (HWND)*this)); + RINOK(t.Create(GetItemName(index), (HWND)*this)) return t.Result; } @@ -1289,7 +1276,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param) if (firstPass && indices.Size() == 1) { - DWORD curTime = GetTickCount() - startTime; + const DWORD curTime = GetTickCount() - startTime; /* if (curTime > 5 * 1000) @@ -1309,7 +1296,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param) DEBUG_PRINT_NUM(" -- firstPass -- time = ", curTime) } - processes.DisableWait(indices[waitResult]); + processes.DisableWait(indices[(unsigned)waitResult]); } firstPass = false; @@ -1321,7 +1308,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param) } - DWORD curTime = GetTickCount() - startTime; + const DWORD curTime = GetTickCount() - startTime; DEBUG_PRINT_NUM("after time = ", curTime) @@ -1441,15 +1428,14 @@ static bool WriteZoneFile(CFSTR fileName, const CByteBuffer &buf) */ /* -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: @@ -1475,9 +1461,6 @@ class CBufSeqOutStream_WithFile: 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); @@ -1562,7 +1545,7 @@ tryInternal tryExternal 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()) @@ -1827,7 +1810,7 @@ void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bo // win7 / win10 work so for some extensions (pdf, html ..); DEBUG_PRINT("#### (HANDLE)process == 0"); // return; - if (res != SZ_OK) + if (res != S_OK) return; } @@ -1836,7 +1819,7 @@ void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bo tpi->FileIndex = index; tpi->RelPath = relPath; - if ((HANDLE)process != 0) + if ((HANDLE)process) tpi->Processes.SetMainProcess(process.Detach()); ::CThread th; diff --git a/CPP/7zip/UI/FileManager/PanelItems.cpp b/CPP/7zip/UI/FileManager/PanelItems.cpp index 3cccf27e..0cb33d8b 100644 --- a/CPP/7zip/UI/FileManager/PanelItems.cpp +++ b/CPP/7zip/UI/FileManager/PanelItems.cpp @@ -41,7 +41,7 @@ static bool GetColumnVisible(PROPID propID, bool isFsFolder) return true; } -static int GetColumnWidth(PROPID propID, VARTYPE /* varType */) +static unsigned GetColumnWidth(PROPID propID, VARTYPE /* varType */) { switch (propID) { @@ -216,7 +216,7 @@ HRESULT CPanel::InitColumns() item.IsVisible = isVisible; item.Width = columnInfo.Width; if (isVisible) - item.Order = order++; + item.Order = (int)(order++); continue; } } @@ -225,14 +225,14 @@ HRESULT CPanel::InitColumns() { 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 @@ HRESULT CPanel::InitColumns() { 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::DeleteColumn(unsigned index) 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 @@ int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData); 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 @@ void CPanel::GetSelectedNames(UStringVector &selectedNames) 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 @@ void CPanel::SaveSelectedState(CSelectedState &s) { 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(const CSelectedState &s) } */ -HRESULT CPanel::RefreshListCtrl_SaveFocused() +HRESULT CPanel::RefreshListCtrl_SaveFocused(bool onTimer) { CSelectedState state; SaveSelectedState(state); + state.CalledFromTimer = onTimer; return RefreshListCtrl(state); } @@ -437,7 +438,7 @@ void CPanel::SetFocusedSelectedItem(int index, bool select) _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 @@ extern UInt32 g_NumMessages; HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) { + m_DropHighlighted_SelectionIndex = -1; + m_DropHighlighted_SubFolderName.Empty(); + if (!_folder) return S_OK; @@ -474,7 +478,8 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) */ _dontShowMode = false; - LoadFullPathAndShow(); + if (!state.CalledFromTimer) + LoadFullPathAndShow(); // OutputDebugStringA("=======\n"); // OutputDebugStringA("s1 \n"); CDisableTimerProcessing timerProcessing(*this); @@ -506,11 +511,13 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) // m_Files.Clear(); + /* if (!_folder) { // throw 1; SetToRootFolder(); } + */ _headerToolBar.EnableButton(kParentFolderID, !IsRootFolder()); @@ -530,16 +537,44 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) } */ + _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 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) 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 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) item.iItem = listViewItemCount; item.iSubItem = subItem++; - item.lParam = i; + item.lParam = (LPARAM)i; /* int finish = nameLen - 4; @@ -731,7 +766,7 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) 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 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) } -void CPanel::GetSelectedItemsIndices(CRecordVector &indices) const +void CPanel::Get_ItemIndices_Selected(CRecordVector &indices) const { indices.Clear(); /* @@ -858,46 +893,49 @@ void CPanel::GetSelectedItemsIndices(CRecordVector &indices) const 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 @@ void CPanel::GetOperatedListViewIndices(CRecordVector &indices) const 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 @@ void CPanel::EditItem(bool useEditor) { bool needRefresh = false; CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); FOR_VECTOR (i, indices) { UInt32 index = indices[i]; @@ -952,10 +990,10 @@ void CPanel::EditItem(bool useEditor) } - 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::EditItem(bool useEditor) 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::OpenFocusedItemAsInternal(const wchar_t *type) 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 @@ void CPanel::OpenSelectedItems(bool tryInternal) } } -UString CPanel::GetItemName(int itemIndex) const +UString CPanel::GetItemName(unsigned itemIndex) const { if (itemIndex == kParentIndex) return L".."; @@ -1028,7 +1066,7 @@ UString CPanel::GetItemName(int itemIndex) const 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 @@ UString CPanel::GetItemName_for_Copy(int itemIndex) const 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 @@ void CPanel::GetItemName(int itemIndex, UString &s) const 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 @@ UString CPanel::GetItemPrefix(int itemIndex) const 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 @@ UString CPanel::GetItemRelPath2(int itemIndex) const 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 @@ bool CPanel::GetItem_BoolProp(UInt32 itemIndex, PROPID propID) const 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 @@ UInt64 CPanel::GetItem_UInt64Prop(int itemIndex, PROPID propID) const return 0; } -UInt64 CPanel::GetItemSize(int itemIndex) const +UInt64 CPanel::GetItemSize(unsigned itemIndex) const { if (itemIndex == kParentIndex) return 0; @@ -1169,7 +1252,7 @@ void CPanel::SaveListViewInfo() 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 @@ void CPanel::ShowColumnsContextMenu(int x, int y) 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 @@ void CPanel::ShowColumnsContextMenu(int x, int y) _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 @@ void CPanel::OnTimer() return; if (wasChanged == 0) return; - OnReload(); + OnReload(true); // onTimer } diff --git a/CPP/7zip/UI/FileManager/PanelKey.cpp b/CPP/7zip/UI/FileManager/PanelKey.cpp index b4130c6b..b67dcf59 100644 --- a/CPP/7zip/UI/FileManager/PanelKey.cpp +++ b/CPP/7zip/UI/FileManager/PanelKey.cpp @@ -29,9 +29,9 @@ static const CVKeyPropIDPair g_VKeyPropIDPairs[] = 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 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result) _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 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result) } 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 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result) 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); } @@ -317,6 +319,14 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result) return true; } return false; + case 'W': + if (ctrl) + { + // SendMessage(); + PostMessage(g_HWND, WM_COMMAND, IDCLOSE, 0); + return true; + } + return false; case 'Z': if (ctrl) { @@ -330,7 +340,7 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result) case '4': if (ctrl) { - int styleIndex = keyDownInfo->wVKey - '1'; + const unsigned styleIndex = (unsigned)(keyDownInfo->wVKey - '1'); SetListViewMode(styleIndex); return true; } diff --git a/CPP/7zip/UI/FileManager/PanelListNotify.cpp b/CPP/7zip/UI/FileManager/PanelListNotify.cpp index d2114f1c..2fb0e873 100644 --- a/CPP/7zip/UI/FileManager/PanelListNotify.cpp +++ b/CPP/7zip/UI/FileManager/PanelListNotify.cpp @@ -289,8 +289,8 @@ LRESULT CPanel::SetItemText(LVITEMW &item) 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 @@ LRESULT CPanel::SetItemText(LVITEMW &item) 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 @@ LRESULT CPanel::SetItemText(LVITEMW &item) 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 @@ LRESULT CPanel::SetItemText(LVITEMW &item) } } - HRESULT res = _folder->GetProperty(realIndex, propID, &prop); + const HRESULT res = _folder->GetProperty(realIndex, propID, &prop); if (res != S_OK) { @@ -517,7 +517,7 @@ LRESULT CPanel::SetItemText(LVITEMW &item) } 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 @@ LRESULT CPanel::SetItemText(LVITEMW &item) 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 @@ extern DWORD g_ComCtl32Version; 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 @@ bool CPanel::OnNotifyList(LPNMHDR header, LRESULT &result) } 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 @@ bool CPanel::OnCustomDraw(LPNMLVCUSTOMDRAW lplvcd, LRESULT &result) 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 @@ void CPanel::Refresh_StatusBar() // DWORD dw = GetTickCount(); CRecordVector indices; - GetOperatedItemIndices(indices); - - wchar_t temp[32]; - ConvertUInt32ToString(indices.Size(), temp); - wcscat(temp, L" / "); - ConvertUInt32ToString(_selectedStatusVector.Size(), temp + wcslen(temp)); - - // 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()))); + Get_ItemIndices_Operated(indices); - wchar_t selectSizeString[32]; - selectSizeString[0] = 0; + { + UString s; + s.Add_UInt32(indices.Size()); + s += " / "; + s.Add_UInt32(_selectedStatusVector.Size()); + + // 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 --git a/CPP/7zip/UI/FileManager/PanelMenu.cpp b/CPP/7zip/UI/FileManager/PanelMenu.cpp index 9e86951c..f0afe15d 100644 --- a/CPP/7zip/UI/FileManager/PanelMenu.cpp +++ b/CPP/7zip/UI/FileManager/PanelMenu.cpp @@ -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 @@ LONG g_DllRefCount = 0; 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 @@ void CPanel::Properties() // message.SelectFirst = false; CRecordVector operatedIndices; - GetOperatedItemIndices(operatedIndices); + Get_ItemIndices_Operated(operatedIndices); if (operatedIndices.Size() == 1) { @@ -346,7 +368,7 @@ void CPanel::Properties() 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 @@ void CPanel::Properties() 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 @@ void CPanel::Properties() 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 @@ void CPanel::Properties() { // 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 @@ void CPanel::EditCopy() */ UString s; CRecordVector indices; - GetSelectedItemsIndices(indices); + Get_ItemIndices_Selected(indices); FOR_VECTOR (i, indices) { if (i != 0) @@ -486,15 +508,25 @@ struct CFolderPidls }; +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 @@ HRESULT CPanel::CreateShellContextMenu( } 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 @@ HRESULT CPanel::CreateShellContextMenu( 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 @@ HRESULT CPanel::CreateShellContextMenu( 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 PrintHex(UString &s, UInt32 v) 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 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned } 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 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned } s2 += buf2; } - s += s1; if (s2.Compare(s1) != 0) { @@ -637,7 +684,6 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned } } - static void PrintAllContextItems(IContextMenu *ctxm, unsigned num) { for (unsigned i = 0; i < num; i++) @@ -645,35 +691,18 @@ static void PrintAllContextItems(IContextMenu *ctxm, unsigned num) 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 @@ void CPanel::CreateSystemMenu(HMENU menuSpec, 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::CreateSystemMenu(HMENU menuSpec, 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 @@ void CPanel::CreateSevenZipMenu(HMENU menuSpec, 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 @@ void CPanel::CreateSevenZipMenu(HMENU menuSpec, { // MessageBox_Error_HRESULT_Caption(res, L"QueryContextMenu"); } - // int code = HRESULT_CODE(res); // int nextItemID = code; } @@ -917,19 +942,22 @@ void CPanel::CreateFileMenu(HMENU menuSpec, 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 @@ void CPanel::CreateFileMenu(HMENU menuSpec, 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 @@ void CPanel::CreateFileMenu(HMENU menuSpec, { 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 @@ void CPanel::CreateFileMenu(HMENU menuSpec, 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 @@ bool CPanel::InvokePluginCommand(unsigned id) #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 @@ bool CPanel::OnContextMenu(HANDLE windowHandle, int xPos, int yPos) */ 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 @@ bool CPanel::OnContextMenu(HANDLE windowHandle, int xPos, int yPos) 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 --git a/CPP/7zip/UI/FileManager/PanelOperations.cpp b/CPP/7zip/UI/FileManager/PanelOperations.cpp index a683b5ea..b61f4e91 100644 --- a/CPP/7zip/UI/FileManager/PanelOperations.cpp +++ b/CPP/7zip/UI/FileManager/PanelOperations.cpp @@ -24,9 +24,6 @@ using namespace NWindows; 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 @@ enum EFolderOpType class CThreadFolderOperations: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: EFolderOpType OpType; UString Name; @@ -58,7 +55,7 @@ class CThreadFolderOperations: public CProgressThreadVirt 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 @@ HRESULT CThreadFolderOperations::DoOperation(CPanel &panel, const UString &progr MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE); MainAddTitle = progressTitle + L' '; - RINOK(Create(progressTitle, MainWindow)); + RINOK(Create(progressTitle, MainWindow)) return Result; } @@ -116,7 +113,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) { CDisableTimerProcessing disableTimerProcessing(*this); CRecordVector indices; - GetOperatedItemIndices(indices); + Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; CSelectedState state; @@ -141,7 +138,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) 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 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) // 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 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) 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 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) 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 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin)) 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 @@ BOOL CPanel::OnEndLabelEdit(LV_DISPINFOW * lpnmh) 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 @@ void CPanel::CreateFile() 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 @@ void CPanel::ChangeComment() 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 @@ void CPanel::ChangeComment() 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 @@ void CPanel::ChangeComment() 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 --git a/CPP/7zip/UI/FileManager/PanelSelect.cpp b/CPP/7zip/UI/FileManager/PanelSelect.cpp index eab9e1ab..f7a16dd5 100644 --- a/CPP/7zip/UI/FileManager/PanelSelect.cpp +++ b/CPP/7zip/UI/FileManager/PanelSelect.cpp @@ -15,7 +15,7 @@ void CPanel::OnShiftSelectMessage() { if (!_mySelectMode) return; - int focusedItem = _listView.GetFocusedItem(); + const int focusedItem = _listView.GetFocusedItem(); if (focusedItem < 0) return; if (!_selectionIsDefined) @@ -26,7 +26,7 @@ void CPanel::OnShiftSelectMessage() 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 @@ void CPanel::OnArrowWithShift() { 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 @@ void CPanel::OnInsert() // _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::OnInsert() /* 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::OnUpWithShift() 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 @@ void CPanel::UpdateSelection() 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::SelectSpec(bool selectMode) 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 @@ void CPanel::InvertSelection() { 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 @@ void CPanel::InvertSelection() 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 @@ void CPanel::KillSelection() { // 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 @@ void CPanel::OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate) 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 @@ void CPanel::OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate) #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 --git a/CPP/7zip/UI/FileManager/PanelSort.cpp b/CPP/7zip/UI/FileManager/PanelSort.cpp index d26acb70..f95f8ee9 100644 --- a/CPP/7zip/UI/FileManager/PanelSort.cpp +++ b/CPP/7zip/UI/FileManager/PanelSort.cpp @@ -52,8 +52,8 @@ int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2) 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 int CompareFileNames_Le16(const Byte *s1, unsigned size1, const Byte *s2, 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 @@ static int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData) // 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 @@ static int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData) } 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); 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 --git a/CPP/7zip/UI/FileManager/PanelSplitFile.cpp b/CPP/7zip/UI/FileManager/PanelSplitFile.cpp index 00a0d801..64aa0397 100644 --- a/CPP/7zip/UI/FileManager/PanelSplitFile.cpp +++ b/CPP/7zip/UI/FileManager/PanelSplitFile.cpp @@ -30,7 +30,7 @@ struct CVolSeqName { UString UnchangedPart; UString ChangedPart; - CVolSeqName(): ChangedPart("000") {}; + CVolSeqName(): ChangedPart("000") {} void SetNumDigits(UInt64 numVolumes) { @@ -64,13 +64,13 @@ UString CVolSeqName::GetNextName() { 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 @@ UString CVolSeqName::GetNextName() class CThreadSplit: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: FString FilePath; FString VolBasePath; @@ -142,7 +142,7 @@ HRESULT CThreadSplit::ProcessVirt() { NIO::CInFile inFile; if (!inFile.Open(FilePath)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); CPreAllocOutFile outFile; @@ -155,7 +155,7 @@ HRESULT CThreadSplit::ProcessVirt() UInt64 length; if (!inFile.GetLength(length)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); CProgressSync &sync = Sync; sync.Set_NumBytesTotal(length); @@ -181,7 +181,7 @@ HRESULT CThreadSplit::ProcessVirt() } 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 @@ HRESULT CThreadSplit::ProcessVirt() 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 @@ HRESULT CThreadSplit::ProcessVirt() } if (!outFile.Write(buffer, needSize, processedSize)) - return GetLastError(); + return GetLastError_noZero_HRESULT(); if (needSize != processedSize) throw g_Message_FileWriteError; @@ -225,7 +225,7 @@ HRESULT CThreadSplit::ProcessVirt() 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 @@ HRESULT CThreadSplit::ProcessVirt() void CApp::Split() { - int srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.Is_IO_FS_Folder()) { @@ -242,7 +242,7 @@ void CApp::Split() return; } CRecordVector indices; - srcPanel.GetOperatedItemIndices(indices); + srcPanel.Get_ItemIndices_Operated(indices); if (indices.IsEmpty()) return; if (indices.Size() != 1) @@ -250,7 +250,7 @@ void CApp::Split() 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 @@ void CApp::Split() } 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 @@ void CApp::Split() 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 @@ void CApp::Split() 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 @@ void CApp::Split() class CThreadCombine: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: FString InputDirPrefix; FStringVector Names; @@ -357,7 +357,7 @@ HRESULT CThreadCombine::ProcessVirt() 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 @@ HRESULT CThreadCombine::ProcessVirt() 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 @@ HRESULT CThreadCombine::ProcessVirt() 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 @@ static void AddInfoFileName(UString &dest, const UString &name) void CApp::Combine() { - int srcPanelIndex = GetFocusedPanelIndex(); + const unsigned srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.IsFSFolder()) { @@ -426,10 +426,10 @@ void CApp::Combine() 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 @@ void CApp::Combine() 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 @@ void CApp::Combine() 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 --git a/CPP/7zip/UI/FileManager/PasswordDialog.cpp b/CPP/7zip/UI/FileManager/PasswordDialog.cpp index 6ead39c3..bf995802 100644 --- a/CPP/7zip/UI/FileManager/PasswordDialog.cpp +++ b/CPP/7zip/UI/FileManager/PasswordDialog.cpp @@ -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 @@ void CPasswordDialog::SetTextSpec() 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 @@ bool CPasswordDialog::OnInit() return CModalDialog::OnInit(); } -bool CPasswordDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CPasswordDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { if (buttonID == IDX_PASSWORD_SHOW) { diff --git a/CPP/7zip/UI/FileManager/PasswordDialog.h b/CPP/7zip/UI/FileManager/PasswordDialog.h index 339ebdaf..e05c4adf 100644 --- a/CPP/7zip/UI/FileManager/PasswordDialog.h +++ b/CPP/7zip/UI/FileManager/PasswordDialog.h @@ -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 @@ class CPasswordDialog: public NWindows::NControl::CModalDialog { 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 @@ class CPasswordDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/FileManager/PluginInterface.h b/CPP/7zip/UI/FileManager/PluginInterface.h index 37654a03..dcb1b4b8 100644 --- a/CPP/7zip/UI/FileManager/PluginInterface.h +++ b/CPP/7zip/UI/FileManager/PluginInterface.h @@ -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) - -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_IFACE_CONSTR_PLUGIN(i, n) \ + Z7_DECL_IFACE_7ZIP(i, 0x0A, n) \ + { Z7_IFACE_COM7_PURE(i) }; + +#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 --git a/CPP/7zip/UI/FileManager/PluginLoader.h b/CPP/7zip/UI/FileManager/PluginLoader.h index fed38d65..d9309f23 100644 --- a/CPP/7zip/UI/FileManager/PluginLoader.h +++ b/CPP/7zip/UI/FileManager/PluginLoader.h @@ -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 @@ class CPluginLibrary: public NWindows::NDLL::CLibrary 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 --git a/CPP/7zip/UI/FileManager/ProgramLocation.h b/CPP/7zip/UI/FileManager/ProgramLocation.h index 6bfb711e..0cd9c747 100644 --- a/CPP/7zip/UI/FileManager/ProgramLocation.h +++ b/CPP/7zip/UI/FileManager/ProgramLocation.h @@ -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 --git a/CPP/7zip/UI/FileManager/ProgressDialog.cpp b/CPP/7zip/UI/FileManager/ProgressDialog.cpp index b688a901..fc6f5599 100644 --- a/CPP/7zip/UI/FileManager/ProgressDialog.cpp +++ b/CPP/7zip/UI/FileManager/ProgressDialog.cpp @@ -15,7 +15,7 @@ extern HINSTANCE g_hInstance; static const UINT_PTR kTimerID = 3; static const UINT kTimerElapse = 100; -#ifdef LANG +#ifdef Z7_LANG #include "LangUtils.h" #endif @@ -32,7 +32,7 @@ HRESULT CProgressSync::ProcessStopAndPause() return S_OK; } -#ifndef _SFX +#ifndef Z7_SFX CProgressDialog::~CProgressDialog() { AddToTitle(L""); @@ -45,15 +45,17 @@ void CProgressDialog::AddToTitle(LPCWSTR s) #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 @@ bool CProgressDialog::OnTimer(WPARAM /* timerID */, LPARAM /* callback */) 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 @@ bool CProgressDialog::OnTimer(WPARAM /* timerID */, LPARAM /* callback */) UString title = s; title += "% "; SetText(title + _title); - #ifndef _SFX + #ifndef Z7_SFX AddToTitle(title + MainAddTitle); #endif _prevPercentValue = percentValue; @@ -159,7 +161,7 @@ bool CProgressDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) return CModalDialog::OnMessage(message, wParam, lParam); } -bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff --git a/CPP/7zip/UI/FileManager/ProgressDialog.h b/CPP/7zip/UI/FileManager/ProgressDialog.h index 35c182a8..1fe9587a 100644 --- a/CPP/7zip/UI/FileManager/ProgressDialog.h +++ b/CPP/7zip/UI/FileManager/ProgressDialog.h @@ -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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog CProgressSync Sync; int IconID; - #ifndef _SFX + #ifndef Z7_SFX HWND MainWindow; UString MainTitle; UString MainAddTitle; @@ -119,8 +122,8 @@ class CProgressDialog: public NWindows::NControl::CModalDialog #endif CProgressDialog(): _timer(0) - #ifndef _SFX - ,MainWindow(0) + #ifndef Z7_SFX + ,MainWindow(NULL) #endif { IconID = -1; @@ -133,7 +136,7 @@ class CProgressDialog: public NWindows::NControl::CModalDialog 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog kCloseMessage = WM_APP + 1 }; - virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); - void ProcessWasFinished() { WaitCreating(); @@ -155,7 +156,7 @@ class CProgressDialog: public NWindows::NControl::CModalDialog PostMsg(kCloseMessage); else _needClose = true; - }; + } }; diff --git a/CPP/7zip/UI/FileManager/ProgressDialog2.cpp b/CPP/7zip/UI/FileManager/ProgressDialog2.cpp index 54273d0c..1521d83c 100644 --- a/CPP/7zip/UI/FileManager/ProgressDialog2.cpp +++ b/CPP/7zip/UI/FileManager/ProgressDialog2.cpp @@ -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 UINT kCreateDelay = static const DWORD kPauseSleepTime = 100; -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { @@ -67,19 +71,19 @@ static const UInt32 kLangIDs_Colon[] = #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 @@ void CProgressSync::AddError_Message_Name(const wchar_t *message, const wchar_t 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 @@ CProgressDialog::CProgressDialog(): 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::AddToTitle(LPCWSTR s) void CProgressDialog::SetTaskbarProgressState() { - #ifdef __ITaskbarList3_INTERFACE_DEFINED__ + // #ifdef __ITaskbarList3_INTERFACE_DEFINED__ if (_taskbarList && _hwndForTaskbar) { TBPFLAG tbpFlags; @@ -302,7 +306,7 @@ void CProgressDialog::SetTaskbarProgressState() tbpFlags = _errorsWereDisplayed ? TBPF_ERROR: TBPF_NORMAL; SetTaskbarProgressState(tbpFlags); } - #endif + // #endif } static const unsigned kTitleFileNameSizeLimit = 36; @@ -331,23 +335,23 @@ bool CProgressDialog::OnInit() 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 @@ bool CProgressDialog::OnInit() _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 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) { 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 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 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 @@ void CProgressDialog::SetProgressRange(UInt64 range) 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 @@ void CProgressDialog::SetProgressPos(UInt64 pos) 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 @@ void GetTimeString(UInt64 timeValue, wchar_t *s) 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 @@ static void ConvertSizeToString(UInt64 v, wchar_t *s) } } -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 @@ void CProgressDialog::UpdateStatInfo(bool showAll) { if (IS_DEFINED_VAL(_prevRemainingSec)) { - INIT_AS_UNDEFINED(_prevRemainingSec); + INIT_AS_UNDEFINED(_prevRemainingSec) SetItemText(IDT_PROGRESS_REMAINING_VAL, L""); } } @@ -790,8 +794,9 @@ void CProgressDialog::UpdateStatInfo(bool showAll) } } { - 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 @@ INT_PTR CProgressDialog::Create(const UString &title, NWindows::CThread &thread, 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 @@ INT_PTR CProgressDialog::Create(const UString &title, NWindows::CThread &thread, 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 @@ void CProgressDialog::SetTitleText() } s.Add_Space(); - #ifndef _SFX + #ifndef Z7_SFX { unsigned len = s.Len(); s += MainAddTitle; @@ -1150,9 +1155,9 @@ void CProgressDialog::AddMessageDirect(LPCWSTR message, bool needNumber) 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 @@ void CProgressDialog::AddMessage(LPCWSTR message) 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 @@ void CProgressDialog::UpdateMessagesDialog() } -bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -1340,7 +1345,7 @@ static void ListView_GetSelected(NControl::CListView &listView, CUIntVector &vec index = listView.GetNextSelectedItem(index); if (index < 0) break; - vector.Add(index); + vector.Add((unsigned)index); } } @@ -1352,7 +1357,7 @@ void CProgressDialog::CopyToClipboard() 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 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param) 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 @@ void CProgressThreadVirt::Process() catch(int v) { m = "Error #"; - m.Add_UInt32(v); + m.Add_UInt32((unsigned)v); } catch(...) { m = "Error"; } if (Result != E_ABORT) diff --git a/CPP/7zip/UI/FileManager/ProgressDialog2.h b/CPP/7zip/UI/FileManager/ProgressDialog2.h index d8259d6a..4ca9be7a 100644 --- a/CPP/7zip/UI/FileManager/ProgressDialog2.h +++ b/CPP/7zip/UI/FileManager/ProgressDialog2.h @@ -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 @@ class CProgressSync public: bool _bytesProgressMode; + bool _isDir; UInt64 _totalBytes; UInt64 _completedBytes; UInt64 _totalFiles; @@ -46,7 +47,6 @@ class CProgressSync UString _titleFileName; UString _status; UString _filePath; - bool _isDir; UStringVector Messages; CProgressFinalMessage FinalMessage; @@ -96,7 +96,8 @@ class CProgressSync 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog 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 @@ class CProgressDialog: public NWindows::NControl::CModalDialog int IconID; HWND MainWindow; - #ifndef _SFX + #ifndef Z7_SFX UString MainTitle; UString MainAddTitle; - ~CProgressDialog(); + ~CProgressDialog() Z7_DESTRUCTOR_override; #endif CProgressDialog(); @@ -265,7 +266,7 @@ class CProgressDialog: public NWindows::NControl::CModalDialog _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 @@ class CProgressThreadVirt: public CProgressDialog 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 --git a/CPP/7zip/UI/FileManager/PropertyName.h b/CPP/7zip/UI/FileManager/PropertyName.h index 4f0d6dc1..fa6e5c54 100644 --- a/CPP/7zip/UI/FileManager/PropertyName.h +++ b/CPP/7zip/UI/FileManager/PropertyName.h @@ -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 --git a/CPP/7zip/UI/FileManager/PropertyName.rc b/CPP/7zip/UI/FileManager/PropertyName.rc index e16c526f..618875bf 100644 --- a/CPP/7zip/UI/FileManager/PropertyName.rc +++ b/CPP/7zip/UI/FileManager/PropertyName.rc @@ -104,4 +104,6 @@ BEGIN 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 --git a/CPP/7zip/UI/FileManager/PropertyNameRes.h b/CPP/7zip/UI/FileManager/PropertyNameRes.h index e3d08db9..913887e4 100644 --- a/CPP/7zip/UI/FileManager/PropertyNameRes.h +++ b/CPP/7zip/UI/FileManager/PropertyNameRes.h @@ -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 --git a/CPP/7zip/UI/FileManager/RegistryAssociations.cpp b/CPP/7zip/UI/FileManager/RegistryAssociations.cpp index 340a11db..88fba2bb 100644 --- a/CPP/7zip/UI/FileManager/RegistryAssociations.cpp +++ b/CPP/7zip/UI/FileManager/RegistryAssociations.cpp @@ -65,18 +65,18 @@ bool CShellExtInfo::ReadFromRegistry(HKEY hkey, const CSysString &ext) 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 --git a/CPP/7zip/UI/FileManager/RegistryAssociations.h b/CPP/7zip/UI/FileManager/RegistryAssociations.h index 975c9d5f..3d7b63db 100644 --- a/CPP/7zip/UI/FileManager/RegistryAssociations.h +++ b/CPP/7zip/UI/FileManager/RegistryAssociations.h @@ -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 --git a/CPP/7zip/UI/FileManager/RegistryPlugins.cpp b/CPP/7zip/UI/FileManager/RegistryPlugins.cpp index 76a5787c..87e5fa16 100644 --- a/CPP/7zip/UI/FileManager/RegistryPlugins.cpp +++ b/CPP/7zip/UI/FileManager/RegistryPlugins.cpp @@ -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 --git a/CPP/7zip/UI/FileManager/RegistryPlugins.h b/CPP/7zip/UI/FileManager/RegistryPlugins.h index dfa6de54..1cb765a8 100644 --- a/CPP/7zip/UI/FileManager/RegistryPlugins.h +++ b/CPP/7zip/UI/FileManager/RegistryPlugins.h @@ -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 @@ enum EPluginType 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 --git a/CPP/7zip/UI/FileManager/RegistryUtils.cpp b/CPP/7zip/UI/FileManager/RegistryUtils.cpp index c8e7f933..5cb15439 100644 --- a/CPP/7zip/UI/FileManager/RegistryUtils.cpp +++ b/CPP/7zip/UI/FileManager/RegistryUtils.cpp @@ -161,6 +161,11 @@ void CFmSettings::Load() { 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 --git a/CPP/7zip/UI/FileManager/RegistryUtils.h b/CPP/7zip/UI/FileManager/RegistryUtils.h index 9d26aea3..e56fbdee 100644 --- a/CPP/7zip/UI/FileManager/RegistryUtils.h +++ b/CPP/7zip/UI/FileManager/RegistryUtils.h @@ -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 --git a/CPP/7zip/UI/FileManager/RootFolder.cpp b/CPP/7zip/UI/FileManager/RootFolder.cpp index 84844c7d..34dd6381 100644 --- a/CPP/7zip/UI/FileManager/RootFolder.cpp +++ b/CPP/7zip/UI/FileManager/RootFolder.cpp @@ -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 @@ void CRootFolder::Init() #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 @@ STDMETHODIMP CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIA 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 @@ static UString GetMyDocsPath() 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 @@ STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolde { 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 @@ STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolde { NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; subFolder = fsFolderSpec; - RINOK(fsFolderSpec->Init(us2fs(s))); + RINOK(fsFolderSpec->Init(us2fs(s))) } } #else @@ -202,9 +209,9 @@ static bool AreEqualNames(const UString &path, const wchar_t *name) 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 @@ STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resu 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 @@ STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resu 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 @@ STDMETHODIMP CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 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 --git a/CPP/7zip/UI/FileManager/RootFolder.h b/CPP/7zip/UI/FileManager/RootFolder.h index e2537837..3f0a31b3 100644 --- a/CPP/7zip/UI/FileManager/RootFolder.h +++ b/CPP/7zip/UI/FileManager/RootFolder.h @@ -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 --git a/CPP/7zip/UI/FileManager/SettingsPage.cpp b/CPP/7zip/UI/FileManager/SettingsPage.cpp index 662a44d0..fc6f1bbd 100644 --- a/CPP/7zip/UI/FileManager/SettingsPage.cpp +++ b/CPP/7zip/UI/FileManager/SettingsPage.cpp @@ -20,6 +20,7 @@ using namespace NWindows; +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { IDX_SETTINGS_SHOW_DOTS, @@ -37,6 +38,7 @@ static const UInt32 kLangIDs[] = IDX_SETTINGS_LOWERCASE_HASHES // , IDT_COMPRESS_MEMORY }; +#endif #define kSettingsTopic "FM/options.htm#settings" @@ -117,7 +119,9 @@ bool CSettingsPage::OnInit() _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(); @@ -240,7 +244,7 @@ LONG CSettingsPage::OnApply() { if (IsLargePageSupported()) { - bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); + const bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); NSecurity::EnablePrivilege_LockMemory(enable); SaveLockMemoryEnable(enable); } @@ -316,7 +320,7 @@ void CSettingsPage::OnNotifyHelp() } /* -bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param) +bool CSettingsPage::OnCommand(unsigned code, unsigned itemID, LPARAM param) { if (code == CBN_SELCHANGE) { @@ -334,7 +338,7 @@ bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param) } */ -bool CSettingsPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSettingsPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff --git a/CPP/7zip/UI/FileManager/SettingsPage.h b/CPP/7zip/UI/FileManager/SettingsPage.h index f3f57a4b..91b9828b 100644 --- a/CPP/7zip/UI/FileManager/SettingsPage.h +++ b/CPP/7zip/UI/FileManager/SettingsPage.h @@ -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 @@ class CSettingsPage: public NWindows::NControl::CPropertyPage */ // 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 --git a/CPP/7zip/UI/FileManager/SplitDialog.cpp b/CPP/7zip/UI/FileManager/SplitDialog.cpp index 0c9fdd17..21d812c5 100644 --- a/CPP/7zip/UI/FileManager/SplitDialog.cpp +++ b/CPP/7zip/UI/FileManager/SplitDialog.cpp @@ -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 @@ static const UInt32 kLangIDs[] = 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 @@ bool CSplitDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) return false; } -bool CSplitDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSplitDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -91,7 +89,7 @@ void CSplitDialog::OnButtonSetPath() 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 --git a/CPP/7zip/UI/FileManager/SplitDialog.h b/CPP/7zip/UI/FileManager/SplitDialog.h index 00aae658..f8971365 100644 --- a/CPP/7zip/UI/FileManager/SplitDialog.h +++ b/CPP/7zip/UI/FileManager/SplitDialog.h @@ -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 @@ class CSplitDialog: public NWindows::NControl::CModalDialog { 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 --git a/CPP/7zip/UI/FileManager/SplitUtils.cpp b/CPP/7zip/UI/FileManager/SplitUtils.cpp index 4b6235b3..1982afba 100644 --- a/CPP/7zip/UI/FileManager/SplitUtils.cpp +++ b/CPP/7zip/UI/FileManager/SplitUtils.cpp @@ -74,7 +74,7 @@ static const char * const k_Sizes[] = 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 --git a/CPP/7zip/UI/FileManager/SplitUtils.h b/CPP/7zip/UI/FileManager/SplitUtils.h index 641dfe6b..d1d44e46 100644 --- a/CPP/7zip/UI/FileManager/SplitUtils.h +++ b/CPP/7zip/UI/FileManager/SplitUtils.h @@ -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 --git a/CPP/7zip/UI/FileManager/StdAfx.h b/CPP/7zip/UI/FileManager/StdAfx.h index 0e6d4461..789cc6e7 100644 --- a/CPP/7zip/UI/FileManager/StdAfx.h +++ b/CPP/7zip/UI/FileManager/StdAfx.h @@ -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" + +#endif -// #include "../../../Common/MyWindows.h" +/* +WINVER and _WIN32_WINNT -// #include -// #include -// #include +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 --git a/CPP/7zip/UI/FileManager/StringUtils.cpp b/CPP/7zip/UI/FileManager/StringUtils.cpp index 04783992..4641d151 100644 --- a/CPP/7zip/UI/FileManager/StringUtils.cpp +++ b/CPP/7zip/UI/FileManager/StringUtils.cpp @@ -24,35 +24,9 @@ void SplitStringToTwoStrings(const UString &src, UString &dest1, UString &dest2) } } -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 --git a/CPP/7zip/UI/FileManager/StringUtils.h b/CPP/7zip/UI/FileManager/StringUtils.h index fc070de1..37aad3ae 100644 --- a/CPP/7zip/UI/FileManager/StringUtils.h +++ b/CPP/7zip/UI/FileManager/StringUtils.h @@ -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 --git a/CPP/7zip/UI/FileManager/SysIconUtils.cpp b/CPP/7zip/UI/FileManager/SysIconUtils.cpp index d8e0f8b1..1c7cab00 100644 --- a/CPP/7zip/UI/FileManager/SysIconUtils.cpp +++ b/CPP/7zip/UI/FileManager/SysIconUtils.cpp @@ -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 @@ extern bool g_IsNT; 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 @@ DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex) 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 @@ DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex) #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 @@ DWORD_PTR GetRealIconIndex(const UString &fileName, DWORD attrib, int &iconIndex { 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 @@ DWORD_PTR GetRealIconIndex(const UString &fileName, DWORD attrib, int &iconIndex } */ -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 @@ static int FindInSorted_Attrib(const CRecordVector &vect, DWORD 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 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin 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 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin 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 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin } 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 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin 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 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const UString &fileName) 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 --git a/CPP/7zip/UI/FileManager/SysIconUtils.h b/CPP/7zip/UI/FileManager/SysIconUtils.h index fde16e46..1d34ef68 100644 --- a/CPP/7zip/UI/FileManager/SysIconUtils.h +++ b/CPP/7zip/UI/FileManager/SysIconUtils.h @@ -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 @@ class CExtToIconMap 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 --git a/CPP/7zip/UI/FileManager/SystemPage.cpp b/CPP/7zip/UI/FileManager/SystemPage.cpp index f7a1adae..93182eac 100644 --- a/CPP/7zip/UI/FileManager/SystemPage.cpp +++ b/CPP/7zip/UI/FileManager/SystemPage.cpp @@ -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 @@ using namespace NWindows; 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 @@ CSysString CModifiedExtInfo::GetString() const else return ProgramKey; return CSysString (s); -}; +} int CSystemPage::AddIcon(const UString &iconPath, int iconIndex) @@ -62,19 +68,19 @@ int CSystemPage::AddIcon(const UString &iconPath, int iconIndex) #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 @@ void CSystemPage::RefreshListItem(unsigned group, unsigned listIndex) _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 @@ bool CSystemPage::OnInit() { _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 @@ bool CSystemPage::OnInit() 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 @@ bool CSystemPage::OnInit() 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 @@ void CSystemPage::OnNotifyHelp() } -bool CSystemPage::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CSystemPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -379,7 +387,7 @@ bool CSystemPage::OnNotify(UINT controlID, LPNMHDR lParam) 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 @@ void CSystemPage::ChangeState(unsigned group) int itemIndex = -1; while ((itemIndex = _listView.GetNextSelectedItem(itemIndex)) != -1) - indices.Add(itemIndex); + indices.Add((unsigned)itemIndex); if (indices.IsEmpty()) FOR_VECTOR (i, _items) diff --git a/CPP/7zip/UI/FileManager/SystemPage.h b/CPP/7zip/UI/FileManager/SystemPage.h index 765214cf..6f2ed0c1 100644 --- a/CPP/7zip/UI/FileManager/SystemPage.h +++ b/CPP/7zip/UI/FileManager/SystemPage.h @@ -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 @@ struct CModifiedExtInfo: public NRegistryAssoc::CShellExtInfo } } OldState = State; - }; + } }; struct CAssoc @@ -116,11 +116,11 @@ class CSystemPage: public NWindows::NControl::CPropertyPage 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 --git a/CPP/7zip/UI/FileManager/TextPairs.cpp b/CPP/7zip/UI/FileManager/TextPairs.cpp index 4edf0256..1ac7098a 100644 --- a/CPP/7zip/UI/FileManager/TextPairs.cpp +++ b/CPP/7zip/UI/FileManager/TextPairs.cpp @@ -100,9 +100,9 @@ static int ComparePairItems(const CTextPair &p1, const CTextPair &p2) 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 @@ int CPairsStorage::FindID(const UString &id, int &insertPos) const 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, int &insertPos) const 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 @@ void CPairsStorage::DeletePair(const UString &id) { 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 @@ void CPairsStorage::SaveToString(UString &text) const text += pair.ID; if (multiWord) text += '\"'; - text += ' '; + text.Add_Space(); text += pair.Value; text += '\x0D'; text.Add_LF(); diff --git a/CPP/7zip/UI/FileManager/TextPairs.h b/CPP/7zip/UI/FileManager/TextPairs.h index 0a71d044..d18233d1 100644 --- a/CPP/7zip/UI/FileManager/TextPairs.h +++ b/CPP/7zip/UI/FileManager/TextPairs.h @@ -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 @@ class CPairsStorage { 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 --git a/CPP/7zip/UI/FileManager/UpdateCallback100.cpp b/CPP/7zip/UI/FileManager/UpdateCallback100.cpp index 67e70fb7..71ad710d 100644 --- a/CPP/7zip/UI/FileManager/UpdateCallback100.cpp +++ b/CPP/7zip/UI/FileManager/UpdateCallback100.cpp @@ -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 @@ STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */) 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 @@ HRESULT CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypte 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 @@ STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefi 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 --git a/CPP/7zip/UI/FileManager/UpdateCallback100.h b/CPP/7zip/UI/FileManager/UpdateCallback100.h index 7cbc11e3..5d56dfb9 100644 --- a/CPP/7zip/UI/FileManager/UpdateCallback100.h +++ b/CPP/7zip/UI/FileManager/UpdateCallback100.h @@ -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 @@ class CUpdateCallback100Imp: public CUpdateCallbackGUI2, public CMyUnknownImp { -public: - - // CUpdateCallback100Imp() {} - - MY_UNKNOWN_IMP7( + Z7_COM_UNKNOWN_IMP_7( IFolderArchiveUpdateCallback, IFolderArchiveUpdateCallback2, IFolderScanProgress, @@ -37,16 +33,14 @@ class CUpdateCallback100Imp: 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 --git a/CPP/7zip/UI/FileManager/VerCtrl.cpp b/CPP/7zip/UI/FileManager/VerCtrl.cpp index 4bb034f8..0c894b83 100644 --- a/CPP/7zip/UI/FileManager/VerCtrl.cpp +++ b/CPP/7zip/UI/FileManager/VerCtrl.cpp @@ -149,7 +149,7 @@ void CApp::VerCtrl(unsigned id) } CRecordVector indices; - panel.GetSelectedItemsIndices(indices); + panel.Get_ItemIndices_Selected(indices); if (indices.Size() != 1) { @@ -223,7 +223,7 @@ void CApp::VerCtrl(unsigned id) if (!ParseNumberString(fi.Name, val)) continue; if ((Int32)val > maxVal) - maxVal = val; + maxVal = (Int32)val; } UInt32 next = (UInt32)maxVal + 1; @@ -320,7 +320,7 @@ void CApp::VerCtrl(unsigned id) 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 --git a/CPP/7zip/UI/FileManager/ViewSettings.cpp b/CPP/7zip/UI/FileManager/ViewSettings.cpp index e0f32929..105554b1 100644 --- a/CPP/7zip/UI/FileManager/ViewSettings.cpp +++ b/CPP/7zip/UI/FileManager/ViewSettings.cpp @@ -37,7 +37,8 @@ static NSynchronization::CCriticalSection g_CS; #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); /* @@ -58,16 +59,16 @@ void CListViewInfo::Save(const UString &id) const 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); @@ -93,11 +94,11 @@ void CListViewInfo::Read(const UString &id) 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; @@ -110,9 +111,9 @@ void CListViewInfo::Read(const UString &id) { 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); } } @@ -143,18 +144,18 @@ void CWindowInfo::Save() const 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); } } @@ -176,18 +177,18 @@ void CWindowInfo::Read(bool &windowPosDefined, bool &panelInfoDefined) 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 --git a/CPP/7zip/UI/FileManager/ViewSettings.h b/CPP/7zip/UI/FileManager/ViewSettings.h index aeb68979..02af0a15 100644 --- a/CPP/7zip/UI/FileManager/ViewSettings.h +++ b/CPP/7zip/UI/FileManager/ViewSettings.h @@ -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 --git a/CPP/7zip/UI/FileManager/makefile b/CPP/7zip/UI/FileManager/makefile index 44feed39..bcc4df0c 100644 --- a/CPP/7zip/UI/FileManager/makefile +++ b/CPP/7zip/UI/FileManager/makefile @@ -1,6 +1,6 @@ PROG = 7zFM.exe CFLAGS = $(CFLAGS) \ - -DEXTERNAL_CODECS \ + -DZ7_EXTERNAL_CODECS \ !include "FM.mak" @@ -85,6 +85,7 @@ UI_COMMON_OBJS = \ EXPLORER_OBJS = \ $O\ContextMenu.obj \ + $O\MyMessages.obj \ $O\RegistryContextMenu.obj \ GUI_OBJS = \ diff --git a/CPP/7zip/UI/FileManager/resource.h b/CPP/7zip/UI/FileManager/resource.h index f4e6f8c2..90f1e52f 100644 --- a/CPP/7zip/UI/FileManager/resource.h +++ b/CPP/7zip/UI/FileManager/resource.h @@ -35,6 +35,13 @@ #define IDM_BLAKE2sp 113 #define IDM_BLAKE3 114 +#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 @@ -99,8 +106,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 --git a/CPP/7zip/UI/FileManager/resource.rc b/CPP/7zip/UI/FileManager/resource.rc index b1127ba0..3c01de4d 100644 --- a/CPP/7zip/UI/FileManager/resource.rc +++ b/CPP/7zip/UI/FileManager/resource.rc @@ -2,7 +2,7 @@ #include "../../GuiCommon.rc" #include "resource.h" -MY_VERSION_INFO_APP("7-Zip ZS File Manager", "7zFM") +MY_VERSION_INFO_APP("7-Zip File Manager", "7zFM") IDR_ACCELERATOR1 ACCELERATORS BEGIN @@ -12,10 +12,27 @@ BEGIN // 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 +// */ -IDM_MENU MENU +// 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 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 @@ BEGIN 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 @@ -54,55 +71,56 @@ BEGIN 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 @@ -116,29 +134,29 @@ BEGIN // 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 @@ -181,7 +199,7 @@ BEGIN 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 --git a/CPP/7zip/UI/GUI/7zG.exe.manifest b/CPP/7zip/UI/GUI/7zG.exe.manifest index 39f516cd..ae964d82 100644 --- a/CPP/7zip/UI/GUI/7zG.exe.manifest +++ b/CPP/7zip/UI/GUI/7zG.exe.manifest @@ -17,4 +17,7 @@ true + + +true diff --git a/CPP/7zip/UI/GUI/BenchmarkDialog.cpp b/CPP/7zip/UI/GUI/BenchmarkDialog.cpp index 71d28e8d..539d6899 100644 --- a/CPP/7zip/UI/GUI/BenchmarkDialog.cpp +++ b/CPP/7zip/UI/GUI/BenchmarkDialog.cpp @@ -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 @@ void CSyncData::Init() NeedPrint_Dec_1 = NeedPrint_Dec = NeedPrint_Tot = false; -}; +} struct CBenchProgressSync @@ -243,7 +241,7 @@ class CBenchmarkDialog; struct CThreadBenchmark { CBenchmarkDialog *BenchmarkDialog; - DECL_EXTERNAL_CODECS_LOC_VARS2; + DECL_EXTERNAL_CODECS_LOC_VARS_DECL // HRESULT Result; HRESULT Process(); @@ -290,15 +288,15 @@ class CBenchmarkDialog: 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 @@ class CBenchmarkDialog: 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 @@ class CBenchmarkDialog: 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 @@ class CBenchmarkDialog: 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 @@ static const UInt32 kLangIDs[] = IDB_RESTART }; -static const UInt32 kLangIDs_Colon[] = +static const UInt32 kLangIDs_RemoveColon[] = { - IDT_BENCH_SIZE + IDT_BENCH_SPEED }; #endif @@ -439,18 +437,18 @@ static int ComboBox_Add_UInt32(NWindows::NControl::CComboBox &cb, UInt32 v) { 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 @@ bool CBenchmarkDialog::OnInit() 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 @@ bool CBenchmarkDialog::OnInit() 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 @@ bool CBenchmarkDialog::OnInit() 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 @@ UInt32 CBenchmarkDialog::GetNumberOfThreads() 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 @@ size_t CBenchmarkDialog::OnChangeDictionary() UString s; Print_MemUsage(s, memUsage); - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES { AString s2; Add_LargePages_String(s2); @@ -875,7 +873,7 @@ void CBenchmarkDialog::StartBenchmark() 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 @@ void CBenchmarkDialog::StartBenchmark() { MyKillTimer(); MessageBoxError_Status(L"Can't create thread"); - }; + } return; } @@ -1000,19 +998,17 @@ void CBenchmarkDialog::PrintTime() 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 @@ static UInt32 GetRating(const CTotalBenchRes &info) if (rating32 != rating64) rating32 = (UInt32)(Int32)-1; return rating32; -}; +} static void AddUsageString(UString &s, const CTotalBenchRes &info) @@ -1088,7 +1084,7 @@ static void AddRatingString(UString &s, const CTotalBenchRes &info) // 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 @@ void CBenchmarkDialog::PrintRating(UInt64 rating, UINT controlID) { // 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 @@ void CBenchmarkDialog::UpdateGui() } -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::OnCommand(int code, int itemID, LPARAM lParam) } -bool CBenchmarkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CBenchmarkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -1425,14 +1420,14 @@ bool CBenchmarkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) // ---------- 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 @@ HRESULT CBenchCallback::SetDecodeResult(const CBenchInfo &info, bool final) } -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 @@ HRESULT CBenchCallback2::CheckBreak() -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 @@ HRESULT Benchmark( COneMethodInfo method; UInt32 numCPUs = 1; - #ifndef _7ZIP_ST + #ifndef Z7_ST numCPUs = NSystem::GetNumberOfProcessors(); #endif UInt32 numThreads = numCPUs; @@ -1860,8 +1855,8 @@ HRESULT Benchmark( 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 @@ HRESULT Benchmark( 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 --git a/CPP/7zip/UI/GUI/BenchmarkDialog.h b/CPP/7zip/UI/GUI/BenchmarkDialog.h index a280592e..63c6dede 100644 --- a/CPP/7zip/UI/GUI/BenchmarkDialog.h +++ b/CPP/7zip/UI/GUI/BenchmarkDialog.h @@ -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 --git a/CPP/7zip/UI/GUI/CompressDialog.cpp b/CPP/7zip/UI/GUI/CompressDialog.cpp index eeeb5752..6b1b6821 100644 --- a/CPP/7zip/UI/GUI/CompressDialog.cpp +++ b/CPP/7zip/UI/GUI/CompressDialog.cpp @@ -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 kSolidLog_FullSolid = 64; 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"; #define k7zFormat "7z" @@ -267,6 +283,13 @@ static const EMethodID g_XzMethods[] = kLZMA2 }; +/* +static const EMethodID g_ZstdMethods[] = +{ + kZSTD +}; +*/ + static const EMethodID g_SwfcMethods[] = { kDeflate @@ -320,7 +343,7 @@ struct CFormatInfo 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[] = { @@ -366,6 +389,17 @@ static const CFormatInfo g_Formats[] = 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 + }, + */ { "zstd", (1 << 1) | (1 << 3) | (1 << 5) | (1 << 11) | (1 << 17) | (1 << 22), @@ -437,7 +471,7 @@ static const signed char g_LevelRanges[][2] = { 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; @@ -495,10 +529,10 @@ void CCompressDialog::SetMethods(const CObjectVector &userCodecs || 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); } @@ -508,9 +542,9 @@ void CCompressDialog::SetMethods(const CObjectVector &userCodecs 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 @@ -545,10 +579,21 @@ bool CCompressDialog::OnInit() _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)); @@ -569,13 +614,13 @@ bool CCompressDialog::OnInit() 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) @@ -585,7 +630,7 @@ bool CCompressDialog::OnInit() if (i == 0 || ai.Name.IsEqualTo_NoCase(m_RegistryInfo.ArcType)) { m_Format.SetCurSel(index); - Info.FormatIndex = arcIndex; + Info.FormatIndex = (int)arcIndex; } } } @@ -602,10 +647,10 @@ bool CCompressDialog::OnInit() 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); @@ -643,10 +688,10 @@ namespace NCompressDialog 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); @@ -657,7 +702,7 @@ void CCompressDialog::UpdatePasswordControl() _password2Control.Show_Bool(!showPassword); } -bool CCompressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CCompressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -829,13 +874,13 @@ void CCompressDialog::FormatChanged(bool isChanged) 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; @@ -845,7 +890,7 @@ void CCompressDialog::OnButtonSFX() { UString fileName; m_ArchivePath.GetText(fileName); - int dotPos = GetExtDotPos(fileName); + const int dotPos = GetExtDotPos(fileName); if (IsSFX()) { if (dotPos >= 0) @@ -857,7 +902,7 @@ void CCompressDialog::OnButtonSFX() { if (dotPos >= 0) { - UString ext = fileName.Ptr(dotPos); + const UString ext = fileName.Ptr(dotPos); if (ext.IsEqualTo_Ascii_NoCase(kExeExt)) { fileName.DeleteFrom(dotPos); @@ -870,36 +915,38 @@ void CCompressDialog::OnButtonSFX() // 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); @@ -917,8 +964,26 @@ bool CCompressDialog::SetArcPathFields(const UString &path, UString &name, bool 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; @@ -928,23 +993,133 @@ void CCompressDialog::OnButtonSetArchive() 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; - UString dummyName; - SetArcPathFields(resPath, dummyName, true); + + 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; + } + + ArcPath_WasChanged(path); } + // in ExtractDialog.cpp extern void AddUniqueString(UStringVector &strings, const UString &srcString); @@ -952,7 +1127,7 @@ static bool IsAsciiString(const UString &s) { 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; } @@ -970,6 +1145,7 @@ static void AddSize_MB(UString &s, UInt64 size) } +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"; @@ -1053,6 +1229,8 @@ void CCompressDialog::OnOK() } SaveOptionsInMem(); + + UStringVector arcPaths; { UString s; if (!GetFinalPath_Smart(s)) @@ -1060,17 +1238,16 @@ void CCompressDialog::OnOK() 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(); @@ -1101,7 +1278,7 @@ void CCompressDialog::OnOK() 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); @@ -1166,34 +1343,83 @@ void CCompressDialog::OnOK() } } - 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) { @@ -1201,21 +1427,21 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) { 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; } @@ -1257,6 +1483,7 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) } case IDC_COMPRESS_DICTIONARY: + // case IDC_COMPRESS_DICTIONARY2: { /* we want to change the reported threads for Auto line and keep selected NumThreads option @@ -1271,6 +1498,7 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) // SetSolidBlockSize(true); } + SetDictionary2(); SetSolidBlockSize(); SetNumThreads(); // we want to change the reported threads for Auto line only SetMemoryUsage(); @@ -1278,7 +1506,12 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) } case IDC_COMPRESS_ORDER: + { + #ifdef PRINT_PARAMS + Print_Params(); + #endif return true; + } case IDC_COMPRESS_SOLID: { @@ -1328,7 +1561,7 @@ void CCompressDialog::SetArchiveName2(bool prevWasSFX) prevExtension = kExeExt; else { - prevExtension += '.'; + prevExtension.Add_Dot(); prevExtension += prevArchiverInfo.GetMainExt(); } const unsigned prevExtensionLen = prevExtension.Len(); @@ -1346,7 +1579,7 @@ void CCompressDialog::SetArchiveName2(bool prevWasSFX) 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()) @@ -1367,7 +1600,7 @@ void CCompressDialog::SetArchiveName(const UString &name) fileName += kExeExt; else { - fileName += '.'; + fileName.Add_Dot(); UString ext = ai.GetMainExt(); if (ai.Flags_HashHandler()) { @@ -1390,7 +1623,7 @@ int CCompressDialog::FindRegistryFormat(const UString &name) { const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[i]; if (name.IsEqualTo_NoCase(GetUnicodeString(fo.FormatID))) - return i; + return (int)i; } return -1; } @@ -1398,14 +1631,14 @@ int CCompressDialog::FindRegistryFormat(const UString &name) 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; } @@ -1416,10 +1649,10 @@ NCompression::CFormatOptions &CCompressDialog::Get_FormatOptions() } -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; @@ -1528,12 +1761,11 @@ static LRESULT ComboBox_AddStringAscii(NControl::CComboBox &cb, const char *s) 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) @@ -1583,10 +1815,10 @@ void CCompressDialog::SetMethod2(int keepMethodId) { 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(); methodLong = method; } @@ -1700,10 +1932,10 @@ UString CCompressDialog::GetMethodSpec(UString &estimatedName) 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; } @@ -1740,10 +1972,10 @@ UString CCompressDialog::GetEncryptionMethodSpec() 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; @@ -1752,16 +1984,20 @@ int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow) 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) { @@ -1874,6 +2110,86 @@ void CCompressDialog::SetDictionary2() 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: { @@ -2043,8 +2359,8 @@ int CCompressDialog::AddOrder(UInt32 size) { 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; } @@ -2107,6 +2423,39 @@ void CCompressDialog::SetOrder2() 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: { @@ -2303,8 +2652,8 @@ void CCompressDialog::SetSolidBlockSize2() 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; } @@ -2315,7 +2664,7 @@ void CCompressDialog::SetSolidBlockSize2() 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; } @@ -2325,7 +2674,7 @@ void CCompressDialog::SetSolidBlockSize2() 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; @@ -2333,7 +2682,7 @@ void CCompressDialog::SetSolidBlockSize2() { 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; } @@ -2342,6 +2691,43 @@ void CCompressDialog::SetSolidBlockSize2() } +/* +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; @@ -2411,7 +2797,10 @@ void CCompressDialog::SetNumThreads2() const UInt64 memUse_Limit = Get_MemUse_Bytes(); - if (autoThreads > 1 && _ramSize_Defined) + if (_ramSize_Defined) + if (autoThreads > 1 + // || (autoThreads == 0 && methodID == kZSTD) + ) { if (isZip) { @@ -2439,6 +2828,20 @@ void CCompressDialog::SetNumThreads2() } 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; @@ -2447,8 +2850,9 @@ void CCompressDialog::SetNumThreads2() { 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) @@ -2456,12 +2860,16 @@ void CCompressDialog::SetNumThreads2() } 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; } @@ -2497,7 +2905,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault) s.Add_UInt64(val); s += '%'; if (isDefault) - sUser = "* "; + sUser = k_Auto_Prefix; else sRegistry = s; sUser += s; @@ -2508,7 +2916,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault) sRegistry = sUser; for (;;) { - int pos = sRegistry.Find(L' '); + const int pos = sRegistry.Find(L' '); if (pos < 0) break; sRegistry.Delete(pos); @@ -2519,7 +2927,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault) } 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; } @@ -2643,11 +3051,16 @@ UInt64 CCompressDialog::GetMemoryUsage_DecompMem(UInt64 &decompressMemory) 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) { @@ -2657,11 +3070,9 @@ UInt64 CCompressDialog::GetMemoryUsage_Dict_DecompMem(UInt64 dict64, UInt64 &dec 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; @@ -2688,6 +3099,12 @@ UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads, } const int methodId = GetMethodID(); + + if (dict64 == (UInt64)(Int64)-1 + // && methodId != kZSTD + ) + return (UInt64)(Int64)-1; + switch (methodId) { @@ -2772,8 +3189,7 @@ UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads, case kFLZMA2: { const UInt32 dict = (dict64 >= kLzmaMaxDictSize ? kLzmaMaxDictSize : (UInt32)dict64); - if (level > FL2_MAX_7Z_CLEVEL) - level = FL2_MAX_7Z_CLEVEL; + // if (level > FL2_MAX_7Z_CLEVEL) level = FL2_MAX_7Z_CLEVEL; /* dual buffer is enabled in Lzma2Encoder.cpp so size is dict * 6 */ size += dict * 6 + (1UL << 18) * numThreads; UInt32 bufSize = dict >> MATCH_BUFFER_SHIFT; @@ -2899,8 +3315,109 @@ void CCompressDialog::SetMemoryUsage() 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(); @@ -2949,6 +3466,24 @@ void CCompressDialog::SaveOptionsInMem() } 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(); @@ -3121,7 +3656,7 @@ int COptionsDialog::AddPrec(unsigned prec, bool isDefault) 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; } @@ -3159,7 +3694,7 @@ void COptionsDialog::SetPrec() // 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) { @@ -3323,7 +3858,7 @@ void COptionsDialog::On_CheckBoxSet_Clicked(const CBoolBox &bb) -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs_Options[] = { IDX_COMPRESS_NT_SYM_LINKS, @@ -3344,9 +3879,9 @@ static const UInt32 kLangIDs_Options[] = 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 @@ -3409,7 +3944,7 @@ bool COptionsDialog::OnInit() } -bool COptionsDialog::OnCommand(int code, int itemID, LPARAM lParam) +bool COptionsDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam) { if (code == CBN_SELCHANGE) { @@ -3427,7 +3962,7 @@ bool COptionsDialog::OnCommand(int code, int itemID, LPARAM lParam) } -bool COptionsDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool COptionsDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { @@ -3464,5 +3999,5 @@ void COptionsDialog::OnOK() void COptionsDialog::OnHelp() { - ShowHelpWindow(kHelpTopic); + ShowHelpWindow(kHelpTopic_Options); } diff --git a/CPP/7zip/UI/GUI/CompressDialog.h b/CPP/7zip/UI/GUI/CompressDialog.h index 382aa821..31a46f58 100644 --- a/CPP/7zip/UI/GUI/CompressDialog.h +++ b/CPP/7zip/UI/GUI/CompressDialog.h @@ -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 @@ namespace NCompressDialog UInt32 Level; UString Method; UInt64 Dict64; + // UInt64 Dict64_Chain; bool OrderMode; UInt32 Order; UString Options; @@ -94,6 +95,7 @@ namespace NCompressDialog NumThreads = (UInt32)(Int32)-1; SolidIsSpecified = false; Dict64 = (UInt64)(Int64)(-1); + // Dict64_Chain = (UInt64)(Int64)(-1); OrderMode = false; Method.Empty(); Options.Empty(); @@ -146,12 +148,15 @@ class CCompressDialog: public NWindows::NControl::CModalDialog 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; @@ -165,6 +170,7 @@ class CCompressDialog: public NWindows::NControl::CModalDialog 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; @@ -203,7 +209,7 @@ class CCompressDialog: public NWindows::NControl::CModalDialog void CheckSFXNameChange(); void SetArchiveName2(bool prevWasSFX); - int GetStaticFormatIndex(); + unsigned GetStaticFormatIndex(); void SetNearestSelectComboBox(NWindows::NControl::CComboBox &comboBox, UInt32 value); @@ -226,6 +232,7 @@ class CCompressDialog: public NWindows::NControl::CModalDialog { SetDictionary2(); EnableMultiCombo(IDC_COMPRESS_DICTIONARY); + // EnableMultiCombo(IDC_COMPRESS_DICTIONARY2); SetOrder2(); EnableMultiCombo(IDC_COMPRESS_ORDER); } @@ -245,6 +252,7 @@ class CCompressDialog: public NWindows::NControl::CModalDialog int AddDict2(size_t sizeReal, size_t sizeShow); int AddDict(size_t size); + // int AddDict_Chain(size_t size); void SetDictionary2(); @@ -256,6 +264,8 @@ class CCompressDialog: public NWindows::NControl::CModalDialog UInt32 GetLevel2(); UInt64 GetDictSpec() { return GetComboValue_64(m_Dictionary, 1); } + // UInt64 GetDictChainSpec() { return GetComboValue_64(m_Dictionary_Chain, 1); } + UInt64 GetDict2() { UInt64 num = GetDictSpec(); @@ -321,6 +331,8 @@ class CCompressDialog: public NWindows::NControl::CModalDialog void PrintMemUsage(UINT res, UInt64 value); void SetMemoryUsage(); + void Print_Params(); + void SetParams(); void SaveOptionsInMem(); @@ -330,7 +342,9 @@ class CCompressDialog: public NWindows::NControl::CModalDialog 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(); @@ -341,11 +355,12 @@ class CCompressDialog: public NWindows::NControl::CModalDialog 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) { @@ -363,15 +378,14 @@ class CCompressDialog: public NWindows::NControl::CModalDialog 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() {} }; @@ -385,10 +399,10 @@ class COptionsDialog: public NWindows::NControl::CModalDialog 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; @@ -444,15 +458,15 @@ class COptionsDialog: public NWindows::NControl::CModalDialog 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); @@ -463,7 +477,7 @@ class COptionsDialog: public NWindows::NControl::CModalDialog // , TimePrec(0) { Reset_TimePrec(); - }; + } }; #endif diff --git a/CPP/7zip/UI/GUI/CompressDialogRes.h b/CPP/7zip/UI/GUI/CompressDialogRes.h index 80b39be5..aa25b89b 100644 --- a/CPP/7zip/UI/GUI/CompressDialogRes.h +++ b/CPP/7zip/UI/GUI/CompressDialogRes.h @@ -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 --git a/CPP/7zip/UI/GUI/ExtractDialog.cpp b/CPP/7zip/UI/GUI/ExtractDialog.cpp index 5132084d..46284820 100644 --- a/CPP/7zip/UI/GUI/ExtractDialog.cpp +++ b/CPP/7zip/UI/GUI/ExtractDialog.cpp @@ -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 @@ using namespace NName; extern HINSTANCE g_hInstance; -#ifndef _SFX +#ifndef Z7_SFX static const UInt32 kPathMode_IDs[] = { @@ -70,7 +70,7 @@ static const #endif -#ifdef LANG +#ifdef Z7_LANG static const UInt32 kLangIDs[] = { @@ -87,23 +87,23 @@ static const UInt32 kLangIDs[] = // 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::CheckButton_TwoBools(UINT id, const CBoolPair &b1, const CB 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 @@ void CExtractDialog::GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2) bool CExtractDialog::OnInit() { - #ifdef LANG + #ifdef Z7_LANG { UString s; LangString_OnlyFromLangFile(IDD_EXTRACT, s); @@ -150,18 +150,18 @@ bool CExtractDialog::OnInit() } 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 @@ bool CExtractDialog::OnInit() UString pathPrefix = DirPath; - #ifndef _SFX + #ifndef Z7_SFX if (_info.SplitDest.Val) { @@ -210,7 +210,7 @@ bool CExtractDialog::OnInit() _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 @@ bool CExtractDialog::OnInit() _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 @@ bool CExtractDialog::OnInit() return CModalDialog::OnInit(); } -#ifndef _SFX +#ifndef Z7_SFX void CExtractDialog::UpdatePasswordControl() { _passwordControl.SetPasswordChar(IsShowPasswordChecked() ? 0 : TEXT('*')); @@ -253,14 +253,14 @@ void CExtractDialog::UpdatePasswordControl() } #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 @@ void CExtractDialog::OnButtonSetPath() 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 AddUniqueString(UStringVector &list, const UString &s) 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 @@ void CExtractDialog::OnOK() #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 @@ void CExtractDialog::OnOK() UString s; - #ifdef NO_REGISTRY + #ifdef Z7_NO_REGISTRY _path.GetText(s); @@ -371,9 +371,9 @@ void CExtractDialog::OnOK() 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 @@ void CExtractDialog::OnOK() 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 @@ void CExtractDialog::OnOK() CModalDialog::OnOK(); } -#ifndef NO_REGISTRY +#ifndef Z7_NO_REGISTRY #define kHelpTopic "fm/plugins/7-zip/extract.htm" void CExtractDialog::OnHelp() { diff --git a/CPP/7zip/UI/GUI/ExtractDialog.h b/CPP/7zip/UI/GUI/ExtractDialog.h index 33349ffc..1565fb8a 100644 --- a/CPP/7zip/UI/GUI/ExtractDialog.h +++ b/CPP/7zip/UI/GUI/ExtractDialog.h @@ -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 @@ namespace NExtractionDialog 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 @@ class CExtractDialog: public NWindows::NControl::CModalDialog 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 @@ class CExtractDialog: public NWindows::NControl::CModalDialog UString DirPath; UString ArcPath; - #ifndef _SFX + #ifndef Z7_SFX UString Password; #endif bool PathMode_Force; @@ -84,16 +84,16 @@ class CExtractDialog: public NWindows::NControl::CModalDialog 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 --git a/CPP/7zip/UI/GUI/ExtractGUI.cpp b/CPP/7zip/UI/GUI/ExtractGUI.cpp index a9191a8b..fdf3cc78 100644 --- a/CPP/7zip/UI/GUI/ExtractGUI.cpp +++ b/CPP/7zip/UI/GUI/ExtractGUI.cpp @@ -36,7 +36,7 @@ using namespace NDir; 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 @@ static void AddSizePair(UString &s, UINT resourceID, UInt64 value) 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 @@ class CThreadExtracting: public CProgressThreadVirt 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 @@ HRESULT CThreadExtracting::ProcessVirt() { CDecompressStat Stat; - #ifndef _SFX + #ifndef Z7_SFX /* if (HashBundle) HashBundle->Init(); @@ -111,20 +111,21 @@ HRESULT CThreadExtracting::ProcessVirt() 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 @@ HRESULT ExtractGUI( UStringVector &archivePathsFull, const NWildcard::CCensorNode &wildcardCensor, CExtractOptions &options, - #ifndef _SFX + #ifndef Z7_SFX CHashBundle *hb, #endif bool showDialog, @@ -184,8 +185,8 @@ HRESULT ExtractGUI( CThreadExtracting extracter; /* - #ifdef EXTERNAL_CODECS - extracter.externalCodecs = __externalCodecs; + #ifdef Z7_EXTERNAL_CODECS + extracter.externalCodecs = _externalCodecs; #endif */ extracter.codecs = codecs; @@ -222,7 +223,7 @@ HRESULT ExtractGUI( 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 @@ HRESULT ExtractGUI( 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 @@ HRESULT ExtractGUI( { 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 @@ HRESULT ExtractGUI( 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 @@ HRESULT ExtractGUI( 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 --git a/CPP/7zip/UI/GUI/ExtractGUI.h b/CPP/7zip/UI/GUI/ExtractGUI.h index 3b412590..13ca6abf 100644 --- a/CPP/7zip/UI/GUI/ExtractGUI.h +++ b/CPP/7zip/UI/GUI/ExtractGUI.h @@ -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 @@ HRESULT ExtractGUI( UStringVector &archivePathsFull, const NWildcard::CCensorNode &wildcardCensor, CExtractOptions &options, - #ifndef _SFX + #ifndef Z7_SFX CHashBundle *hb, #endif bool showDialog, diff --git a/CPP/7zip/UI/GUI/GUI.cpp b/CPP/7zip/UI/GUI/GUI.cpp index 9b566af5..4790db40 100644 --- a/CPP/7zip/UI/GUI/GUI.cpp +++ b/CPP/7zip/UI/GUI/GUI.cpp @@ -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 @@ DWORD g_ComCtl32Version; 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 @@ static int ShowMemErrorMessage() 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 @@ static int Main2() #endif if (commandStrings.Size() == 0) { - MessageBoxW(0, L"Specify command", L"7-Zip ZS", 0); + MessageBoxW(NULL, L"Specify command", L"7-Zip ZS", 0); return 0; } @@ -142,14 +150,14 @@ static int Main2() 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 @@ static int Main2() || 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 @@ static int Main2() // 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 @@ static int Main2() 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 @@ static int Main2() 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 @@ static int Main2() ArchivePathsFullSorted, options.Censor.Pairs.Front().Head, eo, - #ifndef _SFX + #ifndef Z7_SFX hb_ptr, #endif options.ShowDialog, messageWasDisplayed, ecs); @@ -304,14 +312,14 @@ static int Main2() } 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 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, OleInitialize(NULL); #endif + #ifdef Z7_LANG LoadLangOneTime(); + #endif // setlocale(LC_COLLATE, ".ACP"); try @@ -456,7 +466,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, catch(int v) { AString e ("Error: "); - e.Add_UInt32(v); + e.Add_UInt32((unsigned)v); ErrorMessage(e); return NExitCode::kFatalError; } diff --git a/CPP/7zip/UI/GUI/GUI.dsp b/CPP/7zip/UI/GUI/GUI.dsp index b55a115c..3a6b60f8 100644 --- a/CPP/7zip/UI/GUI/GUI.dsp +++ b/CPP/7zip/UI/GUI/GUI.dsp @@ -45,7 +45,7 @@ RSC=rc.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ LINK32=link.exe # 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 @@ SOURCE=..\FileManager\ExtractCallback.h # 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 @@ SOURCE=..\..\Common\MethodProps.h # 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 @@ 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 @@ -872,6 +880,14 @@ SOURCE=..\..\..\Common\CommandLineParser.h # 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 @@ SOURCE=..\..\..\Common\MyVector.h # 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=..\..\Archive\IArchive.h 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 --git a/CPP/7zip/UI/GUI/HashGUI.cpp b/CPP/7zip/UI/GUI/HashGUI.cpp index 21543835..185a2262 100644 --- a/CPP/7zip/UI/GUI/HashGUI.cpp +++ b/CPP/7zip/UI/GUI/HashGUI.cpp @@ -22,7 +22,7 @@ using namespace NWindows; -class CHashCallbackGUI: public CProgressThreadVirt, public IHashCallbackUI +class CHashCallbackGUI Z7_final: public CProgressThreadVirt, public IHashCallbackUI { UInt64 NumFiles; bool _curIsFolder; @@ -31,24 +31,28 @@ class CHashCallbackGUI: public CProgressThreadVirt, public IHashCallbackUI 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::ScanProgress(const CDirItemsStat &st, const FString &p 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 @@ HRESULT CHashCallbackGUI::OpenFileError(const FString &path, DWORD systemError) { // 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 @@ HRESULT HashCalcGUI( 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 @@ HRESULT HashCalcGUI( 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 @@ void ShowHashResults(const CHashBundle &hb, HWND hwnd) ShowHashResults(propPairs, hwnd); } - void CHashCallbackGUI::ProcessWasFinished_GuiVirt() { - ShowHashResults(PropNameValPairs, *this); + if (Result != E_ABORT) + ShowHashResults(PropNameValPairs, *this); } diff --git a/CPP/7zip/UI/GUI/HashGUI.h b/CPP/7zip/UI/GUI/HashGUI.h index 82644535..1ec9c475 100644 --- a/CPP/7zip/UI/GUI/HashGUI.h +++ b/CPP/7zip/UI/GUI/HashGUI.h @@ -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 --git a/CPP/7zip/UI/GUI/StdAfx.h b/CPP/7zip/UI/GUI/StdAfx.h index 1918c8c4..130db8aa 100644 --- a/CPP/7zip/UI/GUI/StdAfx.h +++ b/CPP/7zip/UI/GUI/StdAfx.h @@ -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 --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp b/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp index 1f272cd9..26057a7e 100644 --- a/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp +++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp @@ -51,7 +51,7 @@ HRESULT CUpdateCallbackGUI::StartScanning() 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 @@ HRESULT CUpdateCallbackGUI::FinishScanning(const CDirItemsStat &st) { 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 @@ HRESULT CUpdateCallbackGUI::OpenFileError(const FString &path, DWORD systemError 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 @@ HRESULT CUpdateCallbackGUI::Open_SetCompleted(const UInt64 * /* numFiles */, con return ProgressDialog->Sync.CheckStop(); } -#ifndef _NO_CRYPTO +#ifndef Z7_NO_CRYPTO HRESULT CUpdateCallbackGUI::Open_CryptoGetTextPassword(BSTR *password) { @@ -260,7 +260,7 @@ HRESULT CUpdateCallbackGUI::StartOpenArchive(const wchar_t * /* name */) 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 --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI.h b/CPP/7zip/UI/GUI/UpdateCallbackGUI.h index 2e0c111b..998249a8 100644 --- a/CPP/7zip/UI/GUI/UpdateCallbackGUI.h +++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI.h @@ -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 --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp index 4eeead7d..966f57ec 100644 --- a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp +++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp @@ -31,7 +31,7 @@ void CUpdateCallbackGUI2::Init() _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 --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h index 2b30ad21..e32b6020 100644 --- a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h +++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h @@ -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 @@ class CUpdateCallbackGUI2 NumFiles(0) {} - // ~CUpdateCallbackGUI2(); void Init(); CProgressDialog *ProgressDialog; diff --git a/CPP/7zip/UI/GUI/UpdateGUI.cpp b/CPP/7zip/UI/GUI/UpdateGUI.cpp index 2d041437..aaf7ebda 100644 --- a/CPP/7zip/UI/GUI/UpdateGUI.cpp +++ b/CPP/7zip/UI/GUI/UpdateGUI.cpp @@ -37,7 +37,7 @@ UString HResultToMessage(HRESULT errorCode); class CThreadUpdating: public CProgressThreadVirt { - HRESULT ProcessVirt(); + HRESULT ProcessVirt() Z7_override; public: CCodecs *codecs; const CObjectVector *formatIndices; @@ -185,7 +185,7 @@ static void ParseAndAddPropertires(CObjectVector &properties, 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 @@ static void SetOutProperties( 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 const C_UpdateMode_ToAction_Pair g_UpdateMode_Pairs[] = 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 @@ static HRESULT ShowDialog( } } - + + /* + // 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 @@ static HRESULT ShowDialog( 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 @@ HRESULT UpdateGUI( 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 @@ HRESULT UpdateGUI( 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 --git a/CPP/7zip/UI/GUI/UpdateGUI.h b/CPP/7zip/UI/GUI/UpdateGUI.h index d1880de0..0c43a01b 100644 --- a/CPP/7zip/UI/GUI/UpdateGUI.h +++ b/CPP/7zip/UI/GUI/UpdateGUI.h @@ -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 --git a/CPP/7zip/UI/GUI/makefile b/CPP/7zip/UI/GUI/makefile index 6b048534..a4324d3a 100644 --- a/CPP/7zip/UI/GUI/makefile +++ b/CPP/7zip/UI/GUI/makefile @@ -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 @@ WIN_CTRL_OBJS = \ $O\FilterCoder.obj \ $O\LimitedStreams.obj \ $O\MethodProps.obj \ + $O\MultiOutStream.obj \ $O\ProgressUtils.obj \ $O\PropId.obj \ $O\StreamObjects.obj \ diff --git a/CPP/7zip/warn_clang.mak b/CPP/7zip/warn_clang.mak index ed4f908f..0d007307 100644 --- a/CPP/7zip/warn_clang.mak +++ b/CPP/7zip/warn_clang.mak @@ -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 --git a/CPP/7zip/warn_clang_mac.mak b/CPP/7zip/warn_clang_mac.mak index aadf14f7..ed936c58 100644 --- a/CPP/7zip/warn_clang_mac.mak +++ b/CPP/7zip/warn_clang_mac.mak @@ -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_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) +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 + +CXX_STD_FLAGS = -std=c++11 diff --git a/CPP/7zip/warn_gcc.mak b/CPP/7zip/warn_gcc.mak index 3185326a..7eb1f570 100644 --- a/CPP/7zip/warn_gcc.mak +++ b/CPP/7zip/warn_gcc.mak @@ -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 --git a/CPP/Build.mak b/CPP/Build.mak index 81b796db..0d7f9507 100644 --- a/CPP/Build.mak +++ b/CPP/Build.mak @@ -4,6 +4,11 @@ LIBS = $(LIBS) oleaut32.lib ole32.lib 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) @@ -93,8 +98,21 @@ CFLAGS = $(CFLAGS) -MT 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 @@ -103,10 +121,10 @@ CFLAGS = $(CFLAGS) -MP4 # CFLAGS = $(CFLAGS) -arch:IA32 !ENDIF !ENDIF -!ELSE -CFLAGS = $(CFLAGS) + !ENDIF + !IFDEF MY_CONSOLE CFLAGS = $(CFLAGS) -D_CONSOLE !ENDIF @@ -120,7 +138,7 @@ CFLAGS = $(CFLAGS) -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE CFLAGS_O1 = $(CFLAGS) -O1 CFLAGS_O2 = $(CFLAGS) -O2 /Ob3 -LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF +LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF -INCREMENTAL:NO !IFNDEF UNDER_CE LFLAGS = $(LFLAGS) /LTCG /LARGEADDRESSAWARE @@ -142,6 +160,12 @@ LFLAGS = $(LFLAGS) /SUBSYSTEM:windows,$(MY_SUB_SYS_VER) !ENDIF +!IF "$(PLATFORM)" == "arm64" +# we can get better compression ratio with ARM64 filter if we change alignment to 4096 +# LFLAGS = $(LFLAGS) /FILEALIGN:4096 +!ENDIF + + PROGPATH = $O\$(PROG) @@ -175,6 +199,11 @@ $O: $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) @@ -184,3 +213,12 @@ $O\resource.res: $(*B).rc !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 --git a/CPP/Common/AutoPtr.h b/CPP/Common/AutoPtr.h index 006d3155..0be8a7a4 100644 --- a/CPP/Common/AutoPtr.h +++ b/CPP/Common/AutoPtr.h @@ -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 @@ template class CMyAutoPtr 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 --git a/CPP/Common/Blake3Reg.cpp b/CPP/Common/Blake3Reg.cpp index 1a488d2c..4e170572 100644 --- a/CPP/Common/Blake3Reg.cpp +++ b/CPP/Common/Blake3Reg.cpp @@ -1,4 +1,5 @@ // Blake3Reg.cpp /TR 2021-04-06 +// Blake3Reg.cpp /TR 2022-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // BLAKE3 -class CBLAKE3Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CBLAKE3Hasher + , IHasher +) blake3_hasher _ctx; Byte mtDummy[1 << 7]; public: CBLAKE3Hasher() { blake3_hasher_init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CBLAKE3Hasher::Init() throw() +Z7_COM7F_IMF2(void, CBLAKE3Hasher::Init()) { blake3_hasher_init(&_ctx); } -STDMETHODIMP_(void) CBLAKE3Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CBLAKE3Hasher::Update(const void *data, UInt32 size)) { blake3_hasher_update(&_ctx, data, size); } -STDMETHODIMP_(void) CBLAKE3Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CBLAKE3Hasher::Final(Byte *digest)) { blake3_hasher_finalize(&_ctx, digest, BLAKE3_OUT_LEN); } diff --git a/CPP/Common/C_FileIO.h b/CPP/Common/C_FileIO.h index 6818558b..12d94391 100644 --- a/CPP/Common/C_FileIO.h +++ b/CPP/Common/C_FileIO.h @@ -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 --git a/CPP/Common/CksumReg.cpp b/CPP/Common/CksumReg.cpp index 4cd79a7a..dc5127b7 100644 --- a/CPP/Common/CksumReg.cpp +++ b/CPP/Common/CksumReg.cpp @@ -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 @@ STDMETHODIMP_(void) CCksumHasher::Update(const void *data, UInt32 size) throw() _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 @@ STDMETHODIMP_(void) CCksumHasher::Final(Byte *digest) throw() size >>= 8; } const UInt32 val = crc.GetDigest(); - SetUi32(digest, val); + SetUi32(digest, val) } REGISTER_HASHER(CCksumHasher, 0x202, "CKSUM", 4) diff --git a/CPP/Common/ComTry.h b/CPP/Common/ComTry.h index 297c407b..84746a7d 100644 --- a/CPP/Common/ComTry.h +++ b/CPP/Common/ComTry.h @@ -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 --git a/CPP/Common/CommandLineParser.cpp b/CPP/Common/CommandLineParser.cpp index 6bea75bb..465e0fde 100644 --- a/CPP/Common/CommandLineParser.cpp +++ b/CPP/Common/CommandLineParser.cpp @@ -6,108 +6,41 @@ namespace NCommandLineParser { -static const wchar_t * _SplitCommandLine(const wchar_t* s, UString &dest) +bool SplitCommandLine(const UString &src, UString &dest1, UString &dest2) { - unsigned qcount = 0, bcount = 0; - wchar_t c; const wchar_t *f, *b; - - dest.Empty(); - - // skip spaces: - while (isblank(*s)) { s++; }; - b = f = s; - - while ((c = *s++) != 0) + dest1.Empty(); + dest2.Empty(); + bool quoteMode = false; + unsigned i; + for (i = 0; i < src.Len(); i++) { - switch (c) + wchar_t c = src[i]; + if ((c == L' ' || c == L'\t') && !quoteMode) { - case L'\\': - // a backslash - count them up to quote-char or regular char - bcount++; - break; - case L'"': - // check quote char is escaped: - if (!(bcount & 1)) - { - // preceded by an even number of '\', this is half that - // number of '\': - dest.AddFrom(f, (unsigned)(s - f - bcount/2 - 1)); f = s; - // count quote chars: - qcount++; - } - else - { - // preceded by an odd number of '\', this is half that - // number of '\' followed by an escaped '"': - dest.AddFrom(f, (unsigned)(s - f - bcount/2 - 2)); f = s; - dest += L'"'; - } - bcount = 0; - // now count the number of consecutive quotes (inclusive - // the quote that lead us here): - while (*s == L'"') - { - s++; - if (++qcount == 3) - { - dest += L'"'; - qcount = 0; - } - } - f = s; - if (qcount == 2) - qcount = 0; - break; - case L' ': - case L'\t': - // a space (end of arg or regular char): - if (!qcount) - { - // end of argument: - dest.AddFrom(f, (unsigned)(s - f - 1)); f = s; - // skip to the next one: - while (isblank(*s)) { s++; }; - bcount = 0; - goto done; - } - // no break - a space as regular char: - default: - // a regular character, reset backslash counter - bcount = 0; + dest2 = src.Ptr(i + 1); + return i != 0; } + if (c == L'\"') + quoteMode = !quoteMode; + else + dest1 += c; } - s--; // back to NTS-zero char - dest.AddFrom(f, (unsigned)(s - f)); -done: - // remaining part if argument was found, otherwise NULL: - return (dest.Len() || *b) ? s : NULL; -} - -bool SplitCommandLine(const UString& src, UString& dest1, UString& dest2) -{ - const wchar_t *s = src.Ptr(); - s = _SplitCommandLine(s, dest1); - if (s) { - dest2 = s; - return true; - } else { - dest2.Empty(); - return false; - } + return i != 0; } -void SplitCommandLine(const UString &src, UStringVector &parts) +void SplitCommandLine(const UString &s, UStringVector &parts) { - const wchar_t *s = src.Ptr(); + UString sTemp (s); + sTemp.Trim(); parts.Clear(); for (;;) { - UString s1; - s = _SplitCommandLine(s, s1); - if (s) + UString s1, s2; + if (SplitCommandLine(sTemp, s1, s2)) parts.Add(s1); - if (!s || !*s) + if (s2.IsEmpty()) break; + sTemp = s2; } } diff --git a/CPP/Common/CommandLineParser.h b/CPP/Common/CommandLineParser.h index fbd4fa58..fc6f028e 100644 --- a/CPP/Common/CommandLineParser.h +++ b/CPP/Common/CommandLineParser.h @@ -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 --git a/CPP/Common/Common.h b/CPP/Common/Common.h index 72db7a8b..0c77ab43 100644 --- a/CPP/Common/Common.h +++ b/CPP/Common/Common.h @@ -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 @@ If you don't need some things that are used in 7-Zip, 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 -#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + +#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__ + + +#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 --git a/CPP/Common/CrcReg.cpp b/CPP/Common/CrcReg.cpp index fdbba77b..6cda892f 100644 --- a/CPP/Common/CrcReg.cpp +++ b/CPP/Common/CrcReg.cpp @@ -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 @@ bool CCrcHasher::SetFunctions(UInt32 tSize) 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 @@ STDMETHODIMP CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVAR 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 --git a/CPP/Common/Defs.h b/CPP/Common/Defs.h index 9adb88cf..e302f358 100644 --- a/CPP/Common/Defs.h +++ b/CPP/Common/Defs.h @@ -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 @@ template inline int MyCompare(T a, T b) { 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 --git a/CPP/Common/DynLimBuf.cpp b/CPP/Common/DynLimBuf.cpp index 79141040..1d92af39 100644 --- a/CPP/Common/DynLimBuf.cpp +++ b/CPP/Common/DynLimBuf.cpp @@ -7,7 +7,7 @@ CDynLimBuf::CDynLimBuf(size_t limit) throw() { - _chars = 0; + _chars = NULL; _pos = 0; _size = 0; _sizeLimit = limit; diff --git a/CPP/Common/DynLimBuf.h b/CPP/Common/DynLimBuf.h index e80a7e7c..af22f076 100644 --- a/CPP/Common/DynLimBuf.h +++ b/CPP/Common/DynLimBuf.h @@ -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 --git a/CPP/Common/DynamicBuffer.h b/CPP/Common/DynamicBuffer.h index f6f6b157..714be4a7 100644 --- a/CPP/Common/DynamicBuffer.h +++ b/CPP/Common/DynamicBuffer.h @@ -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 @@ template class CDynamicBuffer } 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 --git a/CPP/Common/IntToString.cpp b/CPP/Common/IntToString.cpp index c87643c8..21b06806 100644 --- a/CPP/Common/IntToString.cpp +++ b/CPP/Common/IntToString.cpp @@ -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 @@ char * ConvertUInt64ToString(UInt64 val, char *s) throw() { 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 @@ void ConvertUInt32ToHex8Digits(UInt32 val, char *s) throw() { unsigned t = val & 0xF; val >>= 4; - s[i] = GET_HEX_CHAR(t);; + s[i] = GET_HEX_CHAR(t); } } @@ -121,7 +121,7 @@ void ConvertUInt32ToHex8Digits(UInt32 val, wchar_t *s) 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 @@ wchar_t * ConvertUInt64ToString(UInt64 val, wchar_t *s) throw() { 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 --git a/CPP/Common/IntToString.h b/CPP/Common/IntToString.h index d0a96ef1..f4fc662e 100644 --- a/CPP/Common/IntToString.h +++ b/CPP/Common/IntToString.h @@ -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 --git a/CPP/Common/Lang.cpp b/CPP/Common/Lang.cpp index 35d37525..b0b4342b 100644 --- a/CPP/Common/Lang.cpp +++ b/CPP/Common/Lang.cpp @@ -12,85 +12,95 @@ void CLang::Clear() throw() { _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 @@ bool CLang::Open(CFSTR fileName, const char *id) 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 @@ bool CLang::Open(CFSTR fileName, const char *id) 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 --git a/CPP/Common/Lang.h b/CPP/Common/Lang.h index cc66677d..76d5418e 100644 --- a/CPP/Common/Lang.h +++ b/CPP/Common/Lang.h @@ -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 --git a/CPP/Common/ListFileUtils.cpp b/CPP/Common/ListFileUtils.cpp index b361b378..e43dbc9c 100644 --- a/CPP/Common/ListFileUtils.cpp +++ b/CPP/Common/ListFileUtils.cpp @@ -66,7 +66,7 @@ bool ReadNamesFromListFile2(CFSTR fileName, UStringVector &strings, UINT codePag 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 @@ bool ReadNamesFromListFile2(CFSTR fileName, UStringVector &strings, UINT codePag 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 --git a/CPP/Common/ListFileUtils.h b/CPP/Common/ListFileUtils.h index a91e4b11..d43cc378 100644 --- a/CPP/Common/ListFileUtils.h +++ b/CPP/Common/ListFileUtils.h @@ -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 --git a/CPP/Common/Md2Reg.cpp b/CPP/Common/Md2Reg.cpp index 1c19b5d2..d3f47ecc 100644 --- a/CPP/Common/Md2Reg.cpp +++ b/CPP/Common/Md2Reg.cpp @@ -12,31 +12,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // MD2 -class CMD2Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CMD2Hasher + , IHasher +) MD2_CTX _ctx; Byte mtDummy[1 << 7]; public: CMD2Hasher() { MD2_Init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CMD2Hasher::Init() throw() +Z7_COM7F_IMF2(void, CMD2Hasher::Init()) { MD2_Init(&_ctx); } -STDMETHODIMP_(void) CMD2Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CMD2Hasher::Update(const void *data, UInt32 size)) { MD2_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CMD2Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CMD2Hasher::Final(Byte *digest)) { MD2_Final(digest, &_ctx); } diff --git a/CPP/Common/Md4Reg.cpp b/CPP/Common/Md4Reg.cpp index 26c4d0b0..06fea910 100644 --- a/CPP/Common/Md4Reg.cpp +++ b/CPP/Common/Md4Reg.cpp @@ -1,4 +1,5 @@ // Md4Reg.cpp /TR 2018-11-02 +// Md4Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // MD4 -class CMD4Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CMD4Hasher + , IHasher +) MD4_CTX _ctx; Byte mtDummy[1 << 7]; public: CMD4Hasher() { MD4_Init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CMD4Hasher::Init() throw() +Z7_COM7F_IMF2(void, CMD4Hasher::Init()) { MD4_Init(&_ctx); } -STDMETHODIMP_(void) CMD4Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CMD4Hasher::Update(const void *data, UInt32 size)) { MD4_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CMD4Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CMD4Hasher::Final(Byte *digest)) { MD4_Final(digest, &_ctx); } diff --git a/CPP/Common/Md5Reg.cpp b/CPP/Common/Md5Reg.cpp index c13bd1e9..8a2aee0b 100644 --- a/CPP/Common/Md5Reg.cpp +++ b/CPP/Common/Md5Reg.cpp @@ -1,4 +1,5 @@ // Md5Reg.cpp /TR 2018-11-02 +// Md5Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // MD5 -class CMD5Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CMD5Hasher + , IHasher +) MD5_CTX _ctx; Byte mtDummy[1 << 7]; public: CMD5Hasher() { MD5_Init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CMD5Hasher::Init() throw() +Z7_COM7F_IMF2(void, CMD5Hasher::Init()) { MD5_Init(&_ctx); } -STDMETHODIMP_(void) CMD5Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CMD5Hasher::Update(const void *data, UInt32 size)) { MD5_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CMD5Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CMD5Hasher::Final(Byte *digest)) { MD5_Final(digest, &_ctx); } diff --git a/CPP/Common/MyBuffer.h b/CPP/Common/MyBuffer.h index 18ab6fa4..bc829f4e 100644 --- a/CPP/Common/MyBuffer.h +++ b/CPP/Common/MyBuffer.h @@ -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 @@ template class CBuffer 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 @@ typedef CBuffer CByteBuffer; 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 @@ template class CObjArray 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 @@ template class CObjArray 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 @@ template class CObjArray2 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 @@ template class CObjArray2 } */ /* - CObjArray2(size_t size): _items(0), _size(0) + CObjArray2(size_t size): _items(NULL), _size(0) { if (size != 0) { @@ -247,7 +256,7 @@ template class CObjArray2 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 --git a/CPP/Common/MyBuffer2.h b/CPP/Common/MyBuffer2.h index 372d478c..23394f8a 100644 --- a/CPP/Common/MyBuffer2.h +++ b/CPP/Common/MyBuffer2.h @@ -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 @@ class CMidBuffer 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 CMidBuffer }; +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 --git a/CPP/Common/MyCom.h b/CPP/Common/MyCom.h index ff542780..65c4330c 100644 --- a/CPP/Common/MyCom.h +++ b/CPP/Common/MyCom.h @@ -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 @@ class CMyComPtr } }; +#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 @@ inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) 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 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 @@ class CMyComBSTR_Wipe: public CMyComBSTR /* 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 MY_QUERYINTERFACE_ENTRY(i) else if (iid == IID_ ## i) \ - { *outObject = (void *)(i *)this; } +#define Z7_COM_QI_ENTRY_UNKNOWN_0 \ + if (iid == IID_IUnknown) \ + { IUnknown *tu = this; *outObject = tu; } -#define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ - { *outObject = (void *)(IUnknown *)(i *)this; } +#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 MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) +#define Z7_COM_QI_BEGIN2(i) \ + Z7_COM_QI_BEGIN \ + Z7_COM_QI_ENTRY_UNKNOWN(i) \ + Z7_COM_QI_ENTRY(i) -#define MY_QUERYINTERFACE_END else return E_NOINTERFACE; ++__m_RefCount; /* AddRef(); */ return S_OK; } +#define Z7_COM_QI_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 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_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 Z7_COM_UNKNOWN_IMP_0 \ + Z7_COM_QI_BEGIN \ + Z7_COM_QI_ENTRY_UNKNOWN_0 \ + Z7_COM_QI_END \ + Z7_COM_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_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 --git a/CPP/Common/MyException.h b/CPP/Common/MyException.h index f0ad1115..06fbdea1 100644 --- a/CPP/Common/MyException.h +++ b/CPP/Common/MyException.h @@ -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 --git a/CPP/Common/MyGuidDef.h b/CPP/Common/MyGuidDef.h index 38aad6e6..ab9993bd 100644 --- a/CPP/Common/MyGuidDef.h +++ b/CPP/Common/MyGuidDef.h @@ -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 @@ typedef GUID CLSID; #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 --git a/CPP/Common/MyInitGuid.h b/CPP/Common/MyInitGuid.h index 04d77e21..3745c79a 100644 --- a/CPP/Common/MyInitGuid.h +++ b/CPP/Common/MyInitGuid.h @@ -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 @@ Also we need IID_IUnknown that is initialized in some file for linking: 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 --git a/CPP/Common/MyLinux.h b/CPP/Common/MyLinux.h index 98b453c1..a8454d7f 100644 --- a/CPP/Common/MyLinux.h +++ b/CPP/Common/MyLinux.h @@ -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 --git a/CPP/Common/MyMap.cpp b/CPP/Common/MyMap.cpp index 923846ae..0a200f0f 100644 --- a/CPP/Common/MyMap.cpp +++ b/CPP/Common/MyMap.cpp @@ -76,7 +76,7 @@ bool CMap32::Set(UInt32 key, UInt32 value) 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 @@ bool CMap32::Set(UInt32 key, UInt32 value) 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 @@ bool CMap32::Set(UInt32 key, UInt32 value) Nodes.Add(e2); return false; } - unsigned bit = GetSubBit(key, --bitPos); + const unsigned bit = GetSubBit(key, --bitPos); if (n.IsLeaf[bit]) { @@ -121,7 +121,7 @@ bool CMap32::Set(UInt32 key, UInt32 value) 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 --git a/CPP/Common/MyMap.h b/CPP/Common/MyMap.h index cbcbadd6..9ca55668 100644 --- a/CPP/Common/MyMap.h +++ b/CPP/Common/MyMap.h @@ -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 --git a/CPP/Common/MyString.cpp b/CPP/Common/MyString.cpp index 8344418c..fa5ef5ef 100644 --- a/CPP/Common/MyString.cpp +++ b/CPP/Common/MyString.cpp @@ -408,7 +408,7 @@ void AString::ReAlloc(unsigned newLimit) // 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 @@ void AString::ReAlloc2(unsigned newLimit) // 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 @@ AString &AString::operator=(char c) 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 @@ AString &AString::operator=(const char *s) 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 @@ AString &AString::operator=(const AString &s) 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 @@ void AString::SetFromWStr_if_Ascii(const wchar_t *s) 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 @@ void AString::SetFromBstr_if_Ascii(BSTR s) 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() { operator+=(' '); } 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 @@ void AString::SetFrom(const char *s, unsigned len) // no check 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 @@ int AString::ReverseFind_PathSepar() const throw() 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 @@ void UString::ReAlloc(unsigned newLimit) // 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 @@ void UString::ReAlloc2(unsigned newLimit) // 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 operator+(const wchar_t *s1, const UString &s2) { return UString(s1, MyS UString::UString() { - _chars = 0; + _chars = NULL; _chars = MY_STRING_NEW_wchar_t(kStartStringCapacity); _len = 0; _limit = kStartStringCapacity - 1; @@ -1163,7 +1167,7 @@ UString &UString::operator=(wchar_t c) 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 @@ UString &UString::operator=(const wchar_t *s) 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 @@ UString &UString::operator=(const UString &s) 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; } @@ -1206,22 +1210,12 @@ UString &UString::operator=(const UString &s) return *this; } -void UString::AddFrom(const wchar_t *s, unsigned len) // no check -{ - if (len) { - Grow(len); - wmemcpy(_chars + _len, s, len); - _len += len; - _chars[_len] = 0; - } -} - void UString::SetFrom(const wchar_t *s, unsigned len) // no check { 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; } @@ -1259,7 +1253,7 @@ void UString::SetFromBstr(LPCOLESTR s) 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; } @@ -1299,7 +1293,7 @@ UString &UString::operator=(const char *s) 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; } @@ -1311,6 +1305,7 @@ UString &UString::operator=(const char *s) return *this; } +void UString::Add_Dot() { operator+=(L'.'); } void UString::Add_Space() { operator+=(L' '); } void UString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); } @@ -1403,31 +1398,26 @@ int UString::ReverseFind(wchar_t c) const throw() { 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() @@ -1611,7 +1601,7 @@ void UString2::ReAlloc2(unsigned newLimit) // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0); if (_chars) { - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = NULL; // _len = 0; } @@ -1661,7 +1651,7 @@ UString2 &UString2::operator=(wchar_t c) { wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1); if (_chars) - MY_STRING_DELETE(_chars); + MY_STRING_DELETE(_chars) _chars = newBuf; } _len = 1; @@ -1679,7 +1669,7 @@ UString2 &UString2::operator=(const wchar_t *s) { 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; @@ -1694,7 +1684,7 @@ void UString2::SetFromAscii(const char *s) { 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; @@ -1713,7 +1703,7 @@ UString2 &UString2::operator=(const UString2 &s) { 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; @@ -1804,46 +1794,74 @@ FString us2fs(const wchar_t *s) #endif // USE_UNICODE_FSTRING -// ---------------------------------------- -UString GetQuotedString(const UString &src) +bool CStringFinder::FindWord_In_LowCaseAsciiList_NoCase(const char *p, const wchar_t *str) { - UString s2 ('\"'); - unsigned bcount = 0; - wchar_t c; const wchar_t *f = src.Ptr(), *s = f, *b = f; - // add string considering backslashes before quote (escape them): - while (1) + _temp.Empty(); + for (;;) { - c = *s++; - switch (c) - { - case L'\\': - // a backslash - save the position and count them up to quote-char or regular char - if (!bcount) b = s-1; - bcount++; - break; - case L'\0': - // end of string (it is always quoted, so need to escape backslashes too): - case L'"': - // add part before backslash (and unescaped backslashes if some are there): - s2.AddFrom(f, (unsigned)(s - f - 1)); - f = s; - if (bcount) { - // escape backslashes before quote (same count of BS again): - s2.AddFrom(b, (unsigned)(s - b - 1)); - } - // done if end of string - if (c == L'\0') goto done; - // escape this quote char: - s2 += L"\\\""; + const wchar_t c = *str++; + if (c == 0) break; - default: - // a regular character, reset backslash counter - bcount = 0; + 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++ != ' '); } - s2.AddFrom(f, (unsigned)(s - f - 1)); -done: + + 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); +} + +UString GetQuotedString(const UString &s) +{ + UString s2 ('\"'); + s2 += s; s2 += '\"'; return s2; } diff --git a/CPP/Common/MyString.h b/CPP/Common/MyString.h index 6d0666fc..f0592ba6 100644 --- a/CPP/Common/MyString.h +++ b/CPP/Common/MyString.h @@ -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 @@ inline char *MyStpCpy(char *dest, const char *src) { for (;;) { - char c = *src; + const char c = *src; *dest = c; if (c == 0) return dest; @@ -79,6 +80,13 @@ inline char *MyStpCpy(char *dest, const char *src) } } +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 MyStringCopy(wchar_t *dest, const wchar_t *src) 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 @@ inline wchar_t *MyWcpCpy(wchar_t *dest, const wchar_t *src) { 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 char *s1, const char *s2) throw(); 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 @@ class AString 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 @@ class AString 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 @@ class AString 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 @@ class AString 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 @@ class AString 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 @@ class AString _chars[index] = 0; } } + void DeleteFrom(int index) + { + DeleteFrom((unsigned)index); + } + void Wipe_and_Empty() { @@ -474,7 +500,7 @@ class AString 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 @@ class UString 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 @@ class UString 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 @@ class UString wchar_t *GetBuf() { return _chars; } + /* + wchar_t *GetBuf_GetMaxAvail(unsigned &availBufLen) + { + availBufLen = _limit; + return _chars; + } + */ + wchar_t *GetBuf(unsigned minLen) { if (minLen > _limit) @@ -628,7 +663,6 @@ class UString UString &operator=(char c) { return (*this)=((wchar_t)(unsigned char)c); } UString &operator=(const wchar_t *s); UString &operator=(const UString &s); - void AddFrom(const wchar_t *s, unsigned len); // no check void SetFrom(const wchar_t *s, unsigned len); // no check void SetFromBstr(LPCOLESTR s); UString &operator=(const char *s); @@ -651,6 +685,7 @@ class UString 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); @@ -663,6 +698,7 @@ class UString 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); } @@ -721,10 +757,12 @@ class UString 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) @@ -747,7 +785,7 @@ class UString 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) {} @@ -835,7 +873,7 @@ class UString2 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; } @@ -913,7 +951,7 @@ typedef CObjectVector CSysStringVector; #ifdef USE_UNICODE_FSTRING - #define __FTEXT(quote) L##quote + #define MY_FTEXT(quote) L##quote typedef wchar_t FChar; typedef UString FString; @@ -924,9 +962,9 @@ typedef CObjectVector CSysStringVector; 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; @@ -980,9 +1018,9 @@ typedef CObjectVector CSysStringVector; 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) @@ -995,13 +1033,29 @@ typedef const FChar *CFSTR; 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 + +UString GetQuotedString(const UString &s); + + #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'\\' @@ -1009,7 +1063,3 @@ typedef CObjectVector FStringVector; #define WCHAR_IN_FILE_NAME_BACKSLASH_REPLACEMENT ((wchar_t)((unsigned)(0xF000) + (unsigned)'\\')) // #define WCHAR_IN_FILE_NAME_BACKSLASH_REPLACEMENT '_' #endif - -UString GetQuotedString(const UString &s); - -#endif diff --git a/CPP/Common/MyTypes.h b/CPP/Common/MyTypes.h index 71b8e7fa..8f44f672 100644 --- a/CPP/Common/MyTypes.h +++ b/CPP/Common/MyTypes.h @@ -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 @@ struct CBoolPair } }; -#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 --git a/CPP/Common/MyUnknown.h b/CPP/Common/MyUnknown.h index ff025cb5..75ee96fa 100644 --- a/CPP/Common/MyUnknown.h +++ b/CPP/Common/MyUnknown.h @@ -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 --git a/CPP/Common/MyVector.h b/CPP/Common/MyVector.h index 3417a176..9ee71058 100644 --- a/CPP/Common/MyVector.h +++ b/CPP/Common/MyVector.h @@ -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 @@ class CRecordVector 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 @@ class CRecordVector 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 @@ class CRecordVector { 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 @@ class CRecordVector 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 @@ class CRecordVector 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 @@ class CRecordVector 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 @@ class CObjectVector 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 @@ class CObjectVector delete (T *)_v[index]; _v.Delete(index); } + // void Delete(int index) { Delete((unsigned)index); } /* void Delete(unsigned index, unsigned num) diff --git a/CPP/Common/MyWindows.cpp b/CPP/Common/MyWindows.cpp index 88f312fb..ae284ebc 100644 --- a/CPP/Common/MyWindows.cpp +++ b/CPP/Common/MyWindows.cpp @@ -78,7 +78,7 @@ BSTR SysAllocStringLen(const OLECHAR *s, UINT len) BSTR SysAllocString(const OLECHAR *s) { if (!s) - return 0; + return NULL; const OLECHAR *s2 = s; while (*s2 != 0) s2++; @@ -181,7 +181,7 @@ BOOL WINAPI FileTimeToLocalFileTime(const FILETIME *fileTime, FILETIME *localFil { 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 @@ BOOL WINAPI LocalFileTimeToFileTime(const FILETIME *localFileTime, FILETIME *fil { 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 @@ VOID WINAPI GetSystemTimeAsFileTime(FILETIME *ft) 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 --git a/CPP/Common/MyWindows.h b/CPP/Common/MyWindows.h index 15db5243..a76e14b7 100644 --- a/CPP/Common/MyWindows.h +++ b/CPP/Common/MyWindows.h @@ -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 @@ typedef LONG SCODE; #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 PROPVARIANT tagVARIANT; 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 @@ typedef struct tagSTATPROPSTG 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); +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); -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 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 --git a/CPP/Common/MyXml.cpp b/CPP/Common/MyXml.cpp index e0145188..a879d34a 100644 --- a/CPP/Common/MyXml.cpp +++ b/CPP/Common/MyXml.cpp @@ -81,7 +81,7 @@ AString CXmlItem::GetSubStringForTag(const char *tag) const const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) { - SKIP_SPACES(s); + SKIP_SPACES(s) const char *beg = s; for (;;) @@ -102,7 +102,7 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) IsTag = true; s++; - SKIP_SPACES(s); + SKIP_SPACES(s) beg = s; for (;; s++) @@ -115,11 +115,11 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) 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 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) SubItems.Clear(); for (;;) { - SKIP_SPACES(s); + SKIP_SPACES(s) if (s[0] == '<' && s[1] == '/') break; CXmlItem &item = SubItems.AddNew(); @@ -168,11 +168,11 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) 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 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) 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 @@ void CXmlItem::AppendTo(AString &s) const FOR_VECTOR (i, Props) { const CXmlProp &prop = Props[i]; - s += ' '; + s.Add_Space(); s += prop.Name; s += '='; s += '\"'; @@ -228,7 +228,7 @@ void CXmlItem::AppendTo(AString &s) const { 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 @@ bool CXml::Parse(const char *s) s = Root.ParseItem(s, 1000); if (!s || !Root.IsTag) return false; - SKIP_SPACES(s); + SKIP_SPACES(s) return *s == 0; } diff --git a/CPP/Common/MyXml.h b/CPP/Common/MyXml.h index 00b7113a..5362602c 100644 --- a/CPP/Common/MyXml.h +++ b/CPP/Common/MyXml.h @@ -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 --git a/CPP/Common/NewHandler.cpp b/CPP/Common/NewHandler.cpp index 65ef41d4..c95833e5 100644 --- a/CPP/Common/NewHandler.cpp +++ b/CPP/Common/NewHandler.cpp @@ -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 @@ __cdecl #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 @@ __cdecl #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 @@ __cdecl 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 @@ __cdecl #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 @@ operator delete[](void *p) throw() #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,52 +158,126 @@ void * __cdecl operator new(size_t size) 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 --git a/CPP/Common/NewHandler.h b/CPP/Common/NewHandler.h index aedeca64..50f6d0a8 100644 --- a/CPP/Common/NewHandler.h +++ b/CPP/Common/NewHandler.h @@ -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 @@ don't throw exception in operator new(). 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 @@ void my_delete(void *p) throw(); #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 --git a/CPP/Common/Random.h b/CPP/Common/Random.h index e784e984..283869e2 100644 --- a/CPP/Common/Random.h +++ b/CPP/Common/Random.h @@ -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 --git a/CPP/Common/Sha1Reg.cpp b/CPP/Common/Sha1Reg.cpp index 0cb2baf7..64eef34a 100644 --- a/CPP/Common/Sha1Reg.cpp +++ b/CPP/Common/Sha1Reg.cpp @@ -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 @@ class CSha1Hasher: 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 --git a/CPP/Common/Sha256Reg.cpp b/CPP/Common/Sha256Reg.cpp index 5f3a35b0..b5689c42 100644 --- a/CPP/Common/Sha256Reg.cpp +++ b/CPP/Common/Sha256Reg.cpp @@ -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 @@ class CSha256Hasher: 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 --git a/CPP/Common/Sha3-256Reg.cpp b/CPP/Common/Sha3-256Reg.cpp index 07bffb31..7c1923d0 100644 --- a/CPP/Common/Sha3-256Reg.cpp +++ b/CPP/Common/Sha3-256Reg.cpp @@ -1,4 +1,5 @@ // Sha3-256Reg.cpp /TR 2023-06-18 +// Sha3-256Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // SHA3-256 -class CSHA3_256Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSHA3_256Hasher + , IHasher +) SHA3_CTX _ctx; Byte mtDummy[1 << 7]; public: CSHA3_256Hasher() { SHA3_Init(&_ctx, 256); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CSHA3_256Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSHA3_256Hasher::Init()) { SHA3_Init(&_ctx, 256); } -STDMETHODIMP_(void) CSHA3_256Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSHA3_256Hasher::Update(const void *data, UInt32 size)) { SHA3_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CSHA3_256Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSHA3_256Hasher::Final(Byte *digest)) { SHA3_Final(digest, &_ctx); } diff --git a/CPP/Common/Sha3-384Reg.cpp b/CPP/Common/Sha3-384Reg.cpp index 3cdd3991..006c7069 100644 --- a/CPP/Common/Sha3-384Reg.cpp +++ b/CPP/Common/Sha3-384Reg.cpp @@ -1,4 +1,5 @@ // Sha3-384Reg.cpp /TR 2023-06-18 +// Sha3-384Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // SHA3-384 -class CSHA3_384Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSHA3_384Hasher + , IHasher +) SHA3_CTX _ctx; Byte mtDummy[1 << 7]; public: CSHA3_384Hasher() { SHA3_Init(&_ctx, 384); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CSHA3_384Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSHA3_384Hasher::Init()) { SHA3_Init(&_ctx, 384); } -STDMETHODIMP_(void) CSHA3_384Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSHA3_384Hasher::Update(const void *data, UInt32 size)) { SHA3_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CSHA3_384Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSHA3_384Hasher::Final(Byte *digest)) { SHA3_Final(digest, &_ctx); } diff --git a/CPP/Common/Sha3-512Reg.cpp b/CPP/Common/Sha3-512Reg.cpp index bc7894a8..d1f9ba62 100644 --- a/CPP/Common/Sha3-512Reg.cpp +++ b/CPP/Common/Sha3-512Reg.cpp @@ -1,4 +1,5 @@ // Sha3-512Reg.cpp /TR 2023-06-18 +// Sha3-512Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // SHA3-512 -class CSHA3_512Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSHA3_512Hasher + , IHasher +) SHA3_CTX _ctx; Byte mtDummy[1 << 7]; public: CSHA3_512Hasher() { SHA3_Init(&_ctx, 512); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CSHA3_512Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSHA3_512Hasher::Init()) { SHA3_Init(&_ctx, 512); } -STDMETHODIMP_(void) CSHA3_512Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSHA3_512Hasher::Update(const void *data, UInt32 size)) { SHA3_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CSHA3_512Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSHA3_512Hasher::Final(Byte *digest)) { SHA3_Final(digest, &_ctx); } diff --git a/CPP/Common/Sha384Reg.cpp b/CPP/Common/Sha384Reg.cpp index aa162cc6..57d956cd 100644 --- a/CPP/Common/Sha384Reg.cpp +++ b/CPP/Common/Sha384Reg.cpp @@ -1,4 +1,5 @@ // Sha384Reg.cpp /TR 2018-11-02 +// Sha384Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // SHA384 -class CSHA384Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSHA384Hasher + , IHasher +) SHA384_CTX _ctx; Byte mtDummy[1 << 7]; public: CSHA384Hasher() { SHA384_Init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CSHA384Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSHA384Hasher::Init()) { SHA384_Init(&_ctx); } -STDMETHODIMP_(void) CSHA384Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSHA384Hasher::Update(const void *data, UInt32 size)) { SHA384_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CSHA384Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSHA384Hasher::Final(Byte *digest)) { SHA384_Final(digest, &_ctx); } diff --git a/CPP/Common/Sha512Reg.cpp b/CPP/Common/Sha512Reg.cpp index a9e8d424..b862305e 100644 --- a/CPP/Common/Sha512Reg.cpp +++ b/CPP/Common/Sha512Reg.cpp @@ -1,4 +1,5 @@ // Sha512Reg.cpp /TR 2018-11-02 +// Sha512Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -12,31 +13,28 @@ EXTERN_C_END #include "../7zip/Common/RegisterCodec.h" // SHA512 -class CSHA512Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CSHA512Hasher + , IHasher +) SHA512_CTX _ctx; Byte mtDummy[1 << 7]; public: CSHA512Hasher() { SHA512_Init(&_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CSHA512Hasher::Init() throw() +Z7_COM7F_IMF2(void, CSHA512Hasher::Init()) { SHA512_Init(&_ctx); } -STDMETHODIMP_(void) CSHA512Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CSHA512Hasher::Update(const void *data, UInt32 size)) { SHA512_Update(&_ctx, (const Byte *)data, size); } -STDMETHODIMP_(void) CSHA512Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CSHA512Hasher::Final(Byte *digest)) { SHA512_Final(digest, &_ctx); } diff --git a/CPP/Common/StdAfx.h b/CPP/Common/StdAfx.h index 420f5c32..a5228b0a 100644 --- a/CPP/Common/StdAfx.h +++ b/CPP/Common/StdAfx.h @@ -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 --git a/CPP/Common/StdInStream.cpp b/CPP/Common/StdInStream.cpp index abad34b6..7b209f1c 100644 --- a/CPP/Common/StdInStream.cpp +++ b/CPP/Common/StdInStream.cpp @@ -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 @@ bool CStdInStream::Close() throw() _streamIsOpen = (fclose(_stream) != 0); return !_streamIsOpen; } +*/ bool CStdInStream::ScanAStringUntilNewLine(AString &s) { diff --git a/CPP/Common/StdInStream.h b/CPP/Common/StdInStream.h index 71578eb4..81ca3bf6 100644 --- a/CPP/Common/StdInStream.h +++ b/CPP/Common/StdInStream.h @@ -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 --git a/CPP/Common/StdOutStream.cpp b/CPP/Common/StdOutStream.cpp index 40799e22..cfa5fdec 100644 --- a/CPP/Common/StdOutStream.cpp +++ b/CPP/Common/StdOutStream.cpp @@ -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 @@ bool CStdOutStream::Close() throw() _streamIsOpen = false; return true; } +*/ bool CStdOutStream::Flush() throw() { @@ -73,7 +75,7 @@ void CStdOutStream::Convert_UString_to_AString(const UString &src, AString &dest 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 --git a/CPP/Common/StdOutStream.h b/CPP/Common/StdOutStream.h index 93f1dfa4..bd15d7cb 100644 --- a/CPP/Common/StdOutStream.h +++ b/CPP/Common/StdOutStream.h @@ -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 @@ class CStdOutStream 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 --git a/CPP/Common/StringConvert.cpp b/CPP/Common/StringConvert.cpp index c0bde0fa..f25396a6 100644 --- a/CPP/Common/StringConvert.cpp +++ b/CPP/Common/StringConvert.cpp @@ -534,6 +534,7 @@ AString UnicodeStringToMultiByte(const UString &src, UINT codePage) +#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE) #ifdef _WIN32 #define U_to_A(a, b, c) UnicodeStringToMultiByte2 @@ -544,8 +545,6 @@ AString UnicodeStringToMultiByte(const UString &src, UINT codePage) // #define A_to_U(a, b, c) MultiByteToUnicodeString2_Native(a, b) #endif -#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE) - bool IsNativeUTF8() { UString u; diff --git a/CPP/Common/StringConvert.h b/CPP/Common/StringConvert.h index 865c0254..2092a2da 100644 --- a/CPP/Common/StringConvert.h +++ b/CPP/Common/StringConvert.h @@ -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 --git a/CPP/Common/StringToInt.h b/CPP/Common/StringToInt.h index 4057e494..c9dce7d1 100644 --- a/CPP/Common/StringToInt.h +++ b/CPP/Common/StringToInt.h @@ -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 --git a/CPP/Common/TextConfig.cpp b/CPP/Common/TextConfig.cpp index 1428aab5..d3e561c2 100644 --- a/CPP/Common/TextConfig.cpp +++ b/CPP/Common/TextConfig.cpp @@ -15,7 +15,7 @@ static AString GetIDString(const char *s, unsigned &finishPos) 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 @@ static bool SkipSpaces(const AString &s, unsigned &pos) { for (; pos < s.Len(); pos++) { - char c = s[pos]; + const char c = s[pos]; if (!IsDelimitChar(c)) { if (c != ';') @@ -111,13 +111,13 @@ int FindTextConfigItem(const CObjectVector &pairs, const char * { 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 --git a/CPP/Common/TextConfig.h b/CPP/Common/TextConfig.h index cc7ce412..2263a442 100644 --- a/CPP/Common/TextConfig.h +++ b/CPP/Common/TextConfig.h @@ -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 --git a/CPP/Common/UTFConvert.cpp b/CPP/Common/UTFConvert.cpp index ac069dba..fb166b7f 100644 --- a/CPP/Common/UTFConvert.cpp +++ b/CPP/Common/UTFConvert.cpp @@ -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 @@ we can place 128 ESCAPE chars to #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 @@ we can place 128 ESCAPE chars to 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 @@ we can place 128 ESCAPE chars to #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 @@ void CUtf8Check::Check_Buf(const char *src, size_t size) throw() 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 @@ void CUtf8Check::Check_Buf(const char *src, size_t size) throw() if (pos == size) Truncated = true; else - _ERROR_UTF8_CHECK + UTF_ERROR_UTF8_CHECK } #ifdef UTF_ESCAPE_BASE @@ -268,7 +268,7 @@ bool CheckUTF8(const char *src, bool allowReduced) throw() return false; unsigned numBytes; - _UTF8_HEAD_PARSE + MY_UTF8_HEAD_PARSE else return false; @@ -285,7 +285,7 @@ bool CheckUTF8(const char *src, bool allowReduced) throw() } while (--numBytes); - if (val < _UTF8_RANGE(pos - 1)) + if (val < MY_UTF8_RANGE(pos - 1)) return false; if (val >= 0x110000) @@ -303,18 +303,18 @@ bool CheckUTF8(const char *src, bool allowReduced) throw() #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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const 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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const 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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const 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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const 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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const 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 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const -#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 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi if (val < 0x80) continue; - if (val < _UTF8_RANGE(1)) + if (val < MY_UTF8_RANGE(1)) { size++; continue; @@ -492,12 +492,12 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi #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 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi 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 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim 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 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim #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 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim } #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 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim { 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 @@ bool ConvertUTF8ToUnicode_Flags(const AString &src, UString &dest, unsigned flag 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 @@ void ConvertUnicodeToUTF8_Flags(const UString &src, AString &dest, unsigned flag 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 @@ bool Unicode_IsThere_Utf16SurrogateError(const UString &src) } */ -#ifndef _WCHART_IS_16BIT +#ifndef Z7_WCHART_IS_16BIT void Convert_UnicodeEsc16_To_UnicodeEscHigh #if UTF_ESCAPE_PLANE == 0 diff --git a/CPP/Common/UTFConvert.h b/CPP/Common/UTFConvert.h index 37c4975a..94a8024f 100644 --- a/CPP/Common/UTFConvert.h +++ b/CPP/Common/UTFConvert.h @@ -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 @@ if (allowReduced == true) - it allows truncated last character-Utf8-sequence 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 @@ UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 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 @@ UTF_FLAG__FROM_UTF8__USE_ESCAPE 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 @@ Main USE CASES with UTF-8 <-> UTF-16 conversions: 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 @@ Main USE CASES with UTF-8 <-> UTF-16 conversions: { 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 Convert_UTF8_Buf_To_Unicode(const char *src, size_t srcSize, UString &dest, 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 @@ UTF_FLAG__TO_UTF8__SURROGATE_ERROR 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__SURROGATE_ERROR } -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 @@ Main use cases: 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_BmpEscape(const UString &src); 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 --git a/CPP/Common/Wildcard.cpp b/CPP/Common/Wildcard.cpp index 861f3f71..798cbd95 100644 --- a/CPP/Common/Wildcard.cpp +++ b/CPP/Common/Wildcard.cpp @@ -125,8 +125,8 @@ static bool EnhancedMaskTest(const wchar_t *mask, const wchar_t *name) { 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 @@ int CCensor::FindPairForPrefix(const UString &prefix) const 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 --git a/CPP/Common/Wildcard.h b/CPP/Common/Wildcard.h index 0fa48873..4f81da92 100644 --- a/CPP/Common/Wildcard.h +++ b/CPP/Common/Wildcard.h @@ -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 @@ class CCensorNode MY_UNCOPYABLE CCensorNode(): Parent(NULL) // , ExcludeDirItems(false) - {}; + {} CCensorNode(const UString &name, CCensorNode *parent): Parent(parent) diff --git a/CPP/Common/XXH32Reg.cpp b/CPP/Common/XXH32Reg.cpp index 8c3dd358..bf670841 100644 --- a/CPP/Common/XXH32Reg.cpp +++ b/CPP/Common/XXH32Reg.cpp @@ -1,4 +1,5 @@ // XXH32Reg.cpp /TR 2018-11-02 +// XXH32Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -11,32 +12,29 @@ #include "../7zip/Common/RegisterCodec.h" // XXH32 -class CXXH32Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CXXH32Hasher + , IHasher +) XXH32_state_t *_ctx; Byte mtDummy[1 << 7]; public: CXXH32Hasher() { _ctx = XXH32_createState(); } ~CXXH32Hasher() { XXH32_freeState(_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CXXH32Hasher::Init() throw() +Z7_COM7F_IMF2(void, CXXH32Hasher::Init()) { XXH32_reset(_ctx, 0); } -STDMETHODIMP_(void) CXXH32Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CXXH32Hasher::Update(const void *data, UInt32 size)) { XXH32_update(_ctx, data, size); } -STDMETHODIMP_(void) CXXH32Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CXXH32Hasher::Final(Byte *digest)) { UInt32 val = XXH32_digest(_ctx); SetUi32(digest, val); diff --git a/CPP/Common/XXH64Reg.cpp b/CPP/Common/XXH64Reg.cpp index f8afa709..33c11073 100644 --- a/CPP/Common/XXH64Reg.cpp +++ b/CPP/Common/XXH64Reg.cpp @@ -1,4 +1,5 @@ // XXH64Reg.cpp /TR 2018-11-02 +// XXH32Reg.cpp /TR 2023-10-22 #include "StdAfx.h" @@ -11,32 +12,29 @@ #include "../7zip/Common/RegisterCodec.h" // XXH64 -class CXXH64Hasher: - public IHasher, - public CMyUnknownImp -{ +Z7_CLASS_IMP_COM_1( + CXXH64Hasher + , IHasher +) XXH64_state_t *_ctx; Byte mtDummy[1 << 7]; public: CXXH64Hasher() { _ctx = XXH64_createState(); } ~CXXH64Hasher() { XXH64_freeState(_ctx); } - - MY_UNKNOWN_IMP1(IHasher) - INTERFACE_IHasher(;) }; -STDMETHODIMP_(void) CXXH64Hasher::Init() throw() +Z7_COM7F_IMF2(void, CXXH64Hasher::Init()) { XXH64_reset(_ctx, 0); } -STDMETHODIMP_(void) CXXH64Hasher::Update(const void *data, UInt32 size) throw() +Z7_COM7F_IMF2(void, CXXH64Hasher::Update(const void *data, UInt32 size)) { XXH64_update(_ctx, data, size); } -STDMETHODIMP_(void) CXXH64Hasher::Final(Byte *digest) throw() +Z7_COM7F_IMF2(void, CXXH64Hasher::Final(Byte *digest)) { UInt64 val = XXH64_digest(_ctx); SetUi64(digest, val); diff --git a/CPP/Common/XzCrc64Reg.cpp b/CPP/Common/XzCrc64Reg.cpp index 33b52493..e9e67efc 100644 --- a/CPP/Common/XzCrc64Reg.cpp +++ b/CPP/Common/XzCrc64Reg.cpp @@ -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 --git a/CPP/Windows/COM.h b/CPP/Windows/COM.h index cee7f702..a8780cac 100644 --- a/CPP/Windows/COM.h +++ b/CPP/Windows/COM.h @@ -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 @@ class CComInitializer // 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 @@ class CStgMedium 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 --git a/CPP/Windows/Clipboard.h b/CPP/Windows/Clipboard.h index 60fedc13..3b4f2fe5 100644 --- a/CPP/Windows/Clipboard.h +++ b/CPP/Windows/Clipboard.h @@ -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 @@ class CClipboard { bool m_Open; public: - CClipboard(): m_Open(false) {}; + CClipboard(): m_Open(false) {} ~CClipboard() { Close(); } bool Open(HWND wndNewOwner) throw(); bool Close() throw(); diff --git a/CPP/Windows/CommonDialog.cpp b/CPP/Windows/CommonDialog.cpp index eaaecada..7a92d5f9 100644 --- a/CPP/Windows/CommonDialog.cpp +++ b/CPP/Windows/CommonDialog.cpp @@ -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 @@ extern bool g_IsNT; namespace NWindows { -#ifndef _UNICODE +/* + GetSaveFileName() + GetOpenFileName() + OPENFILENAME -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() +(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. } -#endif +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 -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; } -}; - -bool CDoubleZeroStringListW::Add(LPCWSTR s) throw() -{ - unsigned len = MyStringLen(s) + 1; - if (len >= Size) - return false; - MyStringCopy(Buf, s); - Buf += len; - Size -= len; - return true; -} +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 @@ contain additional members: #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 @@ So we use size of old version of structure. */ #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]; + p.hwndOwner = hwndOwner; + if (size > 1) { - CDoubleZeroStringListW dz(filterBuf, kFilterBufSize); - dz.Add(filterDescription ? filterDescription : filter); - dz.Add(filter); - dz.Finish(); 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 --git a/CPP/Windows/CommonDialog.h b/CPP/Windows/CommonDialog.h index aaf17ac5..85b071f0 100644 --- a/CPP/Windows/CommonDialog.h +++ b/CPP/Windows/CommonDialog.h @@ -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 --git a/CPP/Windows/Console.h b/CPP/Windows/Console.h index 43e02fa6..818b8d43 100644 --- a/CPP/Windows/Console.h +++ b/CPP/Windows/Console.h @@ -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 --git a/CPP/Windows/Control/ComboBox.cpp b/CPP/Windows/Control/ComboBox.cpp index f6ed8d34..8da487d4 100644 --- a/CPP/Windows/Control/ComboBox.cpp +++ b/CPP/Windows/Control/ComboBox.cpp @@ -43,10 +43,10 @@ LRESULT CComboBox::GetLBText(int index, UString &s) 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 @@ LRESULT CComboBox::GetLBText(int index, UString &s) 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 --git a/CPP/Windows/Control/ComboBox.h b/CPP/Windows/Control/ComboBox.h index f08b1f7c..2a60b8aa 100644 --- a/CPP/Windows/Control/ComboBox.h +++ b/CPP/Windows/Control/ComboBox.h @@ -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 @@ class CComboBox: public CWindow #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 @@ class CComboBox: public CWindow /* 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 @@ class CComboBoxEx: public CComboBox /* 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 @@ class CComboBoxEx: public CComboBox #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 --git a/CPP/Windows/Control/CommandBar.h b/CPP/Windows/Control/CommandBar.h index a6197447..d1b2f178 100644 --- a/CPP/Windows/Control/CommandBar.h +++ b/CPP/Windows/Control/CommandBar.h @@ -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 @@ class CCommandBar: public NWindows::CWindow // 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 --git a/CPP/Windows/Control/Dialog.cpp b/CPP/Windows/Control/Dialog.cpp index 9ddd2342..c8f1bd27 100644 --- a/CPP/Windows/Control/Dialog.cpp +++ b/CPP/Windows/Control/Dialog.cpp @@ -18,7 +18,14 @@ extern bool g_IsNT; 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 @@ bool CDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) 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::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) } } -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 @@ bool CDialog::OnButtonClicked(int buttonID, HWND /* buttonHWND */) 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 @@ int CDialog::Units_To_Pixels_X(int units) 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 @@ bool CDialog::GetItemSizes(int id, int &x, int &y) 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 @@ void CDialog::NormalizePosition() 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 --git a/CPP/Windows/Control/Dialog.h b/CPP/Windows/Control/Dialog.h index 8a39e996..06be4bf9 100644 --- a/CPP/Windows/Control/Dialog.h +++ b/CPP/Windows/Control/Dialog.h @@ -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 @@ namespace NControl { 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 @@ class CDialog: public CWindow 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 @@ class CDialog: public CWindow 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); } + UINT IsButtonChecked_BST(unsigned buttonID) const + { return IsDlgButtonChecked(_window, (int)buttonID); } + bool IsButtonCheckedBool(unsigned buttonID) const + { return (IsButtonChecked_BST(buttonID) == BST_CHECKED); } - bool CheckRadioButton(int firstButtonID, int lastButtonID, int checkButtonID) - { return BOOLToBool(::CheckRadioButton(_window, firstButtonID, lastButtonID, checkButtonID)); } + 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 @@ class CDialog: public CWindow 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 @@ class CDialog: public CWindow 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 @@ class CModelessDialog: public CDialog #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 @@ class CModalDialog: public CDialog #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 --git a/CPP/Windows/Control/Edit.h b/CPP/Windows/Control/Edit.h index 51a22c53..963470d7 100644 --- a/CPP/Windows/Control/Edit.h +++ b/CPP/Windows/Control/Edit.h @@ -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 --git a/CPP/Windows/Control/ImageList.h b/CPP/Windows/Control/ImageList.h index 19feb117..688f1777 100644 --- a/CPP/Windows/Control/ImageList.h +++ b/CPP/Windows/Control/ImageList.h @@ -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 @@ class CImageList 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 --git a/CPP/Windows/Control/ListView.cpp b/CPP/Windows/Control/ListView.cpp index 16cfd396..3e8786a1 100644 --- a/CPP/Windows/Control/ListView.cpp +++ b/CPP/Windows/Control/ListView.cpp @@ -20,78 +20,85 @@ bool CListView::CreateEx(DWORD exStyle, DWORD style, 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 --git a/CPP/Windows/Control/ListView.h b/CPP/Windows/Control/ListView.h index a13b1041..11a33a07 100644 --- a/CPP/Windows/Control/ListView.h +++ b/CPP/Windows/Control/ListView.h @@ -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 @@ class CListView: public NWindows::CWindow } 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 @@ class CListView: public NWindows::CWindow */ 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 @@ class CListView: public NWindows::CWindow 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 @@ class CListView: public NWindows::CWindow 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 CListView: public NWindows::CWindow 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 --git a/CPP/Windows/Control/ProgressBar.h b/CPP/Windows/Control/ProgressBar.h index 03743067..2256aa9e 100644 --- a/CPP/Windows/Control/ProgressBar.h +++ b/CPP/Windows/Control/ProgressBar.h @@ -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 @@ namespace NControl { 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 --git a/CPP/Windows/Control/PropertyPage.cpp b/CPP/Windows/Control/PropertyPage.cpp index ce8696d4..f8effe60 100644 --- a/CPP/Windows/Control/PropertyPage.cpp +++ b/CPP/Windows/Control/PropertyPage.cpp @@ -16,7 +16,13 @@ extern bool g_IsNT; 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 @@ bool CPropertyPage::OnNotify(UINT /* controlID */, LPNMHDR lParam) { 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 @@ INT_PTR MyPropertySheet(const CObjectVector &pagesInfo, HWND hwndPare #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 @@ INT_PTR MyPropertySheet(const CObjectVector &pagesInfo, HWND hwndPare 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 --git a/CPP/Windows/Control/PropertyPage.h b/CPP/Windows/Control/PropertyPage.h index b68fd8fe..264a5d29 100644 --- a/CPP/Windows/Control/PropertyPage.h +++ b/CPP/Windows/Control/PropertyPage.h @@ -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 @@ INT_PTR APIENTRY ProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wPar 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 --git a/CPP/Windows/Control/ReBar.h b/CPP/Windows/Control/ReBar.h index c2d58dbe..b56f018c 100644 --- a/CPP/Windows/Control/ReBar.h +++ b/CPP/Windows/Control/ReBar.h @@ -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 @@ class CReBar: public NWindows::CWindow 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 --git a/CPP/Windows/Control/Static.h b/CPP/Windows/Control/Static.h index 5523b2e6..ceeedf96 100644 --- a/CPP/Windows/Control/Static.h +++ b/CPP/Windows/Control/Static.h @@ -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 --git a/CPP/Windows/Control/StatusBar.h b/CPP/Windows/Control/StatusBar.h index 988b8470..38aca478 100644 --- a/CPP/Windows/Control/StatusBar.h +++ b/CPP/Windows/Control/StatusBar.h @@ -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 @@ class CStatusBar: public NWindows::CWindow { 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 @@ class CStatusBar: public NWindows::CWindow #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 @@ class CStatusBar: public NWindows::CWindow 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 --git a/CPP/Windows/Control/StdAfx.h b/CPP/Windows/Control/StdAfx.h index 1cbd7fea..80866550 100644 --- a/CPP/Windows/Control/StdAfx.h +++ b/CPP/Windows/Control/StdAfx.h @@ -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 --git a/CPP/Windows/Control/ToolBar.h b/CPP/Windows/Control/ToolBar.h index 7bc93a24..2bf20a59 100644 --- a/CPP/Windows/Control/ToolBar.h +++ b/CPP/Windows/Control/ToolBar.h @@ -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 @@ class CToolBar: public NWindows::CWindow #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 --git a/CPP/Windows/Control/Trackbar.h b/CPP/Windows/Control/Trackbar.h index 313e0c85..18d1b291 100644 --- a/CPP/Windows/Control/Trackbar.h +++ b/CPP/Windows/Control/Trackbar.h @@ -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 --git a/CPP/Windows/Control/Window2.cpp b/CPP/Windows/Control/Window2.cpp index 994d96e0..8fe908e0 100644 --- a/CPP/Windows/Control/Window2.cpp +++ b/CPP/Windows/Control/Window2.cpp @@ -32,9 +32,9 @@ static LRESULT CALLBACK WindowProcedure(HWND aHWND, UINT message, WPARAM wParam, 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 @@ LRESULT CWindow2::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) 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 @@ LRESULT CWindow2::OnMessage(UINT message, WPARAM wParam, LPARAM lParam) 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 CWindow2::OnCommand(int /* code */, int /* itemID */, LPARAM /* lParam */, } /* -bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND) +bool CDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND) { switch (buttonID) { diff --git a/CPP/Windows/Control/Window2.h b/CPP/Windows/Control/Window2.h index 7ac580cb..ebb59793 100644 --- a/CPP/Windows/Control/Window2.h +++ b/CPP/Windows/Control/Window2.h @@ -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 @@ namespace NControl { 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 @@ class CWindow2: public CWindow 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 @@ class CWindow2: public CWindow /* 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 --git a/CPP/Windows/DLL.cpp b/CPP/Windows/DLL.cpp index cf5d01a3..b2499ecd 100644 --- a/CPP/Windows/DLL.cpp +++ b/CPP/Windows/DLL.cpp @@ -17,11 +17,11 @@ namespace NDLL { 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 @@ bool MyGetModuleFileName(FString &path) return false; } -#ifndef _SFX +#ifndef Z7_SFX FString GetModuleDirPrefix() { @@ -110,38 +110,35 @@ FString GetModuleDirPrefix() }} -#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 @@ bool CLibrary::Load(CFSTR path) throw() #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 @@ void * CLibrary::GetProc(LPCSTR procName) const return local_GetProcAddress(_module, procName); // return NULL; } +*/ }} diff --git a/CPP/Windows/DLL.h b/CPP/Windows/DLL.h index 0c093eed..19a82b33 100644 --- a/CPP/Windows/DLL.h +++ b/CPP/Windows/DLL.h @@ -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 @@ class CLibrary { 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 @@ class CLibrary } HMODULE Detach() { - HMODULE m = _module; + const HMODULE m = _module; _module = NULL; return m; } @@ -49,28 +70,26 @@ class CLibrary 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 --git a/CPP/Windows/Defs.h b/CPP/Windows/Defs.h index 1d96078d..8ab9cf5e 100644 --- a/CPP/Windows/Defs.h +++ b/CPP/Windows/Defs.h @@ -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 --git a/CPP/Windows/ErrorMsg.cpp b/CPP/Windows/ErrorMsg.cpp index f6343a5c..5acf3adb 100644 --- a/CPP/Windows/ErrorMsg.cpp +++ b/CPP/Windows/ErrorMsg.cpp @@ -19,8 +19,8 @@ namespace NError { 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 @@ static bool MyFormatMessage(DWORD errorCode, UString &message) 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 @@ static bool MyFormatMessage(DWORD errorCode, UString &message) 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 --git a/CPP/Windows/ErrorMsg.h b/CPP/Windows/ErrorMsg.h index 01204eb9..6142b4eb 100644 --- a/CPP/Windows/ErrorMsg.h +++ b/CPP/Windows/ErrorMsg.h @@ -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 --git a/CPP/Windows/FileDir.cpp b/CPP/Windows/FileDir.cpp index cce26385..5b1f340b 100644 --- a/CPP/Windows/FileDir.cpp +++ b/CPP/Windows/FileDir.cpp @@ -65,46 +65,55 @@ namespace NDir { 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 @@ bool SetDirTime(CFSTR path, const CFiTime *cTime, const CFiTime *aTime, const CF 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 @@ bool SetFileAttrib(CFSTR path, DWORD attrib) 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 @@ bool RemoveDir(CFSTR path) 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 @@ bool MyMoveFile(CFSTR oldFile, CFSTR newFile) 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 @@ bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName) 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 @@ bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName) 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 @@ bool CreateDir(CFSTR path) 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 @@ static bool CreateDir2(CFSTR path) 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 @@ bool CreateComplexDir(CFSTR _path) #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 @@ bool DeleteFileAlways(CFSTR path) 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 @@ bool MyGetFullPathName(CFSTR path, FString &resFullPath) #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 @@ bool SetCurrentDir(CFSTR path) } +/* +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 @@ bool GetOnlyDirPrefix(CFSTR path, FString &resDirPrefix) 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 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu for (unsigned i = 0; i < 100; i++) { - path = prefix; + postfix.Empty(); if (addRandom) { char s[16]; @@ -701,14 +780,14 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu 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 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu } 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 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu 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 @@ bool CTempFile::Create(CFSTR prefix, NIO::COutFile *outFile) { 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 @@ bool CTempFile::CreateRandomInTempFolder(CFSTR namePrefix, NIO::COutFile *outFil { 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 @@ bool CTempDir::Create(CFSTR prefix) { 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 @@ bool RemoveDir(CFSTR path) } -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 @@ bool MyMoveFile(CFSTR oldFile, CFSTR newFile) 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 @@ bool GetCurrentDir(FString &path) { 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 @@ static C_umask g_umask; #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 @@ int my_chown(CFSTR path, uid_t owner, gid_t group) bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) { - TRACE_SetFileAttrib(""); + TRACE_SetFileAttrib("") struct stat st; @@ -1056,7 +1151,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) { 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 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) { 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 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) } 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 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) 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 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) 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 SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) 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 --git a/CPP/Windows/FileDir.h b/CPP/Windows/FileDir.h index 08281aaa..573ffa23 100644 --- a/CPP/Windows/FileDir.h +++ b/CPP/Windows/FileDir.h @@ -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 GetCurrentDir(FString &resultPath); bool MyGetTempPath(FString &resultPath); +bool CreateTempFile2(CFSTR prefix, bool addRandom, AString &postfix, NIO::COutFile *outFile); + class CTempFile MY_UNCOPYABLE { bool _mustBeDeleted; diff --git a/CPP/Windows/FileFind.cpp b/CPP/Windows/FileFind.cpp index c6557599..c562a909 100644 --- a/CPP/Windows/FileFind.cpp +++ b/CPP/Windows/FileFind.cpp @@ -39,10 +39,10 @@ typedef struct 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 @@ namespace NFile { #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 @@ bool CFileInfo::IsDots() const throw() 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 @@ static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFil #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 @@ bool CFindFile::FindFirst(CFSTR path, CFileInfo &fi) 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 @@ bool CFindFile::FindNext(CFileInfo &fi) //////////////////////////////// // 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 @@ bool CFindStream::FindFirst(CFSTR path, CStreamInfo &si) 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 @@ DWORD GetFileAttrib(CFSTR path) 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 @@ also we support paths that are not supported by FindFirstFile: 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 @@ HANDLE CFindChangeNotification::FindFirst(CFSTR path, bool watchSubtree, DWORD n { IF_USE_MAIN_PATH _handle = ::FindFirstChangeNotificationW(fs2us(path), BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH + #ifdef Z7_LONG_PATH if (!IsHandleAllocated()) { UString superPath; diff --git a/CPP/Windows/FileFind.h b/CPP/Windows/FileFind.h index fcfe02c7..11408d05 100644 --- a/CPP/Windows/FileFind.h +++ b/CPP/Windows/FileFind.h @@ -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 @@ class CFindChangeNotification MY_UNCOPYABLE 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 --git a/CPP/Windows/FileIO.cpp b/CPP/Windows/FileIO.cpp index e51b0eb3..4ecbb7ed 100644 --- a/CPP/Windows/FileIO.cpp +++ b/CPP/Windows/FileIO.cpp @@ -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 @@ using namespace NName; namespace NWindows { namespace NFile { -#ifdef SUPPORT_DEVICE_FILE +#ifdef Z7_DEVICE_FILE namespace NSystem { @@ -72,7 +72,7 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess, if (!Close()) return false; - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE IsDeviceFile = false; #endif @@ -88,7 +88,7 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess, 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 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess, /* #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::Close() throw() 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::GetPosition(UInt64 &position) const throw() 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 @@ bool CFileBase::SeekToEnd(UInt64 &newPosition) const throw() // ---------- 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 @@ static const UInt32 kChunkSizeMax = (1 << 22); 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 @@ bool CInFile::Read(void *data, UInt32 size, UInt32 &processedSize) throw() 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 @@ bool COutFile::Write(const void *data, UInt32 size, UInt32 &processedSize) throw 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 @@ bool SetDirTime(CFSTR path, const CFiTime *cTime, const CFiTime *aTime, const CF 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 @@ bool COutFile::Create(const char *name, bool createAlways) 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 @@ bool COutFile::SetLength(UInt64 length) throw() 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 --git a/CPP/Windows/FileIO.h b/CPP/Windows/FileIO.h index 80509653..03e061a9 100644 --- a/CPP/Windows/FileIO.h +++ b/CPP/Windows/FileIO.h @@ -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 @@ struct CReparseAttr // 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 @@ class CFileBase MY_UNCOPYABLE 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 @@ struct my_DISK_GEOMETRY_EX class CInFile: public CFileBase { - #ifdef SUPPORT_DEVICE_FILE + #ifdef Z7_DEVICE_FILE #ifndef UNDER_CE @@ -232,6 +234,14 @@ class CInFile: public CFileBase // 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 @@ class CFileBase 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 @@ class COutFile: public CFileBase bool CTime_defined; bool ATime_defined; bool MTime_defined; - CFiTime CTime; CFiTime ATime; CFiTime MTime; @@ -338,10 +348,13 @@ class COutFile: public CFileBase 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 --git a/CPP/Windows/FileLink.cpp b/CPP/Windows/FileLink.cpp index 8ce634fd..2b9fa1a0 100644 --- a/CPP/Windows/FileLink.cpp +++ b/CPP/Windows/FileLink.cpp @@ -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_Alias = (1 << 29); 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 @@ static void WriteString(Byte *dest, const wchar_t *path) wchar_t c = *path++; if (c == 0) return; - Set16(dest, (UInt16)c); + Set16(dest, (UInt16)c) dest += 2; } } @@ -133,10 +142,10 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i 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 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i 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 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i 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 @@ bool CReparseAttr::Parse(const Byte *p, size_t size) 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 @@ bool CReparseAttr::Parse(const Byte *p, size_t size) 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 @@ bool CReparseAttr::Parse(const Byte *p, size_t size) 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 @@ bool CReparseShortInfo::Parse(const Byte *p, size_t size) (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 @@ bool CReparseShortInfo::Parse(const Byte *p, size_t size) 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 @@ UString CReparseAttr::GetPath() const 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 --git a/CPP/Windows/FileMapping.h b/CPP/Windows/FileMapping.h index f90c429f..caa7ea3e 100644 --- a/CPP/Windows/FileMapping.h +++ b/CPP/Windows/FileMapping.h @@ -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 @@ class CFileMapping: public CHandle return res; #else _handle = ::OpenFileMapping(desiredAccess, FALSE, name); - if (_handle != 0) + if (_handle != NULL) return 0; return ::GetLastError(); #endif diff --git a/CPP/Windows/FileName.cpp b/CPP/Windows/FileName.cpp index d61ff7e1..c9c4f8b6 100644 --- a/CPP/Windows/FileName.cpp +++ b/CPP/Windows/FileName.cpp @@ -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 @@ void NormalizeDirPathPrefix(UString &dirPath) #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 @@ void NormalizeDirSeparators(FString &s) #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 @@ bool IsAltPathPrefix(CFSTR s) throw() #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 @@ unsigned GetNetworkServerPrefixSize(CFSTR s) throw() 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 @@ unsigned GetNetworkServerPrefixSize(CFSTR s) throw() 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 IsSuperPath(const wchar_t *s) throw() { return IS_SUPER_PREFIX(s); } 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 @@ static unsigned GetRootPrefixSize_Of_SimplePath(CFSTR s) 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 @@ static unsigned GetRootPrefixSize_Of_SuperPath(CFSTR s) { 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 @@ unsigned GetRootPrefixSize(const wchar_t *s) throw() { return IS_SEPAR(s[0]) ? 1 #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 @@ static bool AreThereDotsFolders(CFSTR s) #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 @@ static bool GetSuperPathBase(CFSTR s, UString &res) 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 @@ static bool GetSuperPathBase(CFSTR s, UString &res) 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 @@ bool GetSuperPath(CFSTR path, UString &superPath) return false; } */ -#endif // WIN_LONG_PATH +#endif // Z7_LONG_PATH bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) { @@ -801,8 +816,11 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) #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 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) 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 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) } 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 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) return true; } + bool GetFullPath(CFSTR path, FString &fullPath) { return GetFullPath(NULL, path, fullPath); diff --git a/CPP/Windows/FileName.h b/CPP/Windows/FileName.h index de8bd134..219b656b 100644 --- a/CPP/Windows/FileName.h +++ b/CPP/Windows/FileName.h @@ -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 IsDrivePath2(const wchar_t *s) throw(); // first 2 chars are drive chars li 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 @@ int FindAltStreamColon(CFSTR path) throw(); 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 @@ int GetUseSuperPathType(CFSTR s) throw(); 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 @@ bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew) #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 --git a/CPP/Windows/FileSystem.cpp b/CPP/Windows/FileSystem.cpp index 62594532..6a262d92 100644 --- a/CPP/Windows/FileSystem.cpp +++ b/CPP/Windows/FileSystem.cpp @@ -71,14 +71,14 @@ UINT MyGetDriveType(CFSTR pathName) } } -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 @@ bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, #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 @@ bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, 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 --git a/CPP/Windows/FileSystem.h b/CPP/Windows/FileSystem.h index 9b49a025..9f9e399c 100644 --- a/CPP/Windows/FileSystem.h +++ b/CPP/Windows/FileSystem.h @@ -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 --git a/CPP/Windows/Handle.h b/CPP/Windows/Handle.h index 5878c830..6ae09ecf 100644 --- a/CPP/Windows/Handle.h +++ b/CPP/Windows/Handle.h @@ -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 @@ class CHandle MY_UNCOPYABLE void Attach(HANDLE handle) { _handle = handle; } HANDLE Detach() { - HANDLE handle = _handle; + const HANDLE handle = _handle; _handle = NULL; return handle; } diff --git a/CPP/Windows/MemoryGlobal.h b/CPP/Windows/MemoryGlobal.h index c217510e..68525915 100644 --- a/CPP/Windows/MemoryGlobal.h +++ b/CPP/Windows/MemoryGlobal.h @@ -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 @@ class CGlobal { HGLOBAL _global; public: - CGlobal(): _global(NULL){}; + CGlobal(): _global(NULL) {} ~CGlobal() { Free(); } operator HGLOBAL() const { return _global; } void Attach(HGLOBAL hGlobal) @@ -22,7 +22,7 @@ class CGlobal } HGLOBAL Detach() { - HGLOBAL h = _global; + const HGLOBAL h = _global; _global = NULL; return h; } @@ -42,10 +42,10 @@ class CGlobalLock CGlobalLock(HGLOBAL hGlobal): _global(hGlobal) { _ptr = GlobalLock(hGlobal); - }; + } ~CGlobalLock() { - if (_ptr != NULL) + if (_ptr) GlobalUnlock(_global); } }; diff --git a/CPP/Windows/MemoryLock.cpp b/CPP/Windows/MemoryLock.cpp index 24866b1a..0bd7504f 100644 --- a/CPP/Windows/MemoryLock.cpp +++ b/CPP/Windows/MemoryLock.cpp @@ -21,7 +21,10 @@ typedef BOOL (WINAPI * Func_LookupPrivilegeValue)(LPCTSTR lpSystemName, LPCTSTR 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 @@ bool EnablePrivilege(LPCTSTR privilegeName, bool enable) #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 @@ typedef void (WINAPI * Func_RtlGetVersion) (OSVERSIONINFOEXW *); 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 --git a/CPP/Windows/MemoryLock.h b/CPP/Windows/MemoryLock.h index dcaf182e..2b850029 100644 --- a/CPP/Windows/MemoryLock.h +++ b/CPP/Windows/MemoryLock.h @@ -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 --git a/CPP/Windows/Menu.cpp b/CPP/Windows/Menu.cpp index 3ad69530..af54c668 100644 --- a/CPP/Windows/Menu.cpp +++ b/CPP/Windows/Menu.cpp @@ -22,8 +22,23 @@ contain additional member: 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 @@ So we use size of old version of structure. */ #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 @@ static void ConvertItemToSysForm(const CMenuItem &item, MENUITEMINFOA &si) { 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()) + const bool isString = item.IsString(); + unsigned bufSize = kMaxSize; + AString a; + if (isString) { - si.cch = kMaxSize; - si.dwTypeData = s; + si.cch = bufSize; + si.dwTypeData = a.GetBuf(bufSize); } - if (GetItemInfo(itemIndex, byPosition, &si)) + 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 @@ bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) #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::SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item) } } + bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item) { #ifndef _UNICODE @@ -188,11 +237,11 @@ bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item) 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 --git a/CPP/Windows/Menu.h b/CPP/Windows/Menu.h index aacdc7c3..e1de4c4b 100644 --- a/CPP/Windows/Menu.h +++ b/CPP/Windows/Menu.h @@ -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 @@ struct CMenuItem // 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 @@ class CMenu 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 @@ class CMenu 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 @@ class CMenu 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 @@ class CMenu 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 @@ class CMenuDestroyer 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 --git a/CPP/Windows/NationalTime.cpp b/CPP/Windows/NationalTime.cpp index 0dcd31e0..d3c38de5 100644 --- a/CPP/Windows/NationalTime.cpp +++ b/CPP/Windows/NationalTime.cpp @@ -16,8 +16,8 @@ bool MyGetTimeFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time, 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 @@ bool MyGetDateFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time, 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 --git a/CPP/Windows/NationalTime.h b/CPP/Windows/NationalTime.h index 49b0e5e8..32ba479f 100644 --- a/CPP/Windows/NationalTime.h +++ b/CPP/Windows/NationalTime.h @@ -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 --git a/CPP/Windows/Net.cpp b/CPP/Windows/Net.cpp index 2a3952a1..0ac82d4e 100644 --- a/CPP/Windows/Net.cpp +++ b/CPP/Windows/Net.cpp @@ -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, LPNETRESOURCE netResourc 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 @@ DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCEW netResour static void SetComplexString(bool &defined, CSysString &destString, LPCTSTR srcString) { - defined = (srcString != 0); + defined = (srcString != NULL); if (defined) destString = srcString; else @@ -179,7 +207,7 @@ DWORD CEnum::Close() { if (!_handleAllocated) return NO_ERROR; - DWORD result = ::WNetCloseEnum(_handle); + const DWORD result = ::WNetCloseEnum(_handle); _handleAllocated = (result != NO_ERROR); return result; } @@ -204,7 +232,7 @@ DWORD CEnum::Next(CResource &resource) 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 @@ DWORD CEnum::Next(CResourceW &resource) 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 @@ DWORD CEnum::Next(CResourceW &resource) return result; } CResource resourceA; - DWORD result = Next(resourceA); + const DWORD result = Next(resourceA); ConvertResourceToResourceW(resourceA, resource); return result; } @@ -249,7 +277,7 @@ DWORD GetResourceParent(const CResource &resource, CResource &parentResource) 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 GetResourceParent(const CResourceW &resource, CResourceW &parentResource) 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 @@ DWORD GetResourceParent(const CResourceW &resource, CResourceW &parentResource) } 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 @@ DWORD GetResourceInformation(const CResource &resource, 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 @@ DWORD GetResourceInformation(const CResourceW &resource, 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 @@ DWORD GetResourceInformation(const CResourceW &resource, 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 --git a/CPP/Windows/Net.h b/CPP/Windows/Net.h index 7b60b1b4..a954bdb2 100644 --- a/CPP/Windows/Net.h +++ b/CPP/Windows/Net.h @@ -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 --git a/CPP/Windows/NtCheck.h b/CPP/Windows/NtCheck.h index 0af32911..362a05ad 100644 --- a/CPP/Windows/NtCheck.h +++ b/CPP/Windows/NtCheck.h @@ -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 --git a/CPP/Windows/ProcessMessages.h b/CPP/Windows/ProcessMessages.h index b2558a01..aa98bbb0 100644 --- a/CPP/Windows/ProcessMessages.h +++ b/CPP/Windows/ProcessMessages.h @@ -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 --git a/CPP/Windows/ProcessUtils.cpp b/CPP/Windows/ProcessUtils.cpp index d42a9a4d..3546ddd6 100644 --- a/CPP/Windows/ProcessUtils.cpp +++ b/CPP/Windows/ProcessUtils.cpp @@ -3,6 +3,7 @@ #include "StdAfx.h" #include "../Common/StringConvert.h" +#include "../Common/MyString.h" #include "ProcessUtils.h" @@ -36,9 +37,9 @@ WRes CProcess::Create(LPCWSTR imageName, const UString ¶ms, LPCWSTR curDir) #endif params; #ifdef UNDER_CE - curDir = 0; + curDir = NULL; #else - imageName = 0; + imageName = NULL; #endif PROCESS_INFORMATION pi; BOOL result; @@ -47,12 +48,12 @@ WRes CProcess::Create(LPCWSTR imageName, const UString ¶ms, LPCWSTR curDir) { 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) @@ -66,12 +67,12 @@ WRes CProcess::Create(LPCWSTR imageName, const UString ¶ms, LPCWSTR curDir) { 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); @@ -86,7 +87,7 @@ WRes CProcess::Create(LPCWSTR imageName, const UString ¶ms, LPCWSTR curDir) WRes MyCreateProcess(LPCWSTR imageName, const UString ¶ms) { CProcess process; - return process.Create(imageName, params, 0); + return process.Create(imageName, params, NULL); } } diff --git a/CPP/Windows/ProcessUtils.h b/CPP/Windows/ProcessUtils.h index e46f9ab2..b1fce3ae 100644 --- a/CPP/Windows/ProcessUtils.h +++ b/CPP/Windows/ProcessUtils.h @@ -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 @@ class CProcess: public CHandle 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 @@ class CProcess: public CHandle { 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)); } - - bool FlushInstructionCache(LPCVOID baseAddress = 0, SIZE_T size = 0) + { return BOOLToBool(::WriteProcessMemory(_handle, baseAddress, + #ifdef Z7_OLD_WIN_SDK + (LPVOID) + #endif + buffer, + size, numberOfBytesWritten)); } + + 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 @@ class CProcess: public CHandle // 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 @@ class CProcess: public CHandle 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 @@ class CProcess: public CHandle { 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 --git a/CPP/Windows/PropVariant.cpp b/CPP/Windows/PropVariant.cpp index 2b179500..457b1dcb 100644 --- a/CPP/Windows/PropVariant.cpp +++ b/CPP/Windows/PropVariant.cpp @@ -197,17 +197,17 @@ BSTR CPropVariant::AllocBstr(unsigned numChars) 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 @@ SET_PROP_FUNC(const FILETIME &, VT_FILETIME, filetime) we call system functions for VT_BSTR and for unknown typed */ -CPropVariant::~CPropVariant() +CPropVariant::~CPropVariant() throw() { switch ((unsigned)vt) { diff --git a/CPP/Windows/PropVariant.h b/CPP/Windows/PropVariant.h index 171402f7..f358fdea 100644 --- a/CPP/Windows/PropVariant.h +++ b/CPP/Windows/PropVariant.h @@ -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 @@ class CPropVariant : public tagPROPVARIANT // wReserved2 = 0; // wReserved3 = 0; // uhVal.QuadPart = 0; - bstrVal = 0; + bstrVal = NULL; } @@ -104,13 +104,13 @@ class CPropVariant : public tagPROPVARIANT 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 --git a/CPP/Windows/PropVariantConv.cpp b/CPP/Windows/PropVariantConv.cpp index 3c9bbd17..5fb96a7c 100644 --- a/CPP/Windows/PropVariantConv.cpp +++ b/CPP/Windows/PropVariantConv.cpp @@ -36,17 +36,17 @@ bool ConvertUtcFileTimeToString2(const FILETIME &utc, unsigned ns100, char *s, i 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 --git a/CPP/Windows/PropVariantConv.h b/CPP/Windows/PropVariantConv.h index 60677840..ec5223bd 100644 --- a/CPP/Windows/PropVariantConv.h +++ b/CPP/Windows/PropVariantConv.h @@ -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 --git a/CPP/Windows/PropVariantUtils.h b/CPP/Windows/PropVariantUtils.h index 3dd8295f..78adb50d 100644 --- a/CPP/Windows/PropVariantUtils.h +++ b/CPP/Windows/PropVariantUtils.h @@ -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 @@ void FlagsToProp(const CUInt32PCharPair *pairs, unsigned num, UInt32 flags, NWin 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 --git a/CPP/Windows/Registry.h b/CPP/Windows/Registry.h index ca79dfe3..0d3b4fcc 100644 --- a/CPP/Windows/Registry.h +++ b/CPP/Windows/Registry.h @@ -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 --git a/CPP/Windows/ResourceString.h b/CPP/Windows/ResourceString.h index f0bdabf4..773307b9 100644 --- a/CPP/Windows/ResourceString.h +++ b/CPP/Windows/ResourceString.h @@ -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 --git a/CPP/Windows/SecurityUtils.cpp b/CPP/Windows/SecurityUtils.cpp index ede83faf..d4282d07 100644 --- a/CPP/Windows/SecurityUtils.cpp +++ b/CPP/Windows/SecurityUtils.cpp @@ -4,9 +4,6 @@ #include "SecurityUtils.h" -#define MY_CAST_FUNC (void(*)()) -// #define MY_CAST_FUNC - namespace NWindows { namespace NSecurity { @@ -35,7 +32,7 @@ bool MyLookupAccountSid(LPCTSTR systemName, PSID sid, 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 @@ typedef BOOL (WINAPI * Func_LookupAccountNameW)( 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 @@ static PSID GetSid(LPWSTR accountName) #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 @@ static PSID GetSid(LPWSTR accountName) 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 @@ bool AddLockMemoryPrivilege() != 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 @@ bool AddLockMemoryPrivilege() 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 --git a/CPP/Windows/SecurityUtils.h b/CPP/Windows/SecurityUtils.h index c0d7b127..4ef3939f 100644 --- a/CPP/Windows/SecurityUtils.h +++ b/CPP/Windows/SecurityUtils.h @@ -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 @@ typedef NTSTATUS (NTAPI *Func_LsaAddAccountRights)(LSA_HANDLE PolicyHandle, #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 @@ class CAccessToken { HANDLE _handle; public: - CAccessToken(): _handle(NULL) {}; + CAccessToken(): _handle(NULL) {} ~CAccessToken() { Close(); } bool Close() { @@ -93,9 +93,9 @@ struct CPolicy 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 --git a/CPP/Windows/Shell.cpp b/CPP/Windows/Shell.cpp index 071833cf..b2a34898 100644 --- a/CPP/Windows/Shell.cpp +++ b/CPP/Windows/Shell.cpp @@ -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 @@ namespace NShell { 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 @@ CItemIDList& CItemIDList::operator=(const CItemIDList &object) } */ + +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 @@ UINT CDrop::QueryCountOfFiles() 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 @@ bool BrowseForFolder(HWND /* owner */, LPCTSTR /* title */, #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 @@ static bool BrowseForFolder(HWND owner, LPCTSTR title, UINT ulFlags, 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 @@ bool BrowseForFolder(HWND owner, LPCTSTR title, #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 @@ static bool BrowseForFolder(HWND owner, LPCWSTR title, UINT ulFlags, 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 --git a/CPP/Windows/Shell.h b/CPP/Windows/Shell.h index de91d3f1..b4cdb304 100644 --- a/CPP/Windows/Shell.h +++ b/CPP/Windows/Shell.h @@ -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 @@ namespace NShell{ class CItemIDList { LPITEMIDLIST m_Object; + Z7_CLASS_NO_COPY(CItemIDList) public: CItemIDList(): m_Object(NULL) {} // CItemIDList(LPCITEMIDLIST itemIDList); @@ -49,6 +55,7 @@ class CItemIDList ///////////////////////////// // CDrop +/* class CDrop { HDROP m_Object; @@ -63,22 +70,51 @@ class CDrop 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 --git a/CPP/Windows/StdAfx.h b/CPP/Windows/StdAfx.h index 1766dfa8..bd5084fd 100644 --- a/CPP/Windows/StdAfx.h +++ b/CPP/Windows/StdAfx.h @@ -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 --git a/CPP/Windows/Synchronization.cpp b/CPP/Windows/Synchronization.cpp index fbf919dc..d5542af4 100644 --- a/CPP/Windows/Synchronization.cpp +++ b/CPP/Windows/Synchronization.cpp @@ -19,6 +19,30 @@ namespace NSynchronization { 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 --git a/CPP/Windows/Synchronization.h b/CPP/Windows/Synchronization.h index 7d2e8d2a..afd03d2c 100644 --- a/CPP/Windows/Synchronization.h +++ b/CPP/Windows/Synchronization.h @@ -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 @@ class CBaseEvent MY_UNCOPYABLE 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 @@ class CSynchro MY_UNCOPYABLE } 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 @@ class CSynchro MY_UNCOPYABLE } 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 @@ struct CBaseHandle_WFMO MY_UNCOPYABLE CSynchro *_sync; CBaseHandle_WFMO(): _sync(NULL) {} + virtual ~CBaseHandle_WFMO(); operator CHandle_WFMO() { return this; } virtual bool IsSignaledAndUpdate() = 0; @@ -283,7 +284,7 @@ class CBaseEvent_WFMO : public CBaseHandle_WFMO // 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 @@ class CBaseEvent_WFMO : public CBaseHandle_WFMO 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 CAutoResetEvent_WFMO: public CBaseEvent_WFMO }; -class CSemaphore_WFMO : public CBaseHandle_WFMO +class CSemaphore_WFMO Z7_final: public CBaseHandle_WFMO { UInt32 _count; UInt32 _maxCount; @@ -365,11 +359,11 @@ class CSemaphore_WFMO : public CBaseHandle_WFMO 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 @@ class CSemaphore_WFMO : public CBaseHandle_WFMO 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 --git a/CPP/Windows/System.cpp b/CPP/Windows/System.cpp index 3a14b77d..dbe287a0 100644 --- a/CPP/Windows/System.cpp +++ b/CPP/Windows/System.cpp @@ -4,6 +4,7 @@ #ifndef _WIN32 #include +#include #ifdef __APPLE__ #include #else @@ -74,7 +75,7 @@ BOOL CProcessAffinity::Get() 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 @@ BOOL CProcessAffinity::Get() 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 @@ UInt32 GetNumberOfProcessors() #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 @@ typedef struct _MY_MEMORYSTATUSEX { #endif -typedef BOOL (WINAPI *GlobalMemoryStatusExP)(MY_LPMEMORYSTATUSEX lpBuffer); +typedef BOOL (WINAPI *Func_GlobalMemoryStatusEx)(MY_LPMEMORYSTATUSEX lpBuffer); #endif // !UNDER_CE @@ -155,9 +157,11 @@ bool GetRamSize(UInt64 &size) #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 @@ bool GetRamSize(UInt64 &size) #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 --git a/CPP/Windows/System.h b/CPP/Windows/System.h index 23cb0dab..06500074 100644 --- a/CPP/Windows/System.h +++ b/CPP/Windows/System.h @@ -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 @@ struct CProcessAffinity UInt32 GetNumSystemThreads() const { return (UInt32)numSysThreads; } BOOL Get(); - #ifdef _7ZIP_AFFINITY_SUPPORTED + #ifdef Z7_AFFINITY_SUPPORTED CCpuSet cpu_set; @@ -86,7 +86,7 @@ struct CProcessAffinity return sched_setaffinity(0, sizeof(cpu_set), &cpu_set) == 0; } - #else + #else // Z7_AFFINITY_SUPPORTED void InitST() { @@ -114,16 +114,19 @@ struct CProcessAffinity 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 --git a/CPP/Windows/SystemInfo.cpp b/CPP/Windows/SystemInfo.cpp index d882a8ee..6bafc804 100644 --- a/CPP/Windows/SystemInfo.cpp +++ b/CPP/Windows/SystemInfo.cpp @@ -102,38 +102,44 @@ static void PrintHex(AString &s, UInt64 v) #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 @@ static void x86cpuid_to_String(const Cx86cpuid &c, AString &s, AString &ver) 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 @@ static void x86cpuid_all_to_String(AString &s) { char temp[32]; ConvertUInt32ToHex8Digits(d[i], temp); - s += " "; + s.Add_Space(); s += temp; } } @@ -215,12 +219,12 @@ static const char * const k_PROCESSOR_ARCHITECTURE[] = , "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 @@ static const char * const k_PF[] = #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 @@ static AString TypeToString2(const char * const table[], unsigned num, UInt32 va 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 @@ void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v) }}}} 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 @@ static void SysInfo_To_String(AString &s, const SYSTEM_INFO &si) 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 @@ static void Add_sysctlbyname_to_String(const char *name, AString &s) { 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 @@ void GetSysInfo(AString &s1, AString &s2) } #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 @@ void CCpuName::Fill() #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 @@ void CCpuName::Fill() { 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 @@ void CCpuName::Fill() 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 @@ void CCpuName::Fill() } 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 @@ void CCpuName::Fill() #endif - #ifdef _7ZIP_LARGE_PAGES + #ifdef Z7_LARGE_PAGES Add_LargePages_String(LargePages); #endif } @@ -608,7 +617,7 @@ void AddCpuFeatures(AString &s) { #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 @@ void AddCpuFeatures(AString &s) { 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 @@ void AddCpuFeatures(AString &s) #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 @@ void AddCpuFeatures(AString &s) 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 @@ void AddCpuFeatures(AString &s) 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 @@ EXTERN_C_END 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 @@ void GetOsInfoText(AString &sRes) 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 @@ void GetOsInfoText(AString &sRes) #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 @@ void GetCpuName_MultiLine(AString &s) } } + +#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 @@ void GetCompiler(AString &s) #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 @@ void GetCompiler(AString &s) 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 --git a/CPP/Windows/SystemInfo.h b/CPP/Windows/SystemInfo.h index e941d0aa..c2e2e3b1 100644 --- a/CPP/Windows/SystemInfo.h +++ b/CPP/Windows/SystemInfo.h @@ -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 PrintSize_KMGT_Or_Hex(AString &s, UInt64 v); void Add_LargePages_String(AString &s); void GetCompiler(AString &s); +void GetVirtCpuid(AString &s); #endif diff --git a/CPP/Windows/Thread.h b/CPP/Windows/Thread.h index 5fca173f..d72f64c4 100644 --- a/CPP/Windows/Thread.h +++ b/CPP/Windows/Thread.h @@ -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 @@ class CThread MY_UNCOPYABLE { ::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 --git a/CPP/Windows/TimeUtils.cpp b/CPP/Windows/TimeUtils.cpp index 77d2c510..e80ae13d 100644 --- a/CPP/Windows/TimeUtils.cpp +++ b/CPP/Windows/TimeUtils.cpp @@ -258,7 +258,7 @@ void GetCurUtc_FiTime(CFiTime &ft) throw() 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 @@ void GetCurUtcFileTime(FILETIME &ft) throw() { 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 --git a/CPP/Windows/TimeUtils.h b/CPP/Windows/TimeUtils.h index 60ee739f..4a9d0f2f 100644 --- a/CPP/Windows/TimeUtils.h +++ b/CPP/Windows/TimeUtils.h @@ -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 --git a/CPP/Windows/Window.cpp b/CPP/Windows/Window.cpp index 32af4aab..102c503a 100644 --- a/CPP/Windows/Window.cpp +++ b/CPP/Windows/Window.cpp @@ -111,7 +111,7 @@ bool MySetWindowText(HWND wnd, LPCWSTR s) } #endif -bool CWindow::GetText(CSysString &s) +bool CWindow::GetText(CSysString &s) const { s.Empty(); unsigned len = (unsigned)GetTextLength(); @@ -119,7 +119,7 @@ bool CWindow::GetText(CSysString &s) 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 @@ bool CWindow::GetText(CSysString &s) } #ifndef _UNICODE -bool CWindow::GetText(UString &s) +bool CWindow::GetText(UString &s) const { if (g_IsNT) { @@ -140,7 +140,7 @@ bool CWindow::GetText(UString &s) 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 @@ bool CWindow::GetText(UString &s) return true; } CSysString sysString; - bool result = GetText(sysString); + const bool result = GetText(sysString); MultiByteToUnicodeString2(s, sysString); return result; } diff --git a/CPP/Windows/Window.h b/CPP/Windows/Window.h index 83726c7a..a99143bd 100644 --- a/CPP/Windows/Window.h +++ b/CPP/Windows/Window.h @@ -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 MY__WM_CHANGEUISTATE 0x0127 -#define MY__WM_UPDATEUISTATE 0x0128 -#define MY__WM_QUERYUISTATE 0x0129 +#define Z7_WIN_UIS_SET UIS_SET +#define Z7_WIN_UIS_CLEAR UIS_CLEAR +#define Z7_WIN_UIS_INITIALIZE UIS_INITIALIZE +#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 @@ bool MySetWindowText(HWND wnd, LPCWSTR s); 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 @@ class CWindow 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 @@ class CWindow { 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 @@ class CWindow { 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 --git a/DOC/7zip.wxs b/DOC/7zip.wxs index 53514af9..4849b80a 100644 --- a/DOC/7zip.wxs +++ b/DOC/7zip.wxs @@ -1,6 +1,6 @@ - + diff --git a/DOC/Methods.txt b/DOC/Methods.txt index d4a1b1dd..541f1c1c 100644 --- a/DOC/Methods.txt +++ b/DOC/Methods.txt @@ -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 @@ List of defined IDs 07 - ARM (little-endian) 08 - ARMT (little-endian) 09 - SPARC +0A - ARM64 21 - LZMA2 @@ -88,6 +89,8 @@ List of defined IDs 0A - Imploding 0C - BZip2 (not used. Use {040202} instead) 0E - LZMA (LZMA-zip) + + 5D - ZSTD 5F - xz 60 - Jpeg 61 - WavPack diff --git a/DOC/lzma.txt b/DOC/lzma.txt index a65988fe..142feb15 100644 --- a/DOC/lzma.txt +++ b/DOC/lzma.txt @@ -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 @@ How To compress data 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 @@ Return code: 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++ LZMA code is just wrapper over ANSI-C code. 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 --git a/DOC/readme.txt b/DOC/readme.txt index faec8dce..5cd90c5c 100644 --- a/DOC/readme.txt +++ b/DOC/readme.txt @@ -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 @@ How to compile in Windows ------------------------- 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 @@ There are two ways to compile 7-Zip binaries: 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 @@ MY_DYNAMIC_LINK 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 @@ So if you compile the version with Assembeler code, you will get faster 7-Zip bi 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 with assembler: 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 @@ Description of 7-Zip sources package 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 @@ Windows common files for Windows related code 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 --git a/DOC/src-history.txt b/DOC/src-history.txt index f546c4e2..c1c1b71a 100644 --- a/DOC/src-history.txt +++ b/DOC/src-history.txt @@ -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 diff --git a/README.md b/README.md index 827db712..039a0106 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ You can install it in two ways: The output should look like this: ``` -7-Zip 22.01 ZS v1.5.5 R3 (x64) : Copyright (c) 1999-2022 Igor Pavlov, 2016-2023 Tino Reichardt : 2023-06-18 +7-Zip 23.01 ZS v1.5.5 R3 (x64) : Copyright (c) 1999-2022 Igor Pavlov, 2016-2023 Tino Reichardt : 2023-06-18 Libs: 0 c:\Program Files\7-Zip-Zstandard\7z.dll @@ -290,7 +290,7 @@ You find this project useful, maybe you consider a donation ;-) ## Version Information -- 7-Zip ZS Version 22.01 +- 7-Zip ZS Version 23.01 - [Brotli] Version 1.0.9 - [Fast LZMA2] Version 1.0.1 - [Lizard] Version 1.0 @@ -299,7 +299,7 @@ You find this project useful, maybe you consider a donation ;-) - [Zstandard] Version 1.5.5 - [BLAKE3] Version 0.3.7 -/TR 2023-06-18 +/TR 2023-10-21 ## Notes