aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--C/7z.h12
-rw-r--r--C/7zAlloc.c69
-rw-r--r--C/7zAlloc.h6
-rw-r--r--C/7zArcIn.c405
-rw-r--r--C/7zBuf.h6
-rw-r--r--C/7zCrc.c130
-rw-r--r--C/7zCrc.h14
-rw-r--r--C/7zCrcOpt.c16
-rw-r--r--C/7zDec.c172
-rw-r--r--C/7zFile.c33
-rw-r--r--C/7zFile.h9
-rw-r--r--C/7zStream.c67
-rw-r--r--C/7zTypes.h262
-rw-r--r--C/7zVersion.h8
-rw-r--r--C/7zWindows.h101
-rw-r--r--C/7zip_gcc_c.mak75
-rw-r--r--C/Aes.c108
-rw-r--r--C/Aes.h36
-rw-r--r--C/AesOpt.c348
-rw-r--r--C/Alloc.c192
-rw-r--r--C/Alloc.h19
-rw-r--r--C/Bcj2.c319
-rw-r--r--C/Bcj2.h270
-rw-r--r--C/Bcj2Enc.c559
-rw-r--r--C/Blake2.h6
-rw-r--r--C/Blake2s.c34
-rw-r--r--C/Bra.c496
-rw-r--r--C/Bra.h115
-rw-r--r--C/Bra86.c221
-rw-r--r--C/BraIA64.c57
-rw-r--r--C/BwtSort.c13
-rw-r--r--C/BwtSort.h6
-rw-r--r--C/Compiler.h162
-rw-r--r--C/CpuArch.c795
-rw-r--r--C/CpuArch.h218
-rw-r--r--C/Delta.h6
-rw-r--r--C/DllSecur.c127
-rw-r--r--C/DllSecur.h6
-rw-r--r--C/HuffEnc.c10
-rw-r--r--C/HuffEnc.h6
-rw-r--r--C/LzFind.c519
-rw-r--r--C/LzFind.h53
-rw-r--r--C/LzFindMt.c70
-rw-r--r--C/LzFindMt.h10
-rw-r--r--C/LzFindOpt.c14
-rw-r--r--C/LzHash.h8
-rw-r--r--C/Lzma2Dec.c12
-rw-r--r--C/Lzma2Dec.h15
-rw-r--r--C/Lzma2DecMt.c155
-rw-r--r--C/Lzma2DecMt.h20
-rw-r--r--C/Lzma2Enc.c174
-rw-r--r--C/Lzma2Enc.h20
-rw-r--r--C/Lzma86.h6
-rw-r--r--C/Lzma86Dec.c7
-rw-r--r--C/Lzma86Enc.c7
-rw-r--r--C/LzmaDec.c190
-rw-r--r--C/LzmaDec.h17
-rw-r--r--C/LzmaEnc.c380
-rw-r--r--C/LzmaEnc.h23
-rw-r--r--C/LzmaLib.c8
-rw-r--r--C/LzmaLib.h12
-rw-r--r--C/MtCoder.c104
-rw-r--r--C/MtCoder.h50
-rw-r--r--C/MtDec.c101
-rw-r--r--C/MtDec.h34
-rw-r--r--C/Ppmd.h12
-rw-r--r--C/Ppmd7.c186
-rw-r--r--C/Ppmd7.h10
-rw-r--r--C/Ppmd7Dec.c57
-rw-r--r--C/Ppmd7Enc.c87
-rw-r--r--C/Ppmd7aDec.c54
-rw-r--r--C/Ppmd8.c248
-rw-r--r--C/Ppmd8.h10
-rw-r--r--C/Ppmd8Dec.c58
-rw-r--r--C/Ppmd8Enc.c86
-rw-r--r--C/Precomp.h6
-rw-r--r--C/RotateDefs.h28
-rw-r--r--C/Sha1.c165
-rw-r--r--C/Sha1.h14
-rw-r--r--C/Sha1Opt.c151
-rw-r--r--C/Sha256.c146
-rw-r--r--C/Sha256.h12
-rw-r--r--C/Sha256Opt.c129
-rw-r--r--C/Sort.h6
-rw-r--r--C/SwapBytes.c800
-rw-r--r--C/SwapBytes.h17
-rw-r--r--C/Threads.c86
-rw-r--r--C/Threads.h50
-rw-r--r--C/Util/7z/7z.dsp8
-rw-r--r--C/Util/7z/7zMain.c85
-rw-r--r--C/Util/7z/Precomp.h10
-rw-r--r--C/Util/7z/makefile2
-rw-r--r--C/Util/7z/makefile.gcc4
-rw-r--r--C/Util/7zipInstall/7zipInstall.c135
-rw-r--r--C/Util/7zipInstall/7zipInstall.dsp8
-rw-r--r--C/Util/7zipInstall/Precomp.h11
-rw-r--r--C/Util/7zipInstall/makefile14
-rw-r--r--C/Util/7zipUninstall/7zipUninstall.c128
-rw-r--r--C/Util/7zipUninstall/7zipUninstall.dsp8
-rw-r--r--C/Util/7zipUninstall/Precomp.h11
-rw-r--r--C/Util/7zipUninstall/makefile4
-rw-r--r--C/Util/Lzma/LzmaUtil.c145
-rw-r--r--C/Util/Lzma/LzmaUtil.dsp16
-rw-r--r--C/Util/Lzma/Precomp.h14
-rw-r--r--C/Util/LzmaLib/LzmaLib.dsp20
-rw-r--r--C/Util/LzmaLib/LzmaLibExports.c13
-rw-r--r--C/Util/LzmaLib/Precomp.c4
-rw-r--r--C/Util/LzmaLib/Precomp.h14
-rw-r--r--C/Util/LzmaLib/makefile22
-rw-r--r--C/Util/SfxSetup/Precomp.h10
-rw-r--r--C/Util/SfxSetup/SfxSetup.c46
-rw-r--r--C/Util/SfxSetup/makefile3
-rw-r--r--C/Util/SfxSetup/makefile_con4
-rw-r--r--C/Xz.c4
-rw-r--r--C/Xz.h56
-rw-r--r--C/XzCrc64.c32
-rw-r--r--C/XzCrc64.h12
-rw-r--r--C/XzCrc64Opt.c28
-rw-r--r--C/XzDec.c300
-rw-r--r--C/XzEnc.c270
-rw-r--r--C/XzEnc.h23
-rw-r--r--C/XzIn.c75
-rw-r--r--C/warn_clang.mak38
-rw-r--r--C/warn_clang_mac.mak38
-rw-r--r--CPP/7zip/7zip.mak4
-rw-r--r--CPP/7zip/7zip_gcc.mak73
-rw-r--r--CPP/7zip/Archive/7z/7z.dsp22
-rw-r--r--CPP/7zip/Archive/7z/7zCompressionMode.h12
-rw-r--r--CPP/7zip/Archive/7z/7zDecode.cpp166
-rw-r--r--CPP/7zip/Archive/7z/7zDecode.h15
-rw-r--r--CPP/7zip/Archive/7z/7zEncode.cpp290
-rw-r--r--CPP/7zip/Archive/7z/7zEncode.h43
-rw-r--r--CPP/7zip/Archive/7z/7zExtract.cpp119
-rw-r--r--CPP/7zip/Archive/7z/7zFolderInStream.cpp116
-rw-r--r--CPP/7zip/Archive/7z/7zFolderInStream.h63
-rw-r--r--CPP/7zip/Archive/7z/7zHandler.cpp147
-rw-r--r--CPP/7zip/Archive/7z/7zHandler.h95
-rw-r--r--CPP/7zip/Archive/7z/7zHandlerOut.cpp168
-rw-r--r--CPP/7zip/Archive/7z/7zHeader.cpp2
-rw-r--r--CPP/7zip/Archive/7z/7zHeader.h16
-rw-r--r--CPP/7zip/Archive/7z/7zIn.cpp269
-rw-r--r--CPP/7zip/Archive/7z/7zIn.h22
-rw-r--r--CPP/7zip/Archive/7z/7zItem.h11
-rw-r--r--CPP/7zip/Archive/7z/7zOut.cpp90
-rw-r--r--CPP/7zip/Archive/7z/7zOut.h41
-rw-r--r--CPP/7zip/Archive/7z/7zProperties.cpp126
-rw-r--r--CPP/7zip/Archive/7z/7zProperties.h8
-rw-r--r--CPP/7zip/Archive/7z/7zRegister.cpp2
-rw-r--r--CPP/7zip/Archive/7z/7zSpecStream.cpp15
-rw-r--r--CPP/7zip/Archive/7z/7zSpecStream.h32
-rw-r--r--CPP/7zip/Archive/7z/7zUpdate.cpp924
-rw-r--r--CPP/7zip/Archive/7z/7zUpdate.h21
-rw-r--r--CPP/7zip/Archive/7z/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/7z/makefile6
-rw-r--r--CPP/7zip/Archive/ApfsHandler.cpp1075
-rw-r--r--CPP/7zip/Archive/ApmHandler.cpp35
-rw-r--r--CPP/7zip/Archive/ArHandler.cpp157
-rw-r--r--CPP/7zip/Archive/Archive.def2
-rw-r--r--CPP/7zip/Archive/Archive2.def2
-rw-r--r--CPP/7zip/Archive/ArchiveExports.cpp15
-rw-r--r--CPP/7zip/Archive/ArjHandler.cpp111
-rw-r--r--CPP/7zip/Archive/Base64Handler.cpp70
-rw-r--r--CPP/7zip/Archive/Bz2Handler.cpp106
-rw-r--r--CPP/7zip/Archive/Cab/CabBlockInStream.cpp6
-rw-r--r--CPP/7zip/Archive/Cab/CabBlockInStream.h18
-rw-r--r--CPP/7zip/Archive/Cab/CabHandler.cpp127
-rw-r--r--CPP/7zip/Archive/Cab/CabHandler.h14
-rw-r--r--CPP/7zip/Archive/Cab/CabHeader.h4
-rw-r--r--CPP/7zip/Archive/Cab/CabIn.cpp60
-rw-r--r--CPP/7zip/Archive/Cab/CabIn.h4
-rw-r--r--CPP/7zip/Archive/Cab/CabItem.h4
-rw-r--r--CPP/7zip/Archive/Cab/CabRegister.cpp2
-rw-r--r--CPP/7zip/Archive/Cab/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/Chm/ChmHandler.cpp188
-rw-r--r--CPP/7zip/Archive/Chm/ChmHandler.h20
-rw-r--r--CPP/7zip/Archive/Chm/ChmIn.cpp45
-rw-r--r--CPP/7zip/Archive/Chm/ChmIn.h6
-rw-r--r--CPP/7zip/Archive/Chm/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/ComHandler.cpp144
-rw-r--r--CPP/7zip/Archive/Common/CoderMixer2.cpp94
-rw-r--r--CPP/7zip/Archive/Common/CoderMixer2.h108
-rw-r--r--CPP/7zip/Archive/Common/DummyOutStream.cpp2
-rw-r--r--CPP/7zip/Archive/Common/DummyOutStream.h14
-rw-r--r--CPP/7zip/Archive/Common/FindSignature.cpp12
-rw-r--r--CPP/7zip/Archive/Common/FindSignature.h4
-rw-r--r--CPP/7zip/Archive/Common/HandlerOut.cpp28
-rw-r--r--CPP/7zip/Archive/Common/HandlerOut.h12
-rw-r--r--CPP/7zip/Archive/Common/InStreamWithCRC.cpp29
-rw-r--r--CPP/7zip/Archive/Common/InStreamWithCRC.h46
-rw-r--r--CPP/7zip/Archive/Common/ItemNameUtils.h4
-rw-r--r--CPP/7zip/Archive/Common/MultiStream.cpp52
-rw-r--r--CPP/7zip/Archive/Common/MultiStream.h51
-rw-r--r--CPP/7zip/Archive/Common/OutStreamWithCRC.cpp4
-rw-r--r--CPP/7zip/Archive/Common/OutStreamWithCRC.h14
-rw-r--r--CPP/7zip/Archive/Common/OutStreamWithSha1.cpp2
-rw-r--r--CPP/7zip/Archive/Common/OutStreamWithSha1.h18
-rw-r--r--CPP/7zip/Archive/Common/ParseProperties.h4
-rw-r--r--CPP/7zip/Archive/Common/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/CpioHandler.cpp820
-rw-r--r--CPP/7zip/Archive/CramfsHandler.cpp117
-rw-r--r--CPP/7zip/Archive/DeflateProps.h4
-rw-r--r--CPP/7zip/Archive/DllExports.cpp16
-rw-r--r--CPP/7zip/Archive/DllExports2.cpp14
-rw-r--r--CPP/7zip/Archive/DmgHandler.cpp166
-rw-r--r--CPP/7zip/Archive/ElfHandler.cpp113
-rw-r--r--CPP/7zip/Archive/ExtHandler.cpp464
-rw-r--r--CPP/7zip/Archive/FatHandler.cpp134
-rw-r--r--CPP/7zip/Archive/FlvHandler.cpp53
-rw-r--r--CPP/7zip/Archive/GptHandler.cpp112
-rw-r--r--CPP/7zip/Archive/GzHandler.cpp153
-rw-r--r--CPP/7zip/Archive/HandlerCont.cpp67
-rw-r--r--CPP/7zip/Archive/HandlerCont.h96
-rw-r--r--CPP/7zip/Archive/HfsHandler.cpp369
-rw-r--r--CPP/7zip/Archive/HfsHandler.h9
-rw-r--r--CPP/7zip/Archive/IArchive.h349
-rw-r--r--CPP/7zip/Archive/IhexHandler.cpp66
-rw-r--r--CPP/7zip/Archive/Iso/IsoHandler.cpp51
-rw-r--r--CPP/7zip/Archive/Iso/IsoHandler.h17
-rw-r--r--CPP/7zip/Archive/Iso/IsoHeader.h4
-rw-r--r--CPP/7zip/Archive/Iso/IsoIn.cpp42
-rw-r--r--CPP/7zip/Archive/Iso/IsoIn.h47
-rw-r--r--CPP/7zip/Archive/Iso/IsoItem.h28
-rw-r--r--CPP/7zip/Archive/Iso/IsoRegister.cpp2
-rw-r--r--CPP/7zip/Archive/Iso/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/LpHandler.cpp121
-rw-r--r--CPP/7zip/Archive/LzhHandler.cpp122
-rw-r--r--CPP/7zip/Archive/LzmaHandler.cpp103
-rw-r--r--CPP/7zip/Archive/MachoHandler.cpp234
-rw-r--r--CPP/7zip/Archive/MbrHandler.cpp202
-rw-r--r--CPP/7zip/Archive/MslzHandler.cpp53
-rw-r--r--CPP/7zip/Archive/MubHandler.cpp93
-rw-r--r--CPP/7zip/Archive/Nsis/NsisDecode.cpp38
-rw-r--r--CPP/7zip/Archive/Nsis/NsisDecode.h6
-rw-r--r--CPP/7zip/Archive/Nsis/NsisHandler.cpp126
-rw-r--r--CPP/7zip/Archive/Nsis/NsisHandler.h14
-rw-r--r--CPP/7zip/Archive/Nsis/NsisIn.cpp350
-rw-r--r--CPP/7zip/Archive/Nsis/NsisIn.h16
-rw-r--r--CPP/7zip/Archive/Nsis/NsisRegister.cpp2
-rw-r--r--CPP/7zip/Archive/Nsis/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/NtfsHandler.cpp291
-rw-r--r--CPP/7zip/Archive/PeHandler.cpp370
-rw-r--r--CPP/7zip/Archive/PpmdHandler.cpp58
-rw-r--r--CPP/7zip/Archive/QcowHandler.cpp60
-rw-r--r--CPP/7zip/Archive/Rar/Rar5Handler.cpp241
-rw-r--r--CPP/7zip/Archive/Rar/Rar5Handler.h30
-rw-r--r--CPP/7zip/Archive/Rar/RarHandler.cpp140
-rw-r--r--CPP/7zip/Archive/Rar/RarHandler.h26
-rw-r--r--CPP/7zip/Archive/Rar/RarHeader.h4
-rw-r--r--CPP/7zip/Archive/Rar/RarItem.h4
-rw-r--r--CPP/7zip/Archive/Rar/RarVol.h10
-rw-r--r--CPP/7zip/Archive/Rar/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/RpmHandler.cpp81
-rw-r--r--CPP/7zip/Archive/SparseHandler.cpp71
-rw-r--r--CPP/7zip/Archive/SplitHandler.cpp87
-rw-r--r--CPP/7zip/Archive/SquashfsHandler.cpp234
-rw-r--r--CPP/7zip/Archive/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/SwfHandler.cpp196
-rw-r--r--CPP/7zip/Archive/Tar/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/Tar/TarHandler.cpp97
-rw-r--r--CPP/7zip/Archive/Tar/TarHandler.h34
-rw-r--r--CPP/7zip/Archive/Tar/TarHandlerOut.cpp38
-rw-r--r--CPP/7zip/Archive/Tar/TarHeader.cpp2
-rw-r--r--CPP/7zip/Archive/Tar/TarHeader.h6
-rw-r--r--CPP/7zip/Archive/Tar/TarIn.cpp94
-rw-r--r--CPP/7zip/Archive/Tar/TarIn.h4
-rw-r--r--CPP/7zip/Archive/Tar/TarItem.h12
-rw-r--r--CPP/7zip/Archive/Tar/TarOut.cpp48
-rw-r--r--CPP/7zip/Archive/Tar/TarOut.h4
-rw-r--r--CPP/7zip/Archive/Tar/TarRegister.cpp2
-rw-r--r--CPP/7zip/Archive/Tar/TarUpdate.cpp92
-rw-r--r--CPP/7zip/Archive/Tar/TarUpdate.h4
-rw-r--r--CPP/7zip/Archive/Udf/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/Udf/UdfHandler.cpp60
-rw-r--r--CPP/7zip/Archive/Udf/UdfHandler.h16
-rw-r--r--CPP/7zip/Archive/Udf/UdfIn.cpp152
-rw-r--r--CPP/7zip/Archive/Udf/UdfIn.h29
-rw-r--r--CPP/7zip/Archive/UefiHandler.cpp191
-rw-r--r--CPP/7zip/Archive/VdiHandler.cpp40
-rw-r--r--CPP/7zip/Archive/VhdHandler.cpp131
-rw-r--r--CPP/7zip/Archive/VhdxHandler.cpp133
-rw-r--r--CPP/7zip/Archive/VmdkHandler.cpp136
-rw-r--r--CPP/7zip/Archive/Wim/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/Wim/WimHandler.cpp123
-rw-r--r--CPP/7zip/Archive/Wim/WimHandler.h38
-rw-r--r--CPP/7zip/Archive/Wim/WimHandlerOut.cpp450
-rw-r--r--CPP/7zip/Archive/Wim/WimIn.cpp147
-rw-r--r--CPP/7zip/Archive/Wim/WimIn.h16
-rw-r--r--CPP/7zip/Archive/XarHandler.cpp81
-rw-r--r--CPP/7zip/Archive/XzHandler.cpp225
-rw-r--r--CPP/7zip/Archive/XzHandler.h4
-rw-r--r--CPP/7zip/Archive/ZHandler.cpp58
-rw-r--r--CPP/7zip/Archive/Zip/StdAfx.h7
-rw-r--r--CPP/7zip/Archive/Zip/ZipAddCommon.cpp135
-rw-r--r--CPP/7zip/Archive/Zip/ZipAddCommon.h7
-rw-r--r--CPP/7zip/Archive/Zip/ZipCompressionMode.h28
-rw-r--r--CPP/7zip/Archive/Zip/ZipHandler.cpp217
-rw-r--r--CPP/7zip/Archive/Zip/ZipHandler.h52
-rw-r--r--CPP/7zip/Archive/Zip/ZipHandlerOut.cpp65
-rw-r--r--CPP/7zip/Archive/Zip/ZipHeader.h4
-rw-r--r--CPP/7zip/Archive/Zip/ZipIn.cpp373
-rw-r--r--CPP/7zip/Archive/Zip/ZipIn.h34
-rw-r--r--CPP/7zip/Archive/Zip/ZipItem.cpp2
-rw-r--r--CPP/7zip/Archive/Zip/ZipItem.h4
-rw-r--r--CPP/7zip/Archive/Zip/ZipOut.cpp57
-rw-r--r--CPP/7zip/Archive/Zip/ZipOut.h10
-rw-r--r--CPP/7zip/Archive/Zip/ZipRegister.cpp2
-rw-r--r--CPP/7zip/Archive/Zip/ZipUpdate.cpp767
-rw-r--r--CPP/7zip/Archive/Zip/ZipUpdate.h11
-rw-r--r--CPP/7zip/Bundles/Alone/Alone.dsp52
-rw-r--r--CPP/7zip/Bundles/Alone/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Alone/makefile2
-rw-r--r--CPP/7zip/Bundles/Alone/makefile.gcc12
-rw-r--r--CPP/7zip/Bundles/Alone2/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Alone2/makefile3
-rw-r--r--CPP/7zip/Bundles/Alone2/makefile.gcc9
-rw-r--r--CPP/7zip/Bundles/Alone7z/Alone.dsp98
-rw-r--r--CPP/7zip/Bundles/Alone7z/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Alone7z/makefile6
-rw-r--r--CPP/7zip/Bundles/Alone7z/makefile.gcc18
-rw-r--r--CPP/7zip/Bundles/Fm/FM.dsp29
-rw-r--r--CPP/7zip/Bundles/Fm/StdAfx.h18
-rw-r--r--CPP/7zip/Bundles/Fm/makefile3
-rw-r--r--CPP/7zip/Bundles/Format7z/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Format7z/makefile6
-rw-r--r--CPP/7zip/Bundles/Format7zExtract/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Format7zExtract/makefile4
-rw-r--r--CPP/7zip/Bundles/Format7zExtractR/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Format7zExtractR/makefile6
-rw-r--r--CPP/7zip/Bundles/Format7zF/Arc.mak4
-rw-r--r--CPP/7zip/Bundles/Format7zF/Arc_gcc.mak6
-rw-r--r--CPP/7zip/Bundles/Format7zF/Format7z.dsp46
-rw-r--r--CPP/7zip/Bundles/Format7zF/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Format7zF/makefile5
-rw-r--r--CPP/7zip/Bundles/Format7zF/makefile.gcc4
-rw-r--r--CPP/7zip/Bundles/Format7zR/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/Format7zR/makefile4
-rw-r--r--CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp44
-rw-r--r--CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp82
-rw-r--r--CPP/7zip/Bundles/LzmaCon/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/LzmaCon/makefile4
-rw-r--r--CPP/7zip/Bundles/LzmaCon/makefile.gcc5
-rw-r--r--CPP/7zip/Bundles/SFXCon/SFXCon.dsp96
-rw-r--r--CPP/7zip/Bundles/SFXCon/SfxCon.cpp42
-rw-r--r--CPP/7zip/Bundles/SFXCon/StdAfx.h7
-rw-r--r--CPP/7zip/Bundles/SFXCon/makefile7
-rw-r--r--CPP/7zip/Bundles/SFXCon/makefile.gcc12
-rw-r--r--CPP/7zip/Bundles/SFXCon/resource.rc6
-rw-r--r--CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp26
-rw-r--r--CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h21
-rw-r--r--CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp12
-rw-r--r--CPP/7zip/Bundles/SFXSetup/ExtractEngine.h4
-rw-r--r--CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp71
-rw-r--r--CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp70
-rw-r--r--CPP/7zip/Bundles/SFXSetup/StdAfx.h13
-rw-r--r--CPP/7zip/Bundles/SFXSetup/makefile11
-rw-r--r--CPP/7zip/Bundles/SFXWin/SFXWin.dsp65
-rw-r--r--CPP/7zip/Bundles/SFXWin/SfxWin.cpp29
-rw-r--r--CPP/7zip/Bundles/SFXWin/StdAfx.h14
-rw-r--r--CPP/7zip/Bundles/SFXWin/makefile9
-rw-r--r--CPP/7zip/Bundles/SFXWin/resource.rc5
-rw-r--r--CPP/7zip/Common/CWrappers.cpp49
-rw-r--r--CPP/7zip/Common/CWrappers.h6
-rw-r--r--CPP/7zip/Common/CreateCoder.cpp113
-rw-r--r--CPP/7zip/Common/CreateCoder.h53
-rw-r--r--CPP/7zip/Common/FilePathAutoRename.h4
-rw-r--r--CPP/7zip/Common/FileStreams.cpp125
-rw-r--r--CPP/7zip/Common/FileStreams.h113
-rw-r--r--CPP/7zip/Common/FilterCoder.cpp365
-rw-r--r--CPP/7zip/Common/FilterCoder.h148
-rw-r--r--CPP/7zip/Common/InBuffer.cpp22
-rw-r--r--CPP/7zip/Common/InBuffer.h16
-rw-r--r--CPP/7zip/Common/InOutTempBuffer.cpp302
-rw-r--r--CPP/7zip/Common/InOutTempBuffer.h59
-rw-r--r--CPP/7zip/Common/LimitedStreams.cpp46
-rw-r--r--CPP/7zip/Common/LimitedStreams.h116
-rw-r--r--CPP/7zip/Common/LockedStream.h4
-rw-r--r--CPP/7zip/Common/MemBlocks.cpp8
-rw-r--r--CPP/7zip/Common/MemBlocks.h8
-rw-r--r--CPP/7zip/Common/MethodId.h4
-rw-r--r--CPP/7zip/Common/MethodProps.cpp71
-rw-r--r--CPP/7zip/Common/MethodProps.h4
-rw-r--r--CPP/7zip/Common/MultiOutStream.cpp849
-rw-r--r--CPP/7zip/Common/MultiOutStream.h160
-rw-r--r--CPP/7zip/Common/OffsetStream.cpp10
-rw-r--r--CPP/7zip/Common/OffsetStream.h22
-rw-r--r--CPP/7zip/Common/OutBuffer.cpp24
-rw-r--r--CPP/7zip/Common/OutBuffer.h10
-rw-r--r--CPP/7zip/Common/OutMemStream.cpp16
-rw-r--r--CPP/7zip/Common/OutMemStream.h27
-rw-r--r--CPP/7zip/Common/ProgressMt.cpp6
-rw-r--r--CPP/7zip/Common/ProgressMt.h19
-rw-r--r--CPP/7zip/Common/ProgressUtils.cpp10
-rw-r--r--CPP/7zip/Common/ProgressUtils.h24
-rw-r--r--CPP/7zip/Common/PropId.cpp4
-rw-r--r--CPP/7zip/Common/RegisterArc.h12
-rw-r--r--CPP/7zip/Common/RegisterCodec.h12
-rw-r--r--CPP/7zip/Common/StdAfx.h7
-rw-r--r--CPP/7zip/Common/StreamBinder.cpp37
-rw-r--r--CPP/7zip/Common/StreamBinder.h4
-rw-r--r--CPP/7zip/Common/StreamObjects.cpp37
-rw-r--r--CPP/7zip/Common/StreamObjects.h84
-rw-r--r--CPP/7zip/Common/StreamUtils.cpp53
-rw-r--r--CPP/7zip/Common/StreamUtils.h22
-rw-r--r--CPP/7zip/Common/UniqBlocks.h4
-rw-r--r--CPP/7zip/Common/VirtThread.cpp6
-rw-r--r--CPP/7zip/Common/VirtThread.h6
-rw-r--r--CPP/7zip/Compress/BZip2Const.h4
-rw-r--r--CPP/7zip/Compress/BZip2Crc.h10
-rw-r--r--CPP/7zip/Compress/BZip2Decoder.cpp106
-rw-r--r--CPP/7zip/Compress/BZip2Decoder.h105
-rw-r--r--CPP/7zip/Compress/BZip2Encoder.cpp46
-rw-r--r--CPP/7zip/Compress/BZip2Encoder.h70
-rw-r--r--CPP/7zip/Compress/BZip2Register.cpp4
-rw-r--r--CPP/7zip/Compress/Bcj2Coder.cpp895
-rw-r--r--CPP/7zip/Compress/Bcj2Coder.h125
-rw-r--r--CPP/7zip/Compress/Bcj2Register.cpp2
-rw-r--r--CPP/7zip/Compress/BcjCoder.cpp12
-rw-r--r--CPP/7zip/Compress/BcjCoder.h32
-rw-r--r--CPP/7zip/Compress/BcjRegister.cpp4
-rw-r--r--CPP/7zip/Compress/BitlDecoder.h22
-rw-r--r--CPP/7zip/Compress/BitlEncoder.h4
-rw-r--r--CPP/7zip/Compress/BitmDecoder.h14
-rw-r--r--CPP/7zip/Compress/BitmEncoder.h4
-rw-r--r--CPP/7zip/Compress/BranchMisc.cpp97
-rw-r--r--CPP/7zip/Compress/BranchMisc.h56
-rw-r--r--CPP/7zip/Compress/BranchRegister.cpp26
-rw-r--r--CPP/7zip/Compress/ByteSwap.cpp105
-rw-r--r--CPP/7zip/Compress/Codec.def1
-rw-r--r--CPP/7zip/Compress/CodecExports.cpp69
-rw-r--r--CPP/7zip/Compress/CopyCoder.cpp27
-rw-r--r--CPP/7zip/Compress/CopyCoder.h37
-rw-r--r--CPP/7zip/Compress/Deflate64Register.cpp5
-rw-r--r--CPP/7zip/Compress/DeflateConst.h4
-rw-r--r--CPP/7zip/Compress/DeflateDecoder.cpp46
-rw-r--r--CPP/7zip/Compress/DeflateDecoder.h68
-rw-r--r--CPP/7zip/Compress/DeflateEncoder.cpp61
-rw-r--r--CPP/7zip/Compress/DeflateEncoder.h22
-rw-r--r--CPP/7zip/Compress/DeflateRegister.cpp4
-rw-r--r--CPP/7zip/Compress/DeltaFilter.cpp48
-rw-r--r--CPP/7zip/Compress/HuffmanDecoder.h8
-rw-r--r--CPP/7zip/Compress/ImplodeDecoder.cpp28
-rw-r--r--CPP/7zip/Compress/ImplodeDecoder.h30
-rw-r--r--CPP/7zip/Compress/ImplodeHuffmanDecoder.h4
-rw-r--r--CPP/7zip/Compress/LzOutWindow.cpp2
-rw-r--r--CPP/7zip/Compress/LzOutWindow.h6
-rw-r--r--CPP/7zip/Compress/LzfseDecoder.cpp83
-rw-r--r--CPP/7zip/Compress/LzfseDecoder.h18
-rw-r--r--CPP/7zip/Compress/LzhDecoder.cpp30
-rw-r--r--CPP/7zip/Compress/LzhDecoder.h17
-rw-r--r--CPP/7zip/Compress/Lzma2Decoder.cpp58
-rw-r--r--CPP/7zip/Compress/Lzma2Decoder.h99
-rw-r--r--CPP/7zip/Compress/Lzma2Encoder.cpp22
-rw-r--r--CPP/7zip/Compress/Lzma2Encoder.h32
-rw-r--r--CPP/7zip/Compress/Lzma2Register.cpp2
-rw-r--r--CPP/7zip/Compress/LzmaDecoder.cpp53
-rw-r--r--CPP/7zip/Compress/LzmaDecoder.h102
-rw-r--r--CPP/7zip/Compress/LzmaEncoder.cpp41
-rw-r--r--CPP/7zip/Compress/LzmaEncoder.h27
-rw-r--r--CPP/7zip/Compress/LzmaRegister.cpp2
-rw-r--r--CPP/7zip/Compress/LzmsDecoder.cpp36
-rw-r--r--CPP/7zip/Compress/LzmsDecoder.h6
-rw-r--r--CPP/7zip/Compress/Lzx.h6
-rw-r--r--CPP/7zip/Compress/LzxDecoder.cpp44
-rw-r--r--CPP/7zip/Compress/LzxDecoder.h13
-rw-r--r--CPP/7zip/Compress/Mtf8.h36
-rw-r--r--CPP/7zip/Compress/PpmdDecoder.cpp46
-rw-r--r--CPP/7zip/Compress/PpmdDecoder.h66
-rw-r--r--CPP/7zip/Compress/PpmdEncoder.cpp20
-rw-r--r--CPP/7zip/Compress/PpmdEncoder.h24
-rw-r--r--CPP/7zip/Compress/PpmdRegister.cpp2
-rw-r--r--CPP/7zip/Compress/PpmdZip.cpp52
-rw-r--r--CPP/7zip/Compress/PpmdZip.h42
-rw-r--r--CPP/7zip/Compress/QuantumDecoder.cpp18
-rw-r--r--CPP/7zip/Compress/QuantumDecoder.h18
-rw-r--r--CPP/7zip/Compress/Rar1Decoder.cpp34
-rw-r--r--CPP/7zip/Compress/Rar1Decoder.h22
-rw-r--r--CPP/7zip/Compress/Rar2Decoder.cpp68
-rw-r--r--CPP/7zip/Compress/Rar2Decoder.h22
-rw-r--r--CPP/7zip/Compress/Rar3Decoder.cpp86
-rw-r--r--CPP/7zip/Compress/Rar3Decoder.h31
-rw-r--r--CPP/7zip/Compress/Rar3Vm.cpp270
-rw-r--r--CPP/7zip/Compress/Rar3Vm.h22
-rw-r--r--CPP/7zip/Compress/Rar5Decoder.cpp108
-rw-r--r--CPP/7zip/Compress/Rar5Decoder.h34
-rw-r--r--CPP/7zip/Compress/ShrinkDecoder.cpp10
-rw-r--r--CPP/7zip/Compress/ShrinkDecoder.h26
-rw-r--r--CPP/7zip/Compress/StdAfx.h7
-rw-r--r--CPP/7zip/Compress/XpressDecoder.cpp4
-rw-r--r--CPP/7zip/Compress/XpressDecoder.h6
-rw-r--r--CPP/7zip/Compress/XzDecoder.cpp20
-rw-r--r--CPP/7zip/Compress/XzDecoder.h53
-rw-r--r--CPP/7zip/Compress/XzEncoder.cpp28
-rw-r--r--CPP/7zip/Compress/XzEncoder.h29
-rw-r--r--CPP/7zip/Compress/ZDecoder.cpp48
-rw-r--r--CPP/7zip/Compress/ZDecoder.h19
-rw-r--r--CPP/7zip/Compress/ZlibDecoder.cpp16
-rw-r--r--CPP/7zip/Compress/ZlibDecoder.h32
-rw-r--r--CPP/7zip/Compress/ZlibEncoder.cpp20
-rw-r--r--CPP/7zip/Compress/ZlibEncoder.h26
-rw-r--r--CPP/7zip/Crypto/7zAes.cpp32
-rw-r--r--CPP/7zip/Crypto/7zAes.h41
-rw-r--r--CPP/7zip/Crypto/7zAesRegister.cpp2
-rw-r--r--CPP/7zip/Crypto/HmacSha1.cpp2
-rw-r--r--CPP/7zip/Crypto/HmacSha1.h4
-rw-r--r--CPP/7zip/Crypto/HmacSha256.cpp2
-rw-r--r--CPP/7zip/Crypto/HmacSha256.h4
-rw-r--r--CPP/7zip/Crypto/MyAes.cpp253
-rw-r--r--CPP/7zip/Crypto/MyAes.h113
-rw-r--r--CPP/7zip/Crypto/MyAesReg.cpp21
-rw-r--r--CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp6
-rw-r--r--CPP/7zip/Crypto/Pbkdf2HmacSha1.h4
-rw-r--r--CPP/7zip/Crypto/RandGen.cpp38
-rw-r--r--CPP/7zip/Crypto/RandGen.h7
-rw-r--r--CPP/7zip/Crypto/Rar20Crypto.cpp14
-rw-r--r--CPP/7zip/Crypto/Rar20Crypto.h15
-rw-r--r--CPP/7zip/Crypto/Rar5Aes.cpp16
-rw-r--r--CPP/7zip/Crypto/Rar5Aes.h20
-rw-r--r--CPP/7zip/Crypto/RarAes.cpp8
-rw-r--r--CPP/7zip/Crypto/RarAes.h23
-rw-r--r--CPP/7zip/Crypto/Sha1Cls.h4
-rw-r--r--CPP/7zip/Crypto/StdAfx.h7
-rw-r--r--CPP/7zip/Crypto/WzAes.cpp31
-rw-r--r--CPP/7zip/Crypto/WzAes.h37
-rw-r--r--CPP/7zip/Crypto/ZipCrypto.cpp14
-rw-r--r--CPP/7zip/Crypto/ZipCrypto.h20
-rw-r--r--CPP/7zip/Crypto/ZipStrong.cpp43
-rw-r--r--CPP/7zip/Crypto/ZipStrong.h36
-rw-r--r--CPP/7zip/Guid.txt6
-rw-r--r--CPP/7zip/ICoder.h406
-rw-r--r--CPP/7zip/IDecl.h62
-rw-r--r--CPP/7zip/IPassword.h27
-rw-r--r--CPP/7zip/IProgress.h19
-rw-r--r--CPP/7zip/IStream.h176
-rw-r--r--CPP/7zip/LzmaDec.mak2
-rw-r--r--CPP/7zip/MyVersionInfo.rc2
-rw-r--r--CPP/7zip/PropID.h6
-rw-r--r--CPP/7zip/UI/Agent/Agent.cpp238
-rw-r--r--CPP/7zip/UI/Agent/Agent.h187
-rw-r--r--CPP/7zip/UI/Agent/AgentOut.cpp118
-rw-r--r--CPP/7zip/UI/Agent/AgentProxy.cpp95
-rw-r--r--CPP/7zip/UI/Agent/AgentProxy.h16
-rw-r--r--CPP/7zip/UI/Agent/ArchiveFolder.cpp11
-rw-r--r--CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp129
-rw-r--r--CPP/7zip/UI/Agent/ArchiveFolderOut.cpp57
-rw-r--r--CPP/7zip/UI/Agent/IFolderArchive.h125
-rw-r--r--CPP/7zip/UI/Agent/StdAfx.h7
-rw-r--r--CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp16
-rw-r--r--CPP/7zip/UI/Agent/UpdateCallbackAgent.h8
-rw-r--r--CPP/7zip/UI/Client7z/Client7z.cpp144
-rw-r--r--CPP/7zip/UI/Client7z/Client7z.dsp94
-rw-r--r--CPP/7zip/UI/Client7z/StdAfx.h7
-rw-r--r--CPP/7zip/UI/Common/ArchiveCommandLine.cpp36
-rw-r--r--CPP/7zip/UI/Common/ArchiveCommandLine.h26
-rw-r--r--CPP/7zip/UI/Common/ArchiveExtractCallback.cpp303
-rw-r--r--CPP/7zip/UI/Common/ArchiveExtractCallback.h151
-rw-r--r--CPP/7zip/UI/Common/ArchiveName.cpp233
-rw-r--r--CPP/7zip/UI/Common/ArchiveName.h12
-rw-r--r--CPP/7zip/UI/Common/ArchiveOpenCallback.cpp269
-rw-r--r--CPP/7zip/UI/Common/ArchiveOpenCallback.h200
-rw-r--r--CPP/7zip/UI/Common/Bench.cpp1105
-rw-r--r--CPP/7zip/UI/Common/Bench.h23
-rw-r--r--CPP/7zip/UI/Common/CompressCall.cpp10
-rw-r--r--CPP/7zip/UI/Common/CompressCall.h4
-rw-r--r--CPP/7zip/UI/Common/CompressCall2.cpp14
-rw-r--r--CPP/7zip/UI/Common/DefaultName.h4
-rw-r--r--CPP/7zip/UI/Common/DirItem.h18
-rw-r--r--CPP/7zip/UI/Common/EnumDirItems.cpp128
-rw-r--r--CPP/7zip/UI/Common/EnumDirItems.h4
-rw-r--r--CPP/7zip/UI/Common/ExitCode.h4
-rw-r--r--CPP/7zip/UI/Common/Extract.cpp59
-rw-r--r--CPP/7zip/UI/Common/Extract.h11
-rw-r--r--CPP/7zip/UI/Common/ExtractMode.h4
-rw-r--r--CPP/7zip/UI/Common/ExtractingFilePath.cpp2
-rw-r--r--CPP/7zip/UI/Common/ExtractingFilePath.h4
-rw-r--r--CPP/7zip/UI/Common/HashCalc.cpp190
-rw-r--r--CPP/7zip/UI/Common/HashCalc.h92
-rw-r--r--CPP/7zip/UI/Common/IFileExtractCallback.h92
-rw-r--r--CPP/7zip/UI/Common/LoadCodecs.cpp314
-rw-r--r--CPP/7zip/UI/Common/LoadCodecs.h136
-rw-r--r--CPP/7zip/UI/Common/OpenArchive.cpp451
-rw-r--r--CPP/7zip/UI/Common/OpenArchive.h45
-rw-r--r--CPP/7zip/UI/Common/PropIDUtils.cpp60
-rw-r--r--CPP/7zip/UI/Common/PropIDUtils.h6
-rw-r--r--CPP/7zip/UI/Common/Property.h4
-rw-r--r--CPP/7zip/UI/Common/SetProperties.cpp9
-rw-r--r--CPP/7zip/UI/Common/SetProperties.h4
-rw-r--r--CPP/7zip/UI/Common/SortUtils.h4
-rw-r--r--CPP/7zip/UI/Common/StdAfx.h7
-rw-r--r--CPP/7zip/UI/Common/TempFiles.h4
-rw-r--r--CPP/7zip/UI/Common/Update.cpp563
-rw-r--r--CPP/7zip/UI/Common/Update.h93
-rw-r--r--CPP/7zip/UI/Common/UpdateAction.h4
-rw-r--r--CPP/7zip/UI/Common/UpdateCallback.cpp203
-rw-r--r--CPP/7zip/UI/Common/UpdateCallback.h177
-rw-r--r--CPP/7zip/UI/Common/UpdatePair.cpp10
-rw-r--r--CPP/7zip/UI/Common/UpdatePair.h4
-rw-r--r--CPP/7zip/UI/Common/UpdateProduce.h9
-rw-r--r--CPP/7zip/UI/Common/WorkDir.cpp39
-rw-r--r--CPP/7zip/UI/Common/WorkDir.h4
-rw-r--r--CPP/7zip/UI/Common/ZipRegistry.cpp14
-rw-r--r--CPP/7zip/UI/Common/ZipRegistry.h17
-rw-r--r--CPP/7zip/UI/Console/BenchCon.cpp8
-rw-r--r--CPP/7zip/UI/Console/BenchCon.h4
-rw-r--r--CPP/7zip/UI/Console/Console.dsp36
-rw-r--r--CPP/7zip/UI/Console/Console.mak4
-rw-r--r--CPP/7zip/UI/Console/Console.manifest3
-rw-r--r--CPP/7zip/UI/Console/ConsoleClose.h8
-rw-r--r--CPP/7zip/UI/Console/ExtractCallbackConsole.cpp42
-rw-r--r--CPP/7zip/UI/Console/ExtractCallbackConsole.h63
-rw-r--r--CPP/7zip/UI/Console/HashCon.cpp2
-rw-r--r--CPP/7zip/UI/Console/HashCon.h17
-rw-r--r--CPP/7zip/UI/Console/List.cpp84
-rw-r--r--CPP/7zip/UI/Console/List.h8
-rw-r--r--CPP/7zip/UI/Console/Main.cpp176
-rw-r--r--CPP/7zip/UI/Console/MainAr.cpp50
-rw-r--r--CPP/7zip/UI/Console/OpenCallbackConsole.cpp6
-rw-r--r--CPP/7zip/UI/Console/OpenCallbackConsole.h16
-rw-r--r--CPP/7zip/UI/Console/PercentPrinter.cpp10
-rw-r--r--CPP/7zip/UI/Console/PercentPrinter.h4
-rw-r--r--CPP/7zip/UI/Console/StdAfx.h7
-rw-r--r--CPP/7zip/UI/Console/UpdateCallbackConsole.cpp24
-rw-r--r--CPP/7zip/UI/Console/UpdateCallbackConsole.h25
-rw-r--r--CPP/7zip/UI/Console/UserInputUtils.cpp15
-rw-r--r--CPP/7zip/UI/Console/UserInputUtils.h4
-rw-r--r--CPP/7zip/UI/Console/makefile3
-rw-r--r--CPP/7zip/UI/Console/makefile.gcc11
-rw-r--r--CPP/7zip/UI/Explorer/ContextMenu.cpp849
-rw-r--r--CPP/7zip/UI/Explorer/ContextMenu.h120
-rw-r--r--CPP/7zip/UI/Explorer/ContextMenuFlags.h4
-rw-r--r--CPP/7zip/UI/Explorer/DllExportsExplorer.cpp49
-rw-r--r--CPP/7zip/UI/Explorer/Explorer.dsp53
-rw-r--r--CPP/7zip/UI/Explorer/MyExplorerCommand.h6
-rw-r--r--CPP/7zip/UI/Explorer/MyMessages.cpp7
-rw-r--r--CPP/7zip/UI/Explorer/MyMessages.h8
-rw-r--r--CPP/7zip/UI/Explorer/RegistryContextMenu.cpp7
-rw-r--r--CPP/7zip/UI/Explorer/RegistryContextMenu.h4
-rw-r--r--CPP/7zip/UI/Explorer/StdAfx.h14
-rw-r--r--CPP/7zip/UI/Explorer/makefile5
-rw-r--r--CPP/7zip/UI/Explorer/resource.h2
-rw-r--r--CPP/7zip/UI/Explorer/resource2.rc1
-rw-r--r--CPP/7zip/UI/Far/ExtractEngine.cpp40
-rw-r--r--CPP/7zip/UI/Far/ExtractEngine.h32
-rw-r--r--CPP/7zip/UI/Far/Far.cpp257
-rw-r--r--CPP/7zip/UI/Far/Far.dsp52
-rw-r--r--CPP/7zip/UI/Far/FarPlugin.h35
-rw-r--r--CPP/7zip/UI/Far/FarUtils.cpp41
-rw-r--r--CPP/7zip/UI/Far/FarUtils.h30
-rw-r--r--CPP/7zip/UI/Far/Messages.h6
-rw-r--r--CPP/7zip/UI/Far/OverwriteDialogFar.cpp18
-rw-r--r--CPP/7zip/UI/Far/OverwriteDialogFar.h4
-rw-r--r--CPP/7zip/UI/Far/Plugin.cpp74
-rw-r--r--CPP/7zip/UI/Far/Plugin.h14
-rw-r--r--CPP/7zip/UI/Far/PluginDelete.cpp6
-rw-r--r--CPP/7zip/UI/Far/PluginRead.cpp16
-rw-r--r--CPP/7zip/UI/Far/PluginWrite.cpp49
-rw-r--r--CPP/7zip/UI/Far/ProgressBox.cpp18
-rw-r--r--CPP/7zip/UI/Far/ProgressBox.h4
-rw-r--r--CPP/7zip/UI/Far/StdAfx.h7
-rw-r--r--CPP/7zip/UI/Far/UpdateCallbackFar.cpp46
-rw-r--r--CPP/7zip/UI/Far/UpdateCallbackFar.h50
-rw-r--r--CPP/7zip/UI/Far/makefile8
-rw-r--r--CPP/7zip/UI/FileManager/7zFM.exe.manifest3
-rw-r--r--CPP/7zip/UI/FileManager/AboutDialog.cpp12
-rw-r--r--CPP/7zip/UI/FileManager/AboutDialog.h12
-rw-r--r--CPP/7zip/UI/FileManager/AltStreamsFolder.cpp301
-rw-r--r--CPP/7zip/UI/FileManager/AltStreamsFolder.h58
-rw-r--r--CPP/7zip/UI/FileManager/App.cpp66
-rw-r--r--CPP/7zip/UI/FileManager/App.h134
-rw-r--r--CPP/7zip/UI/FileManager/AppState.h4
-rw-r--r--CPP/7zip/UI/FileManager/BrowseDialog.cpp419
-rw-r--r--CPP/7zip/UI/FileManager/BrowseDialog.h19
-rw-r--r--CPP/7zip/UI/FileManager/ComboDialog.cpp4
-rw-r--r--CPP/7zip/UI/FileManager/ComboDialog.h12
-rw-r--r--CPP/7zip/UI/FileManager/CopyDialog.cpp15
-rw-r--r--CPP/7zip/UI/FileManager/CopyDialog.h14
-rw-r--r--CPP/7zip/UI/FileManager/DialogSize.h4
-rw-r--r--CPP/7zip/UI/FileManager/EditDialog.cpp16
-rw-r--r--CPP/7zip/UI/FileManager/EditDialog.h10
-rw-r--r--CPP/7zip/UI/FileManager/EditPage.cpp30
-rw-r--r--CPP/7zip/UI/FileManager/EditPage.h18
-rw-r--r--CPP/7zip/UI/FileManager/EnumFormatEtc.cpp41
-rw-r--r--CPP/7zip/UI/FileManager/EnumFormatEtc.h4
-rw-r--r--CPP/7zip/UI/FileManager/ExtractCallback.cpp161
-rw-r--r--CPP/7zip/UI/FileManager/ExtractCallback.h159
-rw-r--r--CPP/7zip/UI/FileManager/FM.cpp117
-rw-r--r--CPP/7zip/UI/FileManager/FM.dsp32
-rw-r--r--CPP/7zip/UI/FileManager/FM.mak8
-rw-r--r--CPP/7zip/UI/FileManager/FSDrives.cpp134
-rw-r--r--CPP/7zip/UI/FileManager/FSDrives.h23
-rw-r--r--CPP/7zip/UI/FileManager/FSFolder.cpp241
-rw-r--r--CPP/7zip/UI/FileManager/FSFolder.h77
-rw-r--r--CPP/7zip/UI/FileManager/FSFolderCopy.cpp266
-rw-r--r--CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp69
-rw-r--r--CPP/7zip/UI/FileManager/FileFolderPluginOpen.h6
-rw-r--r--CPP/7zip/UI/FileManager/FilePlugins.cpp27
-rw-r--r--CPP/7zip/UI/FileManager/FilePlugins.h12
-rw-r--r--CPP/7zip/UI/FileManager/FoldersPage.cpp20
-rw-r--r--CPP/7zip/UI/FileManager/FoldersPage.h14
-rw-r--r--CPP/7zip/UI/FileManager/FormatUtils.h4
-rw-r--r--CPP/7zip/UI/FileManager/HelpUtils.cpp10
-rw-r--r--CPP/7zip/UI/FileManager/HelpUtils.h4
-rw-r--r--CPP/7zip/UI/FileManager/IFolder.h277
-rw-r--r--CPP/7zip/UI/FileManager/LangPage.cpp271
-rw-r--r--CPP/7zip/UI/FileManager/LangPage.h27
-rw-r--r--CPP/7zip/UI/FileManager/LangPage.rc11
-rw-r--r--CPP/7zip/UI/FileManager/LangPageRes.h1
-rw-r--r--CPP/7zip/UI/FileManager/LangUtils.cpp71
-rw-r--r--CPP/7zip/UI/FileManager/LangUtils.h18
-rw-r--r--CPP/7zip/UI/FileManager/LinkDialog.cpp39
-rw-r--r--CPP/7zip/UI/FileManager/LinkDialog.h14
-rw-r--r--CPP/7zip/UI/FileManager/ListViewDialog.cpp16
-rw-r--r--CPP/7zip/UI/FileManager/ListViewDialog.h14
-rw-r--r--CPP/7zip/UI/FileManager/MenuPage.cpp26
-rw-r--r--CPP/7zip/UI/FileManager/MenuPage.h22
-rw-r--r--CPP/7zip/UI/FileManager/MessagesDialog.cpp10
-rw-r--r--CPP/7zip/UI/FileManager/MessagesDialog.h10
-rw-r--r--CPP/7zip/UI/FileManager/MyCom2.h61
-rw-r--r--CPP/7zip/UI/FileManager/MyLoadMenu.cpp358
-rw-r--r--CPP/7zip/UI/FileManager/MyLoadMenu.h8
-rw-r--r--CPP/7zip/UI/FileManager/MyWindowsNew.h53
-rw-r--r--CPP/7zip/UI/FileManager/NetFolder.cpp56
-rw-r--r--CPP/7zip/UI/FileManager/NetFolder.h20
-rw-r--r--CPP/7zip/UI/FileManager/OpenCallback.cpp81
-rw-r--r--CPP/7zip/UI/FileManager/OpenCallback.h69
-rw-r--r--CPP/7zip/UI/FileManager/OptionsDialog.cpp10
-rw-r--r--CPP/7zip/UI/FileManager/OverwriteDialog.cpp12
-rw-r--r--CPP/7zip/UI/FileManager/OverwriteDialog.h12
-rw-r--r--CPP/7zip/UI/FileManager/Panel.cpp198
-rw-r--r--CPP/7zip/UI/FileManager/Panel.h223
-rw-r--r--CPP/7zip/UI/FileManager/PanelCopy.cpp84
-rw-r--r--CPP/7zip/UI/FileManager/PanelCrc.cpp46
-rw-r--r--CPP/7zip/UI/FileManager/PanelDrag.cpp2822
-rw-r--r--CPP/7zip/UI/FileManager/PanelFolderChange.cpp88
-rw-r--r--CPP/7zip/UI/FileManager/PanelItemOpen.cpp144
-rw-r--r--CPP/7zip/UI/FileManager/PanelItems.cpp221
-rw-r--r--CPP/7zip/UI/FileManager/PanelKey.cpp34
-rw-r--r--CPP/7zip/UI/FileManager/PanelListNotify.cpp86
-rw-r--r--CPP/7zip/UI/FileManager/PanelMenu.cpp263
-rw-r--r--CPP/7zip/UI/FileManager/PanelOperations.cpp52
-rw-r--r--CPP/7zip/UI/FileManager/PanelSelect.cpp46
-rw-r--r--CPP/7zip/UI/FileManager/PanelSort.cpp28
-rw-r--r--CPP/7zip/UI/FileManager/PanelSplitFile.cpp64
-rw-r--r--CPP/7zip/UI/FileManager/PasswordDialog.cpp10
-rw-r--r--CPP/7zip/UI/FileManager/PasswordDialog.h12
-rw-r--r--CPP/7zip/UI/FileManager/PluginInterface.h47
-rw-r--r--CPP/7zip/UI/FileManager/PluginLoader.h13
-rw-r--r--CPP/7zip/UI/FileManager/ProgramLocation.h4
-rw-r--r--CPP/7zip/UI/FileManager/ProgressDialog.cpp18
-rw-r--r--CPP/7zip/UI/FileManager/ProgressDialog.h33
-rw-r--r--CPP/7zip/UI/FileManager/ProgressDialog2.cpp127
-rw-r--r--CPP/7zip/UI/FileManager/ProgressDialog2.h47
-rw-r--r--CPP/7zip/UI/FileManager/PropertyName.h4
-rw-r--r--CPP/7zip/UI/FileManager/PropertyName.rc2
-rw-r--r--CPP/7zip/UI/FileManager/PropertyNameRes.h2
-rw-r--r--CPP/7zip/UI/FileManager/RegistryAssociations.cpp6
-rw-r--r--CPP/7zip/UI/FileManager/RegistryAssociations.h4
-rw-r--r--CPP/7zip/UI/FileManager/RegistryPlugins.cpp168
-rw-r--r--CPP/7zip/UI/FileManager/RegistryPlugins.h27
-rw-r--r--CPP/7zip/UI/FileManager/RegistryUtils.cpp5
-rw-r--r--CPP/7zip/UI/FileManager/RegistryUtils.h4
-rw-r--r--CPP/7zip/UI/FileManager/RootFolder.cpp58
-rw-r--r--CPP/7zip/UI/FileManager/RootFolder.h19
-rw-r--r--CPP/7zip/UI/FileManager/SettingsPage.cpp12
-rw-r--r--CPP/7zip/UI/FileManager/SettingsPage.h14
-rw-r--r--CPP/7zip/UI/FileManager/SplitDialog.cpp12
-rw-r--r--CPP/7zip/UI/FileManager/SplitDialog.h14
-rw-r--r--CPP/7zip/UI/FileManager/SplitUtils.cpp2
-rw-r--r--CPP/7zip/UI/FileManager/SplitUtils.h4
-rw-r--r--CPP/7zip/UI/FileManager/StdAfx.h80
-rw-r--r--CPP/7zip/UI/FileManager/StringUtils.cpp26
-rw-r--r--CPP/7zip/UI/FileManager/StringUtils.h8
-rw-r--r--CPP/7zip/UI/FileManager/SysIconUtils.cpp97
-rw-r--r--CPP/7zip/UI/FileManager/SysIconUtils.h13
-rw-r--r--CPP/7zip/UI/FileManager/SystemPage.cpp36
-rw-r--r--CPP/7zip/UI/FileManager/SystemPage.h16
-rw-r--r--CPP/7zip/UI/FileManager/TextPairs.cpp14
-rw-r--r--CPP/7zip/UI/FileManager/TextPairs.h6
-rw-r--r--CPP/7zip/UI/FileManager/UpdateCallback100.cpp36
-rw-r--r--CPP/7zip/UI/FileManager/UpdateCallback100.h30
-rw-r--r--CPP/7zip/UI/FileManager/VerCtrl.cpp6
-rw-r--r--CPP/7zip/UI/FileManager/ViewSettings.cpp59
-rw-r--r--CPP/7zip/UI/FileManager/ViewSettings.h4
-rw-r--r--CPP/7zip/UI/FileManager/makefile3
-rw-r--r--CPP/7zip/UI/FileManager/resource.h10
-rw-r--r--CPP/7zip/UI/FileManager/resource.rc72
-rw-r--r--CPP/7zip/UI/GUI/7zG.exe.manifest3
-rw-r--r--CPP/7zip/UI/GUI/BenchmarkDialog.cpp129
-rw-r--r--CPP/7zip/UI/GUI/BenchmarkDialog.h4
-rw-r--r--CPP/7zip/UI/GUI/CompressDialog.cpp943
-rw-r--r--CPP/7zip/UI/GUI/CompressDialog.h58
-rw-r--r--CPP/7zip/UI/GUI/CompressDialog.rc12
-rw-r--r--CPP/7zip/UI/GUI/CompressDialogRes.h2
-rw-r--r--CPP/7zip/UI/GUI/ExtractDialog.cpp62
-rw-r--r--CPP/7zip/UI/GUI/ExtractDialog.h30
-rw-r--r--CPP/7zip/UI/GUI/ExtractGUI.cpp43
-rw-r--r--CPP/7zip/UI/GUI/ExtractGUI.h6
-rw-r--r--CPP/7zip/UI/GUI/GUI.cpp62
-rw-r--r--CPP/7zip/UI/GUI/GUI.dsp44
-rw-r--r--CPP/7zip/UI/GUI/HashGUI.cpp36
-rw-r--r--CPP/7zip/UI/GUI/HashGUI.h4
-rw-r--r--CPP/7zip/UI/GUI/StdAfx.h21
-rw-r--r--CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp10
-rw-r--r--CPP/7zip/UI/GUI/UpdateCallbackGUI.h23
-rw-r--r--CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp2
-rw-r--r--CPP/7zip/UI/GUI/UpdateCallbackGUI2.h5
-rw-r--r--CPP/7zip/UI/GUI/UpdateGUI.cpp34
-rw-r--r--CPP/7zip/UI/GUI/UpdateGUI.h4
-rw-r--r--CPP/7zip/UI/GUI/makefile7
-rw-r--r--CPP/7zip/warn_clang.mak40
-rw-r--r--CPP/7zip/warn_clang_mac.mak48
-rw-r--r--CPP/7zip/warn_gcc.mak42
-rw-r--r--CPP/Build.mak87
-rw-r--r--CPP/Common/AutoPtr.h10
-rw-r--r--CPP/Common/C_FileIO.h4
-rw-r--r--CPP/Common/CksumReg.cpp23
-rw-r--r--CPP/Common/ComTry.h4
-rw-r--r--CPP/Common/CommandLineParser.h4
-rw-r--r--CPP/Common/Common.h290
-rw-r--r--CPP/Common/CrcReg.cpp45
-rw-r--r--CPP/Common/Defs.h6
-rw-r--r--CPP/Common/DynLimBuf.cpp2
-rw-r--r--CPP/Common/DynLimBuf.h4
-rw-r--r--CPP/Common/DynamicBuffer.h10
-rw-r--r--CPP/Common/IntToString.cpp10
-rw-r--r--CPP/Common/IntToString.h4
-rw-r--r--CPP/Common/Lang.cpp70
-rw-r--r--CPP/Common/Lang.h17
-rw-r--r--CPP/Common/ListFileUtils.cpp4
-rw-r--r--CPP/Common/ListFileUtils.h8
-rw-r--r--CPP/Common/MyBuffer.h49
-rw-r--r--CPP/Common/MyBuffer2.h33
-rw-r--r--CPP/Common/MyCom.h370
-rw-r--r--CPP/Common/MyException.h4
-rw-r--r--CPP/Common/MyGuidDef.h22
-rw-r--r--CPP/Common/MyInitGuid.h26
-rw-r--r--CPP/Common/MyLinux.h4
-rw-r--r--CPP/Common/MyMap.cpp8
-rw-r--r--CPP/Common/MyMap.h4
-rw-r--r--CPP/Common/MyString.cpp140
-rw-r--r--CPP/Common/MyString.h89
-rw-r--r--CPP/Common/MyTypes.h21
-rw-r--r--CPP/Common/MyUnknown.h13
-rw-r--r--CPP/Common/MyVector.h21
-rw-r--r--CPP/Common/MyWindows.cpp8
-rw-r--r--CPP/Common/MyWindows.h120
-rw-r--r--CPP/Common/MyXml.cpp22
-rw-r--r--CPP/Common/MyXml.h4
-rw-r--r--CPP/Common/NewHandler.cpp184
-rw-r--r--CPP/Common/NewHandler.h20
-rw-r--r--CPP/Common/Random.h4
-rw-r--r--CPP/Common/Sha1Reg.cpp29
-rw-r--r--CPP/Common/Sha256Reg.cpp29
-rw-r--r--CPP/Common/StdAfx.h4
-rw-r--r--CPP/Common/StdInStream.cpp5
-rw-r--r--CPP/Common/StdInStream.h12
-rw-r--r--CPP/Common/StdOutStream.cpp8
-rw-r--r--CPP/Common/StdOutStream.h18
-rw-r--r--CPP/Common/StringConvert.cpp3
-rw-r--r--CPP/Common/StringConvert.h4
-rw-r--r--CPP/Common/StringToInt.h4
-rw-r--r--CPP/Common/TextConfig.cpp8
-rw-r--r--CPP/Common/TextConfig.h4
-rw-r--r--CPP/Common/UTFConvert.cpp196
-rw-r--r--CPP/Common/UTFConvert.h64
-rw-r--r--CPP/Common/Wildcard.cpp14
-rw-r--r--CPP/Common/Wildcard.h6
-rw-r--r--CPP/Common/XzCrc64Reg.cpp25
-rw-r--r--CPP/Windows/COM.h32
-rw-r--r--CPP/Windows/Clipboard.h6
-rw-r--r--CPP/Windows/CommonDialog.cpp291
-rw-r--r--CPP/Windows/CommonDialog.h44
-rw-r--r--CPP/Windows/Console.h4
-rw-r--r--CPP/Windows/Control/ComboBox.cpp8
-rw-r--r--CPP/Windows/Control/ComboBox.h22
-rw-r--r--CPP/Windows/Control/CommandBar.h12
-rw-r--r--CPP/Windows/Control/Dialog.cpp51
-rw-r--r--CPP/Windows/Control/Dialog.h114
-rw-r--r--CPP/Windows/Control/Edit.h4
-rw-r--r--CPP/Windows/Control/ImageList.h6
-rw-r--r--CPP/Windows/Control/ListView.cpp47
-rw-r--r--CPP/Windows/Control/ListView.h51
-rw-r--r--CPP/Windows/Control/ProgressBar.h24
-rw-r--r--CPP/Windows/Control/PropertyPage.cpp90
-rw-r--r--CPP/Windows/Control/PropertyPage.h20
-rw-r--r--CPP/Windows/Control/ReBar.h6
-rw-r--r--CPP/Windows/Control/Static.h4
-rw-r--r--CPP/Windows/Control/StatusBar.h10
-rw-r--r--CPP/Windows/Control/StdAfx.h7
-rw-r--r--CPP/Windows/Control/ToolBar.h6
-rw-r--r--CPP/Windows/Control/Trackbar.h4
-rw-r--r--CPP/Windows/Control/Window2.cpp14
-rw-r--r--CPP/Windows/Control/Window2.h16
-rw-r--r--CPP/Windows/DLL.cpp50
-rw-r--r--CPP/Windows/DLL.h49
-rw-r--r--CPP/Windows/Defs.h5
-rw-r--r--CPP/Windows/ErrorMsg.cpp8
-rw-r--r--CPP/Windows/ErrorMsg.h4
-rw-r--r--CPP/Windows/FileDir.cpp235
-rw-r--r--CPP/Windows/FileDir.h6
-rw-r--r--CPP/Windows/FileFind.cpp36
-rw-r--r--CPP/Windows/FileFind.h14
-rw-r--r--CPP/Windows/FileIO.cpp38
-rw-r--r--CPP/Windows/FileIO.h51
-rw-r--r--CPP/Windows/FileLink.cpp79
-rw-r--r--CPP/Windows/FileMapping.h6
-rw-r--r--CPP/Windows/FileName.cpp171
-rw-r--r--CPP/Windows/FileName.h38
-rw-r--r--CPP/Windows/FileSystem.cpp24
-rw-r--r--CPP/Windows/FileSystem.h4
-rw-r--r--CPP/Windows/Handle.h8
-rw-r--r--CPP/Windows/MemoryGlobal.h12
-rw-r--r--CPP/Windows/MemoryLock.cpp28
-rw-r--r--CPP/Windows/MemoryLock.h4
-rw-r--r--CPP/Windows/Menu.cpp155
-rw-r--r--CPP/Windows/Menu.h52
-rw-r--r--CPP/Windows/NationalTime.cpp8
-rw-r--r--CPP/Windows/NationalTime.h4
-rw-r--r--CPP/Windows/Net.cpp56
-rw-r--r--CPP/Windows/Net.h5
-rw-r--r--CPP/Windows/NtCheck.h14
-rw-r--r--CPP/Windows/ProcessMessages.h4
-rw-r--r--CPP/Windows/ProcessUtils.cpp22
-rw-r--r--CPP/Windows/ProcessUtils.h56
-rw-r--r--CPP/Windows/PropVariant.cpp8
-rw-r--r--CPP/Windows/PropVariant.h10
-rw-r--r--CPP/Windows/PropVariantConv.cpp10
-rw-r--r--CPP/Windows/PropVariantConv.h4
-rw-r--r--CPP/Windows/PropVariantUtils.h12
-rw-r--r--CPP/Windows/Registry.h4
-rw-r--r--CPP/Windows/ResourceString.h5
-rw-r--r--CPP/Windows/SecurityUtils.cpp38
-rw-r--r--CPP/Windows/SecurityUtils.h12
-rw-r--r--CPP/Windows/Shell.cpp574
-rw-r--r--CPP/Windows/Shell.h62
-rw-r--r--CPP/Windows/StdAfx.h8
-rw-r--r--CPP/Windows/Synchronization.cpp24
-rw-r--r--CPP/Windows/Synchronization.h50
-rw-r--r--CPP/Windows/System.cpp58
-rw-r--r--CPP/Windows/System.h17
-rw-r--r--CPP/Windows/SystemInfo.cpp291
-rw-r--r--CPP/Windows/SystemInfo.h5
-rw-r--r--CPP/Windows/Thread.h6
-rw-r--r--CPP/Windows/TimeUtils.cpp4
-rw-r--r--CPP/Windows/TimeUtils.h4
-rw-r--r--CPP/Windows/Window.cpp10
-rw-r--r--CPP/Windows/Window.h113
-rw-r--r--DOC/7zip.wxs2
-rw-r--r--DOC/Methods.txt7
-rw-r--r--DOC/lzma.txt43
-rw-r--r--DOC/readme.txt49
-rw-r--r--DOC/src-history.txt22
951 files changed, 39693 insertions, 24648 deletions
diff --git a/C/7z.h b/C/7z.h
index 304f75f..9e27c01 100644
--- a/C/7z.h
+++ b/C/7z.h
@@ -1,8 +1,8 @@
1/* 7z.h -- 7z interface 1/* 7z.h -- 7z interface
22018-07-02 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_H 4#ifndef ZIP7_INC_7Z_H
5#define __7Z_H 5#define ZIP7_INC_7Z_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -98,7 +98,7 @@ typedef struct
98UInt64 SzAr_GetFolderUnpackSize(const CSzAr *p, UInt32 folderIndex); 98UInt64 SzAr_GetFolderUnpackSize(const CSzAr *p, UInt32 folderIndex);
99 99
100SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, 100SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex,
101 ILookInStream *stream, UInt64 startPos, 101 ILookInStreamPtr stream, UInt64 startPos,
102 Byte *outBuffer, size_t outSize, 102 Byte *outBuffer, size_t outSize,
103 ISzAllocPtr allocMain); 103 ISzAllocPtr allocMain);
104 104
@@ -174,7 +174,7 @@ UInt16 *SzArEx_GetFullNameUtf16_Back(const CSzArEx *p, size_t fileIndex, UInt16
174 174
175SRes SzArEx_Extract( 175SRes SzArEx_Extract(
176 const CSzArEx *db, 176 const CSzArEx *db,
177 ILookInStream *inStream, 177 ILookInStreamPtr inStream,
178 UInt32 fileIndex, /* index of file */ 178 UInt32 fileIndex, /* index of file */
179 UInt32 *blockIndex, /* index of solid block */ 179 UInt32 *blockIndex, /* index of solid block */
180 Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */ 180 Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */
@@ -196,7 +196,7 @@ SZ_ERROR_INPUT_EOF
196SZ_ERROR_FAIL 196SZ_ERROR_FAIL
197*/ 197*/
198 198
199SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, 199SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream,
200 ISzAllocPtr allocMain, ISzAllocPtr allocTemp); 200 ISzAllocPtr allocMain, ISzAllocPtr allocTemp);
201 201
202EXTERN_C_END 202EXTERN_C_END
diff --git a/C/7zAlloc.c b/C/7zAlloc.c
index c924a52..2f0659a 100644
--- a/C/7zAlloc.c
+++ b/C/7zAlloc.c
@@ -1,5 +1,5 @@
1/* 7zAlloc.c -- Allocation functions 1/* 7zAlloc.c -- Allocation functions for 7z processing
22017-04-03 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -7,74 +7,83 @@
7 7
8#include "7zAlloc.h" 8#include "7zAlloc.h"
9 9
10/* #define _SZ_ALLOC_DEBUG */ 10/* #define SZ_ALLOC_DEBUG */
11/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ 11/* use SZ_ALLOC_DEBUG to debug alloc/free operations */
12 12
13#ifdef _SZ_ALLOC_DEBUG 13#ifdef SZ_ALLOC_DEBUG
14 14
15/*
15#ifdef _WIN32 16#ifdef _WIN32
16#include <windows.h> 17#include "7zWindows.h"
17#endif 18#endif
19*/
18 20
19#include <stdio.h> 21#include <stdio.h>
20int g_allocCount = 0; 22static int g_allocCount = 0;
21int g_allocCountTemp = 0; 23static int g_allocCountTemp = 0;
22 24
25static void Print_Alloc(const char *s, size_t size, int *counter)
26{
27 const unsigned size2 = (unsigned)size;
28 fprintf(stderr, "\n%s count = %10d : %10u bytes; ", s, *counter, size2);
29 (*counter)++;
30}
31static void Print_Free(const char *s, int *counter)
32{
33 (*counter)--;
34 fprintf(stderr, "\n%s count = %10d", s, *counter);
35}
23#endif 36#endif
24 37
25void *SzAlloc(ISzAllocPtr p, size_t size) 38void *SzAlloc(ISzAllocPtr p, size_t size)
26{ 39{
27 UNUSED_VAR(p); 40 UNUSED_VAR(p)
28 if (size == 0) 41 if (size == 0)
29 return 0; 42 return 0;
30 #ifdef _SZ_ALLOC_DEBUG 43 #ifdef SZ_ALLOC_DEBUG
31 fprintf(stderr, "\nAlloc %10u bytes; count = %10d", (unsigned)size, g_allocCount); 44 Print_Alloc("Alloc", size, &g_allocCount);
32 g_allocCount++;
33 #endif 45 #endif
34 return malloc(size); 46 return malloc(size);
35} 47}
36 48
37void SzFree(ISzAllocPtr p, void *address) 49void SzFree(ISzAllocPtr p, void *address)
38{ 50{
39 UNUSED_VAR(p); 51 UNUSED_VAR(p)
40 #ifdef _SZ_ALLOC_DEBUG 52 #ifdef SZ_ALLOC_DEBUG
41 if (address != 0) 53 if (address)
42 { 54 Print_Free("Free ", &g_allocCount);
43 g_allocCount--;
44 fprintf(stderr, "\nFree; count = %10d", g_allocCount);
45 }
46 #endif 55 #endif
47 free(address); 56 free(address);
48} 57}
49 58
50void *SzAllocTemp(ISzAllocPtr p, size_t size) 59void *SzAllocTemp(ISzAllocPtr p, size_t size)
51{ 60{
52 UNUSED_VAR(p); 61 UNUSED_VAR(p)
53 if (size == 0) 62 if (size == 0)
54 return 0; 63 return 0;
55 #ifdef _SZ_ALLOC_DEBUG 64 #ifdef SZ_ALLOC_DEBUG
56 fprintf(stderr, "\nAlloc_temp %10u bytes; count = %10d", (unsigned)size, g_allocCountTemp); 65 Print_Alloc("Alloc_temp", size, &g_allocCountTemp);
57 g_allocCountTemp++; 66 /*
58 #ifdef _WIN32 67 #ifdef _WIN32
59 return HeapAlloc(GetProcessHeap(), 0, size); 68 return HeapAlloc(GetProcessHeap(), 0, size);
60 #endif 69 #endif
70 */
61 #endif 71 #endif
62 return malloc(size); 72 return malloc(size);
63} 73}
64 74
65void SzFreeTemp(ISzAllocPtr p, void *address) 75void SzFreeTemp(ISzAllocPtr p, void *address)
66{ 76{
67 UNUSED_VAR(p); 77 UNUSED_VAR(p)
68 #ifdef _SZ_ALLOC_DEBUG 78 #ifdef SZ_ALLOC_DEBUG
69 if (address != 0) 79 if (address)
70 { 80 Print_Free("Free_temp ", &g_allocCountTemp);
71 g_allocCountTemp--; 81 /*
72 fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp);
73 }
74 #ifdef _WIN32 82 #ifdef _WIN32
75 HeapFree(GetProcessHeap(), 0, address); 83 HeapFree(GetProcessHeap(), 0, address);
76 return; 84 return;
77 #endif 85 #endif
86 */
78 #endif 87 #endif
79 free(address); 88 free(address);
80} 89}
diff --git a/C/7zAlloc.h b/C/7zAlloc.h
index 44778f9..b2b8b0c 100644
--- a/C/7zAlloc.h
+++ b/C/7zAlloc.h
@@ -1,8 +1,8 @@
1/* 7zAlloc.h -- Allocation functions 1/* 7zAlloc.h -- Allocation functions
22017-04-03 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_ALLOC_H 4#ifndef ZIP7_INC_7Z_ALLOC_H
5#define __7Z_ALLOC_H 5#define ZIP7_INC_7Z_ALLOC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/7zArcIn.c b/C/7zArcIn.c
index 0d9dec4..43fa7c2 100644
--- a/C/7zArcIn.c
+++ b/C/7zArcIn.c
@@ -1,5 +1,5 @@
1/* 7zArcIn.c -- 7z Input functions 1/* 7zArcIn.c -- 7z Input functions
22021-02-09 : Igor Pavlov : Public domain */ 22023-05-11 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -10,10 +10,11 @@
10#include "7zCrc.h" 10#include "7zCrc.h"
11#include "CpuArch.h" 11#include "CpuArch.h"
12 12
13#define MY_ALLOC(T, p, size, alloc) { \ 13#define MY_ALLOC(T, p, size, alloc) \
14 if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; } 14 { if ((p = (T *)ISzAlloc_Alloc(alloc, (size) * sizeof(T))) == NULL) return SZ_ERROR_MEM; }
15 15
16#define MY_ALLOC_ZE(T, p, size, alloc) { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) } 16#define MY_ALLOC_ZE(T, p, size, alloc) \
17 { if ((size) == 0) p = NULL; else MY_ALLOC(T, p, size, alloc) }
17 18
18#define MY_ALLOC_AND_CPY(to, size, from, alloc) \ 19#define MY_ALLOC_AND_CPY(to, size, from, alloc) \
19 { MY_ALLOC(Byte, to, size, alloc); memcpy(to, from, size); } 20 { MY_ALLOC(Byte, to, size, alloc); memcpy(to, from, size); }
@@ -58,7 +59,7 @@ enum EIdEnum
58 59
59const Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; 60const Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
60 61
61#define SzBitUi32s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } 62#define SzBitUi32s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; }
62 63
63static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc) 64static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc)
64{ 65{
@@ -69,8 +70,8 @@ static SRes SzBitUi32s_Alloc(CSzBitUi32s *p, size_t num, ISzAllocPtr alloc)
69 } 70 }
70 else 71 else
71 { 72 {
72 MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc); 73 MY_ALLOC(Byte, p->Defs, (num + 7) >> 3, alloc)
73 MY_ALLOC(UInt32, p->Vals, num, alloc); 74 MY_ALLOC(UInt32, p->Vals, num, alloc)
74 } 75 }
75 return SZ_OK; 76 return SZ_OK;
76} 77}
@@ -81,7 +82,7 @@ static void SzBitUi32s_Free(CSzBitUi32s *p, ISzAllocPtr alloc)
81 ISzAlloc_Free(alloc, p->Vals); p->Vals = NULL; 82 ISzAlloc_Free(alloc, p->Vals); p->Vals = NULL;
82} 83}
83 84
84#define SzBitUi64s_Init(p) { (p)->Defs = NULL; (p)->Vals = NULL; } 85#define SzBitUi64s_INIT(p) { (p)->Defs = NULL; (p)->Vals = NULL; }
85 86
86static void SzBitUi64s_Free(CSzBitUi64s *p, ISzAllocPtr alloc) 87static void SzBitUi64s_Free(CSzBitUi64s *p, ISzAllocPtr alloc)
87{ 88{
@@ -96,7 +97,7 @@ static void SzAr_Init(CSzAr *p)
96 p->NumFolders = 0; 97 p->NumFolders = 0;
97 98
98 p->PackPositions = NULL; 99 p->PackPositions = NULL;
99 SzBitUi32s_Init(&p->FolderCRCs); 100 SzBitUi32s_INIT(&p->FolderCRCs)
100 101
101 p->FoCodersOffsets = NULL; 102 p->FoCodersOffsets = NULL;
102 p->FoStartPackStreamIndex = NULL; 103 p->FoStartPackStreamIndex = NULL;
@@ -142,11 +143,11 @@ void SzArEx_Init(CSzArEx *p)
142 p->FileNameOffsets = NULL; 143 p->FileNameOffsets = NULL;
143 p->FileNames = NULL; 144 p->FileNames = NULL;
144 145
145 SzBitUi32s_Init(&p->CRCs); 146 SzBitUi32s_INIT(&p->CRCs)
146 SzBitUi32s_Init(&p->Attribs); 147 SzBitUi32s_INIT(&p->Attribs)
147 // SzBitUi32s_Init(&p->Parents); 148 // SzBitUi32s_INIT(&p->Parents)
148 SzBitUi64s_Init(&p->MTime); 149 SzBitUi64s_INIT(&p->MTime)
149 SzBitUi64s_Init(&p->CTime); 150 SzBitUi64s_INIT(&p->CTime)
150} 151}
151 152
152void SzArEx_Free(CSzArEx *p, ISzAllocPtr alloc) 153void SzArEx_Free(CSzArEx *p, ISzAllocPtr alloc)
@@ -180,11 +181,20 @@ static int TestSignatureCandidate(const Byte *testBytes)
180 return 1; 181 return 1;
181} 182}
182 183
183#define SzData_Clear(p) { (p)->Data = NULL; (p)->Size = 0; } 184#define SzData_CLEAR(p) { (p)->Data = NULL; (p)->Size = 0; }
185
186#define SZ_READ_BYTE_SD_NOCHECK(_sd_, dest) \
187 (_sd_)->Size--; dest = *(_sd_)->Data++;
188
189#define SZ_READ_BYTE_SD(_sd_, dest) \
190 if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; \
191 SZ_READ_BYTE_SD_NOCHECK(_sd_, dest)
184 192
185#define SZ_READ_BYTE_SD(_sd_, dest) if ((_sd_)->Size == 0) return SZ_ERROR_ARCHIVE; (_sd_)->Size--; dest = *(_sd_)->Data++;
186#define SZ_READ_BYTE(dest) SZ_READ_BYTE_SD(sd, dest) 193#define SZ_READ_BYTE(dest) SZ_READ_BYTE_SD(sd, dest)
187#define SZ_READ_BYTE_2(dest) if (sd.Size == 0) return SZ_ERROR_ARCHIVE; sd.Size--; dest = *sd.Data++; 194
195#define SZ_READ_BYTE_2(dest) \
196 if (sd.Size == 0) return SZ_ERROR_ARCHIVE; \
197 sd.Size--; dest = *sd.Data++;
188 198
189#define SKIP_DATA(sd, size) { sd->Size -= (size_t)(size); sd->Data += (size_t)(size); } 199#define SKIP_DATA(sd, size) { sd->Size -= (size_t)(size); sd->Data += (size_t)(size); }
190#define SKIP_DATA2(sd, size) { sd.Size -= (size_t)(size); sd.Data += (size_t)(size); } 200#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)
192#define SZ_READ_32(dest) if (sd.Size < 4) return SZ_ERROR_ARCHIVE; \ 202#define SZ_READ_32(dest) if (sd.Size < 4) return SZ_ERROR_ARCHIVE; \
193 dest = GetUi32(sd.Data); SKIP_DATA2(sd, 4); 203 dest = GetUi32(sd.Data); SKIP_DATA2(sd, 4);
194 204
195static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value) 205static Z7_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value)
196{ 206{
197 Byte firstByte, mask; 207 Byte firstByte, mask;
198 unsigned i; 208 unsigned i;
199 UInt32 v; 209 UInt32 v;
200 210
201 SZ_READ_BYTE(firstByte); 211 SZ_READ_BYTE(firstByte)
202 if ((firstByte & 0x80) == 0) 212 if ((firstByte & 0x80) == 0)
203 { 213 {
204 *value = firstByte; 214 *value = firstByte;
205 return SZ_OK; 215 return SZ_OK;
206 } 216 }
207 SZ_READ_BYTE(v); 217 SZ_READ_BYTE(v)
208 if ((firstByte & 0x40) == 0) 218 if ((firstByte & 0x40) == 0)
209 { 219 {
210 *value = (((UInt32)firstByte & 0x3F) << 8) | v; 220 *value = (((UInt32)firstByte & 0x3F) << 8) | v;
211 return SZ_OK; 221 return SZ_OK;
212 } 222 }
213 SZ_READ_BYTE(mask); 223 SZ_READ_BYTE(mask)
214 *value = v | ((UInt32)mask << 8); 224 *value = v | ((UInt32)mask << 8);
215 mask = 0x20; 225 mask = 0x20;
216 for (i = 2; i < 8; i++) 226 for (i = 2; i < 8; i++)
@@ -218,11 +228,11 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value)
218 Byte b; 228 Byte b;
219 if ((firstByte & mask) == 0) 229 if ((firstByte & mask) == 0)
220 { 230 {
221 UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1); 231 const UInt64 highPart = (unsigned)firstByte & (unsigned)(mask - 1);
222 *value |= (highPart << (8 * i)); 232 *value |= (highPart << (8 * i));
223 return SZ_OK; 233 return SZ_OK;
224 } 234 }
225 SZ_READ_BYTE(b); 235 SZ_READ_BYTE(b)
226 *value |= ((UInt64)b << (8 * i)); 236 *value |= ((UInt64)b << (8 * i));
227 mask >>= 1; 237 mask >>= 1;
228 } 238 }
@@ -230,7 +240,7 @@ static MY_NO_INLINE SRes ReadNumber(CSzData *sd, UInt64 *value)
230} 240}
231 241
232 242
233static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value) 243static Z7_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value)
234{ 244{
235 Byte firstByte; 245 Byte firstByte;
236 UInt64 value64; 246 UInt64 value64;
@@ -244,7 +254,7 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value)
244 sd->Size--; 254 sd->Size--;
245 return SZ_OK; 255 return SZ_OK;
246 } 256 }
247 RINOK(ReadNumber(sd, &value64)); 257 RINOK(ReadNumber(sd, &value64))
248 if (value64 >= (UInt32)0x80000000 - 1) 258 if (value64 >= (UInt32)0x80000000 - 1)
249 return SZ_ERROR_UNSUPPORTED; 259 return SZ_ERROR_UNSUPPORTED;
250 if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 4))) 260 if (value64 >= ((UInt64)(1) << ((sizeof(size_t) - 1) * 8 + 4)))
@@ -258,10 +268,10 @@ static MY_NO_INLINE SRes SzReadNumber32(CSzData *sd, UInt32 *value)
258static SRes SkipData(CSzData *sd) 268static SRes SkipData(CSzData *sd)
259{ 269{
260 UInt64 size; 270 UInt64 size;
261 RINOK(ReadNumber(sd, &size)); 271 RINOK(ReadNumber(sd, &size))
262 if (size > sd->Size) 272 if (size > sd->Size)
263 return SZ_ERROR_ARCHIVE; 273 return SZ_ERROR_ARCHIVE;
264 SKIP_DATA(sd, size); 274 SKIP_DATA(sd, size)
265 return SZ_OK; 275 return SZ_OK;
266} 276}
267 277
@@ -270,22 +280,22 @@ static SRes WaitId(CSzData *sd, UInt32 id)
270 for (;;) 280 for (;;)
271 { 281 {
272 UInt64 type; 282 UInt64 type;
273 RINOK(ReadID(sd, &type)); 283 RINOK(ReadID(sd, &type))
274 if (type == id) 284 if (type == id)
275 return SZ_OK; 285 return SZ_OK;
276 if (type == k7zIdEnd) 286 if (type == k7zIdEnd)
277 return SZ_ERROR_ARCHIVE; 287 return SZ_ERROR_ARCHIVE;
278 RINOK(SkipData(sd)); 288 RINOK(SkipData(sd))
279 } 289 }
280} 290}
281 291
282static SRes RememberBitVector(CSzData *sd, UInt32 numItems, const Byte **v) 292static SRes RememberBitVector(CSzData *sd, UInt32 numItems, const Byte **v)
283{ 293{
284 UInt32 numBytes = (numItems + 7) >> 3; 294 const UInt32 numBytes = (numItems + 7) >> 3;
285 if (numBytes > sd->Size) 295 if (numBytes > sd->Size)
286 return SZ_ERROR_ARCHIVE; 296 return SZ_ERROR_ARCHIVE;
287 *v = sd->Data; 297 *v = sd->Data;
288 SKIP_DATA(sd, numBytes); 298 SKIP_DATA(sd, numBytes)
289 return SZ_OK; 299 return SZ_OK;
290} 300}
291 301
@@ -307,48 +317,48 @@ static UInt32 CountDefinedBits(const Byte *bits, UInt32 numItems)
307 return sum; 317 return sum;
308} 318}
309 319
310static MY_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc) 320static Z7_NO_INLINE SRes ReadBitVector(CSzData *sd, UInt32 numItems, Byte **v, ISzAllocPtr alloc)
311{ 321{
312 Byte allAreDefined; 322 Byte allAreDefined;
313 Byte *v2; 323 Byte *v2;
314 UInt32 numBytes = (numItems + 7) >> 3; 324 const UInt32 numBytes = (numItems + 7) >> 3;
315 *v = NULL; 325 *v = NULL;
316 SZ_READ_BYTE(allAreDefined); 326 SZ_READ_BYTE(allAreDefined)
317 if (numBytes == 0) 327 if (numBytes == 0)
318 return SZ_OK; 328 return SZ_OK;
319 if (allAreDefined == 0) 329 if (allAreDefined == 0)
320 { 330 {
321 if (numBytes > sd->Size) 331 if (numBytes > sd->Size)
322 return SZ_ERROR_ARCHIVE; 332 return SZ_ERROR_ARCHIVE;
323 MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc); 333 MY_ALLOC_AND_CPY(*v, numBytes, sd->Data, alloc)
324 SKIP_DATA(sd, numBytes); 334 SKIP_DATA(sd, numBytes)
325 return SZ_OK; 335 return SZ_OK;
326 } 336 }
327 MY_ALLOC(Byte, *v, numBytes, alloc); 337 MY_ALLOC(Byte, *v, numBytes, alloc)
328 v2 = *v; 338 v2 = *v;
329 memset(v2, 0xFF, (size_t)numBytes); 339 memset(v2, 0xFF, (size_t)numBytes);
330 { 340 {
331 unsigned numBits = (unsigned)numItems & 7; 341 const unsigned numBits = (unsigned)numItems & 7;
332 if (numBits != 0) 342 if (numBits != 0)
333 v2[(size_t)numBytes - 1] = (Byte)((((UInt32)1 << numBits) - 1) << (8 - numBits)); 343 v2[(size_t)numBytes - 1] = (Byte)((((UInt32)1 << numBits) - 1) << (8 - numBits));
334 } 344 }
335 return SZ_OK; 345 return SZ_OK;
336} 346}
337 347
338static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) 348static Z7_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc)
339{ 349{
340 UInt32 i; 350 UInt32 i;
341 CSzData sd; 351 CSzData sd;
342 UInt32 *vals; 352 UInt32 *vals;
343 const Byte *defs; 353 const Byte *defs;
344 MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc); 354 MY_ALLOC_ZE(UInt32, crcs->Vals, numItems, alloc)
345 sd = *sd2; 355 sd = *sd2;
346 defs = crcs->Defs; 356 defs = crcs->Defs;
347 vals = crcs->Vals; 357 vals = crcs->Vals;
348 for (i = 0; i < numItems; i++) 358 for (i = 0; i < numItems; i++)
349 if (SzBitArray_Check(defs, i)) 359 if (SzBitArray_Check(defs, i))
350 { 360 {
351 SZ_READ_32(vals[i]); 361 SZ_READ_32(vals[i])
352 } 362 }
353 else 363 else
354 vals[i] = 0; 364 vals[i] = 0;
@@ -359,7 +369,7 @@ static MY_NO_INLINE SRes ReadUi32s(CSzData *sd2, UInt32 numItems, CSzBitUi32s *c
359static SRes ReadBitUi32s(CSzData *sd, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc) 369static SRes ReadBitUi32s(CSzData *sd, UInt32 numItems, CSzBitUi32s *crcs, ISzAllocPtr alloc)
360{ 370{
361 SzBitUi32s_Free(crcs, alloc); 371 SzBitUi32s_Free(crcs, alloc);
362 RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc)); 372 RINOK(ReadBitVector(sd, numItems, &crcs->Defs, alloc))
363 return ReadUi32s(sd, numItems, crcs, alloc); 373 return ReadUi32s(sd, numItems, crcs, alloc);
364} 374}
365 375
@@ -367,36 +377,36 @@ static SRes SkipBitUi32s(CSzData *sd, UInt32 numItems)
367{ 377{
368 Byte allAreDefined; 378 Byte allAreDefined;
369 UInt32 numDefined = numItems; 379 UInt32 numDefined = numItems;
370 SZ_READ_BYTE(allAreDefined); 380 SZ_READ_BYTE(allAreDefined)
371 if (!allAreDefined) 381 if (!allAreDefined)
372 { 382 {
373 size_t numBytes = (numItems + 7) >> 3; 383 const size_t numBytes = (numItems + 7) >> 3;
374 if (numBytes > sd->Size) 384 if (numBytes > sd->Size)
375 return SZ_ERROR_ARCHIVE; 385 return SZ_ERROR_ARCHIVE;
376 numDefined = CountDefinedBits(sd->Data, numItems); 386 numDefined = CountDefinedBits(sd->Data, numItems);
377 SKIP_DATA(sd, numBytes); 387 SKIP_DATA(sd, numBytes)
378 } 388 }
379 if (numDefined > (sd->Size >> 2)) 389 if (numDefined > (sd->Size >> 2))
380 return SZ_ERROR_ARCHIVE; 390 return SZ_ERROR_ARCHIVE;
381 SKIP_DATA(sd, (size_t)numDefined * 4); 391 SKIP_DATA(sd, (size_t)numDefined * 4)
382 return SZ_OK; 392 return SZ_OK;
383} 393}
384 394
385static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc) 395static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc)
386{ 396{
387 RINOK(SzReadNumber32(sd, &p->NumPackStreams)); 397 RINOK(SzReadNumber32(sd, &p->NumPackStreams))
388 398
389 RINOK(WaitId(sd, k7zIdSize)); 399 RINOK(WaitId(sd, k7zIdSize))
390 MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc); 400 MY_ALLOC(UInt64, p->PackPositions, (size_t)p->NumPackStreams + 1, alloc)
391 { 401 {
392 UInt64 sum = 0; 402 UInt64 sum = 0;
393 UInt32 i; 403 UInt32 i;
394 UInt32 numPackStreams = p->NumPackStreams; 404 const UInt32 numPackStreams = p->NumPackStreams;
395 for (i = 0; i < numPackStreams; i++) 405 for (i = 0; i < numPackStreams; i++)
396 { 406 {
397 UInt64 packSize; 407 UInt64 packSize;
398 p->PackPositions[i] = sum; 408 p->PackPositions[i] = sum;
399 RINOK(ReadNumber(sd, &packSize)); 409 RINOK(ReadNumber(sd, &packSize))
400 sum += packSize; 410 sum += packSize;
401 if (sum < packSize) 411 if (sum < packSize)
402 return SZ_ERROR_ARCHIVE; 412 return SZ_ERROR_ARCHIVE;
@@ -407,16 +417,16 @@ static SRes ReadPackInfo(CSzAr *p, CSzData *sd, ISzAllocPtr alloc)
407 for (;;) 417 for (;;)
408 { 418 {
409 UInt64 type; 419 UInt64 type;
410 RINOK(ReadID(sd, &type)); 420 RINOK(ReadID(sd, &type))
411 if (type == k7zIdEnd) 421 if (type == k7zIdEnd)
412 return SZ_OK; 422 return SZ_OK;
413 if (type == k7zIdCRC) 423 if (type == k7zIdCRC)
414 { 424 {
415 /* CRC of packed streams is unused now */ 425 /* CRC of packed streams is unused now */
416 RINOK(SkipBitUi32s(sd, p->NumPackStreams)); 426 RINOK(SkipBitUi32s(sd, p->NumPackStreams))
417 continue; 427 continue;
418 } 428 }
419 RINOK(SkipData(sd)); 429 RINOK(SkipData(sd))
420 } 430 }
421} 431}
422 432
@@ -442,7 +452,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
442 f->NumPackStreams = 0; 452 f->NumPackStreams = 0;
443 f->UnpackStream = 0; 453 f->UnpackStream = 0;
444 454
445 RINOK(SzReadNumber32(sd, &numCoders)); 455 RINOK(SzReadNumber32(sd, &numCoders))
446 if (numCoders == 0 || numCoders > SZ_NUM_CODERS_IN_FOLDER_MAX) 456 if (numCoders == 0 || numCoders > SZ_NUM_CODERS_IN_FOLDER_MAX)
447 return SZ_ERROR_UNSUPPORTED; 457 return SZ_ERROR_UNSUPPORTED;
448 458
@@ -453,7 +463,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
453 unsigned idSize, j; 463 unsigned idSize, j;
454 UInt64 id; 464 UInt64 id;
455 465
456 SZ_READ_BYTE(mainByte); 466 SZ_READ_BYTE(mainByte)
457 if ((mainByte & 0xC0) != 0) 467 if ((mainByte & 0xC0) != 0)
458 return SZ_ERROR_UNSUPPORTED; 468 return SZ_ERROR_UNSUPPORTED;
459 469
@@ -481,12 +491,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
481 { 491 {
482 UInt32 numStreams; 492 UInt32 numStreams;
483 493
484 RINOK(SzReadNumber32(sd, &numStreams)); 494 RINOK(SzReadNumber32(sd, &numStreams))
485 if (numStreams > k_NumCodersStreams_in_Folder_MAX) 495 if (numStreams > k_NumCodersStreams_in_Folder_MAX)
486 return SZ_ERROR_UNSUPPORTED; 496 return SZ_ERROR_UNSUPPORTED;
487 coder->NumStreams = (Byte)numStreams; 497 coder->NumStreams = (Byte)numStreams;
488 498
489 RINOK(SzReadNumber32(sd, &numStreams)); 499 RINOK(SzReadNumber32(sd, &numStreams))
490 if (numStreams != 1) 500 if (numStreams != 1)
491 return SZ_ERROR_UNSUPPORTED; 501 return SZ_ERROR_UNSUPPORTED;
492 } 502 }
@@ -499,7 +509,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
499 if ((mainByte & 0x20) != 0) 509 if ((mainByte & 0x20) != 0)
500 { 510 {
501 UInt32 propsSize = 0; 511 UInt32 propsSize = 0;
502 RINOK(SzReadNumber32(sd, &propsSize)); 512 RINOK(SzReadNumber32(sd, &propsSize))
503 if (propsSize > sd->Size) 513 if (propsSize > sd->Size)
504 return SZ_ERROR_ARCHIVE; 514 return SZ_ERROR_ARCHIVE;
505 if (propsSize >= 0x80) 515 if (propsSize >= 0x80)
@@ -549,12 +559,12 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
549 { 559 {
550 CSzBond *bp = f->Bonds + i; 560 CSzBond *bp = f->Bonds + i;
551 561
552 RINOK(SzReadNumber32(sd, &bp->InIndex)); 562 RINOK(SzReadNumber32(sd, &bp->InIndex))
553 if (bp->InIndex >= numInStreams || streamUsed[bp->InIndex]) 563 if (bp->InIndex >= numInStreams || streamUsed[bp->InIndex])
554 return SZ_ERROR_ARCHIVE; 564 return SZ_ERROR_ARCHIVE;
555 streamUsed[bp->InIndex] = True; 565 streamUsed[bp->InIndex] = True;
556 566
557 RINOK(SzReadNumber32(sd, &bp->OutIndex)); 567 RINOK(SzReadNumber32(sd, &bp->OutIndex))
558 if (bp->OutIndex >= numCoders || coderUsed[bp->OutIndex]) 568 if (bp->OutIndex >= numCoders || coderUsed[bp->OutIndex])
559 return SZ_ERROR_ARCHIVE; 569 return SZ_ERROR_ARCHIVE;
560 coderUsed[bp->OutIndex] = True; 570 coderUsed[bp->OutIndex] = True;
@@ -584,7 +594,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
584 for (i = 0; i < numPackStreams; i++) 594 for (i = 0; i < numPackStreams; i++)
585 { 595 {
586 UInt32 index; 596 UInt32 index;
587 RINOK(SzReadNumber32(sd, &index)); 597 RINOK(SzReadNumber32(sd, &index))
588 if (index >= numInStreams || streamUsed[index]) 598 if (index >= numInStreams || streamUsed[index])
589 return SZ_ERROR_ARCHIVE; 599 return SZ_ERROR_ARCHIVE;
590 streamUsed[index] = True; 600 streamUsed[index] = True;
@@ -598,7 +608,7 @@ SRes SzGetNextFolderItem(CSzFolder *f, CSzData *sd)
598} 608}
599 609
600 610
601static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num) 611static Z7_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num)
602{ 612{
603 CSzData sd; 613 CSzData sd;
604 sd = *sd2; 614 sd = *sd2;
@@ -606,7 +616,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num)
606 { 616 {
607 Byte firstByte, mask; 617 Byte firstByte, mask;
608 unsigned i; 618 unsigned i;
609 SZ_READ_BYTE_2(firstByte); 619 SZ_READ_BYTE_2(firstByte)
610 if ((firstByte & 0x80) == 0) 620 if ((firstByte & 0x80) == 0)
611 continue; 621 continue;
612 if ((firstByte & 0x40) == 0) 622 if ((firstByte & 0x40) == 0)
@@ -622,7 +632,7 @@ static MY_NO_INLINE SRes SkipNumbers(CSzData *sd2, UInt32 num)
622 mask >>= 1; 632 mask >>= 1;
623 if (i > sd.Size) 633 if (i > sd.Size)
624 return SZ_ERROR_ARCHIVE; 634 return SZ_ERROR_ARCHIVE;
625 SKIP_DATA2(sd, i); 635 SKIP_DATA2(sd, i)
626 } 636 }
627 *sd2 = sd; 637 *sd2 = sd;
628 return SZ_OK; 638 return SZ_OK;
@@ -645,30 +655,30 @@ static SRes ReadUnpackInfo(CSzAr *p,
645 const Byte *startBufPtr; 655 const Byte *startBufPtr;
646 Byte external; 656 Byte external;
647 657
648 RINOK(WaitId(sd2, k7zIdFolder)); 658 RINOK(WaitId(sd2, k7zIdFolder))
649 659
650 RINOK(SzReadNumber32(sd2, &numFolders)); 660 RINOK(SzReadNumber32(sd2, &numFolders))
651 if (numFolders > numFoldersMax) 661 if (numFolders > numFoldersMax)
652 return SZ_ERROR_UNSUPPORTED; 662 return SZ_ERROR_UNSUPPORTED;
653 p->NumFolders = numFolders; 663 p->NumFolders = numFolders;
654 664
655 SZ_READ_BYTE_SD(sd2, external); 665 SZ_READ_BYTE_SD(sd2, external)
656 if (external == 0) 666 if (external == 0)
657 sd = *sd2; 667 sd = *sd2;
658 else 668 else
659 { 669 {
660 UInt32 index; 670 UInt32 index;
661 RINOK(SzReadNumber32(sd2, &index)); 671 RINOK(SzReadNumber32(sd2, &index))
662 if (index >= numTempBufs) 672 if (index >= numTempBufs)
663 return SZ_ERROR_ARCHIVE; 673 return SZ_ERROR_ARCHIVE;
664 sd.Data = tempBufs[index].data; 674 sd.Data = tempBufs[index].data;
665 sd.Size = tempBufs[index].size; 675 sd.Size = tempBufs[index].size;
666 } 676 }
667 677
668 MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc); 678 MY_ALLOC(size_t, p->FoCodersOffsets, (size_t)numFolders + 1, alloc)
669 MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc); 679 MY_ALLOC(UInt32, p->FoStartPackStreamIndex, (size_t)numFolders + 1, alloc)
670 MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc); 680 MY_ALLOC(UInt32, p->FoToCoderUnpackSizes, (size_t)numFolders + 1, alloc)
671 MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc); 681 MY_ALLOC_ZE(Byte, p->FoToMainUnpackSizeIndex, (size_t)numFolders, alloc)
672 682
673 startBufPtr = sd.Data; 683 startBufPtr = sd.Data;
674 684
@@ -681,7 +691,7 @@ static SRes ReadUnpackInfo(CSzAr *p,
681 691
682 p->FoCodersOffsets[fo] = (size_t)(sd.Data - startBufPtr); 692 p->FoCodersOffsets[fo] = (size_t)(sd.Data - startBufPtr);
683 693
684 RINOK(SzReadNumber32(&sd, &numCoders)); 694 RINOK(SzReadNumber32(&sd, &numCoders))
685 if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) 695 if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX)
686 return SZ_ERROR_UNSUPPORTED; 696 return SZ_ERROR_UNSUPPORTED;
687 697
@@ -691,7 +701,7 @@ static SRes ReadUnpackInfo(CSzAr *p,
691 unsigned idSize; 701 unsigned idSize;
692 UInt32 coderInStreams; 702 UInt32 coderInStreams;
693 703
694 SZ_READ_BYTE_2(mainByte); 704 SZ_READ_BYTE_2(mainByte)
695 if ((mainByte & 0xC0) != 0) 705 if ((mainByte & 0xC0) != 0)
696 return SZ_ERROR_UNSUPPORTED; 706 return SZ_ERROR_UNSUPPORTED;
697 idSize = (mainByte & 0xF); 707 idSize = (mainByte & 0xF);
@@ -699,15 +709,15 @@ static SRes ReadUnpackInfo(CSzAr *p,
699 return SZ_ERROR_UNSUPPORTED; 709 return SZ_ERROR_UNSUPPORTED;
700 if (idSize > sd.Size) 710 if (idSize > sd.Size)
701 return SZ_ERROR_ARCHIVE; 711 return SZ_ERROR_ARCHIVE;
702 SKIP_DATA2(sd, idSize); 712 SKIP_DATA2(sd, idSize)
703 713
704 coderInStreams = 1; 714 coderInStreams = 1;
705 715
706 if ((mainByte & 0x10) != 0) 716 if ((mainByte & 0x10) != 0)
707 { 717 {
708 UInt32 coderOutStreams; 718 UInt32 coderOutStreams;
709 RINOK(SzReadNumber32(&sd, &coderInStreams)); 719 RINOK(SzReadNumber32(&sd, &coderInStreams))
710 RINOK(SzReadNumber32(&sd, &coderOutStreams)); 720 RINOK(SzReadNumber32(&sd, &coderOutStreams))
711 if (coderInStreams > k_Scan_NumCodersStreams_in_Folder_MAX || coderOutStreams != 1) 721 if (coderInStreams > k_Scan_NumCodersStreams_in_Folder_MAX || coderOutStreams != 1)
712 return SZ_ERROR_UNSUPPORTED; 722 return SZ_ERROR_UNSUPPORTED;
713 } 723 }
@@ -717,10 +727,10 @@ static SRes ReadUnpackInfo(CSzAr *p,
717 if ((mainByte & 0x20) != 0) 727 if ((mainByte & 0x20) != 0)
718 { 728 {
719 UInt32 propsSize; 729 UInt32 propsSize;
720 RINOK(SzReadNumber32(&sd, &propsSize)); 730 RINOK(SzReadNumber32(&sd, &propsSize))
721 if (propsSize > sd.Size) 731 if (propsSize > sd.Size)
722 return SZ_ERROR_ARCHIVE; 732 return SZ_ERROR_ARCHIVE;
723 SKIP_DATA2(sd, propsSize); 733 SKIP_DATA2(sd, propsSize)
724 } 734 }
725 } 735 }
726 736
@@ -734,7 +744,7 @@ static SRes ReadUnpackInfo(CSzAr *p,
734 Byte coderUsed[k_Scan_NumCoders_MAX]; 744 Byte coderUsed[k_Scan_NumCoders_MAX];
735 745
736 UInt32 i; 746 UInt32 i;
737 UInt32 numBonds = numCoders - 1; 747 const UInt32 numBonds = numCoders - 1;
738 if (numInStreams < numBonds) 748 if (numInStreams < numBonds)
739 return SZ_ERROR_ARCHIVE; 749 return SZ_ERROR_ARCHIVE;
740 750
@@ -750,12 +760,12 @@ static SRes ReadUnpackInfo(CSzAr *p,
750 { 760 {
751 UInt32 index; 761 UInt32 index;
752 762
753 RINOK(SzReadNumber32(&sd, &index)); 763 RINOK(SzReadNumber32(&sd, &index))
754 if (index >= numInStreams || streamUsed[index]) 764 if (index >= numInStreams || streamUsed[index])
755 return SZ_ERROR_ARCHIVE; 765 return SZ_ERROR_ARCHIVE;
756 streamUsed[index] = True; 766 streamUsed[index] = True;
757 767
758 RINOK(SzReadNumber32(&sd, &index)); 768 RINOK(SzReadNumber32(&sd, &index))
759 if (index >= numCoders || coderUsed[index]) 769 if (index >= numCoders || coderUsed[index])
760 return SZ_ERROR_ARCHIVE; 770 return SZ_ERROR_ARCHIVE;
761 coderUsed[index] = True; 771 coderUsed[index] = True;
@@ -767,7 +777,7 @@ static SRes ReadUnpackInfo(CSzAr *p,
767 for (i = 0; i < numPackStreams; i++) 777 for (i = 0; i < numPackStreams; i++)
768 { 778 {
769 UInt32 index; 779 UInt32 index;
770 RINOK(SzReadNumber32(&sd, &index)); 780 RINOK(SzReadNumber32(&sd, &index))
771 if (index >= numInStreams || streamUsed[index]) 781 if (index >= numInStreams || streamUsed[index])
772 return SZ_ERROR_ARCHIVE; 782 return SZ_ERROR_ARCHIVE;
773 streamUsed[index] = True; 783 streamUsed[index] = True;
@@ -802,7 +812,7 @@ static SRes ReadUnpackInfo(CSzAr *p,
802 const size_t dataSize = (size_t)(sd.Data - startBufPtr); 812 const size_t dataSize = (size_t)(sd.Data - startBufPtr);
803 p->FoStartPackStreamIndex[fo] = packStreamIndex; 813 p->FoStartPackStreamIndex[fo] = packStreamIndex;
804 p->FoCodersOffsets[fo] = dataSize; 814 p->FoCodersOffsets[fo] = dataSize;
805 MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc); 815 MY_ALLOC_ZE_AND_CPY(p->CodersData, dataSize, startBufPtr, alloc)
806 } 816 }
807 817
808 if (external != 0) 818 if (external != 0)
@@ -812,21 +822,21 @@ static SRes ReadUnpackInfo(CSzAr *p,
812 sd = *sd2; 822 sd = *sd2;
813 } 823 }
814 824
815 RINOK(WaitId(&sd, k7zIdCodersUnpackSize)); 825 RINOK(WaitId(&sd, k7zIdCodersUnpackSize))
816 826
817 MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc); 827 MY_ALLOC_ZE(UInt64, p->CoderUnpackSizes, (size_t)numCodersOutStreams, alloc)
818 { 828 {
819 UInt32 i; 829 UInt32 i;
820 for (i = 0; i < numCodersOutStreams; i++) 830 for (i = 0; i < numCodersOutStreams; i++)
821 { 831 {
822 RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i)); 832 RINOK(ReadNumber(&sd, p->CoderUnpackSizes + i))
823 } 833 }
824 } 834 }
825 835
826 for (;;) 836 for (;;)
827 { 837 {
828 UInt64 type; 838 UInt64 type;
829 RINOK(ReadID(&sd, &type)); 839 RINOK(ReadID(&sd, &type))
830 if (type == k7zIdEnd) 840 if (type == k7zIdEnd)
831 { 841 {
832 *sd2 = sd; 842 *sd2 = sd;
@@ -834,10 +844,10 @@ static SRes ReadUnpackInfo(CSzAr *p,
834 } 844 }
835 if (type == k7zIdCRC) 845 if (type == k7zIdCRC)
836 { 846 {
837 RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc)); 847 RINOK(ReadBitUi32s(&sd, numFolders, &p->FolderCRCs, alloc))
838 continue; 848 continue;
839 } 849 }
840 RINOK(SkipData(&sd)); 850 RINOK(SkipData(&sd))
841 } 851 }
842} 852}
843 853
@@ -862,13 +872,13 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi)
862{ 872{
863 UInt64 type = 0; 873 UInt64 type = 0;
864 UInt32 numSubDigests = 0; 874 UInt32 numSubDigests = 0;
865 UInt32 numFolders = p->NumFolders; 875 const UInt32 numFolders = p->NumFolders;
866 UInt32 numUnpackStreams = numFolders; 876 UInt32 numUnpackStreams = numFolders;
867 UInt32 numUnpackSizesInData = 0; 877 UInt32 numUnpackSizesInData = 0;
868 878
869 for (;;) 879 for (;;)
870 { 880 {
871 RINOK(ReadID(sd, &type)); 881 RINOK(ReadID(sd, &type))
872 if (type == k7zIdNumUnpackStream) 882 if (type == k7zIdNumUnpackStream)
873 { 883 {
874 UInt32 i; 884 UInt32 i;
@@ -878,7 +888,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi)
878 for (i = 0; i < numFolders; i++) 888 for (i = 0; i < numFolders; i++)
879 { 889 {
880 UInt32 numStreams; 890 UInt32 numStreams;
881 RINOK(SzReadNumber32(sd, &numStreams)); 891 RINOK(SzReadNumber32(sd, &numStreams))
882 if (numUnpackStreams > numUnpackStreams + numStreams) 892 if (numUnpackStreams > numUnpackStreams + numStreams)
883 return SZ_ERROR_UNSUPPORTED; 893 return SZ_ERROR_UNSUPPORTED;
884 numUnpackStreams += numStreams; 894 numUnpackStreams += numStreams;
@@ -892,7 +902,7 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi)
892 } 902 }
893 if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd) 903 if (type == k7zIdCRC || type == k7zIdSize || type == k7zIdEnd)
894 break; 904 break;
895 RINOK(SkipData(sd)); 905 RINOK(SkipData(sd))
896 } 906 }
897 907
898 if (!ssi->sdNumSubStreams.Data) 908 if (!ssi->sdNumSubStreams.Data)
@@ -908,9 +918,9 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi)
908 if (type == k7zIdSize) 918 if (type == k7zIdSize)
909 { 919 {
910 ssi->sdSizes.Data = sd->Data; 920 ssi->sdSizes.Data = sd->Data;
911 RINOK(SkipNumbers(sd, numUnpackSizesInData)); 921 RINOK(SkipNumbers(sd, numUnpackSizesInData))
912 ssi->sdSizes.Size = (size_t)(sd->Data - ssi->sdSizes.Data); 922 ssi->sdSizes.Size = (size_t)(sd->Data - ssi->sdSizes.Data);
913 RINOK(ReadID(sd, &type)); 923 RINOK(ReadID(sd, &type))
914 } 924 }
915 925
916 for (;;) 926 for (;;)
@@ -920,14 +930,14 @@ static SRes ReadSubStreamsInfo(CSzAr *p, CSzData *sd, CSubStreamInfo *ssi)
920 if (type == k7zIdCRC) 930 if (type == k7zIdCRC)
921 { 931 {
922 ssi->sdCRCs.Data = sd->Data; 932 ssi->sdCRCs.Data = sd->Data;
923 RINOK(SkipBitUi32s(sd, numSubDigests)); 933 RINOK(SkipBitUi32s(sd, numSubDigests))
924 ssi->sdCRCs.Size = (size_t)(sd->Data - ssi->sdCRCs.Data); 934 ssi->sdCRCs.Size = (size_t)(sd->Data - ssi->sdCRCs.Data);
925 } 935 }
926 else 936 else
927 { 937 {
928 RINOK(SkipData(sd)); 938 RINOK(SkipData(sd))
929 } 939 }
930 RINOK(ReadID(sd, &type)); 940 RINOK(ReadID(sd, &type))
931 } 941 }
932} 942}
933 943
@@ -940,31 +950,31 @@ static SRes SzReadStreamsInfo(CSzAr *p,
940{ 950{
941 UInt64 type; 951 UInt64 type;
942 952
943 SzData_Clear(&ssi->sdSizes); 953 SzData_CLEAR(&ssi->sdSizes)
944 SzData_Clear(&ssi->sdCRCs); 954 SzData_CLEAR(&ssi->sdCRCs)
945 SzData_Clear(&ssi->sdNumSubStreams); 955 SzData_CLEAR(&ssi->sdNumSubStreams)
946 956
947 *dataOffset = 0; 957 *dataOffset = 0;
948 RINOK(ReadID(sd, &type)); 958 RINOK(ReadID(sd, &type))
949 if (type == k7zIdPackInfo) 959 if (type == k7zIdPackInfo)
950 { 960 {
951 RINOK(ReadNumber(sd, dataOffset)); 961 RINOK(ReadNumber(sd, dataOffset))
952 if (*dataOffset > p->RangeLimit) 962 if (*dataOffset > p->RangeLimit)
953 return SZ_ERROR_ARCHIVE; 963 return SZ_ERROR_ARCHIVE;
954 RINOK(ReadPackInfo(p, sd, alloc)); 964 RINOK(ReadPackInfo(p, sd, alloc))
955 if (p->PackPositions[p->NumPackStreams] > p->RangeLimit - *dataOffset) 965 if (p->PackPositions[p->NumPackStreams] > p->RangeLimit - *dataOffset)
956 return SZ_ERROR_ARCHIVE; 966 return SZ_ERROR_ARCHIVE;
957 RINOK(ReadID(sd, &type)); 967 RINOK(ReadID(sd, &type))
958 } 968 }
959 if (type == k7zIdUnpackInfo) 969 if (type == k7zIdUnpackInfo)
960 { 970 {
961 RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc)); 971 RINOK(ReadUnpackInfo(p, sd, numFoldersMax, tempBufs, numTempBufs, alloc))
962 RINOK(ReadID(sd, &type)); 972 RINOK(ReadID(sd, &type))
963 } 973 }
964 if (type == k7zIdSubStreamsInfo) 974 if (type == k7zIdSubStreamsInfo)
965 { 975 {
966 RINOK(ReadSubStreamsInfo(p, sd, ssi)); 976 RINOK(ReadSubStreamsInfo(p, sd, ssi))
967 RINOK(ReadID(sd, &type)); 977 RINOK(ReadID(sd, &type))
968 } 978 }
969 else 979 else
970 { 980 {
@@ -976,7 +986,7 @@ static SRes SzReadStreamsInfo(CSzAr *p,
976} 986}
977 987
978static SRes SzReadAndDecodePackedStreams( 988static SRes SzReadAndDecodePackedStreams(
979 ILookInStream *inStream, 989 ILookInStreamPtr inStream,
980 CSzData *sd, 990 CSzData *sd,
981 CBuf *tempBufs, 991 CBuf *tempBufs,
982 UInt32 numFoldersMax, 992 UInt32 numFoldersMax,
@@ -988,7 +998,7 @@ static SRes SzReadAndDecodePackedStreams(
988 UInt32 fo; 998 UInt32 fo;
989 CSubStreamInfo ssi; 999 CSubStreamInfo ssi;
990 1000
991 RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp)); 1001 RINOK(SzReadStreamsInfo(p, sd, numFoldersMax, NULL, 0, &dataStartPos, &ssi, allocTemp))
992 1002
993 dataStartPos += baseOffset; 1003 dataStartPos += baseOffset;
994 if (p->NumFolders == 0) 1004 if (p->NumFolders == 0)
@@ -1000,7 +1010,7 @@ static SRes SzReadAndDecodePackedStreams(
1000 for (fo = 0; fo < p->NumFolders; fo++) 1010 for (fo = 0; fo < p->NumFolders; fo++)
1001 { 1011 {
1002 CBuf *tempBuf = tempBufs + fo; 1012 CBuf *tempBuf = tempBufs + fo;
1003 UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo); 1013 const UInt64 unpackSize = SzAr_GetFolderUnpackSize(p, fo);
1004 if ((size_t)unpackSize != unpackSize) 1014 if ((size_t)unpackSize != unpackSize)
1005 return SZ_ERROR_MEM; 1015 return SZ_ERROR_MEM;
1006 if (!Buf_Create(tempBuf, (size_t)unpackSize, allocTemp)) 1016 if (!Buf_Create(tempBuf, (size_t)unpackSize, allocTemp))
@@ -1010,8 +1020,8 @@ static SRes SzReadAndDecodePackedStreams(
1010 for (fo = 0; fo < p->NumFolders; fo++) 1020 for (fo = 0; fo < p->NumFolders; fo++)
1011 { 1021 {
1012 const CBuf *tempBuf = tempBufs + fo; 1022 const CBuf *tempBuf = tempBufs + fo;
1013 RINOK(LookInStream_SeekTo(inStream, dataStartPos)); 1023 RINOK(LookInStream_SeekTo(inStream, dataStartPos))
1014 RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp)); 1024 RINOK(SzAr_DecodeFolder(p, fo, inStream, dataStartPos, tempBuf->data, tempBuf->size, allocTemp))
1015 } 1025 }
1016 1026
1017 return SZ_OK; 1027 return SZ_OK;
@@ -1046,7 +1056,7 @@ static SRes SzReadFileNames(const Byte *data, size_t size, UInt32 numFiles, size
1046 return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; 1056 return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE;
1047} 1057}
1048 1058
1049static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num, 1059static Z7_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num,
1050 CSzData *sd2, 1060 CSzData *sd2,
1051 const CBuf *tempBufs, UInt32 numTempBufs, 1061 const CBuf *tempBufs, UInt32 numTempBufs,
1052 ISzAllocPtr alloc) 1062 ISzAllocPtr alloc)
@@ -1057,22 +1067,22 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num,
1057 Byte *defs; 1067 Byte *defs;
1058 Byte external; 1068 Byte external;
1059 1069
1060 RINOK(ReadBitVector(sd2, num, &p->Defs, alloc)); 1070 RINOK(ReadBitVector(sd2, num, &p->Defs, alloc))
1061 1071
1062 SZ_READ_BYTE_SD(sd2, external); 1072 SZ_READ_BYTE_SD(sd2, external)
1063 if (external == 0) 1073 if (external == 0)
1064 sd = *sd2; 1074 sd = *sd2;
1065 else 1075 else
1066 { 1076 {
1067 UInt32 index; 1077 UInt32 index;
1068 RINOK(SzReadNumber32(sd2, &index)); 1078 RINOK(SzReadNumber32(sd2, &index))
1069 if (index >= numTempBufs) 1079 if (index >= numTempBufs)
1070 return SZ_ERROR_ARCHIVE; 1080 return SZ_ERROR_ARCHIVE;
1071 sd.Data = tempBufs[index].data; 1081 sd.Data = tempBufs[index].data;
1072 sd.Size = tempBufs[index].size; 1082 sd.Size = tempBufs[index].size;
1073 } 1083 }
1074 1084
1075 MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc); 1085 MY_ALLOC_ZE(CNtfsFileTime, p->Vals, num, alloc)
1076 vals = p->Vals; 1086 vals = p->Vals;
1077 defs = p->Defs; 1087 defs = p->Defs;
1078 for (i = 0; i < num; i++) 1088 for (i = 0; i < num; i++)
@@ -1082,7 +1092,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num,
1082 return SZ_ERROR_ARCHIVE; 1092 return SZ_ERROR_ARCHIVE;
1083 vals[i].Low = GetUi32(sd.Data); 1093 vals[i].Low = GetUi32(sd.Data);
1084 vals[i].High = GetUi32(sd.Data + 4); 1094 vals[i].High = GetUi32(sd.Data + 4);
1085 SKIP_DATA2(sd, 8); 1095 SKIP_DATA2(sd, 8)
1086 } 1096 }
1087 else 1097 else
1088 vals[i].High = vals[i].Low = 0; 1098 vals[i].High = vals[i].Low = 0;
@@ -1100,7 +1110,7 @@ static MY_NO_INLINE SRes ReadTime(CSzBitUi64s *p, UInt32 num,
1100static SRes SzReadHeader2( 1110static SRes SzReadHeader2(
1101 CSzArEx *p, /* allocMain */ 1111 CSzArEx *p, /* allocMain */
1102 CSzData *sd, 1112 CSzData *sd,
1103 ILookInStream *inStream, 1113 ILookInStreamPtr inStream,
1104 CBuf *tempBufs, UInt32 *numTempBufs, 1114 CBuf *tempBufs, UInt32 *numTempBufs,
1105 ISzAllocPtr allocMain, 1115 ISzAllocPtr allocMain,
1106 ISzAllocPtr allocTemp 1116 ISzAllocPtr allocTemp
@@ -1111,26 +1121,26 @@ static SRes SzReadHeader2(
1111{ 1121{
1112 UInt64 type; 1122 UInt64 type;
1113 1123
1114 SzData_Clear(&ssi.sdSizes); 1124 SzData_CLEAR(&ssi.sdSizes)
1115 SzData_Clear(&ssi.sdCRCs); 1125 SzData_CLEAR(&ssi.sdCRCs)
1116 SzData_Clear(&ssi.sdNumSubStreams); 1126 SzData_CLEAR(&ssi.sdNumSubStreams)
1117 1127
1118 ssi.NumSubDigests = 0; 1128 ssi.NumSubDigests = 0;
1119 ssi.NumTotalSubStreams = 0; 1129 ssi.NumTotalSubStreams = 0;
1120 1130
1121 RINOK(ReadID(sd, &type)); 1131 RINOK(ReadID(sd, &type))
1122 1132
1123 if (type == k7zIdArchiveProperties) 1133 if (type == k7zIdArchiveProperties)
1124 { 1134 {
1125 for (;;) 1135 for (;;)
1126 { 1136 {
1127 UInt64 type2; 1137 UInt64 type2;
1128 RINOK(ReadID(sd, &type2)); 1138 RINOK(ReadID(sd, &type2))
1129 if (type2 == k7zIdEnd) 1139 if (type2 == k7zIdEnd)
1130 break; 1140 break;
1131 RINOK(SkipData(sd)); 1141 RINOK(SkipData(sd))
1132 } 1142 }
1133 RINOK(ReadID(sd, &type)); 1143 RINOK(ReadID(sd, &type))
1134 } 1144 }
1135 1145
1136 if (type == k7zIdAdditionalStreamsInfo) 1146 if (type == k7zIdAdditionalStreamsInfo)
@@ -1148,15 +1158,15 @@ static SRes SzReadHeader2(
1148 1158
1149 if (res != SZ_OK) 1159 if (res != SZ_OK)
1150 return res; 1160 return res;
1151 RINOK(ReadID(sd, &type)); 1161 RINOK(ReadID(sd, &type))
1152 } 1162 }
1153 1163
1154 if (type == k7zIdMainStreamsInfo) 1164 if (type == k7zIdMainStreamsInfo)
1155 { 1165 {
1156 RINOK(SzReadStreamsInfo(&p->db, sd, (UInt32)1 << 30, tempBufs, *numTempBufs, 1166 RINOK(SzReadStreamsInfo(&p->db, sd, (UInt32)1 << 30, tempBufs, *numTempBufs,
1157 &p->dataPos, &ssi, allocMain)); 1167 &p->dataPos, &ssi, allocMain))
1158 p->dataPos += p->startPosAfterHeader; 1168 p->dataPos += p->startPosAfterHeader;
1159 RINOK(ReadID(sd, &type)); 1169 RINOK(ReadID(sd, &type))
1160 } 1170 }
1161 1171
1162 if (type == k7zIdEnd) 1172 if (type == k7zIdEnd)
@@ -1174,23 +1184,23 @@ static SRes SzReadHeader2(
1174 const Byte *emptyStreams = NULL; 1184 const Byte *emptyStreams = NULL;
1175 const Byte *emptyFiles = NULL; 1185 const Byte *emptyFiles = NULL;
1176 1186
1177 RINOK(SzReadNumber32(sd, &numFiles)); 1187 RINOK(SzReadNumber32(sd, &numFiles))
1178 p->NumFiles = numFiles; 1188 p->NumFiles = numFiles;
1179 1189
1180 for (;;) 1190 for (;;)
1181 { 1191 {
1182 UInt64 type; 1192 UInt64 type;
1183 UInt64 size; 1193 UInt64 size;
1184 RINOK(ReadID(sd, &type)); 1194 RINOK(ReadID(sd, &type))
1185 if (type == k7zIdEnd) 1195 if (type == k7zIdEnd)
1186 break; 1196 break;
1187 RINOK(ReadNumber(sd, &size)); 1197 RINOK(ReadNumber(sd, &size))
1188 if (size > sd->Size) 1198 if (size > sd->Size)
1189 return SZ_ERROR_ARCHIVE; 1199 return SZ_ERROR_ARCHIVE;
1190 1200
1191 if (type >= ((UInt32)1 << 8)) 1201 if (type >= ((UInt32)1 << 8))
1192 { 1202 {
1193 SKIP_DATA(sd, size); 1203 SKIP_DATA(sd, size)
1194 } 1204 }
1195 else switch ((unsigned)type) 1205 else switch ((unsigned)type)
1196 { 1206 {
@@ -1200,7 +1210,7 @@ static SRes SzReadHeader2(
1200 const Byte *namesData; 1210 const Byte *namesData;
1201 Byte external; 1211 Byte external;
1202 1212
1203 SZ_READ_BYTE(external); 1213 SZ_READ_BYTE(external)
1204 if (external == 0) 1214 if (external == 0)
1205 { 1215 {
1206 namesSize = (size_t)size - 1; 1216 namesSize = (size_t)size - 1;
@@ -1209,7 +1219,7 @@ static SRes SzReadHeader2(
1209 else 1219 else
1210 { 1220 {
1211 UInt32 index; 1221 UInt32 index;
1212 RINOK(SzReadNumber32(sd, &index)); 1222 RINOK(SzReadNumber32(sd, &index))
1213 if (index >= *numTempBufs) 1223 if (index >= *numTempBufs)
1214 return SZ_ERROR_ARCHIVE; 1224 return SZ_ERROR_ARCHIVE;
1215 namesData = (tempBufs)[index].data; 1225 namesData = (tempBufs)[index].data;
@@ -1218,25 +1228,25 @@ static SRes SzReadHeader2(
1218 1228
1219 if ((namesSize & 1) != 0) 1229 if ((namesSize & 1) != 0)
1220 return SZ_ERROR_ARCHIVE; 1230 return SZ_ERROR_ARCHIVE;
1221 MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain); 1231 MY_ALLOC(size_t, p->FileNameOffsets, numFiles + 1, allocMain)
1222 MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain); 1232 MY_ALLOC_ZE_AND_CPY(p->FileNames, namesSize, namesData, allocMain)
1223 RINOK(SzReadFileNames(p->FileNames, namesSize, numFiles, p->FileNameOffsets)) 1233 RINOK(SzReadFileNames(p->FileNames, namesSize, numFiles, p->FileNameOffsets))
1224 if (external == 0) 1234 if (external == 0)
1225 { 1235 {
1226 SKIP_DATA(sd, namesSize); 1236 SKIP_DATA(sd, namesSize)
1227 } 1237 }
1228 break; 1238 break;
1229 } 1239 }
1230 case k7zIdEmptyStream: 1240 case k7zIdEmptyStream:
1231 { 1241 {
1232 RINOK(RememberBitVector(sd, numFiles, &emptyStreams)); 1242 RINOK(RememberBitVector(sd, numFiles, &emptyStreams))
1233 numEmptyStreams = CountDefinedBits(emptyStreams, numFiles); 1243 numEmptyStreams = CountDefinedBits(emptyStreams, numFiles);
1234 emptyFiles = NULL; 1244 emptyFiles = NULL;
1235 break; 1245 break;
1236 } 1246 }
1237 case k7zIdEmptyFile: 1247 case k7zIdEmptyFile:
1238 { 1248 {
1239 RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles)); 1249 RINOK(RememberBitVector(sd, numEmptyStreams, &emptyFiles))
1240 break; 1250 break;
1241 } 1251 }
1242 case k7zIdWinAttrib: 1252 case k7zIdWinAttrib:
@@ -1245,22 +1255,22 @@ static SRes SzReadHeader2(
1245 CSzData sdSwitch; 1255 CSzData sdSwitch;
1246 CSzData *sdPtr; 1256 CSzData *sdPtr;
1247 SzBitUi32s_Free(&p->Attribs, allocMain); 1257 SzBitUi32s_Free(&p->Attribs, allocMain);
1248 RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain)); 1258 RINOK(ReadBitVector(sd, numFiles, &p->Attribs.Defs, allocMain))
1249 1259
1250 SZ_READ_BYTE(external); 1260 SZ_READ_BYTE(external)
1251 if (external == 0) 1261 if (external == 0)
1252 sdPtr = sd; 1262 sdPtr = sd;
1253 else 1263 else
1254 { 1264 {
1255 UInt32 index; 1265 UInt32 index;
1256 RINOK(SzReadNumber32(sd, &index)); 1266 RINOK(SzReadNumber32(sd, &index))
1257 if (index >= *numTempBufs) 1267 if (index >= *numTempBufs)
1258 return SZ_ERROR_ARCHIVE; 1268 return SZ_ERROR_ARCHIVE;
1259 sdSwitch.Data = (tempBufs)[index].data; 1269 sdSwitch.Data = (tempBufs)[index].data;
1260 sdSwitch.Size = (tempBufs)[index].size; 1270 sdSwitch.Size = (tempBufs)[index].size;
1261 sdPtr = &sdSwitch; 1271 sdPtr = &sdSwitch;
1262 } 1272 }
1263 RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain)); 1273 RINOK(ReadUi32s(sdPtr, numFiles, &p->Attribs, allocMain))
1264 break; 1274 break;
1265 } 1275 }
1266 /* 1276 /*
@@ -1273,11 +1283,11 @@ static SRes SzReadHeader2(
1273 break; 1283 break;
1274 } 1284 }
1275 */ 1285 */
1276 case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; 1286 case k7zIdMTime: RINOK(ReadTime(&p->MTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break;
1277 case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)); break; 1287 case k7zIdCTime: RINOK(ReadTime(&p->CTime, numFiles, sd, tempBufs, *numTempBufs, allocMain)) break;
1278 default: 1288 default:
1279 { 1289 {
1280 SKIP_DATA(sd, size); 1290 SKIP_DATA(sd, size)
1281 } 1291 }
1282 } 1292 }
1283 } 1293 }
@@ -1288,10 +1298,10 @@ static SRes SzReadHeader2(
1288 for (;;) 1298 for (;;)
1289 { 1299 {
1290 UInt64 type; 1300 UInt64 type;
1291 RINOK(ReadID(sd, &type)); 1301 RINOK(ReadID(sd, &type))
1292 if (type == k7zIdEnd) 1302 if (type == k7zIdEnd)
1293 break; 1303 break;
1294 RINOK(SkipData(sd)); 1304 RINOK(SkipData(sd))
1295 } 1305 }
1296 1306
1297 { 1307 {
@@ -1303,40 +1313,37 @@ static SRes SzReadHeader2(
1303 UInt64 unpackPos = 0; 1313 UInt64 unpackPos = 0;
1304 const Byte *digestsDefs = NULL; 1314 const Byte *digestsDefs = NULL;
1305 const Byte *digestsVals = NULL; 1315 const Byte *digestsVals = NULL;
1306 UInt32 digestsValsIndex = 0; 1316 UInt32 digestIndex = 0;
1307 UInt32 digestIndex;
1308 Byte allDigestsDefined = 0;
1309 Byte isDirMask = 0; 1317 Byte isDirMask = 0;
1310 Byte crcMask = 0; 1318 Byte crcMask = 0;
1311 Byte mask = 0x80; 1319 Byte mask = 0x80;
1312 1320
1313 MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain); 1321 MY_ALLOC(UInt32, p->FolderToFile, p->db.NumFolders + 1, allocMain)
1314 MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain); 1322 MY_ALLOC_ZE(UInt32, p->FileToFolder, p->NumFiles, allocMain)
1315 MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain); 1323 MY_ALLOC(UInt64, p->UnpackPositions, p->NumFiles + 1, allocMain)
1316 MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain); 1324 MY_ALLOC_ZE(Byte, p->IsDirs, (p->NumFiles + 7) >> 3, allocMain)
1317 1325
1318 RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain)); 1326 RINOK(SzBitUi32s_Alloc(&p->CRCs, p->NumFiles, allocMain))
1319 1327
1320 if (ssi.sdCRCs.Size != 0) 1328 if (ssi.sdCRCs.Size != 0)
1321 { 1329 {
1322 SZ_READ_BYTE_SD(&ssi.sdCRCs, allDigestsDefined); 1330 Byte allDigestsDefined = 0;
1331 SZ_READ_BYTE_SD_NOCHECK(&ssi.sdCRCs, allDigestsDefined)
1323 if (allDigestsDefined) 1332 if (allDigestsDefined)
1324 digestsVals = ssi.sdCRCs.Data; 1333 digestsVals = ssi.sdCRCs.Data;
1325 else 1334 else
1326 { 1335 {
1327 size_t numBytes = (ssi.NumSubDigests + 7) >> 3; 1336 const size_t numBytes = (ssi.NumSubDigests + 7) >> 3;
1328 digestsDefs = ssi.sdCRCs.Data; 1337 digestsDefs = ssi.sdCRCs.Data;
1329 digestsVals = digestsDefs + numBytes; 1338 digestsVals = digestsDefs + numBytes;
1330 } 1339 }
1331 } 1340 }
1332 1341
1333 digestIndex = 0;
1334
1335 for (i = 0; i < numFiles; i++, mask >>= 1) 1342 for (i = 0; i < numFiles; i++, mask >>= 1)
1336 { 1343 {
1337 if (mask == 0) 1344 if (mask == 0)
1338 { 1345 {
1339 UInt32 byteIndex = (i - 1) >> 3; 1346 const UInt32 byteIndex = (i - 1) >> 3;
1340 p->IsDirs[byteIndex] = isDirMask; 1347 p->IsDirs[byteIndex] = isDirMask;
1341 p->CRCs.Defs[byteIndex] = crcMask; 1348 p->CRCs.Defs[byteIndex] = crcMask;
1342 isDirMask = 0; 1349 isDirMask = 0;
@@ -1374,18 +1381,17 @@ static SRes SzReadHeader2(
1374 numSubStreams = 1; 1381 numSubStreams = 1;
1375 if (ssi.sdNumSubStreams.Data) 1382 if (ssi.sdNumSubStreams.Data)
1376 { 1383 {
1377 RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); 1384 RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams))
1378 } 1385 }
1379 remSubStreams = numSubStreams; 1386 remSubStreams = numSubStreams;
1380 if (numSubStreams != 0) 1387 if (numSubStreams != 0)
1381 break; 1388 break;
1382 { 1389 {
1383 UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); 1390 const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex);
1384 unpackPos += folderUnpackSize; 1391 unpackPos += folderUnpackSize;
1385 if (unpackPos < folderUnpackSize) 1392 if (unpackPos < folderUnpackSize)
1386 return SZ_ERROR_ARCHIVE; 1393 return SZ_ERROR_ARCHIVE;
1387 } 1394 }
1388
1389 folderIndex++; 1395 folderIndex++;
1390 } 1396 }
1391 } 1397 }
@@ -1397,47 +1403,44 @@ static SRes SzReadHeader2(
1397 1403
1398 if (--remSubStreams == 0) 1404 if (--remSubStreams == 0)
1399 { 1405 {
1400 UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex); 1406 const UInt64 folderUnpackSize = SzAr_GetFolderUnpackSize(&p->db, folderIndex);
1401 UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]]; 1407 const UInt64 startFolderUnpackPos = p->UnpackPositions[p->FolderToFile[folderIndex]];
1402 if (folderUnpackSize < unpackPos - startFolderUnpackPos) 1408 if (folderUnpackSize < unpackPos - startFolderUnpackPos)
1403 return SZ_ERROR_ARCHIVE; 1409 return SZ_ERROR_ARCHIVE;
1404 unpackPos = startFolderUnpackPos + folderUnpackSize; 1410 unpackPos = startFolderUnpackPos + folderUnpackSize;
1405 if (unpackPos < folderUnpackSize) 1411 if (unpackPos < folderUnpackSize)
1406 return SZ_ERROR_ARCHIVE; 1412 return SZ_ERROR_ARCHIVE;
1407 1413
1408 if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, i)) 1414 if (numSubStreams == 1 && SzBitWithVals_Check(&p->db.FolderCRCs, folderIndex))
1409 { 1415 {
1410 p->CRCs.Vals[i] = p->db.FolderCRCs.Vals[folderIndex]; 1416 p->CRCs.Vals[i] = p->db.FolderCRCs.Vals[folderIndex];
1411 crcMask |= mask; 1417 crcMask |= mask;
1412 } 1418 }
1413 else if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex)))
1414 {
1415 p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4);
1416 digestsValsIndex++;
1417 crcMask |= mask;
1418 }
1419
1420 folderIndex++; 1419 folderIndex++;
1421 } 1420 }
1422 else 1421 else
1423 { 1422 {
1424 UInt64 v; 1423 UInt64 v;
1425 RINOK(ReadNumber(&ssi.sdSizes, &v)); 1424 RINOK(ReadNumber(&ssi.sdSizes, &v))
1426 unpackPos += v; 1425 unpackPos += v;
1427 if (unpackPos < v) 1426 if (unpackPos < v)
1428 return SZ_ERROR_ARCHIVE; 1427 return SZ_ERROR_ARCHIVE;
1429 if (allDigestsDefined || (digestsDefs && SzBitArray_Check(digestsDefs, digestIndex))) 1428 }
1429 if ((crcMask & mask) == 0 && digestsVals)
1430 {
1431 if (!digestsDefs || SzBitArray_Check(digestsDefs, digestIndex))
1430 { 1432 {
1431 p->CRCs.Vals[i] = GetUi32(digestsVals + (size_t)digestsValsIndex * 4); 1433 p->CRCs.Vals[i] = GetUi32(digestsVals);
1432 digestsValsIndex++; 1434 digestsVals += 4;
1433 crcMask |= mask; 1435 crcMask |= mask;
1434 } 1436 }
1437 digestIndex++;
1435 } 1438 }
1436 } 1439 }
1437 1440
1438 if (mask != 0x80) 1441 if (mask != 0x80)
1439 { 1442 {
1440 UInt32 byteIndex = (i - 1) >> 3; 1443 const UInt32 byteIndex = (i - 1) >> 3;
1441 p->IsDirs[byteIndex] = isDirMask; 1444 p->IsDirs[byteIndex] = isDirMask;
1442 p->CRCs.Defs[byteIndex] = crcMask; 1445 p->CRCs.Defs[byteIndex] = crcMask;
1443 } 1446 }
@@ -1454,7 +1457,7 @@ static SRes SzReadHeader2(
1454 break; 1457 break;
1455 if (!ssi.sdNumSubStreams.Data) 1458 if (!ssi.sdNumSubStreams.Data)
1456 return SZ_ERROR_ARCHIVE; 1459 return SZ_ERROR_ARCHIVE;
1457 RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams)); 1460 RINOK(SzReadNumber32(&ssi.sdNumSubStreams, &numSubStreams))
1458 if (numSubStreams != 0) 1461 if (numSubStreams != 0)
1459 return SZ_ERROR_ARCHIVE; 1462 return SZ_ERROR_ARCHIVE;
1460 /* 1463 /*
@@ -1479,7 +1482,7 @@ static SRes SzReadHeader2(
1479static SRes SzReadHeader( 1482static SRes SzReadHeader(
1480 CSzArEx *p, 1483 CSzArEx *p,
1481 CSzData *sd, 1484 CSzData *sd,
1482 ILookInStream *inStream, 1485 ILookInStreamPtr inStream,
1483 ISzAllocPtr allocMain, 1486 ISzAllocPtr allocMain,
1484 ISzAllocPtr allocTemp) 1487 ISzAllocPtr allocTemp)
1485{ 1488{
@@ -1498,7 +1501,7 @@ static SRes SzReadHeader(
1498 for (i = 0; i < NUM_ADDITIONAL_STREAMS_MAX; i++) 1501 for (i = 0; i < NUM_ADDITIONAL_STREAMS_MAX; i++)
1499 Buf_Free(tempBufs + i, allocTemp); 1502 Buf_Free(tempBufs + i, allocTemp);
1500 1503
1501 RINOK(res); 1504 RINOK(res)
1502 1505
1503 if (sd->Size != 0) 1506 if (sd->Size != 0)
1504 return SZ_ERROR_FAIL; 1507 return SZ_ERROR_FAIL;
@@ -1508,7 +1511,7 @@ static SRes SzReadHeader(
1508 1511
1509static SRes SzArEx_Open2( 1512static SRes SzArEx_Open2(
1510 CSzArEx *p, 1513 CSzArEx *p,
1511 ILookInStream *inStream, 1514 ILookInStreamPtr inStream,
1512 ISzAllocPtr allocMain, 1515 ISzAllocPtr allocMain,
1513 ISzAllocPtr allocTemp) 1516 ISzAllocPtr allocTemp)
1514{ 1517{
@@ -1521,9 +1524,9 @@ static SRes SzArEx_Open2(
1521 SRes res; 1524 SRes res;
1522 1525
1523 startArcPos = 0; 1526 startArcPos = 0;
1524 RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR)); 1527 RINOK(ILookInStream_Seek(inStream, &startArcPos, SZ_SEEK_CUR))
1525 1528
1526 RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE)); 1529 RINOK(LookInStream_Read2(inStream, header, k7zStartHeaderSize, SZ_ERROR_NO_ARCHIVE))
1527 1530
1528 if (!TestSignatureCandidate(header)) 1531 if (!TestSignatureCandidate(header))
1529 return SZ_ERROR_NO_ARCHIVE; 1532 return SZ_ERROR_NO_ARCHIVE;
@@ -1552,14 +1555,14 @@ static SRes SzArEx_Open2(
1552 1555
1553 { 1556 {
1554 Int64 pos = 0; 1557 Int64 pos = 0;
1555 RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END)); 1558 RINOK(ILookInStream_Seek(inStream, &pos, SZ_SEEK_END))
1556 if ((UInt64)pos < (UInt64)startArcPos + nextHeaderOffset || 1559 if ((UInt64)pos < (UInt64)startArcPos + nextHeaderOffset ||
1557 (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset || 1560 (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset ||
1558 (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize) 1561 (UInt64)pos < (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset + nextHeaderSize)
1559 return SZ_ERROR_INPUT_EOF; 1562 return SZ_ERROR_INPUT_EOF;
1560 } 1563 }
1561 1564
1562 RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset)); 1565 RINOK(LookInStream_SeekTo(inStream, (UInt64)startArcPos + k7zStartHeaderSize + nextHeaderOffset))
1563 1566
1564 if (!Buf_Create(&buf, nextHeaderSizeT, allocTemp)) 1567 if (!Buf_Create(&buf, nextHeaderSizeT, allocTemp))
1565 return SZ_ERROR_MEM; 1568 return SZ_ERROR_MEM;
@@ -1634,10 +1637,10 @@ static SRes SzArEx_Open2(
1634} 1637}
1635 1638
1636 1639
1637SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, 1640SRes SzArEx_Open(CSzArEx *p, ILookInStreamPtr inStream,
1638 ISzAllocPtr allocMain, ISzAllocPtr allocTemp) 1641 ISzAllocPtr allocMain, ISzAllocPtr allocTemp)
1639{ 1642{
1640 SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp); 1643 const SRes res = SzArEx_Open2(p, inStream, allocMain, allocTemp);
1641 if (res != SZ_OK) 1644 if (res != SZ_OK)
1642 SzArEx_Free(p, allocMain); 1645 SzArEx_Free(p, allocMain);
1643 return res; 1646 return res;
@@ -1646,7 +1649,7 @@ SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream,
1646 1649
1647SRes SzArEx_Extract( 1650SRes SzArEx_Extract(
1648 const CSzArEx *p, 1651 const CSzArEx *p,
1649 ILookInStream *inStream, 1652 ILookInStreamPtr inStream,
1650 UInt32 fileIndex, 1653 UInt32 fileIndex,
1651 UInt32 *blockIndex, 1654 UInt32 *blockIndex,
1652 Byte **tempBuf, 1655 Byte **tempBuf,
@@ -1656,7 +1659,7 @@ SRes SzArEx_Extract(
1656 ISzAllocPtr allocMain, 1659 ISzAllocPtr allocMain,
1657 ISzAllocPtr allocTemp) 1660 ISzAllocPtr allocTemp)
1658{ 1661{
1659 UInt32 folderIndex = p->FileToFolder[fileIndex]; 1662 const UInt32 folderIndex = p->FileToFolder[fileIndex];
1660 SRes res = SZ_OK; 1663 SRes res = SZ_OK;
1661 1664
1662 *offset = 0; 1665 *offset = 0;
@@ -1673,13 +1676,13 @@ SRes SzArEx_Extract(
1673 1676
1674 if (*tempBuf == NULL || *blockIndex != folderIndex) 1677 if (*tempBuf == NULL || *blockIndex != folderIndex)
1675 { 1678 {
1676 UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex); 1679 const UInt64 unpackSizeSpec = SzAr_GetFolderUnpackSize(&p->db, folderIndex);
1677 /* 1680 /*
1678 UInt64 unpackSizeSpec = 1681 UInt64 unpackSizeSpec =
1679 p->UnpackPositions[p->FolderToFile[(size_t)folderIndex + 1]] - 1682 p->UnpackPositions[p->FolderToFile[(size_t)folderIndex + 1]] -
1680 p->UnpackPositions[p->FolderToFile[folderIndex]]; 1683 p->UnpackPositions[p->FolderToFile[folderIndex]];
1681 */ 1684 */
1682 size_t unpackSize = (size_t)unpackSizeSpec; 1685 const size_t unpackSize = (size_t)unpackSizeSpec;
1683 1686
1684 if (unpackSize != unpackSizeSpec) 1687 if (unpackSize != unpackSizeSpec)
1685 return SZ_ERROR_MEM; 1688 return SZ_ERROR_MEM;
@@ -1707,7 +1710,7 @@ SRes SzArEx_Extract(
1707 1710
1708 if (res == SZ_OK) 1711 if (res == SZ_OK)
1709 { 1712 {
1710 UInt64 unpackPos = p->UnpackPositions[fileIndex]; 1713 const UInt64 unpackPos = p->UnpackPositions[fileIndex];
1711 *offset = (size_t)(unpackPos - p->UnpackPositions[p->FolderToFile[folderIndex]]); 1714 *offset = (size_t)(unpackPos - p->UnpackPositions[p->FolderToFile[folderIndex]]);
1712 *outSizeProcessed = (size_t)(p->UnpackPositions[(size_t)fileIndex + 1] - unpackPos); 1715 *outSizeProcessed = (size_t)(p->UnpackPositions[(size_t)fileIndex + 1] - unpackPos);
1713 if (*offset + *outSizeProcessed > *outBufferSize) 1716 if (*offset + *outSizeProcessed > *outBufferSize)
@@ -1723,8 +1726,8 @@ SRes SzArEx_Extract(
1723 1726
1724size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest) 1727size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest)
1725{ 1728{
1726 size_t offs = p->FileNameOffsets[fileIndex]; 1729 const size_t offs = p->FileNameOffsets[fileIndex];
1727 size_t len = p->FileNameOffsets[fileIndex + 1] - offs; 1730 const size_t len = p->FileNameOffsets[fileIndex + 1] - offs;
1728 if (dest != 0) 1731 if (dest != 0)
1729 { 1732 {
1730 size_t i; 1733 size_t i;
diff --git a/C/7zBuf.h b/C/7zBuf.h
index 81d1b5b..c0ba8a7 100644
--- a/C/7zBuf.h
+++ b/C/7zBuf.h
@@ -1,8 +1,8 @@
1/* 7zBuf.h -- Byte Buffer 1/* 7zBuf.h -- Byte Buffer
22017-04-03 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_BUF_H 4#ifndef ZIP7_INC_7Z_BUF_H
5#define __7Z_BUF_H 5#define ZIP7_INC_7Z_BUF_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/7zCrc.c b/C/7zCrc.c
index f186324..c995a8b 100644
--- a/C/7zCrc.c
+++ b/C/7zCrc.c
@@ -1,5 +1,5 @@
1/* 7zCrc.c -- CRC32 init 1/* 7zCrc.c -- CRC32 calculation and init
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -13,22 +13,20 @@
13#else 13#else
14 #define CRC_NUM_TABLES 9 14 #define CRC_NUM_TABLES 9
15 15
16 #define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) 16 UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
17 17 UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table);
18 UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
19 UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table);
20#endif 18#endif
21 19
22#ifndef MY_CPU_BE 20#ifndef MY_CPU_BE
23 UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); 21 UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
24 UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); 22 UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table);
25#endif 23#endif
26 24
27typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); 25/*
28
29extern 26extern
30CRC_FUNC g_CrcUpdateT4; 27CRC_FUNC g_CrcUpdateT4;
31CRC_FUNC g_CrcUpdateT4; 28CRC_FUNC g_CrcUpdateT4;
29*/
32extern 30extern
33CRC_FUNC g_CrcUpdateT8; 31CRC_FUNC g_CrcUpdateT8;
34CRC_FUNC g_CrcUpdateT8; 32CRC_FUNC g_CrcUpdateT8;
@@ -44,20 +42,22 @@ CRC_FUNC g_CrcUpdate;
44 42
45UInt32 g_CrcTable[256 * CRC_NUM_TABLES]; 43UInt32 g_CrcTable[256 * CRC_NUM_TABLES];
46 44
47UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) 45UInt32 Z7_FASTCALL CrcUpdate(UInt32 v, const void *data, size_t size)
48{ 46{
49 return g_CrcUpdate(v, data, size, g_CrcTable); 47 return g_CrcUpdate(v, data, size, g_CrcTable);
50} 48}
51 49
52UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) 50UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size)
53{ 51{
54 return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL; 52 return g_CrcUpdate(CRC_INIT_VAL, data, size, g_CrcTable) ^ CRC_INIT_VAL;
55} 53}
56 54
55#if CRC_NUM_TABLES < 4 \
56 || (CRC_NUM_TABLES == 4 && defined(MY_CPU_BE)) \
57 || (!defined(MY_CPU_LE) && !defined(MY_CPU_BE))
57#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 58#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
58 59UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table);
59UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table); 60UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table)
60UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table)
61{ 61{
62 const Byte *p = (const Byte *)data; 62 const Byte *p = (const Byte *)data;
63 const Byte *pEnd = p + size; 63 const Byte *pEnd = p + size;
@@ -65,7 +65,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U
65 v = CRC_UPDATE_BYTE_2(v, *p); 65 v = CRC_UPDATE_BYTE_2(v, *p);
66 return v; 66 return v;
67} 67}
68 68#endif
69 69
70/* ---------- hardware CRC ---------- */ 70/* ---------- hardware CRC ---------- */
71 71
@@ -78,16 +78,29 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U
78 #if defined(_MSC_VER) 78 #if defined(_MSC_VER)
79 #if defined(MY_CPU_ARM64) 79 #if defined(MY_CPU_ARM64)
80 #if (_MSC_VER >= 1910) 80 #if (_MSC_VER >= 1910)
81 #ifndef __clang__
81 #define USE_ARM64_CRC 82 #define USE_ARM64_CRC
83 #include <intrin.h>
84 #endif
82 #endif 85 #endif
83 #endif 86 #endif
84 #elif (defined(__clang__) && (__clang_major__ >= 3)) \ 87 #elif (defined(__clang__) && (__clang_major__ >= 3)) \
85 || (defined(__GNUC__) && (__GNUC__ > 4)) 88 || (defined(__GNUC__) && (__GNUC__ > 4))
86 #if !defined(__ARM_FEATURE_CRC32) 89 #if !defined(__ARM_FEATURE_CRC32)
87 #define __ARM_FEATURE_CRC32 1 90 #define __ARM_FEATURE_CRC32 1
88 #if (!defined(__clang__) || (__clang_major__ > 3)) // fix these numbers 91 #if defined(__clang__)
92 #if defined(MY_CPU_ARM64)
93 #define ATTRIB_CRC __attribute__((__target__("crc")))
94 #else
95 #define ATTRIB_CRC __attribute__((__target__("armv8-a,crc")))
96 #endif
97 #else
98 #if defined(MY_CPU_ARM64)
99 #define ATTRIB_CRC __attribute__((__target__("+crc")))
100 #else
89 #define ATTRIB_CRC __attribute__((__target__("arch=armv8-a+crc"))) 101 #define ATTRIB_CRC __attribute__((__target__("arch=armv8-a+crc")))
90 #endif 102 #endif
103 #endif
91 #endif 104 #endif
92 #if defined(__ARM_FEATURE_CRC32) 105 #if defined(__ARM_FEATURE_CRC32)
93 #define USE_ARM64_CRC 106 #define USE_ARM64_CRC
@@ -105,7 +118,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const U
105 118
106#pragma message("ARM64 CRC emulation") 119#pragma message("ARM64 CRC emulation")
107 120
108MY_FORCE_INLINE 121Z7_FORCE_INLINE
109UInt32 __crc32b(UInt32 v, UInt32 data) 122UInt32 __crc32b(UInt32 v, UInt32 data)
110{ 123{
111 const UInt32 *table = g_CrcTable; 124 const UInt32 *table = g_CrcTable;
@@ -113,7 +126,7 @@ UInt32 __crc32b(UInt32 v, UInt32 data)
113 return v; 126 return v;
114} 127}
115 128
116MY_FORCE_INLINE 129Z7_FORCE_INLINE
117UInt32 __crc32w(UInt32 v, UInt32 data) 130UInt32 __crc32w(UInt32 v, UInt32 data)
118{ 131{
119 const UInt32 *table = g_CrcTable; 132 const UInt32 *table = g_CrcTable;
@@ -124,7 +137,7 @@ UInt32 __crc32w(UInt32 v, UInt32 data)
124 return v; 137 return v;
125} 138}
126 139
127MY_FORCE_INLINE 140Z7_FORCE_INLINE
128UInt32 __crc32d(UInt32 v, UInt64 data) 141UInt32 __crc32d(UInt32 v, UInt64 data)
129{ 142{
130 const UInt32 *table = g_CrcTable; 143 const UInt32 *table = g_CrcTable;
@@ -156,9 +169,9 @@ UInt32 __crc32d(UInt32 v, UInt64 data)
156// #pragma message("USE ARM HW CRC") 169// #pragma message("USE ARM HW CRC")
157 170
158ATTRIB_CRC 171ATTRIB_CRC
159UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table); 172UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table);
160ATTRIB_CRC 173ATTRIB_CRC
161UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table) 174UInt32 Z7_FASTCALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, const UInt32 *table)
162{ 175{
163 const Byte *p = (const Byte *)data; 176 const Byte *p = (const Byte *)data;
164 UNUSED_VAR(table); 177 UNUSED_VAR(table);
@@ -188,9 +201,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_32(UInt32 v, const void *data, size_t size, cons
188} 201}
189 202
190ATTRIB_CRC 203ATTRIB_CRC
191UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table); 204UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table);
192ATTRIB_CRC 205ATTRIB_CRC
193UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table) 206UInt32 Z7_FASTCALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, const UInt32 *table)
194{ 207{
195 const Byte *p = (const Byte *)data; 208 const Byte *p = (const Byte *)data;
196 UNUSED_VAR(table); 209 UNUSED_VAR(table);
@@ -219,6 +232,9 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons
219 return v; 232 return v;
220} 233}
221 234
235#undef T0_32_UNROLL_BYTES
236#undef T0_64_UNROLL_BYTES
237
222#endif // defined(USE_ARM64_CRC) || defined(USE_CRC_EMU) 238#endif // defined(USE_ARM64_CRC) || defined(USE_CRC_EMU)
223 239
224#endif // MY_CPU_LE 240#endif // MY_CPU_LE
@@ -226,7 +242,7 @@ UInt32 MY_FAST_CALL CrcUpdateT0_64(UInt32 v, const void *data, size_t size, cons
226 242
227 243
228 244
229void MY_FAST_CALL CrcGenerateTable() 245void Z7_FASTCALL CrcGenerateTable(void)
230{ 246{
231 UInt32 i; 247 UInt32 i;
232 for (i = 0; i < 256; i++) 248 for (i = 0; i < 256; i++)
@@ -239,64 +255,62 @@ void MY_FAST_CALL CrcGenerateTable()
239 } 255 }
240 for (i = 256; i < 256 * CRC_NUM_TABLES; i++) 256 for (i = 256; i < 256 * CRC_NUM_TABLES; i++)
241 { 257 {
242 UInt32 r = g_CrcTable[(size_t)i - 256]; 258 const UInt32 r = g_CrcTable[(size_t)i - 256];
243 g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8); 259 g_CrcTable[i] = g_CrcTable[r & 0xFF] ^ (r >> 8);
244 } 260 }
245 261
246 #if CRC_NUM_TABLES < 4 262 #if CRC_NUM_TABLES < 4
247 263 g_CrcUpdate = CrcUpdateT1;
248 g_CrcUpdate = CrcUpdateT1; 264 #elif defined(MY_CPU_LE)
249 265 // g_CrcUpdateT4 = CrcUpdateT4;
250 #else 266 #if CRC_NUM_TABLES < 8
251 267 g_CrcUpdate = CrcUpdateT4;
252 #ifdef MY_CPU_LE 268 #else // CRC_NUM_TABLES >= 8
253
254 g_CrcUpdateT4 = CrcUpdateT4;
255 g_CrcUpdate = CrcUpdateT4;
256
257 #if CRC_NUM_TABLES >= 8
258 g_CrcUpdateT8 = CrcUpdateT8; 269 g_CrcUpdateT8 = CrcUpdateT8;
259 270 /*
260 #ifdef MY_CPU_X86_OR_AMD64 271 #ifdef MY_CPU_X86_OR_AMD64
261 if (!CPU_Is_InOrder()) 272 if (!CPU_Is_InOrder())
262 #endif 273 #endif
263 g_CrcUpdate = CrcUpdateT8; 274 */
275 g_CrcUpdate = CrcUpdateT8;
264 #endif 276 #endif
265
266 #else 277 #else
267 { 278 {
268 #ifndef MY_CPU_BE 279 #ifndef MY_CPU_BE
269 UInt32 k = 0x01020304; 280 UInt32 k = 0x01020304;
270 const Byte *p = (const Byte *)&k; 281 const Byte *p = (const Byte *)&k;
271 if (p[0] == 4 && p[1] == 3) 282 if (p[0] == 4 && p[1] == 3)
272 { 283 {
273 g_CrcUpdateT4 = CrcUpdateT4; 284 #if CRC_NUM_TABLES < 8
274 g_CrcUpdate = CrcUpdateT4; 285 // g_CrcUpdateT4 = CrcUpdateT4;
275 #if CRC_NUM_TABLES >= 8 286 g_CrcUpdate = CrcUpdateT4;
276 g_CrcUpdateT8 = CrcUpdateT8; 287 #else // CRC_NUM_TABLES >= 8
277 g_CrcUpdate = CrcUpdateT8; 288 g_CrcUpdateT8 = CrcUpdateT8;
289 g_CrcUpdate = CrcUpdateT8;
278 #endif 290 #endif
279 } 291 }
280 else if (p[0] != 1 || p[1] != 2) 292 else if (p[0] != 1 || p[1] != 2)
281 g_CrcUpdate = CrcUpdateT1; 293 g_CrcUpdate = CrcUpdateT1;
282 else 294 else
283 #endif 295 #endif // MY_CPU_BE
284 { 296 {
285 for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--) 297 for (i = 256 * CRC_NUM_TABLES - 1; i >= 256; i--)
286 { 298 {
287 UInt32 x = g_CrcTable[(size_t)i - 256]; 299 const UInt32 x = g_CrcTable[(size_t)i - 256];
288 g_CrcTable[i] = CRC_UINT32_SWAP(x); 300 g_CrcTable[i] = Z7_BSWAP32(x);
289 } 301 }
290 g_CrcUpdateT4 = CrcUpdateT1_BeT4; 302 #if CRC_NUM_TABLES <= 4
291 g_CrcUpdate = CrcUpdateT1_BeT4; 303 g_CrcUpdate = CrcUpdateT1;
292 #if CRC_NUM_TABLES >= 8 304 #elif CRC_NUM_TABLES <= 8
293 g_CrcUpdateT8 = CrcUpdateT1_BeT8; 305 // g_CrcUpdateT4 = CrcUpdateT1_BeT4;
294 g_CrcUpdate = CrcUpdateT1_BeT8; 306 g_CrcUpdate = CrcUpdateT1_BeT4;
307 #else // CRC_NUM_TABLES > 8
308 g_CrcUpdateT8 = CrcUpdateT1_BeT8;
309 g_CrcUpdate = CrcUpdateT1_BeT8;
295 #endif 310 #endif
296 } 311 }
297 } 312 }
298 #endif 313 #endif // CRC_NUM_TABLES < 4
299 #endif
300 314
301 #ifdef MY_CPU_LE 315 #ifdef MY_CPU_LE
302 #ifdef USE_ARM64_CRC 316 #ifdef USE_ARM64_CRC
@@ -320,3 +334,7 @@ void MY_FAST_CALL CrcGenerateTable()
320 #endif 334 #endif
321 #endif 335 #endif
322} 336}
337
338#undef kCrcPoly
339#undef CRC64_NUM_TABLES
340#undef CRC_UPDATE_BYTE_2
diff --git a/C/7zCrc.h b/C/7zCrc.h
index 8fd5795..4afaeae 100644
--- a/C/7zCrc.h
+++ b/C/7zCrc.h
@@ -1,8 +1,8 @@
1/* 7zCrc.h -- CRC32 calculation 1/* 7zCrc.h -- CRC32 calculation
22013-01-18 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_CRC_H 4#ifndef ZIP7_INC_7Z_CRC_H
5#define __7Z_CRC_H 5#define ZIP7_INC_7Z_CRC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -11,14 +11,16 @@ EXTERN_C_BEGIN
11extern UInt32 g_CrcTable[]; 11extern UInt32 g_CrcTable[];
12 12
13/* Call CrcGenerateTable one time before other CRC functions */ 13/* Call CrcGenerateTable one time before other CRC functions */
14void MY_FAST_CALL CrcGenerateTable(void); 14void Z7_FASTCALL CrcGenerateTable(void);
15 15
16#define CRC_INIT_VAL 0xFFFFFFFF 16#define CRC_INIT_VAL 0xFFFFFFFF
17#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL) 17#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL)
18#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 18#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
19 19
20UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); 20UInt32 Z7_FASTCALL CrcUpdate(UInt32 crc, const void *data, size_t size);
21UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); 21UInt32 Z7_FASTCALL CrcCalc(const void *data, size_t size);
22
23typedef UInt32 (Z7_FASTCALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table);
22 24
23EXTERN_C_END 25EXTERN_C_END
24 26
diff --git a/C/7zCrcOpt.c b/C/7zCrcOpt.c
index 69fad9c..9c64929 100644
--- a/C/7zCrcOpt.c
+++ b/C/7zCrcOpt.c
@@ -1,5 +1,5 @@
1/* 7zCrcOpt.c -- CRC32 calculation 1/* 7zCrcOpt.c -- CRC32 calculation
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -9,8 +9,8 @@
9 9
10#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 10#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
11 11
12UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table); 12UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table);
13UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table) 13UInt32 Z7_FASTCALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table)
14{ 14{
15 const Byte *p = (const Byte *)data; 15 const Byte *p = (const Byte *)data;
16 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) 16 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
29 return v; 29 return v;
30} 30}
31 31
32UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table); 32UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table);
33UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table) 33UInt32 Z7_FASTCALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table)
34{ 34{
35 const Byte *p = (const Byte *)data; 35 const Byte *p = (const Byte *)data;
36 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 7) != 0; size--, p++) 36 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
61 61
62#ifndef MY_CPU_LE 62#ifndef MY_CPU_LE
63 63
64#define CRC_UINT32_SWAP(v) ((v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24)) 64#define CRC_UINT32_SWAP(v) Z7_BSWAP32(v)
65 65
66#define CRC_UPDATE_BYTE_2_BE(crc, b) (table[(((crc) >> 24) ^ (b))] ^ ((crc) << 8)) 66#define CRC_UPDATE_BYTE_2_BE(crc, b) (table[(((crc) >> 24) ^ (b))] ^ ((crc) << 8))
67 67
68UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table) 68UInt32 Z7_FASTCALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, const UInt32 *table)
69{ 69{
70 const Byte *p = (const Byte *)data; 70 const Byte *p = (const Byte *)data;
71 table += 0x100; 71 table += 0x100;
@@ -86,7 +86,7 @@ UInt32 MY_FAST_CALL CrcUpdateT1_BeT4(UInt32 v, const void *data, size_t size, co
86 return CRC_UINT32_SWAP(v); 86 return CRC_UINT32_SWAP(v);
87} 87}
88 88
89UInt32 MY_FAST_CALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table) 89UInt32 Z7_FASTCALL CrcUpdateT1_BeT8(UInt32 v, const void *data, size_t size, const UInt32 *table)
90{ 90{
91 const Byte *p = (const Byte *)data; 91 const Byte *p = (const Byte *)data;
92 table += 0x100; 92 table += 0x100;
diff --git a/C/7zDec.c b/C/7zDec.c
index fbfd016..96c6035 100644
--- a/C/7zDec.c
+++ b/C/7zDec.c
@@ -1,11 +1,11 @@
1/* 7zDec.c -- Decoding from 7z folder 1/* 7zDec.c -- Decoding from 7z folder
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include <string.h> 6#include <string.h>
7 7
8/* #define _7ZIP_PPMD_SUPPPORT */ 8/* #define Z7_PPMD_SUPPORT */
9 9
10#include "7z.h" 10#include "7z.h"
11#include "7zCrc.h" 11#include "7zCrc.h"
@@ -16,27 +16,49 @@
16#include "Delta.h" 16#include "Delta.h"
17#include "LzmaDec.h" 17#include "LzmaDec.h"
18#include "Lzma2Dec.h" 18#include "Lzma2Dec.h"
19#ifdef _7ZIP_PPMD_SUPPPORT 19#ifdef Z7_PPMD_SUPPORT
20#include "Ppmd7.h" 20#include "Ppmd7.h"
21#endif 21#endif
22 22
23#define k_Copy 0 23#define k_Copy 0
24#ifndef _7Z_NO_METHOD_LZMA2 24#ifndef Z7_NO_METHOD_LZMA2
25#define k_LZMA2 0x21 25#define k_LZMA2 0x21
26#endif 26#endif
27#define k_LZMA 0x30101 27#define k_LZMA 0x30101
28#define k_BCJ2 0x303011B 28#define k_BCJ2 0x303011B
29#ifndef _7Z_NO_METHODS_FILTERS 29
30#if !defined(Z7_NO_METHODS_FILTERS)
31#define Z7_USE_BRANCH_FILTER
32#endif
33
34#if !defined(Z7_NO_METHODS_FILTERS) || \
35 defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARM64)
36#define Z7_USE_FILTER_ARM64
37#ifndef Z7_USE_BRANCH_FILTER
38#define Z7_USE_BRANCH_FILTER
39#endif
40#define k_ARM64 0xa
41#endif
42
43#if !defined(Z7_NO_METHODS_FILTERS) || \
44 defined(Z7_USE_NATIVE_BRANCH_FILTER) && defined(MY_CPU_ARMT)
45#define Z7_USE_FILTER_ARMT
46#ifndef Z7_USE_BRANCH_FILTER
47#define Z7_USE_BRANCH_FILTER
48#endif
49#define k_ARMT 0x3030701
50#endif
51
52#ifndef Z7_NO_METHODS_FILTERS
30#define k_Delta 3 53#define k_Delta 3
31#define k_BCJ 0x3030103 54#define k_BCJ 0x3030103
32#define k_PPC 0x3030205 55#define k_PPC 0x3030205
33#define k_IA64 0x3030401 56#define k_IA64 0x3030401
34#define k_ARM 0x3030501 57#define k_ARM 0x3030501
35#define k_ARMT 0x3030701
36#define k_SPARC 0x3030805 58#define k_SPARC 0x3030805
37#endif 59#endif
38 60
39#ifdef _7ZIP_PPMD_SUPPPORT 61#ifdef Z7_PPMD_SUPPORT
40 62
41#define k_PPMD 0x30401 63#define k_PPMD 0x30401
42 64
@@ -49,12 +71,12 @@ typedef struct
49 UInt64 processed; 71 UInt64 processed;
50 BoolInt extra; 72 BoolInt extra;
51 SRes res; 73 SRes res;
52 const ILookInStream *inStream; 74 ILookInStreamPtr inStream;
53} CByteInToLook; 75} CByteInToLook;
54 76
55static Byte ReadByte(const IByteIn *pp) 77static Byte ReadByte(IByteInPtr pp)
56{ 78{
57 CByteInToLook *p = CONTAINER_FROM_VTBL(pp, CByteInToLook, vt); 79 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInToLook)
58 if (p->cur != p->end) 80 if (p->cur != p->end)
59 return *p->cur++; 81 return *p->cur++;
60 if (p->res == SZ_OK) 82 if (p->res == SZ_OK)
@@ -67,13 +89,13 @@ static Byte ReadByte(const IByteIn *pp)
67 p->cur = p->begin; 89 p->cur = p->begin;
68 p->end = p->begin + size; 90 p->end = p->begin + size;
69 if (size != 0) 91 if (size != 0)
70 return *p->cur++;; 92 return *p->cur++;
71 } 93 }
72 p->extra = True; 94 p->extra = True;
73 return 0; 95 return 0;
74} 96}
75 97
76static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, const ILookInStream *inStream, 98static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream,
77 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) 99 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain)
78{ 100{
79 CPpmd7 ppmd; 101 CPpmd7 ppmd;
@@ -138,14 +160,14 @@ static SRes SzDecodePpmd(const Byte *props, unsigned propsSize, UInt64 inSize, c
138#endif 160#endif
139 161
140 162
141static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, 163static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream,
142 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) 164 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain)
143{ 165{
144 CLzmaDec state; 166 CLzmaDec state;
145 SRes res = SZ_OK; 167 SRes res = SZ_OK;
146 168
147 LzmaDec_Construct(&state); 169 LzmaDec_CONSTRUCT(&state)
148 RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain)); 170 RINOK(LzmaDec_AllocateProbs(&state, props, propsSize, allocMain))
149 state.dic = outBuffer; 171 state.dic = outBuffer;
150 state.dicBufSize = outSize; 172 state.dicBufSize = outSize;
151 LzmaDec_Init(&state); 173 LzmaDec_Init(&state);
@@ -196,18 +218,18 @@ static SRes SzDecodeLzma(const Byte *props, unsigned propsSize, UInt64 inSize, I
196} 218}
197 219
198 220
199#ifndef _7Z_NO_METHOD_LZMA2 221#ifndef Z7_NO_METHOD_LZMA2
200 222
201static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStream *inStream, 223static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize, ILookInStreamPtr inStream,
202 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain) 224 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain)
203{ 225{
204 CLzma2Dec state; 226 CLzma2Dec state;
205 SRes res = SZ_OK; 227 SRes res = SZ_OK;
206 228
207 Lzma2Dec_Construct(&state); 229 Lzma2Dec_CONSTRUCT(&state)
208 if (propsSize != 1) 230 if (propsSize != 1)
209 return SZ_ERROR_DATA; 231 return SZ_ERROR_DATA;
210 RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain)); 232 RINOK(Lzma2Dec_AllocateProbs(&state, props[0], allocMain))
211 state.decoder.dic = outBuffer; 233 state.decoder.dic = outBuffer;
212 state.decoder.dicBufSize = outSize; 234 state.decoder.dicBufSize = outSize;
213 Lzma2Dec_Init(&state); 235 Lzma2Dec_Init(&state);
@@ -257,7 +279,7 @@ static SRes SzDecodeLzma2(const Byte *props, unsigned propsSize, UInt64 inSize,
257#endif 279#endif
258 280
259 281
260static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer) 282static SRes SzDecodeCopy(UInt64 inSize, ILookInStreamPtr inStream, Byte *outBuffer)
261{ 283{
262 while (inSize > 0) 284 while (inSize > 0)
263 { 285 {
@@ -265,13 +287,13 @@ static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer
265 size_t curSize = (1 << 18); 287 size_t curSize = (1 << 18);
266 if (curSize > inSize) 288 if (curSize > inSize)
267 curSize = (size_t)inSize; 289 curSize = (size_t)inSize;
268 RINOK(ILookInStream_Look(inStream, &inBuf, &curSize)); 290 RINOK(ILookInStream_Look(inStream, &inBuf, &curSize))
269 if (curSize == 0) 291 if (curSize == 0)
270 return SZ_ERROR_INPUT_EOF; 292 return SZ_ERROR_INPUT_EOF;
271 memcpy(outBuffer, inBuf, curSize); 293 memcpy(outBuffer, inBuf, curSize);
272 outBuffer += curSize; 294 outBuffer += curSize;
273 inSize -= curSize; 295 inSize -= curSize;
274 RINOK(ILookInStream_Skip(inStream, curSize)); 296 RINOK(ILookInStream_Skip(inStream, curSize))
275 } 297 }
276 return SZ_OK; 298 return SZ_OK;
277} 299}
@@ -282,12 +304,12 @@ static BoolInt IS_MAIN_METHOD(UInt32 m)
282 { 304 {
283 case k_Copy: 305 case k_Copy:
284 case k_LZMA: 306 case k_LZMA:
285 #ifndef _7Z_NO_METHOD_LZMA2 307 #ifndef Z7_NO_METHOD_LZMA2
286 case k_LZMA2: 308 case k_LZMA2:
287 #endif 309 #endif
288 #ifdef _7ZIP_PPMD_SUPPPORT 310 #ifdef Z7_PPMD_SUPPORT
289 case k_PPMD: 311 case k_PPMD:
290 #endif 312 #endif
291 return True; 313 return True;
292 } 314 }
293 return False; 315 return False;
@@ -317,7 +339,7 @@ static SRes CheckSupportedFolder(const CSzFolder *f)
317 } 339 }
318 340
319 341
320 #ifndef _7Z_NO_METHODS_FILTERS 342 #if defined(Z7_USE_BRANCH_FILTER)
321 343
322 if (f->NumCoders == 2) 344 if (f->NumCoders == 2)
323 { 345 {
@@ -333,13 +355,20 @@ static SRes CheckSupportedFolder(const CSzFolder *f)
333 return SZ_ERROR_UNSUPPORTED; 355 return SZ_ERROR_UNSUPPORTED;
334 switch ((UInt32)c->MethodID) 356 switch ((UInt32)c->MethodID)
335 { 357 {
358 #if !defined(Z7_NO_METHODS_FILTERS)
336 case k_Delta: 359 case k_Delta:
337 case k_BCJ: 360 case k_BCJ:
338 case k_PPC: 361 case k_PPC:
339 case k_IA64: 362 case k_IA64:
340 case k_SPARC: 363 case k_SPARC:
341 case k_ARM: 364 case k_ARM:
365 #endif
366 #ifdef Z7_USE_FILTER_ARM64
367 case k_ARM64:
368 #endif
369 #ifdef Z7_USE_FILTER_ARMT
342 case k_ARMT: 370 case k_ARMT:
371 #endif
343 break; 372 break;
344 default: 373 default:
345 return SZ_ERROR_UNSUPPORTED; 374 return SZ_ERROR_UNSUPPORTED;
@@ -372,15 +401,16 @@ static SRes CheckSupportedFolder(const CSzFolder *f)
372 return SZ_ERROR_UNSUPPORTED; 401 return SZ_ERROR_UNSUPPORTED;
373} 402}
374 403
375#ifndef _7Z_NO_METHODS_FILTERS 404
376#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break; 405
377#endif 406
407
378 408
379static SRes SzFolder_Decode2(const CSzFolder *folder, 409static SRes SzFolder_Decode2(const CSzFolder *folder,
380 const Byte *propsData, 410 const Byte *propsData,
381 const UInt64 *unpackSizes, 411 const UInt64 *unpackSizes,
382 const UInt64 *packPositions, 412 const UInt64 *packPositions,
383 ILookInStream *inStream, UInt64 startPos, 413 ILookInStreamPtr inStream, UInt64 startPos,
384 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain, 414 Byte *outBuffer, SizeT outSize, ISzAllocPtr allocMain,
385 Byte *tempBuf[]) 415 Byte *tempBuf[])
386{ 416{
@@ -389,7 +419,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
389 SizeT tempSize3 = 0; 419 SizeT tempSize3 = 0;
390 Byte *tempBuf3 = 0; 420 Byte *tempBuf3 = 0;
391 421
392 RINOK(CheckSupportedFolder(folder)); 422 RINOK(CheckSupportedFolder(folder))
393 423
394 for (ci = 0; ci < folder->NumCoders; ci++) 424 for (ci = 0; ci < folder->NumCoders; ci++)
395 { 425 {
@@ -404,8 +434,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
404 SizeT outSizeCur = outSize; 434 SizeT outSizeCur = outSize;
405 if (folder->NumCoders == 4) 435 if (folder->NumCoders == 4)
406 { 436 {
407 UInt32 indices[] = { 3, 2, 0 }; 437 const UInt32 indices[] = { 3, 2, 0 };
408 UInt64 unpackSize = unpackSizes[ci]; 438 const UInt64 unpackSize = unpackSizes[ci];
409 si = indices[ci]; 439 si = indices[ci];
410 if (ci < 2) 440 if (ci < 2)
411 { 441 {
@@ -431,37 +461,37 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
431 } 461 }
432 offset = packPositions[si]; 462 offset = packPositions[si];
433 inSize = packPositions[(size_t)si + 1] - offset; 463 inSize = packPositions[(size_t)si + 1] - offset;
434 RINOK(LookInStream_SeekTo(inStream, startPos + offset)); 464 RINOK(LookInStream_SeekTo(inStream, startPos + offset))
435 465
436 if (coder->MethodID == k_Copy) 466 if (coder->MethodID == k_Copy)
437 { 467 {
438 if (inSize != outSizeCur) /* check it */ 468 if (inSize != outSizeCur) /* check it */
439 return SZ_ERROR_DATA; 469 return SZ_ERROR_DATA;
440 RINOK(SzDecodeCopy(inSize, inStream, outBufCur)); 470 RINOK(SzDecodeCopy(inSize, inStream, outBufCur))
441 } 471 }
442 else if (coder->MethodID == k_LZMA) 472 else if (coder->MethodID == k_LZMA)
443 { 473 {
444 RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); 474 RINOK(SzDecodeLzma(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain))
445 } 475 }
446 #ifndef _7Z_NO_METHOD_LZMA2 476 #ifndef Z7_NO_METHOD_LZMA2
447 else if (coder->MethodID == k_LZMA2) 477 else if (coder->MethodID == k_LZMA2)
448 { 478 {
449 RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); 479 RINOK(SzDecodeLzma2(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain))
450 } 480 }
451 #endif 481 #endif
452 #ifdef _7ZIP_PPMD_SUPPPORT 482 #ifdef Z7_PPMD_SUPPORT
453 else if (coder->MethodID == k_PPMD) 483 else if (coder->MethodID == k_PPMD)
454 { 484 {
455 RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain)); 485 RINOK(SzDecodePpmd(propsData + coder->PropsOffset, coder->PropsSize, inSize, inStream, outBufCur, outSizeCur, allocMain))
456 } 486 }
457 #endif 487 #endif
458 else 488 else
459 return SZ_ERROR_UNSUPPORTED; 489 return SZ_ERROR_UNSUPPORTED;
460 } 490 }
461 else if (coder->MethodID == k_BCJ2) 491 else if (coder->MethodID == k_BCJ2)
462 { 492 {
463 UInt64 offset = packPositions[1]; 493 const UInt64 offset = packPositions[1];
464 UInt64 s3Size = packPositions[2] - offset; 494 const UInt64 s3Size = packPositions[2] - offset;
465 495
466 if (ci != 3) 496 if (ci != 3)
467 return SZ_ERROR_UNSUPPORTED; 497 return SZ_ERROR_UNSUPPORTED;
@@ -473,8 +503,8 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
473 if (!tempBuf[2] && tempSizes[2] != 0) 503 if (!tempBuf[2] && tempSizes[2] != 0)
474 return SZ_ERROR_MEM; 504 return SZ_ERROR_MEM;
475 505
476 RINOK(LookInStream_SeekTo(inStream, startPos + offset)); 506 RINOK(LookInStream_SeekTo(inStream, startPos + offset))
477 RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2])); 507 RINOK(SzDecodeCopy(s3Size, inStream, tempBuf[2]))
478 508
479 if ((tempSizes[0] & 3) != 0 || 509 if ((tempSizes[0] & 3) != 0 ||
480 (tempSizes[1] & 3) != 0 || 510 (tempSizes[1] & 3) != 0 ||
@@ -493,26 +523,22 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
493 p.destLim = outBuffer + outSize; 523 p.destLim = outBuffer + outSize;
494 524
495 Bcj2Dec_Init(&p); 525 Bcj2Dec_Init(&p);
496 RINOK(Bcj2Dec_Decode(&p)); 526 RINOK(Bcj2Dec_Decode(&p))
497 527
498 { 528 {
499 unsigned i; 529 unsigned i;
500 for (i = 0; i < 4; i++) 530 for (i = 0; i < 4; i++)
501 if (p.bufs[i] != p.lims[i]) 531 if (p.bufs[i] != p.lims[i])
502 return SZ_ERROR_DATA; 532 return SZ_ERROR_DATA;
503 533 if (p.dest != p.destLim || !Bcj2Dec_IsMaybeFinished(&p))
504 if (!Bcj2Dec_IsFinished(&p))
505 return SZ_ERROR_DATA;
506
507 if (p.dest != p.destLim
508 || p.state != BCJ2_STREAM_MAIN)
509 return SZ_ERROR_DATA; 534 return SZ_ERROR_DATA;
510 } 535 }
511 } 536 }
512 } 537 }
513 #ifndef _7Z_NO_METHODS_FILTERS 538 #if defined(Z7_USE_BRANCH_FILTER)
514 else if (ci == 1) 539 else if (ci == 1)
515 { 540 {
541 #if !defined(Z7_NO_METHODS_FILTERS)
516 if (coder->MethodID == k_Delta) 542 if (coder->MethodID == k_Delta)
517 { 543 {
518 if (coder->PropsSize != 1) 544 if (coder->PropsSize != 1)
@@ -522,31 +548,53 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
522 Delta_Init(state); 548 Delta_Init(state);
523 Delta_Decode(state, (unsigned)(propsData[coder->PropsOffset]) + 1, outBuffer, outSize); 549 Delta_Decode(state, (unsigned)(propsData[coder->PropsOffset]) + 1, outBuffer, outSize);
524 } 550 }
551 continue;
525 } 552 }
526 else 553 #endif
554
555 #ifdef Z7_USE_FILTER_ARM64
556 if (coder->MethodID == k_ARM64)
557 {
558 UInt32 pc = 0;
559 if (coder->PropsSize == 4)
560 pc = GetUi32(propsData + coder->PropsOffset);
561 else if (coder->PropsSize != 0)
562 return SZ_ERROR_UNSUPPORTED;
563 z7_BranchConv_ARM64_Dec(outBuffer, outSize, pc);
564 continue;
565 }
566 #endif
567
568 #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT)
527 { 569 {
528 if (coder->PropsSize != 0) 570 if (coder->PropsSize != 0)
529 return SZ_ERROR_UNSUPPORTED; 571 return SZ_ERROR_UNSUPPORTED;
572 #define CASE_BRA_CONV(isa) case k_ ## isa: Z7_BRANCH_CONV_DEC(isa)(outBuffer, outSize, 0); break; // pc = 0;
530 switch (coder->MethodID) 573 switch (coder->MethodID)
531 { 574 {
575 #if !defined(Z7_NO_METHODS_FILTERS)
532 case k_BCJ: 576 case k_BCJ:
533 { 577 {
534 UInt32 state; 578 UInt32 state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL;
535 x86_Convert_Init(state); 579 z7_BranchConvSt_X86_Dec(outBuffer, outSize, 0, &state); // pc = 0
536 x86_Convert(outBuffer, outSize, 0, &state, 0);
537 break; 580 break;
538 } 581 }
539 CASE_BRA_CONV(PPC) 582 CASE_BRA_CONV(PPC)
540 CASE_BRA_CONV(IA64) 583 CASE_BRA_CONV(IA64)
541 CASE_BRA_CONV(SPARC) 584 CASE_BRA_CONV(SPARC)
542 CASE_BRA_CONV(ARM) 585 CASE_BRA_CONV(ARM)
586 #endif
587 #if !defined(Z7_NO_METHODS_FILTERS) || defined(Z7_USE_FILTER_ARMT)
543 CASE_BRA_CONV(ARMT) 588 CASE_BRA_CONV(ARMT)
589 #endif
544 default: 590 default:
545 return SZ_ERROR_UNSUPPORTED; 591 return SZ_ERROR_UNSUPPORTED;
546 } 592 }
593 continue;
547 } 594 }
548 } 595 #endif
549 #endif 596 } // (c == 1)
597 #endif
550 else 598 else
551 return SZ_ERROR_UNSUPPORTED; 599 return SZ_ERROR_UNSUPPORTED;
552 } 600 }
@@ -556,7 +604,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder,
556 604
557 605
558SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex, 606SRes SzAr_DecodeFolder(const CSzAr *p, UInt32 folderIndex,
559 ILookInStream *inStream, UInt64 startPos, 607 ILookInStreamPtr inStream, UInt64 startPos,
560 Byte *outBuffer, size_t outSize, 608 Byte *outBuffer, size_t outSize,
561 ISzAllocPtr allocMain) 609 ISzAllocPtr allocMain)
562{ 610{
diff --git a/C/7zFile.c b/C/7zFile.c
index 13d2efa..ba5daa1 100644
--- a/C/7zFile.c
+++ b/C/7zFile.c
@@ -1,5 +1,5 @@
1/* 7zFile.c -- File IO 1/* 7zFile.c -- File IO
22021-04-29 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -268,7 +268,7 @@ WRes File_Write(CSzFile *p, const void *data, size_t *size)
268 return errno; 268 return errno;
269 if (processed == 0) 269 if (processed == 0)
270 break; 270 break;
271 data = (void *)((Byte *)data + (size_t)processed); 271 data = (const void *)((const Byte *)data + (size_t)processed);
272 originalSize -= (size_t)processed; 272 originalSize -= (size_t)processed;
273 *size += (size_t)processed; 273 *size += (size_t)processed;
274 } 274 }
@@ -287,7 +287,8 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin)
287 DWORD moveMethod; 287 DWORD moveMethod;
288 UInt32 low = (UInt32)*pos; 288 UInt32 low = (UInt32)*pos;
289 LONG high = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */ 289 LONG high = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */
290 switch (origin) 290 // (int) to eliminate clang warning
291 switch ((int)origin)
291 { 292 {
292 case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break; 293 case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break;
293 case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break; 294 case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break;
@@ -308,7 +309,7 @@ WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin)
308 309
309 int moveMethod; // = origin; 310 int moveMethod; // = origin;
310 311
311 switch (origin) 312 switch ((int)origin)
312 { 313 {
313 case SZ_SEEK_SET: moveMethod = SEEK_SET; break; 314 case SZ_SEEK_SET: moveMethod = SEEK_SET; break;
314 case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break; 315 case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break;
@@ -387,10 +388,10 @@ WRes File_GetLength(CSzFile *p, UInt64 *length)
387 388
388/* ---------- FileSeqInStream ---------- */ 389/* ---------- FileSeqInStream ---------- */
389 390
390static SRes FileSeqInStream_Read(const ISeqInStream *pp, void *buf, size_t *size) 391static SRes FileSeqInStream_Read(ISeqInStreamPtr pp, void *buf, size_t *size)
391{ 392{
392 CFileSeqInStream *p = CONTAINER_FROM_VTBL(pp, CFileSeqInStream, vt); 393 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileSeqInStream)
393 WRes wres = File_Read(&p->file, buf, size); 394 const WRes wres = File_Read(&p->file, buf, size);
394 p->wres = wres; 395 p->wres = wres;
395 return (wres == 0) ? SZ_OK : SZ_ERROR_READ; 396 return (wres == 0) ? SZ_OK : SZ_ERROR_READ;
396} 397}
@@ -403,18 +404,18 @@ void FileSeqInStream_CreateVTable(CFileSeqInStream *p)
403 404
404/* ---------- FileInStream ---------- */ 405/* ---------- FileInStream ---------- */
405 406
406static SRes FileInStream_Read(const ISeekInStream *pp, void *buf, size_t *size) 407static SRes FileInStream_Read(ISeekInStreamPtr pp, void *buf, size_t *size)
407{ 408{
408 CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); 409 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream)
409 WRes wres = File_Read(&p->file, buf, size); 410 const WRes wres = File_Read(&p->file, buf, size);
410 p->wres = wres; 411 p->wres = wres;
411 return (wres == 0) ? SZ_OK : SZ_ERROR_READ; 412 return (wres == 0) ? SZ_OK : SZ_ERROR_READ;
412} 413}
413 414
414static SRes FileInStream_Seek(const ISeekInStream *pp, Int64 *pos, ESzSeek origin) 415static SRes FileInStream_Seek(ISeekInStreamPtr pp, Int64 *pos, ESzSeek origin)
415{ 416{
416 CFileInStream *p = CONTAINER_FROM_VTBL(pp, CFileInStream, vt); 417 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileInStream)
417 WRes wres = File_Seek(&p->file, pos, origin); 418 const WRes wres = File_Seek(&p->file, pos, origin);
418 p->wres = wres; 419 p->wres = wres;
419 return (wres == 0) ? SZ_OK : SZ_ERROR_READ; 420 return (wres == 0) ? SZ_OK : SZ_ERROR_READ;
420} 421}
@@ -428,10 +429,10 @@ void FileInStream_CreateVTable(CFileInStream *p)
428 429
429/* ---------- FileOutStream ---------- */ 430/* ---------- FileOutStream ---------- */
430 431
431static size_t FileOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) 432static size_t FileOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size)
432{ 433{
433 CFileOutStream *p = CONTAINER_FROM_VTBL(pp, CFileOutStream, vt); 434 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CFileOutStream)
434 WRes wres = File_Write(&p->file, data, &size); 435 const WRes wres = File_Write(&p->file, data, &size);
435 p->wres = wres; 436 p->wres = wres;
436 return size; 437 return size;
437} 438}
diff --git a/C/7zFile.h b/C/7zFile.h
index 788abb6..f5069cd 100644
--- a/C/7zFile.h
+++ b/C/7zFile.h
@@ -1,8 +1,8 @@
1/* 7zFile.h -- File IO 1/* 7zFile.h -- File IO
22021-02-15 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_FILE_H 4#ifndef ZIP7_INC_FILE_H
5#define __7Z_FILE_H 5#define ZIP7_INC_FILE_H
6 6
7#ifdef _WIN32 7#ifdef _WIN32
8#define USE_WINDOWS_FILE 8#define USE_WINDOWS_FILE
@@ -10,7 +10,8 @@
10#endif 10#endif
11 11
12#ifdef USE_WINDOWS_FILE 12#ifdef USE_WINDOWS_FILE
13#include <windows.h> 13#include "7zWindows.h"
14
14#else 15#else
15// note: USE_FOPEN mode is limited to 32-bit file size 16// note: USE_FOPEN mode is limited to 32-bit file size
16// #define USE_FOPEN 17// #define USE_FOPEN
diff --git a/C/7zStream.c b/C/7zStream.c
index 28a1460..74e75b6 100644
--- a/C/7zStream.c
+++ b/C/7zStream.c
@@ -1,5 +1,5 @@
1/* 7zStream.c -- 7z Stream functions 1/* 7zStream.c -- 7z Stream functions
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -7,12 +7,33 @@
7 7
8#include "7zTypes.h" 8#include "7zTypes.h"
9 9
10SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType) 10
11SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize)
12{
13 size_t size = *processedSize;
14 *processedSize = 0;
15 while (size != 0)
16 {
17 size_t cur = size;
18 const SRes res = ISeqInStream_Read(stream, buf, &cur);
19 *processedSize += cur;
20 buf = (void *)((Byte *)buf + cur);
21 size -= cur;
22 if (res != SZ_OK)
23 return res;
24 if (cur == 0)
25 return SZ_OK;
26 }
27 return SZ_OK;
28}
29
30/*
31SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType)
11{ 32{
12 while (size != 0) 33 while (size != 0)
13 { 34 {
14 size_t processed = size; 35 size_t processed = size;
15 RINOK(ISeqInStream_Read(stream, buf, &processed)); 36 RINOK(ISeqInStream_Read(stream, buf, &processed))
16 if (processed == 0) 37 if (processed == 0)
17 return errorType; 38 return errorType;
18 buf = (void *)((Byte *)buf + processed); 39 buf = (void *)((Byte *)buf + processed);
@@ -21,42 +42,44 @@ SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes
21 return SZ_OK; 42 return SZ_OK;
22} 43}
23 44
24SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size) 45SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size)
25{ 46{
26 return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); 47 return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
27} 48}
49*/
50
28 51
29SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf) 52SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf)
30{ 53{
31 size_t processed = 1; 54 size_t processed = 1;
32 RINOK(ISeqInStream_Read(stream, buf, &processed)); 55 RINOK(ISeqInStream_Read(stream, buf, &processed))
33 return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF; 56 return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF;
34} 57}
35 58
36 59
37 60
38SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset) 61SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset)
39{ 62{
40 Int64 t = (Int64)offset; 63 Int64 t = (Int64)offset;
41 return ILookInStream_Seek(stream, &t, SZ_SEEK_SET); 64 return ILookInStream_Seek(stream, &t, SZ_SEEK_SET);
42} 65}
43 66
44SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size) 67SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size)
45{ 68{
46 const void *lookBuf; 69 const void *lookBuf;
47 if (*size == 0) 70 if (*size == 0)
48 return SZ_OK; 71 return SZ_OK;
49 RINOK(ILookInStream_Look(stream, &lookBuf, size)); 72 RINOK(ILookInStream_Look(stream, &lookBuf, size))
50 memcpy(buf, lookBuf, *size); 73 memcpy(buf, lookBuf, *size);
51 return ILookInStream_Skip(stream, *size); 74 return ILookInStream_Skip(stream, *size);
52} 75}
53 76
54SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType) 77SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType)
55{ 78{
56 while (size != 0) 79 while (size != 0)
57 { 80 {
58 size_t processed = size; 81 size_t processed = size;
59 RINOK(ILookInStream_Read(stream, buf, &processed)); 82 RINOK(ILookInStream_Read(stream, buf, &processed))
60 if (processed == 0) 83 if (processed == 0)
61 return errorType; 84 return errorType;
62 buf = (void *)((Byte *)buf + processed); 85 buf = (void *)((Byte *)buf + processed);
@@ -65,16 +88,16 @@ SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRe
65 return SZ_OK; 88 return SZ_OK;
66} 89}
67 90
68SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size) 91SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size)
69{ 92{
70 return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF); 93 return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
71} 94}
72 95
73 96
74 97
75#define GET_LookToRead2 CLookToRead2 *p = CONTAINER_FROM_VTBL(pp, CLookToRead2, vt); 98#define GET_LookToRead2 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLookToRead2)
76 99
77static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf, size_t *size) 100static SRes LookToRead2_Look_Lookahead(ILookInStreamPtr pp, const void **buf, size_t *size)
78{ 101{
79 SRes res = SZ_OK; 102 SRes res = SZ_OK;
80 GET_LookToRead2 103 GET_LookToRead2
@@ -93,7 +116,7 @@ static SRes LookToRead2_Look_Lookahead(const ILookInStream *pp, const void **buf
93 return res; 116 return res;
94} 117}
95 118
96static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, size_t *size) 119static SRes LookToRead2_Look_Exact(ILookInStreamPtr pp, const void **buf, size_t *size)
97{ 120{
98 SRes res = SZ_OK; 121 SRes res = SZ_OK;
99 GET_LookToRead2 122 GET_LookToRead2
@@ -113,14 +136,14 @@ static SRes LookToRead2_Look_Exact(const ILookInStream *pp, const void **buf, si
113 return res; 136 return res;
114} 137}
115 138
116static SRes LookToRead2_Skip(const ILookInStream *pp, size_t offset) 139static SRes LookToRead2_Skip(ILookInStreamPtr pp, size_t offset)
117{ 140{
118 GET_LookToRead2 141 GET_LookToRead2
119 p->pos += offset; 142 p->pos += offset;
120 return SZ_OK; 143 return SZ_OK;
121} 144}
122 145
123static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size) 146static SRes LookToRead2_Read(ILookInStreamPtr pp, void *buf, size_t *size)
124{ 147{
125 GET_LookToRead2 148 GET_LookToRead2
126 size_t rem = p->size - p->pos; 149 size_t rem = p->size - p->pos;
@@ -134,7 +157,7 @@ static SRes LookToRead2_Read(const ILookInStream *pp, void *buf, size_t *size)
134 return SZ_OK; 157 return SZ_OK;
135} 158}
136 159
137static SRes LookToRead2_Seek(const ILookInStream *pp, Int64 *pos, ESzSeek origin) 160static SRes LookToRead2_Seek(ILookInStreamPtr pp, Int64 *pos, ESzSeek origin)
138{ 161{
139 GET_LookToRead2 162 GET_LookToRead2
140 p->pos = p->size = 0; 163 p->pos = p->size = 0;
@@ -153,9 +176,9 @@ void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead)
153 176
154 177
155 178
156static SRes SecToLook_Read(const ISeqInStream *pp, void *buf, size_t *size) 179static SRes SecToLook_Read(ISeqInStreamPtr pp, void *buf, size_t *size)
157{ 180{
158 CSecToLook *p = CONTAINER_FROM_VTBL(pp, CSecToLook, vt); 181 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToLook)
159 return LookInStream_LookRead(p->realStream, buf, size); 182 return LookInStream_LookRead(p->realStream, buf, size);
160} 183}
161 184
@@ -164,9 +187,9 @@ void SecToLook_CreateVTable(CSecToLook *p)
164 p->vt.Read = SecToLook_Read; 187 p->vt.Read = SecToLook_Read;
165} 188}
166 189
167static SRes SecToRead_Read(const ISeqInStream *pp, void *buf, size_t *size) 190static SRes SecToRead_Read(ISeqInStreamPtr pp, void *buf, size_t *size)
168{ 191{
169 CSecToRead *p = CONTAINER_FROM_VTBL(pp, CSecToRead, vt); 192 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSecToRead)
170 return ILookInStream_Read(p->realStream, buf, size); 193 return ILookInStream_Read(p->realStream, buf, size);
171} 194}
172 195
diff --git a/C/7zTypes.h b/C/7zTypes.h
index f7d7071..1fcb247 100644
--- a/C/7zTypes.h
+++ b/C/7zTypes.h
@@ -1,8 +1,8 @@
1/* 7zTypes.h -- Basic types 1/* 7zTypes.h -- Basic types
22022-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_TYPES_H 4#ifndef ZIP7_7Z_TYPES_H
5#define __7Z_TYPES_H 5#define ZIP7_7Z_TYPES_H
6 6
7#ifdef _WIN32 7#ifdef _WIN32
8/* #include <windows.h> */ 8/* #include <windows.h> */
@@ -52,6 +52,11 @@ typedef int SRes;
52 #define MY_ALIGN(n) 52 #define MY_ALIGN(n)
53 #endif 53 #endif
54#else 54#else
55 /*
56 // C11/C++11:
57 #include <stdalign.h>
58 #define MY_ALIGN(n) alignas(n)
59 */
55 #define MY_ALIGN(n) __attribute__ ((aligned(n))) 60 #define MY_ALIGN(n) __attribute__ ((aligned(n)))
56#endif 61#endif
57 62
@@ -62,7 +67,7 @@ typedef int SRes;
62typedef unsigned WRes; 67typedef unsigned WRes;
63#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) 68#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x)
64 69
65// #define MY_HRES_ERROR__INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR) 70// #define MY_HRES_ERROR_INTERNAL_ERROR MY_SRes_HRESULT_FROM_WRes(ERROR_INTERNAL_ERROR)
66 71
67#else // _WIN32 72#else // _WIN32
68 73
@@ -70,13 +75,13 @@ typedef unsigned WRes;
70typedef int WRes; 75typedef int WRes;
71 76
72// (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT 77// (FACILITY_ERRNO = 0x800) is 7zip's FACILITY constant to represent (errno) errors in HRESULT
73#define MY__FACILITY_ERRNO 0x800 78#define MY_FACILITY_ERRNO 0x800
74#define MY__FACILITY_WIN32 7 79#define MY_FACILITY_WIN32 7
75#define MY__FACILITY__WRes MY__FACILITY_ERRNO 80#define MY_FACILITY_WRes MY_FACILITY_ERRNO
76 81
77#define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \ 82#define MY_HRESULT_FROM_errno_CONST_ERROR(x) ((HRESULT)( \
78 ( (HRESULT)(x) & 0x0000FFFF) \ 83 ( (HRESULT)(x) & 0x0000FFFF) \
79 | (MY__FACILITY__WRes << 16) \ 84 | (MY_FACILITY_WRes << 16) \
80 | (HRESULT)0x80000000 )) 85 | (HRESULT)0x80000000 ))
81 86
82#define MY_SRes_HRESULT_FROM_WRes(x) \ 87#define MY_SRes_HRESULT_FROM_WRes(x) \
@@ -120,17 +125,17 @@ typedef int WRes;
120#define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L) 125#define ERROR_INVALID_REPARSE_DATA ((HRESULT)0x80071128L)
121#define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L) 126#define ERROR_REPARSE_TAG_INVALID ((HRESULT)0x80071129L)
122 127
123// if (MY__FACILITY__WRes != FACILITY_WIN32), 128// if (MY_FACILITY_WRes != FACILITY_WIN32),
124// we use FACILITY_WIN32 for COM errors: 129// we use FACILITY_WIN32 for COM errors:
125#define E_OUTOFMEMORY ((HRESULT)0x8007000EL) 130#define E_OUTOFMEMORY ((HRESULT)0x8007000EL)
126#define E_INVALIDARG ((HRESULT)0x80070057L) 131#define E_INVALIDARG ((HRESULT)0x80070057L)
127#define MY__E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L) 132#define MY_E_ERROR_NEGATIVE_SEEK ((HRESULT)0x80070083L)
128 133
129/* 134/*
130// we can use FACILITY_ERRNO for some COM errors, that have errno equivalents: 135// we can use FACILITY_ERRNO for some COM errors, that have errno equivalents:
131#define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM) 136#define E_OUTOFMEMORY MY_HRESULT_FROM_errno_CONST_ERROR(ENOMEM)
132#define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) 137#define E_INVALIDARG MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL)
133#define MY__E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL) 138#define MY_E_ERROR_NEGATIVE_SEEK MY_HRESULT_FROM_errno_CONST_ERROR(EINVAL)
134*/ 139*/
135 140
136#define TEXT(quote) quote 141#define TEXT(quote) quote
@@ -156,18 +161,18 @@ typedef int WRes;
156 161
157 162
158#ifndef RINOK 163#ifndef RINOK
159#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } 164#define RINOK(x) { const int _result_ = (x); if (_result_ != 0) return _result_; }
160#endif 165#endif
161 166
162#ifndef RINOK_WRes 167#ifndef RINOK_WRes
163#define RINOK_WRes(x) { WRes __result__ = (x); if (__result__ != 0) return __result__; } 168#define RINOK_WRes(x) { const WRes _result_ = (x); if (_result_ != 0) return _result_; }
164#endif 169#endif
165 170
166typedef unsigned char Byte; 171typedef unsigned char Byte;
167typedef short Int16; 172typedef short Int16;
168typedef unsigned short UInt16; 173typedef unsigned short UInt16;
169 174
170#ifdef _LZMA_UINT32_IS_ULONG 175#ifdef Z7_DECL_Int32_AS_long
171typedef long Int32; 176typedef long Int32;
172typedef unsigned long UInt32; 177typedef unsigned long UInt32;
173#else 178#else
@@ -206,37 +211,51 @@ typedef size_t SIZE_T;
206#endif // _WIN32 211#endif // _WIN32
207 212
208 213
209#define MY_HRES_ERROR__INTERNAL_ERROR ((HRESULT)0x8007054FL) 214#define MY_HRES_ERROR_INTERNAL_ERROR ((HRESULT)0x8007054FL)
210 215
211 216
212#ifdef _SZ_NO_INT_64 217#ifdef Z7_DECL_Int64_AS_long
213
214/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
215 NOTES: Some code will work incorrectly in that case! */
216 218
217typedef long Int64; 219typedef long Int64;
218typedef unsigned long UInt64; 220typedef unsigned long UInt64;
219 221
220#else 222#else
221 223
222#if defined(_MSC_VER) || defined(__BORLANDC__) 224#if (defined(_MSC_VER) || defined(__BORLANDC__)) && !defined(__clang__)
223typedef __int64 Int64; 225typedef __int64 Int64;
224typedef unsigned __int64 UInt64; 226typedef unsigned __int64 UInt64;
225#define UINT64_CONST(n) n 227#else
228#if defined(__clang__) || defined(__GNUC__)
229#include <stdint.h>
230typedef int64_t Int64;
231typedef uint64_t UInt64;
226#else 232#else
227typedef long long int Int64; 233typedef long long int Int64;
228typedef unsigned long long int UInt64; 234typedef unsigned long long int UInt64;
229#define UINT64_CONST(n) n ## ULL 235// #define UINT64_CONST(n) n ## ULL
236#endif
230#endif 237#endif
231 238
232#endif 239#endif
233 240
234#ifdef _LZMA_NO_SYSTEM_SIZE_T 241#define UINT64_CONST(n) n
235typedef UInt32 SizeT; 242
243
244#ifdef Z7_DECL_SizeT_AS_unsigned_int
245typedef unsigned int SizeT;
236#else 246#else
237typedef size_t SizeT; 247typedef size_t SizeT;
238#endif 248#endif
239 249
250/*
251#if (defined(_MSC_VER) && _MSC_VER <= 1200)
252typedef size_t MY_uintptr_t;
253#else
254#include <stdint.h>
255typedef uintptr_t MY_uintptr_t;
256#endif
257*/
258
240typedef int BoolInt; 259typedef int BoolInt;
241/* typedef BoolInt Bool; */ 260/* typedef BoolInt Bool; */
242#define True 1 261#define True 1
@@ -244,23 +263,23 @@ typedef int BoolInt;
244 263
245 264
246#ifdef _WIN32 265#ifdef _WIN32
247#define MY_STD_CALL __stdcall 266#define Z7_STDCALL __stdcall
248#else 267#else
249#define MY_STD_CALL 268#define Z7_STDCALL
250#endif 269#endif
251 270
252#ifdef _MSC_VER 271#ifdef _MSC_VER
253 272
254#if _MSC_VER >= 1300 273#if _MSC_VER >= 1300
255#define MY_NO_INLINE __declspec(noinline) 274#define Z7_NO_INLINE __declspec(noinline)
256#else 275#else
257#define MY_NO_INLINE 276#define Z7_NO_INLINE
258#endif 277#endif
259 278
260#define MY_FORCE_INLINE __forceinline 279#define Z7_FORCE_INLINE __forceinline
261 280
262#define MY_CDECL __cdecl 281#define Z7_CDECL __cdecl
263#define MY_FAST_CALL __fastcall 282#define Z7_FASTCALL __fastcall
264 283
265#else // _MSC_VER 284#else // _MSC_VER
266 285
@@ -268,27 +287,25 @@ typedef int BoolInt;
268 || (defined(__clang__) && (__clang_major__ >= 4)) \ 287 || (defined(__clang__) && (__clang_major__ >= 4)) \
269 || defined(__INTEL_COMPILER) \ 288 || defined(__INTEL_COMPILER) \
270 || defined(__xlC__) 289 || defined(__xlC__)
271#define MY_NO_INLINE __attribute__((noinline)) 290#define Z7_NO_INLINE __attribute__((noinline))
272// #define MY_FORCE_INLINE __attribute__((always_inline)) inline 291#define Z7_FORCE_INLINE __attribute__((always_inline)) inline
273#else 292#else
274#define MY_NO_INLINE 293#define Z7_NO_INLINE
294#define Z7_FORCE_INLINE
275#endif 295#endif
276 296
277#define MY_FORCE_INLINE 297#define Z7_CDECL
278
279
280#define MY_CDECL
281 298
282#if defined(_M_IX86) \ 299#if defined(_M_IX86) \
283 || defined(__i386__) 300 || defined(__i386__)
284// #define MY_FAST_CALL __attribute__((fastcall)) 301// #define Z7_FASTCALL __attribute__((fastcall))
285// #define MY_FAST_CALL __attribute__((cdecl)) 302// #define Z7_FASTCALL __attribute__((cdecl))
286#define MY_FAST_CALL 303#define Z7_FASTCALL
287#elif defined(MY_CPU_AMD64) 304#elif defined(MY_CPU_AMD64)
288// #define MY_FAST_CALL __attribute__((ms_abi)) 305// #define Z7_FASTCALL __attribute__((ms_abi))
289#define MY_FAST_CALL 306#define Z7_FASTCALL
290#else 307#else
291#define MY_FAST_CALL 308#define Z7_FASTCALL
292#endif 309#endif
293 310
294#endif // _MSC_VER 311#endif // _MSC_VER
@@ -296,41 +313,49 @@ typedef int BoolInt;
296 313
297/* The following interfaces use first parameter as pointer to structure */ 314/* The following interfaces use first parameter as pointer to structure */
298 315
299typedef struct IByteIn IByteIn; 316// #define Z7_C_IFACE_CONST_QUAL
300struct IByteIn 317#define Z7_C_IFACE_CONST_QUAL const
318
319#define Z7_C_IFACE_DECL(a) \
320 struct a ## _; \
321 typedef Z7_C_IFACE_CONST_QUAL struct a ## _ * a ## Ptr; \
322 typedef struct a ## _ a; \
323 struct a ## _
324
325
326Z7_C_IFACE_DECL (IByteIn)
301{ 327{
302 Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */ 328 Byte (*Read)(IByteInPtr p); /* reads one byte, returns 0 in case of EOF or error */
303}; 329};
304#define IByteIn_Read(p) (p)->Read(p) 330#define IByteIn_Read(p) (p)->Read(p)
305 331
306 332
307typedef struct IByteOut IByteOut; 333Z7_C_IFACE_DECL (IByteOut)
308struct IByteOut
309{ 334{
310 void (*Write)(const IByteOut *p, Byte b); 335 void (*Write)(IByteOutPtr p, Byte b);
311}; 336};
312#define IByteOut_Write(p, b) (p)->Write(p, b) 337#define IByteOut_Write(p, b) (p)->Write(p, b)
313 338
314 339
315typedef struct ISeqInStream ISeqInStream; 340Z7_C_IFACE_DECL (ISeqInStream)
316struct ISeqInStream
317{ 341{
318 SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size); 342 SRes (*Read)(ISeqInStreamPtr p, void *buf, size_t *size);
319 /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. 343 /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
320 (output(*size) < input(*size)) is allowed */ 344 (output(*size) < input(*size)) is allowed */
321}; 345};
322#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) 346#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size)
323 347
348/* try to read as much as avail in stream and limited by (*processedSize) */
349SRes SeqInStream_ReadMax(ISeqInStreamPtr stream, void *buf, size_t *processedSize);
324/* it can return SZ_ERROR_INPUT_EOF */ 350/* it can return SZ_ERROR_INPUT_EOF */
325SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size); 351// SRes SeqInStream_Read(ISeqInStreamPtr stream, void *buf, size_t size);
326SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType); 352// SRes SeqInStream_Read2(ISeqInStreamPtr stream, void *buf, size_t size, SRes errorType);
327SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf); 353SRes SeqInStream_ReadByte(ISeqInStreamPtr stream, Byte *buf);
328 354
329 355
330typedef struct ISeqOutStream ISeqOutStream; 356Z7_C_IFACE_DECL (ISeqOutStream)
331struct ISeqOutStream
332{ 357{
333 size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size); 358 size_t (*Write)(ISeqOutStreamPtr p, const void *buf, size_t size);
334 /* Returns: result - the number of actually written bytes. 359 /* Returns: result - the number of actually written bytes.
335 (result < size) means error */ 360 (result < size) means error */
336}; 361};
@@ -344,29 +369,26 @@ typedef enum
344} ESzSeek; 369} ESzSeek;
345 370
346 371
347typedef struct ISeekInStream ISeekInStream; 372Z7_C_IFACE_DECL (ISeekInStream)
348struct ISeekInStream
349{ 373{
350 SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ 374 SRes (*Read)(ISeekInStreamPtr p, void *buf, size_t *size); /* same as ISeqInStream::Read */
351 SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin); 375 SRes (*Seek)(ISeekInStreamPtr p, Int64 *pos, ESzSeek origin);
352}; 376};
353#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) 377#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size)
354#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) 378#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin)
355 379
356 380
357typedef struct ILookInStream ILookInStream; 381Z7_C_IFACE_DECL (ILookInStream)
358struct ILookInStream
359{ 382{
360 SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size); 383 SRes (*Look)(ILookInStreamPtr p, const void **buf, size_t *size);
361 /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. 384 /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
362 (output(*size) > input(*size)) is not allowed 385 (output(*size) > input(*size)) is not allowed
363 (output(*size) < input(*size)) is allowed */ 386 (output(*size) < input(*size)) is allowed */
364 SRes (*Skip)(const ILookInStream *p, size_t offset); 387 SRes (*Skip)(ILookInStreamPtr p, size_t offset);
365 /* offset must be <= output(*size) of Look */ 388 /* offset must be <= output(*size) of Look */
366 389 SRes (*Read)(ILookInStreamPtr p, void *buf, size_t *size);
367 SRes (*Read)(const ILookInStream *p, void *buf, size_t *size);
368 /* reads directly (without buffer). It's same as ISeqInStream::Read */ 390 /* reads directly (without buffer). It's same as ISeqInStream::Read */
369 SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin); 391 SRes (*Seek)(ILookInStreamPtr p, Int64 *pos, ESzSeek origin);
370}; 392};
371 393
372#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) 394#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size)
@@ -375,19 +397,18 @@ struct ILookInStream
375#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) 397#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin)
376 398
377 399
378SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size); 400SRes LookInStream_LookRead(ILookInStreamPtr stream, void *buf, size_t *size);
379SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset); 401SRes LookInStream_SeekTo(ILookInStreamPtr stream, UInt64 offset);
380 402
381/* reads via ILookInStream::Read */ 403/* reads via ILookInStream::Read */
382SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType); 404SRes LookInStream_Read2(ILookInStreamPtr stream, void *buf, size_t size, SRes errorType);
383SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size); 405SRes LookInStream_Read(ILookInStreamPtr stream, void *buf, size_t size);
384
385 406
386 407
387typedef struct 408typedef struct
388{ 409{
389 ILookInStream vt; 410 ILookInStream vt;
390 const ISeekInStream *realStream; 411 ISeekInStreamPtr realStream;
391 412
392 size_t pos; 413 size_t pos;
393 size_t size; /* it's data size */ 414 size_t size; /* it's data size */
@@ -399,13 +420,13 @@ typedef struct
399 420
400void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); 421void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead);
401 422
402#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } 423#define LookToRead2_INIT(p) { (p)->pos = (p)->size = 0; }
403 424
404 425
405typedef struct 426typedef struct
406{ 427{
407 ISeqInStream vt; 428 ISeqInStream vt;
408 const ILookInStream *realStream; 429 ILookInStreamPtr realStream;
409} CSecToLook; 430} CSecToLook;
410 431
411void SecToLook_CreateVTable(CSecToLook *p); 432void SecToLook_CreateVTable(CSecToLook *p);
@@ -415,20 +436,19 @@ void SecToLook_CreateVTable(CSecToLook *p);
415typedef struct 436typedef struct
416{ 437{
417 ISeqInStream vt; 438 ISeqInStream vt;
418 const ILookInStream *realStream; 439 ILookInStreamPtr realStream;
419} CSecToRead; 440} CSecToRead;
420 441
421void SecToRead_CreateVTable(CSecToRead *p); 442void SecToRead_CreateVTable(CSecToRead *p);
422 443
423 444
424typedef struct ICompressProgress ICompressProgress; 445Z7_C_IFACE_DECL (ICompressProgress)
425
426struct ICompressProgress
427{ 446{
428 SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize); 447 SRes (*Progress)(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize);
429 /* Returns: result. (result != SZ_OK) means break. 448 /* Returns: result. (result != SZ_OK) means break.
430 Value (UInt64)(Int64)-1 for size means unknown value. */ 449 Value (UInt64)(Int64)-1 for size means unknown value. */
431}; 450};
451
432#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) 452#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize)
433 453
434 454
@@ -466,13 +486,13 @@ struct ISzAlloc
466 486
467 487
468 488
469#ifndef MY_container_of 489#ifndef Z7_container_of
470 490
471/* 491/*
472#define MY_container_of(ptr, type, m) container_of(ptr, type, m) 492#define Z7_container_of(ptr, type, m) container_of(ptr, type, m)
473#define MY_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m) 493#define Z7_container_of(ptr, type, m) CONTAINING_RECORD(ptr, type, m)
474#define MY_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m))) 494#define Z7_container_of(ptr, type, m) ((type *)((char *)(ptr) - offsetof(type, m)))
475#define MY_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m)))) 495#define Z7_container_of(ptr, type, m) (&((type *)0)->m == (ptr), ((type *)(((char *)(ptr)) - MY_offsetof(type, m))))
476*/ 496*/
477 497
478/* 498/*
@@ -481,24 +501,64 @@ struct ISzAlloc
481 GCC 4.8.1 : classes with non-public variable members" 501 GCC 4.8.1 : classes with non-public variable members"
482*/ 502*/
483 503
484#define MY_container_of(ptr, type, m) ((type *)(void *)((char *)(void *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) 504#define Z7_container_of(ptr, type, m) \
505 ((type *)(void *)((char *)(void *) \
506 (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m)))
485 507
486#endif 508#define Z7_container_of_CONST(ptr, type, m) \
487 509 ((const type *)(const void *)((const char *)(const void *) \
488#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr)) 510 (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m)))
489 511
490/* 512/*
491#define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) 513#define Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m) \
514 ((type *)(void *)(const void *)((const char *)(const void *) \
515 (1 ? (ptr) : &((type *)NULL)->m) - MY_offsetof(type, m)))
492*/ 516*/
493#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m)
494 517
495#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) 518#endif
519
520#define Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(void *)(ptr))
521
522// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m)
523#define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of(ptr, type, m)
524// #define Z7_CONTAINER_FROM_VTBL(ptr, type, m) Z7_container_of_NON_CONST_FROM_CONST(ptr, type, m)
525
526#define Z7_CONTAINER_FROM_VTBL_CONST(ptr, type, m) Z7_container_of_CONST(ptr, type, m)
527
528#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m)
496/* 529/*
497#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m) 530#define Z7_CONTAINER_FROM_VTBL_CLS(ptr, type, m) Z7_CONTAINER_FROM_VTBL(ptr, type, m)
498*/ 531*/
532#if defined (__clang__) || defined(__GNUC__)
533#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \
534 _Pragma("GCC diagnostic push") \
535 _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
536#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL \
537 _Pragma("GCC diagnostic pop")
538#else
539#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL
540#define Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL
541#endif
542
543#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(ptr, type, m, p) \
544 Z7_DIAGNOSCTIC_IGNORE_BEGIN_CAST_QUAL \
545 type *p = Z7_CONTAINER_FROM_VTBL(ptr, type, m); \
546 Z7_DIAGNOSCTIC_IGNORE_END_CAST_QUAL
547
548#define Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(type) \
549 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR(pp, type, vt, p)
499 550
500 551
501#define MY_memset_0_ARRAY(a) memset((a), 0, sizeof(a)) 552// #define ZIP7_DECLARE_HANDLE(name) typedef void *name;
553#define Z7_DECLARE_HANDLE(name) struct name##_dummy{int unused;}; typedef struct name##_dummy *name;
554
555
556#define Z7_memset_0_ARRAY(a) memset((a), 0, sizeof(a))
557
558#ifndef Z7_ARRAY_SIZE
559#define Z7_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
560#endif
561
502 562
503#ifdef _WIN32 563#ifdef _WIN32
504 564
@@ -527,3 +587,11 @@ struct ISzAlloc
527EXTERN_C_END 587EXTERN_C_END
528 588
529#endif 589#endif
590
591/*
592#ifndef Z7_ST
593#ifdef _7ZIP_ST
594#define Z7_ST
595#endif
596#endif
597*/
diff --git a/C/7zVersion.h b/C/7zVersion.h
index 49ea81d..7549239 100644
--- a/C/7zVersion.h
+++ b/C/7zVersion.h
@@ -1,7 +1,7 @@
1#define MY_VER_MAJOR 22 1#define MY_VER_MAJOR 23
2#define MY_VER_MINOR 01 2#define MY_VER_MINOR 01
3#define MY_VER_BUILD 0 3#define MY_VER_BUILD 0
4#define MY_VERSION_NUMBERS "22.01" 4#define MY_VERSION_NUMBERS "23.01"
5#define MY_VERSION MY_VERSION_NUMBERS 5#define MY_VERSION MY_VERSION_NUMBERS
6 6
7#ifdef MY_CPU_NAME 7#ifdef MY_CPU_NAME
@@ -10,12 +10,12 @@
10 #define MY_VERSION_CPU MY_VERSION 10 #define MY_VERSION_CPU MY_VERSION
11#endif 11#endif
12 12
13#define MY_DATE "2022-07-15" 13#define MY_DATE "2023-06-20"
14#undef MY_COPYRIGHT 14#undef MY_COPYRIGHT
15#undef MY_VERSION_COPYRIGHT_DATE 15#undef MY_VERSION_COPYRIGHT_DATE
16#define MY_AUTHOR_NAME "Igor Pavlov" 16#define MY_AUTHOR_NAME "Igor Pavlov"
17#define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" 17#define MY_COPYRIGHT_PD "Igor Pavlov : Public domain"
18#define MY_COPYRIGHT_CR "Copyright (c) 1999-2022 Igor Pavlov" 18#define MY_COPYRIGHT_CR "Copyright (c) 1999-2023 Igor Pavlov"
19 19
20#ifdef USE_COPYRIGHT_CR 20#ifdef USE_COPYRIGHT_CR
21 #define MY_COPYRIGHT MY_COPYRIGHT_CR 21 #define MY_COPYRIGHT MY_COPYRIGHT_CR
diff --git a/C/7zWindows.h b/C/7zWindows.h
new file mode 100644
index 0000000..42c6db8
--- /dev/null
+++ b/C/7zWindows.h
@@ -0,0 +1,101 @@
1/* 7zWindows.h -- StdAfx
22023-04-02 : Igor Pavlov : Public domain */
3
4#ifndef ZIP7_INC_7Z_WINDOWS_H
5#define ZIP7_INC_7Z_WINDOWS_H
6
7#ifdef _WIN32
8
9#if defined(__clang__)
10# pragma clang diagnostic push
11#endif
12
13#if defined(_MSC_VER)
14
15#pragma warning(push)
16#pragma warning(disable : 4668) // '_WIN32_WINNT' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
17
18#if _MSC_VER == 1900
19// for old kit10 versions
20// #pragma warning(disable : 4255) // winuser.h(13979): warning C4255: 'GetThreadDpiAwarenessContext':
21#endif
22// win10 Windows Kit:
23#endif // _MSC_VER
24
25#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64)
26// for msvc6 without sdk2003
27#define RPC_NO_WINDOWS_H
28#endif
29
30#if defined(__MINGW32__) || defined(__MINGW64__)
31// #if defined(__GNUC__) && !defined(__clang__)
32#include <windows.h>
33#else
34#include <Windows.h>
35#endif
36// #include <basetsd.h>
37// #include <wtypes.h>
38
39// but if precompiled with clang-cl then we need
40// #include <windows.h>
41#if defined(_MSC_VER)
42#pragma warning(pop)
43#endif
44
45#if defined(__clang__)
46# pragma clang diagnostic pop
47#endif
48
49#if defined(_MSC_VER) && _MSC_VER <= 1200 && !defined(_WIN64)
50#ifndef _W64
51
52typedef long LONG_PTR, *PLONG_PTR;
53typedef unsigned long ULONG_PTR, *PULONG_PTR;
54typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
55
56#define Z7_OLD_WIN_SDK
57#endif // _W64
58#endif // _MSC_VER == 1200
59
60#ifdef Z7_OLD_WIN_SDK
61
62#ifndef INVALID_FILE_ATTRIBUTES
63#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
64#endif
65#ifndef INVALID_SET_FILE_POINTER
66#define INVALID_SET_FILE_POINTER ((DWORD)-1)
67#endif
68#ifndef FILE_SPECIAL_ACCESS
69#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS)
70#endif
71
72// ShlObj.h:
73// #define BIF_NEWDIALOGSTYLE 0x0040
74
75#pragma warning(disable : 4201)
76// #pragma warning(disable : 4115)
77
78#undef VARIANT_TRUE
79#define VARIANT_TRUE ((VARIANT_BOOL)-1)
80#endif
81
82#endif // Z7_OLD_WIN_SDK
83
84#ifdef UNDER_CE
85#undef VARIANT_TRUE
86#define VARIANT_TRUE ((VARIANT_BOOL)-1)
87#endif
88
89
90#if defined(_MSC_VER)
91#if _MSC_VER >= 1400 && _MSC_VER <= 1600
92 // BaseTsd.h(148) : 'HandleToULong' : unreferenced inline function has been removed
93 // string.h
94 // #pragma warning(disable : 4514)
95#endif
96#endif
97
98
99/* #include "7zTypes.h" */
100
101#endif
diff --git a/C/7zip_gcc_c.mak b/C/7zip_gcc_c.mak
index 24505f3..f19a99b 100644
--- a/C/7zip_gcc_c.mak
+++ b/C/7zip_gcc_c.mak
@@ -4,15 +4,28 @@ MY_ARCH_2 = $(MY_ARCH)
4MY_ASM = jwasm 4MY_ASM = jwasm
5MY_ASM = asmc 5MY_ASM = asmc
6 6
7ifndef RC
8#RC=windres.exe --target=pe-x86-64
9#RC=windres.exe -F pe-i386
10RC=windres.exe
11endif
12
7PROGPATH = $(O)/$(PROG) 13PROGPATH = $(O)/$(PROG)
8PROGPATH_STATIC = $(O)/$(PROG)s 14PROGPATH_STATIC = $(O)/$(PROG)s
9 15
16ifneq ($(CC), xlc)
17CFLAGS_WARN_WALL = -Wall -Werror -Wextra
18endif
10 19
11# for object file 20# for object file
12CFLAGS_BASE_LIST = -c 21CFLAGS_BASE_LIST = -c
13# for ASM file 22# for ASM file
14# CFLAGS_BASE_LIST = -S 23# CFLAGS_BASE_LIST = -S
15CFLAGS_BASE = $(MY_ARCH_2) -O2 $(CFLAGS_BASE_LIST) -Wall -Werror -Wextra $(CFLAGS_WARN) \ 24
25FLAGS_FLTO =
26FLAGS_FLTO = -flto
27
28CFLAGS_BASE = $(MY_ARCH_2) -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \
16 -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE 29 -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE
17 30
18 31
@@ -93,9 +106,9 @@ DEL_OBJ_EXE = -$(RM) $(O)\*.o $(O)\$(PROG).exe $(O)\$(PROG).dll
93endif 106endif
94 107
95 108
96LIB2 = -lOle32 -loleaut32 -luuid -ladvapi32 -lUser32 109LIB2 = -lOle32 -loleaut32 -luuid -ladvapi32 -lUser32 -lShell32
97 110
98CXXFLAGS_EXTRA = -DUNICODE -D_UNICODE 111CFLAGS_EXTRA = -DUNICODE -D_UNICODE
99# -Wno-delete-non-virtual-dtor 112# -Wno-delete-non-virtual-dtor
100 113
101 114
@@ -103,8 +116,8 @@ else
103 116
104RM = rm -f 117RM = rm -f
105MY_MKDIR=mkdir -p 118MY_MKDIR=mkdir -p
106# CFLAGS_BASE := $(CFLAGS_BASE) -D_7ZIP_ST 119# CFLAGS_BASE := $(CFLAGS_BASE) -DZ7_ST
107# CXXFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE 120# CFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE
108 121
109# LOCAL_LIBS=-lpthread 122# LOCAL_LIBS=-lpthread
110# LOCAL_LIBS_DLL=$(LOCAL_LIBS) -ldl 123# LOCAL_LIBS_DLL=$(LOCAL_LIBS) -ldl
@@ -115,10 +128,6 @@ DEL_OBJ_EXE = -$(RM) $(PROGPATH) $(PROGPATH_STATIC) $(OBJS)
115endif 128endif
116 129
117 130
118
119CFLAGS = $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@
120
121
122ifdef IS_X64 131ifdef IS_X64
123AFLAGS_ABI = -elf64 -DABI_LINUX 132AFLAGS_ABI = -elf64 -DABI_LINUX
124else 133else
@@ -129,12 +138,9 @@ AFLAGS_ABI = -elf -DABI_LINUX -DABI_CDECL
129endif 138endif
130AFLAGS = $(AFLAGS_ABI) -Fo$(O)/ 139AFLAGS = $(AFLAGS_ABI) -Fo$(O)/
131 140
141C_WARN_FLAGS =
132 142
133CXX_WARN_FLAGS = 143CFLAGS = $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CFLAGS_EXTRA) $(C_WARN_FLAGS) $(FLAGS_FLTO) $(CC_SHARED) -o $@
134#-Wno-invalid-offsetof
135#-Wno-reorder
136
137CXXFLAGS = $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS)
138 144
139STATIC_TARGET= 145STATIC_TARGET=
140ifdef COMPL_STATIC 146ifdef COMPL_STATIC
@@ -147,18 +153,27 @@ all: $(O) $(PROGPATH) $(STATIC_TARGET)
147$(O): 153$(O):
148 $(MY_MKDIR) $(O) 154 $(MY_MKDIR) $(O)
149 155
150LFLAGS_ALL = -s $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) 156ifneq ($(CC), $(CROSS_COMPILE)clang)
157LFLAGS_STRIP = -s
158endif
159
160LFLAGS_ALL = $(LFLAGS_STRIP) $(MY_ARCH_2) $(LDFLAGS) $(FLAGS_FLTO) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2)
151$(PROGPATH): $(OBJS) 161$(PROGPATH): $(OBJS)
152 $(CXX) -o $(PROGPATH) $(LFLAGS_ALL) 162 $(CC) -o $(PROGPATH) $(LFLAGS_ALL)
153 163
154$(PROGPATH_STATIC): $(OBJS) 164$(PROGPATH_STATIC): $(OBJS)
155 $(CXX) -static -o $(PROGPATH_STATIC) $(LFLAGS_ALL) 165 $(CC) -static -o $(PROGPATH_STATIC) $(LFLAGS_ALL)
156 166
157 167
158ifndef NO_DEFAULT_RES 168ifndef NO_DEFAULT_RES
169# old mingw without -FO
170# windres.exe $(RFLAGS) resource.rc $O/resource.o
159$O/resource.o: resource.rc 171$O/resource.o: resource.rc
160 windres.exe $(RFLAGS) resource.rc $O/resource.o 172 $(RC) $(RFLAGS) resource.rc $(O)/resource.o
161endif 173endif
174# windres.exe $(RFLAGS) resource.rc $(O)\resource.o
175# windres.exe $(RFLAGS) resource.rc -FO $(O)/resource.o
176# $(RC) $(RFLAGS) resource.rc -FO $(O)/resource.o
162 177
163 178
164 179
@@ -256,10 +271,18 @@ $O/Sha256.o: ../../../C/Sha256.c
256 $(CC) $(CFLAGS) $< 271 $(CC) $(CFLAGS) $<
257$O/Sort.o: ../../../C/Sort.c 272$O/Sort.o: ../../../C/Sort.c
258 $(CC) $(CFLAGS) $< 273 $(CC) $(CFLAGS) $<
274$O/SwapBytes.o: ../../../C/SwapBytes.c
275 $(CC) $(CFLAGS) $<
259$O/Xz.o: ../../../C/Xz.c 276$O/Xz.o: ../../../C/Xz.c
260 $(CC) $(CFLAGS) $< 277 $(CC) $(CFLAGS) $<
261$O/XzCrc64.o: ../../../C/XzCrc64.c 278$O/XzCrc64.o: ../../../C/XzCrc64.c
262 $(CC) $(CFLAGS) $< 279 $(CC) $(CFLAGS) $<
280$O/XzDec.o: ../../../C/XzDec.c
281 $(CC) $(CFLAGS) $<
282$O/XzEnc.o: ../../../C/XzEnc.c
283 $(CC) $(CFLAGS) $<
284$O/XzIn.o: ../../../C/XzIn.c
285 $(CC) $(CFLAGS) $<
263 286
264 287
265ifdef USE_ASM 288ifdef USE_ASM
@@ -310,7 +333,7 @@ $O/LzmaDecOpt.o: ../../../Asm/arm64/LzmaDecOpt.S ../../../Asm/arm64/7zAsm.S
310endif 333endif
311 334
312$O/LzmaDec.o: ../../LzmaDec.c 335$O/LzmaDec.o: ../../LzmaDec.c
313 $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< 336 $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $<
314 337
315else 338else
316 339
@@ -321,22 +344,16 @@ endif
321 344
322 345
323 346
324$O/XzDec.o: ../../../C/XzDec.c
325 $(CC) $(CFLAGS) $<
326$O/XzEnc.o: ../../../C/XzEnc.c
327 $(CC) $(CFLAGS) $<
328$O/XzIn.o: ../../../C/XzIn.c
329 $(CC) $(CFLAGS) $<
330
331
332$O/7zMain.o: ../../../C/Util/7z/7zMain.c 347$O/7zMain.o: ../../../C/Util/7z/7zMain.c
333 $(CC) $(CFLAGS) $< 348 $(CC) $(CFLAGS) $<
334$O/LzmaUtil.o: ../../../C/Util/Lzma/LzmaUtil.c
335 $(CC) $(CFLAGS) $<
336$O/7zipInstall.o: ../../../C/Util/7zipInstall/7zipInstall.c 349$O/7zipInstall.o: ../../../C/Util/7zipInstall/7zipInstall.c
337 $(CC) $(CFLAGS) $< 350 $(CC) $(CFLAGS) $<
338$O/7zipUninstall.o: ../../../C/Util/7zipUninstall/7zipUninstall.c 351$O/7zipUninstall.o: ../../../C/Util/7zipUninstall/7zipUninstall.c
339 $(CC) $(CFLAGS) $< 352 $(CC) $(CFLAGS) $<
353$O/LzmaUtil.o: ../../../C/Util/Lzma/LzmaUtil.c
354 $(CC) $(CFLAGS) $<
355$O/XzUtil.o: ../../../C/Util/Xz/XzUtil.c
356 $(CC) $(CFLAGS) $<
340 357
341 358
342clean: 359clean:
diff --git a/C/Aes.c b/C/Aes.c
index 27e32e6..bcaafab 100644
--- a/C/Aes.c
+++ b/C/Aes.c
@@ -1,5 +1,5 @@
1/* Aes.c -- AES encryption / decryption 1/* Aes.c -- AES encryption / decryption
22021-05-13 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -7,7 +7,7 @@
7#include "Aes.h" 7#include "Aes.h"
8 8
9AES_CODE_FUNC g_AesCbc_Decode; 9AES_CODE_FUNC g_AesCbc_Decode;
10#ifndef _SFX 10#ifndef Z7_SFX
11AES_CODE_FUNC g_AesCbc_Encode; 11AES_CODE_FUNC g_AesCbc_Encode;
12AES_CODE_FUNC g_AesCtr_Code; 12AES_CODE_FUNC g_AesCtr_Code;
13UInt32 g_Aes_SupportedFunctions_Flags; 13UInt32 g_Aes_SupportedFunctions_Flags;
@@ -51,7 +51,7 @@ static Byte InvS[256];
51#define DD(x) (D + (x << 8)) 51#define DD(x) (D + (x << 8))
52 52
53 53
54// #define _SHOW_AES_STATUS 54// #define Z7_SHOW_AES_STATUS
55 55
56#ifdef MY_CPU_X86_OR_AMD64 56#ifdef MY_CPU_X86_OR_AMD64
57 #define USE_HW_AES 57 #define USE_HW_AES
@@ -72,11 +72,11 @@ static Byte InvS[256];
72#endif 72#endif
73 73
74#ifdef USE_HW_AES 74#ifdef USE_HW_AES
75#ifdef _SHOW_AES_STATUS 75#ifdef Z7_SHOW_AES_STATUS
76#include <stdio.h> 76#include <stdio.h>
77#define _PRF(x) x 77#define PRF(x) x
78#else 78#else
79#define _PRF(x) 79#define PRF(x)
80#endif 80#endif
81#endif 81#endif
82 82
@@ -90,23 +90,23 @@ void AesGenTables(void)
90 for (i = 0; i < 256; i++) 90 for (i = 0; i < 256; i++)
91 { 91 {
92 { 92 {
93 UInt32 a1 = Sbox[i]; 93 const UInt32 a1 = Sbox[i];
94 UInt32 a2 = xtime(a1); 94 const UInt32 a2 = xtime(a1);
95 UInt32 a3 = a2 ^ a1; 95 const UInt32 a3 = a2 ^ a1;
96 TT(0)[i] = Ui32(a2, a1, a1, a3); 96 TT(0)[i] = Ui32(a2, a1, a1, a3);
97 TT(1)[i] = Ui32(a3, a2, a1, a1); 97 TT(1)[i] = Ui32(a3, a2, a1, a1);
98 TT(2)[i] = Ui32(a1, a3, a2, a1); 98 TT(2)[i] = Ui32(a1, a3, a2, a1);
99 TT(3)[i] = Ui32(a1, a1, a3, a2); 99 TT(3)[i] = Ui32(a1, a1, a3, a2);
100 } 100 }
101 { 101 {
102 UInt32 a1 = InvS[i]; 102 const UInt32 a1 = InvS[i];
103 UInt32 a2 = xtime(a1); 103 const UInt32 a2 = xtime(a1);
104 UInt32 a4 = xtime(a2); 104 const UInt32 a4 = xtime(a2);
105 UInt32 a8 = xtime(a4); 105 const UInt32 a8 = xtime(a4);
106 UInt32 a9 = a8 ^ a1; 106 const UInt32 a9 = a8 ^ a1;
107 UInt32 aB = a8 ^ a2 ^ a1; 107 const UInt32 aB = a8 ^ a2 ^ a1;
108 UInt32 aD = a8 ^ a4 ^ a1; 108 const UInt32 aD = a8 ^ a4 ^ a1;
109 UInt32 aE = a8 ^ a4 ^ a2; 109 const UInt32 aE = a8 ^ a4 ^ a2;
110 DD(0)[i] = Ui32(aE, a9, aD, aB); 110 DD(0)[i] = Ui32(aE, a9, aD, aB);
111 DD(1)[i] = Ui32(aB, aE, a9, aD); 111 DD(1)[i] = Ui32(aB, aE, a9, aD);
112 DD(2)[i] = Ui32(aD, aB, aE, a9); 112 DD(2)[i] = Ui32(aD, aB, aE, a9);
@@ -116,7 +116,7 @@ void AesGenTables(void)
116 116
117 { 117 {
118 AES_CODE_FUNC d = AesCbc_Decode; 118 AES_CODE_FUNC d = AesCbc_Decode;
119 #ifndef _SFX 119 #ifndef Z7_SFX
120 AES_CODE_FUNC e = AesCbc_Encode; 120 AES_CODE_FUNC e = AesCbc_Encode;
121 AES_CODE_FUNC c = AesCtr_Code; 121 AES_CODE_FUNC c = AesCtr_Code;
122 UInt32 flags = 0; 122 UInt32 flags = 0;
@@ -126,10 +126,10 @@ void AesGenTables(void)
126 if (CPU_IsSupported_AES()) 126 if (CPU_IsSupported_AES())
127 { 127 {
128 // #pragma message ("AES HW") 128 // #pragma message ("AES HW")
129 _PRF(printf("\n===AES HW\n")); 129 PRF(printf("\n===AES HW\n"));
130 d = AesCbc_Decode_HW; 130 d = AesCbc_Decode_HW;
131 131
132 #ifndef _SFX 132 #ifndef Z7_SFX
133 e = AesCbc_Encode_HW; 133 e = AesCbc_Encode_HW;
134 c = AesCtr_Code_HW; 134 c = AesCtr_Code_HW;
135 flags = k_Aes_SupportedFunctions_HW; 135 flags = k_Aes_SupportedFunctions_HW;
@@ -138,9 +138,9 @@ void AesGenTables(void)
138 #ifdef MY_CPU_X86_OR_AMD64 138 #ifdef MY_CPU_X86_OR_AMD64
139 if (CPU_IsSupported_VAES_AVX2()) 139 if (CPU_IsSupported_VAES_AVX2())
140 { 140 {
141 _PRF(printf("\n===vaes avx2\n")); 141 PRF(printf("\n===vaes avx2\n"));
142 d = AesCbc_Decode_HW_256; 142 d = AesCbc_Decode_HW_256;
143 #ifndef _SFX 143 #ifndef Z7_SFX
144 c = AesCtr_Code_HW_256; 144 c = AesCtr_Code_HW_256;
145 flags |= k_Aes_SupportedFunctions_HW_256; 145 flags |= k_Aes_SupportedFunctions_HW_256;
146 #endif 146 #endif
@@ -150,7 +150,7 @@ void AesGenTables(void)
150 #endif 150 #endif
151 151
152 g_AesCbc_Decode = d; 152 g_AesCbc_Decode = d;
153 #ifndef _SFX 153 #ifndef Z7_SFX
154 g_AesCbc_Encode = e; 154 g_AesCbc_Encode = e;
155 g_AesCtr_Code = c; 155 g_AesCtr_Code = c;
156 g_Aes_SupportedFunctions_Flags = flags; 156 g_Aes_SupportedFunctions_Flags = flags;
@@ -194,7 +194,7 @@ void AesGenTables(void)
194#define FD(i, x) InvS[gb(x, m[(i - x) & 3])] 194#define FD(i, x) InvS[gb(x, m[(i - x) & 3])]
195#define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; 195#define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i];
196 196
197void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize) 197void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize)
198{ 198{
199 unsigned i, m; 199 unsigned i, m;
200 const UInt32 *wLim; 200 const UInt32 *wLim;
@@ -230,7 +230,7 @@ void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *w, const Byte *key, unsigned keySize)
230 while (++w != wLim); 230 while (++w != wLim);
231} 231}
232 232
233void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize) 233void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize)
234{ 234{
235 unsigned i, num; 235 unsigned i, num;
236 Aes_SetKey_Enc(w, key, keySize); 236 Aes_SetKey_Enc(w, key, keySize);
@@ -251,7 +251,7 @@ void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *w, const Byte *key, unsigned keySize)
251 src and dest are pointers to 4 UInt32 words. 251 src and dest are pointers to 4 UInt32 words.
252 src and dest can point to same block */ 252 src and dest can point to same block */
253 253
254// MY_FORCE_INLINE 254// Z7_FORCE_INLINE
255static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src) 255static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
256{ 256{
257 UInt32 s[4]; 257 UInt32 s[4];
@@ -265,17 +265,20 @@ static void Aes_Encode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
265 w += 4; 265 w += 4;
266 for (;;) 266 for (;;)
267 { 267 {
268 HT16(m, s, 0); 268 HT16(m, s, 0)
269 if (--numRounds2 == 0) 269 if (--numRounds2 == 0)
270 break; 270 break;
271 HT16(s, m, 4); 271 HT16(s, m, 4)
272 w += 8; 272 w += 8;
273 } 273 }
274 w += 4; 274 w += 4;
275 FT4(0); FT4(1); FT4(2); FT4(3); 275 FT4(0)
276 FT4(1)
277 FT4(2)
278 FT4(3)
276} 279}
277 280
278MY_FORCE_INLINE 281Z7_FORCE_INLINE
279static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src) 282static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
280{ 283{
281 UInt32 s[4]; 284 UInt32 s[4];
@@ -289,12 +292,15 @@ static void Aes_Decode(const UInt32 *w, UInt32 *dest, const UInt32 *src)
289 for (;;) 292 for (;;)
290 { 293 {
291 w -= 8; 294 w -= 8;
292 HD16(m, s, 4); 295 HD16(m, s, 4)
293 if (--numRounds2 == 0) 296 if (--numRounds2 == 0)
294 break; 297 break;
295 HD16(s, m, 0); 298 HD16(s, m, 0)
296 } 299 }
297 FD4(0); FD4(1); FD4(2); FD4(3); 300 FD4(0)
301 FD4(1)
302 FD4(2)
303 FD4(3)
298} 304}
299 305
300void AesCbc_Init(UInt32 *p, const Byte *iv) 306void AesCbc_Init(UInt32 *p, const Byte *iv)
@@ -304,7 +310,7 @@ void AesCbc_Init(UInt32 *p, const Byte *iv)
304 p[i] = GetUi32(iv + i * 4); 310 p[i] = GetUi32(iv + i * 4);
305} 311}
306 312
307void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks) 313void Z7_FASTCALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks)
308{ 314{
309 for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) 315 for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE)
310 { 316 {
@@ -315,14 +321,14 @@ void MY_FAST_CALL AesCbc_Encode(UInt32 *p, Byte *data, size_t numBlocks)
315 321
316 Aes_Encode(p + 4, p, p); 322 Aes_Encode(p + 4, p, p);
317 323
318 SetUi32(data, p[0]); 324 SetUi32(data, p[0])
319 SetUi32(data + 4, p[1]); 325 SetUi32(data + 4, p[1])
320 SetUi32(data + 8, p[2]); 326 SetUi32(data + 8, p[2])
321 SetUi32(data + 12, p[3]); 327 SetUi32(data + 12, p[3])
322 } 328 }
323} 329}
324 330
325void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks) 331void Z7_FASTCALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks)
326{ 332{
327 UInt32 in[4], out[4]; 333 UInt32 in[4], out[4];
328 for (; numBlocks != 0; numBlocks--, data += AES_BLOCK_SIZE) 334 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)
334 340
335 Aes_Decode(p + 4, out, in); 341 Aes_Decode(p + 4, out, in);
336 342
337 SetUi32(data, p[0] ^ out[0]); 343 SetUi32(data, p[0] ^ out[0])
338 SetUi32(data + 4, p[1] ^ out[1]); 344 SetUi32(data + 4, p[1] ^ out[1])
339 SetUi32(data + 8, p[2] ^ out[2]); 345 SetUi32(data + 8, p[2] ^ out[2])
340 SetUi32(data + 12, p[3] ^ out[3]); 346 SetUi32(data + 12, p[3] ^ out[3])
341 347
342 p[0] = in[0]; 348 p[0] = in[0];
343 p[1] = in[1]; 349 p[1] = in[1];
@@ -346,7 +352,7 @@ void MY_FAST_CALL AesCbc_Decode(UInt32 *p, Byte *data, size_t numBlocks)
346 } 352 }
347} 353}
348 354
349void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks) 355void Z7_FASTCALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks)
350{ 356{
351 for (; numBlocks != 0; numBlocks--) 357 for (; numBlocks != 0; numBlocks--)
352 { 358 {
@@ -360,7 +366,7 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks)
360 366
361 for (i = 0; i < 4; i++, data += 4) 367 for (i = 0; i < 4; i++, data += 4)
362 { 368 {
363 UInt32 t = temp[i]; 369 const UInt32 t = temp[i];
364 370
365 #ifdef MY_CPU_LE_UNALIGN 371 #ifdef MY_CPU_LE_UNALIGN
366 *((UInt32 *)(void *)data) ^= t; 372 *((UInt32 *)(void *)data) ^= t;
@@ -373,3 +379,15 @@ void MY_FAST_CALL AesCtr_Code(UInt32 *p, Byte *data, size_t numBlocks)
373 } 379 }
374 } 380 }
375} 381}
382
383#undef xtime
384#undef Ui32
385#undef gb0
386#undef gb1
387#undef gb2
388#undef gb3
389#undef gb
390#undef TT
391#undef DD
392#undef USE_HW_AES
393#undef PRF
diff --git a/C/Aes.h b/C/Aes.h
index 2aa2256..7f0182a 100644
--- a/C/Aes.h
+++ b/C/Aes.h
@@ -1,8 +1,8 @@
1/* Aes.h -- AES encryption / decryption 1/* Aes.h -- AES encryption / decryption
22018-04-28 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __AES_H 4#ifndef ZIP7_INC_AES_H
5#define __AES_H 5#define ZIP7_INC_AES_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -20,19 +20,19 @@ void AesGenTables(void);
20 20
21/* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */ 21/* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */
22/* keySize = 16 or 24 or 32 (bytes) */ 22/* keySize = 16 or 24 or 32 (bytes) */
23typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize); 23typedef void (Z7_FASTCALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize);
24void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize); 24void Z7_FASTCALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize);
25void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize); 25void Z7_FASTCALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize);
26 26
27/* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */ 27/* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */
28void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ 28void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */
29 29
30/* data - 16-byte aligned pointer to data */ 30/* data - 16-byte aligned pointer to data */
31/* numBlocks - the number of 16-byte blocks in data array */ 31/* numBlocks - the number of 16-byte blocks in data array */
32typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks); 32typedef void (Z7_FASTCALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks);
33 33
34extern AES_CODE_FUNC g_AesCbc_Decode; 34extern AES_CODE_FUNC g_AesCbc_Decode;
35#ifndef _SFX 35#ifndef Z7_SFX
36extern AES_CODE_FUNC g_AesCbc_Encode; 36extern AES_CODE_FUNC g_AesCbc_Encode;
37extern AES_CODE_FUNC g_AesCtr_Code; 37extern AES_CODE_FUNC g_AesCtr_Code;
38#define k_Aes_SupportedFunctions_HW (1 << 2) 38#define k_Aes_SupportedFunctions_HW (1 << 2)
@@ -41,19 +41,19 @@ extern UInt32 g_Aes_SupportedFunctions_Flags;
41#endif 41#endif
42 42
43 43
44#define DECLARE__AES_CODE_FUNC(funcName) \ 44#define Z7_DECLARE_AES_CODE_FUNC(funcName) \
45 void MY_FAST_CALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks); 45 void Z7_FASTCALL funcName(UInt32 *ivAes, Byte *data, size_t numBlocks);
46 46
47DECLARE__AES_CODE_FUNC (AesCbc_Encode) 47Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode)
48DECLARE__AES_CODE_FUNC (AesCbc_Decode) 48Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode)
49DECLARE__AES_CODE_FUNC (AesCtr_Code) 49Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code)
50 50
51DECLARE__AES_CODE_FUNC (AesCbc_Encode_HW) 51Z7_DECLARE_AES_CODE_FUNC (AesCbc_Encode_HW)
52DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW) 52Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW)
53DECLARE__AES_CODE_FUNC (AesCtr_Code_HW) 53Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW)
54 54
55DECLARE__AES_CODE_FUNC (AesCbc_Decode_HW_256) 55Z7_DECLARE_AES_CODE_FUNC (AesCbc_Decode_HW_256)
56DECLARE__AES_CODE_FUNC (AesCtr_Code_HW_256) 56Z7_DECLARE_AES_CODE_FUNC (AesCtr_Code_HW_256)
57 57
58EXTERN_C_END 58EXTERN_C_END
59 59
diff --git a/C/AesOpt.c b/C/AesOpt.c
index 8be8ff6..cfa6413 100644
--- a/C/AesOpt.c
+++ b/C/AesOpt.c
@@ -1,39 +1,33 @@
1/* AesOpt.c -- AES optimized code for x86 AES hardware instructions 1/* AesOpt.c -- AES optimized code for x86 AES hardware instructions
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "Aes.h"
6#include "CpuArch.h" 7#include "CpuArch.h"
7 8
8#ifdef MY_CPU_X86_OR_AMD64 9#ifdef MY_CPU_X86_OR_AMD64
9 10
10 #if defined(__clang__) 11 #if defined(__INTEL_COMPILER)
11 #if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 8)
12 #define USE_INTEL_AES
13 #define ATTRIB_AES __attribute__((__target__("aes")))
14 #if (__clang_major__ >= 8)
15 #define USE_INTEL_VAES
16 #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2")))
17 #endif
18 #endif
19 #elif defined(__GNUC__)
20 #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
21 #define USE_INTEL_AES
22 #ifndef __AES__
23 #define ATTRIB_AES __attribute__((__target__("aes")))
24 #endif
25 #if (__GNUC__ >= 8)
26 #define USE_INTEL_VAES
27 #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx2")))
28 #endif
29 #endif
30 #elif defined(__INTEL_COMPILER)
31 #if (__INTEL_COMPILER >= 1110) 12 #if (__INTEL_COMPILER >= 1110)
32 #define USE_INTEL_AES 13 #define USE_INTEL_AES
33 #if (__INTEL_COMPILER >= 1900) 14 #if (__INTEL_COMPILER >= 1900)
34 #define USE_INTEL_VAES 15 #define USE_INTEL_VAES
35 #endif 16 #endif
36 #endif 17 #endif
18 #elif defined(__clang__) && (__clang_major__ > 3 || __clang_major__ == 3 && __clang_minor__ >= 8) \
19 || defined(__GNUC__) && (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4)
20 #define USE_INTEL_AES
21 #if !defined(__AES__)
22 #define ATTRIB_AES __attribute__((__target__("aes")))
23 #endif
24 #if defined(__clang__) && (__clang_major__ >= 8) \
25 || defined(__GNUC__) && (__GNUC__ >= 8)
26 #define USE_INTEL_VAES
27 #if !defined(__AES__) || !defined(__VAES__) || !defined(__AVX__) || !defined(__AVX2__)
28 #define ATTRIB_VAES __attribute__((__target__("aes,vaes,avx,avx2")))
29 #endif
30 #endif
37 #elif defined(_MSC_VER) 31 #elif defined(_MSC_VER)
38 #if (_MSC_VER > 1500) || (_MSC_FULL_VER >= 150030729) 32 #if (_MSC_VER > 1500) || (_MSC_FULL_VER >= 150030729)
39 #define USE_INTEL_AES 33 #define USE_INTEL_AES
@@ -56,12 +50,15 @@
56#include <wmmintrin.h> 50#include <wmmintrin.h>
57 51
58#ifndef USE_INTEL_VAES 52#ifndef USE_INTEL_VAES
59#define AES_TYPE_keys __m128i 53#define AES_TYPE_keys UInt32
60#define AES_TYPE_data __m128i 54#define AES_TYPE_data Byte
55// #define AES_TYPE_keys __m128i
56// #define AES_TYPE_data __m128i
61#endif 57#endif
62 58
63#define AES_FUNC_START(name) \ 59#define AES_FUNC_START(name) \
64 void MY_FAST_CALL name(__m128i *p, __m128i *data, size_t numBlocks) 60 void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks)
61 // void Z7_FASTCALL name(__m128i *p, __m128i *data, size_t numBlocks)
65 62
66#define AES_FUNC_START2(name) \ 63#define AES_FUNC_START2(name) \
67AES_FUNC_START (name); \ 64AES_FUNC_START (name); \
@@ -69,14 +66,16 @@ ATTRIB_AES \
69AES_FUNC_START (name) 66AES_FUNC_START (name)
70 67
71#define MM_OP(op, dest, src) dest = op(dest, src); 68#define MM_OP(op, dest, src) dest = op(dest, src);
72#define MM_OP_m(op, src) MM_OP(op, m, src); 69#define MM_OP_m(op, src) MM_OP(op, m, src)
73 70
74#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src); 71#define MM_XOR( dest, src) MM_OP(_mm_xor_si128, dest, src)
75#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src); 72#define AVX_XOR(dest, src) MM_OP(_mm256_xor_si256, dest, src)
76 73
77 74
78AES_FUNC_START2 (AesCbc_Encode_HW) 75AES_FUNC_START2 (AesCbc_Encode_HW)
79{ 76{
77 __m128i *p = (__m128i *)(void *)ivAes;
78 __m128i *data = (__m128i *)(void *)data8;
80 __m128i m = *p; 79 __m128i m = *p;
81 const __m128i k0 = p[2]; 80 const __m128i k0 = p[2];
82 const __m128i k1 = p[3]; 81 const __m128i k1 = p[3];
@@ -86,17 +85,17 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
86 UInt32 r = numRounds2; 85 UInt32 r = numRounds2;
87 const __m128i *w = p + 4; 86 const __m128i *w = p + 4;
88 __m128i temp = *data; 87 __m128i temp = *data;
89 MM_XOR (temp, k0); 88 MM_XOR (temp, k0)
90 MM_XOR (m, temp); 89 MM_XOR (m, temp)
91 MM_OP_m (_mm_aesenc_si128, k1); 90 MM_OP_m (_mm_aesenc_si128, k1)
92 do 91 do
93 { 92 {
94 MM_OP_m (_mm_aesenc_si128, w[0]); 93 MM_OP_m (_mm_aesenc_si128, w[0])
95 MM_OP_m (_mm_aesenc_si128, w[1]); 94 MM_OP_m (_mm_aesenc_si128, w[1])
96 w += 2; 95 w += 2;
97 } 96 }
98 while (--r); 97 while (--r);
99 MM_OP_m (_mm_aesenclast_si128, w[0]); 98 MM_OP_m (_mm_aesenclast_si128, w[0])
100 *data = m; 99 *data = m;
101 } 100 }
102 *p = m; 101 *p = m;
@@ -104,14 +103,14 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
104 103
105 104
106#define WOP_1(op) 105#define WOP_1(op)
107#define WOP_2(op) WOP_1 (op) op (m1, 1); 106#define WOP_2(op) WOP_1 (op) op (m1, 1)
108#define WOP_3(op) WOP_2 (op) op (m2, 2); 107#define WOP_3(op) WOP_2 (op) op (m2, 2)
109#define WOP_4(op) WOP_3 (op) op (m3, 3); 108#define WOP_4(op) WOP_3 (op) op (m3, 3)
110#ifdef MY_CPU_AMD64 109#ifdef MY_CPU_AMD64
111#define WOP_5(op) WOP_4 (op) op (m4, 4); 110#define WOP_5(op) WOP_4 (op) op (m4, 4)
112#define WOP_6(op) WOP_5 (op) op (m5, 5); 111#define WOP_6(op) WOP_5 (op) op (m5, 5)
113#define WOP_7(op) WOP_6 (op) op (m6, 6); 112#define WOP_7(op) WOP_6 (op) op (m6, 6)
114#define WOP_8(op) WOP_7 (op) op (m7, 7); 113#define WOP_8(op) WOP_7 (op) op (m7, 7)
115#endif 114#endif
116/* 115/*
117#define WOP_9(op) WOP_8 (op) op (m8, 8); 116#define WOP_9(op) WOP_8 (op) op (m8, 8);
@@ -130,20 +129,20 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
130 #define WOP_M1 WOP_4 129 #define WOP_M1 WOP_4
131#endif 130#endif
132 131
133#define WOP(op) op (m0, 0); WOP_M1(op) 132#define WOP(op) op (m0, 0) WOP_M1(op)
134 133
135 134
136#define DECLARE_VAR(reg, ii) __m128i reg 135#define DECLARE_VAR(reg, ii) __m128i reg;
137#define LOAD_data( reg, ii) reg = data[ii]; 136#define LOAD_data( reg, ii) reg = data[ii];
138#define STORE_data( reg, ii) data[ii] = reg; 137#define STORE_data( reg, ii) data[ii] = reg;
139#if (NUM_WAYS > 1) 138#if (NUM_WAYS > 1)
140#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); 139#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1])
141#endif 140#endif
142 141
143#define AVX__DECLARE_VAR(reg, ii) __m256i reg 142#define AVX_DECLARE_VAR(reg, ii) __m256i reg;
144#define AVX__LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii]; 143#define AVX_LOAD_data( reg, ii) reg = ((const __m256i *)(const void *)data)[ii];
145#define AVX__STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg; 144#define AVX_STORE_data( reg, ii) ((__m256i *)(void *)data)[ii] = reg;
146#define AVX__XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii])); 145#define AVX_XOR_data_M1(reg, ii) AVX_XOR (reg, (((const __m256i *)(const void *)(data - 1))[ii]))
147 146
148#define MM_OP_key(op, reg) MM_OP(op, reg, key); 147#define MM_OP_key(op, reg) MM_OP(op, reg, key);
149 148
@@ -154,23 +153,23 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
154#define AES_XOR( reg, ii) MM_OP_key (_mm_xor_si128, reg) 153#define AES_XOR( reg, ii) MM_OP_key (_mm_xor_si128, reg)
155 154
156 155
157#define AVX__AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg) 156#define AVX_AES_DEC( reg, ii) MM_OP_key (_mm256_aesdec_epi128, reg)
158#define AVX__AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg) 157#define AVX_AES_DEC_LAST( reg, ii) MM_OP_key (_mm256_aesdeclast_epi128, reg)
159#define AVX__AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg) 158#define AVX_AES_ENC( reg, ii) MM_OP_key (_mm256_aesenc_epi128, reg)
160#define AVX__AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg) 159#define AVX_AES_ENC_LAST( reg, ii) MM_OP_key (_mm256_aesenclast_epi128, reg)
161#define AVX__AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg) 160#define AVX_AES_XOR( reg, ii) MM_OP_key (_mm256_xor_si256, reg)
162 161
163#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one); reg = ctr; 162#define CTR_START(reg, ii) MM_OP (_mm_add_epi64, ctr, one) reg = ctr;
164#define CTR_END( reg, ii) MM_XOR (data[ii], reg); 163#define CTR_END( reg, ii) MM_XOR (data[ii], reg)
165 164
166#define AVX__CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two); reg = _mm256_xor_si256(ctr2, key); 165#define AVX_CTR_START(reg, ii) MM_OP (_mm256_add_epi64, ctr2, two) reg = _mm256_xor_si256(ctr2, key);
167#define AVX__CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg); 166#define AVX_CTR_END( reg, ii) AVX_XOR (((__m256i *)(void *)data)[ii], reg)
168 167
169#define WOP_KEY(op, n) { \ 168#define WOP_KEY(op, n) { \
170 const __m128i key = w[n]; \ 169 const __m128i key = w[n]; \
171 WOP(op); } 170 WOP(op); }
172 171
173#define AVX__WOP_KEY(op, n) { \ 172#define AVX_WOP_KEY(op, n) { \
174 const __m256i key = w[n]; \ 173 const __m256i key = w[n]; \
175 WOP(op); } 174 WOP(op); }
176 175
@@ -218,6 +217,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
218 217
219AES_FUNC_START2 (AesCbc_Decode_HW) 218AES_FUNC_START2 (AesCbc_Decode_HW)
220{ 219{
220 __m128i *p = (__m128i *)(void *)ivAes;
221 __m128i *data = (__m128i *)(void *)data8;
221 __m128i iv = *p; 222 __m128i iv = *p;
222 const __m128i *wStart = p + *(const UInt32 *)(p + 1) * 2 + 2 - 1; 223 const __m128i *wStart = p + *(const UInt32 *)(p + 1) * 2 + 2 - 1;
223 const __m128i *dataEnd; 224 const __m128i *dataEnd;
@@ -228,7 +229,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
228 const __m128i *w = wStart; 229 const __m128i *w = wStart;
229 230
230 WOP (DECLARE_VAR) 231 WOP (DECLARE_VAR)
231 WOP (LOAD_data); 232 WOP (LOAD_data)
232 WOP_KEY (AES_XOR, 1) 233 WOP_KEY (AES_XOR, 1)
233 234
234 do 235 do
@@ -239,10 +240,10 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
239 while (w != p); 240 while (w != p);
240 WOP_KEY (AES_DEC_LAST, 0) 241 WOP_KEY (AES_DEC_LAST, 0)
241 242
242 MM_XOR (m0, iv); 243 MM_XOR (m0, iv)
243 WOP_M1 (XOR_data_M1) 244 WOP_M1 (XOR_data_M1)
244 iv = data[NUM_WAYS - 1]; 245 iv = data[NUM_WAYS - 1];
245 WOP (STORE_data); 246 WOP (STORE_data)
246 } 247 }
247 WIDE_LOOP_END 248 WIDE_LOOP_END
248 249
@@ -252,15 +253,15 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
252 __m128i m = _mm_xor_si128 (w[2], *data); 253 __m128i m = _mm_xor_si128 (w[2], *data);
253 do 254 do
254 { 255 {
255 MM_OP_m (_mm_aesdec_si128, w[1]); 256 MM_OP_m (_mm_aesdec_si128, w[1])
256 MM_OP_m (_mm_aesdec_si128, w[0]); 257 MM_OP_m (_mm_aesdec_si128, w[0])
257 w -= 2; 258 w -= 2;
258 } 259 }
259 while (w != p); 260 while (w != p);
260 MM_OP_m (_mm_aesdec_si128, w[1]); 261 MM_OP_m (_mm_aesdec_si128, w[1])
261 MM_OP_m (_mm_aesdeclast_si128, w[0]); 262 MM_OP_m (_mm_aesdeclast_si128, w[0])
262 263
263 MM_XOR (m, iv); 264 MM_XOR (m, iv)
264 iv = *data; 265 iv = *data;
265 *data = m; 266 *data = m;
266 } 267 }
@@ -271,6 +272,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
271 272
272AES_FUNC_START2 (AesCtr_Code_HW) 273AES_FUNC_START2 (AesCtr_Code_HW)
273{ 274{
275 __m128i *p = (__m128i *)(void *)ivAes;
276 __m128i *data = (__m128i *)(void *)data8;
274 __m128i ctr = *p; 277 __m128i ctr = *p;
275 UInt32 numRoundsMinus2 = *(const UInt32 *)(p + 1) * 2 - 1; 278 UInt32 numRoundsMinus2 = *(const UInt32 *)(p + 1) * 2 - 1;
276 const __m128i *dataEnd; 279 const __m128i *dataEnd;
@@ -283,7 +286,7 @@ AES_FUNC_START2 (AesCtr_Code_HW)
283 const __m128i *w = p; 286 const __m128i *w = p;
284 UInt32 r = numRoundsMinus2; 287 UInt32 r = numRoundsMinus2;
285 WOP (DECLARE_VAR) 288 WOP (DECLARE_VAR)
286 WOP (CTR_START); 289 WOP (CTR_START)
287 WOP_KEY (AES_XOR, 0) 290 WOP_KEY (AES_XOR, 0)
288 w += 1; 291 w += 1;
289 do 292 do
@@ -294,7 +297,7 @@ AES_FUNC_START2 (AesCtr_Code_HW)
294 while (--r); 297 while (--r);
295 WOP_KEY (AES_ENC_LAST, 0) 298 WOP_KEY (AES_ENC_LAST, 0)
296 299
297 WOP (CTR_END); 300 WOP (CTR_END)
298 } 301 }
299 WIDE_LOOP_END 302 WIDE_LOOP_END
300 303
@@ -303,19 +306,19 @@ AES_FUNC_START2 (AesCtr_Code_HW)
303 UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; 306 UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1;
304 const __m128i *w = p; 307 const __m128i *w = p;
305 __m128i m; 308 __m128i m;
306 MM_OP (_mm_add_epi64, ctr, one); 309 MM_OP (_mm_add_epi64, ctr, one)
307 m = _mm_xor_si128 (ctr, p[0]); 310 m = _mm_xor_si128 (ctr, p[0]);
308 w += 1; 311 w += 1;
309 do 312 do
310 { 313 {
311 MM_OP_m (_mm_aesenc_si128, w[0]); 314 MM_OP_m (_mm_aesenc_si128, w[0])
312 MM_OP_m (_mm_aesenc_si128, w[1]); 315 MM_OP_m (_mm_aesenc_si128, w[1])
313 w += 2; 316 w += 2;
314 } 317 }
315 while (--numRounds2); 318 while (--numRounds2);
316 MM_OP_m (_mm_aesenc_si128, w[0]); 319 MM_OP_m (_mm_aesenc_si128, w[0])
317 MM_OP_m (_mm_aesenclast_si128, w[1]); 320 MM_OP_m (_mm_aesenclast_si128, w[1])
318 MM_XOR (*data, m); 321 MM_XOR (*data, m)
319 } 322 }
320 323
321 p[-2] = ctr; 324 p[-2] = ctr;
@@ -325,17 +328,58 @@ AES_FUNC_START2 (AesCtr_Code_HW)
325 328
326#ifdef USE_INTEL_VAES 329#ifdef USE_INTEL_VAES
327 330
331/*
332GCC before 2013-Jun:
333 <immintrin.h>:
334 #ifdef __AVX__
335 #include <avxintrin.h>
336 #endif
337GCC after 2013-Jun:
338 <immintrin.h>:
339 #include <avxintrin.h>
340CLANG 3.8+:
341{
342 <immintrin.h>:
343 #if !defined(_MSC_VER) || defined(__AVX__)
344 #include <avxintrin.h>
345 #endif
346
347 if (the compiler is clang for Windows and if global arch is not set for __AVX__)
348 [ if (defined(_MSC_VER) && !defined(__AVX__)) ]
349 {
350 <immintrin.h> doesn't include <avxintrin.h>
351 and we have 2 ways to fix it:
352 1) we can define required __AVX__ before <immintrin.h>
353 or
354 2) we can include <avxintrin.h> after <immintrin.h>
355 }
356}
357
358If we include <avxintrin.h> manually for GCC/CLANG, it's
359required that <immintrin.h> must be included before <avxintrin.h>.
360*/
361
362/*
328#if defined(__clang__) && defined(_MSC_VER) 363#if defined(__clang__) && defined(_MSC_VER)
329#define __SSE4_2__
330#define __AES__
331#define __AVX__ 364#define __AVX__
332#define __AVX2__ 365#define __AVX2__
333#define __VAES__ 366#define __VAES__
334#define __AVX512F__
335#define __AVX512VL__
336#endif 367#endif
368*/
337 369
338#include <immintrin.h> 370#include <immintrin.h>
371#if defined(__clang__) && defined(_MSC_VER)
372 #if !defined(__AVX__)
373 #include <avxintrin.h>
374 #endif
375 #if !defined(__AVX2__)
376 #include <avx2intrin.h>
377 #endif
378 #if !defined(__VAES__)
379 #include <vaesintrin.h>
380 #endif
381#endif // __clang__ && _MSC_VER
382
339 383
340#define VAES_FUNC_START2(name) \ 384#define VAES_FUNC_START2(name) \
341AES_FUNC_START (name); \ 385AES_FUNC_START (name); \
@@ -344,6 +388,8 @@ AES_FUNC_START (name)
344 388
345VAES_FUNC_START2 (AesCbc_Decode_HW_256) 389VAES_FUNC_START2 (AesCbc_Decode_HW_256)
346{ 390{
391 __m128i *p = (__m128i *)(void *)ivAes;
392 __m128i *data = (__m128i *)(void *)data8;
347 __m128i iv = *p; 393 __m128i iv = *p;
348 const __m128i *dataEnd; 394 const __m128i *dataEnd;
349 UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; 395 UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1;
@@ -353,22 +399,22 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256)
353 { 399 {
354 const __m256i *w = keys + numRounds - 2; 400 const __m256i *w = keys + numRounds - 2;
355 401
356 WOP (AVX__DECLARE_VAR) 402 WOP (AVX_DECLARE_VAR)
357 WOP (AVX__LOAD_data); 403 WOP (AVX_LOAD_data)
358 AVX__WOP_KEY (AVX__AES_XOR, 1) 404 AVX_WOP_KEY (AVX_AES_XOR, 1)
359 405
360 do 406 do
361 { 407 {
362 AVX__WOP_KEY (AVX__AES_DEC, 0) 408 AVX_WOP_KEY (AVX_AES_DEC, 0)
363 w--; 409 w--;
364 } 410 }
365 while (w != keys); 411 while (w != keys);
366 AVX__WOP_KEY (AVX__AES_DEC_LAST, 0) 412 AVX_WOP_KEY (AVX_AES_DEC_LAST, 0)
367 413
368 AVX_XOR (m0, _mm256_setr_m128i(iv, data[0])); 414 AVX_XOR (m0, _mm256_setr_m128i(iv, data[0]))
369 WOP_M1 (AVX__XOR_data_M1) 415 WOP_M1 (AVX_XOR_data_M1)
370 iv = data[NUM_WAYS * 2 - 1]; 416 iv = data[NUM_WAYS * 2 - 1];
371 WOP (AVX__STORE_data); 417 WOP (AVX_STORE_data)
372 } 418 }
373 WIDE_LOOP_END_AVX(;) 419 WIDE_LOOP_END_AVX(;)
374 420
@@ -378,15 +424,15 @@ VAES_FUNC_START2 (AesCbc_Decode_HW_256)
378 __m128i m = _mm_xor_si128 (w[2], *data); 424 __m128i m = _mm_xor_si128 (w[2], *data);
379 do 425 do
380 { 426 {
381 MM_OP_m (_mm_aesdec_si128, w[1]); 427 MM_OP_m (_mm_aesdec_si128, w[1])
382 MM_OP_m (_mm_aesdec_si128, w[0]); 428 MM_OP_m (_mm_aesdec_si128, w[0])
383 w -= 2; 429 w -= 2;
384 } 430 }
385 while (w != p); 431 while (w != p);
386 MM_OP_m (_mm_aesdec_si128, w[1]); 432 MM_OP_m (_mm_aesdec_si128, w[1])
387 MM_OP_m (_mm_aesdeclast_si128, w[0]); 433 MM_OP_m (_mm_aesdeclast_si128, w[0])
388 434
389 MM_XOR (m, iv); 435 MM_XOR (m, iv)
390 iv = *data; 436 iv = *data;
391 *data = m; 437 *data = m;
392 } 438 }
@@ -403,18 +449,20 @@ AVX2: _mm256_add_epi64 : vpaddq ymm, ymm, ymm
403 _mm256_broadcastsi128_si256 : vbroadcasti128 449 _mm256_broadcastsi128_si256 : vbroadcasti128
404*/ 450*/
405 451
406#define AVX__CTR_LOOP_START \ 452#define AVX_CTR_LOOP_START \
407 ctr2 = _mm256_setr_m128i(_mm_sub_epi64(ctr, one), ctr); \ 453 ctr2 = _mm256_setr_m128i(_mm_sub_epi64(ctr, one), ctr); \
408 two = _mm256_setr_m128i(one, one); \ 454 two = _mm256_setr_m128i(one, one); \
409 two = _mm256_add_epi64(two, two); \ 455 two = _mm256_add_epi64(two, two); \
410 456
411// two = _mm256_setr_epi64x(2, 0, 2, 0); 457// two = _mm256_setr_epi64x(2, 0, 2, 0);
412 458
413#define AVX__CTR_LOOP_ENC \ 459#define AVX_CTR_LOOP_ENC \
414 ctr = _mm256_extracti128_si256 (ctr2, 1); \ 460 ctr = _mm256_extracti128_si256 (ctr2, 1); \
415 461
416VAES_FUNC_START2 (AesCtr_Code_HW_256) 462VAES_FUNC_START2 (AesCtr_Code_HW_256)
417{ 463{
464 __m128i *p = (__m128i *)(void *)ivAes;
465 __m128i *data = (__m128i *)(void *)data8;
418 __m128i ctr = *p; 466 __m128i ctr = *p;
419 UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1; 467 UInt32 numRounds = *(const UInt32 *)(p + 1) * 2 + 1;
420 const __m128i *dataEnd; 468 const __m128i *dataEnd;
@@ -422,44 +470,44 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256)
422 __m256i ctr2, two; 470 __m256i ctr2, two;
423 p += 2; 471 p += 2;
424 472
425 WIDE_LOOP_START_AVX (AVX__CTR_LOOP_START) 473 WIDE_LOOP_START_AVX (AVX_CTR_LOOP_START)
426 { 474 {
427 const __m256i *w = keys; 475 const __m256i *w = keys;
428 UInt32 r = numRounds - 2; 476 UInt32 r = numRounds - 2;
429 WOP (AVX__DECLARE_VAR) 477 WOP (AVX_DECLARE_VAR)
430 AVX__WOP_KEY (AVX__CTR_START, 0); 478 AVX_WOP_KEY (AVX_CTR_START, 0)
431 479
432 w += 1; 480 w += 1;
433 do 481 do
434 { 482 {
435 AVX__WOP_KEY (AVX__AES_ENC, 0) 483 AVX_WOP_KEY (AVX_AES_ENC, 0)
436 w += 1; 484 w += 1;
437 } 485 }
438 while (--r); 486 while (--r);
439 AVX__WOP_KEY (AVX__AES_ENC_LAST, 0) 487 AVX_WOP_KEY (AVX_AES_ENC_LAST, 0)
440 488
441 WOP (AVX__CTR_END); 489 WOP (AVX_CTR_END)
442 } 490 }
443 WIDE_LOOP_END_AVX (AVX__CTR_LOOP_ENC) 491 WIDE_LOOP_END_AVX (AVX_CTR_LOOP_ENC)
444 492
445 SINGLE_LOOP 493 SINGLE_LOOP
446 { 494 {
447 UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1; 495 UInt32 numRounds2 = *(const UInt32 *)(p - 2 + 1) - 1;
448 const __m128i *w = p; 496 const __m128i *w = p;
449 __m128i m; 497 __m128i m;
450 MM_OP (_mm_add_epi64, ctr, one); 498 MM_OP (_mm_add_epi64, ctr, one)
451 m = _mm_xor_si128 (ctr, p[0]); 499 m = _mm_xor_si128 (ctr, p[0]);
452 w += 1; 500 w += 1;
453 do 501 do
454 { 502 {
455 MM_OP_m (_mm_aesenc_si128, w[0]); 503 MM_OP_m (_mm_aesenc_si128, w[0])
456 MM_OP_m (_mm_aesenc_si128, w[1]); 504 MM_OP_m (_mm_aesenc_si128, w[1])
457 w += 2; 505 w += 2;
458 } 506 }
459 while (--numRounds2); 507 while (--numRounds2);
460 MM_OP_m (_mm_aesenc_si128, w[0]); 508 MM_OP_m (_mm_aesenc_si128, w[0])
461 MM_OP_m (_mm_aesenclast_si128, w[1]); 509 MM_OP_m (_mm_aesenclast_si128, w[1])
462 MM_XOR (*data, m); 510 MM_XOR (*data, m)
463 } 511 }
464 512
465 p[-2] = ctr; 513 p[-2] = ctr;
@@ -477,7 +525,7 @@ VAES_FUNC_START2 (AesCtr_Code_HW_256)
477#define AES_TYPE_data Byte 525#define AES_TYPE_data Byte
478 526
479#define AES_FUNC_START(name) \ 527#define AES_FUNC_START(name) \
480 void MY_FAST_CALL name(UInt32 *p, Byte *data, size_t numBlocks) \ 528 void Z7_FASTCALL name(UInt32 *p, Byte *data, size_t numBlocks) \
481 529
482#define AES_COMPAT_STUB(name) \ 530#define AES_COMPAT_STUB(name) \
483 AES_FUNC_START(name); \ 531 AES_FUNC_START(name); \
@@ -496,8 +544,8 @@ AES_COMPAT_STUB (AesCtr_Code)
496#pragma message("VAES HW_SW stub was used") 544#pragma message("VAES HW_SW stub was used")
497 545
498#define VAES_COMPAT_STUB(name) \ 546#define VAES_COMPAT_STUB(name) \
499 void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \ 547 void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks); \
500 void MY_FAST_CALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \ 548 void Z7_FASTCALL name ## _256(UInt32 *p, Byte *data, size_t numBlocks) \
501 { name((AES_TYPE_keys *)(void *)p, (AES_TYPE_data *)(void *)data, numBlocks); } 549 { name((AES_TYPE_keys *)(void *)p, (AES_TYPE_data *)(void *)data, numBlocks); }
502 550
503VAES_COMPAT_STUB (AesCbc_Decode_HW) 551VAES_COMPAT_STUB (AesCbc_Decode_HW)
@@ -551,7 +599,8 @@ VAES_COMPAT_STUB (AesCtr_Code_HW)
551typedef uint8x16_t v128; 599typedef uint8x16_t v128;
552 600
553#define AES_FUNC_START(name) \ 601#define AES_FUNC_START(name) \
554 void MY_FAST_CALL name(v128 *p, v128 *data, size_t numBlocks) 602 void Z7_FASTCALL name(UInt32 *ivAes, Byte *data8, size_t numBlocks)
603 // void Z7_FASTCALL name(v128 *p, v128 *data, size_t numBlocks)
555 604
556#define AES_FUNC_START2(name) \ 605#define AES_FUNC_START2(name) \
557AES_FUNC_START (name); \ 606AES_FUNC_START (name); \
@@ -559,18 +608,20 @@ ATTRIB_AES \
559AES_FUNC_START (name) 608AES_FUNC_START (name)
560 609
561#define MM_OP(op, dest, src) dest = op(dest, src); 610#define MM_OP(op, dest, src) dest = op(dest, src);
562#define MM_OP_m(op, src) MM_OP(op, m, src); 611#define MM_OP_m(op, src) MM_OP(op, m, src)
563#define MM_OP1_m(op) m = op(m); 612#define MM_OP1_m(op) m = op(m);
564 613
565#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src); 614#define MM_XOR( dest, src) MM_OP(veorq_u8, dest, src)
566#define MM_XOR_m( src) MM_XOR(m, src); 615#define MM_XOR_m( src) MM_XOR(m, src)
567 616
568#define AES_E_m(k) MM_OP_m (vaeseq_u8, k); 617#define AES_E_m(k) MM_OP_m (vaeseq_u8, k)
569#define AES_E_MC_m(k) AES_E_m (k); MM_OP1_m(vaesmcq_u8); 618#define AES_E_MC_m(k) AES_E_m (k) MM_OP1_m(vaesmcq_u8)
570 619
571 620
572AES_FUNC_START2 (AesCbc_Encode_HW) 621AES_FUNC_START2 (AesCbc_Encode_HW)
573{ 622{
623 v128 *p = (v128*)(void*)ivAes;
624 v128 *data = (v128*)(void*)data8;
574 v128 m = *p; 625 v128 m = *p;
575 const v128 k0 = p[2]; 626 const v128 k0 = p[2];
576 const v128 k1 = p[3]; 627 const v128 k1 = p[3];
@@ -608,7 +659,7 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
608 AES_E_MC_m (p[14]) 659 AES_E_MC_m (p[14])
609 } 660 }
610 } 661 }
611 AES_E_m (k_z1); 662 AES_E_m (k_z1)
612 MM_XOR_m (k_z0); 663 MM_XOR_m (k_z0);
613 *data = m; 664 *data = m;
614 } 665 }
@@ -617,44 +668,44 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
617 668
618 669
619#define WOP_1(op) 670#define WOP_1(op)
620#define WOP_2(op) WOP_1 (op) op (m1, 1); 671#define WOP_2(op) WOP_1 (op) op (m1, 1)
621#define WOP_3(op) WOP_2 (op) op (m2, 2); 672#define WOP_3(op) WOP_2 (op) op (m2, 2)
622#define WOP_4(op) WOP_3 (op) op (m3, 3); 673#define WOP_4(op) WOP_3 (op) op (m3, 3)
623#define WOP_5(op) WOP_4 (op) op (m4, 4); 674#define WOP_5(op) WOP_4 (op) op (m4, 4)
624#define WOP_6(op) WOP_5 (op) op (m5, 5); 675#define WOP_6(op) WOP_5 (op) op (m5, 5)
625#define WOP_7(op) WOP_6 (op) op (m6, 6); 676#define WOP_7(op) WOP_6 (op) op (m6, 6)
626#define WOP_8(op) WOP_7 (op) op (m7, 7); 677#define WOP_8(op) WOP_7 (op) op (m7, 7)
627 678
628 #define NUM_WAYS 8 679 #define NUM_WAYS 8
629 #define WOP_M1 WOP_8 680 #define WOP_M1 WOP_8
630 681
631#define WOP(op) op (m0, 0); WOP_M1(op) 682#define WOP(op) op (m0, 0) WOP_M1(op)
632 683
633#define DECLARE_VAR(reg, ii) v128 reg 684#define DECLARE_VAR(reg, ii) v128 reg;
634#define LOAD_data( reg, ii) reg = data[ii]; 685#define LOAD_data( reg, ii) reg = data[ii];
635#define STORE_data( reg, ii) data[ii] = reg; 686#define STORE_data( reg, ii) data[ii] = reg;
636#if (NUM_WAYS > 1) 687#if (NUM_WAYS > 1)
637#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1]); 688#define XOR_data_M1(reg, ii) MM_XOR (reg, data[ii- 1])
638#endif 689#endif
639 690
640#define MM_OP_key(op, reg) MM_OP (op, reg, key); 691#define MM_OP_key(op, reg) MM_OP (op, reg, key)
641 692
642#define AES_D_m(k) MM_OP_m (vaesdq_u8, k); 693#define AES_D_m(k) MM_OP_m (vaesdq_u8, k)
643#define AES_D_IMC_m(k) AES_D_m (k); MM_OP1_m (vaesimcq_u8); 694#define AES_D_IMC_m(k) AES_D_m (k) MM_OP1_m (vaesimcq_u8)
644 695
645#define AES_XOR( reg, ii) MM_OP_key (veorq_u8, reg) 696#define AES_XOR( reg, ii) MM_OP_key (veorq_u8, reg)
646#define AES_D( reg, ii) MM_OP_key (vaesdq_u8, reg) 697#define AES_D( reg, ii) MM_OP_key (vaesdq_u8, reg)
647#define AES_E( reg, ii) MM_OP_key (vaeseq_u8, reg) 698#define AES_E( reg, ii) MM_OP_key (vaeseq_u8, reg)
648 699
649#define AES_D_IMC( reg, ii) AES_D (reg, ii); reg = vaesimcq_u8(reg) 700#define AES_D_IMC( reg, ii) AES_D (reg, ii) reg = vaesimcq_u8(reg);
650#define AES_E_MC( reg, ii) AES_E (reg, ii); reg = vaesmcq_u8(reg) 701#define AES_E_MC( reg, ii) AES_E (reg, ii) reg = vaesmcq_u8(reg);
651 702
652#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one); reg = vreinterpretq_u8_u64(ctr); 703#define CTR_START(reg, ii) MM_OP (vaddq_u64, ctr, one) reg = vreinterpretq_u8_u64(ctr);
653#define CTR_END( reg, ii) MM_XOR (data[ii], reg); 704#define CTR_END( reg, ii) MM_XOR (data[ii], reg)
654 705
655#define WOP_KEY(op, n) { \ 706#define WOP_KEY(op, n) { \
656 const v128 key = w[n]; \ 707 const v128 key = w[n]; \
657 WOP(op); } 708 WOP(op) }
658 709
659#define WIDE_LOOP_START \ 710#define WIDE_LOOP_START \
660 dataEnd = data + numBlocks; \ 711 dataEnd = data + numBlocks; \
@@ -672,6 +723,8 @@ AES_FUNC_START2 (AesCbc_Encode_HW)
672 723
673AES_FUNC_START2 (AesCbc_Decode_HW) 724AES_FUNC_START2 (AesCbc_Decode_HW)
674{ 725{
726 v128 *p = (v128*)(void*)ivAes;
727 v128 *data = (v128*)(void*)data8;
675 v128 iv = *p; 728 v128 iv = *p;
676 const v128 *wStart = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; 729 const v128 *wStart = p + ((size_t)*(const UInt32 *)(p + 1)) * 2;
677 const v128 *dataEnd; 730 const v128 *dataEnd;
@@ -681,7 +734,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
681 { 734 {
682 const v128 *w = wStart; 735 const v128 *w = wStart;
683 WOP (DECLARE_VAR) 736 WOP (DECLARE_VAR)
684 WOP (LOAD_data); 737 WOP (LOAD_data)
685 WOP_KEY (AES_D_IMC, 2) 738 WOP_KEY (AES_D_IMC, 2)
686 do 739 do
687 { 740 {
@@ -695,7 +748,7 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
695 MM_XOR (m0, iv); 748 MM_XOR (m0, iv);
696 WOP_M1 (XOR_data_M1) 749 WOP_M1 (XOR_data_M1)
697 iv = data[NUM_WAYS - 1]; 750 iv = data[NUM_WAYS - 1];
698 WOP (STORE_data); 751 WOP (STORE_data)
699 } 752 }
700 WIDE_LOOP_END 753 WIDE_LOOP_END
701 754
@@ -724,6 +777,8 @@ AES_FUNC_START2 (AesCbc_Decode_HW)
724 777
725AES_FUNC_START2 (AesCtr_Code_HW) 778AES_FUNC_START2 (AesCtr_Code_HW)
726{ 779{
780 v128 *p = (v128*)(void*)ivAes;
781 v128 *data = (v128*)(void*)data8;
727 uint64x2_t ctr = vreinterpretq_u64_u8(*p); 782 uint64x2_t ctr = vreinterpretq_u64_u8(*p);
728 const v128 *wEnd = p + ((size_t)*(const UInt32 *)(p + 1)) * 2; 783 const v128 *wEnd = p + ((size_t)*(const UInt32 *)(p + 1)) * 2;
729 const v128 *dataEnd; 784 const v128 *dataEnd;
@@ -735,7 +790,7 @@ AES_FUNC_START2 (AesCtr_Code_HW)
735 { 790 {
736 const v128 *w = p; 791 const v128 *w = p;
737 WOP (DECLARE_VAR) 792 WOP (DECLARE_VAR)
738 WOP (CTR_START); 793 WOP (CTR_START)
739 do 794 do
740 { 795 {
741 WOP_KEY (AES_E_MC, 0) 796 WOP_KEY (AES_E_MC, 0)
@@ -746,7 +801,7 @@ AES_FUNC_START2 (AesCtr_Code_HW)
746 WOP_KEY (AES_E_MC, 0) 801 WOP_KEY (AES_E_MC, 0)
747 WOP_KEY (AES_E, 1) 802 WOP_KEY (AES_E, 1)
748 WOP_KEY (AES_XOR, 2) 803 WOP_KEY (AES_XOR, 2)
749 WOP (CTR_END); 804 WOP (CTR_END)
750 } 805 }
751 WIDE_LOOP_END 806 WIDE_LOOP_END
752 807
@@ -762,10 +817,10 @@ AES_FUNC_START2 (AesCtr_Code_HW)
762 w += 2; 817 w += 2;
763 } 818 }
764 while (w != wEnd); 819 while (w != wEnd);
765 AES_E_MC_m (w[0]); 820 AES_E_MC_m (w[0])
766 AES_E_m (w[1]); 821 AES_E_m (w[1])
767 MM_XOR_m (w[2]); 822 MM_XOR_m (w[2])
768 CTR_END (m, 0); 823 CTR_END (m, 0)
769 } 824 }
770 825
771 p[-2] = vreinterpretq_u8_u64(ctr); 826 p[-2] = vreinterpretq_u8_u64(ctr);
@@ -774,3 +829,12 @@ AES_FUNC_START2 (AesCtr_Code_HW)
774#endif // USE_HW_AES 829#endif // USE_HW_AES
775 830
776#endif // MY_CPU_ARM_OR_ARM64 831#endif // MY_CPU_ARM_OR_ARM64
832
833#undef NUM_WAYS
834#undef WOP_M1
835#undef WOP
836#undef DECLARE_VAR
837#undef LOAD_data
838#undef STORE_data
839#undef USE_INTEL_AES
840#undef USE_HW_AES
diff --git a/C/Alloc.c b/C/Alloc.c
index d1af76c..d841bf2 100644
--- a/C/Alloc.c
+++ b/C/Alloc.c
@@ -1,38 +1,54 @@
1/* Alloc.c -- Memory allocation functions 1/* Alloc.c -- Memory allocation functions
22021-07-13 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include <stdio.h>
7
8#ifdef _WIN32 6#ifdef _WIN32
9#include <Windows.h> 7#include "7zWindows.h"
10#endif 8#endif
11#include <stdlib.h> 9#include <stdlib.h>
12 10
13#include "Alloc.h" 11#include "Alloc.h"
14 12
15/* #define _SZ_ALLOC_DEBUG */ 13#ifdef _WIN32
14#ifdef Z7_LARGE_PAGES
15#if defined(__clang__) || defined(__GNUC__)
16typedef void (*Z7_voidFunction)(void);
17#define MY_CAST_FUNC (Z7_voidFunction)
18#elif defined(_MSC_VER) && _MSC_VER > 1920
19#define MY_CAST_FUNC (void *)
20// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()'
21#else
22#define MY_CAST_FUNC
23#endif
24#endif // Z7_LARGE_PAGES
25#endif // _WIN32
26
27// #define SZ_ALLOC_DEBUG
28/* #define SZ_ALLOC_DEBUG */
16 29
17/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ 30/* use SZ_ALLOC_DEBUG to debug alloc/free operations */
18#ifdef _SZ_ALLOC_DEBUG 31#ifdef SZ_ALLOC_DEBUG
19 32
33#include <string.h>
20#include <stdio.h> 34#include <stdio.h>
21int g_allocCount = 0; 35static int g_allocCount = 0;
22int g_allocCountMid = 0; 36#ifdef _WIN32
23int g_allocCountBig = 0; 37static int g_allocCountMid = 0;
38static int g_allocCountBig = 0;
39#endif
24 40
25 41
26#define CONVERT_INT_TO_STR(charType, tempSize) \ 42#define CONVERT_INT_TO_STR(charType, tempSize) \
27 unsigned char temp[tempSize]; unsigned i = 0; \ 43 char temp[tempSize]; unsigned i = 0; \
28 while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \ 44 while (val >= 10) { temp[i++] = (char)('0' + (unsigned)(val % 10)); val /= 10; } \
29 *s++ = (charType)('0' + (unsigned)val); \ 45 *s++ = (charType)('0' + (unsigned)val); \
30 while (i != 0) { i--; *s++ = temp[i]; } \ 46 while (i != 0) { i--; *s++ = temp[i]; } \
31 *s = 0; 47 *s = 0;
32 48
33static void ConvertUInt64ToString(UInt64 val, char *s) 49static void ConvertUInt64ToString(UInt64 val, char *s)
34{ 50{
35 CONVERT_INT_TO_STR(char, 24); 51 CONVERT_INT_TO_STR(char, 24)
36} 52}
37 53
38#define GET_HEX_CHAR(t) ((char)(((t < 10) ? ('0' + t) : ('A' + (t - 10))))) 54#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)
77 Print(s); 93 Print(s);
78} 94}
79 95
80static void PrintLn() 96static void PrintLn(void)
81{ 97{
82 Print("\n"); 98 Print("\n");
83} 99}
@@ -89,10 +105,10 @@ static void PrintHex(UInt64 v, size_t align)
89 PrintAligned(s, align); 105 PrintAligned(s, align);
90} 106}
91 107
92static void PrintDec(UInt64 v, size_t align) 108static void PrintDec(int v, size_t align)
93{ 109{
94 char s[32]; 110 char s[32];
95 ConvertUInt64ToString(v, s); 111 ConvertUInt64ToString((unsigned)v, s);
96 PrintAligned(s, align); 112 PrintAligned(s, align);
97} 113}
98 114
@@ -102,12 +118,19 @@ static void PrintAddr(void *p)
102} 118}
103 119
104 120
105#define PRINT_ALLOC(name, cnt, size, ptr) \ 121#define PRINT_REALLOC(name, cnt, size, ptr) { \
122 Print(name " "); \
123 if (!ptr) PrintDec(cnt++, 10); \
124 PrintHex(size, 10); \
125 PrintAddr(ptr); \
126 PrintLn(); }
127
128#define PRINT_ALLOC(name, cnt, size, ptr) { \
106 Print(name " "); \ 129 Print(name " "); \
107 PrintDec(cnt++, 10); \ 130 PrintDec(cnt++, 10); \
108 PrintHex(size, 10); \ 131 PrintHex(size, 10); \
109 PrintAddr(ptr); \ 132 PrintAddr(ptr); \
110 PrintLn(); 133 PrintLn(); }
111 134
112#define PRINT_FREE(name, cnt, ptr) if (ptr) { \ 135#define PRINT_FREE(name, cnt, ptr) if (ptr) { \
113 Print(name " "); \ 136 Print(name " "); \
@@ -117,7 +140,9 @@ static void PrintAddr(void *p)
117 140
118#else 141#else
119 142
143#ifdef _WIN32
120#define PRINT_ALLOC(name, cnt, size, ptr) 144#define PRINT_ALLOC(name, cnt, size, ptr)
145#endif
121#define PRINT_FREE(name, cnt, ptr) 146#define PRINT_FREE(name, cnt, ptr)
122#define Print(s) 147#define Print(s)
123#define PrintLn() 148#define PrintLn()
@@ -127,16 +152,31 @@ static void PrintAddr(void *p)
127#endif 152#endif
128 153
129 154
155/*
156by specification:
157 malloc(non_NULL, 0) : returns NULL or a unique pointer value that can later be successfully passed to free()
158 realloc(NULL, size) : the call is equivalent to malloc(size)
159 realloc(non_NULL, 0) : the call is equivalent to free(ptr)
160
161in main compilers:
162 malloc(0) : returns non_NULL
163 realloc(NULL, 0) : returns non_NULL
164 realloc(non_NULL, 0) : returns NULL
165*/
166
130 167
131void *MyAlloc(size_t size) 168void *MyAlloc(size_t size)
132{ 169{
133 if (size == 0) 170 if (size == 0)
134 return NULL; 171 return NULL;
135 PRINT_ALLOC("Alloc ", g_allocCount, size, NULL); 172 // PRINT_ALLOC("Alloc ", g_allocCount, size, NULL)
136 #ifdef _SZ_ALLOC_DEBUG 173 #ifdef SZ_ALLOC_DEBUG
137 { 174 {
138 void *p = malloc(size); 175 void *p = malloc(size);
139 // PRINT_ALLOC("Alloc ", g_allocCount, size, p); 176 if (p)
177 {
178 PRINT_ALLOC("Alloc ", g_allocCount, size, p)
179 }
140 return p; 180 return p;
141 } 181 }
142 #else 182 #else
@@ -146,33 +186,64 @@ void *MyAlloc(size_t size)
146 186
147void MyFree(void *address) 187void MyFree(void *address)
148{ 188{
149 PRINT_FREE("Free ", g_allocCount, address); 189 PRINT_FREE("Free ", g_allocCount, address)
150 190
151 free(address); 191 free(address);
152} 192}
153 193
194void *MyRealloc(void *address, size_t size)
195{
196 if (size == 0)
197 {
198 MyFree(address);
199 return NULL;
200 }
201 // PRINT_REALLOC("Realloc ", g_allocCount, size, address)
202 #ifdef SZ_ALLOC_DEBUG
203 {
204 void *p = realloc(address, size);
205 if (p)
206 {
207 PRINT_REALLOC("Realloc ", g_allocCount, size, address)
208 }
209 return p;
210 }
211 #else
212 return realloc(address, size);
213 #endif
214}
215
216
154#ifdef _WIN32 217#ifdef _WIN32
155 218
156void *MidAlloc(size_t size) 219void *MidAlloc(size_t size)
157{ 220{
158 if (size == 0) 221 if (size == 0)
159 return NULL; 222 return NULL;
160 223 #ifdef SZ_ALLOC_DEBUG
161 PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, NULL); 224 {
162 225 void *p = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
226 if (p)
227 {
228 PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, p)
229 }
230 return p;
231 }
232 #else
163 return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); 233 return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
234 #endif
164} 235}
165 236
166void MidFree(void *address) 237void MidFree(void *address)
167{ 238{
168 PRINT_FREE("Free-Mid", g_allocCountMid, address); 239 PRINT_FREE("Free-Mid", g_allocCountMid, address)
169 240
170 if (!address) 241 if (!address)
171 return; 242 return;
172 VirtualFree(address, 0, MEM_RELEASE); 243 VirtualFree(address, 0, MEM_RELEASE);
173} 244}
174 245
175#ifdef _7ZIP_LARGE_PAGES 246#ifdef Z7_LARGE_PAGES
176 247
177#ifdef MEM_LARGE_PAGES 248#ifdef MEM_LARGE_PAGES
178 #define MY__MEM_LARGE_PAGES MEM_LARGE_PAGES 249 #define MY__MEM_LARGE_PAGES MEM_LARGE_PAGES
@@ -183,34 +254,35 @@ void MidFree(void *address)
183extern 254extern
184SIZE_T g_LargePageSize; 255SIZE_T g_LargePageSize;
185SIZE_T g_LargePageSize = 0; 256SIZE_T g_LargePageSize = 0;
186typedef SIZE_T (WINAPI *GetLargePageMinimumP)(VOID); 257typedef SIZE_T (WINAPI *Func_GetLargePageMinimum)(VOID);
187 258
188#endif // _7ZIP_LARGE_PAGES 259void SetLargePageSize(void)
189
190void SetLargePageSize()
191{ 260{
192 #ifdef _7ZIP_LARGE_PAGES 261 #ifdef Z7_LARGE_PAGES
193 SIZE_T size; 262 SIZE_T size;
194 GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) 263 const
195 GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); 264 Func_GetLargePageMinimum fn =
196 if (!largePageMinimum) 265 (Func_GetLargePageMinimum) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),
266 "GetLargePageMinimum");
267 if (!fn)
197 return; 268 return;
198 size = largePageMinimum(); 269 size = fn();
199 if (size == 0 || (size & (size - 1)) != 0) 270 if (size == 0 || (size & (size - 1)) != 0)
200 return; 271 return;
201 g_LargePageSize = size; 272 g_LargePageSize = size;
202 #endif 273 #endif
203} 274}
204 275
276#endif // Z7_LARGE_PAGES
205 277
206void *BigAlloc(size_t size) 278void *BigAlloc(size_t size)
207{ 279{
208 if (size == 0) 280 if (size == 0)
209 return NULL; 281 return NULL;
210 282
211 PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL); 283 PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL)
212 284
213 #ifdef _7ZIP_LARGE_PAGES 285 #ifdef Z7_LARGE_PAGES
214 { 286 {
215 SIZE_T ps = g_LargePageSize; 287 SIZE_T ps = g_LargePageSize;
216 if (ps != 0 && ps <= (1 << 30) && size > (ps / 2)) 288 if (ps != 0 && ps <= (1 << 30) && size > (ps / 2))
@@ -220,38 +292,38 @@ void *BigAlloc(size_t size)
220 size2 = (size + ps) & ~ps; 292 size2 = (size + ps) & ~ps;
221 if (size2 >= size) 293 if (size2 >= size)
222 { 294 {
223 void *res = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE); 295 void *p = VirtualAlloc(NULL, size2, MEM_COMMIT | MY__MEM_LARGE_PAGES, PAGE_READWRITE);
224 if (res) 296 if (p)
225 return res; 297 {
298 PRINT_ALLOC("Alloc-BM ", g_allocCountMid, size2, p)
299 return p;
300 }
226 } 301 }
227 } 302 }
228 } 303 }
229 #endif 304 #endif
230 305
231 return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); 306 return MidAlloc(size);
232} 307}
233 308
234void BigFree(void *address) 309void BigFree(void *address)
235{ 310{
236 PRINT_FREE("Free-Big", g_allocCountBig, address); 311 PRINT_FREE("Free-Big", g_allocCountBig, address)
237 312 MidFree(address);
238 if (!address)
239 return;
240 VirtualFree(address, 0, MEM_RELEASE);
241} 313}
242 314
243#endif 315#endif // _WIN32
244 316
245 317
246static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MyAlloc(size); } 318static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MyAlloc(size); }
247static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MyFree(address); } 319static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MyFree(address); }
248const ISzAlloc g_Alloc = { SzAlloc, SzFree }; 320const ISzAlloc g_Alloc = { SzAlloc, SzFree };
249 321
250#ifdef _WIN32 322#ifdef _WIN32
251static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MidAlloc(size); } 323static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return MidAlloc(size); }
252static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MidFree(address); } 324static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) MidFree(address); }
253static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return BigAlloc(size); } 325static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p) return BigAlloc(size); }
254static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); BigFree(address); } 326static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p) BigFree(address); }
255const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree }; 327const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree };
256const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; 328const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree };
257#endif 329#endif
@@ -334,7 +406,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size)
334 void *p; 406 void *p;
335 void *pAligned; 407 void *pAligned;
336 size_t newSize; 408 size_t newSize;
337 UNUSED_VAR(pp); 409 UNUSED_VAR(pp)
338 410
339 /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned 411 /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned
340 block to prevent cache line sharing with another allocated blocks */ 412 block to prevent cache line sharing with another allocated blocks */
@@ -362,7 +434,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size)
362 #else 434 #else
363 435
364 void *p; 436 void *p;
365 UNUSED_VAR(pp); 437 UNUSED_VAR(pp)
366 if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size)) 438 if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size))
367 return NULL; 439 return NULL;
368 440
@@ -377,7 +449,7 @@ static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size)
377 449
378static void SzAlignedFree(ISzAllocPtr pp, void *address) 450static void SzAlignedFree(ISzAllocPtr pp, void *address)
379{ 451{
380 UNUSED_VAR(pp); 452 UNUSED_VAR(pp)
381 #ifndef USE_posix_memalign 453 #ifndef USE_posix_memalign
382 if (address) 454 if (address)
383 MyFree(((void **)address)[-1]); 455 MyFree(((void **)address)[-1]);
@@ -401,7 +473,7 @@ const ISzAlloc g_AlignedAlloc = { SzAlignedAlloc, SzAlignedFree };
401 473
402static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size) 474static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size)
403{ 475{
404 CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); 476 const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt);
405 void *adr; 477 void *adr;
406 void *pAligned; 478 void *pAligned;
407 size_t newSize; 479 size_t newSize;
@@ -447,7 +519,7 @@ static void AlignOffsetAlloc_Free(ISzAllocPtr pp, void *address)
447{ 519{
448 if (address) 520 if (address)
449 { 521 {
450 CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); 522 const CAlignOffsetAlloc *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CAlignOffsetAlloc, vt);
451 PrintLn(); 523 PrintLn();
452 Print("- Aligned Free: "); 524 Print("- Aligned Free: ");
453 PrintLn(); 525 PrintLn();
diff --git a/C/Alloc.h b/C/Alloc.h
index 3be2041..fac5b62 100644
--- a/C/Alloc.h
+++ b/C/Alloc.h
@@ -1,19 +1,32 @@
1/* Alloc.h -- Memory allocation functions 1/* Alloc.h -- Memory allocation functions
22021-07-13 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __COMMON_ALLOC_H 4#ifndef ZIP7_INC_ALLOC_H
5#define __COMMON_ALLOC_H 5#define ZIP7_INC_ALLOC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11/*
12 MyFree(NULL) : is allowed, as free(NULL)
13 MyAlloc(0) : returns NULL : but malloc(0) is allowed to return NULL or non_NULL
14 MyRealloc(NULL, 0) : returns NULL : but realloc(NULL, 0) is allowed to return NULL or non_NULL
15MyRealloc() is similar to realloc() for the following cases:
16 MyRealloc(non_NULL, 0) : returns NULL and always calls MyFree(ptr)
17 MyRealloc(NULL, non_ZERO) : returns NULL, if allocation failed
18 MyRealloc(non_NULL, non_ZERO) : returns NULL, if reallocation failed
19*/
20
11void *MyAlloc(size_t size); 21void *MyAlloc(size_t size);
12void MyFree(void *address); 22void MyFree(void *address);
23void *MyRealloc(void *address, size_t size);
13 24
14#ifdef _WIN32 25#ifdef _WIN32
15 26
27#ifdef Z7_LARGE_PAGES
16void SetLargePageSize(void); 28void SetLargePageSize(void);
29#endif
17 30
18void *MidAlloc(size_t size); 31void *MidAlloc(size_t size);
19void MidFree(void *address); 32void MidFree(void *address);
diff --git a/C/Bcj2.c b/C/Bcj2.c
index c7b9567..7cb57ad 100644
--- a/C/Bcj2.c
+++ b/C/Bcj2.c
@@ -1,29 +1,24 @@
1/* Bcj2.c -- BCJ2 Decoder (Converter for x86 code) 1/* Bcj2.c -- BCJ2 Decoder (Converter for x86 code)
22021-02-09 : Igor Pavlov : Public domain */ 22023-03-01 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "Bcj2.h" 6#include "Bcj2.h"
7#include "CpuArch.h" 7#include "CpuArch.h"
8 8
9#define CProb UInt16
10
11#define kTopValue ((UInt32)1 << 24) 9#define kTopValue ((UInt32)1 << 24)
12#define kNumModelBits 11 10#define kNumBitModelTotalBits 11
13#define kBitModelTotal (1 << kNumModelBits) 11#define kBitModelTotal (1 << kNumBitModelTotalBits)
14#define kNumMoveBits 5 12#define kNumMoveBits 5
15 13
16#define _IF_BIT_0 ttt = *prob; bound = (p->range >> kNumModelBits) * ttt; if (p->code < bound) 14// UInt32 bcj2_stats[256 + 2][2];
17#define _UPDATE_0 p->range = bound; *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
18#define _UPDATE_1 p->range -= bound; p->code -= bound; *prob = (CProb)(ttt - (ttt >> kNumMoveBits));
19 15
20void Bcj2Dec_Init(CBcj2Dec *p) 16void Bcj2Dec_Init(CBcj2Dec *p)
21{ 17{
22 unsigned i; 18 unsigned i;
23 19 p->state = BCJ2_STREAM_RC; // BCJ2_DEC_STATE_OK;
24 p->state = BCJ2_DEC_STATE_OK;
25 p->ip = 0; 20 p->ip = 0;
26 p->temp[3] = 0; 21 p->temp = 0;
27 p->range = 0; 22 p->range = 0;
28 p->code = 0; 23 p->code = 0;
29 for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) 24 for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++)
@@ -32,217 +27,248 @@ void Bcj2Dec_Init(CBcj2Dec *p)
32 27
33SRes Bcj2Dec_Decode(CBcj2Dec *p) 28SRes Bcj2Dec_Decode(CBcj2Dec *p)
34{ 29{
30 UInt32 v = p->temp;
31 // const Byte *src;
35 if (p->range <= 5) 32 if (p->range <= 5)
36 { 33 {
37 p->state = BCJ2_DEC_STATE_OK; 34 UInt32 code = p->code;
35 p->state = BCJ2_DEC_STATE_ERROR; /* for case if we return SZ_ERROR_DATA; */
38 for (; p->range != 5; p->range++) 36 for (; p->range != 5; p->range++)
39 { 37 {
40 if (p->range == 1 && p->code != 0) 38 if (p->range == 1 && code != 0)
41 return SZ_ERROR_DATA; 39 return SZ_ERROR_DATA;
42
43 if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) 40 if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC])
44 { 41 {
45 p->state = BCJ2_STREAM_RC; 42 p->state = BCJ2_STREAM_RC;
46 return SZ_OK; 43 return SZ_OK;
47 } 44 }
48 45 code = (code << 8) | *(p->bufs[BCJ2_STREAM_RC])++;
49 p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; 46 p->code = code;
50 } 47 }
51 48 if (code == 0xffffffff)
52 if (p->code == 0xFFFFFFFF)
53 return SZ_ERROR_DATA; 49 return SZ_ERROR_DATA;
54 50 p->range = 0xffffffff;
55 p->range = 0xFFFFFFFF;
56 } 51 }
57 else if (p->state >= BCJ2_DEC_STATE_ORIG_0) 52 // else
58 { 53 {
59 while (p->state <= BCJ2_DEC_STATE_ORIG_3) 54 unsigned state = p->state;
55 // we check BCJ2_IS_32BIT_STREAM() here instead of check in the main loop
56 if (BCJ2_IS_32BIT_STREAM(state))
60 { 57 {
61 Byte *dest = p->dest; 58 const Byte *cur = p->bufs[state];
62 if (dest == p->destLim) 59 if (cur == p->lims[state])
63 return SZ_OK; 60 return SZ_OK;
64 *dest = p->temp[(size_t)p->state - BCJ2_DEC_STATE_ORIG_0]; 61 p->bufs[state] = cur + 4;
65 p->state++; 62 {
66 p->dest = dest + 1; 63 const UInt32 ip = p->ip + 4;
64 v = GetBe32a(cur) - ip;
65 p->ip = ip;
66 }
67 state = BCJ2_DEC_STATE_ORIG_0;
67 } 68 }
68 } 69 if ((unsigned)(state - BCJ2_DEC_STATE_ORIG_0) < 4)
69
70 /*
71 if (BCJ2_IS_32BIT_STREAM(p->state))
72 {
73 const Byte *cur = p->bufs[p->state];
74 if (cur == p->lims[p->state])
75 return SZ_OK;
76 p->bufs[p->state] = cur + 4;
77
78 { 70 {
79 UInt32 val; 71 Byte *dest = p->dest;
80 Byte *dest; 72 for (;;)
81 SizeT rem;
82
83 p->ip += 4;
84 val = GetBe32(cur) - p->ip;
85 dest = p->dest;
86 rem = p->destLim - dest;
87 if (rem < 4)
88 { 73 {
89 SizeT i; 74 if (dest == p->destLim)
90 SetUi32(p->temp, val); 75 {
91 for (i = 0; i < rem; i++) 76 p->state = state;
92 dest[i] = p->temp[i]; 77 p->temp = v;
93 p->dest = dest + rem; 78 return SZ_OK;
94 p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; 79 }
95 return SZ_OK; 80 *dest++ = (Byte)v;
81 p->dest = dest;
82 if (++state == BCJ2_DEC_STATE_ORIG_3 + 1)
83 break;
84 v >>= 8;
96 } 85 }
97 SetUi32(dest, val);
98 p->temp[3] = (Byte)(val >> 24);
99 p->dest = dest + 4;
100 p->state = BCJ2_DEC_STATE_OK;
101 } 86 }
102 } 87 }
103 */
104 88
89 // src = p->bufs[BCJ2_STREAM_MAIN];
105 for (;;) 90 for (;;)
106 { 91 {
92 /*
107 if (BCJ2_IS_32BIT_STREAM(p->state)) 93 if (BCJ2_IS_32BIT_STREAM(p->state))
108 p->state = BCJ2_DEC_STATE_OK; 94 p->state = BCJ2_DEC_STATE_OK;
109 else 95 else
96 */
110 { 97 {
111 if (p->range < kTopValue) 98 if (p->range < kTopValue)
112 { 99 {
113 if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC]) 100 if (p->bufs[BCJ2_STREAM_RC] == p->lims[BCJ2_STREAM_RC])
114 { 101 {
115 p->state = BCJ2_STREAM_RC; 102 p->state = BCJ2_STREAM_RC;
103 p->temp = v;
116 return SZ_OK; 104 return SZ_OK;
117 } 105 }
118 p->range <<= 8; 106 p->range <<= 8;
119 p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; 107 p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++;
120 } 108 }
121
122 { 109 {
123 const Byte *src = p->bufs[BCJ2_STREAM_MAIN]; 110 const Byte *src = p->bufs[BCJ2_STREAM_MAIN];
124 const Byte *srcLim; 111 const Byte *srcLim;
125 Byte *dest; 112 Byte *dest = p->dest;
126 SizeT num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src);
127
128 if (num == 0)
129 { 113 {
130 p->state = BCJ2_STREAM_MAIN; 114 const SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - src);
131 return SZ_OK; 115 SizeT num = (SizeT)(p->destLim - dest);
116 if (num >= rem)
117 num = rem;
118 #define NUM_ITERS 4
119 #if (NUM_ITERS & (NUM_ITERS - 1)) == 0
120 num &= ~((SizeT)NUM_ITERS - 1); // if (NUM_ITERS == (1 << x))
121 #else
122 num -= num % NUM_ITERS; // if (NUM_ITERS != (1 << x))
123 #endif
124 srcLim = src + num;
132 } 125 }
133 126
134 dest = p->dest; 127 #define NUM_SHIFT_BITS 24
135 if (num > (SizeT)(p->destLim - dest)) 128 #define ONE_ITER(indx) { \
129 const unsigned b = src[indx]; \
130 *dest++ = (Byte)b; \
131 v = (v << NUM_SHIFT_BITS) | b; \
132 if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \
133 if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \
134 ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \
135 /* ++dest */; /* v = b; */ }
136
137 if (src != srcLim)
138 for (;;)
136 { 139 {
137 num = (SizeT)(p->destLim - dest); 140 /* The dependency chain of 2-cycle for (v) calculation is not big problem here.
138 if (num == 0) 141 But we can remove dependency chain with v = b in the end of loop. */
139 { 142 ONE_ITER(0)
140 p->state = BCJ2_DEC_STATE_ORIG; 143 #if (NUM_ITERS > 1)
141 return SZ_OK; 144 ONE_ITER(1)
142 } 145 #if (NUM_ITERS > 2)
146 ONE_ITER(2)
147 #if (NUM_ITERS > 3)
148 ONE_ITER(3)
149 #if (NUM_ITERS > 4)
150 ONE_ITER(4)
151 #if (NUM_ITERS > 5)
152 ONE_ITER(5)
153 #if (NUM_ITERS > 6)
154 ONE_ITER(6)
155 #if (NUM_ITERS > 7)
156 ONE_ITER(7)
157 #endif
158 #endif
159 #endif
160 #endif
161 #endif
162 #endif
163 #endif
164
165 src += NUM_ITERS;
166 if (src == srcLim)
167 break;
143 } 168 }
144
145 srcLim = src + num;
146 169
147 if (p->temp[3] == 0x0F && (src[0] & 0xF0) == 0x80) 170 if (src == srcLim)
148 *dest = src[0]; 171 #if (NUM_ITERS > 1)
149 else for (;;) 172 for (;;)
173 #endif
150 { 174 {
151 Byte b = *src; 175 #if (NUM_ITERS > 1)
152 *dest = b; 176 if (src == p->lims[BCJ2_STREAM_MAIN] || dest == p->destLim)
153 if (b != 0x0F) 177 #endif
154 { 178 {
155 if ((b & 0xFE) == 0xE8) 179 const SizeT num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]);
156 break; 180 p->bufs[BCJ2_STREAM_MAIN] = src;
157 dest++; 181 p->dest = dest;
158 if (++src != srcLim) 182 p->ip += (UInt32)num;
159 continue; 183 /* state BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */
160 break; 184 p->state =
185 src == p->lims[BCJ2_STREAM_MAIN] ?
186 (unsigned)BCJ2_STREAM_MAIN :
187 (unsigned)BCJ2_DEC_STATE_ORIG;
188 p->temp = v;
189 return SZ_OK;
161 } 190 }
162 dest++; 191 #if (NUM_ITERS > 1)
163 if (++src == srcLim) 192 ONE_ITER(0)
164 break; 193 src++;
165 if ((*src & 0xF0) != 0x80) 194 #endif
166 continue;
167 *dest = *src;
168 break;
169 } 195 }
170 196
171 num = (SizeT)(src - p->bufs[BCJ2_STREAM_MAIN]);
172
173 if (src == srcLim)
174 { 197 {
175 p->temp[3] = src[-1]; 198 const SizeT num = (SizeT)(dest - p->dest);
176 p->bufs[BCJ2_STREAM_MAIN] = src; 199 p->dest = dest; // p->dest += num;
200 p->bufs[BCJ2_STREAM_MAIN] += num; // = src;
177 p->ip += (UInt32)num; 201 p->ip += (UInt32)num;
178 p->dest += num;
179 p->state =
180 p->bufs[BCJ2_STREAM_MAIN] ==
181 p->lims[BCJ2_STREAM_MAIN] ?
182 (unsigned)BCJ2_STREAM_MAIN :
183 (unsigned)BCJ2_DEC_STATE_ORIG;
184 return SZ_OK;
185 } 202 }
186
187 { 203 {
188 UInt32 bound, ttt; 204 UInt32 bound, ttt;
189 CProb *prob; 205 CBcj2Prob *prob; // unsigned index;
190 Byte b = src[0]; 206 /*
191 Byte prev = (Byte)(num == 0 ? p->temp[3] : src[-1]); 207 prob = p->probs + (unsigned)((Byte)v == 0xe8 ?
192 208 2 + (Byte)(v >> 8) :
193 p->temp[3] = b; 209 ((v >> 5) & 1)); // ((Byte)v < 0xe8 ? 0 : 1));
194 p->bufs[BCJ2_STREAM_MAIN] = src + 1; 210 */
195 num++;
196 p->ip += (UInt32)num;
197 p->dest += num;
198
199 prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)prev : (b == 0xE9 ? 1 : 0));
200
201 _IF_BIT_0
202 { 211 {
203 _UPDATE_0 212 const unsigned c = ((v + 0x17) >> 6) & 1;
213 prob = p->probs + (unsigned)
214 (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1));
215 // (Byte)
216 // 8x->0 : e9->1 : xxe8->xx+2
217 // 8x->0x100 : e9->0x101 : xxe8->xx
218 // (((0x100 - (e & ~v)) & (0x100 | (v >> 8))) + (e & v));
219 // (((0x101 + (~e | v)) & (0x100 | (v >> 8))) + (e & v));
220 }
221 ttt = *prob;
222 bound = (p->range >> kNumBitModelTotalBits) * ttt;
223 if (p->code < bound)
224 {
225 // bcj2_stats[prob - p->probs][0]++;
226 p->range = bound;
227 *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
204 continue; 228 continue;
205 } 229 }
206 _UPDATE_1 230 {
207 231 // bcj2_stats[prob - p->probs][1]++;
232 p->range -= bound;
233 p->code -= bound;
234 *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits));
235 }
208 } 236 }
209 } 237 }
210 } 238 }
211
212 { 239 {
213 UInt32 val; 240 /* (v == 0xe8 ? 0 : 1) uses setcc instruction with additional zero register usage in x64 MSVC. */
214 unsigned cj = (p->temp[3] == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; 241 // const unsigned cj = ((Byte)v == 0xe8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP;
242 const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL;
215 const Byte *cur = p->bufs[cj]; 243 const Byte *cur = p->bufs[cj];
216 Byte *dest; 244 Byte *dest;
217 SizeT rem; 245 SizeT rem;
218
219 if (cur == p->lims[cj]) 246 if (cur == p->lims[cj])
220 { 247 {
221 p->state = cj; 248 p->state = cj;
222 break; 249 break;
223 } 250 }
224 251 v = GetBe32a(cur);
225 val = GetBe32(cur);
226 p->bufs[cj] = cur + 4; 252 p->bufs[cj] = cur + 4;
227 253 {
228 p->ip += 4; 254 const UInt32 ip = p->ip + 4;
229 val -= p->ip; 255 v -= ip;
256 p->ip = ip;
257 }
230 dest = p->dest; 258 dest = p->dest;
231 rem = (SizeT)(p->destLim - dest); 259 rem = (SizeT)(p->destLim - dest);
232
233 if (rem < 4) 260 if (rem < 4)
234 { 261 {
235 p->temp[0] = (Byte)val; if (rem > 0) dest[0] = (Byte)val; val >>= 8; 262 if ((unsigned)rem > 0) { dest[0] = (Byte)v; v >>= 8;
236 p->temp[1] = (Byte)val; if (rem > 1) dest[1] = (Byte)val; val >>= 8; 263 if ((unsigned)rem > 1) { dest[1] = (Byte)v; v >>= 8;
237 p->temp[2] = (Byte)val; if (rem > 2) dest[2] = (Byte)val; val >>= 8; 264 if ((unsigned)rem > 2) { dest[2] = (Byte)v; v >>= 8; }}}
238 p->temp[3] = (Byte)val; 265 p->temp = v;
239 p->dest = dest + rem; 266 p->dest = dest + rem;
240 p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem; 267 p->state = BCJ2_DEC_STATE_ORIG_0 + (unsigned)rem;
241 break; 268 break;
242 } 269 }
243 270 SetUi32(dest, v)
244 SetUi32(dest, val); 271 v >>= 24;
245 p->temp[3] = (Byte)(val >> 24);
246 p->dest = dest + 4; 272 p->dest = dest + 4;
247 } 273 }
248 } 274 }
@@ -252,6 +278,13 @@ SRes Bcj2Dec_Decode(CBcj2Dec *p)
252 p->range <<= 8; 278 p->range <<= 8;
253 p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++; 279 p->code = (p->code << 8) | *(p->bufs[BCJ2_STREAM_RC])++;
254 } 280 }
255
256 return SZ_OK; 281 return SZ_OK;
257} 282}
283
284#undef NUM_ITERS
285#undef ONE_ITER
286#undef NUM_SHIFT_BITS
287#undef kTopValue
288#undef kNumBitModelTotalBits
289#undef kBitModelTotal
290#undef kNumMoveBits
diff --git a/C/Bcj2.h b/C/Bcj2.h
index 8824080..4575545 100644
--- a/C/Bcj2.h
+++ b/C/Bcj2.h
@@ -1,8 +1,8 @@
1/* Bcj2.h -- BCJ2 Converter for x86 code 1/* Bcj2.h -- BCJ2 converter for x86 code (Branch CALL/JUMP variant2)
22014-11-10 : Igor Pavlov : Public domain */ 22023-03-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __BCJ2_H 4#ifndef ZIP7_INC_BCJ2_H
5#define __BCJ2_H 5#define ZIP7_INC_BCJ2_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -26,37 +26,68 @@ enum
26 BCJ2_DEC_STATE_ORIG_3, 26 BCJ2_DEC_STATE_ORIG_3,
27 27
28 BCJ2_DEC_STATE_ORIG, 28 BCJ2_DEC_STATE_ORIG,
29 BCJ2_DEC_STATE_OK 29 BCJ2_DEC_STATE_ERROR /* after detected data error */
30}; 30};
31 31
32enum 32enum
33{ 33{
34 BCJ2_ENC_STATE_ORIG = BCJ2_NUM_STREAMS, 34 BCJ2_ENC_STATE_ORIG = BCJ2_NUM_STREAMS,
35 BCJ2_ENC_STATE_OK 35 BCJ2_ENC_STATE_FINISHED /* it's state after fully encoded stream */
36}; 36};
37 37
38 38
39#define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) 39/* #define BCJ2_IS_32BIT_STREAM(s) ((s) == BCJ2_STREAM_CALL || (s) == BCJ2_STREAM_JUMP) */
40#define BCJ2_IS_32BIT_STREAM(s) ((unsigned)((unsigned)(s) - (unsigned)BCJ2_STREAM_CALL) < 2)
40 41
41/* 42/*
42CBcj2Dec / CBcj2Enc 43CBcj2Dec / CBcj2Enc
43bufs sizes: 44bufs sizes:
44 BUF_SIZE(n) = lims[n] - bufs[n] 45 BUF_SIZE(n) = lims[n] - bufs[n]
45bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be mutliply of 4: 46bufs sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP must be multiply of 4:
46 (BUF_SIZE(BCJ2_STREAM_CALL) & 3) == 0 47 (BUF_SIZE(BCJ2_STREAM_CALL) & 3) == 0
47 (BUF_SIZE(BCJ2_STREAM_JUMP) & 3) == 0 48 (BUF_SIZE(BCJ2_STREAM_JUMP) & 3) == 0
48*/ 49*/
49 50
51// typedef UInt32 CBcj2Prob;
52typedef UInt16 CBcj2Prob;
53
54/*
55BCJ2 encoder / decoder internal requirements:
56 - If last bytes of stream contain marker (e8/e8/0f8x), then
57 there is also encoded symbol (0 : no conversion) in RC stream.
58 - One case of overlapped instructions is supported,
59 if last byte of converted instruction is (0f) and next byte is (8x):
60 marker [xx xx xx 0f] 8x
61 then the pair (0f 8x) is treated as marker.
62*/
63
64/* ---------- BCJ2 Decoder ---------- */
65
50/* 66/*
51CBcj2Dec: 67CBcj2Dec:
52dest is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions: 68(dest) is allowed to overlap with bufs[BCJ2_STREAM_MAIN], with the following conditions:
53 bufs[BCJ2_STREAM_MAIN] >= dest && 69 bufs[BCJ2_STREAM_MAIN] >= dest &&
54 bufs[BCJ2_STREAM_MAIN] - dest >= tempReserv + 70 bufs[BCJ2_STREAM_MAIN] - dest >=
55 BUF_SIZE(BCJ2_STREAM_CALL) + 71 BUF_SIZE(BCJ2_STREAM_CALL) +
56 BUF_SIZE(BCJ2_STREAM_JUMP) 72 BUF_SIZE(BCJ2_STREAM_JUMP)
57 tempReserv = 0 : for first call of Bcj2Dec_Decode 73 reserve = bufs[BCJ2_STREAM_MAIN] - dest -
58 tempReserv = 4 : for any other calls of Bcj2Dec_Decode 74 ( BUF_SIZE(BCJ2_STREAM_CALL) +
59 overlap with offset = 1 is not allowed 75 BUF_SIZE(BCJ2_STREAM_JUMP) )
76 and additional conditions:
77 if (it's first call of Bcj2Dec_Decode() after Bcj2Dec_Init())
78 {
79 (reserve != 1) : if (ver < v23.00)
80 }
81 else // if there are more than one calls of Bcj2Dec_Decode() after Bcj2Dec_Init())
82 {
83 (reserve >= 6) : if (ver < v23.00)
84 (reserve >= 4) : if (ver >= v23.00)
85 We need that (reserve) because after first call of Bcj2Dec_Decode(),
86 CBcj2Dec::temp can contain up to 4 bytes for writing to (dest).
87 }
88 (reserve == 0) is allowed, if we decode full stream via single call of Bcj2Dec_Decode().
89 (reserve == 0) also is allowed in case of multi-call, if we use fixed buffers,
90 and (reserve) is calculated from full (final) sizes of all streams before first call.
60*/ 91*/
61 92
62typedef struct 93typedef struct
@@ -68,21 +99,65 @@ typedef struct
68 99
69 unsigned state; /* BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */ 100 unsigned state; /* BCJ2_STREAM_MAIN has more priority than BCJ2_STATE_ORIG */
70 101
71 UInt32 ip; 102 UInt32 ip; /* property of starting base for decoding */
72 Byte temp[4]; 103 UInt32 temp; /* Byte temp[4]; */
73 UInt32 range; 104 UInt32 range;
74 UInt32 code; 105 UInt32 code;
75 UInt16 probs[2 + 256]; 106 CBcj2Prob probs[2 + 256];
76} CBcj2Dec; 107} CBcj2Dec;
77 108
109
110/* Note:
111 Bcj2Dec_Init() sets (CBcj2Dec::ip = 0)
112 if (ip != 0) property is required, the caller must set CBcj2Dec::ip after Bcj2Dec_Init()
113*/
78void Bcj2Dec_Init(CBcj2Dec *p); 114void Bcj2Dec_Init(CBcj2Dec *p);
79 115
80/* Returns: SZ_OK or SZ_ERROR_DATA */ 116
117/* Bcj2Dec_Decode():
118 returns:
119 SZ_OK
120 SZ_ERROR_DATA : if data in 5 starting bytes of BCJ2_STREAM_RC stream are not correct
121*/
81SRes Bcj2Dec_Decode(CBcj2Dec *p); 122SRes Bcj2Dec_Decode(CBcj2Dec *p);
82 123
83#define Bcj2Dec_IsFinished(_p_) ((_p_)->code == 0) 124/* To check that decoding was finished you can compare
125 sizes of processed streams with sizes known from another sources.
126 You must do at least one mandatory check from the two following options:
127 - the check for size of processed output (ORIG) stream.
128 - the check for size of processed input (MAIN) stream.
129 additional optional checks:
130 - the checks for processed sizes of all input streams (MAIN, CALL, JUMP, RC)
131 - the checks Bcj2Dec_IsMaybeFinished*()
132 also before actual decoding you can check that the
133 following condition is met for stream sizes:
134 ( size(ORIG) == size(MAIN) + size(CALL) + size(JUMP) )
135*/
84 136
137/* (state == BCJ2_STREAM_MAIN) means that decoder is ready for
138 additional input data in BCJ2_STREAM_MAIN stream.
139 Note that (state == BCJ2_STREAM_MAIN) is allowed for non-finished decoding.
140*/
141#define Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) ((_p_)->state == BCJ2_STREAM_MAIN)
85 142
143/* if the stream decoding was finished correctly, then range decoder
144 part of CBcj2Dec also was finished, and then (CBcj2Dec::code == 0).
145 Note that (CBcj2Dec::code == 0) is allowed for non-finished decoding.
146*/
147#define Bcj2Dec_IsMaybeFinished_code(_p_) ((_p_)->code == 0)
148
149/* use Bcj2Dec_IsMaybeFinished() only as additional check
150 after at least one mandatory check from the two following options:
151 - the check for size of processed output (ORIG) stream.
152 - the check for size of processed input (MAIN) stream.
153*/
154#define Bcj2Dec_IsMaybeFinished(_p_) ( \
155 Bcj2Dec_IsMaybeFinished_state_MAIN(_p_) && \
156 Bcj2Dec_IsMaybeFinished_code(_p_))
157
158
159
160/* ---------- BCJ2 Encoder ---------- */
86 161
87typedef enum 162typedef enum
88{ 163{
@@ -91,6 +166,91 @@ typedef enum
91 BCJ2_ENC_FINISH_MODE_END_STREAM 166 BCJ2_ENC_FINISH_MODE_END_STREAM
92} EBcj2Enc_FinishMode; 167} EBcj2Enc_FinishMode;
93 168
169/*
170 BCJ2_ENC_FINISH_MODE_CONTINUE:
171 process non finished encoding.
172 It notifies the encoder that additional further calls
173 can provide more input data (src) than provided by current call.
174 In that case the CBcj2Enc encoder still can move (src) pointer
175 up to (srcLim), but CBcj2Enc encoder can store some of the last
176 processed bytes (up to 4 bytes) from src to internal CBcj2Enc::temp[] buffer.
177 at return:
178 (CBcj2Enc::src will point to position that includes
179 processed data and data copied to (temp[]) buffer)
180 That data from (temp[]) buffer will be used in further calls.
181
182 BCJ2_ENC_FINISH_MODE_END_BLOCK:
183 finish encoding of current block (ended at srcLim) without RC flushing.
184 at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_ORIG) &&
185 CBcj2Enc::src == CBcj2Enc::srcLim)
186 : it shows that block encoding was finished. And the encoder is
187 ready for new (src) data or for stream finish operation.
188 finished block means
189 {
190 CBcj2Enc has completed block encoding up to (srcLim).
191 (1 + 4 bytes) or (2 + 4 bytes) CALL/JUMP cortages will
192 not cross block boundary at (srcLim).
193 temporary CBcj2Enc buffer for (ORIG) src data is empty.
194 3 output uncompressed streams (MAIN, CALL, JUMP) were flushed.
195 RC stream was not flushed. And RC stream will cross block boundary.
196 }
197 Note: some possible implementation of BCJ2 encoder could
198 write branch marker (e8/e8/0f8x) in one call of Bcj2Enc_Encode(),
199 and it could calculate symbol for RC in another call of Bcj2Enc_Encode().
200 BCJ2 encoder uses ip/fileIp/fileSize/relatLimit values to calculate RC symbol.
201 And these CBcj2Enc variables can have different values in different Bcj2Enc_Encode() calls.
202 So caller must finish each block with BCJ2_ENC_FINISH_MODE_END_BLOCK
203 to ensure that RC symbol is calculated and written in proper block.
204
205 BCJ2_ENC_FINISH_MODE_END_STREAM
206 finish encoding of stream (ended at srcLim) fully including RC flushing.
207 at return: if (CBcj2Enc::state == BCJ2_ENC_STATE_FINISHED)
208 : it shows that stream encoding was finished fully,
209 and all output streams were flushed fully.
210 also Bcj2Enc_IsFinished() can be called.
211*/
212
213
214/*
215 32-bit relative offset in JUMP/CALL commands is
216 - (mod 4 GiB) for 32-bit x86 code
217 - signed Int32 for 64-bit x86-64 code
218 BCJ2 encoder also does internal relative to absolute address conversions.
219 And there are 2 possible ways to do it:
220 before v23: we used 32-bit variables and (mod 4 GiB) conversion
221 since v23: we use 64-bit variables and (signed Int32 offset) conversion.
222 The absolute address condition for conversion in v23:
223 ((UInt64)((Int64)ip64 - (Int64)fileIp64 + 5 + (Int32)offset) < (UInt64)fileSize64)
224 note that if (fileSize64 > 2 GiB). there is difference between
225 old (mod 4 GiB) way (v22) and new (signed Int32 offset) way (v23).
226 And new (v23) way is more suitable to encode 64-bit x86-64 code for (fileSize64 > 2 GiB) cases.
227*/
228
229/*
230// for old (v22) way for conversion:
231typedef UInt32 CBcj2Enc_ip_unsigned;
232typedef Int32 CBcj2Enc_ip_signed;
233#define BCJ2_ENC_FileSize_MAX ((UInt32)1 << 31)
234*/
235typedef UInt64 CBcj2Enc_ip_unsigned;
236typedef Int64 CBcj2Enc_ip_signed;
237
238/* maximum size of file that can be used for conversion condition */
239#define BCJ2_ENC_FileSize_MAX ((CBcj2Enc_ip_unsigned)0 - 2)
240
241/* default value of fileSize64_minus1 variable that means
242 that absolute address limitation will not be used */
243#define BCJ2_ENC_FileSizeField_UNLIMITED ((CBcj2Enc_ip_unsigned)0 - 1)
244
245/* calculate value that later can be set to CBcj2Enc::fileSize64_minus1 */
246#define BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize) \
247 ((CBcj2Enc_ip_unsigned)(fileSize) - 1)
248
249/* set CBcj2Enc::fileSize64_minus1 variable from size of file */
250#define Bcj2Enc_SET_FileSize(p, fileSize) \
251 (p)->fileSize64_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(fileSize);
252
253
94typedef struct 254typedef struct
95{ 255{
96 Byte *bufs[BCJ2_NUM_STREAMS]; 256 Byte *bufs[BCJ2_NUM_STREAMS];
@@ -101,45 +261,71 @@ typedef struct
101 unsigned state; 261 unsigned state;
102 EBcj2Enc_FinishMode finishMode; 262 EBcj2Enc_FinishMode finishMode;
103 263
104 Byte prevByte; 264 Byte context;
265 Byte flushRem;
266 Byte isFlushState;
105 267
106 Byte cache; 268 Byte cache;
107 UInt32 range; 269 UInt32 range;
108 UInt64 low; 270 UInt64 low;
109 UInt64 cacheSize; 271 UInt64 cacheSize;
272
273 // UInt32 context; // for marker version, it can include marker flag.
110 274
111 UInt32 ip; 275 /* (ip64) and (fileIp64) correspond to virtual source stream position
112 276 that doesn't include data in temp[] */
113 /* 32-bit ralative offset in JUMP/CALL commands is 277 CBcj2Enc_ip_unsigned ip64; /* current (ip) position */
114 - (mod 4 GB) in 32-bit mode 278 CBcj2Enc_ip_unsigned fileIp64; /* start (ip) position of current file */
115 - signed Int32 in 64-bit mode 279 CBcj2Enc_ip_unsigned fileSize64_minus1; /* size of current file (for conversion limitation) */
116 We use (mod 4 GB) check for fileSize. 280 UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)) : 0 means disable_conversion */
117 Use fileSize up to 2 GB, if you want to support 32-bit and 64-bit code conversion. */ 281 // UInt32 relatExcludeBits;
118 UInt32 fileIp;
119 UInt32 fileSize; /* (fileSize <= ((UInt32)1 << 31)), 0 means no_limit */
120 UInt32 relatLimit; /* (relatLimit <= ((UInt32)1 << 31)), 0 means desable_conversion */
121 282
122 UInt32 tempTarget; 283 UInt32 tempTarget;
123 unsigned tempPos; 284 unsigned tempPos; /* the number of bytes that were copied to temp[] buffer
124 Byte temp[4 * 2]; 285 (tempPos <= 4) outside of Bcj2Enc_Encode() */
125 286 // Byte temp[4]; // for marker version
126 unsigned flushPos; 287 Byte temp[8];
127 288 CBcj2Prob probs[2 + 256];
128 UInt16 probs[2 + 256];
129} CBcj2Enc; 289} CBcj2Enc;
130 290
131void Bcj2Enc_Init(CBcj2Enc *p); 291void Bcj2Enc_Init(CBcj2Enc *p);
132void Bcj2Enc_Encode(CBcj2Enc *p);
133 292
134#define Bcj2Enc_Get_InputData_Size(p) ((SizeT)((p)->srcLim - (p)->src) + (p)->tempPos)
135#define Bcj2Enc_IsFinished(p) ((p)->flushPos == 5)
136 293
294/*
295Bcj2Enc_Encode(): at exit:
296 p->State < BCJ2_NUM_STREAMS : we need more buffer space for output stream
297 (bufs[p->State] == lims[p->State])
298 p->State == BCJ2_ENC_STATE_ORIG : we need more data in input src stream
299 (src == srcLim)
300 p->State == BCJ2_ENC_STATE_FINISHED : after fully encoded stream
301*/
302void Bcj2Enc_Encode(CBcj2Enc *p);
137 303
138#define BCJ2_RELAT_LIMIT_NUM_BITS 26 304/* Bcj2Enc encoder can look ahead for up 4 bytes of source stream.
139#define BCJ2_RELAT_LIMIT ((UInt32)1 << BCJ2_RELAT_LIMIT_NUM_BITS) 305 CBcj2Enc::tempPos : is the number of bytes that were copied from input stream to temp[] buffer.
306 (CBcj2Enc::src) after Bcj2Enc_Encode() is starting position after
307 fully processed data and after data copied to temp buffer.
308 So if the caller needs to get real number of fully processed input
309 bytes (without look ahead data in temp buffer),
310 the caller must subtruct (CBcj2Enc::tempPos) value from processed size
311 value that is calculated based on current (CBcj2Enc::src):
312 cur_processed_pos = Calc_Big_Processed_Pos(enc.src)) -
313 Bcj2Enc_Get_AvailInputSize_in_Temp(&enc);
314*/
315/* get the size of input data that was stored in temp[] buffer: */
316#define Bcj2Enc_Get_AvailInputSize_in_Temp(p) ((p)->tempPos)
140 317
141/* limit for CBcj2Enc::fileSize variable */ 318#define Bcj2Enc_IsFinished(p) ((p)->flushRem == 0)
142#define BCJ2_FileSize_MAX ((UInt32)1 << 31) 319
320/* Note : the decoder supports overlapping of marker (0f 80).
321 But we can eliminate such overlapping cases by setting
322 the limit for relative offset conversion as
323 CBcj2Enc::relatLimit <= (0x0f << 24) == (240 MiB)
324*/
325/* default value for CBcj2Enc::relatLimit */
326#define BCJ2_ENC_RELAT_LIMIT_DEFAULT ((UInt32)0x0f << 24)
327#define BCJ2_ENC_RELAT_LIMIT_MAX ((UInt32)1 << 31)
328// #define BCJ2_RELAT_EXCLUDE_NUM_BITS 5
143 329
144EXTERN_C_END 330EXTERN_C_END
145 331
diff --git a/C/Bcj2Enc.c b/C/Bcj2Enc.c
index 682362a..79460bb 100644
--- a/C/Bcj2Enc.c
+++ b/C/Bcj2Enc.c
@@ -1,60 +1,62 @@
1/* Bcj2Enc.c -- BCJ2 Encoder (Converter for x86 code) 1/* Bcj2Enc.c -- BCJ2 Encoder converter for x86 code (Branch CALL/JUMP variant2)
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6/* #define SHOW_STAT */ 6/* #define SHOW_STAT */
7
8#ifdef SHOW_STAT 7#ifdef SHOW_STAT
9#include <stdio.h> 8#include <stdio.h>
10#define PRF(x) x 9#define PRF2(s) printf("%s ip=%8x tempPos=%d src= %8x\n", s, (unsigned)p->ip64, p->tempPos, (unsigned)(p->srcLim - p->src));
11#else 10#else
12#define PRF(x) 11#define PRF2(s)
13#endif 12#endif
14 13
15#include <string.h>
16
17#include "Bcj2.h" 14#include "Bcj2.h"
18#include "CpuArch.h" 15#include "CpuArch.h"
19 16
20#define CProb UInt16
21
22#define kTopValue ((UInt32)1 << 24) 17#define kTopValue ((UInt32)1 << 24)
23#define kNumModelBits 11 18#define kNumBitModelTotalBits 11
24#define kBitModelTotal (1 << kNumModelBits) 19#define kBitModelTotal (1 << kNumBitModelTotalBits)
25#define kNumMoveBits 5 20#define kNumMoveBits 5
26 21
27void Bcj2Enc_Init(CBcj2Enc *p) 22void Bcj2Enc_Init(CBcj2Enc *p)
28{ 23{
29 unsigned i; 24 unsigned i;
30 25 p->state = BCJ2_ENC_STATE_ORIG;
31 p->state = BCJ2_ENC_STATE_OK;
32 p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; 26 p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
33 27 p->context = 0;
34 p->prevByte = 0; 28 p->flushRem = 5;
35 29 p->isFlushState = 0;
36 p->cache = 0; 30 p->cache = 0;
37 p->range = 0xFFFFFFFF; 31 p->range = 0xffffffff;
38 p->low = 0; 32 p->low = 0;
39 p->cacheSize = 1; 33 p->cacheSize = 1;
40 34 p->ip64 = 0;
41 p->ip = 0; 35 p->fileIp64 = 0;
42 36 p->fileSize64_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED;
43 p->fileIp = 0; 37 p->relatLimit = BCJ2_ENC_RELAT_LIMIT_DEFAULT;
44 p->fileSize = 0; 38 // p->relatExcludeBits = 0;
45 p->relatLimit = BCJ2_RELAT_LIMIT;
46
47 p->tempPos = 0; 39 p->tempPos = 0;
48
49 p->flushPos = 0;
50
51 for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++) 40 for (i = 0; i < sizeof(p->probs) / sizeof(p->probs[0]); i++)
52 p->probs[i] = kBitModelTotal >> 1; 41 p->probs[i] = kBitModelTotal >> 1;
53} 42}
54 43
55static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p) 44// Z7_NO_INLINE
45Z7_FORCE_INLINE
46static BoolInt Bcj2_RangeEnc_ShiftLow(CBcj2Enc *p)
56{ 47{
57 if ((UInt32)p->low < (UInt32)0xFF000000 || (UInt32)(p->low >> 32) != 0) 48 const UInt32 low = (UInt32)p->low;
49 const unsigned high = (unsigned)
50 #if defined(Z7_MSC_VER_ORIGINAL) \
51 && defined(MY_CPU_X86) \
52 && defined(MY_CPU_LE) \
53 && !defined(MY_CPU_64BIT)
54 // we try to rid of __aullshr() call in MSVS-x86
55 (((const UInt32 *)&p->low)[1]); // [1] : for little-endian only
56 #else
57 (p->low >> 32);
58 #endif
59 if (low < (UInt32)0xff000000 || high != 0)
58 { 60 {
59 Byte *buf = p->bufs[BCJ2_STREAM_RC]; 61 Byte *buf = p->bufs[BCJ2_STREAM_RC];
60 do 62 do
@@ -65,247 +67,440 @@ static BoolInt MY_FAST_CALL RangeEnc_ShiftLow(CBcj2Enc *p)
65 p->bufs[BCJ2_STREAM_RC] = buf; 67 p->bufs[BCJ2_STREAM_RC] = buf;
66 return True; 68 return True;
67 } 69 }
68 *buf++ = (Byte)(p->cache + (Byte)(p->low >> 32)); 70 *buf++ = (Byte)(p->cache + high);
69 p->cache = 0xFF; 71 p->cache = 0xff;
70 } 72 }
71 while (--p->cacheSize); 73 while (--p->cacheSize);
72 p->bufs[BCJ2_STREAM_RC] = buf; 74 p->bufs[BCJ2_STREAM_RC] = buf;
73 p->cache = (Byte)((UInt32)p->low >> 24); 75 p->cache = (Byte)(low >> 24);
74 } 76 }
75 p->cacheSize++; 77 p->cacheSize++;
76 p->low = (UInt32)p->low << 8; 78 p->low = low << 8;
77 return False; 79 return False;
78} 80}
79 81
80static void Bcj2Enc_Encode_2(CBcj2Enc *p) 82
81{ 83/*
82 if (BCJ2_IS_32BIT_STREAM(p->state)) 84We can use 2 alternative versions of code:
851) non-marker version:
86 Byte CBcj2Enc::context
87 Byte temp[8];
88 Last byte of marker (e8/e9/[0f]8x) can be written to temp[] buffer.
89 Encoder writes last byte of marker (e8/e9/[0f]8x) to dest, only in conjunction
90 with writing branch symbol to range coder in same Bcj2Enc_Encode_2() call.
91
922) marker version:
93 UInt32 CBcj2Enc::context
94 Byte CBcj2Enc::temp[4];
95 MARKER_FLAG in CBcj2Enc::context shows that CBcj2Enc::context contains finded marker.
96 it's allowed that
97 one call of Bcj2Enc_Encode_2() writes last byte of marker (e8/e9/[0f]8x) to dest,
98 and another call of Bcj2Enc_Encode_2() does offset conversion.
99 So different values of (fileIp) and (fileSize) are possible
100 in these different Bcj2Enc_Encode_2() calls.
101
102Also marker version requires additional if((v & MARKER_FLAG) == 0) check in main loop.
103So we use non-marker version.
104*/
105
106/*
107 Corner cases with overlap in multi-block.
108 before v23: there was one corner case, where converted instruction
109 could start in one sub-stream and finish in next sub-stream.
110 If multi-block (solid) encoding is used,
111 and BCJ2_ENC_FINISH_MODE_END_BLOCK is used for each sub-stream.
112 and (0f) is last byte of previous sub-stream
113 and (8x) is first byte of current sub-stream
114 then (0f 8x) pair is treated as marker by BCJ2 encoder and decoder.
115 BCJ2 encoder can converts 32-bit offset for that (0f 8x) cortage,
116 if that offset meets limit requirements.
117 If encoder allows 32-bit offset conversion for such overlap case,
118 then the data in 3 uncompressed BCJ2 streams for some sub-stream
119 can depend from data of previous sub-stream.
120 That corner case is not big problem, and it's rare case.
121 Since v23.00 we do additional check to prevent conversions in such overlap cases.
122*/
123
124/*
125 Bcj2Enc_Encode_2() output variables at exit:
83 { 126 {
84 Byte *cur = p->bufs[p->state]; 127 if (Bcj2Enc_Encode_2() exits with (p->state == BCJ2_ENC_STATE_ORIG))
85 if (cur == p->lims[p->state]) 128 {
86 return; 129 it means that encoder needs more input data.
87 SetBe32(cur, p->tempTarget); 130 if (p->srcLim == p->src) at exit, then
88 p->bufs[p->state] = cur + 4; 131 {
132 (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM)
133 all input data were read and processed, and we are ready for
134 new input data.
135 }
136 else
137 {
138 (p->srcLim != p->src)
139 (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE)
140 The encoder have found e8/e9/0f_8x marker,
141 and p->src points to last byte of that marker,
142 Bcj2Enc_Encode_2() needs more input data to get totally
143 5 bytes (last byte of marker and 32-bit branch offset)
144 as continuous array starting from p->src.
145 (p->srcLim - p->src < 5) requirement is met after exit.
146 So non-processed resedue from p->src to p->srcLim is always less than 5 bytes.
147 }
148 }
89 } 149 }
150*/
90 151
91 p->state = BCJ2_ENC_STATE_ORIG; 152Z7_NO_INLINE
92 153static void Bcj2Enc_Encode_2(CBcj2Enc *p)
93 for (;;) 154{
155 if (!p->isFlushState)
94 { 156 {
95 if (p->range < kTopValue) 157 const Byte *src;
158 UInt32 v;
96 { 159 {
97 if (RangeEnc_ShiftLow(p)) 160 const unsigned state = p->state;
98 return; 161 if (BCJ2_IS_32BIT_STREAM(state))
99 p->range <<= 8; 162 {
163 Byte *cur = p->bufs[state];
164 if (cur == p->lims[state])
165 return;
166 SetBe32a(cur, p->tempTarget)
167 p->bufs[state] = cur + 4;
168 }
100 } 169 }
170 p->state = BCJ2_ENC_STATE_ORIG; // for main reason of exit
171 src = p->src;
172 v = p->context;
173
174 // #define WRITE_CONTEXT p->context = v; // for marker version
175 #define WRITE_CONTEXT p->context = (Byte)v;
176 #define WRITE_CONTEXT_AND_SRC p->src = src; WRITE_CONTEXT
101 177
178 for (;;)
102 { 179 {
180 // const Byte *src;
181 // UInt32 v;
182 CBcj2Enc_ip_unsigned ip;
183 if (p->range < kTopValue)
184 {
185 // to reduce register pressure and code size: we save and restore local variables.
186 WRITE_CONTEXT_AND_SRC
187 if (Bcj2_RangeEnc_ShiftLow(p))
188 return;
189 p->range <<= 8;
190 src = p->src;
191 v = p->context;
192 }
193 // src = p->src;
194 // #define MARKER_FLAG ((UInt32)1 << 17)
195 // if ((v & MARKER_FLAG) == 0) // for marker version
103 { 196 {
104 const Byte *src = p->src;
105 const Byte *srcLim; 197 const Byte *srcLim;
106 Byte *dest; 198 Byte *dest = p->bufs[BCJ2_STREAM_MAIN];
107 SizeT num = (SizeT)(p->srcLim - src);
108
109 if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE)
110 { 199 {
111 if (num <= 4) 200 const SizeT remSrc = (SizeT)(p->srcLim - src);
112 return; 201 SizeT rem = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest);
113 num -= 4; 202 if (rem >= remSrc)
203 rem = remSrc;
204 srcLim = src + rem;
114 } 205 }
115 else if (num == 0) 206 /* p->context contains context of previous byte:
116 break; 207 bits [0 : 7] : src[-1], if (src) was changed in this call
117 208 bits [8 : 31] : are undefined for non-marker version
118 dest = p->bufs[BCJ2_STREAM_MAIN]; 209 */
119 if (num > (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest)) 210 // v = p->context;
211 #define NUM_SHIFT_BITS 24
212 #define CONV_FLAG ((UInt32)1 << 16)
213 #define ONE_ITER { \
214 b = src[0]; \
215 *dest++ = (Byte)b; \
216 v = (v << NUM_SHIFT_BITS) | b; \
217 if (((b + (0x100 - 0xe8)) & 0xfe) == 0) break; \
218 if (((v - (((UInt32)0x0f << (NUM_SHIFT_BITS)) + 0x80)) & \
219 ((((UInt32)1 << (4 + NUM_SHIFT_BITS)) - 0x1) << 4)) == 0) break; \
220 src++; if (src == srcLim) { break; } }
221
222 if (src != srcLim)
223 for (;;)
120 { 224 {
121 num = (SizeT)(p->lims[BCJ2_STREAM_MAIN] - dest); 225 /* clang can generate ineffective code with setne instead of two jcc instructions.
122 if (num == 0) 226 we can use 2 iterations and external (unsigned b) to avoid that ineffective code genaration. */
123 { 227 unsigned b;
124 p->state = BCJ2_STREAM_MAIN; 228 ONE_ITER
125 return; 229 ONE_ITER
126 }
127 } 230 }
128 231
129 srcLim = src + num; 232 ip = p->ip64 + (CBcj2Enc_ip_unsigned)(SizeT)(dest - p->bufs[BCJ2_STREAM_MAIN]);
233 p->bufs[BCJ2_STREAM_MAIN] = dest;
234 p->ip64 = ip;
130 235
131 if (p->prevByte == 0x0F && (src[0] & 0xF0) == 0x80) 236 if (src == srcLim)
132 *dest = src[0];
133 else for (;;)
134 { 237 {
135 Byte b = *src; 238 WRITE_CONTEXT_AND_SRC
136 *dest = b; 239 if (src != p->srcLim)
137 if (b != 0x0F)
138 { 240 {
139 if ((b & 0xFE) == 0xE8) 241 p->state = BCJ2_STREAM_MAIN;
140 break; 242 return;
141 dest++;
142 if (++src != srcLim)
143 continue;
144 break;
145 } 243 }
146 dest++; 244 /* (p->src == p->srcLim)
147 if (++src == srcLim) 245 (p->state == BCJ2_ENC_STATE_ORIG) */
148 break; 246 if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM)
149 if ((*src & 0xF0) != 0x80) 247 return;
150 continue; 248 /* (p->finishMode == BCJ2_ENC_FINISH_MODE_END_STREAM */
151 *dest = *src; 249 // (p->flushRem == 5);
250 p->isFlushState = 1;
152 break; 251 break;
153 } 252 }
154 253 src++;
155 num = (SizeT)(src - p->src); 254 // p->src = src;
156 255 }
157 if (src == srcLim) 256 // ip = p->ip; // for marker version
158 { 257 /* marker was found */
159 p->prevByte = src[-1]; 258 /* (v) contains marker that was found:
160 p->bufs[BCJ2_STREAM_MAIN] = dest; 259 bits [NUM_SHIFT_BITS : NUM_SHIFT_BITS + 7]
161 p->src = src; 260 : value of src[-2] : xx/xx/0f
162 p->ip += (UInt32)num; 261 bits [0 : 7] : value of src[-1] : e8/e9/8x
163 continue; 262 */
164 } 263 {
165
166 { 264 {
167 Byte context = (Byte)(num == 0 ? p->prevByte : src[-1]); 265 #if NUM_SHIFT_BITS != 24
168 BoolInt needConvert; 266 v &= ~(UInt32)CONV_FLAG;
169 267 #endif
170 p->bufs[BCJ2_STREAM_MAIN] = dest + 1; 268 // UInt32 relat = 0;
171 p->ip += (UInt32)num + 1;
172 src++;
173
174 needConvert = False;
175
176 if ((SizeT)(p->srcLim - src) >= 4) 269 if ((SizeT)(p->srcLim - src) >= 4)
177 { 270 {
178 UInt32 relatVal = GetUi32(src); 271 /*
179 if ((p->fileSize == 0 || (UInt32)(p->ip + 4 + relatVal - p->fileIp) < p->fileSize) 272 if (relat != 0 || (Byte)v != 0xe8)
180 && ((relatVal + p->relatLimit) >> 1) < p->relatLimit) 273 BoolInt isBigOffset = True;
181 needConvert = True; 274 */
275 const UInt32 relat = GetUi32(src);
276 /*
277 #define EXCLUDE_FLAG ((UInt32)1 << 4)
278 #define NEED_CONVERT(rel) ((((rel) + EXCLUDE_FLAG) & (0 - EXCLUDE_FLAG * 2)) != 0)
279 if (p->relatExcludeBits != 0)
280 {
281 const UInt32 flag = (UInt32)1 << (p->relatExcludeBits - 1);
282 isBigOffset = (((relat + flag) & (0 - flag * 2)) != 0);
283 }
284 // isBigOffset = False; // for debug
285 */
286 ip -= p->fileIp64;
287 // Use the following if check, if (ip) is 64-bit:
288 if (ip > (((v + 0x20) >> 5) & 1)) // 23.00 : we eliminate milti-block overlap for (Of 80) and (e8/e9)
289 if ((CBcj2Enc_ip_unsigned)((CBcj2Enc_ip_signed)ip + 4 + (Int32)relat) <= p->fileSize64_minus1)
290 if (((UInt32)(relat + p->relatLimit) >> 1) < p->relatLimit)
291 v |= CONV_FLAG;
182 } 292 }
183 293 else if (p->finishMode == BCJ2_ENC_FINISH_MODE_CONTINUE)
184 { 294 {
185 UInt32 bound; 295 // (p->srcLim - src < 4)
186 unsigned ttt; 296 // /*
187 Byte b = src[-1]; 297 // for non-marker version
188 CProb *prob = p->probs + (unsigned)(b == 0xE8 ? 2 + (unsigned)context : (b == 0xE9 ? 1 : 0)); 298 p->ip64--; // p->ip = ip - 1;
189 299 p->bufs[BCJ2_STREAM_MAIN]--;
190 ttt = *prob; 300 src--;
191 bound = (p->range >> kNumModelBits) * ttt; 301 v >>= NUM_SHIFT_BITS;
192 302 // (0 < p->srcLim - p->src <= 4)
193 if (!needConvert) 303 // */
304 // v |= MARKER_FLAG; // for marker version
305 /* (p->state == BCJ2_ENC_STATE_ORIG) */
306 WRITE_CONTEXT_AND_SRC
307 return;
308 }
309 {
310 const unsigned c = ((v + 0x17) >> 6) & 1;
311 CBcj2Prob *prob = p->probs + (unsigned)
312 (((0 - c) & (Byte)(v >> NUM_SHIFT_BITS)) + c + ((v >> 5) & 1));
313 /*
314 ((Byte)v == 0xe8 ? 2 + ((Byte)(v >> 8)) :
315 ((Byte)v < 0xe8 ? 0 : 1)); // ((v >> 5) & 1));
316 */
317 const unsigned ttt = *prob;
318 const UInt32 bound = (p->range >> kNumBitModelTotalBits) * ttt;
319 if ((v & CONV_FLAG) == 0)
194 { 320 {
321 // static int yyy = 0; yyy++; printf("\n!needConvert = %d\n", yyy);
322 // v = (Byte)v; // for marker version
195 p->range = bound; 323 p->range = bound;
196 *prob = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); 324 *prob = (CBcj2Prob)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
197 p->src = src; 325 // WRITE_CONTEXT_AND_SRC
198 p->prevByte = b;
199 continue; 326 continue;
200 } 327 }
201
202 p->low += bound; 328 p->low += bound;
203 p->range -= bound; 329 p->range -= bound;
204 *prob = (CProb)(ttt - (ttt >> kNumMoveBits)); 330 *prob = (CBcj2Prob)(ttt - (ttt >> kNumMoveBits));
205 331 }
332 // p->context = src[3];
333 {
334 // const unsigned cj = ((Byte)v == 0xe8 ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP);
335 const unsigned cj = (((v + 0x57) >> 6) & 1) + BCJ2_STREAM_CALL;
336 ip = p->ip64;
337 v = GetUi32(src); // relat
338 ip += 4;
339 p->ip64 = ip;
340 src += 4;
341 // p->src = src;
206 { 342 {
207 UInt32 relatVal = GetUi32(src); 343 const UInt32 absol = (UInt32)ip + v;
208 UInt32 absVal; 344 Byte *cur = p->bufs[cj];
209 p->ip += 4; 345 v >>= 24;
210 absVal = p->ip + relatVal; 346 // WRITE_CONTEXT
211 p->prevByte = src[3]; 347 if (cur == p->lims[cj])
212 src += 4;
213 p->src = src;
214 { 348 {
215 unsigned cj = (b == 0xE8) ? BCJ2_STREAM_CALL : BCJ2_STREAM_JUMP; 349 p->state = cj;
216 Byte *cur = p->bufs[cj]; 350 p->tempTarget = absol;
217 if (cur == p->lims[cj]) 351 WRITE_CONTEXT_AND_SRC
218 { 352 return;
219 p->state = cj;
220 p->tempTarget = absVal;
221 return;
222 }
223 SetBe32(cur, absVal);
224 p->bufs[cj] = cur + 4;
225 } 353 }
354 SetBe32a(cur, absol)
355 p->bufs[cj] = cur + 4;
226 } 356 }
227 } 357 }
228 } 358 }
229 } 359 }
230 } 360 } // end of loop
231 } 361 }
232 362
233 if (p->finishMode != BCJ2_ENC_FINISH_MODE_END_STREAM) 363 for (; p->flushRem != 0; p->flushRem--)
234 return; 364 if (Bcj2_RangeEnc_ShiftLow(p))
235
236 for (; p->flushPos < 5; p->flushPos++)
237 if (RangeEnc_ShiftLow(p))
238 return; 365 return;
239 p->state = BCJ2_ENC_STATE_OK; 366 p->state = BCJ2_ENC_STATE_FINISHED;
240} 367}
241 368
242 369
370/*
371BCJ2 encoder needs look ahead for up to 4 bytes in (src) buffer.
372So base function Bcj2Enc_Encode_2()
373 in BCJ2_ENC_FINISH_MODE_CONTINUE mode can return with
374 (p->state == BCJ2_ENC_STATE_ORIG && p->src < p->srcLim)
375Bcj2Enc_Encode() solves that look ahead problem by using p->temp[] buffer.
376 so if (p->state == BCJ2_ENC_STATE_ORIG) after Bcj2Enc_Encode(),
377 then (p->src == p->srcLim).
378 And the caller's code is simpler with Bcj2Enc_Encode().
379*/
380
381Z7_NO_INLINE
243void Bcj2Enc_Encode(CBcj2Enc *p) 382void Bcj2Enc_Encode(CBcj2Enc *p)
244{ 383{
245 PRF(printf("\n")); 384 PRF2("\n----")
246 PRF(printf("---- ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src));
247
248 if (p->tempPos != 0) 385 if (p->tempPos != 0)
249 { 386 {
387 /* extra: number of bytes that were copied from (src) to (temp) buffer in this call */
250 unsigned extra = 0; 388 unsigned extra = 0;
251 389 /* We will touch only minimal required number of bytes in input (src) stream.
390 So we will add input bytes from (src) stream to temp[] with step of 1 byte.
391 We don't add new bytes to temp[] before Bcj2Enc_Encode_2() call
392 in first loop iteration because
393 - previous call of Bcj2Enc_Encode() could use another (finishMode),
394 - previous call could finish with (p->state != BCJ2_ENC_STATE_ORIG).
395 the case with full temp[] buffer (p->tempPos == 4) is possible here.
396 */
252 for (;;) 397 for (;;)
253 { 398 {
399 // (0 < p->tempPos <= 5) // in non-marker version
400 /* p->src : the current src data position including extra bytes
401 that were copied to temp[] buffer in this call */
254 const Byte *src = p->src; 402 const Byte *src = p->src;
255 const Byte *srcLim = p->srcLim; 403 const Byte *srcLim = p->srcLim;
256 EBcj2Enc_FinishMode finishMode = p->finishMode; 404 const EBcj2Enc_FinishMode finishMode = p->finishMode;
257
258 p->src = p->temp;
259 p->srcLim = p->temp + p->tempPos;
260 if (src != srcLim) 405 if (src != srcLim)
406 {
407 /* if there are some src data after the data copied to temp[],
408 then we use MODE_CONTINUE for temp data */
261 p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; 409 p->finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
262 410 }
263 PRF(printf(" ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); 411 p->src = p->temp;
264 412 p->srcLim = p->temp + p->tempPos;
413 PRF2(" ")
265 Bcj2Enc_Encode_2(p); 414 Bcj2Enc_Encode_2(p);
266
267 { 415 {
268 unsigned num = (unsigned)(p->src - p->temp); 416 const unsigned num = (unsigned)(p->src - p->temp);
269 unsigned tempPos = p->tempPos - num; 417 const unsigned tempPos = p->tempPos - num;
270 unsigned i; 418 unsigned i;
271 p->tempPos = tempPos; 419 p->tempPos = tempPos;
272 for (i = 0; i < tempPos; i++) 420 for (i = 0; i < tempPos; i++)
273 p->temp[i] = p->temp[(size_t)i + num]; 421 p->temp[i] = p->temp[(SizeT)i + num];
274 422 // tempPos : number of bytes in temp buffer
275 p->src = src; 423 p->src = src;
276 p->srcLim = srcLim; 424 p->srcLim = srcLim;
277 p->finishMode = finishMode; 425 p->finishMode = finishMode;
278 426 if (p->state != BCJ2_ENC_STATE_ORIG)
279 if (p->state != BCJ2_ENC_STATE_ORIG || src == srcLim) 427 {
428 // (p->tempPos <= 4) // in non-marker version
429 /* if (the reason of exit from Bcj2Enc_Encode_2()
430 is not BCJ2_ENC_STATE_ORIG),
431 then we exit from Bcj2Enc_Encode() with same reason */
432 // optional code begin : we rollback (src) and tempPos, if it's possible:
433 if (extra >= tempPos)
434 extra = tempPos;
435 p->src = src - extra;
436 p->tempPos = tempPos - extra;
437 // optional code end : rollback of (src) and tempPos
280 return; 438 return;
281 439 }
440 /* (p->tempPos <= 4)
441 (p->state == BCJ2_ENC_STATE_ORIG)
442 so encoder needs more data than in temp[] */
443 if (src == srcLim)
444 return; // src buffer has no more input data.
445 /* (src != srcLim)
446 so we can provide more input data from src for Bcj2Enc_Encode_2() */
282 if (extra >= tempPos) 447 if (extra >= tempPos)
283 { 448 {
284 p->src = src - tempPos; 449 /* (extra >= tempPos) means that temp buffer contains
450 only data from src buffer of this call.
451 So now we can encode without temp buffer */
452 p->src = src - tempPos; // rollback (src)
285 p->tempPos = 0; 453 p->tempPos = 0;
286 break; 454 break;
287 } 455 }
288 456 // we append one additional extra byte from (src) to temp[] buffer:
289 p->temp[tempPos] = src[0]; 457 p->temp[tempPos] = *src;
290 p->tempPos = tempPos + 1; 458 p->tempPos = tempPos + 1;
459 // (0 < p->tempPos <= 5) // in non-marker version
291 p->src = src + 1; 460 p->src = src + 1;
292 extra++; 461 extra++;
293 } 462 }
294 } 463 }
295 } 464 }
296 465
297 PRF(printf("++++ ip = %8d tempPos = %8d src = %8d\n", p->ip, p->tempPos, p->srcLim - p->src)); 466 PRF2("++++")
298 467 // (p->tempPos == 0)
299 Bcj2Enc_Encode_2(p); 468 Bcj2Enc_Encode_2(p);
469 PRF2("====")
300 470
301 if (p->state == BCJ2_ENC_STATE_ORIG) 471 if (p->state == BCJ2_ENC_STATE_ORIG)
302 { 472 {
303 const Byte *src = p->src; 473 const Byte *src = p->src;
304 unsigned rem = (unsigned)(p->srcLim - src); 474 const Byte *srcLim = p->srcLim;
305 unsigned i; 475 const unsigned rem = (unsigned)(srcLim - src);
306 for (i = 0; i < rem; i++) 476 /* (rem <= 4) here.
307 p->temp[i] = src[i]; 477 if (p->src != p->srcLim), then
308 p->tempPos = rem; 478 - we copy non-processed bytes from (p->src) to temp[] buffer,
309 p->src = src + rem; 479 - we set p->src equal to p->srcLim.
480 */
481 if (rem)
482 {
483 unsigned i = 0;
484 p->src = srcLim;
485 p->tempPos = rem;
486 // (0 < p->tempPos <= 4)
487 do
488 p->temp[i] = src[i];
489 while (++i != rem);
490 }
491 // (p->tempPos <= 4)
492 // (p->src == p->srcLim)
310 } 493 }
311} 494}
495
496#undef PRF2
497#undef CONV_FLAG
498#undef MARKER_FLAG
499#undef WRITE_CONTEXT
500#undef WRITE_CONTEXT_AND_SRC
501#undef ONE_ITER
502#undef NUM_SHIFT_BITS
503#undef kTopValue
504#undef kNumBitModelTotalBits
505#undef kBitModelTotal
506#undef kNumMoveBits
diff --git a/C/Blake2.h b/C/Blake2.h
index 14f3cb6..7235235 100644
--- a/C/Blake2.h
+++ b/C/Blake2.h
@@ -1,9 +1,9 @@
1/* Blake2.h -- BLAKE2 Hash 1/* Blake2.h -- BLAKE2 Hash
22015-06-30 : Igor Pavlov : Public domain 22023-03-04 : Igor Pavlov : Public domain
32015 : Samuel Neves : Public domain */ 32015 : Samuel Neves : Public domain */
4 4
5#ifndef __BLAKE2_H 5#ifndef ZIP7_INC_BLAKE2_H
6#define __BLAKE2_H 6#define ZIP7_INC_BLAKE2_H
7 7
8#include "7zTypes.h" 8#include "7zTypes.h"
9 9
diff --git a/C/Blake2s.c b/C/Blake2s.c
index 3c56a8b..2a84b57 100644
--- a/C/Blake2s.c
+++ b/C/Blake2s.c
@@ -1,7 +1,9 @@
1/* Blake2s.c -- BLAKE2s and BLAKE2sp Hash 1/* Blake2s.c -- BLAKE2s and BLAKE2sp Hash
22021-02-09 : Igor Pavlov : Public domain 22023-03-04 : Igor Pavlov : Public domain
32015 : Samuel Neves : Public domain */ 32015 : Samuel Neves : Public domain */
4 4
5#include "Precomp.h"
6
5#include <string.h> 7#include <string.h>
6 8
7#include "Blake2.h" 9#include "Blake2.h"
@@ -78,21 +80,21 @@ static void Blake2s_Compress(CBlake2s *p)
78 a += b + m[sigma[2*i+1]]; d ^= a; d = rotr32(d, 8); c += d; b ^= c; b = rotr32(b, 7); \ 80 a += b + m[sigma[2*i+1]]; d ^= a; d = rotr32(d, 8); c += d; b ^= c; b = rotr32(b, 7); \
79 81
80 #define R(r) \ 82 #define R(r) \
81 G(r,0,v[ 0],v[ 4],v[ 8],v[12]); \ 83 G(r,0,v[ 0],v[ 4],v[ 8],v[12]) \
82 G(r,1,v[ 1],v[ 5],v[ 9],v[13]); \ 84 G(r,1,v[ 1],v[ 5],v[ 9],v[13]) \
83 G(r,2,v[ 2],v[ 6],v[10],v[14]); \ 85 G(r,2,v[ 2],v[ 6],v[10],v[14]) \
84 G(r,3,v[ 3],v[ 7],v[11],v[15]); \ 86 G(r,3,v[ 3],v[ 7],v[11],v[15]) \
85 G(r,4,v[ 0],v[ 5],v[10],v[15]); \ 87 G(r,4,v[ 0],v[ 5],v[10],v[15]) \
86 G(r,5,v[ 1],v[ 6],v[11],v[12]); \ 88 G(r,5,v[ 1],v[ 6],v[11],v[12]) \
87 G(r,6,v[ 2],v[ 7],v[ 8],v[13]); \ 89 G(r,6,v[ 2],v[ 7],v[ 8],v[13]) \
88 G(r,7,v[ 3],v[ 4],v[ 9],v[14]); \ 90 G(r,7,v[ 3],v[ 4],v[ 9],v[14]) \
89 91
90 { 92 {
91 unsigned r; 93 unsigned r;
92 for (r = 0; r < BLAKE2S_NUM_ROUNDS; r++) 94 for (r = 0; r < BLAKE2S_NUM_ROUNDS; r++)
93 { 95 {
94 const Byte *sigma = k_Blake2s_Sigma[r]; 96 const Byte *sigma = k_Blake2s_Sigma[r];
95 R(r); 97 R(r)
96 } 98 }
97 /* R(0); R(1); R(2); R(3); R(4); R(5); R(6); R(7); R(8); R(9); */ 99 /* R(0); R(1); R(2); R(3); R(4); R(5); R(6); R(7); R(8); R(9); */
98 } 100 }
@@ -130,7 +132,7 @@ static void Blake2s_Update(CBlake2s *p, const Byte *data, size_t size)
130 } 132 }
131 133
132 memcpy(p->buf + pos, data, rem); 134 memcpy(p->buf + pos, data, rem);
133 Blake2s_Increment_Counter(S, BLAKE2S_BLOCK_SIZE); 135 Blake2s_Increment_Counter(S, BLAKE2S_BLOCK_SIZE)
134 Blake2s_Compress(p); 136 Blake2s_Compress(p);
135 p->bufPos = 0; 137 p->bufPos = 0;
136 data += rem; 138 data += rem;
@@ -143,13 +145,15 @@ static void Blake2s_Final(CBlake2s *p, Byte *digest)
143{ 145{
144 unsigned i; 146 unsigned i;
145 147
146 Blake2s_Increment_Counter(S, (UInt32)p->bufPos); 148 Blake2s_Increment_Counter(S, (UInt32)p->bufPos)
147 Blake2s_Set_LastBlock(p); 149 Blake2s_Set_LastBlock(p)
148 memset(p->buf + p->bufPos, 0, BLAKE2S_BLOCK_SIZE - p->bufPos); 150 memset(p->buf + p->bufPos, 0, BLAKE2S_BLOCK_SIZE - p->bufPos);
149 Blake2s_Compress(p); 151 Blake2s_Compress(p);
150 152
151 for (i = 0; i < 8; i++) 153 for (i = 0; i < 8; i++)
152 SetUi32(digest + sizeof(p->h[i]) * i, p->h[i]); 154 {
155 SetUi32(digest + sizeof(p->h[i]) * i, p->h[i])
156 }
153} 157}
154 158
155 159
@@ -242,3 +246,5 @@ void Blake2sp_Final(CBlake2sp *p, Byte *digest)
242 246
243 Blake2s_Final(&R, digest); 247 Blake2s_Final(&R, digest);
244} 248}
249
250#undef rotr32
diff --git a/C/Bra.c b/C/Bra.c
index 3b854d9..22e0e47 100644
--- a/C/Bra.c
+++ b/C/Bra.c
@@ -1,230 +1,420 @@
1/* Bra.c -- Converters for RISC code 1/* Bra.c -- Branch converters for RISC code
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "CpuArch.h"
7#include "Bra.h" 6#include "Bra.h"
7#include "CpuArch.h"
8#include "RotateDefs.h"
9
10#if defined(MY_CPU_SIZEOF_POINTER) \
11 && ( MY_CPU_SIZEOF_POINTER == 4 \
12 || MY_CPU_SIZEOF_POINTER == 8)
13 #define BR_CONV_USE_OPT_PC_PTR
14#endif
15
16#ifdef BR_CONV_USE_OPT_PC_PTR
17#define BR_PC_INIT pc -= (UInt32)(SizeT)p;
18#define BR_PC_GET (pc + (UInt32)(SizeT)p)
19#else
20#define BR_PC_INIT pc += (UInt32)size;
21#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p))
22// #define BR_PC_INIT
23// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data))
24#endif
25
26#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c;
27// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c;
28
29#define Z7_BRANCH_CONV(name) z7_BranchConv_ ## name
30
31#define Z7_BRANCH_FUNC_MAIN(name) \
32static \
33Z7_FORCE_INLINE \
34Z7_ATTRIB_NO_VECTOR \
35Byte *Z7_BRANCH_CONV(name)(Byte *p, SizeT size, UInt32 pc, int encoding)
8 36
9SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 37#define Z7_BRANCH_FUNC_IMP(name, m, encoding) \
38Z7_NO_INLINE \
39Z7_ATTRIB_NO_VECTOR \
40Byte *m(name)(Byte *data, SizeT size, UInt32 pc) \
41 { return Z7_BRANCH_CONV(name)(data, size, pc, encoding); } \
42
43#ifdef Z7_EXTRACT_ONLY
44#define Z7_BRANCH_FUNCS_IMP(name) \
45 Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0)
46#else
47#define Z7_BRANCH_FUNCS_IMP(name) \
48 Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_DEC, 0) \
49 Z7_BRANCH_FUNC_IMP(name, Z7_BRANCH_CONV_ENC, 1)
50#endif
51
52#if defined(__clang__)
53#define BR_EXTERNAL_FOR
54#define BR_NEXT_ITERATION continue;
55#else
56#define BR_EXTERNAL_FOR for (;;)
57#define BR_NEXT_ITERATION break;
58#endif
59
60#if defined(__clang__) && (__clang_major__ >= 8) \
61 || defined(__GNUC__) && (__GNUC__ >= 1000) \
62 // GCC is not good for __builtin_expect() here
63 /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */
64 // #define Z7_unlikely [[unlikely]]
65 // #define Z7_LIKELY(x) (__builtin_expect((x), 1))
66 #define Z7_UNLIKELY(x) (__builtin_expect((x), 0))
67 // #define Z7_likely [[likely]]
68#else
69 // #define Z7_LIKELY(x) (x)
70 #define Z7_UNLIKELY(x) (x)
71 // #define Z7_likely
72#endif
73
74
75Z7_BRANCH_FUNC_MAIN(ARM64)
10{ 76{
11 Byte *p; 77 // Byte *p = data;
12 const Byte *lim; 78 const Byte *lim;
13 size &= ~(size_t)3; 79 const UInt32 flag = (UInt32)1 << (24 - 4);
14 ip += 4; 80 const UInt32 mask = ((UInt32)1 << 24) - (flag << 1);
15 p = data; 81 size &= ~(SizeT)3;
16 lim = data + size; 82 // if (size == 0) return p;
83 lim = p + size;
84 BR_PC_INIT
85 pc -= 4; // because (p) will point to next instruction
86
87 BR_EXTERNAL_FOR
88 {
89 // Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
90 for (;;)
91 {
92 UInt32 v;
93 if Z7_UNLIKELY(p == lim)
94 return p;
95 v = GetUi32a(p);
96 p += 4;
97 if Z7_UNLIKELY(((v - 0x94000000) & 0xfc000000) == 0)
98 {
99 UInt32 c = BR_PC_GET >> 2;
100 BR_CONVERT_VAL(v, c)
101 v &= 0x03ffffff;
102 v |= 0x94000000;
103 SetUi32a(p - 4, v)
104 BR_NEXT_ITERATION
105 }
106 // v = rotlFixed(v, 8); v += (flag << 8) - 0x90; if Z7_UNLIKELY((v & ((mask << 8) + 0x9f)) == 0)
107 v -= 0x90000000; if Z7_UNLIKELY((v & 0x9f000000) == 0)
108 {
109 UInt32 z, c;
110 // v = rotrFixed(v, 8);
111 v += flag; if Z7_UNLIKELY(v & mask) continue;
112 z = (v & 0xffffffe0) | (v >> 26);
113 c = (BR_PC_GET >> (12 - 3)) & ~(UInt32)7;
114 BR_CONVERT_VAL(z, c)
115 v &= 0x1f;
116 v |= 0x90000000;
117 v |= z << 26;
118 v |= 0x00ffffe0 & ((z & (((flag << 1) - 1))) - flag);
119 SetUi32a(p - 4, v)
120 }
121 }
122 }
123}
124Z7_BRANCH_FUNCS_IMP(ARM64)
17 125
18 if (encoding)
19 126
127Z7_BRANCH_FUNC_MAIN(ARM)
128{
129 // Byte *p = data;
130 const Byte *lim;
131 size &= ~(SizeT)3;
132 lim = p + size;
133 BR_PC_INIT
134 /* in ARM: branch offset is relative to the +2 instructions from current instruction.
135 (p) will point to next instruction */
136 pc += 8 - 4;
137
20 for (;;) 138 for (;;)
21 { 139 {
22 for (;;) 140 for (;;)
23 { 141 {
24 if (p >= lim) 142 if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break;
25 return (SizeT)(p - data); 143 if Z7_UNLIKELY(p >= lim) { return p; } p += 4; if Z7_UNLIKELY(p[-1] == 0xeb) break;
26 p += 4;
27 if (p[-1] == 0xEB)
28 break;
29 } 144 }
30 { 145 {
31 UInt32 v = GetUi32(p - 4); 146 UInt32 v = GetUi32a(p - 4);
32 v <<= 2; 147 UInt32 c = BR_PC_GET >> 2;
33 v += ip + (UInt32)(p - data); 148 BR_CONVERT_VAL(v, c)
34 v >>= 2; 149 v &= 0x00ffffff;
35 v &= 0x00FFFFFF; 150 v |= 0xeb000000;
36 v |= 0xEB000000; 151 SetUi32a(p - 4, v)
37 SetUi32(p - 4, v);
38 } 152 }
39 } 153 }
154}
155Z7_BRANCH_FUNCS_IMP(ARM)
156
40 157
158Z7_BRANCH_FUNC_MAIN(PPC)
159{
160 // Byte *p = data;
161 const Byte *lim;
162 size &= ~(SizeT)3;
163 lim = p + size;
164 BR_PC_INIT
165 pc -= 4; // because (p) will point to next instruction
166
41 for (;;) 167 for (;;)
42 { 168 {
169 UInt32 v;
43 for (;;) 170 for (;;)
44 { 171 {
45 if (p >= lim) 172 if Z7_UNLIKELY(p == lim)
46 return (SizeT)(p - data); 173 return p;
174 // v = GetBe32a(p);
175 v = *(UInt32 *)(void *)p;
47 p += 4; 176 p += 4;
48 if (p[-1] == 0xEB) 177 // if ((v & 0xfc000003) == 0x48000001) break;
49 break; 178 // if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1) break;
179 if Z7_UNLIKELY(
180 ((v - Z7_CONV_BE_TO_NATIVE_CONST32(0x48000001))
181 & Z7_CONV_BE_TO_NATIVE_CONST32(0xfc000003)) == 0) break;
50 } 182 }
51 { 183 {
52 UInt32 v = GetUi32(p - 4); 184 v = Z7_CONV_NATIVE_TO_BE_32(v);
53 v <<= 2; 185 {
54 v -= ip + (UInt32)(p - data); 186 UInt32 c = BR_PC_GET;
55 v >>= 2; 187 BR_CONVERT_VAL(v, c)
56 v &= 0x00FFFFFF; 188 }
57 v |= 0xEB000000; 189 v &= 0x03ffffff;
58 SetUi32(p - 4, v); 190 v |= 0x48000000;
191 SetBe32a(p - 4, v)
59 } 192 }
60 } 193 }
61} 194}
195Z7_BRANCH_FUNCS_IMP(PPC)
62 196
63 197
64SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 198#ifdef Z7_CPU_FAST_ROTATE_SUPPORTED
199#define BR_SPARC_USE_ROTATE
200#endif
201
202Z7_BRANCH_FUNC_MAIN(SPARC)
65{ 203{
66 Byte *p; 204 // Byte *p = data;
67 const Byte *lim; 205 const Byte *lim;
68 size &= ~(size_t)1; 206 const UInt32 flag = (UInt32)1 << 22;
69 p = data; 207 size &= ~(SizeT)3;
70 lim = data + size - 4; 208 lim = p + size;
71 209 BR_PC_INIT
72 if (encoding) 210 pc -= 4; // because (p) will point to next instruction
73
74 for (;;) 211 for (;;)
75 { 212 {
76 UInt32 b1; 213 UInt32 v;
77 for (;;) 214 for (;;)
78 { 215 {
79 UInt32 b3; 216 if Z7_UNLIKELY(p == lim)
80 if (p > lim) 217 return p;
81 return (SizeT)(p - data); 218 /* // the code without GetBe32a():
82 b1 = p[1]; 219 { const UInt32 v = GetUi16a(p) & 0xc0ff; p += 4; if (v == 0x40 || v == 0xc07f) break; }
83 b3 = p[3]; 220 */
84 p += 2; 221 v = GetBe32a(p);
85 b1 ^= 8; 222 p += 4;
86 if ((b3 & b1) >= 0xF8) 223 #ifdef BR_SPARC_USE_ROTATE
224 v = rotlFixed(v, 2);
225 v += (flag << 2) - 1;
226 if Z7_UNLIKELY((v & (3 - (flag << 3))) == 0)
227 #else
228 v += (UInt32)5 << 29;
229 v ^= (UInt32)7 << 29;
230 v += flag;
231 if Z7_UNLIKELY((v & (0 - (flag << 1))) == 0)
232 #endif
87 break; 233 break;
88 } 234 }
89 { 235 {
90 UInt32 v = 236 // UInt32 v = GetBe32a(p - 4);
91 ((UInt32)b1 << 19) 237 #ifndef BR_SPARC_USE_ROTATE
92 + (((UInt32)p[1] & 0x7) << 8) 238 v <<= 2;
93 + (((UInt32)p[-2] << 11)) 239 #endif
94 + (p[0]);
95
96 p += 2;
97 { 240 {
98 UInt32 cur = (ip + (UInt32)(p - data)) >> 1; 241 UInt32 c = BR_PC_GET;
99 v += cur; 242 BR_CONVERT_VAL(v, c)
100 } 243 }
101 244 v &= (flag << 3) - 1;
102 p[-4] = (Byte)(v >> 11); 245 #ifdef BR_SPARC_USE_ROTATE
103 p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); 246 v -= (flag << 2) - 1;
104 p[-2] = (Byte)v; 247 v = rotrFixed(v, 2);
105 p[-1] = (Byte)(0xF8 | (v >> 8)); 248 #else
249 v -= (flag << 2);
250 v >>= 2;
251 v |= (UInt32)1 << 30;
252 #endif
253 SetBe32a(p - 4, v)
106 } 254 }
107 } 255 }
256}
257Z7_BRANCH_FUNCS_IMP(SPARC)
258
259
260Z7_BRANCH_FUNC_MAIN(ARMT)
261{
262 // Byte *p = data;
263 Byte *lim;
264 size &= ~(SizeT)1;
265 // if (size == 0) return p;
266 if (size <= 2) return p;
267 size -= 2;
268 lim = p + size;
269 BR_PC_INIT
270 /* in ARM: branch offset is relative to the +2 instructions from current instruction.
271 (p) will point to the +2 instructions from current instruction */
272 // pc += 4 - 4;
273 // if (encoding) pc -= 0xf800 << 1; else pc += 0xf800 << 1;
274 // #define ARMT_TAIL_PROC { goto armt_tail; }
275 #define ARMT_TAIL_PROC { return p; }
108 276
109 for (;;) 277 do
110 { 278 {
111 UInt32 b1; 279 /* in MSVC 32-bit x86 compilers:
280 UInt32 version : it loads value from memory with movzx
281 Byte version : it loads value to 8-bit register (AL/CL)
282 movzx version is slightly faster in some cpus
283 */
284 unsigned b1;
285 // Byte / unsigned
286 b1 = p[1];
287 // optimized version to reduce one (p >= lim) check:
288 // unsigned a1 = p[1]; b1 = p[3]; p += 2; if Z7_LIKELY((b1 & (a1 ^ 8)) < 0xf8)
112 for (;;) 289 for (;;)
113 { 290 {
114 UInt32 b3; 291 unsigned b3; // Byte / UInt32
115 if (p > lim) 292 /* (Byte)(b3) normalization can use low byte computations in MSVC.
116 return (SizeT)(p - data); 293 It gives smaller code, and no loss of speed in some compilers/cpus.
117 b1 = p[1]; 294 But new MSVC 32-bit x86 compilers use more slow load
118 b3 = p[3]; 295 from memory to low byte register in that case.
119 p += 2; 296 So we try to use full 32-bit computations for faster code.
120 b1 ^= 8; 297 */
121 if ((b3 & b1) >= 0xF8) 298 // if (p >= lim) { ARMT_TAIL_PROC } b3 = b1 + 8; b1 = p[3]; p += 2; if ((b3 & b1) >= 0xf8) break;
122 break; 299 if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b3 = p[3]; p += 2; if Z7_UNLIKELY((b3 & (b1 ^ 8)) >= 0xf8) break;
300 if Z7_UNLIKELY(p >= lim) { ARMT_TAIL_PROC } b1 = p[3]; p += 2; if Z7_UNLIKELY((b1 & (b3 ^ 8)) >= 0xf8) break;
123 } 301 }
124 { 302 {
303 /* we can adjust pc for (0xf800) to rid of (& 0x7FF) operation.
304 But gcc/clang for arm64 can use bfi instruction for full code here */
125 UInt32 v = 305 UInt32 v =
126 ((UInt32)b1 << 19) 306 ((UInt32)GetUi16a(p - 2) << 11) |
307 ((UInt32)GetUi16a(p) & 0x7FF);
308 /*
309 UInt32 v =
310 ((UInt32)p[1 - 2] << 19)
127 + (((UInt32)p[1] & 0x7) << 8) 311 + (((UInt32)p[1] & 0x7) << 8)
128 + (((UInt32)p[-2] << 11)) 312 + (((UInt32)p[-2] << 11))
129 + (p[0]); 313 + (p[0]);
130 314 */
131 p += 2; 315 p += 2;
132 { 316 {
133 UInt32 cur = (ip + (UInt32)(p - data)) >> 1; 317 UInt32 c = BR_PC_GET >> 1;
134 v -= cur; 318 BR_CONVERT_VAL(v, c)
135 } 319 }
136 320 SetUi16a(p - 4, (UInt16)(((v >> 11) & 0x7ff) | 0xf000))
321 SetUi16a(p - 2, (UInt16)(v | 0xf800))
137 /* 322 /*
138 SetUi16(p - 4, (UInt16)(((v >> 11) & 0x7FF) | 0xF000));
139 SetUi16(p - 2, (UInt16)(v | 0xF800));
140 */
141
142 p[-4] = (Byte)(v >> 11); 323 p[-4] = (Byte)(v >> 11);
143 p[-3] = (Byte)(0xF0 | ((v >> 19) & 0x7)); 324 p[-3] = (Byte)(0xf0 | ((v >> 19) & 0x7));
144 p[-2] = (Byte)v; 325 p[-2] = (Byte)v;
145 p[-1] = (Byte)(0xF8 | (v >> 8)); 326 p[-1] = (Byte)(0xf8 | (v >> 8));
327 */
146 } 328 }
147 } 329 }
330 while (p < lim);
331 return p;
332 // armt_tail:
333 // if ((Byte)((lim[1] & 0xf8)) != 0xf0) { lim += 2; } return lim;
334 // return (Byte *)(lim + ((Byte)((lim[1] ^ 0xf0) & 0xf8) == 0 ? 0 : 2));
335 // return (Byte *)(lim + (((lim[1] ^ ~0xfu) & ~7u) == 0 ? 0 : 2));
336 // return (Byte *)(lim + 2 - (((((unsigned)lim[1] ^ 8) + 8) >> 7) & 2));
148} 337}
338Z7_BRANCH_FUNCS_IMP(ARMT)
149 339
150 340
151SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 341// #define BR_IA64_NO_INLINE
152{
153 Byte *p;
154 const Byte *lim;
155 size &= ~(size_t)3;
156 ip -= 4;
157 p = data;
158 lim = data + size;
159
160 for (;;)
161 {
162 for (;;)
163 {
164 if (p >= lim)
165 return (SizeT)(p - data);
166 p += 4;
167 /* if ((v & 0xFC000003) == 0x48000001) */
168 if ((p[-4] & 0xFC) == 0x48 && (p[-1] & 3) == 1)
169 break;
170 }
171 {
172 UInt32 v = GetBe32(p - 4);
173 if (encoding)
174 v += ip + (UInt32)(p - data);
175 else
176 v -= ip + (UInt32)(p - data);
177 v &= 0x03FFFFFF;
178 v |= 0x48000000;
179 SetBe32(p - 4, v);
180 }
181 }
182}
183
184 342
185SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 343Z7_BRANCH_FUNC_MAIN(IA64)
186{ 344{
187 Byte *p; 345 // Byte *p = data;
188 const Byte *lim; 346 const Byte *lim;
189 size &= ~(size_t)3; 347 size &= ~(SizeT)15;
190 ip -= 4; 348 lim = p + size;
191 p = data; 349 pc -= 1 << 4;
192 lim = data + size; 350 pc >>= 4 - 1;
193 351 // pc -= 1 << 1;
352
194 for (;;) 353 for (;;)
195 { 354 {
355 unsigned m;
196 for (;;) 356 for (;;)
197 { 357 {
198 if (p >= lim) 358 if Z7_UNLIKELY(p == lim)
199 return (SizeT)(p - data); 359 return p;
200 /* 360 m = (unsigned)((UInt32)0x334b0000 >> (*p & 0x1e));
201 v = GetBe32(p); 361 p += 16;
202 p += 4; 362 pc += 1 << 1;
203 m = v + ((UInt32)5 << 29); 363 if (m &= 3)
204 m ^= (UInt32)7 << 29;
205 m += (UInt32)1 << 22;
206 if ((m & ((UInt32)0x1FF << 23)) == 0)
207 break;
208 */
209 p += 4;
210 if ((p[-4] == 0x40 && (p[-3] & 0xC0) == 0) ||
211 (p[-4] == 0x7F && (p[-3] >= 0xC0)))
212 break; 364 break;
213 } 365 }
214 { 366 {
215 UInt32 v = GetBe32(p - 4); 367 p += (ptrdiff_t)m * 5 - 20; // negative value is expected here.
216 v <<= 2; 368 do
217 if (encoding) 369 {
218 v += ip + (UInt32)(p - data); 370 const UInt32 t =
219 else 371 #if defined(MY_CPU_X86_OR_AMD64)
220 v -= ip + (UInt32)(p - data); 372 // we use 32-bit load here to reduce code size on x86:
221 373 GetUi32(p);
222 v &= 0x01FFFFFF; 374 #else
223 v -= (UInt32)1 << 24; 375 GetUi16(p);
224 v ^= 0xFF000000; 376 #endif
225 v >>= 2; 377 UInt32 z = GetUi32(p + 1) >> m;
226 v |= 0x40000000; 378 p += 5;
227 SetBe32(p - 4, v); 379 if (((t >> m) & (0x70 << 1)) == 0
380 && ((z - (0x5000000 << 1)) & (0xf000000 << 1)) == 0)
381 {
382 UInt32 v = (UInt32)((0x8fffff << 1) | 1) & z;
383 z ^= v;
384 #ifdef BR_IA64_NO_INLINE
385 v |= (v & ((UInt32)1 << (23 + 1))) >> 3;
386 {
387 UInt32 c = pc;
388 BR_CONVERT_VAL(v, c)
389 }
390 v &= (0x1fffff << 1) | 1;
391 #else
392 {
393 if (encoding)
394 {
395 // pc &= ~(0xc00000 << 1); // we just need to clear at least 2 bits
396 pc &= (0x1fffff << 1) | 1;
397 v += pc;
398 }
399 else
400 {
401 // pc |= 0xc00000 << 1; // we need to set at least 2 bits
402 pc |= ~(UInt32)((0x1fffff << 1) | 1);
403 v -= pc;
404 }
405 }
406 v &= ~(UInt32)(0x600000 << 1);
407 #endif
408 v += (0x700000 << 1);
409 v &= (0x8fffff << 1) | 1;
410 z |= v;
411 z <<= m;
412 SetUi32(p + 1 - 5, z)
413 }
414 m++;
415 }
416 while (m &= 3); // while (m < 4);
228 } 417 }
229 } 418 }
230} 419}
420Z7_BRANCH_FUNCS_IMP(IA64)
diff --git a/C/Bra.h b/C/Bra.h
index 855e37a..a4ee568 100644
--- a/C/Bra.h
+++ b/C/Bra.h
@@ -1,64 +1,99 @@
1/* Bra.h -- Branch converters for executables 1/* Bra.h -- Branch converters for executables
22013-01-18 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __BRA_H 4#ifndef ZIP7_INC_BRA_H
5#define __BRA_H 5#define ZIP7_INC_BRA_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11#define Z7_BRANCH_CONV_DEC(name) z7_BranchConv_ ## name ## _Dec
12#define Z7_BRANCH_CONV_ENC(name) z7_BranchConv_ ## name ## _Enc
13#define Z7_BRANCH_CONV_ST_DEC(name) z7_BranchConvSt_ ## name ## _Dec
14#define Z7_BRANCH_CONV_ST_ENC(name) z7_BranchConvSt_ ## name ## _Enc
15
16#define Z7_BRANCH_CONV_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc)
17#define Z7_BRANCH_CONV_ST_DECL(name) Byte * name(Byte *data, SizeT size, UInt32 pc, UInt32 *state)
18
19typedef Z7_BRANCH_CONV_DECL( (*z7_Func_BranchConv));
20typedef Z7_BRANCH_CONV_ST_DECL((*z7_Func_BranchConvSt));
21
22#define Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL 0
23Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_DEC(X86));
24Z7_BRANCH_CONV_ST_DECL(Z7_BRANCH_CONV_ST_ENC(X86));
25
26#define Z7_BRANCH_FUNCS_DECL(name) \
27Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_DEC(name)); \
28Z7_BRANCH_CONV_DECL(Z7_BRANCH_CONV_ENC(name));
29
30Z7_BRANCH_FUNCS_DECL(ARM64)
31Z7_BRANCH_FUNCS_DECL(ARM)
32Z7_BRANCH_FUNCS_DECL(ARMT)
33Z7_BRANCH_FUNCS_DECL(PPC)
34Z7_BRANCH_FUNCS_DECL(SPARC)
35Z7_BRANCH_FUNCS_DECL(IA64)
36
11/* 37/*
12These functions convert relative addresses to absolute addresses 38These functions convert data that contain CPU instructions.
13in CALL instructions to increase the compression ratio. 39Each such function converts relative addresses to absolute addresses in some
14 40branch instructions: CALL (in all converters) and JUMP (X86 converter only).
15 In: 41Such conversion allows to increase compression ratio, if we compress that data.
16 data - data buffer 42
17 size - size of data 43There are 2 types of converters:
18 ip - current virtual Instruction Pinter (IP) value 44 Byte * Conv_RISC (Byte *data, SizeT size, UInt32 pc);
19 state - state variable for x86 converter 45 Byte * ConvSt_X86(Byte *data, SizeT size, UInt32 pc, UInt32 *state);
20 encoding - 0 (for decoding), 1 (for encoding) 46Each Converter supports 2 versions: one for encoding
21 47and one for decoding (_Enc/_Dec postfixes in function name).
22 Out:
23 state - state variable for x86 converter
24 48
25 Returns: 49In params:
26 The number of processed bytes. If you call these functions with multiple calls, 50 data : data buffer
27 you must start next call with first byte after block of processed bytes. 51 size : size of data
52 pc : current virtual Program Counter (Instruction Pinter) value
53In/Out param:
54 state : pointer to state variable (for X86 converter only)
55
56Return:
57 The pointer to position in (data) buffer after last byte that was processed.
58 If the caller calls converter again, it must call it starting with that position.
59 But the caller is allowed to move data in buffer. so pointer to
60 current processed position also will be changed for next call.
61 Also the caller must increase internal (pc) value for next call.
28 62
63Each converter has some characteristics: Endian, Alignment, LookAhead.
29 Type Endian Alignment LookAhead 64 Type Endian Alignment LookAhead
30 65
31 x86 little 1 4 66 X86 little 1 4
32 ARMT little 2 2 67 ARMT little 2 2
33 ARM little 4 0 68 ARM little 4 0
69 ARM64 little 4 0
34 PPC big 4 0 70 PPC big 4 0
35 SPARC big 4 0 71 SPARC big 4 0
36 IA64 little 16 0 72 IA64 little 16 0
37 73
38 size must be >= Alignment + LookAhead, if it's not last block. 74 (data) must be aligned for (Alignment).
39 If (size < Alignment + LookAhead), converter returns 0. 75 processed size can be calculated as:
40 76 SizeT processed = Conv(data, size, pc) - data;
41 Example: 77 if (processed == 0)
78 it means that converter needs more data for processing.
79 If (size < Alignment + LookAhead)
80 then (processed == 0) is allowed.
42 81
43 UInt32 ip = 0; 82Example code for conversion in loop:
44 for () 83 UInt32 pc = 0;
45 { 84 size = 0;
46 ; size must be >= Alignment + LookAhead, if it's not last block 85 for (;;)
47 SizeT processed = Convert(data, size, ip, 1); 86 {
48 data += processed; 87 size += Load_more_input_data(data + size);
49 size -= processed; 88 SizeT processed = Conv(data, size, pc) - data;
50 ip += processed; 89 if (processed == 0 && no_more_input_data_after_size)
51 } 90 break; // we stop convert loop
91 data += processed;
92 size -= processed;
93 pc += processed;
94 }
52*/ 95*/
53 96
54#define x86_Convert_Init(state) { state = 0; }
55SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding);
56SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
57SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
58SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
59SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
60SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
61
62EXTERN_C_END 97EXTERN_C_END
63 98
64#endif 99#endif
diff --git a/C/Bra86.c b/C/Bra86.c
index 10a0fbd..d81f392 100644
--- a/C/Bra86.c
+++ b/C/Bra86.c
@@ -1,82 +1,187 @@
1/* Bra86.c -- Converter for x86 code (BCJ) 1/* Bra86.c -- Branch converter for X86 code (BCJ)
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "Bra.h" 6#include "Bra.h"
7#include "CpuArch.h"
7 8
8#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0)
9 9
10SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) 10#if defined(MY_CPU_SIZEOF_POINTER) \
11 && ( MY_CPU_SIZEOF_POINTER == 4 \
12 || MY_CPU_SIZEOF_POINTER == 8)
13 #define BR_CONV_USE_OPT_PC_PTR
14#endif
15
16#ifdef BR_CONV_USE_OPT_PC_PTR
17#define BR_PC_INIT pc -= (UInt32)(SizeT)p; // (MY_uintptr_t)
18#define BR_PC_GET (pc + (UInt32)(SizeT)p)
19#else
20#define BR_PC_INIT pc += (UInt32)size;
21#define BR_PC_GET (pc - (UInt32)(SizeT)(lim - p))
22// #define BR_PC_INIT
23// #define BR_PC_GET (pc + (UInt32)(SizeT)(p - data))
24#endif
25
26#define BR_CONVERT_VAL(v, c) if (encoding) v += c; else v -= c;
27// #define BR_CONVERT_VAL(v, c) if (!encoding) c = (UInt32)0 - c; v += c;
28
29#define Z7_BRANCH_CONV_ST(name) z7_BranchConvSt_ ## name
30
31#define BR86_NEED_CONV_FOR_MS_BYTE(b) ((((b) + 1) & 0xfe) == 0)
32
33#ifdef MY_CPU_LE_UNALIGN
34 #define BR86_PREPARE_BCJ_SCAN const UInt32 v = GetUi32(p) ^ 0xe8e8e8e8;
35 #define BR86_IS_BCJ_BYTE(n) ((v & ((UInt32)0xfe << (n) * 8)) == 0)
36#else
37 #define BR86_PREPARE_BCJ_SCAN
38 // bad for MSVC X86 (partial write to byte reg):
39 #define BR86_IS_BCJ_BYTE(n) ((p[n - 4] & 0xfe) == 0xe8)
40 // bad for old MSVC (partial write to byte reg):
41 // #define BR86_IS_BCJ_BYTE(n) (((*p ^ 0xe8) & 0xfe) == 0)
42#endif
43
44static
45Z7_FORCE_INLINE
46Z7_ATTRIB_NO_VECTOR
47Byte *Z7_BRANCH_CONV_ST(X86)(Byte *p, SizeT size, UInt32 pc, UInt32 *state, int encoding)
11{ 48{
12 SizeT pos = 0;
13 UInt32 mask = *state & 7;
14 if (size < 5) 49 if (size < 5)
15 return 0; 50 return p;
16 size -= 4; 51 {
17 ip += 5; 52 // Byte *p = data;
53 const Byte *lim = p + size - 4;
54 unsigned mask = (unsigned)*state; // & 7;
55#ifdef BR_CONV_USE_OPT_PC_PTR
56 /* if BR_CONV_USE_OPT_PC_PTR is defined: we need to adjust (pc) for (+4),
57 because call/jump offset is relative to the next instruction.
58 if BR_CONV_USE_OPT_PC_PTR is not defined : we don't need to adjust (pc) for (+4),
59 because BR_PC_GET uses (pc - (lim - p)), and lim was adjusted for (-4) before.
60 */
61 pc += 4;
62#endif
63 BR_PC_INIT
64 goto start;
18 65
19 for (;;) 66 for (;; mask |= 4)
20 { 67 {
21 Byte *p = data + pos; 68 // cont: mask |= 4;
22 const Byte *limit = data + size; 69 start:
23 for (; p < limit; p++) 70 if (p >= lim)
24 if ((*p & 0xFE) == 0xE8) 71 goto fin;
25 break;
26
27 { 72 {
28 SizeT d = (SizeT)(p - data) - pos; 73 BR86_PREPARE_BCJ_SCAN
29 pos = (SizeT)(p - data); 74 p += 4;
30 if (p >= limit) 75 if (BR86_IS_BCJ_BYTE(0)) { goto m0; } mask >>= 1;
31 { 76 if (BR86_IS_BCJ_BYTE(1)) { goto m1; } mask >>= 1;
32 *state = (d > 2 ? 0 : mask >> (unsigned)d); 77 if (BR86_IS_BCJ_BYTE(2)) { goto m2; } mask = 0;
33 return pos; 78 if (BR86_IS_BCJ_BYTE(3)) { goto a3; }
34 }
35 if (d > 2)
36 mask = 0;
37 else
38 {
39 mask >>= (unsigned)d;
40 if (mask != 0 && (mask > 4 || mask == 3 || Test86MSByte(p[(size_t)(mask >> 1) + 1])))
41 {
42 mask = (mask >> 1) | 4;
43 pos++;
44 continue;
45 }
46 }
47 } 79 }
80 goto main_loop;
48 81
49 if (Test86MSByte(p[4])) 82 m0: p--;
83 m1: p--;
84 m2: p--;
85 if (mask == 0)
86 goto a3;
87 if (p > lim)
88 goto fin_p;
89
90 // if (((0x17u >> mask) & 1) == 0)
91 if (mask > 4 || mask == 3)
92 {
93 mask >>= 1;
94 continue; // goto cont;
95 }
96 mask >>= 1;
97 if (BR86_NEED_CONV_FOR_MS_BYTE(p[mask]))
98 continue; // goto cont;
99 // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont;
50 { 100 {
51 UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); 101 UInt32 v = GetUi32(p);
52 UInt32 cur = ip + (UInt32)pos; 102 UInt32 c;
53 pos += 5; 103 v += (1 << 24); if (v & 0xfe000000) continue; // goto cont;
54 if (encoding) 104 c = BR_PC_GET;
55 v += cur; 105 BR_CONVERT_VAL(v, c)
56 else
57 v -= cur;
58 if (mask != 0)
59 { 106 {
60 unsigned sh = (mask & 6) << 2; 107 mask <<= 3;
61 if (Test86MSByte((Byte)(v >> sh))) 108 if (BR86_NEED_CONV_FOR_MS_BYTE(v >> mask))
62 { 109 {
63 v ^= (((UInt32)0x100 << sh) - 1); 110 v ^= (((UInt32)0x100 << mask) - 1);
64 if (encoding) 111 #ifdef MY_CPU_X86
65 v += cur; 112 // for X86 : we can recalculate (c) to reduce register pressure
66 else 113 c = BR_PC_GET;
67 v -= cur; 114 #endif
115 BR_CONVERT_VAL(v, c)
68 } 116 }
69 mask = 0; 117 mask = 0;
70 } 118 }
71 p[1] = (Byte)v; 119 // v = (v & ((1 << 24) - 1)) - (v & (1 << 24));
72 p[2] = (Byte)(v >> 8); 120 v &= (1 << 25) - 1; v -= (1 << 24);
73 p[3] = (Byte)(v >> 16); 121 SetUi32(p, v)
74 p[4] = (Byte)(0 - ((v >> 24) & 1)); 122 p += 4;
123 goto main_loop;
75 } 124 }
76 else 125
126 main_loop:
127 if (p >= lim)
128 goto fin;
129 for (;;)
77 { 130 {
78 mask = (mask >> 1) | 4; 131 BR86_PREPARE_BCJ_SCAN
79 pos++; 132 p += 4;
133 if (BR86_IS_BCJ_BYTE(0)) { goto a0; }
134 if (BR86_IS_BCJ_BYTE(1)) { goto a1; }
135 if (BR86_IS_BCJ_BYTE(2)) { goto a2; }
136 if (BR86_IS_BCJ_BYTE(3)) { goto a3; }
137 if (p >= lim)
138 goto fin;
139 }
140
141 a0: p--;
142 a1: p--;
143 a2: p--;
144 a3:
145 if (p > lim)
146 goto fin_p;
147 // if (!BR86_NEED_CONV_FOR_MS_BYTE(p[3])) continue; // goto cont;
148 {
149 UInt32 v = GetUi32(p);
150 UInt32 c;
151 v += (1 << 24); if (v & 0xfe000000) continue; // goto cont;
152 c = BR_PC_GET;
153 BR_CONVERT_VAL(v, c)
154 // v = (v & ((1 << 24) - 1)) - (v & (1 << 24));
155 v &= (1 << 25) - 1; v -= (1 << 24);
156 SetUi32(p, v)
157 p += 4;
158 goto main_loop;
80 } 159 }
81 } 160 }
161
162fin_p:
163 p--;
164fin:
165 // the following processing for tail is optional and can be commented
166 /*
167 lim += 4;
168 for (; p < lim; p++, mask >>= 1)
169 if ((*p & 0xfe) == 0xe8)
170 break;
171 */
172 *state = (UInt32)mask;
173 return p;
174 }
82} 175}
176
177
178#define Z7_BRANCH_CONV_ST_FUNC_IMP(name, m, encoding) \
179Z7_NO_INLINE \
180Z7_ATTRIB_NO_VECTOR \
181Byte *m(name)(Byte *data, SizeT size, UInt32 pc, UInt32 *state) \
182 { return Z7_BRANCH_CONV_ST(name)(data, size, pc, state, encoding); }
183
184Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_DEC, 0)
185#ifndef Z7_EXTRACT_ONLY
186Z7_BRANCH_CONV_ST_FUNC_IMP(X86, Z7_BRANCH_CONV_ST_ENC, 1)
187#endif
diff --git a/C/BraIA64.c b/C/BraIA64.c
index d1dbc62..9dfe3e2 100644
--- a/C/BraIA64.c
+++ b/C/BraIA64.c
@@ -1,53 +1,14 @@
1/* BraIA64.c -- Converter for IA-64 code 1/* BraIA64.c -- Converter for IA-64 code
22017-01-26 : Igor Pavlov : Public domain */ 22023-02-20 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "CpuArch.h" 6// the code was moved to Bra.c
7#include "Bra.h"
8 7
9SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 8#ifdef _MSC_VER
10{ 9#pragma warning(disable : 4206) // nonstandard extension used : translation unit is empty
11 SizeT i; 10#endif
12 if (size < 16) 11
13 return 0; 12#if defined(__clang__)
14 size -= 16; 13#pragma GCC diagnostic ignored "-Wempty-translation-unit"
15 i = 0; 14#endif
16 do
17 {
18 unsigned m = ((UInt32)0x334B0000 >> (data[i] & 0x1E)) & 3;
19 if (m)
20 {
21 m++;
22 do
23 {
24 Byte *p = data + (i + (size_t)m * 5 - 8);
25 if (((p[3] >> m) & 15) == 5
26 && (((p[-1] | ((UInt32)p[0] << 8)) >> m) & 0x70) == 0)
27 {
28 unsigned raw = GetUi32(p);
29 unsigned v = raw >> m;
30 v = (v & 0xFFFFF) | ((v & (1 << 23)) >> 3);
31
32 v <<= 4;
33 if (encoding)
34 v += ip + (UInt32)i;
35 else
36 v -= ip + (UInt32)i;
37 v >>= 4;
38
39 v &= 0x1FFFFF;
40 v += 0x700000;
41 v &= 0x8FFFFF;
42 raw &= ~((UInt32)0x8FFFFF << m);
43 raw |= (v << m);
44 SetUi32(p, raw);
45 }
46 }
47 while (++m <= 4);
48 }
49 i += 16;
50 }
51 while (i <= size);
52 return i;
53}
diff --git a/C/BwtSort.c b/C/BwtSort.c
index 3eb57ef..05ad6de 100644
--- a/C/BwtSort.c
+++ b/C/BwtSort.c
@@ -1,5 +1,5 @@
1/* BwtSort.c -- BWT block sorting 1/* BwtSort.c -- BWT block sorting
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -8,8 +8,6 @@
8 8
9/* #define BLOCK_SORT_USE_HEAP_SORT */ 9/* #define BLOCK_SORT_USE_HEAP_SORT */
10 10
11#define NO_INLINE MY_FAST_CALL
12
13/* Don't change it !!! */ 11/* Don't change it !!! */
14#define kNumHashBytes 2 12#define kNumHashBytes 2
15#define kNumHashValues (1 << (kNumHashBytes * 8)) 13#define kNumHashValues (1 << (kNumHashBytes * 8))
@@ -60,7 +58,10 @@ SortGroup - is recursive Range-Sort function with HeapSort optimization for smal
60returns: 1 - if there are groups, 0 - no more groups 58returns: 1 - if there are groups, 0 - no more groups
61*/ 59*/
62 60
63static UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices 61static
62UInt32
63Z7_FASTCALL
64SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices
64 #ifndef BLOCK_SORT_USE_HEAP_SORT 65 #ifndef BLOCK_SORT_USE_HEAP_SORT
65 , UInt32 left, UInt32 range 66 , UInt32 left, UInt32 range
66 #endif 67 #endif
@@ -72,7 +73,7 @@ static UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt3
72 { 73 {
73 /* 74 /*
74 #ifndef BLOCK_SORT_EXTERNAL_FLAGS 75 #ifndef BLOCK_SORT_EXTERNAL_FLAGS
75 SetFinishedGroupSize(ind2, 1); 76 SetFinishedGroupSize(ind2, 1)
76 #endif 77 #endif
77 */ 78 */
78 return 0; 79 return 0;
@@ -463,7 +464,7 @@ UInt32 BlockSort(UInt32 *Indices, const Byte *data, UInt32 blockSize)
463 Indices[(size_t)(i - finishedGroupSize) + 1] &= kIndexMask; 464 Indices[(size_t)(i - finishedGroupSize) + 1] &= kIndexMask;
464 { 465 {
465 UInt32 newGroupSize = groupSize + finishedGroupSize; 466 UInt32 newGroupSize = groupSize + finishedGroupSize;
466 SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize); 467 SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize)
467 finishedGroupSize = newGroupSize; 468 finishedGroupSize = newGroupSize;
468 } 469 }
469 i += groupSize; 470 i += groupSize;
diff --git a/C/BwtSort.h b/C/BwtSort.h
index 7e989a9..a34b243 100644
--- a/C/BwtSort.h
+++ b/C/BwtSort.h
@@ -1,8 +1,8 @@
1/* BwtSort.h -- BWT block sorting 1/* BwtSort.h -- BWT block sorting
22013-01-18 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#ifndef __BWT_SORT_H 4#ifndef ZIP7_INC_BWT_SORT_H
5#define __BWT_SORT_H 5#define ZIP7_INC_BWT_SORT_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/Compiler.h b/C/Compiler.h
index a9816fa..185a52d 100644
--- a/C/Compiler.h
+++ b/C/Compiler.h
@@ -1,12 +1,37 @@
1/* Compiler.h 1/* Compiler.h : Compiler specific defines and pragmas
22021-01-05 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_COMPILER_H 4#ifndef ZIP7_INC_COMPILER_H
5#define __7Z_COMPILER_H 5#define ZIP7_INC_COMPILER_H
6
7#if defined(__clang__)
8# define Z7_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
9#endif
10#if defined(__clang__) && defined(__apple_build_version__)
11# define Z7_APPLE_CLANG_VERSION Z7_CLANG_VERSION
12#elif defined(__clang__)
13# define Z7_LLVM_CLANG_VERSION Z7_CLANG_VERSION
14#elif defined(__GNUC__)
15# define Z7_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
16#endif
17
18#ifdef _MSC_VER
19#if !defined(__clang__) && !defined(__GNUC__)
20#define Z7_MSC_VER_ORIGINAL _MSC_VER
21#endif
22#endif
23
24#if defined(__MINGW32__) || defined(__MINGW64__)
25#define Z7_MINGW
26#endif
27
28// #pragma GCC diagnostic ignored "-Wunknown-pragmas"
29
30#ifdef __clang__
31// padding size of '' with 4 bytes to alignment boundary
32#pragma GCC diagnostic ignored "-Wpadded"
33#endif
6 34
7 #ifdef __clang__
8 #pragma clang diagnostic ignored "-Wunused-private-field"
9 #endif
10 35
11#ifdef _MSC_VER 36#ifdef _MSC_VER
12 37
@@ -17,24 +42,115 @@
17 #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int 42 #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int
18 #endif 43 #endif
19 44
20 #if _MSC_VER >= 1300 45#if defined(_MSC_VER) && _MSC_VER >= 1800
21 #pragma warning(disable : 4996) // This function or variable may be unsafe 46#pragma warning(disable : 4464) // relative include path contains '..'
22 #else 47#endif
23 #pragma warning(disable : 4511) // copy constructor could not be generated 48
24 #pragma warning(disable : 4512) // assignment operator could not be generated 49// == 1200 : -O1 : for __forceinline
25 #pragma warning(disable : 4514) // unreferenced inline function has been removed 50// >= 1900 : -O1 : for printf
26 #pragma warning(disable : 4702) // unreachable code 51#pragma warning(disable : 4710) // function not inlined
27 #pragma warning(disable : 4710) // not inlined 52
28 #pragma warning(disable : 4714) // function marked as __forceinline not inlined 53#if _MSC_VER < 1900
29 #pragma warning(disable : 4786) // identifier was truncated to '255' characters in the debug information 54// winnt.h: 'Int64ShllMod32'
30 #endif 55#pragma warning(disable : 4514) // unreferenced inline function has been removed
56#endif
57
58#if _MSC_VER < 1300
59// #pragma warning(disable : 4702) // unreachable code
60// Bra.c : -O1:
61#pragma warning(disable : 4714) // function marked as __forceinline not inlined
62#endif
63
64/*
65#if _MSC_VER > 1400 && _MSC_VER <= 1900
66// strcat: This function or variable may be unsafe
67// sysinfoapi.h: kit10: GetVersion was declared deprecated
68#pragma warning(disable : 4996)
69#endif
70*/
71
72#if _MSC_VER > 1200
73// -Wall warnings
74
75#pragma warning(disable : 4711) // function selected for automatic inline expansion
76#pragma warning(disable : 4820) // '2' bytes padding added after data member
77
78#if _MSC_VER >= 1400 && _MSC_VER < 1920
79// 1400: string.h: _DBG_MEMCPY_INLINE_
80// 1600 - 191x : smmintrin.h __cplusplus'
81// is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
82#pragma warning(disable : 4668)
83
84// 1400 - 1600 : WinDef.h : 'FARPROC' :
85// 1900 - 191x : immintrin.h: _readfsbase_u32
86// no function prototype given : converting '()' to '(void)'
87#pragma warning(disable : 4255)
88#endif
89
90#if _MSC_VER >= 1914
91// Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified
92#pragma warning(disable : 5045)
93#endif
94
95#endif // _MSC_VER > 1200
96#endif // _MSC_VER
97
98
99#if defined(__clang__) && (__clang_major__ >= 4)
100 #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \
101 _Pragma("clang loop unroll(disable)") \
102 _Pragma("clang loop vectorize(disable)")
103 #define Z7_ATTRIB_NO_VECTORIZE
104#elif defined(__GNUC__) && (__GNUC__ >= 5)
105 #define Z7_ATTRIB_NO_VECTORIZE __attribute__((optimize("no-tree-vectorize")))
106 // __attribute__((optimize("no-unroll-loops")));
107 #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
108#elif defined(_MSC_VER) && (_MSC_VER >= 1920)
109 #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE \
110 _Pragma("loop( no_vector )")
111 #define Z7_ATTRIB_NO_VECTORIZE
112#else
113 #define Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
114 #define Z7_ATTRIB_NO_VECTORIZE
115#endif
116
117#if defined(MY_CPU_X86_OR_AMD64) && ( \
118 defined(__clang__) && (__clang_major__ >= 4) \
119 || defined(__GNUC__) && (__GNUC__ >= 5))
120 #define Z7_ATTRIB_NO_SSE __attribute__((__target__("no-sse")))
121#else
122 #define Z7_ATTRIB_NO_SSE
123#endif
124
125#define Z7_ATTRIB_NO_VECTOR \
126 Z7_ATTRIB_NO_VECTORIZE \
127 Z7_ATTRIB_NO_SSE
128
129
130#if defined(__clang__) && (__clang_major__ >= 8) \
131 || defined(__GNUC__) && (__GNUC__ >= 1000) \
132 /* || defined(_MSC_VER) && (_MSC_VER >= 1920) */
133 // GCC is not good for __builtin_expect()
134 #define Z7_LIKELY(x) (__builtin_expect((x), 1))
135 #define Z7_UNLIKELY(x) (__builtin_expect((x), 0))
136 // #define Z7_unlikely [[unlikely]]
137 // #define Z7_likely [[likely]]
138#else
139 #define Z7_LIKELY(x) (x)
140 #define Z7_UNLIKELY(x) (x)
141 // #define Z7_likely
142#endif
31 143
32 #ifdef __clang__
33 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
34 #pragma clang diagnostic ignored "-Wmicrosoft-exception-spec"
35 // #pragma clang diagnostic ignored "-Wreserved-id-macro"
36 #endif
37 144
145#if (defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 36000))
146#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER \
147 _Pragma("GCC diagnostic push") \
148 _Pragma("GCC diagnostic ignored \"-Wreserved-macro-identifier\"")
149#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER \
150 _Pragma("GCC diagnostic pop")
151#else
152#define Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER
153#define Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER
38#endif 154#endif
39 155
40#define UNUSED_VAR(x) (void)x; 156#define UNUSED_VAR(x) (void)x;
diff --git a/C/CpuArch.c b/C/CpuArch.c
index fa9afe3..33f8a3a 100644
--- a/C/CpuArch.c
+++ b/C/CpuArch.c
@@ -1,187 +1,318 @@
1/* CpuArch.c -- CPU specific code 1/* CpuArch.c -- CPU specific code
22021-07-13 : Igor Pavlov : Public domain */ 22023-05-18 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6// #include <stdio.h>
7
6#include "CpuArch.h" 8#include "CpuArch.h"
7 9
8#ifdef MY_CPU_X86_OR_AMD64 10#ifdef MY_CPU_X86_OR_AMD64
9 11
10#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__) 12#undef NEED_CHECK_FOR_CPUID
11#define USE_ASM 13#if !defined(MY_CPU_AMD64)
14#define NEED_CHECK_FOR_CPUID
12#endif 15#endif
13 16
14#if !defined(USE_ASM) && _MSC_VER >= 1500 17/*
15#include <intrin.h> 18 cpuid instruction supports (subFunction) parameter in ECX,
19 that is used only with some specific (function) parameter values.
20 But we always use only (subFunction==0).
21*/
22/*
23 __cpuid(): MSVC and GCC/CLANG use same function/macro name
24 but parameters are different.
25 We use MSVC __cpuid() parameters style for our z7_x86_cpuid() function.
26*/
27
28#if defined(__GNUC__) /* && (__GNUC__ >= 10) */ \
29 || defined(__clang__) /* && (__clang_major__ >= 10) */
30
31/* there was some CLANG/GCC compilers that have issues with
32 rbx(ebx) handling in asm blocks in -fPIC mode (__PIC__ is defined).
33 compiler's <cpuid.h> contains the macro __cpuid() that is similar to our code.
34 The history of __cpuid() changes in CLANG/GCC:
35 GCC:
36 2007: it preserved ebx for (__PIC__ && __i386__)
37 2013: it preserved rbx and ebx for __PIC__
38 2014: it doesn't preserves rbx and ebx anymore
39 we suppose that (__GNUC__ >= 5) fixed that __PIC__ ebx/rbx problem.
40 CLANG:
41 2014+: it preserves rbx, but only for 64-bit code. No __PIC__ check.
42 Why CLANG cares about 64-bit mode only, and doesn't care about ebx (in 32-bit)?
43 Do we need __PIC__ test for CLANG or we must care about rbx even if
44 __PIC__ is not defined?
45*/
46
47#define ASM_LN "\n"
48
49#if defined(MY_CPU_AMD64) && defined(__PIC__) \
50 && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__))
51
52#define x86_cpuid_MACRO(p, func) { \
53 __asm__ __volatile__ ( \
54 ASM_LN "mov %%rbx, %q1" \
55 ASM_LN "cpuid" \
56 ASM_LN "xchg %%rbx, %q1" \
57 : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); }
58
59 /* "=&r" selects free register. It can select even rbx, if that register is free.
60 "=&D" for (RDI) also works, but the code can be larger with "=&D"
61 "2"(0) means (subFunction = 0),
62 2 is (zero-based) index in the output constraint list "=c" (ECX). */
63
64#elif defined(MY_CPU_X86) && defined(__PIC__) \
65 && ((defined (__GNUC__) && (__GNUC__ < 5)) || defined(__clang__))
66
67#define x86_cpuid_MACRO(p, func) { \
68 __asm__ __volatile__ ( \
69 ASM_LN "mov %%ebx, %k1" \
70 ASM_LN "cpuid" \
71 ASM_LN "xchg %%ebx, %k1" \
72 : "=a" ((p)[0]), "=&r" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); }
73
74#else
75
76#define x86_cpuid_MACRO(p, func) { \
77 __asm__ __volatile__ ( \
78 ASM_LN "cpuid" \
79 : "=a" ((p)[0]), "=b" ((p)[1]), "=c" ((p)[2]), "=d" ((p)[3]) : "0" (func), "2"(0)); }
80
16#endif 81#endif
17 82
18#if defined(USE_ASM) && !defined(MY_CPU_AMD64) 83
19static UInt32 CheckFlag(UInt32 flag) 84void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func)
20{ 85{
21 #ifdef _MSC_VER 86 x86_cpuid_MACRO(p, func)
22 __asm pushfd; 87}
23 __asm pop EAX; 88
24 __asm mov EDX, EAX; 89
25 __asm xor EAX, flag; 90Z7_NO_INLINE
26 __asm push EAX; 91UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void)
27 __asm popfd; 92{
28 __asm pushfd; 93 #if defined(NEED_CHECK_FOR_CPUID)
29 __asm pop EAX; 94 #define EFALGS_CPUID_BIT 21
30 __asm xor EAX, EDX; 95 UInt32 a;
31 __asm push EDX;
32 __asm popfd;
33 __asm and flag, EAX;
34 #else
35 __asm__ __volatile__ ( 96 __asm__ __volatile__ (
36 "pushf\n\t" 97 ASM_LN "pushf"
37 "pop %%EAX\n\t" 98 ASM_LN "pushf"
38 "movl %%EAX,%%EDX\n\t" 99 ASM_LN "pop %0"
39 "xorl %0,%%EAX\n\t" 100 // ASM_LN "movl %0, %1"
40 "push %%EAX\n\t" 101 // ASM_LN "xorl $0x200000, %0"
41 "popf\n\t" 102 ASM_LN "btc %1, %0"
42 "pushf\n\t" 103 ASM_LN "push %0"
43 "pop %%EAX\n\t" 104 ASM_LN "popf"
44 "xorl %%EDX,%%EAX\n\t" 105 ASM_LN "pushf"
45 "push %%EDX\n\t" 106 ASM_LN "pop %0"
46 "popf\n\t" 107 ASM_LN "xorl (%%esp), %0"
47 "andl %%EAX, %0\n\t": 108
48 "=c" (flag) : "c" (flag) : 109 ASM_LN "popf"
49 "%eax", "%edx"); 110 ASM_LN
111 : "=&r" (a) // "=a"
112 : "i" (EFALGS_CPUID_BIT)
113 );
114 if ((a & (1 << EFALGS_CPUID_BIT)) == 0)
115 return 0;
116 #endif
117 {
118 UInt32 p[4];
119 x86_cpuid_MACRO(p, 0)
120 return p[0];
121 }
122}
123
124#undef ASM_LN
125
126#elif !defined(_MSC_VER)
127
128/*
129// for gcc/clang and other: we can try to use __cpuid macro:
130#include <cpuid.h>
131void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func)
132{
133 __cpuid(func, p[0], p[1], p[2], p[3]);
134}
135UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void)
136{
137 return (UInt32)__get_cpuid_max(0, NULL);
138}
139*/
140// for unsupported cpuid:
141void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func)
142{
143 UNUSED_VAR(func)
144 p[0] = p[1] = p[2] = p[3] = 0;
145}
146UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void)
147{
148 return 0;
149}
150
151#else // _MSC_VER
152
153#if !defined(MY_CPU_AMD64)
154
155UInt32 __declspec(naked) Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void)
156{
157 #if defined(NEED_CHECK_FOR_CPUID)
158 #define EFALGS_CPUID_BIT 21
159 __asm pushfd
160 __asm pushfd
161 /*
162 __asm pop eax
163 // __asm mov edx, eax
164 __asm btc eax, EFALGS_CPUID_BIT
165 __asm push eax
166 */
167 __asm btc dword ptr [esp], EFALGS_CPUID_BIT
168 __asm popfd
169 __asm pushfd
170 __asm pop eax
171 // __asm xor eax, edx
172 __asm xor eax, [esp]
173 // __asm push edx
174 __asm popfd
175 __asm and eax, (1 shl EFALGS_CPUID_BIT)
176 __asm jz end_func
177 #endif
178 __asm push ebx
179 __asm xor eax, eax // func
180 __asm xor ecx, ecx // subFunction (optional) for (func == 0)
181 __asm cpuid
182 __asm pop ebx
183 #if defined(NEED_CHECK_FOR_CPUID)
184 end_func:
50 #endif 185 #endif
51 return flag; 186 __asm ret 0
52} 187}
53#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False;
54#else
55#define CHECK_CPUID_IS_SUPPORTED
56#endif
57 188
58#ifndef USE_ASM 189void __declspec(naked) Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func)
59 #ifdef _MSC_VER 190{
191 UNUSED_VAR(p)
192 UNUSED_VAR(func)
193 __asm push ebx
194 __asm push edi
195 __asm mov edi, ecx // p
196 __asm mov eax, edx // func
197 __asm xor ecx, ecx // subfunction (optional) for (func == 0)
198 __asm cpuid
199 __asm mov [edi ], eax
200 __asm mov [edi + 4], ebx
201 __asm mov [edi + 8], ecx
202 __asm mov [edi + 12], edx
203 __asm pop edi
204 __asm pop ebx
205 __asm ret 0
206}
207
208#else // MY_CPU_AMD64
209
60 #if _MSC_VER >= 1600 210 #if _MSC_VER >= 1600
61 #define MY__cpuidex __cpuidex 211 #include <intrin.h>
212 #define MY_cpuidex __cpuidex
62 #else 213 #else
63
64/* 214/*
65 __cpuid (function == 4) requires subfunction number in ECX. 215 __cpuid (func == (0 or 7)) requires subfunction number in ECX.
66 MSDN: The __cpuid intrinsic clears the ECX register before calling the cpuid instruction. 216 MSDN: The __cpuid intrinsic clears the ECX register before calling the cpuid instruction.
67 __cpuid() in new MSVC clears ECX. 217 __cpuid() in new MSVC clears ECX.
68 __cpuid() in old MSVC (14.00) doesn't clear ECX 218 __cpuid() in old MSVC (14.00) x64 doesn't clear ECX
69 We still can use __cpuid for low (function) values that don't require ECX, 219 We still can use __cpuid for low (func) values that don't require ECX,
70 but __cpuid() in old MSVC will be incorrect for some function values: (function == 4). 220 but __cpuid() in old MSVC will be incorrect for some func values: (func == 7).
71 So here we use the hack for old MSVC to send (subFunction) in ECX register to cpuid instruction, 221 So here we use the hack for old MSVC to send (subFunction) in ECX register to cpuid instruction,
72 where ECX value is first parameter for FAST_CALL / NO_INLINE function, 222 where ECX value is first parameter for FASTCALL / NO_INLINE func,
73 So the caller of MY__cpuidex_HACK() sets ECX as subFunction, and 223 So the caller of MY_cpuidex_HACK() sets ECX as subFunction, and
74 old MSVC for __cpuid() doesn't change ECX and cpuid instruction gets (subFunction) value. 224 old MSVC for __cpuid() doesn't change ECX and cpuid instruction gets (subFunction) value.
75 225
76 DON'T remove MY_NO_INLINE and MY_FAST_CALL for MY__cpuidex_HACK() !!! 226DON'T remove Z7_NO_INLINE and Z7_FASTCALL for MY_cpuidex_HACK(): !!!
77*/ 227*/
78
79static 228static
80MY_NO_INLINE 229Z7_NO_INLINE void Z7_FASTCALL MY_cpuidex_HACK(UInt32 subFunction, UInt32 func, int *CPUInfo)
81void MY_FAST_CALL MY__cpuidex_HACK(UInt32 subFunction, int *CPUInfo, UInt32 function)
82{ 230{
83 UNUSED_VAR(subFunction); 231 UNUSED_VAR(subFunction)
84 __cpuid(CPUInfo, function); 232 __cpuid(CPUInfo, func);
85} 233}
86 234 #define MY_cpuidex(info, func, func2) MY_cpuidex_HACK(func2, func, info)
87 #define MY__cpuidex(info, func, func2) MY__cpuidex_HACK(func2, info, func) 235 #pragma message("======== MY_cpuidex_HACK WAS USED ========")
88 #pragma message("======== MY__cpuidex_HACK WAS USED ========") 236 #endif // _MSC_VER >= 1600
89 #endif 237
90 #else 238#if !defined(MY_CPU_AMD64)
91 #define MY__cpuidex(info, func, func2) __cpuid(info, func) 239/* inlining for __cpuid() in MSVC x86 (32-bit) produces big ineffective code,
92 #pragma message("======== (INCORRECT ?) cpuid WAS USED ========") 240 so we disable inlining here */
93 #endif 241Z7_NO_INLINE
94#endif 242#endif
95 243void Z7_FASTCALL z7_x86_cpuid(UInt32 p[4], UInt32 func)
96
97
98
99void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d)
100{ 244{
101 #ifdef USE_ASM 245 MY_cpuidex((int *)p, (int)func, 0);
102 246}
103 #ifdef _MSC_VER
104
105 UInt32 a2, b2, c2, d2;
106 __asm xor EBX, EBX;
107 __asm xor ECX, ECX;
108 __asm xor EDX, EDX;
109 __asm mov EAX, function;
110 __asm cpuid;
111 __asm mov a2, EAX;
112 __asm mov b2, EBX;
113 __asm mov c2, ECX;
114 __asm mov d2, EDX;
115
116 *a = a2;
117 *b = b2;
118 *c = c2;
119 *d = d2;
120
121 #else
122
123 __asm__ __volatile__ (
124 #if defined(MY_CPU_AMD64) && defined(__PIC__)
125 "mov %%rbx, %%rdi;"
126 "cpuid;"
127 "xchg %%rbx, %%rdi;"
128 : "=a" (*a) ,
129 "=D" (*b) ,
130 #elif defined(MY_CPU_X86) && defined(__PIC__)
131 "mov %%ebx, %%edi;"
132 "cpuid;"
133 "xchgl %%ebx, %%edi;"
134 : "=a" (*a) ,
135 "=D" (*b) ,
136 #else
137 "cpuid"
138 : "=a" (*a) ,
139 "=b" (*b) ,
140 #endif
141 "=c" (*c) ,
142 "=d" (*d)
143 : "0" (function), "c"(0) ) ;
144
145 #endif
146
147 #else
148 247
149 int CPUInfo[4]; 248Z7_NO_INLINE
249UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void)
250{
251 int a[4];
252 MY_cpuidex(a, 0, 0);
253 return a[0];
254}
150 255
151 MY__cpuidex(CPUInfo, (int)function, 0); 256#endif // MY_CPU_AMD64
257#endif // _MSC_VER
152 258
153 *a = (UInt32)CPUInfo[0]; 259#if defined(NEED_CHECK_FOR_CPUID)
154 *b = (UInt32)CPUInfo[1]; 260#define CHECK_CPUID_IS_SUPPORTED { if (z7_x86_cpuid_GetMaxFunc() == 0) return 0; }
155 *c = (UInt32)CPUInfo[2]; 261#else
156 *d = (UInt32)CPUInfo[3]; 262#define CHECK_CPUID_IS_SUPPORTED
263#endif
264#undef NEED_CHECK_FOR_CPUID
157 265
158 #endif
159}
160 266
161BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p) 267static
268BoolInt x86cpuid_Func_1(UInt32 *p)
162{ 269{
163 CHECK_CPUID_IS_SUPPORTED 270 CHECK_CPUID_IS_SUPPORTED
164 MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]); 271 z7_x86_cpuid(p, 1);
165 MyCPUID(1, &p->ver, &p->b, &p->c, &p->d);
166 return True; 272 return True;
167} 273}
168 274
169static const UInt32 kVendors[][3] = 275/*
276static const UInt32 kVendors[][1] =
170{ 277{
171 { 0x756E6547, 0x49656E69, 0x6C65746E}, 278 { 0x756E6547 }, // , 0x49656E69, 0x6C65746E },
172 { 0x68747541, 0x69746E65, 0x444D4163}, 279 { 0x68747541 }, // , 0x69746E65, 0x444D4163 },
173 { 0x746E6543, 0x48727561, 0x736C7561} 280 { 0x746E6543 } // , 0x48727561, 0x736C7561 }
174}; 281};
282*/
283
284/*
285typedef struct
286{
287 UInt32 maxFunc;
288 UInt32 vendor[3];
289 UInt32 ver;
290 UInt32 b;
291 UInt32 c;
292 UInt32 d;
293} Cx86cpuid;
294
295enum
296{
297 CPU_FIRM_INTEL,
298 CPU_FIRM_AMD,
299 CPU_FIRM_VIA
300};
301int x86cpuid_GetFirm(const Cx86cpuid *p);
302#define x86cpuid_ver_GetFamily(ver) (((ver >> 16) & 0xff0) | ((ver >> 8) & 0xf))
303#define x86cpuid_ver_GetModel(ver) (((ver >> 12) & 0xf0) | ((ver >> 4) & 0xf))
304#define x86cpuid_ver_GetStepping(ver) (ver & 0xf)
175 305
176int x86cpuid_GetFirm(const Cx86cpuid *p) 306int x86cpuid_GetFirm(const Cx86cpuid *p)
177{ 307{
178 unsigned i; 308 unsigned i;
179 for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++) 309 for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[0]); i++)
180 { 310 {
181 const UInt32 *v = kVendors[i]; 311 const UInt32 *v = kVendors[i];
182 if (v[0] == p->vendor[0] && 312 if (v[0] == p->vendor[0]
183 v[1] == p->vendor[1] && 313 // && v[1] == p->vendor[1]
184 v[2] == p->vendor[2]) 314 // && v[2] == p->vendor[2]
315 )
185 return (int)i; 316 return (int)i;
186 } 317 }
187 return -1; 318 return -1;
@@ -190,41 +321,55 @@ int x86cpuid_GetFirm(const Cx86cpuid *p)
190BoolInt CPU_Is_InOrder() 321BoolInt CPU_Is_InOrder()
191{ 322{
192 Cx86cpuid p; 323 Cx86cpuid p;
193 int firm;
194 UInt32 family, model; 324 UInt32 family, model;
195 if (!x86cpuid_CheckAndRead(&p)) 325 if (!x86cpuid_CheckAndRead(&p))
196 return True; 326 return True;
197 327
198 family = x86cpuid_GetFamily(p.ver); 328 family = x86cpuid_ver_GetFamily(p.ver);
199 model = x86cpuid_GetModel(p.ver); 329 model = x86cpuid_ver_GetModel(p.ver);
200
201 firm = x86cpuid_GetFirm(&p);
202 330
203 switch (firm) 331 switch (x86cpuid_GetFirm(&p))
204 { 332 {
205 case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && ( 333 case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && (
206 /* In-Order Atom CPU */ 334 // In-Order Atom CPU
207 model == 0x1C /* 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330 */ 335 model == 0x1C // 45 nm, N4xx, D4xx, N5xx, D5xx, 230, 330
208 || model == 0x26 /* 45 nm, Z6xx */ 336 || model == 0x26 // 45 nm, Z6xx
209 || model == 0x27 /* 32 nm, Z2460 */ 337 || model == 0x27 // 32 nm, Z2460
210 || model == 0x35 /* 32 nm, Z2760 */ 338 || model == 0x35 // 32 nm, Z2760
211 || model == 0x36 /* 32 nm, N2xxx, D2xxx */ 339 || model == 0x36 // 32 nm, N2xxx, D2xxx
212 ))); 340 )));
213 case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA))); 341 case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA)));
214 case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF)); 342 case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF));
215 } 343 }
216 return True; 344 return False; // v23 : unknown processors are not In-Order
217} 345}
346*/
347
348#ifdef _WIN32
349#include "7zWindows.h"
350#endif
218 351
219#if !defined(MY_CPU_AMD64) && defined(_WIN32) 352#if !defined(MY_CPU_AMD64) && defined(_WIN32)
220#include <Windows.h> 353
221static BoolInt CPU_Sys_Is_SSE_Supported() 354/* for legacy SSE ia32: there is no user-space cpu instruction to check
355 that OS supports SSE register storing/restoring on context switches.
356 So we need some OS-specific function to check that it's safe to use SSE registers.
357*/
358
359Z7_FORCE_INLINE
360static BoolInt CPU_Sys_Is_SSE_Supported(void)
222{ 361{
223 OSVERSIONINFO vi; 362#ifdef _MSC_VER
224 vi.dwOSVersionInfoSize = sizeof(vi); 363 #pragma warning(push)
225 if (!GetVersionEx(&vi)) 364 #pragma warning(disable : 4996) // `GetVersion': was declared deprecated
226 return False; 365#endif
227 return (vi.dwMajorVersion >= 5); 366 /* low byte is major version of Windows
367 We suppose that any Windows version since
368 Windows2000 (major == 5) supports SSE registers */
369 return (Byte)GetVersion() >= 5;
370#if defined(_MSC_VER)
371 #pragma warning(pop)
372#endif
228} 373}
229#define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False; 374#define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False;
230#else 375#else
@@ -232,94 +377,300 @@ static BoolInt CPU_Sys_Is_SSE_Supported()
232#endif 377#endif
233 378
234 379
235static UInt32 X86_CPUID_ECX_Get_Flags() 380#if !defined(MY_CPU_AMD64)
381
382BoolInt CPU_IsSupported_CMOV(void)
236{ 383{
237 Cx86cpuid p; 384 UInt32 a[4];
385 if (!x86cpuid_Func_1(&a[0]))
386 return 0;
387 return (a[3] >> 15) & 1;
388}
389
390BoolInt CPU_IsSupported_SSE(void)
391{
392 UInt32 a[4];
238 CHECK_SYS_SSE_SUPPORT 393 CHECK_SYS_SSE_SUPPORT
239 if (!x86cpuid_CheckAndRead(&p)) 394 if (!x86cpuid_Func_1(&a[0]))
395 return 0;
396 return (a[3] >> 25) & 1;
397}
398
399BoolInt CPU_IsSupported_SSE2(void)
400{
401 UInt32 a[4];
402 CHECK_SYS_SSE_SUPPORT
403 if (!x86cpuid_Func_1(&a[0]))
404 return 0;
405 return (a[3] >> 26) & 1;
406}
407
408#endif
409
410
411static UInt32 x86cpuid_Func_1_ECX(void)
412{
413 UInt32 a[4];
414 CHECK_SYS_SSE_SUPPORT
415 if (!x86cpuid_Func_1(&a[0]))
240 return 0; 416 return 0;
241 return p.c; 417 return a[2];
242} 418}
243 419
244BoolInt CPU_IsSupported_AES() 420BoolInt CPU_IsSupported_AES(void)
245{ 421{
246 return (X86_CPUID_ECX_Get_Flags() >> 25) & 1; 422 return (x86cpuid_Func_1_ECX() >> 25) & 1;
247} 423}
248 424
249BoolInt CPU_IsSupported_SSSE3() 425BoolInt CPU_IsSupported_SSSE3(void)
250{ 426{
251 return (X86_CPUID_ECX_Get_Flags() >> 9) & 1; 427 return (x86cpuid_Func_1_ECX() >> 9) & 1;
252} 428}
253 429
254BoolInt CPU_IsSupported_SSE41() 430BoolInt CPU_IsSupported_SSE41(void)
255{ 431{
256 return (X86_CPUID_ECX_Get_Flags() >> 19) & 1; 432 return (x86cpuid_Func_1_ECX() >> 19) & 1;
257} 433}
258 434
259BoolInt CPU_IsSupported_SHA() 435BoolInt CPU_IsSupported_SHA(void)
260{ 436{
261 Cx86cpuid p;
262 CHECK_SYS_SSE_SUPPORT 437 CHECK_SYS_SSE_SUPPORT
263 if (!x86cpuid_CheckAndRead(&p))
264 return False;
265 438
266 if (p.maxFunc < 7) 439 if (z7_x86_cpuid_GetMaxFunc() < 7)
267 return False; 440 return False;
268 { 441 {
269 UInt32 d[4] = { 0 }; 442 UInt32 d[4];
270 MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); 443 z7_x86_cpuid(d, 7);
271 return (d[1] >> 29) & 1; 444 return (d[1] >> 29) & 1;
272 } 445 }
273} 446}
274 447
275// #include <stdio.h> 448/*
449MSVC: _xgetbv() intrinsic is available since VS2010SP1.
450 MSVC also defines (_XCR_XFEATURE_ENABLED_MASK) macro in
451 <immintrin.h> that we can use or check.
452 For any 32-bit x86 we can use asm code in MSVC,
453 but MSVC asm code is huge after compilation.
454 So _xgetbv() is better
455
456ICC: _xgetbv() intrinsic is available (in what version of ICC?)
457 ICC defines (__GNUC___) and it supports gnu assembler
458 also ICC supports MASM style code with -use-msasm switch.
459 but ICC doesn't support __attribute__((__target__))
460
461GCC/CLANG 9:
462 _xgetbv() is macro that works via __builtin_ia32_xgetbv()
463 and we need __attribute__((__target__("xsave")).
464 But with __target__("xsave") the function will be not
465 inlined to function that has no __target__("xsave") attribute.
466 If we want _xgetbv() call inlining, then we should use asm version
467 instead of calling _xgetbv().
468 Note:intrinsic is broke before GCC 8.2:
469 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85684
470*/
276 471
277#ifdef _WIN32 472#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1100) \
278#include <Windows.h> 473 || defined(_MSC_VER) && (_MSC_VER >= 1600) && (_MSC_FULL_VER >= 160040219) \
474 || defined(__GNUC__) && (__GNUC__ >= 9) \
475 || defined(__clang__) && (__clang_major__ >= 9)
476// we define ATTRIB_XGETBV, if we want to use predefined _xgetbv() from compiler
477#if defined(__INTEL_COMPILER)
478#define ATTRIB_XGETBV
479#elif defined(__GNUC__) || defined(__clang__)
480// we don't define ATTRIB_XGETBV here, because asm version is better for inlining.
481// #define ATTRIB_XGETBV __attribute__((__target__("xsave")))
482#else
483#define ATTRIB_XGETBV
484#endif
485#endif
486
487#if defined(ATTRIB_XGETBV)
488#include <immintrin.h>
279#endif 489#endif
280 490
281BoolInt CPU_IsSupported_AVX2() 491
492// XFEATURE_ENABLED_MASK/XCR0
493#define MY_XCR_XFEATURE_ENABLED_MASK 0
494
495#if defined(ATTRIB_XGETBV)
496ATTRIB_XGETBV
497#endif
498static UInt64 x86_xgetbv_0(UInt32 num)
282{ 499{
283 Cx86cpuid p; 500#if defined(ATTRIB_XGETBV)
284 CHECK_SYS_SSE_SUPPORT 501 {
502 return
503 #if (defined(_MSC_VER))
504 _xgetbv(num);
505 #else
506 __builtin_ia32_xgetbv(
507 #if !defined(__clang__)
508 (int)
509 #endif
510 num);
511 #endif
512 }
513
514#elif defined(__GNUC__) || defined(__clang__) || defined(__SUNPRO_CC)
515
516 UInt32 a, d;
517 #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
518 __asm__
519 (
520 "xgetbv"
521 : "=a"(a), "=d"(d) : "c"(num) : "cc"
522 );
523 #else // is old gcc
524 __asm__
525 (
526 ".byte 0x0f, 0x01, 0xd0" "\n\t"
527 : "=a"(a), "=d"(d) : "c"(num) : "cc"
528 );
529 #endif
530 return ((UInt64)d << 32) | a;
531 // return a;
532
533#elif defined(_MSC_VER) && !defined(MY_CPU_AMD64)
534
535 UInt32 a, d;
536 __asm {
537 push eax
538 push edx
539 push ecx
540 mov ecx, num;
541 // xor ecx, ecx // = MY_XCR_XFEATURE_ENABLED_MASK
542 _emit 0x0f
543 _emit 0x01
544 _emit 0xd0
545 mov a, eax
546 mov d, edx
547 pop ecx
548 pop edx
549 pop eax
550 }
551 return ((UInt64)d << 32) | a;
552 // return a;
553
554#else // it's unknown compiler
555 // #error "Need xgetbv function"
556 UNUSED_VAR(num)
557 // for MSVC-X64 we could call external function from external file.
558 /* Actually we had checked OSXSAVE/AVX in cpuid before.
559 So it's expected that OS supports at least AVX and below. */
560 // if (num != MY_XCR_XFEATURE_ENABLED_MASK) return 0; // if not XCR0
561 return
562 // (1 << 0) | // x87
563 (1 << 1) // SSE
564 | (1 << 2); // AVX
565
566#endif
567}
285 568
569#ifdef _WIN32
570/*
571 Windows versions do not know about new ISA extensions that
572 can be introduced. But we still can use new extensions,
573 even if Windows doesn't report about supporting them,
574 But we can use new extensions, only if Windows knows about new ISA extension
575 that changes the number or size of registers: SSE, AVX/XSAVE, AVX512
576 So it's enough to check
577 MY_PF_AVX_INSTRUCTIONS_AVAILABLE
578 instead of
579 MY_PF_AVX2_INSTRUCTIONS_AVAILABLE
580*/
581#define MY_PF_XSAVE_ENABLED 17
582// #define MY_PF_SSSE3_INSTRUCTIONS_AVAILABLE 36
583// #define MY_PF_SSE4_1_INSTRUCTIONS_AVAILABLE 37
584// #define MY_PF_SSE4_2_INSTRUCTIONS_AVAILABLE 38
585// #define MY_PF_AVX_INSTRUCTIONS_AVAILABLE 39
586// #define MY_PF_AVX2_INSTRUCTIONS_AVAILABLE 40
587// #define MY_PF_AVX512F_INSTRUCTIONS_AVAILABLE 41
588#endif
589
590BoolInt CPU_IsSupported_AVX(void)
591{
286 #ifdef _WIN32 592 #ifdef _WIN32
287 #define MY__PF_XSAVE_ENABLED 17 593 if (!IsProcessorFeaturePresent(MY_PF_XSAVE_ENABLED))
288 if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED))
289 return False; 594 return False;
595 /* PF_AVX_INSTRUCTIONS_AVAILABLE probably is supported starting from
596 some latest Win10 revisions. But we need AVX in older Windows also.
597 So we don't use the following check: */
598 /*
599 if (!IsProcessorFeaturePresent(MY_PF_AVX_INSTRUCTIONS_AVAILABLE))
600 return False;
601 */
290 #endif 602 #endif
291 603
292 if (!x86cpuid_CheckAndRead(&p)) 604 /*
605 OS must use new special XSAVE/XRSTOR instructions to save
606 AVX registers when it required for context switching.
607 At OS statring:
608 OS sets CR4.OSXSAVE flag to signal the processor that OS supports the XSAVE extensions.
609 Also OS sets bitmask in XCR0 register that defines what
610 registers will be processed by XSAVE instruction:
611 XCR0.SSE[bit 0] - x87 registers and state
612 XCR0.SSE[bit 1] - SSE registers and state
613 XCR0.AVX[bit 2] - AVX registers and state
614 CR4.OSXSAVE is reflected to CPUID.1:ECX.OSXSAVE[bit 27].
615 So we can read that bit in user-space.
616 XCR0 is available for reading in user-space by new XGETBV instruction.
617 */
618 {
619 const UInt32 c = x86cpuid_Func_1_ECX();
620 if (0 == (1
621 & (c >> 28) // AVX instructions are supported by hardware
622 & (c >> 27))) // OSXSAVE bit: XSAVE and related instructions are enabled by OS.
623 return False;
624 }
625
626 /* also we can check
627 CPUID.1:ECX.XSAVE [bit 26] : that shows that
628 XSAVE, XRESTOR, XSETBV, XGETBV instructions are supported by hardware.
629 But that check is redundant, because if OSXSAVE bit is set, then XSAVE is also set */
630
631 /* If OS have enabled XSAVE extension instructions (OSXSAVE == 1),
632 in most cases we expect that OS also will support storing/restoring
633 for AVX and SSE states at least.
634 But to be ensure for that we call user-space instruction
635 XGETBV(0) to get XCR0 value that contains bitmask that defines
636 what exact states(registers) OS have enabled for storing/restoring.
637 */
638
639 {
640 const UInt32 bm = (UInt32)x86_xgetbv_0(MY_XCR_XFEATURE_ENABLED_MASK);
641 // printf("\n=== XGetBV=%d\n", bm);
642 return 1
643 & (bm >> 1) // SSE state is supported (set by OS) for storing/restoring
644 & (bm >> 2); // AVX state is supported (set by OS) for storing/restoring
645 }
646 // since Win7SP1: we can use GetEnabledXStateFeatures();
647}
648
649
650BoolInt CPU_IsSupported_AVX2(void)
651{
652 if (!CPU_IsSupported_AVX())
293 return False; 653 return False;
294 if (p.maxFunc < 7) 654 if (z7_x86_cpuid_GetMaxFunc() < 7)
295 return False; 655 return False;
296 { 656 {
297 UInt32 d[4] = { 0 }; 657 UInt32 d[4];
298 MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); 658 z7_x86_cpuid(d, 7);
299 // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); 659 // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]);
300 return 1 660 return 1
301 & (d[1] >> 5); // avx2 661 & (d[1] >> 5); // avx2
302 } 662 }
303} 663}
304 664
305BoolInt CPU_IsSupported_VAES_AVX2() 665BoolInt CPU_IsSupported_VAES_AVX2(void)
306{ 666{
307 Cx86cpuid p; 667 if (!CPU_IsSupported_AVX())
308 CHECK_SYS_SSE_SUPPORT
309
310 #ifdef _WIN32
311 #define MY__PF_XSAVE_ENABLED 17
312 if (!IsProcessorFeaturePresent(MY__PF_XSAVE_ENABLED))
313 return False; 668 return False;
314 #endif 669 if (z7_x86_cpuid_GetMaxFunc() < 7)
315
316 if (!x86cpuid_CheckAndRead(&p))
317 return False;
318 if (p.maxFunc < 7)
319 return False; 670 return False;
320 { 671 {
321 UInt32 d[4] = { 0 }; 672 UInt32 d[4];
322 MyCPUID(7, &d[0], &d[1], &d[2], &d[3]); 673 z7_x86_cpuid(d, 7);
323 // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]); 674 // printf("\ncpuid(7): ebx=%8x ecx=%8x\n", d[1], d[2]);
324 return 1 675 return 1
325 & (d[1] >> 5) // avx2 676 & (d[1] >> 5) // avx2
@@ -328,20 +679,15 @@ BoolInt CPU_IsSupported_VAES_AVX2()
328 } 679 }
329} 680}
330 681
331BoolInt CPU_IsSupported_PageGB() 682BoolInt CPU_IsSupported_PageGB(void)
332{ 683{
333 Cx86cpuid cpuid; 684 CHECK_CPUID_IS_SUPPORTED
334 if (!x86cpuid_CheckAndRead(&cpuid))
335 return False;
336 { 685 {
337 UInt32 d[4] = { 0 }; 686 UInt32 d[4];
338 MyCPUID(0x80000000, &d[0], &d[1], &d[2], &d[3]); 687 z7_x86_cpuid(d, 0x80000000);
339 if (d[0] < 0x80000001) 688 if (d[0] < 0x80000001)
340 return False; 689 return False;
341 } 690 z7_x86_cpuid(d, 0x80000001);
342 {
343 UInt32 d[4] = { 0 };
344 MyCPUID(0x80000001, &d[0], &d[1], &d[2], &d[3]);
345 return (d[3] >> 26) & 1; 691 return (d[3] >> 26) & 1;
346 } 692 }
347} 693}
@@ -351,11 +697,11 @@ BoolInt CPU_IsSupported_PageGB()
351 697
352#ifdef _WIN32 698#ifdef _WIN32
353 699
354#include <Windows.h> 700#include "7zWindows.h"
355 701
356BoolInt CPU_IsSupported_CRC32() { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } 702BoolInt CPU_IsSupported_CRC32(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) ? 1 : 0; }
357BoolInt CPU_IsSupported_CRYPTO() { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } 703BoolInt CPU_IsSupported_CRYPTO(void) { return IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) ? 1 : 0; }
358BoolInt CPU_IsSupported_NEON() { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; } 704BoolInt CPU_IsSupported_NEON(void) { return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) ? 1 : 0; }
359 705
360#else 706#else
361 707
@@ -378,28 +724,27 @@ static void Print_sysctlbyname(const char *name)
378 } 724 }
379} 725}
380*/ 726*/
727/*
728 Print_sysctlbyname("hw.pagesize");
729 Print_sysctlbyname("machdep.cpu.brand_string");
730*/
381 731
382static BoolInt My_sysctlbyname_Get_BoolInt(const char *name) 732static BoolInt z7_sysctlbyname_Get_BoolInt(const char *name)
383{ 733{
384 UInt32 val = 0; 734 UInt32 val = 0;
385 if (My_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1) 735 if (z7_sysctlbyname_Get_UInt32(name, &val) == 0 && val == 1)
386 return 1; 736 return 1;
387 return 0; 737 return 0;
388} 738}
389 739
390 /*
391 Print_sysctlbyname("hw.pagesize");
392 Print_sysctlbyname("machdep.cpu.brand_string");
393 */
394
395BoolInt CPU_IsSupported_CRC32(void) 740BoolInt CPU_IsSupported_CRC32(void)
396{ 741{
397 return My_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32"); 742 return z7_sysctlbyname_Get_BoolInt("hw.optional.armv8_crc32");
398} 743}
399 744
400BoolInt CPU_IsSupported_NEON(void) 745BoolInt CPU_IsSupported_NEON(void)
401{ 746{
402 return My_sysctlbyname_Get_BoolInt("hw.optional.neon"); 747 return z7_sysctlbyname_Get_BoolInt("hw.optional.neon");
403} 748}
404 749
405#ifdef MY_CPU_ARM64 750#ifdef MY_CPU_ARM64
@@ -461,15 +806,15 @@ MY_HWCAP_CHECK_FUNC (AES)
461 806
462#include <sys/sysctl.h> 807#include <sys/sysctl.h>
463 808
464int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize) 809int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize)
465{ 810{
466 return sysctlbyname(name, buf, bufSize, NULL, 0); 811 return sysctlbyname(name, buf, bufSize, NULL, 0);
467} 812}
468 813
469int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val) 814int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val)
470{ 815{
471 size_t bufSize = sizeof(*val); 816 size_t bufSize = sizeof(*val);
472 int res = My_sysctlbyname_Get(name, val, &bufSize); 817 const int res = z7_sysctlbyname_Get(name, val, &bufSize);
473 if (res == 0 && bufSize != sizeof(*val)) 818 if (res == 0 && bufSize != sizeof(*val))
474 return EFAULT; 819 return EFAULT;
475 return res; 820 return res;
diff --git a/C/CpuArch.h b/C/CpuArch.h
index 4856fbb..8e5d8a5 100644
--- a/C/CpuArch.h
+++ b/C/CpuArch.h
@@ -1,8 +1,8 @@
1/* CpuArch.h -- CPU specific code 1/* CpuArch.h -- CPU specific code
22022-07-15 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __CPU_ARCH_H 4#ifndef ZIP7_INC_CPU_ARCH_H
5#define __CPU_ARCH_H 5#define ZIP7_INC_CPU_ARCH_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -51,7 +51,13 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
51 || defined(__AARCH64EB__) \ 51 || defined(__AARCH64EB__) \
52 || defined(__aarch64__) 52 || defined(__aarch64__)
53 #define MY_CPU_ARM64 53 #define MY_CPU_ARM64
54 #define MY_CPU_NAME "arm64" 54 #ifdef __ILP32__
55 #define MY_CPU_NAME "arm64-32"
56 #define MY_CPU_SIZEOF_POINTER 4
57 #else
58 #define MY_CPU_NAME "arm64"
59 #define MY_CPU_SIZEOF_POINTER 8
60 #endif
55 #define MY_CPU_64BIT 61 #define MY_CPU_64BIT
56#endif 62#endif
57 63
@@ -68,8 +74,10 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
68 #define MY_CPU_ARM 74 #define MY_CPU_ARM
69 75
70 #if defined(__thumb__) || defined(__THUMBEL__) || defined(_M_ARMT) 76 #if defined(__thumb__) || defined(__THUMBEL__) || defined(_M_ARMT)
77 #define MY_CPU_ARMT
71 #define MY_CPU_NAME "armt" 78 #define MY_CPU_NAME "armt"
72 #else 79 #else
80 #define MY_CPU_ARM32
73 #define MY_CPU_NAME "arm" 81 #define MY_CPU_NAME "arm"
74 #endif 82 #endif
75 /* #define MY_CPU_32BIT */ 83 /* #define MY_CPU_32BIT */
@@ -103,6 +111,8 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
103 || defined(__PPC__) \ 111 || defined(__PPC__) \
104 || defined(_POWER) 112 || defined(_POWER)
105 113
114#define MY_CPU_PPC_OR_PPC64
115
106#if defined(__ppc64__) \ 116#if defined(__ppc64__) \
107 || defined(__powerpc64__) \ 117 || defined(__powerpc64__) \
108 || defined(_LP64) \ 118 || defined(_LP64) \
@@ -197,6 +207,9 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
197 #error Stop_Compiling_Bad_Endian 207 #error Stop_Compiling_Bad_Endian
198#endif 208#endif
199 209
210#if !defined(MY_CPU_LE) && !defined(MY_CPU_BE)
211 #error Stop_Compiling_CPU_ENDIAN_must_be_detected_at_compile_time
212#endif
200 213
201#if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) 214#if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT)
202 #error Stop_Compiling_Bad_32_64_BIT 215 #error Stop_Compiling_Bad_32_64_BIT
@@ -253,6 +266,67 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
253 266
254 267
255 268
269#ifdef __has_builtin
270 #define Z7_has_builtin(x) __has_builtin(x)
271#else
272 #define Z7_has_builtin(x) 0
273#endif
274
275
276#define Z7_BSWAP32_CONST(v) \
277 ( (((UInt32)(v) << 24) ) \
278 | (((UInt32)(v) << 8) & (UInt32)0xff0000) \
279 | (((UInt32)(v) >> 8) & (UInt32)0xff00 ) \
280 | (((UInt32)(v) >> 24) ))
281
282
283#if defined(_MSC_VER) && (_MSC_VER >= 1300)
284
285#include <stdlib.h>
286
287/* Note: these macros will use bswap instruction (486), that is unsupported in 386 cpu */
288
289#pragma intrinsic(_byteswap_ushort)
290#pragma intrinsic(_byteswap_ulong)
291#pragma intrinsic(_byteswap_uint64)
292
293#define Z7_BSWAP16(v) _byteswap_ushort(v)
294#define Z7_BSWAP32(v) _byteswap_ulong (v)
295#define Z7_BSWAP64(v) _byteswap_uint64(v)
296#define Z7_CPU_FAST_BSWAP_SUPPORTED
297
298#elif (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \
299 || (defined(__clang__) && Z7_has_builtin(__builtin_bswap16))
300
301#define Z7_BSWAP16(v) __builtin_bswap16(v)
302#define Z7_BSWAP32(v) __builtin_bswap32(v)
303#define Z7_BSWAP64(v) __builtin_bswap64(v)
304#define Z7_CPU_FAST_BSWAP_SUPPORTED
305
306#else
307
308#define Z7_BSWAP16(v) ((UInt16) \
309 ( ((UInt32)(v) << 8) \
310 | ((UInt32)(v) >> 8) \
311 ))
312
313#define Z7_BSWAP32(v) Z7_BSWAP32_CONST(v)
314
315#define Z7_BSWAP64(v) \
316 ( ( ( (UInt64)(v) ) << 8 * 7 ) \
317 | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 1) ) << 8 * 5 ) \
318 | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 2) ) << 8 * 3 ) \
319 | ( ( (UInt64)(v) & ((UInt32)0xff << 8 * 3) ) << 8 * 1 ) \
320 | ( ( (UInt64)(v) >> 8 * 1 ) & ((UInt32)0xff << 8 * 3) ) \
321 | ( ( (UInt64)(v) >> 8 * 3 ) & ((UInt32)0xff << 8 * 2) ) \
322 | ( ( (UInt64)(v) >> 8 * 5 ) & ((UInt32)0xff << 8 * 1) ) \
323 | ( ( (UInt64)(v) >> 8 * 7 ) ) \
324 )
325
326#endif
327
328
329
256#ifdef MY_CPU_LE 330#ifdef MY_CPU_LE
257 #if defined(MY_CPU_X86_OR_AMD64) \ 331 #if defined(MY_CPU_X86_OR_AMD64) \
258 || defined(MY_CPU_ARM64) 332 || defined(MY_CPU_ARM64)
@@ -272,13 +346,11 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
272#define GetUi32(p) (*(const UInt32 *)(const void *)(p)) 346#define GetUi32(p) (*(const UInt32 *)(const void *)(p))
273#ifdef MY_CPU_LE_UNALIGN_64 347#ifdef MY_CPU_LE_UNALIGN_64
274#define GetUi64(p) (*(const UInt64 *)(const void *)(p)) 348#define GetUi64(p) (*(const UInt64 *)(const void *)(p))
349#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); }
275#endif 350#endif
276 351
277#define SetUi16(p, v) { *(UInt16 *)(void *)(p) = (v); } 352#define SetUi16(p, v) { *(UInt16 *)(void *)(p) = (v); }
278#define SetUi32(p, v) { *(UInt32 *)(void *)(p) = (v); } 353#define SetUi32(p, v) { *(UInt32 *)(void *)(p) = (v); }
279#ifdef MY_CPU_LE_UNALIGN_64
280#define SetUi64(p, v) { *(UInt64 *)(void *)(p) = (v); }
281#endif
282 354
283#else 355#else
284 356
@@ -305,51 +377,26 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
305#endif 377#endif
306 378
307 379
308#ifndef MY_CPU_LE_UNALIGN_64 380#ifndef GetUi64
309
310#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) 381#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32))
382#endif
311 383
384#ifndef SetUi64
312#define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ 385#define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \
313 SetUi32(_ppp2_ , (UInt32)_vvv2_); \ 386 SetUi32(_ppp2_ , (UInt32)_vvv2_) \
314 SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } 387 SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)) }
315
316#endif 388#endif
317 389
318 390
391#if defined(MY_CPU_LE_UNALIGN) && defined(Z7_CPU_FAST_BSWAP_SUPPORTED)
319 392
393#define GetBe32(p) Z7_BSWAP32 (*(const UInt32 *)(const void *)(p))
394#define SetBe32(p, v) { (*(UInt32 *)(void *)(p)) = Z7_BSWAP32(v); }
320 395
321#ifdef __has_builtin 396#if defined(MY_CPU_LE_UNALIGN_64)
322 #define MY__has_builtin(x) __has_builtin(x) 397#define GetBe64(p) Z7_BSWAP64 (*(const UInt64 *)(const void *)(p))
323#else
324 #define MY__has_builtin(x) 0
325#endif 398#endif
326 399
327#if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ defined(_MSC_VER) && (_MSC_VER >= 1300)
328
329/* Note: we use bswap instruction, that is unsupported in 386 cpu */
330
331#include <stdlib.h>
332
333#pragma intrinsic(_byteswap_ushort)
334#pragma intrinsic(_byteswap_ulong)
335#pragma intrinsic(_byteswap_uint64)
336
337/* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */
338#define GetBe32(p) _byteswap_ulong (*(const UInt32 *)(const void *)(p))
339#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const void *)(p))
340
341#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v)
342
343#elif defined(MY_CPU_LE_UNALIGN) && ( \
344 (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \
345 || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) )
346
347/* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const void *)(p)) */
348#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const void *)(p))
349#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const void *)(p))
350
351#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v)
352
353#else 400#else
354 401
355#define GetBe32(p) ( \ 402#define GetBe32(p) ( \
@@ -358,8 +405,6 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
358 ((UInt32)((const Byte *)(p))[2] << 8) | \ 405 ((UInt32)((const Byte *)(p))[2] << 8) | \
359 ((const Byte *)(p))[3] ) 406 ((const Byte *)(p))[3] )
360 407
361#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4))
362
363#define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ 408#define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \
364 _ppp_[0] = (Byte)(_vvv_ >> 24); \ 409 _ppp_[0] = (Byte)(_vvv_ >> 24); \
365 _ppp_[1] = (Byte)(_vvv_ >> 16); \ 410 _ppp_[1] = (Byte)(_vvv_ >> 16); \
@@ -368,50 +413,83 @@ MY_CPU_64BIT means that processor can work with 64-bit registers.
368 413
369#endif 414#endif
370 415
416#ifndef GetBe64
417#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4))
418#endif
371 419
372#ifndef GetBe16 420#ifndef GetBe16
373
374#define GetBe16(p) ( (UInt16) ( \ 421#define GetBe16(p) ( (UInt16) ( \
375 ((UInt16)((const Byte *)(p))[0] << 8) | \ 422 ((UInt16)((const Byte *)(p))[0] << 8) | \
376 ((const Byte *)(p))[1] )) 423 ((const Byte *)(p))[1] ))
424#endif
425
377 426
427#if defined(MY_CPU_BE)
428#define Z7_CONV_BE_TO_NATIVE_CONST32(v) (v)
429#define Z7_CONV_LE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v)
430#define Z7_CONV_NATIVE_TO_BE_32(v) (v)
431#elif defined(MY_CPU_LE)
432#define Z7_CONV_BE_TO_NATIVE_CONST32(v) Z7_BSWAP32_CONST(v)
433#define Z7_CONV_LE_TO_NATIVE_CONST32(v) (v)
434#define Z7_CONV_NATIVE_TO_BE_32(v) Z7_BSWAP32(v)
435#else
436#error Stop_Compiling_Unknown_Endian_CONV
378#endif 437#endif
379 438
380 439
440#if defined(MY_CPU_BE)
381 441
382#ifdef MY_CPU_X86_OR_AMD64 442#define GetBe32a(p) (*(const UInt32 *)(const void *)(p))
443#define GetBe16a(p) (*(const UInt16 *)(const void *)(p))
444#define SetBe32a(p, v) { *(UInt32 *)(void *)(p) = (v); }
445#define SetBe16a(p, v) { *(UInt16 *)(void *)(p) = (v); }
446
447#define GetUi32a(p) GetUi32(p)
448#define GetUi16a(p) GetUi16(p)
449#define SetUi32a(p, v) SetUi32(p, v)
450#define SetUi16a(p, v) SetUi16(p, v)
451
452#elif defined(MY_CPU_LE)
383 453
384typedef struct 454#define GetUi32a(p) (*(const UInt32 *)(const void *)(p))
385{ 455#define GetUi16a(p) (*(const UInt16 *)(const void *)(p))
386 UInt32 maxFunc; 456#define SetUi32a(p, v) { *(UInt32 *)(void *)(p) = (v); }
387 UInt32 vendor[3]; 457#define SetUi16a(p, v) { *(UInt16 *)(void *)(p) = (v); }
388 UInt32 ver;
389 UInt32 b;
390 UInt32 c;
391 UInt32 d;
392} Cx86cpuid;
393 458
394enum 459#define GetBe32a(p) GetBe32(p)
395{ 460#define GetBe16a(p) GetBe16(p)
396 CPU_FIRM_INTEL, 461#define SetBe32a(p, v) SetBe32(p, v)
397 CPU_FIRM_AMD, 462#define SetBe16a(p, v) SetBe16(p, v)
398 CPU_FIRM_VIA 463
399}; 464#else
465#error Stop_Compiling_Unknown_Endian_CPU_a
466#endif
400 467
401void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d);
402 468
403BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); 469#if defined(MY_CPU_X86_OR_AMD64) \
404int x86cpuid_GetFirm(const Cx86cpuid *p); 470 || defined(MY_CPU_ARM_OR_ARM64) \
471 || defined(MY_CPU_PPC_OR_PPC64)
472 #define Z7_CPU_FAST_ROTATE_SUPPORTED
473#endif
405 474
406#define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF))
407#define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF))
408#define x86cpuid_GetStepping(ver) (ver & 0xF)
409 475
410BoolInt CPU_Is_InOrder(void); 476#ifdef MY_CPU_X86_OR_AMD64
477
478void Z7_FASTCALL z7_x86_cpuid(UInt32 a[4], UInt32 function);
479UInt32 Z7_FASTCALL z7_x86_cpuid_GetMaxFunc(void);
480#if defined(MY_CPU_AMD64)
481#define Z7_IF_X86_CPUID_SUPPORTED
482#else
483#define Z7_IF_X86_CPUID_SUPPORTED if (z7_x86_cpuid_GetMaxFunc())
484#endif
411 485
412BoolInt CPU_IsSupported_AES(void); 486BoolInt CPU_IsSupported_AES(void);
487BoolInt CPU_IsSupported_AVX(void);
413BoolInt CPU_IsSupported_AVX2(void); 488BoolInt CPU_IsSupported_AVX2(void);
414BoolInt CPU_IsSupported_VAES_AVX2(void); 489BoolInt CPU_IsSupported_VAES_AVX2(void);
490BoolInt CPU_IsSupported_CMOV(void);
491BoolInt CPU_IsSupported_SSE(void);
492BoolInt CPU_IsSupported_SSE2(void);
415BoolInt CPU_IsSupported_SSSE3(void); 493BoolInt CPU_IsSupported_SSSE3(void);
416BoolInt CPU_IsSupported_SSE41(void); 494BoolInt CPU_IsSupported_SSE41(void);
417BoolInt CPU_IsSupported_SHA(void); 495BoolInt CPU_IsSupported_SHA(void);
@@ -436,8 +514,8 @@ BoolInt CPU_IsSupported_AES(void);
436#endif 514#endif
437 515
438#if defined(__APPLE__) 516#if defined(__APPLE__)
439int My_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize); 517int z7_sysctlbyname_Get(const char *name, void *buf, size_t *bufSize);
440int My_sysctlbyname_Get_UInt32(const char *name, UInt32 *val); 518int z7_sysctlbyname_Get_UInt32(const char *name, UInt32 *val);
441#endif 519#endif
442 520
443EXTERN_C_END 521EXTERN_C_END
diff --git a/C/Delta.h b/C/Delta.h
index 2fa54ad..7060954 100644
--- a/C/Delta.h
+++ b/C/Delta.h
@@ -1,8 +1,8 @@
1/* Delta.h -- Delta converter 1/* Delta.h -- Delta converter
22013-01-18 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#ifndef __DELTA_H 4#ifndef ZIP7_INC_DELTA_H
5#define __DELTA_H 5#define ZIP7_INC_DELTA_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/DllSecur.c b/C/DllSecur.c
index dce0c96..02a0f97 100644
--- a/C/DllSecur.c
+++ b/C/DllSecur.c
@@ -1,18 +1,28 @@
1/* DllSecur.c -- DLL loading security 1/* DllSecur.c -- DLL loading security
22022-07-15 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#ifdef _WIN32 6#ifdef _WIN32
7 7
8#include <Windows.h> 8#include "7zWindows.h"
9 9
10#include "DllSecur.h" 10#include "DllSecur.h"
11 11
12#ifndef UNDER_CE 12#ifndef UNDER_CE
13 13
14#if defined(__GNUC__) && (__GNUC__ >= 8) 14#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__)
15 #pragma GCC diagnostic ignored "-Wcast-function-type" 15 // #pragma GCC diagnostic ignored "-Wcast-function-type"
16#endif
17
18#if defined(__clang__) || defined(__GNUC__)
19typedef void (*Z7_voidFunction)(void);
20#define MY_CAST_FUNC (Z7_voidFunction)
21#elif defined(_MSC_VER) && _MSC_VER > 1920
22#define MY_CAST_FUNC (void *)
23// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()'
24#else
25#define MY_CAST_FUNC
16#endif 26#endif
17 27
18typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags); 28typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags);
@@ -20,95 +30,82 @@ typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags);
20#define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400 30#define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400
21#define MY_LOAD_LIBRARY_SEARCH_SYSTEM32 0x800 31#define MY_LOAD_LIBRARY_SEARCH_SYSTEM32 0x800
22 32
33#define DELIM "\0"
34
23static const char * const g_Dlls = 35static const char * const g_Dlls =
36 "userenv"
37 DELIM "setupapi"
38 DELIM "apphelp"
39 DELIM "propsys"
40 DELIM "dwmapi"
41 DELIM "cryptbase"
42 DELIM "oleacc"
43 DELIM "clbcatq"
44 DELIM "version"
24 #ifndef _CONSOLE 45 #ifndef _CONSOLE
25 "UXTHEME\0" 46 DELIM "uxtheme"
26 #endif 47 #endif
27 "USERENV\0" 48 DELIM;
28 "SETUPAPI\0"
29 "APPHELP\0"
30 "PROPSYS\0"
31 "DWMAPI\0"
32 "CRYPTBASE\0"
33 "OLEACC\0"
34 "CLBCATQ\0"
35 "VERSION\0"
36 ;
37 49
38#endif 50#endif
39 51
40// #define MY_CAST_FUNC (void(*)()) 52#ifdef __clang__
41#define MY_CAST_FUNC 53 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
54#endif
55#if defined (_MSC_VER) && _MSC_VER >= 1900
56// sysinfoapi.h: kit10: GetVersion was declared deprecated
57#pragma warning(disable : 4996)
58#endif
59
60#define IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN \
61 if ((UInt16)GetVersion() != 6) { \
62 const \
63 Func_SetDefaultDllDirectories setDllDirs = \
64 (Func_SetDefaultDllDirectories) MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \
65 "SetDefaultDllDirectories"); \
66 if (setDllDirs) if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) return; }
42 67
43void My_SetDefaultDllDirectories() 68void My_SetDefaultDllDirectories(void)
44{ 69{
45 #ifndef UNDER_CE 70 #ifndef UNDER_CE
46 71 IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN
47 OSVERSIONINFO vi;
48 vi.dwOSVersionInfoSize = sizeof(vi);
49 if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0)
50 {
51 Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories)
52 MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories");
53 if (setDllDirs)
54 if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS))
55 return;
56 }
57
58 #endif 72 #endif
59} 73}
60 74
61 75
62void LoadSecurityDlls() 76void LoadSecurityDlls(void)
63{ 77{
64 #ifndef UNDER_CE 78 #ifndef UNDER_CE
65 79 // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ???
66 wchar_t buf[MAX_PATH + 100]; 80 IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN
67
68 {
69 // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ???
70 OSVERSIONINFO vi;
71 vi.dwOSVersionInfoSize = sizeof(vi);
72 if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0)
73 {
74 Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories)
75 MY_CAST_FUNC GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories");
76 if (setDllDirs)
77 if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS))
78 return;
79 }
80 }
81
82 {
83 unsigned len = GetSystemDirectoryW(buf, MAX_PATH + 2);
84 if (len == 0 || len > MAX_PATH)
85 return;
86 }
87 { 81 {
82 wchar_t buf[MAX_PATH + 100];
88 const char *dll; 83 const char *dll;
89 unsigned pos = (unsigned)lstrlenW(buf); 84 unsigned pos = GetSystemDirectoryW(buf, MAX_PATH + 2);
90 85 if (pos == 0 || pos > MAX_PATH)
86 return;
91 if (buf[pos - 1] != '\\') 87 if (buf[pos - 1] != '\\')
92 buf[pos++] = '\\'; 88 buf[pos++] = '\\';
93 89 for (dll = g_Dlls; *dll != 0;)
94 for (dll = g_Dlls; dll[0] != 0;)
95 { 90 {
96 unsigned k = 0; 91 wchar_t *dest = &buf[pos];
97 for (;;) 92 for (;;)
98 { 93 {
99 char c = *dll++; 94 const char c = *dll++;
100 buf[pos + k] = (Byte)c;
101 k++;
102 if (c == 0) 95 if (c == 0)
103 break; 96 break;
97 *dest++ = (Byte)c;
104 } 98 }
105 99 dest[0] = '.';
106 lstrcatW(buf, L".dll"); 100 dest[1] = 'd';
101 dest[2] = 'l';
102 dest[3] = 'l';
103 dest[4] = 0;
104 // lstrcatW(buf, L".dll");
107 LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); 105 LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
108 } 106 }
109 } 107 }
110
111 #endif 108 #endif
112} 109}
113 110
114#endif 111#endif // _WIN32
diff --git a/C/DllSecur.h b/C/DllSecur.h
index 64ff26c..9fa4153 100644
--- a/C/DllSecur.h
+++ b/C/DllSecur.h
@@ -1,8 +1,8 @@
1/* DllSecur.h -- DLL loading for security 1/* DllSecur.h -- DLL loading for security
22018-02-19 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#ifndef __DLL_SECUR_H 4#ifndef ZIP7_INC_DLL_SECUR_H
5#define __DLL_SECUR_H 5#define ZIP7_INC_DLL_SECUR_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/HuffEnc.c b/C/HuffEnc.c
index f3c2996..3dc1e39 100644
--- a/C/HuffEnc.c
+++ b/C/HuffEnc.c
@@ -1,5 +1,5 @@
1/* HuffEnc.c -- functions for Huffman encoding 1/* HuffEnc.c -- functions for Huffman encoding
22021-02-09 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -106,7 +106,7 @@ void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymb
106 106
107 p[--e] &= MASK; 107 p[--e] &= MASK;
108 lenCounters[1] = 2; 108 lenCounters[1] = 2;
109 while (e > 0) 109 while (e != 0)
110 { 110 {
111 UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1; 111 UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1;
112 p[e] = (p[e] & MASK) | (len << NUM_BITS); 112 p[e] = (p[e] & MASK) | (len << NUM_BITS);
@@ -146,3 +146,9 @@ void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymb
146 } 146 }
147 } 147 }
148} 148}
149
150#undef kMaxLen
151#undef NUM_BITS
152#undef MASK
153#undef NUM_COUNTERS
154#undef HUFFMAN_SPEED_OPT
diff --git a/C/HuffEnc.h b/C/HuffEnc.h
index 92b6878..cbc5d11 100644
--- a/C/HuffEnc.h
+++ b/C/HuffEnc.h
@@ -1,8 +1,8 @@
1/* HuffEnc.h -- Huffman encoding 1/* HuffEnc.h -- Huffman encoding
22013-01-18 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#ifndef __HUFF_ENC_H 4#ifndef ZIP7_INC_HUFF_ENC_H
5#define __HUFF_ENC_H 5#define ZIP7_INC_HUFF_ENC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/LzFind.c b/C/LzFind.c
index 1b73c28..0fbd5aa 100644
--- a/C/LzFind.c
+++ b/C/LzFind.c
@@ -1,5 +1,5 @@
1/* LzFind.c -- Match finder for LZ algorithms 1/* LzFind.c -- Match finder for LZ algorithms
22021-11-29 : Igor Pavlov : Public domain */ 22023-03-14 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -17,7 +17,7 @@
17#define kEmptyHashValue 0 17#define kEmptyHashValue 0
18 18
19#define kMaxValForNormalize ((UInt32)0) 19#define kMaxValForNormalize ((UInt32)0)
20// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xFFF) // for debug 20// #define kMaxValForNormalize ((UInt32)(1 << 20) + 0xfff) // for debug
21 21
22// #define kNormalizeAlign (1 << 7) // alignment for speculated accesses 22// #define kNormalizeAlign (1 << 7) // alignment for speculated accesses
23 23
@@ -67,10 +67,10 @@
67 67
68static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc) 68static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc)
69{ 69{
70 if (!p->directInput) 70 // if (!p->directInput)
71 { 71 {
72 ISzAlloc_Free(alloc, p->bufferBase); 72 ISzAlloc_Free(alloc, p->bufBase);
73 p->bufferBase = NULL; 73 p->bufBase = NULL;
74 } 74 }
75} 75}
76 76
@@ -79,7 +79,7 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all
79{ 79{
80 if (blockSize == 0) 80 if (blockSize == 0)
81 return 0; 81 return 0;
82 if (!p->bufferBase || p->blockSize != blockSize) 82 if (!p->bufBase || p->blockSize != blockSize)
83 { 83 {
84 // size_t blockSizeT; 84 // size_t blockSizeT;
85 LzInWindow_Free(p, alloc); 85 LzInWindow_Free(p, alloc);
@@ -101,11 +101,11 @@ static int LzInWindow_Create2(CMatchFinder *p, UInt32 blockSize, ISzAllocPtr all
101 #endif 101 #endif
102 */ 102 */
103 103
104 p->bufferBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize); 104 p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, blockSize);
105 // printf("\nbufferBase = %p\n", p->bufferBase); 105 // printf("\nbufferBase = %p\n", p->bufBase);
106 // return 0; // for debug 106 // return 0; // for debug
107 } 107 }
108 return (p->bufferBase != NULL); 108 return (p->bufBase != NULL);
109} 109}
110 110
111static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } 111static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; }
@@ -113,7 +113,7 @@ static const Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return
113static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return GET_AVAIL_BYTES(p); } 113static UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return GET_AVAIL_BYTES(p); }
114 114
115 115
116MY_NO_INLINE 116Z7_NO_INLINE
117static void MatchFinder_ReadBlock(CMatchFinder *p) 117static void MatchFinder_ReadBlock(CMatchFinder *p)
118{ 118{
119 if (p->streamEndWasReached || p->result != SZ_OK) 119 if (p->streamEndWasReached || p->result != SZ_OK)
@@ -127,8 +127,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p)
127 UInt32 curSize = 0xFFFFFFFF - GET_AVAIL_BYTES(p); 127 UInt32 curSize = 0xFFFFFFFF - GET_AVAIL_BYTES(p);
128 if (curSize > p->directInputRem) 128 if (curSize > p->directInputRem)
129 curSize = (UInt32)p->directInputRem; 129 curSize = (UInt32)p->directInputRem;
130 p->directInputRem -= curSize;
131 p->streamPos += curSize; 130 p->streamPos += curSize;
131 p->directInputRem -= curSize;
132 if (p->directInputRem == 0) 132 if (p->directInputRem == 0)
133 p->streamEndWasReached = 1; 133 p->streamEndWasReached = 1;
134 return; 134 return;
@@ -136,8 +136,8 @@ static void MatchFinder_ReadBlock(CMatchFinder *p)
136 136
137 for (;;) 137 for (;;)
138 { 138 {
139 Byte *dest = p->buffer + GET_AVAIL_BYTES(p); 139 const Byte *dest = p->buffer + GET_AVAIL_BYTES(p);
140 size_t size = (size_t)(p->bufferBase + p->blockSize - dest); 140 size_t size = (size_t)(p->bufBase + p->blockSize - dest);
141 if (size == 0) 141 if (size == 0)
142 { 142 {
143 /* we call ReadBlock() after NeedMove() and MoveBlock(). 143 /* we call ReadBlock() after NeedMove() and MoveBlock().
@@ -153,7 +153,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p)
153 // #define kRead 3 153 // #define kRead 3
154 // if (size > kRead) size = kRead; // for debug 154 // if (size > kRead) size = kRead; // for debug
155 155
156 p->result = ISeqInStream_Read(p->stream, dest, &size); 156 /*
157 // we need cast (Byte *)dest.
158 #ifdef __clang__
159 #pragma GCC diagnostic ignored "-Wcast-qual"
160 #endif
161 */
162 p->result = ISeqInStream_Read(p->stream,
163 p->bufBase + (dest - p->bufBase), &size);
157 if (p->result != SZ_OK) 164 if (p->result != SZ_OK)
158 return; 165 return;
159 if (size == 0) 166 if (size == 0)
@@ -173,14 +180,14 @@ static void MatchFinder_ReadBlock(CMatchFinder *p)
173 180
174 181
175 182
176MY_NO_INLINE 183Z7_NO_INLINE
177void MatchFinder_MoveBlock(CMatchFinder *p) 184void MatchFinder_MoveBlock(CMatchFinder *p)
178{ 185{
179 const size_t offset = (size_t)(p->buffer - p->bufferBase) - p->keepSizeBefore; 186 const size_t offset = (size_t)(p->buffer - p->bufBase) - p->keepSizeBefore;
180 const size_t keepBefore = (offset & (kBlockMoveAlign - 1)) + p->keepSizeBefore; 187 const size_t keepBefore = (offset & (kBlockMoveAlign - 1)) + p->keepSizeBefore;
181 p->buffer = p->bufferBase + keepBefore; 188 p->buffer = p->bufBase + keepBefore;
182 memmove(p->bufferBase, 189 memmove(p->bufBase,
183 p->bufferBase + (offset & ~((size_t)kBlockMoveAlign - 1)), 190 p->bufBase + (offset & ~((size_t)kBlockMoveAlign - 1)),
184 keepBefore + (size_t)GET_AVAIL_BYTES(p)); 191 keepBefore + (size_t)GET_AVAIL_BYTES(p));
185} 192}
186 193
@@ -198,7 +205,7 @@ int MatchFinder_NeedMove(CMatchFinder *p)
198 return 0; 205 return 0;
199 if (p->streamEndWasReached || p->result != SZ_OK) 206 if (p->streamEndWasReached || p->result != SZ_OK)
200 return 0; 207 return 0;
201 return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); 208 return ((size_t)(p->bufBase + p->blockSize - p->buffer) <= p->keepSizeAfter);
202} 209}
203 210
204void MatchFinder_ReadIfRequired(CMatchFinder *p) 211void MatchFinder_ReadIfRequired(CMatchFinder *p)
@@ -214,6 +221,8 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
214 p->cutValue = 32; 221 p->cutValue = 32;
215 p->btMode = 1; 222 p->btMode = 1;
216 p->numHashBytes = 4; 223 p->numHashBytes = 4;
224 p->numHashBytes_Min = 2;
225 p->numHashOutBits = 0;
217 p->bigHash = 0; 226 p->bigHash = 0;
218} 227}
219 228
@@ -222,8 +231,10 @@ static void MatchFinder_SetDefaultSettings(CMatchFinder *p)
222void MatchFinder_Construct(CMatchFinder *p) 231void MatchFinder_Construct(CMatchFinder *p)
223{ 232{
224 unsigned i; 233 unsigned i;
225 p->bufferBase = NULL; 234 p->buffer = NULL;
235 p->bufBase = NULL;
226 p->directInput = 0; 236 p->directInput = 0;
237 p->stream = NULL;
227 p->hash = NULL; 238 p->hash = NULL;
228 p->expectedDataSize = (UInt64)(Int64)-1; 239 p->expectedDataSize = (UInt64)(Int64)-1;
229 MatchFinder_SetDefaultSettings(p); 240 MatchFinder_SetDefaultSettings(p);
@@ -238,6 +249,8 @@ void MatchFinder_Construct(CMatchFinder *p)
238 } 249 }
239} 250}
240 251
252#undef kCrcPoly
253
241static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) 254static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc)
242{ 255{
243 ISzAlloc_Free(alloc, p->hash); 256 ISzAlloc_Free(alloc, p->hash);
@@ -252,7 +265,7 @@ void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc)
252 265
253static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) 266static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc)
254{ 267{
255 size_t sizeInBytes = (size_t)num * sizeof(CLzRef); 268 const size_t sizeInBytes = (size_t)num * sizeof(CLzRef);
256 if (sizeInBytes / sizeof(CLzRef) != num) 269 if (sizeInBytes / sizeof(CLzRef) != num)
257 return NULL; 270 return NULL;
258 return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); 271 return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes);
@@ -298,6 +311,62 @@ static UInt32 GetBlockSize(CMatchFinder *p, UInt32 historySize)
298} 311}
299 312
300 313
314// input is historySize
315static UInt32 MatchFinder_GetHashMask2(CMatchFinder *p, UInt32 hs)
316{
317 if (p->numHashBytes == 2)
318 return (1 << 16) - 1;
319 if (hs != 0)
320 hs--;
321 hs |= (hs >> 1);
322 hs |= (hs >> 2);
323 hs |= (hs >> 4);
324 hs |= (hs >> 8);
325 // we propagated 16 bits in (hs). Low 16 bits must be set later
326 if (hs >= (1 << 24))
327 {
328 if (p->numHashBytes == 3)
329 hs = (1 << 24) - 1;
330 /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */
331 }
332 // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2)
333 hs |= (1 << 16) - 1; /* don't change it! */
334 // bt5: we adjust the size with recommended minimum size
335 if (p->numHashBytes >= 5)
336 hs |= (256 << kLzHash_CrcShift_2) - 1;
337 return hs;
338}
339
340// input is historySize
341static UInt32 MatchFinder_GetHashMask(CMatchFinder *p, UInt32 hs)
342{
343 if (p->numHashBytes == 2)
344 return (1 << 16) - 1;
345 if (hs != 0)
346 hs--;
347 hs |= (hs >> 1);
348 hs |= (hs >> 2);
349 hs |= (hs >> 4);
350 hs |= (hs >> 8);
351 // we propagated 16 bits in (hs). Low 16 bits must be set later
352 hs >>= 1;
353 if (hs >= (1 << 24))
354 {
355 if (p->numHashBytes == 3)
356 hs = (1 << 24) - 1;
357 else
358 hs >>= 1;
359 /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */
360 }
361 // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2)
362 hs |= (1 << 16) - 1; /* don't change it! */
363 // bt5: we adjust the size with recommended minimum size
364 if (p->numHashBytes >= 5)
365 hs |= (256 << kLzHash_CrcShift_2) - 1;
366 return hs;
367}
368
369
301int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, 370int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
302 UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, 371 UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
303 ISzAllocPtr alloc) 372 ISzAllocPtr alloc)
@@ -318,78 +387,91 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
318 p->blockSize = 0; 387 p->blockSize = 0;
319 if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc)) 388 if (p->directInput || LzInWindow_Create2(p, GetBlockSize(p, historySize), alloc))
320 { 389 {
321 const UInt32 newCyclicBufferSize = historySize + 1; // do not change it 390 size_t hashSizeSum;
322 UInt32 hs;
323 p->matchMaxLen = matchMaxLen;
324 { 391 {
325 // UInt32 hs4; 392 UInt32 hs;
326 p->fixedHashSize = 0; 393 UInt32 hsCur;
327 hs = (1 << 16) - 1; 394
328 if (p->numHashBytes != 2) 395 if (p->numHashOutBits != 0)
329 { 396 {
330 hs = historySize; 397 unsigned numBits = p->numHashOutBits;
331 if (hs > p->expectedDataSize) 398 const unsigned nbMax =
332 hs = (UInt32)p->expectedDataSize; 399 (p->numHashBytes == 2 ? 16 :
333 if (hs != 0) 400 (p->numHashBytes == 3 ? 24 : 32));
334 hs--; 401 if (numBits > nbMax)
335 hs |= (hs >> 1); 402 numBits = nbMax;
336 hs |= (hs >> 2); 403 if (numBits >= 32)
337 hs |= (hs >> 4); 404 hs = (UInt32)0 - 1;
338 hs |= (hs >> 8); 405 else
339 // we propagated 16 bits in (hs). Low 16 bits must be set later 406 hs = ((UInt32)1 << numBits) - 1;
340 hs >>= 1;
341 if (hs >= (1 << 24))
342 {
343 if (p->numHashBytes == 3)
344 hs = (1 << 24) - 1;
345 else
346 hs >>= 1;
347 /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */
348 }
349
350 // hs = ((UInt32)1 << 25) - 1; // for test
351
352 // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2) 407 // (hash_size >= (1 << 16)) : Required for (numHashBytes > 2)
353 hs |= (1 << 16) - 1; /* don't change it! */ 408 hs |= (1 << 16) - 1; /* don't change it! */
354
355 // bt5: we adjust the size with recommended minimum size
356 if (p->numHashBytes >= 5) 409 if (p->numHashBytes >= 5)
357 hs |= (256 << kLzHash_CrcShift_2) - 1; 410 hs |= (256 << kLzHash_CrcShift_2) - 1;
411 {
412 const UInt32 hs2 = MatchFinder_GetHashMask2(p, historySize);
413 if (hs > hs2)
414 hs = hs2;
415 }
416 hsCur = hs;
417 if (p->expectedDataSize < historySize)
418 {
419 const UInt32 hs2 = MatchFinder_GetHashMask2(p, (UInt32)p->expectedDataSize);
420 if (hsCur > hs2)
421 hsCur = hs2;
422 }
358 } 423 }
359 p->hashMask = hs; 424 else
360 hs++; 425 {
361 426 hs = MatchFinder_GetHashMask(p, historySize);
362 /* 427 hsCur = hs;
363 hs4 = (1 << 20); 428 if (p->expectedDataSize < historySize)
364 if (hs4 > hs) 429 {
365 hs4 = hs; 430 hsCur = MatchFinder_GetHashMask(p, (UInt32)p->expectedDataSize);
366 // hs4 = (1 << 16); // for test 431 if (hsCur > hs) // is it possible?
367 p->hash4Mask = hs4 - 1; 432 hsCur = hs;
368 */ 433 }
434 }
435
436 p->hashMask = hsCur;
369 437
370 if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; 438 hashSizeSum = hs;
371 if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; 439 hashSizeSum++;
372 // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size; 440 if (hashSizeSum < hs)
373 hs += p->fixedHashSize; 441 return 0;
442 {
443 UInt32 fixedHashSize = 0;
444 if (p->numHashBytes > 2 && p->numHashBytes_Min <= 2) fixedHashSize += kHash2Size;
445 if (p->numHashBytes > 3 && p->numHashBytes_Min <= 3) fixedHashSize += kHash3Size;
446 // if (p->numHashBytes > 4) p->fixedHashSize += hs4; // kHash4Size;
447 hashSizeSum += fixedHashSize;
448 p->fixedHashSize = fixedHashSize;
449 }
374 } 450 }
375 451
452 p->matchMaxLen = matchMaxLen;
453
376 { 454 {
377 size_t newSize; 455 size_t newSize;
378 size_t numSons; 456 size_t numSons;
457 const UInt32 newCyclicBufferSize = historySize + 1; // do not change it
379 p->historySize = historySize; 458 p->historySize = historySize;
380 p->hashSizeSum = hs;
381 p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1) 459 p->cyclicBufferSize = newCyclicBufferSize; // it must be = (historySize + 1)
382 460
383 numSons = newCyclicBufferSize; 461 numSons = newCyclicBufferSize;
384 if (p->btMode) 462 if (p->btMode)
385 numSons <<= 1; 463 numSons <<= 1;
386 newSize = hs + numSons; 464 newSize = hashSizeSum + numSons;
465
466 if (numSons < newCyclicBufferSize || newSize < numSons)
467 return 0;
387 468
388 // aligned size is not required here, but it can be better for some loops 469 // aligned size is not required here, but it can be better for some loops
389 #define NUM_REFS_ALIGN_MASK 0xF 470 #define NUM_REFS_ALIGN_MASK 0xF
390 newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK; 471 newSize = (newSize + NUM_REFS_ALIGN_MASK) & ~(size_t)NUM_REFS_ALIGN_MASK;
391 472
392 if (p->hash && p->numRefs == newSize) 473 // 22.02: we don't reallocate buffer, if old size is enough
474 if (p->hash && p->numRefs >= newSize)
393 return 1; 475 return 1;
394 476
395 MatchFinder_FreeThisClassMemory(p, alloc); 477 MatchFinder_FreeThisClassMemory(p, alloc);
@@ -398,7 +480,7 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
398 480
399 if (p->hash) 481 if (p->hash)
400 { 482 {
401 p->son = p->hash + p->hashSizeSum; 483 p->son = p->hash + hashSizeSum;
402 return 1; 484 return 1;
403 } 485 }
404 } 486 }
@@ -470,7 +552,8 @@ void MatchFinder_Init_HighHash(CMatchFinder *p)
470 552
471void MatchFinder_Init_4(CMatchFinder *p) 553void MatchFinder_Init_4(CMatchFinder *p)
472{ 554{
473 p->buffer = p->bufferBase; 555 if (!p->directInput)
556 p->buffer = p->bufBase;
474 { 557 {
475 /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker. 558 /* kEmptyHashValue = 0 (Zero) is used in hash tables as NO-VALUE marker.
476 the code in CMatchFinderMt expects (pos = 1) */ 559 the code in CMatchFinderMt expects (pos = 1) */
@@ -507,20 +590,20 @@ void MatchFinder_Init(CMatchFinder *p)
507 590
508 591
509#ifdef MY_CPU_X86_OR_AMD64 592#ifdef MY_CPU_X86_OR_AMD64
510 #if defined(__clang__) && (__clang_major__ >= 8) \ 593 #if defined(__clang__) && (__clang_major__ >= 4) \
511 || defined(__GNUC__) && (__GNUC__ >= 8) \ 594 || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701)
512 || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900) 595 // || defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900)
513 #define USE_SATUR_SUB_128 596
514 #define USE_AVX2 597 #define USE_LZFIND_SATUR_SUB_128
515 #define ATTRIB_SSE41 __attribute__((__target__("sse4.1"))) 598 #define USE_LZFIND_SATUR_SUB_256
516 #define ATTRIB_AVX2 __attribute__((__target__("avx2"))) 599 #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("sse4.1")))
600 #define LZFIND_ATTRIB_AVX2 __attribute__((__target__("avx2")))
517 #elif defined(_MSC_VER) 601 #elif defined(_MSC_VER)
518 #if (_MSC_VER >= 1600) 602 #if (_MSC_VER >= 1600)
519 #define USE_SATUR_SUB_128 603 #define USE_LZFIND_SATUR_SUB_128
520 #if (_MSC_VER >= 1900) 604 #endif
521 #define USE_AVX2 605 #if (_MSC_VER >= 1900)
522 #include <immintrin.h> // avx 606 #define USE_LZFIND_SATUR_SUB_256
523 #endif
524 #endif 607 #endif
525 #endif 608 #endif
526 609
@@ -529,16 +612,16 @@ void MatchFinder_Init(CMatchFinder *p)
529 612
530 #if defined(__clang__) && (__clang_major__ >= 8) \ 613 #if defined(__clang__) && (__clang_major__ >= 8) \
531 || defined(__GNUC__) && (__GNUC__ >= 8) 614 || defined(__GNUC__) && (__GNUC__ >= 8)
532 #define USE_SATUR_SUB_128 615 #define USE_LZFIND_SATUR_SUB_128
533 #ifdef MY_CPU_ARM64 616 #ifdef MY_CPU_ARM64
534 // #define ATTRIB_SSE41 __attribute__((__target__(""))) 617 // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("")))
535 #else 618 #else
536 // #define ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8"))) 619 // #define LZFIND_ATTRIB_SSE41 __attribute__((__target__("fpu=crypto-neon-fp-armv8")))
537 #endif 620 #endif
538 621
539 #elif defined(_MSC_VER) 622 #elif defined(_MSC_VER)
540 #if (_MSC_VER >= 1910) 623 #if (_MSC_VER >= 1910)
541 #define USE_SATUR_SUB_128 624 #define USE_LZFIND_SATUR_SUB_128
542 #endif 625 #endif
543 #endif 626 #endif
544 627
@@ -550,121 +633,130 @@ void MatchFinder_Init(CMatchFinder *p)
550 633
551#endif 634#endif
552 635
553/*
554#ifndef ATTRIB_SSE41
555 #define ATTRIB_SSE41
556#endif
557#ifndef ATTRIB_AVX2
558 #define ATTRIB_AVX2
559#endif
560*/
561 636
562#ifdef USE_SATUR_SUB_128 637#ifdef USE_LZFIND_SATUR_SUB_128
563 638
564// #define _SHOW_HW_STATUS 639// #define Z7_SHOW_HW_STATUS
565 640
566#ifdef _SHOW_HW_STATUS 641#ifdef Z7_SHOW_HW_STATUS
567#include <stdio.h> 642#include <stdio.h>
568#define _PRF(x) x 643#define PRF(x) x
569_PRF(;) 644PRF(;)
570#else 645#else
571#define _PRF(x) 646#define PRF(x)
572#endif 647#endif
573 648
649
574#ifdef MY_CPU_ARM_OR_ARM64 650#ifdef MY_CPU_ARM_OR_ARM64
575 651
576#ifdef MY_CPU_ARM64 652#ifdef MY_CPU_ARM64
577// #define FORCE_SATUR_SUB_128 653// #define FORCE_LZFIND_SATUR_SUB_128
578#endif 654#endif
655typedef uint32x4_t LzFind_v128;
656#define SASUB_128_V(v, s) \
657 vsubq_u32(vmaxq_u32(v, s), s)
579 658
580typedef uint32x4_t v128; 659#else // MY_CPU_ARM_OR_ARM64
581#define SASUB_128(i) \
582 *(v128 *)(void *)(items + (i) * 4) = \
583 vsubq_u32(vmaxq_u32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2);
584
585#else
586 660
587#include <smmintrin.h> // sse4.1 661#include <smmintrin.h> // sse4.1
588 662
589typedef __m128i v128; 663typedef __m128i LzFind_v128;
590#define SASUB_128(i) \ 664// SSE 4.1
591 *(v128 *)(void *)(items + (i) * 4) = \ 665#define SASUB_128_V(v, s) \
592 _mm_sub_epi32(_mm_max_epu32(*(const v128 *)(const void *)(items + (i) * 4), sub2), sub2); // SSE 4.1 666 _mm_sub_epi32(_mm_max_epu32(v, s), s)
593 667
594#endif 668#endif // MY_CPU_ARM_OR_ARM64
595 669
596 670
671#define SASUB_128(i) \
672 *( LzFind_v128 *)( void *)(items + (i) * 4) = SASUB_128_V( \
673 *(const LzFind_v128 *)(const void *)(items + (i) * 4), sub2);
674
597 675
598MY_NO_INLINE 676Z7_NO_INLINE
599static 677static
600#ifdef ATTRIB_SSE41 678#ifdef LZFIND_ATTRIB_SSE41
601ATTRIB_SSE41 679LZFIND_ATTRIB_SSE41
602#endif 680#endif
603void 681void
604MY_FAST_CALL 682Z7_FASTCALL
605LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim) 683LzFind_SaturSub_128(UInt32 subValue, CLzRef *items, const CLzRef *lim)
606{ 684{
607 v128 sub2 = 685 const LzFind_v128 sub2 =
608 #ifdef MY_CPU_ARM_OR_ARM64 686 #ifdef MY_CPU_ARM_OR_ARM64
609 vdupq_n_u32(subValue); 687 vdupq_n_u32(subValue);
610 #else 688 #else
611 _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); 689 _mm_set_epi32((Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue);
612 #endif 690 #endif
691 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
613 do 692 do
614 { 693 {
615 SASUB_128(0) 694 SASUB_128(0) SASUB_128(1) items += 2 * 4;
616 SASUB_128(1) 695 SASUB_128(0) SASUB_128(1) items += 2 * 4;
617 SASUB_128(2)
618 SASUB_128(3)
619 items += 4 * 4;
620 } 696 }
621 while (items != lim); 697 while (items != lim);
622} 698}
623 699
624 700
625 701
626#ifdef USE_AVX2 702#ifdef USE_LZFIND_SATUR_SUB_256
627 703
628#include <immintrin.h> // avx 704#include <immintrin.h> // avx
705/*
706clang :immintrin.h uses
707#if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \
708 defined(__AVX2__)
709#include <avx2intrin.h>
710#endif
711so we need <avxintrin.h> for clang-cl */
629 712
630#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 713#if defined(__clang__)
714#include <avxintrin.h>
715#include <avx2intrin.h>
716#endif
631 717
632MY_NO_INLINE 718// AVX2:
719#define SASUB_256(i) \
720 *( __m256i *)( void *)(items + (i) * 8) = \
721 _mm256_sub_epi32(_mm256_max_epu32( \
722 *(const __m256i *)(const void *)(items + (i) * 8), sub2), sub2);
723
724Z7_NO_INLINE
633static 725static
634#ifdef ATTRIB_AVX2 726#ifdef LZFIND_ATTRIB_AVX2
635ATTRIB_AVX2 727LZFIND_ATTRIB_AVX2
636#endif 728#endif
637void 729void
638MY_FAST_CALL 730Z7_FASTCALL
639LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim) 731LzFind_SaturSub_256(UInt32 subValue, CLzRef *items, const CLzRef *lim)
640{ 732{
641 __m256i sub2 = _mm256_set_epi32( 733 const __m256i sub2 = _mm256_set_epi32(
642 (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue, 734 (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue,
643 (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue); 735 (Int32)subValue, (Int32)subValue, (Int32)subValue, (Int32)subValue);
736 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
644 do 737 do
645 { 738 {
646 SASUB_256(0) 739 SASUB_256(0) SASUB_256(1) items += 2 * 8;
647 SASUB_256(1) 740 SASUB_256(0) SASUB_256(1) items += 2 * 8;
648 items += 2 * 8;
649 } 741 }
650 while (items != lim); 742 while (items != lim);
651} 743}
652#endif // USE_AVX2 744#endif // USE_LZFIND_SATUR_SUB_256
653 745
654#ifndef FORCE_SATUR_SUB_128 746#ifndef FORCE_LZFIND_SATUR_SUB_128
655typedef void (MY_FAST_CALL *LZFIND_SATUR_SUB_CODE_FUNC)( 747typedef void (Z7_FASTCALL *LZFIND_SATUR_SUB_CODE_FUNC)(
656 UInt32 subValue, CLzRef *items, const CLzRef *lim); 748 UInt32 subValue, CLzRef *items, const CLzRef *lim);
657static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub; 749static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub;
658#endif // FORCE_SATUR_SUB_128 750#endif // FORCE_LZFIND_SATUR_SUB_128
659 751
660#endif // USE_SATUR_SUB_128 752#endif // USE_LZFIND_SATUR_SUB_128
661 753
662 754
663// kEmptyHashValue must be zero 755// kEmptyHashValue must be zero
664// #define SASUB_32(i) v = items[i]; m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; 756// #define SASUB_32(i) { UInt32 v = items[i]; UInt32 m = v - subValue; if (v < subValue) m = kEmptyHashValue; items[i] = m; }
665#define SASUB_32(i) v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; 757#define SASUB_32(i) { UInt32 v = items[i]; if (v < subValue) v = subValue; items[i] = v - subValue; }
666 758
667#ifdef FORCE_SATUR_SUB_128 759#ifdef FORCE_LZFIND_SATUR_SUB_128
668 760
669#define DEFAULT_SaturSub LzFind_SaturSub_128 761#define DEFAULT_SaturSub LzFind_SaturSub_128
670 762
@@ -672,24 +764,19 @@ static LZFIND_SATUR_SUB_CODE_FUNC g_LzFind_SaturSub;
672 764
673#define DEFAULT_SaturSub LzFind_SaturSub_32 765#define DEFAULT_SaturSub LzFind_SaturSub_32
674 766
675MY_NO_INLINE 767Z7_NO_INLINE
676static 768static
677void 769void
678MY_FAST_CALL 770Z7_FASTCALL
679LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim) 771LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim)
680{ 772{
773 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
681 do 774 do
682 { 775 {
683 UInt32 v; 776 SASUB_32(0) SASUB_32(1) items += 2;
684 SASUB_32(0) 777 SASUB_32(0) SASUB_32(1) items += 2;
685 SASUB_32(1) 778 SASUB_32(0) SASUB_32(1) items += 2;
686 SASUB_32(2) 779 SASUB_32(0) SASUB_32(1) items += 2;
687 SASUB_32(3)
688 SASUB_32(4)
689 SASUB_32(5)
690 SASUB_32(6)
691 SASUB_32(7)
692 items += 8;
693 } 780 }
694 while (items != lim); 781 while (items != lim);
695} 782}
@@ -697,27 +784,23 @@ LzFind_SaturSub_32(UInt32 subValue, CLzRef *items, const CLzRef *lim)
697#endif 784#endif
698 785
699 786
700MY_NO_INLINE 787Z7_NO_INLINE
701void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) 788void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems)
702{ 789{
703 #define K_NORM_ALIGN_BLOCK_SIZE (1 << 6) 790 #define LZFIND_NORM_ALIGN_BLOCK_SIZE (1 << 7)
704 791 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
705 CLzRef *lim; 792 for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (LZFIND_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--)
706
707 for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (K_NORM_ALIGN_BLOCK_SIZE - 1)) != 0; numItems--)
708 { 793 {
709 UInt32 v; 794 SASUB_32(0)
710 SASUB_32(0);
711 items++; 795 items++;
712 } 796 }
713
714 { 797 {
715 #define K_NORM_ALIGN_MASK (K_NORM_ALIGN_BLOCK_SIZE / 4 - 1) 798 const size_t k_Align_Mask = (LZFIND_NORM_ALIGN_BLOCK_SIZE / 4 - 1);
716 lim = items + (numItems & ~(size_t)K_NORM_ALIGN_MASK); 799 CLzRef *lim = items + (numItems & ~(size_t)k_Align_Mask);
717 numItems &= K_NORM_ALIGN_MASK; 800 numItems &= k_Align_Mask;
718 if (items != lim) 801 if (items != lim)
719 { 802 {
720 #if defined(USE_SATUR_SUB_128) && !defined(FORCE_SATUR_SUB_128) 803 #if defined(USE_LZFIND_SATUR_SUB_128) && !defined(FORCE_LZFIND_SATUR_SUB_128)
721 if (g_LzFind_SaturSub) 804 if (g_LzFind_SaturSub)
722 g_LzFind_SaturSub(subValue, items, lim); 805 g_LzFind_SaturSub(subValue, items, lim);
723 else 806 else
@@ -726,12 +809,10 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems)
726 } 809 }
727 items = lim; 810 items = lim;
728 } 811 }
729 812 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
730
731 for (; numItems != 0; numItems--) 813 for (; numItems != 0; numItems--)
732 { 814 {
733 UInt32 v; 815 SASUB_32(0)
734 SASUB_32(0);
735 items++; 816 items++;
736 } 817 }
737} 818}
@@ -740,7 +821,7 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems)
740 821
741// call MatchFinder_CheckLimits() only after (p->pos++) update 822// call MatchFinder_CheckLimits() only after (p->pos++) update
742 823
743MY_NO_INLINE 824Z7_NO_INLINE
744static void MatchFinder_CheckLimits(CMatchFinder *p) 825static void MatchFinder_CheckLimits(CMatchFinder *p)
745{ 826{
746 if (// !p->streamEndWasReached && p->result == SZ_OK && 827 if (// !p->streamEndWasReached && p->result == SZ_OK &&
@@ -768,11 +849,14 @@ static void MatchFinder_CheckLimits(CMatchFinder *p)
768 const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */; 849 const UInt32 subValue = (p->pos - p->historySize - 1) /* & ~(UInt32)(kNormalizeAlign - 1) */;
769 // const UInt32 subValue = (1 << 15); // for debug 850 // const UInt32 subValue = (1 << 15); // for debug
770 // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue); 851 // printf("\nMatchFinder_Normalize() subValue == 0x%x\n", subValue);
771 size_t numSonRefs = p->cyclicBufferSize; 852 MatchFinder_REDUCE_OFFSETS(p, subValue)
772 if (p->btMode) 853 MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashMask + 1 + p->fixedHashSize);
773 numSonRefs <<= 1; 854 {
774 Inline_MatchFinder_ReduceOffsets(p, subValue); 855 size_t numSonRefs = p->cyclicBufferSize;
775 MatchFinder_Normalize3(subValue, p->hash, (size_t)p->hashSizeSum + numSonRefs); 856 if (p->btMode)
857 numSonRefs <<= 1;
858 MatchFinder_Normalize3(subValue, p->son, numSonRefs);
859 }
776 } 860 }
777 861
778 if (p->cyclicBufferPos == p->cyclicBufferSize) 862 if (p->cyclicBufferPos == p->cyclicBufferSize)
@@ -785,7 +869,7 @@ static void MatchFinder_CheckLimits(CMatchFinder *p)
785/* 869/*
786 (lenLimit > maxLen) 870 (lenLimit > maxLen)
787*/ 871*/
788MY_FORCE_INLINE 872Z7_FORCE_INLINE
789static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, 873static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
790 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, 874 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
791 UInt32 *d, unsigned maxLen) 875 UInt32 *d, unsigned maxLen)
@@ -867,7 +951,7 @@ static UInt32 * Hc_GetMatchesSpec(size_t lenLimit, UInt32 curMatch, UInt32 pos,
867} 951}
868 952
869 953
870MY_FORCE_INLINE 954Z7_FORCE_INLINE
871UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, 955UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son,
872 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, 956 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue,
873 UInt32 *d, UInt32 maxLen) 957 UInt32 *d, UInt32 maxLen)
@@ -1004,7 +1088,7 @@ static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const
1004 1088
1005#define MOVE_POS_RET MOVE_POS return distances; 1089#define MOVE_POS_RET MOVE_POS return distances;
1006 1090
1007MY_NO_INLINE 1091Z7_NO_INLINE
1008static void MatchFinder_MovePos(CMatchFinder *p) 1092static void MatchFinder_MovePos(CMatchFinder *p)
1009{ 1093{
1010 /* we go here at the end of stream data, when (avail < num_hash_bytes) 1094 /* we go here at the end of stream data, when (avail < num_hash_bytes)
@@ -1015,11 +1099,11 @@ static void MatchFinder_MovePos(CMatchFinder *p)
1015 if (p->btMode) 1099 if (p->btMode)
1016 p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue 1100 p->sons[(p->cyclicBufferPos << p->btMode) + 1] = 0; // kEmptyHashValue
1017 */ 1101 */
1018 MOVE_POS; 1102 MOVE_POS
1019} 1103}
1020 1104
1021#define GET_MATCHES_HEADER2(minLen, ret_op) \ 1105#define GET_MATCHES_HEADER2(minLen, ret_op) \
1022 unsigned lenLimit; UInt32 hv; Byte *cur; UInt32 curMatch; \ 1106 unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \
1023 lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ 1107 lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \
1024 cur = p->buffer; 1108 cur = p->buffer;
1025 1109
@@ -1028,11 +1112,11 @@ static void MatchFinder_MovePos(CMatchFinder *p)
1028 1112
1029#define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue 1113#define MF_PARAMS(p) lenLimit, curMatch, p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue
1030 1114
1031#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS; } while (--num); 1115#define SKIP_FOOTER SkipMatchesSpec(MF_PARAMS(p)); MOVE_POS } while (--num);
1032 1116
1033#define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \ 1117#define GET_MATCHES_FOOTER_BASE(_maxLen_, func) \
1034 distances = func(MF_PARAMS(p), \ 1118 distances = func(MF_PARAMS(p), \
1035 distances, (UInt32)_maxLen_); MOVE_POS_RET; 1119 distances, (UInt32)_maxLen_); MOVE_POS_RET
1036 1120
1037#define GET_MATCHES_FOOTER_BT(_maxLen_) \ 1121#define GET_MATCHES_FOOTER_BT(_maxLen_) \
1038 GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1) 1122 GET_MATCHES_FOOTER_BASE(_maxLen_, GetMatchesSpec1)
@@ -1052,7 +1136,7 @@ static void MatchFinder_MovePos(CMatchFinder *p)
1052static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) 1136static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1053{ 1137{
1054 GET_MATCHES_HEADER(2) 1138 GET_MATCHES_HEADER(2)
1055 HASH2_CALC; 1139 HASH2_CALC
1056 curMatch = p->hash[hv]; 1140 curMatch = p->hash[hv];
1057 p->hash[hv] = p->pos; 1141 p->hash[hv] = p->pos;
1058 GET_MATCHES_FOOTER_BT(1) 1142 GET_MATCHES_FOOTER_BT(1)
@@ -1061,7 +1145,7 @@ static UInt32* Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1061UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) 1145UInt32* Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1062{ 1146{
1063 GET_MATCHES_HEADER(3) 1147 GET_MATCHES_HEADER(3)
1064 HASH_ZIP_CALC; 1148 HASH_ZIP_CALC
1065 curMatch = p->hash[hv]; 1149 curMatch = p->hash[hv];
1066 p->hash[hv] = p->pos; 1150 p->hash[hv] = p->pos;
1067 GET_MATCHES_FOOTER_BT(2) 1151 GET_MATCHES_FOOTER_BT(2)
@@ -1082,7 +1166,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1082 UInt32 *hash; 1166 UInt32 *hash;
1083 GET_MATCHES_HEADER(3) 1167 GET_MATCHES_HEADER(3)
1084 1168
1085 HASH3_CALC; 1169 HASH3_CALC
1086 1170
1087 hash = p->hash; 1171 hash = p->hash;
1088 pos = p->pos; 1172 pos = p->pos;
@@ -1107,7 +1191,7 @@ static UInt32* Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1107 if (maxLen == lenLimit) 1191 if (maxLen == lenLimit)
1108 { 1192 {
1109 SkipMatchesSpec(MF_PARAMS(p)); 1193 SkipMatchesSpec(MF_PARAMS(p));
1110 MOVE_POS_RET; 1194 MOVE_POS_RET
1111 } 1195 }
1112 } 1196 }
1113 1197
@@ -1123,7 +1207,7 @@ static UInt32* Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1123 UInt32 *hash; 1207 UInt32 *hash;
1124 GET_MATCHES_HEADER(4) 1208 GET_MATCHES_HEADER(4)
1125 1209
1126 HASH4_CALC; 1210 HASH4_CALC
1127 1211
1128 hash = p->hash; 1212 hash = p->hash;
1129 pos = p->pos; 1213 pos = p->pos;
@@ -1190,7 +1274,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1190 UInt32 *hash; 1274 UInt32 *hash;
1191 GET_MATCHES_HEADER(5) 1275 GET_MATCHES_HEADER(5)
1192 1276
1193 HASH5_CALC; 1277 HASH5_CALC
1194 1278
1195 hash = p->hash; 1279 hash = p->hash;
1196 pos = p->pos; 1280 pos = p->pos;
@@ -1246,7 +1330,7 @@ static UInt32* Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1246 if (maxLen == lenLimit) 1330 if (maxLen == lenLimit)
1247 { 1331 {
1248 SkipMatchesSpec(MF_PARAMS(p)); 1332 SkipMatchesSpec(MF_PARAMS(p));
1249 MOVE_POS_RET; 1333 MOVE_POS_RET
1250 } 1334 }
1251 break; 1335 break;
1252 } 1336 }
@@ -1263,7 +1347,7 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1263 UInt32 *hash; 1347 UInt32 *hash;
1264 GET_MATCHES_HEADER(4) 1348 GET_MATCHES_HEADER(4)
1265 1349
1266 HASH4_CALC; 1350 HASH4_CALC
1267 1351
1268 hash = p->hash; 1352 hash = p->hash;
1269 pos = p->pos; 1353 pos = p->pos;
@@ -1314,12 +1398,12 @@ static UInt32* Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1314 if (maxLen == lenLimit) 1398 if (maxLen == lenLimit)
1315 { 1399 {
1316 p->son[p->cyclicBufferPos] = curMatch; 1400 p->son[p->cyclicBufferPos] = curMatch;
1317 MOVE_POS_RET; 1401 MOVE_POS_RET
1318 } 1402 }
1319 break; 1403 break;
1320 } 1404 }
1321 1405
1322 GET_MATCHES_FOOTER_HC(maxLen); 1406 GET_MATCHES_FOOTER_HC(maxLen)
1323} 1407}
1324 1408
1325 1409
@@ -1330,7 +1414,7 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1330 UInt32 *hash; 1414 UInt32 *hash;
1331 GET_MATCHES_HEADER(5) 1415 GET_MATCHES_HEADER(5)
1332 1416
1333 HASH5_CALC; 1417 HASH5_CALC
1334 1418
1335 hash = p->hash; 1419 hash = p->hash;
1336 pos = p->pos; 1420 pos = p->pos;
@@ -1386,19 +1470,19 @@ static UInt32 * Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1386 if (maxLen == lenLimit) 1470 if (maxLen == lenLimit)
1387 { 1471 {
1388 p->son[p->cyclicBufferPos] = curMatch; 1472 p->son[p->cyclicBufferPos] = curMatch;
1389 MOVE_POS_RET; 1473 MOVE_POS_RET
1390 } 1474 }
1391 break; 1475 break;
1392 } 1476 }
1393 1477
1394 GET_MATCHES_FOOTER_HC(maxLen); 1478 GET_MATCHES_FOOTER_HC(maxLen)
1395} 1479}
1396 1480
1397 1481
1398UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) 1482UInt32* Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances)
1399{ 1483{
1400 GET_MATCHES_HEADER(3) 1484 GET_MATCHES_HEADER(3)
1401 HASH_ZIP_CALC; 1485 HASH_ZIP_CALC
1402 curMatch = p->hash[hv]; 1486 curMatch = p->hash[hv];
1403 p->hash[hv] = p->pos; 1487 p->hash[hv] = p->pos;
1404 GET_MATCHES_FOOTER_HC(2) 1488 GET_MATCHES_FOOTER_HC(2)
@@ -1409,7 +1493,7 @@ static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1409{ 1493{
1410 SKIP_HEADER(2) 1494 SKIP_HEADER(2)
1411 { 1495 {
1412 HASH2_CALC; 1496 HASH2_CALC
1413 curMatch = p->hash[hv]; 1497 curMatch = p->hash[hv];
1414 p->hash[hv] = p->pos; 1498 p->hash[hv] = p->pos;
1415 } 1499 }
@@ -1420,7 +1504,7 @@ void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1420{ 1504{
1421 SKIP_HEADER(3) 1505 SKIP_HEADER(3)
1422 { 1506 {
1423 HASH_ZIP_CALC; 1507 HASH_ZIP_CALC
1424 curMatch = p->hash[hv]; 1508 curMatch = p->hash[hv];
1425 p->hash[hv] = p->pos; 1509 p->hash[hv] = p->pos;
1426 } 1510 }
@@ -1433,7 +1517,7 @@ static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1433 { 1517 {
1434 UInt32 h2; 1518 UInt32 h2;
1435 UInt32 *hash; 1519 UInt32 *hash;
1436 HASH3_CALC; 1520 HASH3_CALC
1437 hash = p->hash; 1521 hash = p->hash;
1438 curMatch = (hash + kFix3HashSize)[hv]; 1522 curMatch = (hash + kFix3HashSize)[hv];
1439 hash[h2] = 1523 hash[h2] =
@@ -1448,7 +1532,7 @@ static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1448 { 1532 {
1449 UInt32 h2, h3; 1533 UInt32 h2, h3;
1450 UInt32 *hash; 1534 UInt32 *hash;
1451 HASH4_CALC; 1535 HASH4_CALC
1452 hash = p->hash; 1536 hash = p->hash;
1453 curMatch = (hash + kFix4HashSize)[hv]; 1537 curMatch = (hash + kFix4HashSize)[hv];
1454 hash [h2] = 1538 hash [h2] =
@@ -1464,7 +1548,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1464 { 1548 {
1465 UInt32 h2, h3; 1549 UInt32 h2, h3;
1466 UInt32 *hash; 1550 UInt32 *hash;
1467 HASH5_CALC; 1551 HASH5_CALC
1468 hash = p->hash; 1552 hash = p->hash;
1469 curMatch = (hash + kFix5HashSize)[hv]; 1553 curMatch = (hash + kFix5HashSize)[hv];
1470 hash [h2] = 1554 hash [h2] =
@@ -1478,7 +1562,7 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1478 1562
1479#define HC_SKIP_HEADER(minLen) \ 1563#define HC_SKIP_HEADER(minLen) \
1480 do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \ 1564 do { if (p->lenLimit < minLen) { MatchFinder_MovePos(p); num--; continue; } { \
1481 Byte *cur; \ 1565 const Byte *cur; \
1482 UInt32 *hash; \ 1566 UInt32 *hash; \
1483 UInt32 *son; \ 1567 UInt32 *son; \
1484 UInt32 pos = p->pos; \ 1568 UInt32 pos = p->pos; \
@@ -1510,7 +1594,7 @@ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1510 HC_SKIP_HEADER(4) 1594 HC_SKIP_HEADER(4)
1511 1595
1512 UInt32 h2, h3; 1596 UInt32 h2, h3;
1513 HASH4_CALC; 1597 HASH4_CALC
1514 curMatch = (hash + kFix4HashSize)[hv]; 1598 curMatch = (hash + kFix4HashSize)[hv];
1515 hash [h2] = 1599 hash [h2] =
1516 (hash + kFix3HashSize)[h3] = 1600 (hash + kFix3HashSize)[h3] =
@@ -1540,7 +1624,7 @@ void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num)
1540{ 1624{
1541 HC_SKIP_HEADER(3) 1625 HC_SKIP_HEADER(3)
1542 1626
1543 HASH_ZIP_CALC; 1627 HASH_ZIP_CALC
1544 curMatch = hash[hv]; 1628 curMatch = hash[hv];
1545 hash[hv] = pos; 1629 hash[hv] = pos;
1546 1630
@@ -1590,17 +1674,17 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder2 *vTable)
1590 1674
1591 1675
1592 1676
1593void LzFindPrepare() 1677void LzFindPrepare(void)
1594{ 1678{
1595 #ifndef FORCE_SATUR_SUB_128 1679 #ifndef FORCE_LZFIND_SATUR_SUB_128
1596 #ifdef USE_SATUR_SUB_128 1680 #ifdef USE_LZFIND_SATUR_SUB_128
1597 LZFIND_SATUR_SUB_CODE_FUNC f = NULL; 1681 LZFIND_SATUR_SUB_CODE_FUNC f = NULL;
1598 #ifdef MY_CPU_ARM_OR_ARM64 1682 #ifdef MY_CPU_ARM_OR_ARM64
1599 { 1683 {
1600 if (CPU_IsSupported_NEON()) 1684 if (CPU_IsSupported_NEON())
1601 { 1685 {
1602 // #pragma message ("=== LzFind NEON") 1686 // #pragma message ("=== LzFind NEON")
1603 _PRF(printf("\n=== LzFind NEON\n")); 1687 PRF(printf("\n=== LzFind NEON\n"));
1604 f = LzFind_SaturSub_128; 1688 f = LzFind_SaturSub_128;
1605 } 1689 }
1606 // f = 0; // for debug 1690 // f = 0; // for debug
@@ -1609,20 +1693,25 @@ void LzFindPrepare()
1609 if (CPU_IsSupported_SSE41()) 1693 if (CPU_IsSupported_SSE41())
1610 { 1694 {
1611 // #pragma message ("=== LzFind SSE41") 1695 // #pragma message ("=== LzFind SSE41")
1612 _PRF(printf("\n=== LzFind SSE41\n")); 1696 PRF(printf("\n=== LzFind SSE41\n"));
1613 f = LzFind_SaturSub_128; 1697 f = LzFind_SaturSub_128;
1614 1698
1615 #ifdef USE_AVX2 1699 #ifdef USE_LZFIND_SATUR_SUB_256
1616 if (CPU_IsSupported_AVX2()) 1700 if (CPU_IsSupported_AVX2())
1617 { 1701 {
1618 // #pragma message ("=== LzFind AVX2") 1702 // #pragma message ("=== LzFind AVX2")
1619 _PRF(printf("\n=== LzFind AVX2\n")); 1703 PRF(printf("\n=== LzFind AVX2\n"));
1620 f = LzFind_SaturSub_256; 1704 f = LzFind_SaturSub_256;
1621 } 1705 }
1622 #endif 1706 #endif
1623 } 1707 }
1624 #endif // MY_CPU_ARM_OR_ARM64 1708 #endif // MY_CPU_ARM_OR_ARM64
1625 g_LzFind_SaturSub = f; 1709 g_LzFind_SaturSub = f;
1626 #endif // USE_SATUR_SUB_128 1710 #endif // USE_LZFIND_SATUR_SUB_128
1627 #endif // FORCE_SATUR_SUB_128 1711 #endif // FORCE_LZFIND_SATUR_SUB_128
1628} 1712}
1713
1714
1715#undef MOVE_POS
1716#undef MOVE_POS_RET
1717#undef PRF
diff --git a/C/LzFind.h b/C/LzFind.h
index eea873f..a3f72c9 100644
--- a/C/LzFind.h
+++ b/C/LzFind.h
@@ -1,8 +1,8 @@
1/* LzFind.h -- Match finder for LZ algorithms 1/* LzFind.h -- Match finder for LZ algorithms
22021-07-13 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZ_FIND_H 4#ifndef ZIP7_INC_LZ_FIND_H
5#define __LZ_FIND_H 5#define ZIP7_INC_LZ_FIND_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -10,9 +10,9 @@ EXTERN_C_BEGIN
10 10
11typedef UInt32 CLzRef; 11typedef UInt32 CLzRef;
12 12
13typedef struct _CMatchFinder 13typedef struct
14{ 14{
15 Byte *buffer; 15 const Byte *buffer;
16 UInt32 pos; 16 UInt32 pos;
17 UInt32 posLimit; 17 UInt32 posLimit;
18 UInt32 streamPos; /* wrap over Zero is allowed (streamPos < pos). Use (UInt32)(streamPos - pos) */ 18 UInt32 streamPos; /* wrap over Zero is allowed (streamPos < pos). Use (UInt32)(streamPos - pos) */
@@ -32,8 +32,8 @@ typedef struct _CMatchFinder
32 UInt32 hashMask; 32 UInt32 hashMask;
33 UInt32 cutValue; 33 UInt32 cutValue;
34 34
35 Byte *bufferBase; 35 Byte *bufBase;
36 ISeqInStream *stream; 36 ISeqInStreamPtr stream;
37 37
38 UInt32 blockSize; 38 UInt32 blockSize;
39 UInt32 keepSizeBefore; 39 UInt32 keepSizeBefore;
@@ -43,7 +43,9 @@ typedef struct _CMatchFinder
43 size_t directInputRem; 43 size_t directInputRem;
44 UInt32 historySize; 44 UInt32 historySize;
45 UInt32 fixedHashSize; 45 UInt32 fixedHashSize;
46 UInt32 hashSizeSum; 46 Byte numHashBytes_Min;
47 Byte numHashOutBits;
48 Byte _pad2_[2];
47 SRes result; 49 SRes result;
48 UInt32 crc[256]; 50 UInt32 crc[256];
49 size_t numRefs; 51 size_t numRefs;
@@ -69,24 +71,45 @@ void MatchFinder_ReadIfRequired(CMatchFinder *p);
69 71
70void MatchFinder_Construct(CMatchFinder *p); 72void MatchFinder_Construct(CMatchFinder *p);
71 73
72/* Conditions: 74/* (directInput = 0) is default value.
73 historySize <= 3 GB 75 It's required to provide correct (directInput) value
74 keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB 76 before calling MatchFinder_Create().
77 You can set (directInput) by any of the following calls:
78 - MatchFinder_SET_DIRECT_INPUT_BUF()
79 - MatchFinder_SET_STREAM()
80 - MatchFinder_SET_STREAM_MODE()
75*/ 81*/
82
83#define MatchFinder_SET_DIRECT_INPUT_BUF(p, _src_, _srcLen_) { \
84 (p)->stream = NULL; \
85 (p)->directInput = 1; \
86 (p)->buffer = (_src_); \
87 (p)->directInputRem = (_srcLen_); }
88
89/*
90#define MatchFinder_SET_STREAM_MODE(p) { \
91 (p)->directInput = 0; }
92*/
93
94#define MatchFinder_SET_STREAM(p, _stream_) { \
95 (p)->stream = _stream_; \
96 (p)->directInput = 0; }
97
98
76int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, 99int MatchFinder_Create(CMatchFinder *p, UInt32 historySize,
77 UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, 100 UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter,
78 ISzAllocPtr alloc); 101 ISzAllocPtr alloc);
79void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc); 102void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc);
80void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems); 103void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems);
81// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
82 104
83/* 105/*
84#define Inline_MatchFinder_InitPos(p, val) \ 106#define MatchFinder_INIT_POS(p, val) \
85 (p)->pos = (val); \ 107 (p)->pos = (val); \
86 (p)->streamPos = (val); 108 (p)->streamPos = (val);
87*/ 109*/
88 110
89#define Inline_MatchFinder_ReduceOffsets(p, subValue) \ 111// void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue);
112#define MatchFinder_REDUCE_OFFSETS(p, subValue) \
90 (p)->pos -= (subValue); \ 113 (p)->pos -= (subValue); \
91 (p)->streamPos -= (subValue); 114 (p)->streamPos -= (subValue);
92 115
@@ -107,7 +130,7 @@ typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object);
107typedef UInt32 * (*Mf_GetMatches_Func)(void *object, UInt32 *distances); 130typedef UInt32 * (*Mf_GetMatches_Func)(void *object, UInt32 *distances);
108typedef void (*Mf_Skip_Func)(void *object, UInt32); 131typedef void (*Mf_Skip_Func)(void *object, UInt32);
109 132
110typedef struct _IMatchFinder 133typedef struct
111{ 134{
112 Mf_Init_Func Init; 135 Mf_Init_Func Init;
113 Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; 136 Mf_GetNumAvailableBytes_Func GetNumAvailableBytes;
diff --git a/C/LzFindMt.c b/C/LzFindMt.c
index 4e67fc3..5253e6e 100644
--- a/C/LzFindMt.c
+++ b/C/LzFindMt.c
@@ -1,5 +1,5 @@
1/* LzFindMt.c -- multithreaded Match finder for LZ algorithms 1/* LzFindMt.c -- multithreaded Match finder for LZ algorithms
22021-12-21 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -69,7 +69,7 @@ extern UInt64 g_NumIters_Bytes;
69 UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 69 UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
70 h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } 70 h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); }
71 71
72#define __MT_HASH4_CALC { \ 72#define MT_HASH4_CALC { \
73 UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 73 UInt32 temp = p->crc[cur[0]] ^ cur[1]; \
74 h2 = temp & (kHash2Size - 1); \ 74 h2 = temp & (kHash2Size - 1); \
75 temp ^= ((UInt32)cur[2] << 8); \ 75 temp ^= ((UInt32)cur[2] << 8); \
@@ -79,14 +79,14 @@ extern UInt64 g_NumIters_Bytes;
79*/ 79*/
80 80
81 81
82MY_NO_INLINE 82Z7_NO_INLINE
83static void MtSync_Construct(CMtSync *p) 83static void MtSync_Construct(CMtSync *p)
84{ 84{
85 p->affinity = 0; 85 p->affinity = 0;
86 p->wasCreated = False; 86 p->wasCreated = False;
87 p->csWasInitialized = False; 87 p->csWasInitialized = False;
88 p->csWasEntered = False; 88 p->csWasEntered = False;
89 Thread_Construct(&p->thread); 89 Thread_CONSTRUCT(&p->thread)
90 Event_Construct(&p->canStart); 90 Event_Construct(&p->canStart);
91 Event_Construct(&p->wasStopped); 91 Event_Construct(&p->wasStopped);
92 Semaphore_Construct(&p->freeSemaphore); 92 Semaphore_Construct(&p->freeSemaphore);
@@ -116,7 +116,7 @@ static void MtSync_Construct(CMtSync *p)
116 (p)->csWasEntered = False; } 116 (p)->csWasEntered = False; }
117 117
118 118
119MY_NO_INLINE 119Z7_NO_INLINE
120static UInt32 MtSync_GetNextBlock(CMtSync *p) 120static UInt32 MtSync_GetNextBlock(CMtSync *p)
121{ 121{
122 UInt32 numBlocks = 0; 122 UInt32 numBlocks = 0;
@@ -140,14 +140,14 @@ static UInt32 MtSync_GetNextBlock(CMtSync *p)
140 140
141 // buffer is UNLOCKED here 141 // buffer is UNLOCKED here
142 Semaphore_Wait(&p->filledSemaphore); 142 Semaphore_Wait(&p->filledSemaphore);
143 LOCK_BUFFER(p); 143 LOCK_BUFFER(p)
144 return numBlocks; 144 return numBlocks;
145} 145}
146 146
147 147
148/* if Writing (Processing) thread was started, we must call MtSync_StopWriting() */ 148/* if Writing (Processing) thread was started, we must call MtSync_StopWriting() */
149 149
150MY_NO_INLINE 150Z7_NO_INLINE
151static void MtSync_StopWriting(CMtSync *p) 151static void MtSync_StopWriting(CMtSync *p)
152{ 152{
153 if (!Thread_WasCreated(&p->thread) || p->needStart) 153 if (!Thread_WasCreated(&p->thread) || p->needStart)
@@ -185,7 +185,7 @@ static void MtSync_StopWriting(CMtSync *p)
185} 185}
186 186
187 187
188MY_NO_INLINE 188Z7_NO_INLINE
189static void MtSync_Destruct(CMtSync *p) 189static void MtSync_Destruct(CMtSync *p)
190{ 190{
191 PRF(printf("\nMtSync_Destruct %p\n", p)); 191 PRF(printf("\nMtSync_Destruct %p\n", p));
@@ -220,11 +220,11 @@ static void MtSync_Destruct(CMtSync *p)
220 220
221// #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } 221// #define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; }
222// we want to get real system error codes here instead of SZ_ERROR_THREAD 222// we want to get real system error codes here instead of SZ_ERROR_THREAD
223#define RINOK_THREAD(x) RINOK(x) 223#define RINOK_THREAD(x) RINOK_WRes(x)
224 224
225 225
226// call it before each new file (when new starting is required): 226// call it before each new file (when new starting is required):
227MY_NO_INLINE 227Z7_NO_INLINE
228static SRes MtSync_Init(CMtSync *p, UInt32 numBlocks) 228static SRes MtSync_Init(CMtSync *p, UInt32 numBlocks)
229{ 229{
230 WRes wres; 230 WRes wres;
@@ -245,12 +245,12 @@ static WRes MtSync_Create_WRes(CMtSync *p, THREAD_FUNC_TYPE startAddress, void *
245 if (p->wasCreated) 245 if (p->wasCreated)
246 return SZ_OK; 246 return SZ_OK;
247 247
248 RINOK_THREAD(CriticalSection_Init(&p->cs)); 248 RINOK_THREAD(CriticalSection_Init(&p->cs))
249 p->csWasInitialized = True; 249 p->csWasInitialized = True;
250 p->csWasEntered = False; 250 p->csWasEntered = False;
251 251
252 RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); 252 RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart))
253 RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); 253 RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped))
254 254
255 p->needStart = True; 255 p->needStart = True;
256 p->exit = True; /* p->exit is unused before (canStart) Event. 256 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 *
264 else 264 else
265 wres = Thread_Create(&p->thread, startAddress, obj); 265 wres = Thread_Create(&p->thread, startAddress, obj);
266 266
267 RINOK_THREAD(wres); 267 RINOK_THREAD(wres)
268 p->wasCreated = True; 268 p->wasCreated = True;
269 return SZ_OK; 269 return SZ_OK;
270} 270}
271 271
272 272
273MY_NO_INLINE 273Z7_NO_INLINE
274static SRes MtSync_Create(CMtSync *p, THREAD_FUNC_TYPE startAddress, void *obj) 274static SRes MtSync_Create(CMtSync *p, THREAD_FUNC_TYPE startAddress, void *obj)
275{ 275{
276 const WRes wres = MtSync_Create_WRes(p, startAddress, obj); 276 const WRes wres = MtSync_Create_WRes(p, startAddress, obj);
@@ -519,7 +519,7 @@ static void HashThreadFunc(CMatchFinderMt *mt)
519 if (mf->pos > (UInt32)kMtMaxValForNormalize - num) 519 if (mf->pos > (UInt32)kMtMaxValForNormalize - num)
520 { 520 {
521 const UInt32 subValue = (mf->pos - mf->historySize - 1); // & ~(UInt32)(kNormalizeAlign - 1); 521 const UInt32 subValue = (mf->pos - mf->historySize - 1); // & ~(UInt32)(kNormalizeAlign - 1);
522 Inline_MatchFinder_ReduceOffsets(mf, subValue); 522 MatchFinder_REDUCE_OFFSETS(mf, subValue)
523 MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, (size_t)mf->hashMask + 1); 523 MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, (size_t)mf->hashMask + 1);
524 } 524 }
525 525
@@ -560,7 +560,7 @@ static void HashThreadFunc(CMatchFinderMt *mt)
560*/ 560*/
561 561
562 562
563UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, 563UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son,
564 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, 564 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size,
565 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, 565 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize,
566 UInt32 *posRes); 566 UInt32 *posRes);
@@ -749,7 +749,7 @@ static void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex)
749} 749}
750 750
751 751
752MY_NO_INLINE 752Z7_NO_INLINE
753static void BtThreadFunc(CMatchFinderMt *mt) 753static void BtThreadFunc(CMatchFinderMt *mt)
754{ 754{
755 CMtSync *p = &mt->btSync; 755 CMtSync *p = &mt->btSync;
@@ -864,15 +864,15 @@ SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddB
864 if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) 864 if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc))
865 return SZ_ERROR_MEM; 865 return SZ_ERROR_MEM;
866 866
867 RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p)); 867 RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p))
868 RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p)); 868 RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p))
869 return SZ_OK; 869 return SZ_OK;
870} 870}
871 871
872 872
873SRes MatchFinderMt_InitMt(CMatchFinderMt *p) 873SRes MatchFinderMt_InitMt(CMatchFinderMt *p)
874{ 874{
875 RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks)); 875 RINOK(MtSync_Init(&p->hashSync, kMtHashNumBlocks))
876 return MtSync_Init(&p->btSync, kMtBtNumBlocks); 876 return MtSync_Init(&p->btSync, kMtBtNumBlocks);
877} 877}
878 878
@@ -941,7 +941,7 @@ void MatchFinderMt_ReleaseStream(CMatchFinderMt *p)
941} 941}
942 942
943 943
944MY_NO_INLINE 944Z7_NO_INLINE
945static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) 945static UInt32 MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p)
946{ 946{
947 if (p->failure_LZ_BT) 947 if (p->failure_LZ_BT)
@@ -1163,7 +1163,7 @@ UInt32* MatchFinderMt_GetMatches_Bt4(CMatchFinderMt *p, UInt32 *d)
1163*/ 1163*/
1164 1164
1165 1165
1166static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d) 1166static UInt32 * MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1167{ 1167{
1168 UInt32 h2, h3, /* h4, */ c2, c3 /* , c4 */; 1168 UInt32 h2, h3, /* h4, */ c2, c3 /* , c4 */;
1169 UInt32 *hash = p->hash; 1169 UInt32 *hash = p->hash;
@@ -1179,9 +1179,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1179 (hash + kFix3HashSize)[h3] = m; 1179 (hash + kFix3HashSize)[h3] = m;
1180 // (hash + kFix4HashSize)[h4] = m; 1180 // (hash + kFix4HashSize)[h4] = m;
1181 1181
1182 #define _USE_H2 1182 // #define BT5_USE_H2
1183 1183 // #ifdef BT5_USE_H2
1184 #ifdef _USE_H2
1185 if (c2 >= matchMinPos && cur[(ptrdiff_t)c2 - (ptrdiff_t)m] == cur[0]) 1184 if (c2 >= matchMinPos && cur[(ptrdiff_t)c2 - (ptrdiff_t)m] == cur[0])
1186 { 1185 {
1187 d[1] = m - c2 - 1; 1186 d[1] = m - c2 - 1;
@@ -1197,8 +1196,8 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1197 } 1196 }
1198 d[0] = 3; 1197 d[0] = 3;
1199 d += 2; 1198 d += 2;
1200 1199
1201 #ifdef _USE_H4 1200 #ifdef BT5_USE_H4
1202 if (c4 >= matchMinPos) 1201 if (c4 >= matchMinPos)
1203 if ( 1202 if (
1204 cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && 1203 cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] &&
@@ -1214,7 +1213,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1214 d[0] = 2; 1213 d[0] = 2;
1215 d += 2; 1214 d += 2;
1216 } 1215 }
1217 #endif 1216 // #endif
1218 1217
1219 if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0]) 1218 if (c3 >= matchMinPos && cur[(ptrdiff_t)c3 - (ptrdiff_t)m] == cur[0])
1220 { 1219 {
@@ -1228,7 +1227,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1228 d += 2; 1227 d += 2;
1229 } 1228 }
1230 1229
1231 #ifdef _USE_H4 1230 #ifdef BT5_USE_H4
1232 if (c4 >= matchMinPos) 1231 if (c4 >= matchMinPos)
1233 if ( 1232 if (
1234 cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] && 1233 cur[(ptrdiff_t)c4 - (ptrdiff_t)m] == cur[0] &&
@@ -1244,7 +1243,7 @@ static UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *d)
1244} 1243}
1245 1244
1246 1245
1247static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d) 1246static UInt32 * MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d)
1248{ 1247{
1249 const UInt32 *bt = p->btBufPos; 1248 const UInt32 *bt = p->btBufPos;
1250 const UInt32 len = *bt++; 1249 const UInt32 len = *bt++;
@@ -1268,7 +1267,7 @@ static UInt32* MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *d)
1268 1267
1269 1268
1270 1269
1271static UInt32* MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d) 1270static UInt32 * MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *d)
1272{ 1271{
1273 const UInt32 *bt = p->btBufPos; 1272 const UInt32 *bt = p->btBufPos;
1274 UInt32 len = *bt++; 1273 UInt32 len = *bt++;
@@ -1398,3 +1397,10 @@ void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder2 *vTable)
1398 break; 1397 break;
1399 } 1398 }
1400} 1399}
1400
1401#undef RINOK_THREAD
1402#undef PRF
1403#undef MF
1404#undef GetUi24hi_from32
1405#undef LOCK_BUFFER
1406#undef UNLOCK_BUFFER
diff --git a/C/LzFindMt.h b/C/LzFindMt.h
index 660b724..db5923e 100644
--- a/C/LzFindMt.h
+++ b/C/LzFindMt.h
@@ -1,15 +1,15 @@
1/* LzFindMt.h -- multithreaded Match finder for LZ algorithms 1/* LzFindMt.h -- multithreaded Match finder for LZ algorithms
22021-07-12 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZ_FIND_MT_H 4#ifndef ZIP7_INC_LZ_FIND_MT_H
5#define __LZ_FIND_MT_H 5#define ZIP7_INC_LZ_FIND_MT_H
6 6
7#include "LzFind.h" 7#include "LzFind.h"
8#include "Threads.h" 8#include "Threads.h"
9 9
10EXTERN_C_BEGIN 10EXTERN_C_BEGIN
11 11
12typedef struct _CMtSync 12typedef struct
13{ 13{
14 UInt32 numProcessedBlocks; 14 UInt32 numProcessedBlocks;
15 CThread thread; 15 CThread thread;
@@ -39,7 +39,7 @@ typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distance
39typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, 39typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos,
40 UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); 40 UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc);
41 41
42typedef struct _CMatchFinderMt 42typedef struct
43{ 43{
44 /* LZ */ 44 /* LZ */
45 const Byte *pointerToCurPos; 45 const Byte *pointerToCurPos;
diff --git a/C/LzFindOpt.c b/C/LzFindOpt.c
index 8ff006e..85bdc13 100644
--- a/C/LzFindOpt.c
+++ b/C/LzFindOpt.c
@@ -1,5 +1,5 @@
1/* LzFindOpt.c -- multithreaded Match finder for LZ algorithms 1/* LzFindOpt.c -- multithreaded Match finder for LZ algorithms
22021-07-13 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -41,8 +41,8 @@ UInt64 g_NumIters_Bytes;
41// #define CYC_TO_POS_OFFSET 1 // for debug 41// #define CYC_TO_POS_OFFSET 1 // for debug
42 42
43/* 43/*
44MY_NO_INLINE 44Z7_NO_INLINE
45UInt32 * MY_FAST_CALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, 45UInt32 * Z7_FASTCALL GetMatchesSpecN_1(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son,
46 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, UInt32 *posRes) 46 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, UInt32 *posRes)
47{ 47{
48 do 48 do
@@ -214,13 +214,13 @@ else
214 to eliminate "movsx" BUG in old MSVC x64 compiler. 214 to eliminate "movsx" BUG in old MSVC x64 compiler.
215*/ 215*/
216 216
217UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, 217UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son,
218 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, 218 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size,
219 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, 219 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize,
220 UInt32 *posRes); 220 UInt32 *posRes);
221 221
222MY_NO_INLINE 222Z7_NO_INLINE
223UInt32 * MY_FAST_CALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son, 223UInt32 * Z7_FASTCALL GetMatchesSpecN_2(const Byte *lenLimit, size_t pos, const Byte *cur, CLzRef *son,
224 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, 224 UInt32 _cutValue, UInt32 *d, size_t _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size,
225 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, 225 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize,
226 UInt32 *posRes) 226 UInt32 *posRes)
@@ -404,7 +404,7 @@ else
404/* 404/*
405typedef UInt32 uint32plus; // size_t 405typedef UInt32 uint32plus; // size_t
406 406
407UInt32 * MY_FAST_CALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son, 407UInt32 * Z7_FASTCALL GetMatchesSpecN_3(uint32plus lenLimit, size_t pos, const Byte *cur, CLzRef *son,
408 UInt32 _cutValue, UInt32 *d, uint32plus _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size, 408 UInt32 _cutValue, UInt32 *d, uint32plus _maxLen, const UInt32 *hash, const UInt32 *limit, const UInt32 *size,
409 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize, 409 size_t _cyclicBufferPos, UInt32 _cyclicBufferSize,
410 UInt32 *posRes) 410 UInt32 *posRes)
diff --git a/C/LzHash.h b/C/LzHash.h
index 77b898c..2b6290b 100644
--- a/C/LzHash.h
+++ b/C/LzHash.h
@@ -1,8 +1,8 @@
1/* LzHash.h -- HASH functions for LZ algorithms 1/* LzHash.h -- HASH constants for LZ algorithms
22019-10-30 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZ_HASH_H 4#ifndef ZIP7_INC_LZ_HASH_H
5#define __LZ_HASH_H 5#define ZIP7_INC_LZ_HASH_H
6 6
7/* 7/*
8 (kHash2Size >= (1 << 8)) : Required 8 (kHash2Size >= (1 << 8)) : Required
diff --git a/C/Lzma2Dec.c b/C/Lzma2Dec.c
index ac970a8..388cbc7 100644
--- a/C/Lzma2Dec.c
+++ b/C/Lzma2Dec.c
@@ -1,5 +1,5 @@
1/* Lzma2Dec.c -- LZMA2 Decoder 1/* Lzma2Dec.c -- LZMA2 Decoder
22021-02-09 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4/* #define SHOW_DEBUG_INFO */ 4/* #define SHOW_DEBUG_INFO */
5 5
@@ -71,14 +71,14 @@ static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props)
71SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) 71SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc)
72{ 72{
73 Byte props[LZMA_PROPS_SIZE]; 73 Byte props[LZMA_PROPS_SIZE];
74 RINOK(Lzma2Dec_GetOldProps(prop, props)); 74 RINOK(Lzma2Dec_GetOldProps(prop, props))
75 return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc); 75 return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
76} 76}
77 77
78SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc) 78SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc)
79{ 79{
80 Byte props[LZMA_PROPS_SIZE]; 80 Byte props[LZMA_PROPS_SIZE];
81 RINOK(Lzma2Dec_GetOldProps(prop, props)); 81 RINOK(Lzma2Dec_GetOldProps(prop, props))
82 return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc); 82 return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
83} 83}
84 84
@@ -474,8 +474,8 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
474 SizeT outSize = *destLen, inSize = *srcLen; 474 SizeT outSize = *destLen, inSize = *srcLen;
475 *destLen = *srcLen = 0; 475 *destLen = *srcLen = 0;
476 *status = LZMA_STATUS_NOT_SPECIFIED; 476 *status = LZMA_STATUS_NOT_SPECIFIED;
477 Lzma2Dec_Construct(&p); 477 Lzma2Dec_CONSTRUCT(&p)
478 RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc)); 478 RINOK(Lzma2Dec_AllocateProbs(&p, prop, alloc))
479 p.decoder.dic = dest; 479 p.decoder.dic = dest;
480 p.decoder.dicBufSize = outSize; 480 p.decoder.dicBufSize = outSize;
481 Lzma2Dec_Init(&p); 481 Lzma2Dec_Init(&p);
@@ -487,3 +487,5 @@ SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
487 Lzma2Dec_FreeProbs(&p, alloc); 487 Lzma2Dec_FreeProbs(&p, alloc);
488 return res; 488 return res;
489} 489}
490
491#undef PRF
diff --git a/C/Lzma2Dec.h b/C/Lzma2Dec.h
index b8ddeac..1f5233a 100644
--- a/C/Lzma2Dec.h
+++ b/C/Lzma2Dec.h
@@ -1,8 +1,8 @@
1/* Lzma2Dec.h -- LZMA2 Decoder 1/* Lzma2Dec.h -- LZMA2 Decoder
22018-02-19 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA2_DEC_H 4#ifndef ZIP7_INC_LZMA2_DEC_H
5#define __LZMA2_DEC_H 5#define ZIP7_INC_LZMA2_DEC_H
6 6
7#include "LzmaDec.h" 7#include "LzmaDec.h"
8 8
@@ -22,9 +22,10 @@ typedef struct
22 CLzmaDec decoder; 22 CLzmaDec decoder;
23} CLzma2Dec; 23} CLzma2Dec;
24 24
25#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder) 25#define Lzma2Dec_CONSTRUCT(p) LzmaDec_CONSTRUCT(&(p)->decoder)
26#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc) 26#define Lzma2Dec_Construct(p) Lzma2Dec_CONSTRUCT(p)
27#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc) 27#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc)
28#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc)
28 29
29SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); 30SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc);
30SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc); 31SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAllocPtr alloc);
@@ -90,7 +91,7 @@ Lzma2Dec_GetUnpackExtra() returns the value that shows
90 at current input positon. 91 at current input positon.
91*/ 92*/
92 93
93#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0); 94#define Lzma2Dec_GetUnpackExtra(p) ((p)->isExtraMode ? (p)->unpackSize : 0)
94 95
95 96
96/* ---------- One Call Interface ---------- */ 97/* ---------- One Call Interface ---------- */
diff --git a/C/Lzma2DecMt.c b/C/Lzma2DecMt.c
index 9f1dc52..4bc4dde 100644
--- a/C/Lzma2DecMt.c
+++ b/C/Lzma2DecMt.c
@@ -1,44 +1,44 @@
1/* Lzma2DecMt.c -- LZMA2 Decoder Multi-thread 1/* Lzma2DecMt.c -- LZMA2 Decoder Multi-thread
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6// #define SHOW_DEBUG_INFO 6// #define SHOW_DEBUG_INFO
7 7// #define Z7_ST
8// #define _7ZIP_ST
9 8
10#ifdef SHOW_DEBUG_INFO 9#ifdef SHOW_DEBUG_INFO
11#include <stdio.h> 10#include <stdio.h>
12#endif 11#endif
13 12
14#ifndef _7ZIP_ST
15#ifdef SHOW_DEBUG_INFO
16#define PRF(x) x
17#else
18#define PRF(x)
19#endif
20#define PRF_STR(s) PRF(printf("\n" s "\n"))
21#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2))
22#endif
23
24#include "Alloc.h" 13#include "Alloc.h"
25 14
26#include "Lzma2Dec.h" 15#include "Lzma2Dec.h"
27#include "Lzma2DecMt.h" 16#include "Lzma2DecMt.h"
28 17
29#ifndef _7ZIP_ST 18#ifndef Z7_ST
30#include "MtDec.h" 19#include "MtDec.h"
31 20
32#define LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT (1 << 28) 21#define LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT (1 << 28)
33#endif 22#endif
34 23
35 24
25#ifndef Z7_ST
26#ifdef SHOW_DEBUG_INFO
27#define PRF(x) x
28#else
29#define PRF(x)
30#endif
31#define PRF_STR(s) PRF(printf("\n" s "\n");)
32#define PRF_STR_INT_2(s, d1, d2) PRF(printf("\n" s " %d %d\n", (unsigned)d1, (unsigned)d2);)
33#endif
34
35
36void Lzma2DecMtProps_Init(CLzma2DecMtProps *p) 36void Lzma2DecMtProps_Init(CLzma2DecMtProps *p)
37{ 37{
38 p->inBufSize_ST = 1 << 20; 38 p->inBufSize_ST = 1 << 20;
39 p->outStep_ST = 1 << 20; 39 p->outStep_ST = 1 << 20;
40 40
41 #ifndef _7ZIP_ST 41 #ifndef Z7_ST
42 p->numThreads = 1; 42 p->numThreads = 1;
43 p->inBufSize_MT = 1 << 18; 43 p->inBufSize_MT = 1 << 18;
44 p->outBlockMax = LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT; 44 p->outBlockMax = LZMA2DECMT_OUT_BLOCK_MAX_DEFAULT;
@@ -48,7 +48,7 @@ void Lzma2DecMtProps_Init(CLzma2DecMtProps *p)
48 48
49 49
50 50
51#ifndef _7ZIP_ST 51#ifndef Z7_ST
52 52
53/* ---------- CLzma2DecMtThread ---------- */ 53/* ---------- CLzma2DecMtThread ---------- */
54 54
@@ -81,7 +81,7 @@ typedef struct
81 81
82/* ---------- CLzma2DecMt ---------- */ 82/* ---------- CLzma2DecMt ---------- */
83 83
84typedef struct 84struct CLzma2DecMt
85{ 85{
86 // ISzAllocPtr alloc; 86 // ISzAllocPtr alloc;
87 ISzAllocPtr allocMid; 87 ISzAllocPtr allocMid;
@@ -90,9 +90,9 @@ typedef struct
90 CLzma2DecMtProps props; 90 CLzma2DecMtProps props;
91 Byte prop; 91 Byte prop;
92 92
93 ISeqInStream *inStream; 93 ISeqInStreamPtr inStream;
94 ISeqOutStream *outStream; 94 ISeqOutStreamPtr outStream;
95 ICompressProgress *progress; 95 ICompressProgressPtr progress;
96 96
97 BoolInt finishMode; 97 BoolInt finishMode;
98 BoolInt outSize_Defined; 98 BoolInt outSize_Defined;
@@ -111,14 +111,13 @@ typedef struct
111 size_t inPos; 111 size_t inPos;
112 size_t inLim; 112 size_t inLim;
113 113
114 #ifndef _7ZIP_ST 114 #ifndef Z7_ST
115 UInt64 outProcessed_Parse; 115 UInt64 outProcessed_Parse;
116 BoolInt mtc_WasConstructed; 116 BoolInt mtc_WasConstructed;
117 CMtDec mtc; 117 CMtDec mtc;
118 CLzma2DecMtThread coders[MTDEC__THREADS_MAX]; 118 CLzma2DecMtThread coders[MTDEC_THREADS_MAX];
119 #endif 119 #endif
120 120};
121} CLzma2DecMt;
122 121
123 122
124 123
@@ -142,11 +141,11 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid)
142 141
143 // Lzma2DecMtProps_Init(&p->props); 142 // Lzma2DecMtProps_Init(&p->props);
144 143
145 #ifndef _7ZIP_ST 144 #ifndef Z7_ST
146 p->mtc_WasConstructed = False; 145 p->mtc_WasConstructed = False;
147 { 146 {
148 unsigned i; 147 unsigned i;
149 for (i = 0; i < MTDEC__THREADS_MAX; i++) 148 for (i = 0; i < MTDEC_THREADS_MAX; i++)
150 { 149 {
151 CLzma2DecMtThread *t = &p->coders[i]; 150 CLzma2DecMtThread *t = &p->coders[i];
152 t->dec_created = False; 151 t->dec_created = False;
@@ -156,16 +155,16 @@ CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid)
156 } 155 }
157 #endif 156 #endif
158 157
159 return p; 158 return (CLzma2DecMtHandle)(void *)p;
160} 159}
161 160
162 161
163#ifndef _7ZIP_ST 162#ifndef Z7_ST
164 163
165static void Lzma2DecMt_FreeOutBufs(CLzma2DecMt *p) 164static void Lzma2DecMt_FreeOutBufs(CLzma2DecMt *p)
166{ 165{
167 unsigned i; 166 unsigned i;
168 for (i = 0; i < MTDEC__THREADS_MAX; i++) 167 for (i = 0; i < MTDEC_THREADS_MAX; i++)
169 { 168 {
170 CLzma2DecMtThread *t = &p->coders[i]; 169 CLzma2DecMtThread *t = &p->coders[i];
171 if (t->outBuf) 170 if (t->outBuf)
@@ -196,13 +195,15 @@ static void Lzma2DecMt_FreeSt(CLzma2DecMt *p)
196} 195}
197 196
198 197
199void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp) 198// #define GET_CLzma2DecMt_p CLzma2DecMt *p = (CLzma2DecMt *)(void *)pp;
199
200void Lzma2DecMt_Destroy(CLzma2DecMtHandle p)
200{ 201{
201 CLzma2DecMt *p = (CLzma2DecMt *)pp; 202 // GET_CLzma2DecMt_p
202 203
203 Lzma2DecMt_FreeSt(p); 204 Lzma2DecMt_FreeSt(p);
204 205
205 #ifndef _7ZIP_ST 206 #ifndef Z7_ST
206 207
207 if (p->mtc_WasConstructed) 208 if (p->mtc_WasConstructed)
208 { 209 {
@@ -211,7 +212,7 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp)
211 } 212 }
212 { 213 {
213 unsigned i; 214 unsigned i;
214 for (i = 0; i < MTDEC__THREADS_MAX; i++) 215 for (i = 0; i < MTDEC_THREADS_MAX; i++)
215 { 216 {
216 CLzma2DecMtThread *t = &p->coders[i]; 217 CLzma2DecMtThread *t = &p->coders[i];
217 if (t->dec_created) 218 if (t->dec_created)
@@ -226,19 +227,19 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle pp)
226 227
227 #endif 228 #endif
228 229
229 ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); 230 ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p);
230} 231}
231 232
232 233
233 234
234#ifndef _7ZIP_ST 235#ifndef Z7_ST
235 236
236static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) 237static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc)
237{ 238{
238 CLzma2DecMt *me = (CLzma2DecMt *)obj; 239 CLzma2DecMt *me = (CLzma2DecMt *)obj;
239 CLzma2DecMtThread *t = &me->coders[coderIndex]; 240 CLzma2DecMtThread *t = &me->coders[coderIndex];
240 241
241 PRF_STR_INT_2("Parse", coderIndex, cc->srcSize); 242 PRF_STR_INT_2("Parse", coderIndex, cc->srcSize)
242 243
243 cc->state = MTDEC_PARSE_CONTINUE; 244 cc->state = MTDEC_PARSE_CONTINUE;
244 245
@@ -246,7 +247,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa
246 { 247 {
247 if (!t->dec_created) 248 if (!t->dec_created)
248 { 249 {
249 Lzma2Dec_Construct(&t->dec); 250 Lzma2Dec_CONSTRUCT(&t->dec)
250 t->dec_created = True; 251 t->dec_created = True;
251 AlignOffsetAlloc_CreateVTable(&t->alloc); 252 AlignOffsetAlloc_CreateVTable(&t->alloc);
252 { 253 {
@@ -297,7 +298,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa
297 // that must be finished at position <= outBlockMax. 298 // that must be finished at position <= outBlockMax.
298 299
299 { 300 {
300 const SizeT srcOrig = cc->srcSize; 301 const size_t srcOrig = cc->srcSize;
301 SizeT srcSize_Point = 0; 302 SizeT srcSize_Point = 0;
302 SizeT dicPos_Point = 0; 303 SizeT dicPos_Point = 0;
303 304
@@ -306,10 +307,10 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa
306 307
307 for (;;) 308 for (;;)
308 { 309 {
309 SizeT srcCur = srcOrig - cc->srcSize; 310 SizeT srcCur = (SizeT)(srcOrig - cc->srcSize);
310 311
311 status = Lzma2Dec_Parse(&t->dec, 312 status = Lzma2Dec_Parse(&t->dec,
312 limit - t->dec.decoder.dicPos, 313 (SizeT)limit - t->dec.decoder.dicPos,
313 cc->src + cc->srcSize, &srcCur, 314 cc->src + cc->srcSize, &srcCur,
314 checkFinishBlock); 315 checkFinishBlock);
315 316
@@ -333,7 +334,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa
333 if (t->dec.decoder.dicPos >= (1 << 14)) 334 if (t->dec.decoder.dicPos >= (1 << 14))
334 break; 335 break;
335 dicPos_Point = t->dec.decoder.dicPos; 336 dicPos_Point = t->dec.decoder.dicPos;
336 srcSize_Point = cc->srcSize; 337 srcSize_Point = (SizeT)cc->srcSize;
337 continue; 338 continue;
338 } 339 }
339 340
@@ -391,7 +392,7 @@ static void Lzma2DecMt_MtCallback_Parse(void *obj, unsigned coderIndex, CMtDecCa
391 if (unpackRem != 0) 392 if (unpackRem != 0)
392 { 393 {
393 /* we also reserve space for max possible number of output bytes of current LZMA chunk */ 394 /* we also reserve space for max possible number of output bytes of current LZMA chunk */
394 SizeT rem = limit - dicPos; 395 size_t rem = limit - dicPos;
395 if (rem > unpackRem) 396 if (rem > unpackRem)
396 rem = unpackRem; 397 rem = unpackRem;
397 dicPos += rem; 398 dicPos += rem;
@@ -444,7 +445,7 @@ static SRes Lzma2DecMt_MtCallback_PreCode(void *pp, unsigned coderIndex)
444 } 445 }
445 446
446 t->dec.decoder.dic = dest; 447 t->dec.decoder.dic = dest;
447 t->dec.decoder.dicBufSize = t->outPreSize; 448 t->dec.decoder.dicBufSize = (SizeT)t->outPreSize;
448 449
449 t->needInit = True; 450 t->needInit = True;
450 451
@@ -462,7 +463,7 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex,
462 463
463 UNUSED_VAR(srcFinished) 464 UNUSED_VAR(srcFinished)
464 465
465 PRF_STR_INT_2("Code", coderIndex, srcSize); 466 PRF_STR_INT_2("Code", coderIndex, srcSize)
466 467
467 *inCodePos = t->inCodeSize; 468 *inCodePos = t->inCodeSize;
468 *outCodePos = 0; 469 *outCodePos = 0;
@@ -476,13 +477,13 @@ static SRes Lzma2DecMt_MtCallback_Code(void *pp, unsigned coderIndex,
476 477
477 { 478 {
478 ELzmaStatus status; 479 ELzmaStatus status;
479 size_t srcProcessed = srcSize; 480 SizeT srcProcessed = (SizeT)srcSize;
480 BoolInt blockWasFinished = 481 BoolInt blockWasFinished =
481 ((int)t->parseStatus == LZMA_STATUS_FINISHED_WITH_MARK 482 ((int)t->parseStatus == LZMA_STATUS_FINISHED_WITH_MARK
482 || t->parseStatus == LZMA2_PARSE_STATUS_NEW_BLOCK); 483 || t->parseStatus == LZMA2_PARSE_STATUS_NEW_BLOCK);
483 484
484 SRes res = Lzma2Dec_DecodeToDic(&t->dec, 485 SRes res = Lzma2Dec_DecodeToDic(&t->dec,
485 t->outPreSize, 486 (SizeT)t->outPreSize,
486 src, &srcProcessed, 487 src, &srcProcessed,
487 blockWasFinished ? LZMA_FINISH_END : LZMA_FINISH_ANY, 488 blockWasFinished ? LZMA_FINISH_END : LZMA_FINISH_ANY,
488 &status); 489 &status);
@@ -540,7 +541,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex,
540 UNUSED_VAR(srcSize) 541 UNUSED_VAR(srcSize)
541 UNUSED_VAR(isCross) 542 UNUSED_VAR(isCross)
542 543
543 PRF_STR_INT_2("Write", coderIndex, srcSize); 544 PRF_STR_INT_2("Write", coderIndex, srcSize)
544 545
545 *needContinue = False; 546 *needContinue = False;
546 *canRecode = True; 547 *canRecode = True;
@@ -588,7 +589,7 @@ static SRes Lzma2DecMt_MtCallback_Write(void *pp, unsigned coderIndex,
588 *needContinue = needContinue2; 589 *needContinue = needContinue2;
589 return SZ_OK; 590 return SZ_OK;
590 } 591 }
591 RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0)); 592 RINOK(MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0))
592 } 593 }
593 } 594 }
594 595
@@ -611,11 +612,11 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p)
611{ 612{
612 if (!p->dec_created) 613 if (!p->dec_created)
613 { 614 {
614 Lzma2Dec_Construct(&p->dec); 615 Lzma2Dec_CONSTRUCT(&p->dec)
615 p->dec_created = True; 616 p->dec_created = True;
616 } 617 }
617 618
618 RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt)); 619 RINOK(Lzma2Dec_Allocate(&p->dec, p->prop, &p->alignOffsetAlloc.vt))
619 620
620 if (!p->inBuf || p->inBufSize != p->props.inBufSize_ST) 621 if (!p->inBuf || p->inBufSize != p->props.inBufSize_ST)
621 { 622 {
@@ -634,7 +635,7 @@ static SRes Lzma2Dec_Prepare_ST(CLzma2DecMt *p)
634 635
635 636
636static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p 637static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
637 #ifndef _7ZIP_ST 638 #ifndef Z7_ST
638 , BoolInt tMode 639 , BoolInt tMode
639 #endif 640 #endif
640 ) 641 )
@@ -646,7 +647,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
646 647
647 CLzma2Dec *dec; 648 CLzma2Dec *dec;
648 649
649 #ifndef _7ZIP_ST 650 #ifndef Z7_ST
650 if (tMode) 651 if (tMode)
651 { 652 {
652 Lzma2DecMt_FreeOutBufs(p); 653 Lzma2DecMt_FreeOutBufs(p);
@@ -654,7 +655,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
654 } 655 }
655 #endif 656 #endif
656 657
657 RINOK(Lzma2Dec_Prepare_ST(p)); 658 RINOK(Lzma2Dec_Prepare_ST(p))
658 659
659 dec = &p->dec; 660 dec = &p->dec;
660 661
@@ -681,7 +682,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
681 682
682 if (inPos == inLim) 683 if (inPos == inLim)
683 { 684 {
684 #ifndef _7ZIP_ST 685 #ifndef Z7_ST
685 if (tMode) 686 if (tMode)
686 { 687 {
687 inData = MtDec_Read(&p->mtc, &inLim); 688 inData = MtDec_Read(&p->mtc, &inLim);
@@ -710,7 +711,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
710 { 711 {
711 SizeT next = dec->decoder.dicBufSize; 712 SizeT next = dec->decoder.dicBufSize;
712 if (next - wrPos > p->props.outStep_ST) 713 if (next - wrPos > p->props.outStep_ST)
713 next = wrPos + p->props.outStep_ST; 714 next = wrPos + (SizeT)p->props.outStep_ST;
714 size = next - dicPos; 715 size = next - dicPos;
715 } 716 }
716 717
@@ -726,7 +727,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
726 } 727 }
727 } 728 }
728 729
729 inProcessed = inLim - inPos; 730 inProcessed = (SizeT)(inLim - inPos);
730 731
731 res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status); 732 res = Lzma2Dec_DecodeToDic(dec, dicPos + size, inData + inPos, &inProcessed, finishMode, &status);
732 733
@@ -755,7 +756,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
755 dec->decoder.dicPos = 0; 756 dec->decoder.dicPos = 0;
756 wrPos = dec->decoder.dicPos; 757 wrPos = dec->decoder.dicPos;
757 758
758 RINOK(res2); 759 RINOK(res2)
759 760
760 if (needStop) 761 if (needStop)
761 { 762 {
@@ -788,7 +789,7 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
788 UInt64 outDelta = p->outProcessed - outPrev; 789 UInt64 outDelta = p->outProcessed - outPrev;
789 if (inDelta >= (1 << 22) || outDelta >= (1 << 22)) 790 if (inDelta >= (1 << 22) || outDelta >= (1 << 22))
790 { 791 {
791 RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed)); 792 RINOK(ICompressProgress_Progress(p->progress, p->inProcessed, p->outProcessed))
792 inPrev = p->inProcessed; 793 inPrev = p->inProcessed;
793 outPrev = p->outProcessed; 794 outPrev = p->outProcessed;
794 } 795 }
@@ -798,20 +799,20 @@ static SRes Lzma2Dec_Decode_ST(CLzma2DecMt *p
798 799
799 800
800 801
801SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp, 802SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p,
802 Byte prop, 803 Byte prop,
803 const CLzma2DecMtProps *props, 804 const CLzma2DecMtProps *props,
804 ISeqOutStream *outStream, const UInt64 *outDataSize, int finishMode, 805 ISeqOutStreamPtr outStream, const UInt64 *outDataSize, int finishMode,
805 // Byte *outBuf, size_t *outBufSize, 806 // Byte *outBuf, size_t *outBufSize,
806 ISeqInStream *inStream, 807 ISeqInStreamPtr inStream,
807 // const Byte *inData, size_t inDataSize, 808 // const Byte *inData, size_t inDataSize,
808 UInt64 *inProcessed, 809 UInt64 *inProcessed,
809 // UInt64 *outProcessed, 810 // UInt64 *outProcessed,
810 int *isMT, 811 int *isMT,
811 ICompressProgress *progress) 812 ICompressProgressPtr progress)
812{ 813{
813 CLzma2DecMt *p = (CLzma2DecMt *)pp; 814 // GET_CLzma2DecMt_p
814 #ifndef _7ZIP_ST 815 #ifndef Z7_ST
815 BoolInt tMode; 816 BoolInt tMode;
816 #endif 817 #endif
817 818
@@ -845,7 +846,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp,
845 *isMT = False; 846 *isMT = False;
846 847
847 848
848 #ifndef _7ZIP_ST 849 #ifndef Z7_ST
849 850
850 tMode = False; 851 tMode = False;
851 852
@@ -939,7 +940,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp,
939 p->readWasFinished = p->mtc.readWasFinished; 940 p->readWasFinished = p->mtc.readWasFinished;
940 p->inProcessed = p->mtc.inProcessed; 941 p->inProcessed = p->mtc.inProcessed;
941 942
942 PRF_STR("----- decoding ST -----"); 943 PRF_STR("----- decoding ST -----")
943 } 944 }
944 } 945 }
945 946
@@ -950,7 +951,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp,
950 951
951 { 952 {
952 SRes res = Lzma2Dec_Decode_ST(p 953 SRes res = Lzma2Dec_Decode_ST(p
953 #ifndef _7ZIP_ST 954 #ifndef Z7_ST
954 , tMode 955 , tMode
955 #endif 956 #endif
956 ); 957 );
@@ -967,7 +968,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp,
967 res = p->readRes; 968 res = p->readRes;
968 969
969 /* 970 /*
970 #ifndef _7ZIP_ST 971 #ifndef Z7_ST
971 if (res == SZ_OK && tMode && p->mtc.parseRes != SZ_OK) 972 if (res == SZ_OK && tMode && p->mtc.parseRes != SZ_OK)
972 res = p->mtc.parseRes; 973 res = p->mtc.parseRes;
973 #endif 974 #endif
@@ -980,13 +981,13 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle pp,
980 981
981/* ---------- Read from CLzma2DecMtHandle Interface ---------- */ 982/* ---------- Read from CLzma2DecMtHandle Interface ---------- */
982 983
983SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp, 984SRes Lzma2DecMt_Init(CLzma2DecMtHandle p,
984 Byte prop, 985 Byte prop,
985 const CLzma2DecMtProps *props, 986 const CLzma2DecMtProps *props,
986 const UInt64 *outDataSize, int finishMode, 987 const UInt64 *outDataSize, int finishMode,
987 ISeqInStream *inStream) 988 ISeqInStreamPtr inStream)
988{ 989{
989 CLzma2DecMt *p = (CLzma2DecMt *)pp; 990 // GET_CLzma2DecMt_p
990 991
991 if (prop > 40) 992 if (prop > 40)
992 return SZ_ERROR_UNSUPPORTED; 993 return SZ_ERROR_UNSUPPORTED;
@@ -1015,11 +1016,11 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp,
1015} 1016}
1016 1017
1017 1018
1018SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, 1019SRes Lzma2DecMt_Read(CLzma2DecMtHandle p,
1019 Byte *data, size_t *outSize, 1020 Byte *data, size_t *outSize,
1020 UInt64 *inStreamProcessed) 1021 UInt64 *inStreamProcessed)
1021{ 1022{
1022 CLzma2DecMt *p = (CLzma2DecMt *)pp; 1023 // GET_CLzma2DecMt_p
1023 ELzmaFinishMode finishMode; 1024 ELzmaFinishMode finishMode;
1024 SRes readRes; 1025 SRes readRes;
1025 size_t size = *outSize; 1026 size_t size = *outSize;
@@ -1055,8 +1056,8 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp,
1055 readRes = ISeqInStream_Read(p->inStream, p->inBuf, &p->inLim); 1056 readRes = ISeqInStream_Read(p->inStream, p->inBuf, &p->inLim);
1056 } 1057 }
1057 1058
1058 inCur = p->inLim - p->inPos; 1059 inCur = (SizeT)(p->inLim - p->inPos);
1059 outCur = size; 1060 outCur = (SizeT)size;
1060 1061
1061 res = Lzma2Dec_DecodeToBuf(&p->dec, data, &outCur, 1062 res = Lzma2Dec_DecodeToBuf(&p->dec, data, &outCur,
1062 p->inBuf + p->inPos, &inCur, finishMode, &status); 1063 p->inBuf + p->inPos, &inCur, finishMode, &status);
@@ -1088,3 +1089,7 @@ SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp,
1088 return readRes; 1089 return readRes;
1089 } 1090 }
1090} 1091}
1092
1093#undef PRF
1094#undef PRF_STR
1095#undef PRF_STR_INT_2
diff --git a/C/Lzma2DecMt.h b/C/Lzma2DecMt.h
index 7791c31..93a5cd5 100644
--- a/C/Lzma2DecMt.h
+++ b/C/Lzma2DecMt.h
@@ -1,8 +1,8 @@
1/* Lzma2DecMt.h -- LZMA2 Decoder Multi-thread 1/* Lzma2DecMt.h -- LZMA2 Decoder Multi-thread
22018-02-17 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA2_DEC_MT_H 4#ifndef ZIP7_INC_LZMA2_DEC_MT_H
5#define __LZMA2_DEC_MT_H 5#define ZIP7_INC_LZMA2_DEC_MT_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -13,7 +13,7 @@ typedef struct
13 size_t inBufSize_ST; 13 size_t inBufSize_ST;
14 size_t outStep_ST; 14 size_t outStep_ST;
15 15
16 #ifndef _7ZIP_ST 16 #ifndef Z7_ST
17 unsigned numThreads; 17 unsigned numThreads;
18 size_t inBufSize_MT; 18 size_t inBufSize_MT;
19 size_t outBlockMax; 19 size_t outBlockMax;
@@ -38,7 +38,9 @@ SRes:
38 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) 38 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version)
39*/ 39*/
40 40
41typedef void * CLzma2DecMtHandle; 41typedef struct CLzma2DecMt CLzma2DecMt;
42typedef CLzma2DecMt * CLzma2DecMtHandle;
43// Z7_DECLARE_HANDLE(CLzma2DecMtHandle)
42 44
43CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid); 45CLzma2DecMtHandle Lzma2DecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid);
44void Lzma2DecMt_Destroy(CLzma2DecMtHandle p); 46void Lzma2DecMt_Destroy(CLzma2DecMtHandle p);
@@ -46,11 +48,11 @@ void Lzma2DecMt_Destroy(CLzma2DecMtHandle p);
46SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p, 48SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p,
47 Byte prop, 49 Byte prop,
48 const CLzma2DecMtProps *props, 50 const CLzma2DecMtProps *props,
49 ISeqOutStream *outStream, 51 ISeqOutStreamPtr outStream,
50 const UInt64 *outDataSize, // NULL means undefined 52 const UInt64 *outDataSize, // NULL means undefined
51 int finishMode, // 0 - partial unpacking is allowed, 1 - if lzma2 stream must be finished 53 int finishMode, // 0 - partial unpacking is allowed, 1 - if lzma2 stream must be finished
52 // Byte *outBuf, size_t *outBufSize, 54 // Byte *outBuf, size_t *outBufSize,
53 ISeqInStream *inStream, 55 ISeqInStreamPtr inStream,
54 // const Byte *inData, size_t inDataSize, 56 // const Byte *inData, size_t inDataSize,
55 57
56 // out variables: 58 // out variables:
@@ -58,7 +60,7 @@ SRes Lzma2DecMt_Decode(CLzma2DecMtHandle p,
58 int *isMT, /* out: (*isMT == 0), if single thread decoding was used */ 60 int *isMT, /* out: (*isMT == 0), if single thread decoding was used */
59 61
60 // UInt64 *outProcessed, 62 // UInt64 *outProcessed,
61 ICompressProgress *progress); 63 ICompressProgressPtr progress);
62 64
63 65
64/* ---------- Read from CLzma2DecMtHandle Interface ---------- */ 66/* ---------- Read from CLzma2DecMtHandle Interface ---------- */
@@ -67,7 +69,7 @@ SRes Lzma2DecMt_Init(CLzma2DecMtHandle pp,
67 Byte prop, 69 Byte prop,
68 const CLzma2DecMtProps *props, 70 const CLzma2DecMtProps *props,
69 const UInt64 *outDataSize, int finishMode, 71 const UInt64 *outDataSize, int finishMode,
70 ISeqInStream *inStream); 72 ISeqInStreamPtr inStream);
71 73
72SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp, 74SRes Lzma2DecMt_Read(CLzma2DecMtHandle pp,
73 Byte *data, size_t *outSize, 75 Byte *data, size_t *outSize,
diff --git a/C/Lzma2Enc.c b/C/Lzma2Enc.c
index e61a5df..703e146 100644
--- a/C/Lzma2Enc.c
+++ b/C/Lzma2Enc.c
@@ -1,18 +1,18 @@
1/* Lzma2Enc.c -- LZMA2 Encoder 1/* Lzma2Enc.c -- LZMA2 Encoder
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include <string.h> 6#include <string.h>
7 7
8/* #define _7ZIP_ST */ 8/* #define Z7_ST */
9 9
10#include "Lzma2Enc.h" 10#include "Lzma2Enc.h"
11 11
12#ifndef _7ZIP_ST 12#ifndef Z7_ST
13#include "MtCoder.h" 13#include "MtCoder.h"
14#else 14#else
15#define MTCODER__THREADS_MAX 1 15#define MTCODER_THREADS_MAX 1
16#endif 16#endif
17 17
18#define LZMA2_CONTROL_LZMA (1 << 7) 18#define LZMA2_CONTROL_LZMA (1 << 7)
@@ -40,7 +40,7 @@
40typedef struct 40typedef struct
41{ 41{
42 ISeqInStream vt; 42 ISeqInStream vt;
43 ISeqInStream *realStream; 43 ISeqInStreamPtr realStream;
44 UInt64 limit; 44 UInt64 limit;
45 UInt64 processed; 45 UInt64 processed;
46 int finished; 46 int finished;
@@ -53,15 +53,15 @@ static void LimitedSeqInStream_Init(CLimitedSeqInStream *p)
53 p->finished = 0; 53 p->finished = 0;
54} 54}
55 55
56static SRes LimitedSeqInStream_Read(const ISeqInStream *pp, void *data, size_t *size) 56static SRes LimitedSeqInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size)
57{ 57{
58 CLimitedSeqInStream *p = CONTAINER_FROM_VTBL(pp, CLimitedSeqInStream, vt); 58 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLimitedSeqInStream)
59 size_t size2 = *size; 59 size_t size2 = *size;
60 SRes res = SZ_OK; 60 SRes res = SZ_OK;
61 61
62 if (p->limit != (UInt64)(Int64)-1) 62 if (p->limit != (UInt64)(Int64)-1)
63 { 63 {
64 UInt64 rem = p->limit - p->processed; 64 const UInt64 rem = p->limit - p->processed;
65 if (size2 > rem) 65 if (size2 > rem)
66 size2 = (size_t)rem; 66 size2 = (size_t)rem;
67 } 67 }
@@ -95,8 +95,8 @@ static SRes Lzma2EncInt_InitStream(CLzma2EncInt *p, const CLzma2EncProps *props)
95 { 95 {
96 SizeT propsSize = LZMA_PROPS_SIZE; 96 SizeT propsSize = LZMA_PROPS_SIZE;
97 Byte propsEncoded[LZMA_PROPS_SIZE]; 97 Byte propsEncoded[LZMA_PROPS_SIZE];
98 RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps)); 98 RINOK(LzmaEnc_SetProps(p->enc, &props->lzmaProps))
99 RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize)); 99 RINOK(LzmaEnc_WriteProperties(p->enc, propsEncoded, &propsSize))
100 p->propsByte = propsEncoded[0]; 100 p->propsByte = propsEncoded[0];
101 p->propsAreSet = True; 101 p->propsAreSet = True;
102 } 102 }
@@ -111,23 +111,23 @@ static void Lzma2EncInt_InitBlock(CLzma2EncInt *p)
111} 111}
112 112
113 113
114SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, 114SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize,
115 ISzAllocPtr alloc, ISzAllocPtr allocBig); 115 ISzAllocPtr alloc, ISzAllocPtr allocBig);
116SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, 116SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen,
117 UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); 117 UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig);
118SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, 118SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit,
119 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); 119 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize);
120const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); 120const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p);
121void LzmaEnc_Finish(CLzmaEncHandle pp); 121void LzmaEnc_Finish(CLzmaEncHandle p);
122void LzmaEnc_SaveState(CLzmaEncHandle pp); 122void LzmaEnc_SaveState(CLzmaEncHandle p);
123void LzmaEnc_RestoreState(CLzmaEncHandle pp); 123void LzmaEnc_RestoreState(CLzmaEncHandle p);
124 124
125/* 125/*
126UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp); 126UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p);
127*/ 127*/
128 128
129static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf, 129static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf,
130 size_t *packSizeRes, ISeqOutStream *outStream) 130 size_t *packSizeRes, ISeqOutStreamPtr outStream)
131{ 131{
132 size_t packSizeLimit = *packSizeRes; 132 size_t packSizeLimit = *packSizeRes;
133 size_t packSize = packSizeLimit; 133 size_t packSize = packSizeLimit;
@@ -167,7 +167,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf,
167 167
168 while (unpackSize > 0) 168 while (unpackSize > 0)
169 { 169 {
170 UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE; 170 const UInt32 u = (unpackSize < LZMA2_COPY_CHUNK_SIZE) ? unpackSize : LZMA2_COPY_CHUNK_SIZE;
171 if (packSizeLimit - destPos < u + 3) 171 if (packSizeLimit - destPos < u + 3)
172 return SZ_ERROR_OUTPUT_EOF; 172 return SZ_ERROR_OUTPUT_EOF;
173 outBuf[destPos++] = (Byte)(p->srcPos == 0 ? LZMA2_CONTROL_COPY_RESET_DIC : LZMA2_CONTROL_COPY_NO_RESET); 173 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,
196 196
197 { 197 {
198 size_t destPos = 0; 198 size_t destPos = 0;
199 UInt32 u = unpackSize - 1; 199 const UInt32 u = unpackSize - 1;
200 UInt32 pm = (UInt32)(packSize - 1); 200 const UInt32 pm = (UInt32)(packSize - 1);
201 unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0); 201 const unsigned mode = (p->srcPos == 0) ? 3 : (p->needInitState ? (p->needInitProp ? 2 : 1) : 0);
202 202
203 PRF(printf(" ")); 203 PRF(printf(" "));
204 204
@@ -231,7 +231,7 @@ static SRes Lzma2EncInt_EncodeSubblock(CLzma2EncInt *p, Byte *outBuf,
231void Lzma2EncProps_Init(CLzma2EncProps *p) 231void Lzma2EncProps_Init(CLzma2EncProps *p)
232{ 232{
233 LzmaEncProps_Init(&p->lzmaProps); 233 LzmaEncProps_Init(&p->lzmaProps);
234 p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO; 234 p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO;
235 p->numBlockThreads_Reduced = -1; 235 p->numBlockThreads_Reduced = -1;
236 p->numBlockThreads_Max = -1; 236 p->numBlockThreads_Max = -1;
237 p->numTotalThreads = -1; 237 p->numTotalThreads = -1;
@@ -251,8 +251,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p)
251 t2 = p->numBlockThreads_Max; 251 t2 = p->numBlockThreads_Max;
252 t3 = p->numTotalThreads; 252 t3 = p->numTotalThreads;
253 253
254 if (t2 > MTCODER__THREADS_MAX) 254 if (t2 > MTCODER_THREADS_MAX)
255 t2 = MTCODER__THREADS_MAX; 255 t2 = MTCODER_THREADS_MAX;
256 256
257 if (t3 <= 0) 257 if (t3 <= 0)
258 { 258 {
@@ -268,8 +268,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p)
268 t1 = 1; 268 t1 = 1;
269 t2 = t3; 269 t2 = t3;
270 } 270 }
271 if (t2 > MTCODER__THREADS_MAX) 271 if (t2 > MTCODER_THREADS_MAX)
272 t2 = MTCODER__THREADS_MAX; 272 t2 = MTCODER_THREADS_MAX;
273 } 273 }
274 else if (t1 <= 0) 274 else if (t1 <= 0)
275 { 275 {
@@ -286,8 +286,8 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p)
286 286
287 fileSize = p->lzmaProps.reduceSize; 287 fileSize = p->lzmaProps.reduceSize;
288 288
289 if ( p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID 289 if ( p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID
290 && p->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 290 && p->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO
291 && (p->blockSize < fileSize || fileSize == (UInt64)(Int64)-1)) 291 && (p->blockSize < fileSize || fileSize == (UInt64)(Int64)-1))
292 p->lzmaProps.reduceSize = p->blockSize; 292 p->lzmaProps.reduceSize = p->blockSize;
293 293
@@ -297,19 +297,19 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p)
297 297
298 t1 = p->lzmaProps.numThreads; 298 t1 = p->lzmaProps.numThreads;
299 299
300 if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) 300 if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID)
301 { 301 {
302 t2r = t2 = 1; 302 t2r = t2 = 1;
303 t3 = t1; 303 t3 = t1;
304 } 304 }
305 else if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO && t2 <= 1) 305 else if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO && t2 <= 1)
306 { 306 {
307 /* if there is no block multi-threading, we use SOLID block */ 307 /* if there is no block multi-threading, we use SOLID block */
308 p->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; 308 p->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID;
309 } 309 }
310 else 310 else
311 { 311 {
312 if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) 312 if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO)
313 { 313 {
314 const UInt32 kMinSize = (UInt32)1 << 20; 314 const UInt32 kMinSize = (UInt32)1 << 20;
315 const UInt32 kMaxSize = (UInt32)1 << 28; 315 const UInt32 kMaxSize = (UInt32)1 << 28;
@@ -344,7 +344,7 @@ void Lzma2EncProps_Normalize(CLzma2EncProps *p)
344} 344}
345 345
346 346
347static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize) 347static SRes Progress(ICompressProgressPtr p, UInt64 inSize, UInt64 outSize)
348{ 348{
349 return (p && ICompressProgress_Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK; 349 return (p && ICompressProgress_Progress(p, inSize, outSize) != SZ_OK) ? SZ_ERROR_PROGRESS : SZ_OK;
350} 350}
@@ -352,7 +352,7 @@ static SRes Progress(ICompressProgress *p, UInt64 inSize, UInt64 outSize)
352 352
353/* ---------- Lzma2 ---------- */ 353/* ---------- Lzma2 ---------- */
354 354
355typedef struct 355struct CLzma2Enc
356{ 356{
357 Byte propEncoded; 357 Byte propEncoded;
358 CLzma2EncProps props; 358 CLzma2EncProps props;
@@ -363,23 +363,22 @@ typedef struct
363 ISzAllocPtr alloc; 363 ISzAllocPtr alloc;
364 ISzAllocPtr allocBig; 364 ISzAllocPtr allocBig;
365 365
366 CLzma2EncInt coders[MTCODER__THREADS_MAX]; 366 CLzma2EncInt coders[MTCODER_THREADS_MAX];
367 367
368 #ifndef _7ZIP_ST 368 #ifndef Z7_ST
369 369
370 ISeqOutStream *outStream; 370 ISeqOutStreamPtr outStream;
371 Byte *outBuf; 371 Byte *outBuf;
372 size_t outBuf_Rem; /* remainder in outBuf */ 372 size_t outBuf_Rem; /* remainder in outBuf */
373 373
374 size_t outBufSize; /* size of allocated outBufs[i] */ 374 size_t outBufSize; /* size of allocated outBufs[i] */
375 size_t outBufsDataSizes[MTCODER__BLOCKS_MAX]; 375 size_t outBufsDataSizes[MTCODER_BLOCKS_MAX];
376 BoolInt mtCoder_WasConstructed; 376 BoolInt mtCoder_WasConstructed;
377 CMtCoder mtCoder; 377 CMtCoder mtCoder;
378 Byte *outBufs[MTCODER__BLOCKS_MAX]; 378 Byte *outBufs[MTCODER_BLOCKS_MAX];
379 379
380 #endif 380 #endif
381 381};
382} CLzma2Enc;
383 382
384 383
385 384
@@ -396,30 +395,30 @@ CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig)
396 p->allocBig = allocBig; 395 p->allocBig = allocBig;
397 { 396 {
398 unsigned i; 397 unsigned i;
399 for (i = 0; i < MTCODER__THREADS_MAX; i++) 398 for (i = 0; i < MTCODER_THREADS_MAX; i++)
400 p->coders[i].enc = NULL; 399 p->coders[i].enc = NULL;
401 } 400 }
402 401
403 #ifndef _7ZIP_ST 402 #ifndef Z7_ST
404 p->mtCoder_WasConstructed = False; 403 p->mtCoder_WasConstructed = False;
405 { 404 {
406 unsigned i; 405 unsigned i;
407 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 406 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
408 p->outBufs[i] = NULL; 407 p->outBufs[i] = NULL;
409 p->outBufSize = 0; 408 p->outBufSize = 0;
410 } 409 }
411 #endif 410 #endif
412 411
413 return p; 412 return (CLzma2EncHandle)p;
414} 413}
415 414
416 415
417#ifndef _7ZIP_ST 416#ifndef Z7_ST
418 417
419static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p) 418static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p)
420{ 419{
421 unsigned i; 420 unsigned i;
422 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 421 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
423 if (p->outBufs[i]) 422 if (p->outBufs[i])
424 { 423 {
425 ISzAlloc_Free(p->alloc, p->outBufs[i]); 424 ISzAlloc_Free(p->alloc, p->outBufs[i]);
@@ -430,12 +429,13 @@ static void Lzma2Enc_FreeOutBufs(CLzma2Enc *p)
430 429
431#endif 430#endif
432 431
432// #define GET_CLzma2Enc_p CLzma2Enc *p = (CLzma2Enc *)(void *)p;
433 433
434void Lzma2Enc_Destroy(CLzma2EncHandle pp) 434void Lzma2Enc_Destroy(CLzma2EncHandle p)
435{ 435{
436 CLzma2Enc *p = (CLzma2Enc *)pp; 436 // GET_CLzma2Enc_p
437 unsigned i; 437 unsigned i;
438 for (i = 0; i < MTCODER__THREADS_MAX; i++) 438 for (i = 0; i < MTCODER_THREADS_MAX; i++)
439 { 439 {
440 CLzma2EncInt *t = &p->coders[i]; 440 CLzma2EncInt *t = &p->coders[i];
441 if (t->enc) 441 if (t->enc)
@@ -446,7 +446,7 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp)
446 } 446 }
447 447
448 448
449 #ifndef _7ZIP_ST 449 #ifndef Z7_ST
450 if (p->mtCoder_WasConstructed) 450 if (p->mtCoder_WasConstructed)
451 { 451 {
452 MtCoder_Destruct(&p->mtCoder); 452 MtCoder_Destruct(&p->mtCoder);
@@ -458,13 +458,13 @@ void Lzma2Enc_Destroy(CLzma2EncHandle pp)
458 ISzAlloc_Free(p->alloc, p->tempBufLzma); 458 ISzAlloc_Free(p->alloc, p->tempBufLzma);
459 p->tempBufLzma = NULL; 459 p->tempBufLzma = NULL;
460 460
461 ISzAlloc_Free(p->alloc, pp); 461 ISzAlloc_Free(p->alloc, p);
462} 462}
463 463
464 464
465SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props) 465SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props)
466{ 466{
467 CLzma2Enc *p = (CLzma2Enc *)pp; 467 // GET_CLzma2Enc_p
468 CLzmaEncProps lzmaProps = props->lzmaProps; 468 CLzmaEncProps lzmaProps = props->lzmaProps;
469 LzmaEncProps_Normalize(&lzmaProps); 469 LzmaEncProps_Normalize(&lzmaProps);
470 if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX) 470 if (lzmaProps.lc + lzmaProps.lp > LZMA2_LCLP_MAX)
@@ -475,16 +475,16 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle pp, const CLzma2EncProps *props)
475} 475}
476 476
477 477
478void Lzma2Enc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) 478void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize)
479{ 479{
480 CLzma2Enc *p = (CLzma2Enc *)pp; 480 // GET_CLzma2Enc_p
481 p->expectedDataSize = expectedDataSiize; 481 p->expectedDataSize = expectedDataSiize;
482} 482}
483 483
484 484
485Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp) 485Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p)
486{ 486{
487 CLzma2Enc *p = (CLzma2Enc *)pp; 487 // GET_CLzma2Enc_p
488 unsigned i; 488 unsigned i;
489 UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps); 489 UInt32 dicSize = LzmaEncProps_GetDictSize(&p->props.lzmaProps);
490 for (i = 0; i < 40; i++) 490 for (i = 0; i < 40; i++)
@@ -497,12 +497,12 @@ Byte Lzma2Enc_WriteProperties(CLzma2EncHandle pp)
497static SRes Lzma2Enc_EncodeMt1( 497static SRes Lzma2Enc_EncodeMt1(
498 CLzma2Enc *me, 498 CLzma2Enc *me,
499 CLzma2EncInt *p, 499 CLzma2EncInt *p,
500 ISeqOutStream *outStream, 500 ISeqOutStreamPtr outStream,
501 Byte *outBuf, size_t *outBufSize, 501 Byte *outBuf, size_t *outBufSize,
502 ISeqInStream *inStream, 502 ISeqInStreamPtr inStream,
503 const Byte *inData, size_t inDataSize, 503 const Byte *inData, size_t inDataSize,
504 int finished, 504 int finished,
505 ICompressProgress *progress) 505 ICompressProgressPtr progress)
506{ 506{
507 UInt64 unpackTotal = 0; 507 UInt64 unpackTotal = 0;
508 UInt64 packTotal = 0; 508 UInt64 packTotal = 0;
@@ -540,12 +540,12 @@ static SRes Lzma2Enc_EncodeMt1(
540 } 540 }
541 } 541 }
542 542
543 RINOK(Lzma2EncInt_InitStream(p, &me->props)); 543 RINOK(Lzma2EncInt_InitStream(p, &me->props))
544 544
545 for (;;) 545 for (;;)
546 { 546 {
547 SRes res = SZ_OK; 547 SRes res = SZ_OK;
548 size_t inSizeCur = 0; 548 SizeT inSizeCur = 0;
549 549
550 Lzma2EncInt_InitBlock(p); 550 Lzma2EncInt_InitBlock(p);
551 551
@@ -559,7 +559,7 @@ static SRes Lzma2Enc_EncodeMt1(
559 if (me->expectedDataSize != (UInt64)(Int64)-1 559 if (me->expectedDataSize != (UInt64)(Int64)-1
560 && me->expectedDataSize >= unpackTotal) 560 && me->expectedDataSize >= unpackTotal)
561 expected = me->expectedDataSize - unpackTotal; 561 expected = me->expectedDataSize - unpackTotal;
562 if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID 562 if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID
563 && expected > me->props.blockSize) 563 && expected > me->props.blockSize)
564 expected = (size_t)me->props.blockSize; 564 expected = (size_t)me->props.blockSize;
565 565
@@ -569,14 +569,14 @@ static SRes Lzma2Enc_EncodeMt1(
569 &limitedInStream.vt, 569 &limitedInStream.vt,
570 LZMA2_KEEP_WINDOW_SIZE, 570 LZMA2_KEEP_WINDOW_SIZE,
571 me->alloc, 571 me->alloc,
572 me->allocBig)); 572 me->allocBig))
573 } 573 }
574 else 574 else
575 { 575 {
576 inSizeCur = inDataSize - (size_t)unpackTotal; 576 inSizeCur = (SizeT)(inDataSize - (size_t)unpackTotal);
577 if (me->props.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID 577 if (me->props.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID
578 && inSizeCur > me->props.blockSize) 578 && inSizeCur > me->props.blockSize)
579 inSizeCur = (size_t)me->props.blockSize; 579 inSizeCur = (SizeT)(size_t)me->props.blockSize;
580 580
581 // LzmaEnc_SetDataSize(p->enc, inSizeCur); 581 // LzmaEnc_SetDataSize(p->enc, inSizeCur);
582 582
@@ -584,7 +584,7 @@ static SRes Lzma2Enc_EncodeMt1(
584 inData + (size_t)unpackTotal, inSizeCur, 584 inData + (size_t)unpackTotal, inSizeCur,
585 LZMA2_KEEP_WINDOW_SIZE, 585 LZMA2_KEEP_WINDOW_SIZE,
586 me->alloc, 586 me->alloc,
587 me->allocBig)); 587 me->allocBig))
588 } 588 }
589 589
590 for (;;) 590 for (;;)
@@ -621,7 +621,7 @@ static SRes Lzma2Enc_EncodeMt1(
621 621
622 unpackTotal += p->srcPos; 622 unpackTotal += p->srcPos;
623 623
624 RINOK(res); 624 RINOK(res)
625 625
626 if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur)) 626 if (p->srcPos != (inStream ? limitedInStream.processed : inSizeCur))
627 return SZ_ERROR_FAIL; 627 return SZ_ERROR_FAIL;
@@ -652,12 +652,12 @@ static SRes Lzma2Enc_EncodeMt1(
652 652
653 653
654 654
655#ifndef _7ZIP_ST 655#ifndef Z7_ST
656 656
657static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, 657static SRes Lzma2Enc_MtCallback_Code(void *p, unsigned coderIndex, unsigned outBufIndex,
658 const Byte *src, size_t srcSize, int finished) 658 const Byte *src, size_t srcSize, int finished)
659{ 659{
660 CLzma2Enc *me = (CLzma2Enc *)pp; 660 CLzma2Enc *me = (CLzma2Enc *)p;
661 size_t destSize = me->outBufSize; 661 size_t destSize = me->outBufSize;
662 SRes res; 662 SRes res;
663 CMtProgressThunk progressThunk; 663 CMtProgressThunk progressThunk;
@@ -692,9 +692,9 @@ static SRes Lzma2Enc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned out
692} 692}
693 693
694 694
695static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex) 695static SRes Lzma2Enc_MtCallback_Write(void *p, unsigned outBufIndex)
696{ 696{
697 CLzma2Enc *me = (CLzma2Enc *)pp; 697 CLzma2Enc *me = (CLzma2Enc *)p;
698 size_t size = me->outBufsDataSizes[outBufIndex]; 698 size_t size = me->outBufsDataSizes[outBufIndex];
699 const Byte *data = me->outBufs[outBufIndex]; 699 const Byte *data = me->outBufs[outBufIndex];
700 700
@@ -713,14 +713,14 @@ static SRes Lzma2Enc_MtCallback_Write(void *pp, unsigned outBufIndex)
713 713
714 714
715 715
716SRes Lzma2Enc_Encode2(CLzma2EncHandle pp, 716SRes Lzma2Enc_Encode2(CLzma2EncHandle p,
717 ISeqOutStream *outStream, 717 ISeqOutStreamPtr outStream,
718 Byte *outBuf, size_t *outBufSize, 718 Byte *outBuf, size_t *outBufSize,
719 ISeqInStream *inStream, 719 ISeqInStreamPtr inStream,
720 const Byte *inData, size_t inDataSize, 720 const Byte *inData, size_t inDataSize,
721 ICompressProgress *progress) 721 ICompressProgressPtr progress)
722{ 722{
723 CLzma2Enc *p = (CLzma2Enc *)pp; 723 // GET_CLzma2Enc_p
724 724
725 if (inStream && inData) 725 if (inStream && inData)
726 return SZ_ERROR_PARAM; 726 return SZ_ERROR_PARAM;
@@ -730,11 +730,11 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp,
730 730
731 { 731 {
732 unsigned i; 732 unsigned i;
733 for (i = 0; i < MTCODER__THREADS_MAX; i++) 733 for (i = 0; i < MTCODER_THREADS_MAX; i++)
734 p->coders[i].propsAreSet = False; 734 p->coders[i].propsAreSet = False;
735 } 735 }
736 736
737 #ifndef _7ZIP_ST 737 #ifndef Z7_ST
738 738
739 if (p->props.numBlockThreads_Reduced > 1) 739 if (p->props.numBlockThreads_Reduced > 1)
740 { 740 {
@@ -772,7 +772,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp,
772 return SZ_ERROR_PARAM; /* SZ_ERROR_MEM */ 772 return SZ_ERROR_PARAM; /* SZ_ERROR_MEM */
773 773
774 { 774 {
775 size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16; 775 const size_t destBlockSize = p->mtCoder.blockSize + (p->mtCoder.blockSize >> 10) + 16;
776 if (destBlockSize < p->mtCoder.blockSize) 776 if (destBlockSize < p->mtCoder.blockSize)
777 return SZ_ERROR_PARAM; 777 return SZ_ERROR_PARAM;
778 if (p->outBufSize != destBlockSize) 778 if (p->outBufSize != destBlockSize)
@@ -784,7 +784,7 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp,
784 p->mtCoder.expectedDataSize = p->expectedDataSize; 784 p->mtCoder.expectedDataSize = p->expectedDataSize;
785 785
786 { 786 {
787 SRes res = MtCoder_Code(&p->mtCoder); 787 const SRes res = MtCoder_Code(&p->mtCoder);
788 if (!outStream) 788 if (!outStream)
789 *outBufSize = (size_t)(p->outBuf - outBuf); 789 *outBufSize = (size_t)(p->outBuf - outBuf);
790 return res; 790 return res;
@@ -801,3 +801,5 @@ SRes Lzma2Enc_Encode2(CLzma2EncHandle pp,
801 True, /* finished */ 801 True, /* finished */
802 progress); 802 progress);
803} 803}
804
805#undef PRF
diff --git a/C/Lzma2Enc.h b/C/Lzma2Enc.h
index 6a6110f..cb25275 100644
--- a/C/Lzma2Enc.h
+++ b/C/Lzma2Enc.h
@@ -1,15 +1,15 @@
1/* Lzma2Enc.h -- LZMA2 Encoder 1/* Lzma2Enc.h -- LZMA2 Encoder
22017-07-27 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA2_ENC_H 4#ifndef ZIP7_INC_LZMA2_ENC_H
5#define __LZMA2_ENC_H 5#define ZIP7_INC_LZMA2_ENC_H
6 6
7#include "LzmaEnc.h" 7#include "LzmaEnc.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11#define LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 0 11#define LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO 0
12#define LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID ((UInt64)(Int64)-1) 12#define LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID ((UInt64)(Int64)-1)
13 13
14typedef struct 14typedef struct
15{ 15{
@@ -36,7 +36,9 @@ SRes:
36 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) 36 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version)
37*/ 37*/
38 38
39typedef void * CLzma2EncHandle; 39typedef struct CLzma2Enc CLzma2Enc;
40typedef CLzma2Enc * CLzma2EncHandle;
41// Z7_DECLARE_HANDLE(CLzma2EncHandle)
40 42
41CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); 43CLzma2EncHandle Lzma2Enc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig);
42void Lzma2Enc_Destroy(CLzma2EncHandle p); 44void Lzma2Enc_Destroy(CLzma2EncHandle p);
@@ -44,11 +46,11 @@ SRes Lzma2Enc_SetProps(CLzma2EncHandle p, const CLzma2EncProps *props);
44void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize); 46void Lzma2Enc_SetDataSize(CLzma2EncHandle p, UInt64 expectedDataSiize);
45Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p); 47Byte Lzma2Enc_WriteProperties(CLzma2EncHandle p);
46SRes Lzma2Enc_Encode2(CLzma2EncHandle p, 48SRes Lzma2Enc_Encode2(CLzma2EncHandle p,
47 ISeqOutStream *outStream, 49 ISeqOutStreamPtr outStream,
48 Byte *outBuf, size_t *outBufSize, 50 Byte *outBuf, size_t *outBufSize,
49 ISeqInStream *inStream, 51 ISeqInStreamPtr inStream,
50 const Byte *inData, size_t inDataSize, 52 const Byte *inData, size_t inDataSize,
51 ICompressProgress *progress); 53 ICompressProgressPtr progress);
52 54
53EXTERN_C_END 55EXTERN_C_END
54 56
diff --git a/C/Lzma86.h b/C/Lzma86.h
index bebed5c..e7707e2 100644
--- a/C/Lzma86.h
+++ b/C/Lzma86.h
@@ -1,8 +1,8 @@
1/* Lzma86.h -- LZMA + x86 (BCJ) Filter 1/* Lzma86.h -- LZMA + x86 (BCJ) Filter
22013-01-18 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA86_H 4#ifndef ZIP7_INC_LZMA86_H
5#define __LZMA86_H 5#define ZIP7_INC_LZMA86_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/Lzma86Dec.c b/C/Lzma86Dec.c
index 2103174..f094d4c 100644
--- a/C/Lzma86Dec.c
+++ b/C/Lzma86Dec.c
@@ -1,5 +1,5 @@
1/* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder 1/* Lzma86Dec.c -- LZMA + x86 (BCJ) Filter Decoder
22016-05-16 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -46,9 +46,8 @@ SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen)
46 return res; 46 return res;
47 if (useFilter == 1) 47 if (useFilter == 1)
48 { 48 {
49 UInt32 x86State; 49 UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL;
50 x86_Convert_Init(x86State); 50 z7_BranchConvSt_X86_Dec(dest, *destLen, 0, &x86State);
51 x86_Convert(dest, *destLen, 0, &x86State, 0);
52 } 51 }
53 return SZ_OK; 52 return SZ_OK;
54} 53}
diff --git a/C/Lzma86Enc.c b/C/Lzma86Enc.c
index 14fcd65..0cdde1c 100644
--- a/C/Lzma86Enc.c
+++ b/C/Lzma86Enc.c
@@ -1,5 +1,5 @@
1/* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder 1/* Lzma86Enc.c -- LZMA + x86 (BCJ) Filter Encoder
22018-07-04 : Igor Pavlov : Public domain */ 22023-03-03 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -46,9 +46,8 @@ int Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen,
46 memcpy(filteredStream, src, srcLen); 46 memcpy(filteredStream, src, srcLen);
47 } 47 }
48 { 48 {
49 UInt32 x86State; 49 UInt32 x86State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL;
50 x86_Convert_Init(x86State); 50 z7_BranchConvSt_X86_Enc(filteredStream, srcLen, 0, &x86State);
51 x86_Convert(filteredStream, srcLen, 0, &x86State, 1);
52 } 51 }
53 } 52 }
54 53
diff --git a/C/LzmaDec.c b/C/LzmaDec.c
index d6742e5..69bb8bb 100644
--- a/C/LzmaDec.c
+++ b/C/LzmaDec.c
@@ -1,5 +1,5 @@
1/* LzmaDec.c -- LZMA Decoder 1/* LzmaDec.c -- LZMA Decoder
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-07 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -8,15 +8,15 @@
8/* #include "CpuArch.h" */ 8/* #include "CpuArch.h" */
9#include "LzmaDec.h" 9#include "LzmaDec.h"
10 10
11#define kNumTopBits 24 11// #define kNumTopBits 24
12#define kTopValue ((UInt32)1 << kNumTopBits) 12#define kTopValue ((UInt32)1 << 24)
13 13
14#define kNumBitModelTotalBits 11 14#define kNumBitModelTotalBits 11
15#define kBitModelTotal (1 << kNumBitModelTotalBits) 15#define kBitModelTotal (1 << kNumBitModelTotalBits)
16 16
17#define RC_INIT_SIZE 5 17#define RC_INIT_SIZE 5
18 18
19#ifndef _LZMA_DEC_OPT 19#ifndef Z7_LZMA_DEC_OPT
20 20
21#define kNumMoveBits 5 21#define kNumMoveBits 5
22#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } 22#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); }
@@ -25,14 +25,14 @@
25#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); 25#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
26#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); 26#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits));
27#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ 27#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \
28 { UPDATE_0(p); i = (i + i); A0; } else \ 28 { UPDATE_0(p) i = (i + i); A0; } else \
29 { UPDATE_1(p); i = (i + i) + 1; A1; } 29 { UPDATE_1(p) i = (i + i) + 1; A1; }
30 30
31#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } 31#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); }
32 32
33#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ 33#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \
34 { UPDATE_0(p + i); A0; } else \ 34 { UPDATE_0(p + i) A0; } else \
35 { UPDATE_1(p + i); A1; } 35 { UPDATE_1(p + i) A1; }
36#define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) 36#define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; )
37#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) 37#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; )
38#define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) 38#define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; )
@@ -40,19 +40,19 @@
40#define TREE_DECODE(probs, limit, i) \ 40#define TREE_DECODE(probs, limit, i) \
41 { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } 41 { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; }
42 42
43/* #define _LZMA_SIZE_OPT */ 43/* #define Z7_LZMA_SIZE_OPT */
44 44
45#ifdef _LZMA_SIZE_OPT 45#ifdef Z7_LZMA_SIZE_OPT
46#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) 46#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i)
47#else 47#else
48#define TREE_6_DECODE(probs, i) \ 48#define TREE_6_DECODE(probs, i) \
49 { i = 1; \ 49 { i = 1; \
50 TREE_GET_BIT(probs, i); \ 50 TREE_GET_BIT(probs, i) \
51 TREE_GET_BIT(probs, i); \ 51 TREE_GET_BIT(probs, i) \
52 TREE_GET_BIT(probs, i); \ 52 TREE_GET_BIT(probs, i) \
53 TREE_GET_BIT(probs, i); \ 53 TREE_GET_BIT(probs, i) \
54 TREE_GET_BIT(probs, i); \ 54 TREE_GET_BIT(probs, i) \
55 TREE_GET_BIT(probs, i); \ 55 TREE_GET_BIT(probs, i) \
56 i -= 0x40; } 56 i -= 0x40; }
57#endif 57#endif
58 58
@@ -64,25 +64,25 @@
64 probLit = prob + (offs + bit + symbol); \ 64 probLit = prob + (offs + bit + symbol); \
65 GET_BIT2(probLit, symbol, offs ^= bit; , ;) 65 GET_BIT2(probLit, symbol, offs ^= bit; , ;)
66 66
67#endif // _LZMA_DEC_OPT 67#endif // Z7_LZMA_DEC_OPT
68 68
69 69
70#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); } 70#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_INPUT_EOF; range <<= 8; code = (code << 8) | (*buf++); }
71 71
72#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) 72#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound)
73#define UPDATE_0_CHECK range = bound; 73#define UPDATE_0_CHECK range = bound;
74#define UPDATE_1_CHECK range -= bound; code -= bound; 74#define UPDATE_1_CHECK range -= bound; code -= bound;
75#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ 75#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \
76 { UPDATE_0_CHECK; i = (i + i); A0; } else \ 76 { UPDATE_0_CHECK i = (i + i); A0; } else \
77 { UPDATE_1_CHECK; i = (i + i) + 1; A1; } 77 { UPDATE_1_CHECK i = (i + i) + 1; A1; }
78#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) 78#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;)
79#define TREE_DECODE_CHECK(probs, limit, i) \ 79#define TREE_DECODE_CHECK(probs, limit, i) \
80 { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } 80 { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; }
81 81
82 82
83#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ 83#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \
84 { UPDATE_0_CHECK; i += m; m += m; } else \ 84 { UPDATE_0_CHECK i += m; m += m; } else \
85 { UPDATE_1_CHECK; m += m; i += m; } 85 { UPDATE_1_CHECK m += m; i += m; }
86 86
87 87
88#define kNumPosBitsMax 4 88#define kNumPosBitsMax 4
@@ -224,14 +224,14 @@ Out:
224*/ 224*/
225 225
226 226
227#ifdef _LZMA_DEC_OPT 227#ifdef Z7_LZMA_DEC_OPT
228 228
229int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); 229int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit);
230 230
231#else 231#else
232 232
233static 233static
234int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) 234int Z7_FASTCALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
235{ 235{
236 CLzmaProb *probs = GET_PROBS; 236 CLzmaProb *probs = GET_PROBS;
237 unsigned state = (unsigned)p->state; 237 unsigned state = (unsigned)p->state;
@@ -263,7 +263,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
263 IF_BIT_0(prob) 263 IF_BIT_0(prob)
264 { 264 {
265 unsigned symbol; 265 unsigned symbol;
266 UPDATE_0(prob); 266 UPDATE_0(prob)
267 prob = probs + Literal; 267 prob = probs + Literal;
268 if (processedPos != 0 || checkDicSize != 0) 268 if (processedPos != 0 || checkDicSize != 0)
269 prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); 269 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
273 { 273 {
274 state -= (state < 4) ? state : 3; 274 state -= (state < 4) ? state : 3;
275 symbol = 1; 275 symbol = 1;
276 #ifdef _LZMA_SIZE_OPT 276 #ifdef Z7_LZMA_SIZE_OPT
277 do { NORMAL_LITER_DEC } while (symbol < 0x100); 277 do { NORMAL_LITER_DEC } while (symbol < 0x100);
278 #else 278 #else
279 NORMAL_LITER_DEC 279 NORMAL_LITER_DEC
@@ -292,7 +292,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
292 unsigned offs = 0x100; 292 unsigned offs = 0x100;
293 state -= (state < 10) ? 3 : 6; 293 state -= (state < 10) ? 3 : 6;
294 symbol = 1; 294 symbol = 1;
295 #ifdef _LZMA_SIZE_OPT 295 #ifdef Z7_LZMA_SIZE_OPT
296 do 296 do
297 { 297 {
298 unsigned bit; 298 unsigned bit;
@@ -321,25 +321,25 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
321 } 321 }
322 322
323 { 323 {
324 UPDATE_1(prob); 324 UPDATE_1(prob)
325 prob = probs + IsRep + state; 325 prob = probs + IsRep + state;
326 IF_BIT_0(prob) 326 IF_BIT_0(prob)
327 { 327 {
328 UPDATE_0(prob); 328 UPDATE_0(prob)
329 state += kNumStates; 329 state += kNumStates;
330 prob = probs + LenCoder; 330 prob = probs + LenCoder;
331 } 331 }
332 else 332 else
333 { 333 {
334 UPDATE_1(prob); 334 UPDATE_1(prob)
335 prob = probs + IsRepG0 + state; 335 prob = probs + IsRepG0 + state;
336 IF_BIT_0(prob) 336 IF_BIT_0(prob)
337 { 337 {
338 UPDATE_0(prob); 338 UPDATE_0(prob)
339 prob = probs + IsRep0Long + COMBINED_PS_STATE; 339 prob = probs + IsRep0Long + COMBINED_PS_STATE;
340 IF_BIT_0(prob) 340 IF_BIT_0(prob)
341 { 341 {
342 UPDATE_0(prob); 342 UPDATE_0(prob)
343 343
344 // that case was checked before with kBadRepCode 344 // that case was checked before with kBadRepCode
345 // if (checkDicSize == 0 && processedPos == 0) { len = kMatchSpecLen_Error_Data + 1; break; } 345 // 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
353 state = state < kNumLitStates ? 9 : 11; 353 state = state < kNumLitStates ? 9 : 11;
354 continue; 354 continue;
355 } 355 }
356 UPDATE_1(prob); 356 UPDATE_1(prob)
357 } 357 }
358 else 358 else
359 { 359 {
360 UInt32 distance; 360 UInt32 distance;
361 UPDATE_1(prob); 361 UPDATE_1(prob)
362 prob = probs + IsRepG1 + state; 362 prob = probs + IsRepG1 + state;
363 IF_BIT_0(prob) 363 IF_BIT_0(prob)
364 { 364 {
365 UPDATE_0(prob); 365 UPDATE_0(prob)
366 distance = rep1; 366 distance = rep1;
367 } 367 }
368 else 368 else
369 { 369 {
370 UPDATE_1(prob); 370 UPDATE_1(prob)
371 prob = probs + IsRepG2 + state; 371 prob = probs + IsRepG2 + state;
372 IF_BIT_0(prob) 372 IF_BIT_0(prob)
373 { 373 {
374 UPDATE_0(prob); 374 UPDATE_0(prob)
375 distance = rep2; 375 distance = rep2;
376 } 376 }
377 else 377 else
378 { 378 {
379 UPDATE_1(prob); 379 UPDATE_1(prob)
380 distance = rep3; 380 distance = rep3;
381 rep3 = rep2; 381 rep3 = rep2;
382 } 382 }
@@ -389,37 +389,37 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
389 prob = probs + RepLenCoder; 389 prob = probs + RepLenCoder;
390 } 390 }
391 391
392 #ifdef _LZMA_SIZE_OPT 392 #ifdef Z7_LZMA_SIZE_OPT
393 { 393 {
394 unsigned lim, offset; 394 unsigned lim, offset;
395 CLzmaProb *probLen = prob + LenChoice; 395 CLzmaProb *probLen = prob + LenChoice;
396 IF_BIT_0(probLen) 396 IF_BIT_0(probLen)
397 { 397 {
398 UPDATE_0(probLen); 398 UPDATE_0(probLen)
399 probLen = prob + LenLow + GET_LEN_STATE; 399 probLen = prob + LenLow + GET_LEN_STATE;
400 offset = 0; 400 offset = 0;
401 lim = (1 << kLenNumLowBits); 401 lim = (1 << kLenNumLowBits);
402 } 402 }
403 else 403 else
404 { 404 {
405 UPDATE_1(probLen); 405 UPDATE_1(probLen)
406 probLen = prob + LenChoice2; 406 probLen = prob + LenChoice2;
407 IF_BIT_0(probLen) 407 IF_BIT_0(probLen)
408 { 408 {
409 UPDATE_0(probLen); 409 UPDATE_0(probLen)
410 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); 410 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
411 offset = kLenNumLowSymbols; 411 offset = kLenNumLowSymbols;
412 lim = (1 << kLenNumLowBits); 412 lim = (1 << kLenNumLowBits);
413 } 413 }
414 else 414 else
415 { 415 {
416 UPDATE_1(probLen); 416 UPDATE_1(probLen)
417 probLen = prob + LenHigh; 417 probLen = prob + LenHigh;
418 offset = kLenNumLowSymbols * 2; 418 offset = kLenNumLowSymbols * 2;
419 lim = (1 << kLenNumHighBits); 419 lim = (1 << kLenNumHighBits);
420 } 420 }
421 } 421 }
422 TREE_DECODE(probLen, lim, len); 422 TREE_DECODE(probLen, lim, len)
423 len += offset; 423 len += offset;
424 } 424 }
425 #else 425 #else
@@ -427,32 +427,32 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
427 CLzmaProb *probLen = prob + LenChoice; 427 CLzmaProb *probLen = prob + LenChoice;
428 IF_BIT_0(probLen) 428 IF_BIT_0(probLen)
429 { 429 {
430 UPDATE_0(probLen); 430 UPDATE_0(probLen)
431 probLen = prob + LenLow + GET_LEN_STATE; 431 probLen = prob + LenLow + GET_LEN_STATE;
432 len = 1; 432 len = 1;
433 TREE_GET_BIT(probLen, len); 433 TREE_GET_BIT(probLen, len)
434 TREE_GET_BIT(probLen, len); 434 TREE_GET_BIT(probLen, len)
435 TREE_GET_BIT(probLen, len); 435 TREE_GET_BIT(probLen, len)
436 len -= 8; 436 len -= 8;
437 } 437 }
438 else 438 else
439 { 439 {
440 UPDATE_1(probLen); 440 UPDATE_1(probLen)
441 probLen = prob + LenChoice2; 441 probLen = prob + LenChoice2;
442 IF_BIT_0(probLen) 442 IF_BIT_0(probLen)
443 { 443 {
444 UPDATE_0(probLen); 444 UPDATE_0(probLen)
445 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); 445 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
446 len = 1; 446 len = 1;
447 TREE_GET_BIT(probLen, len); 447 TREE_GET_BIT(probLen, len)
448 TREE_GET_BIT(probLen, len); 448 TREE_GET_BIT(probLen, len)
449 TREE_GET_BIT(probLen, len); 449 TREE_GET_BIT(probLen, len)
450 } 450 }
451 else 451 else
452 { 452 {
453 UPDATE_1(probLen); 453 UPDATE_1(probLen)
454 probLen = prob + LenHigh; 454 probLen = prob + LenHigh;
455 TREE_DECODE(probLen, (1 << kLenNumHighBits), len); 455 TREE_DECODE(probLen, (1 << kLenNumHighBits), len)
456 len += kLenNumLowSymbols * 2; 456 len += kLenNumLowSymbols * 2;
457 } 457 }
458 } 458 }
@@ -464,7 +464,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
464 UInt32 distance; 464 UInt32 distance;
465 prob = probs + PosSlot + 465 prob = probs + PosSlot +
466 ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); 466 ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits);
467 TREE_6_DECODE(prob, distance); 467 TREE_6_DECODE(prob, distance)
468 if (distance >= kStartPosModelIndex) 468 if (distance >= kStartPosModelIndex)
469 { 469 {
470 unsigned posSlot = (unsigned)distance; 470 unsigned posSlot = (unsigned)distance;
@@ -479,7 +479,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
479 distance++; 479 distance++;
480 do 480 do
481 { 481 {
482 REV_BIT_VAR(prob, distance, m); 482 REV_BIT_VAR(prob, distance, m)
483 } 483 }
484 while (--numDirectBits); 484 while (--numDirectBits);
485 distance -= m; 485 distance -= m;
@@ -514,10 +514,10 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
514 distance <<= kNumAlignBits; 514 distance <<= kNumAlignBits;
515 { 515 {
516 unsigned i = 1; 516 unsigned i = 1;
517 REV_BIT_CONST(prob, i, 1); 517 REV_BIT_CONST(prob, i, 1)
518 REV_BIT_CONST(prob, i, 2); 518 REV_BIT_CONST(prob, i, 2)
519 REV_BIT_CONST(prob, i, 4); 519 REV_BIT_CONST(prob, i, 4)
520 REV_BIT_LAST (prob, i, 8); 520 REV_BIT_LAST (prob, i, 8)
521 distance |= i; 521 distance |= i;
522 } 522 }
523 if (distance == (UInt32)0xFFFFFFFF) 523 if (distance == (UInt32)0xFFFFFFFF)
@@ -592,7 +592,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
592 } 592 }
593 while (dicPos < limit && buf < bufLimit); 593 while (dicPos < limit && buf < bufLimit);
594 594
595 NORMALIZE; 595 NORMALIZE
596 596
597 p->buf = buf; 597 p->buf = buf;
598 p->range = range; 598 p->range = range;
@@ -613,7 +613,7 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit
613 613
614 614
615 615
616static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) 616static void Z7_FASTCALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit)
617{ 617{
618 unsigned len = (unsigned)p->remainLen; 618 unsigned len = (unsigned)p->remainLen;
619 if (len == 0 /* || len >= kMatchSpecLenStart */) 619 if (len == 0 /* || len >= kMatchSpecLenStart */)
@@ -683,7 +683,7 @@ and we support the following state of (p->checkDicSize):
683 (p->checkDicSize == p->prop.dicSize) 683 (p->checkDicSize == p->prop.dicSize)
684*/ 684*/
685 685
686static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) 686static int Z7_FASTCALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit)
687{ 687{
688 if (p->checkDicSize == 0) 688 if (p->checkDicSize == 0)
689 { 689 {
@@ -767,54 +767,54 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt
767 else 767 else
768 { 768 {
769 unsigned len; 769 unsigned len;
770 UPDATE_1_CHECK; 770 UPDATE_1_CHECK
771 771
772 prob = probs + IsRep + state; 772 prob = probs + IsRep + state;
773 IF_BIT_0_CHECK(prob) 773 IF_BIT_0_CHECK(prob)
774 { 774 {
775 UPDATE_0_CHECK; 775 UPDATE_0_CHECK
776 state = 0; 776 state = 0;
777 prob = probs + LenCoder; 777 prob = probs + LenCoder;
778 res = DUMMY_MATCH; 778 res = DUMMY_MATCH;
779 } 779 }
780 else 780 else
781 { 781 {
782 UPDATE_1_CHECK; 782 UPDATE_1_CHECK
783 res = DUMMY_REP; 783 res = DUMMY_REP;
784 prob = probs + IsRepG0 + state; 784 prob = probs + IsRepG0 + state;
785 IF_BIT_0_CHECK(prob) 785 IF_BIT_0_CHECK(prob)
786 { 786 {
787 UPDATE_0_CHECK; 787 UPDATE_0_CHECK
788 prob = probs + IsRep0Long + COMBINED_PS_STATE; 788 prob = probs + IsRep0Long + COMBINED_PS_STATE;
789 IF_BIT_0_CHECK(prob) 789 IF_BIT_0_CHECK(prob)
790 { 790 {
791 UPDATE_0_CHECK; 791 UPDATE_0_CHECK
792 break; 792 break;
793 } 793 }
794 else 794 else
795 { 795 {
796 UPDATE_1_CHECK; 796 UPDATE_1_CHECK
797 } 797 }
798 } 798 }
799 else 799 else
800 { 800 {
801 UPDATE_1_CHECK; 801 UPDATE_1_CHECK
802 prob = probs + IsRepG1 + state; 802 prob = probs + IsRepG1 + state;
803 IF_BIT_0_CHECK(prob) 803 IF_BIT_0_CHECK(prob)
804 { 804 {
805 UPDATE_0_CHECK; 805 UPDATE_0_CHECK
806 } 806 }
807 else 807 else
808 { 808 {
809 UPDATE_1_CHECK; 809 UPDATE_1_CHECK
810 prob = probs + IsRepG2 + state; 810 prob = probs + IsRepG2 + state;
811 IF_BIT_0_CHECK(prob) 811 IF_BIT_0_CHECK(prob)
812 { 812 {
813 UPDATE_0_CHECK; 813 UPDATE_0_CHECK
814 } 814 }
815 else 815 else
816 { 816 {
817 UPDATE_1_CHECK; 817 UPDATE_1_CHECK
818 } 818 }
819 } 819 }
820 } 820 }
@@ -826,31 +826,31 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt
826 const CLzmaProb *probLen = prob + LenChoice; 826 const CLzmaProb *probLen = prob + LenChoice;
827 IF_BIT_0_CHECK(probLen) 827 IF_BIT_0_CHECK(probLen)
828 { 828 {
829 UPDATE_0_CHECK; 829 UPDATE_0_CHECK
830 probLen = prob + LenLow + GET_LEN_STATE; 830 probLen = prob + LenLow + GET_LEN_STATE;
831 offset = 0; 831 offset = 0;
832 limit = 1 << kLenNumLowBits; 832 limit = 1 << kLenNumLowBits;
833 } 833 }
834 else 834 else
835 { 835 {
836 UPDATE_1_CHECK; 836 UPDATE_1_CHECK
837 probLen = prob + LenChoice2; 837 probLen = prob + LenChoice2;
838 IF_BIT_0_CHECK(probLen) 838 IF_BIT_0_CHECK(probLen)
839 { 839 {
840 UPDATE_0_CHECK; 840 UPDATE_0_CHECK
841 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); 841 probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits);
842 offset = kLenNumLowSymbols; 842 offset = kLenNumLowSymbols;
843 limit = 1 << kLenNumLowBits; 843 limit = 1 << kLenNumLowBits;
844 } 844 }
845 else 845 else
846 { 846 {
847 UPDATE_1_CHECK; 847 UPDATE_1_CHECK
848 probLen = prob + LenHigh; 848 probLen = prob + LenHigh;
849 offset = kLenNumLowSymbols * 2; 849 offset = kLenNumLowSymbols * 2;
850 limit = 1 << kLenNumHighBits; 850 limit = 1 << kLenNumHighBits;
851 } 851 }
852 } 852 }
853 TREE_DECODE_CHECK(probLen, limit, len); 853 TREE_DECODE_CHECK(probLen, limit, len)
854 len += offset; 854 len += offset;
855 } 855 }
856 856
@@ -860,7 +860,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt
860 prob = probs + PosSlot + 860 prob = probs + PosSlot +
861 ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << 861 ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) <<
862 kNumPosSlotBits); 862 kNumPosSlotBits);
863 TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); 863 TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot)
864 if (posSlot >= kStartPosModelIndex) 864 if (posSlot >= kStartPosModelIndex)
865 { 865 {
866 unsigned numDirectBits = ((posSlot >> 1) - 1); 866 unsigned numDirectBits = ((posSlot >> 1) - 1);
@@ -888,7 +888,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt
888 unsigned m = 1; 888 unsigned m = 1;
889 do 889 do
890 { 890 {
891 REV_BIT_CHECK(prob, i, m); 891 REV_BIT_CHECK(prob, i, m)
892 } 892 }
893 while (--numDirectBits); 893 while (--numDirectBits);
894 } 894 }
@@ -897,7 +897,7 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, const Byt
897 } 897 }
898 break; 898 break;
899 } 899 }
900 NORMALIZE_CHECK; 900 NORMALIZE_CHECK
901 901
902 *bufOut = buf; 902 *bufOut = buf;
903 return res; 903 return res;
@@ -943,7 +943,7 @@ When the decoder lookahead, and the lookahead symbol is not end_marker, we have
943*/ 943*/
944 944
945 945
946#define RETURN__NOT_FINISHED__FOR_FINISH \ 946#define RETURN_NOT_FINISHED_FOR_FINISH \
947 *status = LZMA_STATUS_NOT_FINISHED; \ 947 *status = LZMA_STATUS_NOT_FINISHED; \
948 return SZ_ERROR_DATA; // for strict mode 948 return SZ_ERROR_DATA; // for strict mode
949 // return SZ_OK; // for relaxed mode 949 // return SZ_OK; // for relaxed mode
@@ -1029,7 +1029,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr
1029 } 1029 }
1030 if (p->remainLen != 0) 1030 if (p->remainLen != 0)
1031 { 1031 {
1032 RETURN__NOT_FINISHED__FOR_FINISH; 1032 RETURN_NOT_FINISHED_FOR_FINISH
1033 } 1033 }
1034 checkEndMarkNow = 1; 1034 checkEndMarkNow = 1;
1035 } 1035 }
@@ -1072,7 +1072,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr
1072 for (i = 0; i < (unsigned)dummyProcessed; i++) 1072 for (i = 0; i < (unsigned)dummyProcessed; i++)
1073 p->tempBuf[i] = src[i]; 1073 p->tempBuf[i] = src[i];
1074 // p->remainLen = kMatchSpecLen_Error_Data; 1074 // p->remainLen = kMatchSpecLen_Error_Data;
1075 RETURN__NOT_FINISHED__FOR_FINISH; 1075 RETURN_NOT_FINISHED_FOR_FINISH
1076 } 1076 }
1077 1077
1078 bufLimit = src; 1078 bufLimit = src;
@@ -1150,7 +1150,7 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr
1150 (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize; 1150 (*srcLen) += (unsigned)dummyProcessed - p->tempBufSize;
1151 p->tempBufSize = (unsigned)dummyProcessed; 1151 p->tempBufSize = (unsigned)dummyProcessed;
1152 // p->remainLen = kMatchSpecLen_Error_Data; 1152 // p->remainLen = kMatchSpecLen_Error_Data;
1153 RETURN__NOT_FINISHED__FOR_FINISH; 1153 RETURN_NOT_FINISHED_FOR_FINISH
1154 } 1154 }
1155 } 1155 }
1156 1156
@@ -1299,8 +1299,8 @@ static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAl
1299SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) 1299SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc)
1300{ 1300{
1301 CLzmaProps propNew; 1301 CLzmaProps propNew;
1302 RINOK(LzmaProps_Decode(&propNew, props, propsSize)); 1302 RINOK(LzmaProps_Decode(&propNew, props, propsSize))
1303 RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); 1303 RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc))
1304 p->prop = propNew; 1304 p->prop = propNew;
1305 return SZ_OK; 1305 return SZ_OK;
1306} 1306}
@@ -1309,14 +1309,14 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll
1309{ 1309{
1310 CLzmaProps propNew; 1310 CLzmaProps propNew;
1311 SizeT dicBufSize; 1311 SizeT dicBufSize;
1312 RINOK(LzmaProps_Decode(&propNew, props, propsSize)); 1312 RINOK(LzmaProps_Decode(&propNew, props, propsSize))
1313 RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); 1313 RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc))
1314 1314
1315 { 1315 {
1316 UInt32 dictSize = propNew.dicSize; 1316 UInt32 dictSize = propNew.dicSize;
1317 SizeT mask = ((UInt32)1 << 12) - 1; 1317 SizeT mask = ((UInt32)1 << 12) - 1;
1318 if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; 1318 if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1;
1319 else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;; 1319 else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;
1320 dicBufSize = ((SizeT)dictSize + mask) & ~mask; 1320 dicBufSize = ((SizeT)dictSize + mask) & ~mask;
1321 if (dicBufSize < dictSize) 1321 if (dicBufSize < dictSize)
1322 dicBufSize = dictSize; 1322 dicBufSize = dictSize;
@@ -1348,8 +1348,8 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
1348 *status = LZMA_STATUS_NOT_SPECIFIED; 1348 *status = LZMA_STATUS_NOT_SPECIFIED;
1349 if (inSize < RC_INIT_SIZE) 1349 if (inSize < RC_INIT_SIZE)
1350 return SZ_ERROR_INPUT_EOF; 1350 return SZ_ERROR_INPUT_EOF;
1351 LzmaDec_Construct(&p); 1351 LzmaDec_CONSTRUCT(&p)
1352 RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)); 1352 RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc))
1353 p.dic = dest; 1353 p.dic = dest;
1354 p.dicBufSize = outSize; 1354 p.dicBufSize = outSize;
1355 LzmaDec_Init(&p); 1355 LzmaDec_Init(&p);
diff --git a/C/LzmaDec.h b/C/LzmaDec.h
index 6f12962..b0ce28f 100644
--- a/C/LzmaDec.h
+++ b/C/LzmaDec.h
@@ -1,19 +1,19 @@
1/* LzmaDec.h -- LZMA Decoder 1/* LzmaDec.h -- LZMA Decoder
22020-03-19 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA_DEC_H 4#ifndef ZIP7_INC_LZMA_DEC_H
5#define __LZMA_DEC_H 5#define ZIP7_INC_LZMA_DEC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11/* #define _LZMA_PROB32 */ 11/* #define Z7_LZMA_PROB32 */
12/* _LZMA_PROB32 can increase the speed on some CPUs, 12/* Z7_LZMA_PROB32 can increase the speed on some CPUs,
13 but memory usage for CLzmaDec::probs will be doubled in that case */ 13 but memory usage for CLzmaDec::probs will be doubled in that case */
14 14
15typedef 15typedef
16#ifdef _LZMA_PROB32 16#ifdef Z7_LZMA_PROB32
17 UInt32 17 UInt32
18#else 18#else
19 UInt16 19 UInt16
@@ -25,7 +25,7 @@ typedef
25 25
26#define LZMA_PROPS_SIZE 5 26#define LZMA_PROPS_SIZE 5
27 27
28typedef struct _CLzmaProps 28typedef struct
29{ 29{
30 Byte lc; 30 Byte lc;
31 Byte lp; 31 Byte lp;
@@ -73,7 +73,8 @@ typedef struct
73 Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; 73 Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
74} CLzmaDec; 74} CLzmaDec;
75 75
76#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } 76#define LzmaDec_CONSTRUCT(p) { (p)->dic = NULL; (p)->probs = NULL; }
77#define LzmaDec_Construct(p) LzmaDec_CONSTRUCT(p)
77 78
78void LzmaDec_Init(CLzmaDec *p); 79void LzmaDec_Init(CLzmaDec *p);
79 80
diff --git a/C/LzmaEnc.c b/C/LzmaEnc.c
index c8b31a1..6d13cac 100644
--- a/C/LzmaEnc.c
+++ b/C/LzmaEnc.c
@@ -1,5 +1,5 @@
1/* LzmaEnc.c -- LZMA Encoder 1/* LzmaEnc.c -- LZMA Encoder
22022-07-15: Igor Pavlov : Public domain */ 22023-04-13: Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -16,22 +16,22 @@
16#include "LzmaEnc.h" 16#include "LzmaEnc.h"
17 17
18#include "LzFind.h" 18#include "LzFind.h"
19#ifndef _7ZIP_ST 19#ifndef Z7_ST
20#include "LzFindMt.h" 20#include "LzFindMt.h"
21#endif 21#endif
22 22
23/* the following LzmaEnc_* declarations is internal LZMA interface for LZMA2 encoder */ 23/* the following LzmaEnc_* declarations is internal LZMA interface for LZMA2 encoder */
24 24
25SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, ISeqInStream *inStream, UInt32 keepWindowSize, 25SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p, ISeqInStreamPtr inStream, UInt32 keepWindowSize,
26 ISzAllocPtr alloc, ISzAllocPtr allocBig); 26 ISzAllocPtr alloc, ISzAllocPtr allocBig);
27SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, 27SRes LzmaEnc_MemPrepare(CLzmaEncHandle p, const Byte *src, SizeT srcLen,
28 UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig); 28 UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig);
29SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, 29SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit,
30 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize); 30 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize);
31const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp); 31const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p);
32void LzmaEnc_Finish(CLzmaEncHandle pp); 32void LzmaEnc_Finish(CLzmaEncHandle p);
33void LzmaEnc_SaveState(CLzmaEncHandle pp); 33void LzmaEnc_SaveState(CLzmaEncHandle p);
34void LzmaEnc_RestoreState(CLzmaEncHandle pp); 34void LzmaEnc_RestoreState(CLzmaEncHandle p);
35 35
36#ifdef SHOW_STAT 36#ifdef SHOW_STAT
37static unsigned g_STAT_OFFSET = 0; 37static unsigned g_STAT_OFFSET = 0;
@@ -40,8 +40,8 @@ static unsigned g_STAT_OFFSET = 0;
40/* for good normalization speed we still reserve 256 MB before 4 GB range */ 40/* for good normalization speed we still reserve 256 MB before 4 GB range */
41#define kLzmaMaxHistorySize ((UInt32)15 << 28) 41#define kLzmaMaxHistorySize ((UInt32)15 << 28)
42 42
43#define kNumTopBits 24 43// #define kNumTopBits 24
44#define kTopValue ((UInt32)1 << kNumTopBits) 44#define kTopValue ((UInt32)1 << 24)
45 45
46#define kNumBitModelTotalBits 11 46#define kNumBitModelTotalBits 11
47#define kBitModelTotal (1 << kNumBitModelTotalBits) 47#define kBitModelTotal (1 << kNumBitModelTotalBits)
@@ -60,6 +60,7 @@ void LzmaEncProps_Init(CLzmaEncProps *p)
60 p->dictSize = p->mc = 0; 60 p->dictSize = p->mc = 0;
61 p->reduceSize = (UInt64)(Int64)-1; 61 p->reduceSize = (UInt64)(Int64)-1;
62 p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; 62 p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
63 p->numHashOutBits = 0;
63 p->writeEndMark = 0; 64 p->writeEndMark = 0;
64 p->affinity = 0; 65 p->affinity = 0;
65} 66}
@@ -99,7 +100,7 @@ void LzmaEncProps_Normalize(CLzmaEncProps *p)
99 100
100 if (p->numThreads < 0) 101 if (p->numThreads < 0)
101 p->numThreads = 102 p->numThreads =
102 #ifndef _7ZIP_ST 103 #ifndef Z7_ST
103 ((p->btMode && p->algo) ? 2 : 1); 104 ((p->btMode && p->algo) ? 2 : 1);
104 #else 105 #else
105 1; 106 1;
@@ -293,7 +294,7 @@ typedef struct
293#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) 294#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
294 295
295typedef 296typedef
296#ifdef _LZMA_PROB32 297#ifdef Z7_LZMA_PROB32
297 UInt32 298 UInt32
298#else 299#else
299 UInt16 300 UInt16
@@ -350,7 +351,7 @@ typedef struct
350 Byte *buf; 351 Byte *buf;
351 Byte *bufLim; 352 Byte *bufLim;
352 Byte *bufBase; 353 Byte *bufBase;
353 ISeqOutStream *outStream; 354 ISeqOutStreamPtr outStream;
354 UInt64 processed; 355 UInt64 processed;
355 SRes res; 356 SRes res;
356} CRangeEnc; 357} CRangeEnc;
@@ -383,7 +384,7 @@ typedef struct
383typedef UInt32 CProbPrice; 384typedef UInt32 CProbPrice;
384 385
385 386
386typedef struct 387struct CLzmaEnc
387{ 388{
388 void *matchFinderObj; 389 void *matchFinderObj;
389 IMatchFinder2 matchFinder; 390 IMatchFinder2 matchFinder;
@@ -426,7 +427,7 @@ typedef struct
426 UInt32 dictSize; 427 UInt32 dictSize;
427 SRes result; 428 SRes result;
428 429
429 #ifndef _7ZIP_ST 430 #ifndef Z7_ST
430 BoolInt mtMode; 431 BoolInt mtMode;
431 // begin of CMatchFinderMt is used in LZ thread 432 // begin of CMatchFinderMt is used in LZ thread
432 CMatchFinderMt matchFinderMt; 433 CMatchFinderMt matchFinderMt;
@@ -439,7 +440,7 @@ typedef struct
439 440
440 // we suppose that we have 8-bytes alignment after CMatchFinder 441 // we suppose that we have 8-bytes alignment after CMatchFinder
441 442
442 #ifndef _7ZIP_ST 443 #ifndef Z7_ST
443 Byte pad[128]; 444 Byte pad[128];
444 #endif 445 #endif
445 446
@@ -479,77 +480,59 @@ typedef struct
479 CSaveState saveState; 480 CSaveState saveState;
480 481
481 // BoolInt mf_Failure; 482 // BoolInt mf_Failure;
482 #ifndef _7ZIP_ST 483 #ifndef Z7_ST
483 Byte pad2[128]; 484 Byte pad2[128];
484 #endif 485 #endif
485} CLzmaEnc; 486};
486 487
487 488
488#define MFB (p->matchFinderBase) 489#define MFB (p->matchFinderBase)
489/* 490/*
490#ifndef _7ZIP_ST 491#ifndef Z7_ST
491#define MFB (p->matchFinderMt.MatchFinder) 492#define MFB (p->matchFinderMt.MatchFinder)
492#endif 493#endif
493*/ 494*/
494 495
495#define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr)); 496// #define GET_CLzmaEnc_p CLzmaEnc *p = (CLzmaEnc*)(void *)p;
496 497// #define GET_const_CLzmaEnc_p const CLzmaEnc *p = (const CLzmaEnc*)(const void *)p;
497void LzmaEnc_SaveState(CLzmaEncHandle pp) 498
498{ 499#define COPY_ARR(dest, src, arr) memcpy((dest)->arr, (src)->arr, sizeof((src)->arr));
499 CLzmaEnc *p = (CLzmaEnc *)pp; 500
500 CSaveState *dest = &p->saveState; 501#define COPY_LZMA_ENC_STATE(d, s, p) \
501 502 (d)->state = (s)->state; \
502 dest->state = p->state; 503 COPY_ARR(d, s, reps) \
503 504 COPY_ARR(d, s, posAlignEncoder) \
504 dest->lenProbs = p->lenProbs; 505 COPY_ARR(d, s, isRep) \
505 dest->repLenProbs = p->repLenProbs; 506 COPY_ARR(d, s, isRepG0) \
506 507 COPY_ARR(d, s, isRepG1) \
507 COPY_ARR(dest, p, reps); 508 COPY_ARR(d, s, isRepG2) \
508 509 COPY_ARR(d, s, isMatch) \
509 COPY_ARR(dest, p, posAlignEncoder); 510 COPY_ARR(d, s, isRep0Long) \
510 COPY_ARR(dest, p, isRep); 511 COPY_ARR(d, s, posSlotEncoder) \
511 COPY_ARR(dest, p, isRepG0); 512 COPY_ARR(d, s, posEncoders) \
512 COPY_ARR(dest, p, isRepG1); 513 (d)->lenProbs = (s)->lenProbs; \
513 COPY_ARR(dest, p, isRepG2); 514 (d)->repLenProbs = (s)->repLenProbs; \
514 COPY_ARR(dest, p, isMatch); 515 memcpy((d)->litProbs, (s)->litProbs, ((UInt32)0x300 << (p)->lclp) * sizeof(CLzmaProb));
515 COPY_ARR(dest, p, isRep0Long); 516
516 COPY_ARR(dest, p, posSlotEncoder); 517void LzmaEnc_SaveState(CLzmaEncHandle p)
517 COPY_ARR(dest, p, posEncoders); 518{
518 519 // GET_CLzmaEnc_p
519 memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb)); 520 CSaveState *v = &p->saveState;
521 COPY_LZMA_ENC_STATE(v, p, p)
520} 522}
521 523
522 524void LzmaEnc_RestoreState(CLzmaEncHandle p)
523void LzmaEnc_RestoreState(CLzmaEncHandle pp)
524{ 525{
525 CLzmaEnc *dest = (CLzmaEnc *)pp; 526 // GET_CLzmaEnc_p
526 const CSaveState *p = &dest->saveState; 527 const CSaveState *v = &p->saveState;
527 528 COPY_LZMA_ENC_STATE(p, v, p)
528 dest->state = p->state;
529
530 dest->lenProbs = p->lenProbs;
531 dest->repLenProbs = p->repLenProbs;
532
533 COPY_ARR(dest, p, reps);
534
535 COPY_ARR(dest, p, posAlignEncoder);
536 COPY_ARR(dest, p, isRep);
537 COPY_ARR(dest, p, isRepG0);
538 COPY_ARR(dest, p, isRepG1);
539 COPY_ARR(dest, p, isRepG2);
540 COPY_ARR(dest, p, isMatch);
541 COPY_ARR(dest, p, isRep0Long);
542 COPY_ARR(dest, p, posSlotEncoder);
543 COPY_ARR(dest, p, posEncoders);
544
545 memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb));
546} 529}
547 530
548 531
549 532Z7_NO_INLINE
550SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) 533SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props2)
551{ 534{
552 CLzmaEnc *p = (CLzmaEnc *)pp; 535 // GET_CLzmaEnc_p
553 CLzmaEncProps props = *props2; 536 CLzmaEncProps props = *props2;
554 LzmaEncProps_Normalize(&props); 537 LzmaEncProps_Normalize(&props);
555 538
@@ -585,6 +568,7 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
585 p->fastMode = (props.algo == 0); 568 p->fastMode = (props.algo == 0);
586 // p->_maxMode = True; 569 // p->_maxMode = True;
587 MFB.btMode = (Byte)(props.btMode ? 1 : 0); 570 MFB.btMode = (Byte)(props.btMode ? 1 : 0);
571 // MFB.btMode = (Byte)(props.btMode);
588 { 572 {
589 unsigned numHashBytes = 4; 573 unsigned numHashBytes = 4;
590 if (props.btMode) 574 if (props.btMode)
@@ -595,13 +579,15 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
595 if (props.numHashBytes >= 5) numHashBytes = 5; 579 if (props.numHashBytes >= 5) numHashBytes = 5;
596 580
597 MFB.numHashBytes = numHashBytes; 581 MFB.numHashBytes = numHashBytes;
582 // MFB.numHashBytes_Min = 2;
583 MFB.numHashOutBits = (Byte)props.numHashOutBits;
598 } 584 }
599 585
600 MFB.cutValue = props.mc; 586 MFB.cutValue = props.mc;
601 587
602 p->writeEndMark = (BoolInt)props.writeEndMark; 588 p->writeEndMark = (BoolInt)props.writeEndMark;
603 589
604 #ifndef _7ZIP_ST 590 #ifndef Z7_ST
605 /* 591 /*
606 if (newMultiThread != _multiThread) 592 if (newMultiThread != _multiThread)
607 { 593 {
@@ -618,9 +604,9 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
618} 604}
619 605
620 606
621void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize) 607void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize)
622{ 608{
623 CLzmaEnc *p = (CLzmaEnc *)pp; 609 // GET_CLzmaEnc_p
624 MFB.expectedDataSize = expectedDataSiize; 610 MFB.expectedDataSize = expectedDataSiize;
625} 611}
626 612
@@ -684,7 +670,7 @@ static void RangeEnc_Init(CRangeEnc *p)
684 p->res = SZ_OK; 670 p->res = SZ_OK;
685} 671}
686 672
687MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p) 673Z7_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p)
688{ 674{
689 const size_t num = (size_t)(p->buf - p->bufBase); 675 const size_t num = (size_t)(p->buf - p->bufBase);
690 if (p->res == SZ_OK) 676 if (p->res == SZ_OK)
@@ -696,7 +682,7 @@ MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p)
696 p->buf = p->bufBase; 682 p->buf = p->bufBase;
697} 683}
698 684
699MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) 685Z7_NO_INLINE static void Z7_FASTCALL RangeEnc_ShiftLow(CRangeEnc *p)
700{ 686{
701 UInt32 low = (UInt32)p->low; 687 UInt32 low = (UInt32)p->low;
702 unsigned high = (unsigned)(p->low >> 32); 688 unsigned high = (unsigned)(p->low >> 32);
@@ -741,9 +727,9 @@ static void RangeEnc_FlushData(CRangeEnc *p)
741 ttt = *(prob); \ 727 ttt = *(prob); \
742 newBound = (range >> kNumBitModelTotalBits) * ttt; 728 newBound = (range >> kNumBitModelTotalBits) * ttt;
743 729
744// #define _LZMA_ENC_USE_BRANCH 730// #define Z7_LZMA_ENC_USE_BRANCH
745 731
746#ifdef _LZMA_ENC_USE_BRANCH 732#ifdef Z7_LZMA_ENC_USE_BRANCH
747 733
748#define RC_BIT(p, prob, bit) { \ 734#define RC_BIT(p, prob, bit) { \
749 RC_BIT_PRE(p, prob) \ 735 RC_BIT_PRE(p, prob) \
@@ -811,7 +797,7 @@ static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym)
811 CLzmaProb *prob = probs + (sym >> 8); 797 CLzmaProb *prob = probs + (sym >> 8);
812 UInt32 bit = (sym >> 7) & 1; 798 UInt32 bit = (sym >> 7) & 1;
813 sym <<= 1; 799 sym <<= 1;
814 RC_BIT(p, prob, bit); 800 RC_BIT(p, prob, bit)
815 } 801 }
816 while (sym < 0x10000); 802 while (sym < 0x10000);
817 p->range = range; 803 p->range = range;
@@ -833,7 +819,7 @@ static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UIn
833 bit = (sym >> 7) & 1; 819 bit = (sym >> 7) & 1;
834 sym <<= 1; 820 sym <<= 1;
835 offs &= ~(matchByte ^ sym); 821 offs &= ~(matchByte ^ sym);
836 RC_BIT(p, prob, bit); 822 RC_BIT(p, prob, bit)
837 } 823 }
838 while (sym < 0x10000); 824 while (sym < 0x10000);
839 p->range = range; 825 p->range = range;
@@ -867,10 +853,10 @@ static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices)
867 853
868 854
869#define GET_PRICE(prob, bit) \ 855#define GET_PRICE(prob, bit) \
870 p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; 856 p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]
871 857
872#define GET_PRICEa(prob, bit) \ 858#define GET_PRICEa(prob, bit) \
873 ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; 859 ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]
874 860
875#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] 861#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
876#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] 862#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
921 unsigned bit = sym & 1; 907 unsigned bit = sym & 1;
922 // RangeEnc_EncodeBit(rc, probs + m, bit); 908 // RangeEnc_EncodeBit(rc, probs + m, bit);
923 sym >>= 1; 909 sym >>= 1;
924 RC_BIT(rc, probs + m, bit); 910 RC_BIT(rc, probs + m, bit)
925 m = (m << 1) | bit; 911 m = (m << 1) | bit;
926 } 912 }
927 while (--numBits); 913 while (--numBits);
@@ -944,15 +930,15 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS
944 UInt32 range, ttt, newBound; 930 UInt32 range, ttt, newBound;
945 CLzmaProb *probs = p->low; 931 CLzmaProb *probs = p->low;
946 range = rc->range; 932 range = rc->range;
947 RC_BIT_PRE(rc, probs); 933 RC_BIT_PRE(rc, probs)
948 if (sym >= kLenNumLowSymbols) 934 if (sym >= kLenNumLowSymbols)
949 { 935 {
950 RC_BIT_1(rc, probs); 936 RC_BIT_1(rc, probs)
951 probs += kLenNumLowSymbols; 937 probs += kLenNumLowSymbols;
952 RC_BIT_PRE(rc, probs); 938 RC_BIT_PRE(rc, probs)
953 if (sym >= kLenNumLowSymbols * 2) 939 if (sym >= kLenNumLowSymbols * 2)
954 { 940 {
955 RC_BIT_1(rc, probs); 941 RC_BIT_1(rc, probs)
956 rc->range = range; 942 rc->range = range;
957 // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2); 943 // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2);
958 LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2); 944 LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2);
@@ -965,11 +951,11 @@ static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posS
965 { 951 {
966 unsigned m; 952 unsigned m;
967 unsigned bit; 953 unsigned bit;
968 RC_BIT_0(rc, probs); 954 RC_BIT_0(rc, probs)
969 probs += (posState << (1 + kLenNumLowBits)); 955 probs += (posState << (1 + kLenNumLowBits));
970 bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit; 956 bit = (sym >> 2) ; RC_BIT(rc, probs + 1, bit) m = (1 << 1) + bit;
971 bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit; 957 bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit) m = (m << 1) + bit;
972 bit = sym & 1; RC_BIT(rc, probs + m, bit); 958 bit = sym & 1; RC_BIT(rc, probs + m, bit)
973 rc->range = range; 959 rc->range = range;
974 } 960 }
975} 961}
@@ -990,7 +976,7 @@ static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *price
990} 976}
991 977
992 978
993MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables( 979Z7_NO_INLINE static void Z7_FASTCALL LenPriceEnc_UpdateTables(
994 CLenPriceEnc *p, 980 CLenPriceEnc *p,
995 unsigned numPosStates, 981 unsigned numPosStates,
996 const CLenEnc *enc, 982 const CLenEnc *enc,
@@ -1152,7 +1138,7 @@ static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes)
1152 + GET_PRICE_1(p->isRep[state]) \ 1138 + GET_PRICE_1(p->isRep[state]) \
1153 + GET_PRICE_0(p->isRepG0[state]) 1139 + GET_PRICE_0(p->isRepG0[state])
1154 1140
1155MY_FORCE_INLINE 1141Z7_FORCE_INLINE
1156static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState) 1142static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState)
1157{ 1143{
1158 UInt32 price; 1144 UInt32 price;
@@ -1331,7 +1317,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1331 LitEnc_GetPrice(probs, curByte, p->ProbPrices)); 1317 LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1332 } 1318 }
1333 1319
1334 MakeAs_Lit(&p->opt[1]); 1320 MakeAs_Lit(&p->opt[1])
1335 1321
1336 matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); 1322 matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
1337 repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); 1323 repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
@@ -1343,7 +1329,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1343 if (shortRepPrice < p->opt[1].price) 1329 if (shortRepPrice < p->opt[1].price)
1344 { 1330 {
1345 p->opt[1].price = shortRepPrice; 1331 p->opt[1].price = shortRepPrice;
1346 MakeAs_ShortRep(&p->opt[1]); 1332 MakeAs_ShortRep(&p->opt[1])
1347 } 1333 }
1348 if (last < 2) 1334 if (last < 2)
1349 { 1335 {
@@ -1410,7 +1396,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1410 else 1396 else
1411 { 1397 {
1412 unsigned slot; 1398 unsigned slot;
1413 GetPosSlot2(dist, slot); 1399 GetPosSlot2(dist, slot)
1414 price += p->alignPrices[dist & kAlignMask]; 1400 price += p->alignPrices[dist & kAlignMask];
1415 price += p->posSlotPrices[lenToPosState][slot]; 1401 price += p->posSlotPrices[lenToPosState][slot];
1416 } 1402 }
@@ -1486,7 +1472,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1486 unsigned delta = best - cur; 1472 unsigned delta = best - cur;
1487 if (delta != 0) 1473 if (delta != 0)
1488 { 1474 {
1489 MOVE_POS(p, delta); 1475 MOVE_POS(p, delta)
1490 } 1476 }
1491 } 1477 }
1492 cur = best; 1478 cur = best;
@@ -1633,7 +1619,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1633 { 1619 {
1634 nextOpt->price = litPrice; 1620 nextOpt->price = litPrice;
1635 nextOpt->len = 1; 1621 nextOpt->len = 1;
1636 MakeAs_Lit(nextOpt); 1622 MakeAs_Lit(nextOpt)
1637 nextIsLit = True; 1623 nextIsLit = True;
1638 } 1624 }
1639 } 1625 }
@@ -1667,7 +1653,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1667 { 1653 {
1668 nextOpt->price = shortRepPrice; 1654 nextOpt->price = shortRepPrice;
1669 nextOpt->len = 1; 1655 nextOpt->len = 1;
1670 MakeAs_ShortRep(nextOpt); 1656 MakeAs_ShortRep(nextOpt)
1671 nextIsLit = False; 1657 nextIsLit = False;
1672 } 1658 }
1673 } 1659 }
@@ -1871,7 +1857,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1871 dist = MATCHES[(size_t)offs + 1]; 1857 dist = MATCHES[(size_t)offs + 1];
1872 1858
1873 // if (dist >= kNumFullDistances) 1859 // if (dist >= kNumFullDistances)
1874 GetPosSlot2(dist, posSlot); 1860 GetPosSlot2(dist, posSlot)
1875 1861
1876 for (len = /*2*/ startLen; ; len++) 1862 for (len = /*2*/ startLen; ; len++)
1877 { 1863 {
@@ -1962,7 +1948,7 @@ static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1962 break; 1948 break;
1963 dist = MATCHES[(size_t)offs + 1]; 1949 dist = MATCHES[(size_t)offs + 1];
1964 // if (dist >= kNumFullDistances) 1950 // if (dist >= kNumFullDistances)
1965 GetPosSlot2(dist, posSlot); 1951 GetPosSlot2(dist, posSlot)
1966 } 1952 }
1967 } 1953 }
1968 } 1954 }
@@ -2138,7 +2124,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState)
2138 { 2124 {
2139 UInt32 ttt, newBound; 2125 UInt32 ttt, newBound;
2140 RC_BIT_PRE(p, probs + m) 2126 RC_BIT_PRE(p, probs + m)
2141 RC_BIT_1(&p->rc, probs + m); 2127 RC_BIT_1(&p->rc, probs + m)
2142 m = (m << 1) + 1; 2128 m = (m << 1) + 1;
2143 } 2129 }
2144 while (m < (1 << kNumPosSlotBits)); 2130 while (m < (1 << kNumPosSlotBits));
@@ -2163,7 +2149,7 @@ static void WriteEndMarker(CLzmaEnc *p, unsigned posState)
2163 { 2149 {
2164 UInt32 ttt, newBound; 2150 UInt32 ttt, newBound;
2165 RC_BIT_PRE(p, probs + m) 2151 RC_BIT_PRE(p, probs + m)
2166 RC_BIT_1(&p->rc, probs + m); 2152 RC_BIT_1(&p->rc, probs + m)
2167 m = (m << 1) + 1; 2153 m = (m << 1) + 1;
2168 } 2154 }
2169 while (m < kAlignTableSize); 2155 while (m < kAlignTableSize);
@@ -2179,7 +2165,7 @@ static SRes CheckErrors(CLzmaEnc *p)
2179 if (p->rc.res != SZ_OK) 2165 if (p->rc.res != SZ_OK)
2180 p->result = SZ_ERROR_WRITE; 2166 p->result = SZ_ERROR_WRITE;
2181 2167
2182 #ifndef _7ZIP_ST 2168 #ifndef Z7_ST
2183 if ( 2169 if (
2184 // p->mf_Failure || 2170 // p->mf_Failure ||
2185 (p->mtMode && 2171 (p->mtMode &&
@@ -2187,7 +2173,7 @@ static SRes CheckErrors(CLzmaEnc *p)
2187 p->matchFinderMt.failure_LZ_BT)) 2173 p->matchFinderMt.failure_LZ_BT))
2188 ) 2174 )
2189 { 2175 {
2190 p->result = MY_HRES_ERROR__INTERNAL_ERROR; 2176 p->result = MY_HRES_ERROR_INTERNAL_ERROR;
2191 // printf("\nCheckErrors p->matchFinderMt.failureLZ\n"); 2177 // printf("\nCheckErrors p->matchFinderMt.failureLZ\n");
2192 } 2178 }
2193 #endif 2179 #endif
@@ -2201,7 +2187,7 @@ static SRes CheckErrors(CLzmaEnc *p)
2201} 2187}
2202 2188
2203 2189
2204MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos) 2190Z7_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
2205{ 2191{
2206 /* ReleaseMFStream(); */ 2192 /* ReleaseMFStream(); */
2207 p->finished = True; 2193 p->finished = True;
@@ -2213,7 +2199,7 @@ MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
2213} 2199}
2214 2200
2215 2201
2216MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p) 2202Z7_NO_INLINE static void FillAlignPrices(CLzmaEnc *p)
2217{ 2203{
2218 unsigned i; 2204 unsigned i;
2219 const CProbPrice *ProbPrices = p->ProbPrices; 2205 const CProbPrice *ProbPrices = p->ProbPrices;
@@ -2237,7 +2223,7 @@ MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p)
2237} 2223}
2238 2224
2239 2225
2240MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p) 2226Z7_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p)
2241{ 2227{
2242 // int y; for (y = 0; y < 100; y++) { 2228 // int y; for (y = 0; y < 100; y++) {
2243 2229
@@ -2337,7 +2323,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p)
2337 RangeEnc_Construct(&p->rc); 2323 RangeEnc_Construct(&p->rc);
2338 MatchFinder_Construct(&MFB); 2324 MatchFinder_Construct(&MFB);
2339 2325
2340 #ifndef _7ZIP_ST 2326 #ifndef Z7_ST
2341 p->matchFinderMt.MatchFinder = &MFB; 2327 p->matchFinderMt.MatchFinder = &MFB;
2342 MatchFinderMt_Construct(&p->matchFinderMt); 2328 MatchFinderMt_Construct(&p->matchFinderMt);
2343 #endif 2329 #endif
@@ -2345,7 +2331,7 @@ static void LzmaEnc_Construct(CLzmaEnc *p)
2345 { 2331 {
2346 CLzmaEncProps props; 2332 CLzmaEncProps props;
2347 LzmaEncProps_Init(&props); 2333 LzmaEncProps_Init(&props);
2348 LzmaEnc_SetProps(p, &props); 2334 LzmaEnc_SetProps((CLzmaEncHandle)(void *)p, &props);
2349 } 2335 }
2350 2336
2351 #ifndef LZMA_LOG_BSR 2337 #ifndef LZMA_LOG_BSR
@@ -2376,7 +2362,7 @@ static void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc)
2376 2362
2377static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig) 2363static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2378{ 2364{
2379 #ifndef _7ZIP_ST 2365 #ifndef Z7_ST
2380 MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); 2366 MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
2381 #endif 2367 #endif
2382 2368
@@ -2387,21 +2373,22 @@ static void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBi
2387 2373
2388void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig) 2374void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2389{ 2375{
2390 LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); 2376 // GET_CLzmaEnc_p
2377 LzmaEnc_Destruct(p, alloc, allocBig);
2391 ISzAlloc_Free(alloc, p); 2378 ISzAlloc_Free(alloc, p);
2392} 2379}
2393 2380
2394 2381
2395MY_NO_INLINE 2382Z7_NO_INLINE
2396static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize) 2383static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize)
2397{ 2384{
2398 UInt32 nowPos32, startPos32; 2385 UInt32 nowPos32, startPos32;
2399 if (p->needInit) 2386 if (p->needInit)
2400 { 2387 {
2401 #ifndef _7ZIP_ST 2388 #ifndef Z7_ST
2402 if (p->mtMode) 2389 if (p->mtMode)
2403 { 2390 {
2404 RINOK(MatchFinderMt_InitMt(&p->matchFinderMt)); 2391 RINOK(MatchFinderMt_InitMt(&p->matchFinderMt))
2405 } 2392 }
2406 #endif 2393 #endif
2407 p->matchFinder.Init(p->matchFinderObj); 2394 p->matchFinder.Init(p->matchFinderObj);
@@ -2410,7 +2397,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2410 2397
2411 if (p->finished) 2398 if (p->finished)
2412 return p->result; 2399 return p->result;
2413 RINOK(CheckErrors(p)); 2400 RINOK(CheckErrors(p))
2414 2401
2415 nowPos32 = (UInt32)p->nowPos64; 2402 nowPos32 = (UInt32)p->nowPos64;
2416 startPos32 = nowPos32; 2403 startPos32 = nowPos32;
@@ -2473,7 +2460,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2473 const Byte *data; 2460 const Byte *data;
2474 unsigned state; 2461 unsigned state;
2475 2462
2476 RC_BIT_0(&p->rc, probs); 2463 RC_BIT_0(&p->rc, probs)
2477 p->rc.range = range; 2464 p->rc.range = range;
2478 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; 2465 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2479 probs = LIT_PROBS(nowPos32, *(data - 1)); 2466 probs = LIT_PROBS(nowPos32, *(data - 1));
@@ -2487,53 +2474,53 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2487 } 2474 }
2488 else 2475 else
2489 { 2476 {
2490 RC_BIT_1(&p->rc, probs); 2477 RC_BIT_1(&p->rc, probs)
2491 probs = &p->isRep[p->state]; 2478 probs = &p->isRep[p->state];
2492 RC_BIT_PRE(&p->rc, probs) 2479 RC_BIT_PRE(&p->rc, probs)
2493 2480
2494 if (dist < LZMA_NUM_REPS) 2481 if (dist < LZMA_NUM_REPS)
2495 { 2482 {
2496 RC_BIT_1(&p->rc, probs); 2483 RC_BIT_1(&p->rc, probs)
2497 probs = &p->isRepG0[p->state]; 2484 probs = &p->isRepG0[p->state];
2498 RC_BIT_PRE(&p->rc, probs) 2485 RC_BIT_PRE(&p->rc, probs)
2499 if (dist == 0) 2486 if (dist == 0)
2500 { 2487 {
2501 RC_BIT_0(&p->rc, probs); 2488 RC_BIT_0(&p->rc, probs)
2502 probs = &p->isRep0Long[p->state][posState]; 2489 probs = &p->isRep0Long[p->state][posState];
2503 RC_BIT_PRE(&p->rc, probs) 2490 RC_BIT_PRE(&p->rc, probs)
2504 if (len != 1) 2491 if (len != 1)
2505 { 2492 {
2506 RC_BIT_1_BASE(&p->rc, probs); 2493 RC_BIT_1_BASE(&p->rc, probs)
2507 } 2494 }
2508 else 2495 else
2509 { 2496 {
2510 RC_BIT_0_BASE(&p->rc, probs); 2497 RC_BIT_0_BASE(&p->rc, probs)
2511 p->state = kShortRepNextStates[p->state]; 2498 p->state = kShortRepNextStates[p->state];
2512 } 2499 }
2513 } 2500 }
2514 else 2501 else
2515 { 2502 {
2516 RC_BIT_1(&p->rc, probs); 2503 RC_BIT_1(&p->rc, probs)
2517 probs = &p->isRepG1[p->state]; 2504 probs = &p->isRepG1[p->state];
2518 RC_BIT_PRE(&p->rc, probs) 2505 RC_BIT_PRE(&p->rc, probs)
2519 if (dist == 1) 2506 if (dist == 1)
2520 { 2507 {
2521 RC_BIT_0_BASE(&p->rc, probs); 2508 RC_BIT_0_BASE(&p->rc, probs)
2522 dist = p->reps[1]; 2509 dist = p->reps[1];
2523 } 2510 }
2524 else 2511 else
2525 { 2512 {
2526 RC_BIT_1(&p->rc, probs); 2513 RC_BIT_1(&p->rc, probs)
2527 probs = &p->isRepG2[p->state]; 2514 probs = &p->isRepG2[p->state];
2528 RC_BIT_PRE(&p->rc, probs) 2515 RC_BIT_PRE(&p->rc, probs)
2529 if (dist == 2) 2516 if (dist == 2)
2530 { 2517 {
2531 RC_BIT_0_BASE(&p->rc, probs); 2518 RC_BIT_0_BASE(&p->rc, probs)
2532 dist = p->reps[2]; 2519 dist = p->reps[2];
2533 } 2520 }
2534 else 2521 else
2535 { 2522 {
2536 RC_BIT_1_BASE(&p->rc, probs); 2523 RC_BIT_1_BASE(&p->rc, probs)
2537 dist = p->reps[3]; 2524 dist = p->reps[3];
2538 p->reps[3] = p->reps[2]; 2525 p->reps[3] = p->reps[2];
2539 } 2526 }
@@ -2557,7 +2544,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2557 else 2544 else
2558 { 2545 {
2559 unsigned posSlot; 2546 unsigned posSlot;
2560 RC_BIT_0(&p->rc, probs); 2547 RC_BIT_0(&p->rc, probs)
2561 p->rc.range = range; 2548 p->rc.range = range;
2562 p->state = kMatchNextStates[p->state]; 2549 p->state = kMatchNextStates[p->state];
2563 2550
@@ -2571,7 +2558,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2571 p->reps[0] = dist + 1; 2558 p->reps[0] = dist + 1;
2572 2559
2573 p->matchPriceCount++; 2560 p->matchPriceCount++;
2574 GetPosSlot(dist, posSlot); 2561 GetPosSlot(dist, posSlot)
2575 // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot); 2562 // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot);
2576 { 2563 {
2577 UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits); 2564 UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits);
@@ -2582,7 +2569,7 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2582 CLzmaProb *prob = probs + (sym >> kNumPosSlotBits); 2569 CLzmaProb *prob = probs + (sym >> kNumPosSlotBits);
2583 UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1; 2570 UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1;
2584 sym <<= 1; 2571 sym <<= 1;
2585 RC_BIT(&p->rc, prob, bit); 2572 RC_BIT(&p->rc, prob, bit)
2586 } 2573 }
2587 while (sym < (1 << kNumPosSlotBits * 2)); 2574 while (sym < (1 << kNumPosSlotBits * 2));
2588 p->rc.range = range; 2575 p->rc.range = range;
@@ -2626,10 +2613,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpa
2626 { 2613 {
2627 unsigned m = 1; 2614 unsigned m = 1;
2628 unsigned bit; 2615 unsigned bit;
2629 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; 2616 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit;
2630 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; 2617 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit;
2631 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit; 2618 bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit) m = (m << 1) + bit;
2632 bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); 2619 bit = dist & 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit)
2633 p->rc.range = range; 2620 p->rc.range = range;
2634 // p->alignPriceCount++; 2621 // p->alignPriceCount++;
2635 } 2622 }
@@ -2704,7 +2691,7 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc,
2704 if (!RangeEnc_Alloc(&p->rc, alloc)) 2691 if (!RangeEnc_Alloc(&p->rc, alloc))
2705 return SZ_ERROR_MEM; 2692 return SZ_ERROR_MEM;
2706 2693
2707 #ifndef _7ZIP_ST 2694 #ifndef Z7_ST
2708 p->mtMode = (p->multiThread && !p->fastMode && (MFB.btMode != 0)); 2695 p->mtMode = (p->multiThread && !p->fastMode && (MFB.btMode != 0));
2709 #endif 2696 #endif
2710 2697
@@ -2748,15 +2735,14 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc,
2748 (numFastBytes + LZMA_MATCH_LEN_MAX + 1) 2735 (numFastBytes + LZMA_MATCH_LEN_MAX + 1)
2749 */ 2736 */
2750 2737
2751 #ifndef _7ZIP_ST 2738 #ifndef Z7_ST
2752 if (p->mtMode) 2739 if (p->mtMode)
2753 { 2740 {
2754 RINOK(MatchFinderMt_Create(&p->matchFinderMt, dictSize, beforeSize, 2741 RINOK(MatchFinderMt_Create(&p->matchFinderMt, dictSize, beforeSize,
2755 p->numFastBytes, LZMA_MATCH_LEN_MAX + 1 /* 18.04 */ 2742 p->numFastBytes, LZMA_MATCH_LEN_MAX + 1 /* 18.04 */
2756 , allocBig)); 2743 , allocBig))
2757 p->matchFinderObj = &p->matchFinderMt; 2744 p->matchFinderObj = &p->matchFinderMt;
2758 MFB.bigHash = (Byte)( 2745 MFB.bigHash = (Byte)(MFB.hashMask >= 0xFFFFFF ? 1 : 0);
2759 (p->dictSize > kBigHashDicLimit && MFB.hashMask >= 0xFFFFFF) ? 1 : 0);
2760 MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); 2746 MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
2761 } 2747 }
2762 else 2748 else
@@ -2872,59 +2858,53 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr
2872 2858
2873 p->finished = False; 2859 p->finished = False;
2874 p->result = SZ_OK; 2860 p->result = SZ_OK;
2875 RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig)); 2861 p->nowPos64 = 0;
2862 p->needInit = 1;
2863 RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig))
2876 LzmaEnc_Init(p); 2864 LzmaEnc_Init(p);
2877 LzmaEnc_InitPrices(p); 2865 LzmaEnc_InitPrices(p);
2878 p->nowPos64 = 0;
2879 return SZ_OK; 2866 return SZ_OK;
2880} 2867}
2881 2868
2882static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, 2869static SRes LzmaEnc_Prepare(CLzmaEncHandle p,
2870 ISeqOutStreamPtr outStream,
2871 ISeqInStreamPtr inStream,
2883 ISzAllocPtr alloc, ISzAllocPtr allocBig) 2872 ISzAllocPtr alloc, ISzAllocPtr allocBig)
2884{ 2873{
2885 CLzmaEnc *p = (CLzmaEnc *)pp; 2874 // GET_CLzmaEnc_p
2886 MFB.stream = inStream; 2875 MatchFinder_SET_STREAM(&MFB, inStream)
2887 p->needInit = 1;
2888 p->rc.outStream = outStream; 2876 p->rc.outStream = outStream;
2889 return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig); 2877 return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
2890} 2878}
2891 2879
2892SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, 2880SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle p,
2893 ISeqInStream *inStream, UInt32 keepWindowSize, 2881 ISeqInStreamPtr inStream, UInt32 keepWindowSize,
2894 ISzAllocPtr alloc, ISzAllocPtr allocBig) 2882 ISzAllocPtr alloc, ISzAllocPtr allocBig)
2895{ 2883{
2896 CLzmaEnc *p = (CLzmaEnc *)pp; 2884 // GET_CLzmaEnc_p
2897 MFB.stream = inStream; 2885 MatchFinder_SET_STREAM(&MFB, inStream)
2898 p->needInit = 1;
2899 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); 2886 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2900} 2887}
2901 2888
2902static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) 2889SRes LzmaEnc_MemPrepare(CLzmaEncHandle p,
2903{ 2890 const Byte *src, SizeT srcLen,
2904 MFB.directInput = 1; 2891 UInt32 keepWindowSize,
2905 MFB.bufferBase = (Byte *)src; 2892 ISzAllocPtr alloc, ISzAllocPtr allocBig)
2906 MFB.directInputRem = srcLen;
2907}
2908
2909SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
2910 UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2911{ 2893{
2912 CLzmaEnc *p = (CLzmaEnc *)pp; 2894 // GET_CLzmaEnc_p
2913 LzmaEnc_SetInputBuf(p, src, srcLen); 2895 MatchFinder_SET_DIRECT_INPUT_BUF(&MFB, src, srcLen)
2914 p->needInit = 1; 2896 LzmaEnc_SetDataSize(p, srcLen);
2915
2916 LzmaEnc_SetDataSize(pp, srcLen);
2917 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); 2897 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2918} 2898}
2919 2899
2920void LzmaEnc_Finish(CLzmaEncHandle pp) 2900void LzmaEnc_Finish(CLzmaEncHandle p)
2921{ 2901{
2922 #ifndef _7ZIP_ST 2902 #ifndef Z7_ST
2923 CLzmaEnc *p = (CLzmaEnc *)pp; 2903 // GET_CLzmaEnc_p
2924 if (p->mtMode) 2904 if (p->mtMode)
2925 MatchFinderMt_ReleaseStream(&p->matchFinderMt); 2905 MatchFinderMt_ReleaseStream(&p->matchFinderMt);
2926 #else 2906 #else
2927 UNUSED_VAR(pp); 2907 UNUSED_VAR(p)
2928 #endif 2908 #endif
2929} 2909}
2930 2910
@@ -2933,13 +2913,13 @@ typedef struct
2933{ 2913{
2934 ISeqOutStream vt; 2914 ISeqOutStream vt;
2935 Byte *data; 2915 Byte *data;
2936 SizeT rem; 2916 size_t rem;
2937 BoolInt overflow; 2917 BoolInt overflow;
2938} CLzmaEnc_SeqOutStreamBuf; 2918} CLzmaEnc_SeqOutStreamBuf;
2939 2919
2940static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size) 2920static size_t SeqOutStreamBuf_Write(ISeqOutStreamPtr pp, const void *data, size_t size)
2941{ 2921{
2942 CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt); 2922 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CLzmaEnc_SeqOutStreamBuf)
2943 if (p->rem < size) 2923 if (p->rem < size)
2944 { 2924 {
2945 size = p->rem; 2925 size = p->rem;
@@ -2956,25 +2936,25 @@ static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, s
2956 2936
2957 2937
2958/* 2938/*
2959UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) 2939UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle p)
2960{ 2940{
2961 const CLzmaEnc *p = (CLzmaEnc *)pp; 2941 GET_const_CLzmaEnc_p
2962 return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); 2942 return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
2963} 2943}
2964*/ 2944*/
2965 2945
2966const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) 2946const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle p)
2967{ 2947{
2968 const CLzmaEnc *p = (CLzmaEnc *)pp; 2948 // GET_const_CLzmaEnc_p
2969 return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; 2949 return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2970} 2950}
2971 2951
2972 2952
2973// (desiredPackSize == 0) is not allowed 2953// (desiredPackSize == 0) is not allowed
2974SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit, 2954SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle p, BoolInt reInit,
2975 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) 2955 Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
2976{ 2956{
2977 CLzmaEnc *p = (CLzmaEnc *)pp; 2957 // GET_CLzmaEnc_p
2978 UInt64 nowPos64; 2958 UInt64 nowPos64;
2979 SRes res; 2959 SRes res;
2980 CLzmaEnc_SeqOutStreamBuf outStream; 2960 CLzmaEnc_SeqOutStreamBuf outStream;
@@ -3006,12 +2986,12 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit,
3006} 2986}
3007 2987
3008 2988
3009MY_NO_INLINE 2989Z7_NO_INLINE
3010static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) 2990static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgressPtr progress)
3011{ 2991{
3012 SRes res = SZ_OK; 2992 SRes res = SZ_OK;
3013 2993
3014 #ifndef _7ZIP_ST 2994 #ifndef Z7_ST
3015 Byte allocaDummy[0x300]; 2995 Byte allocaDummy[0x300];
3016 allocaDummy[0] = 0; 2996 allocaDummy[0] = 0;
3017 allocaDummy[1] = allocaDummy[0]; 2997 allocaDummy[1] = allocaDummy[0];
@@ -3033,7 +3013,7 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
3033 } 3013 }
3034 } 3014 }
3035 3015
3036 LzmaEnc_Finish(p); 3016 LzmaEnc_Finish((CLzmaEncHandle)(void *)p);
3037 3017
3038 /* 3018 /*
3039 if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB)) 3019 if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&MFB))
@@ -3045,21 +3025,22 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
3045} 3025}
3046 3026
3047 3027
3048SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, 3028SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress,
3049 ISzAllocPtr alloc, ISzAllocPtr allocBig) 3029 ISzAllocPtr alloc, ISzAllocPtr allocBig)
3050{ 3030{
3051 RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig)); 3031 // GET_CLzmaEnc_p
3052 return LzmaEnc_Encode2((CLzmaEnc *)pp, progress); 3032 RINOK(LzmaEnc_Prepare(p, outStream, inStream, alloc, allocBig))
3033 return LzmaEnc_Encode2(p, progress);
3053} 3034}
3054 3035
3055 3036
3056SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) 3037SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *props, SizeT *size)
3057{ 3038{
3058 if (*size < LZMA_PROPS_SIZE) 3039 if (*size < LZMA_PROPS_SIZE)
3059 return SZ_ERROR_PARAM; 3040 return SZ_ERROR_PARAM;
3060 *size = LZMA_PROPS_SIZE; 3041 *size = LZMA_PROPS_SIZE;
3061 { 3042 {
3062 const CLzmaEnc *p = (const CLzmaEnc *)pp; 3043 // GET_CLzmaEnc_p
3063 const UInt32 dictSize = p->dictSize; 3044 const UInt32 dictSize = p->dictSize;
3064 UInt32 v; 3045 UInt32 v;
3065 props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); 3046 props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
@@ -3083,23 +3064,24 @@ SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
3083 while (v < dictSize); 3064 while (v < dictSize);
3084 } 3065 }
3085 3066
3086 SetUi32(props + 1, v); 3067 SetUi32(props + 1, v)
3087 return SZ_OK; 3068 return SZ_OK;
3088 } 3069 }
3089} 3070}
3090 3071
3091 3072
3092unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp) 3073unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p)
3093{ 3074{
3094 return (unsigned)((CLzmaEnc *)pp)->writeEndMark; 3075 // GET_CLzmaEnc_p
3076 return (unsigned)p->writeEndMark;
3095} 3077}
3096 3078
3097 3079
3098SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 3080SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
3099 int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) 3081 int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
3100{ 3082{
3101 SRes res; 3083 SRes res;
3102 CLzmaEnc *p = (CLzmaEnc *)pp; 3084 // GET_CLzmaEnc_p
3103 3085
3104 CLzmaEnc_SeqOutStreamBuf outStream; 3086 CLzmaEnc_SeqOutStreamBuf outStream;
3105 3087
@@ -3111,7 +3093,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte
3111 p->writeEndMark = writeEndMark; 3093 p->writeEndMark = writeEndMark;
3112 p->rc.outStream = &outStream.vt; 3094 p->rc.outStream = &outStream.vt;
3113 3095
3114 res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig); 3096 res = LzmaEnc_MemPrepare(p, src, srcLen, 0, alloc, allocBig);
3115 3097
3116 if (res == SZ_OK) 3098 if (res == SZ_OK)
3117 { 3099 {
@@ -3120,7 +3102,7 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte
3120 res = SZ_ERROR_FAIL; 3102 res = SZ_ERROR_FAIL;
3121 } 3103 }
3122 3104
3123 *destLen -= outStream.rem; 3105 *destLen -= (SizeT)outStream.rem;
3124 if (outStream.overflow) 3106 if (outStream.overflow)
3125 return SZ_ERROR_OUTPUT_EOF; 3107 return SZ_ERROR_OUTPUT_EOF;
3126 return res; 3108 return res;
@@ -3129,9 +3111,9 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte
3129 3111
3130SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 3112SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
3131 const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, 3113 const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
3132 ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig) 3114 ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
3133{ 3115{
3134 CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); 3116 CLzmaEncHandle p = LzmaEnc_Create(alloc);
3135 SRes res; 3117 SRes res;
3136 if (!p) 3118 if (!p)
3137 return SZ_ERROR_MEM; 3119 return SZ_ERROR_MEM;
@@ -3151,10 +3133,10 @@ SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
3151 3133
3152 3134
3153/* 3135/*
3154#ifndef _7ZIP_ST 3136#ifndef Z7_ST
3155void LzmaEnc_GetLzThreads(CLzmaEncHandle pp, HANDLE lz_threads[2]) 3137void LzmaEnc_GetLzThreads(CLzmaEncHandle p, HANDLE lz_threads[2])
3156{ 3138{
3157 const CLzmaEnc *p = (CLzmaEnc *)pp; 3139 GET_const_CLzmaEnc_p
3158 lz_threads[0] = p->matchFinderMt.hashSync.thread; 3140 lz_threads[0] = p->matchFinderMt.hashSync.thread;
3159 lz_threads[1] = p->matchFinderMt.btSync.thread; 3141 lz_threads[1] = p->matchFinderMt.btSync.thread;
3160} 3142}
diff --git a/C/LzmaEnc.h b/C/LzmaEnc.h
index bc2ed50..9f8039a 100644
--- a/C/LzmaEnc.h
+++ b/C/LzmaEnc.h
@@ -1,8 +1,8 @@
1/* LzmaEnc.h -- LZMA Encoder 1/* LzmaEnc.h -- LZMA Encoder
22019-10-30 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA_ENC_H 4#ifndef ZIP7_INC_LZMA_ENC_H
5#define __LZMA_ENC_H 5#define ZIP7_INC_LZMA_ENC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -10,7 +10,7 @@ EXTERN_C_BEGIN
10 10
11#define LZMA_PROPS_SIZE 5 11#define LZMA_PROPS_SIZE 5
12 12
13typedef struct _CLzmaEncProps 13typedef struct
14{ 14{
15 int level; /* 0 <= level <= 9 */ 15 int level; /* 0 <= level <= 9 */
16 UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version 16 UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version
@@ -23,10 +23,13 @@ typedef struct _CLzmaEncProps
23 int fb; /* 5 <= fb <= 273, default = 32 */ 23 int fb; /* 5 <= fb <= 273, default = 32 */
24 int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */ 24 int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */
25 int numHashBytes; /* 2, 3 or 4, default = 4 */ 25 int numHashBytes; /* 2, 3 or 4, default = 4 */
26 unsigned numHashOutBits; /* default = ? */
26 UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */ 27 UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */
27 unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */ 28 unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */
28 int numThreads; /* 1 or 2, default = 2 */ 29 int numThreads; /* 1 or 2, default = 2 */
29 30
31 // int _pad;
32
30 UInt64 reduceSize; /* estimated size of data that will be compressed. default = (UInt64)(Int64)-1. 33 UInt64 reduceSize; /* estimated size of data that will be compressed. default = (UInt64)(Int64)-1.
31 Encoder uses this value to reduce dictionary size */ 34 Encoder uses this value to reduce dictionary size */
32 35
@@ -51,7 +54,9 @@ SRes:
51 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version) 54 SZ_ERROR_THREAD - error in multithreading functions (only for Mt version)
52*/ 55*/
53 56
54typedef void * CLzmaEncHandle; 57typedef struct CLzmaEnc CLzmaEnc;
58typedef CLzmaEnc * CLzmaEncHandle;
59// Z7_DECLARE_HANDLE(CLzmaEncHandle)
55 60
56CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc); 61CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc);
57void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig); 62void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig);
@@ -61,17 +66,17 @@ void LzmaEnc_SetDataSize(CLzmaEncHandle p, UInt64 expectedDataSiize);
61SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); 66SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size);
62unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p); 67unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle p);
63 68
64SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, 69SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream,
65 ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); 70 ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig);
66SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 71SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
67 int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); 72 int writeEndMark, ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig);
68 73
69 74
70/* ---------- One Call Interface ---------- */ 75/* ---------- One Call Interface ---------- */
71 76
72SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 77SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
73 const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, 78 const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
74 ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig); 79 ICompressProgressPtr progress, ISzAllocPtr alloc, ISzAllocPtr allocBig);
75 80
76EXTERN_C_END 81EXTERN_C_END
77 82
diff --git a/C/LzmaLib.c b/C/LzmaLib.c
index 706e9e5..785e884 100644
--- a/C/LzmaLib.c
+++ b/C/LzmaLib.c
@@ -1,12 +1,14 @@
1/* LzmaLib.c -- LZMA library wrapper 1/* LzmaLib.c -- LZMA library wrapper
22015-06-13 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3
4#include "Precomp.h"
3 5
4#include "Alloc.h" 6#include "Alloc.h"
5#include "LzmaDec.h" 7#include "LzmaDec.h"
6#include "LzmaEnc.h" 8#include "LzmaEnc.h"
7#include "LzmaLib.h" 9#include "LzmaLib.h"
8 10
9MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, 11Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen,
10 unsigned char *outProps, size_t *outPropsSize, 12 unsigned char *outProps, size_t *outPropsSize,
11 int level, /* 0 <= level <= 9, default = 5 */ 13 int level, /* 0 <= level <= 9, default = 5 */
12 unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */ 14 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
32} 34}
33 35
34 36
35MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, 37Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen,
36 const unsigned char *props, size_t propsSize) 38 const unsigned char *props, size_t propsSize)
37{ 39{
38 ELzmaStatus status; 40 ELzmaStatus status;
diff --git a/C/LzmaLib.h b/C/LzmaLib.h
index c343a85..d7c0724 100644
--- a/C/LzmaLib.h
+++ b/C/LzmaLib.h
@@ -1,14 +1,14 @@
1/* LzmaLib.h -- LZMA library interface 1/* LzmaLib.h -- LZMA library interface
22021-04-03 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __LZMA_LIB_H 4#ifndef ZIP7_INC_LZMA_LIB_H
5#define __LZMA_LIB_H 5#define ZIP7_INC_LZMA_LIB_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11#define MY_STDAPI int MY_STD_CALL 11#define Z7_STDAPI int Z7_STDCALL
12 12
13#define LZMA_PROPS_SIZE 5 13#define LZMA_PROPS_SIZE 5
14 14
@@ -100,7 +100,7 @@ Returns:
100 SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) 100 SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
101*/ 101*/
102 102
103MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, 103Z7_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen,
104 unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */ 104 unsigned char *outProps, size_t *outPropsSize, /* *outPropsSize must be = 5 */
105 int level, /* 0 <= level <= 9, default = 5 */ 105 int level, /* 0 <= level <= 9, default = 5 */
106 unsigned dictSize, /* default = (1 << 24) */ 106 unsigned dictSize, /* default = (1 << 24) */
@@ -130,7 +130,7 @@ Returns:
130 SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer (src) 130 SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer (src)
131*/ 131*/
132 132
133MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen, 133Z7_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen,
134 const unsigned char *props, size_t propsSize); 134 const unsigned char *props, size_t propsSize);
135 135
136EXTERN_C_END 136EXTERN_C_END
diff --git a/C/MtCoder.c b/C/MtCoder.c
index 99dc909..6f58abb 100644
--- a/C/MtCoder.c
+++ b/C/MtCoder.c
@@ -1,28 +1,28 @@
1/* MtCoder.c -- Multi-thread Coder 1/* MtCoder.c -- Multi-thread Coder
22021-12-21 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#include "MtCoder.h" 6#include "MtCoder.h"
7 7
8#ifndef _7ZIP_ST 8#ifndef Z7_ST
9 9
10static SRes MtProgressThunk_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) 10static SRes MtProgressThunk_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize)
11{ 11{
12 CMtProgressThunk *thunk = CONTAINER_FROM_VTBL(pp, CMtProgressThunk, vt); 12 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CMtProgressThunk)
13 UInt64 inSize2 = 0; 13 UInt64 inSize2 = 0;
14 UInt64 outSize2 = 0; 14 UInt64 outSize2 = 0;
15 if (inSize != (UInt64)(Int64)-1) 15 if (inSize != (UInt64)(Int64)-1)
16 { 16 {
17 inSize2 = inSize - thunk->inSize; 17 inSize2 = inSize - p->inSize;
18 thunk->inSize = inSize; 18 p->inSize = inSize;
19 } 19 }
20 if (outSize != (UInt64)(Int64)-1) 20 if (outSize != (UInt64)(Int64)-1)
21 { 21 {
22 outSize2 = outSize - thunk->outSize; 22 outSize2 = outSize - p->outSize;
23 thunk->outSize = outSize; 23 p->outSize = outSize;
24 } 24 }
25 return MtProgress_ProgressAdd(thunk->mtProgress, inSize2, outSize2); 25 return MtProgress_ProgressAdd(p->mtProgress, inSize2, outSize2);
26} 26}
27 27
28 28
@@ -36,20 +36,12 @@ void MtProgressThunk_CreateVTable(CMtProgressThunk *p)
36#define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } 36#define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; }
37 37
38 38
39static WRes ArEvent_OptCreate_And_Reset(CEvent *p)
40{
41 if (Event_IsCreated(p))
42 return Event_Reset(p);
43 return AutoResetEvent_CreateNotSignaled(p);
44}
45
46
47static THREAD_FUNC_DECL ThreadFunc(void *pp); 39static THREAD_FUNC_DECL ThreadFunc(void *pp);
48 40
49 41
50static SRes MtCoderThread_CreateAndStart(CMtCoderThread *t) 42static SRes MtCoderThread_CreateAndStart(CMtCoderThread *t)
51{ 43{
52 WRes wres = ArEvent_OptCreate_And_Reset(&t->startEvent); 44 WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->startEvent);
53 if (wres == 0) 45 if (wres == 0)
54 { 46 {
55 t->stop = False; 47 t->stop = False;
@@ -84,24 +76,6 @@ static void MtCoderThread_Destruct(CMtCoderThread *t)
84 76
85 77
86 78
87static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize)
88{
89 size_t size = *processedSize;
90 *processedSize = 0;
91 while (size != 0)
92 {
93 size_t cur = size;
94 SRes res = ISeqInStream_Read(stream, data, &cur);
95 *processedSize += cur;
96 data += cur;
97 size -= cur;
98 RINOK(res);
99 if (cur == 0)
100 return SZ_OK;
101 }
102 return SZ_OK;
103}
104
105 79
106/* 80/*
107 ThreadFunc2() returns: 81 ThreadFunc2() returns:
@@ -152,7 +126,7 @@ static SRes ThreadFunc2(CMtCoderThread *t)
152 } 126 }
153 if (res == SZ_OK) 127 if (res == SZ_OK)
154 { 128 {
155 res = FullRead(mtc->inStream, t->inBuf, &size); 129 res = SeqInStream_ReadMax(mtc->inStream, t->inBuf, &size);
156 readProcessed = mtc->readProcessed + size; 130 readProcessed = mtc->readProcessed + size;
157 mtc->readProcessed = readProcessed; 131 mtc->readProcessed = readProcessed;
158 } 132 }
@@ -253,7 +227,7 @@ static SRes ThreadFunc2(CMtCoderThread *t)
253 block->finished = finished; 227 block->finished = finished;
254 } 228 }
255 229
256 #ifdef MTCODER__USE_WRITE_THREAD 230 #ifdef MTCODER_USE_WRITE_THREAD
257 RINOK_THREAD(Event_Set(&mtc->writeEvents[bi])) 231 RINOK_THREAD(Event_Set(&mtc->writeEvents[bi]))
258 #else 232 #else
259 { 233 {
@@ -352,7 +326,7 @@ static THREAD_FUNC_DECL ThreadFunc(void *pp)
352 MtProgress_SetError(&mtc->mtProgress, res); 326 MtProgress_SetError(&mtc->mtProgress, res);
353 } 327 }
354 328
355 #ifndef MTCODER__USE_WRITE_THREAD 329 #ifndef MTCODER_USE_WRITE_THREAD
356 { 330 {
357 unsigned numFinished = (unsigned)InterlockedIncrement(&mtc->numFinishedThreads); 331 unsigned numFinished = (unsigned)InterlockedIncrement(&mtc->numFinishedThreads);
358 if (numFinished == mtc->numStartedThreads) 332 if (numFinished == mtc->numStartedThreads)
@@ -389,7 +363,7 @@ void MtCoder_Construct(CMtCoder *p)
389 Event_Construct(&p->readEvent); 363 Event_Construct(&p->readEvent);
390 Semaphore_Construct(&p->blocksSemaphore); 364 Semaphore_Construct(&p->blocksSemaphore);
391 365
392 for (i = 0; i < MTCODER__THREADS_MAX; i++) 366 for (i = 0; i < MTCODER_THREADS_MAX; i++)
393 { 367 {
394 CMtCoderThread *t = &p->threads[i]; 368 CMtCoderThread *t = &p->threads[i];
395 t->mtCoder = p; 369 t->mtCoder = p;
@@ -397,11 +371,11 @@ void MtCoder_Construct(CMtCoder *p)
397 t->inBuf = NULL; 371 t->inBuf = NULL;
398 t->stop = False; 372 t->stop = False;
399 Event_Construct(&t->startEvent); 373 Event_Construct(&t->startEvent);
400 Thread_Construct(&t->thread); 374 Thread_CONSTRUCT(&t->thread)
401 } 375 }
402 376
403 #ifdef MTCODER__USE_WRITE_THREAD 377 #ifdef MTCODER_USE_WRITE_THREAD
404 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 378 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
405 Event_Construct(&p->writeEvents[i]); 379 Event_Construct(&p->writeEvents[i]);
406 #else 380 #else
407 Event_Construct(&p->finishedEvent); 381 Event_Construct(&p->finishedEvent);
@@ -424,14 +398,14 @@ static void MtCoder_Free(CMtCoder *p)
424 Event_Set(&p->readEvent); 398 Event_Set(&p->readEvent);
425 */ 399 */
426 400
427 for (i = 0; i < MTCODER__THREADS_MAX; i++) 401 for (i = 0; i < MTCODER_THREADS_MAX; i++)
428 MtCoderThread_Destruct(&p->threads[i]); 402 MtCoderThread_Destruct(&p->threads[i]);
429 403
430 Event_Close(&p->readEvent); 404 Event_Close(&p->readEvent);
431 Semaphore_Close(&p->blocksSemaphore); 405 Semaphore_Close(&p->blocksSemaphore);
432 406
433 #ifdef MTCODER__USE_WRITE_THREAD 407 #ifdef MTCODER_USE_WRITE_THREAD
434 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 408 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
435 Event_Close(&p->writeEvents[i]); 409 Event_Close(&p->writeEvents[i]);
436 #else 410 #else
437 Event_Close(&p->finishedEvent); 411 Event_Close(&p->finishedEvent);
@@ -455,20 +429,20 @@ SRes MtCoder_Code(CMtCoder *p)
455 unsigned i; 429 unsigned i;
456 SRes res = SZ_OK; 430 SRes res = SZ_OK;
457 431
458 if (numThreads > MTCODER__THREADS_MAX) 432 if (numThreads > MTCODER_THREADS_MAX)
459 numThreads = MTCODER__THREADS_MAX; 433 numThreads = MTCODER_THREADS_MAX;
460 numBlocksMax = MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads); 434 numBlocksMax = MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads);
461 435
462 if (p->blockSize < ((UInt32)1 << 26)) numBlocksMax++; 436 if (p->blockSize < ((UInt32)1 << 26)) numBlocksMax++;
463 if (p->blockSize < ((UInt32)1 << 24)) numBlocksMax++; 437 if (p->blockSize < ((UInt32)1 << 24)) numBlocksMax++;
464 if (p->blockSize < ((UInt32)1 << 22)) numBlocksMax++; 438 if (p->blockSize < ((UInt32)1 << 22)) numBlocksMax++;
465 439
466 if (numBlocksMax > MTCODER__BLOCKS_MAX) 440 if (numBlocksMax > MTCODER_BLOCKS_MAX)
467 numBlocksMax = MTCODER__BLOCKS_MAX; 441 numBlocksMax = MTCODER_BLOCKS_MAX;
468 442
469 if (p->blockSize != p->allocatedBufsSize) 443 if (p->blockSize != p->allocatedBufsSize)
470 { 444 {
471 for (i = 0; i < MTCODER__THREADS_MAX; i++) 445 for (i = 0; i < MTCODER_THREADS_MAX; i++)
472 { 446 {
473 CMtCoderThread *t = &p->threads[i]; 447 CMtCoderThread *t = &p->threads[i];
474 if (t->inBuf) 448 if (t->inBuf)
@@ -484,23 +458,23 @@ SRes MtCoder_Code(CMtCoder *p)
484 458
485 MtProgress_Init(&p->mtProgress, p->progress); 459 MtProgress_Init(&p->mtProgress, p->progress);
486 460
487 #ifdef MTCODER__USE_WRITE_THREAD 461 #ifdef MTCODER_USE_WRITE_THREAD
488 for (i = 0; i < numBlocksMax; i++) 462 for (i = 0; i < numBlocksMax; i++)
489 { 463 {
490 RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->writeEvents[i])); 464 RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->writeEvents[i]))
491 } 465 }
492 #else 466 #else
493 RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); 467 RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent))
494 #endif 468 #endif
495 469
496 { 470 {
497 RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->readEvent)); 471 RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->readEvent))
498 RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax)); 472 RINOK_THREAD(Semaphore_OptCreateInit(&p->blocksSemaphore, numBlocksMax, numBlocksMax))
499 } 473 }
500 474
501 for (i = 0; i < MTCODER__BLOCKS_MAX - 1; i++) 475 for (i = 0; i < MTCODER_BLOCKS_MAX - 1; i++)
502 p->freeBlockList[i] = i + 1; 476 p->freeBlockList[i] = i + 1;
503 p->freeBlockList[MTCODER__BLOCKS_MAX - 1] = (unsigned)(int)-1; 477 p->freeBlockList[MTCODER_BLOCKS_MAX - 1] = (unsigned)(int)-1;
504 p->freeBlockHead = 0; 478 p->freeBlockHead = 0;
505 479
506 p->readProcessed = 0; 480 p->readProcessed = 0;
@@ -508,10 +482,10 @@ SRes MtCoder_Code(CMtCoder *p)
508 p->numBlocksMax = numBlocksMax; 482 p->numBlocksMax = numBlocksMax;
509 p->stopReading = False; 483 p->stopReading = False;
510 484
511 #ifndef MTCODER__USE_WRITE_THREAD 485 #ifndef MTCODER_USE_WRITE_THREAD
512 p->writeIndex = 0; 486 p->writeIndex = 0;
513 p->writeRes = SZ_OK; 487 p->writeRes = SZ_OK;
514 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 488 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
515 p->ReadyBlocks[i] = False; 489 p->ReadyBlocks[i] = False;
516 p->numFinishedThreads = 0; 490 p->numFinishedThreads = 0;
517 #endif 491 #endif
@@ -522,12 +496,12 @@ SRes MtCoder_Code(CMtCoder *p)
522 // for (i = 0; i < numThreads; i++) 496 // for (i = 0; i < numThreads; i++)
523 { 497 {
524 CMtCoderThread *nextThread = &p->threads[p->numStartedThreads++]; 498 CMtCoderThread *nextThread = &p->threads[p->numStartedThreads++];
525 RINOK(MtCoderThread_CreateAndStart(nextThread)); 499 RINOK(MtCoderThread_CreateAndStart(nextThread))
526 } 500 }
527 501
528 RINOK_THREAD(Event_Set(&p->readEvent)) 502 RINOK_THREAD(Event_Set(&p->readEvent))
529 503
530 #ifdef MTCODER__USE_WRITE_THREAD 504 #ifdef MTCODER_USE_WRITE_THREAD
531 { 505 {
532 unsigned bi = 0; 506 unsigned bi = 0;
533 507
@@ -582,7 +556,7 @@ SRes MtCoder_Code(CMtCoder *p)
582 if (res == SZ_OK) 556 if (res == SZ_OK)
583 res = p->mtProgress.res; 557 res = p->mtProgress.res;
584 558
585 #ifndef MTCODER__USE_WRITE_THREAD 559 #ifndef MTCODER_USE_WRITE_THREAD
586 if (res == SZ_OK) 560 if (res == SZ_OK)
587 res = p->writeRes; 561 res = p->writeRes;
588 #endif 562 #endif
@@ -593,3 +567,5 @@ SRes MtCoder_Code(CMtCoder *p)
593} 567}
594 568
595#endif 569#endif
570
571#undef RINOK_THREAD
diff --git a/C/MtCoder.h b/C/MtCoder.h
index 5a5f4d1..1231d3c 100644
--- a/C/MtCoder.h
+++ b/C/MtCoder.h
@@ -1,30 +1,30 @@
1/* MtCoder.h -- Multi-thread Coder 1/* MtCoder.h -- Multi-thread Coder
22018-07-04 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __MT_CODER_H 4#ifndef ZIP7_INC_MT_CODER_H
5#define __MT_CODER_H 5#define ZIP7_INC_MT_CODER_H
6 6
7#include "MtDec.h" 7#include "MtDec.h"
8 8
9EXTERN_C_BEGIN 9EXTERN_C_BEGIN
10 10
11/* 11/*
12 if ( defined MTCODER__USE_WRITE_THREAD) : main thread writes all data blocks to output stream 12 if ( defined MTCODER_USE_WRITE_THREAD) : main thread writes all data blocks to output stream
13 if (not defined MTCODER__USE_WRITE_THREAD) : any coder thread can write data blocks to output stream 13 if (not defined MTCODER_USE_WRITE_THREAD) : any coder thread can write data blocks to output stream
14*/ 14*/
15/* #define MTCODER__USE_WRITE_THREAD */ 15/* #define MTCODER_USE_WRITE_THREAD */
16 16
17#ifndef _7ZIP_ST 17#ifndef Z7_ST
18 #define MTCODER__GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1) 18 #define MTCODER_GET_NUM_BLOCKS_FROM_THREADS(numThreads) ((numThreads) + (numThreads) / 8 + 1)
19 #define MTCODER__THREADS_MAX 64 19 #define MTCODER_THREADS_MAX 64
20 #define MTCODER__BLOCKS_MAX (MTCODER__GET_NUM_BLOCKS_FROM_THREADS(MTCODER__THREADS_MAX) + 3) 20 #define MTCODER_BLOCKS_MAX (MTCODER_GET_NUM_BLOCKS_FROM_THREADS(MTCODER_THREADS_MAX) + 3)
21#else 21#else
22 #define MTCODER__THREADS_MAX 1 22 #define MTCODER_THREADS_MAX 1
23 #define MTCODER__BLOCKS_MAX 1 23 #define MTCODER_BLOCKS_MAX 1
24#endif 24#endif
25 25
26 26
27#ifndef _7ZIP_ST 27#ifndef Z7_ST
28 28
29 29
30typedef struct 30typedef struct
@@ -37,15 +37,15 @@ typedef struct
37 37
38void MtProgressThunk_CreateVTable(CMtProgressThunk *p); 38void MtProgressThunk_CreateVTable(CMtProgressThunk *p);
39 39
40#define MtProgressThunk_Init(p) { (p)->inSize = 0; (p)->outSize = 0; } 40#define MtProgressThunk_INIT(p) { (p)->inSize = 0; (p)->outSize = 0; }
41 41
42 42
43struct _CMtCoder; 43struct CMtCoder_;
44 44
45 45
46typedef struct 46typedef struct
47{ 47{
48 struct _CMtCoder *mtCoder; 48 struct CMtCoder_ *mtCoder;
49 unsigned index; 49 unsigned index;
50 int stop; 50 int stop;
51 Byte *inBuf; 51 Byte *inBuf;
@@ -71,7 +71,7 @@ typedef struct
71} CMtCoderBlock; 71} CMtCoderBlock;
72 72
73 73
74typedef struct _CMtCoder 74typedef struct CMtCoder_
75{ 75{
76 /* input variables */ 76 /* input variables */
77 77
@@ -79,11 +79,11 @@ typedef struct _CMtCoder
79 unsigned numThreadsMax; 79 unsigned numThreadsMax;
80 UInt64 expectedDataSize; 80 UInt64 expectedDataSize;
81 81
82 ISeqInStream *inStream; 82 ISeqInStreamPtr inStream;
83 const Byte *inData; 83 const Byte *inData;
84 size_t inDataSize; 84 size_t inDataSize;
85 85
86 ICompressProgress *progress; 86 ICompressProgressPtr progress;
87 ISzAllocPtr allocBig; 87 ISzAllocPtr allocBig;
88 88
89 IMtCoderCallback2 *mtCallback; 89 IMtCoderCallback2 *mtCallback;
@@ -100,13 +100,13 @@ typedef struct _CMtCoder
100 BoolInt stopReading; 100 BoolInt stopReading;
101 SRes readRes; 101 SRes readRes;
102 102
103 #ifdef MTCODER__USE_WRITE_THREAD 103 #ifdef MTCODER_USE_WRITE_THREAD
104 CAutoResetEvent writeEvents[MTCODER__BLOCKS_MAX]; 104 CAutoResetEvent writeEvents[MTCODER_BLOCKS_MAX];
105 #else 105 #else
106 CAutoResetEvent finishedEvent; 106 CAutoResetEvent finishedEvent;
107 SRes writeRes; 107 SRes writeRes;
108 unsigned writeIndex; 108 unsigned writeIndex;
109 Byte ReadyBlocks[MTCODER__BLOCKS_MAX]; 109 Byte ReadyBlocks[MTCODER_BLOCKS_MAX];
110 LONG numFinishedThreads; 110 LONG numFinishedThreads;
111 #endif 111 #endif
112 112
@@ -120,11 +120,11 @@ typedef struct _CMtCoder
120 CCriticalSection cs; 120 CCriticalSection cs;
121 121
122 unsigned freeBlockHead; 122 unsigned freeBlockHead;
123 unsigned freeBlockList[MTCODER__BLOCKS_MAX]; 123 unsigned freeBlockList[MTCODER_BLOCKS_MAX];
124 124
125 CMtProgress mtProgress; 125 CMtProgress mtProgress;
126 CMtCoderBlock blocks[MTCODER__BLOCKS_MAX]; 126 CMtCoderBlock blocks[MTCODER_BLOCKS_MAX];
127 CMtCoderThread threads[MTCODER__THREADS_MAX]; 127 CMtCoderThread threads[MTCODER_THREADS_MAX];
128} CMtCoder; 128} CMtCoder;
129 129
130 130
diff --git a/C/MtDec.c b/C/MtDec.c
index 45a6713..7820699 100644
--- a/C/MtDec.c
+++ b/C/MtDec.c
@@ -1,5 +1,5 @@
1/* MtDec.c -- Multi-thread Decoder 1/* MtDec.c -- Multi-thread Decoder
22021-12-21 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -14,7 +14,7 @@
14 14
15#include "MtDec.h" 15#include "MtDec.h"
16 16
17#ifndef _7ZIP_ST 17#ifndef Z7_ST
18 18
19#ifdef SHOW_DEBUG_INFO 19#ifdef SHOW_DEBUG_INFO
20#define PRF(x) x 20#define PRF(x) x
@@ -24,7 +24,7 @@
24 24
25#define PRF_STR_INT(s, d) PRF(printf("\n" s " %d\n", (unsigned)d)) 25#define PRF_STR_INT(s, d) PRF(printf("\n" s " %d\n", (unsigned)d))
26 26
27void MtProgress_Init(CMtProgress *p, ICompressProgress *progress) 27void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress)
28{ 28{
29 p->progress = progress; 29 p->progress = progress;
30 p->res = SZ_OK; 30 p->res = SZ_OK;
@@ -81,36 +81,28 @@ void MtProgress_SetError(CMtProgress *p, SRes res)
81#define RINOK_THREAD(x) RINOK_WRes(x) 81#define RINOK_THREAD(x) RINOK_WRes(x)
82 82
83 83
84static WRes ArEvent_OptCreate_And_Reset(CEvent *p) 84struct CMtDecBufLink_
85{ 85{
86 if (Event_IsCreated(p)) 86 struct CMtDecBufLink_ *next;
87 return Event_Reset(p);
88 return AutoResetEvent_CreateNotSignaled(p);
89}
90
91
92struct __CMtDecBufLink
93{
94 struct __CMtDecBufLink *next;
95 void *pad[3]; 87 void *pad[3];
96}; 88};
97 89
98typedef struct __CMtDecBufLink CMtDecBufLink; 90typedef struct CMtDecBufLink_ CMtDecBufLink;
99 91
100#define MTDEC__LINK_DATA_OFFSET sizeof(CMtDecBufLink) 92#define MTDEC__LINK_DATA_OFFSET sizeof(CMtDecBufLink)
101#define MTDEC__DATA_PTR_FROM_LINK(link) ((Byte *)(link) + MTDEC__LINK_DATA_OFFSET) 93#define MTDEC__DATA_PTR_FROM_LINK(link) ((Byte *)(link) + MTDEC__LINK_DATA_OFFSET)
102 94
103 95
104 96
105static THREAD_FUNC_DECL ThreadFunc(void *pp); 97static THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp);
106 98
107 99
108static WRes MtDecThread_CreateEvents(CMtDecThread *t) 100static WRes MtDecThread_CreateEvents(CMtDecThread *t)
109{ 101{
110 WRes wres = ArEvent_OptCreate_And_Reset(&t->canWrite); 102 WRes wres = AutoResetEvent_OptCreate_And_Reset(&t->canWrite);
111 if (wres == 0) 103 if (wres == 0)
112 { 104 {
113 wres = ArEvent_OptCreate_And_Reset(&t->canRead); 105 wres = AutoResetEvent_OptCreate_And_Reset(&t->canRead);
114 if (wres == 0) 106 if (wres == 0)
115 return SZ_OK; 107 return SZ_OK;
116 } 108 }
@@ -126,7 +118,7 @@ static SRes MtDecThread_CreateAndStart(CMtDecThread *t)
126 { 118 {
127 if (Thread_WasCreated(&t->thread)) 119 if (Thread_WasCreated(&t->thread))
128 return SZ_OK; 120 return SZ_OK;
129 wres = Thread_Create(&t->thread, ThreadFunc, t); 121 wres = Thread_Create(&t->thread, MtDec_ThreadFunc, t);
130 if (wres == 0) 122 if (wres == 0)
131 return SZ_OK; 123 return SZ_OK;
132 } 124 }
@@ -167,7 +159,7 @@ static void MtDecThread_CloseThread(CMtDecThread *t)
167static void MtDec_CloseThreads(CMtDec *p) 159static void MtDec_CloseThreads(CMtDec *p)
168{ 160{
169 unsigned i; 161 unsigned i;
170 for (i = 0; i < MTDEC__THREADS_MAX; i++) 162 for (i = 0; i < MTDEC_THREADS_MAX; i++)
171 MtDecThread_CloseThread(&p->threads[i]); 163 MtDecThread_CloseThread(&p->threads[i]);
172} 164}
173 165
@@ -179,25 +171,6 @@ static void MtDecThread_Destruct(CMtDecThread *t)
179 171
180 172
181 173
182static SRes FullRead(ISeqInStream *stream, Byte *data, size_t *processedSize)
183{
184 size_t size = *processedSize;
185 *processedSize = 0;
186 while (size != 0)
187 {
188 size_t cur = size;
189 SRes res = ISeqInStream_Read(stream, data, &cur);
190 *processedSize += cur;
191 data += cur;
192 size -= cur;
193 RINOK(res);
194 if (cur == 0)
195 return SZ_OK;
196 }
197 return SZ_OK;
198}
199
200
201static SRes MtDec_GetError_Spec(CMtDec *p, UInt64 interruptIndex, BoolInt *wasInterrupted) 174static SRes MtDec_GetError_Spec(CMtDec *p, UInt64 interruptIndex, BoolInt *wasInterrupted)
202{ 175{
203 SRes res; 176 SRes res;
@@ -253,7 +226,7 @@ Byte *MtDec_GetCrossBuff(CMtDec *p)
253 226
254 227
255/* 228/*
256 ThreadFunc2() returns: 229 MtDec_ThreadFunc2() returns:
257 0 - in all normal cases (even for stream error or memory allocation error) 230 0 - in all normal cases (even for stream error or memory allocation error)
258 (!= 0) - WRes error return by system threading function 231 (!= 0) - WRes error return by system threading function
259*/ 232*/
@@ -261,11 +234,11 @@ Byte *MtDec_GetCrossBuff(CMtDec *p)
261// #define MTDEC_ProgessStep (1 << 22) 234// #define MTDEC_ProgessStep (1 << 22)
262#define MTDEC_ProgessStep (1 << 0) 235#define MTDEC_ProgessStep (1 << 0)
263 236
264static WRes ThreadFunc2(CMtDecThread *t) 237static WRes MtDec_ThreadFunc2(CMtDecThread *t)
265{ 238{
266 CMtDec *p = t->mtDec; 239 CMtDec *p = t->mtDec;
267 240
268 PRF_STR_INT("ThreadFunc2", t->index); 241 PRF_STR_INT("MtDec_ThreadFunc2", t->index)
269 242
270 // SetThreadAffinityMask(GetCurrentThread(), 1 << t->index); 243 // SetThreadAffinityMask(GetCurrentThread(), 1 << t->index);
271 244
@@ -295,13 +268,13 @@ static WRes ThreadFunc2(CMtDecThread *t)
295 // CMtDecCallbackInfo parse; 268 // CMtDecCallbackInfo parse;
296 CMtDecThread *nextThread; 269 CMtDecThread *nextThread;
297 270
298 PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index); 271 PRF_STR_INT("=============== Event_Wait(&t->canRead)", t->index)
299 272
300 RINOK_THREAD(Event_Wait(&t->canRead)); 273 RINOK_THREAD(Event_Wait(&t->canRead))
301 if (p->exitThread) 274 if (p->exitThread)
302 return 0; 275 return 0;
303 276
304 PRF_STR_INT("after Event_Wait(&t->canRead)", t->index); 277 PRF_STR_INT("after Event_Wait(&t->canRead)", t->index)
305 278
306 // if (t->index == 3) return 19; // for test 279 // if (t->index == 3) return 19; // for test
307 280
@@ -373,7 +346,7 @@ static WRes ThreadFunc2(CMtDecThread *t)
373 { 346 {
374 size = p->inBufSize; 347 size = p->inBufSize;
375 348
376 res = FullRead(p->inStream, data, &size); 349 res = SeqInStream_ReadMax(p->inStream, data, &size);
377 350
378 // size = 10; // test 351 // size = 10; // test
379 352
@@ -615,7 +588,7 @@ static WRes ThreadFunc2(CMtDecThread *t)
615 // if ( !finish ) we must call Event_Set(&nextThread->canWrite) in any case 588 // if ( !finish ) we must call Event_Set(&nextThread->canWrite) in any case
616 // if ( finish ) we switch to single-thread mode and there are 2 ways at the end of current iteration (current block): 589 // if ( finish ) we switch to single-thread mode and there are 2 ways at the end of current iteration (current block):
617 // - if (needContinue) after Write(&needContinue), we restore decoding with new iteration 590 // - if (needContinue) after Write(&needContinue), we restore decoding with new iteration
618 // - otherwise we stop decoding and exit from ThreadFunc2() 591 // - otherwise we stop decoding and exit from MtDec_ThreadFunc2()
619 592
620 // Don't change (finish) variable in the further code 593 // Don't change (finish) variable in the further code
621 594
@@ -688,7 +661,7 @@ static WRes ThreadFunc2(CMtDecThread *t)
688 661
689 // ---------- WRITE ---------- 662 // ---------- WRITE ----------
690 663
691 RINOK_THREAD(Event_Wait(&t->canWrite)); 664 RINOK_THREAD(Event_Wait(&t->canWrite))
692 665
693 { 666 {
694 BoolInt isErrorMode = False; 667 BoolInt isErrorMode = False;
@@ -801,14 +774,14 @@ static WRes ThreadFunc2(CMtDecThread *t)
801 774
802 if (!finish) 775 if (!finish)
803 { 776 {
804 RINOK_THREAD(Event_Set(&nextThread->canWrite)); 777 RINOK_THREAD(Event_Set(&nextThread->canWrite))
805 } 778 }
806 else 779 else
807 { 780 {
808 if (needContinue) 781 if (needContinue)
809 { 782 {
810 // we restore decoding with new iteration 783 // we restore decoding with new iteration
811 RINOK_THREAD(Event_Set(&p->threads[0].canWrite)); 784 RINOK_THREAD(Event_Set(&p->threads[0].canWrite))
812 } 785 }
813 else 786 else
814 { 787 {
@@ -817,7 +790,7 @@ static WRes ThreadFunc2(CMtDecThread *t)
817 return SZ_OK; 790 return SZ_OK;
818 p->exitThread = True; 791 p->exitThread = True;
819 } 792 }
820 RINOK_THREAD(Event_Set(&p->threads[0].canRead)); 793 RINOK_THREAD(Event_Set(&p->threads[0].canRead))
821 } 794 }
822 } 795 }
823 } 796 }
@@ -836,7 +809,7 @@ static WRes ThreadFunc2(CMtDecThread *t)
836#endif 809#endif
837 810
838 811
839static THREAD_FUNC_DECL ThreadFunc1(void *pp) 812static THREAD_FUNC_DECL MtDec_ThreadFunc1(void *pp)
840{ 813{
841 WRes res; 814 WRes res;
842 815
@@ -845,7 +818,7 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp)
845 818
846 // fprintf(stdout, "\n%d = %p\n", t->index, &t); 819 // fprintf(stdout, "\n%d = %p\n", t->index, &t);
847 820
848 res = ThreadFunc2(t); 821 res = MtDec_ThreadFunc2(t);
849 p = t->mtDec; 822 p = t->mtDec;
850 if (res == 0) 823 if (res == 0)
851 return (THREAD_FUNC_RET_TYPE)(UINT_PTR)p->exitThreadWRes; 824 return (THREAD_FUNC_RET_TYPE)(UINT_PTR)p->exitThreadWRes;
@@ -862,14 +835,14 @@ static THREAD_FUNC_DECL ThreadFunc1(void *pp)
862 return (THREAD_FUNC_RET_TYPE)(UINT_PTR)res; 835 return (THREAD_FUNC_RET_TYPE)(UINT_PTR)res;
863} 836}
864 837
865static MY_NO_INLINE THREAD_FUNC_DECL ThreadFunc(void *pp) 838static Z7_NO_INLINE THREAD_FUNC_DECL MtDec_ThreadFunc(void *pp)
866{ 839{
867 #ifdef USE_ALLOCA 840 #ifdef USE_ALLOCA
868 CMtDecThread *t = (CMtDecThread *)pp; 841 CMtDecThread *t = (CMtDecThread *)pp;
869 // fprintf(stderr, "\n%d = %p - before", t->index, &t); 842 // fprintf(stderr, "\n%d = %p - before", t->index, &t);
870 t->allocaPtr = alloca(t->index * 128); 843 t->allocaPtr = alloca(t->index * 128);
871 #endif 844 #endif
872 return ThreadFunc1(pp); 845 return MtDec_ThreadFunc1(pp);
873} 846}
874 847
875 848
@@ -883,7 +856,7 @@ int MtDec_PrepareRead(CMtDec *p)
883 856
884 { 857 {
885 unsigned i; 858 unsigned i;
886 for (i = 0; i < MTDEC__THREADS_MAX; i++) 859 for (i = 0; i < MTDEC_THREADS_MAX; i++)
887 if (i > p->numStartedThreads 860 if (i > p->numStartedThreads
888 || p->numFilledThreads <= 861 || p->numFilledThreads <=
889 (i >= p->filledThreadStart ? 862 (i >= p->filledThreadStart ?
@@ -987,7 +960,7 @@ void MtDec_Construct(CMtDec *p)
987 960
988 p->allocatedBufsSize = 0; 961 p->allocatedBufsSize = 0;
989 962
990 for (i = 0; i < MTDEC__THREADS_MAX; i++) 963 for (i = 0; i < MTDEC_THREADS_MAX; i++)
991 { 964 {
992 CMtDecThread *t = &p->threads[i]; 965 CMtDecThread *t = &p->threads[i];
993 t->mtDec = p; 966 t->mtDec = p;
@@ -995,7 +968,7 @@ void MtDec_Construct(CMtDec *p)
995 t->inBuf = NULL; 968 t->inBuf = NULL;
996 Event_Construct(&t->canRead); 969 Event_Construct(&t->canRead);
997 Event_Construct(&t->canWrite); 970 Event_Construct(&t->canWrite);
998 Thread_Construct(&t->thread); 971 Thread_CONSTRUCT(&t->thread)
999 } 972 }
1000 973
1001 // Event_Construct(&p->finishedEvent); 974 // Event_Construct(&p->finishedEvent);
@@ -1010,7 +983,7 @@ static void MtDec_Free(CMtDec *p)
1010 983
1011 p->exitThread = True; 984 p->exitThread = True;
1012 985
1013 for (i = 0; i < MTDEC__THREADS_MAX; i++) 986 for (i = 0; i < MTDEC_THREADS_MAX; i++)
1014 MtDecThread_Destruct(&p->threads[i]); 987 MtDecThread_Destruct(&p->threads[i]);
1015 988
1016 // Event_Close(&p->finishedEvent); 989 // Event_Close(&p->finishedEvent);
@@ -1061,15 +1034,15 @@ SRes MtDec_Code(CMtDec *p)
1061 1034
1062 { 1035 {
1063 unsigned numThreads = p->numThreadsMax; 1036 unsigned numThreads = p->numThreadsMax;
1064 if (numThreads > MTDEC__THREADS_MAX) 1037 if (numThreads > MTDEC_THREADS_MAX)
1065 numThreads = MTDEC__THREADS_MAX; 1038 numThreads = MTDEC_THREADS_MAX;
1066 p->numStartedThreads_Limit = numThreads; 1039 p->numStartedThreads_Limit = numThreads;
1067 p->numStartedThreads = 0; 1040 p->numStartedThreads = 0;
1068 } 1041 }
1069 1042
1070 if (p->inBufSize != p->allocatedBufsSize) 1043 if (p->inBufSize != p->allocatedBufsSize)
1071 { 1044 {
1072 for (i = 0; i < MTDEC__THREADS_MAX; i++) 1045 for (i = 0; i < MTDEC_THREADS_MAX; i++)
1073 { 1046 {
1074 CMtDecThread *t = &p->threads[i]; 1047 CMtDecThread *t = &p->threads[i];
1075 if (t->inBuf) 1048 if (t->inBuf)
@@ -1086,7 +1059,7 @@ SRes MtDec_Code(CMtDec *p)
1086 1059
1087 MtProgress_Init(&p->mtProgress, p->progress); 1060 MtProgress_Init(&p->mtProgress, p->progress);
1088 1061
1089 // RINOK_THREAD(ArEvent_OptCreate_And_Reset(&p->finishedEvent)); 1062 // RINOK_THREAD(AutoResetEvent_OptCreate_And_Reset(&p->finishedEvent))
1090 p->exitThread = False; 1063 p->exitThread = False;
1091 p->exitThreadWRes = 0; 1064 p->exitThreadWRes = 0;
1092 1065
@@ -1098,7 +1071,7 @@ SRes MtDec_Code(CMtDec *p)
1098 wres = MtDecThread_CreateEvents(nextThread); 1071 wres = MtDecThread_CreateEvents(nextThread);
1099 if (wres == 0) { wres = Event_Set(&nextThread->canWrite); 1072 if (wres == 0) { wres = Event_Set(&nextThread->canWrite);
1100 if (wres == 0) { wres = Event_Set(&nextThread->canRead); 1073 if (wres == 0) { wres = Event_Set(&nextThread->canRead);
1101 if (wres == 0) { THREAD_FUNC_RET_TYPE res = ThreadFunc(nextThread); 1074 if (wres == 0) { THREAD_FUNC_RET_TYPE res = MtDec_ThreadFunc(nextThread);
1102 wres = (WRes)(UINT_PTR)res; 1075 wres = (WRes)(UINT_PTR)res;
1103 if (wres != 0) 1076 if (wres != 0)
1104 { 1077 {
@@ -1137,3 +1110,5 @@ SRes MtDec_Code(CMtDec *p)
1137} 1110}
1138 1111
1139#endif 1112#endif
1113
1114#undef PRF
diff --git a/C/MtDec.h b/C/MtDec.h
index c2da46a..c28e8d9 100644
--- a/C/MtDec.h
+++ b/C/MtDec.h
@@ -1,46 +1,46 @@
1/* MtDec.h -- Multi-thread Decoder 1/* MtDec.h -- Multi-thread Decoder
22020-03-05 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __MT_DEC_H 4#ifndef ZIP7_INC_MT_DEC_H
5#define __MT_DEC_H 5#define ZIP7_INC_MT_DEC_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
9#ifndef _7ZIP_ST 9#ifndef Z7_ST
10#include "Threads.h" 10#include "Threads.h"
11#endif 11#endif
12 12
13EXTERN_C_BEGIN 13EXTERN_C_BEGIN
14 14
15#ifndef _7ZIP_ST 15#ifndef Z7_ST
16 16
17#ifndef _7ZIP_ST 17#ifndef Z7_ST
18 #define MTDEC__THREADS_MAX 32 18 #define MTDEC_THREADS_MAX 32
19#else 19#else
20 #define MTDEC__THREADS_MAX 1 20 #define MTDEC_THREADS_MAX 1
21#endif 21#endif
22 22
23 23
24typedef struct 24typedef struct
25{ 25{
26 ICompressProgress *progress; 26 ICompressProgressPtr progress;
27 SRes res; 27 SRes res;
28 UInt64 totalInSize; 28 UInt64 totalInSize;
29 UInt64 totalOutSize; 29 UInt64 totalOutSize;
30 CCriticalSection cs; 30 CCriticalSection cs;
31} CMtProgress; 31} CMtProgress;
32 32
33void MtProgress_Init(CMtProgress *p, ICompressProgress *progress); 33void MtProgress_Init(CMtProgress *p, ICompressProgressPtr progress);
34SRes MtProgress_Progress_ST(CMtProgress *p); 34SRes MtProgress_Progress_ST(CMtProgress *p);
35SRes MtProgress_ProgressAdd(CMtProgress *p, UInt64 inSize, UInt64 outSize); 35SRes MtProgress_ProgressAdd(CMtProgress *p, UInt64 inSize, UInt64 outSize);
36SRes MtProgress_GetError(CMtProgress *p); 36SRes MtProgress_GetError(CMtProgress *p);
37void MtProgress_SetError(CMtProgress *p, SRes res); 37void MtProgress_SetError(CMtProgress *p, SRes res);
38 38
39struct _CMtDec; 39struct CMtDec;
40 40
41typedef struct 41typedef struct
42{ 42{
43 struct _CMtDec *mtDec; 43 struct CMtDec_ *mtDec;
44 unsigned index; 44 unsigned index;
45 void *inBuf; 45 void *inBuf;
46 46
@@ -117,7 +117,7 @@ typedef struct
117 117
118 118
119 119
120typedef struct _CMtDec 120typedef struct CMtDec_
121{ 121{
122 /* input variables */ 122 /* input variables */
123 123
@@ -126,11 +126,11 @@ typedef struct _CMtDec
126 // size_t inBlockMax; 126 // size_t inBlockMax;
127 unsigned numThreadsMax_2; 127 unsigned numThreadsMax_2;
128 128
129 ISeqInStream *inStream; 129 ISeqInStreamPtr inStream;
130 // const Byte *inData; 130 // const Byte *inData;
131 // size_t inDataSize; 131 // size_t inDataSize;
132 132
133 ICompressProgress *progress; 133 ICompressProgressPtr progress;
134 ISzAllocPtr alloc; 134 ISzAllocPtr alloc;
135 135
136 IMtDecCallback2 *mtCallback; 136 IMtDecCallback2 *mtCallback;
@@ -171,11 +171,11 @@ typedef struct _CMtDec
171 unsigned filledThreadStart; 171 unsigned filledThreadStart;
172 unsigned numFilledThreads; 172 unsigned numFilledThreads;
173 173
174 #ifndef _7ZIP_ST 174 #ifndef Z7_ST
175 BoolInt needInterrupt; 175 BoolInt needInterrupt;
176 UInt64 interruptIndex; 176 UInt64 interruptIndex;
177 CMtProgress mtProgress; 177 CMtProgress mtProgress;
178 CMtDecThread threads[MTDEC__THREADS_MAX]; 178 CMtDecThread threads[MTDEC_THREADS_MAX];
179 #endif 179 #endif
180} CMtDec; 180} CMtDec;
181 181
diff --git a/C/Ppmd.h b/C/Ppmd.h
index b198792..66b2626 100644
--- a/C/Ppmd.h
+++ b/C/Ppmd.h
@@ -1,9 +1,9 @@
1/* Ppmd.h -- PPMD codec common code 1/* Ppmd.h -- PPMD codec common code
22021-04-13 : Igor Pavlov : Public domain 22023-03-05 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ 3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 4
5#ifndef __PPMD_H 5#ifndef ZIP7_INC_PPMD_H
6#define __PPMD_H 6#define ZIP7_INC_PPMD_H
7 7
8#include "CpuArch.h" 8#include "CpuArch.h"
9 9
@@ -48,8 +48,10 @@ typedef struct
48 Byte Count; /* Count to next change of Shift */ 48 Byte Count; /* Count to next change of Shift */
49} CPpmd_See; 49} CPpmd_See;
50 50
51#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \ 51#define Ppmd_See_UPDATE(p) \
52 { (p)->Summ = (UInt16)((p)->Summ << 1); (p)->Count = (Byte)(3 << (p)->Shift++); } 52 { if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \
53 { (p)->Summ = (UInt16)((p)->Summ << 1); \
54 (p)->Count = (Byte)(3 << (p)->Shift++); }}
53 55
54 56
55typedef struct 57typedef struct
diff --git a/C/Ppmd7.c b/C/Ppmd7.c
index cf401cb..6e1307e 100644
--- a/C/Ppmd7.c
+++ b/C/Ppmd7.c
@@ -1,5 +1,5 @@
1/* Ppmd7.c -- PPMdH codec 1/* Ppmd7.c -- PPMdH codec
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */ 3This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
4 4
5#include "Precomp.h" 5#include "Precomp.h"
@@ -14,7 +14,7 @@ This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
14MY_ALIGN(16) 14MY_ALIGN(16)
15static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; 15static const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
16MY_ALIGN(16) 16MY_ALIGN(16)
17static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; 17static const UInt16 PPMD7_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
18 18
19#define MAX_FREQ 124 19#define MAX_FREQ 124
20#define UNIT_SIZE 12 20#define UNIT_SIZE 12
@@ -33,7 +33,7 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x
33#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx) 33#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx)
34#define SUFFIX(ctx) CTX((ctx)->Suffix) 34#define SUFFIX(ctx) CTX((ctx)->Suffix)
35 35
36typedef CPpmd7_Context * CTX_PTR; 36typedef CPpmd7_Context * PPMD7_CTX_PTR;
37 37
38struct CPpmd7_Node_; 38struct CPpmd7_Node_;
39 39
@@ -107,14 +107,14 @@ BoolInt Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAllocPtr alloc)
107// ---------- Internal Memory Allocator ---------- 107// ---------- Internal Memory Allocator ----------
108 108
109/* We can use CPpmd7_Node in list of free units (as in Ppmd8) 109/* We can use CPpmd7_Node in list of free units (as in Ppmd8)
110 But we still need one additional list walk pass in GlueFreeBlocks(). 110 But we still need one additional list walk pass in Ppmd7_GlueFreeBlocks().
111 So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in InsertNode() / RemoveNode() 111 So we use simple CPpmd_Void_Ref instead of CPpmd7_Node in Ppmd7_InsertNode() / Ppmd7_RemoveNode()
112*/ 112*/
113 113
114#define EMPTY_NODE 0 114#define EMPTY_NODE 0
115 115
116 116
117static void InsertNode(CPpmd7 *p, void *node, unsigned indx) 117static void Ppmd7_InsertNode(CPpmd7 *p, void *node, unsigned indx)
118{ 118{
119 *((CPpmd_Void_Ref *)node) = p->FreeList[indx]; 119 *((CPpmd_Void_Ref *)node) = p->FreeList[indx];
120 // ((CPpmd7_Node *)node)->Next = (CPpmd7_Node_Ref)p->FreeList[indx]; 120 // ((CPpmd7_Node *)node)->Next = (CPpmd7_Node_Ref)p->FreeList[indx];
@@ -124,7 +124,7 @@ static void InsertNode(CPpmd7 *p, void *node, unsigned indx)
124} 124}
125 125
126 126
127static void *RemoveNode(CPpmd7 *p, unsigned indx) 127static void *Ppmd7_RemoveNode(CPpmd7 *p, unsigned indx)
128{ 128{
129 CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]); 129 CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]);
130 p->FreeList[indx] = *node; 130 p->FreeList[indx] = *node;
@@ -134,32 +134,32 @@ static void *RemoveNode(CPpmd7 *p, unsigned indx)
134} 134}
135 135
136 136
137static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx) 137static void Ppmd7_SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
138{ 138{
139 unsigned i, nu = I2U(oldIndx) - I2U(newIndx); 139 unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
140 ptr = (Byte *)ptr + U2B(I2U(newIndx)); 140 ptr = (Byte *)ptr + U2B(I2U(newIndx));
141 if (I2U(i = U2I(nu)) != nu) 141 if (I2U(i = U2I(nu)) != nu)
142 { 142 {
143 unsigned k = I2U(--i); 143 unsigned k = I2U(--i);
144 InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); 144 Ppmd7_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1);
145 } 145 }
146 InsertNode(p, ptr, i); 146 Ppmd7_InsertNode(p, ptr, i);
147} 147}
148 148
149 149
150/* we use CPpmd7_Node_Union union to solve XLC -O2 strict pointer aliasing problem */ 150/* we use CPpmd7_Node_Union union to solve XLC -O2 strict pointer aliasing problem */
151 151
152typedef union _CPpmd7_Node_Union 152typedef union
153{ 153{
154 CPpmd7_Node Node; 154 CPpmd7_Node Node;
155 CPpmd7_Node_Ref NextRef; 155 CPpmd7_Node_Ref NextRef;
156} CPpmd7_Node_Union; 156} CPpmd7_Node_Union;
157 157
158/* Original PPmdH (Ppmd7) code uses doubly linked list in GlueFreeBlocks() 158/* Original PPmdH (Ppmd7) code uses doubly linked list in Ppmd7_GlueFreeBlocks()
159 we use single linked list similar to Ppmd8 code */ 159 we use single linked list similar to Ppmd8 code */
160 160
161 161
162static void GlueFreeBlocks(CPpmd7 *p) 162static void Ppmd7_GlueFreeBlocks(CPpmd7 *p)
163{ 163{
164 /* 164 /*
165 we use first UInt16 field of 12-bytes UNITs as record type stamp 165 we use first UInt16 field of 12-bytes UNITs as record type stamp
@@ -239,27 +239,27 @@ static void GlueFreeBlocks(CPpmd7 *p)
239 if (nu == 0) 239 if (nu == 0)
240 continue; 240 continue;
241 for (; nu > 128; nu -= 128, node += 128) 241 for (; nu > 128; nu -= 128, node += 128)
242 InsertNode(p, node, PPMD_NUM_INDEXES - 1); 242 Ppmd7_InsertNode(p, node, PPMD_NUM_INDEXES - 1);
243 if (I2U(i = U2I(nu)) != nu) 243 if (I2U(i = U2I(nu)) != nu)
244 { 244 {
245 unsigned k = I2U(--i); 245 unsigned k = I2U(--i);
246 InsertNode(p, node + k, (unsigned)nu - k - 1); 246 Ppmd7_InsertNode(p, node + k, (unsigned)nu - k - 1);
247 } 247 }
248 InsertNode(p, node, i); 248 Ppmd7_InsertNode(p, node, i);
249 } 249 }
250} 250}
251 251
252 252
253MY_NO_INLINE 253Z7_NO_INLINE
254static void *AllocUnitsRare(CPpmd7 *p, unsigned indx) 254static void *Ppmd7_AllocUnitsRare(CPpmd7 *p, unsigned indx)
255{ 255{
256 unsigned i; 256 unsigned i;
257 257
258 if (p->GlueCount == 0) 258 if (p->GlueCount == 0)
259 { 259 {
260 GlueFreeBlocks(p); 260 Ppmd7_GlueFreeBlocks(p);
261 if (p->FreeList[indx] != 0) 261 if (p->FreeList[indx] != 0)
262 return RemoveNode(p, indx); 262 return Ppmd7_RemoveNode(p, indx);
263 } 263 }
264 264
265 i = indx; 265 i = indx;
@@ -277,17 +277,17 @@ static void *AllocUnitsRare(CPpmd7 *p, unsigned indx)
277 while (p->FreeList[i] == 0); 277 while (p->FreeList[i] == 0);
278 278
279 { 279 {
280 void *block = RemoveNode(p, i); 280 void *block = Ppmd7_RemoveNode(p, i);
281 SplitBlock(p, block, i, indx); 281 Ppmd7_SplitBlock(p, block, i, indx);
282 return block; 282 return block;
283 } 283 }
284} 284}
285 285
286 286
287static void *AllocUnits(CPpmd7 *p, unsigned indx) 287static void *Ppmd7_AllocUnits(CPpmd7 *p, unsigned indx)
288{ 288{
289 if (p->FreeList[indx] != 0) 289 if (p->FreeList[indx] != 0)
290 return RemoveNode(p, indx); 290 return Ppmd7_RemoveNode(p, indx);
291 { 291 {
292 UInt32 numBytes = U2B(I2U(indx)); 292 UInt32 numBytes = U2B(I2U(indx));
293 Byte *lo = p->LoUnit; 293 Byte *lo = p->LoUnit;
@@ -297,11 +297,11 @@ static void *AllocUnits(CPpmd7 *p, unsigned indx)
297 return lo; 297 return lo;
298 } 298 }
299 } 299 }
300 return AllocUnitsRare(p, indx); 300 return Ppmd7_AllocUnitsRare(p, indx);
301} 301}
302 302
303 303
304#define MyMem12Cpy(dest, src, num) \ 304#define MEM_12_CPY(dest, src, num) \
305 { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ 305 { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \
306 do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } 306 do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); }
307 307
@@ -315,12 +315,12 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU
315 return oldPtr; 315 return oldPtr;
316 if (p->FreeList[i1] != 0) 316 if (p->FreeList[i1] != 0)
317 { 317 {
318 void *ptr = RemoveNode(p, i1); 318 void *ptr = Ppmd7_RemoveNode(p, i1);
319 MyMem12Cpy(ptr, oldPtr, newNU); 319 MEM_12_CPY(ptr, oldPtr, newNU)
320 InsertNode(p, oldPtr, i0); 320 Ppmd7_InsertNode(p, oldPtr, i0);
321 return ptr; 321 return ptr;
322 } 322 }
323 SplitBlock(p, oldPtr, i0, i1); 323 Ppmd7_SplitBlock(p, oldPtr, i0, i1);
324 return oldPtr; 324 return oldPtr;
325} 325}
326*/ 326*/
@@ -329,14 +329,14 @@ static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU
329#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 329#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
330static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) 330static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v)
331{ 331{
332 Ppmd_SET_SUCCESSOR(p, v); 332 Ppmd_SET_SUCCESSOR(p, v)
333} 333}
334 334
335 335
336 336
337MY_NO_INLINE 337Z7_NO_INLINE
338static 338static
339void RestartModel(CPpmd7 *p) 339void Ppmd7_RestartModel(CPpmd7 *p)
340{ 340{
341 unsigned i, k; 341 unsigned i, k;
342 342
@@ -352,8 +352,8 @@ void RestartModel(CPpmd7 *p)
352 p->PrevSuccess = 0; 352 p->PrevSuccess = 0;
353 353
354 { 354 {
355 CPpmd7_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ 355 CPpmd7_Context *mc = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
356 CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ 356 CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd7_AllocUnits(p, PPMD_NUM_INDEXES - 1); */
357 357
358 p->LoUnit += U2B(256 / 2); 358 p->LoUnit += U2B(256 / 2);
359 p->MaxContext = p->MinContext = mc; 359 p->MaxContext = p->MinContext = mc;
@@ -391,7 +391,7 @@ void RestartModel(CPpmd7 *p)
391 { 391 {
392 unsigned m; 392 unsigned m;
393 UInt16 *dest = p->BinSumm[i] + k; 393 UInt16 *dest = p->BinSumm[i] + k;
394 UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2)); 394 const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD7_kInitBinEsc[k] / (i + 2));
395 for (m = 0; m < 64; m += 8) 395 for (m = 0; m < 64; m += 8)
396 dest[m] = val; 396 dest[m] = val;
397 } 397 }
@@ -423,13 +423,13 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder)
423{ 423{
424 p->MaxOrder = maxOrder; 424 p->MaxOrder = maxOrder;
425 425
426 RestartModel(p); 426 Ppmd7_RestartModel(p);
427} 427}
428 428
429 429
430 430
431/* 431/*
432 CreateSuccessors() 432 Ppmd7_CreateSuccessors()
433 It's called when (FoundState->Successor) is RAW-Successor, 433 It's called when (FoundState->Successor) is RAW-Successor,
434 that is the link to position in Raw text. 434 that is the link to position in Raw text.
435 So we create Context records and write the links to 435 So we create Context records and write the links to
@@ -445,10 +445,10 @@ void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder)
445 also it can return pointer to real context of same order, 445 also it can return pointer to real context of same order,
446*/ 446*/
447 447
448MY_NO_INLINE 448Z7_NO_INLINE
449static CTX_PTR CreateSuccessors(CPpmd7 *p) 449static PPMD7_CTX_PTR Ppmd7_CreateSuccessors(CPpmd7 *p)
450{ 450{
451 CTX_PTR c = p->MinContext; 451 PPMD7_CTX_PTR c = p->MinContext;
452 CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); 452 CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState);
453 Byte newSym, newFreq; 453 Byte newSym, newFreq;
454 unsigned numPs = 0; 454 unsigned numPs = 0;
@@ -522,15 +522,15 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p)
522 522
523 do 523 do
524 { 524 {
525 CTX_PTR c1; 525 PPMD7_CTX_PTR c1;
526 /* = AllocContext(p); */ 526 /* = AllocContext(p); */
527 if (p->HiUnit != p->LoUnit) 527 if (p->HiUnit != p->LoUnit)
528 c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); 528 c1 = (PPMD7_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE);
529 else if (p->FreeList[0] != 0) 529 else if (p->FreeList[0] != 0)
530 c1 = (CTX_PTR)RemoveNode(p, 0); 530 c1 = (PPMD7_CTX_PTR)Ppmd7_RemoveNode(p, 0);
531 else 531 else
532 { 532 {
533 c1 = (CTX_PTR)AllocUnitsRare(p, 0); 533 c1 = (PPMD7_CTX_PTR)Ppmd7_AllocUnitsRare(p, 0);
534 if (!c1) 534 if (!c1)
535 return NULL; 535 return NULL;
536 } 536 }
@@ -550,16 +550,16 @@ static CTX_PTR CreateSuccessors(CPpmd7 *p)
550 550
551 551
552 552
553#define SwapStates(s) \ 553#define SWAP_STATES(s) \
554 { CPpmd_State tmp = s[0]; s[0] = s[-1]; s[-1] = tmp; } 554 { CPpmd_State tmp = s[0]; s[0] = s[-1]; s[-1] = tmp; }
555 555
556 556
557void Ppmd7_UpdateModel(CPpmd7 *p); 557void Ppmd7_UpdateModel(CPpmd7 *p);
558MY_NO_INLINE 558Z7_NO_INLINE
559void Ppmd7_UpdateModel(CPpmd7 *p) 559void Ppmd7_UpdateModel(CPpmd7 *p)
560{ 560{
561 CPpmd_Void_Ref maxSuccessor, minSuccessor; 561 CPpmd_Void_Ref maxSuccessor, minSuccessor;
562 CTX_PTR c, mc; 562 PPMD7_CTX_PTR c, mc;
563 unsigned s0, ns; 563 unsigned s0, ns;
564 564
565 565
@@ -592,7 +592,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
592 592
593 if (s[0].Freq >= s[-1].Freq) 593 if (s[0].Freq >= s[-1].Freq)
594 { 594 {
595 SwapStates(s); 595 SWAP_STATES(s)
596 s--; 596 s--;
597 } 597 }
598 } 598 }
@@ -610,10 +610,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
610 { 610 {
611 /* MAX ORDER context */ 611 /* MAX ORDER context */
612 /* (FoundState->Successor) is RAW-Successor. */ 612 /* (FoundState->Successor) is RAW-Successor. */
613 p->MaxContext = p->MinContext = CreateSuccessors(p); 613 p->MaxContext = p->MinContext = Ppmd7_CreateSuccessors(p);
614 if (!p->MinContext) 614 if (!p->MinContext)
615 { 615 {
616 RestartModel(p); 616 Ppmd7_RestartModel(p);
617 return; 617 return;
618 } 618 }
619 SetSuccessor(p->FoundState, REF(p->MinContext)); 619 SetSuccessor(p->FoundState, REF(p->MinContext));
@@ -629,7 +629,7 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
629 p->Text = text; 629 p->Text = text;
630 if (text >= p->UnitsStart) 630 if (text >= p->UnitsStart)
631 { 631 {
632 RestartModel(p); 632 Ppmd7_RestartModel(p);
633 return; 633 return;
634 } 634 }
635 maxSuccessor = REF(text); 635 maxSuccessor = REF(text);
@@ -645,10 +645,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
645 if (minSuccessor <= maxSuccessor) 645 if (minSuccessor <= maxSuccessor)
646 { 646 {
647 // minSuccessor is RAW-Successor. So we will create real contexts records: 647 // minSuccessor is RAW-Successor. So we will create real contexts records:
648 CTX_PTR cs = CreateSuccessors(p); 648 PPMD7_CTX_PTR cs = Ppmd7_CreateSuccessors(p);
649 if (!cs) 649 if (!cs)
650 { 650 {
651 RestartModel(p); 651 Ppmd7_RestartModel(p);
652 return; 652 return;
653 } 653 }
654 minSuccessor = REF(cs); 654 minSuccessor = REF(cs);
@@ -715,16 +715,16 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
715 unsigned i = U2I(oldNU); 715 unsigned i = U2I(oldNU);
716 if (i != U2I((size_t)oldNU + 1)) 716 if (i != U2I((size_t)oldNU + 1))
717 { 717 {
718 void *ptr = AllocUnits(p, i + 1); 718 void *ptr = Ppmd7_AllocUnits(p, i + 1);
719 void *oldPtr; 719 void *oldPtr;
720 if (!ptr) 720 if (!ptr)
721 { 721 {
722 RestartModel(p); 722 Ppmd7_RestartModel(p);
723 return; 723 return;
724 } 724 }
725 oldPtr = STATS(c); 725 oldPtr = STATS(c);
726 MyMem12Cpy(ptr, oldPtr, oldNU); 726 MEM_12_CPY(ptr, oldPtr, oldNU)
727 InsertNode(p, oldPtr, i); 727 Ppmd7_InsertNode(p, oldPtr, i);
728 c->Union4.Stats = STATS_REF(ptr); 728 c->Union4.Stats = STATS_REF(ptr);
729 } 729 }
730 } 730 }
@@ -739,10 +739,10 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
739 else 739 else
740 { 740 {
741 // instead of One-symbol context we create 2-symbol context 741 // instead of One-symbol context we create 2-symbol context
742 CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); 742 CPpmd_State *s = (CPpmd_State*)Ppmd7_AllocUnits(p, 0);
743 if (!s) 743 if (!s)
744 { 744 {
745 RestartModel(p); 745 Ppmd7_RestartModel(p);
746 return; 746 return;
747 } 747 }
748 { 748 {
@@ -795,8 +795,8 @@ void Ppmd7_UpdateModel(CPpmd7 *p)
795 795
796 796
797 797
798MY_NO_INLINE 798Z7_NO_INLINE
799static void Rescale(CPpmd7 *p) 799static void Ppmd7_Rescale(CPpmd7 *p)
800{ 800{
801 unsigned i, adder, sumFreq, escFreq; 801 unsigned i, adder, sumFreq, escFreq;
802 CPpmd_State *stats = STATS(p->MinContext); 802 CPpmd_State *stats = STATS(p->MinContext);
@@ -885,7 +885,7 @@ static void Rescale(CPpmd7 *p)
885 *s = *stats; 885 *s = *stats;
886 s->Freq = (Byte)freq; // (freq <= 260 / 4) 886 s->Freq = (Byte)freq; // (freq <= 260 / 4)
887 p->FoundState = s; 887 p->FoundState = s;
888 InsertNode(p, stats, U2I(n0)); 888 Ppmd7_InsertNode(p, stats, U2I(n0));
889 return; 889 return;
890 } 890 }
891 891
@@ -899,13 +899,13 @@ static void Rescale(CPpmd7 *p)
899 { 899 {
900 if (p->FreeList[i1] != 0) 900 if (p->FreeList[i1] != 0)
901 { 901 {
902 void *ptr = RemoveNode(p, i1); 902 void *ptr = Ppmd7_RemoveNode(p, i1);
903 p->MinContext->Union4.Stats = STATS_REF(ptr); 903 p->MinContext->Union4.Stats = STATS_REF(ptr);
904 MyMem12Cpy(ptr, (const void *)stats, n1); 904 MEM_12_CPY(ptr, (const void *)stats, n1)
905 InsertNode(p, stats, i0); 905 Ppmd7_InsertNode(p, stats, i0);
906 } 906 }
907 else 907 else
908 SplitBlock(p, stats, i0, i1); 908 Ppmd7_SplitBlock(p, stats, i0, i1);
909 } 909 }
910 } 910 }
911 } 911 }
@@ -948,9 +948,9 @@ CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq)
948} 948}
949 949
950 950
951static void NextContext(CPpmd7 *p) 951static void Ppmd7_NextContext(CPpmd7 *p)
952{ 952{
953 CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); 953 PPMD7_CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
954 if (p->OrderFall == 0 && (const Byte *)c > p->Text) 954 if (p->OrderFall == 0 && (const Byte *)c > p->Text)
955 p->MaxContext = p->MinContext = c; 955 p->MaxContext = p->MinContext = c;
956 else 956 else
@@ -967,12 +967,12 @@ void Ppmd7_Update1(CPpmd7 *p)
967 s->Freq = (Byte)freq; 967 s->Freq = (Byte)freq;
968 if (freq > s[-1].Freq) 968 if (freq > s[-1].Freq)
969 { 969 {
970 SwapStates(s); 970 SWAP_STATES(s)
971 p->FoundState = --s; 971 p->FoundState = --s;
972 if (freq > MAX_FREQ) 972 if (freq > MAX_FREQ)
973 Rescale(p); 973 Ppmd7_Rescale(p);
974 } 974 }
975 NextContext(p); 975 Ppmd7_NextContext(p);
976} 976}
977 977
978 978
@@ -988,8 +988,8 @@ void Ppmd7_Update1_0(CPpmd7 *p)
988 freq += 4; 988 freq += 4;
989 s->Freq = (Byte)freq; 989 s->Freq = (Byte)freq;
990 if (freq > MAX_FREQ) 990 if (freq > MAX_FREQ)
991 Rescale(p); 991 Ppmd7_Rescale(p);
992 NextContext(p); 992 Ppmd7_NextContext(p);
993} 993}
994 994
995 995
@@ -1000,7 +1000,7 @@ void Ppmd7_UpdateBin(CPpmd7 *p)
1000 p->FoundState->Freq = (Byte)(freq + (freq < 128)); 1000 p->FoundState->Freq = (Byte)(freq + (freq < 128));
1001 p->PrevSuccess = 1; 1001 p->PrevSuccess = 1;
1002 p->RunLength++; 1002 p->RunLength++;
1003 NextContext(p); 1003 Ppmd7_NextContext(p);
1004} 1004}
1005*/ 1005*/
1006 1006
@@ -1013,7 +1013,7 @@ void Ppmd7_Update2(CPpmd7 *p)
1013 p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); 1013 p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4);
1014 s->Freq = (Byte)freq; 1014 s->Freq = (Byte)freq;
1015 if (freq > MAX_FREQ) 1015 if (freq > MAX_FREQ)
1016 Rescale(p); 1016 Ppmd7_Rescale(p);
1017 Ppmd7_UpdateModel(p); 1017 Ppmd7_UpdateModel(p);
1018} 1018}
1019 1019
@@ -1042,8 +1042,8 @@ Last UNIT of array at offset (Size - 12) is root order-0 CPpmd7_Context record.
1042The code can free UNITs memory blocks that were allocated to store CPpmd_State vectors. 1042The code can free UNITs memory blocks that were allocated to store CPpmd_State vectors.
1043The code doesn't free UNITs allocated for CPpmd7_Context records. 1043The code doesn't free UNITs allocated for CPpmd7_Context records.
1044 1044
1045The code calls RestartModel(), when there is no free memory for allocation. 1045The code calls Ppmd7_RestartModel(), when there is no free memory for allocation.
1046And RestartModel() changes the state to orignal start state, with full free block. 1046And Ppmd7_RestartModel() changes the state to orignal start state, with full free block.
1047 1047
1048 1048
1049The code allocates UNITs with the following order: 1049The code allocates UNITs with the following order:
@@ -1051,14 +1051,14 @@ The code allocates UNITs with the following order:
1051Allocation of 1 UNIT for Context record 1051Allocation of 1 UNIT for Context record
1052 - from free space (HiUnit) down to (LoUnit) 1052 - from free space (HiUnit) down to (LoUnit)
1053 - from FreeList[0] 1053 - from FreeList[0]
1054 - AllocUnitsRare() 1054 - Ppmd7_AllocUnitsRare()
1055 1055
1056AllocUnits() for CPpmd_State vectors: 1056Ppmd7_AllocUnits() for CPpmd_State vectors:
1057 - from FreeList[i] 1057 - from FreeList[i]
1058 - from free space (LoUnit) up to (HiUnit) 1058 - from free space (LoUnit) up to (HiUnit)
1059 - AllocUnitsRare() 1059 - Ppmd7_AllocUnitsRare()
1060 1060
1061AllocUnitsRare() 1061Ppmd7_AllocUnitsRare()
1062 - if (GlueCount == 0) 1062 - if (GlueCount == 0)
1063 { Glue lists, GlueCount = 255, allocate from FreeList[i]] } 1063 { Glue lists, GlueCount = 255, allocate from FreeList[i]] }
1064 - loop for all higher sized FreeList[...] lists 1064 - loop for all higher sized FreeList[...] lists
@@ -1093,8 +1093,8 @@ The PPMd code tries to fulfill the condition:
1093We have (Sum(Stats[].Freq) <= 256 * 124), because of (MAX_FREQ = 124) 1093We have (Sum(Stats[].Freq) <= 256 * 124), because of (MAX_FREQ = 124)
1094So (4 = 128 - 124) is average reserve for Escape_Freq for each symbol. 1094So (4 = 128 - 124) is average reserve for Escape_Freq for each symbol.
1095If (CPpmd_State::Freq) is not aligned for 4, the reserve can be 5, 6 or 7. 1095If (CPpmd_State::Freq) is not aligned for 4, the reserve can be 5, 6 or 7.
1096SummFreq and Escape_Freq can be changed in Rescale() and *Update*() functions. 1096SummFreq and Escape_Freq can be changed in Ppmd7_Rescale() and *Update*() functions.
1097Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Rescale() for 1097Ppmd7_Rescale() can remove symbols only from max-order contexts. So Escape_Freq can increase after multiple calls of Ppmd7_Rescale() for
1098max-order context. 1098max-order context.
1099 1099
1100When the PPMd code still break (Total <= RC::Range) condition in range coder, 1100When the PPMd code still break (Total <= RC::Range) condition in range coder,
@@ -1102,3 +1102,21 @@ we have two ways to resolve that problem:
1102 1) we can report error, if we want to keep compatibility with original PPMd code that has no fix for such cases. 1102 1) we can report error, if we want to keep compatibility with original PPMd code that has no fix for such cases.
1103 2) we can reduce (Total) value to (RC::Range) by reducing (Escape_Freq) part of (Total) value. 1103 2) we can reduce (Total) value to (RC::Range) by reducing (Escape_Freq) part of (Total) value.
1104*/ 1104*/
1105
1106#undef MAX_FREQ
1107#undef UNIT_SIZE
1108#undef U2B
1109#undef U2I
1110#undef I2U
1111#undef I2U_UInt16
1112#undef REF
1113#undef STATS_REF
1114#undef CTX
1115#undef STATS
1116#undef ONE_STATE
1117#undef SUFFIX
1118#undef NODE
1119#undef EMPTY_NODE
1120#undef MEM_12_CPY
1121#undef SUCCESSOR
1122#undef SWAP_STATES
diff --git a/C/Ppmd7.h b/C/Ppmd7.h
index d31809a..d9eb326 100644
--- a/C/Ppmd7.h
+++ b/C/Ppmd7.h
@@ -1,11 +1,11 @@
1/* Ppmd7.h -- Ppmd7 (PPMdH) compression codec 1/* Ppmd7.h -- Ppmd7 (PPMdH) compression codec
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.H (2001): Dmitry Shkarin : Public domain */ 4 PPMd var.H (2001): Dmitry Shkarin : Public domain */
5 5
6 6
7#ifndef __PPMD7_H 7#ifndef ZIP7_INC_PPMD7_H
8#define __PPMD7_H 8#define ZIP7_INC_PPMD7_H
9 9
10#include "Ppmd.h" 10#include "Ppmd.h"
11 11
@@ -55,7 +55,7 @@ typedef struct
55 UInt32 Range; 55 UInt32 Range;
56 UInt32 Code; 56 UInt32 Code;
57 UInt32 Low; 57 UInt32 Low;
58 IByteIn *Stream; 58 IByteInPtr Stream;
59} CPpmd7_RangeDec; 59} CPpmd7_RangeDec;
60 60
61 61
@@ -66,7 +66,7 @@ typedef struct
66 // Byte _dummy_[3]; 66 // Byte _dummy_[3];
67 UInt64 Low; 67 UInt64 Low;
68 UInt64 CacheSize; 68 UInt64 CacheSize;
69 IByteOut *Stream; 69 IByteOutPtr Stream;
70} CPpmd7z_RangeEnc; 70} CPpmd7z_RangeEnc;
71 71
72 72
diff --git a/C/Ppmd7Dec.c b/C/Ppmd7Dec.c
index 55d74ff..8323828 100644
--- a/C/Ppmd7Dec.c
+++ b/C/Ppmd7Dec.c
@@ -1,5 +1,5 @@
1/* Ppmd7Dec.c -- Ppmd7z (PPMdH with 7z Range Coder) Decoder 1/* Ppmd7Dec.c -- Ppmd7z (PPMdH with 7z Range Coder) Decoder
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.H (2001): Dmitry Shkarin : Public domain */ 4 PPMd var.H (2001): Dmitry Shkarin : Public domain */
5 5
@@ -8,7 +8,7 @@ This code is based on:
8 8
9#include "Ppmd7.h" 9#include "Ppmd7.h"
10 10
11#define kTopValue (1 << 24) 11#define kTopValue ((UInt32)1 << 24)
12 12
13 13
14#define READ_BYTE(p) IByteIn_Read((p)->Stream) 14#define READ_BYTE(p) IByteIn_Read((p)->Stream)
@@ -37,9 +37,9 @@ BoolInt Ppmd7z_RangeDec_Init(CPpmd7_RangeDec *p)
37 37
38#define R (&p->rc.dec) 38#define R (&p->rc.dec)
39 39
40MY_FORCE_INLINE 40Z7_FORCE_INLINE
41// MY_NO_INLINE 41// Z7_NO_INLINE
42static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) 42static void Ppmd7z_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size)
43{ 43{
44 44
45 45
@@ -48,18 +48,18 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size)
48 RC_NORM_LOCAL(R) 48 RC_NORM_LOCAL(R)
49} 49}
50 50
51#define RC_Decode(start, size) RangeDec_Decode(p, start, size); 51#define RC_Decode(start, size) Ppmd7z_RD_Decode(p, start, size);
52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) 52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R)
53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) 53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total)))
54 54
55 55
56#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) 56#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref))
57typedef CPpmd7_Context * CTX_PTR; 57// typedef CPpmd7_Context * CTX_PTR;
58#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 58#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
59void Ppmd7_UpdateModel(CPpmd7 *p); 59void Ppmd7_UpdateModel(CPpmd7 *p);
60 60
61#define MASK(sym) ((unsigned char *)charMask)[sym] 61#define MASK(sym) ((unsigned char *)charMask)[sym]
62// MY_FORCE_INLINE 62// Z7_FORCE_INLINE
63// static 63// static
64int Ppmd7z_DecodeSymbol(CPpmd7 *p) 64int Ppmd7z_DecodeSymbol(CPpmd7 *p)
65{ 65{
@@ -70,7 +70,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
70 CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); 70 CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext);
71 unsigned i; 71 unsigned i;
72 UInt32 count, hiCnt; 72 UInt32 count, hiCnt;
73 UInt32 summFreq = p->MinContext->Union2.SummFreq; 73 const UInt32 summFreq = p->MinContext->Union2.SummFreq;
74 74
75 75
76 76
@@ -81,7 +81,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
81 if ((Int32)(count -= s->Freq) < 0) 81 if ((Int32)(count -= s->Freq) < 0)
82 { 82 {
83 Byte sym; 83 Byte sym;
84 RC_DecodeFinal(0, s->Freq); 84 RC_DecodeFinal(0, s->Freq)
85 p->FoundState = s; 85 p->FoundState = s;
86 sym = s->Symbol; 86 sym = s->Symbol;
87 Ppmd7_Update1_0(p); 87 Ppmd7_Update1_0(p);
@@ -96,7 +96,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
96 if ((Int32)(count -= (++s)->Freq) < 0) 96 if ((Int32)(count -= (++s)->Freq) < 0)
97 { 97 {
98 Byte sym; 98 Byte sym;
99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
100 p->FoundState = s; 100 p->FoundState = s;
101 sym = s->Symbol; 101 sym = s->Symbol;
102 Ppmd7_Update1(p); 102 Ppmd7_Update1(p);
@@ -109,10 +109,10 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
109 return PPMD7_SYM_ERROR; 109 return PPMD7_SYM_ERROR;
110 110
111 hiCnt -= count; 111 hiCnt -= count;
112 RC_Decode(hiCnt, summFreq - hiCnt); 112 RC_Decode(hiCnt, summFreq - hiCnt)
113 113
114 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); 114 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol);
115 PPMD_SetAllBitsIn256Bytes(charMask); 115 PPMD_SetAllBitsIn256Bytes(charMask)
116 // i = p->MinContext->NumStats - 1; 116 // i = p->MinContext->NumStats - 1;
117 // do { MASK((--s)->Symbol) = 0; } while (--i); 117 // do { MASK((--s)->Symbol) = 0; } while (--i);
118 { 118 {
@@ -152,7 +152,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
152 // Ppmd7_UpdateBin(p); 152 // Ppmd7_UpdateBin(p);
153 { 153 {
154 unsigned freq = s->Freq; 154 unsigned freq = s->Freq;
155 CTX_PTR c = CTX(SUCCESSOR(s)); 155 CPpmd7_Context *c = CTX(SUCCESSOR(s));
156 sym = s->Symbol; 156 sym = s->Symbol;
157 p->FoundState = s; 157 p->FoundState = s;
158 p->PrevSuccess = 1; 158 p->PrevSuccess = 1;
@@ -176,7 +176,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
176 R->Range -= size0; 176 R->Range -= size0;
177 RC_NORM_LOCAL(R) 177 RC_NORM_LOCAL(R)
178 178
179 PPMD_SetAllBitsIn256Bytes(charMask); 179 PPMD_SetAllBitsIn256Bytes(charMask)
180 MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; 180 MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0;
181 p->PrevSuccess = 0; 181 p->PrevSuccess = 0;
182 } 182 }
@@ -245,13 +245,13 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
245 { 245 {
246 count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; 246 count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break;
247 // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; 247 // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break;
248 }; 248 }
249 } 249 }
250 s--; 250 s--;
251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
252 252
253 // new (see->Summ) value can overflow over 16-bits in some rare cases 253 // new (see->Summ) value can overflow over 16-bits in some rare cases
254 Ppmd_See_Update(see); 254 Ppmd_See_UPDATE(see)
255 p->FoundState = s; 255 p->FoundState = s;
256 sym = s->Symbol; 256 sym = s->Symbol;
257 Ppmd7_Update2(p); 257 Ppmd7_Update2(p);
@@ -261,7 +261,7 @@ int Ppmd7z_DecodeSymbol(CPpmd7 *p)
261 if (count >= freqSum) 261 if (count >= freqSum)
262 return PPMD7_SYM_ERROR; 262 return PPMD7_SYM_ERROR;
263 263
264 RC_Decode(hiCnt, freqSum - hiCnt); 264 RC_Decode(hiCnt, freqSum - hiCnt)
265 265
266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. 266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols.
267 // new (see->Summ) value can overflow over 16-bits in some rare cases 267 // 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)
295 return buf; 295 return buf;
296} 296}
297*/ 297*/
298
299#undef kTopValue
300#undef READ_BYTE
301#undef RC_NORM_BASE
302#undef RC_NORM_1
303#undef RC_NORM
304#undef RC_NORM_LOCAL
305#undef RC_NORM_REMOTE
306#undef R
307#undef RC_Decode
308#undef RC_DecodeFinal
309#undef RC_GetThreshold
310#undef CTX
311#undef SUCCESSOR
312#undef MASK
diff --git a/C/Ppmd7Enc.c b/C/Ppmd7Enc.c
index 62139c5..41106ba 100644
--- a/C/Ppmd7Enc.c
+++ b/C/Ppmd7Enc.c
@@ -1,5 +1,5 @@
1/* Ppmd7Enc.c -- Ppmd7z (PPMdH with 7z Range Coder) Encoder 1/* Ppmd7Enc.c -- Ppmd7z (PPMdH with 7z Range Coder) Encoder
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.H (2001): Dmitry Shkarin : Public domain */ 4 PPMd var.H (2001): Dmitry Shkarin : Public domain */
5 5
@@ -8,7 +8,7 @@ This code is based on:
8 8
9#include "Ppmd7.h" 9#include "Ppmd7.h"
10 10
11#define kTopValue (1 << 24) 11#define kTopValue ((UInt32)1 << 24)
12 12
13#define R (&p->rc.enc) 13#define R (&p->rc.enc)
14 14
@@ -20,8 +20,8 @@ void Ppmd7z_Init_RangeEnc(CPpmd7 *p)
20 R->CacheSize = 1; 20 R->CacheSize = 1;
21} 21}
22 22
23MY_NO_INLINE 23Z7_NO_INLINE
24static void RangeEnc_ShiftLow(CPpmd7 *p) 24static void Ppmd7z_RangeEnc_ShiftLow(CPpmd7 *p)
25{ 25{
26 if ((UInt32)R->Low < (UInt32)0xFF000000 || (unsigned)(R->Low >> 32) != 0) 26 if ((UInt32)R->Low < (UInt32)0xFF000000 || (unsigned)(R->Low >> 32) != 0)
27 { 27 {
@@ -38,53 +38,53 @@ static void RangeEnc_ShiftLow(CPpmd7 *p)
38 R->Low = (UInt32)((UInt32)R->Low << 8); 38 R->Low = (UInt32)((UInt32)R->Low << 8);
39} 39}
40 40
41#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; RangeEnc_ShiftLow(p); 41#define RC_NORM_BASE(p) if (R->Range < kTopValue) { R->Range <<= 8; Ppmd7z_RangeEnc_ShiftLow(p);
42#define RC_NORM_1(p) RC_NORM_BASE(p) } 42#define RC_NORM_1(p) RC_NORM_BASE(p) }
43#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }} 43#define RC_NORM(p) RC_NORM_BASE(p) RC_NORM_BASE(p) }}
44 44
45// we must use only one type of Normalization from two: LOCAL or REMOTE 45// we must use only one type of Normalization from two: LOCAL or REMOTE
46#define RC_NORM_LOCAL(p) // RC_NORM(p) 46#define RC_NORM_LOCAL(p) // RC_NORM(p)
47#define RC_NORM_REMOTE(p) RC_NORM(p) 47#define RC_NORM_REMOTE(p) RC_NORM(p)
48 48
49/* 49/*
50#define RangeEnc_Encode(p, start, _size_) \ 50#define Ppmd7z_RangeEnc_Encode(p, start, _size_) \
51 { UInt32 size = _size_; \ 51 { UInt32 size = _size_; \
52 R->Low += start * R->Range; \ 52 R->Low += start * R->Range; \
53 R->Range *= size; \ 53 R->Range *= size; \
54 RC_NORM_LOCAL(p); } 54 RC_NORM_LOCAL(p); }
55*/ 55*/
56 56
57MY_FORCE_INLINE 57Z7_FORCE_INLINE
58// MY_NO_INLINE 58// Z7_NO_INLINE
59static void RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size) 59static void Ppmd7z_RangeEnc_Encode(CPpmd7 *p, UInt32 start, UInt32 size)
60{ 60{
61 R->Low += start * R->Range; 61 R->Low += start * R->Range;
62 R->Range *= size; 62 R->Range *= size;
63 RC_NORM_LOCAL(p); 63 RC_NORM_LOCAL(p)
64} 64}
65 65
66void Ppmd7z_Flush_RangeEnc(CPpmd7 *p) 66void Ppmd7z_Flush_RangeEnc(CPpmd7 *p)
67{ 67{
68 unsigned i; 68 unsigned i;
69 for (i = 0; i < 5; i++) 69 for (i = 0; i < 5; i++)
70 RangeEnc_ShiftLow(p); 70 Ppmd7z_RangeEnc_ShiftLow(p);
71} 71}
72 72
73 73
74 74
75#define RC_Encode(start, size) RangeEnc_Encode(p, start, size); 75#define RC_Encode(start, size) Ppmd7z_RangeEnc_Encode(p, start, size);
76#define RC_EncodeFinal(start, size) RC_Encode(start, size); RC_NORM_REMOTE(p); 76#define RC_EncodeFinal(start, size) RC_Encode(start, size) RC_NORM_REMOTE(p)
77 77
78#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) 78#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref))
79#define SUFFIX(ctx) CTX((ctx)->Suffix) 79#define SUFFIX(ctx) CTX((ctx)->Suffix)
80typedef CPpmd7_Context * CTX_PTR; 80// typedef CPpmd7_Context * CTX_PTR;
81#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 81#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
82 82
83void Ppmd7_UpdateModel(CPpmd7 *p); 83void Ppmd7_UpdateModel(CPpmd7 *p);
84 84
85#define MASK(sym) ((unsigned char *)charMask)[sym] 85#define MASK(sym) ((unsigned char *)charMask)[sym]
86 86
87MY_FORCE_INLINE 87Z7_FORCE_INLINE
88static 88static
89void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol) 89void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
90{ 90{
@@ -104,7 +104,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
104 if (s->Symbol == symbol) 104 if (s->Symbol == symbol)
105 { 105 {
106 // R->Range /= p->MinContext->Union2.SummFreq; 106 // R->Range /= p->MinContext->Union2.SummFreq;
107 RC_EncodeFinal(0, s->Freq); 107 RC_EncodeFinal(0, s->Freq)
108 p->FoundState = s; 108 p->FoundState = s;
109 Ppmd7_Update1_0(p); 109 Ppmd7_Update1_0(p);
110 return; 110 return;
@@ -117,7 +117,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
117 if ((++s)->Symbol == symbol) 117 if ((++s)->Symbol == symbol)
118 { 118 {
119 // R->Range /= p->MinContext->Union2.SummFreq; 119 // R->Range /= p->MinContext->Union2.SummFreq;
120 RC_EncodeFinal(sum, s->Freq); 120 RC_EncodeFinal(sum, s->Freq)
121 p->FoundState = s; 121 p->FoundState = s;
122 Ppmd7_Update1(p); 122 Ppmd7_Update1(p);
123 return; 123 return;
@@ -127,10 +127,10 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
127 while (--i); 127 while (--i);
128 128
129 // R->Range /= p->MinContext->Union2.SummFreq; 129 // R->Range /= p->MinContext->Union2.SummFreq;
130 RC_Encode(sum, p->MinContext->Union2.SummFreq - sum); 130 RC_Encode(sum, p->MinContext->Union2.SummFreq - sum)
131 131
132 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); 132 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol);
133 PPMD_SetAllBitsIn256Bytes(charMask); 133 PPMD_SetAllBitsIn256Bytes(charMask)
134 // MASK(s->Symbol) = 0; 134 // MASK(s->Symbol) = 0;
135 // i = p->MinContext->NumStats - 1; 135 // i = p->MinContext->NumStats - 1;
136 // do { MASK((--s)->Symbol) = 0; } while (--i); 136 // do { MASK((--s)->Symbol) = 0; } while (--i);
@@ -153,20 +153,20 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
153 UInt16 *prob = Ppmd7_GetBinSumm(p); 153 UInt16 *prob = Ppmd7_GetBinSumm(p);
154 CPpmd_State *s = Ppmd7Context_OneState(p->MinContext); 154 CPpmd_State *s = Ppmd7Context_OneState(p->MinContext);
155 UInt32 pr = *prob; 155 UInt32 pr = *prob;
156 UInt32 bound = (R->Range >> 14) * pr; 156 const UInt32 bound = (R->Range >> 14) * pr;
157 pr = PPMD_UPDATE_PROB_1(pr); 157 pr = PPMD_UPDATE_PROB_1(pr);
158 if (s->Symbol == symbol) 158 if (s->Symbol == symbol)
159 { 159 {
160 *prob = (UInt16)(pr + (1 << PPMD_INT_BITS)); 160 *prob = (UInt16)(pr + (1 << PPMD_INT_BITS));
161 // RangeEnc_EncodeBit_0(p, bound); 161 // RangeEnc_EncodeBit_0(p, bound);
162 R->Range = bound; 162 R->Range = bound;
163 RC_NORM_1(p); 163 RC_NORM_1(p)
164 164
165 // p->FoundState = s; 165 // p->FoundState = s;
166 // Ppmd7_UpdateBin(p); 166 // Ppmd7_UpdateBin(p);
167 { 167 {
168 unsigned freq = s->Freq; 168 const unsigned freq = s->Freq;
169 CTX_PTR c = CTX(SUCCESSOR(s)); 169 CPpmd7_Context *c = CTX(SUCCESSOR(s));
170 p->FoundState = s; 170 p->FoundState = s;
171 p->PrevSuccess = 1; 171 p->PrevSuccess = 1;
172 p->RunLength++; 172 p->RunLength++;
@@ -187,7 +187,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
187 R->Range -= bound; 187 R->Range -= bound;
188 RC_NORM_LOCAL(p) 188 RC_NORM_LOCAL(p)
189 189
190 PPMD_SetAllBitsIn256Bytes(charMask); 190 PPMD_SetAllBitsIn256Bytes(charMask)
191 MASK(s->Symbol) = 0; 191 MASK(s->Symbol) = 0;
192 p->PrevSuccess = 0; 192 p->PrevSuccess = 0;
193 } 193 }
@@ -248,14 +248,14 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
248 248
249 do 249 do
250 { 250 {
251 unsigned cur = s->Symbol; 251 const unsigned cur = s->Symbol;
252 if ((int)cur == symbol) 252 if ((int)cur == symbol)
253 { 253 {
254 UInt32 low = sum; 254 const UInt32 low = sum;
255 UInt32 freq = s->Freq; 255 const UInt32 freq = s->Freq;
256 unsigned num2; 256 unsigned num2;
257 257
258 Ppmd_See_Update(see); 258 Ppmd_See_UPDATE(see)
259 p->FoundState = s; 259 p->FoundState = s;
260 sum += escFreq; 260 sum += escFreq;
261 261
@@ -279,7 +279,7 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
279 279
280 280
281 R->Range /= sum; 281 R->Range /= sum;
282 RC_EncodeFinal(low, freq); 282 RC_EncodeFinal(low, freq)
283 Ppmd7_Update2(p); 283 Ppmd7_Update2(p);
284 return; 284 return;
285 } 285 }
@@ -289,21 +289,21 @@ void Ppmd7z_EncodeSymbol(CPpmd7 *p, int symbol)
289 while (--i); 289 while (--i);
290 290
291 { 291 {
292 UInt32 total = sum + escFreq; 292 const UInt32 total = sum + escFreq;
293 see->Summ = (UInt16)(see->Summ + total); 293 see->Summ = (UInt16)(see->Summ + total);
294 294
295 R->Range /= total; 295 R->Range /= total;
296 RC_Encode(sum, escFreq); 296 RC_Encode(sum, escFreq)
297 } 297 }
298 298
299 { 299 {
300 CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext); 300 const CPpmd_State *s2 = Ppmd7_GetStats(p, p->MinContext);
301 s--; 301 s--;
302 MASK(s->Symbol) = 0; 302 MASK(s->Symbol) = 0;
303 do 303 do
304 { 304 {
305 unsigned sym0 = s2[0].Symbol; 305 const unsigned sym0 = s2[0].Symbol;
306 unsigned sym1 = s2[1].Symbol; 306 const unsigned sym1 = s2[1].Symbol;
307 s2 += 2; 307 s2 += 2;
308 MASK(sym0) = 0; 308 MASK(sym0) = 0;
309 MASK(sym1) = 0; 309 MASK(sym1) = 0;
@@ -321,3 +321,18 @@ void Ppmd7z_EncodeSymbols(CPpmd7 *p, const Byte *buf, const Byte *lim)
321 Ppmd7z_EncodeSymbol(p, *buf); 321 Ppmd7z_EncodeSymbol(p, *buf);
322 } 322 }
323} 323}
324
325#undef kTopValue
326#undef WRITE_BYTE
327#undef RC_NORM_BASE
328#undef RC_NORM_1
329#undef RC_NORM
330#undef RC_NORM_LOCAL
331#undef RC_NORM_REMOTE
332#undef R
333#undef RC_Encode
334#undef RC_EncodeFinal
335#undef SUFFIX
336#undef CTX
337#undef SUCCESSOR
338#undef MASK
diff --git a/C/Ppmd7aDec.c b/C/Ppmd7aDec.c
index c424578..55e164e 100644
--- a/C/Ppmd7aDec.c
+++ b/C/Ppmd7aDec.c
@@ -1,5 +1,5 @@
1/* Ppmd7aDec.c -- PPMd7a (PPMdH) Decoder 1/* Ppmd7aDec.c -- PPMd7a (PPMdH) Decoder
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.H (2001): Dmitry Shkarin : Public domain 4 PPMd var.H (2001): Dmitry Shkarin : Public domain
5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ 5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
@@ -8,8 +8,8 @@ This code is based on:
8 8
9#include "Ppmd7.h" 9#include "Ppmd7.h"
10 10
11#define kTop (1 << 24) 11#define kTop ((UInt32)1 << 24)
12#define kBot (1 << 15) 12#define kBot ((UInt32)1 << 15)
13 13
14#define READ_BYTE(p) IByteIn_Read((p)->Stream) 14#define READ_BYTE(p) IByteIn_Read((p)->Stream)
15 15
@@ -37,9 +37,9 @@ BoolInt Ppmd7a_RangeDec_Init(CPpmd7_RangeDec *p)
37 37
38#define R (&p->rc.dec) 38#define R (&p->rc.dec)
39 39
40MY_FORCE_INLINE 40Z7_FORCE_INLINE
41// MY_NO_INLINE 41// Z7_NO_INLINE
42static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size) 42static void Ppmd7a_RD_Decode(CPpmd7 *p, UInt32 start, UInt32 size)
43{ 43{
44 start *= R->Range; 44 start *= R->Range;
45 R->Low += start; 45 R->Low += start;
@@ -48,9 +48,9 @@ static void RangeDec_Decode(CPpmd7 *p, UInt32 start, UInt32 size)
48 RC_NORM_LOCAL(R) 48 RC_NORM_LOCAL(R)
49} 49}
50 50
51#define RC_Decode(start, size) RangeDec_Decode(p, start, size); 51#define RC_Decode(start, size) Ppmd7a_RD_Decode(p, start, size);
52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) 52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R)
53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) 53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total)))
54 54
55 55
56#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref)) 56#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref))
@@ -70,7 +70,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
70 CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext); 70 CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext);
71 unsigned i; 71 unsigned i;
72 UInt32 count, hiCnt; 72 UInt32 count, hiCnt;
73 UInt32 summFreq = p->MinContext->Union2.SummFreq; 73 const UInt32 summFreq = p->MinContext->Union2.SummFreq;
74 74
75 if (summFreq > R->Range) 75 if (summFreq > R->Range)
76 return PPMD7_SYM_ERROR; 76 return PPMD7_SYM_ERROR;
@@ -81,7 +81,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
81 if ((Int32)(count -= s->Freq) < 0) 81 if ((Int32)(count -= s->Freq) < 0)
82 { 82 {
83 Byte sym; 83 Byte sym;
84 RC_DecodeFinal(0, s->Freq); 84 RC_DecodeFinal(0, s->Freq)
85 p->FoundState = s; 85 p->FoundState = s;
86 sym = s->Symbol; 86 sym = s->Symbol;
87 Ppmd7_Update1_0(p); 87 Ppmd7_Update1_0(p);
@@ -96,7 +96,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
96 if ((Int32)(count -= (++s)->Freq) < 0) 96 if ((Int32)(count -= (++s)->Freq) < 0)
97 { 97 {
98 Byte sym; 98 Byte sym;
99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
100 p->FoundState = s; 100 p->FoundState = s;
101 sym = s->Symbol; 101 sym = s->Symbol;
102 Ppmd7_Update1(p); 102 Ppmd7_Update1(p);
@@ -109,10 +109,10 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
109 return PPMD7_SYM_ERROR; 109 return PPMD7_SYM_ERROR;
110 110
111 hiCnt -= count; 111 hiCnt -= count;
112 RC_Decode(hiCnt, summFreq - hiCnt); 112 RC_Decode(hiCnt, summFreq - hiCnt)
113 113
114 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol); 114 p->HiBitsFlag = PPMD7_HiBitsFlag_3(p->FoundState->Symbol);
115 PPMD_SetAllBitsIn256Bytes(charMask); 115 PPMD_SetAllBitsIn256Bytes(charMask)
116 // i = p->MinContext->NumStats - 1; 116 // i = p->MinContext->NumStats - 1;
117 // do { MASK((--s)->Symbol) = 0; } while (--i); 117 // do { MASK((--s)->Symbol) = 0; } while (--i);
118 { 118 {
@@ -176,7 +176,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
176 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - size0; 176 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - size0;
177 RC_NORM_LOCAL(R) 177 RC_NORM_LOCAL(R)
178 178
179 PPMD_SetAllBitsIn256Bytes(charMask); 179 PPMD_SetAllBitsIn256Bytes(charMask)
180 MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0; 180 MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0;
181 p->PrevSuccess = 0; 181 p->PrevSuccess = 0;
182 } 182 }
@@ -245,13 +245,13 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
245 { 245 {
246 count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; 246 count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break;
247 // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break; 247 // count -= s->Freq & (unsigned)(MASK((s)->Symbol)); s++; if ((Int32)count < 0) break;
248 }; 248 }
249 } 249 }
250 s--; 250 s--;
251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
252 252
253 // new (see->Summ) value can overflow over 16-bits in some rare cases 253 // new (see->Summ) value can overflow over 16-bits in some rare cases
254 Ppmd_See_Update(see); 254 Ppmd_See_UPDATE(see)
255 p->FoundState = s; 255 p->FoundState = s;
256 sym = s->Symbol; 256 sym = s->Symbol;
257 Ppmd7_Update2(p); 257 Ppmd7_Update2(p);
@@ -261,7 +261,7 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
261 if (count >= freqSum) 261 if (count >= freqSum)
262 return PPMD7_SYM_ERROR; 262 return PPMD7_SYM_ERROR;
263 263
264 RC_Decode(hiCnt, freqSum - hiCnt); 264 RC_Decode(hiCnt, freqSum - hiCnt)
265 265
266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. 266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols.
267 // new (see->Summ) value can overflow over 16-bits in some rare cases 267 // new (see->Summ) value can overflow over 16-bits in some rare cases
@@ -277,3 +277,19 @@ int Ppmd7a_DecodeSymbol(CPpmd7 *p)
277 while (s != s2); 277 while (s != s2);
278 } 278 }
279} 279}
280
281#undef kTop
282#undef kBot
283#undef READ_BYTE
284#undef RC_NORM_BASE
285#undef RC_NORM_1
286#undef RC_NORM
287#undef RC_NORM_LOCAL
288#undef RC_NORM_REMOTE
289#undef R
290#undef RC_Decode
291#undef RC_DecodeFinal
292#undef RC_GetThreshold
293#undef CTX
294#undef SUCCESSOR
295#undef MASK
diff --git a/C/Ppmd8.c b/C/Ppmd8.c
index fda8b88..28abf27 100644
--- a/C/Ppmd8.c
+++ b/C/Ppmd8.c
@@ -1,5 +1,5 @@
1/* Ppmd8.c -- PPMdI codec 1/* Ppmd8.c -- PPMdI codec
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */ 3This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */
4 4
5#include "Precomp.h" 5#include "Precomp.h"
@@ -14,7 +14,7 @@ This code is based on PPMd var.I (2002): Dmitry Shkarin : Public domain */
14MY_ALIGN(16) 14MY_ALIGN(16)
15static const Byte PPMD8_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; 15static const Byte PPMD8_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
16MY_ALIGN(16) 16MY_ALIGN(16)
17static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; 17static const UInt16 PPMD8_kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
18 18
19#define MAX_FREQ 124 19#define MAX_FREQ 124
20#define UNIT_SIZE 12 20#define UNIT_SIZE 12
@@ -33,7 +33,7 @@ static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x
33#define ONE_STATE(ctx) Ppmd8Context_OneState(ctx) 33#define ONE_STATE(ctx) Ppmd8Context_OneState(ctx)
34#define SUFFIX(ctx) CTX((ctx)->Suffix) 34#define SUFFIX(ctx) CTX((ctx)->Suffix)
35 35
36typedef CPpmd8_Context * CTX_PTR; 36typedef CPpmd8_Context * PPMD8_CTX_PTR;
37 37
38struct CPpmd8_Node_; 38struct CPpmd8_Node_;
39 39
@@ -114,7 +114,7 @@ BoolInt Ppmd8_Alloc(CPpmd8 *p, UInt32 size, ISzAllocPtr alloc)
114#define EMPTY_NODE 0xFFFFFFFF 114#define EMPTY_NODE 0xFFFFFFFF
115 115
116 116
117static void InsertNode(CPpmd8 *p, void *node, unsigned indx) 117static void Ppmd8_InsertNode(CPpmd8 *p, void *node, unsigned indx)
118{ 118{
119 ((CPpmd8_Node *)node)->Stamp = EMPTY_NODE; 119 ((CPpmd8_Node *)node)->Stamp = EMPTY_NODE;
120 ((CPpmd8_Node *)node)->Next = (CPpmd8_Node_Ref)p->FreeList[indx]; 120 ((CPpmd8_Node *)node)->Next = (CPpmd8_Node_Ref)p->FreeList[indx];
@@ -124,7 +124,7 @@ static void InsertNode(CPpmd8 *p, void *node, unsigned indx)
124} 124}
125 125
126 126
127static void *RemoveNode(CPpmd8 *p, unsigned indx) 127static void *Ppmd8_RemoveNode(CPpmd8 *p, unsigned indx)
128{ 128{
129 CPpmd8_Node *node = NODE((CPpmd8_Node_Ref)p->FreeList[indx]); 129 CPpmd8_Node *node = NODE((CPpmd8_Node_Ref)p->FreeList[indx]);
130 p->FreeList[indx] = node->Next; 130 p->FreeList[indx] = node->Next;
@@ -134,16 +134,16 @@ static void *RemoveNode(CPpmd8 *p, unsigned indx)
134} 134}
135 135
136 136
137static void SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx) 137static void Ppmd8_SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
138{ 138{
139 unsigned i, nu = I2U(oldIndx) - I2U(newIndx); 139 unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
140 ptr = (Byte *)ptr + U2B(I2U(newIndx)); 140 ptr = (Byte *)ptr + U2B(I2U(newIndx));
141 if (I2U(i = U2I(nu)) != nu) 141 if (I2U(i = U2I(nu)) != nu)
142 { 142 {
143 unsigned k = I2U(--i); 143 unsigned k = I2U(--i);
144 InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1); 144 Ppmd8_InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1);
145 } 145 }
146 InsertNode(p, ptr, i); 146 Ppmd8_InsertNode(p, ptr, i);
147} 147}
148 148
149 149
@@ -159,7 +159,7 @@ static void SplitBlock(CPpmd8 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
159 159
160 160
161 161
162static void GlueFreeBlocks(CPpmd8 *p) 162static void Ppmd8_GlueFreeBlocks(CPpmd8 *p)
163{ 163{
164 /* 164 /*
165 we use first UInt32 field of 12-bytes UNITs as record type stamp 165 we use first UInt32 field of 12-bytes UNITs as record type stamp
@@ -239,27 +239,27 @@ static void GlueFreeBlocks(CPpmd8 *p)
239 if (nu == 0) 239 if (nu == 0)
240 continue; 240 continue;
241 for (; nu > 128; nu -= 128, node += 128) 241 for (; nu > 128; nu -= 128, node += 128)
242 InsertNode(p, node, PPMD_NUM_INDEXES - 1); 242 Ppmd8_InsertNode(p, node, PPMD_NUM_INDEXES - 1);
243 if (I2U(i = U2I(nu)) != nu) 243 if (I2U(i = U2I(nu)) != nu)
244 { 244 {
245 unsigned k = I2U(--i); 245 unsigned k = I2U(--i);
246 InsertNode(p, node + k, (unsigned)nu - k - 1); 246 Ppmd8_InsertNode(p, node + k, (unsigned)nu - k - 1);
247 } 247 }
248 InsertNode(p, node, i); 248 Ppmd8_InsertNode(p, node, i);
249 } 249 }
250} 250}
251 251
252 252
253MY_NO_INLINE 253Z7_NO_INLINE
254static void *AllocUnitsRare(CPpmd8 *p, unsigned indx) 254static void *Ppmd8_AllocUnitsRare(CPpmd8 *p, unsigned indx)
255{ 255{
256 unsigned i; 256 unsigned i;
257 257
258 if (p->GlueCount == 0) 258 if (p->GlueCount == 0)
259 { 259 {
260 GlueFreeBlocks(p); 260 Ppmd8_GlueFreeBlocks(p);
261 if (p->FreeList[indx] != 0) 261 if (p->FreeList[indx] != 0)
262 return RemoveNode(p, indx); 262 return Ppmd8_RemoveNode(p, indx);
263 } 263 }
264 264
265 i = indx; 265 i = indx;
@@ -277,17 +277,17 @@ static void *AllocUnitsRare(CPpmd8 *p, unsigned indx)
277 while (p->FreeList[i] == 0); 277 while (p->FreeList[i] == 0);
278 278
279 { 279 {
280 void *block = RemoveNode(p, i); 280 void *block = Ppmd8_RemoveNode(p, i);
281 SplitBlock(p, block, i, indx); 281 Ppmd8_SplitBlock(p, block, i, indx);
282 return block; 282 return block;
283 } 283 }
284} 284}
285 285
286 286
287static void *AllocUnits(CPpmd8 *p, unsigned indx) 287static void *Ppmd8_AllocUnits(CPpmd8 *p, unsigned indx)
288{ 288{
289 if (p->FreeList[indx] != 0) 289 if (p->FreeList[indx] != 0)
290 return RemoveNode(p, indx); 290 return Ppmd8_RemoveNode(p, indx);
291 { 291 {
292 UInt32 numBytes = U2B(I2U(indx)); 292 UInt32 numBytes = U2B(I2U(indx));
293 Byte *lo = p->LoUnit; 293 Byte *lo = p->LoUnit;
@@ -297,11 +297,11 @@ static void *AllocUnits(CPpmd8 *p, unsigned indx)
297 return lo; 297 return lo;
298 } 298 }
299 } 299 }
300 return AllocUnitsRare(p, indx); 300 return Ppmd8_AllocUnitsRare(p, indx);
301} 301}
302 302
303 303
304#define MyMem12Cpy(dest, src, num) \ 304#define MEM_12_CPY(dest, src, num) \
305 { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \ 305 { UInt32 *d = (UInt32 *)dest; const UInt32 *z = (const UInt32 *)src; UInt32 n = num; \
306 do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); } 306 do { d[0] = z[0]; d[1] = z[1]; d[2] = z[2]; z += 3; d += 3; } while (--n); }
307 307
@@ -315,26 +315,26 @@ static void *ShrinkUnits(CPpmd8 *p, void *oldPtr, unsigned oldNU, unsigned newNU
315 return oldPtr; 315 return oldPtr;
316 if (p->FreeList[i1] != 0) 316 if (p->FreeList[i1] != 0)
317 { 317 {
318 void *ptr = RemoveNode(p, i1); 318 void *ptr = Ppmd8_RemoveNode(p, i1);
319 MyMem12Cpy(ptr, oldPtr, newNU); 319 MEM_12_CPY(ptr, oldPtr, newNU)
320 InsertNode(p, oldPtr, i0); 320 Ppmd8_InsertNode(p, oldPtr, i0);
321 return ptr; 321 return ptr;
322 } 322 }
323 SplitBlock(p, oldPtr, i0, i1); 323 Ppmd8_SplitBlock(p, oldPtr, i0, i1);
324 return oldPtr; 324 return oldPtr;
325} 325}
326 326
327 327
328static void FreeUnits(CPpmd8 *p, void *ptr, unsigned nu) 328static void FreeUnits(CPpmd8 *p, void *ptr, unsigned nu)
329{ 329{
330 InsertNode(p, ptr, U2I(nu)); 330 Ppmd8_InsertNode(p, ptr, U2I(nu));
331} 331}
332 332
333 333
334static void SpecialFreeUnit(CPpmd8 *p, void *ptr) 334static void SpecialFreeUnit(CPpmd8 *p, void *ptr)
335{ 335{
336 if ((Byte *)ptr != p->UnitsStart) 336 if ((Byte *)ptr != p->UnitsStart)
337 InsertNode(p, ptr, 0); 337 Ppmd8_InsertNode(p, ptr, 0);
338 else 338 else
339 { 339 {
340 #ifdef PPMD8_FREEZE_SUPPORT 340 #ifdef PPMD8_FREEZE_SUPPORT
@@ -352,10 +352,10 @@ static void *MoveUnitsUp(CPpmd8 *p, void *oldPtr, unsigned nu)
352 void *ptr; 352 void *ptr;
353 if ((Byte *)oldPtr > p->UnitsStart + (1 << 14) || REF(oldPtr) > p->FreeList[indx]) 353 if ((Byte *)oldPtr > p->UnitsStart + (1 << 14) || REF(oldPtr) > p->FreeList[indx])
354 return oldPtr; 354 return oldPtr;
355 ptr = RemoveNode(p, indx); 355 ptr = Ppmd8_RemoveNode(p, indx);
356 MyMem12Cpy(ptr, oldPtr, nu); 356 MEM_12_CPY(ptr, oldPtr, nu)
357 if ((Byte *)oldPtr != p->UnitsStart) 357 if ((Byte *)oldPtr != p->UnitsStart)
358 InsertNode(p, oldPtr, indx); 358 Ppmd8_InsertNode(p, oldPtr, indx);
359 else 359 else
360 p->UnitsStart += U2B(I2U(indx)); 360 p->UnitsStart += U2B(I2U(indx));
361 return ptr; 361 return ptr;
@@ -411,22 +411,22 @@ static void ExpandTextArea(CPpmd8 *p)
411 411
412 412
413#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 413#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
414static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v) 414static void Ppmd8State_SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v)
415{ 415{
416 Ppmd_SET_SUCCESSOR(p, v); 416 Ppmd_SET_SUCCESSOR(p, v)
417} 417}
418 418
419#define RESET_TEXT(offs) { p->Text = p->Base + p->AlignOffset + (offs); } 419#define RESET_TEXT(offs) { p->Text = p->Base + p->AlignOffset + (offs); }
420 420
421MY_NO_INLINE 421Z7_NO_INLINE
422static 422static
423void RestartModel(CPpmd8 *p) 423void Ppmd8_RestartModel(CPpmd8 *p)
424{ 424{
425 unsigned i, k, m; 425 unsigned i, k, m;
426 426
427 memset(p->FreeList, 0, sizeof(p->FreeList)); 427 memset(p->FreeList, 0, sizeof(p->FreeList));
428 memset(p->Stamps, 0, sizeof(p->Stamps)); 428 memset(p->Stamps, 0, sizeof(p->Stamps));
429 RESET_TEXT(0); 429 RESET_TEXT(0)
430 p->HiUnit = p->Text + p->Size; 430 p->HiUnit = p->Text + p->Size;
431 p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE; 431 p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE;
432 p->GlueCount = 0; 432 p->GlueCount = 0;
@@ -436,8 +436,8 @@ void RestartModel(CPpmd8 *p)
436 p->PrevSuccess = 0; 436 p->PrevSuccess = 0;
437 437
438 { 438 {
439 CPpmd8_Context *mc = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */ 439 CPpmd8_Context *mc = (PPMD8_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
440 CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */ 440 CPpmd_State *s = (CPpmd_State *)p->LoUnit; /* Ppmd8_AllocUnits(p, PPMD_NUM_INDEXES - 1); */
441 441
442 p->LoUnit += U2B(256 / 2); 442 p->LoUnit += U2B(256 / 2);
443 p->MaxContext = p->MinContext = mc; 443 p->MaxContext = p->MinContext = mc;
@@ -452,7 +452,7 @@ void RestartModel(CPpmd8 *p)
452 { 452 {
453 s->Symbol = (Byte)i; 453 s->Symbol = (Byte)i;
454 s->Freq = 1; 454 s->Freq = 1;
455 SetSuccessor(s, 0); 455 Ppmd8State_SetSuccessor(s, 0);
456 } 456 }
457 } 457 }
458 458
@@ -475,7 +475,7 @@ void RestartModel(CPpmd8 *p)
475 { 475 {
476 unsigned r; 476 unsigned r;
477 UInt16 *dest = p->BinSumm[m] + k; 477 UInt16 *dest = p->BinSumm[m] + k;
478 UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 1)); 478 const UInt16 val = (UInt16)(PPMD_BIN_SCALE - PPMD8_kInitBinEsc[k] / (i + 1));
479 for (r = 0; r < 64; r += 8) 479 for (r = 0; r < 64; r += 8)
480 dest[r] = val; 480 dest[r] = val;
481 } 481 }
@@ -507,7 +507,7 @@ void Ppmd8_Init(CPpmd8 *p, unsigned maxOrder, unsigned restoreMethod)
507{ 507{
508 p->MaxOrder = maxOrder; 508 p->MaxOrder = maxOrder;
509 p->RestoreMethod = restoreMethod; 509 p->RestoreMethod = restoreMethod;
510 RestartModel(p); 510 Ppmd8_RestartModel(p);
511} 511}
512 512
513 513
@@ -531,7 +531,7 @@ Refresh() is called when we remove some symbols (successors) in context.
531It increases Escape_Freq for sum of all removed symbols. 531It increases Escape_Freq for sum of all removed symbols.
532*/ 532*/
533 533
534static void Refresh(CPpmd8 *p, CTX_PTR ctx, unsigned oldNU, unsigned scale) 534static void Refresh(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned oldNU, unsigned scale)
535{ 535{
536 unsigned i = ctx->NumStats, escFreq, sumFreq, flags; 536 unsigned i = ctx->NumStats, escFreq, sumFreq, flags;
537 CPpmd_State *s = (CPpmd_State *)ShrinkUnits(p, STATS(ctx), oldNU, (i + 2) >> 1); 537 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)
581} 581}
582 582
583 583
584static void SwapStates(CPpmd_State *t1, CPpmd_State *t2) 584static void SWAP_STATES(CPpmd_State *t1, CPpmd_State *t2)
585{ 585{
586 CPpmd_State tmp = *t1; 586 CPpmd_State tmp = *t1;
587 *t1 = *t2; 587 *t1 = *t2;
@@ -597,7 +597,7 @@ CutOff() reduces contexts:
597 if the (Union4.Stats) is close to (UnitsStart), it moves it up. 597 if the (Union4.Stats) is close to (UnitsStart), it moves it up.
598*/ 598*/
599 599
600static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order) 600static CPpmd_Void_Ref CutOff(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned order)
601{ 601{
602 int ns = ctx->NumStats; 602 int ns = ctx->NumStats;
603 unsigned nu; 603 unsigned nu;
@@ -613,7 +613,7 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order)
613 successor = CutOff(p, CTX(successor), order + 1); 613 successor = CutOff(p, CTX(successor), order + 1);
614 else 614 else
615 successor = 0; 615 successor = 0;
616 SetSuccessor(s, successor); 616 Ppmd8State_SetSuccessor(s, successor);
617 if (successor || order <= 9) /* O_BOUND */ 617 if (successor || order <= 9) /* O_BOUND */
618 return REF(ctx); 618 return REF(ctx);
619 } 619 }
@@ -630,11 +630,11 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order)
630 if ((UInt32)((Byte *)stats - p->UnitsStart) <= (1 << 14) 630 if ((UInt32)((Byte *)stats - p->UnitsStart) <= (1 << 14)
631 && (CPpmd_Void_Ref)ctx->Union4.Stats <= p->FreeList[indx]) 631 && (CPpmd_Void_Ref)ctx->Union4.Stats <= p->FreeList[indx])
632 { 632 {
633 void *ptr = RemoveNode(p, indx); 633 void *ptr = Ppmd8_RemoveNode(p, indx);
634 ctx->Union4.Stats = STATS_REF(ptr); 634 ctx->Union4.Stats = STATS_REF(ptr);
635 MyMem12Cpy(ptr, (const void *)stats, nu); 635 MEM_12_CPY(ptr, (const void *)stats, nu)
636 if ((Byte *)stats != p->UnitsStart) 636 if ((Byte *)stats != p->UnitsStart)
637 InsertNode(p, stats, indx); 637 Ppmd8_InsertNode(p, stats, indx);
638 else 638 else
639 p->UnitsStart += U2B(I2U(indx)); 639 p->UnitsStart += U2B(I2U(indx));
640 stats = ptr; 640 stats = ptr;
@@ -656,16 +656,16 @@ static CPpmd_Void_Ref CutOff(CPpmd8 *p, CTX_PTR ctx, unsigned order)
656 } 656 }
657 else 657 else
658 { 658 {
659 SwapStates(s, s2); 659 SWAP_STATES(s, s2);
660 SetSuccessor(s2, 0); 660 Ppmd8State_SetSuccessor(s2, 0);
661 } 661 }
662 } 662 }
663 else 663 else
664 { 664 {
665 if (order < p->MaxOrder) 665 if (order < p->MaxOrder)
666 SetSuccessor(s, CutOff(p, CTX(successor), order + 1)); 666 Ppmd8State_SetSuccessor(s, CutOff(p, CTX(successor), order + 1));
667 else 667 else
668 SetSuccessor(s, 0); 668 Ppmd8State_SetSuccessor(s, 0);
669 } 669 }
670 } 670 }
671 while (--s >= stats); 671 while (--s >= stats);
@@ -711,7 +711,7 @@ RemoveBinContexts()
711 removes Bin Context without Successor, if suffix of that context is also binary. 711 removes Bin Context without Successor, if suffix of that context is also binary.
712*/ 712*/
713 713
714static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order) 714static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, PPMD8_CTX_PTR ctx, unsigned order)
715{ 715{
716 if (!ctx->NumStats) 716 if (!ctx->NumStats)
717 { 717 {
@@ -721,7 +721,7 @@ static CPpmd_Void_Ref RemoveBinContexts(CPpmd8 *p, CTX_PTR ctx, unsigned order)
721 successor = RemoveBinContexts(p, CTX(successor), order + 1); 721 successor = RemoveBinContexts(p, CTX(successor), order + 1);
722 else 722 else
723 successor = 0; 723 successor = 0;
724 SetSuccessor(s, successor); 724 Ppmd8State_SetSuccessor(s, successor);
725 /* Suffix context can be removed already, since different (high-order) 725 /* Suffix context can be removed already, since different (high-order)
726 Successors may refer to same context. So we check Flags == 0xFF (Stamp == EMPTY_NODE) */ 726 Successors may refer to same context. So we check Flags == 0xFF (Stamp == EMPTY_NODE) */
727 if (!successor && (!SUFFIX(ctx)->NumStats || SUFFIX(ctx)->Flags == 0xFF)) 727 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)
737 { 737 {
738 CPpmd_Void_Ref successor = SUCCESSOR(s); 738 CPpmd_Void_Ref successor = SUCCESSOR(s);
739 if ((Byte *)Ppmd8_GetPtr(p, successor) >= p->UnitsStart && order < p->MaxOrder) 739 if ((Byte *)Ppmd8_GetPtr(p, successor) >= p->UnitsStart && order < p->MaxOrder)
740 SetSuccessor(s, RemoveBinContexts(p, CTX(successor), order + 1)); 740 Ppmd8State_SetSuccessor(s, RemoveBinContexts(p, CTX(successor), order + 1));
741 else 741 else
742 SetSuccessor(s, 0); 742 Ppmd8State_SetSuccessor(s, 0);
743 } 743 }
744 while (--s >= STATS(ctx)); 744 while (--s >= STATS(ctx));
745 } 745 }
@@ -767,15 +767,15 @@ static UInt32 GetUsedMemory(const CPpmd8 *p)
767#endif 767#endif
768 768
769 769
770static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError 770static void RestoreModel(CPpmd8 *p, PPMD8_CTX_PTR ctxError
771 #ifdef PPMD8_FREEZE_SUPPORT 771 #ifdef PPMD8_FREEZE_SUPPORT
772 , CTX_PTR fSuccessor 772 , PPMD8_CTX_PTR fSuccessor
773 #endif 773 #endif
774 ) 774 )
775{ 775{
776 CTX_PTR c; 776 PPMD8_CTX_PTR c;
777 CPpmd_State *s; 777 CPpmd_State *s;
778 RESET_TEXT(0); 778 RESET_TEXT(0)
779 779
780 // we go here in cases of error of allocation for context (c1) 780 // we go here in cases of error of allocation for context (c1)
781 // Order(MinContext) < Order(ctxError) <= Order(MaxContext) 781 // Order(MinContext) < Order(ctxError) <= Order(MaxContext)
@@ -831,7 +831,7 @@ static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError
831 else 831 else
832 #endif 832 #endif
833 if (p->RestoreMethod == PPMD8_RESTORE_METHOD_RESTART || GetUsedMemory(p) < (p->Size >> 1)) 833 if (p->RestoreMethod == PPMD8_RESTORE_METHOD_RESTART || GetUsedMemory(p) < (p->Size >> 1))
834 RestartModel(p); 834 Ppmd8_RestartModel(p);
835 else 835 else
836 { 836 {
837 while (p->MaxContext->Suffix) 837 while (p->MaxContext->Suffix)
@@ -850,8 +850,8 @@ static void RestoreModel(CPpmd8 *p, CTX_PTR ctxError
850 850
851 851
852 852
853MY_NO_INLINE 853Z7_NO_INLINE
854static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PTR c) 854static PPMD8_CTX_PTR Ppmd8_CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, PPMD8_CTX_PTR c)
855{ 855{
856 856
857 CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState); 857 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
927 927
928 do 928 do
929 { 929 {
930 CTX_PTR c1; 930 PPMD8_CTX_PTR c1;
931 /* = AllocContext(p); */ 931 /* = AllocContext(p); */
932 if (p->HiUnit != p->LoUnit) 932 if (p->HiUnit != p->LoUnit)
933 c1 = (CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE); 933 c1 = (PPMD8_CTX_PTR)(void *)(p->HiUnit -= UNIT_SIZE);
934 else if (p->FreeList[0] != 0) 934 else if (p->FreeList[0] != 0)
935 c1 = (CTX_PTR)RemoveNode(p, 0); 935 c1 = (PPMD8_CTX_PTR)Ppmd8_RemoveNode(p, 0);
936 else 936 else
937 { 937 {
938 c1 = (CTX_PTR)AllocUnitsRare(p, 0); 938 c1 = (PPMD8_CTX_PTR)Ppmd8_AllocUnitsRare(p, 0);
939 if (!c1) 939 if (!c1)
940 return NULL; 940 return NULL;
941 } 941 }
@@ -943,9 +943,9 @@ static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PT
943 c1->NumStats = 0; 943 c1->NumStats = 0;
944 c1->Union2.State2.Symbol = newSym; 944 c1->Union2.State2.Symbol = newSym;
945 c1->Union2.State2.Freq = newFreq; 945 c1->Union2.State2.Freq = newFreq;
946 SetSuccessor(ONE_STATE(c1), upBranch); 946 Ppmd8State_SetSuccessor(ONE_STATE(c1), upBranch);
947 c1->Suffix = REF(c); 947 c1->Suffix = REF(c);
948 SetSuccessor(ps[--numPs], REF(c1)); 948 Ppmd8State_SetSuccessor(ps[--numPs], REF(c1));
949 c = c1; 949 c = c1;
950 } 950 }
951 while (numPs != 0); 951 while (numPs != 0);
@@ -954,10 +954,10 @@ static CTX_PTR CreateSuccessors(CPpmd8 *p, BoolInt skip, CPpmd_State *s1, CTX_PT
954} 954}
955 955
956 956
957static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c) 957static PPMD8_CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, PPMD8_CTX_PTR c)
958{ 958{
959 CPpmd_State *s = NULL; 959 CPpmd_State *s = NULL;
960 CTX_PTR c1 = c; 960 PPMD8_CTX_PTR c1 = c;
961 CPpmd_Void_Ref upBranch = REF(p->Text); 961 CPpmd_Void_Ref upBranch = REF(p->Text);
962 962
963 #ifdef PPMD8_FREEZE_SUPPORT 963 #ifdef PPMD8_FREEZE_SUPPORT
@@ -967,7 +967,7 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
967 ps[numPs++] = p->FoundState; 967 ps[numPs++] = p->FoundState;
968 #endif 968 #endif
969 969
970 SetSuccessor(p->FoundState, upBranch); 970 Ppmd8State_SetSuccessor(p->FoundState, upBranch);
971 p->OrderFall++; 971 p->OrderFall++;
972 972
973 for (;;) 973 for (;;)
@@ -985,8 +985,8 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
985 #ifdef PPMD8_FREEZE_SUPPORT 985 #ifdef PPMD8_FREEZE_SUPPORT
986 if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) 986 if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
987 { 987 {
988 do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); 988 do { Ppmd8State_SetSuccessor(ps[--numPs], REF(c)); } while (numPs);
989 RESET_TEXT(1); 989 RESET_TEXT(1)
990 p->OrderFall = 1; 990 p->OrderFall = 1;
991 } 991 }
992 #endif 992 #endif
@@ -1014,7 +1014,7 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
1014 #ifdef PPMD8_FREEZE_SUPPORT 1014 #ifdef PPMD8_FREEZE_SUPPORT
1015 ps[numPs++] = s; 1015 ps[numPs++] = s;
1016 #endif 1016 #endif
1017 SetSuccessor(s, upBranch); 1017 Ppmd8State_SetSuccessor(s, upBranch);
1018 p->OrderFall++; 1018 p->OrderFall++;
1019 } 1019 }
1020 1020
@@ -1022,8 +1022,8 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
1022 if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) 1022 if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
1023 { 1023 {
1024 c = CTX(SUCCESSOR(s)); 1024 c = CTX(SUCCESSOR(s));
1025 do { SetSuccessor(ps[--numPs], REF(c)); } while (numPs); 1025 do { Ppmd8State_SetSuccessor(ps[--numPs], REF(c)); } while (numPs);
1026 RESET_TEXT(1); 1026 RESET_TEXT(1)
1027 p->OrderFall = 1; 1027 p->OrderFall = 1;
1028 return c; 1028 return c;
1029 } 1029 }
@@ -1031,15 +1031,15 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
1031 #endif 1031 #endif
1032 if (SUCCESSOR(s) <= upBranch) 1032 if (SUCCESSOR(s) <= upBranch)
1033 { 1033 {
1034 CTX_PTR successor; 1034 PPMD8_CTX_PTR successor;
1035 CPpmd_State *s2 = p->FoundState; 1035 CPpmd_State *s2 = p->FoundState;
1036 p->FoundState = s; 1036 p->FoundState = s;
1037 1037
1038 successor = CreateSuccessors(p, False, NULL, c); 1038 successor = Ppmd8_CreateSuccessors(p, False, NULL, c);
1039 if (!successor) 1039 if (!successor)
1040 SetSuccessor(s, 0); 1040 Ppmd8State_SetSuccessor(s, 0);
1041 else 1041 else
1042 SetSuccessor(s, REF(successor)); 1042 Ppmd8State_SetSuccessor(s, REF(successor));
1043 p->FoundState = s2; 1043 p->FoundState = s2;
1044 } 1044 }
1045 1045
@@ -1047,7 +1047,7 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
1047 CPpmd_Void_Ref successor = SUCCESSOR(s); 1047 CPpmd_Void_Ref successor = SUCCESSOR(s);
1048 if (p->OrderFall == 1 && c1 == p->MaxContext) 1048 if (p->OrderFall == 1 && c1 == p->MaxContext)
1049 { 1049 {
1050 SetSuccessor(p->FoundState, successor); 1050 Ppmd8State_SetSuccessor(p->FoundState, successor);
1051 p->Text--; 1051 p->Text--;
1052 } 1052 }
1053 if (successor == 0) 1053 if (successor == 0)
@@ -1059,11 +1059,11 @@ static CTX_PTR ReduceOrder(CPpmd8 *p, CPpmd_State *s1, CTX_PTR c)
1059 1059
1060 1060
1061void Ppmd8_UpdateModel(CPpmd8 *p); 1061void Ppmd8_UpdateModel(CPpmd8 *p);
1062MY_NO_INLINE 1062Z7_NO_INLINE
1063void Ppmd8_UpdateModel(CPpmd8 *p) 1063void Ppmd8_UpdateModel(CPpmd8 *p)
1064{ 1064{
1065 CPpmd_Void_Ref maxSuccessor, minSuccessor = SUCCESSOR(p->FoundState); 1065 CPpmd_Void_Ref maxSuccessor, minSuccessor = SUCCESSOR(p->FoundState);
1066 CTX_PTR c; 1066 PPMD8_CTX_PTR c;
1067 unsigned s0, ns, fFreq = p->FoundState->Freq; 1067 unsigned s0, ns, fFreq = p->FoundState->Freq;
1068 Byte flag, fSymbol = p->FoundState->Symbol; 1068 Byte flag, fSymbol = p->FoundState->Symbol;
1069 { 1069 {
@@ -1096,7 +1096,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1096 1096
1097 if (s[0].Freq >= s[-1].Freq) 1097 if (s[0].Freq >= s[-1].Freq)
1098 { 1098 {
1099 SwapStates(&s[0], &s[-1]); 1099 SWAP_STATES(&s[0], &s[-1]);
1100 s--; 1100 s--;
1101 } 1101 }
1102 } 1102 }
@@ -1112,14 +1112,14 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1112 c = p->MaxContext; 1112 c = p->MaxContext;
1113 if (p->OrderFall == 0 && minSuccessor) 1113 if (p->OrderFall == 0 && minSuccessor)
1114 { 1114 {
1115 CTX_PTR cs = CreateSuccessors(p, True, s, p->MinContext); 1115 PPMD8_CTX_PTR cs = Ppmd8_CreateSuccessors(p, True, s, p->MinContext);
1116 if (!cs) 1116 if (!cs)
1117 { 1117 {
1118 SetSuccessor(p->FoundState, 0); 1118 Ppmd8State_SetSuccessor(p->FoundState, 0);
1119 RESTORE_MODEL(c, CTX(minSuccessor)); 1119 RESTORE_MODEL(c, CTX(minSuccessor));
1120 return; 1120 return;
1121 } 1121 }
1122 SetSuccessor(p->FoundState, REF(cs)); 1122 Ppmd8State_SetSuccessor(p->FoundState, REF(cs));
1123 p->MinContext = p->MaxContext = cs; 1123 p->MinContext = p->MaxContext = cs;
1124 return; 1124 return;
1125 } 1125 }
@@ -1141,7 +1141,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1141 1141
1142 if (!minSuccessor) 1142 if (!minSuccessor)
1143 { 1143 {
1144 CTX_PTR cs = ReduceOrder(p, s, p->MinContext); 1144 PPMD8_CTX_PTR cs = ReduceOrder(p, s, p->MinContext);
1145 if (!cs) 1145 if (!cs)
1146 { 1146 {
1147 RESTORE_MODEL(c, NULL); 1147 RESTORE_MODEL(c, NULL);
@@ -1151,7 +1151,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1151 } 1151 }
1152 else if ((Byte *)Ppmd8_GetPtr(p, minSuccessor) < p->UnitsStart) 1152 else if ((Byte *)Ppmd8_GetPtr(p, minSuccessor) < p->UnitsStart)
1153 { 1153 {
1154 CTX_PTR cs = CreateSuccessors(p, False, s, p->MinContext); 1154 PPMD8_CTX_PTR cs = Ppmd8_CreateSuccessors(p, False, s, p->MinContext);
1155 if (!cs) 1155 if (!cs)
1156 { 1156 {
1157 RESTORE_MODEL(c, NULL); 1157 RESTORE_MODEL(c, NULL);
@@ -1169,7 +1169,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1169 else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE) 1169 else if (p->RestoreMethod > PPMD8_RESTORE_METHOD_FREEZE)
1170 { 1170 {
1171 maxSuccessor = minSuccessor; 1171 maxSuccessor = minSuccessor;
1172 RESET_TEXT(0); 1172 RESET_TEXT(0)
1173 p->OrderFall = 0; 1173 p->OrderFall = 0;
1174 } 1174 }
1175 #endif 1175 #endif
@@ -1219,7 +1219,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1219 unsigned i = U2I(oldNU); 1219 unsigned i = U2I(oldNU);
1220 if (i != U2I((size_t)oldNU + 1)) 1220 if (i != U2I((size_t)oldNU + 1))
1221 { 1221 {
1222 void *ptr = AllocUnits(p, i + 1); 1222 void *ptr = Ppmd8_AllocUnits(p, i + 1);
1223 void *oldPtr; 1223 void *oldPtr;
1224 if (!ptr) 1224 if (!ptr)
1225 { 1225 {
@@ -1227,8 +1227,8 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1227 return; 1227 return;
1228 } 1228 }
1229 oldPtr = STATS(c); 1229 oldPtr = STATS(c);
1230 MyMem12Cpy(ptr, oldPtr, oldNU); 1230 MEM_12_CPY(ptr, oldPtr, oldNU)
1231 InsertNode(p, oldPtr, i); 1231 Ppmd8_InsertNode(p, oldPtr, i);
1232 c->Union4.Stats = STATS_REF(ptr); 1232 c->Union4.Stats = STATS_REF(ptr);
1233 } 1233 }
1234 } 1234 }
@@ -1243,7 +1243,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1243 else 1243 else
1244 { 1244 {
1245 1245
1246 CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0); 1246 CPpmd_State *s = (CPpmd_State*)Ppmd8_AllocUnits(p, 0);
1247 if (!s) 1247 if (!s)
1248 { 1248 {
1249 RESTORE_MODEL(c, CTX(minSuccessor)); 1249 RESTORE_MODEL(c, CTX(minSuccessor));
@@ -1255,7 +1255,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1255 s->Symbol = c->Union2.State2.Symbol; 1255 s->Symbol = c->Union2.State2.Symbol;
1256 s->Successor_0 = c->Union4.State4.Successor_0; 1256 s->Successor_0 = c->Union4.State4.Successor_0;
1257 s->Successor_1 = c->Union4.State4.Successor_1; 1257 s->Successor_1 = c->Union4.State4.Successor_1;
1258 // SetSuccessor(s, c->Union4.Stats); // call it only for debug purposes to check the order of 1258 // Ppmd8State_SetSuccessor(s, c->Union4.Stats); // call it only for debug purposes to check the order of
1259 // (Successor_0 and Successor_1) in LE/BE. 1259 // (Successor_0 and Successor_1) in LE/BE.
1260 c->Union4.Stats = REF(s); 1260 c->Union4.Stats = REF(s);
1261 if (freq < MAX_FREQ / 4 - 1) 1261 if (freq < MAX_FREQ / 4 - 1)
@@ -1275,7 +1275,7 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1275 UInt32 sf = (UInt32)s0 + sum; 1275 UInt32 sf = (UInt32)s0 + sum;
1276 s->Symbol = fSymbol; 1276 s->Symbol = fSymbol;
1277 c->NumStats = (Byte)(ns1 + 1); 1277 c->NumStats = (Byte)(ns1 + 1);
1278 SetSuccessor(s, maxSuccessor); 1278 Ppmd8State_SetSuccessor(s, maxSuccessor);
1279 c->Flags |= flag; 1279 c->Flags |= flag;
1280 if (cf < 6 * sf) 1280 if (cf < 6 * sf)
1281 { 1281 {
@@ -1299,8 +1299,8 @@ void Ppmd8_UpdateModel(CPpmd8 *p)
1299 1299
1300 1300
1301 1301
1302MY_NO_INLINE 1302Z7_NO_INLINE
1303static void Rescale(CPpmd8 *p) 1303static void Ppmd8_Rescale(CPpmd8 *p)
1304{ 1304{
1305 unsigned i, adder, sumFreq, escFreq; 1305 unsigned i, adder, sumFreq, escFreq;
1306 CPpmd_State *stats = STATS(p->MinContext); 1306 CPpmd_State *stats = STATS(p->MinContext);
@@ -1389,7 +1389,7 @@ static void Rescale(CPpmd8 *p)
1389 *s = *stats; 1389 *s = *stats;
1390 s->Freq = (Byte)freq; 1390 s->Freq = (Byte)freq;
1391 p->FoundState = s; 1391 p->FoundState = s;
1392 InsertNode(p, stats, U2I(n0)); 1392 Ppmd8_InsertNode(p, stats, U2I(n0));
1393 return; 1393 return;
1394 } 1394 }
1395 1395
@@ -1452,9 +1452,9 @@ CPpmd_See *Ppmd8_MakeEscFreq(CPpmd8 *p, unsigned numMasked1, UInt32 *escFreq)
1452} 1452}
1453 1453
1454 1454
1455static void NextContext(CPpmd8 *p) 1455static void Ppmd8_NextContext(CPpmd8 *p)
1456{ 1456{
1457 CTX_PTR c = CTX(SUCCESSOR(p->FoundState)); 1457 PPMD8_CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
1458 if (p->OrderFall == 0 && (const Byte *)c >= p->UnitsStart) 1458 if (p->OrderFall == 0 && (const Byte *)c >= p->UnitsStart)
1459 p->MaxContext = p->MinContext = c; 1459 p->MaxContext = p->MinContext = c;
1460 else 1460 else
@@ -1471,12 +1471,12 @@ void Ppmd8_Update1(CPpmd8 *p)
1471 s->Freq = (Byte)freq; 1471 s->Freq = (Byte)freq;
1472 if (freq > s[-1].Freq) 1472 if (freq > s[-1].Freq)
1473 { 1473 {
1474 SwapStates(s, &s[-1]); 1474 SWAP_STATES(s, &s[-1]);
1475 p->FoundState = --s; 1475 p->FoundState = --s;
1476 if (freq > MAX_FREQ) 1476 if (freq > MAX_FREQ)
1477 Rescale(p); 1477 Ppmd8_Rescale(p);
1478 } 1478 }
1479 NextContext(p); 1479 Ppmd8_NextContext(p);
1480} 1480}
1481 1481
1482 1482
@@ -1492,8 +1492,8 @@ void Ppmd8_Update1_0(CPpmd8 *p)
1492 freq += 4; 1492 freq += 4;
1493 s->Freq = (Byte)freq; 1493 s->Freq = (Byte)freq;
1494 if (freq > MAX_FREQ) 1494 if (freq > MAX_FREQ)
1495 Rescale(p); 1495 Ppmd8_Rescale(p);
1496 NextContext(p); 1496 Ppmd8_NextContext(p);
1497} 1497}
1498 1498
1499 1499
@@ -1504,7 +1504,7 @@ void Ppmd8_UpdateBin(CPpmd8 *p)
1504 p->FoundState->Freq = (Byte)(freq + (freq < 196)); // Ppmd8 (196) 1504 p->FoundState->Freq = (Byte)(freq + (freq < 196)); // Ppmd8 (196)
1505 p->PrevSuccess = 1; 1505 p->PrevSuccess = 1;
1506 p->RunLength++; 1506 p->RunLength++;
1507 NextContext(p); 1507 Ppmd8_NextContext(p);
1508} 1508}
1509*/ 1509*/
1510 1510
@@ -1517,7 +1517,7 @@ void Ppmd8_Update2(CPpmd8 *p)
1517 p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4); 1517 p->MinContext->Union2.SummFreq = (UInt16)(p->MinContext->Union2.SummFreq + 4);
1518 s->Freq = (Byte)freq; 1518 s->Freq = (Byte)freq;
1519 if (freq > MAX_FREQ) 1519 if (freq > MAX_FREQ)
1520 Rescale(p); 1520 Ppmd8_Rescale(p);
1521 Ppmd8_UpdateModel(p); 1521 Ppmd8_UpdateModel(p);
1522} 1522}
1523 1523
@@ -1526,7 +1526,7 @@ void Ppmd8_Update2(CPpmd8 *p)
1526 GlueCount, and Glue method 1526 GlueCount, and Glue method
1527 BinSum 1527 BinSum
1528 See / EscFreq 1528 See / EscFreq
1529 CreateSuccessors updates more suffix contexts 1529 Ppmd8_CreateSuccessors updates more suffix contexts
1530 Ppmd8_UpdateModel consts. 1530 Ppmd8_UpdateModel consts.
1531 PrevSuccess Update 1531 PrevSuccess Update
1532 1532
@@ -1535,3 +1535,31 @@ Flags:
1535 (1 << 3) - there is symbol in Stats with (sym >= 0x40) in 1535 (1 << 3) - there is symbol in Stats with (sym >= 0x40) in
1536 (1 << 4) - main symbol of context is (sym >= 0x40) 1536 (1 << 4) - main symbol of context is (sym >= 0x40)
1537*/ 1537*/
1538
1539#undef RESET_TEXT
1540#undef FLAG_RESCALED
1541#undef FLAG_PREV_HIGH
1542#undef HiBits_Prepare
1543#undef HiBits_Convert_3
1544#undef HiBits_Convert_4
1545#undef PPMD8_HiBitsFlag_3
1546#undef PPMD8_HiBitsFlag_4
1547#undef RESTORE_MODEL
1548
1549#undef MAX_FREQ
1550#undef UNIT_SIZE
1551#undef U2B
1552#undef U2I
1553#undef I2U
1554
1555#undef REF
1556#undef STATS_REF
1557#undef CTX
1558#undef STATS
1559#undef ONE_STATE
1560#undef SUFFIX
1561#undef NODE
1562#undef EMPTY_NODE
1563#undef MEM_12_CPY
1564#undef SUCCESSOR
1565#undef SWAP_STATES
diff --git a/C/Ppmd8.h b/C/Ppmd8.h
index fe93fe7..d5bb57e 100644
--- a/C/Ppmd8.h
+++ b/C/Ppmd8.h
@@ -1,11 +1,11 @@
1/* Ppmd8.h -- Ppmd8 (PPMdI) compression codec 1/* Ppmd8.h -- Ppmd8 (PPMdI) compression codec
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.I (2002): Dmitry Shkarin : Public domain 4 PPMd var.I (2002): Dmitry Shkarin : Public domain
5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ 5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
6 6
7#ifndef __PPMD8_H 7#ifndef ZIP7_INC_PPMD8_H
8#define __PPMD8_H 8#define ZIP7_INC_PPMD8_H
9 9
10#include "Ppmd.h" 10#include "Ppmd.h"
11 11
@@ -87,8 +87,8 @@ typedef struct
87 UInt32 Low; 87 UInt32 Low;
88 union 88 union
89 { 89 {
90 IByteIn *In; 90 IByteInPtr In;
91 IByteOut *Out; 91 IByteOutPtr Out;
92 } Stream; 92 } Stream;
93 93
94 Byte Indx2Units[PPMD_NUM_INDEXES + 2]; // +2 for alignment 94 Byte Indx2Units[PPMD_NUM_INDEXES + 2]; // +2 for alignment
diff --git a/C/Ppmd8Dec.c b/C/Ppmd8Dec.c
index d205de2..72d3626 100644
--- a/C/Ppmd8Dec.c
+++ b/C/Ppmd8Dec.c
@@ -1,5 +1,5 @@
1/* Ppmd8Dec.c -- Ppmd8 (PPMdI) Decoder 1/* Ppmd8Dec.c -- Ppmd8 (PPMdI) Decoder
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.I (2002): Dmitry Shkarin : Public domain 4 PPMd var.I (2002): Dmitry Shkarin : Public domain
5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ 5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
@@ -8,8 +8,8 @@ This code is based on:
8 8
9#include "Ppmd8.h" 9#include "Ppmd8.h"
10 10
11#define kTop (1 << 24) 11#define kTop ((UInt32)1 << 24)
12#define kBot (1 << 15) 12#define kBot ((UInt32)1 << 15)
13 13
14#define READ_BYTE(p) IByteIn_Read((p)->Stream.In) 14#define READ_BYTE(p) IByteIn_Read((p)->Stream.In)
15 15
@@ -37,9 +37,9 @@ BoolInt Ppmd8_Init_RangeDec(CPpmd8 *p)
37 37
38#define R p 38#define R p
39 39
40MY_FORCE_INLINE 40Z7_FORCE_INLINE
41// MY_NO_INLINE 41// Z7_NO_INLINE
42static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size) 42static void Ppmd8_RD_Decode(CPpmd8 *p, UInt32 start, UInt32 size)
43{ 43{
44 start *= R->Range; 44 start *= R->Range;
45 R->Low += start; 45 R->Low += start;
@@ -48,13 +48,13 @@ static void RangeDec_Decode(CPpmd8 *p, UInt32 start, UInt32 size)
48 RC_NORM_LOCAL(R) 48 RC_NORM_LOCAL(R)
49} 49}
50 50
51#define RC_Decode(start, size) RangeDec_Decode(p, start, size); 51#define RC_Decode(start, size) Ppmd8_RD_Decode(p, start, size);
52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R) 52#define RC_DecodeFinal(start, size) RC_Decode(start, size) RC_NORM_REMOTE(R)
53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total))) 53#define RC_GetThreshold(total) (R->Code / (R->Range /= (total)))
54 54
55 55
56#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref)) 56#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref))
57typedef CPpmd8_Context * CTX_PTR; 57// typedef CPpmd8_Context * CTX_PTR;
58#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 58#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
59void Ppmd8_UpdateModel(CPpmd8 *p); 59void Ppmd8_UpdateModel(CPpmd8 *p);
60 60
@@ -81,7 +81,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
81 if ((Int32)(count -= s->Freq) < 0) 81 if ((Int32)(count -= s->Freq) < 0)
82 { 82 {
83 Byte sym; 83 Byte sym;
84 RC_DecodeFinal(0, s->Freq); 84 RC_DecodeFinal(0, s->Freq)
85 p->FoundState = s; 85 p->FoundState = s;
86 sym = s->Symbol; 86 sym = s->Symbol;
87 Ppmd8_Update1_0(p); 87 Ppmd8_Update1_0(p);
@@ -96,7 +96,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
96 if ((Int32)(count -= (++s)->Freq) < 0) 96 if ((Int32)(count -= (++s)->Freq) < 0)
97 { 97 {
98 Byte sym; 98 Byte sym;
99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 99 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
100 p->FoundState = s; 100 p->FoundState = s;
101 sym = s->Symbol; 101 sym = s->Symbol;
102 Ppmd8_Update1(p); 102 Ppmd8_Update1(p);
@@ -109,10 +109,10 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
109 return PPMD8_SYM_ERROR; 109 return PPMD8_SYM_ERROR;
110 110
111 hiCnt -= count; 111 hiCnt -= count;
112 RC_Decode(hiCnt, summFreq - hiCnt); 112 RC_Decode(hiCnt, summFreq - hiCnt)
113 113
114 114
115 PPMD_SetAllBitsIn256Bytes(charMask); 115 PPMD_SetAllBitsIn256Bytes(charMask)
116 // i = p->MinContext->NumStats - 1; 116 // i = p->MinContext->NumStats - 1;
117 // do { MASK((--s)->Symbol) = 0; } while (--i); 117 // do { MASK((--s)->Symbol) = 0; } while (--i);
118 { 118 {
@@ -152,7 +152,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
152 // Ppmd8_UpdateBin(p); 152 // Ppmd8_UpdateBin(p);
153 { 153 {
154 unsigned freq = s->Freq; 154 unsigned freq = s->Freq;
155 CTX_PTR c = CTX(SUCCESSOR(s)); 155 CPpmd8_Context *c = CTX(SUCCESSOR(s));
156 sym = s->Symbol; 156 sym = s->Symbol;
157 p->FoundState = s; 157 p->FoundState = s;
158 p->PrevSuccess = 1; 158 p->PrevSuccess = 1;
@@ -176,7 +176,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
176 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - size0; 176 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - size0;
177 RC_NORM_LOCAL(R) 177 RC_NORM_LOCAL(R)
178 178
179 PPMD_SetAllBitsIn256Bytes(charMask); 179 PPMD_SetAllBitsIn256Bytes(charMask)
180 MASK(Ppmd8Context_OneState(p->MinContext)->Symbol) = 0; 180 MASK(Ppmd8Context_OneState(p->MinContext)->Symbol) = 0;
181 p->PrevSuccess = 0; 181 p->PrevSuccess = 0;
182 } 182 }
@@ -227,7 +227,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
227 see = Ppmd8_MakeEscFreq(p, numMasked, &freqSum); 227 see = Ppmd8_MakeEscFreq(p, numMasked, &freqSum);
228 freqSum += hiCnt; 228 freqSum += hiCnt;
229 freqSum2 = freqSum; 229 freqSum2 = freqSum;
230 PPMD8_CORRECT_SUM_RANGE(R, freqSum2); 230 PPMD8_CORRECT_SUM_RANGE(R, freqSum2)
231 231
232 232
233 count = RC_GetThreshold(freqSum2); 233 count = RC_GetThreshold(freqSum2);
@@ -235,7 +235,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
235 if (count < hiCnt) 235 if (count < hiCnt)
236 { 236 {
237 Byte sym; 237 Byte sym;
238 // Ppmd_See_Update(see); // new (see->Summ) value can overflow over 16-bits in some rare cases 238 // Ppmd_See_UPDATE(see) // new (see->Summ) value can overflow over 16-bits in some rare cases
239 s = Ppmd8_GetStats(p, p->MinContext); 239 s = Ppmd8_GetStats(p, p->MinContext);
240 hiCnt = count; 240 hiCnt = count;
241 241
@@ -248,10 +248,10 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
248 } 248 }
249 } 249 }
250 s--; 250 s--;
251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq); 251 RC_DecodeFinal((hiCnt - count) - s->Freq, s->Freq)
252 252
253 // new (see->Summ) value can overflow over 16-bits in some rare cases 253 // new (see->Summ) value can overflow over 16-bits in some rare cases
254 Ppmd_See_Update(see); 254 Ppmd_See_UPDATE(see)
255 p->FoundState = s; 255 p->FoundState = s;
256 sym = s->Symbol; 256 sym = s->Symbol;
257 Ppmd8_Update2(p); 257 Ppmd8_Update2(p);
@@ -261,7 +261,7 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
261 if (count >= freqSum2) 261 if (count >= freqSum2)
262 return PPMD8_SYM_ERROR; 262 return PPMD8_SYM_ERROR;
263 263
264 RC_Decode(hiCnt, freqSum2 - hiCnt); 264 RC_Decode(hiCnt, freqSum2 - hiCnt)
265 265
266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols. 266 // We increase (see->Summ) for sum of Freqs of all non_Masked symbols.
267 // new (see->Summ) value can overflow over 16-bits in some rare cases 267 // new (see->Summ) value can overflow over 16-bits in some rare cases
@@ -277,3 +277,19 @@ int Ppmd8_DecodeSymbol(CPpmd8 *p)
277 while (s != s2); 277 while (s != s2);
278 } 278 }
279} 279}
280
281#undef kTop
282#undef kBot
283#undef READ_BYTE
284#undef RC_NORM_BASE
285#undef RC_NORM_1
286#undef RC_NORM
287#undef RC_NORM_LOCAL
288#undef RC_NORM_REMOTE
289#undef R
290#undef RC_Decode
291#undef RC_DecodeFinal
292#undef RC_GetThreshold
293#undef CTX
294#undef SUCCESSOR
295#undef MASK
diff --git a/C/Ppmd8Enc.c b/C/Ppmd8Enc.c
index 32ff805..9e29ef7 100644
--- a/C/Ppmd8Enc.c
+++ b/C/Ppmd8Enc.c
@@ -1,5 +1,5 @@
1/* Ppmd8Enc.c -- Ppmd8 (PPMdI) Encoder 1/* Ppmd8Enc.c -- Ppmd8 (PPMdI) Encoder
22021-04-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on: 3This code is based on:
4 PPMd var.I (2002): Dmitry Shkarin : Public domain 4 PPMd var.I (2002): Dmitry Shkarin : Public domain
5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ 5 Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
@@ -8,8 +8,8 @@ This code is based on:
8 8
9#include "Ppmd8.h" 9#include "Ppmd8.h"
10 10
11#define kTop (1 << 24) 11#define kTop ((UInt32)1 << 24)
12#define kBot (1 << 15) 12#define kBot ((UInt32)1 << 15)
13 13
14#define WRITE_BYTE(p) IByteOut_Write(p->Stream.Out, (Byte)(p->Low >> 24)) 14#define WRITE_BYTE(p) IByteOut_Write(p->Stream.Out, (Byte)(p->Low >> 24))
15 15
@@ -54,13 +54,13 @@ void Ppmd8_Flush_RangeEnc(CPpmd8 *p)
54 54
55 55
56 56
57MY_FORCE_INLINE 57Z7_FORCE_INLINE
58// MY_NO_INLINE 58// Z7_NO_INLINE
59static void RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total) 59static void Ppmd8_RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total)
60{ 60{
61 R->Low += start * (R->Range /= total); 61 R->Low += start * (R->Range /= total);
62 R->Range *= size; 62 R->Range *= size;
63 RC_NORM_LOCAL(R); 63 RC_NORM_LOCAL(R)
64} 64}
65 65
66 66
@@ -72,19 +72,19 @@ static void RangeEnc_Encode(CPpmd8 *p, UInt32 start, UInt32 size, UInt32 total)
72 72
73 73
74 74
75#define RC_Encode(start, size, total) RangeEnc_Encode(p, start, size, total); 75#define RC_Encode(start, size, total) Ppmd8_RangeEnc_Encode(p, start, size, total);
76#define RC_EncodeFinal(start, size, total) RC_Encode(start, size, total); RC_NORM_REMOTE(p); 76#define RC_EncodeFinal(start, size, total) RC_Encode(start, size, total) RC_NORM_REMOTE(p)
77 77
78#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref)) 78#define CTX(ref) ((CPpmd8_Context *)Ppmd8_GetContext(p, ref))
79 79
80typedef CPpmd8_Context * CTX_PTR; 80// typedef CPpmd8_Context * CTX_PTR;
81#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p) 81#define SUCCESSOR(p) Ppmd_GET_SUCCESSOR(p)
82 82
83void Ppmd8_UpdateModel(CPpmd8 *p); 83void Ppmd8_UpdateModel(CPpmd8 *p);
84 84
85#define MASK(sym) ((unsigned char *)charMask)[sym] 85#define MASK(sym) ((unsigned char *)charMask)[sym]
86 86
87// MY_FORCE_INLINE 87// Z7_FORCE_INLINE
88// static 88// static
89void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol) 89void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
90{ 90{
@@ -104,7 +104,7 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
104 if (s->Symbol == symbol) 104 if (s->Symbol == symbol)
105 { 105 {
106 106
107 RC_EncodeFinal(0, s->Freq, summFreq); 107 RC_EncodeFinal(0, s->Freq, summFreq)
108 p->FoundState = s; 108 p->FoundState = s;
109 Ppmd8_Update1_0(p); 109 Ppmd8_Update1_0(p);
110 return; 110 return;
@@ -117,7 +117,7 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
117 if ((++s)->Symbol == symbol) 117 if ((++s)->Symbol == symbol)
118 { 118 {
119 119
120 RC_EncodeFinal(sum, s->Freq, summFreq); 120 RC_EncodeFinal(sum, s->Freq, summFreq)
121 p->FoundState = s; 121 p->FoundState = s;
122 Ppmd8_Update1(p); 122 Ppmd8_Update1(p);
123 return; 123 return;
@@ -127,10 +127,10 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
127 while (--i); 127 while (--i);
128 128
129 129
130 RC_Encode(sum, summFreq - sum, summFreq); 130 RC_Encode(sum, summFreq - sum, summFreq)
131 131
132 132
133 PPMD_SetAllBitsIn256Bytes(charMask); 133 PPMD_SetAllBitsIn256Bytes(charMask)
134 // MASK(s->Symbol) = 0; 134 // MASK(s->Symbol) = 0;
135 // i = p->MinContext->NumStats; 135 // i = p->MinContext->NumStats;
136 // do { MASK((--s)->Symbol) = 0; } while (--i); 136 // do { MASK((--s)->Symbol) = 0; } while (--i);
@@ -153,20 +153,20 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
153 UInt16 *prob = Ppmd8_GetBinSumm(p); 153 UInt16 *prob = Ppmd8_GetBinSumm(p);
154 CPpmd_State *s = Ppmd8Context_OneState(p->MinContext); 154 CPpmd_State *s = Ppmd8Context_OneState(p->MinContext);
155 UInt32 pr = *prob; 155 UInt32 pr = *prob;
156 UInt32 bound = (R->Range >> 14) * pr; 156 const UInt32 bound = (R->Range >> 14) * pr;
157 pr = PPMD_UPDATE_PROB_1(pr); 157 pr = PPMD_UPDATE_PROB_1(pr);
158 if (s->Symbol == symbol) 158 if (s->Symbol == symbol)
159 { 159 {
160 *prob = (UInt16)(pr + (1 << PPMD_INT_BITS)); 160 *prob = (UInt16)(pr + (1 << PPMD_INT_BITS));
161 // RangeEnc_EncodeBit_0(p, bound); 161 // RangeEnc_EncodeBit_0(p, bound);
162 R->Range = bound; 162 R->Range = bound;
163 RC_NORM(R); 163 RC_NORM(R)
164 164
165 // p->FoundState = s; 165 // p->FoundState = s;
166 // Ppmd8_UpdateBin(p); 166 // Ppmd8_UpdateBin(p);
167 { 167 {
168 unsigned freq = s->Freq; 168 const unsigned freq = s->Freq;
169 CTX_PTR c = CTX(SUCCESSOR(s)); 169 CPpmd8_Context *c = CTX(SUCCESSOR(s));
170 p->FoundState = s; 170 p->FoundState = s;
171 p->PrevSuccess = 1; 171 p->PrevSuccess = 1;
172 p->RunLength++; 172 p->RunLength++;
@@ -187,7 +187,7 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
187 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - bound; 187 R->Range = (R->Range & ~((UInt32)PPMD_BIN_SCALE - 1)) - bound;
188 RC_NORM_LOCAL(R) 188 RC_NORM_LOCAL(R)
189 189
190 PPMD_SetAllBitsIn256Bytes(charMask); 190 PPMD_SetAllBitsIn256Bytes(charMask)
191 MASK(s->Symbol) = 0; 191 MASK(s->Symbol) = 0;
192 p->PrevSuccess = 0; 192 p->PrevSuccess = 0;
193 } 193 }
@@ -248,14 +248,14 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
248 248
249 do 249 do
250 { 250 {
251 unsigned cur = s->Symbol; 251 const unsigned cur = s->Symbol;
252 if ((int)cur == symbol) 252 if ((int)cur == symbol)
253 { 253 {
254 UInt32 low = sum; 254 const UInt32 low = sum;
255 UInt32 freq = s->Freq; 255 const UInt32 freq = s->Freq;
256 unsigned num2; 256 unsigned num2;
257 257
258 Ppmd_See_Update(see); 258 Ppmd_See_UPDATE(see)
259 p->FoundState = s; 259 p->FoundState = s;
260 sum += escFreq; 260 sum += escFreq;
261 261
@@ -277,9 +277,9 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
277 } 277 }
278 } 278 }
279 279
280 PPMD8_CORRECT_SUM_RANGE(p, sum); 280 PPMD8_CORRECT_SUM_RANGE(p, sum)
281 281
282 RC_EncodeFinal(low, freq, sum); 282 RC_EncodeFinal(low, freq, sum)
283 Ppmd8_Update2(p); 283 Ppmd8_Update2(p);
284 return; 284 return;
285 } 285 }
@@ -291,19 +291,19 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
291 { 291 {
292 UInt32 total = sum + escFreq; 292 UInt32 total = sum + escFreq;
293 see->Summ = (UInt16)(see->Summ + total); 293 see->Summ = (UInt16)(see->Summ + total);
294 PPMD8_CORRECT_SUM_RANGE(p, total); 294 PPMD8_CORRECT_SUM_RANGE(p, total)
295 295
296 RC_Encode(sum, total - sum, total); 296 RC_Encode(sum, total - sum, total)
297 } 297 }
298 298
299 { 299 {
300 CPpmd_State *s2 = Ppmd8_GetStats(p, p->MinContext); 300 const CPpmd_State *s2 = Ppmd8_GetStats(p, p->MinContext);
301 s--; 301 s--;
302 MASK(s->Symbol) = 0; 302 MASK(s->Symbol) = 0;
303 do 303 do
304 { 304 {
305 unsigned sym0 = s2[0].Symbol; 305 const unsigned sym0 = s2[0].Symbol;
306 unsigned sym1 = s2[1].Symbol; 306 const unsigned sym1 = s2[1].Symbol;
307 s2 += 2; 307 s2 += 2;
308 MASK(sym0) = 0; 308 MASK(sym0) = 0;
309 MASK(sym1) = 0; 309 MASK(sym1) = 0;
@@ -312,3 +312,27 @@ void Ppmd8_EncodeSymbol(CPpmd8 *p, int symbol)
312 } 312 }
313 } 313 }
314} 314}
315
316
317
318
319
320
321
322
323
324#undef kTop
325#undef kBot
326#undef WRITE_BYTE
327#undef RC_NORM_BASE
328#undef RC_NORM_1
329#undef RC_NORM
330#undef RC_NORM_LOCAL
331#undef RC_NORM_REMOTE
332#undef R
333#undef RC_Encode
334#undef RC_EncodeFinal
335
336#undef CTX
337#undef SUCCESSOR
338#undef MASK
diff --git a/C/Precomp.h b/C/Precomp.h
index e8ff8b4..69afb2f 100644
--- a/C/Precomp.h
+++ b/C/Precomp.h
@@ -1,8 +1,8 @@
1/* Precomp.h -- StdAfx 1/* Precomp.h -- StdAfx
22013-11-12 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_PRECOMP_H 4#ifndef ZIP7_INC_PRECOMP_H
5#define __7Z_PRECOMP_H 5#define ZIP7_INC_PRECOMP_H
6 6
7#include "Compiler.h" 7#include "Compiler.h"
8/* #include "7zTypes.h" */ 8/* #include "7zTypes.h" */
diff --git a/C/RotateDefs.h b/C/RotateDefs.h
index 8f01d1a..c16b4f8 100644
--- a/C/RotateDefs.h
+++ b/C/RotateDefs.h
@@ -1,14 +1,14 @@
1/* RotateDefs.h -- Rotate functions 1/* RotateDefs.h -- Rotate functions
22015-03-25 : Igor Pavlov : Public domain */ 22023-06-18 : Igor Pavlov : Public domain */
3 3
4#ifndef __ROTATE_DEFS_H 4#ifndef ZIP7_INC_ROTATE_DEFS_H
5#define __ROTATE_DEFS_H 5#define ZIP7_INC_ROTATE_DEFS_H
6 6
7#ifdef _MSC_VER 7#ifdef _MSC_VER
8 8
9#include <stdlib.h> 9#include <stdlib.h>
10 10
11/* don't use _rotl with MINGW. It can insert slow call to function. */ 11/* don't use _rotl with old MINGW. It can insert slow call to function. */
12 12
13/* #if (_MSC_VER >= 1200) */ 13/* #if (_MSC_VER >= 1200) */
14#pragma intrinsic(_rotl) 14#pragma intrinsic(_rotl)
@@ -18,12 +18,32 @@
18#define rotlFixed(x, n) _rotl((x), (n)) 18#define rotlFixed(x, n) _rotl((x), (n))
19#define rotrFixed(x, n) _rotr((x), (n)) 19#define rotrFixed(x, n) _rotr((x), (n))
20 20
21#if (_MSC_VER >= 1300)
22#define Z7_ROTL64(x, n) _rotl64((x), (n))
23#define Z7_ROTR64(x, n) _rotr64((x), (n))
24#else
25#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n))))
26#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
27#endif
28
21#else 29#else
22 30
23/* new compilers can translate these macros to fast commands. */ 31/* new compilers can translate these macros to fast commands. */
24 32
33#if defined(__clang__) && (__clang_major__ >= 4) \
34 || defined(__GNUC__) && (__GNUC__ >= 5)
35/* GCC 4.9.0 and clang 3.5 can recognize more correct version: */
36#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (-(n) & 31)))
37#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (-(n) & 31)))
38#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (-(n) & 63)))
39#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (-(n) & 63)))
40#else
41/* for old GCC / clang: */
25#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) 42#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
26#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) 43#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
44#define Z7_ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n))))
45#define Z7_ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
46#endif
27 47
28#endif 48#endif
29 49
diff --git a/C/Sha1.c b/C/Sha1.c
index 9665b5b..fd6c018 100644
--- a/C/Sha1.c
+++ b/C/Sha1.c
@@ -1,5 +1,5 @@
1/* Sha1.c -- SHA-1 Hash 1/* Sha1.c -- SHA-1 Hash
22021-07-13 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ library. */ 3This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ library. */
4 4
5#include "Precomp.h" 5#include "Precomp.h"
@@ -17,48 +17,48 @@ This code is based on public domain code of Steve Reid from Wei Dai's Crypto++ l
17#ifdef MY_CPU_X86_OR_AMD64 17#ifdef MY_CPU_X86_OR_AMD64
18 #ifdef _MSC_VER 18 #ifdef _MSC_VER
19 #if _MSC_VER >= 1200 19 #if _MSC_VER >= 1200
20 #define _SHA_SUPPORTED 20 #define Z7_COMPILER_SHA1_SUPPORTED
21 #endif 21 #endif
22 #elif defined(__clang__) 22 #elif defined(__clang__)
23 #if (__clang_major__ >= 8) // fix that check 23 #if (__clang_major__ >= 8) // fix that check
24 #define _SHA_SUPPORTED 24 #define Z7_COMPILER_SHA1_SUPPORTED
25 #endif 25 #endif
26 #elif defined(__GNUC__) 26 #elif defined(__GNUC__)
27 #if (__GNUC__ >= 8) // fix that check 27 #if (__GNUC__ >= 8) // fix that check
28 #define _SHA_SUPPORTED 28 #define Z7_COMPILER_SHA1_SUPPORTED
29 #endif 29 #endif
30 #elif defined(__INTEL_COMPILER) 30 #elif defined(__INTEL_COMPILER)
31 #if (__INTEL_COMPILER >= 1800) // fix that check 31 #if (__INTEL_COMPILER >= 1800) // fix that check
32 #define _SHA_SUPPORTED 32 #define Z7_COMPILER_SHA1_SUPPORTED
33 #endif 33 #endif
34 #endif 34 #endif
35#elif defined(MY_CPU_ARM_OR_ARM64) 35#elif defined(MY_CPU_ARM_OR_ARM64)
36 #ifdef _MSC_VER 36 #ifdef _MSC_VER
37 #if _MSC_VER >= 1910 && _MSC_VER >= 1929 && _MSC_FULL_VER >= 192930037 37 #if _MSC_VER >= 1910 && _MSC_VER >= 1929 && _MSC_FULL_VER >= 192930037
38 #define _SHA_SUPPORTED 38 #define Z7_COMPILER_SHA1_SUPPORTED
39 #endif 39 #endif
40 #elif defined(__clang__) 40 #elif defined(__clang__)
41 #if (__clang_major__ >= 8) // fix that check 41 #if (__clang_major__ >= 8) // fix that check
42 #define _SHA_SUPPORTED 42 #define Z7_COMPILER_SHA1_SUPPORTED
43 #endif 43 #endif
44 #elif defined(__GNUC__) 44 #elif defined(__GNUC__)
45 #if (__GNUC__ >= 6) // fix that check 45 #if (__GNUC__ >= 6) // fix that check
46 #define _SHA_SUPPORTED 46 #define Z7_COMPILER_SHA1_SUPPORTED
47 #endif 47 #endif
48 #endif 48 #endif
49#endif 49#endif
50 50
51void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); 51void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks);
52 52
53#ifdef _SHA_SUPPORTED 53#ifdef Z7_COMPILER_SHA1_SUPPORTED
54 void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); 54 void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks);
55 55
56 static SHA1_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha1_UpdateBlocks; 56 static SHA1_FUNC_UPDATE_BLOCKS g_SHA1_FUNC_UPDATE_BLOCKS = Sha1_UpdateBlocks;
57 static SHA1_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; 57 static SHA1_FUNC_UPDATE_BLOCKS g_SHA1_FUNC_UPDATE_BLOCKS_HW;
58 58
59 #define UPDATE_BLOCKS(p) p->func_UpdateBlocks 59 #define SHA1_UPDATE_BLOCKS(p) p->func_UpdateBlocks
60#else 60#else
61 #define UPDATE_BLOCKS(p) Sha1_UpdateBlocks 61 #define SHA1_UPDATE_BLOCKS(p) Sha1_UpdateBlocks
62#endif 62#endif
63 63
64 64
@@ -66,16 +66,16 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
66{ 66{
67 SHA1_FUNC_UPDATE_BLOCKS func = Sha1_UpdateBlocks; 67 SHA1_FUNC_UPDATE_BLOCKS func = Sha1_UpdateBlocks;
68 68
69 #ifdef _SHA_SUPPORTED 69 #ifdef Z7_COMPILER_SHA1_SUPPORTED
70 if (algo != SHA1_ALGO_SW) 70 if (algo != SHA1_ALGO_SW)
71 { 71 {
72 if (algo == SHA1_ALGO_DEFAULT) 72 if (algo == SHA1_ALGO_DEFAULT)
73 func = g_FUNC_UPDATE_BLOCKS; 73 func = g_SHA1_FUNC_UPDATE_BLOCKS;
74 else 74 else
75 { 75 {
76 if (algo != SHA1_ALGO_HW) 76 if (algo != SHA1_ALGO_HW)
77 return False; 77 return False;
78 func = g_FUNC_UPDATE_BLOCKS_HW; 78 func = g_SHA1_FUNC_UPDATE_BLOCKS_HW;
79 if (!func) 79 if (!func)
80 return False; 80 return False;
81 } 81 }
@@ -91,21 +91,22 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
91 91
92 92
93/* define it for speed optimization */ 93/* define it for speed optimization */
94// #define _SHA1_UNROLL 94// #define Z7_SHA1_UNROLL
95 95
96// allowed unroll steps: (1, 2, 4, 5, 20) 96// allowed unroll steps: (1, 2, 4, 5, 20)
97 97
98#ifdef _SHA1_UNROLL 98#undef Z7_SHA1_BIG_W
99#ifdef Z7_SHA1_UNROLL
99 #define STEP_PRE 20 100 #define STEP_PRE 20
100 #define STEP_MAIN 20 101 #define STEP_MAIN 20
101#else 102#else
102 #define _SHA1_BIG_W 103 #define Z7_SHA1_BIG_W
103 #define STEP_PRE 5 104 #define STEP_PRE 5
104 #define STEP_MAIN 5 105 #define STEP_MAIN 5
105#endif 106#endif
106 107
107 108
108#ifdef _SHA1_BIG_W 109#ifdef Z7_SHA1_BIG_W
109 #define kNumW 80 110 #define kNumW 80
110 #define w(i) W[i] 111 #define w(i) W[i]
111#else 112#else
@@ -150,11 +151,11 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
150*/ 151*/
151 152
152#define M5(i, fx, wx0, wx1) \ 153#define M5(i, fx, wx0, wx1) \
153 T5 ( a,b,c,d,e, fx, wx0((i) ) ); \ 154 T5 ( a,b,c,d,e, fx, wx0((i) ) ) \
154 T5 ( e,a,b,c,d, fx, wx1((i)+1) ); \ 155 T5 ( e,a,b,c,d, fx, wx1((i)+1) ) \
155 T5 ( d,e,a,b,c, fx, wx1((i)+2) ); \ 156 T5 ( d,e,a,b,c, fx, wx1((i)+2) ) \
156 T5 ( c,d,e,a,b, fx, wx1((i)+3) ); \ 157 T5 ( c,d,e,a,b, fx, wx1((i)+3) ) \
157 T5 ( b,c,d,e,a, fx, wx1((i)+4) ); \ 158 T5 ( b,c,d,e,a, fx, wx1((i)+4) ) \
158 159
159#define R5(i, fx, wx) \ 160#define R5(i, fx, wx) \
160 M5 ( i, fx, wx, wx) \ 161 M5 ( i, fx, wx, wx) \
@@ -163,17 +164,17 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
163#if STEP_PRE > 5 164#if STEP_PRE > 5
164 165
165 #define R20_START \ 166 #define R20_START \
166 R5 ( 0, f0, w0); \ 167 R5 ( 0, f0, w0) \
167 R5 ( 5, f0, w0); \ 168 R5 ( 5, f0, w0) \
168 R5 ( 10, f0, w0); \ 169 R5 ( 10, f0, w0) \
169 M5 ( 15, f0, w0, w1); \ 170 M5 ( 15, f0, w0, w1) \
170 171
171 #elif STEP_PRE == 5 172 #elif STEP_PRE == 5
172 173
173 #define R20_START \ 174 #define R20_START \
174 { size_t i; for (i = 0; i < 15; i += STEP_PRE) \ 175 { size_t i; for (i = 0; i < 15; i += STEP_PRE) \
175 { R5(i, f0, w0); } } \ 176 { R5(i, f0, w0) } } \
176 M5 ( 15, f0, w0, w1); \ 177 M5 ( 15, f0, w0, w1) \
177 178
178#else 179#else
179 180
@@ -187,8 +188,8 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
187 188
188 #define R20_START \ 189 #define R20_START \
189 { size_t i; for (i = 0; i < 16; i += STEP_PRE) \ 190 { size_t i; for (i = 0; i < 16; i += STEP_PRE) \
190 { R_PRE(i, f0, w0); } } \ 191 { R_PRE(i, f0, w0) } } \
191 R4 ( 16, f0, w1); \ 192 R4 ( 16, f0, w1) \
192 193
193#endif 194#endif
194 195
@@ -197,10 +198,10 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
197#if STEP_MAIN > 5 198#if STEP_MAIN > 5
198 199
199 #define R20(ii, fx) \ 200 #define R20(ii, fx) \
200 R5 ( (ii) , fx, w1); \ 201 R5 ( (ii) , fx, w1) \
201 R5 ( (ii) + 5 , fx, w1); \ 202 R5 ( (ii) + 5 , fx, w1) \
202 R5 ( (ii) + 10, fx, w1); \ 203 R5 ( (ii) + 10, fx, w1) \
203 R5 ( (ii) + 15, fx, w1); \ 204 R5 ( (ii) + 15, fx, w1) \
204 205
205#else 206#else
206 207
@@ -216,7 +217,7 @@ BoolInt Sha1_SetFunction(CSha1 *p, unsigned algo)
216 217
217 #define R20(ii, fx) \ 218 #define R20(ii, fx) \
218 { size_t i; for (i = (ii); i < (ii) + 20; i += STEP_MAIN) \ 219 { size_t i; for (i = (ii); i < (ii) + 20; i += STEP_MAIN) \
219 { R_MAIN(i, fx, w1); } } \ 220 { R_MAIN(i, fx, w1) } } \
220 221
221#endif 222#endif
222 223
@@ -235,8 +236,8 @@ void Sha1_InitState(CSha1 *p)
235void Sha1_Init(CSha1 *p) 236void Sha1_Init(CSha1 *p)
236{ 237{
237 p->func_UpdateBlocks = 238 p->func_UpdateBlocks =
238 #ifdef _SHA_SUPPORTED 239 #ifdef Z7_COMPILER_SHA1_SUPPORTED
239 g_FUNC_UPDATE_BLOCKS; 240 g_SHA1_FUNC_UPDATE_BLOCKS;
240 #else 241 #else
241 NULL; 242 NULL;
242 #endif 243 #endif
@@ -244,8 +245,8 @@ void Sha1_Init(CSha1 *p)
244} 245}
245 246
246 247
247MY_NO_INLINE 248Z7_NO_INLINE
248void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks) 249void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks)
249{ 250{
250 UInt32 a, b, c, d, e; 251 UInt32 a, b, c, d, e;
251 UInt32 W[kNumW]; 252 UInt32 W[kNumW];
@@ -266,9 +267,9 @@ void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t nu
266 #endif 267 #endif
267 268
268 R20_START 269 R20_START
269 R20(20, f1); 270 R20(20, f1)
270 R20(40, f2); 271 R20(40, f2)
271 R20(60, f3); 272 R20(60, f3)
272 273
273 a += state[0]; 274 a += state[0];
274 b += state[1]; 275 b += state[1];
@@ -288,7 +289,7 @@ void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t nu
288} 289}
289 290
290 291
291#define Sha1_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) 292#define Sha1_UpdateBlock(p) SHA1_UPDATE_BLOCKS(p)(p->state, p->buffer, 1)
292 293
293void Sha1_Update(CSha1 *p, const Byte *data, size_t size) 294void Sha1_Update(CSha1 *p, const Byte *data, size_t size)
294{ 295{
@@ -318,7 +319,7 @@ void Sha1_Update(CSha1 *p, const Byte *data, size_t size)
318 } 319 }
319 { 320 {
320 size_t numBlocks = size >> 6; 321 size_t numBlocks = size >> 6;
321 UPDATE_BLOCKS(p)(p->state, data, numBlocks); 322 SHA1_UPDATE_BLOCKS(p)(p->state, data, numBlocks);
322 size &= 0x3F; 323 size &= 0x3F;
323 if (size == 0) 324 if (size == 0)
324 return; 325 return;
@@ -361,18 +362,18 @@ void Sha1_Final(CSha1 *p, Byte *digest)
361 memset(&p->buffer[pos], 0, (64 - 8) - pos); 362 memset(&p->buffer[pos], 0, (64 - 8) - pos);
362 363
363 { 364 {
364 UInt64 numBits = (p->count << 3); 365 const UInt64 numBits = (p->count << 3);
365 SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); 366 SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32))
366 SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); 367 SetBe32(p->buffer + 64 - 4, (UInt32)(numBits))
367 } 368 }
368 369
369 Sha1_UpdateBlock(p); 370 Sha1_UpdateBlock(p);
370 371
371 SetBe32(digest, p->state[0]); 372 SetBe32(digest, p->state[0])
372 SetBe32(digest + 4, p->state[1]); 373 SetBe32(digest + 4, p->state[1])
373 SetBe32(digest + 8, p->state[2]); 374 SetBe32(digest + 8, p->state[2])
374 SetBe32(digest + 12, p->state[3]); 375 SetBe32(digest + 12, p->state[3])
375 SetBe32(digest + 16, p->state[4]); 376 SetBe32(digest + 16, p->state[4])
376 377
377 378
378 379
@@ -384,10 +385,10 @@ void Sha1_Final(CSha1 *p, Byte *digest)
384void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size) 385void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size)
385{ 386{
386 const UInt64 numBits = (p->count + size) << 3; 387 const UInt64 numBits = (p->count + size) << 3;
387 SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 2], (UInt32)(numBits >> 32)); 388 SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 2], (UInt32)(numBits >> 32))
388 SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 1], (UInt32)(numBits)); 389 SetBe32(&((UInt32 *)(void *)block)[SHA1_NUM_BLOCK_WORDS - 1], (UInt32)(numBits))
389 // SetBe32((UInt32 *)(block + size), 0x80000000); 390 // SetBe32((UInt32 *)(block + size), 0x80000000);
390 SetUi32((UInt32 *)(void *)(block + size), 0x80); 391 SetUi32((UInt32 *)(void *)(block + size), 0x80)
391 size += 4; 392 size += 4;
392 while (size != (SHA1_NUM_BLOCK_WORDS - 2) * 4) 393 while (size != (SHA1_NUM_BLOCK_WORDS - 2) * 4)
393 { 394 {
@@ -407,19 +408,19 @@ void Sha1_GetBlockDigest(const CSha1 *p, const Byte *data, Byte *destDigest)
407 st[3] = p->state[3]; 408 st[3] = p->state[3];
408 st[4] = p->state[4]; 409 st[4] = p->state[4];
409 410
410 UPDATE_BLOCKS(p)(st, data, 1); 411 SHA1_UPDATE_BLOCKS(p)(st, data, 1);
411 412
412 SetBe32(destDigest + 0 , st[0]); 413 SetBe32(destDigest + 0 , st[0])
413 SetBe32(destDigest + 1 * 4, st[1]); 414 SetBe32(destDigest + 1 * 4, st[1])
414 SetBe32(destDigest + 2 * 4, st[2]); 415 SetBe32(destDigest + 2 * 4, st[2])
415 SetBe32(destDigest + 3 * 4, st[3]); 416 SetBe32(destDigest + 3 * 4, st[3])
416 SetBe32(destDigest + 4 * 4, st[4]); 417 SetBe32(destDigest + 4 * 4, st[4])
417} 418}
418 419
419 420
420void Sha1Prepare() 421void Sha1Prepare(void)
421{ 422{
422 #ifdef _SHA_SUPPORTED 423 #ifdef Z7_COMPILER_SHA1_SUPPORTED
423 SHA1_FUNC_UPDATE_BLOCKS f, f_hw; 424 SHA1_FUNC_UPDATE_BLOCKS f, f_hw;
424 f = Sha1_UpdateBlocks; 425 f = Sha1_UpdateBlocks;
425 f_hw = NULL; 426 f_hw = NULL;
@@ -467,7 +468,31 @@ void Sha1Prepare()
467 f = f_hw = Sha1_UpdateBlocks_HW; 468 f = f_hw = Sha1_UpdateBlocks_HW;
468 } 469 }
469 } 470 }
470 g_FUNC_UPDATE_BLOCKS = f; 471 g_SHA1_FUNC_UPDATE_BLOCKS = f;
471 g_FUNC_UPDATE_BLOCKS_HW = f_hw; 472 g_SHA1_FUNC_UPDATE_BLOCKS_HW = f_hw;
472 #endif 473 #endif
473} 474}
475
476#undef kNumW
477#undef w
478#undef w0
479#undef w1
480#undef f0
481#undef f1
482#undef f2
483#undef f3
484#undef T1
485#undef T5
486#undef M5
487#undef R1
488#undef R2
489#undef R4
490#undef R5
491#undef R20_START
492#undef R_PRE
493#undef R_MAIN
494#undef STEP_PRE
495#undef STEP_MAIN
496#undef Z7_SHA1_BIG_W
497#undef Z7_SHA1_UNROLL
498#undef Z7_COMPILER_SHA1_SUPPORTED
diff --git a/C/Sha1.h b/C/Sha1.h
index 345a816..fecd9d3 100644
--- a/C/Sha1.h
+++ b/C/Sha1.h
@@ -1,8 +1,8 @@
1/* Sha1.h -- SHA-1 Hash 1/* Sha1.h -- SHA-1 Hash
22021-02-08 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_SHA1_H 4#ifndef ZIP7_INC_SHA1_H
5#define __7Z_SHA1_H 5#define ZIP7_INC_SHA1_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -14,7 +14,7 @@ EXTERN_C_BEGIN
14#define SHA1_BLOCK_SIZE (SHA1_NUM_BLOCK_WORDS * 4) 14#define SHA1_BLOCK_SIZE (SHA1_NUM_BLOCK_WORDS * 4)
15#define SHA1_DIGEST_SIZE (SHA1_NUM_DIGEST_WORDS * 4) 15#define SHA1_DIGEST_SIZE (SHA1_NUM_DIGEST_WORDS * 4)
16 16
17typedef void (MY_FAST_CALL *SHA1_FUNC_UPDATE_BLOCKS)(UInt32 state[5], const Byte *data, size_t numBlocks); 17typedef void (Z7_FASTCALL *SHA1_FUNC_UPDATE_BLOCKS)(UInt32 state[5], const Byte *data, size_t numBlocks);
18 18
19/* 19/*
20 if (the system supports different SHA1 code implementations) 20 if (the system supports different SHA1 code implementations)
@@ -34,9 +34,9 @@ typedef struct
34{ 34{
35 SHA1_FUNC_UPDATE_BLOCKS func_UpdateBlocks; 35 SHA1_FUNC_UPDATE_BLOCKS func_UpdateBlocks;
36 UInt64 count; 36 UInt64 count;
37 UInt64 __pad_2[2]; 37 UInt64 _pad_2[2];
38 UInt32 state[SHA1_NUM_DIGEST_WORDS]; 38 UInt32 state[SHA1_NUM_DIGEST_WORDS];
39 UInt32 __pad_3[3]; 39 UInt32 _pad_3[3];
40 Byte buffer[SHA1_BLOCK_SIZE]; 40 Byte buffer[SHA1_BLOCK_SIZE];
41} CSha1; 41} CSha1;
42 42
@@ -62,7 +62,7 @@ void Sha1_Final(CSha1 *p, Byte *digest);
62void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size); 62void Sha1_PrepareBlock(const CSha1 *p, Byte *block, unsigned size);
63void Sha1_GetBlockDigest(const CSha1 *p, const Byte *data, Byte *destDigest); 63void Sha1_GetBlockDigest(const CSha1 *p, const Byte *data, Byte *destDigest);
64 64
65// void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); 65// void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks);
66 66
67/* 67/*
68call Sha1Prepare() once at program start. 68call Sha1Prepare() once at program start.
diff --git a/C/Sha1Opt.c b/C/Sha1Opt.c
index 63132da..27796aa 100644
--- a/C/Sha1Opt.c
+++ b/C/Sha1Opt.c
@@ -1,7 +1,9 @@
1/* Sha1Opt.c -- SHA-1 optimized code for SHA-1 hardware instructions 1/* Sha1Opt.c -- SHA-1 optimized code for SHA-1 hardware instructions
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5#include "Compiler.h"
6#include "CpuArch.h"
5 7
6#if defined(_MSC_VER) 8#if defined(_MSC_VER)
7#if (_MSC_VER < 1900) && (_MSC_VER >= 1200) 9#if (_MSC_VER < 1900) && (_MSC_VER >= 1200)
@@ -9,41 +11,26 @@
9#endif 11#endif
10#endif 12#endif
11 13
12#include "CpuArch.h"
13
14#ifdef MY_CPU_X86_OR_AMD64 14#ifdef MY_CPU_X86_OR_AMD64
15 #if defined(__clang__) 15 #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1600) // fix that check
16 #if (__clang_major__ >= 8) // fix that check
17 #define USE_HW_SHA 16 #define USE_HW_SHA
18 #ifndef __SHA__ 17 #elif defined(Z7_LLVM_CLANG_VERSION) && (Z7_LLVM_CLANG_VERSION >= 30800) \
19 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) 18 || defined(Z7_APPLE_CLANG_VERSION) && (Z7_APPLE_CLANG_VERSION >= 50100) \
20 #if defined(_MSC_VER) 19 || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40900)
21 // SSSE3: for clang-cl:
22 #include <tmmintrin.h>
23 #define __SHA__
24 #endif
25 #endif
26 #pragma clang diagnostic ignored "-Wvector-conversion"
27 #endif
28 #elif defined(__GNUC__)
29 #if (__GNUC__ >= 8) // fix that check
30 #define USE_HW_SHA 20 #define USE_HW_SHA
31 #ifndef __SHA__ 21 #if !defined(_INTEL_COMPILER)
22 // icc defines __GNUC__, but icc doesn't support __attribute__(__target__)
23 #if !defined(__SHA__) || !defined(__SSSE3__)
32 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) 24 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3")))
33 // #pragma GCC target("sha,ssse3")
34 #endif 25 #endif
35 #endif 26 #endif
36 #elif defined(__INTEL_COMPILER)
37 #if (__INTEL_COMPILER >= 1800) // fix that check
38 #define USE_HW_SHA
39 #endif
40 #elif defined(_MSC_VER) 27 #elif defined(_MSC_VER)
41 #ifdef USE_MY_MM 28 #ifdef USE_MY_MM
42 #define USE_VER_MIN 1300 29 #define USE_VER_MIN 1300
43 #else 30 #else
44 #define USE_VER_MIN 1910 31 #define USE_VER_MIN 1900
45 #endif 32 #endif
46 #if _MSC_VER >= USE_VER_MIN 33 #if (_MSC_VER >= USE_VER_MIN)
47 #define USE_HW_SHA 34 #define USE_HW_SHA
48 #endif 35 #endif
49 #endif 36 #endif
@@ -52,16 +39,19 @@
52#ifdef USE_HW_SHA 39#ifdef USE_HW_SHA
53 40
54// #pragma message("Sha1 HW") 41// #pragma message("Sha1 HW")
55// #include <wmmintrin.h>
56 42
57#if !defined(_MSC_VER) || (_MSC_VER >= 1900) 43// sse/sse2/ssse3:
44#include <tmmintrin.h>
45// sha*:
58#include <immintrin.h> 46#include <immintrin.h>
59#else
60#include <emmintrin.h>
61 47
62#if defined(_MSC_VER) && (_MSC_VER >= 1600) 48#if defined (__clang__) && defined(_MSC_VER)
63// #include <intrin.h> 49 // #if !defined(__SSSE3__)
64#endif 50 // #endif
51 #if !defined(__SHA__)
52 #include <shaintrin.h>
53 #endif
54#else
65 55
66#ifdef USE_MY_MM 56#ifdef USE_MY_MM
67#include "My_mm.h" 57#include "My_mm.h"
@@ -87,37 +77,37 @@ SHA:
87 _mm_sha1* 77 _mm_sha1*
88*/ 78*/
89 79
90#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); 80
91#define XOR_SI128(dest, src) dest = _mm_xor_si128(dest, src); 81#define XOR_SI128(dest, src) dest = _mm_xor_si128(dest, src);
92#define SHUFFLE_EPI8(dest, mask) dest = _mm_shuffle_epi8(dest, mask); 82#define SHUFFLE_EPI8(dest, mask) dest = _mm_shuffle_epi8(dest, mask);
93#define SHUFFLE_EPI32(dest, mask) dest = _mm_shuffle_epi32(dest, mask); 83#define SHUFFLE_EPI32(dest, mask) dest = _mm_shuffle_epi32(dest, mask);
94 84#ifdef __clang__
95#define SHA1_RND4(abcd, e0, f) abcd = _mm_sha1rnds4_epu32(abcd, e0, f); 85#define SHA1_RNDS4_RET_TYPE_CAST (__m128i)
96#define SHA1_NEXTE(e, m) e = _mm_sha1nexte_epu32(e, m); 86#else
97 87#define SHA1_RNDS4_RET_TYPE_CAST
98 88#endif
99 89#define SHA1_RND4(abcd, e0, f) abcd = SHA1_RNDS4_RET_TYPE_CAST _mm_sha1rnds4_epu32(abcd, e0, f);
100 90#define SHA1_NEXTE(e, m) e = _mm_sha1nexte_epu32(e, m);
101 91#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src);
102#define SHA1_MSG1(dest, src) dest = _mm_sha1msg1_epu32(dest, src); 92#define SHA1_MSG1(dest, src) dest = _mm_sha1msg1_epu32(dest, src);
103#define SHA1_MSG2(dest, src) dest = _mm_sha1msg2_epu32(dest, src); 93#define SHA1_MSG2(dest, src) dest = _mm_sha1msg2_epu32(dest, src);
104 94
105 95
106#define LOAD_SHUFFLE(m, k) \ 96#define LOAD_SHUFFLE(m, k) \
107 m = _mm_loadu_si128((const __m128i *)(const void *)(data + (k) * 16)); \ 97 m = _mm_loadu_si128((const __m128i *)(const void *)(data + (k) * 16)); \
108 SHUFFLE_EPI8(m, mask); \ 98 SHUFFLE_EPI8(m, mask) \
109 99
110#define SM1(m0, m1, m2, m3) \ 100#define SM1(m0, m1, m2, m3) \
111 SHA1_MSG1(m0, m1); \ 101 SHA1_MSG1(m0, m1) \
112 102
113#define SM2(m0, m1, m2, m3) \ 103#define SM2(m0, m1, m2, m3) \
114 XOR_SI128(m3, m1); \ 104 XOR_SI128(m3, m1) \
115 SHA1_MSG2(m3, m2); \ 105 SHA1_MSG2(m3, m2) \
116 106
117#define SM3(m0, m1, m2, m3) \ 107#define SM3(m0, m1, m2, m3) \
118 XOR_SI128(m3, m1); \ 108 XOR_SI128(m3, m1) \
119 SM1(m0, m1, m2, m3) \ 109 SM1(m0, m1, m2, m3) \
120 SHA1_MSG2(m3, m2); \ 110 SHA1_MSG2(m3, m2) \
121 111
122#define NNN(m0, m1, m2, m3) 112#define NNN(m0, m1, m2, m3)
123 113
@@ -139,9 +129,9 @@ SHA:
139 129
140#define R4(k, e0, e1, m0, m1, m2, m3, OP) \ 130#define R4(k, e0, e1, m0, m1, m2, m3, OP) \
141 e1 = abcd; \ 131 e1 = abcd; \
142 SHA1_RND4(abcd, e0, (k) / 5); \ 132 SHA1_RND4(abcd, e0, (k) / 5) \
143 SHA1_NEXTE(e1, m1); \ 133 SHA1_NEXTE(e1, m1) \
144 OP(m0, m1, m2, m3); \ 134 OP(m0, m1, m2, m3) \
145 135
146#define R16(k, mx, OP0, OP1, OP2, OP3) \ 136#define R16(k, mx, OP0, OP1, OP2, OP3) \
147 R4 ( (k)*4+0, e0,e1, m0,m1,m2,m3, OP0 ) \ 137 R4 ( (k)*4+0, e0,e1, m0,m1,m2,m3, OP0 ) \
@@ -150,18 +140,18 @@ SHA:
150 R4 ( (k)*4+3, e1,e0, m3,mx,m1,m2, OP3 ) \ 140 R4 ( (k)*4+3, e1,e0, m3,mx,m1,m2, OP3 ) \
151 141
152#define PREPARE_STATE \ 142#define PREPARE_STATE \
153 SHUFFLE_EPI32 (abcd, 0x1B); \ 143 SHUFFLE_EPI32 (abcd, 0x1B) \
154 SHUFFLE_EPI32 (e0, 0x1B); \ 144 SHUFFLE_EPI32 (e0, 0x1B) \
155 145
156 146
157 147
158 148
159 149
160void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); 150void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks);
161#ifdef ATTRIB_SHA 151#ifdef ATTRIB_SHA
162ATTRIB_SHA 152ATTRIB_SHA
163#endif 153#endif
164void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) 154void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks)
165{ 155{
166 const __m128i mask = _mm_set_epi32(0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); 156 const __m128i mask = _mm_set_epi32(0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f);
167 157
@@ -190,15 +180,15 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t
190 LOAD_SHUFFLE (m2, 2) 180 LOAD_SHUFFLE (m2, 2)
191 LOAD_SHUFFLE (m3, 3) 181 LOAD_SHUFFLE (m3, 3)
192 182
193 ADD_EPI32(e0, m0); 183 ADD_EPI32(e0, m0)
194 184
195 R16 ( 0, m0, SM1, SM3, SM3, SM3 ); 185 R16 ( 0, m0, SM1, SM3, SM3, SM3 )
196 R16 ( 1, m0, SM3, SM3, SM3, SM3 ); 186 R16 ( 1, m0, SM3, SM3, SM3, SM3 )
197 R16 ( 2, m0, SM3, SM3, SM3, SM3 ); 187 R16 ( 2, m0, SM3, SM3, SM3, SM3 )
198 R16 ( 3, m0, SM3, SM3, SM3, SM3 ); 188 R16 ( 3, m0, SM3, SM3, SM3, SM3 )
199 R16 ( 4, e2, SM2, NNN, NNN, NNN ); 189 R16 ( 4, e2, SM2, NNN, NNN, NNN )
200 190
201 ADD_EPI32(abcd, abcd_save); 191 ADD_EPI32(abcd, abcd_save)
202 192
203 data += 64; 193 data += 64;
204 } 194 }
@@ -274,11 +264,11 @@ typedef uint32x4_t v128;
274#define H(e) e = vsha1h_u32(vgetq_lane_u32(abcd, 0)) 264#define H(e) e = vsha1h_u32(vgetq_lane_u32(abcd, 0))
275#define T(m, c) t = vaddq_u32(m, c) 265#define T(m, c) t = vaddq_u32(m, c)
276 266
277void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 267void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
278#ifdef ATTRIB_SHA 268#ifdef ATTRIB_SHA
279ATTRIB_SHA 269ATTRIB_SHA
280#endif 270#endif
281void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) 271void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks)
282{ 272{
283 v128 abcd; 273 v128 abcd;
284 v128 c0, c1, c2, c3; 274 v128 c0, c1, c2, c3;
@@ -353,12 +343,12 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t
353// #include <stdlib.h> 343// #include <stdlib.h>
354 344
355// #include "Sha1.h" 345// #include "Sha1.h"
356void MY_FAST_CALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks); 346void Z7_FASTCALL Sha1_UpdateBlocks(UInt32 state[5], const Byte *data, size_t numBlocks);
357 347
358#pragma message("Sha1 HW-SW stub was used") 348#pragma message("Sha1 HW-SW stub was used")
359 349
360void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks); 350void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks);
361void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks) 351void Z7_FASTCALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t numBlocks)
362{ 352{
363 Sha1_UpdateBlocks(state, data, numBlocks); 353 Sha1_UpdateBlocks(state, data, numBlocks);
364 /* 354 /*
@@ -371,3 +361,26 @@ void MY_FAST_CALL Sha1_UpdateBlocks_HW(UInt32 state[5], const Byte *data, size_t
371} 361}
372 362
373#endif 363#endif
364
365#undef SU0
366#undef SU1
367#undef C
368#undef P
369#undef M
370#undef H
371#undef T
372#undef MY_rev32_for_LE
373#undef NNN
374#undef LOAD_128
375#undef STORE_128
376#undef LOAD_SHUFFLE
377#undef SM1
378#undef SM2
379#undef SM3
380#undef NNN
381#undef R4
382#undef R16
383#undef PREPARE_STATE
384#undef USE_HW_SHA
385#undef ATTRIB_SHA
386#undef USE_VER_MIN
diff --git a/C/Sha256.c b/C/Sha256.c
index 8b3983e..018cf6f 100644
--- a/C/Sha256.c
+++ b/C/Sha256.c
@@ -1,5 +1,5 @@
1/* Sha256.c -- SHA-256 Hash 1/* Sha256.c -- SHA-256 Hash
22021-04-01 : Igor Pavlov : Public domain 22023-04-02 : Igor Pavlov : Public domain
3This code is based on public domain code from Wei Dai's Crypto++ library. */ 3This code is based on public domain code from Wei Dai's Crypto++ library. */
4 4
5#include "Precomp.h" 5#include "Precomp.h"
@@ -17,48 +17,48 @@ This code is based on public domain code from Wei Dai's Crypto++ library. */
17#ifdef MY_CPU_X86_OR_AMD64 17#ifdef MY_CPU_X86_OR_AMD64
18 #ifdef _MSC_VER 18 #ifdef _MSC_VER
19 #if _MSC_VER >= 1200 19 #if _MSC_VER >= 1200
20 #define _SHA_SUPPORTED 20 #define Z7_COMPILER_SHA256_SUPPORTED
21 #endif 21 #endif
22 #elif defined(__clang__) 22 #elif defined(__clang__)
23 #if (__clang_major__ >= 8) // fix that check 23 #if (__clang_major__ >= 8) // fix that check
24 #define _SHA_SUPPORTED 24 #define Z7_COMPILER_SHA256_SUPPORTED
25 #endif 25 #endif
26 #elif defined(__GNUC__) 26 #elif defined(__GNUC__)
27 #if (__GNUC__ >= 8) // fix that check 27 #if (__GNUC__ >= 8) // fix that check
28 #define _SHA_SUPPORTED 28 #define Z7_COMPILER_SHA256_SUPPORTED
29 #endif 29 #endif
30 #elif defined(__INTEL_COMPILER) 30 #elif defined(__INTEL_COMPILER)
31 #if (__INTEL_COMPILER >= 1800) // fix that check 31 #if (__INTEL_COMPILER >= 1800) // fix that check
32 #define _SHA_SUPPORTED 32 #define Z7_COMPILER_SHA256_SUPPORTED
33 #endif 33 #endif
34 #endif 34 #endif
35#elif defined(MY_CPU_ARM_OR_ARM64) 35#elif defined(MY_CPU_ARM_OR_ARM64)
36 #ifdef _MSC_VER 36 #ifdef _MSC_VER
37 #if _MSC_VER >= 1910 37 #if _MSC_VER >= 1910
38 #define _SHA_SUPPORTED 38 #define Z7_COMPILER_SHA256_SUPPORTED
39 #endif 39 #endif
40 #elif defined(__clang__) 40 #elif defined(__clang__)
41 #if (__clang_major__ >= 8) // fix that check 41 #if (__clang_major__ >= 8) // fix that check
42 #define _SHA_SUPPORTED 42 #define Z7_COMPILER_SHA256_SUPPORTED
43 #endif 43 #endif
44 #elif defined(__GNUC__) 44 #elif defined(__GNUC__)
45 #if (__GNUC__ >= 6) // fix that check 45 #if (__GNUC__ >= 6) // fix that check
46 #define _SHA_SUPPORTED 46 #define Z7_COMPILER_SHA256_SUPPORTED
47 #endif 47 #endif
48 #endif 48 #endif
49#endif 49#endif
50 50
51void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); 51void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks);
52 52
53#ifdef _SHA_SUPPORTED 53#ifdef Z7_COMPILER_SHA256_SUPPORTED
54 void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 54 void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
55 55
56 static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks; 56 static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS = Sha256_UpdateBlocks;
57 static SHA256_FUNC_UPDATE_BLOCKS g_FUNC_UPDATE_BLOCKS_HW; 57 static SHA256_FUNC_UPDATE_BLOCKS g_SHA256_FUNC_UPDATE_BLOCKS_HW;
58 58
59 #define UPDATE_BLOCKS(p) p->func_UpdateBlocks 59 #define SHA256_UPDATE_BLOCKS(p) p->func_UpdateBlocks
60#else 60#else
61 #define UPDATE_BLOCKS(p) Sha256_UpdateBlocks 61 #define SHA256_UPDATE_BLOCKS(p) Sha256_UpdateBlocks
62#endif 62#endif
63 63
64 64
@@ -66,16 +66,16 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo)
66{ 66{
67 SHA256_FUNC_UPDATE_BLOCKS func = Sha256_UpdateBlocks; 67 SHA256_FUNC_UPDATE_BLOCKS func = Sha256_UpdateBlocks;
68 68
69 #ifdef _SHA_SUPPORTED 69 #ifdef Z7_COMPILER_SHA256_SUPPORTED
70 if (algo != SHA256_ALGO_SW) 70 if (algo != SHA256_ALGO_SW)
71 { 71 {
72 if (algo == SHA256_ALGO_DEFAULT) 72 if (algo == SHA256_ALGO_DEFAULT)
73 func = g_FUNC_UPDATE_BLOCKS; 73 func = g_SHA256_FUNC_UPDATE_BLOCKS;
74 else 74 else
75 { 75 {
76 if (algo != SHA256_ALGO_HW) 76 if (algo != SHA256_ALGO_HW)
77 return False; 77 return False;
78 func = g_FUNC_UPDATE_BLOCKS_HW; 78 func = g_SHA256_FUNC_UPDATE_BLOCKS_HW;
79 if (!func) 79 if (!func)
80 return False; 80 return False;
81 } 81 }
@@ -92,17 +92,18 @@ BoolInt Sha256_SetFunction(CSha256 *p, unsigned algo)
92 92
93/* define it for speed optimization */ 93/* define it for speed optimization */
94 94
95#ifdef _SFX 95#ifdef Z7_SFX
96 #define STEP_PRE 1 96 #define STEP_PRE 1
97 #define STEP_MAIN 1 97 #define STEP_MAIN 1
98#else 98#else
99 #define STEP_PRE 2 99 #define STEP_PRE 2
100 #define STEP_MAIN 4 100 #define STEP_MAIN 4
101 // #define _SHA256_UNROLL 101 // #define Z7_SHA256_UNROLL
102#endif 102#endif
103 103
104#undef Z7_SHA256_BIG_W
104#if STEP_MAIN != 16 105#if STEP_MAIN != 16
105 #define _SHA256_BIG_W 106 #define Z7_SHA256_BIG_W
106#endif 107#endif
107 108
108 109
@@ -124,8 +125,8 @@ void Sha256_InitState(CSha256 *p)
124void Sha256_Init(CSha256 *p) 125void Sha256_Init(CSha256 *p)
125{ 126{
126 p->func_UpdateBlocks = 127 p->func_UpdateBlocks =
127 #ifdef _SHA_SUPPORTED 128 #ifdef Z7_COMPILER_SHA256_SUPPORTED
128 g_FUNC_UPDATE_BLOCKS; 129 g_SHA256_FUNC_UPDATE_BLOCKS;
129 #else 130 #else
130 NULL; 131 NULL;
131 #endif 132 #endif
@@ -145,7 +146,7 @@ void Sha256_Init(CSha256 *p)
145 146
146#define blk2_main(j, i) s1(w(j, (i)-2)) + w(j, (i)-7) + s0(w(j, (i)-15)) 147#define blk2_main(j, i) s1(w(j, (i)-2)) + w(j, (i)-7) + s0(w(j, (i)-15))
147 148
148#ifdef _SHA256_BIG_W 149#ifdef Z7_SHA256_BIG_W
149 // we use +i instead of +(i) to change the order to solve CLANG compiler warning for signed/unsigned. 150 // we use +i instead of +(i) to change the order to solve CLANG compiler warning for signed/unsigned.
150 #define w(j, i) W[(size_t)(j) + i] 151 #define w(j, i) W[(size_t)(j) + i]
151 #define blk2(j, i) (w(j, i) = w(j, (i)-16) + blk2_main(j, i)) 152 #define blk2(j, i) (w(j, i) = w(j, (i)-16) + blk2_main(j, i))
@@ -176,7 +177,7 @@ void Sha256_Init(CSha256 *p)
176#define R1_PRE(i) T1( W_PRE, i) 177#define R1_PRE(i) T1( W_PRE, i)
177#define R1_MAIN(i) T1( W_MAIN, i) 178#define R1_MAIN(i) T1( W_MAIN, i)
178 179
179#if (!defined(_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4) 180#if (!defined(Z7_SHA256_UNROLL) || STEP_MAIN < 8) && (STEP_MAIN >= 4)
180#define R2_MAIN(i) \ 181#define R2_MAIN(i) \
181 R1_MAIN(i) \ 182 R1_MAIN(i) \
182 R1_MAIN(i + 1) \ 183 R1_MAIN(i + 1) \
@@ -185,7 +186,7 @@ void Sha256_Init(CSha256 *p)
185 186
186 187
187 188
188#if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 189#if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8
189 190
190#define T4( a,b,c,d,e,f,g,h, wx, i) \ 191#define T4( a,b,c,d,e,f,g,h, wx, i) \
191 h += S1(e) + Ch(e,f,g) + K[(i)+(size_t)(j)] + wx(i); \ 192 h += S1(e) + Ch(e,f,g) + K[(i)+(size_t)(j)] + wx(i); \
@@ -223,7 +224,7 @@ void Sha256_Init(CSha256 *p)
223 224
224#endif 225#endif
225 226
226void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 227void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
227 228
228// static 229// static
229extern MY_ALIGN(64) 230extern MY_ALIGN(64)
@@ -252,11 +253,11 @@ const UInt32 SHA256_K_ARRAY[64] = {
252#define K SHA256_K_ARRAY 253#define K SHA256_K_ARRAY
253 254
254 255
255MY_NO_INLINE 256Z7_NO_INLINE
256void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks) 257void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks)
257{ 258{
258 UInt32 W 259 UInt32 W
259 #ifdef _SHA256_BIG_W 260 #ifdef Z7_SHA256_BIG_W
260 [64]; 261 [64];
261 #else 262 #else
262 [16]; 263 [16];
@@ -266,7 +267,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t
266 267
267 UInt32 a,b,c,d,e,f,g,h; 268 UInt32 a,b,c,d,e,f,g,h;
268 269
269 #if !defined(_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4) 270 #if !defined(Z7_SHA256_UNROLL) || (STEP_MAIN <= 4) || (STEP_PRE <= 4)
270 UInt32 tmp; 271 UInt32 tmp;
271 #endif 272 #endif
272 273
@@ -297,12 +298,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t
297 298
298 #else 299 #else
299 300
300 R1_PRE(0); 301 R1_PRE(0)
301 #if STEP_PRE >= 2 302 #if STEP_PRE >= 2
302 R1_PRE(1); 303 R1_PRE(1)
303 #if STEP_PRE >= 4 304 #if STEP_PRE >= 4
304 R1_PRE(2); 305 R1_PRE(2)
305 R1_PRE(3); 306 R1_PRE(3)
306 #endif 307 #endif
307 #endif 308 #endif
308 309
@@ -311,32 +312,32 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t
311 312
312 for (j = 16; j < 64; j += STEP_MAIN) 313 for (j = 16; j < 64; j += STEP_MAIN)
313 { 314 {
314 #if defined(_SHA256_UNROLL) && STEP_MAIN >= 8 315 #if defined(Z7_SHA256_UNROLL) && STEP_MAIN >= 8
315 316
316 #if STEP_MAIN < 8 317 #if STEP_MAIN < 8
317 R4_MAIN(0); 318 R4_MAIN(0)
318 #else 319 #else
319 R8_MAIN(0); 320 R8_MAIN(0)
320 #if STEP_MAIN == 16 321 #if STEP_MAIN == 16
321 R8_MAIN(8); 322 R8_MAIN(8)
322 #endif 323 #endif
323 #endif 324 #endif
324 325
325 #else 326 #else
326 327
327 R1_MAIN(0); 328 R1_MAIN(0)
328 #if STEP_MAIN >= 2 329 #if STEP_MAIN >= 2
329 R1_MAIN(1); 330 R1_MAIN(1)
330 #if STEP_MAIN >= 4 331 #if STEP_MAIN >= 4
331 R2_MAIN(2); 332 R2_MAIN(2)
332 #if STEP_MAIN >= 8 333 #if STEP_MAIN >= 8
333 R2_MAIN(4); 334 R2_MAIN(4)
334 R2_MAIN(6); 335 R2_MAIN(6)
335 #if STEP_MAIN >= 16 336 #if STEP_MAIN >= 16
336 R2_MAIN(8); 337 R2_MAIN(8)
337 R2_MAIN(10); 338 R2_MAIN(10)
338 R2_MAIN(12); 339 R2_MAIN(12)
339 R2_MAIN(14); 340 R2_MAIN(14)
340 #endif 341 #endif
341 #endif 342 #endif
342 #endif 343 #endif
@@ -367,7 +368,7 @@ void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t
367#undef s1 368#undef s1
368#undef K 369#undef K
369 370
370#define Sha256_UpdateBlock(p) UPDATE_BLOCKS(p)(p->state, p->buffer, 1) 371#define Sha256_UpdateBlock(p) SHA256_UPDATE_BLOCKS(p)(p->state, p->buffer, 1)
371 372
372void Sha256_Update(CSha256 *p, const Byte *data, size_t size) 373void Sha256_Update(CSha256 *p, const Byte *data, size_t size)
373{ 374{
@@ -397,7 +398,7 @@ void Sha256_Update(CSha256 *p, const Byte *data, size_t size)
397 } 398 }
398 { 399 {
399 size_t numBlocks = size >> 6; 400 size_t numBlocks = size >> 6;
400 UPDATE_BLOCKS(p)(p->state, data, numBlocks); 401 SHA256_UPDATE_BLOCKS(p)(p->state, data, numBlocks);
401 size &= 0x3F; 402 size &= 0x3F;
402 if (size == 0) 403 if (size == 0)
403 return; 404 return;
@@ -441,8 +442,8 @@ void Sha256_Final(CSha256 *p, Byte *digest)
441 442
442 { 443 {
443 UInt64 numBits = (p->count << 3); 444 UInt64 numBits = (p->count << 3);
444 SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32)); 445 SetBe32(p->buffer + 64 - 8, (UInt32)(numBits >> 32))
445 SetBe32(p->buffer + 64 - 4, (UInt32)(numBits)); 446 SetBe32(p->buffer + 64 - 4, (UInt32)(numBits))
446 } 447 }
447 448
448 Sha256_UpdateBlock(p); 449 Sha256_UpdateBlock(p);
@@ -451,8 +452,8 @@ void Sha256_Final(CSha256 *p, Byte *digest)
451 { 452 {
452 UInt32 v0 = p->state[i]; 453 UInt32 v0 = p->state[i];
453 UInt32 v1 = p->state[(size_t)i + 1]; 454 UInt32 v1 = p->state[(size_t)i + 1];
454 SetBe32(digest , v0); 455 SetBe32(digest , v0)
455 SetBe32(digest + 4, v1); 456 SetBe32(digest + 4, v1)
456 digest += 8; 457 digest += 8;
457 } 458 }
458 459
@@ -460,9 +461,9 @@ void Sha256_Final(CSha256 *p, Byte *digest)
460} 461}
461 462
462 463
463void Sha256Prepare() 464void Sha256Prepare(void)
464{ 465{
465 #ifdef _SHA_SUPPORTED 466 #ifdef Z7_COMPILER_SHA256_SUPPORTED
466 SHA256_FUNC_UPDATE_BLOCKS f, f_hw; 467 SHA256_FUNC_UPDATE_BLOCKS f, f_hw;
467 f = Sha256_UpdateBlocks; 468 f = Sha256_UpdateBlocks;
468 f_hw = NULL; 469 f_hw = NULL;
@@ -480,7 +481,36 @@ void Sha256Prepare()
480 // printf("\n========== HW SHA256 ======== \n"); 481 // printf("\n========== HW SHA256 ======== \n");
481 f = f_hw = Sha256_UpdateBlocks_HW; 482 f = f_hw = Sha256_UpdateBlocks_HW;
482 } 483 }
483 g_FUNC_UPDATE_BLOCKS = f; 484 g_SHA256_FUNC_UPDATE_BLOCKS = f;
484 g_FUNC_UPDATE_BLOCKS_HW = f_hw; 485 g_SHA256_FUNC_UPDATE_BLOCKS_HW = f_hw;
485 #endif 486 #endif
486} 487}
488
489#undef S0
490#undef S1
491#undef s0
492#undef s1
493#undef Ch
494#undef Maj
495#undef W_MAIN
496#undef W_PRE
497#undef w
498#undef blk2_main
499#undef blk2
500#undef T1
501#undef T4
502#undef T8
503#undef R1_PRE
504#undef R1_MAIN
505#undef R2_MAIN
506#undef R4
507#undef R4_PRE
508#undef R4_MAIN
509#undef R8
510#undef R8_PRE
511#undef R8_MAIN
512#undef STEP_PRE
513#undef STEP_MAIN
514#undef Z7_SHA256_BIG_W
515#undef Z7_SHA256_UNROLL
516#undef Z7_COMPILER_SHA256_SUPPORTED
diff --git a/C/Sha256.h b/C/Sha256.h
index aa38501..9e04223 100644
--- a/C/Sha256.h
+++ b/C/Sha256.h
@@ -1,8 +1,8 @@
1/* Sha256.h -- SHA-256 Hash 1/* Sha256.h -- SHA-256 Hash
22021-01-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_SHA256_H 4#ifndef ZIP7_INC_SHA256_H
5#define __7Z_SHA256_H 5#define ZIP7_INC_SHA256_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
@@ -14,7 +14,7 @@ EXTERN_C_BEGIN
14#define SHA256_BLOCK_SIZE (SHA256_NUM_BLOCK_WORDS * 4) 14#define SHA256_BLOCK_SIZE (SHA256_NUM_BLOCK_WORDS * 4)
15#define SHA256_DIGEST_SIZE (SHA256_NUM_DIGEST_WORDS * 4) 15#define SHA256_DIGEST_SIZE (SHA256_NUM_DIGEST_WORDS * 4)
16 16
17typedef void (MY_FAST_CALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks); 17typedef void (Z7_FASTCALL *SHA256_FUNC_UPDATE_BLOCKS)(UInt32 state[8], const Byte *data, size_t numBlocks);
18 18
19/* 19/*
20 if (the system supports different SHA256 code implementations) 20 if (the system supports different SHA256 code implementations)
@@ -34,7 +34,7 @@ typedef struct
34{ 34{
35 SHA256_FUNC_UPDATE_BLOCKS func_UpdateBlocks; 35 SHA256_FUNC_UPDATE_BLOCKS func_UpdateBlocks;
36 UInt64 count; 36 UInt64 count;
37 UInt64 __pad_2[2]; 37 UInt64 _pad_2[2];
38 UInt32 state[SHA256_NUM_DIGEST_WORDS]; 38 UInt32 state[SHA256_NUM_DIGEST_WORDS];
39 39
40 Byte buffer[SHA256_BLOCK_SIZE]; 40 Byte buffer[SHA256_BLOCK_SIZE];
@@ -62,7 +62,7 @@ void Sha256_Final(CSha256 *p, Byte *digest);
62 62
63 63
64 64
65// void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); 65// void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks);
66 66
67/* 67/*
68call Sha256Prepare() once at program start. 68call Sha256Prepare() once at program start.
diff --git a/C/Sha256Opt.c b/C/Sha256Opt.c
index decc138..e4465e3 100644
--- a/C/Sha256Opt.c
+++ b/C/Sha256Opt.c
@@ -1,7 +1,9 @@
1/* Sha256Opt.c -- SHA-256 optimized code for SHA-256 hardware instructions 1/* Sha256Opt.c -- SHA-256 optimized code for SHA-256 hardware instructions
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5#include "Compiler.h"
6#include "CpuArch.h"
5 7
6#if defined(_MSC_VER) 8#if defined(_MSC_VER)
7#if (_MSC_VER < 1900) && (_MSC_VER >= 1200) 9#if (_MSC_VER < 1900) && (_MSC_VER >= 1200)
@@ -9,41 +11,26 @@
9#endif 11#endif
10#endif 12#endif
11 13
12#include "CpuArch.h"
13
14#ifdef MY_CPU_X86_OR_AMD64 14#ifdef MY_CPU_X86_OR_AMD64
15 #if defined(__clang__) 15 #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1600) // fix that check
16 #if (__clang_major__ >= 8) // fix that check
17 #define USE_HW_SHA 16 #define USE_HW_SHA
18 #ifndef __SHA__ 17 #elif defined(Z7_LLVM_CLANG_VERSION) && (Z7_LLVM_CLANG_VERSION >= 30800) \
19 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) 18 || defined(Z7_APPLE_CLANG_VERSION) && (Z7_APPLE_CLANG_VERSION >= 50100) \
20 #if defined(_MSC_VER) 19 || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40900)
21 // SSSE3: for clang-cl:
22 #include <tmmintrin.h>
23 #define __SHA__
24 #endif
25 #endif
26
27 #endif
28 #elif defined(__GNUC__)
29 #if (__GNUC__ >= 8) // fix that check
30 #define USE_HW_SHA 20 #define USE_HW_SHA
31 #ifndef __SHA__ 21 #if !defined(_INTEL_COMPILER)
22 // icc defines __GNUC__, but icc doesn't support __attribute__(__target__)
23 #if !defined(__SHA__) || !defined(__SSSE3__)
32 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3"))) 24 #define ATTRIB_SHA __attribute__((__target__("sha,ssse3")))
33 // #pragma GCC target("sha,ssse3")
34 #endif 25 #endif
35 #endif 26 #endif
36 #elif defined(__INTEL_COMPILER)
37 #if (__INTEL_COMPILER >= 1800) // fix that check
38 #define USE_HW_SHA
39 #endif
40 #elif defined(_MSC_VER) 27 #elif defined(_MSC_VER)
41 #ifdef USE_MY_MM 28 #ifdef USE_MY_MM
42 #define USE_VER_MIN 1300 29 #define USE_VER_MIN 1300
43 #else 30 #else
44 #define USE_VER_MIN 1910 31 #define USE_VER_MIN 1900
45 #endif 32 #endif
46 #if _MSC_VER >= USE_VER_MIN 33 #if (_MSC_VER >= USE_VER_MIN)
47 #define USE_HW_SHA 34 #define USE_HW_SHA
48 #endif 35 #endif
49 #endif 36 #endif
@@ -52,16 +39,19 @@
52#ifdef USE_HW_SHA 39#ifdef USE_HW_SHA
53 40
54// #pragma message("Sha256 HW") 41// #pragma message("Sha256 HW")
55// #include <wmmintrin.h>
56 42
57#if !defined(_MSC_VER) || (_MSC_VER >= 1900) 43// sse/sse2/ssse3:
44#include <tmmintrin.h>
45// sha*:
58#include <immintrin.h> 46#include <immintrin.h>
59#else
60#include <emmintrin.h>
61 47
62#if defined(_MSC_VER) && (_MSC_VER >= 1600) 48#if defined (__clang__) && defined(_MSC_VER)
63// #include <intrin.h> 49 // #if !defined(__SSSE3__)
64#endif 50 // #endif
51 #if !defined(__SHA__)
52 #include <shaintrin.h>
53 #endif
54#else
65 55
66#ifdef USE_MY_MM 56#ifdef USE_MY_MM
67#include "My_mm.h" 57#include "My_mm.h"
@@ -98,9 +88,9 @@ const UInt32 SHA256_K_ARRAY[64];
98#define K SHA256_K_ARRAY 88#define K SHA256_K_ARRAY
99 89
100 90
101#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src); 91#define ADD_EPI32(dest, src) dest = _mm_add_epi32(dest, src);
102#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src); 92#define SHA256_MSG1(dest, src) dest = _mm_sha256msg1_epu32(dest, src);
103#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src); 93#define SHA25G_MSG2(dest, src) dest = _mm_sha256msg2_epu32(dest, src);
104 94
105 95
106#define LOAD_SHUFFLE(m, k) \ 96#define LOAD_SHUFFLE(m, k) \
@@ -112,7 +102,7 @@ const UInt32 SHA256_K_ARRAY[64];
112 102
113#define SM2(g0, g1, g2, g3) \ 103#define SM2(g0, g1, g2, g3) \
114 tmp = _mm_alignr_epi8(g1, g0, 4); \ 104 tmp = _mm_alignr_epi8(g1, g0, 4); \
115 ADD_EPI32(g2, tmp); \ 105 ADD_EPI32(g2, tmp) \
116 SHA25G_MSG2(g2, g1); \ 106 SHA25G_MSG2(g2, g1); \
117 107
118// #define LS0(k, g0, g1, g2, g3) LOAD_SHUFFLE(g0, k) 108// #define LS0(k, g0, g1, g2, g3) LOAD_SHUFFLE(g0, k)
@@ -138,16 +128,16 @@ const UInt32 SHA256_K_ARRAY[64];
138// We use scheme with 3 rounds ahead for SHA256_MSG1 / 2 rounds ahead for SHA256_MSG2 128// We use scheme with 3 rounds ahead for SHA256_MSG1 / 2 rounds ahead for SHA256_MSG2
139 129
140#define R4(k, g0, g1, g2, g3, OP0, OP1) \ 130#define R4(k, g0, g1, g2, g3, OP0, OP1) \
141 RND2_0(g0, k); \ 131 RND2_0(g0, k) \
142 OP0(g0, g1, g2, g3); \ 132 OP0(g0, g1, g2, g3) \
143 RND2_1; \ 133 RND2_1 \
144 OP1(g0, g1, g2, g3); \ 134 OP1(g0, g1, g2, g3) \
145 135
146#define R16(k, OP0, OP1, OP2, OP3, OP4, OP5, OP6, OP7) \ 136#define R16(k, OP0, OP1, OP2, OP3, OP4, OP5, OP6, OP7) \
147 R4 ( (k)*4+0, m0, m1, m2, m3, OP0, OP1 ) \ 137 R4 ( (k)*4+0, m0,m1,m2,m3, OP0, OP1 ) \
148 R4 ( (k)*4+1, m1, m2, m3, m0, OP2, OP3 ) \ 138 R4 ( (k)*4+1, m1,m2,m3,m0, OP2, OP3 ) \
149 R4 ( (k)*4+2, m2, m3, m0, m1, OP4, OP5 ) \ 139 R4 ( (k)*4+2, m2,m3,m0,m1, OP4, OP5 ) \
150 R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ 140 R4 ( (k)*4+3, m3,m0,m1,m2, OP6, OP7 ) \
151 141
152#define PREPARE_STATE \ 142#define PREPARE_STATE \
153 tmp = _mm_shuffle_epi32(state0, 0x1B); /* abcd */ \ 143 tmp = _mm_shuffle_epi32(state0, 0x1B); /* abcd */ \
@@ -157,11 +147,11 @@ const UInt32 SHA256_K_ARRAY[64];
157 state1 = _mm_unpackhi_epi64(state1, tmp); /* abef */ \ 147 state1 = _mm_unpackhi_epi64(state1, tmp); /* abef */ \
158 148
159 149
160void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 150void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
161#ifdef ATTRIB_SHA 151#ifdef ATTRIB_SHA
162ATTRIB_SHA 152ATTRIB_SHA
163#endif 153#endif
164void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) 154void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks)
165{ 155{
166 const __m128i mask = _mm_set_epi32(0x0c0d0e0f, 0x08090a0b, 0x04050607, 0x00010203); 156 const __m128i mask = _mm_set_epi32(0x0c0d0e0f, 0x08090a0b, 0x04050607, 0x00010203);
167 __m128i tmp; 157 __m128i tmp;
@@ -192,13 +182,13 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size
192 182
193 183
194 184
195 R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 ); 185 R16 ( 0, NNN, NNN, SM1, NNN, SM1, SM2, SM1, SM2 )
196 R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); 186 R16 ( 1, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 )
197 R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 ); 187 R16 ( 2, SM1, SM2, SM1, SM2, SM1, SM2, SM1, SM2 )
198 R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN ); 188 R16 ( 3, SM1, SM2, NNN, SM2, NNN, NNN, NNN, NNN )
199 189
200 ADD_EPI32(state0, state0_save); 190 ADD_EPI32(state0, state0_save)
201 ADD_EPI32(state1, state1_save); 191 ADD_EPI32(state1, state1_save)
202 192
203 data += 64; 193 data += 64;
204 } 194 }
@@ -298,11 +288,11 @@ const UInt32 SHA256_K_ARRAY[64];
298 R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \ 288 R4 ( (k)*4+3, m3, m0, m1, m2, OP6, OP7 ) \
299 289
300 290
301void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 291void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
302#ifdef ATTRIB_SHA 292#ifdef ATTRIB_SHA
303ATTRIB_SHA 293ATTRIB_SHA
304#endif 294#endif
305void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) 295void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks)
306{ 296{
307 v128 state0, state1; 297 v128 state0, state1;
308 298
@@ -353,12 +343,12 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size
353// #include <stdlib.h> 343// #include <stdlib.h>
354 344
355// #include "Sha256.h" 345// #include "Sha256.h"
356void MY_FAST_CALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks); 346void Z7_FASTCALL Sha256_UpdateBlocks(UInt32 state[8], const Byte *data, size_t numBlocks);
357 347
358#pragma message("Sha256 HW-SW stub was used") 348#pragma message("Sha256 HW-SW stub was used")
359 349
360void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks); 350void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks);
361void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks) 351void Z7_FASTCALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size_t numBlocks)
362{ 352{
363 Sha256_UpdateBlocks(state, data, numBlocks); 353 Sha256_UpdateBlocks(state, data, numBlocks);
364 /* 354 /*
@@ -371,3 +361,26 @@ void MY_FAST_CALL Sha256_UpdateBlocks_HW(UInt32 state[8], const Byte *data, size
371} 361}
372 362
373#endif 363#endif
364
365
366
367#undef K
368#undef RND2
369#undef RND2_0
370#undef RND2_1
371
372#undef MY_rev32_for_LE
373#undef NNN
374#undef LOAD_128
375#undef STORE_128
376#undef LOAD_SHUFFLE
377#undef SM1
378#undef SM2
379
380#undef NNN
381#undef R4
382#undef R16
383#undef PREPARE_STATE
384#undef USE_HW_SHA
385#undef ATTRIB_SHA
386#undef USE_VER_MIN
diff --git a/C/Sort.h b/C/Sort.h
index 2e2963a..1817b65 100644
--- a/C/Sort.h
+++ b/C/Sort.h
@@ -1,8 +1,8 @@
1/* Sort.h -- Sort functions 1/* Sort.h -- Sort functions
22014-04-05 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_SORT_H 4#ifndef ZIP7_INC_SORT_H
5#define __7Z_SORT_H 5#define ZIP7_INC_SORT_H
6 6
7#include "7zTypes.h" 7#include "7zTypes.h"
8 8
diff --git a/C/SwapBytes.c b/C/SwapBytes.c
new file mode 100644
index 0000000..7901bba
--- /dev/null
+++ b/C/SwapBytes.c
@@ -0,0 +1,800 @@
1/* SwapBytes.c -- Byte Swap conversion filter
22023-04-07 : Igor Pavlov : Public domain */
3
4#include "Precomp.h"
5
6#include "Compiler.h"
7#include "CpuArch.h"
8#include "RotateDefs.h"
9#include "SwapBytes.h"
10
11typedef UInt16 CSwapUInt16;
12typedef UInt32 CSwapUInt32;
13
14// #define k_SwapBytes_Mode_BASE 0
15
16#ifdef MY_CPU_X86_OR_AMD64
17
18#define k_SwapBytes_Mode_SSE2 1
19#define k_SwapBytes_Mode_SSSE3 2
20#define k_SwapBytes_Mode_AVX2 3
21
22 // #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1900)
23 #if defined(__clang__) && (__clang_major__ >= 4) \
24 || defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40701)
25 #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_AVX2
26 #define SWAP_ATTRIB_SSE2 __attribute__((__target__("sse2")))
27 #define SWAP_ATTRIB_SSSE3 __attribute__((__target__("ssse3")))
28 #define SWAP_ATTRIB_AVX2 __attribute__((__target__("avx2")))
29 #elif defined(_MSC_VER)
30 #if (_MSC_VER == 1900)
31 #pragma warning(disable : 4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX
32 #endif
33 #if (_MSC_VER >= 1900)
34 #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_AVX2
35 #elif (_MSC_VER >= 1500) // (VS2008)
36 #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_SSSE3
37 #elif (_MSC_VER >= 1310) // (VS2003)
38 #define k_SwapBytes_Mode_MAX k_SwapBytes_Mode_SSE2
39 #endif
40 #endif // _MSC_VER
41
42/*
43// for debug
44#ifdef k_SwapBytes_Mode_MAX
45#undef k_SwapBytes_Mode_MAX
46#endif
47*/
48
49#ifndef k_SwapBytes_Mode_MAX
50#define k_SwapBytes_Mode_MAX 0
51#endif
52
53#if (k_SwapBytes_Mode_MAX != 0) && defined(MY_CPU_AMD64)
54 #define k_SwapBytes_Mode_MIN k_SwapBytes_Mode_SSE2
55#else
56 #define k_SwapBytes_Mode_MIN 0
57#endif
58
59#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_AVX2)
60 #define USE_SWAP_AVX2
61#endif
62#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_SSSE3)
63 #define USE_SWAP_SSSE3
64#endif
65#if (k_SwapBytes_Mode_MAX >= k_SwapBytes_Mode_SSE2)
66 #define USE_SWAP_128
67#endif
68
69#if k_SwapBytes_Mode_MAX <= k_SwapBytes_Mode_MIN || !defined(USE_SWAP_128)
70#define FORCE_SWAP_MODE
71#endif
72
73
74#ifdef USE_SWAP_128
75/*
76 <mmintrin.h> MMX
77<xmmintrin.h> SSE
78<emmintrin.h> SSE2
79<pmmintrin.h> SSE3
80<tmmintrin.h> SSSE3
81<smmintrin.h> SSE4.1
82<nmmintrin.h> SSE4.2
83<ammintrin.h> SSE4A
84<wmmintrin.h> AES
85<immintrin.h> AVX, AVX2, FMA
86*/
87
88#include <emmintrin.h> // sse2
89// typedef __m128i v128;
90
91#define SWAP2_128(i) { \
92 const __m128i v = *(const __m128i *)(const void *)(items + (i) * 8); \
93 *( __m128i *)( void *)(items + (i) * 8) = \
94 _mm_or_si128( \
95 _mm_slli_epi16(v, 8), \
96 _mm_srli_epi16(v, 8)); }
97// _mm_or_si128() has more ports to execute than _mm_add_epi16().
98
99static
100#ifdef SWAP_ATTRIB_SSE2
101SWAP_ATTRIB_SSE2
102#endif
103void
104Z7_FASTCALL
105SwapBytes2_128(CSwapUInt16 *items, const CSwapUInt16 *lim)
106{
107 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
108 do
109 {
110 SWAP2_128(0) SWAP2_128(1) items += 2 * 8;
111 SWAP2_128(0) SWAP2_128(1) items += 2 * 8;
112 }
113 while (items != lim);
114}
115
116/*
117// sse2
118#define SWAP4_128_pack(i) { \
119 __m128i v = *(const __m128i *)(const void *)(items + (i) * 4); \
120 __m128i v0 = _mm_unpacklo_epi8(v, mask); \
121 __m128i v1 = _mm_unpackhi_epi8(v, mask); \
122 v0 = _mm_shufflelo_epi16(v0, 0x1b); \
123 v1 = _mm_shufflelo_epi16(v1, 0x1b); \
124 v0 = _mm_shufflehi_epi16(v0, 0x1b); \
125 v1 = _mm_shufflehi_epi16(v1, 0x1b); \
126 *(__m128i *)(void *)(items + (i) * 4) = _mm_packus_epi16(v0, v1); }
127
128static
129#ifdef SWAP_ATTRIB_SSE2
130SWAP_ATTRIB_SSE2
131#endif
132void
133Z7_FASTCALL
134SwapBytes4_128_pack(CSwapUInt32 *items, const CSwapUInt32 *lim)
135{
136 const __m128i mask = _mm_setzero_si128();
137 // const __m128i mask = _mm_set_epi16(0, 0, 0, 0, 0, 0, 0, 0);
138 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
139 do
140 {
141 SWAP4_128_pack(0); items += 1 * 4;
142 // SWAP4_128_pack(0); SWAP4_128_pack(1); items += 2 * 4;
143 }
144 while (items != lim);
145}
146
147// sse2
148#define SWAP4_128_shift(i) { \
149 __m128i v = *(const __m128i *)(const void *)(items + (i) * 4); \
150 __m128i v2; \
151 v2 = _mm_or_si128( \
152 _mm_slli_si128(_mm_and_si128(v, mask), 1), \
153 _mm_and_si128(_mm_srli_si128(v, 1), mask)); \
154 v = _mm_or_si128( \
155 _mm_slli_epi32(v, 24), \
156 _mm_srli_epi32(v, 24)); \
157 *(__m128i *)(void *)(items + (i) * 4) = _mm_or_si128(v2, v); }
158
159static
160#ifdef SWAP_ATTRIB_SSE2
161SWAP_ATTRIB_SSE2
162#endif
163void
164Z7_FASTCALL
165SwapBytes4_128_shift(CSwapUInt32 *items, const CSwapUInt32 *lim)
166{
167 #define M1 0xff00
168 const __m128i mask = _mm_set_epi32(M1, M1, M1, M1);
169 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
170 do
171 {
172 // SWAP4_128_shift(0) SWAP4_128_shift(1) items += 2 * 4;
173 // SWAP4_128_shift(0) SWAP4_128_shift(1) items += 2 * 4;
174 SWAP4_128_shift(0); items += 1 * 4;
175 }
176 while (items != lim);
177}
178*/
179
180
181#if defined(USE_SWAP_SSSE3) || defined(USE_SWAP_AVX2)
182
183#define SWAP_SHUF_REV_SEQ_2_VALS(v) (v)+1, (v)
184#define SWAP_SHUF_REV_SEQ_4_VALS(v) (v)+3, (v)+2, (v)+1, (v)
185
186#define SWAP2_SHUF_MASK_16_BYTES \
187 SWAP_SHUF_REV_SEQ_2_VALS (0 * 2), \
188 SWAP_SHUF_REV_SEQ_2_VALS (1 * 2), \
189 SWAP_SHUF_REV_SEQ_2_VALS (2 * 2), \
190 SWAP_SHUF_REV_SEQ_2_VALS (3 * 2), \
191 SWAP_SHUF_REV_SEQ_2_VALS (4 * 2), \
192 SWAP_SHUF_REV_SEQ_2_VALS (5 * 2), \
193 SWAP_SHUF_REV_SEQ_2_VALS (6 * 2), \
194 SWAP_SHUF_REV_SEQ_2_VALS (7 * 2)
195
196#define SWAP4_SHUF_MASK_16_BYTES \
197 SWAP_SHUF_REV_SEQ_4_VALS (0 * 4), \
198 SWAP_SHUF_REV_SEQ_4_VALS (1 * 4), \
199 SWAP_SHUF_REV_SEQ_4_VALS (2 * 4), \
200 SWAP_SHUF_REV_SEQ_4_VALS (3 * 4)
201
202#if defined(USE_SWAP_AVX2)
203/* if we use 256_BIT_INIT_MASK, each static array mask will be larger for 16 bytes */
204// #define SWAP_USE_256_BIT_INIT_MASK
205#endif
206
207#if defined(SWAP_USE_256_BIT_INIT_MASK) && defined(USE_SWAP_AVX2)
208#define SWAP_MASK_INIT_SIZE 32
209#else
210#define SWAP_MASK_INIT_SIZE 16
211#endif
212
213MY_ALIGN(SWAP_MASK_INIT_SIZE)
214static const Byte k_ShufMask_Swap2[] =
215{
216 SWAP2_SHUF_MASK_16_BYTES
217 #if SWAP_MASK_INIT_SIZE > 16
218 , SWAP2_SHUF_MASK_16_BYTES
219 #endif
220};
221
222MY_ALIGN(SWAP_MASK_INIT_SIZE)
223static const Byte k_ShufMask_Swap4[] =
224{
225 SWAP4_SHUF_MASK_16_BYTES
226 #if SWAP_MASK_INIT_SIZE > 16
227 , SWAP4_SHUF_MASK_16_BYTES
228 #endif
229};
230
231
232#ifdef USE_SWAP_SSSE3
233
234#include <tmmintrin.h> // ssse3
235
236#define SHUF_128(i) *(items + (i)) = \
237 _mm_shuffle_epi8(*(items + (i)), mask); // SSSE3
238
239// Z7_NO_INLINE
240static
241#ifdef SWAP_ATTRIB_SSSE3
242SWAP_ATTRIB_SSSE3
243#endif
244Z7_ATTRIB_NO_VECTORIZE
245void
246Z7_FASTCALL
247ShufBytes_128(void *items8, const void *lim8, const void *mask128_ptr)
248{
249 __m128i *items = (__m128i *)items8;
250 const __m128i *lim = (const __m128i *)lim8;
251 // const __m128i mask = _mm_set_epi8(SHUF_SWAP2_MASK_16_VALS);
252 // const __m128i mask = _mm_set_epi8(SHUF_SWAP4_MASK_16_VALS);
253 // const __m128i mask = _mm_load_si128((const __m128i *)(const void *)&(k_ShufMask_Swap4[0]));
254 // const __m128i mask = _mm_load_si128((const __m128i *)(const void *)&(k_ShufMask_Swap4[0]));
255 // const __m128i mask = *(const __m128i *)(const void *)&(k_ShufMask_Swap4[0]);
256 const __m128i mask = *(const __m128i *)mask128_ptr;
257 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
258 do
259 {
260 SHUF_128(0) SHUF_128(1) items += 2;
261 SHUF_128(0) SHUF_128(1) items += 2;
262 }
263 while (items != lim);
264}
265
266#endif // USE_SWAP_SSSE3
267
268
269
270#ifdef USE_SWAP_AVX2
271
272#include <immintrin.h> // avx, avx2
273#if defined(__clang__)
274#include <avxintrin.h>
275#include <avx2intrin.h>
276#endif
277
278#define SHUF_256(i) *(items + (i)) = \
279 _mm256_shuffle_epi8(*(items + (i)), mask); // AVX2
280
281// Z7_NO_INLINE
282static
283#ifdef SWAP_ATTRIB_AVX2
284SWAP_ATTRIB_AVX2
285#endif
286Z7_ATTRIB_NO_VECTORIZE
287void
288Z7_FASTCALL
289ShufBytes_256(void *items8, const void *lim8, const void *mask128_ptr)
290{
291 __m256i *items = (__m256i *)items8;
292 const __m256i *lim = (const __m256i *)lim8;
293 /*
294 UNUSED_VAR(mask128_ptr)
295 __m256i mask =
296 for Swap4: _mm256_setr_epi8(SWAP4_SHUF_MASK_16_BYTES, SWAP4_SHUF_MASK_16_BYTES);
297 for Swap2: _mm256_setr_epi8(SWAP2_SHUF_MASK_16_BYTES, SWAP2_SHUF_MASK_16_BYTES);
298 */
299 const __m256i mask =
300 #if SWAP_MASK_INIT_SIZE > 16
301 *(const __m256i *)(const void *)mask128_ptr;
302 #else
303 /* msvc: broadcastsi128() version reserves the stack for no reason
304 msvc 19.29-: _mm256_insertf128_si256() / _mm256_set_m128i)) versions use non-avx movdqu xmm0,XMMWORD PTR [r8]
305 msvc 19.30+ (VS2022): replaces _mm256_set_m128i(m,m) to vbroadcastf128(m) as we want
306 */
307 // _mm256_broadcastsi128_si256(*mask128_ptr);
308 /*
309 #define MY_mm256_set_m128i(hi, lo) _mm256_insertf128_si256(_mm256_castsi128_si256(lo), (hi), 1)
310 MY_mm256_set_m128i
311 */
312 _mm256_set_m128i(
313 *(const __m128i *)mask128_ptr,
314 *(const __m128i *)mask128_ptr);
315 #endif
316
317 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
318 do
319 {
320 SHUF_256(0) SHUF_256(1) items += 2;
321 SHUF_256(0) SHUF_256(1) items += 2;
322 }
323 while (items != lim);
324}
325
326#endif // USE_SWAP_AVX2
327#endif // USE_SWAP_SSSE3 || USE_SWAP_AVX2
328#endif // USE_SWAP_128
329
330
331
332// compile message "NEON intrinsics not available with the soft-float ABI"
333#elif defined(MY_CPU_ARM_OR_ARM64) || \
334 (defined(__ARM_ARCH) && (__ARM_ARCH >= 7))
335// #elif defined(MY_CPU_ARM64)
336
337 #if defined(__clang__) && (__clang_major__ >= 8) \
338 || defined(__GNUC__) && (__GNUC__ >= 8)
339 #if (defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) \
340 || defined(MY_CPU_ARM64)
341 #define USE_SWAP_128
342 #endif
343 #ifdef MY_CPU_ARM64
344 // #define SWAP_ATTRIB_NEON __attribute__((__target__("")))
345 #else
346 // #define SWAP_ATTRIB_NEON __attribute__((__target__("fpu=crypto-neon-fp-armv8")))
347 #endif
348 #elif defined(_MSC_VER)
349 #if (_MSC_VER >= 1910)
350 #define USE_SWAP_128
351 #endif
352 #endif
353
354 #if defined(_MSC_VER) && defined(MY_CPU_ARM64)
355 #include <arm64_neon.h>
356 #else
357 #include <arm_neon.h>
358 #endif
359
360#ifndef USE_SWAP_128
361 #define FORCE_SWAP_MODE
362#else
363
364#ifdef MY_CPU_ARM64
365 // for debug : comment it
366 #define FORCE_SWAP_MODE
367#else
368 #define k_SwapBytes_Mode_NEON 1
369#endif
370// typedef uint8x16_t v128;
371#define SWAP2_128(i) *(uint8x16_t *) (void *)(items + (i) * 8) = \
372 vrev16q_u8(*(const uint8x16_t *)(const void *)(items + (i) * 8));
373#define SWAP4_128(i) *(uint8x16_t *) (void *)(items + (i) * 4) = \
374 vrev32q_u8(*(const uint8x16_t *)(const void *)(items + (i) * 4));
375
376// Z7_NO_INLINE
377static
378#ifdef SWAP_ATTRIB_NEON
379SWAP_ATTRIB_NEON
380#endif
381Z7_ATTRIB_NO_VECTORIZE
382void
383Z7_FASTCALL
384SwapBytes2_128(CSwapUInt16 *items, const CSwapUInt16 *lim)
385{
386 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
387 do
388 {
389 SWAP2_128(0) SWAP2_128(1) items += 2 * 8;
390 SWAP2_128(0) SWAP2_128(1) items += 2 * 8;
391 }
392 while (items != lim);
393}
394
395// Z7_NO_INLINE
396static
397#ifdef SWAP_ATTRIB_NEON
398SWAP_ATTRIB_NEON
399#endif
400Z7_ATTRIB_NO_VECTORIZE
401void
402Z7_FASTCALL
403SwapBytes4_128(CSwapUInt32 *items, const CSwapUInt32 *lim)
404{
405 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
406 do
407 {
408 SWAP4_128(0) SWAP4_128(1) items += 2 * 4;
409 SWAP4_128(0) SWAP4_128(1) items += 2 * 4;
410 }
411 while (items != lim);
412}
413
414#endif // USE_SWAP_128
415
416#else // MY_CPU_ARM_OR_ARM64
417#define FORCE_SWAP_MODE
418#endif // MY_CPU_ARM_OR_ARM64
419
420
421
422
423
424
425#if defined(Z7_MSC_VER_ORIGINAL) && defined(MY_CPU_X86)
426 /* _byteswap_ushort() in MSVC x86 32-bit works via slow { mov dh, al; mov dl, ah }
427 So we use own versions of byteswap function */
428 #if (_MSC_VER < 1400 ) // old MSVC-X86 without _rotr16() support
429 #define SWAP2_16(i) { UInt32 v = items[i]; v += (v << 16); v >>= 8; items[i] = (CSwapUInt16)v; }
430 #else // is new MSVC-X86 with fast _rotr16()
431 #include <intrin.h>
432 #define SWAP2_16(i) { items[i] = _rotr16(items[i], 8); }
433 #endif
434#else // is not MSVC-X86
435 #define SWAP2_16(i) { CSwapUInt16 v = items[i]; items[i] = Z7_BSWAP16(v); }
436#endif // MSVC-X86
437
438#if defined(Z7_CPU_FAST_BSWAP_SUPPORTED)
439 #define SWAP4_32(i) { CSwapUInt32 v = items[i]; items[i] = Z7_BSWAP32(v); }
440#else
441 #define SWAP4_32(i) \
442 { UInt32 v = items[i]; \
443 v = ((v & 0xff00ff) << 8) + ((v >> 8) & 0xff00ff); \
444 v = rotlFixed(v, 16); \
445 items[i] = v; }
446#endif
447
448
449
450
451#if defined(FORCE_SWAP_MODE) && defined(USE_SWAP_128)
452 #define DEFAULT_Swap2 SwapBytes2_128
453 #if !defined(MY_CPU_X86_OR_AMD64)
454 #define DEFAULT_Swap4 SwapBytes4_128
455 #endif
456#endif
457
458#if !defined(DEFAULT_Swap2) || !defined(DEFAULT_Swap4)
459
460#define SWAP_BASE_FUNCS_PREFIXES \
461Z7_FORCE_INLINE \
462static \
463Z7_ATTRIB_NO_VECTOR \
464void Z7_FASTCALL
465
466
467#ifdef MY_CPU_64BIT
468
469#if defined(MY_CPU_ARM64) \
470 && defined(__ARM_ARCH) && (__ARM_ARCH >= 8) \
471 && ( (defined(__GNUC__) && (__GNUC__ >= 4)) \
472 || (defined(__clang__) && (__clang_major__ >= 4)))
473
474 #define SWAP2_64_VAR(v) asm ("rev16 %x0,%x0" : "+r" (v));
475 #define SWAP4_64_VAR(v) asm ("rev32 %x0,%x0" : "+r" (v));
476
477#else // is not ARM64-GNU
478
479#if !defined(MY_CPU_X86_OR_AMD64) || (k_SwapBytes_Mode_MIN == 0) || !defined(USE_SWAP_128)
480 #define SWAP2_64_VAR(v) \
481 v = ( 0x00ff00ff00ff00ff & (v >> 8)) \
482 + ((0x00ff00ff00ff00ff & v) << 8);
483 /* plus gives faster code in MSVC */
484#endif
485
486#ifdef Z7_CPU_FAST_BSWAP_SUPPORTED
487 #define SWAP4_64_VAR(v) \
488 v = Z7_BSWAP64(v); \
489 v = Z7_ROTL64(v, 32);
490#else
491 #define SWAP4_64_VAR(v) \
492 v = ( 0x000000ff000000ff & (v >> 24)) \
493 + ((0x000000ff000000ff & v) << 24 ) \
494 + ( 0x0000ff000000ff00 & (v >> 8)) \
495 + ((0x0000ff000000ff00 & v) << 8 ) \
496 ;
497#endif
498
499#endif // ARM64-GNU
500
501
502#ifdef SWAP2_64_VAR
503
504#define SWAP2_64(i) { \
505 UInt64 v = *(const UInt64 *)(const void *)(items + (i) * 4); \
506 SWAP2_64_VAR(v) \
507 *(UInt64 *)(void *)(items + (i) * 4) = v; }
508
509SWAP_BASE_FUNCS_PREFIXES
510SwapBytes2_64(CSwapUInt16 *items, const CSwapUInt16 *lim)
511{
512 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
513 do
514 {
515 SWAP2_64(0) SWAP2_64(1) items += 2 * 4;
516 SWAP2_64(0) SWAP2_64(1) items += 2 * 4;
517 }
518 while (items != lim);
519}
520
521 #define DEFAULT_Swap2 SwapBytes2_64
522 #if !defined(FORCE_SWAP_MODE)
523 #define SWAP2_DEFAULT_MODE 0
524 #endif
525#else // !defined(SWAP2_64_VAR)
526 #define DEFAULT_Swap2 SwapBytes2_128
527 #if !defined(FORCE_SWAP_MODE)
528 #define SWAP2_DEFAULT_MODE 1
529 #endif
530#endif // SWAP2_64_VAR
531
532
533#define SWAP4_64(i) { \
534 UInt64 v = *(const UInt64 *)(const void *)(items + (i) * 2); \
535 SWAP4_64_VAR(v) \
536 *(UInt64 *)(void *)(items + (i) * 2) = v; }
537
538SWAP_BASE_FUNCS_PREFIXES
539SwapBytes4_64(CSwapUInt32 *items, const CSwapUInt32 *lim)
540{
541 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
542 do
543 {
544 SWAP4_64(0) SWAP4_64(1) items += 2 * 2;
545 SWAP4_64(0) SWAP4_64(1) items += 2 * 2;
546 }
547 while (items != lim);
548}
549
550#define DEFAULT_Swap4 SwapBytes4_64
551
552#else // is not 64BIT
553
554
555#if defined(MY_CPU_ARM_OR_ARM64) \
556 && defined(__ARM_ARCH) && (__ARM_ARCH >= 6) \
557 && ( (defined(__GNUC__) && (__GNUC__ >= 4)) \
558 || (defined(__clang__) && (__clang_major__ >= 4)))
559
560#ifdef MY_CPU_64BIT
561 #define SWAP2_32_VAR(v) asm ("rev16 %w0,%w0" : "+r" (v));
562#else
563 #define SWAP2_32_VAR(v) asm ("rev16 %0,%0" : "+r" (v)); // for clang/gcc
564 // asm ("rev16 %r0,%r0" : "+r" (a)); // for gcc
565#endif
566
567#elif defined(_MSC_VER) && (_MSC_VER < 1300) && defined(MY_CPU_X86) \
568 || !defined(Z7_CPU_FAST_BSWAP_SUPPORTED) \
569 || !defined(Z7_CPU_FAST_ROTATE_SUPPORTED)
570 // old msvc doesn't support _byteswap_ulong()
571 #define SWAP2_32_VAR(v) \
572 v = ((v & 0xff00ff) << 8) + ((v >> 8) & 0xff00ff);
573
574#else // is not ARM and is not old-MSVC-X86 and fast BSWAP/ROTATE are supported
575 #define SWAP2_32_VAR(v) \
576 v = Z7_BSWAP32(v); \
577 v = rotlFixed(v, 16);
578
579#endif // GNU-ARM*
580
581#define SWAP2_32(i) { \
582 UInt32 v = *(const UInt32 *)(const void *)(items + (i) * 2); \
583 SWAP2_32_VAR(v); \
584 *(UInt32 *)(void *)(items + (i) * 2) = v; }
585
586
587SWAP_BASE_FUNCS_PREFIXES
588SwapBytes2_32(CSwapUInt16 *items, const CSwapUInt16 *lim)
589{
590 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
591 do
592 {
593 SWAP2_32(0) SWAP2_32(1) items += 2 * 2;
594 SWAP2_32(0) SWAP2_32(1) items += 2 * 2;
595 }
596 while (items != lim);
597}
598
599
600SWAP_BASE_FUNCS_PREFIXES
601SwapBytes4_32(CSwapUInt32 *items, const CSwapUInt32 *lim)
602{
603 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
604 do
605 {
606 SWAP4_32(0) SWAP4_32(1) items += 2;
607 SWAP4_32(0) SWAP4_32(1) items += 2;
608 }
609 while (items != lim);
610}
611
612#define DEFAULT_Swap2 SwapBytes2_32
613#define DEFAULT_Swap4 SwapBytes4_32
614#if !defined(FORCE_SWAP_MODE)
615 #define SWAP2_DEFAULT_MODE 0
616#endif
617
618#endif // MY_CPU_64BIT
619#endif // if !defined(DEFAULT_Swap2) || !defined(DEFAULT_Swap4)
620
621
622
623#if !defined(FORCE_SWAP_MODE)
624static unsigned g_SwapBytes_Mode;
625#endif
626
627/* size of largest unrolled loop iteration: 128 bytes = 4 * 32 bytes (AVX). */
628#define SWAP_ITERATION_BLOCK_SIZE_MAX (1 << 7)
629
630// 32 bytes for (AVX) or 2 * 16-bytes for NEON.
631#define SWAP_VECTOR_ALIGN_SIZE (1 << 5)
632
633Z7_NO_INLINE
634void z7_SwapBytes2(CSwapUInt16 *items, size_t numItems)
635{
636 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
637 for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (SWAP_VECTOR_ALIGN_SIZE - 1)) != 0; numItems--)
638 {
639 SWAP2_16(0)
640 items++;
641 }
642 {
643 const size_t k_Align_Mask = SWAP_ITERATION_BLOCK_SIZE_MAX / sizeof(CSwapUInt16) - 1;
644 size_t numItems2 = numItems;
645 CSwapUInt16 *lim;
646 numItems &= k_Align_Mask;
647 numItems2 &= ~(size_t)k_Align_Mask;
648 lim = items + numItems2;
649 if (numItems2 != 0)
650 {
651 #if !defined(FORCE_SWAP_MODE)
652 #ifdef MY_CPU_X86_OR_AMD64
653 #ifdef USE_SWAP_AVX2
654 if (g_SwapBytes_Mode > k_SwapBytes_Mode_SSSE3)
655 ShufBytes_256((__m256i *)(void *)items,
656 (const __m256i *)(const void *)lim,
657 (const __m128i *)(const void *)&(k_ShufMask_Swap2[0]));
658 else
659 #endif
660 #ifdef USE_SWAP_SSSE3
661 if (g_SwapBytes_Mode >= k_SwapBytes_Mode_SSSE3)
662 ShufBytes_128((__m128i *)(void *)items,
663 (const __m128i *)(const void *)lim,
664 (const __m128i *)(const void *)&(k_ShufMask_Swap2[0]));
665 else
666 #endif
667 #endif // MY_CPU_X86_OR_AMD64
668 #if SWAP2_DEFAULT_MODE == 0
669 if (g_SwapBytes_Mode != 0)
670 SwapBytes2_128(items, lim);
671 else
672 #endif
673 #endif // FORCE_SWAP_MODE
674 DEFAULT_Swap2(items, lim);
675 }
676 items = lim;
677 }
678 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
679 for (; numItems != 0; numItems--)
680 {
681 SWAP2_16(0)
682 items++;
683 }
684}
685
686
687Z7_NO_INLINE
688void z7_SwapBytes4(CSwapUInt32 *items, size_t numItems)
689{
690 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
691 for (; numItems != 0 && ((unsigned)(ptrdiff_t)items & (SWAP_VECTOR_ALIGN_SIZE - 1)) != 0; numItems--)
692 {
693 SWAP4_32(0)
694 items++;
695 }
696 {
697 const size_t k_Align_Mask = SWAP_ITERATION_BLOCK_SIZE_MAX / sizeof(CSwapUInt32) - 1;
698 size_t numItems2 = numItems;
699 CSwapUInt32 *lim;
700 numItems &= k_Align_Mask;
701 numItems2 &= ~(size_t)k_Align_Mask;
702 lim = items + numItems2;
703 if (numItems2 != 0)
704 {
705 #if !defined(FORCE_SWAP_MODE)
706 #ifdef MY_CPU_X86_OR_AMD64
707 #ifdef USE_SWAP_AVX2
708 if (g_SwapBytes_Mode > k_SwapBytes_Mode_SSSE3)
709 ShufBytes_256((__m256i *)(void *)items,
710 (const __m256i *)(const void *)lim,
711 (const __m128i *)(const void *)&(k_ShufMask_Swap4[0]));
712 else
713 #endif
714 #ifdef USE_SWAP_SSSE3
715 if (g_SwapBytes_Mode >= k_SwapBytes_Mode_SSSE3)
716 ShufBytes_128((__m128i *)(void *)items,
717 (const __m128i *)(const void *)lim,
718 (const __m128i *)(const void *)&(k_ShufMask_Swap4[0]));
719 else
720 #endif
721 #else // MY_CPU_X86_OR_AMD64
722
723 if (g_SwapBytes_Mode != 0)
724 SwapBytes4_128(items, lim);
725 else
726 #endif // MY_CPU_X86_OR_AMD64
727 #endif // FORCE_SWAP_MODE
728 DEFAULT_Swap4(items, lim);
729 }
730 items = lim;
731 }
732 Z7_PRAGMA_OPT_DISABLE_LOOP_UNROLL_VECTORIZE
733 for (; numItems != 0; numItems--)
734 {
735 SWAP4_32(0)
736 items++;
737 }
738}
739
740
741// #define SHOW_HW_STATUS
742
743#ifdef SHOW_HW_STATUS
744#include <stdio.h>
745#define PRF(x) x
746#else
747#define PRF(x)
748#endif
749
750void z7_SwapBytesPrepare(void)
751{
752#ifndef FORCE_SWAP_MODE
753 unsigned mode = 0; // k_SwapBytes_Mode_BASE;
754
755#ifdef MY_CPU_ARM_OR_ARM64
756 {
757 if (CPU_IsSupported_NEON())
758 {
759 // #pragma message ("=== SwapBytes NEON")
760 PRF(printf("\n=== SwapBytes NEON\n");)
761 mode = k_SwapBytes_Mode_NEON;
762 }
763 }
764#else // MY_CPU_ARM_OR_ARM64
765 {
766 #ifdef USE_SWAP_AVX2
767 if (CPU_IsSupported_AVX2())
768 {
769 // #pragma message ("=== SwapBytes AVX2")
770 PRF(printf("\n=== SwapBytes AVX2\n");)
771 mode = k_SwapBytes_Mode_AVX2;
772 }
773 else
774 #endif
775 #ifdef USE_SWAP_SSSE3
776 if (CPU_IsSupported_SSSE3())
777 {
778 // #pragma message ("=== SwapBytes SSSE3")
779 PRF(printf("\n=== SwapBytes SSSE3\n");)
780 mode = k_SwapBytes_Mode_SSSE3;
781 }
782 else
783 #endif
784 #if !defined(MY_CPU_AMD64)
785 if (CPU_IsSupported_SSE2())
786 #endif
787 {
788 // #pragma message ("=== SwapBytes SSE2")
789 PRF(printf("\n=== SwapBytes SSE2\n");)
790 mode = k_SwapBytes_Mode_SSE2;
791 }
792 }
793#endif // MY_CPU_ARM_OR_ARM64
794 g_SwapBytes_Mode = mode;
795 // g_SwapBytes_Mode = 0; // for debug
796#endif // FORCE_SWAP_MODE
797 PRF(printf("\n=== SwapBytesPrepare\n");)
798}
799
800#undef PRF
diff --git a/C/SwapBytes.h b/C/SwapBytes.h
new file mode 100644
index 0000000..d442467
--- /dev/null
+++ b/C/SwapBytes.h
@@ -0,0 +1,17 @@
1/* SwapBytes.h -- Byte Swap conversion filter
22023-04-02 : Igor Pavlov : Public domain */
3
4#ifndef ZIP7_INC_SWAP_BYTES_H
5#define ZIP7_INC_SWAP_BYTES_H
6
7#include "7zTypes.h"
8
9EXTERN_C_BEGIN
10
11void z7_SwapBytes2(UInt16 *data, size_t numItems);
12void z7_SwapBytes4(UInt32 *data, size_t numItems);
13void z7_SwapBytesPrepare(void);
14
15EXTERN_C_END
16
17#endif
diff --git a/C/Threads.c b/C/Threads.c
index 58eb90f..cf52bd3 100644
--- a/C/Threads.c
+++ b/C/Threads.c
@@ -1,5 +1,5 @@
1/* Threads.c -- multithreading library 1/* Threads.c -- multithreading library
22021-12-21 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -11,9 +11,9 @@
11 11
12#include "Threads.h" 12#include "Threads.h"
13 13
14static WRes GetError() 14static WRes GetError(void)
15{ 15{
16 DWORD res = GetLastError(); 16 const DWORD res = GetLastError();
17 return res ? (WRes)res : 1; 17 return res ? (WRes)res : 1;
18} 18}
19 19
@@ -173,6 +173,9 @@ WRes CriticalSection_Init(CCriticalSection *p)
173 Windows XP, 2003 : can raise a STATUS_NO_MEMORY exception 173 Windows XP, 2003 : can raise a STATUS_NO_MEMORY exception
174 Windows Vista+ : no exceptions */ 174 Windows Vista+ : no exceptions */
175 #ifdef _MSC_VER 175 #ifdef _MSC_VER
176 #ifdef __clang__
177 #pragma GCC diagnostic ignored "-Wlanguage-extension-token"
178 #endif
176 __try 179 __try
177 #endif 180 #endif
178 { 181 {
@@ -193,18 +196,26 @@ WRes CriticalSection_Init(CCriticalSection *p)
193// ---------- POSIX ---------- 196// ---------- POSIX ----------
194 197
195#ifndef __APPLE__ 198#ifndef __APPLE__
196#ifndef _7ZIP_AFFINITY_DISABLE 199#ifndef Z7_AFFINITY_DISABLE
197// _GNU_SOURCE can be required for pthread_setaffinity_np() / CPU_ZERO / CPU_SET 200// _GNU_SOURCE can be required for pthread_setaffinity_np() / CPU_ZERO / CPU_SET
201// clang < 3.6 : unknown warning group '-Wreserved-id-macro'
202// clang 3.6 - 12.01 : gives warning "macro name is a reserved identifier"
203// clang >= 13 : do not give warning
204#if !defined(_GNU_SOURCE)
205 #if defined(__clang__) && (__clang_major__ >= 4) && (__clang_major__ <= 12)
206 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
207 #endif
198#define _GNU_SOURCE 208#define _GNU_SOURCE
199#endif 209#endif // !defined(_GNU_SOURCE)
200#endif 210#endif // Z7_AFFINITY_DISABLE
211#endif // __APPLE__
201 212
202#include "Threads.h" 213#include "Threads.h"
203 214
204#include <errno.h> 215#include <errno.h>
205#include <stdlib.h> 216#include <stdlib.h>
206#include <string.h> 217#include <string.h>
207#ifdef _7ZIP_AFFINITY_SUPPORTED 218#ifdef Z7_AFFINITY_SUPPORTED
208// #include <sched.h> 219// #include <sched.h>
209#endif 220#endif
210 221
@@ -212,15 +223,12 @@ WRes CriticalSection_Init(CCriticalSection *p)
212// #include <stdio.h> 223// #include <stdio.h>
213// #define PRF(p) p 224// #define PRF(p) p
214#define PRF(p) 225#define PRF(p)
215 226#define Print(s) PRF(printf("\n%s\n", s);)
216#define Print(s) PRF(printf("\n%s\n", s))
217
218// #include <stdio.h>
219 227
220WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, const CCpuSet *cpuSet) 228WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, const CCpuSet *cpuSet)
221{ 229{
222 // new thread in Posix probably inherits affinity from parrent thread 230 // new thread in Posix probably inherits affinity from parrent thread
223 Print("Thread_Create_With_CpuSet"); 231 Print("Thread_Create_With_CpuSet")
224 232
225 pthread_attr_t attr; 233 pthread_attr_t attr;
226 int ret; 234 int ret;
@@ -228,7 +236,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param,
228 236
229 p->_created = 0; 237 p->_created = 0;
230 238
231 RINOK(pthread_attr_init(&attr)); 239 RINOK(pthread_attr_init(&attr))
232 240
233 ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 241 ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
234 242
@@ -236,7 +244,7 @@ WRes Thread_Create_With_CpuSet(CThread *p, THREAD_FUNC_TYPE func, LPVOID param,
236 { 244 {
237 if (cpuSet) 245 if (cpuSet)
238 { 246 {
239 #ifdef _7ZIP_AFFINITY_SUPPORTED 247 #ifdef Z7_AFFINITY_SUPPORTED
240 248
241 /* 249 /*
242 printf("\n affinity :"); 250 printf("\n affinity :");
@@ -292,7 +300,7 @@ WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param)
292 300
293WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, CAffinityMask affinity) 301WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param, CAffinityMask affinity)
294{ 302{
295 Print("Thread_Create_WithAffinity"); 303 Print("Thread_Create_WithAffinity")
296 CCpuSet cs; 304 CCpuSet cs;
297 unsigned i; 305 unsigned i;
298 CpuSet_Zero(&cs); 306 CpuSet_Zero(&cs);
@@ -312,7 +320,7 @@ WRes Thread_Create_With_Affinity(CThread *p, THREAD_FUNC_TYPE func, LPVOID param
312 320
313WRes Thread_Close(CThread *p) 321WRes Thread_Close(CThread *p)
314{ 322{
315 // Print("Thread_Close"); 323 // Print("Thread_Close")
316 int ret; 324 int ret;
317 if (!p->_created) 325 if (!p->_created)
318 return 0; 326 return 0;
@@ -326,7 +334,7 @@ WRes Thread_Close(CThread *p)
326 334
327WRes Thread_Wait_Close(CThread *p) 335WRes Thread_Wait_Close(CThread *p)
328{ 336{
329 // Print("Thread_Wait_Close"); 337 // Print("Thread_Wait_Close")
330 void *thread_return; 338 void *thread_return;
331 int ret; 339 int ret;
332 if (!p->_created) 340 if (!p->_created)
@@ -343,8 +351,8 @@ WRes Thread_Wait_Close(CThread *p)
343 351
344static WRes Event_Create(CEvent *p, int manualReset, int signaled) 352static WRes Event_Create(CEvent *p, int manualReset, int signaled)
345{ 353{
346 RINOK(pthread_mutex_init(&p->_mutex, NULL)); 354 RINOK(pthread_mutex_init(&p->_mutex, NULL))
347 RINOK(pthread_cond_init(&p->_cond, NULL)); 355 RINOK(pthread_cond_init(&p->_cond, NULL))
348 p->_manual_reset = manualReset; 356 p->_manual_reset = manualReset;
349 p->_state = (signaled ? True : False); 357 p->_state = (signaled ? True : False);
350 p->_created = 1; 358 p->_created = 1;
@@ -363,7 +371,7 @@ WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p)
363 371
364WRes Event_Set(CEvent *p) 372WRes Event_Set(CEvent *p)
365{ 373{
366 RINOK(pthread_mutex_lock(&p->_mutex)); 374 RINOK(pthread_mutex_lock(&p->_mutex))
367 p->_state = True; 375 p->_state = True;
368 int res1 = pthread_cond_broadcast(&p->_cond); 376 int res1 = pthread_cond_broadcast(&p->_cond);
369 int res2 = pthread_mutex_unlock(&p->_mutex); 377 int res2 = pthread_mutex_unlock(&p->_mutex);
@@ -372,14 +380,14 @@ WRes Event_Set(CEvent *p)
372 380
373WRes Event_Reset(CEvent *p) 381WRes Event_Reset(CEvent *p)
374{ 382{
375 RINOK(pthread_mutex_lock(&p->_mutex)); 383 RINOK(pthread_mutex_lock(&p->_mutex))
376 p->_state = False; 384 p->_state = False;
377 return pthread_mutex_unlock(&p->_mutex); 385 return pthread_mutex_unlock(&p->_mutex);
378} 386}
379 387
380WRes Event_Wait(CEvent *p) 388WRes Event_Wait(CEvent *p)
381{ 389{
382 RINOK(pthread_mutex_lock(&p->_mutex)); 390 RINOK(pthread_mutex_lock(&p->_mutex))
383 while (p->_state == False) 391 while (p->_state == False)
384 { 392 {
385 // ETIMEDOUT 393 // ETIMEDOUT
@@ -411,8 +419,8 @@ WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount)
411{ 419{
412 if (initCount > maxCount || maxCount < 1) 420 if (initCount > maxCount || maxCount < 1)
413 return EINVAL; 421 return EINVAL;
414 RINOK(pthread_mutex_init(&p->_mutex, NULL)); 422 RINOK(pthread_mutex_init(&p->_mutex, NULL))
415 RINOK(pthread_cond_init(&p->_cond, NULL)); 423 RINOK(pthread_cond_init(&p->_cond, NULL))
416 p->_count = initCount; 424 p->_count = initCount;
417 p->_maxCount = maxCount; 425 p->_maxCount = maxCount;
418 p->_created = 1; 426 p->_created = 1;
@@ -448,7 +456,7 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount)
448 if (releaseCount < 1) 456 if (releaseCount < 1)
449 return EINVAL; 457 return EINVAL;
450 458
451 RINOK(pthread_mutex_lock(&p->_mutex)); 459 RINOK(pthread_mutex_lock(&p->_mutex))
452 460
453 newCount = p->_count + releaseCount; 461 newCount = p->_count + releaseCount;
454 if (newCount > p->_maxCount) 462 if (newCount > p->_maxCount)
@@ -458,13 +466,13 @@ WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount)
458 p->_count = newCount; 466 p->_count = newCount;
459 ret = pthread_cond_broadcast(&p->_cond); 467 ret = pthread_cond_broadcast(&p->_cond);
460 } 468 }
461 RINOK(pthread_mutex_unlock(&p->_mutex)); 469 RINOK(pthread_mutex_unlock(&p->_mutex))
462 return ret; 470 return ret;
463} 471}
464 472
465WRes Semaphore_Wait(CSemaphore *p) 473WRes Semaphore_Wait(CSemaphore *p)
466{ 474{
467 RINOK(pthread_mutex_lock(&p->_mutex)); 475 RINOK(pthread_mutex_lock(&p->_mutex))
468 while (p->_count < 1) 476 while (p->_count < 1)
469 { 477 {
470 pthread_cond_wait(&p->_cond, &p->_mutex); 478 pthread_cond_wait(&p->_cond, &p->_mutex);
@@ -489,7 +497,7 @@ WRes Semaphore_Close(CSemaphore *p)
489 497
490WRes CriticalSection_Init(CCriticalSection *p) 498WRes CriticalSection_Init(CCriticalSection *p)
491{ 499{
492 // Print("CriticalSection_Init"); 500 // Print("CriticalSection_Init")
493 if (!p) 501 if (!p)
494 return EINTR; 502 return EINTR;
495 return pthread_mutex_init(&p->_mutex, NULL); 503 return pthread_mutex_init(&p->_mutex, NULL);
@@ -497,7 +505,7 @@ WRes CriticalSection_Init(CCriticalSection *p)
497 505
498void CriticalSection_Enter(CCriticalSection *p) 506void CriticalSection_Enter(CCriticalSection *p)
499{ 507{
500 // Print("CriticalSection_Enter"); 508 // Print("CriticalSection_Enter")
501 if (p) 509 if (p)
502 { 510 {
503 // int ret = 511 // int ret =
@@ -507,7 +515,7 @@ void CriticalSection_Enter(CCriticalSection *p)
507 515
508void CriticalSection_Leave(CCriticalSection *p) 516void CriticalSection_Leave(CCriticalSection *p)
509{ 517{
510 // Print("CriticalSection_Leave"); 518 // Print("CriticalSection_Leave")
511 if (p) 519 if (p)
512 { 520 {
513 // int ret = 521 // int ret =
@@ -517,7 +525,7 @@ void CriticalSection_Leave(CCriticalSection *p)
517 525
518void CriticalSection_Delete(CCriticalSection *p) 526void CriticalSection_Delete(CCriticalSection *p)
519{ 527{
520 // Print("CriticalSection_Delete"); 528 // Print("CriticalSection_Delete")
521 if (p) 529 if (p)
522 { 530 {
523 // int ret = 531 // int ret =
@@ -527,14 +535,28 @@ void CriticalSection_Delete(CCriticalSection *p)
527 535
528LONG InterlockedIncrement(LONG volatile *addend) 536LONG InterlockedIncrement(LONG volatile *addend)
529{ 537{
530 // Print("InterlockedIncrement"); 538 // Print("InterlockedIncrement")
531 #ifdef USE_HACK_UNSAFE_ATOMIC 539 #ifdef USE_HACK_UNSAFE_ATOMIC
532 LONG val = *addend + 1; 540 LONG val = *addend + 1;
533 *addend = val; 541 *addend = val;
534 return val; 542 return val;
535 #else 543 #else
544
545 #if defined(__clang__) && (__clang_major__ >= 8)
546 #pragma GCC diagnostic ignored "-Watomic-implicit-seq-cst"
547 #endif
536 return __sync_add_and_fetch(addend, 1); 548 return __sync_add_and_fetch(addend, 1);
537 #endif 549 #endif
538} 550}
539 551
540#endif // _WIN32 552#endif // _WIN32
553
554WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p)
555{
556 if (Event_IsCreated(p))
557 return Event_Reset(p);
558 return AutoResetEvent_CreateNotSignaled(p);
559}
560
561#undef PRF
562#undef Print
diff --git a/C/Threads.h b/C/Threads.h
index 89ecb92..4028464 100644
--- a/C/Threads.h
+++ b/C/Threads.h
@@ -1,18 +1,19 @@
1/* Threads.h -- multithreading library 1/* Threads.h -- multithreading library
22021-12-21 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_THREADS_H 4#ifndef ZIP7_INC_THREADS_H
5#define __7Z_THREADS_H 5#define ZIP7_INC_THREADS_H
6 6
7#ifdef _WIN32 7#ifdef _WIN32
8#include <Windows.h> 8#include "7zWindows.h"
9
9#else 10#else
10 11
11#if defined(__linux__) 12#if defined(__linux__)
12#if !defined(__APPLE__) && !defined(_AIX) && !defined(__ANDROID__) 13#if !defined(__APPLE__) && !defined(_AIX) && !defined(__ANDROID__)
13#ifndef _7ZIP_AFFINITY_DISABLE 14#ifndef Z7_AFFINITY_DISABLE
14#define _7ZIP_AFFINITY_SUPPORTED 15#define Z7_AFFINITY_SUPPORTED
15// #pragma message(" ==== _7ZIP_AFFINITY_SUPPORTED") 16// #pragma message(" ==== Z7_AFFINITY_SUPPORTED")
16// #define _GNU_SOURCE 17// #define _GNU_SOURCE
17#endif 18#endif
18#endif 19#endif
@@ -33,7 +34,7 @@ WRes Handle_WaitObject(HANDLE h);
33 34
34typedef HANDLE CThread; 35typedef HANDLE CThread;
35 36
36#define Thread_Construct(p) { *(p) = NULL; } 37#define Thread_CONSTRUCT(p) { *(p) = NULL; }
37#define Thread_WasCreated(p) (*(p) != NULL) 38#define Thread_WasCreated(p) (*(p) != NULL)
38#define Thread_Close(p) HandlePtr_Close(p) 39#define Thread_Close(p) HandlePtr_Close(p)
39// #define Thread_Wait(p) Handle_WaitObject(*(p)) 40// #define Thread_Wait(p) Handle_WaitObject(*(p))
@@ -52,42 +53,46 @@ typedef
52 #endif 53 #endif
53 THREAD_FUNC_RET_TYPE; 54 THREAD_FUNC_RET_TYPE;
54 55
56#define THREAD_FUNC_RET_ZERO 0
57
55typedef DWORD_PTR CAffinityMask; 58typedef DWORD_PTR CAffinityMask;
56typedef DWORD_PTR CCpuSet; 59typedef DWORD_PTR CCpuSet;
57 60
58#define CpuSet_Zero(p) { *(p) = 0; } 61#define CpuSet_Zero(p) *(p) = (0)
59#define CpuSet_Set(p, cpu) { *(p) |= ((DWORD_PTR)1 << (cpu)); } 62#define CpuSet_Set(p, cpu) *(p) |= ((DWORD_PTR)1 << (cpu))
60 63
61#else // _WIN32 64#else // _WIN32
62 65
63typedef struct _CThread 66typedef struct
64{ 67{
65 pthread_t _tid; 68 pthread_t _tid;
66 int _created; 69 int _created;
67} CThread; 70} CThread;
68 71
69#define Thread_Construct(p) { (p)->_tid = 0; (p)->_created = 0; } 72#define Thread_CONSTRUCT(p) { (p)->_tid = 0; (p)->_created = 0; }
70#define Thread_WasCreated(p) ((p)->_created != 0) 73#define Thread_WasCreated(p) ((p)->_created != 0)
71WRes Thread_Close(CThread *p); 74WRes Thread_Close(CThread *p);
72// #define Thread_Wait Thread_Wait_Close 75// #define Thread_Wait Thread_Wait_Close
73 76
74typedef void * THREAD_FUNC_RET_TYPE; 77typedef void * THREAD_FUNC_RET_TYPE;
78#define THREAD_FUNC_RET_ZERO NULL
79
75 80
76typedef UInt64 CAffinityMask; 81typedef UInt64 CAffinityMask;
77 82
78#ifdef _7ZIP_AFFINITY_SUPPORTED 83#ifdef Z7_AFFINITY_SUPPORTED
79 84
80typedef cpu_set_t CCpuSet; 85typedef cpu_set_t CCpuSet;
81#define CpuSet_Zero(p) CPU_ZERO(p) 86#define CpuSet_Zero(p) CPU_ZERO(p)
82#define CpuSet_Set(p, cpu) CPU_SET(cpu, p) 87#define CpuSet_Set(p, cpu) CPU_SET(cpu, p)
83#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p) 88#define CpuSet_IsSet(p, cpu) CPU_ISSET(cpu, p)
84 89
85#else 90#else
86 91
87typedef UInt64 CCpuSet; 92typedef UInt64 CCpuSet;
88#define CpuSet_Zero(p) { *(p) = 0; } 93#define CpuSet_Zero(p) *(p) = (0)
89#define CpuSet_Set(p, cpu) { *(p) |= ((UInt64)1 << (cpu)); } 94#define CpuSet_Set(p, cpu) *(p) |= ((UInt64)1 << (cpu))
90#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0) 95#define CpuSet_IsSet(p, cpu) ((*(p) & ((UInt64)1 << (cpu))) != 0)
91 96
92#endif 97#endif
93 98
@@ -95,7 +100,7 @@ typedef UInt64 CCpuSet;
95#endif // _WIN32 100#endif // _WIN32
96 101
97 102
98#define THREAD_FUNC_CALL_TYPE MY_STD_CALL 103#define THREAD_FUNC_CALL_TYPE Z7_STDCALL
99 104
100#if defined(_WIN32) && defined(__GNUC__) 105#if defined(_WIN32) && defined(__GNUC__)
101/* GCC compiler for x86 32-bit uses the rule: 106/* GCC compiler for x86 32-bit uses the rule:
@@ -187,6 +192,7 @@ WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled);
187WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p); 192WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p);
188WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled); 193WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled);
189WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p); 194WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p);
195
190WRes Event_Set(CEvent *p); 196WRes Event_Set(CEvent *p);
191WRes Event_Reset(CEvent *p); 197WRes Event_Reset(CEvent *p);
192WRes Event_Wait(CEvent *p); 198WRes Event_Wait(CEvent *p);
@@ -227,6 +233,8 @@ LONG InterlockedIncrement(LONG volatile *addend);
227 233
228#endif // _WIN32 234#endif // _WIN32
229 235
236WRes AutoResetEvent_OptCreate_And_Reset(CAutoResetEvent *p);
237
230EXTERN_C_END 238EXTERN_C_END
231 239
232#endif 240#endif
diff --git a/C/Util/7z/7z.dsp b/C/Util/7z/7z.dsp
index be0f0a7..11e1b03 100644
--- a/C/Util/7z/7z.dsp
+++ b/C/Util/7z/7z.dsp
@@ -42,7 +42,7 @@ RSC=rc.exe
42# PROP Ignore_Export_Lib 0 42# PROP Ignore_Export_Lib 0
43# PROP Target_Dir "" 43# PROP Target_Dir ""
44# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c 44# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
45# ADD CPP /nologo /MD /W4 /WX /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /FAcs /Yu"Precomp.h" /FD /c 45# 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
46# ADD BASE RSC /l 0x419 /d "NDEBUG" 46# ADD BASE RSC /l 0x419 /d "NDEBUG"
47# ADD RSC /l 0x419 /d "NDEBUG" 47# ADD RSC /l 0x419 /d "NDEBUG"
48BSC32=bscmake.exe 48BSC32=bscmake.exe
@@ -67,7 +67,7 @@ LINK32=link.exe
67# PROP Ignore_Export_Lib 0 67# PROP Ignore_Export_Lib 0
68# PROP Target_Dir "" 68# PROP Target_Dir ""
69# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c 69# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
70# 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 70# 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
71# ADD BASE RSC /l 0x419 /d "_DEBUG" 71# ADD BASE RSC /l 0x419 /d "_DEBUG"
72# ADD RSC /l 0x419 /d "_DEBUG" 72# ADD RSC /l 0x419 /d "_DEBUG"
73BSC32=bscmake.exe 73BSC32=bscmake.exe
@@ -145,6 +145,10 @@ SOURCE=..\..\7zTypes.h
145# End Source File 145# End Source File
146# Begin Source File 146# Begin Source File
147 147
148SOURCE=..\..\7zWindows.h
149# End Source File
150# Begin Source File
151
148SOURCE=..\..\Bcj2.c 152SOURCE=..\..\Bcj2.c
149# End Source File 153# End Source File
150# Begin Source File 154# Begin Source File
diff --git a/C/Util/7z/7zMain.c b/C/Util/7z/7zMain.c
index 9d55509..547920a 100644
--- a/C/Util/7z/7zMain.c
+++ b/C/Util/7z/7zMain.c
@@ -1,5 +1,5 @@
1/* 7zMain.c - Test application for 7z Decoder 1/* 7zMain.c - Test application for 7z Decoder
22021-04-29 : Igor Pavlov : Public domain */ 22023-04-04 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -32,10 +32,10 @@
32#endif 32#endif
33#endif 33#endif
34 34
35
36#define kInputBufSize ((size_t)1 << 18) 35#define kInputBufSize ((size_t)1 << 18)
37 36
38static const ISzAlloc g_Alloc = { SzAlloc, SzFree }; 37static const ISzAlloc g_Alloc = { SzAlloc, SzFree };
38// static const ISzAlloc g_Alloc_temp = { SzAllocTemp, SzFreeTemp };
39 39
40 40
41static void Print(const char *s) 41static void Print(const char *s)
@@ -53,19 +53,19 @@ static int Buf_EnsureSize(CBuf *dest, size_t size)
53} 53}
54 54
55#ifndef _WIN32 55#ifndef _WIN32
56#define _USE_UTF8 56#define MY_USE_UTF8
57#endif 57#endif
58 58
59/* #define _USE_UTF8 */ 59/* #define MY_USE_UTF8 */
60 60
61#ifdef _USE_UTF8 61#ifdef MY_USE_UTF8
62 62
63#define _UTF8_START(n) (0x100 - (1 << (7 - (n)))) 63#define MY_UTF8_START(n) (0x100 - (1 << (7 - (n))))
64 64
65#define _UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) 65#define MY_UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6))
66 66
67#define _UTF8_HEAD(n, val) ((Byte)(_UTF8_START(n) + (val >> (6 * (n))))) 67#define MY_UTF8_HEAD(n, val) ((Byte)(MY_UTF8_START(n) + (val >> (6 * (n)))))
68#define _UTF8_CHAR(n, val) ((Byte)(0x80 + (((val) >> (6 * (n))) & 0x3F))) 68#define MY_UTF8_CHAR(n, val) ((Byte)(0x80 + (((val) >> (6 * (n))) & 0x3F)))
69 69
70static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim) 70static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim)
71{ 71{
@@ -82,7 +82,7 @@ static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim)
82 if (val < 0x80) 82 if (val < 0x80)
83 continue; 83 continue;
84 84
85 if (val < _UTF8_RANGE(1)) 85 if (val < MY_UTF8_RANGE(1))
86 { 86 {
87 size++; 87 size++;
88 continue; 88 continue;
@@ -90,7 +90,7 @@ static size_t Utf16_To_Utf8_Calc(const UInt16 *src, const UInt16 *srcLim)
90 90
91 if (val >= 0xD800 && val < 0xDC00 && src != srcLim) 91 if (val >= 0xD800 && val < 0xDC00 && src != srcLim)
92 { 92 {
93 UInt32 c2 = *src; 93 const UInt32 c2 = *src;
94 if (c2 >= 0xDC00 && c2 < 0xE000) 94 if (c2 >= 0xDC00 && c2 < 0xE000)
95 { 95 {
96 src++; 96 src++;
@@ -119,33 +119,33 @@ static Byte *Utf16_To_Utf8(Byte *dest, const UInt16 *src, const UInt16 *srcLim)
119 continue; 119 continue;
120 } 120 }
121 121
122 if (val < _UTF8_RANGE(1)) 122 if (val < MY_UTF8_RANGE(1))
123 { 123 {
124 dest[0] = _UTF8_HEAD(1, val); 124 dest[0] = MY_UTF8_HEAD(1, val);
125 dest[1] = _UTF8_CHAR(0, val); 125 dest[1] = MY_UTF8_CHAR(0, val);
126 dest += 2; 126 dest += 2;
127 continue; 127 continue;
128 } 128 }
129 129
130 if (val >= 0xD800 && val < 0xDC00 && src != srcLim) 130 if (val >= 0xD800 && val < 0xDC00 && src != srcLim)
131 { 131 {
132 UInt32 c2 = *src; 132 const UInt32 c2 = *src;
133 if (c2 >= 0xDC00 && c2 < 0xE000) 133 if (c2 >= 0xDC00 && c2 < 0xE000)
134 { 134 {
135 src++; 135 src++;
136 val = (((val - 0xD800) << 10) | (c2 - 0xDC00)) + 0x10000; 136 val = (((val - 0xD800) << 10) | (c2 - 0xDC00)) + 0x10000;
137 dest[0] = _UTF8_HEAD(3, val); 137 dest[0] = MY_UTF8_HEAD(3, val);
138 dest[1] = _UTF8_CHAR(2, val); 138 dest[1] = MY_UTF8_CHAR(2, val);
139 dest[2] = _UTF8_CHAR(1, val); 139 dest[2] = MY_UTF8_CHAR(1, val);
140 dest[3] = _UTF8_CHAR(0, val); 140 dest[3] = MY_UTF8_CHAR(0, val);
141 dest += 4; 141 dest += 4;
142 continue; 142 continue;
143 } 143 }
144 } 144 }
145 145
146 dest[0] = _UTF8_HEAD(2, val); 146 dest[0] = MY_UTF8_HEAD(2, val);
147 dest[1] = _UTF8_CHAR(1, val); 147 dest[1] = MY_UTF8_CHAR(1, val);
148 dest[2] = _UTF8_CHAR(0, val); 148 dest[2] = MY_UTF8_CHAR(0, val);
149 dest += 3; 149 dest += 3;
150 } 150 }
151} 151}
@@ -163,7 +163,7 @@ static SRes Utf16_To_Utf8Buf(CBuf *dest, const UInt16 *src, size_t srcLen)
163#endif 163#endif
164 164
165static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s 165static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s
166 #ifndef _USE_UTF8 166 #ifndef MY_USE_UTF8
167 , UINT codePage 167 , UINT codePage
168 #endif 168 #endif
169 ) 169 )
@@ -171,7 +171,7 @@ static SRes Utf16_To_Char(CBuf *buf, const UInt16 *s
171 unsigned len = 0; 171 unsigned len = 0;
172 for (len = 0; s[len] != 0; len++) {} 172 for (len = 0; s[len] != 0; len++) {}
173 173
174 #ifndef _USE_UTF8 174 #ifndef MY_USE_UTF8
175 { 175 {
176 const unsigned size = len * 3 + 100; 176 const unsigned size = len * 3 + 100;
177 if (!Buf_EnsureSize(buf, size)) 177 if (!Buf_EnsureSize(buf, size))
@@ -216,7 +216,7 @@ static WRes MyCreateDir(const UInt16 *name)
216 CBuf buf; 216 CBuf buf;
217 WRes res; 217 WRes res;
218 Buf_Init(&buf); 218 Buf_Init(&buf);
219 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); 219 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM))
220 220
221 res = 221 res =
222 #ifdef _WIN32 222 #ifdef _WIN32
@@ -239,7 +239,7 @@ static WRes OutFile_OpenUtf16(CSzFile *p, const UInt16 *name)
239 CBuf buf; 239 CBuf buf;
240 WRes res; 240 WRes res;
241 Buf_Init(&buf); 241 Buf_Init(&buf);
242 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); 242 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM))
243 res = OutFile_Open(p, (const char *)buf.data); 243 res = OutFile_Open(p, (const char *)buf.data);
244 Buf_Free(&buf, &g_Alloc); 244 Buf_Free(&buf, &g_Alloc);
245 return res; 245 return res;
@@ -253,7 +253,7 @@ static SRes PrintString(const UInt16 *s)
253 SRes res; 253 SRes res;
254 Buf_Init(&buf); 254 Buf_Init(&buf);
255 res = Utf16_To_Char(&buf, s 255 res = Utf16_To_Char(&buf, s
256 #ifndef _USE_UTF8 256 #ifndef MY_USE_UTF8
257 , CP_OEMCP 257 , CP_OEMCP
258 #endif 258 #endif
259 ); 259 );
@@ -328,12 +328,12 @@ typedef struct _FILETIME
328 328
329static LONG TIME_GetBias() 329static LONG TIME_GetBias()
330{ 330{
331 time_t utc = time(NULL); 331 const time_t utc = time(NULL);
332 struct tm *ptm = localtime(&utc); 332 struct tm *ptm = localtime(&utc);
333 int localdaylight = ptm->tm_isdst; /* daylight for local timezone */ 333 const int localdaylight = ptm->tm_isdst; /* daylight for local timezone */
334 ptm = gmtime(&utc); 334 ptm = gmtime(&utc);
335 ptm->tm_isdst = localdaylight; /* use local daylight, not that of Greenwich */ 335 ptm->tm_isdst = localdaylight; /* use local daylight, not that of Greenwich */
336 LONG bias = (int)(mktime(ptm)-utc); 336 const LONG bias = (int)(mktime(ptm) - utc);
337 return bias; 337 return bias;
338} 338}
339 339
@@ -352,7 +352,7 @@ static BOOL WINAPI FileTimeToLocalFileTime(const FILETIME *fileTime, FILETIME *l
352{ 352{
353 UInt64 v = GET_TIME_64(fileTime); 353 UInt64 v = GET_TIME_64(fileTime);
354 v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC); 354 v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC);
355 SET_FILETIME(localFileTime, v); 355 SET_FILETIME(localFileTime, v)
356 return TRUE; 356 return TRUE;
357} 357}
358 358
@@ -364,7 +364,7 @@ static const UInt64 kUnixTimeOffset =
364 364
365static Int64 Time_FileTimeToUnixTime64(const FILETIME *ft) 365static Int64 Time_FileTimeToUnixTime64(const FILETIME *ft)
366{ 366{
367 UInt64 winTime = GET_TIME_64(ft); 367 const UInt64 winTime = GET_TIME_64(ft);
368 return (Int64)(winTime / kNumTimeQuantumsInSecond) - (Int64)kUnixTimeOffset; 368 return (Int64)(winTime / kNumTimeQuantumsInSecond) - (Int64)kUnixTimeOffset;
369} 369}
370 370
@@ -384,8 +384,8 @@ static void FILETIME_To_timespec(const FILETIME *ft, struct MY_ST_TIMESPEC *ts)
384 if (sec2 == sec) 384 if (sec2 == sec)
385 { 385 {
386 ts->tv_sec = sec2; 386 ts->tv_sec = sec2;
387 UInt64 winTime = GET_TIME_64(ft); 387 const UInt64 winTime = GET_TIME_64(ft);
388 ts->tv_nsec = (long)((winTime % 10000000) * 100);; 388 ts->tv_nsec = (long)((winTime % 10000000) * 100);
389 return; 389 return;
390 } 390 }
391 } 391 }
@@ -407,7 +407,7 @@ static WRes Set_File_FILETIME(const UInt16 *name, const FILETIME *mTime)
407 CBuf buf; 407 CBuf buf;
408 int res; 408 int res;
409 Buf_Init(&buf); 409 Buf_Init(&buf);
410 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM)); 410 RINOK(Utf16_To_Char(&buf, name MY_FILE_CODE_PAGE_PARAM))
411 FILETIME_To_timespec(NULL, &times[0]); 411 FILETIME_To_timespec(NULL, &times[0]);
412 FILETIME_To_timespec(mTime, &times[1]); 412 FILETIME_To_timespec(mTime, &times[1]);
413 res = utimensat(AT_FDCWD, (const char *)buf.data, times, flags); 413 res = utimensat(AT_FDCWD, (const char *)buf.data, times, flags);
@@ -461,7 +461,7 @@ static void ConvertFileTimeToString(const CNtfsFileTime *nTime, char *s)
461 ms[1] = 29; 461 ms[1] = 29;
462 for (mon = 0;; mon++) 462 for (mon = 0;; mon++)
463 { 463 {
464 unsigned d = ms[mon]; 464 const unsigned d = ms[mon];
465 if (v < d) 465 if (v < d)
466 break; 466 break;
467 v -= d; 467 v -= d;
@@ -474,7 +474,7 @@ static void ConvertFileTimeToString(const CNtfsFileTime *nTime, char *s)
474 UIntToStr_2(s, sec); s[2] = 0; 474 UIntToStr_2(s, sec); s[2] = 0;
475} 475}
476 476
477static void PrintLF() 477static void PrintLF(void)
478{ 478{
479 Print("\n"); 479 Print("\n");
480} 480}
@@ -541,7 +541,7 @@ static void GetAttribString(UInt32 wa, BoolInt isDir, char *s)
541 541
542// #define NUM_PARENTS_MAX 128 542// #define NUM_PARENTS_MAX 128
543 543
544int MY_CDECL main(int numargs, char *args[]) 544int Z7_CDECL main(int numargs, char *args[])
545{ 545{
546 ISzAlloc allocImp; 546 ISzAlloc allocImp;
547 ISzAlloc allocTempImp; 547 ISzAlloc allocTempImp;
@@ -581,6 +581,7 @@ int MY_CDECL main(int numargs, char *args[])
581 581
582 allocImp = g_Alloc; 582 allocImp = g_Alloc;
583 allocTempImp = g_Alloc; 583 allocTempImp = g_Alloc;
584 // allocTempImp = g_Alloc_temp;
584 585
585 { 586 {
586 WRes wres = 587 WRes wres =
@@ -611,7 +612,7 @@ int MY_CDECL main(int numargs, char *args[])
611 { 612 {
612 lookStream.bufSize = kInputBufSize; 613 lookStream.bufSize = kInputBufSize;
613 lookStream.realStream = &archiveStream.vt; 614 lookStream.realStream = &archiveStream.vt;
614 LookToRead2_Init(&lookStream); 615 LookToRead2_INIT(&lookStream)
615 } 616 }
616 } 617 }
617 618
@@ -767,7 +768,7 @@ int MY_CDECL main(int numargs, char *args[])
767 } 768 }
768 else 769 else
769 { 770 {
770 WRes wres = OutFile_OpenUtf16(&outFile, destPath); 771 const WRes wres = OutFile_OpenUtf16(&outFile, destPath);
771 if (wres != 0) 772 if (wres != 0)
772 { 773 {
773 PrintError_WRes("cannot open output file", wres); 774 PrintError_WRes("cannot open output file", wres);
@@ -779,7 +780,7 @@ int MY_CDECL main(int numargs, char *args[])
779 processedSize = outSizeProcessed; 780 processedSize = outSizeProcessed;
780 781
781 { 782 {
782 WRes wres = File_Write(&outFile, outBuffer + offset, &processedSize); 783 const WRes wres = File_Write(&outFile, outBuffer + offset, &processedSize);
783 if (wres != 0 || processedSize != outSizeProcessed) 784 if (wres != 0 || processedSize != outSizeProcessed)
784 { 785 {
785 PrintError_WRes("cannot write output file", wres); 786 PrintError_WRes("cannot write output file", wres);
@@ -819,7 +820,7 @@ int MY_CDECL main(int numargs, char *args[])
819 #endif 820 #endif
820 821
821 { 822 {
822 WRes wres = File_Close(&outFile); 823 const WRes wres = File_Close(&outFile);
823 if (wres != 0) 824 if (wres != 0)
824 { 825 {
825 PrintError_WRes("cannot close output file", wres); 826 PrintError_WRes("cannot close output file", wres);
diff --git a/C/Util/7z/Precomp.h b/C/Util/7z/Precomp.h
index 588a66f..bc8fa21 100644
--- a/C/Util/7z/Precomp.h
+++ b/C/Util/7z/Precomp.h
@@ -1,8 +1,12 @@
1/* Precomp.h -- StdAfx 1/* Precomp.h -- StdAfx
22013-06-16 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_PRECOMP_H 4#ifndef ZIP7_INC_PRECOMP_H
5#define __7Z_PRECOMP_H 5#define ZIP7_INC_PRECOMP_H
6
7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
6 10
7#include "../../Compiler.h" 11#include "../../Compiler.h"
8#include "../../7zTypes.h" 12#include "../../7zTypes.h"
diff --git a/C/Util/7z/makefile b/C/Util/7z/makefile
index 9a49fd5..dfc560e 100644
--- a/C/Util/7z/makefile
+++ b/C/Util/7z/makefile
@@ -1,4 +1,4 @@
1CFLAGS = $(CFLAGS) -D_7ZIP_PPMD_SUPPPORT 1CFLAGS = $(CFLAGS) -DZ7_PPMD_SUPPORT -DZ7_EXTRACT_ONLY
2 2
3PROG = 7zDec.exe 3PROG = 7zDec.exe
4 4
diff --git a/C/Util/7z/makefile.gcc b/C/Util/7z/makefile.gcc
index 4263d67..f48d362 100644
--- a/C/Util/7z/makefile.gcc
+++ b/C/Util/7z/makefile.gcc
@@ -1,6 +1,6 @@
1PROG = 7zdec 1PROG = 7zdec
2 2
3LOCAL_FLAGS = -D_7ZIP_PPMD_SUPPPORT 3LOCAL_FLAGS = -DZ7_PPMD_SUPPORT -DZ7_EXTRACT_ONLY
4 4
5include ../../../CPP/7zip/LzmaDec_gcc.mak 5include ../../../CPP/7zip/LzmaDec_gcc.mak
6 6
@@ -19,8 +19,6 @@ OBJS = \
19 $O/Ppmd7Dec.o \ 19 $O/Ppmd7Dec.o \
20 $O/7zCrc.o \ 20 $O/7zCrc.o \
21 $O/7zCrcOpt.o \ 21 $O/7zCrcOpt.o \
22 $O/Sha256.o \
23 $O/Sha256Opt.o \
24 $O/7zAlloc.o \ 22 $O/7zAlloc.o \
25 $O/7zArcIn.o \ 23 $O/7zArcIn.o \
26 $O/7zBuf.o \ 24 $O/7zBuf.o \
diff --git a/C/Util/7zipInstall/7zipInstall.c b/C/Util/7zipInstall/7zipInstall.c
index 2649734..7f5fd19 100644
--- a/C/Util/7zipInstall/7zipInstall.c
+++ b/C/Util/7zipInstall/7zipInstall.c
@@ -1,16 +1,31 @@
1/* 7zipInstall.c - 7-Zip Installer 1/* 7zipInstall.c - 7-Zip Installer
22022-07-15 : Igor Pavlov : Public domain */ 22023-04-04 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#define SZ_ERROR_ABORT 100 6#define SZ_ERROR_ABORT 100
7 7
8#ifdef _MSC_VER 8#include "../../7zWindows.h"
9
10#if defined(_MSC_VER) && _MSC_VER < 1600
9#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union 11#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union
10#endif 12#endif
11 13
12#include <windows.h> 14#ifdef Z7_OLD_WIN_SDK
15struct IShellView;
16#define SHFOLDERAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE
17SHFOLDERAPI SHGetFolderPathW(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
18#define BIF_NEWDIALOGSTYLE 0x0040 // Use the new dialog layout with the ability to resize
19typedef enum {
20 SHGFP_TYPE_CURRENT = 0, // current value for user, verify it exists
21 SHGFP_TYPE_DEFAULT = 1, // default value, may not exist
22} SHGFP_TYPE;
23#endif
24#if defined(__MINGW32__) || defined(__MINGW64__)
25#include <shlobj.h>
26#else
13#include <ShlObj.h> 27#include <ShlObj.h>
28#endif
14 29
15#include "../../7z.h" 30#include "../../7z.h"
16#include "../../7zAlloc.h" 31#include "../../7zAlloc.h"
@@ -22,40 +37,46 @@
22 37
23#include "resource.h" 38#include "resource.h"
24 39
25#if defined(__GNUC__) && (__GNUC__ >= 8) 40#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__)
26 #pragma GCC diagnostic ignored "-Wcast-function-type" 41 // #pragma GCC diagnostic ignored "-Wcast-function-type"
42#endif
43
44#if defined(__clang__) || defined(__GNUC__)
45typedef void (*Z7_voidFunction)(void);
46#define MY_CAST_FUNC (Z7_voidFunction)
47#elif defined(_MSC_VER) && _MSC_VER > 1920
48#define MY_CAST_FUNC (void *)
49// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()'
50#else
51#define MY_CAST_FUNC
27#endif 52#endif
28 53
29#define LLL_(quote) L##quote 54#define LLL_(quote) L##quote
30#define LLL(quote) LLL_(quote) 55#define LLL(quote) LLL_(quote)
31 56
32#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
33
34#define wcscat lstrcatW 57#define wcscat lstrcatW
35#define wcslen lstrlenW 58#define wcslen (size_t)lstrlenW
36#define wcscpy lstrcpyW 59#define wcscpy lstrcpyW
37// wcsncpy() and lstrcpynW() work differently. We don't use them. 60// wcsncpy() and lstrcpynW() work differently. We don't use them.
38 61
39
40#define kInputBufSize ((size_t)1 << 18) 62#define kInputBufSize ((size_t)1 << 18)
41 63
42 64#define Z7_7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR)
43#define _7ZIP_CUR_VER ((MY_VER_MAJOR << 16) | MY_VER_MINOR) 65#define Z7_7ZIP_DLL_VER_COMPAT ((16 << 16) | 3)
44#define _7ZIP_DLL_VER_COMPAT ((16 << 16) | 3)
45 66
46static LPCSTR const k_7zip = "7-Zip"; 67static LPCSTR const k_7zip = "7-Zip";
47 68
48static LPCWSTR const k_Reg_Software_7zip = L"Software\\7-Zip"; 69static LPCWSTR const k_Reg_Software_7zip = L"Software\\7-Zip";
49 70
50// #define _64BIT_INSTALLER 1 71// #define Z7_64BIT_INSTALLER 1
51 72
52#ifdef _WIN64 73#ifdef _WIN64
53 #define _64BIT_INSTALLER 1 74 #define Z7_64BIT_INSTALLER 1
54#endif 75#endif
55 76
56#define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION) 77#define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION)
57 78
58#ifdef _64BIT_INSTALLER 79#ifdef Z7_64BIT_INSTALLER
59 80
60 // #define USE_7ZIP_32_DLL 81 // #define USE_7ZIP_32_DLL
61 82
@@ -84,14 +105,14 @@ static LPCWSTR const k_7zip_Setup = k_7zip_with_Ver L" Setup";
84static LPCWSTR const k_Reg_Path = L"Path"; 105static LPCWSTR const k_Reg_Path = L"Path";
85 106
86static LPCWSTR const k_Reg_Path32 = L"Path" 107static LPCWSTR const k_Reg_Path32 = L"Path"
87 #ifdef _64BIT_INSTALLER 108 #ifdef Z7_64BIT_INSTALLER
88 L"64" 109 L"64"
89 #else 110 #else
90 L"32" 111 L"32"
91 #endif 112 #endif
92 ; 113 ;
93 114
94#if defined(_64BIT_INSTALLER) && !defined(_WIN64) 115#if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64)
95 #define k_Reg_WOW_Flag KEY_WOW64_64KEY 116 #define k_Reg_WOW_Flag KEY_WOW64_64KEY
96#else 117#else
97 #define k_Reg_WOW_Flag 0 118 #define k_Reg_WOW_Flag 0
@@ -126,8 +147,6 @@ static WCHAR cmdError[MAX_PATH + 4];
126static WCHAR path[MAX_PATH * 2 + 40]; 147static WCHAR path[MAX_PATH * 2 + 40];
127 148
128 149
129// #define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c)))
130
131 150
132static void CpyAscii(wchar_t *dest, const char *s) 151static void CpyAscii(wchar_t *dest, const char *s)
133{ 152{
@@ -200,9 +219,12 @@ static DWORD GetFileVersion(LPCWSTR s)
200 return 0; 219 return 0;
201 } 220 }
202 221
203 my_GetFileVersionInfoSizeW = (Func_GetFileVersionInfoSizeW)GetProcAddress(g_version_dll_hModule, "GetFileVersionInfoSizeW"); 222 my_GetFileVersionInfoSizeW = (Func_GetFileVersionInfoSizeW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule,
204 my_GetFileVersionInfoW = (Func_GetFileVersionInfoW)GetProcAddress(g_version_dll_hModule, "GetFileVersionInfoW"); 223 "GetFileVersionInfoSizeW");
205 my_VerQueryValueW = (Func_VerQueryValueW)GetProcAddress(g_version_dll_hModule, "VerQueryValueW"); 224 my_GetFileVersionInfoW = (Func_GetFileVersionInfoW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule,
225 "GetFileVersionInfoW");
226 my_VerQueryValueW = (Func_VerQueryValueW) MY_CAST_FUNC GetProcAddress(g_version_dll_hModule,
227 "VerQueryValueW");
206 228
207 if (!my_GetFileVersionInfoSizeW 229 if (!my_GetFileVersionInfoSizeW
208 || !my_GetFileVersionInfoW 230 || !my_GetFileVersionInfoW
@@ -253,7 +275,7 @@ static int ReverseFind_PathSepar(const wchar_t *s)
253 } 275 }
254} 276}
255 277
256static WRes CreateComplexDir() 278static WRes CreateComplexDir(void)
257{ 279{
258 WCHAR s[MAX_PATH + 10]; 280 WCHAR s[MAX_PATH + 10];
259 281
@@ -287,7 +309,7 @@ static WRes CreateComplexDir()
287 { 309 {
288 size_t len = wcslen(s); 310 size_t len = wcslen(s);
289 { 311 {
290 int pos = ReverseFind_PathSepar(s); 312 const int pos = ReverseFind_PathSepar(s);
291 if (pos < 0) 313 if (pos < 0)
292 return wres; 314 return wres;
293 if ((unsigned)pos < prefixSize) 315 if ((unsigned)pos < prefixSize)
@@ -297,7 +319,7 @@ static WRes CreateComplexDir()
297 if (len == 1) 319 if (len == 1)
298 return 0; 320 return 0;
299 s[pos] = 0; 321 s[pos] = 0;
300 len = pos; 322 len = (unsigned)pos;
301 } 323 }
302 } 324 }
303 325
@@ -309,7 +331,7 @@ static WRes CreateComplexDir()
309 break; 331 break;
310 if (wres == ERROR_ALREADY_EXISTS) 332 if (wres == ERROR_ALREADY_EXISTS)
311 { 333 {
312 DWORD attrib = GetFileAttributesW(s); 334 const DWORD attrib = GetFileAttributesW(s);
313 if (attrib != INVALID_FILE_ATTRIBUTES) 335 if (attrib != INVALID_FILE_ATTRIBUTES)
314 if ((attrib & FILE_ATTRIBUTE_DIRECTORY) == 0) 336 if ((attrib & FILE_ATTRIBUTE_DIRECTORY) == 0)
315 return ERROR_ALREADY_EXISTS; 337 return ERROR_ALREADY_EXISTS;
@@ -323,7 +345,7 @@ static WRes CreateComplexDir()
323 345
324 for (;;) 346 for (;;)
325 { 347 {
326 size_t pos = wcslen(s); 348 const size_t pos = wcslen(s);
327 if (pos >= len) 349 if (pos >= len)
328 return 0; 350 return 0;
329 s[pos] = CHAR_PATH_SEPARATOR; 351 s[pos] = CHAR_PATH_SEPARATOR;
@@ -339,7 +361,7 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest)
339{ 361{
340 DWORD cnt = MAX_PATH * sizeof(name[0]); 362 DWORD cnt = MAX_PATH * sizeof(name[0]);
341 DWORD type = 0; 363 DWORD type = 0;
342 LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, (DWORD *)&cnt); 364 const LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, &cnt);
343 if (type != REG_SZ) 365 if (type != REG_SZ)
344 return False; 366 return False;
345 return res == ERROR_SUCCESS; 367 return res == ERROR_SUCCESS;
@@ -348,11 +370,11 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest)
348static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) 370static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest)
349{ 371{
350 HKEY key = 0; 372 HKEY key = 0;
351 LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); 373 const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key);
352 if (res != ERROR_SUCCESS) 374 if (res != ERROR_SUCCESS)
353 return False; 375 return False;
354 { 376 {
355 BoolInt res2 = MyRegistry_QueryString(key, valName, dest); 377 const BoolInt res2 = MyRegistry_QueryString(key, valName, dest);
356 RegCloseKey(key); 378 RegCloseKey(key);
357 return res2; 379 return res2;
358 } 380 }
@@ -550,7 +572,7 @@ static void NormalizePrefix(WCHAR *s)
550 572
551 for (;; i++) 573 for (;; i++)
552 { 574 {
553 wchar_t c = s[i]; 575 const wchar_t c = s[i];
554 if (c == 0) 576 if (c == 0)
555 break; 577 break;
556 if (c == '/') 578 if (c == '/')
@@ -587,7 +609,7 @@ static LPCWSTR FindSubString(LPCWSTR s1, const char *s2)
587 return NULL; 609 return NULL;
588 for (i = 0;; i++) 610 for (i = 0;; i++)
589 { 611 {
590 Byte b = s2[i]; 612 const char b = s2[i];
591 if (b == 0) 613 if (b == 0)
592 return s1; 614 return s1;
593 if (MyWCharLower_Ascii(s1[i]) != (Byte)MyCharLower_Ascii(b)) 615 if (MyWCharLower_Ascii(s1[i]) != (Byte)MyCharLower_Ascii(b))
@@ -610,7 +632,7 @@ static void Set7zipPostfix(WCHAR *s)
610 632
611static int Install(void); 633static int Install(void);
612 634
613static void OnClose() 635static void OnClose(void)
614{ 636{
615 if (g_Install_was_Pressed && !g_Finished) 637 if (g_Install_was_Pressed && !g_Finished)
616 { 638 {
@@ -624,7 +646,13 @@ static void OnClose()
624 g_HWND = NULL; 646 g_HWND = NULL;
625} 647}
626 648
627static INT_PTR CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 649static
650#ifdef Z7_OLD_WIN_SDK
651 BOOL
652#else
653 INT_PTR
654#endif
655CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
628{ 656{
629 // UNUSED_VAR(hwnd) 657 // UNUSED_VAR(hwnd)
630 UNUSED_VAR(lParam) 658 UNUSED_VAR(lParam)
@@ -730,7 +758,7 @@ static LONG SetRegKey_Path2(HKEY parentKey)
730 return res; 758 return res;
731} 759}
732 760
733static void SetRegKey_Path() 761static void SetRegKey_Path(void)
734{ 762{
735 SetRegKey_Path2(HKEY_CURRENT_USER); 763 SetRegKey_Path2(HKEY_CURRENT_USER);
736 SetRegKey_Path2(HKEY_LOCAL_MACHINE); 764 SetRegKey_Path2(HKEY_LOCAL_MACHINE);
@@ -828,7 +856,7 @@ static void SetShellProgramsGroup(HWND hwndOwner)
828static LPCWSTR const k_Shell_Approved = L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"; 856static LPCWSTR const k_Shell_Approved = L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved";
829static LPCWSTR const k_7zip_ShellExtension = L"7-Zip Shell Extension"; 857static LPCWSTR const k_7zip_ShellExtension = L"7-Zip Shell Extension";
830 858
831static void WriteCLSID() 859static void WriteCLSID(void)
832{ 860{
833 HKEY destKey; 861 HKEY destKey;
834 LONG res; 862 LONG res;
@@ -879,12 +907,12 @@ static LPCSTR const k_ShellEx_Items[] =
879 , "Drive\\shellex\\DragDropHandlers" 907 , "Drive\\shellex\\DragDropHandlers"
880}; 908};
881 909
882static void WriteShellEx() 910static void WriteShellEx(void)
883{ 911{
884 unsigned i; 912 unsigned i;
885 WCHAR destPath[MAX_PATH + 40]; 913 WCHAR destPath[MAX_PATH + 40];
886 914
887 for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) 915 for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++)
888 { 916 {
889 CpyAscii(destPath, k_ShellEx_Items[i]); 917 CpyAscii(destPath, k_ShellEx_Items[i]);
890 CatAscii(destPath, "\\7-Zip"); 918 CatAscii(destPath, "\\7-Zip");
@@ -968,7 +996,7 @@ static const wchar_t *GetCmdParam(const wchar_t *s)
968 quoteMode = !quoteMode; 996 quoteMode = !quoteMode;
969 continue; 997 continue;
970 } 998 }
971 if (pos >= ARRAY_SIZE(cmd) - 1) 999 if (pos >= Z7_ARRAY_SIZE(cmd) - 1)
972 exit(1); 1000 exit(1);
973 cmd[pos++] = c; 1001 cmd[pos++] = c;
974 } 1002 }
@@ -1026,7 +1054,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1026 for (;;) 1054 for (;;)
1027 { 1055 {
1028 { 1056 {
1029 wchar_t c = *s; 1057 const wchar_t c = *s;
1030 if (c == 0) 1058 if (c == 0)
1031 break; 1059 break;
1032 if (c == ' ') 1060 if (c == ' ')
@@ -1070,11 +1098,12 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1070 } 1098 }
1071 } 1099 }
1072 1100
1073 #if defined(_64BIT_INSTALLER) && !defined(_WIN64) 1101 #if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64)
1074 { 1102 {
1075 BOOL isWow64 = FALSE; 1103 BOOL isWow64 = FALSE;
1076 Func_IsWow64Process func_IsWow64Process = (Func_IsWow64Process) 1104 const Func_IsWow64Process func_IsWow64Process = (Func_IsWow64Process)
1077 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process"); 1105 MY_CAST_FUNC GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
1106 "IsWow64Process");
1078 1107
1079 if (func_IsWow64Process) 1108 if (func_IsWow64Process)
1080 func_IsWow64Process(GetCurrentProcess(), &isWow64); 1109 func_IsWow64Process(GetCurrentProcess(), &isWow64);
@@ -1093,7 +1122,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1093 { 1122 {
1094 HKEY key = 0; 1123 HKEY key = 0;
1095 BoolInt ok = False; 1124 BoolInt ok = False;
1096 LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, k_Reg_Software_7zip, 0, KEY_READ | k_Reg_WOW_Flag, &key); 1125 const LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, k_Reg_Software_7zip, 0, KEY_READ | k_Reg_WOW_Flag, &key);
1097 if (res == ERROR_SUCCESS) 1126 if (res == ERROR_SUCCESS)
1098 { 1127 {
1099 ok = MyRegistry_QueryString(key, k_Reg_Path32, path); 1128 ok = MyRegistry_QueryString(key, k_Reg_Path32, path);
@@ -1109,7 +1138,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1109 CpyAscii(path, "\\Program Files\\"); 1138 CpyAscii(path, "\\Program Files\\");
1110 #else 1139 #else
1111 1140
1112 #ifdef _64BIT_INSTALLER 1141 #ifdef Z7_64BIT_INSTALLER
1113 { 1142 {
1114 DWORD ttt = GetEnvironmentVariableW(L"ProgramW6432", path, MAX_PATH); 1143 DWORD ttt = GetEnvironmentVariableW(L"ProgramW6432", path, MAX_PATH);
1115 if (ttt == 0 || ttt > MAX_PATH) 1144 if (ttt == 0 || ttt > MAX_PATH)
@@ -1150,7 +1179,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1150 return 1; 1179 return 1;
1151 1180
1152 { 1181 {
1153 HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); 1182 const HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON));
1154 // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); 1183 // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
1155 SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); 1184 SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
1156 } 1185 }
@@ -1244,7 +1273,7 @@ static int Install(void)
1244 allocTempImp.Free = SzFreeTemp; 1273 allocTempImp.Free = SzFreeTemp;
1245 1274
1246 { 1275 {
1247 DWORD len = GetModuleFileNameW(NULL, sfxPath, MAX_PATH); 1276 const DWORD len = GetModuleFileNameW(NULL, sfxPath, MAX_PATH);
1248 if (len == 0 || len > MAX_PATH) 1277 if (len == 0 || len > MAX_PATH)
1249 return 1; 1278 return 1;
1250 } 1279 }
@@ -1286,7 +1315,7 @@ if (res == SZ_OK)
1286 1315
1287 for (;;) 1316 for (;;)
1288 { 1317 {
1289 wchar_t c = path[i++]; 1318 const wchar_t c = path[i++];
1290 if (c == 0) 1319 if (c == 0)
1291 break; 1320 break;
1292 if (c != ' ') 1321 if (c != ' ')
@@ -1318,7 +1347,7 @@ if (res == SZ_OK)
1318 { 1347 {
1319 lookStream.bufSize = kInputBufSize; 1348 lookStream.bufSize = kInputBufSize;
1320 lookStream.realStream = &archiveStream.vt; 1349 lookStream.realStream = &archiveStream.vt;
1321 LookToRead2_Init(&lookStream); 1350 LookToRead2_INIT(&lookStream)
1322 } 1351 }
1323 } 1352 }
1324 1353
@@ -1372,7 +1401,7 @@ if (res == SZ_OK)
1372 } 1401 }
1373 1402
1374 { 1403 {
1375 size_t len = SzArEx_GetFileNameUtf16(&db, i, NULL); 1404 const size_t len = SzArEx_GetFileNameUtf16(&db, i, NULL);
1376 if (len >= MAX_PATH) 1405 if (len >= MAX_PATH)
1377 { 1406 {
1378 res = SZ_ERROR_FAIL; 1407 res = SZ_ERROR_FAIL;
@@ -1468,8 +1497,8 @@ if (res == SZ_OK)
1468 #endif 1497 #endif
1469 ) 1498 )
1470 { 1499 {
1471 DWORD ver = GetFileVersion(path); 1500 const DWORD ver = GetFileVersion(path);
1472 fileLevel = ((ver < _7ZIP_DLL_VER_COMPAT || ver > _7ZIP_CUR_VER) ? 2 : 1); 1501 fileLevel = ((ver < Z7_7ZIP_DLL_VER_COMPAT || ver > Z7_7ZIP_CUR_VER) ? 2 : 1);
1473 tempIndex++; 1502 tempIndex++;
1474 continue; 1503 continue;
1475 } 1504 }
@@ -1537,7 +1566,7 @@ if (res == SZ_OK)
1537 #endif 1566 #endif
1538 1567
1539 { 1568 {
1540 SRes winRes2 = File_Close(&outFile); 1569 const WRes winRes2 = File_Close(&outFile);
1541 if (res != SZ_OK) 1570 if (res != SZ_OK)
1542 break; 1571 break;
1543 if (winRes2 != 0) 1572 if (winRes2 != 0)
diff --git a/C/Util/7zipInstall/7zipInstall.dsp b/C/Util/7zipInstall/7zipInstall.dsp
index d3b5c4c..4c6ea4d 100644
--- a/C/Util/7zipInstall/7zipInstall.dsp
+++ b/C/Util/7zipInstall/7zipInstall.dsp
@@ -152,6 +152,10 @@ SOURCE=..\..\7zVersion.h
152# End Source File 152# End Source File
153# Begin Source File 153# Begin Source File
154 154
155SOURCE=..\..\7zWindows.h
156# End Source File
157# Begin Source File
158
155SOURCE=..\..\Bcj2.c 159SOURCE=..\..\Bcj2.c
156# End Source File 160# End Source File
157# Begin Source File 161# Begin Source File
@@ -220,6 +224,10 @@ SOURCE=..\..\LzmaDec.h
220# PROP Default_Filter "" 224# PROP Default_Filter ""
221# Begin Source File 225# Begin Source File
222 226
227SOURCE=..\..\Compiler.h
228# End Source File
229# Begin Source File
230
223SOURCE=.\Precomp.c 231SOURCE=.\Precomp.c
224# ADD CPP /Yc"Precomp.h" 232# ADD CPP /Yc"Precomp.h"
225# End Source File 233# End Source File
diff --git a/C/Util/7zipInstall/Precomp.h b/C/Util/7zipInstall/Precomp.h
index 4c90d47..bc8fa21 100644
--- a/C/Util/7zipInstall/Precomp.h
+++ b/C/Util/7zipInstall/Precomp.h
@@ -1,11 +1,14 @@
1/* Precomp.h -- StdAfx 1/* Precomp.h -- StdAfx
22015-05-24 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_PRECOMP_H 4#ifndef ZIP7_INC_PRECOMP_H
5#define __7Z_PRECOMP_H 5#define ZIP7_INC_PRECOMP_H
6 6
7#include "../../Compiler.h" 7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
8 10
11#include "../../Compiler.h"
9#include "../../7zTypes.h" 12#include "../../7zTypes.h"
10 13
11#endif 14#endif
diff --git a/C/Util/7zipInstall/makefile b/C/Util/7zipInstall/makefile
index ab8893a..18e2783 100644
--- a/C/Util/7zipInstall/makefile
+++ b/C/Util/7zipInstall/makefile
@@ -1,15 +1,16 @@
1PROG = 7zipInstall.exe 1PROG = 7zipInstall.exe
2MY_FIXED = 1 2MY_FIXED = 1
3 3
4!IFDEF _64BIT_INSTALLER 4!IFDEF Z7_64BIT_INSTALLER
5CFLAGS = $(CFLAGS) -D_64BIT_INSTALLER 5CFLAGS = $(CFLAGS) -DZ7_64BIT_INSTALLER
6!ENDIF 6!ENDIF
7 7
8CFLAGS = $(CFLAGS) -D_LZMA_SIZE_OPT
9
10CFLAGS = $(CFLAGS) \ 8CFLAGS = $(CFLAGS) \
11 -D_7Z_NO_METHOD_LZMA2 \ 9 -DZ7_LZMA_SIZE_OPT \
12 -D_7Z_NO_METHODS_FILTERS 10 -DZ7_NO_METHOD_LZMA2 \
11 -DZ7_NO_METHODS_FILTERS \
12 -DZ7_USE_NATIVE_BRANCH_FILTER \
13 -DZ7_EXTRACT_ONLY \
13 14
14MAIN_OBJS = \ 15MAIN_OBJS = \
15 $O\7zipInstall.obj \ 16 $O\7zipInstall.obj \
@@ -25,6 +26,7 @@ C_OBJS = \
25 $O\7zDec.obj \ 26 $O\7zDec.obj \
26 $O\7zStream.obj \ 27 $O\7zStream.obj \
27 $O\Bcj2.obj \ 28 $O\Bcj2.obj \
29 $O\Bra.obj \
28 $O\CpuArch.obj \ 30 $O\CpuArch.obj \
29 $O\DllSecur.obj \ 31 $O\DllSecur.obj \
30 $O\LzmaDec.obj \ 32 $O\LzmaDec.obj \
diff --git a/C/Util/7zipUninstall/7zipUninstall.c b/C/Util/7zipUninstall/7zipUninstall.c
index c8e8a89..8bc18b3 100644
--- a/C/Util/7zipUninstall/7zipUninstall.c
+++ b/C/Util/7zipUninstall/7zipUninstall.c
@@ -3,40 +3,64 @@
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
6#ifdef _MSC_VER 6// #define SZ_ERROR_ABORT 100
7
8#include "../../7zWindows.h"
9
10#if defined(_MSC_VER) && _MSC_VER < 1600
7#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union 11#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union
8#pragma warning(disable : 4011) // vs2010: identifier truncated to _CRT_SECURE_CPP_OVERLOAD_SECURE
9#endif 12#endif
10 13
11// #define SZ_ERROR_ABORT 100 14#ifdef Z7_OLD_WIN_SDK
12 15struct IShellView;
13#include <windows.h> 16#define SHFOLDERAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE
17SHFOLDERAPI SHGetFolderPathW(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
18#define BIF_NEWDIALOGSTYLE 0x0040 // Use the new dialog layout with the ability to resize
19typedef enum {
20 SHGFP_TYPE_CURRENT = 0, // current value for user, verify it exists
21 SHGFP_TYPE_DEFAULT = 1, // default value, may not exist
22} SHGFP_TYPE;
23#endif
24#if defined(__MINGW32__) || defined(__MINGW64__)
25#include <shlobj.h>
26#else
14#include <ShlObj.h> 27#include <ShlObj.h>
28#endif
15 29
16#include "../../7zVersion.h" 30#include "../../7zVersion.h"
17 31
18#include "resource.h" 32#include "resource.h"
19 33
20#if defined(__GNUC__) && (__GNUC__ >= 8) 34#if (defined(__GNUC__) && (__GNUC__ >= 8)) || defined(__clang__)
21 #pragma GCC diagnostic ignored "-Wcast-function-type" 35 // #pragma GCC diagnostic ignored "-Wcast-function-type"
22#endif 36#endif
23 37
38#if defined(_MSC_VER) && _MSC_VER > 1920
39#define MY_CAST_FUNC (void *)
40// #pragma warning(disable : 4191) // 'type cast': unsafe conversion from 'FARPROC' to 'void (__cdecl *)()'
41#else
42#define MY_CAST_FUNC
43#endif
44
45
24#define LLL_(quote) L##quote 46#define LLL_(quote) L##quote
25#define LLL(quote) LLL_(quote) 47#define LLL(quote) LLL_(quote)
26 48
27#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 49#define wcscat lstrcatW
50#define wcslen (size_t)lstrlenW
51#define wcscpy lstrcpyW
28 52
29// static LPCWSTR const k_7zip = L"7-Zip"; 53// static LPCWSTR const k_7zip = L"7-Zip";
30 54
31// #define _64BIT_INSTALLER 1 55// #define Z7_64BIT_INSTALLER 1
32 56
33#ifdef _WIN64 57#ifdef _WIN64
34 #define _64BIT_INSTALLER 1 58 #define Z7_64BIT_INSTALLER 1
35#endif 59#endif
36 60
37#define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION) 61#define k_7zip_with_Ver_base L"7-Zip " LLL(MY_VERSION)
38 62
39#ifdef _64BIT_INSTALLER 63#ifdef Z7_64BIT_INSTALLER
40 64
41 // #define USE_7ZIP_32_DLL 65 // #define USE_7ZIP_32_DLL
42 66
@@ -64,14 +88,14 @@ static LPCWSTR const k_Reg_Software_7zip = L"Software\\7-Zip";
64static LPCWSTR const k_Reg_Path = L"Path"; 88static LPCWSTR const k_Reg_Path = L"Path";
65 89
66static LPCWSTR const k_Reg_Path32 = L"Path" 90static LPCWSTR const k_Reg_Path32 = L"Path"
67 #ifdef _64BIT_INSTALLER 91 #ifdef Z7_64BIT_INSTALLER
68 L"64" 92 L"64"
69 #else 93 #else
70 L"32" 94 L"32"
71 #endif 95 #endif
72 ; 96 ;
73 97
74#if defined(_64BIT_INSTALLER) && !defined(_WIN64) 98#if defined(Z7_64BIT_INSTALLER) && !defined(_WIN64)
75 #define k_Reg_WOW_Flag KEY_WOW64_64KEY 99 #define k_Reg_WOW_Flag KEY_WOW64_64KEY
76#else 100#else
77 #define k_Reg_WOW_Flag 0 101 #define k_Reg_WOW_Flag 0
@@ -116,14 +140,14 @@ static WCHAR copyPath[MAX_PATH * 2 + 40];
116 140
117static LPCWSTR const kUninstallExe = L"Uninstall.exe"; 141static LPCWSTR const kUninstallExe = L"Uninstall.exe";
118 142
119#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c))) 143#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) - 0x20 : (c)))
120 144
121 145
122static void CpyAscii(wchar_t *dest, const char *s) 146static void CpyAscii(wchar_t *dest, const char *s)
123{ 147{
124 for (;;) 148 for (;;)
125 { 149 {
126 Byte b = (Byte)*s++; 150 const Byte b = (Byte)*s++;
127 *dest++ = b; 151 *dest++ = b;
128 if (b == 0) 152 if (b == 0)
129 return; 153 return;
@@ -173,7 +197,7 @@ static BoolInt IsString1PrefixedByString2_NoCase(const wchar_t *s1, const wchar_
173 for (;;) 197 for (;;)
174 { 198 {
175 wchar_t c1; 199 wchar_t c1;
176 wchar_t c2 = *s2++; 200 const wchar_t c2 = *s2++;
177 if (c2 == 0) 201 if (c2 == 0)
178 return True; 202 return True;
179 c1 = *s1++; 203 c1 = *s1++;
@@ -184,7 +208,7 @@ static BoolInt IsString1PrefixedByString2_NoCase(const wchar_t *s1, const wchar_
184 208
185static void NormalizePrefix(WCHAR *s) 209static void NormalizePrefix(WCHAR *s)
186{ 210{
187 size_t len = wcslen(s); 211 const size_t len = wcslen(s);
188 if (len != 0) 212 if (len != 0)
189 if (s[len - 1] != WCHAR_PATH_SEPARATOR) 213 if (s[len - 1] != WCHAR_PATH_SEPARATOR)
190 { 214 {
@@ -197,7 +221,7 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest)
197{ 221{
198 DWORD cnt = MAX_PATH * sizeof(name[0]); 222 DWORD cnt = MAX_PATH * sizeof(name[0]);
199 DWORD type = 0; 223 DWORD type = 0;
200 LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, (DWORD *)&cnt); 224 const LONG res = RegQueryValueExW(hKey, name, NULL, &type, (LPBYTE)dest, &cnt);
201 if (type != REG_SZ) 225 if (type != REG_SZ)
202 return False; 226 return False;
203 return res == ERROR_SUCCESS; 227 return res == ERROR_SUCCESS;
@@ -206,11 +230,11 @@ static int MyRegistry_QueryString(HKEY hKey, LPCWSTR name, LPWSTR dest)
206static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) 230static int MyRegistry_QueryString2(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest)
207{ 231{
208 HKEY key = 0; 232 HKEY key = 0;
209 LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key); 233 const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag, &key);
210 if (res != ERROR_SUCCESS) 234 if (res != ERROR_SUCCESS)
211 return False; 235 return False;
212 { 236 {
213 BoolInt res2 = MyRegistry_QueryString(key, valName, dest); 237 const BoolInt res2 = MyRegistry_QueryString(key, valName, dest);
214 RegCloseKey(key); 238 RegCloseKey(key);
215 return res2; 239 return res2;
216 } 240 }
@@ -237,11 +261,11 @@ static LONG MyRegistry_DeleteKey(HKEY parentKey, LPCWSTR name)
237static int MyRegistry_QueryString2_32(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest) 261static int MyRegistry_QueryString2_32(HKEY hKey, LPCWSTR keyName, LPCWSTR valName, LPWSTR dest)
238{ 262{
239 HKEY key = 0; 263 HKEY key = 0;
240 LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag_32, &key); 264 const LONG res = RegOpenKeyExW(hKey, keyName, 0, KEY_READ | k_Reg_WOW_Flag_32, &key);
241 if (res != ERROR_SUCCESS) 265 if (res != ERROR_SUCCESS)
242 return False; 266 return False;
243 { 267 {
244 BoolInt res2 = MyRegistry_QueryString(key, valName, dest); 268 const BoolInt res2 = MyRegistry_QueryString(key, valName, dest);
245 RegCloseKey(key); 269 RegCloseKey(key);
246 return res2; 270 return res2;
247 } 271 }
@@ -282,7 +306,7 @@ static void MyReg_DeleteVal_Path_if_Equal(HKEY hKey, LPCWSTR name)
282static void SetRegKey_Path2(HKEY parentKey) 306static void SetRegKey_Path2(HKEY parentKey)
283{ 307{
284 HKEY key = 0; 308 HKEY key = 0;
285 LONG res = MyRegistry_OpenKey_ReadWrite(parentKey, k_Reg_Software_7zip, &key); 309 const LONG res = MyRegistry_OpenKey_ReadWrite(parentKey, k_Reg_Software_7zip, &key);
286 if (res == ERROR_SUCCESS) 310 if (res == ERROR_SUCCESS)
287 { 311 {
288 MyReg_DeleteVal_Path_if_Equal(key, k_Reg_Path32); 312 MyReg_DeleteVal_Path_if_Equal(key, k_Reg_Path32);
@@ -293,7 +317,7 @@ static void SetRegKey_Path2(HKEY parentKey)
293 } 317 }
294} 318}
295 319
296static void SetRegKey_Path() 320static void SetRegKey_Path(void)
297{ 321{
298 SetRegKey_Path2(HKEY_CURRENT_USER); 322 SetRegKey_Path2(HKEY_CURRENT_USER);
299 SetRegKey_Path2(HKEY_LOCAL_MACHINE); 323 SetRegKey_Path2(HKEY_LOCAL_MACHINE);
@@ -426,7 +450,7 @@ static BoolInt AreEqual_Path_PrefixName(const wchar_t *s, const wchar_t *prefix,
426 return AreStringsEqual_NoCase(s + wcslen(prefix), name); 450 return AreStringsEqual_NoCase(s + wcslen(prefix), name);
427} 451}
428 452
429static void WriteCLSID() 453static void WriteCLSID(void)
430{ 454{
431 WCHAR s[MAX_PATH + 30]; 455 WCHAR s[MAX_PATH + 30];
432 456
@@ -435,14 +459,14 @@ static void WriteCLSID()
435 if (AreEqual_Path_PrefixName(s, path, L"7-zip.dll")) 459 if (AreEqual_Path_PrefixName(s, path, L"7-zip.dll"))
436 { 460 {
437 { 461 {
438 LONG res = MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); 462 const LONG res = MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc);
439 if (res == ERROR_SUCCESS) 463 if (res == ERROR_SUCCESS)
440 MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip); 464 MyRegistry_DeleteKey(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip);
441 } 465 }
442 466
443 { 467 {
444 unsigned i; 468 unsigned i;
445 for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) 469 for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++)
446 { 470 {
447 WCHAR destPath[MAX_PATH]; 471 WCHAR destPath[MAX_PATH];
448 CpyAscii(destPath, k_ShellEx_Items[i]); 472 CpyAscii(destPath, k_ShellEx_Items[i]);
@@ -454,7 +478,7 @@ static void WriteCLSID()
454 478
455 { 479 {
456 HKEY destKey = 0; 480 HKEY destKey = 0;
457 LONG res = MyRegistry_OpenKey_ReadWrite(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); 481 const LONG res = MyRegistry_OpenKey_ReadWrite(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey);
458 if (res == ERROR_SUCCESS) 482 if (res == ERROR_SUCCESS)
459 { 483 {
460 RegDeleteValueW(destKey, k_7zip_CLSID); 484 RegDeleteValueW(destKey, k_7zip_CLSID);
@@ -472,14 +496,14 @@ static void WriteCLSID()
472 if (AreEqual_Path_PrefixName(s, path, L"7-zip32.dll")) 496 if (AreEqual_Path_PrefixName(s, path, L"7-zip32.dll"))
473 { 497 {
474 { 498 {
475 LONG res = MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc); 499 const LONG res = MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip_Inproc);
476 if (res == ERROR_SUCCESS) 500 if (res == ERROR_SUCCESS)
477 MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip); 501 MyRegistry_DeleteKey_32(HKEY_CLASSES_ROOT, k_Reg_CLSID_7zip);
478 } 502 }
479 503
480 { 504 {
481 unsigned i; 505 unsigned i;
482 for (i = 0; i < ARRAY_SIZE(k_ShellEx_Items); i++) 506 for (i = 0; i < Z7_ARRAY_SIZE(k_ShellEx_Items); i++)
483 { 507 {
484 WCHAR destPath[MAX_PATH]; 508 WCHAR destPath[MAX_PATH];
485 CpyAscii(destPath, k_ShellEx_Items[i]); 509 CpyAscii(destPath, k_ShellEx_Items[i]);
@@ -491,7 +515,7 @@ static void WriteCLSID()
491 515
492 { 516 {
493 HKEY destKey = 0; 517 HKEY destKey = 0;
494 LONG res = MyRegistry_OpenKey_ReadWrite_32(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey); 518 const LONG res = MyRegistry_OpenKey_ReadWrite_32(HKEY_LOCAL_MACHINE, k_Shell_Approved, &destKey);
495 if (res == ERROR_SUCCESS) 519 if (res == ERROR_SUCCESS)
496 { 520 {
497 RegDeleteValueW(destKey, k_7zip_CLSID); 521 RegDeleteValueW(destKey, k_7zip_CLSID);
@@ -526,7 +550,7 @@ static const wchar_t *GetCmdParam(const wchar_t *s)
526 BoolInt quoteMode = False; 550 BoolInt quoteMode = False;
527 for (;; s++) 551 for (;; s++)
528 { 552 {
529 wchar_t c = *s; 553 const wchar_t c = *s;
530 if (c == 0 || (c == L' ' && !quoteMode)) 554 if (c == 0 || (c == L' ' && !quoteMode))
531 break; 555 break;
532 if (c == L'\"') 556 if (c == L'\"')
@@ -534,7 +558,7 @@ static const wchar_t *GetCmdParam(const wchar_t *s)
534 quoteMode = !quoteMode; 558 quoteMode = !quoteMode;
535 continue; 559 continue;
536 } 560 }
537 if (pos >= ARRAY_SIZE(cmd) - 1) 561 if (pos >= Z7_ARRAY_SIZE(cmd) - 1)
538 exit(1); 562 exit(1);
539 cmd[pos++] = c; 563 cmd[pos++] = c;
540 } 564 }
@@ -558,7 +582,7 @@ static void RemoveQuotes(wchar_t *s)
558} 582}
559*/ 583*/
560 584
561static BoolInt DoesFileOrDirExist() 585static BoolInt DoesFileOrDirExist(void)
562{ 586{
563 return (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES); 587 return (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES);
564} 588}
@@ -573,7 +597,7 @@ static BOOL RemoveFileAfterReboot2(const WCHAR *s)
573 #endif 597 #endif
574} 598}
575 599
576static BOOL RemoveFileAfterReboot() 600static BOOL RemoveFileAfterReboot(void)
577{ 601{
578 return RemoveFileAfterReboot2(path); 602 return RemoveFileAfterReboot2(path);
579} 603}
@@ -584,7 +608,7 @@ static BoolInt IsThereSpace(const wchar_t *s)
584{ 608{
585 for (;;) 609 for (;;)
586 { 610 {
587 wchar_t c = *s++; 611 const wchar_t c = *s++;
588 if (c == 0) 612 if (c == 0)
589 return False; 613 return False;
590 if (c == ' ') 614 if (c == ' ')
@@ -594,7 +618,7 @@ static BoolInt IsThereSpace(const wchar_t *s)
594 618
595static void AddPathParam(wchar_t *dest, const wchar_t *src) 619static void AddPathParam(wchar_t *dest, const wchar_t *src)
596{ 620{
597 BoolInt needQuote = IsThereSpace(src); 621 const BoolInt needQuote = IsThereSpace(src);
598 if (needQuote) 622 if (needQuote)
599 CatAscii(dest, "\""); 623 CatAscii(dest, "\"");
600 wcscat(dest, src); 624 wcscat(dest, src);
@@ -618,9 +642,9 @@ static BoolInt GetErrorMessage(DWORD errorCode, WCHAR *message)
618 return True; 642 return True;
619} 643}
620 644
621static BOOL RemoveDir() 645static BOOL RemoveDir(void)
622{ 646{
623 DWORD attrib = GetFileAttributesW(path); 647 const DWORD attrib = GetFileAttributesW(path);
624 if (attrib == INVALID_FILE_ATTRIBUTES) 648 if (attrib == INVALID_FILE_ATTRIBUTES)
625 return TRUE; 649 return TRUE;
626 if (RemoveDirectoryW(path)) 650 if (RemoveDirectoryW(path))
@@ -670,7 +694,7 @@ static const char * const k_Names =
670 694
671 695
672 696
673static int Install() 697static int Install(void)
674{ 698{
675 SRes res = SZ_OK; 699 SRes res = SZ_OK;
676 WRes winRes = 0; 700 WRes winRes = 0;
@@ -724,7 +748,7 @@ static int Install()
724 748
725 for (;;) 749 for (;;)
726 { 750 {
727 char c = *curName; 751 const char c = *curName;
728 if (c == 0) 752 if (c == 0)
729 break; 753 break;
730 curName++; 754 curName++;
@@ -743,7 +767,7 @@ static int Install()
743 SetWindowTextW(g_InfoLine_HWND, temp); 767 SetWindowTextW(g_InfoLine_HWND, temp);
744 768
745 { 769 {
746 DWORD attrib = GetFileAttributesW(path); 770 const DWORD attrib = GetFileAttributesW(path);
747 if (attrib == INVALID_FILE_ATTRIBUTES) 771 if (attrib == INVALID_FILE_ATTRIBUTES)
748 continue; 772 continue;
749 if (attrib & FILE_ATTRIBUTE_READONLY) 773 if (attrib & FILE_ATTRIBUTE_READONLY)
@@ -803,7 +827,7 @@ static int Install()
803} 827}
804 828
805 829
806static void OnClose() 830static void OnClose(void)
807{ 831{
808 if (g_Install_was_Pressed && !g_Finished) 832 if (g_Install_was_Pressed && !g_Finished)
809 { 833 {
@@ -817,7 +841,13 @@ static void OnClose()
817 g_HWND = NULL; 841 g_HWND = NULL;
818} 842}
819 843
820static INT_PTR CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 844static
845#ifdef Z7_OLD_WIN_SDK
846 BOOL
847#else
848 INT_PTR
849#endif
850CALLBACK MyDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
821{ 851{
822 UNUSED_VAR(lParam) 852 UNUSED_VAR(lParam)
823 853
@@ -905,7 +935,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
905 #endif 935 #endif
906 936
907 #ifndef UNDER_CE 937 #ifndef UNDER_CE
908 func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) 938 func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) MY_CAST_FUNC
909 GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW"); 939 GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW");
910 #endif 940 #endif
911 941
@@ -976,7 +1006,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
976 1006
977 { 1007 {
978 wchar_t *name; 1008 wchar_t *name;
979 DWORD len = GetModuleFileNameW(NULL, modulePath, MAX_PATH); 1009 const DWORD len = GetModuleFileNameW(NULL, modulePath, MAX_PATH);
980 if (len == 0 || len > MAX_PATH) 1010 if (len == 0 || len > MAX_PATH)
981 return 1; 1011 return 1;
982 1012
@@ -987,7 +1017,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
987 wchar_t *s = modulePrefix; 1017 wchar_t *s = modulePrefix;
988 for (;;) 1018 for (;;)
989 { 1019 {
990 wchar_t c = *s++; 1020 const wchar_t c = *s++;
991 if (c == 0) 1021 if (c == 0)
992 break; 1022 break;
993 if (c == WCHAR_PATH_SEPARATOR) 1023 if (c == WCHAR_PATH_SEPARATOR)
@@ -1037,7 +1067,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1037 unsigned k; 1067 unsigned k;
1038 for (k = 0; k < 8; k++) 1068 for (k = 0; k < 8; k++)
1039 { 1069 {
1040 unsigned t = value & 0xF; 1070 const unsigned t = value & 0xF;
1041 value >>= 4; 1071 value >>= 4;
1042 s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10))); 1072 s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
1043 } 1073 }
@@ -1134,7 +1164,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
1134 return 1; 1164 return 1;
1135 1165
1136 { 1166 {
1137 HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); 1167 const HICON hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON));
1138 // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); 1168 // SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
1139 SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); 1169 SendMessage(g_HWND, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
1140 } 1170 }
diff --git a/C/Util/7zipUninstall/7zipUninstall.dsp b/C/Util/7zipUninstall/7zipUninstall.dsp
index cc7b6b6..bb7473f 100644
--- a/C/Util/7zipUninstall/7zipUninstall.dsp
+++ b/C/Util/7zipUninstall/7zipUninstall.dsp
@@ -104,6 +104,14 @@ SOURCE=..\..\7zVersion.h
104# PROP Default_Filter "" 104# PROP Default_Filter ""
105# Begin Source File 105# Begin Source File
106 106
107SOURCE=..\..\7zWindows.h
108# End Source File
109# Begin Source File
110
111SOURCE=..\..\Compiler.h
112# End Source File
113# Begin Source File
114
107SOURCE=.\Precomp.c 115SOURCE=.\Precomp.c
108# ADD CPP /Yc"Precomp.h" 116# ADD CPP /Yc"Precomp.h"
109# End Source File 117# End Source File
diff --git a/C/Util/7zipUninstall/Precomp.h b/C/Util/7zipUninstall/Precomp.h
index 4c90d47..bc8fa21 100644
--- a/C/Util/7zipUninstall/Precomp.h
+++ b/C/Util/7zipUninstall/Precomp.h
@@ -1,11 +1,14 @@
1/* Precomp.h -- StdAfx 1/* Precomp.h -- StdAfx
22015-05-24 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_PRECOMP_H 4#ifndef ZIP7_INC_PRECOMP_H
5#define __7Z_PRECOMP_H 5#define ZIP7_INC_PRECOMP_H
6 6
7#include "../../Compiler.h" 7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
8 10
11#include "../../Compiler.h"
9#include "../../7zTypes.h" 12#include "../../7zTypes.h"
10 13
11#endif 14#endif
diff --git a/C/Util/7zipUninstall/makefile b/C/Util/7zipUninstall/makefile
index 60c2fe2..9d8aafc 100644
--- a/C/Util/7zipUninstall/makefile
+++ b/C/Util/7zipUninstall/makefile
@@ -1,8 +1,8 @@
1PROG = 7zipUninstall.exe 1PROG = 7zipUninstall.exe
2MY_FIXED = 1 2MY_FIXED = 1
3 3
4!IFDEF _64BIT_INSTALLER 4!IFDEF Z7_64BIT_INSTALLER
5CFLAGS = $(CFLAGS) -D_64BIT_INSTALLER 5CFLAGS = $(CFLAGS) -DZ7_64BIT_INSTALLER
6!ENDIF 6!ENDIF
7 7
8MAIN_OBJS = \ 8MAIN_OBJS = \
diff --git a/C/Util/Lzma/LzmaUtil.c b/C/Util/Lzma/LzmaUtil.c
index 62a5907..b9b974b 100644
--- a/C/Util/Lzma/LzmaUtil.c
+++ b/C/Util/Lzma/LzmaUtil.c
@@ -1,7 +1,7 @@
1/* LzmaUtil.c -- Test application for LZMA compression 1/* LzmaUtil.c -- Test application for LZMA compression
22021-11-01 : Igor Pavlov : Public domain */ 22023-03-07 : Igor Pavlov : Public domain */
3 3
4#include "../../Precomp.h" 4#include "Precomp.h"
5 5
6#include <stdio.h> 6#include <stdio.h>
7#include <stdlib.h> 7#include <stdlib.h>
@@ -21,48 +21,80 @@ static const char * const kCantWriteMessage = "Cannot write output file";
21static const char * const kCantAllocateMessage = "Cannot allocate memory"; 21static const char * const kCantAllocateMessage = "Cannot allocate memory";
22static const char * const kDataErrorMessage = "Data error"; 22static const char * const kDataErrorMessage = "Data error";
23 23
24static void PrintHelp(char *buffer) 24static void Print(const char *s)
25{ 25{
26 strcat(buffer, 26 fputs(s, stdout);
27 "\nLZMA-C " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE "\n\n"
28 "Usage: lzma <e|d> inputFile outputFile\n"
29 " e: encode file\n"
30 " d: decode file\n");
31} 27}
32 28
33static int PrintError(char *buffer, const char *message) 29static void PrintHelp(void)
34{ 30{
35 strcat(buffer, "\nError: "); 31 Print(
36 strcat(buffer, message); 32 "\n" "LZMA-C " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE
37 strcat(buffer, "\n"); 33 "\n"
34 "\n" "Usage: lzma <e|d> inputFile outputFile"
35 "\n" " e: encode file"
36 "\n" " d: decode file"
37 "\n");
38}
39
40static int PrintError(const char *message)
41{
42 Print("\nError: ");
43 Print(message);
44 Print("\n");
38 return 1; 45 return 1;
39} 46}
40 47
41static int PrintError_WRes(char *buffer, const char *message, WRes wres) 48#define CONVERT_INT_TO_STR(charType, tempSize) \
49 unsigned char temp[tempSize]; unsigned i = 0; \
50 while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \
51 *s++ = (charType)('0' + (unsigned)val); \
52 while (i != 0) { i--; *s++ = (charType)temp[i]; } \
53 *s = 0; \
54 return s;
55
56static char * Convert_unsigned_To_str(unsigned val, char *s)
42{ 57{
43 strcat(buffer, "\nError: "); 58 CONVERT_INT_TO_STR(char, 32)
44 strcat(buffer, message); 59}
45 sprintf(buffer + strlen(buffer), "\nSystem error code: %d", (unsigned)wres); 60
61static void Print_unsigned(unsigned code)
62{
63 char str[32];
64 Convert_unsigned_To_str(code, str);
65 Print(str);
66}
67
68static int PrintError_WRes(const char *message, WRes wres)
69{
70 PrintError(message);
71 Print("\nSystem error code: ");
72 Print_unsigned((unsigned)wres);
46 #ifndef _WIN32 73 #ifndef _WIN32
47 { 74 {
48 const char *s = strerror(wres); 75 const char *s = strerror(wres);
49 if (s) 76 if (s)
50 sprintf(buffer + strlen(buffer), " : %s", s); 77 {
78 Print(" : ");
79 Print(s);
80 }
51 } 81 }
52 #endif 82 #endif
53 strcat(buffer, "\n"); 83 Print("\n");
54 return 1; 84 return 1;
55} 85}
56 86
57static int PrintErrorNumber(char *buffer, SRes val) 87static int PrintErrorNumber(SRes val)
58{ 88{
59 sprintf(buffer + strlen(buffer), "\n7-Zip error code: %d\n", (unsigned)val); 89 Print("\n7-Zip error code: ");
90 Print_unsigned((unsigned)val);
91 Print("\n");
60 return 1; 92 return 1;
61} 93}
62 94
63static int PrintUserError(char *buffer) 95static int PrintUserError(void)
64{ 96{
65 return PrintError(buffer, "Incorrect command"); 97 return PrintError("Incorrect command");
66} 98}
67 99
68 100
@@ -70,10 +102,10 @@ static int PrintUserError(char *buffer)
70#define OUT_BUF_SIZE (1 << 16) 102#define OUT_BUF_SIZE (1 << 16)
71 103
72 104
73static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream, 105static SRes Decode2(CLzmaDec *state, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream,
74 UInt64 unpackSize) 106 UInt64 unpackSize)
75{ 107{
76 int thereIsSize = (unpackSize != (UInt64)(Int64)-1); 108 const int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
77 Byte inBuf[IN_BUF_SIZE]; 109 Byte inBuf[IN_BUF_SIZE];
78 Byte outBuf[OUT_BUF_SIZE]; 110 Byte outBuf[OUT_BUF_SIZE];
79 size_t inPos = 0, inSize = 0, outPos = 0; 111 size_t inPos = 0, inSize = 0, outPos = 0;
@@ -83,7 +115,7 @@ static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inS
83 if (inPos == inSize) 115 if (inPos == inSize)
84 { 116 {
85 inSize = IN_BUF_SIZE; 117 inSize = IN_BUF_SIZE;
86 RINOK(inStream->Read(inStream, inBuf, &inSize)); 118 RINOK(inStream->Read(inStream, inBuf, &inSize))
87 inPos = 0; 119 inPos = 0;
88 } 120 }
89 { 121 {
@@ -124,7 +156,7 @@ static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inS
124} 156}
125 157
126 158
127static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream) 159static SRes Decode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream)
128{ 160{
129 UInt64 unpackSize; 161 UInt64 unpackSize;
130 int i; 162 int i;
@@ -137,27 +169,29 @@ static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
137 169
138 /* Read and parse header */ 170 /* Read and parse header */
139 171
140 RINOK(SeqInStream_Read(inStream, header, sizeof(header))); 172 {
141 173 size_t size = sizeof(header);
174 RINOK(SeqInStream_ReadMax(inStream, header, &size))
175 if (size != sizeof(header))
176 return SZ_ERROR_INPUT_EOF;
177 }
142 unpackSize = 0; 178 unpackSize = 0;
143 for (i = 0; i < 8; i++) 179 for (i = 0; i < 8; i++)
144 unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8); 180 unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);
145 181
146 LzmaDec_Construct(&state); 182 LzmaDec_CONSTRUCT(&state)
147 RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc)); 183 RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc))
148 res = Decode2(&state, outStream, inStream, unpackSize); 184 res = Decode2(&state, outStream, inStream, unpackSize);
149 LzmaDec_Free(&state, &g_Alloc); 185 LzmaDec_Free(&state, &g_Alloc);
150 return res; 186 return res;
151} 187}
152 188
153static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs) 189static SRes Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, UInt64 fileSize)
154{ 190{
155 CLzmaEncHandle enc; 191 CLzmaEncHandle enc;
156 SRes res; 192 SRes res;
157 CLzmaEncProps props; 193 CLzmaEncProps props;
158 194
159 UNUSED_VAR(rs);
160
161 enc = LzmaEnc_Create(&g_Alloc); 195 enc = LzmaEnc_Create(&g_Alloc);
162 if (enc == 0) 196 if (enc == 0)
163 return SZ_ERROR_MEM; 197 return SZ_ERROR_MEM;
@@ -187,7 +221,7 @@ static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 file
187} 221}
188 222
189 223
190static int main2(int numArgs, const char *args[], char *rs) 224int Z7_CDECL main(int numArgs, const char *args[])
191{ 225{
192 CFileSeqInStream inStream; 226 CFileSeqInStream inStream;
193 CFileOutStream outStream; 227 CFileOutStream outStream;
@@ -208,29 +242,31 @@ static int main2(int numArgs, const char *args[], char *rs)
208 242
209 if (numArgs == 1) 243 if (numArgs == 1)
210 { 244 {
211 PrintHelp(rs); 245 PrintHelp();
212 return 0; 246 return 0;
213 } 247 }
214 248
215 if (numArgs < 3 || numArgs > 4 || strlen(args[1]) != 1) 249 if (numArgs < 3 || numArgs > 4 || strlen(args[1]) != 1)
216 return PrintUserError(rs); 250 return PrintUserError();
217 251
218 c = args[1][0]; 252 c = args[1][0];
219 encodeMode = (c == 'e' || c == 'E'); 253 encodeMode = (c == 'e' || c == 'E');
220 if (!encodeMode && c != 'd' && c != 'D') 254 if (!encodeMode && c != 'd' && c != 'D')
221 return PrintUserError(rs); 255 return PrintUserError();
222 256
257 /*
223 { 258 {
224 size_t t4 = sizeof(UInt32); 259 size_t t4 = sizeof(UInt32);
225 size_t t8 = sizeof(UInt64); 260 size_t t8 = sizeof(UInt64);
226 if (t4 != 4 || t8 != 8) 261 if (t4 != 4 || t8 != 8)
227 return PrintError(rs, "Incorrect UInt32 or UInt64"); 262 return PrintError("Incorrect UInt32 or UInt64");
228 } 263 }
264 */
229 265
230 { 266 {
231 WRes wres = InFile_Open(&inStream.file, args[2]); 267 const WRes wres = InFile_Open(&inStream.file, args[2]);
232 if (wres != 0) 268 if (wres != 0)
233 return PrintError_WRes(rs, "Cannot open input file", wres); 269 return PrintError_WRes("Cannot open input file", wres);
234 } 270 }
235 271
236 if (numArgs > 3) 272 if (numArgs > 3)
@@ -239,18 +275,18 @@ static int main2(int numArgs, const char *args[], char *rs)
239 useOutFile = True; 275 useOutFile = True;
240 wres = OutFile_Open(&outStream.file, args[3]); 276 wres = OutFile_Open(&outStream.file, args[3]);
241 if (wres != 0) 277 if (wres != 0)
242 return PrintError_WRes(rs, "Cannot open output file", wres); 278 return PrintError_WRes("Cannot open output file", wres);
243 } 279 }
244 else if (encodeMode) 280 else if (encodeMode)
245 PrintUserError(rs); 281 PrintUserError();
246 282
247 if (encodeMode) 283 if (encodeMode)
248 { 284 {
249 UInt64 fileSize; 285 UInt64 fileSize;
250 WRes wres = File_GetLength(&inStream.file, &fileSize); 286 const WRes wres = File_GetLength(&inStream.file, &fileSize);
251 if (wres != 0) 287 if (wres != 0)
252 return PrintError_WRes(rs, "Cannot get file length", wres); 288 return PrintError_WRes("Cannot get file length", wres);
253 res = Encode(&outStream.vt, &inStream.vt, fileSize, rs); 289 res = Encode(&outStream.vt, &inStream.vt, fileSize);
254 } 290 }
255 else 291 else
256 { 292 {
@@ -264,23 +300,14 @@ static int main2(int numArgs, const char *args[], char *rs)
264 if (res != SZ_OK) 300 if (res != SZ_OK)
265 { 301 {
266 if (res == SZ_ERROR_MEM) 302 if (res == SZ_ERROR_MEM)
267 return PrintError(rs, kCantAllocateMessage); 303 return PrintError(kCantAllocateMessage);
268 else if (res == SZ_ERROR_DATA) 304 else if (res == SZ_ERROR_DATA)
269 return PrintError(rs, kDataErrorMessage); 305 return PrintError(kDataErrorMessage);
270 else if (res == SZ_ERROR_WRITE) 306 else if (res == SZ_ERROR_WRITE)
271 return PrintError_WRes(rs, kCantWriteMessage, outStream.wres); 307 return PrintError_WRes(kCantWriteMessage, outStream.wres);
272 else if (res == SZ_ERROR_READ) 308 else if (res == SZ_ERROR_READ)
273 return PrintError_WRes(rs, kCantReadMessage, inStream.wres); 309 return PrintError_WRes(kCantReadMessage, inStream.wres);
274 return PrintErrorNumber(rs, res); 310 return PrintErrorNumber(res);
275 } 311 }
276 return 0; 312 return 0;
277} 313}
278
279
280int MY_CDECL main(int numArgs, const char *args[])
281{
282 char rs[1000] = { 0 };
283 int res = main2(numArgs, args, rs);
284 fputs(rs, stdout);
285 return res;
286}
diff --git a/C/Util/Lzma/LzmaUtil.dsp b/C/Util/Lzma/LzmaUtil.dsp
index 4e38e4a..e2e7d42 100644
--- a/C/Util/Lzma/LzmaUtil.dsp
+++ b/C/Util/Lzma/LzmaUtil.dsp
@@ -106,6 +106,10 @@ SOURCE=..\..\7zVersion.h
106# End Source File 106# End Source File
107# Begin Source File 107# Begin Source File
108 108
109SOURCE=..\..\7zWindows.h
110# End Source File
111# Begin Source File
112
109SOURCE=..\..\Alloc.c 113SOURCE=..\..\Alloc.c
110# End Source File 114# End Source File
111# Begin Source File 115# Begin Source File
@@ -114,6 +118,10 @@ SOURCE=..\..\Alloc.h
114# End Source File 118# End Source File
115# Begin Source File 119# Begin Source File
116 120
121SOURCE=..\..\Compiler.h
122# End Source File
123# Begin Source File
124
117SOURCE=..\..\CpuArch.h 125SOURCE=..\..\CpuArch.h
118# End Source File 126# End Source File
119# Begin Source File 127# Begin Source File
@@ -162,6 +170,14 @@ SOURCE=.\LzmaUtil.c
162# End Source File 170# End Source File
163# Begin Source File 171# Begin Source File
164 172
173SOURCE=..\..\Precomp.h
174# End Source File
175# Begin Source File
176
177SOURCE=.\Precomp.h
178# End Source File
179# Begin Source File
180
165SOURCE=..\..\Threads.c 181SOURCE=..\..\Threads.c
166# End Source File 182# End Source File
167# Begin Source File 183# Begin Source File
diff --git a/C/Util/Lzma/Precomp.h b/C/Util/Lzma/Precomp.h
new file mode 100644
index 0000000..bc8fa21
--- /dev/null
+++ b/C/Util/Lzma/Precomp.h
@@ -0,0 +1,14 @@
1/* Precomp.h -- StdAfx
22023-03-04 : Igor Pavlov : Public domain */
3
4#ifndef ZIP7_INC_PRECOMP_H
5#define ZIP7_INC_PRECOMP_H
6
7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
10
11#include "../../Compiler.h"
12#include "../../7zTypes.h"
13
14#endif
diff --git a/C/Util/LzmaLib/LzmaLib.dsp b/C/Util/LzmaLib/LzmaLib.dsp
index 6ce91dc..bacd967 100644
--- a/C/Util/LzmaLib/LzmaLib.dsp
+++ b/C/Util/LzmaLib/LzmaLib.dsp
@@ -101,6 +101,10 @@ SOURCE=.\LzmaLib.def
101 101
102SOURCE=.\LzmaLibExports.c 102SOURCE=.\LzmaLibExports.c
103# End Source File 103# End Source File
104# Begin Source File
105
106SOURCE=.\Precomp.h
107# End Source File
104# End Group 108# End Group
105# Begin Source File 109# Begin Source File
106 110
@@ -108,6 +112,10 @@ SOURCE=..\..\7zTypes.h
108# End Source File 112# End Source File
109# Begin Source File 113# Begin Source File
110 114
115SOURCE=..\..\7zWindows.h
116# End Source File
117# Begin Source File
118
111SOURCE=..\..\Alloc.c 119SOURCE=..\..\Alloc.c
112# End Source File 120# End Source File
113# Begin Source File 121# Begin Source File
@@ -116,6 +124,14 @@ SOURCE=..\..\Alloc.h
116# End Source File 124# End Source File
117# Begin Source File 125# Begin Source File
118 126
127SOURCE=..\..\Compiler.h
128# End Source File
129# Begin Source File
130
131SOURCE=..\..\CpuArch.h
132# End Source File
133# Begin Source File
134
119SOURCE=..\..\IStream.h 135SOURCE=..\..\IStream.h
120# End Source File 136# End Source File
121# Begin Source File 137# Begin Source File
@@ -168,6 +184,10 @@ SOURCE=..\..\LzmaLib.h
168# End Source File 184# End Source File
169# Begin Source File 185# Begin Source File
170 186
187SOURCE=..\..\Precomp.h
188# End Source File
189# Begin Source File
190
171SOURCE=.\resource.rc 191SOURCE=.\resource.rc
172# End Source File 192# End Source File
173# Begin Source File 193# Begin Source File
diff --git a/C/Util/LzmaLib/LzmaLibExports.c b/C/Util/LzmaLib/LzmaLibExports.c
index 4a28a9a..a46c9a8 100644
--- a/C/Util/LzmaLib/LzmaLibExports.c
+++ b/C/Util/LzmaLib/LzmaLibExports.c
@@ -1,14 +1,15 @@
1/* LzmaLibExports.c -- LZMA library DLL Entry point 1/* LzmaLibExports.c -- LZMA library DLL Entry point
22015-11-08 : Igor Pavlov : Public domain */ 22023-03-05 : Igor Pavlov : Public domain */
3 3
4#include "../../Precomp.h" 4#include "Precomp.h"
5 5
6#include <windows.h> 6#include "../../7zWindows.h"
7 7
8BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved);
8BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) 9BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
9{ 10{
10 UNUSED_VAR(hInstance); 11 UNUSED_VAR(hInstance)
11 UNUSED_VAR(dwReason); 12 UNUSED_VAR(dwReason)
12 UNUSED_VAR(lpReserved); 13 UNUSED_VAR(lpReserved)
13 return TRUE; 14 return TRUE;
14} 15}
diff --git a/C/Util/LzmaLib/Precomp.c b/C/Util/LzmaLib/Precomp.c
new file mode 100644
index 0000000..01605e3
--- /dev/null
+++ b/C/Util/LzmaLib/Precomp.c
@@ -0,0 +1,4 @@
1/* Precomp.c -- StdAfx
22013-01-21 : Igor Pavlov : Public domain */
3
4#include "Precomp.h"
diff --git a/C/Util/LzmaLib/Precomp.h b/C/Util/LzmaLib/Precomp.h
new file mode 100644
index 0000000..bc8fa21
--- /dev/null
+++ b/C/Util/LzmaLib/Precomp.h
@@ -0,0 +1,14 @@
1/* Precomp.h -- StdAfx
22023-03-04 : Igor Pavlov : Public domain */
3
4#ifndef ZIP7_INC_PRECOMP_H
5#define ZIP7_INC_PRECOMP_H
6
7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
10
11#include "../../Compiler.h"
12#include "../../7zTypes.h"
13
14#endif
diff --git a/C/Util/LzmaLib/makefile b/C/Util/LzmaLib/makefile
index b36f1de..b8e054e 100644
--- a/C/Util/LzmaLib/makefile
+++ b/C/Util/LzmaLib/makefile
@@ -21,6 +21,7 @@ C_OBJS = \
21 $O\Threads.obj \ 21 $O\Threads.obj \
22 22
23OBJS = \ 23OBJS = \
24 $O\Precomp.obj \
24 $(LIB_OBJS) \ 25 $(LIB_OBJS) \
25 $(C_OBJS) \ 26 $(C_OBJS) \
26 $O\resource.res 27 $O\resource.res
@@ -30,7 +31,24 @@ OBJS = \
30$(SLIBPATH): $O $(OBJS) 31$(SLIBPATH): $O $(OBJS)
31 lib -out:$(SLIBPATH) $(OBJS) $(LIBS) 32 lib -out:$(SLIBPATH) $(OBJS) $(LIBS)
32 33
34
35MAK_SINGLE_FILE = 1
36
37$O\Precomp.obj: Precomp.c
38 $(CCOMPL_PCH)
39
40!IFDEF MAK_SINGLE_FILE
41
33$(LIB_OBJS): $(*B).c 42$(LIB_OBJS): $(*B).c
34 $(COMPL_O2) 43 $(CCOMPL_USE)
35$(C_OBJS): ../../$(*B).c 44$(C_OBJS): ../../$(*B).c
36 $(COMPL_O2) 45 $(CCOMPL_USE)
46
47!ELSE
48
49{.}.c{$O}.obj::
50 $(CCOMPLB_USE)
51{../../../C}.c{$O}.obj::
52 $(CCOMPLB_USE)
53
54!ENDIF
diff --git a/C/Util/SfxSetup/Precomp.h b/C/Util/SfxSetup/Precomp.h
index 588a66f..bc8fa21 100644
--- a/C/Util/SfxSetup/Precomp.h
+++ b/C/Util/SfxSetup/Precomp.h
@@ -1,8 +1,12 @@
1/* Precomp.h -- StdAfx 1/* Precomp.h -- StdAfx
22013-06-16 : Igor Pavlov : Public domain */ 22023-03-04 : Igor Pavlov : Public domain */
3 3
4#ifndef __7Z_PRECOMP_H 4#ifndef ZIP7_INC_PRECOMP_H
5#define __7Z_PRECOMP_H 5#define ZIP7_INC_PRECOMP_H
6
7#if defined(_MSC_VER) && _MSC_VER >= 1800
8#pragma warning(disable : 4464) // relative include path contains '..'
9#endif
6 10
7#include "../../Compiler.h" 11#include "../../Compiler.h"
8#include "../../7zTypes.h" 12#include "../../7zTypes.h"
diff --git a/C/Util/SfxSetup/SfxSetup.c b/C/Util/SfxSetup/SfxSetup.c
index ef19aea..7304a0b 100644
--- a/C/Util/SfxSetup/SfxSetup.c
+++ b/C/Util/SfxSetup/SfxSetup.c
@@ -26,6 +26,12 @@
26 26
27#define kInputBufSize ((size_t)1 << 18) 27#define kInputBufSize ((size_t)1 << 18)
28 28
29
30#define wcscat lstrcatW
31#define wcslen (size_t)lstrlenW
32#define wcscpy lstrcpyW
33// wcsncpy() and lstrcpynW() work differently. We don't use them.
34
29static const char * const kExts[] = 35static const char * const kExts[] =
30{ 36{
31 "bat" 37 "bat"
@@ -64,7 +70,7 @@ static unsigned FindExt(const wchar_t *s, unsigned *extLen)
64 return len; 70 return len;
65} 71}
66 72
67#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) -= 0x20 : (c))) 73#define MAKE_CHAR_UPPER(c) ((((c) >= 'a' && (c) <= 'z') ? (c) - 0x20 : (c)))
68 74
69static unsigned FindItem(const char * const *items, unsigned num, const wchar_t *s, unsigned len) 75static unsigned FindItem(const char * const *items, unsigned num, const wchar_t *s, unsigned len)
70{ 76{
@@ -72,13 +78,13 @@ static unsigned FindItem(const char * const *items, unsigned num, const wchar_t
72 for (i = 0; i < num; i++) 78 for (i = 0; i < num; i++)
73 { 79 {
74 const char *item = items[i]; 80 const char *item = items[i];
75 unsigned itemLen = (unsigned)strlen(item); 81 const unsigned itemLen = (unsigned)strlen(item);
76 unsigned j; 82 unsigned j;
77 if (len != itemLen) 83 if (len != itemLen)
78 continue; 84 continue;
79 for (j = 0; j < len; j++) 85 for (j = 0; j < len; j++)
80 { 86 {
81 unsigned c = (Byte)item[j]; 87 const unsigned c = (Byte)item[j];
82 if (c != s[j] && MAKE_CHAR_UPPER(c) != s[j]) 88 if (c != s[j] && MAKE_CHAR_UPPER(c) != s[j])
83 break; 89 break;
84 } 90 }
@@ -96,10 +102,20 @@ static BOOL WINAPI HandlerRoutine(DWORD ctrlType)
96} 102}
97#endif 103#endif
98 104
105
106#ifdef _CONSOLE
107static void PrintStr(const char *s)
108{
109 fputs(s, stdout);
110}
111#endif
112
99static void PrintErrorMessage(const char *message) 113static void PrintErrorMessage(const char *message)
100{ 114{
101 #ifdef _CONSOLE 115 #ifdef _CONSOLE
102 printf("\n7-Zip Error: %s\n", message); 116 PrintStr("\n7-Zip Error: ");
117 PrintStr(message);
118 PrintStr("\n");
103 #else 119 #else
104 #ifdef UNDER_CE 120 #ifdef UNDER_CE
105 WCHAR messageW[256 + 4]; 121 WCHAR messageW[256 + 4];
@@ -179,7 +195,7 @@ static WRes RemoveDirWithSubItems(WCHAR *path)
179 WIN32_FIND_DATAW fd; 195 WIN32_FIND_DATAW fd;
180 HANDLE handle; 196 HANDLE handle;
181 WRes res = 0; 197 WRes res = 0;
182 size_t len = wcslen(path); 198 const size_t len = wcslen(path);
183 wcscpy(path + len, L"*"); 199 wcscpy(path + len, L"*");
184 handle = FindFirstFileW(path, &fd); 200 handle = FindFirstFileW(path, &fd);
185 path[len] = L'\0'; 201 path[len] = L'\0';
@@ -228,7 +244,7 @@ static WRes RemoveDirWithSubItems(WCHAR *path)
228} 244}
229 245
230#ifdef _CONSOLE 246#ifdef _CONSOLE
231int MY_CDECL main() 247int Z7_CDECL main(void)
232#else 248#else
233int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 249int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
234 #ifdef UNDER_CE 250 #ifdef UNDER_CE
@@ -290,7 +306,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
290 BoolInt quoteMode = False; 306 BoolInt quoteMode = False;
291 for (;; cmdLineParams++) 307 for (;; cmdLineParams++)
292 { 308 {
293 wchar_t c = *cmdLineParams; 309 const wchar_t c = *cmdLineParams;
294 if (c == L'\"') 310 if (c == L'\"')
295 quoteMode = !quoteMode; 311 quoteMode = !quoteMode;
296 else if (c == 0 || (c == L' ' && !quoteMode)) 312 else if (c == 0 || (c == L' ' && !quoteMode))
@@ -324,7 +340,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
324 unsigned k; 340 unsigned k;
325 for (k = 0; k < 8; k++) 341 for (k = 0; k < 8; k++)
326 { 342 {
327 unsigned t = value & 0xF; 343 const unsigned t = value & 0xF;
328 value >>= 4; 344 value >>= 4;
329 s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10))); 345 s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
330 } 346 }
@@ -386,7 +402,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
386 { 402 {
387 lookStream.bufSize = kInputBufSize; 403 lookStream.bufSize = kInputBufSize;
388 lookStream.realStream = &archiveStream.vt; 404 lookStream.realStream = &archiveStream.vt;
389 LookToRead2_Init(&lookStream); 405 LookToRead2_INIT(&lookStream)
390 } 406 }
391 } 407 }
392 408
@@ -455,11 +471,11 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
455 unsigned extLen; 471 unsigned extLen;
456 const WCHAR *name = temp + nameStartPos; 472 const WCHAR *name = temp + nameStartPos;
457 unsigned len = (unsigned)wcslen(name); 473 unsigned len = (unsigned)wcslen(name);
458 unsigned nameLen = FindExt(temp + nameStartPos, &extLen); 474 const unsigned nameLen = FindExt(temp + nameStartPos, &extLen);
459 unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen); 475 const unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen);
460 unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen); 476 const unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen);
461 477
462 unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12)); 478 const unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12));
463 if (minPrice > price) 479 if (minPrice > price)
464 { 480 {
465 minPrice = price; 481 minPrice = price;
@@ -500,7 +516,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
500 #endif 516 #endif
501 517
502 { 518 {
503 SRes res2 = File_Close(&outFile); 519 const SRes res2 = File_Close(&outFile);
504 if (res != SZ_OK) 520 if (res != SZ_OK)
505 break; 521 break;
506 if (res2 != SZ_OK) 522 if (res2 != SZ_OK)
@@ -550,7 +566,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
550 WCHAR oldCurDir[MAX_PATH + 2]; 566 WCHAR oldCurDir[MAX_PATH + 2];
551 oldCurDir[0] = 0; 567 oldCurDir[0] = 0;
552 { 568 {
553 DWORD needLen = GetCurrentDirectory(MAX_PATH + 1, oldCurDir); 569 const DWORD needLen = GetCurrentDirectory(MAX_PATH + 1, oldCurDir);
554 if (needLen == 0 || needLen > MAX_PATH) 570 if (needLen == 0 || needLen > MAX_PATH)
555 oldCurDir[0] = 0; 571 oldCurDir[0] = 0;
556 SetCurrentDirectory(workCurDir); 572 SetCurrentDirectory(workCurDir);
diff --git a/C/Util/SfxSetup/makefile b/C/Util/SfxSetup/makefile
index 544da67..bc0cf8b 100644
--- a/C/Util/SfxSetup/makefile
+++ b/C/Util/SfxSetup/makefile
@@ -1,6 +1,9 @@
1PROG = 7zS2.sfx 1PROG = 7zS2.sfx
2MY_FIXED = 1 2MY_FIXED = 1
3 3
4CFLAGS = $(CFLAGS) \
5 -DZ7_EXTRACT_ONLY \
6
4C_OBJS = \ 7C_OBJS = \
5 $O\7zAlloc.obj \ 8 $O\7zAlloc.obj \
6 $O\7zArcIn.obj \ 9 $O\7zArcIn.obj \
diff --git a/C/Util/SfxSetup/makefile_con b/C/Util/SfxSetup/makefile_con
index d0f8352..9f4b916 100644
--- a/C/Util/SfxSetup/makefile_con
+++ b/C/Util/SfxSetup/makefile_con
@@ -1,6 +1,8 @@
1PROG = 7zS2con.sfx 1PROG = 7zS2con.sfx
2MY_FIXED = 1 2MY_FIXED = 1
3CFLAGS = $(CFLAGS) -D_CONSOLE 3
4CFLAGS = $(CFLAGS) -D_CONSOLE \
5 -DZ7_EXTRACT_ONLY \
4 6
5C_OBJS = \ 7C_OBJS = \
6 $O\7zAlloc.obj \ 8 $O\7zAlloc.obj \
diff --git a/C/Xz.c b/C/Xz.c
index 7c53b60..4ad0710 100644
--- a/C/Xz.c
+++ b/C/Xz.c
@@ -1,5 +1,5 @@
1/* Xz.c - Xz 1/* Xz.c - Xz
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -70,7 +70,7 @@ int XzCheck_Final(CXzCheck *p, Byte *digest)
70 switch (p->mode) 70 switch (p->mode)
71 { 71 {
72 case XZ_CHECK_CRC32: 72 case XZ_CHECK_CRC32:
73 SetUi32(digest, CRC_GET_DIGEST(p->crc)); 73 SetUi32(digest, CRC_GET_DIGEST(p->crc))
74 break; 74 break;
75 case XZ_CHECK_CRC64: 75 case XZ_CHECK_CRC64:
76 { 76 {
diff --git a/C/Xz.h b/C/Xz.h
index 849b944..d5001f6 100644
--- a/C/Xz.h
+++ b/C/Xz.h
@@ -1,21 +1,23 @@
1/* Xz.h - Xz interface 1/* Xz.h - Xz interface
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __XZ_H 4#ifndef ZIP7_INC_XZ_H
5#define __XZ_H 5#define ZIP7_INC_XZ_H
6 6
7#include "Sha256.h" 7#include "Sha256.h"
8#include "Delta.h"
8 9
9EXTERN_C_BEGIN 10EXTERN_C_BEGIN
10 11
11#define XZ_ID_Subblock 1 12#define XZ_ID_Subblock 1
12#define XZ_ID_Delta 3 13#define XZ_ID_Delta 3
13#define XZ_ID_X86 4 14#define XZ_ID_X86 4
14#define XZ_ID_PPC 5 15#define XZ_ID_PPC 5
15#define XZ_ID_IA64 6 16#define XZ_ID_IA64 6
16#define XZ_ID_ARM 7 17#define XZ_ID_ARM 7
17#define XZ_ID_ARMT 8 18#define XZ_ID_ARMT 8
18#define XZ_ID_SPARC 9 19#define XZ_ID_SPARC 9
20#define XZ_ID_ARM64 0xa
19#define XZ_ID_LZMA2 0x21 21#define XZ_ID_LZMA2 0x21
20 22
21unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value); 23unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value);
@@ -53,7 +55,7 @@ typedef struct
53#define XzBlock_HasUnsupportedFlags(p) (((p)->flags & ~(XZ_BF_NUM_FILTERS_MASK | XZ_BF_PACK_SIZE | XZ_BF_UNPACK_SIZE)) != 0) 55#define XzBlock_HasUnsupportedFlags(p) (((p)->flags & ~(XZ_BF_NUM_FILTERS_MASK | XZ_BF_PACK_SIZE | XZ_BF_UNPACK_SIZE)) != 0)
54 56
55SRes XzBlock_Parse(CXzBlock *p, const Byte *header); 57SRes XzBlock_Parse(CXzBlock *p, const Byte *header);
56SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes); 58SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes);
57 59
58/* ---------- xz stream ---------- */ 60/* ---------- xz stream ---------- */
59 61
@@ -101,7 +103,7 @@ typedef UInt16 CXzStreamFlags;
101unsigned XzFlags_GetCheckSize(CXzStreamFlags f); 103unsigned XzFlags_GetCheckSize(CXzStreamFlags f);
102 104
103SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf); 105SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf);
104SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream); 106SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream);
105 107
106typedef struct 108typedef struct
107{ 109{
@@ -112,6 +114,7 @@ typedef struct
112typedef struct 114typedef struct
113{ 115{
114 CXzStreamFlags flags; 116 CXzStreamFlags flags;
117 // Byte _pad[6];
115 size_t numBlocks; 118 size_t numBlocks;
116 CXzBlockSizes *blocks; 119 CXzBlockSizes *blocks;
117 UInt64 startOffset; 120 UInt64 startOffset;
@@ -134,7 +137,7 @@ typedef struct
134 137
135void Xzs_Construct(CXzs *p); 138void Xzs_Construct(CXzs *p);
136void Xzs_Free(CXzs *p, ISzAllocPtr alloc); 139void Xzs_Free(CXzs *p, ISzAllocPtr alloc);
137SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc); 140SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr inStream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc);
138 141
139UInt64 Xzs_GetNumBlocks(const CXzs *p); 142UInt64 Xzs_GetNumBlocks(const CXzs *p);
140UInt64 Xzs_GetUnpackSize(const CXzs *p); 143UInt64 Xzs_GetUnpackSize(const CXzs *p);
@@ -160,9 +163,9 @@ typedef enum
160} ECoderFinishMode; 163} ECoderFinishMode;
161 164
162 165
163typedef struct _IStateCoder 166typedef struct
164{ 167{
165 void *p; 168 void *p; // state object;
166 void (*Free)(void *p, ISzAllocPtr alloc); 169 void (*Free)(void *p, ISzAllocPtr alloc);
167 SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAllocPtr alloc); 170 SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAllocPtr alloc);
168 void (*Init)(void *p); 171 void (*Init)(void *p);
@@ -174,6 +177,20 @@ typedef struct _IStateCoder
174} IStateCoder; 177} IStateCoder;
175 178
176 179
180typedef struct
181{
182 UInt32 methodId;
183 UInt32 delta;
184 UInt32 ip;
185 UInt32 X86_State;
186 Byte delta_State[DELTA_STATE_SIZE];
187} CXzBcFilterStateBase;
188
189typedef SizeT (*Xz_Func_BcFilterStateBase_Filter)(CXzBcFilterStateBase *p, Byte *data, SizeT size);
190
191SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id,
192 Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc);
193
177 194
178#define MIXCODER_NUM_FILTERS_MAX 4 195#define MIXCODER_NUM_FILTERS_MAX 4
179 196
@@ -422,7 +439,7 @@ typedef struct
422 size_t outStep_ST; // size of output buffer for Single-Thread decoding 439 size_t outStep_ST; // size of output buffer for Single-Thread decoding
423 BoolInt ignoreErrors; // if set to 1, the decoder can ignore some errors and it skips broken parts of data. 440 BoolInt ignoreErrors; // if set to 1, the decoder can ignore some errors and it skips broken parts of data.
424 441
425 #ifndef _7ZIP_ST 442 #ifndef Z7_ST
426 unsigned numThreads; // the number of threads for Multi-Thread decoding. if (umThreads == 1) it will use Single-thread decoding 443 unsigned numThreads; // the number of threads for Multi-Thread decoding. if (umThreads == 1) it will use Single-thread decoding
427 size_t inBufSize_MT; // size of small input data buffers for Multi-Thread decoding. Big number of such small buffers can be created 444 size_t inBufSize_MT; // size of small input data buffers for Multi-Thread decoding. Big number of such small buffers can be created
428 size_t memUseMax; // the limit of total memory usage for Multi-Thread decoding. 445 size_t memUseMax; // the limit of total memory usage for Multi-Thread decoding.
@@ -432,8 +449,9 @@ typedef struct
432 449
433void XzDecMtProps_Init(CXzDecMtProps *p); 450void XzDecMtProps_Init(CXzDecMtProps *p);
434 451
435 452typedef struct CXzDecMt CXzDecMt;
436typedef void * CXzDecMtHandle; 453typedef CXzDecMt * CXzDecMtHandle;
454// Z7_DECLARE_HANDLE(CXzDecMtHandle)
437 455
438/* 456/*
439 alloc : XzDecMt uses CAlignOffsetAlloc internally for addresses allocated by (alloc). 457 alloc : XzDecMt uses CAlignOffsetAlloc internally for addresses allocated by (alloc).
@@ -503,14 +521,14 @@ SRes XzDecMt_Decode(CXzDecMtHandle p,
503 const CXzDecMtProps *props, 521 const CXzDecMtProps *props,
504 const UInt64 *outDataSize, // NULL means undefined 522 const UInt64 *outDataSize, // NULL means undefined
505 int finishMode, // 0 - partial unpacking is allowed, 1 - xz stream(s) must be finished 523 int finishMode, // 0 - partial unpacking is allowed, 1 - xz stream(s) must be finished
506 ISeqOutStream *outStream, 524 ISeqOutStreamPtr outStream,
507 // Byte *outBuf, size_t *outBufSize, 525 // Byte *outBuf, size_t *outBufSize,
508 ISeqInStream *inStream, 526 ISeqInStreamPtr inStream,
509 // const Byte *inData, size_t inDataSize, 527 // const Byte *inData, size_t inDataSize,
510 CXzStatInfo *stat, // out: decoding results and statistics 528 CXzStatInfo *stat, // out: decoding results and statistics
511 int *isMT, // out: 0 means that ST (Single-Thread) version was used 529 int *isMT, // out: 0 means that ST (Single-Thread) version was used
512 // 1 means that MT (Multi-Thread) version was used 530 // 1 means that MT (Multi-Thread) version was used
513 ICompressProgress *progress); 531 ICompressProgressPtr progress);
514 532
515EXTERN_C_END 533EXTERN_C_END
516 534
diff --git a/C/XzCrc64.c b/C/XzCrc64.c
index b6d02cb..c2fad6c 100644
--- a/C/XzCrc64.c
+++ b/C/XzCrc64.c
@@ -1,5 +1,5 @@
1/* XzCrc64.c -- CRC64 calculation 1/* XzCrc64.c -- CRC64 calculation
22017-05-23 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -12,39 +12,30 @@
12 #define CRC64_NUM_TABLES 4 12 #define CRC64_NUM_TABLES 4
13#else 13#else
14 #define CRC64_NUM_TABLES 5 14 #define CRC64_NUM_TABLES 5
15 #define CRC_UINT64_SWAP(v) \
16 ((v >> 56) \
17 | ((v >> 40) & ((UInt64)0xFF << 8)) \
18 | ((v >> 24) & ((UInt64)0xFF << 16)) \
19 | ((v >> 8) & ((UInt64)0xFF << 24)) \
20 | ((v << 8) & ((UInt64)0xFF << 32)) \
21 | ((v << 24) & ((UInt64)0xFF << 40)) \
22 | ((v << 40) & ((UInt64)0xFF << 48)) \
23 | ((v << 56)))
24 15
25 UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); 16 UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table);
26#endif 17#endif
27 18
28#ifndef MY_CPU_BE 19#ifndef MY_CPU_BE
29 UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); 20 UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table);
30#endif 21#endif
31 22
32typedef UInt64 (MY_FAST_CALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table); 23typedef UInt64 (Z7_FASTCALL *CRC64_FUNC)(UInt64 v, const void *data, size_t size, const UInt64 *table);
33 24
34static CRC64_FUNC g_Crc64Update; 25static CRC64_FUNC g_Crc64Update;
35UInt64 g_Crc64Table[256 * CRC64_NUM_TABLES]; 26UInt64 g_Crc64Table[256 * CRC64_NUM_TABLES];
36 27
37UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size) 28UInt64 Z7_FASTCALL Crc64Update(UInt64 v, const void *data, size_t size)
38{ 29{
39 return g_Crc64Update(v, data, size, g_Crc64Table); 30 return g_Crc64Update(v, data, size, g_Crc64Table);
40} 31}
41 32
42UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size) 33UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size)
43{ 34{
44 return g_Crc64Update(CRC64_INIT_VAL, data, size, g_Crc64Table) ^ CRC64_INIT_VAL; 35 return g_Crc64Update(CRC64_INIT_VAL, data, size, g_Crc64Table) ^ CRC64_INIT_VAL;
45} 36}
46 37
47void MY_FAST_CALL Crc64GenerateTable() 38void Z7_FASTCALL Crc64GenerateTable(void)
48{ 39{
49 UInt32 i; 40 UInt32 i;
50 for (i = 0; i < 256; i++) 41 for (i = 0; i < 256; i++)
@@ -57,7 +48,7 @@ void MY_FAST_CALL Crc64GenerateTable()
57 } 48 }
58 for (i = 256; i < 256 * CRC64_NUM_TABLES; i++) 49 for (i = 256; i < 256 * CRC64_NUM_TABLES; i++)
59 { 50 {
60 UInt64 r = g_Crc64Table[(size_t)i - 256]; 51 const UInt64 r = g_Crc64Table[(size_t)i - 256];
61 g_Crc64Table[i] = g_Crc64Table[r & 0xFF] ^ (r >> 8); 52 g_Crc64Table[i] = g_Crc64Table[r & 0xFF] ^ (r >> 8);
62 } 53 }
63 54
@@ -76,11 +67,14 @@ void MY_FAST_CALL Crc64GenerateTable()
76 { 67 {
77 for (i = 256 * CRC64_NUM_TABLES - 1; i >= 256; i--) 68 for (i = 256 * CRC64_NUM_TABLES - 1; i >= 256; i--)
78 { 69 {
79 UInt64 x = g_Crc64Table[(size_t)i - 256]; 70 const UInt64 x = g_Crc64Table[(size_t)i - 256];
80 g_Crc64Table[i] = CRC_UINT64_SWAP(x); 71 g_Crc64Table[i] = Z7_BSWAP64(x);
81 } 72 }
82 g_Crc64Update = XzCrc64UpdateT1_BeT4; 73 g_Crc64Update = XzCrc64UpdateT1_BeT4;
83 } 74 }
84 } 75 }
85 #endif 76 #endif
86} 77}
78
79#undef kCrc64Poly
80#undef CRC64_NUM_TABLES
diff --git a/C/XzCrc64.h b/C/XzCrc64.h
index 08dbc33..ca46869 100644
--- a/C/XzCrc64.h
+++ b/C/XzCrc64.h
@@ -1,8 +1,8 @@
1/* XzCrc64.h -- CRC64 calculation 1/* XzCrc64.h -- CRC64 calculation
22013-01-18 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#ifndef __XZ_CRC64_H 4#ifndef ZIP7_INC_XZ_CRC64_H
5#define __XZ_CRC64_H 5#define ZIP7_INC_XZ_CRC64_H
6 6
7#include <stddef.h> 7#include <stddef.h>
8 8
@@ -12,14 +12,14 @@ EXTERN_C_BEGIN
12 12
13extern UInt64 g_Crc64Table[]; 13extern UInt64 g_Crc64Table[];
14 14
15void MY_FAST_CALL Crc64GenerateTable(void); 15void Z7_FASTCALL Crc64GenerateTable(void);
16 16
17#define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF) 17#define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF)
18#define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL) 18#define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL)
19#define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 19#define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
20 20
21UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size); 21UInt64 Z7_FASTCALL Crc64Update(UInt64 crc, const void *data, size_t size);
22UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size); 22UInt64 Z7_FASTCALL Crc64Calc(const void *data, size_t size);
23 23
24EXTERN_C_END 24EXTERN_C_END
25 25
diff --git a/C/XzCrc64Opt.c b/C/XzCrc64Opt.c
index 93a9fff..d03374c 100644
--- a/C/XzCrc64Opt.c
+++ b/C/XzCrc64Opt.c
@@ -1,5 +1,5 @@
1/* XzCrc64Opt.c -- CRC64 calculation 1/* XzCrc64Opt.c -- CRC64 calculation
22021-02-09 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -9,15 +9,15 @@
9 9
10#define CRC64_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 10#define CRC64_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
11 11
12UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table); 12UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table);
13UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table) 13UInt64 Z7_FASTCALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, const UInt64 *table)
14{ 14{
15 const Byte *p = (const Byte *)data; 15 const Byte *p = (const Byte *)data;
16 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) 16 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
17 v = CRC64_UPDATE_BYTE_2(v, *p); 17 v = CRC64_UPDATE_BYTE_2(v, *p);
18 for (; size >= 4; size -= 4, p += 4) 18 for (; size >= 4; size -= 4, p += 4)
19 { 19 {
20 UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p; 20 const UInt32 d = (UInt32)v ^ *(const UInt32 *)(const void *)p;
21 v = (v >> 32) 21 v = (v >> 32)
22 ^ (table + 0x300)[((d ) & 0xFF)] 22 ^ (table + 0x300)[((d ) & 0xFF)]
23 ^ (table + 0x200)[((d >> 8) & 0xFF)] 23 ^ (table + 0x200)[((d >> 8) & 0xFF)]
@@ -34,29 +34,19 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT4(UInt64 v, const void *data, size_t size, con
34 34
35#ifndef MY_CPU_LE 35#ifndef MY_CPU_LE
36 36
37#define CRC_UINT64_SWAP(v) \
38 ((v >> 56) \
39 | ((v >> 40) & ((UInt64)0xFF << 8)) \
40 | ((v >> 24) & ((UInt64)0xFF << 16)) \
41 | ((v >> 8) & ((UInt64)0xFF << 24)) \
42 | ((v << 8) & ((UInt64)0xFF << 32)) \
43 | ((v << 24) & ((UInt64)0xFF << 40)) \
44 | ((v << 40) & ((UInt64)0xFF << 48)) \
45 | ((v << 56)))
46
47#define CRC64_UPDATE_BYTE_2_BE(crc, b) (table[(Byte)((crc) >> 56) ^ (b)] ^ ((crc) << 8)) 37#define CRC64_UPDATE_BYTE_2_BE(crc, b) (table[(Byte)((crc) >> 56) ^ (b)] ^ ((crc) << 8))
48 38
49UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table); 39UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table);
50UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table) 40UInt64 Z7_FASTCALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size, const UInt64 *table)
51{ 41{
52 const Byte *p = (const Byte *)data; 42 const Byte *p = (const Byte *)data;
53 table += 0x100; 43 table += 0x100;
54 v = CRC_UINT64_SWAP(v); 44 v = Z7_BSWAP64(v);
55 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++) 45 for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
56 v = CRC64_UPDATE_BYTE_2_BE(v, *p); 46 v = CRC64_UPDATE_BYTE_2_BE(v, *p);
57 for (; size >= 4; size -= 4, p += 4) 47 for (; size >= 4; size -= 4, p += 4)
58 { 48 {
59 UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p; 49 const UInt32 d = (UInt32)(v >> 32) ^ *(const UInt32 *)(const void *)p;
60 v = (v << 32) 50 v = (v << 32)
61 ^ (table + 0x000)[((d ) & 0xFF)] 51 ^ (table + 0x000)[((d ) & 0xFF)]
62 ^ (table + 0x100)[((d >> 8) & 0xFF)] 52 ^ (table + 0x100)[((d >> 8) & 0xFF)]
@@ -65,7 +55,7 @@ UInt64 MY_FAST_CALL XzCrc64UpdateT1_BeT4(UInt64 v, const void *data, size_t size
65 } 55 }
66 for (; size > 0; size--, p++) 56 for (; size > 0; size--, p++)
67 v = CRC64_UPDATE_BYTE_2_BE(v, *p); 57 v = CRC64_UPDATE_BYTE_2_BE(v, *p);
68 return CRC_UINT64_SWAP(v); 58 return Z7_BSWAP64(v);
69} 59}
70 60
71#endif 61#endif
diff --git a/C/XzDec.c b/C/XzDec.c
index 3f96a37..a5f7039 100644
--- a/C/XzDec.c
+++ b/C/XzDec.c
@@ -1,5 +1,5 @@
1/* XzDec.c -- Xz Decode 1/* XzDec.c -- Xz Decode
22021-09-04 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -67,7 +67,8 @@ unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value)
67 return 0; 67 return 0;
68} 68}
69 69
70/* ---------- BraState ---------- */ 70
71/* ---------- XzBcFilterState ---------- */
71 72
72#define BRA_BUF_SIZE (1 << 14) 73#define BRA_BUF_SIZE (1 << 14)
73 74
@@ -76,27 +77,29 @@ typedef struct
76 size_t bufPos; 77 size_t bufPos;
77 size_t bufConv; 78 size_t bufConv;
78 size_t bufTotal; 79 size_t bufTotal;
80 Byte *buf; // must be aligned for 4 bytes
81 Xz_Func_BcFilterStateBase_Filter filter_func;
82 // int encodeMode;
83 CXzBcFilterStateBase base;
84 // Byte buf[BRA_BUF_SIZE];
85} CXzBcFilterState;
79 86
80 int encodeMode;
81
82 UInt32 methodId;
83 UInt32 delta;
84 UInt32 ip;
85 UInt32 x86State;
86 Byte deltaState[DELTA_STATE_SIZE];
87 87
88 Byte buf[BRA_BUF_SIZE]; 88static void XzBcFilterState_Free(void *pp, ISzAllocPtr alloc)
89} CBraState;
90
91static void BraState_Free(void *pp, ISzAllocPtr alloc)
92{ 89{
93 ISzAlloc_Free(alloc, pp); 90 if (pp)
91 {
92 CXzBcFilterState *p = ((CXzBcFilterState *)pp);
93 ISzAlloc_Free(alloc, p->buf);
94 ISzAlloc_Free(alloc, pp);
95 }
94} 96}
95 97
96static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) 98
99static SRes XzBcFilterState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc)
97{ 100{
98 CBraState *p = ((CBraState *)pp); 101 CXzBcFilterStateBase *p = &((CXzBcFilterState *)pp)->base;
99 UNUSED_VAR(alloc); 102 UNUSED_VAR(alloc)
100 p->ip = 0; 103 p->ip = 0;
101 if (p->methodId == XZ_ID_Delta) 104 if (p->methodId == XZ_ID_Delta)
102 { 105 {
@@ -114,6 +117,7 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA
114 case XZ_ID_PPC: 117 case XZ_ID_PPC:
115 case XZ_ID_ARM: 118 case XZ_ID_ARM:
116 case XZ_ID_SPARC: 119 case XZ_ID_SPARC:
120 case XZ_ID_ARM64:
117 if ((v & 3) != 0) 121 if ((v & 3) != 0)
118 return SZ_ERROR_UNSUPPORTED; 122 return SZ_ERROR_UNSUPPORTED;
119 break; 123 break;
@@ -134,73 +138,90 @@ static SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzA
134 return SZ_OK; 138 return SZ_OK;
135} 139}
136 140
137static void BraState_Init(void *pp) 141
142static void XzBcFilterState_Init(void *pp)
138{ 143{
139 CBraState *p = ((CBraState *)pp); 144 CXzBcFilterState *p = ((CXzBcFilterState *)pp);
140 p->bufPos = p->bufConv = p->bufTotal = 0; 145 p->bufPos = p->bufConv = p->bufTotal = 0;
141 x86_Convert_Init(p->x86State); 146 p->base.X86_State = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL;
142 if (p->methodId == XZ_ID_Delta) 147 if (p->base.methodId == XZ_ID_Delta)
143 Delta_Init(p->deltaState); 148 Delta_Init(p->base.delta_State);
144} 149}
145 150
146 151
147#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: size = isa ## _Convert(data, size, p->ip, p->encodeMode); break; 152static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Dec[] =
148 153{
149static SizeT BraState_Filter(void *pp, Byte *data, SizeT size) 154 Z7_BRANCH_CONV_DEC(PPC),
155 Z7_BRANCH_CONV_DEC(IA64),
156 Z7_BRANCH_CONV_DEC(ARM),
157 Z7_BRANCH_CONV_DEC(ARMT),
158 Z7_BRANCH_CONV_DEC(SPARC),
159 Z7_BRANCH_CONV_DEC(ARM64)
160};
161
162static SizeT XzBcFilterStateBase_Filter_Dec(CXzBcFilterStateBase *p, Byte *data, SizeT size)
150{ 163{
151 CBraState *p = ((CBraState *)pp);
152 switch (p->methodId) 164 switch (p->methodId)
153 { 165 {
154 case XZ_ID_Delta: 166 case XZ_ID_Delta:
155 if (p->encodeMode) 167 Delta_Decode(p->delta_State, p->delta, data, size);
156 Delta_Encode(p->deltaState, p->delta, data, size);
157 else
158 Delta_Decode(p->deltaState, p->delta, data, size);
159 break; 168 break;
160 case XZ_ID_X86: 169 case XZ_ID_X86:
161 size = x86_Convert(data, size, p->ip, &p->x86State, p->encodeMode); 170 size = (SizeT)(z7_BranchConvSt_X86_Dec(data, size, p->ip, &p->X86_State) - data);
171 break;
172 default:
173 if (p->methodId >= XZ_ID_PPC)
174 {
175 const UInt32 i = p->methodId - XZ_ID_PPC;
176 if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Dec))
177 size = (SizeT)(g_Funcs_BranchConv_RISC_Dec[i](data, size, p->ip) - data);
178 }
162 break; 179 break;
163 CASE_BRA_CONV(PPC)
164 CASE_BRA_CONV(IA64)
165 CASE_BRA_CONV(ARM)
166 CASE_BRA_CONV(ARMT)
167 CASE_BRA_CONV(SPARC)
168 } 180 }
169 p->ip += (UInt32)size; 181 p->ip += (UInt32)size;
170 return size; 182 return size;
171} 183}
172 184
173 185
174static SRes BraState_Code2(void *pp, 186static SizeT XzBcFilterState_Filter(void *pp, Byte *data, SizeT size)
187{
188 CXzBcFilterState *p = ((CXzBcFilterState *)pp);
189 return p->filter_func(&p->base, data, size);
190}
191
192
193static SRes XzBcFilterState_Code2(void *pp,
175 Byte *dest, SizeT *destLen, 194 Byte *dest, SizeT *destLen,
176 const Byte *src, SizeT *srcLen, int srcWasFinished, 195 const Byte *src, SizeT *srcLen, int srcWasFinished,
177 ECoderFinishMode finishMode, 196 ECoderFinishMode finishMode,
178 // int *wasFinished 197 // int *wasFinished
179 ECoderStatus *status) 198 ECoderStatus *status)
180{ 199{
181 CBraState *p = ((CBraState *)pp); 200 CXzBcFilterState *p = ((CXzBcFilterState *)pp);
182 SizeT destRem = *destLen; 201 SizeT destRem = *destLen;
183 SizeT srcRem = *srcLen; 202 SizeT srcRem = *srcLen;
184 UNUSED_VAR(finishMode); 203 UNUSED_VAR(finishMode)
185 204
186 *destLen = 0; 205 *destLen = 0;
187 *srcLen = 0; 206 *srcLen = 0;
188 // *wasFinished = False; 207 // *wasFinished = False;
189 *status = CODER_STATUS_NOT_FINISHED; 208 *status = CODER_STATUS_NOT_FINISHED;
190 209
191 while (destRem > 0) 210 while (destRem != 0)
192 { 211 {
193 if (p->bufPos != p->bufConv)
194 { 212 {
195 size_t size = p->bufConv - p->bufPos; 213 size_t size = p->bufConv - p->bufPos;
196 if (size > destRem) 214 if (size)
197 size = destRem; 215 {
198 memcpy(dest, p->buf + p->bufPos, size); 216 if (size > destRem)
199 p->bufPos += size; 217 size = destRem;
200 *destLen += size; 218 memcpy(dest, p->buf + p->bufPos, size);
201 dest += size; 219 p->bufPos += size;
202 destRem -= size; 220 *destLen += size;
203 continue; 221 dest += size;
222 destRem -= size;
223 continue;
224 }
204 } 225 }
205 226
206 p->bufTotal -= p->bufPos; 227 p->bufTotal -= p->bufPos;
@@ -220,7 +241,7 @@ static SRes BraState_Code2(void *pp,
220 if (p->bufTotal == 0) 241 if (p->bufTotal == 0)
221 break; 242 break;
222 243
223 p->bufConv = BraState_Filter(pp, p->buf, p->bufTotal); 244 p->bufConv = p->filter_func(&p->base, p->buf, p->bufTotal);
224 245
225 if (p->bufConv == 0) 246 if (p->bufConv == 0)
226 { 247 {
@@ -240,27 +261,37 @@ static SRes BraState_Code2(void *pp,
240} 261}
241 262
242 263
243SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); 264#define XZ_IS_SUPPORTED_FILTER_ID(id) \
244SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc) 265 ((id) >= XZ_ID_Delta && (id) <= XZ_ID_ARM64)
266
267SRes Xz_StateCoder_Bc_SetFromMethod_Func(IStateCoder *p, UInt64 id,
268 Xz_Func_BcFilterStateBase_Filter func, ISzAllocPtr alloc)
245{ 269{
246 CBraState *decoder; 270 CXzBcFilterState *decoder;
247 if (id < XZ_ID_Delta || id > XZ_ID_SPARC) 271 if (!XZ_IS_SUPPORTED_FILTER_ID(id))
248 return SZ_ERROR_UNSUPPORTED; 272 return SZ_ERROR_UNSUPPORTED;
249 decoder = (CBraState *)p->p; 273 decoder = (CXzBcFilterState *)p->p;
250 if (!decoder) 274 if (!decoder)
251 { 275 {
252 decoder = (CBraState *)ISzAlloc_Alloc(alloc, sizeof(CBraState)); 276 decoder = (CXzBcFilterState *)ISzAlloc_Alloc(alloc, sizeof(CXzBcFilterState));
253 if (!decoder) 277 if (!decoder)
254 return SZ_ERROR_MEM; 278 return SZ_ERROR_MEM;
279 decoder->buf = ISzAlloc_Alloc(alloc, BRA_BUF_SIZE);
280 if (!decoder->buf)
281 {
282 ISzAlloc_Free(alloc, decoder);
283 return SZ_ERROR_MEM;
284 }
255 p->p = decoder; 285 p->p = decoder;
256 p->Free = BraState_Free; 286 p->Free = XzBcFilterState_Free;
257 p->SetProps = BraState_SetProps; 287 p->SetProps = XzBcFilterState_SetProps;
258 p->Init = BraState_Init; 288 p->Init = XzBcFilterState_Init;
259 p->Code2 = BraState_Code2; 289 p->Code2 = XzBcFilterState_Code2;
260 p->Filter = BraState_Filter; 290 p->Filter = XzBcFilterState_Filter;
291 decoder->filter_func = func;
261 } 292 }
262 decoder->methodId = (UInt32)id; 293 decoder->base.methodId = (UInt32)id;
263 decoder->encodeMode = encodeMode; 294 // decoder->encodeMode = encodeMode;
264 return SZ_OK; 295 return SZ_OK;
265} 296}
266 297
@@ -279,9 +310,9 @@ static void SbState_Free(void *pp, ISzAllocPtr alloc)
279 310
280static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc) 311static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAllocPtr alloc)
281{ 312{
282 UNUSED_VAR(pp); 313 UNUSED_VAR(pp)
283 UNUSED_VAR(props); 314 UNUSED_VAR(props)
284 UNUSED_VAR(alloc); 315 UNUSED_VAR(alloc)
285 return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED; 316 return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED;
286} 317}
287 318
@@ -297,7 +328,7 @@ static SRes SbState_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *src,
297{ 328{
298 CSbDec *p = (CSbDec *)pp; 329 CSbDec *p = (CSbDec *)pp;
299 SRes res; 330 SRes res;
300 UNUSED_VAR(srcWasFinished); 331 UNUSED_VAR(srcWasFinished)
301 p->dest = dest; 332 p->dest = dest;
302 p->destLen = *destLen; 333 p->destLen = *destLen;
303 p->src = src; 334 p->src = src;
@@ -389,7 +420,7 @@ static SRes Lzma2State_Code2(void *pp, Byte *dest, SizeT *destLen, const Byte *s
389 ELzmaStatus status2; 420 ELzmaStatus status2;
390 /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */ 421 /* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */
391 SRes res; 422 SRes res;
392 UNUSED_VAR(srcWasFinished); 423 UNUSED_VAR(srcWasFinished)
393 if (spec->outBufMode) 424 if (spec->outBufMode)
394 { 425 {
395 SizeT dicPos = spec->decoder.decoder.dicPos; 426 SizeT dicPos = spec->decoder.decoder.dicPos;
@@ -420,7 +451,7 @@ static SRes Lzma2State_SetFromMethod(IStateCoder *p, Byte *outBuf, size_t outBuf
420 p->Init = Lzma2State_Init; 451 p->Init = Lzma2State_Init;
421 p->Code2 = Lzma2State_Code2; 452 p->Code2 = Lzma2State_Code2;
422 p->Filter = NULL; 453 p->Filter = NULL;
423 Lzma2Dec_Construct(&spec->decoder); 454 Lzma2Dec_CONSTRUCT(&spec->decoder)
424 } 455 }
425 spec->outBufMode = False; 456 spec->outBufMode = False;
426 if (outBuf) 457 if (outBuf)
@@ -519,7 +550,8 @@ static SRes MixCoder_SetFromMethod(CMixCoder *p, unsigned coderIndex, UInt64 met
519 } 550 }
520 if (coderIndex == 0) 551 if (coderIndex == 0)
521 return SZ_ERROR_UNSUPPORTED; 552 return SZ_ERROR_UNSUPPORTED;
522 return BraState_SetFromMethod(sc, methodId, 0, p->alloc); 553 return Xz_StateCoder_Bc_SetFromMethod_Func(sc, methodId,
554 XzBcFilterStateBase_Filter_Dec, p->alloc);
523} 555}
524 556
525 557
@@ -568,7 +600,7 @@ static SRes MixCoder_Code(CMixCoder *p,
568 SizeT destLen2, srcLen2; 600 SizeT destLen2, srcLen2;
569 int wasFinished; 601 int wasFinished;
570 602
571 PRF_STR("------- MixCoder Single ----------"); 603 PRF_STR("------- MixCoder Single ----------")
572 604
573 srcLen2 = srcLenOrig; 605 srcLen2 = srcLenOrig;
574 destLen2 = destLenOrig; 606 destLen2 = destLenOrig;
@@ -615,14 +647,14 @@ static SRes MixCoder_Code(CMixCoder *p,
615 processed = coder->Filter(coder->p, p->outBuf, processed); 647 processed = coder->Filter(coder->p, p->outBuf, processed);
616 if (wasFinished || (destFinish && p->outWritten == destLenOrig)) 648 if (wasFinished || (destFinish && p->outWritten == destLenOrig))
617 processed = p->outWritten; 649 processed = p->outWritten;
618 PRF_STR_INT("filter", i); 650 PRF_STR_INT("filter", i)
619 } 651 }
620 *destLen = processed; 652 *destLen = processed;
621 } 653 }
622 return res; 654 return res;
623 } 655 }
624 656
625 PRF_STR("standard mix"); 657 PRF_STR("standard mix")
626 658
627 if (p->numCoders != 1) 659 if (p->numCoders != 1)
628 { 660 {
@@ -779,7 +811,7 @@ static BoolInt Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte
779 811
780static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p) 812static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p)
781{ 813{
782 unsigned numFilters = XzBlock_GetNumFilters(p) - 1; 814 const unsigned numFilters = XzBlock_GetNumFilters(p) - 1;
783 unsigned i; 815 unsigned i;
784 { 816 {
785 const CXzFilter *f = &p->filters[numFilters]; 817 const CXzFilter *f = &p->filters[numFilters];
@@ -795,8 +827,7 @@ static BoolInt XzBlock_AreSupportedFilters(const CXzBlock *p)
795 if (f->propsSize != 1) 827 if (f->propsSize != 1)
796 return False; 828 return False;
797 } 829 }
798 else if (f->id < XZ_ID_Delta 830 else if (!XZ_IS_SUPPORTED_FILTER_ID(f->id)
799 || f->id > XZ_ID_SPARC
800 || (f->propsSize != 0 && f->propsSize != 4)) 831 || (f->propsSize != 0 && f->propsSize != 4))
801 return False; 832 return False;
802 } 833 }
@@ -821,22 +852,24 @@ SRes XzBlock_Parse(CXzBlock *p, const Byte *header)
821 p->packSize = (UInt64)(Int64)-1; 852 p->packSize = (UInt64)(Int64)-1;
822 if (XzBlock_HasPackSize(p)) 853 if (XzBlock_HasPackSize(p))
823 { 854 {
824 READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize); 855 READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize)
825 if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63) 856 if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63)
826 return SZ_ERROR_ARCHIVE; 857 return SZ_ERROR_ARCHIVE;
827 } 858 }
828 859
829 p->unpackSize = (UInt64)(Int64)-1; 860 p->unpackSize = (UInt64)(Int64)-1;
830 if (XzBlock_HasUnpackSize(p)) 861 if (XzBlock_HasUnpackSize(p))
831 READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize); 862 {
863 READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize)
864 }
832 865
833 numFilters = XzBlock_GetNumFilters(p); 866 numFilters = XzBlock_GetNumFilters(p);
834 for (i = 0; i < numFilters; i++) 867 for (i = 0; i < numFilters; i++)
835 { 868 {
836 CXzFilter *filter = p->filters + i; 869 CXzFilter *filter = p->filters + i;
837 UInt64 size; 870 UInt64 size;
838 READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id); 871 READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id)
839 READ_VARINT_AND_CHECK(header, pos, headerSize, &size); 872 READ_VARINT_AND_CHECK(header, pos, headerSize, &size)
840 if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX) 873 if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX)
841 return SZ_ERROR_ARCHIVE; 874 return SZ_ERROR_ARCHIVE;
842 filter->propsSize = (UInt32)size; 875 filter->propsSize = (UInt32)size;
@@ -894,20 +927,20 @@ static SRes XzDecMix_Init(CMixCoder *p, const CXzBlock *block, Byte *outBuf, siz
894 MixCoder_Free(p); 927 MixCoder_Free(p);
895 for (i = 0; i < numFilters; i++) 928 for (i = 0; i < numFilters; i++)
896 { 929 {
897 RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize)); 930 RINOK(MixCoder_SetFromMethod(p, i, block->filters[numFilters - 1 - i].id, outBuf, outBufSize))
898 } 931 }
899 p->numCoders = numFilters; 932 p->numCoders = numFilters;
900 } 933 }
901 else 934 else
902 { 935 {
903 RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize)); 936 RINOK(MixCoder_ResetFromMethod(p, 0, block->filters[numFilters - 1].id, outBuf, outBufSize))
904 } 937 }
905 938
906 for (i = 0; i < numFilters; i++) 939 for (i = 0; i < numFilters; i++)
907 { 940 {
908 const CXzFilter *f = &block->filters[numFilters - 1 - i]; 941 const CXzFilter *f = &block->filters[numFilters - 1 - i];
909 IStateCoder *sc = &p->coders[i]; 942 IStateCoder *sc = &p->coders[i];
910 RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc)); 943 RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc))
911 } 944 }
912 945
913 MixCoder_Init(p); 946 MixCoder_Init(p);
@@ -1054,14 +1087,14 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
1054 (*destLen) += destLen2; 1087 (*destLen) += destLen2;
1055 p->unpackSize += destLen2; 1088 p->unpackSize += destLen2;
1056 1089
1057 RINOK(res); 1090 RINOK(res)
1058 1091
1059 if (*status != CODER_STATUS_FINISHED_WITH_MARK) 1092 if (*status != CODER_STATUS_FINISHED_WITH_MARK)
1060 { 1093 {
1061 if (p->block.packSize == p->packSize 1094 if (p->block.packSize == p->packSize
1062 && *status == CODER_STATUS_NEEDS_MORE_INPUT) 1095 && *status == CODER_STATUS_NEEDS_MORE_INPUT)
1063 { 1096 {
1064 PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT"); 1097 PRF_STR("CODER_STATUS_NEEDS_MORE_INPUT")
1065 *status = CODER_STATUS_NOT_SPECIFIED; 1098 *status = CODER_STATUS_NOT_SPECIFIED;
1066 return SZ_ERROR_DATA; 1099 return SZ_ERROR_DATA;
1067 } 1100 }
@@ -1078,7 +1111,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
1078 if ((p->block.packSize != (UInt64)(Int64)-1 && p->block.packSize != p->packSize) 1111 if ((p->block.packSize != (UInt64)(Int64)-1 && p->block.packSize != p->packSize)
1079 || (p->block.unpackSize != (UInt64)(Int64)-1 && p->block.unpackSize != p->unpackSize)) 1112 || (p->block.unpackSize != (UInt64)(Int64)-1 && p->block.unpackSize != p->unpackSize))
1080 { 1113 {
1081 PRF_STR("ERROR: block.size mismatch"); 1114 PRF_STR("ERROR: block.size mismatch")
1082 return SZ_ERROR_DATA; 1115 return SZ_ERROR_DATA;
1083 } 1116 }
1084 } 1117 }
@@ -1109,7 +1142,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
1109 } 1142 }
1110 else 1143 else
1111 { 1144 {
1112 RINOK(Xz_ParseHeader(&p->streamFlags, p->buf)); 1145 RINOK(Xz_ParseHeader(&p->streamFlags, p->buf))
1113 p->numStartedStreams++; 1146 p->numStartedStreams++;
1114 p->indexSize = 0; 1147 p->indexSize = 0;
1115 p->numBlocks = 0; 1148 p->numBlocks = 0;
@@ -1155,7 +1188,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
1155 } 1188 }
1156 else 1189 else
1157 { 1190 {
1158 RINOK(XzBlock_Parse(&p->block, p->buf)); 1191 RINOK(XzBlock_Parse(&p->block, p->buf))
1159 if (!XzBlock_AreSupportedFilters(&p->block)) 1192 if (!XzBlock_AreSupportedFilters(&p->block))
1160 return SZ_ERROR_UNSUPPORTED; 1193 return SZ_ERROR_UNSUPPORTED;
1161 p->numTotalBlocks++; 1194 p->numTotalBlocks++;
@@ -1168,7 +1201,7 @@ SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
1168 p->headerParsedOk = True; 1201 p->headerParsedOk = True;
1169 return SZ_OK; 1202 return SZ_OK;
1170 } 1203 }
1171 RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize)); 1204 RINOK(XzDecMix_Init(&p->decoder, &p->block, p->outBuf, p->outBufSize))
1172 } 1205 }
1173 break; 1206 break;
1174 } 1207 }
@@ -1389,7 +1422,7 @@ UInt64 XzUnpacker_GetExtraSize(const CXzUnpacker *p)
1389 1422
1390 1423
1391 1424
1392#ifndef _7ZIP_ST 1425#ifndef Z7_ST
1393#include "MtDec.h" 1426#include "MtDec.h"
1394#endif 1427#endif
1395 1428
@@ -1400,7 +1433,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p)
1400 p->outStep_ST = 1 << 20; 1433 p->outStep_ST = 1 << 20;
1401 p->ignoreErrors = False; 1434 p->ignoreErrors = False;
1402 1435
1403 #ifndef _7ZIP_ST 1436 #ifndef Z7_ST
1404 p->numThreads = 1; 1437 p->numThreads = 1;
1405 p->inBufSize_MT = 1 << 18; 1438 p->inBufSize_MT = 1 << 18;
1406 p->memUseMax = sizeof(size_t) << 28; 1439 p->memUseMax = sizeof(size_t) << 28;
@@ -1409,7 +1442,7 @@ void XzDecMtProps_Init(CXzDecMtProps *p)
1409 1442
1410 1443
1411 1444
1412#ifndef _7ZIP_ST 1445#ifndef Z7_ST
1413 1446
1414/* ---------- CXzDecMtThread ---------- */ 1447/* ---------- CXzDecMtThread ---------- */
1415 1448
@@ -1448,7 +1481,7 @@ typedef struct
1448 1481
1449/* ---------- CXzDecMt ---------- */ 1482/* ---------- CXzDecMt ---------- */
1450 1483
1451typedef struct 1484struct CXzDecMt
1452{ 1485{
1453 CAlignOffsetAlloc alignOffsetAlloc; 1486 CAlignOffsetAlloc alignOffsetAlloc;
1454 ISzAllocPtr allocMid; 1487 ISzAllocPtr allocMid;
@@ -1456,9 +1489,9 @@ typedef struct
1456 CXzDecMtProps props; 1489 CXzDecMtProps props;
1457 size_t unpackBlockMaxSize; 1490 size_t unpackBlockMaxSize;
1458 1491
1459 ISeqInStream *inStream; 1492 ISeqInStreamPtr inStream;
1460 ISeqOutStream *outStream; 1493 ISeqOutStreamPtr outStream;
1461 ICompressProgress *progress; 1494 ICompressProgressPtr progress;
1462 1495
1463 BoolInt finishMode; 1496 BoolInt finishMode;
1464 BoolInt outSize_Defined; 1497 BoolInt outSize_Defined;
@@ -1481,7 +1514,7 @@ typedef struct
1481 ECoderStatus status; 1514 ECoderStatus status;
1482 SRes codeRes; 1515 SRes codeRes;
1483 1516
1484 #ifndef _7ZIP_ST 1517 #ifndef Z7_ST
1485 BoolInt mainDecoderWasCalled; 1518 BoolInt mainDecoderWasCalled;
1486 // int statErrorDefined; 1519 // int statErrorDefined;
1487 int finishedDecoderIndex; 1520 int finishedDecoderIndex;
@@ -1504,10 +1537,9 @@ typedef struct
1504 1537
1505 BoolInt mtc_WasConstructed; 1538 BoolInt mtc_WasConstructed;
1506 CMtDec mtc; 1539 CMtDec mtc;
1507 CXzDecMtThread coders[MTDEC__THREADS_MAX]; 1540 CXzDecMtThread coders[MTDEC_THREADS_MAX];
1508 #endif 1541 #endif
1509 1542};
1510} CXzDecMt;
1511 1543
1512 1544
1513 1545
@@ -1535,11 +1567,11 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid)
1535 1567
1536 XzDecMtProps_Init(&p->props); 1568 XzDecMtProps_Init(&p->props);
1537 1569
1538 #ifndef _7ZIP_ST 1570 #ifndef Z7_ST
1539 p->mtc_WasConstructed = False; 1571 p->mtc_WasConstructed = False;
1540 { 1572 {
1541 unsigned i; 1573 unsigned i;
1542 for (i = 0; i < MTDEC__THREADS_MAX; i++) 1574 for (i = 0; i < MTDEC_THREADS_MAX; i++)
1543 { 1575 {
1544 CXzDecMtThread *coder = &p->coders[i]; 1576 CXzDecMtThread *coder = &p->coders[i];
1545 coder->dec_created = False; 1577 coder->dec_created = False;
@@ -1549,16 +1581,16 @@ CXzDecMtHandle XzDecMt_Create(ISzAllocPtr alloc, ISzAllocPtr allocMid)
1549 } 1581 }
1550 #endif 1582 #endif
1551 1583
1552 return p; 1584 return (CXzDecMtHandle)p;
1553} 1585}
1554 1586
1555 1587
1556#ifndef _7ZIP_ST 1588#ifndef Z7_ST
1557 1589
1558static void XzDecMt_FreeOutBufs(CXzDecMt *p) 1590static void XzDecMt_FreeOutBufs(CXzDecMt *p)
1559{ 1591{
1560 unsigned i; 1592 unsigned i;
1561 for (i = 0; i < MTDEC__THREADS_MAX; i++) 1593 for (i = 0; i < MTDEC_THREADS_MAX; i++)
1562 { 1594 {
1563 CXzDecMtThread *coder = &p->coders[i]; 1595 CXzDecMtThread *coder = &p->coders[i];
1564 if (coder->outBuf) 1596 if (coder->outBuf)
@@ -1595,13 +1627,15 @@ static void XzDecMt_FreeSt(CXzDecMt *p)
1595} 1627}
1596 1628
1597 1629
1598void XzDecMt_Destroy(CXzDecMtHandle pp) 1630// #define GET_CXzDecMt_p CXzDecMt *p = pp;
1631
1632void XzDecMt_Destroy(CXzDecMtHandle p)
1599{ 1633{
1600 CXzDecMt *p = (CXzDecMt *)pp; 1634 // GET_CXzDecMt_p
1601 1635
1602 XzDecMt_FreeSt(p); 1636 XzDecMt_FreeSt(p);
1603 1637
1604 #ifndef _7ZIP_ST 1638 #ifndef Z7_ST
1605 1639
1606 if (p->mtc_WasConstructed) 1640 if (p->mtc_WasConstructed)
1607 { 1641 {
@@ -1610,7 +1644,7 @@ void XzDecMt_Destroy(CXzDecMtHandle pp)
1610 } 1644 }
1611 { 1645 {
1612 unsigned i; 1646 unsigned i;
1613 for (i = 0; i < MTDEC__THREADS_MAX; i++) 1647 for (i = 0; i < MTDEC_THREADS_MAX; i++)
1614 { 1648 {
1615 CXzDecMtThread *t = &p->coders[i]; 1649 CXzDecMtThread *t = &p->coders[i];
1616 if (t->dec_created) 1650 if (t->dec_created)
@@ -1625,12 +1659,12 @@ void XzDecMt_Destroy(CXzDecMtHandle pp)
1625 1659
1626 #endif 1660 #endif
1627 1661
1628 ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, pp); 1662 ISzAlloc_Free(p->alignOffsetAlloc.baseAlloc, p);
1629} 1663}
1630 1664
1631 1665
1632 1666
1633#ifndef _7ZIP_ST 1667#ifndef Z7_ST
1634 1668
1635static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc) 1669static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbackInfo *cc)
1636{ 1670{
@@ -1696,7 +1730,7 @@ static void XzDecMt_Callback_Parse(void *obj, unsigned coderIndex, CMtDecCallbac
1696 coder->dec.parseMode = True; 1730 coder->dec.parseMode = True;
1697 coder->dec.headerParsedOk = False; 1731 coder->dec.headerParsedOk = False;
1698 1732
1699 PRF_STR_INT("Parse", srcSize2); 1733 PRF_STR_INT("Parse", srcSize2)
1700 1734
1701 res = XzUnpacker_Code(&coder->dec, 1735 res = XzUnpacker_Code(&coder->dec,
1702 NULL, &destSize, 1736 NULL, &destSize,
@@ -2071,7 +2105,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex,
2071 } 2105 }
2072 data += cur; 2106 data += cur;
2073 size -= cur; 2107 size -= cur;
2074 // PRF_STR_INT("Written size =", size); 2108 // PRF_STR_INT("Written size =", size)
2075 if (size == 0) 2109 if (size == 0)
2076 break; 2110 break;
2077 res = MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0); 2111 res = MtProgress_ProgressAdd(&me->mtc.mtProgress, 0, 0);
@@ -2087,7 +2121,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex,
2087 return res; 2121 return res;
2088 } 2122 }
2089 2123
2090 RINOK(res); 2124 RINOK(res)
2091 2125
2092 if (coder->inPreSize != coder->inCodeSize 2126 if (coder->inPreSize != coder->inCodeSize
2093 || coder->blockPackTotal != coder->inCodeSize) 2127 || coder->blockPackTotal != coder->inCodeSize)
@@ -2106,13 +2140,13 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex,
2106 // (coder->state == MTDEC_PARSE_END) means that there are no other working threads 2140 // (coder->state == MTDEC_PARSE_END) means that there are no other working threads
2107 // so we can use mtc variables without lock 2141 // so we can use mtc variables without lock
2108 2142
2109 PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed); 2143 PRF_STR_INT("Write MTDEC_PARSE_END", me->mtc.inProcessed)
2110 2144
2111 me->mtc.mtProgress.totalInSize = me->mtc.inProcessed; 2145 me->mtc.mtProgress.totalInSize = me->mtc.inProcessed;
2112 { 2146 {
2113 CXzUnpacker *dec = &me->dec; 2147 CXzUnpacker *dec = &me->dec;
2114 2148
2115 PRF_STR_INT("PostSingle", srcSize); 2149 PRF_STR_INT("PostSingle", srcSize)
2116 2150
2117 { 2151 {
2118 size_t srcProcessed = srcSize; 2152 size_t srcProcessed = srcSize;
@@ -2186,7 +2220,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex,
2186 me->mtc.crossEnd = srcSize; 2220 me->mtc.crossEnd = srcSize;
2187 } 2221 }
2188 2222
2189 PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd); 2223 PRF_STR_INT("XZ_STATE_STREAM_HEADER crossEnd = ", (unsigned)me->mtc.crossEnd)
2190 2224
2191 return SZ_OK; 2225 return SZ_OK;
2192 } 2226 }
@@ -2277,7 +2311,7 @@ static SRes XzDecMt_Callback_Write(void *pp, unsigned coderIndex,
2277 UInt64 inDelta = me->mtc.inProcessed - inProgressPrev; 2311 UInt64 inDelta = me->mtc.inProcessed - inProgressPrev;
2278 if (inDelta >= (1 << 22)) 2312 if (inDelta >= (1 << 22))
2279 { 2313 {
2280 RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress)); 2314 RINOK(MtProgress_Progress_ST(&me->mtc.mtProgress))
2281 inProgressPrev = me->mtc.inProcessed; 2315 inProgressPrev = me->mtc.inProcessed;
2282 } 2316 }
2283 } 2317 }
@@ -2331,7 +2365,7 @@ void XzStatInfo_Clear(CXzStatInfo *p)
2331*/ 2365*/
2332 2366
2333static SRes XzDecMt_Decode_ST(CXzDecMt *p 2367static SRes XzDecMt_Decode_ST(CXzDecMt *p
2334 #ifndef _7ZIP_ST 2368 #ifndef Z7_ST
2335 , BoolInt tMode 2369 , BoolInt tMode
2336 #endif 2370 #endif
2337 , CXzStatInfo *stat) 2371 , CXzStatInfo *stat)
@@ -2343,7 +2377,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p
2343 2377
2344 CXzUnpacker *dec; 2378 CXzUnpacker *dec;
2345 2379
2346 #ifndef _7ZIP_ST 2380 #ifndef Z7_ST
2347 if (tMode) 2381 if (tMode)
2348 { 2382 {
2349 XzDecMt_FreeOutBufs(p); 2383 XzDecMt_FreeOutBufs(p);
@@ -2400,7 +2434,7 @@ static SRes XzDecMt_Decode_ST(CXzDecMt *p
2400 2434
2401 if (inPos == inLim) 2435 if (inPos == inLim)
2402 { 2436 {
2403 #ifndef _7ZIP_ST 2437 #ifndef Z7_ST
2404 if (tMode) 2438 if (tMode)
2405 { 2439 {
2406 inData = MtDec_Read(&p->mtc, &inLim); 2440 inData = MtDec_Read(&p->mtc, &inLim);
@@ -2577,19 +2611,19 @@ static void XzStatInfo_SetStat(const CXzUnpacker *dec,
2577 2611
2578 2612
2579 2613
2580SRes XzDecMt_Decode(CXzDecMtHandle pp, 2614SRes XzDecMt_Decode(CXzDecMtHandle p,
2581 const CXzDecMtProps *props, 2615 const CXzDecMtProps *props,
2582 const UInt64 *outDataSize, int finishMode, 2616 const UInt64 *outDataSize, int finishMode,
2583 ISeqOutStream *outStream, 2617 ISeqOutStreamPtr outStream,
2584 // Byte *outBuf, size_t *outBufSize, 2618 // Byte *outBuf, size_t *outBufSize,
2585 ISeqInStream *inStream, 2619 ISeqInStreamPtr inStream,
2586 // const Byte *inData, size_t inDataSize, 2620 // const Byte *inData, size_t inDataSize,
2587 CXzStatInfo *stat, 2621 CXzStatInfo *stat,
2588 int *isMT, 2622 int *isMT,
2589 ICompressProgress *progress) 2623 ICompressProgressPtr progress)
2590{ 2624{
2591 CXzDecMt *p = (CXzDecMt *)pp; 2625 // GET_CXzDecMt_p
2592 #ifndef _7ZIP_ST 2626 #ifndef Z7_ST
2593 BoolInt tMode; 2627 BoolInt tMode;
2594 #endif 2628 #endif
2595 2629
@@ -2640,7 +2674,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp,
2640 */ 2674 */
2641 2675
2642 2676
2643 #ifndef _7ZIP_ST 2677 #ifndef Z7_ST
2644 2678
2645 p->isBlockHeaderState_Parse = False; 2679 p->isBlockHeaderState_Parse = False;
2646 p->isBlockHeaderState_Write = False; 2680 p->isBlockHeaderState_Write = False;
@@ -2782,7 +2816,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp,
2782 return res; 2816 return res;
2783 } 2817 }
2784 2818
2785 PRF_STR("----- decoding ST -----"); 2819 PRF_STR("----- decoding ST -----")
2786 } 2820 }
2787 2821
2788 #endif 2822 #endif
@@ -2792,13 +2826,13 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp,
2792 2826
2793 { 2827 {
2794 SRes res = XzDecMt_Decode_ST(p 2828 SRes res = XzDecMt_Decode_ST(p
2795 #ifndef _7ZIP_ST 2829 #ifndef Z7_ST
2796 , tMode 2830 , tMode
2797 #endif 2831 #endif
2798 , stat 2832 , stat
2799 ); 2833 );
2800 2834
2801 #ifndef _7ZIP_ST 2835 #ifndef Z7_ST
2802 // we must set error code from MT decoding at first 2836 // we must set error code from MT decoding at first
2803 if (p->mainErrorCode != SZ_OK) 2837 if (p->mainErrorCode != SZ_OK)
2804 stat->DecodeRes = p->mainErrorCode; 2838 stat->DecodeRes = p->mainErrorCode;
@@ -2835,3 +2869,7 @@ SRes XzDecMt_Decode(CXzDecMtHandle pp,
2835 return res; 2869 return res;
2836 } 2870 }
2837} 2871}
2872
2873#undef PRF
2874#undef PRF_STR
2875#undef PRF_STR_INT_2
diff --git a/C/XzEnc.c b/C/XzEnc.c
index be174cc..22408e2 100644
--- a/C/XzEnc.c
+++ b/C/XzEnc.c
@@ -1,5 +1,5 @@
1/* XzEnc.c -- Xz Encode 1/* XzEnc.c -- Xz Encode
22021-04-01 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -18,13 +18,13 @@
18 18
19#include "XzEnc.h" 19#include "XzEnc.h"
20 20
21// #define _7ZIP_ST 21// #define Z7_ST
22 22
23#ifndef _7ZIP_ST 23#ifndef Z7_ST
24#include "MtCoder.h" 24#include "MtCoder.h"
25#else 25#else
26#define MTCODER__THREADS_MAX 1 26#define MTCODER_THREADS_MAX 1
27#define MTCODER__BLOCKS_MAX 1 27#define MTCODER_BLOCKS_MAX 1
28#endif 28#endif
29 29
30#define XZ_GET_PAD_SIZE(dataSize) ((4 - ((unsigned)(dataSize) & 3)) & 3) 30#define XZ_GET_PAD_SIZE(dataSize) ((4 - ((unsigned)(dataSize) & 3)) & 3)
@@ -35,25 +35,25 @@
35#define XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(unpackSize) (XZ_BLOCK_HEADER_SIZE_MAX + XZ_GET_MAX_BLOCK_PACK_SIZE(unpackSize)) 35#define XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(unpackSize) (XZ_BLOCK_HEADER_SIZE_MAX + XZ_GET_MAX_BLOCK_PACK_SIZE(unpackSize))
36 36
37 37
38#define XzBlock_ClearFlags(p) (p)->flags = 0; 38// #define XzBlock_ClearFlags(p) (p)->flags = 0;
39#define XzBlock_SetNumFilters(p, n) (p)->flags = (Byte)((p)->flags | ((n) - 1)); 39#define XzBlock_ClearFlags_SetNumFilters(p, n) (p)->flags = (Byte)((n) - 1);
40#define XzBlock_SetHasPackSize(p) (p)->flags |= XZ_BF_PACK_SIZE; 40#define XzBlock_SetHasPackSize(p) (p)->flags |= XZ_BF_PACK_SIZE;
41#define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE; 41#define XzBlock_SetHasUnpackSize(p) (p)->flags |= XZ_BF_UNPACK_SIZE;
42 42
43 43
44static SRes WriteBytes(ISeqOutStream *s, const void *buf, size_t size) 44static SRes WriteBytes(ISeqOutStreamPtr s, const void *buf, size_t size)
45{ 45{
46 return (ISeqOutStream_Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE; 46 return (ISeqOutStream_Write(s, buf, size) == size) ? SZ_OK : SZ_ERROR_WRITE;
47} 47}
48 48
49static SRes WriteBytesUpdateCrc(ISeqOutStream *s, const void *buf, size_t size, UInt32 *crc) 49static SRes WriteBytes_UpdateCrc(ISeqOutStreamPtr s, const void *buf, size_t size, UInt32 *crc)
50{ 50{
51 *crc = CrcUpdate(*crc, buf, size); 51 *crc = CrcUpdate(*crc, buf, size);
52 return WriteBytes(s, buf, size); 52 return WriteBytes(s, buf, size);
53} 53}
54 54
55 55
56static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s) 56static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStreamPtr s)
57{ 57{
58 UInt32 crc; 58 UInt32 crc;
59 Byte header[XZ_STREAM_HEADER_SIZE]; 59 Byte header[XZ_STREAM_HEADER_SIZE];
@@ -61,12 +61,12 @@ static SRes Xz_WriteHeader(CXzStreamFlags f, ISeqOutStream *s)
61 header[XZ_SIG_SIZE] = (Byte)(f >> 8); 61 header[XZ_SIG_SIZE] = (Byte)(f >> 8);
62 header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF); 62 header[XZ_SIG_SIZE + 1] = (Byte)(f & 0xFF);
63 crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE); 63 crc = CrcCalc(header + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE);
64 SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc); 64 SetUi32(header + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE, crc)
65 return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE); 65 return WriteBytes(s, header, XZ_STREAM_HEADER_SIZE);
66} 66}
67 67
68 68
69static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s) 69static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStreamPtr s)
70{ 70{
71 Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; 71 Byte header[XZ_BLOCK_HEADER_SIZE_MAX];
72 72
@@ -91,7 +91,7 @@ static SRes XzBlock_WriteHeader(const CXzBlock *p, ISeqOutStream *s)
91 header[pos++] = 0; 91 header[pos++] = 0;
92 92
93 header[0] = (Byte)(pos >> 2); 93 header[0] = (Byte)(pos >> 2);
94 SetUi32(header + pos, CrcCalc(header, pos)); 94 SetUi32(header + pos, CrcCalc(header, pos))
95 return WriteBytes(s, header, pos + 4); 95 return WriteBytes(s, header, pos + 4);
96} 96}
97 97
@@ -182,7 +182,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64
182 size_t newSize = p->allocated * 2 + 16 * 2; 182 size_t newSize = p->allocated * 2 + 16 * 2;
183 if (newSize < p->size + pos) 183 if (newSize < p->size + pos)
184 return SZ_ERROR_MEM; 184 return SZ_ERROR_MEM;
185 RINOK(XzEncIndex_ReAlloc(p, newSize, alloc)); 185 RINOK(XzEncIndex_ReAlloc(p, newSize, alloc))
186 } 186 }
187 memcpy(p->blocks + p->size, buf, pos); 187 memcpy(p->blocks + p->size, buf, pos);
188 p->size += pos; 188 p->size += pos;
@@ -191,7 +191,7 @@ static SRes XzEncIndex_AddIndexRecord(CXzEncIndex *p, UInt64 unpackSize, UInt64
191} 191}
192 192
193 193
194static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStream *s) 194static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, ISeqOutStreamPtr s)
195{ 195{
196 Byte buf[32]; 196 Byte buf[32];
197 UInt64 globalPos; 197 UInt64 globalPos;
@@ -200,8 +200,8 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I
200 200
201 globalPos = pos; 201 globalPos = pos;
202 buf[0] = 0; 202 buf[0] = 0;
203 RINOK(WriteBytesUpdateCrc(s, buf, pos, &crc)); 203 RINOK(WriteBytes_UpdateCrc(s, buf, pos, &crc))
204 RINOK(WriteBytesUpdateCrc(s, p->blocks, p->size, &crc)); 204 RINOK(WriteBytes_UpdateCrc(s, p->blocks, p->size, &crc))
205 globalPos += p->size; 205 globalPos += p->size;
206 206
207 pos = XZ_GET_PAD_SIZE(globalPos); 207 pos = XZ_GET_PAD_SIZE(globalPos);
@@ -211,12 +211,12 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I
211 globalPos += pos; 211 globalPos += pos;
212 212
213 crc = CrcUpdate(crc, buf + 4 - pos, pos); 213 crc = CrcUpdate(crc, buf + 4 - pos, pos);
214 SetUi32(buf + 4, CRC_GET_DIGEST(crc)); 214 SetUi32(buf + 4, CRC_GET_DIGEST(crc))
215 215
216 SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2)); 216 SetUi32(buf + 8 + 4, (UInt32)(globalPos >> 2))
217 buf[8 + 8] = (Byte)(flags >> 8); 217 buf[8 + 8] = (Byte)(flags >> 8);
218 buf[8 + 9] = (Byte)(flags & 0xFF); 218 buf[8 + 9] = (Byte)(flags & 0xFF);
219 SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6)); 219 SetUi32(buf + 8, CrcCalc(buf + 8 + 4, 6))
220 buf[8 + 10] = XZ_FOOTER_SIG_0; 220 buf[8 + 10] = XZ_FOOTER_SIG_0;
221 buf[8 + 11] = XZ_FOOTER_SIG_1; 221 buf[8 + 11] = XZ_FOOTER_SIG_1;
222 222
@@ -230,7 +230,7 @@ static SRes XzEncIndex_WriteFooter(const CXzEncIndex *p, CXzStreamFlags flags, I
230typedef struct 230typedef struct
231{ 231{
232 ISeqInStream vt; 232 ISeqInStream vt;
233 ISeqInStream *realStream; 233 ISeqInStreamPtr realStream;
234 const Byte *data; 234 const Byte *data;
235 UInt64 limit; 235 UInt64 limit;
236 UInt64 processed; 236 UInt64 processed;
@@ -251,9 +251,9 @@ static void SeqCheckInStream_GetDigest(CSeqCheckInStream *p, Byte *digest)
251 XzCheck_Final(&p->check, digest); 251 XzCheck_Final(&p->check, digest);
252} 252}
253 253
254static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *size) 254static SRes SeqCheckInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size)
255{ 255{
256 CSeqCheckInStream *p = CONTAINER_FROM_VTBL(pp, CSeqCheckInStream, vt); 256 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqCheckInStream)
257 size_t size2 = *size; 257 size_t size2 = *size;
258 SRes res = SZ_OK; 258 SRes res = SZ_OK;
259 259
@@ -285,15 +285,15 @@ static SRes SeqCheckInStream_Read(const ISeqInStream *pp, void *data, size_t *si
285typedef struct 285typedef struct
286{ 286{
287 ISeqOutStream vt; 287 ISeqOutStream vt;
288 ISeqOutStream *realStream; 288 ISeqOutStreamPtr realStream;
289 Byte *outBuf; 289 Byte *outBuf;
290 size_t outBufLimit; 290 size_t outBufLimit;
291 UInt64 processed; 291 UInt64 processed;
292} CSeqSizeOutStream; 292} CSeqSizeOutStream;
293 293
294static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data, size_t size) 294static size_t SeqSizeOutStream_Write(ISeqOutStreamPtr pp, const void *data, size_t size)
295{ 295{
296 CSeqSizeOutStream *p = CONTAINER_FROM_VTBL(pp, CSeqSizeOutStream, vt); 296 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqSizeOutStream)
297 if (p->realStream) 297 if (p->realStream)
298 size = ISeqOutStream_Write(p->realStream, data, size); 298 size = ISeqOutStream_Write(p->realStream, data, size);
299 else 299 else
@@ -313,8 +313,8 @@ static size_t SeqSizeOutStream_Write(const ISeqOutStream *pp, const void *data,
313 313
314typedef struct 314typedef struct
315{ 315{
316 ISeqInStream p; 316 ISeqInStream vt;
317 ISeqInStream *realStream; 317 ISeqInStreamPtr realStream;
318 IStateCoder StateCoder; 318 IStateCoder StateCoder;
319 Byte *buf; 319 Byte *buf;
320 size_t curPos; 320 size_t curPos;
@@ -323,7 +323,39 @@ typedef struct
323} CSeqInFilter; 323} CSeqInFilter;
324 324
325 325
326SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, int encodeMode, ISzAllocPtr alloc); 326static const z7_Func_BranchConv g_Funcs_BranchConv_RISC_Enc[] =
327{
328 Z7_BRANCH_CONV_ENC(PPC),
329 Z7_BRANCH_CONV_ENC(IA64),
330 Z7_BRANCH_CONV_ENC(ARM),
331 Z7_BRANCH_CONV_ENC(ARMT),
332 Z7_BRANCH_CONV_ENC(SPARC),
333 Z7_BRANCH_CONV_ENC(ARM64)
334};
335
336static SizeT XzBcFilterStateBase_Filter_Enc(CXzBcFilterStateBase *p, Byte *data, SizeT size)
337{
338 switch (p->methodId)
339 {
340 case XZ_ID_Delta:
341 Delta_Encode(p->delta_State, p->delta, data, size);
342 break;
343 case XZ_ID_X86:
344 size = (SizeT)(z7_BranchConvSt_X86_Enc(data, size, p->ip, &p->X86_State) - data);
345 break;
346 default:
347 if (p->methodId >= XZ_ID_PPC)
348 {
349 const UInt32 i = p->methodId - XZ_ID_PPC;
350 if (i < Z7_ARRAY_SIZE(g_Funcs_BranchConv_RISC_Enc))
351 size = (SizeT)(g_Funcs_BranchConv_RISC_Enc[i](data, size, p->ip) - data);
352 }
353 break;
354 }
355 p->ip += (UInt32)size;
356 return size;
357}
358
327 359
328static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPtr alloc) 360static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPtr alloc)
329{ 361{
@@ -335,17 +367,17 @@ static SRes SeqInFilter_Init(CSeqInFilter *p, const CXzFilter *props, ISzAllocPt
335 } 367 }
336 p->curPos = p->endPos = 0; 368 p->curPos = p->endPos = 0;
337 p->srcWasFinished = 0; 369 p->srcWasFinished = 0;
338 RINOK(BraState_SetFromMethod(&p->StateCoder, props->id, 1, alloc)); 370 RINOK(Xz_StateCoder_Bc_SetFromMethod_Func(&p->StateCoder, props->id, XzBcFilterStateBase_Filter_Enc, alloc))
339 RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc)); 371 RINOK(p->StateCoder.SetProps(p->StateCoder.p, props->props, props->propsSize, alloc))
340 p->StateCoder.Init(p->StateCoder.p); 372 p->StateCoder.Init(p->StateCoder.p);
341 return SZ_OK; 373 return SZ_OK;
342} 374}
343 375
344 376
345static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size) 377static SRes SeqInFilter_Read(ISeqInStreamPtr pp, void *data, size_t *size)
346{ 378{
347 CSeqInFilter *p = CONTAINER_FROM_VTBL(pp, CSeqInFilter, p); 379 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInFilter)
348 size_t sizeOriginal = *size; 380 const size_t sizeOriginal = *size;
349 if (sizeOriginal == 0) 381 if (sizeOriginal == 0)
350 return SZ_OK; 382 return SZ_OK;
351 *size = 0; 383 *size = 0;
@@ -356,7 +388,7 @@ static SRes SeqInFilter_Read(const ISeqInStream *pp, void *data, size_t *size)
356 { 388 {
357 p->curPos = 0; 389 p->curPos = 0;
358 p->endPos = FILTER_BUF_SIZE; 390 p->endPos = FILTER_BUF_SIZE;
359 RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos)); 391 RINOK(ISeqInStream_Read(p->realStream, p->buf, &p->endPos))
360 if (p->endPos == 0) 392 if (p->endPos == 0)
361 p->srcWasFinished = 1; 393 p->srcWasFinished = 1;
362 } 394 }
@@ -381,7 +413,7 @@ static void SeqInFilter_Construct(CSeqInFilter *p)
381{ 413{
382 p->buf = NULL; 414 p->buf = NULL;
383 p->StateCoder.p = NULL; 415 p->StateCoder.p = NULL;
384 p->p.Read = SeqInFilter_Read; 416 p->vt.Read = SeqInFilter_Read;
385} 417}
386 418
387static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc) 419static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc)
@@ -406,13 +438,13 @@ static void SeqInFilter_Free(CSeqInFilter *p, ISzAllocPtr alloc)
406typedef struct 438typedef struct
407{ 439{
408 ISeqInStream vt; 440 ISeqInStream vt;
409 ISeqInStream *inStream; 441 ISeqInStreamPtr inStream;
410 CSbEnc enc; 442 CSbEnc enc;
411} CSbEncInStream; 443} CSbEncInStream;
412 444
413static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size) 445static SRes SbEncInStream_Read(ISeqInStreamPtr pp, void *data, size_t *size)
414{ 446{
415 CSbEncInStream *p = CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt); 447 CSbEncInStream *p = Z7_CONTAINER_FROM_VTBL(pp, CSbEncInStream, vt);
416 size_t sizeOriginal = *size; 448 size_t sizeOriginal = *size;
417 if (sizeOriginal == 0) 449 if (sizeOriginal == 0)
418 return SZ_OK; 450 return SZ_OK;
@@ -422,7 +454,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size)
422 if (p->enc.needRead && !p->enc.readWasFinished) 454 if (p->enc.needRead && !p->enc.readWasFinished)
423 { 455 {
424 size_t processed = p->enc.needReadSizeMax; 456 size_t processed = p->enc.needReadSizeMax;
425 RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed)); 457 RINOK(p->inStream->Read(p->inStream, p->enc.buf + p->enc.readPos, &processed))
426 p->enc.readPos += processed; 458 p->enc.readPos += processed;
427 if (processed == 0) 459 if (processed == 0)
428 { 460 {
@@ -433,7 +465,7 @@ static SRes SbEncInStream_Read(const ISeqInStream *pp, void *data, size_t *size)
433 } 465 }
434 466
435 *size = sizeOriginal; 467 *size = sizeOriginal;
436 RINOK(SbEnc_Read(&p->enc, data, size)); 468 RINOK(SbEnc_Read(&p->enc, data, size))
437 if (*size != 0 || !p->enc.needRead) 469 if (*size != 0 || !p->enc.needRead)
438 return SZ_OK; 470 return SZ_OK;
439 } 471 }
@@ -473,7 +505,7 @@ void XzFilterProps_Init(CXzFilterProps *p)
473void XzProps_Init(CXzProps *p) 505void XzProps_Init(CXzProps *p)
474{ 506{
475 p->checkId = XZ_CHECK_CRC32; 507 p->checkId = XZ_CHECK_CRC32;
476 p->blockSize = XZ_PROPS__BLOCK_SIZE__AUTO; 508 p->blockSize = XZ_PROPS_BLOCK_SIZE_AUTO;
477 p->numBlockThreads_Reduced = -1; 509 p->numBlockThreads_Reduced = -1;
478 p->numBlockThreads_Max = -1; 510 p->numBlockThreads_Max = -1;
479 p->numTotalThreads = -1; 511 p->numTotalThreads = -1;
@@ -502,8 +534,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p)
502 t2 = p->numBlockThreads_Max; 534 t2 = p->numBlockThreads_Max;
503 t3 = p->numTotalThreads; 535 t3 = p->numTotalThreads;
504 536
505 if (t2 > MTCODER__THREADS_MAX) 537 if (t2 > MTCODER_THREADS_MAX)
506 t2 = MTCODER__THREADS_MAX; 538 t2 = MTCODER_THREADS_MAX;
507 539
508 if (t3 <= 0) 540 if (t3 <= 0)
509 { 541 {
@@ -519,8 +551,8 @@ static void XzEncProps_Normalize_Fixed(CXzProps *p)
519 t1 = 1; 551 t1 = 1;
520 t2 = t3; 552 t2 = t3;
521 } 553 }
522 if (t2 > MTCODER__THREADS_MAX) 554 if (t2 > MTCODER_THREADS_MAX)
523 t2 = MTCODER__THREADS_MAX; 555 t2 = MTCODER_THREADS_MAX;
524 } 556 }
525 else if (t1 <= 0) 557 else if (t1 <= 0)
526 { 558 {
@@ -571,7 +603,7 @@ static void XzProps_Normalize(CXzProps *p)
571 /* we normalize xzProps properties, but we normalize only some of CXzProps::lzma2Props properties. 603 /* we normalize xzProps properties, but we normalize only some of CXzProps::lzma2Props properties.
572 Lzma2Enc_SetProps() will normalize lzma2Props later. */ 604 Lzma2Enc_SetProps() will normalize lzma2Props later. */
573 605
574 if (p->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID) 606 if (p->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID)
575 { 607 {
576 p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; 608 p->lzma2Props.lzmaProps.reduceSize = p->reduceSize;
577 p->numBlockThreads_Reduced = 1; 609 p->numBlockThreads_Reduced = 1;
@@ -583,15 +615,15 @@ static void XzProps_Normalize(CXzProps *p)
583 else 615 else
584 { 616 {
585 CLzma2EncProps *lzma2 = &p->lzma2Props; 617 CLzma2EncProps *lzma2 = &p->lzma2Props;
586 if (p->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) 618 if (p->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO)
587 { 619 {
588 // xz-auto 620 // xz-auto
589 p->lzma2Props.lzmaProps.reduceSize = p->reduceSize; 621 p->lzma2Props.lzmaProps.reduceSize = p->reduceSize;
590 622
591 if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) 623 if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID)
592 { 624 {
593 // if (xz-auto && lzma2-solid) - we use solid for both 625 // if (xz-auto && lzma2-solid) - we use solid for both
594 p->blockSize = XZ_PROPS__BLOCK_SIZE__SOLID; 626 p->blockSize = XZ_PROPS_BLOCK_SIZE_SOLID;
595 p->numBlockThreads_Reduced = 1; 627 p->numBlockThreads_Reduced = 1;
596 p->numBlockThreads_Max = 1; 628 p->numBlockThreads_Max = 1;
597 if (p->lzma2Props.numTotalThreads <= 0) 629 if (p->lzma2Props.numTotalThreads <= 0)
@@ -610,9 +642,9 @@ static void XzProps_Normalize(CXzProps *p)
610 p->blockSize = tp.blockSize; // fixed or solid 642 p->blockSize = tp.blockSize; // fixed or solid
611 p->numBlockThreads_Reduced = tp.numBlockThreads_Reduced; 643 p->numBlockThreads_Reduced = tp.numBlockThreads_Reduced;
612 p->numBlockThreads_Max = tp.numBlockThreads_Max; 644 p->numBlockThreads_Max = tp.numBlockThreads_Max;
613 if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) 645 if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO)
614 lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID 646 lzma2->blockSize = tp.blockSize; // fixed or solid, LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID
615 if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) 647 if (lzma2->lzmaProps.reduceSize > tp.blockSize && tp.blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID)
616 lzma2->lzmaProps.reduceSize = tp.blockSize; 648 lzma2->lzmaProps.reduceSize = tp.blockSize;
617 lzma2->numBlockThreads_Reduced = 1; 649 lzma2->numBlockThreads_Reduced = 1;
618 lzma2->numBlockThreads_Max = 1; 650 lzma2->numBlockThreads_Max = 1;
@@ -631,9 +663,9 @@ static void XzProps_Normalize(CXzProps *p)
631 r = p->blockSize; 663 r = p->blockSize;
632 lzma2->lzmaProps.reduceSize = r; 664 lzma2->lzmaProps.reduceSize = r;
633 } 665 }
634 if (lzma2->blockSize == LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO) 666 if (lzma2->blockSize == LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO)
635 lzma2->blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; 667 lzma2->blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID;
636 else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID) 668 else if (lzma2->blockSize > p->blockSize && lzma2->blockSize != LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID)
637 lzma2->blockSize = p->blockSize; 669 lzma2->blockSize = p->blockSize;
638 670
639 XzEncProps_Normalize_Fixed(p); 671 XzEncProps_Normalize_Fixed(p);
@@ -704,17 +736,17 @@ typedef struct
704static SRes Xz_CompressBlock( 736static SRes Xz_CompressBlock(
705 CLzma2WithFilters *lzmaf, 737 CLzma2WithFilters *lzmaf,
706 738
707 ISeqOutStream *outStream, 739 ISeqOutStreamPtr outStream,
708 Byte *outBufHeader, 740 Byte *outBufHeader,
709 Byte *outBufData, size_t outBufDataLimit, 741 Byte *outBufData, size_t outBufDataLimit,
710 742
711 ISeqInStream *inStream, 743 ISeqInStreamPtr inStream,
712 // UInt64 expectedSize, 744 // UInt64 expectedSize,
713 const Byte *inBuf, // used if (!inStream) 745 const Byte *inBuf, // used if (!inStream)
714 size_t inBufSize, // used if (!inStream), it's block size, props->blockSize is ignored 746 size_t inBufSize, // used if (!inStream), it's block size, props->blockSize is ignored
715 747
716 const CXzProps *props, 748 const CXzProps *props,
717 ICompressProgress *progress, 749 ICompressProgressPtr progress,
718 int *inStreamFinished, /* only for inStream version */ 750 int *inStreamFinished, /* only for inStream version */
719 CXzEncBlockInfo *blockSizes, 751 CXzEncBlockInfo *blockSizes,
720 ISzAllocPtr alloc, 752 ISzAllocPtr alloc,
@@ -731,12 +763,12 @@ static SRes Xz_CompressBlock(
731 763
732 *inStreamFinished = False; 764 *inStreamFinished = False;
733 765
734 RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig)); 766 RINOK(Lzma2WithFilters_Create(lzmaf, alloc, allocBig))
735 767
736 RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props)); 768 RINOK(Lzma2Enc_SetProps(lzmaf->lzma2, &props->lzma2Props))
737 769
738 XzBlock_ClearFlags(&block); 770 // XzBlock_ClearFlags(&block)
739 XzBlock_SetNumFilters(&block, 1 + (fp ? 1 : 0)); 771 XzBlock_ClearFlags_SetNumFilters(&block, 1 + (fp ? 1 : 0))
740 772
741 if (fp) 773 if (fp)
742 { 774 {
@@ -752,7 +784,7 @@ static SRes Xz_CompressBlock(
752 else if (fp->ipDefined) 784 else if (fp->ipDefined)
753 { 785 {
754 Byte *ptr = filter->props; 786 Byte *ptr = filter->props;
755 SetUi32(ptr, fp->ip); 787 SetUi32(ptr, fp->ip)
756 filter->propsSize = 4; 788 filter->propsSize = 4;
757 } 789 }
758 } 790 }
@@ -777,13 +809,13 @@ static SRes Xz_CompressBlock(
777 if (props->blockSize != (UInt64)(Int64)-1) 809 if (props->blockSize != (UInt64)(Int64)-1)
778 if (expectedSize > props->blockSize) 810 if (expectedSize > props->blockSize)
779 block.unpackSize = props->blockSize; 811 block.unpackSize = props->blockSize;
780 XzBlock_SetHasUnpackSize(&block); 812 XzBlock_SetHasUnpackSize(&block)
781 } 813 }
782 */ 814 */
783 815
784 if (outStream) 816 if (outStream)
785 { 817 {
786 RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); 818 RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt))
787 } 819 }
788 820
789 checkInStream.vt.Read = SeqCheckInStream_Read; 821 checkInStream.vt.Read = SeqCheckInStream_Read;
@@ -801,13 +833,13 @@ static SRes Xz_CompressBlock(
801 if (fp->id == XZ_ID_Subblock) 833 if (fp->id == XZ_ID_Subblock)
802 { 834 {
803 lzmaf->sb.inStream = &checkInStream.vt; 835 lzmaf->sb.inStream = &checkInStream.vt;
804 RINOK(SbEncInStream_Init(&lzmaf->sb)); 836 RINOK(SbEncInStream_Init(&lzmaf->sb))
805 } 837 }
806 else 838 else
807 #endif 839 #endif
808 { 840 {
809 lzmaf->filter.realStream = &checkInStream.vt; 841 lzmaf->filter.realStream = &checkInStream.vt;
810 RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc)); 842 RINOK(SeqInFilter_Init(&lzmaf->filter, filter, alloc))
811 } 843 }
812 } 844 }
813 845
@@ -841,7 +873,7 @@ static SRes Xz_CompressBlock(
841 #ifdef USE_SUBBLOCK 873 #ifdef USE_SUBBLOCK
842 (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.vt: 874 (fp->id == XZ_ID_Subblock) ? &lzmaf->sb.vt:
843 #endif 875 #endif
844 &lzmaf->filter.p) : 876 &lzmaf->filter.vt) :
845 &checkInStream.vt) : NULL, 877 &checkInStream.vt) : NULL,
846 878
847 useStream ? NULL : inBuf, 879 useStream ? NULL : inBuf,
@@ -852,7 +884,7 @@ static SRes Xz_CompressBlock(
852 if (outBuf) 884 if (outBuf)
853 seqSizeOutStream.processed += outSize; 885 seqSizeOutStream.processed += outSize;
854 886
855 RINOK(res); 887 RINOK(res)
856 blockSizes->unpackSize = checkInStream.processed; 888 blockSizes->unpackSize = checkInStream.processed;
857 } 889 }
858 { 890 {
@@ -866,7 +898,7 @@ static SRes Xz_CompressBlock(
866 buf[3] = 0; 898 buf[3] = 0;
867 899
868 SeqCheckInStream_GetDigest(&checkInStream, buf + 4); 900 SeqCheckInStream_GetDigest(&checkInStream, buf + 4);
869 RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId))); 901 RINOK(WriteBytes(&seqSizeOutStream.vt, buf + (4 - padSize), padSize + XzFlags_GetCheckSize((CXzStreamFlags)props->checkId)))
870 902
871 blockSizes->totalSize = seqSizeOutStream.processed - padSize; 903 blockSizes->totalSize = seqSizeOutStream.processed - padSize;
872 904
@@ -877,12 +909,12 @@ static SRes Xz_CompressBlock(
877 seqSizeOutStream.processed = 0; 909 seqSizeOutStream.processed = 0;
878 910
879 block.unpackSize = blockSizes->unpackSize; 911 block.unpackSize = blockSizes->unpackSize;
880 XzBlock_SetHasUnpackSize(&block); 912 XzBlock_SetHasUnpackSize(&block)
881 913
882 block.packSize = packSize; 914 block.packSize = packSize;
883 XzBlock_SetHasPackSize(&block); 915 XzBlock_SetHasPackSize(&block)
884 916
885 RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt)); 917 RINOK(XzBlock_WriteHeader(&block, &seqSizeOutStream.vt))
886 918
887 blockSizes->headerSize = (size_t)seqSizeOutStream.processed; 919 blockSizes->headerSize = (size_t)seqSizeOutStream.processed;
888 blockSizes->totalSize += seqSizeOutStream.processed; 920 blockSizes->totalSize += seqSizeOutStream.processed;
@@ -906,15 +938,15 @@ static SRes Xz_CompressBlock(
906typedef struct 938typedef struct
907{ 939{
908 ICompressProgress vt; 940 ICompressProgress vt;
909 ICompressProgress *progress; 941 ICompressProgressPtr progress;
910 UInt64 inOffset; 942 UInt64 inOffset;
911 UInt64 outOffset; 943 UInt64 outOffset;
912} CCompressProgress_XzEncOffset; 944} CCompressProgress_XzEncOffset;
913 945
914 946
915static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) 947static SRes CompressProgress_XzEncOffset_Progress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize)
916{ 948{
917 const CCompressProgress_XzEncOffset *p = CONTAINER_FROM_VTBL(pp, CCompressProgress_XzEncOffset, vt); 949 const CCompressProgress_XzEncOffset *p = Z7_CONTAINER_FROM_VTBL_CONST(pp, CCompressProgress_XzEncOffset, vt);
918 inSize += p->inOffset; 950 inSize += p->inOffset;
919 outSize += p->outOffset; 951 outSize += p->outOffset;
920 return ICompressProgress_Progress(p->progress, inSize, outSize); 952 return ICompressProgress_Progress(p->progress, inSize, outSize);
@@ -923,7 +955,7 @@ static SRes CompressProgress_XzEncOffset_Progress(const ICompressProgress *pp, U
923 955
924 956
925 957
926typedef struct 958struct CXzEnc
927{ 959{
928 ISzAllocPtr alloc; 960 ISzAllocPtr alloc;
929 ISzAllocPtr allocBig; 961 ISzAllocPtr allocBig;
@@ -933,20 +965,19 @@ typedef struct
933 965
934 CXzEncIndex xzIndex; 966 CXzEncIndex xzIndex;
935 967
936 CLzma2WithFilters lzmaf_Items[MTCODER__THREADS_MAX]; 968 CLzma2WithFilters lzmaf_Items[MTCODER_THREADS_MAX];
937 969
938 size_t outBufSize; /* size of allocated outBufs[i] */ 970 size_t outBufSize; /* size of allocated outBufs[i] */
939 Byte *outBufs[MTCODER__BLOCKS_MAX]; 971 Byte *outBufs[MTCODER_BLOCKS_MAX];
940 972
941 #ifndef _7ZIP_ST 973 #ifndef Z7_ST
942 unsigned checkType; 974 unsigned checkType;
943 ISeqOutStream *outStream; 975 ISeqOutStreamPtr outStream;
944 BoolInt mtCoder_WasConstructed; 976 BoolInt mtCoder_WasConstructed;
945 CMtCoder mtCoder; 977 CMtCoder mtCoder;
946 CXzEncBlockInfo EncBlocks[MTCODER__BLOCKS_MAX]; 978 CXzEncBlockInfo EncBlocks[MTCODER_BLOCKS_MAX];
947 #endif 979 #endif
948 980};
949} CXzEnc;
950 981
951 982
952static void XzEnc_Construct(CXzEnc *p) 983static void XzEnc_Construct(CXzEnc *p)
@@ -955,13 +986,13 @@ static void XzEnc_Construct(CXzEnc *p)
955 986
956 XzEncIndex_Construct(&p->xzIndex); 987 XzEncIndex_Construct(&p->xzIndex);
957 988
958 for (i = 0; i < MTCODER__THREADS_MAX; i++) 989 for (i = 0; i < MTCODER_THREADS_MAX; i++)
959 Lzma2WithFilters_Construct(&p->lzmaf_Items[i]); 990 Lzma2WithFilters_Construct(&p->lzmaf_Items[i]);
960 991
961 #ifndef _7ZIP_ST 992 #ifndef Z7_ST
962 p->mtCoder_WasConstructed = False; 993 p->mtCoder_WasConstructed = False;
963 { 994 {
964 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 995 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
965 p->outBufs[i] = NULL; 996 p->outBufs[i] = NULL;
966 p->outBufSize = 0; 997 p->outBufSize = 0;
967 } 998 }
@@ -972,7 +1003,7 @@ static void XzEnc_Construct(CXzEnc *p)
972static void XzEnc_FreeOutBufs(CXzEnc *p) 1003static void XzEnc_FreeOutBufs(CXzEnc *p)
973{ 1004{
974 unsigned i; 1005 unsigned i;
975 for (i = 0; i < MTCODER__BLOCKS_MAX; i++) 1006 for (i = 0; i < MTCODER_BLOCKS_MAX; i++)
976 if (p->outBufs[i]) 1007 if (p->outBufs[i])
977 { 1008 {
978 ISzAlloc_Free(p->alloc, p->outBufs[i]); 1009 ISzAlloc_Free(p->alloc, p->outBufs[i]);
@@ -988,10 +1019,10 @@ static void XzEnc_Free(CXzEnc *p, ISzAllocPtr alloc)
988 1019
989 XzEncIndex_Free(&p->xzIndex, alloc); 1020 XzEncIndex_Free(&p->xzIndex, alloc);
990 1021
991 for (i = 0; i < MTCODER__THREADS_MAX; i++) 1022 for (i = 0; i < MTCODER_THREADS_MAX; i++)
992 Lzma2WithFilters_Free(&p->lzmaf_Items[i], alloc); 1023 Lzma2WithFilters_Free(&p->lzmaf_Items[i], alloc);
993 1024
994 #ifndef _7ZIP_ST 1025 #ifndef Z7_ST
995 if (p->mtCoder_WasConstructed) 1026 if (p->mtCoder_WasConstructed)
996 { 1027 {
997 MtCoder_Destruct(&p->mtCoder); 1028 MtCoder_Destruct(&p->mtCoder);
@@ -1013,37 +1044,38 @@ CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig)
1013 p->expectedDataSize = (UInt64)(Int64)-1; 1044 p->expectedDataSize = (UInt64)(Int64)-1;
1014 p->alloc = alloc; 1045 p->alloc = alloc;
1015 p->allocBig = allocBig; 1046 p->allocBig = allocBig;
1016 return p; 1047 return (CXzEncHandle)p;
1017} 1048}
1018 1049
1050// #define GET_CXzEnc_p CXzEnc *p = (CXzEnc *)(void *)pp;
1019 1051
1020void XzEnc_Destroy(CXzEncHandle pp) 1052void XzEnc_Destroy(CXzEncHandle p)
1021{ 1053{
1022 CXzEnc *p = (CXzEnc *)pp; 1054 // GET_CXzEnc_p
1023 XzEnc_Free(p, p->alloc); 1055 XzEnc_Free(p, p->alloc);
1024 ISzAlloc_Free(p->alloc, p); 1056 ISzAlloc_Free(p->alloc, p);
1025} 1057}
1026 1058
1027 1059
1028SRes XzEnc_SetProps(CXzEncHandle pp, const CXzProps *props) 1060SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props)
1029{ 1061{
1030 CXzEnc *p = (CXzEnc *)pp; 1062 // GET_CXzEnc_p
1031 p->xzProps = *props; 1063 p->xzProps = *props;
1032 XzProps_Normalize(&p->xzProps); 1064 XzProps_Normalize(&p->xzProps);
1033 return SZ_OK; 1065 return SZ_OK;
1034} 1066}
1035 1067
1036 1068
1037void XzEnc_SetDataSize(CXzEncHandle pp, UInt64 expectedDataSiize) 1069void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize)
1038{ 1070{
1039 CXzEnc *p = (CXzEnc *)pp; 1071 // GET_CXzEnc_p
1040 p->expectedDataSize = expectedDataSiize; 1072 p->expectedDataSize = expectedDataSiize;
1041} 1073}
1042 1074
1043 1075
1044 1076
1045 1077
1046#ifndef _7ZIP_ST 1078#ifndef Z7_ST
1047 1079
1048static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex, 1080static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBufIndex,
1049 const Byte *src, size_t srcSize, int finished) 1081 const Byte *src, size_t srcSize, int finished)
@@ -1073,7 +1105,7 @@ static SRes XzEnc_MtCallback_Code(void *pp, unsigned coderIndex, unsigned outBuf
1073 1105
1074 MtProgressThunk_CreateVTable(&progressThunk); 1106 MtProgressThunk_CreateVTable(&progressThunk);
1075 progressThunk.mtProgress = &me->mtCoder.mtProgress; 1107 progressThunk.mtProgress = &me->mtCoder.mtProgress;
1076 MtProgressThunk_Init(&progressThunk); 1108 MtProgressThunk_INIT(&progressThunk)
1077 1109
1078 { 1110 {
1079 CXzEncBlockInfo blockSizes; 1111 CXzEncBlockInfo blockSizes;
@@ -1112,11 +1144,11 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex)
1112 const CXzEncBlockInfo *bInfo = &me->EncBlocks[outBufIndex]; 1144 const CXzEncBlockInfo *bInfo = &me->EncBlocks[outBufIndex];
1113 const Byte *data = me->outBufs[outBufIndex]; 1145 const Byte *data = me->outBufs[outBufIndex];
1114 1146
1115 RINOK(WriteBytes(me->outStream, data, bInfo->headerSize)); 1147 RINOK(WriteBytes(me->outStream, data, bInfo->headerSize))
1116 1148
1117 { 1149 {
1118 UInt64 totalPackFull = bInfo->totalSize + XZ_GET_PAD_SIZE(bInfo->totalSize); 1150 UInt64 totalPackFull = bInfo->totalSize + XZ_GET_PAD_SIZE(bInfo->totalSize);
1119 RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize)); 1151 RINOK(WriteBytes(me->outStream, data + XZ_BLOCK_HEADER_SIZE_MAX, (size_t)totalPackFull - bInfo->headerSize))
1120 } 1152 }
1121 1153
1122 return XzEncIndex_AddIndexRecord(&me->xzIndex, bInfo->unpackSize, bInfo->totalSize, me->alloc); 1154 return XzEncIndex_AddIndexRecord(&me->xzIndex, bInfo->unpackSize, bInfo->totalSize, me->alloc);
@@ -1126,9 +1158,9 @@ static SRes XzEnc_MtCallback_Write(void *pp, unsigned outBufIndex)
1126 1158
1127 1159
1128 1160
1129SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress) 1161SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress)
1130{ 1162{
1131 CXzEnc *p = (CXzEnc *)pp; 1163 // GET_CXzEnc_p
1132 1164
1133 const CXzProps *props = &p->xzProps; 1165 const CXzProps *props = &p->xzProps;
1134 1166
@@ -1137,7 +1169,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1137 UInt64 numBlocks = 1; 1169 UInt64 numBlocks = 1;
1138 UInt64 blockSize = props->blockSize; 1170 UInt64 blockSize = props->blockSize;
1139 1171
1140 if (blockSize != XZ_PROPS__BLOCK_SIZE__SOLID 1172 if (blockSize != XZ_PROPS_BLOCK_SIZE_SOLID
1141 && props->reduceSize != (UInt64)(Int64)-1) 1173 && props->reduceSize != (UInt64)(Int64)-1)
1142 { 1174 {
1143 numBlocks = props->reduceSize / blockSize; 1175 numBlocks = props->reduceSize / blockSize;
@@ -1147,13 +1179,13 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1147 else 1179 else
1148 blockSize = (UInt64)1 << 62; 1180 blockSize = (UInt64)1 << 62;
1149 1181
1150 RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc)); 1182 RINOK(XzEncIndex_PreAlloc(&p->xzIndex, numBlocks, blockSize, XZ_GET_ESTIMATED_BLOCK_TOTAL_PACK_SIZE(blockSize), p->alloc))
1151 } 1183 }
1152 1184
1153 RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream)); 1185 RINOK(Xz_WriteHeader((CXzStreamFlags)props->checkId, outStream))
1154 1186
1155 1187
1156 #ifndef _7ZIP_ST 1188 #ifndef Z7_ST
1157 if (props->numBlockThreads_Reduced > 1) 1189 if (props->numBlockThreads_Reduced > 1)
1158 { 1190 {
1159 IMtCoderCallback2 vt; 1191 IMtCoderCallback2 vt;
@@ -1180,8 +1212,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1180 p->mtCoder.mtCallback = &vt; 1212 p->mtCoder.mtCallback = &vt;
1181 p->mtCoder.mtCallbackObject = p; 1213 p->mtCoder.mtCallbackObject = p;
1182 1214
1183 if ( props->blockSize == XZ_PROPS__BLOCK_SIZE__SOLID 1215 if ( props->blockSize == XZ_PROPS_BLOCK_SIZE_SOLID
1184 || props->blockSize == XZ_PROPS__BLOCK_SIZE__AUTO) 1216 || props->blockSize == XZ_PROPS_BLOCK_SIZE_AUTO)
1185 return SZ_ERROR_FAIL; 1217 return SZ_ERROR_FAIL;
1186 1218
1187 p->mtCoder.blockSize = (size_t)props->blockSize; 1219 p->mtCoder.blockSize = (size_t)props->blockSize;
@@ -1200,7 +1232,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1200 p->mtCoder.numThreadsMax = (unsigned)props->numBlockThreads_Max; 1232 p->mtCoder.numThreadsMax = (unsigned)props->numBlockThreads_Max;
1201 p->mtCoder.expectedDataSize = p->expectedDataSize; 1233 p->mtCoder.expectedDataSize = p->expectedDataSize;
1202 1234
1203 RINOK(MtCoder_Code(&p->mtCoder)); 1235 RINOK(MtCoder_Code(&p->mtCoder))
1204 } 1236 }
1205 else 1237 else
1206 #endif 1238 #endif
@@ -1217,7 +1249,7 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1217 1249
1218 writeStartSizes = 0; 1250 writeStartSizes = 0;
1219 1251
1220 if (props->blockSize != XZ_PROPS__BLOCK_SIZE__SOLID) 1252 if (props->blockSize != XZ_PROPS_BLOCK_SIZE_SOLID)
1221 { 1253 {
1222 writeStartSizes = (props->forceWriteSizesInHeader > 0); 1254 writeStartSizes = (props->forceWriteSizesInHeader > 0);
1223 1255
@@ -1274,18 +1306,18 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1274 &inStreamFinished, 1306 &inStreamFinished,
1275 &blockSizes, 1307 &blockSizes,
1276 p->alloc, 1308 p->alloc,
1277 p->allocBig)); 1309 p->allocBig))
1278 1310
1279 { 1311 {
1280 UInt64 totalPackFull = blockSizes.totalSize + XZ_GET_PAD_SIZE(blockSizes.totalSize); 1312 UInt64 totalPackFull = blockSizes.totalSize + XZ_GET_PAD_SIZE(blockSizes.totalSize);
1281 1313
1282 if (writeStartSizes) 1314 if (writeStartSizes)
1283 { 1315 {
1284 RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize)); 1316 RINOK(WriteBytes(outStream, p->outBufs[0], blockSizes.headerSize))
1285 RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize)); 1317 RINOK(WriteBytes(outStream, bufData, (size_t)totalPackFull - blockSizes.headerSize))
1286 } 1318 }
1287 1319
1288 RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc)); 1320 RINOK(XzEncIndex_AddIndexRecord(&p->xzIndex, blockSizes.unpackSize, blockSizes.totalSize, p->alloc))
1289 1321
1290 progress2.inOffset += blockSizes.unpackSize; 1322 progress2.inOffset += blockSizes.unpackSize;
1291 progress2.outOffset += totalPackFull; 1323 progress2.outOffset += totalPackFull;
@@ -1302,8 +1334,8 @@ SRes XzEnc_Encode(CXzEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStr
1302 1334
1303#include "Alloc.h" 1335#include "Alloc.h"
1304 1336
1305SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, 1337SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream,
1306 const CXzProps *props, ICompressProgress *progress) 1338 const CXzProps *props, ICompressProgressPtr progress)
1307{ 1339{
1308 SRes res; 1340 SRes res;
1309 CXzEncHandle xz = XzEnc_Create(&g_Alloc, &g_BigAlloc); 1341 CXzEncHandle xz = XzEnc_Create(&g_Alloc, &g_BigAlloc);
@@ -1317,7 +1349,7 @@ SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream,
1317} 1349}
1318 1350
1319 1351
1320SRes Xz_EncodeEmpty(ISeqOutStream *outStream) 1352SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream)
1321{ 1353{
1322 SRes res; 1354 SRes res;
1323 CXzEncIndex xzIndex; 1355 CXzEncIndex xzIndex;
diff --git a/C/XzEnc.h b/C/XzEnc.h
index 0c29e7e..77b78c0 100644
--- a/C/XzEnc.h
+++ b/C/XzEnc.h
@@ -1,8 +1,8 @@
1/* XzEnc.h -- Xz Encode 1/* XzEnc.h -- Xz Encode
22017-06-27 : Igor Pavlov : Public domain */ 22023-04-13 : Igor Pavlov : Public domain */
3 3
4#ifndef __XZ_ENC_H 4#ifndef ZIP7_INC_XZ_ENC_H
5#define __XZ_ENC_H 5#define ZIP7_INC_XZ_ENC_H
6 6
7#include "Lzma2Enc.h" 7#include "Lzma2Enc.h"
8 8
@@ -11,8 +11,8 @@
11EXTERN_C_BEGIN 11EXTERN_C_BEGIN
12 12
13 13
14#define XZ_PROPS__BLOCK_SIZE__AUTO LZMA2_ENC_PROPS__BLOCK_SIZE__AUTO 14#define XZ_PROPS_BLOCK_SIZE_AUTO LZMA2_ENC_PROPS_BLOCK_SIZE_AUTO
15#define XZ_PROPS__BLOCK_SIZE__SOLID LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID 15#define XZ_PROPS_BLOCK_SIZE_SOLID LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID
16 16
17 17
18typedef struct 18typedef struct
@@ -41,19 +41,20 @@ typedef struct
41 41
42void XzProps_Init(CXzProps *p); 42void XzProps_Init(CXzProps *p);
43 43
44 44typedef struct CXzEnc CXzEnc;
45typedef void * CXzEncHandle; 45typedef CXzEnc * CXzEncHandle;
46// Z7_DECLARE_HANDLE(CXzEncHandle)
46 47
47CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig); 48CXzEncHandle XzEnc_Create(ISzAllocPtr alloc, ISzAllocPtr allocBig);
48void XzEnc_Destroy(CXzEncHandle p); 49void XzEnc_Destroy(CXzEncHandle p);
49SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props); 50SRes XzEnc_SetProps(CXzEncHandle p, const CXzProps *props);
50void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize); 51void XzEnc_SetDataSize(CXzEncHandle p, UInt64 expectedDataSiize);
51SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress); 52SRes XzEnc_Encode(CXzEncHandle p, ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream, ICompressProgressPtr progress);
52 53
53SRes Xz_Encode(ISeqOutStream *outStream, ISeqInStream *inStream, 54SRes Xz_Encode(ISeqOutStreamPtr outStream, ISeqInStreamPtr inStream,
54 const CXzProps *props, ICompressProgress *progress); 55 const CXzProps *props, ICompressProgressPtr progress);
55 56
56SRes Xz_EncodeEmpty(ISeqOutStream *outStream); 57SRes Xz_EncodeEmpty(ISeqOutStreamPtr outStream);
57 58
58EXTERN_C_END 59EXTERN_C_END
59 60
diff --git a/C/XzIn.c b/C/XzIn.c
index 84f868e..d0fc763 100644
--- a/C/XzIn.c
+++ b/C/XzIn.c
@@ -1,5 +1,5 @@
1/* XzIn.c - Xz input 1/* XzIn.c - Xz input
22021-09-04 : Igor Pavlov : Public domain */ 22023-04-02 : Igor Pavlov : Public domain */
3 3
4#include "Precomp.h" 4#include "Precomp.h"
5 5
@@ -15,11 +15,13 @@
15#define XZ_FOOTER_SIG_CHECK(p) ((p)[0] == XZ_FOOTER_SIG_0 && (p)[1] == XZ_FOOTER_SIG_1) 15#define XZ_FOOTER_SIG_CHECK(p) ((p)[0] == XZ_FOOTER_SIG_0 && (p)[1] == XZ_FOOTER_SIG_1)
16 16
17 17
18SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream) 18SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStreamPtr inStream)
19{ 19{
20 Byte sig[XZ_STREAM_HEADER_SIZE]; 20 Byte sig[XZ_STREAM_HEADER_SIZE];
21 RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE)); 21 size_t processedSize = XZ_STREAM_HEADER_SIZE;
22 if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0) 22 RINOK(SeqInStream_ReadMax(inStream, sig, &processedSize))
23 if (processedSize != XZ_STREAM_HEADER_SIZE
24 || memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0)
23 return SZ_ERROR_NO_ARCHIVE; 25 return SZ_ERROR_NO_ARCHIVE;
24 return Xz_ParseHeader(p, sig); 26 return Xz_ParseHeader(p, sig);
25} 27}
@@ -29,12 +31,12 @@ SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream)
29 if (s == 0) return SZ_ERROR_ARCHIVE; \ 31 if (s == 0) return SZ_ERROR_ARCHIVE; \
30 pos += s; } 32 pos += s; }
31 33
32SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, UInt32 *headerSizeRes) 34SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStreamPtr inStream, BoolInt *isIndex, UInt32 *headerSizeRes)
33{ 35{
34 Byte header[XZ_BLOCK_HEADER_SIZE_MAX]; 36 Byte header[XZ_BLOCK_HEADER_SIZE_MAX];
35 unsigned headerSize; 37 unsigned headerSize;
36 *headerSizeRes = 0; 38 *headerSizeRes = 0;
37 RINOK(SeqInStream_ReadByte(inStream, &header[0])); 39 RINOK(SeqInStream_ReadByte(inStream, &header[0]))
38 headerSize = (unsigned)header[0]; 40 headerSize = (unsigned)header[0];
39 if (headerSize == 0) 41 if (headerSize == 0)
40 { 42 {
@@ -46,7 +48,12 @@ SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, BoolInt *isIndex, U
46 *isIndex = False; 48 *isIndex = False;
47 headerSize = (headerSize << 2) + 4; 49 headerSize = (headerSize << 2) + 4;
48 *headerSizeRes = headerSize; 50 *headerSizeRes = headerSize;
49 RINOK(SeqInStream_Read(inStream, header + 1, headerSize - 1)); 51 {
52 size_t processedSize = headerSize - 1;
53 RINOK(SeqInStream_ReadMax(inStream, header + 1, &processedSize))
54 if (processedSize != headerSize - 1)
55 return SZ_ERROR_INPUT_EOF;
56 }
50 return XzBlock_Parse(p, header); 57 return XzBlock_Parse(p, header);
51} 58}
52 59
@@ -58,7 +65,9 @@ UInt64 Xz_GetUnpackSize(const CXzStream *p)
58 UInt64 size = 0; 65 UInt64 size = 0;
59 size_t i; 66 size_t i;
60 for (i = 0; i < p->numBlocks; i++) 67 for (i = 0; i < p->numBlocks; i++)
61 ADD_SIZE_CHECK(size, p->blocks[i].unpackSize); 68 {
69 ADD_SIZE_CHECK(size, p->blocks[i].unpackSize)
70 }
62 return size; 71 return size;
63} 72}
64 73
@@ -67,12 +76,14 @@ UInt64 Xz_GetPackSize(const CXzStream *p)
67 UInt64 size = 0; 76 UInt64 size = 0;
68 size_t i; 77 size_t i;
69 for (i = 0; i < p->numBlocks; i++) 78 for (i = 0; i < p->numBlocks; i++)
70 ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3); 79 {
80 ADD_SIZE_CHECK(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3)
81 }
71 return size; 82 return size;
72} 83}
73 84
74/* 85/*
75SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream) 86SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStreamPtr inStream)
76{ 87{
77 return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f)); 88 return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f));
78} 89}
@@ -93,7 +104,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt
93 104
94 { 105 {
95 UInt64 numBlocks64; 106 UInt64 numBlocks64;
96 READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64); 107 READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64)
97 numBlocks = (size_t)numBlocks64; 108 numBlocks = (size_t)numBlocks64;
98 if (numBlocks != numBlocks64 || numBlocks * 2 > size) 109 if (numBlocks != numBlocks64 || numBlocks * 2 > size)
99 return SZ_ERROR_ARCHIVE; 110 return SZ_ERROR_ARCHIVE;
@@ -110,8 +121,8 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt
110 for (i = 0; i < numBlocks; i++) 121 for (i = 0; i < numBlocks; i++)
111 { 122 {
112 CXzBlockSizes *block = &p->blocks[i]; 123 CXzBlockSizes *block = &p->blocks[i];
113 READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize); 124 READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize)
114 READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize); 125 READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize)
115 if (block->totalSize == 0) 126 if (block->totalSize == 0)
116 return SZ_ERROR_ARCHIVE; 127 return SZ_ERROR_ARCHIVE;
117 } 128 }
@@ -122,7 +133,7 @@ static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAllocPt
122 return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE; 133 return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE;
123} 134}
124 135
125static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAllocPtr alloc) 136static SRes Xz_ReadIndex(CXzStream *p, ILookInStreamPtr stream, UInt64 indexSize, ISzAllocPtr alloc)
126{ 137{
127 SRes res; 138 SRes res;
128 size_t size; 139 size_t size;
@@ -142,14 +153,14 @@ static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize,
142 return res; 153 return res;
143} 154}
144 155
145static SRes LookInStream_SeekRead_ForArc(ILookInStream *stream, UInt64 offset, void *buf, size_t size) 156static SRes LookInStream_SeekRead_ForArc(ILookInStreamPtr stream, UInt64 offset, void *buf, size_t size)
146{ 157{
147 RINOK(LookInStream_SeekTo(stream, offset)); 158 RINOK(LookInStream_SeekTo(stream, offset))
148 return LookInStream_Read(stream, buf, size); 159 return LookInStream_Read(stream, buf, size);
149 /* return LookInStream_Read2(stream, buf, size, SZ_ERROR_NO_ARCHIVE); */ 160 /* return LookInStream_Read2(stream, buf, size, SZ_ERROR_NO_ARCHIVE); */
150} 161}
151 162
152static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAllocPtr alloc) 163static SRes Xz_ReadBackward(CXzStream *p, ILookInStreamPtr stream, Int64 *startOffset, ISzAllocPtr alloc)
153{ 164{
154 UInt64 indexSize; 165 UInt64 indexSize;
155 Byte buf[XZ_STREAM_FOOTER_SIZE]; 166 Byte buf[XZ_STREAM_FOOTER_SIZE];
@@ -159,7 +170,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
159 return SZ_ERROR_NO_ARCHIVE; 170 return SZ_ERROR_NO_ARCHIVE;
160 171
161 pos -= XZ_STREAM_FOOTER_SIZE; 172 pos -= XZ_STREAM_FOOTER_SIZE;
162 RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); 173 RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE))
163 174
164 if (!XZ_FOOTER_SIG_CHECK(buf + 10)) 175 if (!XZ_FOOTER_SIG_CHECK(buf + 10))
165 { 176 {
@@ -174,7 +185,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
174 185
175 i = (pos > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)pos; 186 i = (pos > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)pos;
176 pos -= i; 187 pos -= i;
177 RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i)); 188 RINOK(LookInStream_SeekRead_ForArc(stream, pos, temp, i))
178 total += (UInt32)i; 189 total += (UInt32)i;
179 for (; i != 0; i--) 190 for (; i != 0; i--)
180 if (temp[i - 1] != 0) 191 if (temp[i - 1] != 0)
@@ -193,7 +204,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
193 if (pos < XZ_STREAM_FOOTER_SIZE) 204 if (pos < XZ_STREAM_FOOTER_SIZE)
194 return SZ_ERROR_NO_ARCHIVE; 205 return SZ_ERROR_NO_ARCHIVE;
195 pos -= XZ_STREAM_FOOTER_SIZE; 206 pos -= XZ_STREAM_FOOTER_SIZE;
196 RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE)); 207 RINOK(LookInStream_SeekRead_ForArc(stream, pos, buf, XZ_STREAM_FOOTER_SIZE))
197 if (!XZ_FOOTER_SIG_CHECK(buf + 10)) 208 if (!XZ_FOOTER_SIG_CHECK(buf + 10))
198 return SZ_ERROR_NO_ARCHIVE; 209 return SZ_ERROR_NO_ARCHIVE;
199 } 210 }
@@ -217,8 +228,8 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
217 return SZ_ERROR_ARCHIVE; 228 return SZ_ERROR_ARCHIVE;
218 229
219 pos -= indexSize; 230 pos -= indexSize;
220 RINOK(LookInStream_SeekTo(stream, pos)); 231 RINOK(LookInStream_SeekTo(stream, pos))
221 RINOK(Xz_ReadIndex(p, stream, indexSize, alloc)); 232 RINOK(Xz_ReadIndex(p, stream, indexSize, alloc))
222 233
223 { 234 {
224 UInt64 totalSize = Xz_GetPackSize(p); 235 UInt64 totalSize = Xz_GetPackSize(p);
@@ -227,7 +238,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
227 || pos < totalSize + XZ_STREAM_HEADER_SIZE) 238 || pos < totalSize + XZ_STREAM_HEADER_SIZE)
228 return SZ_ERROR_ARCHIVE; 239 return SZ_ERROR_ARCHIVE;
229 pos -= (totalSize + XZ_STREAM_HEADER_SIZE); 240 pos -= (totalSize + XZ_STREAM_HEADER_SIZE);
230 RINOK(LookInStream_SeekTo(stream, pos)); 241 RINOK(LookInStream_SeekTo(stream, pos))
231 *startOffset = (Int64)pos; 242 *startOffset = (Int64)pos;
232 } 243 }
233 { 244 {
@@ -236,7 +247,7 @@ static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOff
236 SecToRead_CreateVTable(&secToRead); 247 SecToRead_CreateVTable(&secToRead);
237 secToRead.realStream = stream; 248 secToRead.realStream = stream;
238 249
239 RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt)); 250 RINOK(Xz_ReadHeader(&headerFlags, &secToRead.vt))
240 return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE; 251 return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE;
241 } 252 }
242} 253}
@@ -274,7 +285,9 @@ UInt64 Xzs_GetUnpackSize(const CXzs *p)
274 UInt64 size = 0; 285 UInt64 size = 0;
275 size_t i; 286 size_t i;
276 for (i = 0; i < p->num; i++) 287 for (i = 0; i < p->num; i++)
277 ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i])); 288 {
289 ADD_SIZE_CHECK(size, Xz_GetUnpackSize(&p->streams[i]))
290 }
278 return size; 291 return size;
279} 292}
280 293
@@ -284,15 +297,17 @@ UInt64 Xzs_GetPackSize(const CXzs *p)
284 UInt64 size = 0; 297 UInt64 size = 0;
285 size_t i; 298 size_t i;
286 for (i = 0; i < p->num; i++) 299 for (i = 0; i < p->num; i++)
287 ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i])); 300 {
301 ADD_SIZE_CHECK(size, Xz_GetTotalSize(&p->streams[i]))
302 }
288 return size; 303 return size;
289} 304}
290*/ 305*/
291 306
292SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAllocPtr alloc) 307SRes Xzs_ReadBackward(CXzs *p, ILookInStreamPtr stream, Int64 *startOffset, ICompressProgressPtr progress, ISzAllocPtr alloc)
293{ 308{
294 Int64 endOffset = 0; 309 Int64 endOffset = 0;
295 RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END)); 310 RINOK(ILookInStream_Seek(stream, &endOffset, SZ_SEEK_END))
296 *startOffset = endOffset; 311 *startOffset = endOffset;
297 for (;;) 312 for (;;)
298 { 313 {
@@ -301,7 +316,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr
301 Xz_Construct(&st); 316 Xz_Construct(&st);
302 res = Xz_ReadBackward(&st, stream, startOffset, alloc); 317 res = Xz_ReadBackward(&st, stream, startOffset, alloc);
303 st.startOffset = (UInt64)*startOffset; 318 st.startOffset = (UInt64)*startOffset;
304 RINOK(res); 319 RINOK(res)
305 if (p->num == p->numAllocated) 320 if (p->num == p->numAllocated)
306 { 321 {
307 const size_t newNum = p->num + p->num / 4 + 1; 322 const size_t newNum = p->num + p->num / 4 + 1;
@@ -317,7 +332,7 @@ SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompr
317 p->streams[p->num++] = st; 332 p->streams[p->num++] = st;
318 if (*startOffset == 0) 333 if (*startOffset == 0)
319 break; 334 break;
320 RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset)); 335 RINOK(LookInStream_SeekTo(stream, (UInt64)*startOffset))
321 if (progress && ICompressProgress_Progress(progress, (UInt64)(endOffset - *startOffset), (UInt64)(Int64)-1) != SZ_OK) 336 if (progress && ICompressProgress_Progress(progress, (UInt64)(endOffset - *startOffset), (UInt64)(Int64)-1) != SZ_OK)
322 return SZ_ERROR_PROGRESS; 337 return SZ_ERROR_PROGRESS;
323 } 338 }
diff --git a/C/warn_clang.mak b/C/warn_clang.mak
index ed4f908..0d6446d 100644
--- a/C/warn_clang.mak
+++ b/C/warn_clang.mak
@@ -1,37 +1 @@
1CFLAGS_WARN_CLANG_3_8_UNIQ = \ CFLAGS_WARN = -Weverything -Wfatal-errors
2 -Wno-reserved-id-macro \
3 -Wno-old-style-cast \
4 -Wno-c++11-long-long \
5 -Wno-unused-macros \
6
7CFLAGS_WARN_CLANG_3_8 = \
8 $(CFLAGS_WARN_CLANG_3_8_UNIQ) \
9 -Weverything \
10 -Wno-extra-semi \
11 -Wno-sign-conversion \
12 -Wno-language-extension-token \
13 -Wno-global-constructors \
14 -Wno-non-virtual-dtor \
15 -Wno-switch-enum \
16 -Wno-covered-switch-default \
17 -Wno-cast-qual \
18 -Wno-padded \
19 -Wno-exit-time-destructors \
20 -Wno-weak-vtables \
21
22CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \
23 -Wno-extra-semi-stmt \
24 -Wno-zero-as-null-pointer-constant \
25 -Wno-deprecated-dynamic-exception-spec \
26 -Wno-c++98-compat-pedantic \
27 -Wno-atomic-implicit-seq-cst \
28 -Wconversion \
29 -Wno-sign-conversion \
30
31CFLAGS_WARN_1 = \
32 -Wno-deprecated-copy-dtor \
33
34
35
36
37CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_1)
diff --git a/C/warn_clang_mac.mak b/C/warn_clang_mac.mak
index 41044a2..44afc53 100644
--- a/C/warn_clang_mac.mak
+++ b/C/warn_clang_mac.mak
@@ -1,37 +1 @@
1CFLAGS_WARN_CLANG_3_8_UNIQ = \ CFLAGS_WARN = -Weverything -Wfatal-errors -Wno-poison-system-directories
2 -Wno-reserved-id-macro \
3 -Wno-old-style-cast \
4 -Wno-c++11-long-long \
5 -Wno-unused-macros \
6
7CFLAGS_WARN_CLANG_3_8 = \
8 $(CFLAGS_WARN_CLANG_3_8_UNIQ) \
9 -Weverything \
10 -Wno-extra-semi \
11 -Wno-sign-conversion \
12 -Wno-language-extension-token \
13 -Wno-global-constructors \
14 -Wno-non-virtual-dtor \
15 -Wno-switch-enum \
16 -Wno-covered-switch-default \
17 -Wno-cast-qual \
18 -Wno-padded \
19 -Wno-exit-time-destructors \
20 -Wno-weak-vtables \
21
22CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \
23 -Wno-extra-semi-stmt \
24 -Wno-zero-as-null-pointer-constant \
25 -Wno-deprecated-dynamic-exception-spec \
26 -Wno-c++98-compat-pedantic \
27 -Wno-atomic-implicit-seq-cst \
28 -Wconversion \
29 -Wno-sign-conversion \
30
31CFLAGS_WARN_MAC = \
32 -Wno-poison-system-directories \
33 -Wno-c++11-long-long \
34 -Wno-atomic-implicit-seq-cst \
35
36
37CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_MAC)
diff --git a/CPP/7zip/7zip.mak b/CPP/7zip/7zip.mak
index 7fbe2ad..6f4a0a1 100644
--- a/CPP/7zip/7zip.mak
+++ b/CPP/7zip/7zip.mak
@@ -5,14 +5,14 @@ OBJS = \
5 $(WIN_OBJS) \ 5 $(WIN_OBJS) \
6 $(WIN_CTRL_OBJS) \ 6 $(WIN_CTRL_OBJS) \
7 $(7ZIP_COMMON_OBJS) \ 7 $(7ZIP_COMMON_OBJS) \
8 $(AR_OBJS) \
9 $(AR_COMMON_OBJS) \
10 $(UI_COMMON_OBJS) \ 8 $(UI_COMMON_OBJS) \
11 $(AGENT_OBJS) \ 9 $(AGENT_OBJS) \
12 $(CONSOLE_OBJS) \ 10 $(CONSOLE_OBJS) \
13 $(EXPLORER_OBJS) \ 11 $(EXPLORER_OBJS) \
14 $(FM_OBJS) \ 12 $(FM_OBJS) \
15 $(GUI_OBJS) \ 13 $(GUI_OBJS) \
14 $(AR_COMMON_OBJS) \
15 $(AR_OBJS) \
16 $(7Z_OBJS) \ 16 $(7Z_OBJS) \
17 $(CAB_OBJS) \ 17 $(CAB_OBJS) \
18 $(CHM_OBJS) \ 18 $(CHM_OBJS) \
diff --git a/CPP/7zip/7zip_gcc.mak b/CPP/7zip/7zip_gcc.mak
index f65cff2..8bf0594 100644
--- a/CPP/7zip/7zip_gcc.mak
+++ b/CPP/7zip/7zip_gcc.mak
@@ -12,23 +12,35 @@ ifdef USE_JWASM
12MY_ASM = jwasm 12MY_ASM = jwasm
13endif 13endif
14 14
15ifndef RC
16RC=windres.exe --target=pe-x86-64
17RC=windres.exe -F pe-i386
18RC=windres.exe
19endif
20
15 21
16PROGPATH = $(O)/$(PROG) 22PROGPATH = $(O)/$(PROG)
17PROGPATH_STATIC = $(O)/$(PROG)s 23PROGPATH_STATIC = $(O)/$(PROG)s
18 24
19 25
20ifneq ($(CC), xlc) 26ifneq ($(CC), xlc)
21CFLAGS_WARN_WALL = -Wall -Werror -Wextra 27CFLAGS_WARN_WALL = -Werror -Wall -Wextra
22endif 28endif
23 29
24# for object file 30# for object file
31# -Wa,-aln=test.s
32# -save-temps
25CFLAGS_BASE_LIST = -c 33CFLAGS_BASE_LIST = -c
26# CFLAGS_BASE_LIST = -S 34# CFLAGS_BASE_LIST = -S
27CFLAGS_BASE = -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \ 35CFLAGS_BASE = -O2 $(CFLAGS_BASE_LIST) $(CFLAGS_WARN_WALL) $(CFLAGS_WARN) \
28 -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE \ 36 -DNDEBUG -D_REENTRANT -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE \
29 -fPIC 37 -fPIC
30 38
31# -D_7ZIP_AFFINITY_DISABLE 39FLAGS_FLTO = -ffunction-sections
40FLAGS_FLTO = -flto
41FLAGS_FLTO =
42#
43# -DZ7_AFFINITY_DISABLE
32 44
33 45
34ifdef SystemDrive 46ifdef SystemDrive
@@ -83,8 +95,7 @@ endif
83else 95else
84 96
85LDFLAGS = $(LDFLAGS_STATIC) 97LDFLAGS = $(LDFLAGS_STATIC)
86# -s is not required for clang, do we need it for GGC ??? 98# -s is not required for clang, do we need it for GCC ???
87# -s
88 99
89#-static -static-libgcc -static-libstdc++ 100#-static -static-libgcc -static-libstdc++
90 101
@@ -113,7 +124,7 @@ MY_MKDIR=mkdir
113DEL_OBJ_EXE = -$(RM) $(O)\*.o $(O)\$(PROG).exe $(O)\$(PROG).dll 124DEL_OBJ_EXE = -$(RM) $(O)\*.o $(O)\$(PROG).exe $(O)\$(PROG).dll
114endif 125endif
115 126
116LIB2_GUI = -lOle32 -lGdi32 -lComctl32 -lComdlg32 $(LIB_HTMLHELP) 127LIB2_GUI = -lOle32 -lGdi32 -lComctl32 -lComdlg32 -lShell32 $(LIB_HTMLHELP)
117LIB2 = -loleaut32 -luuid -ladvapi32 -lUser32 $(LIB2_GUI) 128LIB2 = -loleaut32 -luuid -ladvapi32 -lUser32 $(LIB2_GUI)
118 129
119CXXFLAGS_EXTRA = -DUNICODE -D_UNICODE 130CXXFLAGS_EXTRA = -DUNICODE -D_UNICODE
@@ -126,7 +137,7 @@ RM = rm -f
126MY_MKDIR=mkdir -p 137MY_MKDIR=mkdir -p
127DEL_OBJ_EXE = -$(RM) $(PROGPATH) $(PROGPATH_STATIC) $(OBJS) 138DEL_OBJ_EXE = -$(RM) $(PROGPATH) $(PROGPATH_STATIC) $(OBJS)
128 139
129# CFLAGS_BASE := $(CFLAGS_BASE) -D_7ZIP_ST 140# CFLAGS_BASE := $(CFLAGS_BASE) -DZ7_ST
130# CXXFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE 141# CXXFLAGS_EXTRA = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE
131 142
132# LOCAL_LIBS=-lpthread 143# LOCAL_LIBS=-lpthread
@@ -138,7 +149,7 @@ endif
138 149
139 150
140 151
141CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(CC_SHARED) -o $@ 152CFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CC_SHARED) -o $@
142 153
143 154
144ifdef IS_MINGW 155ifdef IS_MINGW
@@ -170,7 +181,7 @@ endif # IS_MINGW
170 181
171 182
172ifdef USE_ASM 183ifdef USE_ASM
173CONSOLE_ASM_FLAGS=-D_7ZIP_ASM 184CONSOLE_ASM_FLAGS=-DZ7_7ZIP_ASM
174else 185else
175CONSOLE_ASM_FLAGS= 186CONSOLE_ASM_FLAGS=
176endif 187endif
@@ -179,7 +190,7 @@ CXX_WARN_FLAGS =
179#-Wno-invalid-offsetof 190#-Wno-invalid-offsetof
180#-Wno-reorder 191#-Wno-reorder
181 192
182CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(CXXFLAGS_EXTRA) $(CC_SHARED) -o $@ $(CXX_WARN_FLAGS) 193CXXFLAGS = $(MY_ARCH_2) $(LOCAL_FLAGS) $(CXXFLAGS_BASE2) $(CFLAGS_BASE) $(FLAGS_FLTO) $(CXXFLAGS_EXTRA) $(CC_SHARED) $(CXX_WARN_FLAGS) $(CXX_STD_FLAGS) -o $@
183 194
184STATIC_TARGET= 195STATIC_TARGET=
185ifdef COMPL_STATIC 196ifdef COMPL_STATIC
@@ -192,7 +203,20 @@ all: $(O) $(PROGPATH) $(STATIC_TARGET)
192$(O): 203$(O):
193 $(MY_MKDIR) $(O) 204 $(MY_MKDIR) $(O)
194 205
195LFLAGS_ALL = -s $(MY_ARCH_2) $(LDFLAGS) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2) 206# LDFLAGS3= -flto
207# LDFLAGS3= -Wl,--gc-sections
208# -Wl,--print-gc-sections
209
210ifneq ($(CC), $(CROSS_COMPILE)clang)
211LFLAGS_STRIP = -s
212endif
213
214LFLAGS_ALL = $(LFLAGS_STRIP) $(MY_ARCH_2) $(LDFLAGS) $(FLAGS_FLTO) $(LD_arch) $(OBJS) $(MY_LIBS) $(LIB2)
215
216# -s : GCC : Remove all symbol table and relocation information from the executable.
217# -s : CLANG : unsupported
218# -s
219
196$(PROGPATH): $(OBJS) 220$(PROGPATH): $(OBJS)
197 $(CXX) -o $(PROGPATH) $(LFLAGS_ALL) 221 $(CXX) -o $(PROGPATH) $(LFLAGS_ALL)
198 222
@@ -206,7 +230,14 @@ $(PROGPATH_STATIC): $(OBJS)
206 230
207ifndef NO_DEFAULT_RES 231ifndef NO_DEFAULT_RES
208$O/resource.o: resource.rc 232$O/resource.o: resource.rc
209 windres.exe $(RFLAGS) resource.rc $O/resource.o 233 $(RC) $(RFLAGS) resource.rc $@
234
235# windres.exe : in old version mingw:
236# $(RFLAGS) resource.rc $O/resource.o
237# windres.exe : in new version mingw:
238# $(RC) $(RFLAGS) resource.rc -FO $@
239
240
210endif 241endif
211 242
212$O/LzmaAlone.o: LzmaAlone.cpp 243$O/LzmaAlone.o: LzmaAlone.cpp
@@ -383,6 +414,8 @@ $O/MethodId.o: ../../Common/MethodId.cpp
383 $(CXX) $(CXXFLAGS) $< 414 $(CXX) $(CXXFLAGS) $<
384$O/MethodProps.o: ../../Common/MethodProps.cpp 415$O/MethodProps.o: ../../Common/MethodProps.cpp
385 $(CXX) $(CXXFLAGS) $< 416 $(CXX) $(CXXFLAGS) $<
417$O/MultiOutStream.o: ../../Common/MultiOutStream.cpp
418 $(CXX) $(CXXFLAGS) $<
386$O/OffsetStream.o: ../../Common/OffsetStream.cpp 419$O/OffsetStream.o: ../../Common/OffsetStream.cpp
387 $(CXX) $(CXXFLAGS) $< 420 $(CXX) $(CXXFLAGS) $<
388$O/OutBuffer.o: ../../Common/OutBuffer.cpp 421$O/OutBuffer.o: ../../Common/OutBuffer.cpp
@@ -1144,10 +1177,19 @@ $O/Sha256.o: ../../../../C/Sha256.c
1144 $(CC) $(CFLAGS) $< 1177 $(CC) $(CFLAGS) $<
1145$O/Sort.o: ../../../../C/Sort.c 1178$O/Sort.o: ../../../../C/Sort.c
1146 $(CC) $(CFLAGS) $< 1179 $(CC) $(CFLAGS) $<
1180$O/SwapBytes.o: ../../../../C/SwapBytes.c
1181 $(CC) $(CFLAGS) $<
1147$O/Xz.o: ../../../../C/Xz.c 1182$O/Xz.o: ../../../../C/Xz.c
1148 $(CC) $(CFLAGS) $< 1183 $(CC) $(CFLAGS) $<
1149$O/XzCrc64.o: ../../../../C/XzCrc64.c 1184$O/XzCrc64.o: ../../../../C/XzCrc64.c
1150 $(CC) $(CFLAGS) $< 1185 $(CC) $(CFLAGS) $<
1186$O/XzDec.o: ../../../../C/XzDec.c
1187 $(CC) $(CFLAGS) $<
1188$O/XzEnc.o: ../../../../C/XzEnc.c
1189 $(CC) $(CFLAGS) $<
1190$O/XzIn.o: ../../../../C/XzIn.c
1191 $(CC) $(CFLAGS) $<
1192
1151 1193
1152ifdef USE_ASM 1194ifdef USE_ASM
1153ifdef IS_X64 1195ifdef IS_X64
@@ -1216,7 +1258,7 @@ $O/LzmaDecOpt.o: ../../../../Asm/arm64/LzmaDecOpt.S ../../../../Asm/arm64/7zAsm.
1216endif 1258endif
1217 1259
1218$O/LzmaDec.o: ../../../../C/LzmaDec.c 1260$O/LzmaDec.o: ../../../../C/LzmaDec.c
1219 $(CC) $(CFLAGS) -D_LZMA_DEC_OPT $< 1261 $(CC) $(CFLAGS) -DZ7_LZMA_DEC_OPT $<
1220 1262
1221else 1263else
1222 1264
@@ -1227,13 +1269,6 @@ endif
1227 1269
1228 1270
1229 1271
1230$O/XzDec.o: ../../../../C/XzDec.c
1231 $(CC) $(CFLAGS) $<
1232$O/XzEnc.o: ../../../../C/XzEnc.c
1233 $(CC) $(CFLAGS) $<
1234$O/XzIn.o: ../../../../C/XzIn.c
1235 $(CC) $(CFLAGS) $<
1236
1237 1272
1238$O/7zMain.o: ../../../../C/Util/7z/7zMain.c 1273$O/7zMain.o: ../../../../C/Util/7z/7zMain.c
1239 $(CC) $(CFLAGS) $< 1274 $(CC) $(CFLAGS) $<
diff --git a/CPP/7zip/Archive/7z/7z.dsp b/CPP/7zip/Archive/7z/7z.dsp
index ffd2872..2c3e144 100644
--- a/CPP/7zip/Archive/7z/7z.dsp
+++ b/CPP/7zip/Archive/7z/7z.dsp
@@ -43,7 +43,7 @@ RSC=rc.exe
43# PROP Ignore_Export_Lib 1 43# PROP Ignore_Export_Lib 1
44# PROP Target_Dir "" 44# PROP Target_Dir ""
45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c 45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c
46# 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 46# 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
47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
49# ADD BASE RSC /l 0x419 /d "NDEBUG" 49# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -53,7 +53,7 @@ BSC32=bscmake.exe
53# ADD BSC32 /nologo 53# ADD BSC32 /nologo
54LINK32=link.exe 54LINK32=link.exe
55# 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 55# 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
56# 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 56# 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
57# SUBTRACT LINK32 /pdb:none 57# SUBTRACT LINK32 /pdb:none
58 58
59!ELSEIF "$(CFG)" == "7z - Win32 Debug" 59!ELSEIF "$(CFG)" == "7z - Win32 Debug"
@@ -70,7 +70,7 @@ LINK32=link.exe
70# PROP Ignore_Export_Lib 1 70# PROP Ignore_Export_Lib 1
71# PROP Target_Dir "" 71# PROP Target_Dir ""
72# 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 72# 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
73# 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 73# 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
74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
76# ADD BASE RSC /l 0x419 /d "_DEBUG" 76# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -80,7 +80,7 @@ BSC32=bscmake.exe
80# ADD BSC32 /nologo 80# ADD BSC32 /nologo
81LINK32=link.exe 81LINK32=link.exe
82# 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 82# 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
83# 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 83# 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
84 84
85!ENDIF 85!ENDIF
86 86
@@ -101,7 +101,11 @@ SOURCE=..\ArchiveExports.cpp
101# End Source File 101# End Source File
102# Begin Source File 102# Begin Source File
103 103
104SOURCE=..\DllExports.cpp 104SOURCE=..\..\Compress\CodecExports.cpp
105# End Source File
106# Begin Source File
107
108SOURCE=..\DllExports2.cpp
105# End Source File 109# End Source File
106# Begin Source File 110# Begin Source File
107 111
@@ -514,14 +518,6 @@ SOURCE=..\..\Common\VirtThread.h
514# PROP Default_Filter "" 518# PROP Default_Filter ""
515# Begin Source File 519# Begin Source File
516 520
517SOURCE=..\..\..\Windows\DLL.cpp
518# End Source File
519# Begin Source File
520
521SOURCE=..\..\..\Windows\DLL.h
522# End Source File
523# Begin Source File
524
525SOURCE=..\..\..\Windows\FileDir.cpp 521SOURCE=..\..\..\Windows\FileDir.cpp
526# End Source File 522# End Source File
527# Begin Source File 523# Begin Source File
diff --git a/CPP/7zip/Archive/7z/7zCompressionMode.h b/CPP/7zip/Archive/7z/7zCompressionMode.h
index 9e84634..ac1f6ad 100644
--- a/CPP/7zip/Archive/7z/7zCompressionMode.h
+++ b/CPP/7zip/Archive/7z/7zCompressionMode.h
@@ -1,7 +1,7 @@
1// 7zCompressionMode.h 1// 7zCompressionMode.h
2 2
3#ifndef __7Z_COMPRESSION_MODE_H 3#ifndef ZIP7_INC_7Z_COMPRESSION_MODE_H
4#define __7Z_COMPRESSION_MODE_H 4#define ZIP7_INC_7Z_COMPRESSION_MODE_H
5 5
6#include "../../Common/MethodId.h" 6#include "../../Common/MethodId.h"
7#include "../../Common/MethodProps.h" 7#include "../../Common/MethodProps.h"
@@ -53,7 +53,7 @@ struct CCompressionMethodMode
53 bool DefaultMethod_was_Inserted; 53 bool DefaultMethod_was_Inserted;
54 bool Filter_was_Inserted; 54 bool Filter_was_Inserted;
55 55
56 #ifndef _7ZIP_ST 56 #ifndef Z7_ST
57 UInt32 NumThreads; 57 UInt32 NumThreads;
58 bool NumThreads_WasForced; 58 bool NumThreads_WasForced;
59 bool MultiThreadMixer; 59 bool MultiThreadMixer;
@@ -69,7 +69,7 @@ struct CCompressionMethodMode
69 CCompressionMethodMode(): 69 CCompressionMethodMode():
70 DefaultMethod_was_Inserted(false) 70 DefaultMethod_was_Inserted(false)
71 , Filter_was_Inserted(false) 71 , Filter_was_Inserted(false)
72 #ifndef _7ZIP_ST 72 #ifndef Z7_ST
73 , NumThreads(1) 73 , NumThreads(1)
74 , NumThreads_WasForced(false) 74 , NumThreads_WasForced(false)
75 , MultiThreadMixer(true) 75 , MultiThreadMixer(true)
@@ -79,6 +79,10 @@ struct CCompressionMethodMode
79 , PasswordIsDefined(false) 79 , PasswordIsDefined(false)
80 {} 80 {}
81 81
82#ifdef Z7_CPP_IS_SUPPORTED_default
83 CCompressionMethodMode(const CCompressionMethodMode &) = default;
84 CCompressionMethodMode& operator =(const CCompressionMethodMode &) = default;
85#endif
82 ~CCompressionMethodMode() { Password.Wipe_and_Empty(); } 86 ~CCompressionMethodMode() { Password.Wipe_and_Empty(); }
83}; 87};
84 88
diff --git a/CPP/7zip/Archive/7z/7zDecode.cpp b/CPP/7zip/Archive/7z/7zDecode.cpp
index c27c8fb..5420dce 100644
--- a/CPP/7zip/Archive/7z/7zDecode.cpp
+++ b/CPP/7zip/Archive/7z/7zDecode.cpp
@@ -5,25 +5,23 @@
5#include "../../Common/LimitedStreams.h" 5#include "../../Common/LimitedStreams.h"
6#include "../../Common/ProgressUtils.h" 6#include "../../Common/ProgressUtils.h"
7#include "../../Common/StreamObjects.h" 7#include "../../Common/StreamObjects.h"
8#include "../../Common/StreamUtils.h"
8 9
9#include "7zDecode.h" 10#include "7zDecode.h"
10 11
11namespace NArchive { 12namespace NArchive {
12namespace N7z { 13namespace N7z {
13 14
14class CDecProgress: 15Z7_CLASS_IMP_COM_1(
15 public ICompressProgressInfo, 16 CDecProgress
16 public CMyUnknownImp 17 , ICompressProgressInfo
17{ 18)
18 CMyComPtr<ICompressProgressInfo> _progress; 19 CMyComPtr<ICompressProgressInfo> _progress;
19public: 20public:
20 CDecProgress(ICompressProgressInfo *progress): _progress(progress) {} 21 CDecProgress(ICompressProgressInfo *progress): _progress(progress) {}
21
22 MY_UNKNOWN_IMP1(ICompressProgressInfo)
23 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
24}; 22};
25 23
26STDMETHODIMP CDecProgress::SetRatioInfo(const UInt64 * /* inSize */, const UInt64 *outSize) 24Z7_COM7F_IMF(CDecProgress::SetRatioInfo(const UInt64 * /* inSize */, const UInt64 *outSize))
27{ 25{
28 return _progress->SetRatioInfo(NULL, outSize); 26 return _progress->SetRatioInfo(NULL, outSize);
29} 27}
@@ -110,20 +108,23 @@ static bool AreBindInfoExEqual(const CBindInfoEx &a1, const CBindInfoEx &a2)
110} 108}
111 109
112CDecoder::CDecoder(bool useMixerMT): 110CDecoder::CDecoder(bool useMixerMT):
113 _bindInfoPrev_Defined(false), 111 _bindInfoPrev_Defined(false)
114 _useMixerMT(useMixerMT) 112{
115{} 113 #if defined(USE_MIXER_ST) && defined(USE_MIXER_MT)
114 _useMixerMT = useMixerMT;
115 #else
116 UNUSED_VAR(useMixerMT)
117 #endif
118}
116 119
117 120
118struct CLockedInStream: 121Z7_CLASS_IMP_COM_0(
119 public IUnknown, 122 CLockedInStream
120 public CMyUnknownImp 123)
121{ 124public:
122 CMyComPtr<IInStream> Stream; 125 CMyComPtr<IInStream> Stream;
123 UInt64 Pos; 126 UInt64 Pos;
124 127
125 MY_UNKNOWN_IMP
126
127 #ifdef USE_MIXER_MT 128 #ifdef USE_MIXER_MT
128 NWindows::NSynchronization::CCriticalSection CriticalSection; 129 NWindows::NSynchronization::CCriticalSection CriticalSection;
129 #endif 130 #endif
@@ -132,10 +133,10 @@ struct CLockedInStream:
132 133
133#ifdef USE_MIXER_MT 134#ifdef USE_MIXER_MT
134 135
135class CLockedSequentialInStreamMT: 136Z7_CLASS_IMP_COM_1(
136 public ISequentialInStream, 137 CLockedSequentialInStreamMT
137 public CMyUnknownImp 138 , ISequentialInStream
138{ 139)
139 CLockedInStream *_glob; 140 CLockedInStream *_glob;
140 UInt64 _pos; 141 UInt64 _pos;
141 CMyComPtr<IUnknown> _globRef; 142 CMyComPtr<IUnknown> _globRef;
@@ -146,24 +147,20 @@ public:
146 _glob = lockedInStream; 147 _glob = lockedInStream;
147 _pos = startPos; 148 _pos = startPos;
148 } 149 }
149
150 MY_UNKNOWN_IMP1(ISequentialInStream)
151
152 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
153}; 150};
154 151
155STDMETHODIMP CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 *processedSize) 152Z7_COM7F_IMF(CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 *processedSize))
156{ 153{
157 NWindows::NSynchronization::CCriticalSectionLock lock(_glob->CriticalSection); 154 NWindows::NSynchronization::CCriticalSectionLock lock(_glob->CriticalSection);
158 155
159 if (_pos != _glob->Pos) 156 if (_pos != _glob->Pos)
160 { 157 {
161 RINOK(_glob->Stream->Seek((Int64)_pos, STREAM_SEEK_SET, NULL)); 158 RINOK(InStream_SeekSet(_glob->Stream, _pos))
162 _glob->Pos = _pos; 159 _glob->Pos = _pos;
163 } 160 }
164 161
165 UInt32 realProcessedSize = 0; 162 UInt32 realProcessedSize = 0;
166 HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); 163 const HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize);
167 _pos += realProcessedSize; 164 _pos += realProcessedSize;
168 _glob->Pos = _pos; 165 _glob->Pos = _pos;
169 if (processedSize) 166 if (processedSize)
@@ -176,10 +173,10 @@ STDMETHODIMP CLockedSequentialInStreamMT::Read(void *data, UInt32 size, UInt32 *
176 173
177#ifdef USE_MIXER_ST 174#ifdef USE_MIXER_ST
178 175
179class CLockedSequentialInStreamST: 176Z7_CLASS_IMP_COM_1(
180 public ISequentialInStream, 177 CLockedSequentialInStreamST
181 public CMyUnknownImp 178 , ISequentialInStream
182{ 179)
183 CLockedInStream *_glob; 180 CLockedInStream *_glob;
184 UInt64 _pos; 181 UInt64 _pos;
185 CMyComPtr<IUnknown> _globRef; 182 CMyComPtr<IUnknown> _globRef;
@@ -190,22 +187,18 @@ public:
190 _glob = lockedInStream; 187 _glob = lockedInStream;
191 _pos = startPos; 188 _pos = startPos;
192 } 189 }
193
194 MY_UNKNOWN_IMP1(ISequentialInStream)
195
196 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
197}; 190};
198 191
199STDMETHODIMP CLockedSequentialInStreamST::Read(void *data, UInt32 size, UInt32 *processedSize) 192Z7_COM7F_IMF(CLockedSequentialInStreamST::Read(void *data, UInt32 size, UInt32 *processedSize))
200{ 193{
201 if (_pos != _glob->Pos) 194 if (_pos != _glob->Pos)
202 { 195 {
203 RINOK(_glob->Stream->Seek((Int64)_pos, STREAM_SEEK_SET, NULL)); 196 RINOK(InStream_SeekSet(_glob->Stream, _pos))
204 _glob->Pos = _pos; 197 _glob->Pos = _pos;
205 } 198 }
206 199
207 UInt32 realProcessedSize = 0; 200 UInt32 realProcessedSize = 0;
208 HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize); 201 const HRESULT res = _glob->Stream->Read(data, size, &realProcessedSize);
209 _pos += realProcessedSize; 202 _pos += realProcessedSize;
210 _glob->Pos = _pos; 203 _glob->Pos = _pos;
211 if (processedSize) 204 if (processedSize)
@@ -234,9 +227,9 @@ HRESULT CDecoder::Decode(
234 227
235 , bool &dataAfterEnd_Error 228 , bool &dataAfterEnd_Error
236 229
237 _7Z_DECODER_CRYPRO_VARS_DECL 230 Z7_7Z_DECODER_CRYPRO_VARS_DECL
238 231
239 #if !defined(_7ZIP_ST) 232 #if !defined(Z7_ST)
240 , bool mtMode, UInt32 numThreads, UInt64 memUsage 233 , bool mtMode, UInt32 numThreads, UInt64 memUsage
241 #endif 234 #endif
242 ) 235 )
@@ -268,7 +261,7 @@ HRESULT CDecoder::Decode(
268 We don't need to init isEncrypted and passwordIsDefined 261 We don't need to init isEncrypted and passwordIsDefined
269 We must upgrade them only 262 We must upgrade them only
270 263
271 #ifndef _NO_CRYPTO 264 #ifndef Z7_NO_CRYPTO
272 isEncrypted = false; 265 isEncrypted = false;
273 passwordIsDefined = false; 266 passwordIsDefined = false;
274 #endif 267 #endif
@@ -300,13 +293,13 @@ HRESULT CDecoder::Decode(
300 #endif 293 #endif
301 } 294 }
302 295
303 RINOK(_mixer->SetBindInfo(bindInfo)); 296 RINOK(_mixer->SetBindInfo(bindInfo))
304 297
305 FOR_VECTOR(i, folderInfo.Coders) 298 FOR_VECTOR(i, folderInfo.Coders)
306 { 299 {
307 const CCoderInfo &coderInfo = folderInfo.Coders[i]; 300 const CCoderInfo &coderInfo = folderInfo.Coders[i];
308 301
309 #ifndef _SFX 302 #ifndef Z7_SFX
310 // we don't support RAR codecs here 303 // we don't support RAR codecs here
311 if ((coderInfo.MethodID >> 8) == 0x403) 304 if ((coderInfo.MethodID >> 8) == 0x403)
312 return E_NOTIMPL; 305 return E_NOTIMPL;
@@ -315,7 +308,7 @@ HRESULT CDecoder::Decode(
315 CCreatedCoder cod; 308 CCreatedCoder cod;
316 RINOK(CreateCoder_Id( 309 RINOK(CreateCoder_Id(
317 EXTERNAL_CODECS_LOC_VARS 310 EXTERNAL_CODECS_LOC_VARS
318 coderInfo.MethodID, false, cod)); 311 coderInfo.MethodID, false, cod))
319 312
320 if (coderInfo.IsSimpleCoder()) 313 if (coderInfo.IsSimpleCoder())
321 { 314 {
@@ -333,13 +326,13 @@ HRESULT CDecoder::Decode(
333 326
334 // now there is no codec that uses another external codec 327 // now there is no codec that uses another external codec
335 /* 328 /*
336 #ifdef EXTERNAL_CODECS 329 #ifdef Z7_EXTERNAL_CODECS
337 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo; 330 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
338 decoderUnknown.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); 331 decoderUnknown.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
339 if (setCompressCodecsInfo) 332 if (setCompressCodecsInfo)
340 { 333 {
341 // we must use g_ExternalCodecs also 334 // we must use g_ExternalCodecs also
342 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(__externalCodecs->GetCodecs)); 335 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs));
343 } 336 }
344 #endif 337 #endif
345 */ 338 */
@@ -349,14 +342,14 @@ HRESULT CDecoder::Decode(
349 _bindInfoPrev_Defined = true; 342 _bindInfoPrev_Defined = true;
350 } 343 }
351 344
352 RINOK(_mixer->ReInit2()); 345 RINOK(_mixer->ReInit2())
353 346
354 UInt32 packStreamIndex = 0; 347 UInt32 packStreamIndex = 0;
355 UInt32 unpackStreamIndexStart = folders.FoToCoderUnpackSizes[folderIndex]; 348 UInt32 unpackStreamIndexStart = folders.FoToCoderUnpackSizes[folderIndex];
356 349
357 unsigned i; 350 unsigned i;
358 351
359 #if !defined(_7ZIP_ST) 352 #if !defined(Z7_ST)
360 bool mt_wasUsed = false; 353 bool mt_wasUsed = false;
361 #endif 354 #endif
362 355
@@ -365,59 +358,81 @@ HRESULT CDecoder::Decode(
365 const CCoderInfo &coderInfo = folderInfo.Coders[i]; 358 const CCoderInfo &coderInfo = folderInfo.Coders[i];
366 IUnknown *decoder = _mixer->GetCoder(i).GetUnknown(); 359 IUnknown *decoder = _mixer->GetCoder(i).GetUnknown();
367 360
368 #if !defined(_7ZIP_ST) 361 // now there is no codec that uses another external codec
362 /*
363 #ifdef Z7_EXTERNAL_CODECS
364 {
365 Z7_DECL_CMyComPtr_QI_FROM(ISetCompressCodecsInfo,
366 setCompressCodecsInfo, decoder)
367 if (setCompressCodecsInfo)
368 {
369 // we must use g_ExternalCodecs also
370 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs))
371 }
372 }
373 #endif
374 */
375
376 #if !defined(Z7_ST)
369 if (!mt_wasUsed) 377 if (!mt_wasUsed)
370 { 378 {
371 if (mtMode) 379 if (mtMode)
372 { 380 {
373 CMyComPtr<ICompressSetCoderMt> setCoderMt; 381 Z7_DECL_CMyComPtr_QI_FROM(ICompressSetCoderMt,
374 decoder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); 382 setCoderMt, decoder)
375 if (setCoderMt) 383 if (setCoderMt)
376 { 384 {
377 mt_wasUsed = true; 385 mt_wasUsed = true;
378 RINOK(setCoderMt->SetNumberOfThreads(numThreads)); 386 RINOK(setCoderMt->SetNumberOfThreads(numThreads))
379 } 387 }
380 } 388 }
381 // if (memUsage != 0) 389 // if (memUsage != 0)
382 { 390 {
383 CMyComPtr<ICompressSetMemLimit> setMemLimit; 391 Z7_DECL_CMyComPtr_QI_FROM(ICompressSetMemLimit,
384 decoder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit); 392 setMemLimit, decoder)
385 if (setMemLimit) 393 if (setMemLimit)
386 { 394 {
387 mt_wasUsed = true; 395 mt_wasUsed = true;
388 RINOK(setMemLimit->SetMemLimit(memUsage)); 396 RINOK(setMemLimit->SetMemLimit(memUsage))
389 } 397 }
390 } 398 }
391 } 399 }
392 #endif 400 #endif
393 401
394 { 402 {
395 CMyComPtr<ICompressSetDecoderProperties2> setDecoderProperties; 403 Z7_DECL_CMyComPtr_QI_FROM(
396 decoder->QueryInterface(IID_ICompressSetDecoderProperties2, (void **)&setDecoderProperties); 404 ICompressSetDecoderProperties2,
405 setDecoderProperties, decoder)
406 const CByteBuffer &props = coderInfo.Props;
407 const UInt32 size32 = (UInt32)props.Size();
408 if (props.Size() != size32)
409 return E_NOTIMPL;
397 if (setDecoderProperties) 410 if (setDecoderProperties)
398 { 411 {
399 const CByteBuffer &props = coderInfo.Props;
400 const UInt32 size32 = (UInt32)props.Size();
401 if (props.Size() != size32)
402 return E_NOTIMPL;
403 HRESULT res = setDecoderProperties->SetDecoderProperties2((const Byte *)props, size32); 412 HRESULT res = setDecoderProperties->SetDecoderProperties2((const Byte *)props, size32);
404 if (res == E_INVALIDARG) 413 if (res == E_INVALIDARG)
405 res = E_NOTIMPL; 414 res = E_NOTIMPL;
406 RINOK(res); 415 RINOK(res)
416 }
417 else if (size32 != 0)
418 {
419 // v23: we fail, if decoder doesn't support properties
420 return E_NOTIMPL;
407 } 421 }
408 } 422 }
409 423
410 #ifndef _NO_CRYPTO 424 #ifndef Z7_NO_CRYPTO
411 { 425 {
412 CMyComPtr<ICryptoSetPassword> cryptoSetPassword; 426 Z7_DECL_CMyComPtr_QI_FROM(
413 decoder->QueryInterface(IID_ICryptoSetPassword, (void **)&cryptoSetPassword); 427 ICryptoSetPassword,
428 cryptoSetPassword, decoder)
414 if (cryptoSetPassword) 429 if (cryptoSetPassword)
415 { 430 {
416 isEncrypted = true; 431 isEncrypted = true;
417 if (!getTextPassword) 432 if (!getTextPassword)
418 return E_NOTIMPL; 433 return E_NOTIMPL;
419 CMyComBSTR_Wipe passwordBSTR; 434 CMyComBSTR_Wipe passwordBSTR;
420 RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR)); 435 RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR))
421 passwordIsDefined = true; 436 passwordIsDefined = true;
422 password.Wipe_and_Empty(); 437 password.Wipe_and_Empty();
423 size_t len = 0; 438 size_t len = 0;
@@ -429,23 +444,24 @@ HRESULT CDecoder::Decode(
429 CByteBuffer_Wipe buffer(len * 2); 444 CByteBuffer_Wipe buffer(len * 2);
430 for (size_t k = 0; k < len; k++) 445 for (size_t k = 0; k < len; k++)
431 { 446 {
432 wchar_t c = passwordBSTR[k]; 447 const wchar_t c = passwordBSTR[k];
433 ((Byte *)buffer)[k * 2] = (Byte)c; 448 ((Byte *)buffer)[k * 2] = (Byte)c;
434 ((Byte *)buffer)[k * 2 + 1] = (Byte)(c >> 8); 449 ((Byte *)buffer)[k * 2 + 1] = (Byte)(c >> 8);
435 } 450 }
436 RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)buffer.Size())); 451 RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)buffer.Size()))
437 } 452 }
438 } 453 }
439 #endif 454 #endif
440 455
441 bool finishMode = false; 456 bool finishMode = false;
442 { 457 {
443 CMyComPtr<ICompressSetFinishMode> setFinishMode; 458 Z7_DECL_CMyComPtr_QI_FROM(
444 decoder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); 459 ICompressSetFinishMode,
460 setFinishMode, decoder)
445 if (setFinishMode) 461 if (setFinishMode)
446 { 462 {
447 finishMode = fullUnpack; 463 finishMode = fullUnpack;
448 RINOK(setFinishMode->SetFinishMode(BoolToUInt(finishMode))); 464 RINOK(setFinishMode->SetFinishMode(BoolToUInt(finishMode)))
449 } 465 }
450 } 466 }
451 467
@@ -497,8 +513,8 @@ HRESULT CDecoder::Decode(
497 if (folderInfo.PackStreams.Size() > 1) 513 if (folderInfo.PackStreams.Size() > 1)
498 { 514 {
499 // lockedInStream.Pos = (UInt64)(Int64)-1; 515 // lockedInStream.Pos = (UInt64)(Int64)-1;
500 // RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &lockedInStream.Pos)); 516 // RINOK(InStream_GetPos(inStream, lockedInStream.Pos))
501 RINOK(inStream->Seek((Int64)(startPos + packPositions[0]), STREAM_SEEK_SET, &lockedInStreamSpec->Pos)); 517 RINOK(inStream->Seek((Int64)(startPos + packPositions[0]), STREAM_SEEK_SET, &lockedInStreamSpec->Pos))
502 lockedInStreamSpec->Stream = inStream; 518 lockedInStreamSpec->Stream = inStream;
503 519
504 #ifdef USE_MIXER_MT 520 #ifdef USE_MIXER_MT
@@ -523,7 +539,7 @@ HRESULT CDecoder::Decode(
523 539
524 if (folderInfo.PackStreams.Size() == 1) 540 if (folderInfo.PackStreams.Size() == 1)
525 { 541 {
526 RINOK(inStream->Seek((Int64)packPos, STREAM_SEEK_SET, NULL)); 542 RINOK(InStream_SeekSet(inStream, packPos))
527 packStream = inStream; 543 packStream = inStream;
528 } 544 }
529 else 545 else
diff --git a/CPP/7zip/Archive/7z/7zDecode.h b/CPP/7zip/Archive/7z/7zDecode.h
index eeb146e..ee9d9c2 100644
--- a/CPP/7zip/Archive/7z/7zDecode.h
+++ b/CPP/7zip/Archive/7z/7zDecode.h
@@ -1,7 +1,7 @@
1// 7zDecode.h 1// 7zDecode.h
2 2
3#ifndef __7Z_DECODE_H 3#ifndef ZIP7_INC_7Z_DECODE_H
4#define __7Z_DECODE_H 4#define ZIP7_INC_7Z_DECODE_H
5 5
6#include "../Common/CoderMixer2.h" 6#include "../Common/CoderMixer2.h"
7 7
@@ -24,10 +24,13 @@ struct CBindInfoEx: public NCoderMixer2::CBindInfo
24class CDecoder 24class CDecoder
25{ 25{
26 bool _bindInfoPrev_Defined; 26 bool _bindInfoPrev_Defined;
27 #ifdef USE_MIXER_ST
28 #ifdef USE_MIXER_MT
29 bool _useMixerMT;
30 #endif
31 #endif
27 CBindInfoEx _bindInfoPrev; 32 CBindInfoEx _bindInfoPrev;
28 33
29 bool _useMixerMT;
30
31 #ifdef USE_MIXER_ST 34 #ifdef USE_MIXER_ST
32 NCoderMixer2::CMixerST *_mixerST; 35 NCoderMixer2::CMixerST *_mixerST;
33 #endif 36 #endif
@@ -57,9 +60,9 @@ public:
57 , ISequentialInStream **inStreamMainRes 60 , ISequentialInStream **inStreamMainRes
58 , bool &dataAfterEnd_Error 61 , bool &dataAfterEnd_Error
59 62
60 _7Z_DECODER_CRYPRO_VARS_DECL 63 Z7_7Z_DECODER_CRYPRO_VARS_DECL
61 64
62 #if !defined(_7ZIP_ST) 65 #if !defined(Z7_ST)
63 , bool mtMode, UInt32 numThreads, UInt64 memUsage 66 , bool mtMode, UInt32 numThreads, UInt64 memUsage
64 #endif 67 #endif
65 ); 68 );
diff --git a/CPP/7zip/Archive/7z/7zEncode.cpp b/CPP/7zip/Archive/7z/7zEncode.cpp
index 83b0f18..78c91cf 100644
--- a/CPP/7zip/Archive/7z/7zEncode.cpp
+++ b/CPP/7zip/Archive/7z/7zEncode.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../Common/ComTry.h"
6
5#include "../../Common/CreateCoder.h" 7#include "../../Common/CreateCoder.h"
6#include "../../Common/FilterCoder.h" 8#include "../../Common/FilterCoder.h"
7#include "../../Common/LimitedStreams.h" 9#include "../../Common/LimitedStreams.h"
@@ -19,11 +21,11 @@ void CEncoder::InitBindConv()
19{ 21{
20 unsigned numIn = _bindInfo.Coders.Size(); 22 unsigned numIn = _bindInfo.Coders.Size();
21 23
22 _SrcIn_to_DestOut.ClearAndSetSize(numIn); 24 SrcIn_to_DestOut.ClearAndSetSize(numIn);
23 _DestOut_to_SrcIn.ClearAndSetSize(numIn); 25 DestOut_to_SrcIn.ClearAndSetSize(numIn);
24 26
25 unsigned numOut = _bindInfo.GetNum_Bonds_and_PackStreams(); 27 unsigned numOut = _bindInfo.GetNum_Bonds_and_PackStreams();
26 _SrcOut_to_DestIn.ClearAndSetSize(numOut); 28 SrcOut_to_DestIn.ClearAndSetSize(numOut);
27 // _DestIn_to_SrcOut.ClearAndSetSize(numOut); 29 // _DestIn_to_SrcOut.ClearAndSetSize(numOut);
28 30
29 UInt32 destIn = 0; 31 UInt32 destIn = 0;
@@ -38,15 +40,15 @@ void CEncoder::InitBindConv()
38 numIn--; 40 numIn--;
39 numOut -= coder.NumStreams; 41 numOut -= coder.NumStreams;
40 42
41 _SrcIn_to_DestOut[numIn] = destOut; 43 SrcIn_to_DestOut[numIn] = destOut;
42 _DestOut_to_SrcIn[destOut] = numIn; 44 DestOut_to_SrcIn[destOut] = numIn;
43 45
44 destOut++; 46 destOut++;
45 47
46 for (UInt32 j = 0; j < coder.NumStreams; j++, destIn++) 48 for (UInt32 j = 0; j < coder.NumStreams; j++, destIn++)
47 { 49 {
48 UInt32 index = numOut + j; 50 UInt32 index = numOut + j;
49 _SrcOut_to_DestIn[index] = destIn; 51 SrcOut_to_DestIn[index] = destIn;
50 // _DestIn_to_SrcOut[destIn] = index; 52 // _DestIn_to_SrcOut[destIn] = index;
51 } 53 }
52 } 54 }
@@ -62,8 +64,8 @@ void CEncoder::SetFolder(CFolder &folder)
62 { 64 {
63 CBond &fb = folder.Bonds[i]; 65 CBond &fb = folder.Bonds[i];
64 const NCoderMixer2::CBond &mixerBond = _bindInfo.Bonds[_bindInfo.Bonds.Size() - 1 - i]; 66 const NCoderMixer2::CBond &mixerBond = _bindInfo.Bonds[_bindInfo.Bonds.Size() - 1 - i];
65 fb.PackIndex = _SrcOut_to_DestIn[mixerBond.PackIndex]; 67 fb.PackIndex = SrcOut_to_DestIn[mixerBond.PackIndex];
66 fb.UnpackIndex = _SrcIn_to_DestOut[mixerBond.UnpackIndex]; 68 fb.UnpackIndex = SrcIn_to_DestOut[mixerBond.UnpackIndex];
67 } 69 }
68 70
69 folder.Coders.SetSize(_bindInfo.Coders.Size()); 71 folder.Coders.SetSize(_bindInfo.Coders.Size());
@@ -81,15 +83,16 @@ void CEncoder::SetFolder(CFolder &folder)
81 folder.PackStreams.SetSize(_bindInfo.PackStreams.Size()); 83 folder.PackStreams.SetSize(_bindInfo.PackStreams.Size());
82 84
83 for (i = 0; i < _bindInfo.PackStreams.Size(); i++) 85 for (i = 0; i < _bindInfo.PackStreams.Size(); i++)
84 folder.PackStreams[i] = _SrcOut_to_DestIn[_bindInfo.PackStreams[i]]; 86 folder.PackStreams[i] = SrcOut_to_DestIn[_bindInfo.PackStreams[i]];
85} 87}
86 88
87 89
88 90
89static HRESULT SetCoderProps2(const CProps &props, const UInt64 *dataSizeReduce, IUnknown *coder) 91static HRESULT SetCoderProps2(const CProps &props, const UInt64 *dataSizeReduce, IUnknown *coder)
90{ 92{
91 CMyComPtr<ICompressSetCoderProperties> setCoderProperties; 93 Z7_DECL_CMyComPtr_QI_FROM(
92 coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); 94 ICompressSetCoderProperties,
95 setCoderProperties, coder)
93 if (setCoderProperties) 96 if (setCoderProperties)
94 return props.SetCoderProps(setCoderProperties, dataSizeReduce); 97 return props.SetCoderProps(setCoderProperties, dataSizeReduce);
95 return props.AreThereNonOptionalProps() ? E_INVALIDARG : S_OK; 98 return props.AreThereNonOptionalProps() ? E_INVALIDARG : S_OK;
@@ -103,11 +106,11 @@ void CMtEncMultiProgress::Init(ICompressProgressInfo *progress)
103 OutSize = 0; 106 OutSize = 0;
104} 107}
105 108
106STDMETHODIMP CMtEncMultiProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) 109Z7_COM7F_IMF(CMtEncMultiProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */))
107{ 110{
108 UInt64 outSize2; 111 UInt64 outSize2;
109 { 112 {
110 #ifndef _7ZIP_ST 113 #ifndef Z7_ST
111 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); 114 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
112 #endif 115 #endif
113 outSize2 = OutSize; 116 outSize2 = OutSize;
@@ -146,7 +149,7 @@ HRESULT CEncoder::CreateMixerCoder(
146 #endif 149 #endif
147 } 150 }
148 151
149 RINOK(_mixer->SetBindInfo(_bindInfo)); 152 RINOK(_mixer->SetBindInfo(_bindInfo))
150 153
151 FOR_VECTOR (m, _options.Methods) 154 FOR_VECTOR (m, _options.Methods)
152 { 155 {
@@ -158,23 +161,27 @@ HRESULT CEncoder::CreateMixerCoder(
158 { 161 {
159 RINOK(CreateCoder_Index( 162 RINOK(CreateCoder_Index(
160 EXTERNAL_CODECS_LOC_VARS 163 EXTERNAL_CODECS_LOC_VARS
161 (unsigned)methodFull.CodecIndex, true, cod)); 164 (unsigned)methodFull.CodecIndex, true, cod))
162 } 165 }
163 else 166 else
164 { 167 {
165 RINOK(CreateCoder_Id( 168 RINOK(CreateCoder_Id(
166 EXTERNAL_CODECS_LOC_VARS 169 EXTERNAL_CODECS_LOC_VARS
167 methodFull.Id, true, cod)); 170 methodFull.Id, true, cod))
168 } 171 }
169 172
170 if (cod.NumStreams != methodFull.NumStreams)
171 return E_FAIL;
172 if (!cod.Coder && !cod.Coder2) 173 if (!cod.Coder && !cod.Coder2)
174 {
175 return E_NOTIMPL; // unsupported method, if encoder
176 // return E_FAIL;
177 }
178
179 if (cod.NumStreams != methodFull.NumStreams)
173 return E_FAIL; 180 return E_FAIL;
174 181
175 CMyComPtr<IUnknown> encoderCommon = cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2; 182 CMyComPtr<IUnknown> encoderCommon = cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2;
176 183
177 #ifndef _7ZIP_ST 184 #ifndef Z7_ST
178 if (methodFull.Set_NumThreads) 185 if (methodFull.Set_NumThreads)
179 { 186 {
180 CMyComPtr<ICompressSetCoderMt> setCoderMt; 187 CMyComPtr<ICompressSetCoderMt> setCoderMt;
@@ -184,12 +191,12 @@ HRESULT CEncoder::CreateMixerCoder(
184 RINOK(setCoderMt->SetNumberOfThreads( 191 RINOK(setCoderMt->SetNumberOfThreads(
185 /* _options.NumThreads */ 192 /* _options.NumThreads */
186 methodFull.NumThreads 193 methodFull.NumThreads
187 )); 194 ))
188 } 195 }
189 } 196 }
190 #endif 197 #endif
191 198
192 RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon)); 199 RINOK(SetCoderProps2(methodFull, inSizeForReduce, encoderCommon))
193 200
194 /* 201 /*
195 CMyComPtr<ICryptoResetSalt> resetSalt; 202 CMyComPtr<ICryptoResetSalt> resetSalt;
@@ -202,13 +209,13 @@ HRESULT CEncoder::CreateMixerCoder(
202 209
203 // now there is no codec that uses another external codec 210 // now there is no codec that uses another external codec
204 /* 211 /*
205 #ifdef EXTERNAL_CODECS 212 #ifdef Z7_EXTERNAL_CODECS
206 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo; 213 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
207 encoderCommon.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); 214 encoderCommon.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
208 if (setCompressCodecsInfo) 215 if (setCompressCodecsInfo)
209 { 216 {
210 // we must use g_ExternalCodecs also 217 // we must use g_ExternalCodecs also
211 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(__externalCodecs->GetCodecs)); 218 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs));
212 } 219 }
213 #endif 220 #endif
214 */ 221 */
@@ -226,7 +233,7 @@ HRESULT CEncoder::CreateMixerCoder(
226 ((Byte *)buffer)[i * 2] = (Byte)c; 233 ((Byte *)buffer)[i * 2] = (Byte)c;
227 ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); 234 ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8);
228 } 235 }
229 RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)sizeInBytes)); 236 RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, (UInt32)sizeInBytes))
230 } 237 }
231 238
232 _mixer->AddCoder(cod); 239 _mixer->AddCoder(cod);
@@ -236,85 +243,94 @@ HRESULT CEncoder::CreateMixerCoder(
236 243
237 244
238 245
239class CSequentialOutTempBufferImp2: 246Z7_CLASS_IMP_COM_1(
240 public ISequentialOutStream, 247 CSequentialOutTempBufferImp2
241 public CMyUnknownImp 248 , ISequentialOutStream
242{ 249)
243 CInOutTempBuffer *_buf;
244public: 250public:
245 CMtEncMultiProgress *_mtProgresSpec; 251 CInOutTempBuffer TempBuffer;
252 CMtEncMultiProgress *_mtProgressSpec;
246 253
247 CSequentialOutTempBufferImp2(): _buf(0), _mtProgresSpec(NULL) {} 254 CSequentialOutTempBufferImp2(): _mtProgressSpec(NULL) {}
248 void Init(CInOutTempBuffer *buffer) { _buf = buffer; }
249 MY_UNKNOWN_IMP1(ISequentialOutStream)
250
251 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
252}; 255};
253 256
254STDMETHODIMP CSequentialOutTempBufferImp2::Write(const void *data, UInt32 size, UInt32 *processed) 257Z7_COM7F_IMF(CSequentialOutTempBufferImp2::Write(const void *data, UInt32 size, UInt32 *processed))
255{ 258{
256 HRESULT res = _buf->Write_HRESULT(data, size); 259 COM_TRY_BEGIN
257 if (res != S_OK) 260 if (processed)
258 { 261 *processed = 0;
259 if (processed) 262 RINOK(TempBuffer.Write_HRESULT(data, size))
260 *processed = 0;
261 return res;
262 }
263 if (processed) 263 if (processed)
264 *processed = size; 264 *processed = size;
265 if (_mtProgresSpec) 265 if (_mtProgressSpec)
266 _mtProgresSpec->AddOutSize(size); 266 _mtProgressSpec->AddOutSize(size);
267 return S_OK; 267 return S_OK;
268 COM_TRY_END
268} 269}
269 270
270 271
271class CSequentialOutMtNotify: 272Z7_CLASS_IMP_COM_1(
272 public ISequentialOutStream, 273 CSequentialOutMtNotify
273 public CMyUnknownImp 274 , ISequentialOutStream
274{ 275)
275public: 276public:
276 CMyComPtr<ISequentialOutStream> _stream; 277 CMyComPtr<ISequentialOutStream> _stream;
277 CMtEncMultiProgress *_mtProgresSpec; 278 CMtEncMultiProgress *_mtProgressSpec;
278 279
279 CSequentialOutMtNotify(): _mtProgresSpec(NULL) {} 280 CSequentialOutMtNotify(): _mtProgressSpec(NULL) {}
280 MY_UNKNOWN_IMP1(ISequentialOutStream)
281
282 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
283}; 281};
284 282
285STDMETHODIMP CSequentialOutMtNotify::Write(const void *data, UInt32 size, UInt32 *processed) 283Z7_COM7F_IMF(CSequentialOutMtNotify::Write(const void *data, UInt32 size, UInt32 *processed))
286{ 284{
287 UInt32 realProcessed = 0; 285 UInt32 realProcessed = 0;
288 HRESULT res = _stream->Write(data, size, &realProcessed); 286 HRESULT res = _stream->Write(data, size, &realProcessed);
289 if (processed) 287 if (processed)
290 *processed = realProcessed; 288 *processed = realProcessed;
291 if (_mtProgresSpec) 289 if (_mtProgressSpec)
292 _mtProgresSpec->AddOutSize(size); 290 _mtProgressSpec->AddOutSize(size);
293 return res; 291 return res;
294} 292}
295 293
296 294
295static HRESULT FillProps_from_Coder(IUnknown *coder, CByteBuffer &props)
296{
297 Z7_DECL_CMyComPtr_QI_FROM(
298 ICompressWriteCoderProperties,
299 writeCoderProperties, coder)
300 if (writeCoderProperties)
301 {
302 CDynBufSeqOutStream *outStreamSpec = new CDynBufSeqOutStream;
303 CMyComPtr<ISequentialOutStream> dynOutStream(outStreamSpec);
304 outStreamSpec->Init();
305 RINOK(writeCoderProperties->WriteCoderProperties(dynOutStream))
306 outStreamSpec->CopyToBuffer(props);
307 }
308 else
309 props.Free();
310 return S_OK;
311}
297 312
298HRESULT CEncoder::Encode( 313HRESULT CEncoder::Encode1(
299 DECL_EXTERNAL_CODECS_LOC_VARS 314 DECL_EXTERNAL_CODECS_LOC_VARS
300 ISequentialInStream *inStream, 315 ISequentialInStream *inStream,
301 // const UInt64 *inStreamSize, 316 // const UInt64 *inStreamSize,
302 const UInt64 *inSizeForReduce, 317 const UInt64 *inSizeForReduce,
318 UInt64 expectedDataSize,
303 CFolder &folderItem, 319 CFolder &folderItem,
304 CRecordVector<UInt64> &coderUnpackSizes, 320 // CRecordVector<UInt64> &coderUnpackSizes,
305 UInt64 &unpackSize, 321 // UInt64 &unpackSize,
306 ISequentialOutStream *outStream, 322 ISequentialOutStream *outStream,
307 CRecordVector<UInt64> &packSizes, 323 CRecordVector<UInt64> &packSizes,
308 ICompressProgressInfo *compressProgress) 324 ICompressProgressInfo *compressProgress)
309{ 325{
310 RINOK(EncoderConstr()); 326 RINOK(EncoderConstr())
311 327
312 if (!_mixerRef) 328 if (!_mixerRef)
313 { 329 {
314 RINOK(CreateMixerCoder(EXTERNAL_CODECS_LOC_VARS inSizeForReduce)); 330 RINOK(CreateMixerCoder(EXTERNAL_CODECS_LOC_VARS inSizeForReduce))
315 } 331 }
316 332
317 RINOK(_mixer->ReInit2()); 333 RINOK(_mixer->ReInit2())
318 334
319 CMtEncMultiProgress *mtProgressSpec = NULL; 335 CMtEncMultiProgress *mtProgressSpec = NULL;
320 CMyComPtr<ICompressProgressInfo> mtProgress; 336 CMyComPtr<ICompressProgressInfo> mtProgress;
@@ -322,30 +338,21 @@ HRESULT CEncoder::Encode(
322 CSequentialOutMtNotify *mtOutStreamNotifySpec = NULL; 338 CSequentialOutMtNotify *mtOutStreamNotifySpec = NULL;
323 CMyComPtr<ISequentialOutStream> mtOutStreamNotify; 339 CMyComPtr<ISequentialOutStream> mtOutStreamNotify;
324 340
325 CObjectVector<CInOutTempBuffer> inOutTempBuffers; 341 CRecordVector<CSequentialOutTempBufferImp2 *> tempBufferSpecs;
326 CObjectVector<CSequentialOutTempBufferImp2 *> tempBufferSpecs;
327 CObjectVector<CMyComPtr<ISequentialOutStream> > tempBuffers; 342 CObjectVector<CMyComPtr<ISequentialOutStream> > tempBuffers;
328 343
329 unsigned numMethods = _bindInfo.Coders.Size();
330
331 unsigned i; 344 unsigned i;
332 345
333 for (i = 1; i < _bindInfo.PackStreams.Size(); i++) 346 for (i = 1; i < _bindInfo.PackStreams.Size(); i++)
334 { 347 {
335 CInOutTempBuffer &iotb = inOutTempBuffers.AddNew(); 348 CSequentialOutTempBufferImp2 *tempBufferSpec = new CSequentialOutTempBufferImp2();
336 iotb.Create();
337 iotb.InitWriting();
338 }
339
340 for (i = 1; i < _bindInfo.PackStreams.Size(); i++)
341 {
342 CSequentialOutTempBufferImp2 *tempBufferSpec = new CSequentialOutTempBufferImp2;
343 CMyComPtr<ISequentialOutStream> tempBuffer = tempBufferSpec; 349 CMyComPtr<ISequentialOutStream> tempBuffer = tempBufferSpec;
344 tempBufferSpec->Init(&inOutTempBuffers[i - 1]);
345 tempBuffers.Add(tempBuffer);
346 tempBufferSpecs.Add(tempBufferSpec); 350 tempBufferSpecs.Add(tempBufferSpec);
351 tempBuffers.Add(tempBuffer);
347 } 352 }
348 353
354 const unsigned numMethods = _bindInfo.Coders.Size();
355
349 for (i = 0; i < numMethods; i++) 356 for (i = 0; i < numMethods; i++)
350 _mixer->SetCoderInfo(i, NULL, NULL, false); 357 _mixer->SetCoderInfo(i, NULL, NULL, false);
351 358
@@ -360,15 +367,19 @@ HRESULT CEncoder::Encode(
360 */ 367 */
361 368
362 369
370 /*
363 CSequentialInStreamSizeCount2 *inStreamSizeCountSpec = new CSequentialInStreamSizeCount2; 371 CSequentialInStreamSizeCount2 *inStreamSizeCountSpec = new CSequentialInStreamSizeCount2;
364 CMyComPtr<ISequentialInStream> inStreamSizeCount = inStreamSizeCountSpec; 372 CMyComPtr<ISequentialInStream> inStreamSizeCount = inStreamSizeCountSpec;
373 */
365 374
366 CSequentialOutStreamSizeCount *outStreamSizeCountSpec = NULL; 375 CSequentialOutStreamSizeCount *outStreamSizeCountSpec = NULL;
367 CMyComPtr<ISequentialOutStream> outStreamSizeCount; 376 CMyComPtr<ISequentialOutStream> outStreamSizeCount;
368 377
369 inStreamSizeCountSpec->Init(inStream); 378 // inStreamSizeCountSpec->Init(inStream);
379
380 // ISequentialInStream *inStreamPointer = inStreamSizeCount;
381 ISequentialInStream *inStreamPointer = inStream;
370 382
371 ISequentialInStream *inStreamPointer = inStreamSizeCount;
372 CRecordVector<ISequentialOutStream *> outStreamPointers; 383 CRecordVector<ISequentialOutStream *> outStreamPointers;
373 384
374 SetFolder(folderItem); 385 SetFolder(folderItem);
@@ -376,49 +387,66 @@ HRESULT CEncoder::Encode(
376 for (i = 0; i < numMethods; i++) 387 for (i = 0; i < numMethods; i++)
377 { 388 {
378 IUnknown *coder = _mixer->GetCoder(i).GetUnknown(); 389 IUnknown *coder = _mixer->GetCoder(i).GetUnknown();
390 /*
391 {
392 CEncoder *sfEncoder = NULL;
393 Z7_DECL_CMyComPtr_QI_FROM(
394 IGetSfEncoderInternal,
395 sf, coder)
396 if (sf)
397 {
398 RINOK(sf->GetSfEncoder(&sfEncoder));
399 if (!sfEncoder)
400 return E_FAIL;
379 401
380 CMyComPtr<ICryptoResetInitVector> resetInitVector; 402 }
381 coder->QueryInterface(IID_ICryptoResetInitVector, (void **)&resetInitVector); 403 }
382 if (resetInitVector) 404 */
405 /*
406 #ifdef Z7_EXTERNAL_CODECS
383 { 407 {
384 resetInitVector->ResetInitVector(); 408 Z7_DECL_CMyComPtr_QI_FROM(
409 ISetCompressCodecsInfo,
410 setCompressCodecsInfo, coder)
411 if (setCompressCodecsInfo)
412 {
413 // we must use g_ExternalCodecs also
414 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(_externalCodecs->GetCodecs))
415 }
385 } 416 }
386 417 #endif
418 */
387 { 419 {
388 CMyComPtr<ICompressSetCoderPropertiesOpt> optProps; 420 Z7_DECL_CMyComPtr_QI_FROM(
389 coder->QueryInterface(IID_ICompressSetCoderPropertiesOpt, (void **)&optProps); 421 ICryptoResetInitVector,
390 if (optProps) 422 resetInitVector, coder)
423 if (resetInitVector)
391 { 424 {
392 PROPID propID = NCoderPropID::kExpectedDataSize; 425 RINOK(resetInitVector->ResetInitVector())
393 NWindows::NCOM::CPropVariant prop = (UInt64)unpackSize;
394 RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1));
395 } 426 }
396 } 427 }
397
398 CMyComPtr<ICompressWriteCoderProperties> writeCoderProperties;
399 coder->QueryInterface(IID_ICompressWriteCoderProperties, (void **)&writeCoderProperties);
400
401 CByteBuffer &props = folderItem.Coders[numMethods - 1 - i].Props;
402
403 if (writeCoderProperties)
404 { 428 {
405 CDynBufSeqOutStream *outStreamSpec = new CDynBufSeqOutStream; 429 Z7_DECL_CMyComPtr_QI_FROM(
406 CMyComPtr<ISequentialOutStream> dynOutStream(outStreamSpec); 430 ICompressSetCoderPropertiesOpt,
407 outStreamSpec->Init(); 431 optProps, coder)
408 RINOK(writeCoderProperties->WriteCoderProperties(dynOutStream)); 432 if (optProps)
409 outStreamSpec->CopyToBuffer(props); 433 {
434 const PROPID propID = NCoderPropID::kExpectedDataSize;
435 NWindows::NCOM::CPropVariant prop = (UInt64)expectedDataSize;
436 RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1))
437 }
410 } 438 }
411 else 439 // we must write properties from coder after ResetInitVector()
412 props.Free(); 440 RINOK(FillProps_from_Coder(coder, folderItem.Coders[numMethods - 1 - i].Props))
413 } 441 }
414 442
415 _mixer->SelectMainCoder(false); 443 _mixer->SelectMainCoder(false);
416 UInt32 mainCoder = _mixer->MainCoderIndex; 444 const UInt32 mainCoder = _mixer->MainCoderIndex;
417 445
418 bool useMtProgress = false; 446 bool useMtProgress = false;
419 if (!_mixer->Is_PackSize_Correct_for_Coder(mainCoder)) 447 if (!_mixer->Is_PackSize_Correct_for_Coder(mainCoder))
420 { 448 {
421 #ifdef _7ZIP_ST 449 #ifdef Z7_ST
422 if (!_mixer->IsThere_ExternalCoder_in_PackTree(mainCoder)) 450 if (!_mixer->IsThere_ExternalCoder_in_PackTree(mainCoder))
423 #endif 451 #endif
424 useMtProgress = true; 452 useMtProgress = true;
@@ -433,11 +461,11 @@ HRESULT CEncoder::Encode(
433 mtOutStreamNotifySpec = new CSequentialOutMtNotify; 461 mtOutStreamNotifySpec = new CSequentialOutMtNotify;
434 mtOutStreamNotify = mtOutStreamNotifySpec; 462 mtOutStreamNotify = mtOutStreamNotifySpec;
435 mtOutStreamNotifySpec->_stream = outStream; 463 mtOutStreamNotifySpec->_stream = outStream;
436 mtOutStreamNotifySpec->_mtProgresSpec = mtProgressSpec; 464 mtOutStreamNotifySpec->_mtProgressSpec = mtProgressSpec;
437 465
438 FOR_VECTOR(t, tempBufferSpecs) 466 FOR_VECTOR (t, tempBufferSpecs)
439 { 467 {
440 tempBufferSpecs[t]->_mtProgresSpec = mtProgressSpec; 468 tempBufferSpecs[t]->_mtProgressSpec = mtProgressSpec;
441 } 469 }
442 } 470 }
443 471
@@ -459,35 +487,49 @@ HRESULT CEncoder::Encode(
459 RINOK(_mixer->Code( 487 RINOK(_mixer->Code(
460 &inStreamPointer, 488 &inStreamPointer,
461 &outStreamPointers.Front(), 489 &outStreamPointers.Front(),
462 mtProgress ? (ICompressProgressInfo *)mtProgress : compressProgress, dataAfterEnd_Error)); 490 mtProgress ? (ICompressProgressInfo *)mtProgress : compressProgress, dataAfterEnd_Error))
463 491
464 if (_bindInfo.PackStreams.Size() != 0) 492 if (_bindInfo.PackStreams.Size() != 0)
465 packSizes.Add(outStreamSizeCountSpec->GetSize()); 493 packSizes.Add(outStreamSizeCountSpec->GetSize());
466 494
467 for (i = 1; i < _bindInfo.PackStreams.Size(); i++) 495 for (i = 1; i < _bindInfo.PackStreams.Size(); i++)
468 { 496 {
469 CInOutTempBuffer &inOutTempBuffer = inOutTempBuffers[i - 1]; 497 CInOutTempBuffer &iotb = tempBufferSpecs[i - 1]->TempBuffer;
470 RINOK(inOutTempBuffer.WriteToStream(outStream)); 498 RINOK(iotb.WriteToStream(outStream))
471 packSizes.Add(inOutTempBuffer.GetDataSize()); 499 packSizes.Add(iotb.GetDataSize());
472 } 500 }
473 501
474 unpackSize = 0; 502 /* Code() in some future codec can change properties.
475 503 v23: so we fill properties again after Code() */
476 for (i = 0; i < _bindInfo.Coders.Size(); i++) 504 for (i = 0; i < numMethods; i++)
505 {
506 IUnknown *coder = _mixer->GetCoder(i).GetUnknown();
507 RINOK(FillProps_from_Coder(coder, folderItem.Coders[numMethods - 1 - i].Props))
508 }
509
510 return S_OK;
511}
512
513
514void CEncoder::Encode_Post(
515 UInt64 unpackSize,
516 CRecordVector<UInt64> &coderUnpackSizes)
517{
518 // unpackSize = 0;
519 for (unsigned i = 0; i < _bindInfo.Coders.Size(); i++)
477 { 520 {
478 int bond = _bindInfo.FindBond_for_UnpackStream(_DestOut_to_SrcIn[i]); 521 const int bond = _bindInfo.FindBond_for_UnpackStream(DestOut_to_SrcIn[i]);
479 UInt64 streamSize; 522 UInt64 streamSize;
480 if (bond < 0) 523 if (bond < 0)
481 { 524 {
482 streamSize = inStreamSizeCountSpec->GetSize(); 525 // streamSize = inStreamSizeCountSpec->GetSize();
483 unpackSize = streamSize; 526 // unpackSize = streamSize;
527 streamSize = unpackSize;
484 } 528 }
485 else 529 else
486 streamSize = _mixer->GetBondStreamSize((unsigned)bond); 530 streamSize = _mixer->GetBondStreamSize((unsigned)bond);
487 coderUnpackSizes.Add(streamSize); 531 coderUnpackSizes.Add(streamSize);
488 } 532 }
489
490 return S_OK;
491} 533}
492 534
493 535
@@ -610,15 +652,15 @@ HRESULT CEncoder::EncoderConstr()
610 if (_bindInfo.Coders[ci].NumStreams == 0) 652 if (_bindInfo.Coders[ci].NumStreams == 0)
611 break; 653 break;
612 654
613 UInt32 outIndex = _bindInfo.Coder_to_Stream[ci]; 655 const UInt32 outIndex = _bindInfo.Coder_to_Stream[ci];
614 int bond = _bindInfo.FindBond_for_PackStream(outIndex); 656 const int bond = _bindInfo.FindBond_for_PackStream(outIndex);
615 if (bond >= 0) 657 if (bond >= 0)
616 { 658 {
617 ci = _bindInfo.Bonds[(unsigned)bond].UnpackIndex; 659 ci = _bindInfo.Bonds[(unsigned)bond].UnpackIndex;
618 continue; 660 continue;
619 } 661 }
620 662
621 int si = _bindInfo.FindStream_in_PackStreams(outIndex); 663 const int si = _bindInfo.FindStream_in_PackStreams(outIndex);
622 if (si >= 0) 664 if (si >= 0)
623 _bindInfo.PackStreams.MoveToFront((unsigned)si); 665 _bindInfo.PackStreams.MoveToFront((unsigned)si);
624 break; 666 break;
diff --git a/CPP/7zip/Archive/7z/7zEncode.h b/CPP/7zip/Archive/7z/7zEncode.h
index 6ea7f27..849ac63 100644
--- a/CPP/7zip/Archive/7z/7zEncode.h
+++ b/CPP/7zip/Archive/7z/7zEncode.h
@@ -1,7 +1,7 @@
1// 7zEncode.h 1// 7zEncode.h
2 2
3#ifndef __7Z_ENCODE_H 3#ifndef ZIP7_INC_7Z_ENCODE_H
4#define __7Z_ENCODE_H 4#define ZIP7_INC_7Z_ENCODE_H
5 5
6#include "7zCompressionMode.h" 6#include "7zCompressionMode.h"
7 7
@@ -12,12 +12,12 @@
12namespace NArchive { 12namespace NArchive {
13namespace N7z { 13namespace N7z {
14 14
15class CMtEncMultiProgress: 15Z7_CLASS_IMP_COM_1(
16 public ICompressProgressInfo, 16 CMtEncMultiProgress,
17 public CMyUnknownImp 17 ICompressProgressInfo
18{ 18)
19 CMyComPtr<ICompressProgressInfo> _progress; 19 CMyComPtr<ICompressProgressInfo> _progress;
20 #ifndef _7ZIP_ST 20 #ifndef Z7_ST
21 NWindows::NSynchronization::CCriticalSection CriticalSection; 21 NWindows::NSynchronization::CCriticalSection CriticalSection;
22 #endif 22 #endif
23 23
@@ -30,18 +30,15 @@ public:
30 30
31 void AddOutSize(UInt64 addOutSize) 31 void AddOutSize(UInt64 addOutSize)
32 { 32 {
33 #ifndef _7ZIP_ST 33 #ifndef Z7_ST
34 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); 34 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
35 #endif 35 #endif
36 OutSize += addOutSize; 36 OutSize += addOutSize;
37 } 37 }
38
39 MY_UNKNOWN_IMP1(ICompressProgressInfo)
40
41 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
42}; 38};
43 39
44class CEncoder MY_UNCOPYABLE 40
41class CEncoder Z7_final MY_UNCOPYABLE
45{ 42{
46 #ifdef USE_MIXER_ST 43 #ifdef USE_MIXER_ST
47 NCoderMixer2::CMixerST *_mixerST; 44 NCoderMixer2::CMixerST *_mixerST;
@@ -57,10 +54,10 @@ class CEncoder MY_UNCOPYABLE
57 NCoderMixer2::CBindInfo _bindInfo; 54 NCoderMixer2::CBindInfo _bindInfo;
58 CRecordVector<CMethodId> _decompressionMethods; 55 CRecordVector<CMethodId> _decompressionMethods;
59 56
60 CRecordVector<UInt32> _SrcIn_to_DestOut; 57 CRecordVector<UInt32> SrcIn_to_DestOut;
61 CRecordVector<UInt32> _SrcOut_to_DestIn; 58 CRecordVector<UInt32> SrcOut_to_DestIn;
62 // CRecordVector<UInt32> _DestIn_to_SrcOut; 59 // CRecordVector<UInt32> DestIn_to_SrcOut;
63 CRecordVector<UInt32> _DestOut_to_SrcIn; 60 CRecordVector<UInt32> DestOut_to_SrcIn;
64 61
65 void InitBindConv(); 62 void InitBindConv();
66 void SetFolder(CFolder &folder); 63 void SetFolder(CFolder &folder);
@@ -74,17 +71,23 @@ public:
74 CEncoder(const CCompressionMethodMode &options); 71 CEncoder(const CCompressionMethodMode &options);
75 ~CEncoder(); 72 ~CEncoder();
76 HRESULT EncoderConstr(); 73 HRESULT EncoderConstr();
77 HRESULT Encode( 74 HRESULT Encode1(
78 DECL_EXTERNAL_CODECS_LOC_VARS 75 DECL_EXTERNAL_CODECS_LOC_VARS
79 ISequentialInStream *inStream, 76 ISequentialInStream *inStream,
80 // const UInt64 *inStreamSize, 77 // const UInt64 *inStreamSize,
81 const UInt64 *inSizeForReduce, 78 const UInt64 *inSizeForReduce,
79 UInt64 expectedDataSize,
82 CFolder &folderItem, 80 CFolder &folderItem,
83 CRecordVector<UInt64> &coderUnpackSizes, 81 // CRecordVector<UInt64> &coderUnpackSizes,
84 UInt64 &unpackSize, 82 // UInt64 &unpackSize,
85 ISequentialOutStream *outStream, 83 ISequentialOutStream *outStream,
86 CRecordVector<UInt64> &packSizes, 84 CRecordVector<UInt64> &packSizes,
87 ICompressProgressInfo *compressProgress); 85 ICompressProgressInfo *compressProgress);
86
87 void Encode_Post(
88 UInt64 unpackSize,
89 CRecordVector<UInt64> &coderUnpackSizes);
90
88}; 91};
89 92
90}} 93}}
diff --git a/CPP/7zip/Archive/7z/7zExtract.cpp b/CPP/7zip/Archive/7z/7zExtract.cpp
index 8ca815d..5498c59 100644
--- a/CPP/7zip/Archive/7z/7zExtract.cpp
+++ b/CPP/7zip/Archive/7z/7zExtract.cpp
@@ -16,10 +16,11 @@
16namespace NArchive { 16namespace NArchive {
17namespace N7z { 17namespace N7z {
18 18
19class CFolderOutStream: 19Z7_CLASS_IMP_COM_1(
20 public ISequentialOutStream, 20 CFolderOutStream
21 public CMyUnknownImp 21 , ISequentialOutStream
22{ 22 /* , ICompressGetSubStreamSize */
23)
23 CMyComPtr<ISequentialOutStream> _stream; 24 CMyComPtr<ISequentialOutStream> _stream;
24public: 25public:
25 bool TestMode; 26 bool TestMode;
@@ -31,6 +32,7 @@ private:
31 UInt64 _rem; 32 UInt64 _rem;
32 33
33 const UInt32 *_indexes; 34 const UInt32 *_indexes;
35 // unsigned _startIndex;
34 unsigned _numFiles; 36 unsigned _numFiles;
35 unsigned _fileIndex; 37 unsigned _fileIndex;
36 38
@@ -40,8 +42,6 @@ private:
40 HRESULT ProcessEmptyFiles(); 42 HRESULT ProcessEmptyFiles();
41 43
42public: 44public:
43 MY_UNKNOWN_IMP1(ISequentialOutStream)
44
45 const CDbEx *_db; 45 const CDbEx *_db;
46 CMyComPtr<IArchiveExtractCallback> ExtractCallback; 46 CMyComPtr<IArchiveExtractCallback> ExtractCallback;
47 47
@@ -52,8 +52,6 @@ public:
52 CheckCrc(true) 52 CheckCrc(true)
53 {} 53 {}
54 54
55 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
56
57 HRESULT Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles); 55 HRESULT Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles);
58 HRESULT FlushCorrupted(Int32 callbackOperationResult); 56 HRESULT FlushCorrupted(Int32 callbackOperationResult);
59 57
@@ -63,6 +61,7 @@ public:
63 61
64HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles) 62HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsigned numFiles)
65{ 63{
64 // _startIndex = startIndex;
66 _fileIndex = startIndex; 65 _fileIndex = startIndex;
67 _indexes = indexes; 66 _indexes = indexes;
68 _numFiles = numFiles; 67 _numFiles = numFiles;
@@ -76,11 +75,10 @@ HRESULT CFolderOutStream::Init(unsigned startIndex, const UInt32 *indexes, unsig
76HRESULT CFolderOutStream::OpenFile(bool isCorrupted) 75HRESULT CFolderOutStream::OpenFile(bool isCorrupted)
77{ 76{
78 const CFileItem &fi = _db->Files[_fileIndex]; 77 const CFileItem &fi = _db->Files[_fileIndex];
79 UInt32 nextFileIndex = (_indexes ? *_indexes : _fileIndex); 78 const UInt32 nextFileIndex = (_indexes ? *_indexes : _fileIndex);
80 Int32 askMode = (_fileIndex == nextFileIndex) ? 79 Int32 askMode = (_fileIndex == nextFileIndex) ? TestMode ?
81 (TestMode ? 80 NExtract::NAskMode::kTest :
82 NExtract::NAskMode::kTest : 81 NExtract::NAskMode::kExtract :
83 NExtract::NAskMode::kExtract) :
84 NExtract::NAskMode::kSkip; 82 NExtract::NAskMode::kSkip;
85 83
86 if (isCorrupted 84 if (isCorrupted
@@ -90,7 +88,7 @@ HRESULT CFolderOutStream::OpenFile(bool isCorrupted)
90 askMode = NExtract::NAskMode::kTest; 88 askMode = NExtract::NAskMode::kTest;
91 89
92 CMyComPtr<ISequentialOutStream> realOutStream; 90 CMyComPtr<ISequentialOutStream> realOutStream;
93 RINOK(ExtractCallback->GetStream(_fileIndex, &realOutStream, askMode)); 91 RINOK(ExtractCallback->GetStream(_fileIndex, &realOutStream, askMode))
94 92
95 _stream = realOutStream; 93 _stream = realOutStream;
96 _crc = CRC_INIT_VAL; 94 _crc = CRC_INIT_VAL;
@@ -136,13 +134,13 @@ HRESULT CFolderOutStream::ProcessEmptyFiles()
136{ 134{
137 while (_numFiles != 0 && _db->Files[_fileIndex].Size == 0) 135 while (_numFiles != 0 && _db->Files[_fileIndex].Size == 0)
138 { 136 {
139 RINOK(OpenFile()); 137 RINOK(OpenFile())
140 RINOK(CloseFile()); 138 RINOK(CloseFile())
141 } 139 }
142 return S_OK; 140 return S_OK;
143} 141}
144 142
145STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 143Z7_COM7F_IMF(CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
146{ 144{
147 if (processedSize) 145 if (processedSize)
148 *processedSize = 0; 146 *processedSize = 0;
@@ -170,16 +168,16 @@ STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *proc
170 _rem -= cur; 168 _rem -= cur;
171 if (_rem == 0) 169 if (_rem == 0)
172 { 170 {
173 RINOK(CloseFile()); 171 RINOK(CloseFile())
174 RINOK(ProcessEmptyFiles()); 172 RINOK(ProcessEmptyFiles())
175 } 173 }
176 RINOK(result); 174 RINOK(result)
177 if (cur == 0) 175 if (cur == 0)
178 break; 176 break;
179 continue; 177 continue;
180 } 178 }
181 179
182 RINOK(ProcessEmptyFiles()); 180 RINOK(ProcessEmptyFiles())
183 if (_numFiles == 0) 181 if (_numFiles == 0)
184 { 182 {
185 // we support partial extracting 183 // we support partial extracting
@@ -192,7 +190,7 @@ STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *proc
192 // return S_FALSE; 190 // return S_FALSE;
193 return k_My_HRESULT_WritingWasCut; 191 return k_My_HRESULT_WritingWasCut;
194 } 192 }
195 RINOK(OpenFile()); 193 RINOK(OpenFile())
196 } 194 }
197 195
198 return S_OK; 196 return S_OK;
@@ -204,18 +202,32 @@ HRESULT CFolderOutStream::FlushCorrupted(Int32 callbackOperationResult)
204 { 202 {
205 if (_fileIsOpen) 203 if (_fileIsOpen)
206 { 204 {
207 RINOK(CloseFile_and_SetResult(callbackOperationResult)); 205 RINOK(CloseFile_and_SetResult(callbackOperationResult))
208 } 206 }
209 else 207 else
210 { 208 {
211 RINOK(OpenFile(true)); 209 RINOK(OpenFile(true))
212 } 210 }
213 } 211 }
214 return S_OK; 212 return S_OK;
215} 213}
216 214
217STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 215/*
218 Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec) 216Z7_COM7F_IMF(CFolderOutStream::GetSubStreamSize(UInt64 subStream, UInt64 *value))
217{
218 *value = 0;
219 // const unsigned numFiles_Original = _numFiles + _fileIndex - _startIndex;
220 const unsigned numFiles_Original = _numFiles;
221 if (subStream >= numFiles_Original)
222 return S_FALSE; // E_FAIL;
223 *value = _db->Files[_startIndex + (unsigned)subStream].Size;
224 return S_OK;
225}
226*/
227
228
229Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
230 Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec))
219{ 231{
220 // for GCC 232 // for GCC
221 // CFolderOutStream *folderOutStream = new CFolderOutStream; 233 // CFolderOutStream *folderOutStream = new CFolderOutStream;
@@ -229,7 +241,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
229 241
230 // numItems = (UInt32)(Int32)-1; 242 // numItems = (UInt32)(Int32)-1;
231 243
232 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 244 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
233 if (allFilesMode) 245 if (allFilesMode)
234 numItems = _db.Files.Size(); 246 numItems = _db.Files.Size();
235 247
@@ -244,8 +256,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
244 256
245 for (i = 0; i < numItems; i++) 257 for (i = 0; i < numItems; i++)
246 { 258 {
247 UInt32 fileIndex = allFilesMode ? i : indices[i]; 259 const UInt32 fileIndex = allFilesMode ? i : indices[i];
248 CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; 260 const CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex];
249 if (folderIndex == kNumNoIndex) 261 if (folderIndex == kNumNoIndex)
250 continue; 262 continue;
251 if (folderIndex != prevFolder || fileIndex < nextFile) 263 if (folderIndex != prevFolder || fileIndex < nextFile)
@@ -257,7 +269,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
257 } 269 }
258 } 270 }
259 271
260 RINOK(extractCallback->SetTotal(importantTotalUnpacked)); 272 RINOK(extractCallback->SetTotal(importantTotalUnpacked))
261 273
262 CLocalProgress *lps = new CLocalProgress; 274 CLocalProgress *lps = new CLocalProgress;
263 CMyComPtr<ICompressProgressInfo> progress = lps; 275 CMyComPtr<ICompressProgressInfo> progress = lps;
@@ -268,8 +280,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
268 false 280 false
269 #elif !defined(USE_MIXER_ST) 281 #elif !defined(USE_MIXER_ST)
270 true 282 true
271 #elif !defined(__7Z_SET_PROPERTIES) 283 #elif !defined(Z7_7Z_SET_PROPERTIES)
272 #ifdef _7ZIP_ST 284 #ifdef Z7_ST
273 false 285 false
274 #else 286 #else
275 true 287 true
@@ -281,8 +293,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
281 293
282 UInt64 curPacked, curUnpacked; 294 UInt64 curPacked, curUnpacked;
283 295
284 CMyComPtr<IArchiveExtractCallbackMessage> callbackMessage; 296 CMyComPtr<IArchiveExtractCallbackMessage2> callbackMessage;
285 extractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage, &callbackMessage); 297 extractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage2, &callbackMessage);
286 298
287 CFolderOutStream *folderOutStream = new CFolderOutStream; 299 CFolderOutStream *folderOutStream = new CFolderOutStream;
288 CMyComPtr<ISequentialOutStream> outStream(folderOutStream); 300 CMyComPtr<ISequentialOutStream> outStream(folderOutStream);
@@ -294,7 +306,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
294 306
295 for (UInt32 i = 0;; lps->OutSize += curUnpacked, lps->InSize += curPacked) 307 for (UInt32 i = 0;; lps->OutSize += curUnpacked, lps->InSize += curPacked)
296 { 308 {
297 RINOK(lps->SetCur()); 309 RINOK(lps->SetCur())
298 310
299 if (i >= numItems) 311 if (i >= numItems)
300 break; 312 break;
@@ -303,7 +315,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
303 curPacked = 0; 315 curPacked = 0;
304 316
305 UInt32 fileIndex = allFilesMode ? i : indices[i]; 317 UInt32 fileIndex = allFilesMode ? i : indices[i];
306 CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex]; 318 const CNum folderIndex = _db.FileIndexToFolderIndexMap[fileIndex];
307 319
308 UInt32 numSolidFiles = 1; 320 UInt32 numSolidFiles = 1;
309 321
@@ -316,7 +328,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
316 328
317 for (k = i + 1; k < numItems; k++) 329 for (k = i + 1; k < numItems; k++)
318 { 330 {
319 UInt32 fileIndex2 = allFilesMode ? k : indices[k]; 331 const UInt32 fileIndex2 = allFilesMode ? k : indices[k];
320 if (_db.FileIndexToFolderIndexMap[fileIndex2] != folderIndex 332 if (_db.FileIndexToFolderIndexMap[fileIndex2] != folderIndex
321 || fileIndex2 < nextFile) 333 || fileIndex2 < nextFile)
322 break; 334 break;
@@ -330,20 +342,26 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
330 } 342 }
331 343
332 { 344 {
333 HRESULT result = folderOutStream->Init(fileIndex, 345 const HRESULT result = folderOutStream->Init(fileIndex,
334 allFilesMode ? NULL : indices + i, 346 allFilesMode ? NULL : indices + i,
335 numSolidFiles); 347 numSolidFiles);
336 348
337 i += numSolidFiles; 349 i += numSolidFiles;
338 350
339 RINOK(result); 351 RINOK(result)
340 } 352 }
341 353
342 // to test solid block with zero unpacked size we disable that code
343 if (folderOutStream->WasWritingFinished()) 354 if (folderOutStream->WasWritingFinished())
355 {
356 // for debug: to test zero size stream unpacking
357 // if (folderIndex == kNumNoIndex) // enable this check for debug
344 continue; 358 continue;
359 }
360
361 if (folderIndex == kNumNoIndex)
362 return E_FAIL;
345 363
346 #ifndef _NO_CRYPTO 364 #ifndef Z7_NO_CRYPTO
347 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 365 CMyComPtr<ICryptoGetTextPassword> getTextPassword;
348 if (extractCallback) 366 if (extractCallback)
349 extractCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); 367 extractCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword);
@@ -351,16 +369,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
351 369
352 try 370 try
353 { 371 {
354 #ifndef _NO_CRYPTO 372 #ifndef Z7_NO_CRYPTO
355 bool isEncrypted = false; 373 bool isEncrypted = false;
356 bool passwordIsDefined = false; 374 bool passwordIsDefined = false;
357 UString_Wipe password; 375 UString_Wipe password;
358 #endif 376 #endif
359 377
360
361 bool dataAfterEnd_Error = false; 378 bool dataAfterEnd_Error = false;
362 379
363 HRESULT result = decoder.Decode( 380 const HRESULT result = decoder.Decode(
364 EXTERNAL_CODECS_VARS 381 EXTERNAL_CODECS_VARS
365 _inStream, 382 _inStream,
366 _db.ArcInfo.DataStartPosition, 383 _db.ArcInfo.DataStartPosition,
@@ -372,15 +389,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
372 NULL // *inStreamMainRes 389 NULL // *inStreamMainRes
373 , dataAfterEnd_Error 390 , dataAfterEnd_Error
374 391
375 _7Z_DECODER_CRYPRO_VARS 392 Z7_7Z_DECODER_CRYPRO_VARS
376 #if !defined(_7ZIP_ST) 393 #if !defined(Z7_ST)
377 , true, _numThreads, _memUsage_Decompress 394 , true, _numThreads, _memUsage_Decompress
378 #endif 395 #endif
379 ); 396 );
380 397
381 if (result == S_FALSE || result == E_NOTIMPL || dataAfterEnd_Error) 398 if (result == S_FALSE || result == E_NOTIMPL || dataAfterEnd_Error)
382 { 399 {
383 bool wasFinished = folderOutStream->WasWritingFinished(); 400 const bool wasFinished = folderOutStream->WasWritingFinished();
384 401
385 int resOp = NExtract::NOperationResult::kDataError; 402 int resOp = NExtract::NOperationResult::kDataError;
386 403
@@ -392,14 +409,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
392 resOp = NExtract::NOperationResult::kDataAfterEnd; 409 resOp = NExtract::NOperationResult::kDataAfterEnd;
393 } 410 }
394 411
395 RINOK(folderOutStream->FlushCorrupted(resOp)); 412 RINOK(folderOutStream->FlushCorrupted(resOp))
396 413
397 if (wasFinished) 414 if (wasFinished)
398 { 415 {
399 // we don't show error, if it's after required files 416 // we don't show error, if it's after required files
400 if (/* !folderOutStream->ExtraWriteWasCut && */ callbackMessage) 417 if (/* !folderOutStream->ExtraWriteWasCut && */ callbackMessage)
401 { 418 {
402 RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, resOp)); 419 RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, resOp))
403 } 420 }
404 } 421 }
405 continue; 422 continue;
@@ -408,12 +425,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
408 if (result != S_OK) 425 if (result != S_OK)
409 return result; 426 return result;
410 427
411 RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)); 428 RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError))
412 continue; 429 continue;
413 } 430 }
414 catch(...) 431 catch(...)
415 { 432 {
416 RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError)); 433 RINOK(folderOutStream->FlushCorrupted(NExtract::NOperationResult::kDataError))
417 // continue; 434 // continue;
418 // return E_FAIL; 435 // return E_FAIL;
419 throw; 436 throw;
diff --git a/CPP/7zip/Archive/7z/7zFolderInStream.cpp b/CPP/7zip/Archive/7z/7zFolderInStream.cpp
index cf50e69..0823189 100644
--- a/CPP/7zip/Archive/7z/7zFolderInStream.cpp
+++ b/CPP/7zip/Archive/7z/7zFolderInStream.cpp
@@ -15,32 +15,38 @@ void CFolderInStream::Init(IArchiveUpdateCallback *updateCallback,
15 _updateCallback = updateCallback; 15 _updateCallback = updateCallback;
16 _indexes = indexes; 16 _indexes = indexes;
17 _numFiles = numFiles; 17 _numFiles = numFiles;
18
19 _totalSize_for_Coder = 0;
20 ClearFileInfo();
18 21
19 Processed.ClearAndReserve(numFiles); 22 Processed.ClearAndReserve(numFiles);
20 CRCs.ClearAndReserve(numFiles);
21 Sizes.ClearAndReserve(numFiles); 23 Sizes.ClearAndReserve(numFiles);
22 24 CRCs.ClearAndReserve(numFiles);
23 if (Need_CTime) CTimes.ClearAndReserve(numFiles);
24 if (Need_ATime) ATimes.ClearAndReserve(numFiles);
25 if (Need_MTime) MTimes.ClearAndReserve(numFiles);
26 if (Need_Attrib) Attribs.ClearAndReserve(numFiles);
27 TimesDefined.ClearAndReserve(numFiles); 25 TimesDefined.ClearAndReserve(numFiles);
28 26 MTimes.ClearAndReserve(Need_MTime ? numFiles : (unsigned)0);
27 CTimes.ClearAndReserve(Need_CTime ? numFiles : (unsigned)0);
28 ATimes.ClearAndReserve(Need_ATime ? numFiles : (unsigned)0);
29 Attribs.ClearAndReserve(Need_Attrib ? numFiles : (unsigned)0);
30
31 // FolderCrc = CRC_INIT_VAL;
29 _stream.Release(); 32 _stream.Release();
30} 33}
31 34
32HRESULT CFolderInStream::OpenStream() 35void CFolderInStream::ClearFileInfo()
33{ 36{
34 _pos = 0; 37 _pos = 0;
35 _crc = CRC_INIT_VAL; 38 _crc = CRC_INIT_VAL;
36 _size_Defined = false; 39 _size_Defined = false;
37 _times_Defined = false; 40 _times_Defined = false;
38 _size = 0; 41 _size = 0;
42 FILETIME_Clear(_mTime);
39 FILETIME_Clear(_cTime); 43 FILETIME_Clear(_cTime);
40 FILETIME_Clear(_aTime); 44 FILETIME_Clear(_aTime);
41 FILETIME_Clear(_mTime);
42 _attrib = 0; 45 _attrib = 0;
46}
43 47
48HRESULT CFolderInStream::OpenStream()
49{
44 while (Processed.Size() < _numFiles) 50 while (Processed.Size() < _numFiles)
45 { 51 {
46 CMyComPtr<ISequentialInStream> stream; 52 CMyComPtr<ISequentialInStream> stream;
@@ -83,7 +89,7 @@ HRESULT CFolderInStream::OpenStream()
83 } 89 }
84 } 90 }
85 91
86 RINOK(AddFileInfo(result == S_OK)); 92 RINOK(AddFileInfo(result == S_OK))
87 } 93 }
88 return S_OK; 94 return S_OK;
89} 95}
@@ -117,13 +123,13 @@ HRESULT CFolderInStream::AddFileInfo(bool isProcessed)
117 // const UInt32 index = _indexes[Processed.Size()]; 123 // const UInt32 index = _indexes[Processed.Size()];
118 Processed.AddInReserved(isProcessed); 124 Processed.AddInReserved(isProcessed);
119 Sizes.AddInReserved(_pos); 125 Sizes.AddInReserved(_pos);
120 const UInt32 crc = CRC_GET_DIGEST(_crc); 126 CRCs.AddInReserved(CRC_GET_DIGEST(_crc));
121 CRCs.AddInReserved(crc); 127 if (Need_Attrib) Attribs.AddInReserved(_attrib);
122 TimesDefined.AddInReserved(_times_Defined); 128 TimesDefined.AddInReserved(_times_Defined);
129 if (Need_MTime) AddFt(MTimes, _mTime);
123 if (Need_CTime) AddFt(CTimes, _cTime); 130 if (Need_CTime) AddFt(CTimes, _cTime);
124 if (Need_ATime) AddFt(ATimes, _aTime); 131 if (Need_ATime) AddFt(ATimes, _aTime);
125 if (Need_MTime) AddFt(MTimes, _mTime); 132 ClearFileInfo();
126 if (Need_Attrib) Attribs.AddInReserved(_attrib);
127 /* 133 /*
128 if (isProcessed && _reportArcProp) 134 if (isProcessed && _reportArcProp)
129 RINOK(ReportItemProps(_reportArcProp, index, _pos, &crc)) 135 RINOK(ReportItemProps(_reportArcProp, index, _pos, &crc))
@@ -131,7 +137,7 @@ HRESULT CFolderInStream::AddFileInfo(bool isProcessed)
131 return _updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); 137 return _updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK);
132} 138}
133 139
134STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 140Z7_COM7F_IMF(CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
135{ 141{
136 if (processedSize) 142 if (processedSize)
137 *processedSize = 0; 143 *processedSize = 0;
@@ -139,38 +145,65 @@ STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSiz
139 { 145 {
140 if (_stream) 146 if (_stream)
141 { 147 {
148 /*
149 if (_pos == 0)
150 {
151 const UInt32 align = (UInt32)1 << AlignLog;
152 const UInt32 offset = (UInt32)_totalSize_for_Coder & (align - 1);
153 if (offset != 0)
154 {
155 UInt32 cur = align - offset;
156 if (cur > size)
157 cur = size;
158 memset(data, 0, cur);
159 data = (Byte *)data + cur;
160 size -= cur;
161 // _pos += cur; // for debug
162 _totalSize_for_Coder += cur;
163 if (processedSize)
164 *processedSize += cur;
165 continue;
166 }
167 }
168 */
142 UInt32 cur = size; 169 UInt32 cur = size;
143 const UInt32 kMax = (UInt32)1 << 20; 170 const UInt32 kMax = (UInt32)1 << 20;
144 if (cur > kMax) 171 if (cur > kMax)
145 cur = kMax; 172 cur = kMax;
146 RINOK(_stream->Read(data, cur, &cur)); 173 RINOK(_stream->Read(data, cur, &cur))
147 if (cur != 0) 174 if (cur != 0)
148 { 175 {
176 // if (Need_Crc)
149 _crc = CrcUpdate(_crc, data, cur); 177 _crc = CrcUpdate(_crc, data, cur);
178 /*
179 if (FolderCrc)
180 FolderCrc = CrcUpdate(FolderCrc, data, cur);
181 */
150 _pos += cur; 182 _pos += cur;
183 _totalSize_for_Coder += cur;
151 if (processedSize) 184 if (processedSize)
152 *processedSize = cur; 185 *processedSize = cur; // use +=cur, if continue is possible in loop
153 return S_OK; 186 return S_OK;
154 } 187 }
155 188
156 _stream.Release(); 189 _stream.Release();
157 RINOK(AddFileInfo(true)); 190 RINOK(AddFileInfo(true))
158 } 191 }
159 192
160 if (Processed.Size() >= _numFiles) 193 if (Processed.Size() >= _numFiles)
161 break; 194 break;
162 RINOK(OpenStream()); 195 RINOK(OpenStream())
163 } 196 }
164 return S_OK; 197 return S_OK;
165} 198}
166 199
167STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value) 200Z7_COM7F_IMF(CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value))
168{ 201{
169 *value = 0; 202 *value = 0;
170 if (subStream > Sizes.Size()) 203 if (subStream > Sizes.Size())
171 return S_FALSE; // E_FAIL; 204 return S_FALSE; // E_FAIL;
172 205
173 unsigned index = (unsigned)subStream; 206 const unsigned index = (unsigned)subStream;
174 if (index < Sizes.Size()) 207 if (index < Sizes.Size())
175 { 208 {
176 *value = Sizes[index]; 209 *value = Sizes[index];
@@ -187,4 +220,45 @@ STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value)
187 return S_OK; 220 return S_OK;
188} 221}
189 222
223
224/*
225HRESULT CFolderInStream::CloseCrcStream()
226{
227 if (!_crcStream)
228 return S_OK;
229 if (!_crcStream_Spec->WasFinished())
230 return E_FAIL;
231 _crc = _crcStream_Spec->GetCRC() ^ CRC_INIT_VAL; // change it
232 const UInt64 size = _crcStream_Spec->GetSize();
233 _pos = size;
234 _totalSize_for_Coder += size;
235 _crcStream.Release();
236 // _crcStream->ReleaseStream();
237 _stream.Release();
238 return AddFileInfo(true);
239}
240
241Z7_COM7F_IMF(CFolderInStream::GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream)
242{
243 RINOK(CloseCrcStream())
244 *stream = NULL;
245 *streamIndexRes = Processed.Size();
246 if (Processed.Size() >= _numFiles)
247 return S_OK;
248 RINOK(OpenStream());
249 if (!_stream)
250 return S_OK;
251 if (!_crcStream)
252 {
253 _crcStream_Spec = new CSequentialInStreamWithCRC;
254 _crcStream = _crcStream_Spec;
255 }
256 _crcStream_Spec->Init();
257 _crcStream_Spec->SetStream(_stream);
258 *stream = _crcStream;
259 _crcStream->AddRef();
260 return S_OK;
261}
262*/
263
190}} 264}}
diff --git a/CPP/7zip/Archive/7z/7zFolderInStream.h b/CPP/7zip/Archive/7z/7zFolderInStream.h
index f054e68..6447b25 100644
--- a/CPP/7zip/Archive/7z/7zFolderInStream.h
+++ b/CPP/7zip/Archive/7z/7zFolderInStream.h
@@ -1,12 +1,13 @@
1// 7zFolderInStream.h 1// 7zFolderInStream.h
2 2
3#ifndef __7Z_FOLDER_IN_STREAM_H 3#ifndef ZIP7_INC_7Z_FOLDER_IN_STREAM_H
4#define __7Z_FOLDER_IN_STREAM_H 4#define ZIP7_INC_7Z_FOLDER_IN_STREAM_H
5 5
6#include "../../../../C/7zCrc.h" 6#include "../../../../C/7zCrc.h"
7 7
8#include "../../../Common/MyCom.h" 8#include "../../../Common/MyCom.h"
9#include "../../../Common/MyVector.h" 9#include "../../../Common/MyVector.h"
10// #include "../Common/InStreamWithCRC.h"
10 11
11#include "../../ICoder.h" 12#include "../../ICoder.h"
12#include "../IArchive.h" 13#include "../IArchive.h"
@@ -14,20 +15,26 @@
14namespace NArchive { 15namespace NArchive {
15namespace N7z { 16namespace N7z {
16 17
17class CFolderInStream: 18Z7_CLASS_IMP_COM_2(
18 public ISequentialInStream, 19 CFolderInStream
19 public ICompressGetSubStreamSize, 20 , ISequentialInStream
20 public CMyUnknownImp 21 , ICompressGetSubStreamSize
21{ 22)
23 /*
24 Z7_COM7F_IMP(GetNextStream(UInt64 *streamIndex))
25 Z7_IFACE_COM7_IMP(ICompressInSubStreams)
26 */
27
22 CMyComPtr<ISequentialInStream> _stream; 28 CMyComPtr<ISequentialInStream> _stream;
29 UInt64 _totalSize_for_Coder;
23 UInt64 _pos; 30 UInt64 _pos;
24 UInt32 _crc; 31 UInt32 _crc;
25 bool _size_Defined; 32 bool _size_Defined;
26 bool _times_Defined; 33 bool _times_Defined;
27 UInt64 _size; 34 UInt64 _size;
35 FILETIME _mTime;
28 FILETIME _cTime; 36 FILETIME _cTime;
29 FILETIME _aTime; 37 FILETIME _aTime;
30 FILETIME _mTime;
31 UInt32 _attrib; 38 UInt32 _attrib;
32 39
33 unsigned _numFiles; 40 unsigned _numFiles;
@@ -35,34 +42,40 @@ class CFolderInStream:
35 42
36 CMyComPtr<IArchiveUpdateCallback> _updateCallback; 43 CMyComPtr<IArchiveUpdateCallback> _updateCallback;
37 44
45 void ClearFileInfo();
38 HRESULT OpenStream(); 46 HRESULT OpenStream();
39 HRESULT AddFileInfo(bool isProcessed); 47 HRESULT AddFileInfo(bool isProcessed);
40 48 // HRESULT CloseCrcStream();
41public: 49public:
50 bool Need_MTime;
51 bool Need_CTime;
52 bool Need_ATime;
53 bool Need_Attrib;
54 // bool Need_Crc;
55 // bool Need_FolderCrc;
56 // unsigned AlignLog;
57
42 CRecordVector<bool> Processed; 58 CRecordVector<bool> Processed;
43 CRecordVector<UInt32> CRCs;
44 CRecordVector<UInt64> Sizes; 59 CRecordVector<UInt64> Sizes;
45 CRecordVector<UInt64> CTimes; 60 CRecordVector<UInt32> CRCs;
46 CRecordVector<UInt64> ATimes;
47 CRecordVector<UInt64> MTimes;
48 CRecordVector<UInt32> Attribs; 61 CRecordVector<UInt32> Attribs;
49 CRecordVector<bool> TimesDefined; 62 CRecordVector<bool> TimesDefined;
63 CRecordVector<UInt64> MTimes;
64 CRecordVector<UInt64> CTimes;
65 CRecordVector<UInt64> ATimes;
66 // UInt32 FolderCrc;
50 67
51 bool Need_CTime; 68 // UInt32 GetFolderCrc() const { return CRC_GET_DIGEST(FolderCrc); }
52 bool Need_ATime; 69 // CSequentialInStreamWithCRC *_crcStream_Spec;
53 bool Need_MTime; 70 // CMyComPtr<ISequentialInStream> _crcStream;
54 bool Need_Attrib;
55
56 // CMyComPtr<IArchiveUpdateCallbackArcProp> _reportArcProp; 71 // CMyComPtr<IArchiveUpdateCallbackArcProp> _reportArcProp;
57 72
58 MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize)
59 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
60 STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value);
61
62 void Init(IArchiveUpdateCallback *updateCallback, const UInt32 *indexes, unsigned numFiles); 73 void Init(IArchiveUpdateCallback *updateCallback, const UInt32 *indexes, unsigned numFiles);
63 74
64 bool WasFinished() const { return Processed.Size() == _numFiles; } 75 bool WasFinished() const { return Processed.Size() == _numFiles; }
65 76
77 UInt64 Get_TotalSize_for_Coder() const { return _totalSize_for_Coder; }
78 /*
66 UInt64 GetFullSize() const 79 UInt64 GetFullSize() const
67 { 80 {
68 UInt64 size = 0; 81 UInt64 size = 0;
@@ -70,12 +83,16 @@ public:
70 size += Sizes[i]; 83 size += Sizes[i];
71 return size; 84 return size;
72 } 85 }
86 */
73 87
74 CFolderInStream(): 88 CFolderInStream():
89 Need_MTime(false),
75 Need_CTime(false), 90 Need_CTime(false),
76 Need_ATime(false), 91 Need_ATime(false),
77 Need_MTime(false),
78 Need_Attrib(false) 92 Need_Attrib(false)
93 // , Need_Crc(true)
94 // , Need_FolderCrc(false)
95 // , AlignLog(0)
79 {} 96 {}
80}; 97};
81 98
diff --git a/CPP/7zip/Archive/7z/7zHandler.cpp b/CPP/7zip/Archive/7z/7zHandler.cpp
index ca22f88..23d3a9d 100644
--- a/CPP/7zip/Archive/7z/7zHandler.cpp
+++ b/CPP/7zip/Archive/7z/7zHandler.cpp
@@ -7,7 +7,7 @@
7#include "../../../Common/ComTry.h" 7#include "../../../Common/ComTry.h"
8#include "../../../Common/IntToString.h" 8#include "../../../Common/IntToString.h"
9 9
10#ifndef __7Z_SET_PROPERTIES 10#ifndef Z7_7Z_SET_PROPERTIES
11#include "../../../Windows/System.h" 11#include "../../../Windows/System.h"
12#endif 12#endif
13 13
@@ -16,8 +16,8 @@
16#include "7zHandler.h" 16#include "7zHandler.h"
17#include "7zProperties.h" 17#include "7zProperties.h"
18 18
19#ifdef __7Z_SET_PROPERTIES 19#ifdef Z7_7Z_SET_PROPERTIES
20#ifdef EXTRACT_ONLY 20#ifdef Z7_EXTRACT_ONLY
21#include "../Common/ParseProperties.h" 21#include "../Common/ParseProperties.h"
22#endif 22#endif
23#endif 23#endif
@@ -30,40 +30,40 @@ namespace N7z {
30 30
31CHandler::CHandler() 31CHandler::CHandler()
32{ 32{
33 #ifndef _NO_CRYPTO 33 #ifndef Z7_NO_CRYPTO
34 _isEncrypted = false; 34 _isEncrypted = false;
35 _passwordIsDefined = false; 35 _passwordIsDefined = false;
36 #endif 36 #endif
37 37
38 #ifdef EXTRACT_ONLY 38 #ifdef Z7_EXTRACT_ONLY
39 39
40 _crcSize = 4; 40 _crcSize = 4;
41 41
42 #ifdef __7Z_SET_PROPERTIES 42 #ifdef Z7_7Z_SET_PROPERTIES
43 _useMultiThreadMixer = true; 43 _useMultiThreadMixer = true;
44 #endif 44 #endif
45 45
46 #endif 46 #endif
47} 47}
48 48
49STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 49Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
50{ 50{
51 *numItems = _db.Files.Size(); 51 *numItems = _db.Files.Size();
52 return S_OK; 52 return S_OK;
53} 53}
54 54
55#ifdef _SFX 55#ifdef Z7_SFX
56 56
57IMP_IInArchive_ArcProps_NO_Table 57IMP_IInArchive_ArcProps_NO_Table
58 58
59STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) 59Z7_COM7F_IMF(CHandler::GetNumberOfProperties(UInt32 *numProps))
60{ 60{
61 *numProps = 0; 61 *numProps = 0;
62 return S_OK; 62 return S_OK;
63} 63}
64 64
65STDMETHODIMP CHandler::GetPropertyInfo(UInt32 /* index */, 65Z7_COM7F_IMF(CHandler::GetPropertyInfo(UInt32 /* index */,
66 BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */) 66 BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */))
67{ 67{
68 return E_NOTIMPL; 68 return E_NOTIMPL;
69} 69}
@@ -110,8 +110,7 @@ static void ConvertMethodIdToString(AString &res, UInt64 id)
110 110
111static char *GetStringForSizeValue(char *s, UInt32 val) 111static char *GetStringForSizeValue(char *s, UInt32 val)
112{ 112{
113 unsigned i; 113 for (unsigned i = 0; i < 32; i++)
114 for (i = 0; i <= 31; i++)
115 if (((UInt32)1 << i) == val) 114 if (((UInt32)1 << i) == val)
116 { 115 {
117 if (i >= 10) 116 if (i >= 10)
@@ -190,15 +189,15 @@ void CHandler::AddMethodName(AString &s, UInt64 id)
190 189
191#endif 190#endif
192 191
193STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 192Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
194{ 193{
195 #ifndef _SFX 194 #ifndef Z7_SFX
196 COM_TRY_BEGIN 195 COM_TRY_BEGIN
197 #endif 196 #endif
198 NCOM::CPropVariant prop; 197 NCOM::CPropVariant prop;
199 switch (propID) 198 switch (propID)
200 { 199 {
201 #ifndef _SFX 200 #ifndef Z7_SFX
202 case kpidMethod: 201 case kpidMethod:
203 { 202 {
204 AString s; 203 AString s;
@@ -220,6 +219,12 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
220 GetStringForSizeValue(temp, pm.LzmaDic); 219 GetStringForSizeValue(temp, pm.LzmaDic);
221 s += temp; 220 s += temp;
222 } 221 }
222 /*
223 else if (id == k_ZSTD)
224 {
225 s += "ZSTD";
226 }
227 */
223 else 228 else
224 AddMethodName(s, id); 229 AddMethodName(s, id);
225 } 230 }
@@ -269,7 +274,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
269 } 274 }
270 } 275 }
271 return prop.Detach(value); 276 return prop.Detach(value);
272 #ifndef _SFX 277 #ifndef Z7_SFX
273 COM_TRY_END 278 COM_TRY_END
274 #endif 279 #endif
275} 280}
@@ -285,17 +290,17 @@ bool CHandler::IsFolderEncrypted(CNum folderIndex) const
285{ 290{
286 if (folderIndex == kNumNoIndex) 291 if (folderIndex == kNumNoIndex)
287 return false; 292 return false;
288 size_t startPos = _db.FoCodersDataOffset[folderIndex]; 293 const size_t startPos = _db.FoCodersDataOffset[folderIndex];
289 const Byte *p = _db.CodersData + startPos; 294 const Byte *p = _db.CodersData + startPos;
290 size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; 295 const size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos;
291 CInByte2 inByte; 296 CInByte2 inByte;
292 inByte.Init(p, size); 297 inByte.Init(p, size);
293 298
294 CNum numCoders = inByte.ReadNum(); 299 CNum numCoders = inByte.ReadNum();
295 for (; numCoders != 0; numCoders--) 300 for (; numCoders != 0; numCoders--)
296 { 301 {
297 Byte mainByte = inByte.ReadByte(); 302 const Byte mainByte = inByte.ReadByte();
298 unsigned idSize = (mainByte & 0xF); 303 const unsigned idSize = (mainByte & 0xF);
299 const Byte *longID = inByte.GetPtr(); 304 const Byte *longID = inByte.GetPtr();
300 UInt64 id64 = 0; 305 UInt64 id64 = 0;
301 for (unsigned j = 0; j < idSize; j++) 306 for (unsigned j = 0; j < idSize; j++)
@@ -309,20 +314,20 @@ bool CHandler::IsFolderEncrypted(CNum folderIndex) const
309 return false; 314 return false;
310} 315}
311 316
312STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 317Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
313{ 318{
314 *numProps = 0; 319 *numProps = 0;
315 return S_OK; 320 return S_OK;
316} 321}
317 322
318STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 323Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
319{ 324{
320 *name = NULL; 325 *name = NULL;
321 *propID = kpidNtSecure; 326 *propID = kpidNtSecure;
322 return S_OK; 327 return S_OK;
323} 328}
324 329
325STDMETHODIMP CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType) 330Z7_COM7F_IMF(CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType))
326{ 331{
327 /* 332 /*
328 const CFileItem &file = _db.Files[index]; 333 const CFileItem &file = _db.Files[index];
@@ -334,7 +339,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *par
334 return S_OK; 339 return S_OK;
335} 340}
336 341
337STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 342Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
338{ 343{
339 *data = NULL; 344 *data = NULL;
340 *dataSize = 0; 345 *dataSize = 0;
@@ -376,7 +381,7 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data
376 return S_OK; 381 return S_OK;
377} 382}
378 383
379#ifndef _SFX 384#ifndef Z7_SFX
380 385
381HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const 386HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
382{ 387{
@@ -389,9 +394,9 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
389 unsigned pos = kTempSize; 394 unsigned pos = kTempSize;
390 temp[--pos] = 0; 395 temp[--pos] = 0;
391 396
392 size_t startPos = _db.FoCodersDataOffset[folderIndex]; 397 const size_t startPos = _db.FoCodersDataOffset[folderIndex];
393 const Byte *p = _db.CodersData + startPos; 398 const Byte *p = _db.CodersData + startPos;
394 size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos; 399 const size_t size = _db.FoCodersDataOffset[folderIndex + 1] - startPos;
395 CInByte2 inByte; 400 CInByte2 inByte;
396 inByte.Init(p, size); 401 inByte.Init(p, size);
397 402
@@ -403,10 +408,10 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
403 { 408 {
404 if (pos < 32) // max size of property 409 if (pos < 32) // max size of property
405 break; 410 break;
406 Byte mainByte = inByte.ReadByte(); 411 const Byte mainByte = inByte.ReadByte();
407 unsigned idSize = (mainByte & 0xF);
408 const Byte *longID = inByte.GetPtr();
409 UInt64 id64 = 0; 412 UInt64 id64 = 0;
413 const unsigned idSize = (mainByte & 0xF);
414 const Byte *longID = inByte.GetPtr();
410 for (unsigned j = 0; j < idSize; j++) 415 for (unsigned j = 0; j < idSize; j++)
411 id64 = ((id64 << 8) | longID[j]); 416 id64 = ((id64 << 8) | longID[j]);
412 inByte.SkipDataNoCheck(idSize); 417 inByte.SkipDataNoCheck(idSize);
@@ -432,21 +437,21 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
432 437
433 if (id64 <= (UInt32)0xFFFFFFFF) 438 if (id64 <= (UInt32)0xFFFFFFFF)
434 { 439 {
435 UInt32 id = (UInt32)id64; 440 const UInt32 id = (UInt32)id64;
436 if (id == k_LZMA) 441 if (id == k_LZMA)
437 { 442 {
438 name = "LZMA"; 443 name = "LZMA";
439 if (propsSize == 5) 444 if (propsSize == 5)
440 { 445 {
441 UInt32 dicSize = GetUi32((const Byte *)props + 1); 446 const UInt32 dicSize = GetUi32((const Byte *)props + 1);
442 char *dest = GetStringForSizeValue(s, dicSize); 447 char *dest = GetStringForSizeValue(s, dicSize);
443 UInt32 d = props[0]; 448 UInt32 d = props[0];
444 if (d != 0x5D) 449 if (d != 0x5D)
445 { 450 {
446 UInt32 lc = d % 9; 451 const UInt32 lc = d % 9;
447 d /= 9; 452 d /= 9;
448 UInt32 pb = d / 5; 453 const UInt32 pb = d / 5;
449 UInt32 lp = d % 5; 454 const UInt32 lp = d % 5;
450 if (lc != 3) dest = AddProp32(dest, "lc", lc); 455 if (lc != 3) dest = AddProp32(dest, "lc", lc);
451 if (lp != 0) dest = AddProp32(dest, "lp", lp); 456 if (lp != 0) dest = AddProp32(dest, "lp", lp);
452 if (pb != 2) dest = AddProp32(dest, "pb", pb); 457 if (pb != 2) dest = AddProp32(dest, "pb", pb);
@@ -477,6 +482,16 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
477 if (propsSize == 1) 482 if (propsSize == 1)
478 ConvertUInt32ToString((UInt32)props[0] + 1, s); 483 ConvertUInt32ToString((UInt32)props[0] + 1, s);
479 } 484 }
485 else if (id == k_ARM64)
486 {
487 name = "ARM64";
488 if (propsSize == 4)
489 ConvertUInt32ToString(GetUi32(props), s);
490 /*
491 else if (propsSize != 0)
492 MyStringCopy(s, "unsupported");
493 */
494 }
480 else if (id == k_BCJ2) name = "BCJ2"; 495 else if (id == k_BCJ2) name = "BCJ2";
481 else if (id == k_BCJ) name = "BCJ"; 496 else if (id == k_BCJ) name = "BCJ";
482 else if (id == k_AES) 497 else if (id == k_AES)
@@ -484,8 +499,8 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
484 name = "7zAES"; 499 name = "7zAES";
485 if (propsSize >= 1) 500 if (propsSize >= 1)
486 { 501 {
487 Byte firstByte = props[0]; 502 const Byte firstByte = props[0];
488 UInt32 numCyclesPower = firstByte & 0x3F; 503 const UInt32 numCyclesPower = firstByte & 0x3F;
489 ConvertUInt32ToString(numCyclesPower, s); 504 ConvertUInt32ToString(numCyclesPower, s);
490 } 505 }
491 } 506 }
@@ -493,8 +508,8 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
493 508
494 if (name) 509 if (name)
495 { 510 {
496 unsigned nameLen = MyStringLen(name); 511 const unsigned nameLen = MyStringLen(name);
497 unsigned propsLen = MyStringLen(s); 512 const unsigned propsLen = MyStringLen(s);
498 unsigned totalLen = nameLen + propsLen; 513 unsigned totalLen = nameLen + propsLen;
499 if (propsLen != 0) 514 if (propsLen != 0)
500 totalLen++; 515 totalLen++;
@@ -523,7 +538,7 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
523 pos -= ConvertMethodIdToString_Back(temp + pos, id64); 538 pos -= ConvertMethodIdToString_Back(temp + pos, id64);
524 else 539 else
525 { 540 {
526 unsigned len = methodName.Len(); 541 const unsigned len = methodName.Len();
527 if (len + 5 > pos) 542 if (len + 5 > pos)
528 break; 543 break;
529 pos -= len; 544 pos -= len;
@@ -547,9 +562,9 @@ HRESULT CHandler::SetMethodToProp(CNum folderIndex, PROPVARIANT *prop) const
547 562
548#endif 563#endif
549 564
550STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 565Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
551{ 566{
552 RINOK(PropVariant_Clear(value)); 567 RINOK(PropVariant_Clear(value))
553 // COM_TRY_BEGIN 568 // COM_TRY_BEGIN
554 // NCOM::CPropVariant prop; 569 // NCOM::CPropVariant prop;
555 570
@@ -576,7 +591,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
576 { 591 {
577 // prop = ref2.PackSize; 592 // prop = ref2.PackSize;
578 { 593 {
579 CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; 594 const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
580 if (folderIndex != kNumNoIndex) 595 if (folderIndex != kNumNoIndex)
581 { 596 {
582 if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2) 597 if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2)
@@ -617,24 +632,24 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
617 632
618 case kpidPath: return _db.GetPath_Prop(index, value); 633 case kpidPath: return _db.GetPath_Prop(index, value);
619 634
620 #ifndef _SFX 635 #ifndef Z7_SFX
621 636
622 case kpidMethod: return SetMethodToProp(_db.FileIndexToFolderIndexMap[index2], value); 637 case kpidMethod: return SetMethodToProp(_db.FileIndexToFolderIndexMap[index2], value);
623 case kpidBlock: 638 case kpidBlock:
624 { 639 {
625 CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; 640 const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
626 if (folderIndex != kNumNoIndex) 641 if (folderIndex != kNumNoIndex)
627 PropVarEm_Set_UInt32(value, (UInt32)folderIndex); 642 PropVarEm_Set_UInt32(value, (UInt32)folderIndex);
628 } 643 }
629 break; 644 break;
630 /* 645 #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES
631 case kpidPackedSize0: 646 case kpidPackedSize0:
632 case kpidPackedSize1: 647 case kpidPackedSize1:
633 case kpidPackedSize2: 648 case kpidPackedSize2:
634 case kpidPackedSize3: 649 case kpidPackedSize3:
635 case kpidPackedSize4: 650 case kpidPackedSize4:
636 { 651 {
637 CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; 652 const CNum folderIndex = _db.FileIndexToFolderIndexMap[index2];
638 if (folderIndex != kNumNoIndex) 653 if (folderIndex != kNumNoIndex)
639 { 654 {
640 if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 && 655 if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 &&
@@ -648,7 +663,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
648 PropVarEm_Set_UInt64(value, 0); 663 PropVarEm_Set_UInt64(value, 0);
649 } 664 }
650 break; 665 break;
651 */ 666 #endif
652 667
653 #endif 668 #endif
654 } 669 }
@@ -657,13 +672,13 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
657 // COM_TRY_END 672 // COM_TRY_END
658} 673}
659 674
660STDMETHODIMP CHandler::Open(IInStream *stream, 675Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
661 const UInt64 *maxCheckStartPosition, 676 const UInt64 *maxCheckStartPosition,
662 IArchiveOpenCallback *openArchiveCallback) 677 IArchiveOpenCallback *openArchiveCallback))
663{ 678{
664 COM_TRY_BEGIN 679 COM_TRY_BEGIN
665 Close(); 680 Close();
666 #ifndef _SFX 681 #ifndef Z7_SFX
667 _fileInfoPopIDs.Clear(); 682 _fileInfoPopIDs.Clear();
668 #endif 683 #endif
669 684
@@ -671,31 +686,31 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
671 { 686 {
672 CMyComPtr<IArchiveOpenCallback> openArchiveCallbackTemp = openArchiveCallback; 687 CMyComPtr<IArchiveOpenCallback> openArchiveCallbackTemp = openArchiveCallback;
673 688
674 #ifndef _NO_CRYPTO 689 #ifndef Z7_NO_CRYPTO
675 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 690 CMyComPtr<ICryptoGetTextPassword> getTextPassword;
676 if (openArchiveCallback) 691 if (openArchiveCallback)
677 openArchiveCallbackTemp.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); 692 openArchiveCallbackTemp.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword);
678 #endif 693 #endif
679 694
680 CInArchive archive( 695 CInArchive archive(
681 #ifdef __7Z_SET_PROPERTIES 696 #ifdef Z7_7Z_SET_PROPERTIES
682 _useMultiThreadMixer 697 _useMultiThreadMixer
683 #else 698 #else
684 true 699 true
685 #endif 700 #endif
686 ); 701 );
687 _db.IsArc = false; 702 _db.IsArc = false;
688 RINOK(archive.Open(stream, maxCheckStartPosition)); 703 RINOK(archive.Open(stream, maxCheckStartPosition))
689 _db.IsArc = true; 704 _db.IsArc = true;
690 705
691 HRESULT result = archive.ReadDatabase( 706 HRESULT result = archive.ReadDatabase(
692 EXTERNAL_CODECS_VARS 707 EXTERNAL_CODECS_VARS
693 _db 708 _db
694 #ifndef _NO_CRYPTO 709 #ifndef Z7_NO_CRYPTO
695 , getTextPassword, _isEncrypted, _passwordIsDefined, _password 710 , getTextPassword, _isEncrypted, _passwordIsDefined, _password
696 #endif 711 #endif
697 ); 712 );
698 RINOK(result); 713 RINOK(result)
699 714
700 _inStream = stream; 715 _inStream = stream;
701 } 716 }
@@ -708,19 +723,19 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
708 return E_OUTOFMEMORY; 723 return E_OUTOFMEMORY;
709 } 724 }
710 // _inStream = stream; 725 // _inStream = stream;
711 #ifndef _SFX 726 #ifndef Z7_SFX
712 FillPopIDs(); 727 FillPopIDs();
713 #endif 728 #endif
714 return S_OK; 729 return S_OK;
715 COM_TRY_END 730 COM_TRY_END
716} 731}
717 732
718STDMETHODIMP CHandler::Close() 733Z7_COM7F_IMF(CHandler::Close())
719{ 734{
720 COM_TRY_BEGIN 735 COM_TRY_BEGIN
721 _inStream.Release(); 736 _inStream.Release();
722 _db.Clear(); 737 _db.Clear();
723 #ifndef _NO_CRYPTO 738 #ifndef Z7_NO_CRYPTO
724 _isEncrypted = false; 739 _isEncrypted = false;
725 _passwordIsDefined = false; 740 _passwordIsDefined = false;
726 _password.Wipe_and_Empty(); 741 _password.Wipe_and_Empty();
@@ -729,10 +744,10 @@ STDMETHODIMP CHandler::Close()
729 COM_TRY_END 744 COM_TRY_END
730} 745}
731 746
732#ifdef __7Z_SET_PROPERTIES 747#ifdef Z7_7Z_SET_PROPERTIES
733#ifdef EXTRACT_ONLY 748#ifdef Z7_EXTRACT_ONLY
734 749
735STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 750Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
736{ 751{
737 COM_TRY_BEGIN 752 COM_TRY_BEGIN
738 753
@@ -747,19 +762,19 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
747 return E_INVALIDARG; 762 return E_INVALIDARG;
748 const PROPVARIANT &value = values[i]; 763 const PROPVARIANT &value = values[i];
749 UInt32 number; 764 UInt32 number;
750 unsigned index = ParseStringToUInt32(name, number); 765 const unsigned index = ParseStringToUInt32(name, number);
751 if (index == 0) 766 if (index == 0)
752 { 767 {
753 if (name.IsEqualTo("mtf")) 768 if (name.IsEqualTo("mtf"))
754 { 769 {
755 RINOK(PROPVARIANT_to_bool(value, _useMultiThreadMixer)); 770 RINOK(PROPVARIANT_to_bool(value, _useMultiThreadMixer))
756 continue; 771 continue;
757 } 772 }
758 { 773 {
759 HRESULT hres; 774 HRESULT hres;
760 if (SetCommonProperty(name, value, hres)) 775 if (SetCommonProperty(name, value, hres))
761 { 776 {
762 RINOK(hres); 777 RINOK(hres)
763 continue; 778 continue;
764 } 779 }
765 } 780 }
diff --git a/CPP/7zip/Archive/7z/7zHandler.h b/CPP/7zip/Archive/7z/7zHandler.h
index 08bd654..b1c0466 100644
--- a/CPP/7zip/Archive/7z/7zHandler.h
+++ b/CPP/7zip/Archive/7z/7zHandler.h
@@ -1,26 +1,26 @@
1// 7z/Handler.h 1// 7z/Handler.h
2 2
3#ifndef __7Z_HANDLER_H 3#ifndef ZIP7_7Z_HANDLER_H
4#define __7Z_HANDLER_H 4#define ZIP7_7Z_HANDLER_H
5 5
6#include "../../ICoder.h" 6#include "../../ICoder.h"
7#include "../IArchive.h" 7#include "../IArchive.h"
8 8
9#include "../../Common/CreateCoder.h" 9#include "../../Common/CreateCoder.h"
10 10
11#ifndef __7Z_SET_PROPERTIES 11#ifndef Z7_7Z_SET_PROPERTIES
12 12
13#ifdef EXTRACT_ONLY 13#ifdef Z7_EXTRACT_ONLY
14 #if !defined(_7ZIP_ST) && !defined(_SFX) 14 #if !defined(Z7_ST) && !defined(Z7_SFX)
15 #define __7Z_SET_PROPERTIES 15 #define Z7_7Z_SET_PROPERTIES
16 #endif 16 #endif
17#else 17#else
18 #define __7Z_SET_PROPERTIES 18 #define Z7_7Z_SET_PROPERTIES
19#endif 19#endif
20 20
21#endif 21#endif
22 22
23// #ifdef __7Z_SET_PROPERTIES 23// #ifdef Z7_7Z_SET_PROPERTIES
24#include "../Common/HandlerOut.h" 24#include "../Common/HandlerOut.h"
25// #endif 25// #endif
26 26
@@ -31,7 +31,7 @@ namespace NArchive {
31namespace N7z { 31namespace N7z {
32 32
33 33
34#ifndef EXTRACT_ONLY 34#ifndef Z7_EXTRACT_ONLY
35 35
36class COutHandler: public CMultiMethodProps 36class COutHandler: public CMultiMethodProps
37{ 37{
@@ -79,73 +79,63 @@ public:
79 79
80#endif 80#endif
81 81
82class CHandler: 82class CHandler Z7_final:
83 public IInArchive, 83 public IInArchive,
84 public IArchiveGetRawProps, 84 public IArchiveGetRawProps,
85 85
86 #ifdef __7Z_SET_PROPERTIES 86 #ifdef Z7_7Z_SET_PROPERTIES
87 public ISetProperties, 87 public ISetProperties,
88 #endif 88 #endif
89 89
90 #ifndef EXTRACT_ONLY 90 #ifndef Z7_EXTRACT_ONLY
91 public IOutArchive, 91 public IOutArchive,
92 #endif 92 #endif
93 93
94 PUBLIC_ISetCompressCodecsInfo 94 Z7_PUBLIC_ISetCompressCodecsInfo_IFEC
95 95
96 public CMyUnknownImp, 96 public CMyUnknownImp,
97 97
98 #ifndef EXTRACT_ONLY 98 #ifndef Z7_EXTRACT_ONLY
99 public COutHandler 99 public COutHandler
100 #else 100 #else
101 public CCommonMethodProps 101 public CCommonMethodProps
102 #endif 102 #endif
103{ 103{
104public: 104 Z7_COM_QI_BEGIN2(IInArchive)
105 MY_QUERYINTERFACE_BEGIN2(IInArchive) 105 Z7_COM_QI_ENTRY(IArchiveGetRawProps)
106 MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) 106 #ifdef Z7_7Z_SET_PROPERTIES
107 #ifdef __7Z_SET_PROPERTIES 107 Z7_COM_QI_ENTRY(ISetProperties)
108 MY_QUERYINTERFACE_ENTRY(ISetProperties) 108 #endif
109 #endif 109 #ifndef Z7_EXTRACT_ONLY
110 #ifndef EXTRACT_ONLY 110 Z7_COM_QI_ENTRY(IOutArchive)
111 MY_QUERYINTERFACE_ENTRY(IOutArchive) 111 #endif
112 #endif 112 Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC
113 QUERY_ENTRY_ISetCompressCodecsInfo 113 Z7_COM_QI_END
114 MY_QUERYINTERFACE_END 114 Z7_COM_ADDREF_RELEASE
115 MY_ADDREF_RELEASE 115
116 116 Z7_IFACE_COM7_IMP(IInArchive)
117 INTERFACE_IInArchive(;) 117 Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
118 INTERFACE_IArchiveGetRawProps(;) 118 #ifdef Z7_7Z_SET_PROPERTIES
119 119 Z7_IFACE_COM7_IMP(ISetProperties)
120 #ifdef __7Z_SET_PROPERTIES 120 #endif
121 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps); 121 #ifndef Z7_EXTRACT_ONLY
122 #endif 122 Z7_IFACE_COM7_IMP(IOutArchive)
123 123 #endif
124 #ifndef EXTRACT_ONLY
125 INTERFACE_IOutArchive(;)
126 #endif
127
128 DECL_ISetCompressCodecsInfo 124 DECL_ISetCompressCodecsInfo
129 125
130 CHandler();
131 ~CHandler()
132 {
133 Close();
134 }
135
136private: 126private:
137 CMyComPtr<IInStream> _inStream; 127 CMyComPtr<IInStream> _inStream;
138 NArchive::N7z::CDbEx _db; 128 NArchive::N7z::CDbEx _db;
139 129
140 #ifndef _NO_CRYPTO 130 #ifndef Z7_NO_CRYPTO
141 bool _isEncrypted; 131 bool _isEncrypted;
142 bool _passwordIsDefined; 132 bool _passwordIsDefined;
143 UString _password; // _Wipe 133 UString _password; // _Wipe
144 #endif 134 #endif
145 135
146 #ifdef EXTRACT_ONLY 136 #ifdef Z7_EXTRACT_ONLY
147 137
148 #ifdef __7Z_SET_PROPERTIES 138 #ifdef Z7_7Z_SET_PROPERTIES
149 bool _useMultiThreadMixer; 139 bool _useMultiThreadMixer;
150 #endif 140 #endif
151 141
@@ -162,7 +152,7 @@ private:
162 #endif 152 #endif
163 153
164 bool IsFolderEncrypted(CNum folderIndex) const; 154 bool IsFolderEncrypted(CNum folderIndex) const;
165 #ifndef _SFX 155 #ifndef Z7_SFX
166 156
167 CRecordVector<UInt64> _fileInfoPopIDs; 157 CRecordVector<UInt64> _fileInfoPopIDs;
168 void FillPopIDs(); 158 void FillPopIDs();
@@ -172,6 +162,13 @@ private:
172 #endif 162 #endif
173 163
174 DECL_EXTERNAL_CODECS_VARS 164 DECL_EXTERNAL_CODECS_VARS
165
166public:
167 CHandler();
168 ~CHandler()
169 {
170 Close();
171 }
175}; 172};
176 173
177}} 174}}
diff --git a/CPP/7zip/Archive/7z/7zHandlerOut.cpp b/CPP/7zip/Archive/7z/7zHandlerOut.cpp
index bf4e7a6..ff8735f 100644
--- a/CPP/7zip/Archive/7z/7zHandlerOut.cpp
+++ b/CPP/7zip/Archive/7z/7zHandlerOut.cpp
@@ -13,7 +13,7 @@
13#include "7zOut.h" 13#include "7zOut.h"
14#include "7zUpdate.h" 14#include "7zUpdate.h"
15 15
16#ifndef EXTRACT_ONLY 16#ifndef Z7_EXTRACT_ONLY
17 17
18using namespace NWindows; 18using namespace NWindows;
19 19
@@ -35,7 +35,7 @@ static const UInt32 k_Dictionary_ForHeaders =
35 1 << 20; 35 1 << 20;
36 #endif 36 #endif
37 37
38STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 38Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type))
39{ 39{
40 *type = NFileTimeType::kWindows; 40 *type = NFileTimeType::kWindows;
41 return S_OK; 41 return S_OK;
@@ -43,10 +43,11 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type)
43 43
44HRESULT CHandler::PropsMethod_To_FullMethod(CMethodFull &dest, const COneMethodInfo &m) 44HRESULT CHandler::PropsMethod_To_FullMethod(CMethodFull &dest, const COneMethodInfo &m)
45{ 45{
46 bool isFilter;
46 dest.CodecIndex = FindMethod_Index( 47 dest.CodecIndex = FindMethod_Index(
47 EXTERNAL_CODECS_VARS 48 EXTERNAL_CODECS_VARS
48 m.MethodName, true, 49 m.MethodName, true,
49 dest.Id, dest.NumStreams); 50 dest.Id, dest.NumStreams, isFilter);
50 if (dest.CodecIndex < 0) 51 if (dest.CodecIndex < 0)
51 return E_INVALIDARG; 52 return E_INVALIDARG;
52 (CProps &)dest = (CProps &)m; 53 (CProps &)dest = (CProps &)m;
@@ -118,7 +119,7 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode)
118 119
119 SetGlobalLevelTo(oneMethodInfo); 120 SetGlobalLevelTo(oneMethodInfo);
120 121
121 #ifndef _7ZIP_ST 122 #ifndef Z7_ST
122 const bool numThreads_WasSpecifiedInMethod = (oneMethodInfo.Get_NumThreads() >= 0); 123 const bool numThreads_WasSpecifiedInMethod = (oneMethodInfo.Get_NumThreads() >= 0);
123 if (!numThreads_WasSpecifiedInMethod) 124 if (!numThreads_WasSpecifiedInMethod)
124 { 125 {
@@ -128,9 +129,9 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode)
128 #endif 129 #endif
129 130
130 CMethodFull &methodFull = methodMode.Methods.AddNew(); 131 CMethodFull &methodFull = methodMode.Methods.AddNew();
131 RINOK(PropsMethod_To_FullMethod(methodFull, oneMethodInfo)); 132 RINOK(PropsMethod_To_FullMethod(methodFull, oneMethodInfo))
132 133
133 #ifndef _7ZIP_ST 134 #ifndef Z7_ST
134 methodFull.Set_NumThreads = true; 135 methodFull.Set_NumThreads = true;
135 methodFull.NumThreads = methodMode.NumThreads; 136 methodFull.NumThreads = methodMode.NumThreads;
136 #endif 137 #endif
@@ -147,15 +148,55 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode)
147 case k_Deflate: dicSize = (UInt32)1 << 15; break; 148 case k_Deflate: dicSize = (UInt32)1 << 15; break;
148 case k_Deflate64: dicSize = (UInt32)1 << 16; break; 149 case k_Deflate64: dicSize = (UInt32)1 << 16; break;
149 case k_BZip2: dicSize = oneMethodInfo.Get_BZip2_BlockSize(); break; 150 case k_BZip2: dicSize = oneMethodInfo.Get_BZip2_BlockSize(); break;
151 // case k_ZSTD: dicSize = 1 << 23; break;
150 default: continue; 152 default: continue;
151 } 153 }
152 154
153 UInt64 numSolidBytes; 155 UInt64 numSolidBytes;
154 156
157 /*
158 if (methodFull.Id == k_ZSTD)
159 {
160 // continue;
161 NCompress::NZstd::CEncoderProps encoderProps;
162 RINOK(oneMethodInfo.Set_PropsTo_zstd(encoderProps));
163 CZstdEncProps &zstdProps = encoderProps.EncProps;
164 ZstdEncProps_NormalizeFull(&zstdProps);
165 UInt64 cs = (UInt64)(zstdProps.jobSize);
166 UInt32 winSize = (UInt32)(1 << zstdProps.windowLog);
167 if (cs < winSize)
168 cs = winSize;
169 numSolidBytes = cs << 6;
170 const UInt64 kSolidBytes_Zstd_Max = ((UInt64)1 << 34);
171 if (numSolidBytes > kSolidBytes_Zstd_Max)
172 numSolidBytes = kSolidBytes_Zstd_Max;
173
174 methodFull.Set_NumThreads = false; // we don't use ICompressSetCoderMt::SetNumberOfThreads() for LZMA2 encoder
175
176 #ifndef Z7_ST
177 if (!numThreads_WasSpecifiedInMethod
178 && !methodMode.NumThreads_WasForced
179 && methodMode.MemoryUsageLimit_WasSet
180 )
181 {
182 const UInt32 numThreads_Original = methodMode.NumThreads;
183 const UInt32 numThreads_New = ZstdEncProps_GetNumThreads_for_MemUsageLimit(
184 &zstdProps,
185 methodMode.MemoryUsageLimit,
186 numThreads_Original);
187 if (numThreads_Original != numThreads_New)
188 {
189 CMultiMethodProps::SetMethodThreadsTo_Replace(methodFull, numThreads_New);
190 }
191 }
192 #endif
193 }
194 else
195 */
155 if (methodFull.Id == k_LZMA2) 196 if (methodFull.Id == k_LZMA2)
156 { 197 {
157 // he we calculate default chunk Size for LZMA2 as defined in LZMA2 encoder code 198 // he we calculate default chunk Size for LZMA2 as defined in LZMA2 encoder code
158 /* lzma2 code use dictionary upo to fake 4 GiB to calculate ChunkSize. 199 /* lzma2 code use dictionary up to fake 4 GiB to calculate ChunkSize.
159 So we do same */ 200 So we do same */
160 UInt64 cs = (UInt64)dicSize << 2; 201 UInt64 cs = (UInt64)dicSize << 2;
161 const UInt32 kMinSize = (UInt32)1 << 20; 202 const UInt32 kMinSize = (UInt32)1 << 20;
@@ -167,10 +208,10 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode)
167 cs &= ~(UInt64)(kMinSize - 1); 208 cs &= ~(UInt64)(kMinSize - 1);
168 // we want to use at least 64 chunks (threads) per one solid block. 209 // we want to use at least 64 chunks (threads) per one solid block.
169 210
170 // here we don't use chunckSize property 211 // here we don't use chunkSize property
171 numSolidBytes = cs << 6; 212 numSolidBytes = cs << 6;
172 213
173 // here we get real chunckSize 214 // here we get real chunkSize
174 cs = oneMethodInfo.Get_Xz_BlockSize(); 215 cs = oneMethodInfo.Get_Xz_BlockSize();
175 if (dicSize > cs) 216 if (dicSize > cs)
176 dicSize = cs; 217 dicSize = cs;
@@ -181,7 +222,7 @@ HRESULT CHandler::SetMainMethod(CCompressionMethodMode &methodMode)
181 222
182 methodFull.Set_NumThreads = false; // we don't use ICompressSetCoderMt::SetNumberOfThreads() for LZMA2 encoder 223 methodFull.Set_NumThreads = false; // we don't use ICompressSetCoderMt::SetNumberOfThreads() for LZMA2 encoder
183 224
184 #ifndef _7ZIP_ST 225 #ifndef Z7_ST
185 if (!numThreads_WasSpecifiedInMethod 226 if (!numThreads_WasSpecifiedInMethod
186 && !methodMode.NumThreads_WasForced 227 && !methodMode.NumThreads_WasForced
187 && methodMode.MemoryUsageLimit_WasSet 228 && methodMode.MemoryUsageLimit_WasSet
@@ -261,7 +302,7 @@ static HRESULT GetTime(IArchiveUpdateCallback *updateCallback, unsigned index, P
261 // ft = 0; 302 // ft = 0;
262 // ftDefined = false; 303 // ftDefined = false;
263 NCOM::CPropVariant prop; 304 NCOM::CPropVariant prop;
264 RINOK(updateCallback->GetProperty(index, propID, &prop)); 305 RINOK(updateCallback->GetProperty(index, propID, &prop))
265 if (prop.vt == VT_FILETIME) 306 if (prop.vt == VT_FILETIME)
266 { 307 {
267 ft = prop.filetime.dwLowDateTime | ((UInt64)prop.filetime.dwHighDateTime << 32); 308 ft = prop.filetime.dwLowDateTime | ((UInt64)prop.filetime.dwHighDateTime << 32);
@@ -344,13 +385,13 @@ static int AddFolder(CObjectVector<CTreeFolder> &treeFolders, int cur, const USt
344} 385}
345*/ 386*/
346 387
347STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 388Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
348 IArchiveUpdateCallback *updateCallback) 389 IArchiveUpdateCallback *updateCallback))
349{ 390{
350 COM_TRY_BEGIN 391 COM_TRY_BEGIN
351 392
352 const CDbEx *db = 0; 393 const CDbEx *db = NULL;
353 #ifdef _7Z_VOL 394 #ifdef Z7_7Z_VOL
354 if (_volumes.Size() > 1) 395 if (_volumes.Size() > 1)
355 return E_FAIL; 396 return E_FAIL;
356 const CVolume *volume = 0; 397 const CVolume *volume = 0;
@@ -360,7 +401,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
360 db = &volume->Database; 401 db = &volume->Database;
361 } 402 }
362 #else 403 #else
363 if (_inStream != 0) 404 if (_inStream)
364 db = &_db; 405 db = &_db;
365 #endif 406 #endif
366 407
@@ -368,8 +409,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
368 return E_NOTIMPL; 409 return E_NOTIMPL;
369 410
370 /* 411 /*
371 CMyComPtr<IArchiveGetRawProps> getRawProps; 412 Z7_DECL_CMyComPtr_QI_FROM(
372 updateCallback->QueryInterface(IID_IArchiveGetRawProps, (void **)&getRawProps); 413 IArchiveGetRawProps,
414 getRawProps, updateCallback)
373 415
374 CUniqBlocks secureBlocks; 416 CUniqBlocks secureBlocks;
375 secureBlocks.AddUniq(NULL, 0); 417 secureBlocks.AddUniq(NULL, 0);
@@ -406,7 +448,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
406 UInt32 indexInArchive; 448 UInt32 indexInArchive;
407 if (!updateCallback) 449 if (!updateCallback)
408 return E_FAIL; 450 return E_FAIL;
409 RINOK(updateCallback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); 451 RINOK(updateCallback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive))
410 CUpdateItem ui; 452 CUpdateItem ui;
411 ui.NewProps = IntToBool(newProps); 453 ui.NewProps = IntToBool(newProps);
412 ui.NewData = IntToBool(newData); 454 ui.NewData = IntToBool(newData);
@@ -445,7 +487,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
445 if (need_Attrib) 487 if (need_Attrib)
446 { 488 {
447 NCOM::CPropVariant prop; 489 NCOM::CPropVariant prop;
448 RINOK(updateCallback->GetProperty(i, kpidAttrib, &prop)); 490 RINOK(updateCallback->GetProperty(i, kpidAttrib, &prop))
449 if (prop.vt == VT_EMPTY) 491 if (prop.vt == VT_EMPTY)
450 ui.AttribDefined = false; 492 ui.AttribDefined = false;
451 else if (prop.vt != VT_UI4) 493 else if (prop.vt != VT_UI4)
@@ -458,9 +500,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
458 } 500 }
459 501
460 // we need MTime to sort files. 502 // we need MTime to sort files.
461 if (need_CTime) RINOK(GetTime(updateCallback, i, kpidCTime, ui.CTime, ui.CTimeDefined)); 503 if (need_CTime) RINOK(GetTime(updateCallback, i, kpidCTime, ui.CTime, ui.CTimeDefined))
462 if (need_ATime) RINOK(GetTime(updateCallback, i, kpidATime, ui.ATime, ui.ATimeDefined)); 504 if (need_ATime) RINOK(GetTime(updateCallback, i, kpidATime, ui.ATime, ui.ATimeDefined))
463 if (need_MTime) RINOK(GetTime(updateCallback, i, kpidMTime, ui.MTime, ui.MTimeDefined)); 505 if (need_MTime) RINOK(GetTime(updateCallback, i, kpidMTime, ui.MTime, ui.MTimeDefined))
464 506
465 /* 507 /*
466 if (getRawProps) 508 if (getRawProps)
@@ -478,7 +520,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
478 520
479 { 521 {
480 NCOM::CPropVariant prop; 522 NCOM::CPropVariant prop;
481 RINOK(updateCallback->GetProperty(i, kpidPath, &prop)); 523 RINOK(updateCallback->GetProperty(i, kpidPath, &prop))
482 if (prop.vt == VT_EMPTY) 524 if (prop.vt == VT_EMPTY)
483 { 525 {
484 } 526 }
@@ -492,7 +534,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
492 } 534 }
493 { 535 {
494 NCOM::CPropVariant prop; 536 NCOM::CPropVariant prop;
495 RINOK(updateCallback->GetProperty(i, kpidIsDir, &prop)); 537 RINOK(updateCallback->GetProperty(i, kpidIsDir, &prop))
496 if (prop.vt == VT_EMPTY) 538 if (prop.vt == VT_EMPTY)
497 folderStatusIsDefined = false; 539 folderStatusIsDefined = false;
498 else if (prop.vt != VT_BOOL) 540 else if (prop.vt != VT_BOOL)
@@ -506,7 +548,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
506 548
507 { 549 {
508 NCOM::CPropVariant prop; 550 NCOM::CPropVariant prop;
509 RINOK(updateCallback->GetProperty(i, kpidIsAnti, &prop)); 551 RINOK(updateCallback->GetProperty(i, kpidIsAnti, &prop))
510 if (prop.vt == VT_EMPTY) 552 if (prop.vt == VT_EMPTY)
511 ui.IsAnti = false; 553 ui.IsAnti = false;
512 else if (prop.vt != VT_BOOL) 554 else if (prop.vt != VT_BOOL)
@@ -623,7 +665,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
623 if (!ui.IsDir) 665 if (!ui.IsDir)
624 { 666 {
625 NCOM::CPropVariant prop; 667 NCOM::CPropVariant prop;
626 RINOK(updateCallback->GetProperty(i, kpidSize, &prop)); 668 RINOK(updateCallback->GetProperty(i, kpidSize, &prop))
627 if (prop.vt != VT_UI8) 669 if (prop.vt != VT_UI8)
628 return E_INVALIDARG; 670 return E_INVALIDARG;
629 ui.Size = (UInt64)prop.uhVal.QuadPart; 671 ui.Size = (UInt64)prop.uhVal.QuadPart;
@@ -650,7 +692,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
650 methodMode.MemoryUsageLimit = _memUsage_Compress; 692 methodMode.MemoryUsageLimit = _memUsage_Compress;
651 methodMode.MemoryUsageLimit_WasSet = _memUsage_WasSet; 693 methodMode.MemoryUsageLimit_WasSet = _memUsage_WasSet;
652 694
653 #ifndef _7ZIP_ST 695 #ifndef Z7_ST
654 { 696 {
655 UInt32 numThreads = _numThreads; 697 UInt32 numThreads = _numThreads;
656 const UInt32 kNumThreads_Max = 1024; 698 const UInt32 kNumThreads_Max = 1024;
@@ -664,13 +706,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
664 } 706 }
665 #endif 707 #endif
666 708
667 HRESULT res = SetMainMethod(methodMode); 709 const HRESULT res = SetMainMethod(methodMode);
668 RINOK(res); 710 RINOK(res)
669 711
670 RINOK(SetHeaderMethod(headerMethod)); 712 RINOK(SetHeaderMethod(headerMethod))
671 713
672 CMyComPtr<ICryptoGetTextPassword2> getPassword2; 714 Z7_DECL_CMyComPtr_QI_FROM(
673 updateCallback->QueryInterface(IID_ICryptoGetTextPassword2, (void **)&getPassword2); 715 ICryptoGetTextPassword2,
716 getPassword2, updateCallback)
674 717
675 methodMode.PasswordIsDefined = false; 718 methodMode.PasswordIsDefined = false;
676 methodMode.Password.Wipe_and_Empty(); 719 methodMode.Password.Wipe_and_Empty();
@@ -678,7 +721,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
678 { 721 {
679 CMyComBSTR_Wipe password; 722 CMyComBSTR_Wipe password;
680 Int32 passwordIsDefined; 723 Int32 passwordIsDefined;
681 RINOK(getPassword2->CryptoGetTextPassword2(&passwordIsDefined, &password)); 724 RINOK(getPassword2->CryptoGetTextPassword2(&passwordIsDefined, &password))
682 methodMode.PasswordIsDefined = IntToBool(passwordIsDefined); 725 methodMode.PasswordIsDefined = IntToBool(passwordIsDefined);
683 if (methodMode.PasswordIsDefined && password) 726 if (methodMode.PasswordIsDefined && password)
684 methodMode.Password = password; 727 methodMode.Password = password;
@@ -688,7 +731,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
688 731
689 bool encryptHeaders = false; 732 bool encryptHeaders = false;
690 733
691 #ifndef _NO_CRYPTO 734 #ifndef Z7_NO_CRYPTO
692 if (!methodMode.PasswordIsDefined && _passwordIsDefined) 735 if (!methodMode.PasswordIsDefined && _passwordIsDefined)
693 { 736 {
694 // if header is compressed, we use that password for updated archive 737 // if header is compressed, we use that password for updated archive
@@ -701,7 +744,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
701 { 744 {
702 if (_encryptHeadersSpecified) 745 if (_encryptHeadersSpecified)
703 encryptHeaders = _encryptHeaders; 746 encryptHeaders = _encryptHeaders;
704 #ifndef _NO_CRYPTO 747 #ifndef Z7_NO_CRYPTO
705 else 748 else
706 encryptHeaders = _passwordIsDefined; 749 encryptHeaders = _passwordIsDefined;
707 #endif 750 #endif
@@ -716,13 +759,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
716 if (numItems < 2) 759 if (numItems < 2)
717 compressMainHeader = false; 760 compressMainHeader = false;
718 761
719 int level = GetLevel(); 762 const int level = GetLevel();
720 763
721 CUpdateOptions options; 764 CUpdateOptions options;
722 options.Need_CTime = need_CTime; 765 options.Need_CTime = need_CTime;
723 options.Need_ATime = need_ATime; 766 options.Need_ATime = need_ATime;
724 options.Need_MTime = need_MTime; 767 options.Need_MTime = need_MTime;
725 options.Need_Attrib = need_Attrib; 768 options.Need_Attrib = need_Attrib;
769 // options.Need_Crc = (_crcSize != 0); // for debug
726 770
727 options.Method = &methodMode; 771 options.Method = &methodMode;
728 options.HeaderMethod = (_compressHeaders || encryptHeaders) ? &headerMethod : NULL; 772 options.HeaderMethod = (_compressHeaders || encryptHeaders) ? &headerMethod : NULL;
@@ -748,12 +792,6 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
748 792
749 options.MultiThreadMixer = _useMultiThreadMixer; 793 options.MultiThreadMixer = _useMultiThreadMixer;
750 794
751 COutArchive archive;
752 CArchiveDatabaseOut newDatabase;
753
754 CMyComPtr<ICryptoGetTextPassword> getPassword;
755 updateCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getPassword);
756
757 /* 795 /*
758 if (secureBlocks.Sorted.Size() > 1) 796 if (secureBlocks.Sorted.Size() > 1)
759 { 797 {
@@ -766,9 +804,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
766 } 804 }
767 */ 805 */
768 806
769 res = Update( 807 return Update(
770 EXTERNAL_CODECS_VARS 808 EXTERNAL_CODECS_VARS
771 #ifdef _7Z_VOL 809 #ifdef Z7_7Z_VOL
772 volume ? volume->Stream: 0, 810 volume ? volume->Stream: 0,
773 volume ? db : 0, 811 volume ? db : 0,
774 #else 812 #else
@@ -778,18 +816,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
778 updateItems, 816 updateItems,
779 // treeFolders, 817 // treeFolders,
780 // secureBlocks, 818 // secureBlocks,
781 archive, newDatabase, outStream, updateCallback, options 819 outStream, updateCallback, options);
782 #ifndef _NO_CRYPTO
783 , getPassword
784 #endif
785 );
786
787 RINOK(res);
788
789 updateItems.ClearAndFree();
790
791 return archive.WriteDatabase(EXTERNAL_CODECS_VARS
792 newDatabase, options.HeaderMethod, options.HeaderOptions);
793 820
794 COM_TRY_END 821 COM_TRY_END
795} 822}
@@ -798,7 +825,7 @@ static HRESULT ParseBond(UString &srcString, UInt32 &coder, UInt32 &stream)
798{ 825{
799 stream = 0; 826 stream = 0;
800 { 827 {
801 unsigned index = ParseStringToUInt32(srcString, coder); 828 const unsigned index = ParseStringToUInt32(srcString, coder);
802 if (index == 0) 829 if (index == 0)
803 return E_INVALIDARG; 830 return E_INVALIDARG;
804 srcString.DeleteFrontal(index); 831 srcString.DeleteFrontal(index);
@@ -806,7 +833,7 @@ static HRESULT ParseBond(UString &srcString, UInt32 &coder, UInt32 &stream)
806 if (srcString[0] == 's') 833 if (srcString[0] == 's')
807 { 834 {
808 srcString.Delete(0); 835 srcString.Delete(0);
809 unsigned index = ParseStringToUInt32(srcString, stream); 836 const unsigned index = ParseStringToUInt32(srcString, stream);
810 if (index == 0) 837 if (index == 0)
811 return E_INVALIDARG; 838 return E_INVALIDARG;
812 srcString.DeleteFrontal(index); 839 srcString.DeleteFrontal(index);
@@ -860,7 +887,7 @@ HRESULT COutHandler::SetSolidFromString(const UString &s)
860 i += (unsigned)(end - start); 887 i += (unsigned)(end - start);
861 if (i == s2.Len()) 888 if (i == s2.Len())
862 return E_INVALIDARG; 889 return E_INVALIDARG;
863 wchar_t c = s2[i++]; 890 const wchar_t c = s2[i++];
864 if (c == 'f') 891 if (c == 'f')
865 { 892 {
866 if (v < 1) 893 if (v < 1)
@@ -912,7 +939,7 @@ HRESULT COutHandler::SetSolidFromPROPVARIANT(const PROPVARIANT &value)
912 939
913static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest) 940static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest)
914{ 941{
915 RINOK(PROPVARIANT_to_bool(prop, dest.Val)); 942 RINOK(PROPVARIANT_to_bool(prop, dest.Val))
916 dest.Def = true; 943 dest.Def = true;
917 return S_OK; 944 return S_OK;
918} 945}
@@ -935,7 +962,7 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val
935 } 962 }
936 963
937 UInt32 number; 964 UInt32 number;
938 unsigned index = ParseStringToUInt32(name, number); 965 const unsigned index = ParseStringToUInt32(name, number);
939 // UString realName = name.Ptr(index); 966 // UString realName = name.Ptr(index);
940 if (index == 0) 967 if (index == 0)
941 { 968 {
@@ -946,20 +973,20 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val
946 if (name.IsEqualTo("hcf")) 973 if (name.IsEqualTo("hcf"))
947 { 974 {
948 bool compressHeadersFull = true; 975 bool compressHeadersFull = true;
949 RINOK(PROPVARIANT_to_bool(value, compressHeadersFull)); 976 RINOK(PROPVARIANT_to_bool(value, compressHeadersFull))
950 return compressHeadersFull ? S_OK: E_INVALIDARG; 977 return compressHeadersFull ? S_OK: E_INVALIDARG;
951 } 978 }
952 979
953 if (name.IsEqualTo("he")) 980 if (name.IsEqualTo("he"))
954 { 981 {
955 RINOK(PROPVARIANT_to_bool(value, _encryptHeaders)); 982 RINOK(PROPVARIANT_to_bool(value, _encryptHeaders))
956 _encryptHeadersSpecified = true; 983 _encryptHeadersSpecified = true;
957 return S_OK; 984 return S_OK;
958 } 985 }
959 986
960 { 987 {
961 bool processed; 988 bool processed;
962 RINOK(TimeOptions.Parse(name, value, processed)); 989 RINOK(TimeOptions.Parse(name, value, processed))
963 if (processed) 990 if (processed)
964 { 991 {
965 if ( TimeOptions.Prec != (UInt32)(Int32)-1 992 if ( TimeOptions.Prec != (UInt32)(Int32)-1
@@ -982,7 +1009,7 @@ HRESULT COutHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &val
982 return CMultiMethodProps::SetProperty(name, value); 1009 return CMultiMethodProps::SetProperty(name, value);
983} 1010}
984 1011
985STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 1012Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
986{ 1013{
987 COM_TRY_BEGIN 1014 COM_TRY_BEGIN
988 _bonds.Clear(); 1015 _bonds.Clear();
@@ -997,6 +1024,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
997 1024
998 const PROPVARIANT &value = values[i]; 1025 const PROPVARIANT &value = values[i];
999 1026
1027 if (name.Find(L':') >= 0) // 'b' was used as NCoderPropID::kBlockSize2 before v23
1000 if (name[0] == 'b') 1028 if (name[0] == 'b')
1001 { 1029 {
1002 if (value.vt != VT_EMPTY) 1030 if (value.vt != VT_EMPTY)
@@ -1004,12 +1032,12 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1004 name.Delete(0); 1032 name.Delete(0);
1005 1033
1006 CBond2 bond; 1034 CBond2 bond;
1007 RINOK(ParseBond(name, bond.OutCoder, bond.OutStream)); 1035 RINOK(ParseBond(name, bond.OutCoder, bond.OutStream))
1008 if (name[0] != ':') 1036 if (name[0] != ':')
1009 return E_INVALIDARG; 1037 return E_INVALIDARG;
1010 name.Delete(0); 1038 name.Delete(0);
1011 UInt32 inStream = 0; 1039 UInt32 inStream = 0;
1012 RINOK(ParseBond(name, bond.InCoder, inStream)); 1040 RINOK(ParseBond(name, bond.InCoder, inStream))
1013 if (inStream != 0) 1041 if (inStream != 0)
1014 return E_INVALIDARG; 1042 return E_INVALIDARG;
1015 if (!name.IsEmpty()) 1043 if (!name.IsEmpty())
@@ -1018,7 +1046,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1018 continue; 1046 continue;
1019 } 1047 }
1020 1048
1021 RINOK(SetProperty(name, value)); 1049 RINOK(SetProperty(name, value))
1022 } 1050 }
1023 1051
1024 unsigned numEmptyMethods = GetNumEmptyMethods(); 1052 unsigned numEmptyMethods = GetNumEmptyMethods();
diff --git a/CPP/7zip/Archive/7z/7zHeader.cpp b/CPP/7zip/Archive/7z/7zHeader.cpp
index acff2fd..d5f9497 100644
--- a/CPP/7zip/Archive/7z/7zHeader.cpp
+++ b/CPP/7zip/Archive/7z/7zHeader.cpp
@@ -8,7 +8,7 @@ namespace NArchive {
8namespace N7z { 8namespace N7z {
9 9
10Byte kSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; 10Byte kSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
11#ifdef _7Z_VOL 11#ifdef Z7_7Z_VOL
12Byte kFinishSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C + 1}; 12Byte kFinishSignature[kSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C + 1};
13#endif 13#endif
14 14
diff --git a/CPP/7zip/Archive/7z/7zHeader.h b/CPP/7zip/Archive/7z/7zHeader.h
index e1bbc0a..bd96ca3 100644
--- a/CPP/7zip/Archive/7z/7zHeader.h
+++ b/CPP/7zip/Archive/7z/7zHeader.h
@@ -1,7 +1,7 @@
1// 7z/7zHeader.h 1// 7z/7zHeader.h
2 2
3#ifndef __7Z_HEADER_H 3#ifndef ZIP7_INC_7Z_HEADER_H
4#define __7Z_HEADER_H 4#define ZIP7_INC_7Z_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
@@ -11,13 +11,13 @@ namespace N7z {
11const unsigned kSignatureSize = 6; 11const unsigned kSignatureSize = 6;
12extern Byte kSignature[kSignatureSize]; 12extern Byte kSignature[kSignatureSize];
13 13
14// #define _7Z_VOL 14// #define Z7_7Z_VOL
15// 7z-MultiVolume is not finished yet. 15// 7z-MultiVolume is not finished yet.
16// It can work already, but I still do not like some 16// It can work already, but I still do not like some
17// things of that new multivolume format. 17// things of that new multivolume format.
18// So please keep it commented. 18// So please keep it commented.
19 19
20#ifdef _7Z_VOL 20#ifdef Z7_7Z_VOL
21extern Byte kFinishSignature[kSignatureSize]; 21extern Byte kFinishSignature[kSignatureSize];
22#endif 22#endif
23 23
@@ -38,7 +38,7 @@ struct CStartHeader
38 38
39const UInt32 kStartHeaderSize = 20; 39const UInt32 kStartHeaderSize = 20;
40 40
41#ifdef _7Z_VOL 41#ifdef Z7_7Z_VOL
42struct CFinishHeader: public CStartHeader 42struct CFinishHeader: public CStartHeader
43{ 43{
44 UInt64 ArchiveStartOffset; // data offset from end if that struct 44 UInt64 ArchiveStartOffset; // data offset from end if that struct
@@ -99,6 +99,7 @@ namespace NID
99 99
100const UInt32 k_Copy = 0; 100const UInt32 k_Copy = 0;
101const UInt32 k_Delta = 3; 101const UInt32 k_Delta = 3;
102const UInt32 k_ARM64 = 0xa;
102 103
103const UInt32 k_LZMA2 = 0x21; 104const UInt32 k_LZMA2 = 0x21;
104 105
@@ -122,14 +123,17 @@ const UInt32 k_SPARC = 0x3030805;
122 123
123const UInt32 k_AES = 0x6F10701; 124const UInt32 k_AES = 0x6F10701;
124 125
126// const UInt32 k_ZSTD = 0x4015D; // winzip zstd
127// 0x4F71101, 7z-zstd
125 128
126static inline bool IsFilterMethod(UInt64 m) 129static inline bool IsFilterMethod(UInt64 m)
127{ 130{
128 if (m > (UInt64)0xFFFFFFFF) 131 if (m > (UInt32)0xFFFFFFFF)
129 return false; 132 return false;
130 switch ((UInt32)m) 133 switch ((UInt32)m)
131 { 134 {
132 case k_Delta: 135 case k_Delta:
136 case k_ARM64:
133 case k_BCJ: 137 case k_BCJ:
134 case k_BCJ2: 138 case k_BCJ2:
135 case k_PPC: 139 case k_PPC:
diff --git a/CPP/7zip/Archive/7z/7zIn.cpp b/CPP/7zip/Archive/7z/7zIn.cpp
index 7134595..4defd27 100644
--- a/CPP/7zip/Archive/7z/7zIn.cpp
+++ b/CPP/7zip/Archive/7z/7zIn.cpp
@@ -11,6 +11,7 @@
11#include "../../../../C/7zCrc.h" 11#include "../../../../C/7zCrc.h"
12#include "../../../../C/CpuArch.h" 12#include "../../../../C/CpuArch.h"
13 13
14#include "../../../Common/MyBuffer2.h"
14// #include "../../../Common/UTFConvert.h" 15// #include "../../../Common/UTFConvert.h"
15 16
16#include "../../Common/StreamObjects.h" 17#include "../../Common/StreamObjects.h"
@@ -24,7 +25,7 @@
24#define Get64(p) GetUi64(p) 25#define Get64(p) GetUi64(p)
25 26
26// define FORMAT_7Z_RECOVERY if you want to recover multivolume archives with empty StartHeader 27// define FORMAT_7Z_RECOVERY if you want to recover multivolume archives with empty StartHeader
27#ifndef _SFX 28#ifndef Z7_SFX
28#define FORMAT_7Z_RECOVERY 29#define FORMAT_7Z_RECOVERY
29#endif 30#endif
30 31
@@ -34,6 +35,9 @@ using namespace NCOM;
34namespace NArchive { 35namespace NArchive {
35namespace N7z { 36namespace N7z {
36 37
38#define k_Scan_NumCoders_MAX 64
39#define k_Scan_NumCodersStreams_in_Folder_MAX 64
40
37unsigned BoolVector_CountSum(const CBoolVector &v); 41unsigned BoolVector_CountSum(const CBoolVector &v);
38unsigned BoolVector_CountSum(const CBoolVector &v) 42unsigned BoolVector_CountSum(const CBoolVector &v)
39{ 43{
@@ -62,13 +66,13 @@ static void BoolVector_Fill_False(CBoolVector &v, unsigned size)
62class CInArchiveException {}; 66class CInArchiveException {};
63class CUnsupportedFeatureException: public CInArchiveException {}; 67class CUnsupportedFeatureException: public CInArchiveException {};
64 68
65MY_ATTR_NORETURN 69Z7_ATTR_NORETURN
66static void ThrowException() { throw CInArchiveException(); } 70static void ThrowException() { throw CInArchiveException(); }
67MY_ATTR_NORETURN 71Z7_ATTR_NORETURN
68static inline void ThrowEndOfData() { ThrowException(); } 72static inline void ThrowEndOfData() { ThrowException(); }
69MY_ATTR_NORETURN 73Z7_ATTR_NORETURN
70static inline void ThrowUnsupported() { throw CUnsupportedFeatureException(); } 74static inline void ThrowUnsupported() { throw CUnsupportedFeatureException(); }
71MY_ATTR_NORETURN 75Z7_ATTR_NORETURN
72static inline void ThrowIncorrect() { ThrowException(); } 76static inline void ThrowIncorrect() { ThrowException(); }
73 77
74class CStreamSwitch 78class CStreamSwitch
@@ -113,12 +117,12 @@ void CStreamSwitch::Set(CInArchive *archive, const CByteBuffer &byteBuffer)
113void CStreamSwitch::Set(CInArchive *archive, const CObjectVector<CByteBuffer> *dataVector) 117void CStreamSwitch::Set(CInArchive *archive, const CObjectVector<CByteBuffer> *dataVector)
114{ 118{
115 Remove(); 119 Remove();
116 Byte external = archive->ReadByte(); 120 const Byte external = archive->ReadByte();
117 if (external != 0) 121 if (external != 0)
118 { 122 {
119 if (!dataVector) 123 if (!dataVector)
120 ThrowIncorrect(); 124 ThrowIncorrect();
121 CNum dataIndex = archive->ReadNum(); 125 const CNum dataIndex = archive->ReadNum();
122 if (dataIndex >= dataVector->Size()) 126 if (dataIndex >= dataVector->Size())
123 ThrowIncorrect(); 127 ThrowIncorrect();
124 Set(archive, (*dataVector)[dataIndex]); 128 Set(archive, (*dataVector)[dataIndex]);
@@ -171,7 +175,7 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed)
171 return 0; 175 return 0;
172 } 176 }
173 177
174 unsigned b = *p++; 178 const unsigned b = *p++;
175 size--; 179 size--;
176 180
177 if ((b & 0x80) == 0) 181 if ((b & 0x80) == 0)
@@ -192,10 +196,10 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed)
192 196
193 for (unsigned i = 1; i < 8; i++) 197 for (unsigned i = 1; i < 8; i++)
194 { 198 {
195 unsigned mask = (unsigned)0x80 >> i; 199 const unsigned mask = (unsigned)0x80 >> i;
196 if ((b & mask) == 0) 200 if ((b & mask) == 0)
197 { 201 {
198 UInt64 high = b & (mask - 1); 202 const UInt64 high = b & (mask - 1);
199 value |= (high << (i * 8)); 203 value |= (high << (i * 8));
200 processed = i + 1; 204 processed = i + 1;
201 return value; 205 return value;
@@ -219,7 +223,7 @@ static UInt64 ReadNumberSpec(const Byte *p, size_t size, size_t &processed)
219UInt64 CInByte2::ReadNumber() 223UInt64 CInByte2::ReadNumber()
220{ 224{
221 size_t processed; 225 size_t processed;
222 UInt64 res = ReadNumberSpec(_buffer + _pos, _size - _pos, processed); 226 const UInt64 res = ReadNumberSpec(_buffer + _pos, _size - _pos, processed);
223 if (processed == 0) 227 if (processed == 0)
224 ThrowEndOfData(); 228 ThrowEndOfData();
225 _pos += processed; 229 _pos += processed;
@@ -239,7 +243,7 @@ CNum CInByte2::ReadNum()
239 } 243 }
240 } 244 }
241 */ 245 */
242 UInt64 value = ReadNumber(); 246 const UInt64 value = ReadNumber();
243 if (value > kNumMax) 247 if (value > kNumMax)
244 ThrowUnsupported(); 248 ThrowUnsupported();
245 return (CNum)value; 249 return (CNum)value;
@@ -249,7 +253,7 @@ UInt32 CInByte2::ReadUInt32()
249{ 253{
250 if (_pos + 4 > _size) 254 if (_pos + 4 > _size)
251 ThrowEndOfData(); 255 ThrowEndOfData();
252 UInt32 res = Get32(_buffer + _pos); 256 const UInt32 res = Get32(_buffer + _pos);
253 _pos += 4; 257 _pos += 4;
254 return res; 258 return res;
255} 259}
@@ -258,54 +262,101 @@ UInt64 CInByte2::ReadUInt64()
258{ 262{
259 if (_pos + 8 > _size) 263 if (_pos + 8 > _size)
260 ThrowEndOfData(); 264 ThrowEndOfData();
261 UInt64 res = Get64(_buffer + _pos); 265 const UInt64 res = Get64(_buffer + _pos);
262 _pos += 8; 266 _pos += 8;
263 return res; 267 return res;
264} 268}
265 269
266#define CHECK_SIGNATURE if (p[0] != '7' || p[1] != 'z' || p[2] != 0xBC || p[3] != 0xAF || p[4] != 0x27 || p[5] != 0x1C) return false; 270#define Y0 '7'
271#define Y1 'z'
272#define Y2 0xBC
273#define Y3 0xAF
274#define Y4 0x27
275#define Y5 0x1C
276
277#define IS_SIGNATURE(p)( \
278 (p)[2] == Y2 && \
279 (p)[3] == Y3 && \
280 (p)[5] == Y5 && \
281 (p)[4] == Y4 && \
282 (p)[1] == Y1 && \
283 (p)[0] == Y0)
284
285/* FindSignature_10() is allowed to access data up to and including &limit[9].
286 limit[10] access is not allowed.
287 return:
288 (return_ptr < limit) : signature was found at (return_ptr)
289 (return_ptr >= limit) : limit was reached or crossed. So no signature found before limit
290*/
291Z7_NO_INLINE
292static const Byte *FindSignature_10(const Byte *p, const Byte *limit)
293{
294 for (;;)
295 {
296 for (;;)
297 {
298 if (p >= limit)
299 return limit;
300 const Byte b = p[5];
301 p += 6;
302 if (b == Y0) { break; }
303 if (b == Y1) { p -= 1; break; }
304 if (b == Y2) { p -= 2; break; }
305 if (b == Y3) { p -= 3; break; }
306 if (b == Y4) { p -= 4; break; }
307 if (b == Y5) { p -= 5; break; }
308 }
309 if (IS_SIGNATURE(p - 1))
310 return p - 1;
311 }
312}
313
267 314
268static inline bool TestSignature(const Byte *p) 315static inline bool TestStartCrc(const Byte *p)
269{ 316{
270 CHECK_SIGNATURE
271 return CrcCalc(p + 12, 20) == Get32(p + 8); 317 return CrcCalc(p + 12, 20) == Get32(p + 8);
272} 318}
273 319
274#ifdef FORMAT_7Z_RECOVERY
275static inline bool TestSignature2(const Byte *p) 320static inline bool TestSignature2(const Byte *p)
276{ 321{
277 CHECK_SIGNATURE; 322 if (!IS_SIGNATURE(p))
278 if (CrcCalc(p + 12, 20) == Get32(p + 8)) 323 return false;
324 #ifdef FORMAT_7Z_RECOVERY
325 if (TestStartCrc(p))
279 return true; 326 return true;
280 for (unsigned i = 8; i < kHeaderSize; i++) 327 for (unsigned i = 8; i < kHeaderSize; i++)
281 if (p[i] != 0) 328 if (p[i] != 0)
282 return false; 329 return false;
283 return (p[6] != 0 || p[7] != 0); 330 return (p[6] != 0 || p[7] != 0);
331 #else
332 return TestStartCrc(p);
333 #endif
284} 334}
285#else 335
286#define TestSignature2(p) TestSignature(p)
287#endif
288 336
289HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit) 337HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
290{ 338{
291 RINOK(ReadStream_FALSE(stream, _header, kHeaderSize)); 339 RINOK(ReadStream_FALSE(stream, _header, kHeaderSize))
292 340
293 if (TestSignature2(_header)) 341 if (TestSignature2(_header))
294 return S_OK; 342 return S_OK;
295 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) 343 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0)
296 return S_FALSE; 344 return S_FALSE;
297 345
298 const UInt32 kBufSize = 1 << 15; 346 const UInt32 kBufSize = (1 << 15) + kHeaderSize; // must be > (kHeaderSize * 2)
299 CByteArr buf(kBufSize); 347 CAlignedBuffer1 buf(kBufSize);
300 memcpy(buf, _header, kHeaderSize); 348 memcpy(buf, _header, kHeaderSize);
301 UInt64 offset = 0; 349 UInt64 offset = 0;
302 350
303 for (;;) 351 for (;;)
304 { 352 {
305 UInt32 readSize = kBufSize - kHeaderSize; 353 UInt32 readSize =
354 (offset == 0) ?
355 kBufSize - kHeaderSize - kHeaderSize :
356 kBufSize - kHeaderSize;
306 if (searchHeaderSizeLimit) 357 if (searchHeaderSizeLimit)
307 { 358 {
308 UInt64 rem = *searchHeaderSizeLimit - offset; 359 const UInt64 rem = *searchHeaderSizeLimit - offset;
309 if (readSize > rem) 360 if (readSize > rem)
310 readSize = (UInt32)rem; 361 readSize = (UInt32)rem;
311 if (readSize == 0) 362 if (readSize == 0)
@@ -313,29 +364,28 @@ HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *search
313 } 364 }
314 365
315 UInt32 processed = 0; 366 UInt32 processed = 0;
316 RINOK(stream->Read(buf + kHeaderSize, readSize, &processed)); 367 RINOK(stream->Read(buf + kHeaderSize, readSize, &processed))
317 if (processed == 0) 368 if (processed == 0)
318 return S_FALSE; 369 return S_FALSE;
370
371 /* &buf[0] was already tested for signature before.
372 So first search here will be for &buf[1] */
319 373
320 for (UInt32 pos = 0;;) 374 for (UInt32 pos = 0;;)
321 { 375 {
322 const Byte *p = buf + pos + 1; 376 const Byte *p = buf + pos + 1;
323 const Byte *lim = buf + processed; 377 const Byte *lim = buf + processed + 1;
324 for (; p <= lim; p += 4) 378 /* we have (kHeaderSize - 1 = 31) filled bytes starting from (lim),
325 { 379 and it's safe to access just 10 bytes in that reserved area */
326 if (p[0] == '7') break; 380 p = FindSignature_10(p, lim);
327 if (p[1] == '7') { p += 1; break; } 381 if (p >= lim)
328 if (p[2] == '7') { p += 2; break; }
329 if (p[3] == '7') { p += 3; break; }
330 };
331 if (p > lim)
332 break; 382 break;
333 pos = (UInt32)(p - buf); 383 pos = (UInt32)(p - buf);
334 if (TestSignature(p)) 384 if (TestStartCrc(p))
335 { 385 {
336 memcpy(_header, p, kHeaderSize); 386 memcpy(_header, p, kHeaderSize);
337 _arhiveBeginStreamPosition += offset + pos; 387 _arhiveBeginStreamPosition += offset + pos;
338 return stream->Seek((Int64)(_arhiveBeginStreamPosition + kHeaderSize), STREAM_SEEK_SET, NULL); 388 return InStream_SeekSet(stream, _arhiveBeginStreamPosition + kHeaderSize);
339 } 389 }
340 } 390 }
341 391
@@ -349,10 +399,8 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
349{ 399{
350 HeadersSize = 0; 400 HeadersSize = 0;
351 Close(); 401 Close();
352 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_arhiveBeginStreamPosition)) 402 RINOK(InStream_GetPos_GetSize(stream, _arhiveBeginStreamPosition, _fileEndPosition))
353 RINOK(stream->Seek(0, STREAM_SEEK_END, &_fileEndPosition)) 403 RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit))
354 RINOK(stream->Seek((Int64)_arhiveBeginStreamPosition, STREAM_SEEK_SET, NULL))
355 RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit));
356 _stream = stream; 404 _stream = stream;
357 return S_OK; 405 return S_OK;
358} 406}
@@ -378,9 +426,9 @@ void CInArchive::ReadArchiveProperties(CInArchiveInfo & /* archiveInfo */)
378 426
379void CInByte2::ParseFolder(CFolder &folder) 427void CInByte2::ParseFolder(CFolder &folder)
380{ 428{
381 UInt32 numCoders = ReadNum(); 429 const UInt32 numCoders = ReadNum();
382 430
383 if (numCoders == 0) 431 if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX)
384 ThrowUnsupported(); 432 ThrowUnsupported();
385 433
386 folder.Coders.SetSize(numCoders); 434 folder.Coders.SetSize(numCoders);
@@ -391,10 +439,10 @@ void CInByte2::ParseFolder(CFolder &folder)
391 { 439 {
392 CCoderInfo &coder = folder.Coders[i]; 440 CCoderInfo &coder = folder.Coders[i];
393 { 441 {
394 Byte mainByte = ReadByte(); 442 const Byte mainByte = ReadByte();
395 if ((mainByte & 0xC0) != 0) 443 if ((mainByte & 0xC0) != 0)
396 ThrowUnsupported(); 444 ThrowUnsupported();
397 unsigned idSize = (mainByte & 0xF); 445 const unsigned idSize = (mainByte & 0xF);
398 if (idSize > 8 || idSize > GetRem()) 446 if (idSize > 8 || idSize > GetRem())
399 ThrowUnsupported(); 447 ThrowUnsupported();
400 const Byte *longID = GetPtr(); 448 const Byte *longID = GetPtr();
@@ -407,7 +455,9 @@ void CInByte2::ParseFolder(CFolder &folder)
407 if ((mainByte & 0x10) != 0) 455 if ((mainByte & 0x10) != 0)
408 { 456 {
409 coder.NumStreams = ReadNum(); 457 coder.NumStreams = ReadNum();
458 // if (coder.NumStreams > k_Scan_NumCodersStreams_in_Folder_MAX) ThrowUnsupported();
410 /* numOutStreams = */ ReadNum(); 459 /* numOutStreams = */ ReadNum();
460 // if (ReadNum() != 1) // numOutStreams ThrowUnsupported();
411 } 461 }
412 else 462 else
413 { 463 {
@@ -416,7 +466,7 @@ void CInByte2::ParseFolder(CFolder &folder)
416 466
417 if ((mainByte & 0x20) != 0) 467 if ((mainByte & 0x20) != 0)
418 { 468 {
419 CNum propsSize = ReadNum(); 469 const CNum propsSize = ReadNum();
420 coder.Props.Alloc((size_t)propsSize); 470 coder.Props.Alloc((size_t)propsSize);
421 ReadBytes((Byte *)coder.Props, (size_t)propsSize); 471 ReadBytes((Byte *)coder.Props, (size_t)propsSize);
422 } 472 }
@@ -426,7 +476,7 @@ void CInByte2::ParseFolder(CFolder &folder)
426 numInStreams += coder.NumStreams; 476 numInStreams += coder.NumStreams;
427 } 477 }
428 478
429 UInt32 numBonds = numCoders - 1; 479 const UInt32 numBonds = numCoders - 1;
430 folder.Bonds.SetSize(numBonds); 480 folder.Bonds.SetSize(numBonds);
431 for (i = 0; i < numBonds; i++) 481 for (i = 0; i < numBonds; i++)
432 { 482 {
@@ -437,7 +487,7 @@ void CInByte2::ParseFolder(CFolder &folder)
437 487
438 if (numInStreams < numBonds) 488 if (numInStreams < numBonds)
439 ThrowUnsupported(); 489 ThrowUnsupported();
440 UInt32 numPackStreams = numInStreams - numBonds; 490 const UInt32 numPackStreams = numInStreams - numBonds;
441 folder.PackStreams.SetSize(numPackStreams); 491 folder.PackStreams.SetSize(numPackStreams);
442 492
443 if (numPackStreams == 1) 493 if (numPackStreams == 1)
@@ -458,7 +508,7 @@ void CInByte2::ParseFolder(CFolder &folder)
458 508
459void CFolders::ParseFolderInfo(unsigned folderIndex, CFolder &folder) const 509void CFolders::ParseFolderInfo(unsigned folderIndex, CFolder &folder) const
460{ 510{
461 size_t startPos = FoCodersDataOffset[folderIndex]; 511 const size_t startPos = FoCodersDataOffset[folderIndex];
462 CInByte2 inByte; 512 CInByte2 inByte;
463 inByte.Init(CodersData + startPos, FoCodersDataOffset[folderIndex + 1] - startPos); 513 inByte.Init(CodersData + startPos, FoCodersDataOffset[folderIndex + 1] - startPos);
464 inByte.ParseFolder(folder); 514 inByte.ParseFolder(folder);
@@ -473,8 +523,8 @@ void CDatabase::GetPath(unsigned index, UString &path) const
473 if (!NameOffsets || !NamesBuf) 523 if (!NameOffsets || !NamesBuf)
474 return; 524 return;
475 525
476 size_t offset = NameOffsets[index]; 526 const size_t offset = NameOffsets[index];
477 size_t size = NameOffsets[index + 1] - offset; 527 const size_t size = NameOffsets[index + 1] - offset;
478 528
479 if (size >= (1 << 28)) 529 if (size >= (1 << 28))
480 return; 530 return;
@@ -507,8 +557,8 @@ HRESULT CDatabase::GetPath_Prop(unsigned index, PROPVARIANT *path) const throw()
507 if (!NameOffsets || !NamesBuf) 557 if (!NameOffsets || !NamesBuf)
508 return S_OK; 558 return S_OK;
509 559
510 size_t offset = NameOffsets[index]; 560 const size_t offset = NameOffsets[index];
511 size_t size = NameOffsets[index + 1] - offset; 561 const size_t size = NameOffsets[index + 1] - offset;
512 562
513 if (size >= (1 << 14)) 563 if (size >= (1 << 14))
514 return S_OK; 564 return S_OK;
@@ -530,7 +580,7 @@ HRESULT CDatabase::GetPath_Prop(unsigned index, PROPVARIANT *path) const throw()
530 #else 580 #else
531 */ 581 */
532 582
533 RINOK(PropVarEm_Alloc_Bstr(path, (unsigned)size - 1)); 583 RINOK(PropVarEm_Alloc_Bstr(path, (unsigned)size - 1))
534 wchar_t *s = path->bstrVal; 584 wchar_t *s = path->bstrVal;
535 const Byte *p = ((const Byte *)NamesBuf + offset * 2); 585 const Byte *p = ((const Byte *)NamesBuf + offset * 2);
536 // Utf16LE__To_WCHARs_Sep(p, size, s); 586 // Utf16LE__To_WCHARs_Sep(p, size, s);
@@ -601,7 +651,7 @@ void CInArchive::WaitId(UInt64 id)
601{ 651{
602 for (;;) 652 for (;;)
603 { 653 {
604 UInt64 type = ReadID(); 654 const UInt64 type = ReadID();
605 if (type == id) 655 if (type == id)
606 return; 656 return;
607 if (type == NID::kEnd) 657 if (type == NID::kEnd)
@@ -613,7 +663,7 @@ void CInArchive::WaitId(UInt64 id)
613 663
614void CInArchive::Read_UInt32_Vector(CUInt32DefVector &v) 664void CInArchive::Read_UInt32_Vector(CUInt32DefVector &v)
615{ 665{
616 unsigned numItems = v.Defs.Size(); 666 const unsigned numItems = v.Defs.Size();
617 v.Vals.ClearAndSetSize(numItems); 667 v.Vals.ClearAndSetSize(numItems);
618 UInt32 *p = &v.Vals[0]; 668 UInt32 *p = &v.Vals[0];
619 const bool *defs = &v.Defs[0]; 669 const bool *defs = &v.Defs[0];
@@ -634,12 +684,9 @@ void CInArchive::ReadHashDigests(unsigned numItems, CUInt32DefVector &crcs)
634} 684}
635 685
636 686
637#define k_Scan_NumCoders_MAX 64
638#define k_Scan_NumCodersStreams_in_Folder_MAX 64
639
640void CInArchive::ReadPackInfo(CFolders &f) 687void CInArchive::ReadPackInfo(CFolders &f)
641{ 688{
642 CNum numPackStreams = ReadNum(); 689 const CNum numPackStreams = ReadNum();
643 690
644 WaitId(NID::kSize); 691 WaitId(NID::kSize);
645 f.PackPositions.Alloc(numPackStreams + 1); 692 f.PackPositions.Alloc(numPackStreams + 1);
@@ -648,7 +695,7 @@ void CInArchive::ReadPackInfo(CFolders &f)
648 for (CNum i = 0; i < numPackStreams; i++) 695 for (CNum i = 0; i < numPackStreams; i++)
649 { 696 {
650 f.PackPositions[i] = sum; 697 f.PackPositions[i] = sum;
651 UInt64 packSize = ReadNumber(); 698 const UInt64 packSize = ReadNumber();
652 sum += packSize; 699 sum += packSize;
653 if (sum < packSize) 700 if (sum < packSize)
654 ThrowIncorrect(); 701 ThrowIncorrect();
@@ -676,7 +723,7 @@ void CInArchive::ReadUnpackInfo(
676 CFolders &folders) 723 CFolders &folders)
677{ 724{
678 WaitId(NID::kFolder); 725 WaitId(NID::kFolder);
679 CNum numFolders = ReadNum(); 726 const CNum numFolders = ReadNum();
680 727
681 CNum numCodersOutStreams = 0; 728 CNum numCodersOutStreams = 0;
682 { 729 {
@@ -704,18 +751,18 @@ void CInArchive::ReadUnpackInfo(
704 folders.FoCodersDataOffset[fo] = (size_t)(_inByteBack->GetPtr() - startBufPtr); 751 folders.FoCodersDataOffset[fo] = (size_t)(_inByteBack->GetPtr() - startBufPtr);
705 752
706 CNum numInStreams = 0; 753 CNum numInStreams = 0;
707 CNum numCoders = inByte->ReadNum(); 754 const CNum numCoders = inByte->ReadNum();
708 755
709 if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX) 756 if (numCoders == 0 || numCoders > k_Scan_NumCoders_MAX)
710 ThrowUnsupported(); 757 ThrowUnsupported();
711 758
712 for (CNum ci = 0; ci < numCoders; ci++) 759 for (CNum ci = 0; ci < numCoders; ci++)
713 { 760 {
714 Byte mainByte = inByte->ReadByte(); 761 const Byte mainByte = inByte->ReadByte();
715 if ((mainByte & 0xC0) != 0) 762 if ((mainByte & 0xC0) != 0)
716 ThrowUnsupported(); 763 ThrowUnsupported();
717 764
718 unsigned idSize = (mainByte & 0xF); 765 const unsigned idSize = (mainByte & 0xF);
719 if (idSize > 8) 766 if (idSize > 8)
720 ThrowUnsupported(); 767 ThrowUnsupported();
721 if (idSize > inByte->GetRem()) 768 if (idSize > inByte->GetRem())
@@ -744,18 +791,18 @@ void CInArchive::ReadUnpackInfo(
744 791
745 if ((mainByte & 0x20) != 0) 792 if ((mainByte & 0x20) != 0)
746 { 793 {
747 CNum propsSize = inByte->ReadNum(); 794 const CNum propsSize = inByte->ReadNum();
748 if (propsSize > inByte->GetRem()) 795 if (propsSize > inByte->GetRem())
749 ThrowEndOfData(); 796 ThrowEndOfData();
750 if (id == k_LZMA2 && propsSize == 1) 797 if (id == k_LZMA2 && propsSize == 1)
751 { 798 {
752 Byte v = *_inByteBack->GetPtr(); 799 const Byte v = *_inByteBack->GetPtr();
753 if (folders.ParsedMethods.Lzma2Prop < v) 800 if (folders.ParsedMethods.Lzma2Prop < v)
754 folders.ParsedMethods.Lzma2Prop = v; 801 folders.ParsedMethods.Lzma2Prop = v;
755 } 802 }
756 else if (id == k_LZMA && propsSize == 5) 803 else if (id == k_LZMA && propsSize == 5)
757 { 804 {
758 UInt32 dicSize = GetUi32(_inByteBack->GetPtr() + 1); 805 const UInt32 dicSize = GetUi32(_inByteBack->GetPtr() + 1);
759 if (folders.ParsedMethods.LzmaDic < dicSize) 806 if (folders.ParsedMethods.LzmaDic < dicSize)
760 folders.ParsedMethods.LzmaDic = dicSize; 807 folders.ParsedMethods.LzmaDic = dicSize;
761 } 808 }
@@ -771,7 +818,7 @@ void CInArchive::ReadUnpackInfo(
771 else 818 else
772 { 819 {
773 UInt32 i; 820 UInt32 i;
774 CNum numBonds = numCoders - 1; 821 const CNum numBonds = numCoders - 1;
775 if (numInStreams < numBonds) 822 if (numInStreams < numBonds)
776 ThrowUnsupported(); 823 ThrowUnsupported();
777 824
@@ -796,7 +843,7 @@ void CInArchive::ReadUnpackInfo(
796 if (numPackStreams != 1) 843 if (numPackStreams != 1)
797 for (i = 0; i < numPackStreams; i++) 844 for (i = 0; i < numPackStreams; i++)
798 { 845 {
799 CNum index = inByte->ReadNum(); // PackStreams 846 const CNum index = inByte->ReadNum(); // PackStreams
800 if (index >= numInStreams || StreamUsed[index]) 847 if (index >= numInStreams || StreamUsed[index])
801 ThrowUnsupported(); 848 ThrowUnsupported();
802 StreamUsed[index] = true; 849 StreamUsed[index] = true;
@@ -838,7 +885,7 @@ void CInArchive::ReadUnpackInfo(
838 885
839 for (;;) 886 for (;;)
840 { 887 {
841 UInt64 type = ReadID(); 888 const UInt64 type = ReadID();
842 if (type == NID::kEnd) 889 if (type == NID::kEnd)
843 return; 890 return;
844 if (type == NID::kCRC) 891 if (type == NID::kCRC)
@@ -882,19 +929,19 @@ void CInArchive::ReadSubStreamsInfo(
882 { 929 {
883 // v3.13 incorrectly worked with empty folders 930 // v3.13 incorrectly worked with empty folders
884 // v4.07: we check that folder is empty 931 // v4.07: we check that folder is empty
885 CNum numSubstreams = folders.NumUnpackStreamsVector[i]; 932 const CNum numSubstreams = folders.NumUnpackStreamsVector[i];
886 if (numSubstreams == 0) 933 if (numSubstreams == 0)
887 continue; 934 continue;
888 UInt64 sum = 0; 935 UInt64 sum = 0;
889 for (CNum j = 1; j < numSubstreams; j++) 936 for (CNum j = 1; j < numSubstreams; j++)
890 { 937 {
891 UInt64 size = ReadNumber(); 938 const UInt64 size = ReadNumber();
892 unpackSizes.Add(size); 939 unpackSizes.Add(size);
893 sum += size; 940 sum += size;
894 if (sum < size) 941 if (sum < size)
895 ThrowIncorrect(); 942 ThrowIncorrect();
896 } 943 }
897 UInt64 folderUnpackSize = folders.GetFolderUnpackSize(i); 944 const UInt64 folderUnpackSize = folders.GetFolderUnpackSize(i);
898 if (folderUnpackSize < sum) 945 if (folderUnpackSize < sum)
899 ThrowIncorrect(); 946 ThrowIncorrect();
900 unpackSizes.Add(folderUnpackSize - sum); 947 unpackSizes.Add(folderUnpackSize - sum);
@@ -907,7 +954,7 @@ void CInArchive::ReadSubStreamsInfo(
907 { 954 {
908 /* v9.26 - v9.29 incorrectly worked: 955 /* v9.26 - v9.29 incorrectly worked:
909 if (folders.NumUnpackStreamsVector[i] == 0), it threw error */ 956 if (folders.NumUnpackStreamsVector[i] == 0), it threw error */
910 CNum val = folders.NumUnpackStreamsVector[i]; 957 const CNum val = folders.NumUnpackStreamsVector[i];
911 if (val > 1) 958 if (val > 1)
912 ThrowIncorrect(); 959 ThrowIncorrect();
913 if (val == 1) 960 if (val == 1)
@@ -918,7 +965,7 @@ void CInArchive::ReadSubStreamsInfo(
918 unsigned numDigests = 0; 965 unsigned numDigests = 0;
919 for (i = 0; i < folders.NumFolders; i++) 966 for (i = 0; i < folders.NumFolders; i++)
920 { 967 {
921 CNum numSubstreams = folders.NumUnpackStreamsVector[i]; 968 const CNum numSubstreams = folders.NumUnpackStreamsVector[i];
922 if (numSubstreams != 1 || !folders.FolderCRCs.ValidAndDefined(i)) 969 if (numSubstreams != 1 || !folders.FolderCRCs.ValidAndDefined(i))
923 numDigests += numSubstreams; 970 numDigests += numSubstreams;
924 } 971 }
@@ -941,7 +988,7 @@ void CInArchive::ReadSubStreamsInfo(
941 988
942 for (i = 0; i < folders.NumFolders; i++) 989 for (i = 0; i < folders.NumFolders; i++)
943 { 990 {
944 CNum numSubstreams = folders.NumUnpackStreamsVector[i]; 991 const CNum numSubstreams = folders.NumUnpackStreamsVector[i];
945 if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i)) 992 if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i))
946 { 993 {
947 digests.Defs[k] = true; 994 digests.Defs[k] = true;
@@ -973,7 +1020,7 @@ void CInArchive::ReadSubStreamsInfo(
973 unsigned k = 0; 1020 unsigned k = 0;
974 for (i = 0; i < folders.NumFolders; i++) 1021 for (i = 0; i < folders.NumFolders; i++)
975 { 1022 {
976 CNum numSubstreams = folders.NumUnpackStreamsVector[i]; 1023 const CNum numSubstreams = folders.NumUnpackStreamsVector[i];
977 if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i)) 1024 if (numSubstreams == 1 && folders.FolderCRCs.ValidAndDefined(i))
978 { 1025 {
979 digests.Defs[k] = true; 1026 digests.Defs[k] = true;
@@ -1069,7 +1116,7 @@ void CInArchive::ReadBoolVector(unsigned numItems, CBoolVector &v)
1069 1116
1070void CInArchive::ReadBoolVector2(unsigned numItems, CBoolVector &v) 1117void CInArchive::ReadBoolVector2(unsigned numItems, CBoolVector &v)
1071{ 1118{
1072 Byte allAreDefined = ReadByte(); 1119 const Byte allAreDefined = ReadByte();
1073 if (allAreDefined == 0) 1120 if (allAreDefined == 0)
1074 { 1121 {
1075 ReadBoolVector(numItems, v); 1122 ReadBoolVector(numItems, v);
@@ -1106,7 +1153,7 @@ HRESULT CInArchive::ReadAndDecodePackedStreams(
1106 DECL_EXTERNAL_CODECS_LOC_VARS 1153 DECL_EXTERNAL_CODECS_LOC_VARS
1107 UInt64 baseOffset, 1154 UInt64 baseOffset,
1108 UInt64 &dataOffset, CObjectVector<CByteBuffer> &dataVector 1155 UInt64 &dataOffset, CObjectVector<CByteBuffer> &dataVector
1109 _7Z_DECODER_CRYPRO_VARS_DECL 1156 Z7_7Z_DECODER_CRYPRO_VARS_DECL
1110 ) 1157 )
1111{ 1158{
1112 CFolders folders; 1159 CFolders folders;
@@ -1148,15 +1195,15 @@ HRESULT CInArchive::ReadAndDecodePackedStreams(
1148 NULL // **inStreamMainRes 1195 NULL // **inStreamMainRes
1149 , dataAfterEnd_Error 1196 , dataAfterEnd_Error
1150 1197
1151 _7Z_DECODER_CRYPRO_VARS 1198 Z7_7Z_DECODER_CRYPRO_VARS
1152 #if !defined(_7ZIP_ST) 1199 #if !defined(Z7_ST)
1153 , false // mtMode 1200 , false // mtMode
1154 , 1 // numThreads 1201 , 1 // numThreads
1155 , 0 // memUsage 1202 , 0 // memUsage
1156 #endif 1203 #endif
1157 ); 1204 );
1158 1205
1159 RINOK(result); 1206 RINOK(result)
1160 1207
1161 if (dataAfterEnd_Error) 1208 if (dataAfterEnd_Error)
1162 ThereIsHeaderError = true; 1209 ThereIsHeaderError = true;
@@ -1178,7 +1225,7 @@ HRESULT CInArchive::ReadAndDecodePackedStreams(
1178HRESULT CInArchive::ReadHeader( 1225HRESULT CInArchive::ReadHeader(
1179 DECL_EXTERNAL_CODECS_LOC_VARS 1226 DECL_EXTERNAL_CODECS_LOC_VARS
1180 CDbEx &db 1227 CDbEx &db
1181 _7Z_DECODER_CRYPRO_VARS_DECL 1228 Z7_7Z_DECODER_CRYPRO_VARS_DECL
1182 ) 1229 )
1183{ 1230{
1184 UInt64 type = ReadID(); 1231 UInt64 type = ReadID();
@@ -1193,14 +1240,14 @@ HRESULT CInArchive::ReadHeader(
1193 1240
1194 if (type == NID::kAdditionalStreamsInfo) 1241 if (type == NID::kAdditionalStreamsInfo)
1195 { 1242 {
1196 HRESULT result = ReadAndDecodePackedStreams( 1243 const HRESULT result = ReadAndDecodePackedStreams(
1197 EXTERNAL_CODECS_LOC_VARS 1244 EXTERNAL_CODECS_LOC_VARS
1198 db.ArcInfo.StartPositionAfterHeader, 1245 db.ArcInfo.StartPositionAfterHeader,
1199 db.ArcInfo.DataStartPosition2, 1246 db.ArcInfo.DataStartPosition2,
1200 dataVector 1247 dataVector
1201 _7Z_DECODER_CRYPRO_VARS 1248 Z7_7Z_DECODER_CRYPRO_VARS
1202 ); 1249 );
1203 RINOK(result); 1250 RINOK(result)
1204 db.ArcInfo.DataStartPosition2 += db.ArcInfo.StartPositionAfterHeader; 1251 db.ArcInfo.DataStartPosition2 += db.ArcInfo.StartPositionAfterHeader;
1205 type = ReadID(); 1252 type = ReadID();
1206 } 1253 }
@@ -1240,7 +1287,7 @@ HRESULT CInArchive::ReadHeader(
1240 const UInt64 type2 = ReadID(); 1287 const UInt64 type2 = ReadID();
1241 if (type2 == NID::kEnd) 1288 if (type2 == NID::kEnd)
1242 break; 1289 break;
1243 UInt64 size = ReadNumber(); 1290 const UInt64 size = ReadNumber();
1244 if (size > _inByteBack->GetRem()) 1291 if (size > _inByteBack->GetRem())
1245 ThrowIncorrect(); 1292 ThrowIncorrect();
1246 CStreamSwitch switchProp; 1293 CStreamSwitch switchProp;
@@ -1255,7 +1302,7 @@ HRESULT CInArchive::ReadHeader(
1255 { 1302 {
1256 CStreamSwitch streamSwitch; 1303 CStreamSwitch streamSwitch;
1257 streamSwitch.Set(this, &dataVector); 1304 streamSwitch.Set(this, &dataVector);
1258 size_t rem = _inByteBack->GetRem(); 1305 const size_t rem = _inByteBack->GetRem();
1259 db.NamesBuf.Alloc(rem); 1306 db.NamesBuf.Alloc(rem);
1260 ReadBytes(db.NamesBuf, rem); 1307 ReadBytes(db.NamesBuf, rem);
1261 db.NameOffsets.Alloc(numFiles + 1); 1308 db.NameOffsets.Alloc(numFiles + 1);
@@ -1471,7 +1518,7 @@ void CDbEx::FillLinks()
1471 1518
1472 for (i = 0; i < Files.Size(); i++) 1519 for (i = 0; i < Files.Size(); i++)
1473 { 1520 {
1474 bool emptyStream = !Files[i].HasStream; 1521 const bool emptyStream = !Files[i].HasStream;
1475 if (indexInFolder == 0) 1522 if (indexInFolder == 0)
1476 { 1523 {
1477 if (emptyStream) 1524 if (emptyStream)
@@ -1528,7 +1575,7 @@ void CDbEx::FillLinks()
1528HRESULT CInArchive::ReadDatabase2( 1575HRESULT CInArchive::ReadDatabase2(
1529 DECL_EXTERNAL_CODECS_LOC_VARS 1576 DECL_EXTERNAL_CODECS_LOC_VARS
1530 CDbEx &db 1577 CDbEx &db
1531 _7Z_DECODER_CRYPRO_VARS_DECL 1578 Z7_7Z_DECODER_CRYPRO_VARS_DECL
1532 ) 1579 )
1533{ 1580{
1534 db.Clear(); 1581 db.Clear();
@@ -1548,22 +1595,22 @@ HRESULT CInArchive::ReadDatabase2(
1548 UInt32 nextHeaderCRC = Get32(_header + 28); 1595 UInt32 nextHeaderCRC = Get32(_header + 28);
1549 1596
1550 #ifdef FORMAT_7Z_RECOVERY 1597 #ifdef FORMAT_7Z_RECOVERY
1551 UInt32 crcFromArc = Get32(_header + 8); 1598 const UInt32 crcFromArc = Get32(_header + 8);
1552 if (crcFromArc == 0 && nextHeaderOffset == 0 && nextHeaderSize == 0 && nextHeaderCRC == 0) 1599 if (crcFromArc == 0 && nextHeaderOffset == 0 && nextHeaderSize == 0 && nextHeaderCRC == 0)
1553 { 1600 {
1554 UInt64 cur, fileSize; 1601 UInt64 cur, fileSize;
1555 RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &cur)); 1602 RINOK(InStream_GetPos(_stream, cur))
1556 const unsigned kCheckSize = 512; 1603 const unsigned kCheckSize = 512;
1557 Byte buf[kCheckSize]; 1604 Byte buf[kCheckSize];
1558 RINOK(_stream->Seek(0, STREAM_SEEK_END, &fileSize)); 1605 RINOK(InStream_GetSize_SeekToEnd(_stream, fileSize))
1559 const UInt64 rem = fileSize - cur; 1606 const UInt64 rem = fileSize - cur;
1560 unsigned checkSize = kCheckSize; 1607 unsigned checkSize = kCheckSize;
1561 if (rem < kCheckSize) 1608 if (rem < kCheckSize)
1562 checkSize = (unsigned)(rem); 1609 checkSize = (unsigned)(rem);
1563 if (checkSize < 3) 1610 if (checkSize < 3)
1564 return S_FALSE; 1611 return S_FALSE;
1565 RINOK(_stream->Seek((Int64)(fileSize - checkSize), STREAM_SEEK_SET, NULL)); 1612 RINOK(InStream_SeekSet(_stream, fileSize - checkSize))
1566 RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize)); 1613 RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize))
1567 1614
1568 if (buf[checkSize - 1] != 0) 1615 if (buf[checkSize - 1] != 0)
1569 return S_FALSE; 1616 return S_FALSE;
@@ -1580,7 +1627,7 @@ HRESULT CInArchive::ReadDatabase2(
1580 nextHeaderSize = checkSize - i; 1627 nextHeaderSize = checkSize - i;
1581 nextHeaderOffset = rem - nextHeaderSize; 1628 nextHeaderOffset = rem - nextHeaderSize;
1582 nextHeaderCRC = CrcCalc(buf + i, (size_t)nextHeaderSize); 1629 nextHeaderCRC = CrcCalc(buf + i, (size_t)nextHeaderSize);
1583 RINOK(_stream->Seek((Int64)cur, STREAM_SEEK_SET, NULL)); 1630 RINOK(InStream_SeekSet(_stream, cur))
1584 db.StartHeaderWasRecovered = true; 1631 db.StartHeaderWasRecovered = true;
1585 } 1632 }
1586 else 1633 else
@@ -1622,14 +1669,14 @@ HRESULT CInArchive::ReadDatabase2(
1622 db.UnexpectedEnd = true; 1669 db.UnexpectedEnd = true;
1623 return S_FALSE; 1670 return S_FALSE;
1624 } 1671 }
1625 RINOK(_stream->Seek((Int64)nextHeaderOffset, STREAM_SEEK_CUR, NULL)); 1672 RINOK(_stream->Seek((Int64)nextHeaderOffset, STREAM_SEEK_CUR, NULL))
1626 1673
1627 size_t nextHeaderSize_t = (size_t)nextHeaderSize; 1674 const size_t nextHeaderSize_t = (size_t)nextHeaderSize;
1628 if (nextHeaderSize_t != nextHeaderSize) 1675 if (nextHeaderSize_t != nextHeaderSize)
1629 return E_OUTOFMEMORY; 1676 return E_OUTOFMEMORY;
1630 CByteBuffer buffer2(nextHeaderSize_t); 1677 CByteBuffer buffer2(nextHeaderSize_t);
1631 1678
1632 RINOK(ReadStream_FALSE(_stream, buffer2, nextHeaderSize_t)); 1679 RINOK(ReadStream_FALSE(_stream, buffer2, nextHeaderSize_t))
1633 1680
1634 if (CrcCalc(buffer2, nextHeaderSize_t) != nextHeaderCRC) 1681 if (CrcCalc(buffer2, nextHeaderSize_t) != nextHeaderCRC)
1635 ThrowIncorrect(); 1682 ThrowIncorrect();
@@ -1642,19 +1689,19 @@ HRESULT CInArchive::ReadDatabase2(
1642 1689
1643 CObjectVector<CByteBuffer> dataVector; 1690 CObjectVector<CByteBuffer> dataVector;
1644 1691
1645 UInt64 type = ReadID(); 1692 const UInt64 type = ReadID();
1646 if (type != NID::kHeader) 1693 if (type != NID::kHeader)
1647 { 1694 {
1648 if (type != NID::kEncodedHeader) 1695 if (type != NID::kEncodedHeader)
1649 ThrowIncorrect(); 1696 ThrowIncorrect();
1650 HRESULT result = ReadAndDecodePackedStreams( 1697 const HRESULT result = ReadAndDecodePackedStreams(
1651 EXTERNAL_CODECS_LOC_VARS 1698 EXTERNAL_CODECS_LOC_VARS
1652 db.ArcInfo.StartPositionAfterHeader, 1699 db.ArcInfo.StartPositionAfterHeader,
1653 db.ArcInfo.DataStartPosition2, 1700 db.ArcInfo.DataStartPosition2,
1654 dataVector 1701 dataVector
1655 _7Z_DECODER_CRYPRO_VARS 1702 Z7_7Z_DECODER_CRYPRO_VARS
1656 ); 1703 );
1657 RINOK(result); 1704 RINOK(result)
1658 if (dataVector.Size() == 0) 1705 if (dataVector.Size() == 0)
1659 return S_OK; 1706 return S_OK;
1660 if (dataVector.Size() > 1) 1707 if (dataVector.Size() > 1)
@@ -1672,7 +1719,7 @@ HRESULT CInArchive::ReadDatabase2(
1672 return ReadHeader( 1719 return ReadHeader(
1673 EXTERNAL_CODECS_LOC_VARS 1720 EXTERNAL_CODECS_LOC_VARS
1674 db 1721 db
1675 _7Z_DECODER_CRYPRO_VARS 1722 Z7_7Z_DECODER_CRYPRO_VARS
1676 ); 1723 );
1677} 1724}
1678 1725
@@ -1680,14 +1727,14 @@ HRESULT CInArchive::ReadDatabase2(
1680HRESULT CInArchive::ReadDatabase( 1727HRESULT CInArchive::ReadDatabase(
1681 DECL_EXTERNAL_CODECS_LOC_VARS 1728 DECL_EXTERNAL_CODECS_LOC_VARS
1682 CDbEx &db 1729 CDbEx &db
1683 _7Z_DECODER_CRYPRO_VARS_DECL 1730 Z7_7Z_DECODER_CRYPRO_VARS_DECL
1684 ) 1731 )
1685{ 1732{
1686 try 1733 try
1687 { 1734 {
1688 HRESULT res = ReadDatabase2( 1735 const HRESULT res = ReadDatabase2(
1689 EXTERNAL_CODECS_LOC_VARS db 1736 EXTERNAL_CODECS_LOC_VARS db
1690 _7Z_DECODER_CRYPRO_VARS 1737 Z7_7Z_DECODER_CRYPRO_VARS
1691 ); 1738 );
1692 if (ThereIsHeaderError) 1739 if (ThereIsHeaderError)
1693 db.ThereIsHeaderError = true; 1740 db.ThereIsHeaderError = true;
diff --git a/CPP/7zip/Archive/7z/7zIn.h b/CPP/7zip/Archive/7z/7zIn.h
index ffa1e4b..a9c14fb 100644
--- a/CPP/7zip/Archive/7z/7zIn.h
+++ b/CPP/7zip/Archive/7z/7zIn.h
@@ -1,7 +1,7 @@
1// 7zIn.h 1// 7zIn.h
2 2
3#ifndef __7Z_IN_H 3#ifndef ZIP7_INC_7Z_IN_H
4#define __7Z_IN_H 4#define ZIP7_INC_7Z_IN_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -22,12 +22,12 @@ namespace N7z {
22 We don't need to init isEncrypted and passwordIsDefined 22 We don't need to init isEncrypted and passwordIsDefined
23 We must upgrade them only */ 23 We must upgrade them only */
24 24
25#ifdef _NO_CRYPTO 25#ifdef Z7_NO_CRYPTO
26#define _7Z_DECODER_CRYPRO_VARS_DECL 26#define Z7_7Z_DECODER_CRYPRO_VARS_DECL
27#define _7Z_DECODER_CRYPRO_VARS 27#define Z7_7Z_DECODER_CRYPRO_VARS
28#else 28#else
29#define _7Z_DECODER_CRYPRO_VARS_DECL , ICryptoGetTextPassword *getTextPassword, bool &isEncrypted, bool &passwordIsDefined, UString &password 29#define Z7_7Z_DECODER_CRYPRO_VARS_DECL , ICryptoGetTextPassword *getTextPassword, bool &isEncrypted, bool &passwordIsDefined, UString &password
30#define _7Z_DECODER_CRYPRO_VARS , getTextPassword, isEncrypted, passwordIsDefined, password 30#define Z7_7Z_DECODER_CRYPRO_VARS , getTextPassword, isEncrypted, passwordIsDefined, password
31#endif 31#endif
32 32
33struct CParsedMethods 33struct CParsedMethods
@@ -418,17 +418,17 @@ class CInArchive
418 DECL_EXTERNAL_CODECS_LOC_VARS 418 DECL_EXTERNAL_CODECS_LOC_VARS
419 UInt64 baseOffset, UInt64 &dataOffset, 419 UInt64 baseOffset, UInt64 &dataOffset,
420 CObjectVector<CByteBuffer> &dataVector 420 CObjectVector<CByteBuffer> &dataVector
421 _7Z_DECODER_CRYPRO_VARS_DECL 421 Z7_7Z_DECODER_CRYPRO_VARS_DECL
422 ); 422 );
423 HRESULT ReadHeader( 423 HRESULT ReadHeader(
424 DECL_EXTERNAL_CODECS_LOC_VARS 424 DECL_EXTERNAL_CODECS_LOC_VARS
425 CDbEx &db 425 CDbEx &db
426 _7Z_DECODER_CRYPRO_VARS_DECL 426 Z7_7Z_DECODER_CRYPRO_VARS_DECL
427 ); 427 );
428 HRESULT ReadDatabase2( 428 HRESULT ReadDatabase2(
429 DECL_EXTERNAL_CODECS_LOC_VARS 429 DECL_EXTERNAL_CODECS_LOC_VARS
430 CDbEx &db 430 CDbEx &db
431 _7Z_DECODER_CRYPRO_VARS_DECL 431 Z7_7Z_DECODER_CRYPRO_VARS_DECL
432 ); 432 );
433public: 433public:
434 CInArchive(bool useMixerMT): 434 CInArchive(bool useMixerMT):
@@ -442,7 +442,7 @@ public:
442 HRESULT ReadDatabase( 442 HRESULT ReadDatabase(
443 DECL_EXTERNAL_CODECS_LOC_VARS 443 DECL_EXTERNAL_CODECS_LOC_VARS
444 CDbEx &db 444 CDbEx &db
445 _7Z_DECODER_CRYPRO_VARS_DECL 445 Z7_7Z_DECODER_CRYPRO_VARS_DECL
446 ); 446 );
447}; 447};
448 448
diff --git a/CPP/7zip/Archive/7z/7zItem.h b/CPP/7zip/Archive/7z/7zItem.h
index 0f9fdad..e8c68be 100644
--- a/CPP/7zip/Archive/7z/7zItem.h
+++ b/CPP/7zip/Archive/7z/7zItem.h
@@ -1,7 +1,7 @@
1// 7zItem.h 1// 7zItem.h
2 2
3#ifndef __7Z_ITEM_H 3#ifndef ZIP7_INC_7Z_ITEM_H
4#define __7Z_ITEM_H 4#define ZIP7_INC_7Z_ITEM_H
5 5
6#include "../../../Common/MyBuffer.h" 6#include "../../../Common/MyBuffer.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
@@ -36,7 +36,7 @@ struct CBond
36 36
37struct CFolder 37struct CFolder
38{ 38{
39 CLASS_NO_COPY(CFolder) 39 Z7_CLASS_NO_COPY(CFolder)
40public: 40public:
41 CObjArray2<CCoderInfo> Coders; 41 CObjArray2<CCoderInfo> Coders;
42 CObjArray2<CBond> Bonds; 42 CObjArray2<CBond> Bonds;
@@ -129,6 +129,11 @@ struct CUInt32DefVector
129 bool CheckSize(unsigned size) const { return Defs.Size() == size || Defs.Size() == 0; } 129 bool CheckSize(unsigned size) const { return Defs.Size() == size || Defs.Size() == 0; }
130 130
131 void SetItem(unsigned index, bool defined, UInt32 value); 131 void SetItem(unsigned index, bool defined, UInt32 value);
132 void if_NonEmpty_FillResedue_with_false(unsigned numItems)
133 {
134 if (Defs.Size() != 0 && Defs.Size() < numItems)
135 SetItem(numItems - 1, false, 0);
136 }
132}; 137};
133 138
134 139
diff --git a/CPP/7zip/Archive/7z/7zOut.cpp b/CPP/7zip/Archive/7z/7zOut.cpp
index 2786bf2..7f8fa5b 100644
--- a/CPP/7zip/Archive/7z/7zOut.cpp
+++ b/CPP/7zip/Archive/7z/7zOut.cpp
@@ -14,16 +14,14 @@
14namespace NArchive { 14namespace NArchive {
15namespace N7z { 15namespace N7z {
16 16
17HRESULT COutArchive::WriteSignature() 17static void FillSignature(Byte *buf)
18{ 18{
19 Byte buf[8];
20 memcpy(buf, kSignature, kSignatureSize); 19 memcpy(buf, kSignature, kSignatureSize);
21 buf[kSignatureSize] = kMajorVersion; 20 buf[kSignatureSize] = kMajorVersion;
22 buf[kSignatureSize + 1] = 4; 21 buf[kSignatureSize + 1] = 4;
23 return WriteDirect(buf, 8);
24} 22}
25 23
26#ifdef _7Z_VOL 24#ifdef Z7_7Z_VOL
27HRESULT COutArchive::WriteFinishSignature() 25HRESULT COutArchive::WriteFinishSignature()
28{ 26{
29 RINOK(WriteDirect(kFinishSignature, kSignatureSize)); 27 RINOK(WriteDirect(kFinishSignature, kSignatureSize));
@@ -49,15 +47,16 @@ static void SetUInt64(Byte *p, UInt64 d)
49 47
50HRESULT COutArchive::WriteStartHeader(const CStartHeader &h) 48HRESULT COutArchive::WriteStartHeader(const CStartHeader &h)
51{ 49{
52 Byte buf[24]; 50 Byte buf[32];
53 SetUInt64(buf + 4, h.NextHeaderOffset); 51 FillSignature(buf);
54 SetUInt64(buf + 12, h.NextHeaderSize); 52 SetUInt64(buf + 8 + 4, h.NextHeaderOffset);
55 SetUInt32(buf + 20, h.NextHeaderCRC); 53 SetUInt64(buf + 8 + 12, h.NextHeaderSize);
56 SetUInt32(buf, CrcCalc(buf + 4, 20)); 54 SetUInt32(buf + 8 + 20, h.NextHeaderCRC);
57 return WriteDirect(buf, 24); 55 SetUInt32(buf + 8, CrcCalc(buf + 8 + 4, 20));
56 return WriteDirect(buf, sizeof(buf));
58} 57}
59 58
60#ifdef _7Z_VOL 59#ifdef Z7_7Z_VOL
61HRESULT COutArchive::WriteFinishHeader(const CFinishHeader &h) 60HRESULT COutArchive::WriteFinishHeader(const CFinishHeader &h)
62{ 61{
63 CCRC crc; 62 CCRC crc;
@@ -75,15 +74,15 @@ HRESULT COutArchive::WriteFinishHeader(const CFinishHeader &h)
75} 74}
76#endif 75#endif
77 76
78HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker) 77HRESULT COutArchive::Create_and_WriteStartPrefix(ISequentialOutStream *stream /* , bool endMarker */)
79{ 78{
80 Close(); 79 Close();
81 #ifdef _7Z_VOL 80 #ifdef Z7_7Z_VOL
82 // endMarker = false; 81 // endMarker = false;
83 _endMarker = endMarker; 82 _endMarker = endMarker;
84 #endif 83 #endif
85 SeqStream = stream; 84 SeqStream = stream;
86 if (!endMarker) 85 // if (!endMarker)
87 { 86 {
88 SeqStream.QueryInterface(IID_IOutStream, &Stream); 87 SeqStream.QueryInterface(IID_IOutStream, &Stream);
89 if (!Stream) 88 if (!Stream)
@@ -91,8 +90,13 @@ HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker)
91 return E_NOTIMPL; 90 return E_NOTIMPL;
92 // endMarker = true; 91 // endMarker = true;
93 } 92 }
93 RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &_signatureHeaderPos))
94 Byte buf[32];
95 FillSignature(buf);
96 memset(&buf[8], 0, 32 - 8);
97 return WriteDirect(buf, sizeof(buf));
94 } 98 }
95 #ifdef _7Z_VOL 99 #ifdef Z7_7Z_VOL
96 if (endMarker) 100 if (endMarker)
97 { 101 {
98 /* 102 /*
@@ -101,17 +105,10 @@ HRESULT COutArchive::Create(ISequentialOutStream *stream, bool endMarker)
101 sh.NextHeaderSize = (UInt32)(Int32)-1; 105 sh.NextHeaderSize = (UInt32)(Int32)-1;
102 sh.NextHeaderCRC = 0; 106 sh.NextHeaderCRC = 0;
103 WriteStartHeader(sh); 107 WriteStartHeader(sh);
108 return S_OK;
104 */ 109 */
105 } 110 }
106 else
107 #endif 111 #endif
108 {
109 if (!Stream)
110 return E_FAIL;
111 RINOK(WriteSignature());
112 RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &_prefixHeaderPos));
113 }
114 return S_OK;
115} 112}
116 113
117void COutArchive::Close() 114void COutArchive::Close()
@@ -120,17 +117,6 @@ void COutArchive::Close()
120 Stream.Release(); 117 Stream.Release();
121} 118}
122 119
123HRESULT COutArchive::SkipPrefixArchiveHeader()
124{
125 #ifdef _7Z_VOL
126 if (_endMarker)
127 return S_OK;
128 #endif
129 Byte buf[24];
130 memset(buf, 0, 24);
131 return WriteDirect(buf, 24);
132}
133
134UInt64 COutArchive::GetPos() const 120UInt64 COutArchive::GetPos() const
135{ 121{
136 if (_countMode) 122 if (_countMode)
@@ -216,7 +202,7 @@ static unsigned GetBigNumberSize(UInt64 value)
216 return i; 202 return i;
217} 203}
218 204
219#ifdef _7Z_VOL 205#ifdef Z7_7Z_VOL
220UInt32 COutArchive::GetVolHeadersSize(UInt64 dataSize, int nameLength, bool props) 206UInt32 COutArchive::GetVolHeadersSize(UInt64 dataSize, int nameLength, bool props)
221{ 207{
222 UInt32 result = GetBigNumberSize(dataSize) * 2 + 41; 208 UInt32 result = GetBigNumberSize(dataSize) * 2 + 41;
@@ -515,14 +501,20 @@ HRESULT COutArchive::EncodeStream(
515 outFolders.FolderUnpackCRCs.Defs.Add(true); 501 outFolders.FolderUnpackCRCs.Defs.Add(true);
516 outFolders.FolderUnpackCRCs.Vals.Add(CrcCalc(data, data.Size())); 502 outFolders.FolderUnpackCRCs.Vals.Add(CrcCalc(data, data.Size()));
517 // outFolders.NumUnpackStreamsVector.Add(1); 503 // outFolders.NumUnpackStreamsVector.Add(1);
518 UInt64 dataSize64 = data.Size(); 504 const UInt64 dataSize64 = data.Size();
519 UInt64 unpackSize = data.Size(); 505 const UInt64 expectSize = data.Size();
520 RINOK(encoder.Encode( 506 RINOK(encoder.Encode1(
521 EXTERNAL_CODECS_LOC_VARS 507 EXTERNAL_CODECS_LOC_VARS
522 stream, 508 stream,
523 // NULL, 509 // NULL,
524 &dataSize64, 510 &dataSize64, // inSizeForReduce
525 folders.AddNew(), outFolders.CoderUnpackSizes, unpackSize, SeqStream, packSizes, NULL)) 511 expectSize,
512 folders.AddNew(),
513 // outFolders.CoderUnpackSizes, unpackSize,
514 SeqStream, packSizes, NULL))
515 if (!streamSpec->WasFinished())
516 return E_FAIL;
517 encoder.Encode_Post(dataSize64, outFolders.CoderUnpackSizes);
526 return S_OK; 518 return S_OK;
527} 519}
528 520
@@ -833,15 +825,15 @@ HRESULT COutArchive::WriteDatabase(
833 { 825 {
834 headerSize = 0; 826 headerSize = 0;
835 headerOffset = 0; 827 headerOffset = 0;
836 headerCRC = CrcCalc(0, 0); 828 headerCRC = CrcCalc(NULL, 0);
837 } 829 }
838 else 830 else
839 { 831 {
840 bool encodeHeaders = false; 832 bool encodeHeaders = false;
841 if (options != 0) 833 if (options)
842 if (options->IsEmpty()) 834 if (options->IsEmpty())
843 options = 0; 835 options = NULL;
844 if (options != 0) 836 if (options)
845 if (options->PasswordIsDefined || headerOptions.CompressMainHeader) 837 if (options->PasswordIsDefined || headerOptions.CompressMainHeader)
846 encodeHeaders = true; 838 encodeHeaders = true;
847 839
@@ -876,7 +868,7 @@ HRESULT COutArchive::WriteDatabase(
876 RINOK(EncodeStream( 868 RINOK(EncodeStream(
877 EXTERNAL_CODECS_LOC_VARS 869 EXTERNAL_CODECS_LOC_VARS
878 encoder, buf, 870 encoder, buf,
879 packSizes, folders, outFolders)); 871 packSizes, folders, outFolders))
880 872
881 _writeToStream = true; 873 _writeToStream = true;
882 874
@@ -890,11 +882,11 @@ HRESULT COutArchive::WriteDatabase(
890 FOR_VECTOR (i, packSizes) 882 FOR_VECTOR (i, packSizes)
891 headerOffset += packSizes[i]; 883 headerOffset += packSizes[i];
892 } 884 }
893 RINOK(_outByte.Flush()); 885 RINOK(_outByte.Flush())
894 headerCRC = CRC_GET_DIGEST(_crc); 886 headerCRC = CRC_GET_DIGEST(_crc);
895 headerSize = _outByte.GetProcessedSize(); 887 headerSize = _outByte.GetProcessedSize();
896 } 888 }
897 #ifdef _7Z_VOL 889 #ifdef Z7_7Z_VOL
898 if (_endMarker) 890 if (_endMarker)
899 { 891 {
900 CFinishHeader h; 892 CFinishHeader h;
@@ -910,14 +902,16 @@ HRESULT COutArchive::WriteDatabase(
910 } 902 }
911 else 903 else
912 #endif 904 #endif
905 if (Stream)
913 { 906 {
914 CStartHeader h; 907 CStartHeader h;
915 h.NextHeaderSize = headerSize; 908 h.NextHeaderSize = headerSize;
916 h.NextHeaderCRC = headerCRC; 909 h.NextHeaderCRC = headerCRC;
917 h.NextHeaderOffset = headerOffset; 910 h.NextHeaderOffset = headerOffset;
918 RINOK(Stream->Seek((Int64)_prefixHeaderPos, STREAM_SEEK_SET, NULL)); 911 RINOK(Stream->Seek((Int64)_signatureHeaderPos, STREAM_SEEK_SET, NULL))
919 return WriteStartHeader(h); 912 return WriteStartHeader(h);
920 } 913 }
914 return S_OK;
921} 915}
922 916
923void CUInt32DefVector::SetItem(unsigned index, bool defined, UInt32 value) 917void 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 1ebad56..940cafc 100644
--- a/CPP/7zip/Archive/7z/7zOut.h
+++ b/CPP/7zip/Archive/7z/7zOut.h
@@ -1,7 +1,7 @@
1// 7zOut.h 1// 7zOut.h
2 2
3#ifndef __7Z_OUT_H 3#ifndef ZIP7_INC_7Z_OUT_H
4#define __7Z_OUT_H 4#define ZIP7_INC_7Z_OUT_H
5 5
6#include "7zCompressionMode.h" 6#include "7zCompressionMode.h"
7#include "7zEncode.h" 7#include "7zEncode.h"
@@ -14,6 +14,8 @@
14namespace NArchive { 14namespace NArchive {
15namespace N7z { 15namespace N7z {
16 16
17const unsigned k_StartHeadersRewriteSize = 32;
18
17class CWriteBufferLoc 19class CWriteBufferLoc
18{ 20{
19 Byte *_data; 21 Byte *_data;
@@ -240,8 +242,6 @@ struct CArchiveDatabaseOut: public COutFolders
240 242
241class COutArchive 243class COutArchive
242{ 244{
243 UInt64 _prefixHeaderPos;
244
245 HRESULT WriteDirect(const void *data, UInt32 size) { return WriteStream(SeqStream, data, size); } 245 HRESULT WriteDirect(const void *data, UInt32 size) { return WriteStream(SeqStream, data, size); }
246 246
247 UInt64 GetPos() const; 247 UInt64 GetPos() const;
@@ -290,44 +290,39 @@ class COutArchive
290 290
291 bool _countMode; 291 bool _countMode;
292 bool _writeToStream; 292 bool _writeToStream;
293 size_t _countSize; 293 bool _useAlign;
294 UInt32 _crc; 294 #ifdef Z7_7Z_VOL
295 COutBuffer _outByte;
296 CWriteBufferLoc _outByte2;
297
298 #ifdef _7Z_VOL
299 bool _endMarker; 295 bool _endMarker;
300 #endif 296 #endif
297 UInt32 _crc;
298 size_t _countSize;
299 CWriteBufferLoc _outByte2;
300 COutBuffer _outByte;
301 UInt64 _signatureHeaderPos;
302 CMyComPtr<IOutStream> Stream;
301 303
302 bool _useAlign; 304 #ifdef Z7_7Z_VOL
303
304 HRESULT WriteSignature();
305 #ifdef _7Z_VOL
306 HRESULT WriteFinishSignature(); 305 HRESULT WriteFinishSignature();
307 #endif
308 HRESULT WriteStartHeader(const CStartHeader &h);
309 #ifdef _7Z_VOL
310 HRESULT WriteFinishHeader(const CFinishHeader &h); 306 HRESULT WriteFinishHeader(const CFinishHeader &h);
311 #endif 307 #endif
312 CMyComPtr<IOutStream> Stream; 308 HRESULT WriteStartHeader(const CStartHeader &h);
309
313public: 310public:
311 CMyComPtr<ISequentialOutStream> SeqStream;
314 312
315 COutArchive() { _outByte.Create(1 << 16); } 313 COutArchive() { _outByte.Create(1 << 16); }
316 CMyComPtr<ISequentialOutStream> SeqStream; 314 HRESULT Create_and_WriteStartPrefix(ISequentialOutStream *stream /* , bool endMarker */);
317 HRESULT Create(ISequentialOutStream *stream, bool endMarker);
318 void Close(); 315 void Close();
319 HRESULT SkipPrefixArchiveHeader();
320 HRESULT WriteDatabase( 316 HRESULT WriteDatabase(
321 DECL_EXTERNAL_CODECS_LOC_VARS 317 DECL_EXTERNAL_CODECS_LOC_VARS
322 const CArchiveDatabaseOut &db, 318 const CArchiveDatabaseOut &db,
323 const CCompressionMethodMode *options, 319 const CCompressionMethodMode *options,
324 const CHeaderOptions &headerOptions); 320 const CHeaderOptions &headerOptions);
325 321
326 #ifdef _7Z_VOL 322 #ifdef Z7_7Z_VOL
327 static UInt32 GetVolHeadersSize(UInt64 dataSize, int nameLength = 0, bool props = false); 323 static UInt32 GetVolHeadersSize(UInt64 dataSize, int nameLength = 0, bool props = false);
328 static UInt64 GetVolPureSize(UInt64 volSize, int nameLength = 0, bool props = false); 324 static UInt64 GetVolPureSize(UInt64 volSize, int nameLength = 0, bool props = false);
329 #endif 325 #endif
330
331}; 326};
332 327
333}} 328}}
diff --git a/CPP/7zip/Archive/7z/7zProperties.cpp b/CPP/7zip/Archive/7z/7zProperties.cpp
index 4cb5a5e..d3b3cbe 100644
--- a/CPP/7zip/Archive/7z/7zProperties.cpp
+++ b/CPP/7zip/Archive/7z/7zProperties.cpp
@@ -2,56 +2,63 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "7zProperties.h"
6#include "7zHeader.h"
7#include "7zHandler.h" 5#include "7zHandler.h"
8 6#include "7zProperties.h"
9// #define _MULTI_PACK
10 7
11namespace NArchive { 8namespace NArchive {
12namespace N7z { 9namespace N7z {
13 10
14struct CPropMap 11struct CPropMap
15{ 12{
16 UInt32 FilePropID; 13 Byte FilePropID;
17 CStatProp StatProp; 14 // CStatProp StatProp;
15 VARTYPE vt;
16 UInt32 StatPropID;
18}; 17};
19 18
19// #define STAT_PROP(name, id, vt) { name, id, vt }
20#define STAT_PROP(name, id, vt) vt, id
21
22#define STAT_PROP2(id, vt) STAT_PROP(NULL, id, vt)
23
24#define k_7z_id_Encrypted 97
25#define k_7z_id_Method 98
26#define k_7z_id_Block 99
27
20static const CPropMap kPropMap[] = 28static const CPropMap kPropMap[] =
21{ 29{
22 { NID::kName, { NULL, kpidPath, VT_BSTR } }, 30 { NID::kName, STAT_PROP2(kpidPath, VT_BSTR) },
23 { NID::kSize, { NULL, kpidSize, VT_UI8 } }, 31 { NID::kSize, STAT_PROP2(kpidSize, VT_UI8) },
24 { NID::kPackInfo, { NULL, kpidPackSize, VT_UI8 } }, 32 { NID::kPackInfo, STAT_PROP2(kpidPackSize, VT_UI8) },
25 33
26 #ifdef _MULTI_PACK 34 #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES
27 { 100, { "Pack0", kpidPackedSize0, VT_UI8 } }, 35#define k_7z_id_PackedSize0 100
28 { 101, { "Pack1", kpidPackedSize1, VT_UI8 } }, 36 { k_7z_id_PackedSize0 + 0, STAT_PROP("Pack0", kpidPackedSize0, VT_UI8) },
29 { 102, { "Pack2", kpidPackedSize2, VT_UI8 } }, 37 { k_7z_id_PackedSize0 + 1, STAT_PROP("Pack1", kpidPackedSize1, VT_UI8) },
30 { 103, { "Pack3", kpidPackedSize3, VT_UI8 } }, 38 { k_7z_id_PackedSize0 + 2, STAT_PROP("Pack2", kpidPackedSize2, VT_UI8) },
31 { 104, { "Pack4", kpidPackedSize4, VT_UI8 } }, 39 { k_7z_id_PackedSize0 + 3, STAT_PROP("Pack3", kpidPackedSize3, VT_UI8) },
40 { k_7z_id_PackedSize0 + 4, STAT_PROP("Pack4", kpidPackedSize4, VT_UI8) },
32 #endif 41 #endif
33 42
34 { NID::kCTime, { NULL, kpidCTime, VT_FILETIME } }, 43 { NID::kCTime, STAT_PROP2(kpidCTime, VT_FILETIME) },
35 { NID::kMTime, { NULL, kpidMTime, VT_FILETIME } }, 44 { NID::kMTime, STAT_PROP2(kpidMTime, VT_FILETIME) },
36 { NID::kATime, { NULL, kpidATime, VT_FILETIME } }, 45 { NID::kATime, STAT_PROP2(kpidATime, VT_FILETIME) },
37 { NID::kWinAttrib, { NULL, kpidAttrib, VT_UI4 } }, 46 { NID::kWinAttrib, STAT_PROP2(kpidAttrib, VT_UI4) },
38 { NID::kStartPos, { NULL, kpidPosition, VT_UI8 } }, 47 { NID::kStartPos, STAT_PROP2(kpidPosition, VT_UI8) },
39 48
40 { NID::kCRC, { NULL, kpidCRC, VT_UI4 } }, 49 { NID::kCRC, STAT_PROP2(kpidCRC, VT_UI4) },
41 50 // { NID::kIsAux, STAT_PROP2(kpidIsAux, VT_BOOL) },
42// { NID::kIsAux, { NULL, kpidIsAux, VT_BOOL } }, 51 { NID::kAnti, STAT_PROP2(kpidIsAnti, VT_BOOL) }
43 { NID::kAnti, { NULL, kpidIsAnti, VT_BOOL } } 52
44 53 #ifndef Z7_SFX
45 #ifndef _SFX 54 , { k_7z_id_Encrypted, STAT_PROP2(kpidEncrypted, VT_BOOL) }
46 , 55 , { k_7z_id_Method, STAT_PROP2(kpidMethod, VT_BSTR) }
47 { 97, { NULL, kpidEncrypted, VT_BOOL } }, 56 , { k_7z_id_Block, STAT_PROP2(kpidBlock, VT_UI4) }
48 { 98, { NULL, kpidMethod, VT_BSTR } },
49 { 99, { NULL, kpidBlock, VT_UI4 } }
50 #endif 57 #endif
51}; 58};
52 59
53static void CopyOneItem(CRecordVector<UInt64> &src, 60static void CopyOneItem(CRecordVector<UInt64> &src,
54 CRecordVector<UInt64> &dest, UInt32 item) 61 CRecordVector<UInt64> &dest, const UInt32 item)
55{ 62{
56 FOR_VECTOR (i, src) 63 FOR_VECTOR (i, src)
57 if (src[i] == item) 64 if (src[i] == item)
@@ -62,7 +69,7 @@ static void CopyOneItem(CRecordVector<UInt64> &src,
62 } 69 }
63} 70}
64 71
65static void RemoveOneItem(CRecordVector<UInt64> &src, UInt32 item) 72static void RemoveOneItem(CRecordVector<UInt64> &src, const UInt32 item)
66{ 73{
67 FOR_VECTOR (i, src) 74 FOR_VECTOR (i, src)
68 if (src[i] == item) 75 if (src[i] == item)
@@ -72,7 +79,7 @@ static void RemoveOneItem(CRecordVector<UInt64> &src, UInt32 item)
72 } 79 }
73} 80}
74 81
75static void InsertToHead(CRecordVector<UInt64> &dest, UInt32 item) 82static void InsertToHead(CRecordVector<UInt64> &dest, const UInt32 item)
76{ 83{
77 FOR_VECTOR (i, dest) 84 FOR_VECTOR (i, dest)
78 if (dest[i] == item) 85 if (dest[i] == item)
@@ -89,7 +96,7 @@ void CHandler::FillPopIDs()
89{ 96{
90 _fileInfoPopIDs.Clear(); 97 _fileInfoPopIDs.Clear();
91 98
92 #ifdef _7Z_VOL 99 #ifdef Z7_7Z_VOL
93 if (_volumes.Size() < 1) 100 if (_volumes.Size() < 1)
94 return; 101 return;
95 const CVolume &volume = _volumes.Front(); 102 const CVolume &volume = _volumes.Front();
@@ -105,34 +112,31 @@ void CHandler::FillPopIDs()
105 RemoveOneItem(fileInfoPopIDs, NID::kNtSecure); 112 RemoveOneItem(fileInfoPopIDs, NID::kNtSecure);
106 */ 113 */
107 114
108 COPY_ONE_ITEM(kName); 115 COPY_ONE_ITEM(kName)
109 COPY_ONE_ITEM(kAnti); 116 COPY_ONE_ITEM(kAnti)
110 COPY_ONE_ITEM(kSize); 117 COPY_ONE_ITEM(kSize)
111 COPY_ONE_ITEM(kPackInfo); 118 COPY_ONE_ITEM(kPackInfo)
112 COPY_ONE_ITEM(kCTime); 119 COPY_ONE_ITEM(kCTime)
113 COPY_ONE_ITEM(kMTime); 120 COPY_ONE_ITEM(kMTime)
114 COPY_ONE_ITEM(kATime); 121 COPY_ONE_ITEM(kATime)
115 COPY_ONE_ITEM(kWinAttrib); 122 COPY_ONE_ITEM(kWinAttrib)
116 COPY_ONE_ITEM(kCRC); 123 COPY_ONE_ITEM(kCRC)
117 COPY_ONE_ITEM(kComment); 124 COPY_ONE_ITEM(kComment)
118 125
119 _fileInfoPopIDs += fileInfoPopIDs; 126 _fileInfoPopIDs += fileInfoPopIDs;
120 127
121 #ifndef _SFX 128 #ifndef Z7_SFX
122 _fileInfoPopIDs.Add(97); 129 _fileInfoPopIDs.Add(k_7z_id_Encrypted);
123 _fileInfoPopIDs.Add(98); 130 _fileInfoPopIDs.Add(k_7z_id_Method);
124 _fileInfoPopIDs.Add(99); 131 _fileInfoPopIDs.Add(k_7z_id_Block);
125 #endif 132 #endif
126 133
127 #ifdef _MULTI_PACK 134 #ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES
128 _fileInfoPopIDs.Add(100); 135 for (unsigned i = 0; i < 5; i++)
129 _fileInfoPopIDs.Add(101); 136 _fileInfoPopIDs.Add(k_7z_id_PackedSize0 + i);
130 _fileInfoPopIDs.Add(102);
131 _fileInfoPopIDs.Add(103);
132 _fileInfoPopIDs.Add(104);
133 #endif 137 #endif
134 138
135 #ifndef _SFX 139 #ifndef Z7_SFX
136 InsertToHead(_fileInfoPopIDs, NID::kMTime); 140 InsertToHead(_fileInfoPopIDs, NID::kMTime);
137 InsertToHead(_fileInfoPopIDs, NID::kPackInfo); 141 InsertToHead(_fileInfoPopIDs, NID::kPackInfo);
138 InsertToHead(_fileInfoPopIDs, NID::kSize); 142 InsertToHead(_fileInfoPopIDs, NID::kSize);
@@ -140,25 +144,29 @@ void CHandler::FillPopIDs()
140 #endif 144 #endif
141} 145}
142 146
143STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) 147Z7_COM7F_IMF(CHandler::GetNumberOfProperties(UInt32 *numProps))
144{ 148{
145 *numProps = _fileInfoPopIDs.Size(); 149 *numProps = _fileInfoPopIDs.Size();
146 return S_OK; 150 return S_OK;
147} 151}
148 152
149STDMETHODIMP CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) 153Z7_COM7F_IMF(CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType))
150{ 154{
151 if (index >= _fileInfoPopIDs.Size()) 155 if (index >= _fileInfoPopIDs.Size())
152 return E_INVALIDARG; 156 return E_INVALIDARG;
153 UInt64 id = _fileInfoPopIDs[index]; 157 const UInt64 id = _fileInfoPopIDs[index];
154 for (unsigned i = 0; i < ARRAY_SIZE(kPropMap); i++) 158 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPropMap); i++)
155 { 159 {
156 const CPropMap &pr = kPropMap[i]; 160 const CPropMap &pr = kPropMap[i];
157 if (pr.FilePropID == id) 161 if (pr.FilePropID == id)
158 { 162 {
163 *propID = pr.StatPropID;
164 *varType = pr.vt;
165 /*
159 const CStatProp &st = pr.StatProp; 166 const CStatProp &st = pr.StatProp;
160 *propID = st.PropID; 167 *propID = st.PropID;
161 *varType = st.vt; 168 *varType = st.vt;
169 */
162 /* 170 /*
163 if (st.lpwstrName) 171 if (st.lpwstrName)
164 *name = ::SysAllocString(st.lpwstrName); 172 *name = ::SysAllocString(st.lpwstrName);
diff --git a/CPP/7zip/Archive/7z/7zProperties.h b/CPP/7zip/Archive/7z/7zProperties.h
index 6618179..091c39b 100644
--- a/CPP/7zip/Archive/7z/7zProperties.h
+++ b/CPP/7zip/Archive/7z/7zProperties.h
@@ -1,13 +1,16 @@
1// 7zProperties.h 1// 7zProperties.h
2 2
3#ifndef __7Z_PROPERTIES_H 3#ifndef ZIP7_INC_7Z_PROPERTIES_H
4#define __7Z_PROPERTIES_H 4#define ZIP7_INC_7Z_PROPERTIES_H
5 5
6#include "../../PropID.h" 6#include "../../PropID.h"
7 7
8namespace NArchive { 8namespace NArchive {
9namespace N7z { 9namespace N7z {
10 10
11// #define Z7_7Z_SHOW_PACK_STREAMS_SIZES // for debug
12
13#ifdef Z7_7Z_SHOW_PACK_STREAMS_SIZES
11enum 14enum
12{ 15{
13 kpidPackedSize0 = kpidUserDefined, 16 kpidPackedSize0 = kpidUserDefined,
@@ -16,6 +19,7 @@ enum
16 kpidPackedSize3, 19 kpidPackedSize3,
17 kpidPackedSize4 20 kpidPackedSize4
18}; 21};
22#endif
19 23
20}} 24}}
21 25
diff --git a/CPP/7zip/Archive/7z/7zRegister.cpp b/CPP/7zip/Archive/7z/7zRegister.cpp
index eac8b4f..1f11079 100644
--- a/CPP/7zip/Archive/7z/7zRegister.cpp
+++ b/CPP/7zip/Archive/7z/7zRegister.cpp
@@ -22,6 +22,6 @@ REGISTER_ARC_IO_DECREMENT_SIG(
22 | NArcInfoFlags::kMTime_Default 22 | NArcInfoFlags::kMTime_Default
23 , TIME_PREC_TO_ARC_FLAGS_MASK(NFileTimeType::kWindows) 23 , TIME_PREC_TO_ARC_FLAGS_MASK(NFileTimeType::kWindows)
24 | TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(NFileTimeType::kWindows) 24 | TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(NFileTimeType::kWindows)
25 , NULL); 25 , NULL)
26 26
27}} 27}}
diff --git a/CPP/7zip/Archive/7z/7zSpecStream.cpp b/CPP/7zip/Archive/7z/7zSpecStream.cpp
index 8e45d98..8b531bc 100644
--- a/CPP/7zip/Archive/7z/7zSpecStream.cpp
+++ b/CPP/7zip/Archive/7z/7zSpecStream.cpp
@@ -4,19 +4,28 @@
4 4
5#include "7zSpecStream.h" 5#include "7zSpecStream.h"
6 6
7STDMETHODIMP CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize) 7/*
8Z7_COM7F_IMF(CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize))
8{ 9{
9 UInt32 realProcessedSize; 10 UInt32 realProcessedSize;
10 HRESULT result = _stream->Read(data, size, &realProcessedSize); 11 const HRESULT result = _stream->Read(data, size, &realProcessedSize);
11 _size += realProcessedSize; 12 _size += realProcessedSize;
12 if (processedSize) 13 if (processedSize)
13 *processedSize = realProcessedSize; 14 *processedSize = realProcessedSize;
14 return result; 15 return result;
15} 16}
16 17
17STDMETHODIMP CSequentialInStreamSizeCount2::GetSubStreamSize(UInt64 subStream, UInt64 *value) 18Z7_COM7F_IMF(CSequentialInStreamSizeCount2::GetSubStreamSize(UInt64 subStream, UInt64 *value))
18{ 19{
19 if (!_getSubStreamSize) 20 if (!_getSubStreamSize)
20 return E_NOTIMPL; 21 return E_NOTIMPL;
21 return _getSubStreamSize->GetSubStreamSize(subStream, value); 22 return _getSubStreamSize->GetSubStreamSize(subStream, value);
22} 23}
24
25Z7_COM7F_IMF(CSequentialInStreamSizeCount2::GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream))
26{
27 if (!_compressGetSubStreamSize)
28 return E_NOTIMPL;
29 return _compressGetSubStreamSize->GetNextInSubStream(streamIndexRes, stream);
30}
31*/
diff --git a/CPP/7zip/Archive/7z/7zSpecStream.h b/CPP/7zip/Archive/7z/7zSpecStream.h
index 2115506..78f631e 100644
--- a/CPP/7zip/Archive/7z/7zSpecStream.h
+++ b/CPP/7zip/Archive/7z/7zSpecStream.h
@@ -1,35 +1,49 @@
1// 7zSpecStream.h 1// 7zSpecStream.h
2 2
3#ifndef __7Z_SPEC_STREAM_H 3#ifndef ZIP7_INC_7Z_SPEC_STREAM_H
4#define __7Z_SPEC_STREAM_H 4#define ZIP7_INC_7Z_SPEC_STREAM_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../../ICoder.h" 8#include "../../ICoder.h"
9 9
10class CSequentialInStreamSizeCount2: 10/*
11#define Z7_COM_QI_ENTRY_AG_2(i, sub0, sub) else if (iid == IID_ ## i) \
12 { if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \
13 { i *ti = this; *outObject = ti; } }
14
15class CSequentialInStreamSizeCount2 Z7_final:
11 public ISequentialInStream, 16 public ISequentialInStream,
12 public ICompressGetSubStreamSize, 17 public ICompressGetSubStreamSize,
18 public ICompressInSubStreams,
13 public CMyUnknownImp 19 public CMyUnknownImp
14{ 20{
21 Z7_COM_QI_BEGIN2(ISequentialInStream)
22 Z7_COM_QI_ENTRY(ICompressGetSubStreamSize)
23 Z7_COM_QI_ENTRY_AG_2(ISequentialInStream, _stream, _compressGetSubStreamSize)
24 Z7_COM_QI_END
25 Z7_COM_ADDREF_RELEASE
26
27 Z7_IFACE_COM7_IMP(ISequentialInStream)
28 Z7_IFACE_COM7_IMP(ICompressGetSubStreamSize)
29 Z7_IFACE_COM7_IMP(ICompressInSubStreams)
30
15 CMyComPtr<ISequentialInStream> _stream; 31 CMyComPtr<ISequentialInStream> _stream;
16 CMyComPtr<ICompressGetSubStreamSize> _getSubStreamSize; 32 CMyComPtr<ICompressGetSubStreamSize> _getSubStreamSize;
33 CMyComPtr<ICompressInSubStreams> _compressGetSubStreamSize;
17 UInt64 _size; 34 UInt64 _size;
18public: 35public:
19 void Init(ISequentialInStream *stream) 36 void Init(ISequentialInStream *stream)
20 { 37 {
21 _size = 0; 38 _size = 0;
22 _getSubStreamSize.Release(); 39 _getSubStreamSize.Release();
40 _compressGetSubStreamSize.Release();
23 _stream = stream; 41 _stream = stream;
24 _stream.QueryInterface(IID_ICompressGetSubStreamSize, &_getSubStreamSize); 42 _stream.QueryInterface(IID_ICompressGetSubStreamSize, &_getSubStreamSize);
43 _stream.QueryInterface(IID_ICompressInSubStreams, &_compressGetSubStreamSize);
25 } 44 }
26 UInt64 GetSize() const { return _size; } 45 UInt64 GetSize() const { return _size; }
27
28 MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize)
29
30 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
31
32 STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value);
33}; 46};
47*/
34 48
35#endif 49#endif
diff --git a/CPP/7zip/Archive/7z/7zUpdate.cpp b/CPP/7zip/Archive/7z/7zUpdate.cpp
index b6fd192..4e9ea5d 100644
--- a/CPP/7zip/Archive/7z/7zUpdate.cpp
+++ b/CPP/7zip/Archive/7z/7zUpdate.cpp
@@ -4,6 +4,8 @@
4 4
5#include "../../../../C/CpuArch.h" 5#include "../../../../C/CpuArch.h"
6 6
7#include "../../../Common/MyLinux.h"
8#include "../../../Common/StringToInt.h"
7#include "../../../Common/Wildcard.h" 9#include "../../../Common/Wildcard.h"
8 10
9#include "../../Common/CreateCoder.h" 11#include "../../Common/CreateCoder.h"
@@ -24,24 +26,43 @@
24namespace NArchive { 26namespace NArchive {
25namespace N7z { 27namespace N7z {
26 28
27
28#define k_X86 k_BCJ 29#define k_X86 k_BCJ
29 30
30struct CFilterMode 31struct CFilterMode
31{ 32{
32 UInt32 Id; 33 UInt32 Id;
33 UInt32 Delta; 34 UInt32 Delta; // required File Size alignment, if Id is not k_Delta.
34 35 // (Delta == 0) means unknown alignment
35 CFilterMode(): Id(0), Delta(0) {} 36 UInt32 Offset; // for k_ARM64
37 // UInt32 AlignSizeOpt; // for k_ARM64
38
39 CFilterMode():
40 Id(0),
41 Delta(0),
42 Offset(0)
43 // , AlignSizeOpt(0)
44 {}
45
46 void ClearFilterMode()
47 {
48 Id = 0;
49 Delta = 0;
50 Offset = 0;
51 // AlignSizeOpt = 0;
52 }
36 53
54 // it sets Delta as Align value, if Id is exe filter
55 // in another cases it sets Delta = 0, that
37 void SetDelta() 56 void SetDelta()
38 { 57 {
39 if (Id == k_IA64) 58 if (Id == k_IA64)
40 Delta = 16; 59 Delta = 16;
41 else if (Id == k_ARM || Id == k_PPC || Id == k_SPARC) 60 else if (Id == k_ARM64 || Id == k_ARM || Id == k_PPC || Id == k_SPARC)
42 Delta = 4; 61 Delta = 4;
43 else if (Id == k_ARMT) 62 else if (Id == k_ARMT)
44 Delta = 2; 63 Delta = 2;
64 else if (Id == k_BCJ || Id == k_BCJ2)
65 Delta = 1; // do we need it?
45 else 66 else
46 Delta = 0; 67 Delta = 0;
47 } 68 }
@@ -78,6 +99,7 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode)
78 { 99 {
79 case 0x014C: 100 case 0x014C:
80 case 0x8664: filterId = k_X86; break; 101 case 0x8664: filterId = k_X86; break;
102 case 0xAA64: filterId = k_ARM64; break;
81 103
82 /* 104 /*
83 IMAGE_FILE_MACHINE_ARM 0x01C0 // ARM LE 105 IMAGE_FILE_MACHINE_ARM 0x01C0 // ARM LE
@@ -94,6 +116,7 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode)
94 default: return 0; 116 default: return 0;
95 } 117 }
96 118
119 // const UInt32 numSections = GetUi16(p + 2);
97 optHeaderSize = GetUi16(p + 16); 120 optHeaderSize = GetUi16(p + 16);
98 if (optHeaderSize > (1 << 10)) 121 if (optHeaderSize > (1 << 10))
99 return 0; 122 return 0;
@@ -109,6 +132,63 @@ static int Parse_EXE(const Byte *buf, size_t size, CFilterMode *filterMode)
109 return 0; 132 return 0;
110 } 133 }
111 134
135 /*
136 // Windows exe file sizes are not aligned for 4 KiB.
137 // So we can't use (CFilterMode::Offset != 0) in solid archives.
138 // So we just don't set Offset here.
139#define NUM_SCAN_SECTIONS_MAX (1 << 6)
140#define EXE_SECTION_OFFSET_MAX (1 << 27)
141#define EXE_SECTION_SIZE_MIN (1 << 8)
142#define EXE_SECTION_SIZE_MAX (1 << 27)
143#define PE_SectHeaderSize 40
144#define PE_SECT_EXECUTE 0x20000000
145
146 if (numSections > NUM_SCAN_SECTIONS_MAX)
147 return 0;
148
149 p += optHeaderSize;
150 // UInt32 numExeSections = 0;
151 // bool execute_finded = false;
152 // UInt32 sect_va = 0;
153 // UInt32 sect_size = 0;
154 // UInt32 sect_offset = 0;
155
156 for (UInt32 i = 0; i < numSections
157 // && numExeSections < numSectionsMax
158 ; i++, p += PE_SectHeaderSize)
159 {
160 UInt32 characts, rawSize, offset;
161 if ((UInt32)(p - buf) + PE_SectHeaderSize > size)
162 return 0;
163 rawSize = GetUi32(p + 16);
164 offset = GetUi32(p + 20);
165 characts = GetUi32(p + 36);
166 if (rawSize >= EXE_SECTION_SIZE_MIN &&
167 rawSize <= EXE_SECTION_SIZE_MAX &&
168 offset <= EXE_SECTION_OFFSET_MAX &&
169 // offset < limit &&
170 offset > 0)
171 {
172 if ((characts & PE_SECT_EXECUTE) != 0)
173 {
174 // execute_finded = true;
175 // sect_va = GetUi32(p + 12);
176 // sect_size = rawSize;
177 // sect_offset = offset;
178 break;
179 }
180 }
181 }
182
183 filterMode->Offset = 0;
184 if (filterId == k_ARM64)
185 {
186 // filterMode->AlignSizeOpt = (1 << 12);
187 // const UInt32 offs = (sect_va - sect_offset) & 0xFFF;
188 // if (offs != 0)
189 // filterMode->Offset = offs; // change it
190 }
191 */
112 filterMode->Id = filterId; 192 filterMode->Id = filterId;
113 return 1; 193 return 1;
114} 194}
@@ -164,8 +244,9 @@ static int Parse_ELF(const Byte *buf, size_t size, CFilterMode *filterMode)
164 case 20: 244 case 20:
165 case 21: if (!be) return 0; filterId = k_PPC; break; 245 case 21: if (!be) return 0; filterId = k_PPC; break;
166 case 40: if ( be) return 0; filterId = k_ARM; break; 246 case 40: if ( be) return 0; filterId = k_ARM; break;
167 247 case 183: if (be) return 0; filterId = k_ARM64; break;
168 /* Some IA-64 ELF exacutable have size that is not aligned for 16 bytes. 248
249 /* Some IA-64 ELF executables have size that is not aligned for 16 bytes.
169 So we don't use IA-64 filter for IA-64 ELF */ 250 So we don't use IA-64 filter for IA-64 ELF */
170 // case 50: if ( be) return 0; filterId = k_IA64; break; 251 // case 50: if ( be) return 0; filterId = k_IA64; break;
171 252
@@ -192,6 +273,7 @@ static int Parse_ELF(const Byte *buf, size_t size, CFilterMode *filterMode)
192#define MACH_MACHINE_PPC 18 273#define MACH_MACHINE_PPC 18
193#define MACH_MACHINE_PPC64 (MACH_ARCH_ABI64 | MACH_MACHINE_PPC) 274#define MACH_MACHINE_PPC64 (MACH_ARCH_ABI64 | MACH_MACHINE_PPC)
194#define MACH_MACHINE_AMD64 (MACH_ARCH_ABI64 | MACH_MACHINE_386) 275#define MACH_MACHINE_AMD64 (MACH_ARCH_ABI64 | MACH_MACHINE_386)
276#define MACH_MACHINE_ARM64 (MACH_ARCH_ABI64 | MACH_MACHINE_ARM)
195 277
196static unsigned Parse_MACH(const Byte *buf, size_t size, CFilterMode *filterMode) 278static unsigned Parse_MACH(const Byte *buf, size_t size, CFilterMode *filterMode)
197{ 279{
@@ -218,6 +300,7 @@ static unsigned Parse_MACH(const Byte *buf, size_t size, CFilterMode *filterMode
218 case MACH_MACHINE_SPARC: if (!be) return 0; filterId = k_SPARC; break; 300 case MACH_MACHINE_SPARC: if (!be) return 0; filterId = k_SPARC; break;
219 case MACH_MACHINE_PPC: 301 case MACH_MACHINE_PPC:
220 case MACH_MACHINE_PPC64: if (!be) return 0; filterId = k_PPC; break; 302 case MACH_MACHINE_PPC64: if (!be) return 0; filterId = k_PPC; break;
303 case MACH_MACHINE_ARM64: if ( be) return 0; filterId = k_ARM64; break;
221 default: return 0; 304 default: return 0;
222 } 305 }
223 306
@@ -284,10 +367,15 @@ static BoolInt Parse_WAV(const Byte *buf, size_t size, CFilterMode *filterMode)
284 return False; 367 return False;
285} 368}
286 369
370
371/*
372 filterMode->Delta will be set as:
373 = delta value : [1, 256] : for k_Delta
374 = 0 for another filters (branch filters)
375*/
287static BoolInt ParseFile(const Byte *buf, size_t size, CFilterMode *filterMode) 376static BoolInt ParseFile(const Byte *buf, size_t size, CFilterMode *filterMode)
288{ 377{
289 filterMode->Id = 0; 378 filterMode->ClearFilterMode();
290 filterMode->Delta = 0;
291 379
292 if (Parse_EXE(buf, size, filterMode)) return True; 380 if (Parse_EXE(buf, size, filterMode)) return True;
293 if (Parse_ELF(buf, size, filterMode)) return True; 381 if (Parse_ELF(buf, size, filterMode)) return True;
@@ -315,18 +403,44 @@ struct CFilterMode2: public CFilterMode
315 else if (!m.Encrypted) 403 else if (!m.Encrypted)
316 return 1; 404 return 1;
317 405
318 if (Id < m.Id) return -1; 406 const UInt32 id1 = Id;
319 if (Id > m.Id) return 1; 407 const UInt32 id2 = m.Id;
408 /*
409 // we can change the order to place k_ARM64 files close to another exe files
410 if (id1 <= k_SPARC &&
411 id2 <= k_SPARC)
412 {
413 #define k_ARM64_FOR_SORT 0x3030901
414 if (id1 == k_ARM64) id1 = k_ARM64_FOR_SORT;
415 if (id2 == k_ARM64) id2 = k_ARM64_FOR_SORT;
416 }
417 */
418 if (id1 < id2) return -1;
419 if (id1 > id2) return 1;
320 420
321 if (Delta < m.Delta) return -1; 421 if (Delta < m.Delta) return -1;
322 if (Delta > m.Delta) return 1; 422 if (Delta > m.Delta) return 1;
323 423
424 if (Offset < m.Offset) return -1;
425 if (Offset > m.Offset) return 1;
426
427 /* we don't go here, because GetGroup()
428 and operator ==(const CFilterMode2 &m)
429 add only unique CFilterMode2:: { Id, Delta, Offset, Encrypted } items.
430 */
431 /*
432 if (GroupIndex < m.GroupIndex) return -1;
433 if (GroupIndex > m.GroupIndex) return 1;
434 */
324 return 0; 435 return 0;
325 } 436 }
326 437
327 bool operator ==(const CFilterMode2 &m) const 438 bool operator ==(const CFilterMode2 &m) const
328 { 439 {
329 return Id == m.Id && Delta == m.Delta && Encrypted == m.Encrypted; 440 return Id == m.Id
441 && Delta == m.Delta
442 && Offset == m.Offset
443 && Encrypted == m.Encrypted;
330 } 444 }
331}; 445};
332 446
@@ -367,6 +481,7 @@ static inline bool IsExeFilter(CMethodId m)
367{ 481{
368 switch (m) 482 switch (m)
369 { 483 {
484 case k_ARM64:
370 case k_BCJ: 485 case k_BCJ:
371 case k_BCJ2: 486 case k_BCJ2:
372 case k_ARM: 487 case k_ARM:
@@ -383,8 +498,9 @@ static unsigned Get_FilterGroup_for_Folder(
383 CRecordVector<CFilterMode2> &filters, const CFolderEx &f, bool extractFilter) 498 CRecordVector<CFilterMode2> &filters, const CFolderEx &f, bool extractFilter)
384{ 499{
385 CFilterMode2 m; 500 CFilterMode2 m;
386 m.Id = 0; 501 // m.Id = 0;
387 m.Delta = 0; 502 // m.Delta = 0;
503 // m.Offset = 0;
388 m.Encrypted = f.IsEncrypted(); 504 m.Encrypted = f.IsEncrypted();
389 505
390 if (extractFilter) 506 if (extractFilter)
@@ -405,6 +521,9 @@ static unsigned Get_FilterGroup_for_Folder(
405 if (m.Id == k_BCJ2) 521 if (m.Id == k_BCJ2)
406 m.Id = k_BCJ; 522 m.Id = k_BCJ;
407 m.SetDelta(); 523 m.SetDelta();
524 if (m.Id == k_ARM64)
525 if (coder.Props.Size() == 4)
526 m.Offset = GetUi32(coder.Props);
408 } 527 }
409 } 528 }
410 529
@@ -417,15 +536,15 @@ static unsigned Get_FilterGroup_for_Folder(
417static HRESULT WriteRange(IInStream *inStream, ISequentialOutStream *outStream, 536static HRESULT WriteRange(IInStream *inStream, ISequentialOutStream *outStream,
418 UInt64 position, UInt64 size, ICompressProgressInfo *progress) 537 UInt64 position, UInt64 size, ICompressProgressInfo *progress)
419{ 538{
420 RINOK(inStream->Seek((Int64)position, STREAM_SEEK_SET, 0)); 539 RINOK(InStream_SeekSet(inStream, position))
421 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; 540 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
422 CMyComPtr<CLimitedSequentialInStream> inStreamLimited(streamSpec); 541 CMyComPtr<ISequentialInStream> inStreamLimited(streamSpec);
423 streamSpec->SetStream(inStream); 542 streamSpec->SetStream(inStream);
424 streamSpec->Init(size); 543 streamSpec->Init(size);
425 544
426 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; 545 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
427 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; 546 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
428 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); 547 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress))
429 return (copyCoderSpec->TotalSize == size ? S_OK : E_FAIL); 548 return (copyCoderSpec->TotalSize == size ? S_OK : E_FAIL);
430} 549}
431 550
@@ -445,7 +564,7 @@ UString CUpdateItem::GetExtension() const
445} 564}
446*/ 565*/
447 566
448#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 567#define RINOZ(x) { const int _t_ = (x); if (_t_ != 0) return _t_; }
449 568
450#define RINOZ_COMP(a, b) RINOZ(MyCompare(a, b)) 569#define RINOZ_COMP(a, b) RINOZ(MyCompare(a, b))
451 570
@@ -630,7 +749,7 @@ struct CRefItem
630 unsigned NamePos; 749 unsigned NamePos;
631 unsigned ExtensionIndex; 750 unsigned ExtensionIndex;
632 751
633 CRefItem() {}; 752 CRefItem() {}
634 CRefItem(UInt32 index, const CUpdateItem &ui, bool sortByType): 753 CRefItem(UInt32 index, const CUpdateItem &ui, bool sortByType):
635 UpdateItem(&ui), 754 UpdateItem(&ui),
636 Index(index), 755 Index(index),
@@ -710,16 +829,16 @@ static int CompareUpdateItems(const CRefItem *p1, const CRefItem *p2, void *para
710 829
711 // bool sortByType = *(bool *)param; 830 // bool sortByType = *(bool *)param;
712 const CSortParam *sortParam = (const CSortParam *)param; 831 const CSortParam *sortParam = (const CSortParam *)param;
713 bool sortByType = sortParam->SortByType; 832 const bool sortByType = sortParam->SortByType;
714 if (sortByType) 833 if (sortByType)
715 { 834 {
716 RINOZ_COMP(a1.ExtensionIndex, a2.ExtensionIndex); 835 RINOZ_COMP(a1.ExtensionIndex, a2.ExtensionIndex)
717 RINOZ(CompareFileNames(u1.Name.Ptr(a1.ExtensionPos), u2.Name.Ptr(a2.ExtensionPos))); 836 RINOZ(CompareFileNames(u1.Name.Ptr(a1.ExtensionPos), u2.Name.Ptr(a2.ExtensionPos)))
718 RINOZ(CompareFileNames(u1.Name.Ptr(a1.NamePos), u2.Name.Ptr(a2.NamePos))); 837 RINOZ(CompareFileNames(u1.Name.Ptr(a1.NamePos), u2.Name.Ptr(a2.NamePos)))
719 if (!u1.MTimeDefined && u2.MTimeDefined) return 1; 838 if (!u1.MTimeDefined && u2.MTimeDefined) return 1;
720 if (u1.MTimeDefined && !u2.MTimeDefined) return -1; 839 if (u1.MTimeDefined && !u2.MTimeDefined) return -1;
721 if (u1.MTimeDefined && u2.MTimeDefined) RINOZ_COMP(u1.MTime, u2.MTime); 840 if (u1.MTimeDefined && u2.MTimeDefined) RINOZ_COMP(u1.MTime, u2.MTime)
722 RINOZ_COMP(u1.Size, u2.Size); 841 RINOZ_COMP(u1.Size, u2.Size)
723 } 842 }
724 /* 843 /*
725 int par1 = a1.UpdateItem->ParentFolderIndex; 844 int par1 = a1.UpdateItem->ParentFolderIndex;
@@ -765,9 +884,9 @@ static int CompareUpdateItems(const CRefItem *p1, const CRefItem *p2, void *para
765 } 884 }
766 */ 885 */
767 // RINOZ_COMP(a1.UpdateItem->ParentSortIndex, a2.UpdateItem->ParentSortIndex); 886 // RINOZ_COMP(a1.UpdateItem->ParentSortIndex, a2.UpdateItem->ParentSortIndex);
768 RINOK(CompareFileNames(u1.Name, u2.Name)); 887 RINOK(CompareFileNames(u1.Name, u2.Name))
769 RINOZ_COMP(a1.UpdateItem->IndexInClient, a2.UpdateItem->IndexInClient); 888 RINOZ_COMP(a1.UpdateItem->IndexInClient, a2.UpdateItem->IndexInClient)
770 RINOZ_COMP(a1.UpdateItem->IndexInArchive, a2.UpdateItem->IndexInArchive); 889 RINOZ_COMP(a1.UpdateItem->IndexInArchive, a2.UpdateItem->IndexInArchive)
771 return 0; 890 return 0;
772} 891}
773 892
@@ -778,7 +897,7 @@ struct CSolidGroup
778 CRecordVector<CFolderRepack> folderRefs; 897 CRecordVector<CFolderRepack> folderRefs;
779}; 898};
780 899
781static const char * const g_ExeExts[] = 900static const char * const g_Exe_Exts[] =
782{ 901{
783 "dll" 902 "dll"
784 , "exe" 903 , "exe"
@@ -787,14 +906,65 @@ static const char * const g_ExeExts[] =
787 , "sys" 906 , "sys"
788}; 907};
789 908
790static bool IsExeExt(const wchar_t *ext) 909static const char * const g_ExeUnix_Exts[] =
910{
911 "so"
912 , "dylib"
913};
914
915static bool IsExt_Exe(const wchar_t *ext)
791{ 916{
792 for (unsigned i = 0; i < ARRAY_SIZE(g_ExeExts); i++) 917 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Exe_Exts); i++)
793 if (StringsAreEqualNoCase_Ascii(ext, g_ExeExts[i])) 918 if (StringsAreEqualNoCase_Ascii(ext, g_Exe_Exts[i]))
794 return true; 919 return true;
795 return false; 920 return false;
796} 921}
797 922
923/*
924static bool IsExt_ExeUnix(const wchar_t *ext)
925{
926 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExeUnix_Exts); i++)
927 if (StringsAreEqualNoCase_Ascii(ext, g_ExeUnix_Exts[i]))
928 return true;
929 return false;
930}
931*/
932
933// we try to find "so" extension in such name: libstdc++.so.6.0.29
934static bool IsExt_ExeUnix_NumericAllowed(const UString &path)
935{
936 unsigned pos = path.Len();
937 unsigned dotPos = pos;
938 for (;;)
939 {
940 if (pos == 0)
941 return false;
942 const wchar_t c = path[--pos];
943 if (IS_PATH_SEPAR(c))
944 return false;
945 if (c == '.')
946 {
947 const unsigned num = (dotPos - pos) - 1;
948 if (num < 1)
949 return false;
950 const wchar_t *cur = path.Ptr(pos + 1);
951 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExeUnix_Exts); i++)
952 {
953 const char *ext = g_ExeUnix_Exts[i];
954 if (num == MyStringLen(ext))
955 if (IsString1PrefixedByString2_NoCase_Ascii(cur, ext))
956 return true;
957 }
958 const wchar_t *end;
959 ConvertStringToUInt32(cur, &end);
960 if ((size_t)(end - cur) != num)
961 return false;
962 dotPos = pos;
963 }
964 }
965}
966
967
798struct CAnalysis 968struct CAnalysis
799{ 969{
800 CMyComPtr<IArchiveUpdateCallbackFile> Callback; 970 CMyComPtr<IArchiveUpdateCallbackFile> Callback;
@@ -802,6 +972,8 @@ struct CAnalysis
802 972
803 bool ParseWav; 973 bool ParseWav;
804 bool ParseExe; 974 bool ParseExe;
975 bool ParseExeUnix;
976 bool ParseNoExt;
805 bool ParseAll; 977 bool ParseAll;
806 978
807 /* 979 /*
@@ -811,8 +983,10 @@ struct CAnalysis
811 */ 983 */
812 984
813 CAnalysis(): 985 CAnalysis():
814 ParseWav(true), 986 ParseWav(false),
815 ParseExe(false), 987 ParseExe(false),
988 ParseExeUnix(false),
989 ParseNoExt(false),
816 ParseAll(false) 990 ParseAll(false)
817 /* 991 /*
818 , Need_ATime(false) 992 , Need_ATime(false)
@@ -829,32 +1003,46 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo
829{ 1003{
830 filterMode.Id = 0; 1004 filterMode.Id = 0;
831 filterMode.Delta = 0; 1005 filterMode.Delta = 0;
1006 filterMode.Offset = 0;
832 1007
833 CFilterMode filterModeTemp = filterMode; 1008 CFilterMode filterModeTemp = filterMode;
834 1009
835 int slashPos = ui.Name.ReverseFind_PathSepar(); 1010 const int slashPos = ui.Name.ReverseFind_PathSepar();
836 int dotPos = ui.Name.ReverseFind_Dot(); 1011 const int dotPos = ui.Name.ReverseFind_Dot();
837 1012
838 // if (dotPos > slashPos) 1013 // if (dotPos > slashPos)
839 { 1014 {
840 bool needReadFile = ParseAll; 1015 bool needReadFile = ParseAll;
841 1016 /* if (Callback) is not supported by client,
1017 we still try to use file name extension to detect executable file */
842 bool probablyIsSameIsa = false; 1018 bool probablyIsSameIsa = false;
843 1019
844 if (!needReadFile || !Callback) 1020 if (!needReadFile || !Callback)
845 { 1021 {
846 const wchar_t *ext; 1022 const wchar_t *ext = NULL;
847 if (dotPos > slashPos) 1023 if (dotPos > slashPos)
848 ext = ui.Name.Ptr((unsigned)(dotPos + 1)); 1024 ext = ui.Name.Ptr((unsigned)(dotPos + 1));
849 else 1025 // 7-zip stores posix attributes in high 16 bits and sets (0x8000) flag
850 ext = ui.Name.RightPtr(0);
851
852 // p7zip uses the trick to store posix attributes in high 16 bits
853 if (ui.Attrib & 0x8000) 1026 if (ui.Attrib & 0x8000)
854 { 1027 {
855 unsigned st_mode = ui.Attrib >> 16; 1028 const unsigned st_mode = ui.Attrib >> 16;
856 // st_mode = 00111; 1029 /* note: executable ".so" can be without execute permission,
857 if ((st_mode & 00111) && (ui.Size >= 2048)) 1030 and symbolic link to such ".so" file is possible */
1031 // st_mode = 00111; // for debug
1032 /* in Linux we expect such permissions:
1033 0755 : for most executables
1034 0644 : for some ".so" files
1035 0777 : in WSL for all files.
1036 We can try to exclude some such 0777 cases from analysis,
1037 if there is non-executable extension.
1038 */
1039
1040 if ((st_mode & (
1041 MY_LIN_S_IXUSR |
1042 MY_LIN_S_IXGRP |
1043 MY_LIN_S_IXOTH)) != 0
1044 && MY_LIN_S_ISREG(st_mode)
1045 && (ui.Size >= (1u << 11)))
858 { 1046 {
859 #ifndef _WIN32 1047 #ifndef _WIN32
860 probablyIsSameIsa = true; 1048 probablyIsSameIsa = true;
@@ -863,36 +1051,45 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo
863 } 1051 }
864 } 1052 }
865 1053
866 if (IsExeExt(ext)) 1054 if (!needReadFile)
867 {
868 needReadFile = true;
869 #ifdef _WIN32
870 probablyIsSameIsa = true;
871 needReadFile = ParseExe;
872 #endif
873 }
874 else if (StringsAreEqualNoCase_Ascii(ext, "wav"))
875 {
876 needReadFile = ParseWav;
877 }
878 /*
879 else if (!needReadFile && ParseUnixExt)
880 { 1055 {
881 if (StringsAreEqualNoCase_Ascii(ext, "so") 1056 if (!ext)
882 || StringsAreEqualNoCase_Ascii(ext, "")) 1057 needReadFile = ParseNoExt;
883 1058 else
884 needReadFile = true; 1059 {
1060 bool isUnixExt = false;
1061 if (ParseExeUnix)
1062 isUnixExt = IsExt_ExeUnix_NumericAllowed(ui.Name);
1063 if (isUnixExt)
1064 {
1065 needReadFile = true;
1066 #ifndef _WIN32
1067 probablyIsSameIsa = true;
1068 #endif
1069 }
1070 else if (IsExt_Exe(ext))
1071 {
1072 needReadFile = ParseExe;
1073 #ifdef _WIN32
1074 probablyIsSameIsa = true;
1075 #endif
1076 }
1077 else if (StringsAreEqualNoCase_Ascii(ext, "wav"))
1078 {
1079 if (!needReadFile)
1080 needReadFile = ParseWav;
1081 }
1082 }
885 } 1083 }
886 */
887 } 1084 }
888 1085
889 if (needReadFile && Callback) 1086 if (needReadFile)
890 { 1087 {
891 if (Buffer.Size() != kAnalysisBufSize) 1088 BoolInt parseRes = false;
892 { 1089 if (Callback)
893 Buffer.Alloc(kAnalysisBufSize);
894 }
895 { 1090 {
1091 if (Buffer.Size() != kAnalysisBufSize)
1092 Buffer.Alloc(kAnalysisBufSize);
896 CMyComPtr<ISequentialInStream> stream; 1093 CMyComPtr<ISequentialInStream> stream;
897 HRESULT result = Callback->GetStream2(index, &stream, NUpdateNotifyOp::kAnalyze); 1094 HRESULT result = Callback->GetStream2(index, &stream, NUpdateNotifyOp::kAnalyze);
898 if (result == S_OK && stream) 1095 if (result == S_OK && stream)
@@ -908,40 +1105,60 @@ HRESULT CAnalysis::GetFilterGroup(UInt32 index, const CUpdateItem &ui, CFilterMo
908 ATime_Defined = true; 1105 ATime_Defined = true;
909 } 1106 }
910 */ 1107 */
911
912 size_t size = kAnalysisBufSize; 1108 size_t size = kAnalysisBufSize;
913 result = ReadStream(stream, Buffer, &size); 1109 result = ReadStream(stream, Buffer, &size);
914 stream.Release(); 1110 stream.Release();
915 // RINOK(Callback->SetOperationResult2(index, NUpdate::NOperationResult::kOK)); 1111 // RINOK(Callback->SetOperationResult2(index, NUpdate::NOperationResult::kOK));
916 if (result == S_OK) 1112 if (result == S_OK)
917 { 1113 {
918 BoolInt parseRes = ParseFile(Buffer, size, &filterModeTemp); 1114 parseRes = ParseFile(Buffer, size, &filterModeTemp);
919 if (parseRes && filterModeTemp.Delta == 0) 1115 }
920 { 1116 }
921 filterModeTemp.SetDelta(); 1117 } // Callback
922 if (filterModeTemp.Delta != 0 && filterModeTemp.Id != k_Delta) 1118 else if (probablyIsSameIsa)
923 { 1119 {
924 if (ui.Size % filterModeTemp.Delta != 0) 1120 #ifdef MY_CPU_X86_OR_AMD64
925 { 1121 filterModeTemp.Id = k_X86;
926 parseRes = false; 1122 #endif
927 } 1123 #ifdef MY_CPU_ARM64
928 } 1124 filterModeTemp.Id = k_ARM64;
929 } 1125 #endif
930 if (!parseRes) 1126 parseRes = true;
1127 }
1128
1129 if (parseRes
1130 && filterModeTemp.Id != k_Delta
1131 && filterModeTemp.Delta == 0)
1132 {
1133 /* ParseFile() sets (filterModeTemp.Delta == 0) for all
1134 methods except of k_Delta. */
1135 // it's not k_Delta
1136 // So we call SetDelta() to set Delta
1137 filterModeTemp.SetDelta();
1138 if (filterModeTemp.Delta > 1)
1139 {
1140 /* If file Size is not aligned, then branch filter
1141 will not work for next file in solid block.
1142 Maybe we should allow filter for non-aligned-size file in non-solid archives ?
1143 */
1144 if (ui.Size % filterModeTemp.Delta != 0)
1145 parseRes = false;
1146 // windows exe files are not aligned for 4 KiB.
1147 /*
1148 else if (filterModeTemp.Id == k_ARM64 && filterModeTemp.Offset != 0)
1149 {
1150 if (ui.Size % (1 << 12) != 0)
931 { 1151 {
932 filterModeTemp.Id = 0; 1152 // If Size is not aligned for 4 KiB, then Offset will not work for next file in solid block.
933 filterModeTemp.Delta = 0; 1153 // so we place such file in group with (Offset==0).
1154 filterModeTemp.Offset = 0;
934 } 1155 }
935 } 1156 }
1157 */
936 } 1158 }
937 } 1159 }
938 } 1160 if (!parseRes)
939 else if ((needReadFile && !Callback) || probablyIsSameIsa) 1161 filterModeTemp.ClearFilterMode();
940 {
941 #ifdef MY_CPU_X86_OR_AMD64
942 if (probablyIsSameIsa)
943 filterModeTemp.Id = k_X86;
944 #endif
945 } 1162 }
946 } 1163 }
947 1164
@@ -1010,7 +1227,7 @@ static HRESULT AddBcj2Methods(CCompressionMethodMode &mode)
1010 mode.Methods.Add(m); 1227 mode.Methods.Add(m);
1011 mode.Methods.Add(m); 1228 mode.Methods.Add(m);
1012 1229
1013 RINOK(AddBondForFilter(mode)); 1230 RINOK(AddBondForFilter(mode))
1014 CBond2 bond; 1231 CBond2 bond;
1015 bond.OutCoder = 0; 1232 bond.OutCoder = 0;
1016 bond.InCoder = methodIndex; bond.OutStream = 1; mode.Bonds.Add(bond); 1233 bond.InCoder = methodIndex; bond.OutStream = 1; mode.Bonds.Add(bond);
@@ -1024,7 +1241,7 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode,
1024 if (mode.Filter_was_Inserted) 1241 if (mode.Filter_was_Inserted)
1025 { 1242 {
1026 const CMethodFull &m = mode.Methods[0]; 1243 const CMethodFull &m = mode.Methods[0];
1027 CMethodId id = m.Id; 1244 const CMethodId id = m.Id;
1028 if (id == k_BCJ2) 1245 if (id == k_BCJ2)
1029 return AddBcj2Methods(mode); 1246 return AddBcj2Methods(mode);
1030 if (!m.IsSimpleCoder()) 1247 if (!m.IsSimpleCoder())
@@ -1039,7 +1256,7 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode,
1039 CMethodFull &m = mode.Methods.InsertNew(0); 1256 CMethodFull &m = mode.Methods.InsertNew(0);
1040 1257
1041 { 1258 {
1042 FOR_VECTOR(k, mode.Bonds) 1259 FOR_VECTOR (k, mode.Bonds)
1043 { 1260 {
1044 CBond2 &bond = mode.Bonds[k]; 1261 CBond2 &bond = mode.Bonds[k];
1045 bond.InCoder++; 1262 bond.InCoder++;
@@ -1059,23 +1276,32 @@ static HRESULT MakeExeMethod(CCompressionMethodMode &mode,
1059 GetMethodFull(filterMode.Id, 1, m); 1276 GetMethodFull(filterMode.Id, 1, m);
1060 if (filterMode.Id == k_Delta) 1277 if (filterMode.Id == k_Delta)
1061 m.AddProp32(NCoderPropID::kDefaultProp, filterMode.Delta); 1278 m.AddProp32(NCoderPropID::kDefaultProp, filterMode.Delta);
1279 else if (filterMode.Id == k_ARM64)
1280 {
1281 // if (filterMode.Offset != 0)
1282 m.AddProp32(
1283 NCoderPropID::kDefaultProp,
1284 // NCoderPropID::kBranchOffset,
1285 filterMode.Offset);
1286 }
1062 res = AddFilterBond(mode); 1287 res = AddFilterBond(mode);
1063 1288
1064 int alignBits = -1; 1289 int alignBits = -1;
1065 if (filterMode.Id == k_Delta || filterMode.Delta != 0)
1066 {
1067 if (filterMode.Delta == 1) alignBits = 0;
1068 else if (filterMode.Delta == 2) alignBits = 1;
1069 else if (filterMode.Delta == 4) alignBits = 2;
1070 else if (filterMode.Delta == 8) alignBits = 3;
1071 else if (filterMode.Delta == 16) alignBits = 4;
1072 }
1073 else
1074 { 1290 {
1075 // alignBits = GetAlignForFilterMethod(filterMode.Id); 1291 const UInt32 delta = filterMode.Delta;
1292 if (delta == 0 || delta > 16)
1293 {
1294 // if (delta == 0) alignBits = GetAlignForFilterMethod(filterMode.Id);
1295 }
1296 else if ((delta & ((1 << 4) - 1)) == 0) alignBits = 4;
1297 else if ((delta & ((1 << 3) - 1)) == 0) alignBits = 3;
1298 else if ((delta & ((1 << 2) - 1)) == 0) alignBits = 2;
1299 else if ((delta & ((1 << 1) - 1)) == 0) alignBits = 1;
1300 // else alignBits = 0;
1301 /* alignBits=0 is default mode for lzma/lzma2.
1302 So we don't set alignBits=0 here. */
1076 } 1303 }
1077 1304 if (res == S_OK && alignBits > 0)
1078 if (res == S_OK && alignBits >= 0)
1079 { 1305 {
1080 unsigned nextCoder = 1; 1306 unsigned nextCoder = 1;
1081 if (!mode.Bonds.IsEmpty()) 1307 if (!mode.Bonds.IsEmpty())
@@ -1135,13 +1361,13 @@ static void UpdateItem_To_FileItem(const CUpdateItem &ui,
1135 1361
1136 1362
1137 1363
1138class CRepackInStreamWithSizes: 1364Z7_CLASS_IMP_COM_2(
1139 public ISequentialInStream, 1365 CRepackInStreamWithSizes
1140 public ICompressGetSubStreamSize, 1366 , ISequentialInStream
1141 public CMyUnknownImp 1367 , ICompressGetSubStreamSize
1142{ 1368)
1143 CMyComPtr<ISequentialInStream> _stream; 1369 CMyComPtr<ISequentialInStream> _stream;
1144 // UInt64 _size; 1370 UInt64 _size;
1145 const CBoolVector *_extractStatuses; 1371 const CBoolVector *_extractStatuses;
1146 UInt32 _startIndex; 1372 UInt32 _startIndex;
1147public: 1373public:
@@ -1151,37 +1377,28 @@ public:
1151 { 1377 {
1152 _startIndex = startIndex; 1378 _startIndex = startIndex;
1153 _extractStatuses = extractStatuses; 1379 _extractStatuses = extractStatuses;
1154 // _size = 0; 1380 _size = 0;
1155 _stream = stream; 1381 _stream = stream;
1156 } 1382 }
1157 // UInt64 GetSize() const { return _size; } 1383 UInt64 GetSize() const { return _size; }
1158
1159 MY_UNKNOWN_IMP2(ISequentialInStream, ICompressGetSubStreamSize)
1160
1161 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
1162
1163 STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value);
1164}; 1384};
1165 1385
1166STDMETHODIMP CRepackInStreamWithSizes::Read(void *data, UInt32 size, UInt32 *processedSize) 1386Z7_COM7F_IMF(CRepackInStreamWithSizes::Read(void *data, UInt32 size, UInt32 *processedSize))
1167{ 1387{
1168 return _stream->Read(data, size, processedSize);
1169 /*
1170 UInt32 realProcessedSize; 1388 UInt32 realProcessedSize;
1171 HRESULT result = _stream->Read(data, size, &realProcessedSize); 1389 const HRESULT result = _stream->Read(data, size, &realProcessedSize);
1172 _size += realProcessedSize; 1390 _size += realProcessedSize;
1173 if (processedSize) 1391 if (processedSize)
1174 *processedSize = realProcessedSize; 1392 *processedSize = realProcessedSize;
1175 return result; 1393 return result;
1176 */
1177} 1394}
1178 1395
1179STDMETHODIMP CRepackInStreamWithSizes::GetSubStreamSize(UInt64 subStream, UInt64 *value) 1396Z7_COM7F_IMF(CRepackInStreamWithSizes::GetSubStreamSize(UInt64 subStream, UInt64 *value))
1180{ 1397{
1181 *value = 0; 1398 *value = 0;
1182 if (subStream >= _extractStatuses->Size()) 1399 if (subStream >= _extractStatuses->Size())
1183 return S_FALSE; // E_FAIL; 1400 return S_FALSE; // E_FAIL;
1184 unsigned index = (unsigned)subStream; 1401 const unsigned index = (unsigned)subStream;
1185 if ((*_extractStatuses)[index]) 1402 if ((*_extractStatuses)[index])
1186 { 1403 {
1187 const CFileItem &fi = _db->Files[_startIndex + index]; 1404 const CFileItem &fi = _db->Files[_startIndex + index];
@@ -1212,7 +1429,7 @@ protected:
1212public: 1429public:
1213 const CDbEx *_db; 1430 const CDbEx *_db;
1214 CMyComPtr<IArchiveUpdateCallbackFile> _opCallback; 1431 CMyComPtr<IArchiveUpdateCallbackFile> _opCallback;
1215 CMyComPtr<IArchiveExtractCallbackMessage> _extractCallback; 1432 CMyComPtr<IArchiveExtractCallbackMessage2> _extractCallback;
1216 1433
1217 HRESULT Init(UInt32 startIndex, const CBoolVector *extractStatuses); 1434 HRESULT Init(UInt32 startIndex, const CBoolVector *extractStatuses);
1218 HRESULT CheckFinishedState() const { return (_currentIndex == _extractStatuses->Size()) ? S_OK: E_FAIL; } 1435 HRESULT CheckFinishedState() const { return (_currentIndex == _extractStatuses->Size()) ? S_OK: E_FAIL; }
@@ -1241,7 +1458,7 @@ HRESULT CRepackStreamBase::OpenFile()
1241 NEventIndexType::kInArcIndex, arcIndex, 1458 NEventIndexType::kInArcIndex, arcIndex,
1242 _needWrite ? 1459 _needWrite ?
1243 NUpdateNotifyOp::kRepack : 1460 NUpdateNotifyOp::kRepack :
1244 NUpdateNotifyOp::kSkip)); 1461 NUpdateNotifyOp::kSkip))
1245 } 1462 }
1246 1463
1247 _crc = CRC_INIT_VAL; 1464 _crc = CRC_INIT_VAL;
@@ -1267,7 +1484,7 @@ HRESULT CRepackStreamBase::CloseFile()
1267 { 1484 {
1268 RINOK(_extractCallback->ReportExtractResult( 1485 RINOK(_extractCallback->ReportExtractResult(
1269 NEventIndexType::kInArcIndex, arcIndex, 1486 NEventIndexType::kInArcIndex, arcIndex,
1270 NExtract::NOperationResult::kCRCError)); 1487 NExtract::NOperationResult::kCRCError))
1271 } 1488 }
1272 // return S_FALSE; 1489 // return S_FALSE;
1273 return k_My_HRESULT_CRC_ERROR; 1490 return k_My_HRESULT_CRC_ERROR;
@@ -1277,30 +1494,28 @@ HRESULT CRepackStreamBase::ProcessEmptyFiles()
1277{ 1494{
1278 while (_currentIndex < _extractStatuses->Size() && _db->Files[_startIndex + _currentIndex].Size == 0) 1495 while (_currentIndex < _extractStatuses->Size() && _db->Files[_startIndex + _currentIndex].Size == 0)
1279 { 1496 {
1280 RINOK(OpenFile()); 1497 RINOK(OpenFile())
1281 RINOK(CloseFile()); 1498 RINOK(CloseFile())
1282 } 1499 }
1283 return S_OK; 1500 return S_OK;
1284} 1501}
1285 1502
1286 1503
1287 1504
1288#ifndef _7ZIP_ST 1505#ifndef Z7_ST
1289 1506
1290class CFolderOutStream2: 1507class CFolderOutStream2 Z7_final:
1291 public CRepackStreamBase, 1508 public CRepackStreamBase,
1292 public ISequentialOutStream, 1509 public ISequentialOutStream,
1293 public CMyUnknownImp 1510 public CMyUnknownImp
1294{ 1511{
1512 Z7_COM_UNKNOWN_IMP_0
1513 Z7_IFACE_COM7_IMP(ISequentialOutStream)
1295public: 1514public:
1296 CMyComPtr<ISequentialOutStream> _stream; 1515 CMyComPtr<ISequentialOutStream> _stream;
1297
1298 MY_UNKNOWN_IMP
1299
1300 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
1301}; 1516};
1302 1517
1303STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *processedSize) 1518Z7_COM7F_IMF(CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *processedSize))
1304{ 1519{
1305 if (processedSize) 1520 if (processedSize)
1306 *processedSize = 0; 1521 *processedSize = 0;
@@ -1322,22 +1537,22 @@ STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *pro
1322 _rem -= cur; 1537 _rem -= cur;
1323 if (_rem == 0) 1538 if (_rem == 0)
1324 { 1539 {
1325 RINOK(CloseFile()); 1540 RINOK(CloseFile())
1326 RINOK(ProcessEmptyFiles()); 1541 RINOK(ProcessEmptyFiles())
1327 } 1542 }
1328 RINOK(result); 1543 RINOK(result)
1329 if (cur == 0) 1544 if (cur == 0)
1330 break; 1545 break;
1331 continue; 1546 continue;
1332 } 1547 }
1333 1548
1334 RINOK(ProcessEmptyFiles()); 1549 RINOK(ProcessEmptyFiles())
1335 if (_currentIndex == _extractStatuses->Size()) 1550 if (_currentIndex == _extractStatuses->Size())
1336 { 1551 {
1337 // we don't support write cut here 1552 // we don't support write cut here
1338 return E_FAIL; 1553 return E_FAIL;
1339 } 1554 }
1340 RINOK(OpenFile()); 1555 RINOK(OpenFile())
1341 } 1556 }
1342 1557
1343 return S_OK; 1558 return S_OK;
@@ -1349,18 +1564,19 @@ STDMETHODIMP CFolderOutStream2::Write(const void *data, UInt32 size, UInt32 *pro
1349 1564
1350static const UInt32 kTempBufSize = 1 << 16; 1565static const UInt32 kTempBufSize = 1 << 16;
1351 1566
1352class CFolderInStream2: 1567class CFolderInStream2 Z7_final:
1353 public CRepackStreamBase, 1568 public CRepackStreamBase,
1354 public ISequentialInStream, 1569 public ISequentialInStream,
1355 public CMyUnknownImp 1570 public CMyUnknownImp
1356{ 1571{
1572 Z7_COM_UNKNOWN_IMP_0
1573 Z7_IFACE_COM7_IMP(ISequentialInStream)
1574
1357 Byte *_buf; 1575 Byte *_buf;
1358public: 1576public:
1359 CMyComPtr<ISequentialInStream> _inStream; 1577 CMyComPtr<ISequentialInStream> _inStream;
1360 HRESULT Result; 1578 HRESULT Result;
1361 1579
1362 MY_UNKNOWN_IMP
1363
1364 CFolderInStream2(): 1580 CFolderInStream2():
1365 Result(S_OK) 1581 Result(S_OK)
1366 { 1582 {
@@ -1373,10 +1589,9 @@ public:
1373 } 1589 }
1374 1590
1375 void Init() { Result = S_OK; } 1591 void Init() { Result = S_OK; }
1376 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
1377}; 1592};
1378 1593
1379STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSize) 1594Z7_COM7F_IMF(CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSize))
1380{ 1595{
1381 if (processedSize) 1596 if (processedSize)
1382 *processedSize = 0; 1597 *processedSize = 0;
@@ -1397,7 +1612,7 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi
1397 cur = kTempBufSize; 1612 cur = kTempBufSize;
1398 } 1613 }
1399 1614
1400 HRESULT result = _inStream->Read(buf, cur, &cur); 1615 const HRESULT result = _inStream->Read(buf, cur, &cur);
1401 _crc = CrcUpdate(_crc, buf, cur); 1616 _crc = CrcUpdate(_crc, buf, cur);
1402 _rem -= cur; 1617 _rem -= cur;
1403 1618
@@ -1414,11 +1629,11 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi
1414 1629
1415 if (_rem == 0) 1630 if (_rem == 0)
1416 { 1631 {
1417 RINOK(CloseFile()); 1632 RINOK(CloseFile())
1418 RINOK(ProcessEmptyFiles()); 1633 RINOK(ProcessEmptyFiles())
1419 } 1634 }
1420 1635
1421 RINOK(result); 1636 RINOK(result)
1422 1637
1423 if (cur == 0) 1638 if (cur == 0)
1424 return E_FAIL; 1639 return E_FAIL;
@@ -1426,20 +1641,20 @@ STDMETHODIMP CFolderInStream2::Read(void *data, UInt32 size, UInt32 *processedSi
1426 continue; 1641 continue;
1427 } 1642 }
1428 1643
1429 RINOK(ProcessEmptyFiles()); 1644 RINOK(ProcessEmptyFiles())
1430 if (_currentIndex == _extractStatuses->Size()) 1645 if (_currentIndex == _extractStatuses->Size())
1431 { 1646 {
1432 return S_OK; 1647 return S_OK;
1433 } 1648 }
1434 RINOK(OpenFile()); 1649 RINOK(OpenFile())
1435 } 1650 }
1436 1651
1437 return S_OK; 1652 return S_OK;
1438} 1653}
1439 1654
1440 1655
1441class CThreadDecoder 1656class CThreadDecoder Z7_final
1442 #ifndef _7ZIP_ST 1657 #ifndef Z7_ST
1443 : public CVirtThread 1658 : public CVirtThread
1444 #endif 1659 #endif
1445{ 1660{
@@ -1449,7 +1664,7 @@ public:
1449 CThreadDecoder(bool multiThreadMixer): 1664 CThreadDecoder(bool multiThreadMixer):
1450 Decoder(multiThreadMixer) 1665 Decoder(multiThreadMixer)
1451 { 1666 {
1452 #ifndef _7ZIP_ST 1667 #ifndef Z7_ST
1453 if (multiThreadMixer) 1668 if (multiThreadMixer)
1454 { 1669 {
1455 MtMode = false; 1670 MtMode = false;
@@ -1463,7 +1678,7 @@ public:
1463 // send_UnpackSize = false; 1678 // send_UnpackSize = false;
1464 } 1679 }
1465 1680
1466 #ifndef _7ZIP_ST 1681 #ifndef Z7_ST
1467 1682
1468 bool dataAfterEnd_Error; 1683 bool dataAfterEnd_Error;
1469 HRESULT Result; 1684 HRESULT Result;
@@ -1479,31 +1694,39 @@ public:
1479 // bool send_UnpackSize; 1694 // bool send_UnpackSize;
1480 // UInt64 UnpackSize; 1695 // UInt64 UnpackSize;
1481 1696
1482 #ifndef _NO_CRYPTO 1697 #ifndef Z7_NO_CRYPTO
1483 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 1698 CMyComPtr<ICryptoGetTextPassword> getTextPassword;
1484 #endif 1699 #endif
1485 1700
1486 DECL_EXTERNAL_CODECS_LOC_VARS2; 1701 DECL_EXTERNAL_CODECS_LOC_VARS_DECL
1487 1702
1488 #ifndef _7ZIP_ST 1703 #ifndef Z7_ST
1489 bool MtMode; 1704 bool MtMode;
1490 UInt32 NumThreads; 1705 UInt32 NumThreads;
1491 #endif 1706 #endif
1492 1707
1493 1708
1494 ~CThreadDecoder() { CVirtThread::WaitThreadFinish(); } 1709 ~CThreadDecoder() Z7_DESTRUCTOR_override
1495 virtual void Execute(); 1710 {
1711 /* WaitThreadFinish() will be called in ~CVirtThread().
1712 But we need WaitThreadFinish() call before
1713 destructors of this class members.
1714 */
1715 CVirtThread::WaitThreadFinish();
1716 }
1717private:
1718 virtual void Execute() Z7_override;
1496 1719
1497 #endif 1720 #endif
1498}; 1721};
1499 1722
1500#ifndef _7ZIP_ST 1723#ifndef Z7_ST
1501 1724
1502void CThreadDecoder::Execute() 1725void CThreadDecoder::Execute()
1503{ 1726{
1504 try 1727 try
1505 { 1728 {
1506 #ifndef _NO_CRYPTO 1729 #ifndef Z7_NO_CRYPTO
1507 bool isEncrypted = false; 1730 bool isEncrypted = false;
1508 bool passwordIsDefined = false; 1731 bool passwordIsDefined = false;
1509 UString password; 1732 UString password;
@@ -1526,8 +1749,8 @@ void CThreadDecoder::Execute()
1526 NULL // *inStreamMainRes 1749 NULL // *inStreamMainRes
1527 , dataAfterEnd_Error 1750 , dataAfterEnd_Error
1528 1751
1529 _7Z_DECODER_CRYPRO_VARS 1752 Z7_7Z_DECODER_CRYPRO_VARS
1530 #ifndef _7ZIP_ST 1753 #ifndef Z7_ST
1531 , MtMode, NumThreads, 1754 , MtMode, NumThreads,
1532 0 // MemUsage 1755 0 // MemUsage
1533 #endif 1756 #endif
@@ -1548,20 +1771,17 @@ void CThreadDecoder::Execute()
1548 1771
1549#endif 1772#endif
1550 1773
1551#ifndef _NO_CRYPTO 1774#ifndef Z7_NO_CRYPTO
1552 1775
1553class CCryptoGetTextPassword: 1776Z7_CLASS_IMP_NOQIB_1(
1554 public ICryptoGetTextPassword, 1777 CCryptoGetTextPassword
1555 public CMyUnknownImp 1778 , ICryptoGetTextPassword
1556{ 1779)
1557public: 1780public:
1558 UString Password; 1781 UString Password;
1559
1560 MY_UNKNOWN_IMP
1561 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
1562}; 1782};
1563 1783
1564STDMETHODIMP CCryptoGetTextPassword::CryptoGetTextPassword(BSTR *password) 1784Z7_COM7F_IMF(CCryptoGetTextPassword::CryptoGetTextPassword(BSTR *password))
1565{ 1785{
1566 return StringToBstr(Password, password); 1786 return StringToBstr(Password, password);
1567} 1787}
@@ -1585,58 +1805,70 @@ HRESULT Update(
1585 DECL_EXTERNAL_CODECS_LOC_VARS 1805 DECL_EXTERNAL_CODECS_LOC_VARS
1586 IInStream *inStream, 1806 IInStream *inStream,
1587 const CDbEx *db, 1807 const CDbEx *db,
1588 const CObjectVector<CUpdateItem> &updateItems, 1808 CObjectVector<CUpdateItem> &updateItems,
1589 // const CObjectVector<CTreeFolder> &treeFolders, 1809 // const CObjectVector<CTreeFolder> &treeFolders,
1590 // const CUniqBlocks &secureBlocks, 1810 // const CUniqBlocks &secureBlocks,
1591 COutArchive &archive,
1592 CArchiveDatabaseOut &newDatabase,
1593 ISequentialOutStream *seqOutStream, 1811 ISequentialOutStream *seqOutStream,
1594 IArchiveUpdateCallback *updateCallback, 1812 IArchiveUpdateCallback *updateCallback,
1595 const CUpdateOptions &options 1813 const CUpdateOptions &options)
1596 #ifndef _NO_CRYPTO
1597 , ICryptoGetTextPassword *getDecoderPassword
1598 #endif
1599 )
1600{ 1814{
1601 UInt64 numSolidFiles = options.NumSolidFiles; 1815 UInt64 numSolidFiles = options.NumSolidFiles;
1602 if (numSolidFiles == 0) 1816 if (numSolidFiles == 0)
1603 numSolidFiles = 1; 1817 numSolidFiles = 1;
1604 1818
1605 CMyComPtr<IArchiveUpdateCallbackFile> opCallback; 1819 Z7_DECL_CMyComPtr_QI_FROM(
1606 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); 1820 IArchiveUpdateCallbackFile,
1821 opCallback, updateCallback)
1607 1822
1608 CMyComPtr<IArchiveExtractCallbackMessage> extractCallback; 1823 Z7_DECL_CMyComPtr_QI_FROM(
1609 updateCallback->QueryInterface(IID_IArchiveExtractCallbackMessage, (void **)&extractCallback); 1824 IArchiveExtractCallbackMessage2,
1825 extractCallback, updateCallback)
1610 1826
1611 /* 1827 /*
1612 CMyComPtr<IArchiveUpdateCallbackArcProp> reportArcProp; 1828 Z7_DECL_CMyComPtr_QI_FROM(
1613 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); 1829 IArchiveUpdateCallbackArcProp,
1830 reportArcProp, updateCallback)
1614 */ 1831 */
1615 1832
1616 // size_t totalSecureDataSize = (size_t)secureBlocks.GetTotalSizeInBytes(); 1833 // size_t totalSecureDataSize = (size_t)secureBlocks.GetTotalSizeInBytes();
1617 1834
1618 /* 1835 CMyComPtr<IStreamSetRestriction> v_StreamSetRestriction;
1619 CMyComPtr<IOutStream> outStream;
1620 RINOK(seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStream));
1621 if (!outStream)
1622 return E_NOTIMPL;
1623 */
1624
1625 UInt64 startBlockSize = db ? db->ArcInfo.StartPosition: 0;
1626 if (startBlockSize > 0 && !options.RemoveSfxBlock)
1627 { 1836 {
1628 RINOK(WriteRange(inStream, seqOutStream, 0, startBlockSize, NULL)); 1837 Z7_DECL_CMyComPtr_QI_FROM(
1838 IOutStream,
1839 outStream, seqOutStream)
1840 if (!outStream)
1841 return E_NOTIMPL;
1842 const UInt64 sfxBlockSize = (db && !options.RemoveSfxBlock) ?
1843 db->ArcInfo.StartPosition: 0;
1844 seqOutStream->QueryInterface(IID_IStreamSetRestriction, (void **)&v_StreamSetRestriction);
1845 if (v_StreamSetRestriction)
1846 {
1847 UInt64 offset = 0;
1848 RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &offset))
1849 RINOK(v_StreamSetRestriction->SetRestriction(
1850 outStream ? offset + sfxBlockSize : 0,
1851 outStream ? offset + sfxBlockSize + k_StartHeadersRewriteSize : 0))
1852 }
1853 outStream.Release();
1854 if (sfxBlockSize != 0)
1855 {
1856 RINOK(WriteRange(inStream, seqOutStream, 0, sfxBlockSize, NULL))
1857 }
1629 } 1858 }
1630 1859
1631 CIntArr fileIndexToUpdateIndexMap; 1860 CIntArr fileIndexToUpdateIndexMap;
1632 UInt64 complexity = 0; 1861 UInt64 complexity = 0;
1633 UInt64 inSizeForReduce2 = 0; 1862 UInt64 inSizeForReduce2 = 0;
1863
1864 #ifndef Z7_NO_CRYPTO
1634 bool needEncryptedRepack = false; 1865 bool needEncryptedRepack = false;
1866 #endif
1635 1867
1636 CRecordVector<CFilterMode2> filters; 1868 CRecordVector<CFilterMode2> filters;
1637 CObjectVector<CSolidGroup> groups; 1869 CObjectVector<CSolidGroup> groups;
1638 1870
1639 #ifndef _7ZIP_ST 1871 #ifndef Z7_ST
1640 bool thereAreRepacks = false; 1872 bool thereAreRepacks = false;
1641 #endif 1873 #endif
1642 1874
@@ -1646,11 +1878,15 @@ HRESULT Update(
1646 const CCompressionMethodMode &method = *options.Method; 1878 const CCompressionMethodMode &method = *options.Method;
1647 1879
1648 FOR_VECTOR (i, method.Methods) 1880 FOR_VECTOR (i, method.Methods)
1881 {
1882 /* IsFilterMethod() knows only built-in codecs
1883 FIXME: we should check IsFilter status for external filters too */
1649 if (IsFilterMethod(method.Methods[i].Id)) 1884 if (IsFilterMethod(method.Methods[i].Id))
1650 { 1885 {
1651 useFilters = false; 1886 useFilters = false;
1652 break; 1887 break;
1653 } 1888 }
1889 }
1654 } 1890 }
1655 1891
1656 if (db) 1892 if (db)
@@ -1672,7 +1908,7 @@ HRESULT Update(
1672 { 1908 {
1673 CNum indexInFolder = 0; 1909 CNum indexInFolder = 0;
1674 CNum numCopyItems = 0; 1910 CNum numCopyItems = 0;
1675 CNum numUnpackStreams = db->NumUnpackStreamsVector[i]; 1911 const CNum numUnpackStreams = db->NumUnpackStreamsVector[i];
1676 UInt64 repackSize = 0; 1912 UInt64 repackSize = 0;
1677 1913
1678 for (CNum fi = db->FolderStartFileIndex[i]; indexInFolder < numUnpackStreams; fi++) 1914 for (CNum fi = db->FolderStartFileIndex[i]; indexInFolder < numUnpackStreams; fi++)
@@ -1684,7 +1920,7 @@ HRESULT Update(
1684 if (file.HasStream) 1920 if (file.HasStream)
1685 { 1921 {
1686 indexInFolder++; 1922 indexInFolder++;
1687 int updateIndex = fileIndexToUpdateIndexMap[fi]; 1923 const int updateIndex = fileIndexToUpdateIndexMap[fi];
1688 if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData) 1924 if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData)
1689 { 1925 {
1690 numCopyItems++; 1926 numCopyItems++;
@@ -1702,11 +1938,13 @@ HRESULT Update(
1702 CFolderEx f; 1938 CFolderEx f;
1703 db->ParseFolderEx(i, f); 1939 db->ParseFolderEx(i, f);
1704 1940
1941 #ifndef Z7_NO_CRYPTO
1705 const bool isEncrypted = f.IsEncrypted(); 1942 const bool isEncrypted = f.IsEncrypted();
1943 #endif
1706 const bool needCopy = (numCopyItems == numUnpackStreams); 1944 const bool needCopy = (numCopyItems == numUnpackStreams);
1707 const bool extractFilter = (useFilters || needCopy); 1945 const bool extractFilter = (useFilters || needCopy);
1708 1946
1709 unsigned groupIndex = Get_FilterGroup_for_Folder(filters, f, extractFilter); 1947 const unsigned groupIndex = Get_FilterGroup_for_Folder(filters, f, extractFilter);
1710 1948
1711 while (groupIndex >= groups.Size()) 1949 while (groupIndex >= groups.Size())
1712 groups.AddNew(); 1950 groups.AddNew();
@@ -1717,14 +1955,16 @@ HRESULT Update(
1717 complexity += db->GetFolderFullPackSize(i); 1955 complexity += db->GetFolderFullPackSize(i);
1718 else 1956 else
1719 { 1957 {
1720 #ifndef _7ZIP_ST 1958 #ifndef Z7_ST
1721 thereAreRepacks = true; 1959 thereAreRepacks = true;
1722 #endif 1960 #endif
1723 complexity += repackSize; 1961 complexity += repackSize;
1724 if (inSizeForReduce2 < repackSize) 1962 if (inSizeForReduce2 < repackSize)
1725 inSizeForReduce2 = repackSize; 1963 inSizeForReduce2 = repackSize;
1964 #ifndef Z7_NO_CRYPTO
1726 if (isEncrypted) 1965 if (isEncrypted)
1727 needEncryptedRepack = true; 1966 needEncryptedRepack = true;
1967 #endif
1728 } 1968 }
1729 } 1969 }
1730 } 1970 }
@@ -1749,13 +1989,13 @@ HRESULT Update(
1749 if (inSizeForReduce < inSizeForReduce2) 1989 if (inSizeForReduce < inSizeForReduce2)
1750 inSizeForReduce = inSizeForReduce2; 1990 inSizeForReduce = inSizeForReduce2;
1751 1991
1752 RINOK(updateCallback->SetTotal(complexity)); 1992 RINOK(updateCallback->SetTotal(complexity))
1753 1993
1754 CLocalProgress *lps = new CLocalProgress; 1994 CLocalProgress *lps = new CLocalProgress;
1755 CMyComPtr<ICompressProgressInfo> progress = lps; 1995 CMyComPtr<ICompressProgressInfo> progress = lps;
1756 lps->Init(updateCallback, true); 1996 lps->Init(updateCallback, true);
1757 1997
1758 #ifndef _7ZIP_ST 1998 #ifndef Z7_ST
1759 1999
1760 CStreamBinder sb; 2000 CStreamBinder sb;
1761 /* 2001 /*
@@ -1769,13 +2009,13 @@ HRESULT Update(
1769 2009
1770 CThreadDecoder threadDecoder(options.MultiThreadMixer); 2010 CThreadDecoder threadDecoder(options.MultiThreadMixer);
1771 2011
1772 #ifndef _7ZIP_ST 2012 #ifndef Z7_ST
1773 if (options.MultiThreadMixer && thereAreRepacks) 2013 if (options.MultiThreadMixer && thereAreRepacks)
1774 { 2014 {
1775 #ifdef EXTERNAL_CODECS 2015 #ifdef Z7_EXTERNAL_CODECS
1776 threadDecoder.__externalCodecs = __externalCodecs; 2016 threadDecoder._externalCodecs = _externalCodecs;
1777 #endif 2017 #endif
1778 WRes wres = threadDecoder.Create(); 2018 const WRes wres = threadDecoder.Create();
1779 if (wres != 0) 2019 if (wres != 0)
1780 return HRESULT_FROM_WIN32(wres); 2020 return HRESULT_FROM_WIN32(wres);
1781 } 2021 }
@@ -1784,22 +2024,23 @@ HRESULT Update(
1784 { 2024 {
1785 CAnalysis analysis; 2025 CAnalysis analysis;
1786 // analysis.Need_ATime = options.Need_ATime; 2026 // analysis.Need_ATime = options.Need_ATime;
1787 if (options.AnalysisLevel == 0) 2027 int analysisLevel = options.AnalysisLevel;
1788 { 2028 // (analysisLevel < 0) means default level (5)
1789 analysis.ParseWav = false; 2029 if (analysisLevel < 0)
1790 analysis.ParseExe = false; 2030 analysisLevel = 5;
1791 analysis.ParseAll = false; 2031 if (analysisLevel != 0)
1792 }
1793 else
1794 { 2032 {
1795 analysis.Callback = opCallback; 2033 analysis.Callback = opCallback;
1796 if (options.AnalysisLevel > 0) 2034 analysis.ParseWav = true;
2035 if (analysisLevel >= 5)
1797 { 2036 {
1798 analysis.ParseWav = true; 2037 analysis.ParseExe = true;
1799 if (options.AnalysisLevel >= 7) 2038 analysis.ParseExeUnix = true;
2039 // analysis.ParseNoExt = true;
2040 if (analysisLevel >= 7)
1800 { 2041 {
1801 analysis.ParseExe = true; 2042 analysis.ParseNoExt = true;
1802 if (options.AnalysisLevel >= 9) 2043 if (analysisLevel >= 9)
1803 analysis.ParseAll = true; 2044 analysis.ParseAll = true;
1804 } 2045 }
1805 } 2046 }
@@ -1819,7 +2060,7 @@ HRESULT Update(
1819 if (useFilters) 2060 if (useFilters)
1820 { 2061 {
1821 // analysis.ATime_Defined = false; 2062 // analysis.ATime_Defined = false;
1822 RINOK(analysis.GetFilterGroup(i, ui, fm)); 2063 RINOK(analysis.GetFilterGroup(i, ui, fm))
1823 /* 2064 /*
1824 if (analysis.ATime_Defined) 2065 if (analysis.ATime_Defined)
1825 { 2066 {
@@ -1830,7 +2071,7 @@ HRESULT Update(
1830 } 2071 }
1831 fm.Encrypted = method.PasswordIsDefined; 2072 fm.Encrypted = method.PasswordIsDefined;
1832 2073
1833 unsigned groupIndex = GetGroup(filters, fm); 2074 const unsigned groupIndex = GetGroup(filters, fm);
1834 while (groupIndex >= groups.Size()) 2075 while (groupIndex >= groups.Size())
1835 groups.AddNew(); 2076 groups.AddNew();
1836 groups[groupIndex].Indices.Add(i); 2077 groups[groupIndex].Indices.Add(i);
@@ -1838,7 +2079,7 @@ HRESULT Update(
1838 } 2079 }
1839 2080
1840 2081
1841 #ifndef _NO_CRYPTO 2082 #ifndef Z7_NO_CRYPTO
1842 2083
1843 CCryptoGetTextPassword *getPasswordSpec = NULL; 2084 CCryptoGetTextPassword *getPasswordSpec = NULL;
1844 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 2085 CMyComPtr<ICryptoGetTextPassword> getTextPassword;
@@ -1847,7 +2088,7 @@ HRESULT Update(
1847 getPasswordSpec = new CCryptoGetTextPassword; 2088 getPasswordSpec = new CCryptoGetTextPassword;
1848 getTextPassword = getPasswordSpec; 2089 getTextPassword = getPasswordSpec;
1849 2090
1850 #ifndef _7ZIP_ST 2091 #ifndef Z7_ST
1851 threadDecoder.getTextPassword = getPasswordSpec; 2092 threadDecoder.getTextPassword = getPasswordSpec;
1852 #endif 2093 #endif
1853 2094
@@ -1855,10 +2096,13 @@ HRESULT Update(
1855 getPasswordSpec->Password = options.Method->Password; 2096 getPasswordSpec->Password = options.Method->Password;
1856 else 2097 else
1857 { 2098 {
2099 Z7_DECL_CMyComPtr_QI_FROM(
2100 ICryptoGetTextPassword,
2101 getDecoderPassword, updateCallback)
1858 if (!getDecoderPassword) 2102 if (!getDecoderPassword)
1859 return E_NOTIMPL; 2103 return E_NOTIMPL;
1860 CMyComBSTR password; 2104 CMyComBSTR password;
1861 RINOK(getDecoderPassword->CryptoGetTextPassword(&password)); 2105 RINOK(getDecoderPassword->CryptoGetTextPassword(&password))
1862 if (password) 2106 if (password)
1863 getPasswordSpec->Password = password; 2107 getPasswordSpec->Password = password;
1864 } 2108 }
@@ -1866,11 +2110,12 @@ HRESULT Update(
1866 2110
1867 #endif 2111 #endif
1868 2112
1869
1870 // ---------- Compress ---------- 2113 // ---------- Compress ----------
1871 2114
1872 RINOK(archive.Create(seqOutStream, false)); 2115 COutArchive archive;
1873 RINOK(archive.SkipPrefixArchiveHeader()); 2116 CArchiveDatabaseOut newDatabase;
2117
2118 RINOK(archive.Create_and_WriteStartPrefix(seqOutStream))
1874 2119
1875 /* 2120 /*
1876 CIntVector treeFolderToArcIndex; 2121 CIntVector treeFolderToArcIndex;
@@ -1973,7 +2218,6 @@ HRESULT Update(
1973 2218
1974 { 2219 {
1975 // ---------- Sort Filters ---------- 2220 // ---------- Sort Filters ----------
1976
1977 FOR_VECTOR (i, filters) 2221 FOR_VECTOR (i, filters)
1978 { 2222 {
1979 filters[i].GroupIndex = i; 2223 filters[i].GroupIndex = i;
@@ -1987,22 +2231,22 @@ HRESULT Update(
1987 2231
1988 CCompressionMethodMode method = *options.Method; 2232 CCompressionMethodMode method = *options.Method;
1989 { 2233 {
1990 HRESULT res = MakeExeMethod(method, filterMode, 2234 const HRESULT res = MakeExeMethod(method, filterMode,
1991 #ifdef _7ZIP_ST 2235 #ifdef Z7_ST
1992 false 2236 false
1993 #else 2237 #else
1994 options.MaxFilter && options.MultiThreadMixer 2238 options.MaxFilter && options.MultiThreadMixer
1995 #endif 2239 #endif
1996 ); 2240 );
1997 2241
1998 RINOK(res); 2242 RINOK(res)
1999 } 2243 }
2000 2244
2001 if (filterMode.Encrypted) 2245 if (filterMode.Encrypted)
2002 { 2246 {
2003 if (!method.PasswordIsDefined) 2247 if (!method.PasswordIsDefined)
2004 { 2248 {
2005 #ifndef _NO_CRYPTO 2249 #ifndef Z7_NO_CRYPTO
2006 if (getPasswordSpec) 2250 if (getPasswordSpec)
2007 method.Password = getPasswordSpec->Password; 2251 method.Password = getPasswordSpec->Password;
2008 #endif 2252 #endif
@@ -2021,13 +2265,13 @@ HRESULT Update(
2021 2265
2022 const CSolidGroup &group = groups[filterMode.GroupIndex]; 2266 const CSolidGroup &group = groups[filterMode.GroupIndex];
2023 2267
2024 FOR_VECTOR(folderRefIndex, group.folderRefs) 2268 FOR_VECTOR (folderRefIndex, group.folderRefs)
2025 { 2269 {
2026 const CFolderRepack &rep = group.folderRefs[folderRefIndex]; 2270 const CFolderRepack &rep = group.folderRefs[folderRefIndex];
2027 2271
2028 unsigned folderIndex = rep.FolderIndex; 2272 const unsigned folderIndex = rep.FolderIndex;
2029 2273
2030 CNum numUnpackStreams = db->NumUnpackStreamsVector[folderIndex]; 2274 const CNum numUnpackStreams = db->NumUnpackStreamsVector[folderIndex];
2031 2275
2032 if (rep.NumCopyFiles == numUnpackStreams) 2276 if (rep.NumCopyFiles == numUnpackStreams)
2033 { 2277 {
@@ -2035,7 +2279,7 @@ HRESULT Update(
2035 { 2279 {
2036 RINOK(opCallback->ReportOperation( 2280 RINOK(opCallback->ReportOperation(
2037 NEventIndexType::kBlockIndex, (UInt32)folderIndex, 2281 NEventIndexType::kBlockIndex, (UInt32)folderIndex,
2038 NUpdateNotifyOp::kReplicate)); 2282 NUpdateNotifyOp::kReplicate))
2039 2283
2040 // ---------- Copy old solid block ---------- 2284 // ---------- Copy old solid block ----------
2041 { 2285 {
@@ -2047,21 +2291,27 @@ HRESULT Update(
2047 indexInFolder++; 2291 indexInFolder++;
2048 RINOK(opCallback->ReportOperation( 2292 RINOK(opCallback->ReportOperation(
2049 NEventIndexType::kInArcIndex, (UInt32)fi, 2293 NEventIndexType::kInArcIndex, (UInt32)fi,
2050 NUpdateNotifyOp::kReplicate)); 2294 NUpdateNotifyOp::kReplicate))
2051 } 2295 }
2052 } 2296 }
2053 } 2297 }
2054 } 2298 }
2055 2299
2056 UInt64 packSize = db->GetFolderFullPackSize(folderIndex); 2300 const UInt64 packSize = db->GetFolderFullPackSize(folderIndex);
2057 RINOK(WriteRange(inStream, archive.SeqStream, 2301 RINOK(WriteRange(inStream, archive.SeqStream,
2058 db->GetFolderStreamPos(folderIndex, 0), packSize, progress)); 2302 db->GetFolderStreamPos(folderIndex, 0), packSize, progress))
2059 lps->ProgressOffset += packSize; 2303 lps->ProgressOffset += packSize;
2060 2304
2305 const unsigned folderIndex_New = newDatabase.Folders.Size();
2061 CFolder &folder = newDatabase.Folders.AddNew(); 2306 CFolder &folder = newDatabase.Folders.AddNew();
2307 // v23.01: we copy FolderCrc, if FolderCrc was used
2308 if (db->FolderCRCs.ValidAndDefined(folderIndex))
2309 newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New,
2310 true, db->FolderCRCs.Vals[folderIndex]);
2311
2062 db->ParseFolderInfo(folderIndex, folder); 2312 db->ParseFolderInfo(folderIndex, folder);
2063 CNum startIndex = db->FoStartPackStreamIndex[folderIndex]; 2313 const CNum startIndex = db->FoStartPackStreamIndex[folderIndex];
2064 FOR_VECTOR(j, folder.PackStreams) 2314 FOR_VECTOR (j, folder.PackStreams)
2065 { 2315 {
2066 newDatabase.PackSizes.Add(db->GetStreamPackSize(startIndex + j)); 2316 newDatabase.PackSizes.Add(db->GetStreamPackSize(startIndex + j));
2067 // newDatabase.PackCRCsDefined.Add(db.PackCRCsDefined[startIndex + j]); 2317 // newDatabase.PackCRCsDefined.Add(db.PackCRCsDefined[startIndex + j]);
@@ -2069,7 +2319,7 @@ HRESULT Update(
2069 } 2319 }
2070 2320
2071 size_t indexStart = db->FoToCoderUnpackSizes[folderIndex]; 2321 size_t indexStart = db->FoToCoderUnpackSizes[folderIndex];
2072 size_t indexEnd = db->FoToCoderUnpackSizes[folderIndex + 1]; 2322 const size_t indexEnd = db->FoToCoderUnpackSizes[folderIndex + 1];
2073 for (; indexStart < indexEnd; indexStart++) 2323 for (; indexStart < indexEnd; indexStart++)
2074 newDatabase.CoderUnpackSizes.Add(db->CoderUnpackSizes[indexStart]); 2324 newDatabase.CoderUnpackSizes.Add(db->CoderUnpackSizes[indexStart]);
2075 } 2325 }
@@ -2108,7 +2358,7 @@ HRESULT Update(
2108 if (file.HasStream) 2358 if (file.HasStream)
2109 { 2359 {
2110 indexInFolder++; 2360 indexInFolder++;
2111 int updateIndex = fileIndexToUpdateIndexMap[fi]; 2361 const int updateIndex = fileIndexToUpdateIndexMap[fi];
2112 if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData) 2362 if (updateIndex >= 0 && !updateItems[(unsigned)updateIndex].NewData)
2113 needExtract = true; 2363 needExtract = true;
2114 // decodeSize += file.Size; 2364 // decodeSize += file.Size;
@@ -2130,7 +2380,6 @@ HRESULT Update(
2130 unsigned startPackIndex = newDatabase.PackSizes.Size(); 2380 unsigned startPackIndex = newDatabase.PackSizes.Size();
2131 UInt64 curUnpackSize; 2381 UInt64 curUnpackSize;
2132 { 2382 {
2133
2134 CMyComPtr<ISequentialInStream> sbInStream; 2383 CMyComPtr<ISequentialInStream> sbInStream;
2135 CRepackStreamBase *repackBase; 2384 CRepackStreamBase *repackBase;
2136 CFolderInStream2 *FosSpec2 = NULL; 2385 CFolderInStream2 *FosSpec2 = NULL;
@@ -2138,13 +2387,13 @@ HRESULT Update(
2138 CRepackInStreamWithSizes *inStreamSizeCountSpec = new CRepackInStreamWithSizes; 2387 CRepackInStreamWithSizes *inStreamSizeCountSpec = new CRepackInStreamWithSizes;
2139 CMyComPtr<ISequentialInStream> inStreamSizeCount = inStreamSizeCountSpec; 2388 CMyComPtr<ISequentialInStream> inStreamSizeCount = inStreamSizeCountSpec;
2140 { 2389 {
2141 #ifndef _7ZIP_ST 2390 #ifndef Z7_ST
2142 if (options.MultiThreadMixer) 2391 if (options.MultiThreadMixer)
2143 { 2392 {
2144 repackBase = threadDecoder.FosSpec; 2393 repackBase = threadDecoder.FosSpec;
2145 CMyComPtr<ISequentialOutStream> sbOutStream; 2394 CMyComPtr<ISequentialOutStream> sbOutStream;
2146 sb.CreateStreams2(sbInStream, sbOutStream); 2395 sb.CreateStreams2(sbInStream, sbOutStream);
2147 RINOK(sb.Create_ReInit()); 2396 RINOK(sb.Create_ReInit())
2148 2397
2149 threadDecoder.FosSpec->_stream = sbOutStream; 2398 threadDecoder.FosSpec->_stream = sbOutStream;
2150 2399
@@ -2164,7 +2413,7 @@ HRESULT Update(
2164 sbInStream = FosSpec2; 2413 sbInStream = FosSpec2;
2165 repackBase = FosSpec2; 2414 repackBase = FosSpec2;
2166 2415
2167 #ifndef _NO_CRYPTO 2416 #ifndef Z7_NO_CRYPTO
2168 bool isEncrypted = false; 2417 bool isEncrypted = false;
2169 bool passwordIsDefined = false; 2418 bool passwordIsDefined = false;
2170 UString password; 2419 UString password;
@@ -2173,7 +2422,7 @@ HRESULT Update(
2173 CMyComPtr<ISequentialInStream> decodedStream; 2422 CMyComPtr<ISequentialInStream> decodedStream;
2174 bool dataAfterEnd_Error = false; 2423 bool dataAfterEnd_Error = false;
2175 2424
2176 HRESULT res = threadDecoder.Decoder.Decode( 2425 const HRESULT res = threadDecoder.Decoder.Decode(
2177 EXTERNAL_CODECS_LOC_VARS 2426 EXTERNAL_CODECS_LOC_VARS
2178 inStream, 2427 inStream,
2179 db->ArcInfo.DataStartPosition, // db->GetFolderStreamPos(folderIndex, 0);, 2428 db->ArcInfo.DataStartPosition, // db->GetFolderStreamPos(folderIndex, 0);,
@@ -2187,15 +2436,15 @@ HRESULT Update(
2187 &decodedStream 2436 &decodedStream
2188 , dataAfterEnd_Error 2437 , dataAfterEnd_Error
2189 2438
2190 _7Z_DECODER_CRYPRO_VARS 2439 Z7_7Z_DECODER_CRYPRO_VARS
2191 #ifndef _7ZIP_ST 2440 #ifndef Z7_ST
2192 , false // mtMode 2441 , false // mtMode
2193 , 1 // numThreads 2442 , 1 // numThreads
2194 , 0 // memUsage 2443 , 0 // memUsage
2195 #endif 2444 #endif
2196 ); 2445 );
2197 2446
2198 RINOK(res); 2447 RINOK(res)
2199 if (!decodedStream) 2448 if (!decodedStream)
2200 return E_FAIL; 2449 return E_FAIL;
2201 2450
@@ -2207,12 +2456,12 @@ HRESULT Update(
2207 repackBase->_extractCallback = extractCallback; 2456 repackBase->_extractCallback = extractCallback;
2208 2457
2209 UInt32 startIndex = db->FolderStartFileIndex[folderIndex]; 2458 UInt32 startIndex = db->FolderStartFileIndex[folderIndex];
2210 RINOK(repackBase->Init(startIndex, &extractStatuses)); 2459 RINOK(repackBase->Init(startIndex, &extractStatuses))
2211 2460
2212 inStreamSizeCountSpec->_db = db; 2461 inStreamSizeCountSpec->_db = db;
2213 inStreamSizeCountSpec->Init(sbInStream, startIndex, &extractStatuses); 2462 inStreamSizeCountSpec->Init(sbInStream, startIndex, &extractStatuses);
2214 2463
2215 #ifndef _7ZIP_ST 2464 #ifndef Z7_ST
2216 if (options.MultiThreadMixer) 2465 if (options.MultiThreadMixer)
2217 { 2466 {
2218 WRes wres = threadDecoder.Start(); 2467 WRes wres = threadDecoder.Start();
@@ -2222,20 +2471,29 @@ HRESULT Update(
2222 #endif 2471 #endif
2223 } 2472 }
2224 2473
2225 curUnpackSize = sizeToEncode; 2474 // curUnpackSize = sizeToEncode;
2226 2475
2227 HRESULT encodeRes = encoder.Encode( 2476 HRESULT encodeRes = encoder.Encode1(
2228 EXTERNAL_CODECS_LOC_VARS 2477 EXTERNAL_CODECS_LOC_VARS
2229 inStreamSizeCount, 2478 inStreamSizeCount,
2230 // NULL, 2479 // NULL,
2231 &inSizeForReduce, 2480 &inSizeForReduce,
2232 newDatabase.Folders.AddNew(), newDatabase.CoderUnpackSizes, curUnpackSize, 2481 sizeToEncode, // expectedDataSize
2482 newDatabase.Folders.AddNew(),
2483 // newDatabase.CoderUnpackSizes, curUnpackSize,
2233 archive.SeqStream, newDatabase.PackSizes, progress); 2484 archive.SeqStream, newDatabase.PackSizes, progress);
2234 2485
2235 if (encodeRes == k_My_HRESULT_CRC_ERROR) 2486 if (encodeRes == k_My_HRESULT_CRC_ERROR)
2236 return E_FAIL; 2487 return E_FAIL;
2237 2488
2238 #ifndef _7ZIP_ST 2489 curUnpackSize = inStreamSizeCountSpec->GetSize();
2490
2491 if (encodeRes == S_OK)
2492 {
2493 encoder.Encode_Post(curUnpackSize, newDatabase.CoderUnpackSizes);
2494 }
2495
2496 #ifndef Z7_ST
2239 if (options.MultiThreadMixer) 2497 if (options.MultiThreadMixer)
2240 { 2498 {
2241 // 16.00: hang was fixed : for case if decoding was not finished. 2499 // 16.00: hang was fixed : for case if decoding was not finished.
@@ -2244,12 +2502,12 @@ HRESULT Update(
2244 sbInStream.Release(); 2502 sbInStream.Release();
2245 2503
2246 { 2504 {
2247 WRes wres = threadDecoder.WaitExecuteFinish(); 2505 const WRes wres = threadDecoder.WaitExecuteFinish();
2248 if (wres != 0) 2506 if (wres != 0)
2249 return HRESULT_FROM_WIN32(wres); 2507 return HRESULT_FROM_WIN32(wres);
2250 } 2508 }
2251 2509
2252 HRESULT decodeRes = threadDecoder.Result; 2510 const HRESULT decodeRes = threadDecoder.Result;
2253 // if (res == k_My_HRESULT_CRC_ERROR) 2511 // if (res == k_My_HRESULT_CRC_ERROR)
2254 if (decodeRes == S_FALSE || threadDecoder.dataAfterEnd_Error) 2512 if (decodeRes == S_FALSE || threadDecoder.dataAfterEnd_Error)
2255 { 2513 {
@@ -2260,12 +2518,12 @@ HRESULT Update(
2260 // NEventIndexType::kBlockIndex, (UInt32)folderIndex, 2518 // NEventIndexType::kBlockIndex, (UInt32)folderIndex,
2261 (decodeRes != S_OK ? 2519 (decodeRes != S_OK ?
2262 NExtract::NOperationResult::kDataError : 2520 NExtract::NOperationResult::kDataError :
2263 NExtract::NOperationResult::kDataAfterEnd))); 2521 NExtract::NOperationResult::kDataAfterEnd)))
2264 } 2522 }
2265 if (decodeRes != S_OK) 2523 if (decodeRes != S_OK)
2266 return E_FAIL; 2524 return E_FAIL;
2267 } 2525 }
2268 RINOK(decodeRes); 2526 RINOK(decodeRes)
2269 if (encodeRes == S_OK) 2527 if (encodeRes == S_OK)
2270 if (sb.ProcessedSize != sizeToEncode) 2528 if (sb.ProcessedSize != sizeToEncode)
2271 encodeRes = E_FAIL; 2529 encodeRes = E_FAIL;
@@ -2279,15 +2537,15 @@ HRESULT Update(
2279 { 2537 {
2280 RINOK(extractCallback->ReportExtractResult( 2538 RINOK(extractCallback->ReportExtractResult(
2281 NEventIndexType::kBlockIndex, (UInt32)folderIndex, 2539 NEventIndexType::kBlockIndex, (UInt32)folderIndex,
2282 NExtract::NOperationResult::kDataError)); 2540 NExtract::NOperationResult::kDataError))
2283 } 2541 }
2284 return E_FAIL; 2542 return E_FAIL;
2285 } 2543 }
2286 RINOK(FosSpec2->Result); 2544 RINOK(FosSpec2->Result)
2287 } 2545 }
2288 2546
2289 RINOK(encodeRes); 2547 RINOK(encodeRes)
2290 RINOK(repackBase->CheckFinishedState()); 2548 RINOK(repackBase->CheckFinishedState())
2291 2549
2292 if (curUnpackSize != sizeToEncode) 2550 if (curUnpackSize != sizeToEncode)
2293 return E_FAIL; 2551 return E_FAIL;
@@ -2306,7 +2564,7 @@ HRESULT Update(
2306 if (db->Files[fi].HasStream) 2564 if (db->Files[fi].HasStream)
2307 { 2565 {
2308 indexInFolder++; 2566 indexInFolder++;
2309 int updateIndex = fileIndexToUpdateIndexMap[fi]; 2567 const int updateIndex = fileIndexToUpdateIndexMap[fi];
2310 if (updateIndex >= 0) 2568 if (updateIndex >= 0)
2311 { 2569 {
2312 const CUpdateItem &ui = updateItems[(unsigned)updateIndex]; 2570 const CUpdateItem &ui = updateItems[(unsigned)updateIndex];
@@ -2343,13 +2601,13 @@ HRESULT Update(
2343 2601
2344 // ---------- Compress files to new solid blocks ---------- 2602 // ---------- Compress files to new solid blocks ----------
2345 2603
2346 unsigned numFiles = group.Indices.Size(); 2604 const unsigned numFiles = group.Indices.Size();
2347 if (numFiles == 0) 2605 if (numFiles == 0)
2348 continue; 2606 continue;
2349 CRecordVector<CRefItem> refItems; 2607 CRecordVector<CRefItem> refItems;
2350 refItems.ClearAndSetSize(numFiles); 2608 refItems.ClearAndSetSize(numFiles);
2351 // bool sortByType = (options.UseTypeSorting && isSoid); // numSolidFiles > 1 2609 // bool sortByType = (options.UseTypeSorting && isSoid); // numSolidFiles > 1
2352 bool sortByType = options.UseTypeSorting; 2610 const bool sortByType = options.UseTypeSorting;
2353 2611
2354 unsigned i; 2612 unsigned i;
2355 2613
@@ -2365,7 +2623,7 @@ HRESULT Update(
2365 2623
2366 for (i = 0; i < numFiles; i++) 2624 for (i = 0; i < numFiles; i++)
2367 { 2625 {
2368 UInt32 index = refItems[i].Index; 2626 const UInt32 index = refItems[i].Index;
2369 indices[i] = index; 2627 indices[i] = index;
2370 /* 2628 /*
2371 const CUpdateItem &ui = updateItems[index]; 2629 const CUpdateItem &ui = updateItems[index];
@@ -2395,8 +2653,8 @@ HRESULT Update(
2395 break; 2653 break;
2396 if (options.SolidExtension) 2654 if (options.SolidExtension)
2397 { 2655 {
2398 int slashPos = ui.Name.ReverseFind_PathSepar(); 2656 const int slashPos = ui.Name.ReverseFind_PathSepar();
2399 int dotPos = ui.Name.ReverseFind_Dot(); 2657 const int dotPos = ui.Name.ReverseFind_Dot();
2400 const wchar_t *ext = ui.Name.Ptr(dotPos <= slashPos ? ui.Name.Len() : (unsigned)(dotPos + 1)); 2658 const wchar_t *ext = ui.Name.Ptr(dotPos <= slashPos ? ui.Name.Len() : (unsigned)(dotPos + 1));
2401 if (numSubFiles == 0) 2659 if (numSubFiles == 0)
2402 prevExtension = ext; 2660 prevExtension = ext;
@@ -2408,7 +2666,7 @@ HRESULT Update(
2408 if (numSubFiles < 1) 2666 if (numSubFiles < 1)
2409 numSubFiles = 1; 2667 numSubFiles = 1;
2410 2668
2411 RINOK(lps->SetCur()); 2669 RINOK(lps->SetCur())
2412 2670
2413 /* 2671 /*
2414 const unsigned folderIndex = newDatabase.NumUnpackStreamsVector.Size(); 2672 const unsigned folderIndex = newDatabase.NumUnpackStreamsVector.Size();
@@ -2431,31 +2689,45 @@ HRESULT Update(
2431 inStreamSpec->Need_ATime = options.Need_ATime; 2689 inStreamSpec->Need_ATime = options.Need_ATime;
2432 inStreamSpec->Need_MTime = options.Need_MTime; 2690 inStreamSpec->Need_MTime = options.Need_MTime;
2433 inStreamSpec->Need_Attrib = options.Need_Attrib; 2691 inStreamSpec->Need_Attrib = options.Need_Attrib;
2692 // inStreamSpec->Need_Crc = options.Need_Crc;
2434 2693
2435 inStreamSpec->Init(updateCallback, &indices[i], numSubFiles); 2694 inStreamSpec->Init(updateCallback, &indices[i], numSubFiles);
2436 2695
2437 unsigned startPackIndex = newDatabase.PackSizes.Size(); 2696 unsigned startPackIndex = newDatabase.PackSizes.Size();
2438 UInt64 curFolderUnpackSize = totalSize; 2697 // UInt64 curFolderUnpackSize = totalSize;
2439 // curFolderUnpackSize = (UInt64)(Int64)-1; // for debug 2698 // curFolderUnpackSize = (UInt64)(Int64)-1; // for debug
2699 const UInt64 expectedDataSize = totalSize;
2700
2701 // const unsigned folderIndex_New = newDatabase.Folders.Size();
2440 2702
2441 RINOK(encoder.Encode( 2703 RINOK(encoder.Encode1(
2442 EXTERNAL_CODECS_LOC_VARS 2704 EXTERNAL_CODECS_LOC_VARS
2443 solidInStream, 2705 solidInStream,
2444 // NULL, 2706 // NULL,
2445 &inSizeForReduce, 2707 &inSizeForReduce,
2446 newDatabase.Folders.AddNew(), newDatabase.CoderUnpackSizes, curFolderUnpackSize, 2708 expectedDataSize, // expected size
2447 archive.SeqStream, newDatabase.PackSizes, progress)); 2709 newDatabase.Folders.AddNew(),
2710 // newDatabase.CoderUnpackSizes, curFolderUnpackSize,
2711 archive.SeqStream, newDatabase.PackSizes, progress))
2448 2712
2449 if (!inStreamSpec->WasFinished()) 2713 if (!inStreamSpec->WasFinished())
2450 return E_FAIL; 2714 return E_FAIL;
2451 2715
2716 /*
2717 if (inStreamSpec->Need_FolderCrc)
2718 newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New,
2719 true, inStreamSpec->GetFolderCrc());
2720 */
2721
2722 const UInt64 curFolderUnpackSize = inStreamSpec->Get_TotalSize_for_Coder();
2723 encoder.Encode_Post(curFolderUnpackSize, newDatabase.CoderUnpackSizes);
2724
2452 UInt64 packSize = 0; 2725 UInt64 packSize = 0;
2453 // const UInt32 numStreams = newDatabase.PackSizes.Size() - startPackIndex; 2726 // const UInt32 numStreams = newDatabase.PackSizes.Size() - startPackIndex;
2454 for (; startPackIndex < newDatabase.PackSizes.Size(); startPackIndex++) 2727 for (; startPackIndex < newDatabase.PackSizes.Size(); startPackIndex++)
2455 packSize += newDatabase.PackSizes[startPackIndex]; 2728 packSize += newDatabase.PackSizes[startPackIndex];
2456 lps->OutSize += packSize; 2729 lps->OutSize += packSize;
2457 2730
2458 lps->InSize += curFolderUnpackSize;
2459 // for () 2731 // for ()
2460 // newDatabase.PackCRCsDefined.Add(false); 2732 // newDatabase.PackCRCsDefined.Add(false);
2461 // newDatabase.PackCRCs.Add(0); 2733 // newDatabase.PackCRCs.Add(0);
@@ -2496,14 +2768,15 @@ HRESULT Update(
2496 // name += ".locked"; // for debug 2768 // name += ".locked"; // for debug
2497 } 2769 }
2498 2770
2771 // if (inStreamSpec->Need_Crc)
2499 file.Crc = inStreamSpec->CRCs[subIndex]; 2772 file.Crc = inStreamSpec->CRCs[subIndex];
2500 file.Size = inStreamSpec->Sizes[subIndex]; 2773 file.Size = inStreamSpec->Sizes[subIndex];
2501 2774
2502 procSize += file.Size; 2775 procSize += file.Size;
2503 // if (file.Size >= 0) // test purposes 2776 // if (file.Size >= 0) // for debug: test purposes
2504 if (file.Size != 0) 2777 if (file.Size != 0)
2505 { 2778 {
2506 file.CrcDefined = true; 2779 file.CrcDefined = true; // inStreamSpec->Need_Crc;
2507 file.HasStream = true; 2780 file.HasStream = true;
2508 numUnpackStreams++; 2781 numUnpackStreams++;
2509 } 2782 }
@@ -2549,9 +2822,66 @@ HRESULT Update(
2549 newDatabase.AddFile(file, file2, name); 2822 newDatabase.AddFile(file, file2, name);
2550 } 2823 }
2551 2824
2825 /*
2826 // for debug:
2827 // we can write crc to folders area, if folder contains only one file
2828 if (numUnpackStreams == 1 && numSubFiles == 1)
2829 {
2830 const CFileItem &file = newDatabase.Files.Back();
2831 if (file.CrcDefined)
2832 newDatabase.FolderUnpackCRCs.SetItem(folderIndex_New, true, file.Crc);
2833 }
2834 */
2835
2836 /*
2552 // it's optional check to ensure that sizes are correct 2837 // it's optional check to ensure that sizes are correct
2553 if (procSize != curFolderUnpackSize) 2838 if (inStreamSpec->TotalSize_for_Coder != curFolderUnpackSize)
2554 return E_FAIL; 2839 return E_FAIL;
2840 */
2841 // if (inStreamSpec->AlignLog == 0)
2842 {
2843 if (procSize != curFolderUnpackSize)
2844 return E_FAIL;
2845 }
2846 // else
2847 {
2848 /*
2849 {
2850 const CFolder &old = newDatabase.Folders.Back();
2851 CFolder &folder = newDatabase.Folders.AddNew();
2852 {
2853 const unsigned numBonds = old.Bonds.Size();
2854 folder.Bonds.SetSize(numBonds + 1);
2855 for (unsigned k = 0; k < numBonds; k++)
2856 folder.Bonds[k] = old.Bonds[k];
2857 CBond &bond = folder.Bonds[numBonds];
2858 bond.PackIndex = 0;
2859 bond.UnpackIndex = 0;
2860 }
2861 {
2862 const unsigned numCoders = old.Coders.Size();
2863 folder.Coders.SetSize(numCoders + 1);
2864 for (unsigned k = 0; k < numCoders; k++)
2865 folder.Coders[k] = old.Coders[k];
2866 CCoderInfo &cod = folder.Coders[numCoders];
2867 cod.Props.Alloc(1);
2868 cod.Props[0] = (Byte)inStreamSpec->AlignLog;
2869 cod.NumStreams = 1;
2870 }
2871 {
2872 const unsigned numPackStreams = old.Coders.Size();
2873 folder.Coders.SetSize(numPackStreams);
2874 for (unsigned k = 0; k < numPackStreams; k++)
2875 folder.PackStreams[k] = old.PackStreams[k];
2876 }
2877 }
2878 newDatabase.Folders.Delete(newDatabase.Folders.Size() - 2);
2879 */
2880 }
2881
2882
2883 lps->InSize += procSize;
2884 // lps->InSize += curFolderUnpackSize;
2555 2885
2556 // numUnpackStreams = 0 is very bad case for locked files 2886 // numUnpackStreams = 0 is very bad case for locked files
2557 // v3.13 doesn't understand it. 2887 // v3.13 doesn't understand it.
@@ -2561,7 +2891,7 @@ HRESULT Update(
2561 if (skippedSize != 0 && complexity >= skippedSize) 2891 if (skippedSize != 0 && complexity >= skippedSize)
2562 { 2892 {
2563 complexity -= skippedSize; 2893 complexity -= skippedSize;
2564 RINOK(updateCallback->SetTotal(complexity)); 2894 RINOK(updateCallback->SetTotal(complexity))
2565 } 2895 }
2566 2896
2567 /* 2897 /*
@@ -2604,7 +2934,7 @@ HRESULT Update(
2604 } 2934 }
2605 } 2935 }
2606 2936
2607 RINOK(lps->SetCur()); 2937 RINOK(lps->SetCur())
2608 2938
2609 /* 2939 /*
2610 fileIndexToUpdateIndexMap.ClearAndFree(); 2940 fileIndexToUpdateIndexMap.ClearAndFree();
@@ -2634,10 +2964,26 @@ HRESULT Update(
2634 } 2964 }
2635 } 2965 }
2636 */ 2966 */
2967
2968 {
2969 const unsigned numFolders = newDatabase.Folders.Size();
2970 if (newDatabase.NumUnpackStreamsVector.Size() != numFolders
2971 || newDatabase.FolderUnpackCRCs.Defs.Size() > numFolders)
2972 return E_FAIL;
2973 newDatabase.FolderUnpackCRCs.if_NonEmpty_FillResedue_with_false(numFolders);
2974 }
2975
2976 updateItems.ClearAndFree();
2637 newDatabase.ReserveDown(); 2977 newDatabase.ReserveDown();
2638 2978
2639 if (opCallback) 2979 if (opCallback)
2640 RINOK(opCallback->ReportOperation(NEventIndexType::kNoIndex, (UInt32)(Int32)-1, NUpdateNotifyOp::kHeader)); 2980 RINOK(opCallback->ReportOperation(NEventIndexType::kNoIndex, (UInt32)(Int32)-1, NUpdateNotifyOp::kHeader))
2981
2982 RINOK(archive.WriteDatabase(EXTERNAL_CODECS_LOC_VARS
2983 newDatabase, options.HeaderMethod, options.HeaderOptions))
2984
2985 if (v_StreamSetRestriction)
2986 RINOK(v_StreamSetRestriction->SetRestriction(0, 0))
2641 2987
2642 return S_OK; 2988 return S_OK;
2643} 2989}
diff --git a/CPP/7zip/Archive/7z/7zUpdate.h b/CPP/7zip/Archive/7z/7zUpdate.h
index e6c48ca..de4117a 100644
--- a/CPP/7zip/Archive/7z/7zUpdate.h
+++ b/CPP/7zip/Archive/7z/7zUpdate.h
@@ -1,7 +1,7 @@
1// 7zUpdate.h 1// 7zUpdate.h
2 2
3#ifndef __7Z_UPDATE_H 3#ifndef ZIP7_INC_7Z_UPDATE_H
4#define __7Z_UPDATE_H 4#define ZIP7_INC_7Z_UPDATE_H
5 5
6#include "../IArchive.h" 6#include "../IArchive.h"
7 7
@@ -9,7 +9,6 @@
9 9
10#include "7zCompressionMode.h" 10#include "7zCompressionMode.h"
11#include "7zIn.h" 11#include "7zIn.h"
12#include "7zOut.h"
13 12
14namespace NArchive { 13namespace NArchive {
15namespace N7z { 14namespace N7z {
@@ -95,8 +94,6 @@ struct CUpdateOptions
95 bool MaxFilter; // use BCJ2 filter instead of BCJ 94 bool MaxFilter; // use BCJ2 filter instead of BCJ
96 int AnalysisLevel; 95 int AnalysisLevel;
97 96
98 CHeaderOptions HeaderOptions;
99
100 UInt64 NumSolidFiles; 97 UInt64 NumSolidFiles;
101 UInt64 NumSolidBytes; 98 UInt64 NumSolidBytes;
102 bool SolidExtension; 99 bool SolidExtension;
@@ -110,6 +107,9 @@ struct CUpdateOptions
110 bool Need_ATime; 107 bool Need_ATime;
111 bool Need_MTime; 108 bool Need_MTime;
112 bool Need_Attrib; 109 bool Need_Attrib;
110 // bool Need_Crc;
111
112 CHeaderOptions HeaderOptions;
113 113
114 CUpdateOptions(): 114 CUpdateOptions():
115 Method(NULL), 115 Method(NULL),
@@ -127,6 +127,7 @@ struct CUpdateOptions
127 Need_ATime(false), 127 Need_ATime(false),
128 Need_MTime(false), 128 Need_MTime(false),
129 Need_Attrib(false) 129 Need_Attrib(false)
130 // , Need_Crc(true)
130 {} 131 {}
131}; 132};
132 133
@@ -134,18 +135,12 @@ HRESULT Update(
134 DECL_EXTERNAL_CODECS_LOC_VARS 135 DECL_EXTERNAL_CODECS_LOC_VARS
135 IInStream *inStream, 136 IInStream *inStream,
136 const CDbEx *db, 137 const CDbEx *db,
137 const CObjectVector<CUpdateItem> &updateItems, 138 CObjectVector<CUpdateItem> &updateItems,
138 // const CObjectVector<CTreeFolder> &treeFolders, // treeFolders[0] is root 139 // const CObjectVector<CTreeFolder> &treeFolders, // treeFolders[0] is root
139 // const CUniqBlocks &secureBlocks, 140 // const CUniqBlocks &secureBlocks,
140 COutArchive &archive,
141 CArchiveDatabaseOut &newDatabase,
142 ISequentialOutStream *seqOutStream, 141 ISequentialOutStream *seqOutStream,
143 IArchiveUpdateCallback *updateCallback, 142 IArchiveUpdateCallback *updateCallback,
144 const CUpdateOptions &options 143 const CUpdateOptions &options);
145 #ifndef _NO_CRYPTO
146 , ICryptoGetTextPassword *getDecoderPassword
147 #endif
148 );
149}} 144}}
150 145
151#endif 146#endif
diff --git a/CPP/7zip/Archive/7z/StdAfx.h b/CPP/7zip/Archive/7z/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/7z/StdAfx.h
+++ b/CPP/7zip/Archive/7z/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/7z/makefile b/CPP/7zip/Archive/7z/makefile
index a3b077d..ff60e4d 100644
--- a/CPP/7zip/Archive/7z/makefile
+++ b/CPP/7zip/Archive/7z/makefile
@@ -1,11 +1,11 @@
1PROG = 7z.dll 1PROG = 7z.dll
2DEF_FILE = ../Archive.def 2DEF_FILE = ../Archive.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DEXTERNAL_CODECS \ 4 -DZ7_EXTERNAL_CODECS \
5 5
6AR_OBJS = \ 6AR_OBJS = \
7 $O\ArchiveExports.obj \ 7 $O\ArchiveExports.obj \
8 $O\DllExports.obj \ 8 $O\DllExports2.obj \
9 9
107Z_OBJS = \ 107Z_OBJS = \
11 $O\7zCompressionMode.obj \ 11 $O\7zCompressionMode.obj \
@@ -34,7 +34,6 @@ COMMON_OBJS = \
34 $O\Wildcard.obj \ 34 $O\Wildcard.obj \
35 35
36WIN_OBJS = \ 36WIN_OBJS = \
37 $O\DLL.obj \
38 $O\FileDir.obj \ 37 $O\FileDir.obj \
39 $O\FileFind.obj \ 38 $O\FileFind.obj \
40 $O\FileIO.obj \ 39 $O\FileIO.obj \
@@ -61,6 +60,7 @@ WIN_OBJS = \
61 60
62COMPRESS_OBJS = \ 61COMPRESS_OBJS = \
63 $O\CopyCoder.obj \ 62 $O\CopyCoder.obj \
63 $O\CodecExports.obj \
64 64
65AR_COMMON_OBJS = \ 65AR_COMMON_OBJS = \
66 $O\CoderMixer2.obj \ 66 $O\CoderMixer2.obj \
diff --git a/CPP/7zip/Archive/ApfsHandler.cpp b/CPP/7zip/Archive/ApfsHandler.cpp
index 2c16de1..5fb7e0a 100644
--- a/CPP/7zip/Archive/ApfsHandler.cpp
+++ b/CPP/7zip/Archive/ApfsHandler.cpp
@@ -12,9 +12,11 @@
12#endif 12#endif
13 13
14#include "../../../C/CpuArch.h" 14#include "../../../C/CpuArch.h"
15#include "../../../C/Sha256.h"
15 16
16#include "../../Common/ComTry.h" 17#include "../../Common/ComTry.h"
17#include "../../Common/IntToString.h" 18#include "../../Common/IntToString.h"
19#include "../../Common/MyBuffer2.h"
18#include "../../Common/MyLinux.h" 20#include "../../Common/MyLinux.h"
19#include "../../Common/UTFConvert.h" 21#include "../../Common/UTFConvert.h"
20 22
@@ -87,7 +89,8 @@ struct CUuid
87 89
88typedef UInt64 oid_t; 90typedef UInt64 oid_t;
89typedef UInt64 xid_t; 91typedef UInt64 xid_t;
90typedef Int64 paddr_t; 92// typedef Int64 paddr_t;
93typedef UInt64 paddr_t_unsigned;
91 94
92#define G64o G64 95#define G64o G64
93#define G64x G64 96#define G64x G64
@@ -140,8 +143,10 @@ struct prange_t
140#define OBJECT_TYPE_GBITMAP_BLOCK 0x1b 143#define OBJECT_TYPE_GBITMAP_BLOCK 0x1b
141#define OBJECT_TYPE_ER_RECOVERY_BLOCK 0x1c 144#define OBJECT_TYPE_ER_RECOVERY_BLOCK 0x1c
142#define OBJECT_TYPE_SNAP_META_EXT 0x1d 145#define OBJECT_TYPE_SNAP_META_EXT 0x1d
146*/
143#define OBJECT_TYPE_INTEGRITY_META 0x1e 147#define OBJECT_TYPE_INTEGRITY_META 0x1e
144#define OBJECT_TYPE_FEXT_TREE 0x1f 148#define OBJECT_TYPE_FEXT_TREE 0x1f
149/*
145#define OBJECT_TYPE_RESERVED_20 0x20 150#define OBJECT_TYPE_RESERVED_20 0x20
146 151
147#define OBJECT_TYPE_INVALID 0x0 152#define OBJECT_TYPE_INVALID 0x0
@@ -152,8 +157,9 @@ struct prange_t
152 157
153#define OBJ_VIRTUAL 0x0 158#define OBJ_VIRTUAL 0x0
154#define OBJ_EPHEMERAL 0x80000000 159#define OBJ_EPHEMERAL 0x80000000
160*/
155#define OBJ_PHYSICAL 0x40000000 161#define OBJ_PHYSICAL 0x40000000
156 162/*
157#define OBJ_NOHEADER 0x20000000 163#define OBJ_NOHEADER 0x20000000
158#define OBJ_ENCRYPTED 0x10000000 164#define OBJ_ENCRYPTED 0x10000000
159#define OBJ_NONPERSISTENT 0x08000000 165#define OBJ_NONPERSISTENT 0x08000000
@@ -167,6 +173,8 @@ struct prange_t
167 173
168// #define MAX_CKSUM_SIZE 8 174// #define MAX_CKSUM_SIZE 8
169 175
176static const unsigned k_obj_phys_Size = 0x20;
177
170// obj_phys_t 178// obj_phys_t
171struct CPhys 179struct CPhys
172{ 180{
@@ -183,10 +191,10 @@ struct CPhys
183void CPhys::Parse(const Byte *p) 191void CPhys::Parse(const Byte *p)
184{ 192{
185 // memcpy(cksum, p, MAX_CKSUM_SIZE); 193 // memcpy(cksum, p, MAX_CKSUM_SIZE);
186 G64o (8, oid); 194 G64o (8, oid)
187 G64x (0x10, xid); 195 G64x (0x10, xid)
188 G32 (0x18, type); 196 G32 (0x18, type)
189 G32 (0x1C, subtype); 197 G32 (0x1C, subtype)
190} 198}
191 199
192#define NX_MAX_FILE_SYSTEMS 100 200#define NX_MAX_FILE_SYSTEMS 100
@@ -216,7 +224,9 @@ typedef enum
216#define APFS_INCOMPAT_NORMALIZATION_INSENSITIVE (1 << 3) 224#define APFS_INCOMPAT_NORMALIZATION_INSENSITIVE (1 << 3)
217/* 225/*
218#define APFS_INCOMPAT_INCOMPLETE_RESTORE (1 << 4) 226#define APFS_INCOMPAT_INCOMPLETE_RESTORE (1 << 4)
227*/
219#define APFS_INCOMPAT_SEALED_VOLUME (1 << 5) 228#define APFS_INCOMPAT_SEALED_VOLUME (1 << 5)
229/*
220#define APFS_INCOMPAT_RESERVED_40 (1 << 6) 230#define APFS_INCOMPAT_RESERVED_40 (1 << 6)
221*/ 231*/
222 232
@@ -301,7 +311,7 @@ struct CSuperBlock2
301 { 311 {
302 for (unsigned i = 0; i < NX_MAX_FILE_SYSTEMS; i++) 312 for (unsigned i = 0; i < NX_MAX_FILE_SYSTEMS; i++)
303 { 313 {
304 G64o (0xb8 + i * 8, fs_oid[i]); 314 G64o (0xb8 + i * 8, fs_oid[i])
305 } 315 }
306 } 316 }
307}; 317};
@@ -369,17 +379,18 @@ bool CSuperBlock::Parse(const Byte *p)
369 if (!CheckFletcher64(p, kApfsHeaderSize)) 379 if (!CheckFletcher64(p, kApfsHeaderSize))
370 return false; 380 return false;
371 381
372 G32 (0x24, block_size); 382 G32 (0x24, block_size)
373 { 383 {
374 unsigned logSize = GetLogSize(block_size); 384 const unsigned logSize = GetLogSize(block_size);
385 // don't change it. Some code requires (block_size <= 16)
375 if (logSize < 12 || logSize > 16) 386 if (logSize < 12 || logSize > 16)
376 return false; 387 return false;
377 block_size_Log = logSize; 388 block_size_Log = logSize;
378 } 389 }
379 390
380 G64 (0x28, block_count); 391 G64 (0x28, block_count)
381 392
382 static const UInt64 kArcSize_MAX = (UInt64)1 << 62; 393 const UInt64 kArcSize_MAX = (UInt64)1 << 62;
383 if (block_count > (kArcSize_MAX >> block_size_Log)) 394 if (block_count > (kArcSize_MAX >> block_size_Log))
384 return false; 395 return false;
385 396
@@ -402,10 +413,10 @@ bool CSuperBlock::Parse(const Byte *p)
402 G32 (0x94, xp_data_len); 413 G32 (0x94, xp_data_len);
403 G64o (0x98, spaceman_oid); 414 G64o (0x98, spaceman_oid);
404 */ 415 */
405 G64o (0xa0, omap_oid); 416 G64o (0xa0, omap_oid)
406 // G64o (0xa8, reaper_oid); 417 // G64o (0xa8, reaper_oid);
407 // G32 (0xb0, test_type); 418 // G32 (0xb0, test_type);
408 G32 (0xb4, max_file_systems); 419 G32 (0xb4, max_file_systems)
409 if (max_file_systems > NX_MAX_FILE_SYSTEMS) 420 if (max_file_systems > NX_MAX_FILE_SYSTEMS)
410 return false; 421 return false;
411 /* 422 /*
@@ -448,6 +459,87 @@ bool CSuperBlock::Parse(const Byte *p)
448} 459}
449 460
450 461
462enum apfs_hash_type_t
463{
464 APFS_HASH_INVALID = 0,
465 APFS_HASH_SHA256 = 1,
466 APFS_HASH_SHA512_256 = 2,
467 APFS_HASH_SHA384 = 3,
468 APFS_HASH_SHA512 = 4,
469
470 APFS_HASH_MIN = APFS_HASH_SHA256,
471 APFS_HASH_MAX = APFS_HASH_SHA512,
472
473 APFS_HASH_DEFAULT = APFS_HASH_SHA256
474};
475
476static unsigned GetHashSize(unsigned hashType)
477{
478 if (hashType > APFS_HASH_MAX) return 0;
479 if (hashType < APFS_HASH_MIN) return 0;
480 if (hashType == APFS_HASH_SHA256) return 32;
481 return hashType * 16;
482}
483
484#define APFS_HASH_MAX_SIZE 64
485
486static const char * const g_hash_types[] =
487{
488 NULL
489 , "SHA256"
490 , "SHA512_256"
491 , "SHA384"
492 , "SHA512"
493};
494
495
496struct C_integrity_meta_phys
497{
498 // CPhys im_o;
499 // UInt32 im_version;
500 UInt32 im_flags;
501 // apfs_hash_type_t
502 UInt32 im_hash_type;
503 // UInt32 im_root_hash_offset;
504 // xid_t im_broken_xid;
505 // UInt64 im_reserved[9];
506
507 unsigned HashSize;
508 Byte Hash[APFS_HASH_MAX_SIZE];
509
510 bool Is_SHA256() const { return im_hash_type == APFS_HASH_SHA256; }
511
512 C_integrity_meta_phys()
513 {
514 memset(this, 0, sizeof(*this));
515 }
516 bool Parse(const Byte *p, size_t size, oid_t oid);
517};
518
519bool C_integrity_meta_phys::Parse(const Byte *p, size_t size, oid_t oid)
520{
521 CPhys o;
522 if (!CheckFletcher64(p, size))
523 return false;
524 o.Parse(p);
525 if (o.GetType() != OBJECT_TYPE_INTEGRITY_META)
526 return false;
527 if (o.oid != oid)
528 return false;
529 // G32 (0x20, im_version);
530 G32 (0x24, im_flags)
531 G32 (0x28, im_hash_type)
532 UInt32 im_root_hash_offset;
533 G32 (0x2C, im_root_hash_offset)
534 // G64x (0x30, im_broken_xid);
535 const unsigned hashSize = GetHashSize(im_hash_type);
536 HashSize = hashSize;
537 if (im_root_hash_offset >= size || size - im_root_hash_offset < hashSize)
538 return false;
539 memcpy(Hash, p + im_root_hash_offset, hashSize);
540 return true;
541}
542
451 543
452struct C_omap_phys 544struct C_omap_phys
453{ 545{
@@ -485,7 +577,7 @@ bool C_omap_phys::Parse(const Byte *p, size_t size, oid_t oid)
485 G32 (0x28, tree_type); 577 G32 (0x28, tree_type);
486 G32 (0x2C, snapshot_tree_type); 578 G32 (0x2C, snapshot_tree_type);
487 */ 579 */
488 G64o (0x30, tree_oid); 580 G64o (0x30, tree_oid)
489 /* 581 /*
490 G64o (0x38, snapshot_tree_oid); 582 G64o (0x38, snapshot_tree_oid);
491 G64x (0x40, most_recent_snap); 583 G64x (0x40, most_recent_snap);
@@ -509,8 +601,8 @@ struct nloc
509 601
510 void Parse(const Byte *p) 602 void Parse(const Byte *p)
511 { 603 {
512 G16 (0, off); 604 G16 (0, off)
513 G16 (2, len); 605 G16 (2, len)
514 } 606 }
515 UInt32 GetEnd() const { return (UInt32)off + len; } 607 UInt32 GetEnd() const { return (UInt32)off + len; }
516 bool CheckOverLimit(UInt32 limit) 608 bool CheckOverLimit(UInt32 limit)
@@ -542,8 +634,8 @@ struct kvoff
542 634
543 void Parse(const Byte *p) 635 void Parse(const Byte *p)
544 { 636 {
545 G16 (0, k); 637 G16 (0, k)
546 G16 (2, v); 638 G16 (2, v)
547 } 639 }
548}; 640};
549 641
@@ -551,9 +643,9 @@ struct kvoff
551#define BTNODE_ROOT (1 << 0) 643#define BTNODE_ROOT (1 << 0)
552#define BTNODE_LEAF (1 << 1) 644#define BTNODE_LEAF (1 << 1)
553#define BTNODE_FIXED_KV_SIZE (1 << 2) 645#define BTNODE_FIXED_KV_SIZE (1 << 2)
554/*
555#define BTNODE_HASHED (1 << 3) 646#define BTNODE_HASHED (1 << 3)
556#define BTNODE_NOHEADER (1 << 4) 647#define BTNODE_NOHEADER (1 << 4)
648/*
557#define BTNODE_CHECK_KOFF_INVAL (1 << 15) 649#define BTNODE_CHECK_KOFF_INVAL (1 << 15)
558*/ 650*/
559 651
@@ -563,7 +655,7 @@ static const unsigned k_Toc_offset = 0x38;
563struct CBTreeNodePhys 655struct CBTreeNodePhys
564{ 656{
565 // btn_ prefix 657 // btn_ prefix
566 CPhys o; 658 CPhys ophys;
567 UInt16 flags; 659 UInt16 flags;
568 UInt16 level; // the number of child levels below this node. 0 - for a leaf node, 1 for the immediate parent of a leaf node 660 UInt16 level; // the number of child levels below this node. 0 - for a leaf node, 1 for the immediate parent of a leaf node
569 UInt32 nkeys; // The number of keys stored in this node. 661 UInt32 nkeys; // The number of keys stored in this node.
@@ -575,21 +667,35 @@ struct CBTreeNodePhys
575 */ 667 */
576 668
577 bool Is_FIXED_KV_SIZE() const { return (flags & BTNODE_FIXED_KV_SIZE) != 0; } 669 bool Is_FIXED_KV_SIZE() const { return (flags & BTNODE_FIXED_KV_SIZE) != 0; }
670 bool Is_NOHEADER() const { return (flags & BTNODE_NOHEADER) != 0; }
671 bool Is_HASHED() const { return (flags & BTNODE_HASHED) != 0; }
578 672
579 bool Parse(const Byte *p, size_t size) 673 bool Parse(const Byte *p, size_t size, bool noHeader = false)
580 { 674 {
581 if (!CheckFletcher64(p, size)) 675 G16 (0x20, flags)
582 return false; 676 G16 (0x22, level)
583 o.Parse(p); 677 G32 (0x24, nkeys)
584 G16 (0x20, flags);
585 G16 (0x22, level);
586 G32 (0x24, nkeys);
587 table_space.Parse(p + 0x28); 678 table_space.Parse(p + 0x28);
588 /* 679 /*
589 free_space.Parse(p + 0x2C); 680 free_space.Parse(p + 0x2C);
590 key_free_list.Parse(p + 0x30); 681 key_free_list.Parse(p + 0x30);
591 val_free_list.Parse(p + 0x34); 682 val_free_list.Parse(p + 0x34);
592 */ 683 */
684 memset(&ophys, 0, sizeof(ophys));
685 if (noHeader)
686 {
687 for (unsigned i = 0; i < k_obj_phys_Size; i++)
688 if (p[i] != 0)
689 return false;
690 }
691 else
692 {
693 if (!CheckFletcher64(p, size))
694 return false;
695 ophys.Parse(p);
696 }
697 if (Is_NOHEADER() != noHeader)
698 return false;
593 return true; 699 return true;
594 } 700 }
595}; 701};
@@ -606,6 +712,7 @@ struct CBTreeNodePhys
606#define BTREE_KV_NONALIGNED (1 << 6) 712#define BTREE_KV_NONALIGNED (1 << 6)
607#define BTREE_HASHED (1 << 7) 713#define BTREE_HASHED (1 << 7)
608*/ 714*/
715#define BTREE_NOHEADER (1 << 8)
609 716
610/* 717/*
611 BTREE_EPHEMERAL: The nodes in the B-tree use ephemeral object identifiers to link to child nodes 718 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
624 731
625 void Parse(const Byte *p) 732 void Parse(const Byte *p)
626 { 733 {
627 G32 (0, flags); 734 G32 (0, flags)
628 G32 (4, node_size); 735 G32 (4, node_size)
629 G32 (8, key_size); 736 G32 (8, key_size)
630 G32 (12, val_size); 737 G32 (12, val_size)
631 } 738 }
632}; 739};
633 740
@@ -643,14 +750,15 @@ struct btree_info
643 750
644 bool Is_EPHEMERAL() const { return (fixed.flags & BTREE_EPHEMERAL) != 0; } 751 bool Is_EPHEMERAL() const { return (fixed.flags & BTREE_EPHEMERAL) != 0; }
645 bool Is_PHYSICAL() const { return (fixed.flags & BTREE_PHYSICAL) != 0; } 752 bool Is_PHYSICAL() const { return (fixed.flags & BTREE_PHYSICAL) != 0; }
753 bool Is_NOHEADER() const { return (fixed.flags & BTREE_NOHEADER) != 0; }
646 754
647 void Parse(const Byte *p) 755 void Parse(const Byte *p)
648 { 756 {
649 fixed.Parse(p); 757 fixed.Parse(p);
650 G32 (0x10, longest_key); 758 G32 (0x10, longest_key)
651 G32 (0x14, longest_val); 759 G32 (0x14, longest_val)
652 G64 (0x18, key_count); 760 G64 (0x18, key_count)
653 G64 (0x20, node_count); 761 G64 (0x20, node_count)
654 } 762 }
655}; 763};
656 764
@@ -685,7 +793,7 @@ struct wrapped_meta_crypto_state
685 793
686 794
687#define APFS_MODIFIED_NAMELEN 32 795#define APFS_MODIFIED_NAMELEN 32
688#define sizeof__apfs_modified_by_t (APFS_MODIFIED_NAMELEN + 16); 796#define sizeof_apfs_modified_by_t (APFS_MODIFIED_NAMELEN + 16)
689 797
690struct apfs_modified_by_t 798struct apfs_modified_by_t
691{ 799{
@@ -697,8 +805,8 @@ struct apfs_modified_by_t
697 { 805 {
698 memcpy(id, p, APFS_MODIFIED_NAMELEN); 806 memcpy(id, p, APFS_MODIFIED_NAMELEN);
699 p += APFS_MODIFIED_NAMELEN; 807 p += APFS_MODIFIED_NAMELEN;
700 G64 (0, timestamp); 808 G64 (0, timestamp)
701 G64x (8, last_xid); 809 G64x (8, last_xid)
702 } 810 }
703}; 811};
704 812
@@ -711,7 +819,7 @@ struct CApfs
711 // apfs_ 819 // apfs_
712 CPhys o; 820 CPhys o;
713 // UInt32 magic; 821 // UInt32 magic;
714 UInt32 fs_index; // e index of the object identifier for this volume's file system in the container's array of file systems. 822 UInt32 fs_index; // index of the object identifier for this volume's file system in the container's array of file systems.
715 // UInt64 features; 823 // UInt64 features;
716 // UInt64 readonly_compatible_features; 824 // UInt64 readonly_compatible_features;
717 UInt64 incompatible_features; 825 UInt64 incompatible_features;
@@ -759,9 +867,11 @@ struct CApfs
759 UInt64 cloneinfo_xid; 867 UInt64 cloneinfo_xid;
760 oid_t snap_meta_ext_oid; 868 oid_t snap_meta_ext_oid;
761 CUuid volume_group_id; 869 CUuid volume_group_id;
762 oid_t integrity_meta_oid; 870 */
763 oid_t fext_tree_oid; 871 oid_t integrity_meta_oid; // virtual object identifier of the integrity metadata object
764 UInt32 fext_tree_type; 872 oid_t fext_tree_oid; // virtual object identifier of the file extent tree.
873 UInt32 fext_tree_type; // The type of the file extent tree.
874 /*
765 UInt32 reserved_type; 875 UInt32 reserved_type;
766 oid_t reserved_oid; 876 oid_t reserved_oid;
767 */ 877 */
@@ -793,21 +903,21 @@ bool CApfs::Parse(const Byte *p, size_t size)
793 return false; 903 return false;
794 // if (o.GetType() != OBJECT_TYPE_NX_SUPERBLOCK) return false; 904 // if (o.GetType() != OBJECT_TYPE_NX_SUPERBLOCK) return false;
795 905
796 G32 (0x24, fs_index); 906 G32 (0x24, fs_index)
797 // G64 (0x28, features); 907 // G64 (0x28, features);
798 // G64 (0x30, readonly_compatible_features); 908 // G64 (0x30, readonly_compatible_features);
799 G64 (0x38, incompatible_features); 909 G64 (0x38, incompatible_features)
800 G64 (0x40, unmount_time); 910 G64 (0x40, unmount_time)
801 // G64 (0x48, fs_reserve_block_count); 911 // G64 (0x48, fs_reserve_block_count);
802 // G64 (0x50, fs_quota_block_count); 912 // G64 (0x50, fs_quota_block_count);
803 G64 (0x58, fs_alloc_count); 913 G64 (0x58, fs_alloc_count)
804 // meta_crypto.Parse(p + 0x60); 914 // meta_crypto.Parse(p + 0x60);
805 // G32 (0x74, root_tree_type); 915 // G32 (0x74, root_tree_type);
806 // G32 (0x78, extentref_tree_type); 916 // G32 (0x78, extentref_tree_type);
807 // G32 (0x7C, snap_meta_tree_type); 917 // G32 (0x7C, snap_meta_tree_type);
808 918
809 G64o (0x80, omap_oid); 919 G64o (0x80, omap_oid)
810 G64o (0x88, root_tree_oid); 920 G64o (0x88, root_tree_oid)
811 /* 921 /*
812 G64o (0x90, extentref_tree_oid); 922 G64o (0x90, extentref_tree_oid);
813 G64o (0x98, snap_meta_tree_oid); 923 G64o (0x98, snap_meta_tree_oid);
@@ -815,23 +925,23 @@ bool CApfs::Parse(const Byte *p, size_t size)
815 G64o (0xa8, revert_to_sblock_oid); 925 G64o (0xa8, revert_to_sblock_oid);
816 G64 (0xb0, next_obj_id); 926 G64 (0xb0, next_obj_id);
817 */ 927 */
818 G64 (0xb8, num_files); 928 G64 (0xb8, num_files)
819 G64 (0xc0, num_directories); 929 G64 (0xc0, num_directories)
820 G64 (0xc8, num_symlinks); 930 G64 (0xc8, num_symlinks)
821 G64 (0xd0, num_other_fsobjects); 931 G64 (0xd0, num_other_fsobjects)
822 G64 (0xd8, num_snapshots); 932 G64 (0xd8, num_snapshots)
823 G64 (0xe0, total_blocks_alloced); 933 G64 (0xe0, total_blocks_alloced)
824 G64 (0xe8, total_blocks_freed); 934 G64 (0xe8, total_blocks_freed)
825 vol_uuid.SetFrom(p + 0xf0); 935 vol_uuid.SetFrom(p + 0xf0);
826 G64 (0x100, last_mod_time); 936 G64 (0x100, last_mod_time)
827 G64 (0x108, fs_flags); 937 G64 (0x108, fs_flags)
828 p += 0x110; 938 p += 0x110;
829 formatted_by.Parse(p); 939 formatted_by.Parse(p);
830 p += sizeof__apfs_modified_by_t; 940 p += sizeof_apfs_modified_by_t;
831 for (unsigned i = 0; i < APFS_MAX_HIST; i++) 941 for (unsigned i = 0; i < APFS_MAX_HIST; i++)
832 { 942 {
833 modified_by[i].Parse(p); 943 modified_by[i].Parse(p);
834 p += sizeof__apfs_modified_by_t; 944 p += sizeof_apfs_modified_by_t;
835 } 945 }
836 memcpy(volname, p, APFS_VOLNAME_LEN); 946 memcpy(volname, p, APFS_VOLNAME_LEN);
837 p += APFS_VOLNAME_LEN; 947 p += APFS_VOLNAME_LEN;
@@ -845,9 +955,11 @@ bool CApfs::Parse(const Byte *p, size_t size)
845 G64 (0x20, cloneinfo_xid); 955 G64 (0x20, cloneinfo_xid);
846 G64o (0x28, snap_meta_ext_oid); 956 G64o (0x28, snap_meta_ext_oid);
847 volume_group_id.SetFrom(p + 0x30); 957 volume_group_id.SetFrom(p + 0x30);
848 G64o (0x40, integrity_meta_oid); 958 */
849 G64o (0x48, fext_tree_oid); 959 G64o (0x40, integrity_meta_oid)
850 G32 (0x50, fext_tree_type); 960 G64o (0x48, fext_tree_oid)
961 G32 (0x50, fext_tree_type)
962 /*
851 G32 (0x54, reserved_type); 963 G32 (0x54, reserved_type);
852 G64o (0x58, reserved_oid); 964 G64o (0x58, reserved_oid);
853 */ 965 */
@@ -888,7 +1000,7 @@ struct j_key_t
888{ 1000{
889 UInt64 obj_id_and_type; 1001 UInt64 obj_id_and_type;
890 1002
891 void Parse(const Byte *p) { G64(0, obj_id_and_type); } 1003 void Parse(const Byte *p) { G64(0, obj_id_and_type) }
892 unsigned GetType() const { return (unsigned)(obj_id_and_type >> OBJ_TYPE_SHIFT); } 1004 unsigned GetType() const { return (unsigned)(obj_id_and_type >> OBJ_TYPE_SHIFT); }
893 UInt64 GetID() const { return obj_id_and_type & OBJ_ID_MASK; } 1005 UInt64 GetID() const { return obj_id_and_type & OBJ_ID_MASK; }
894}; 1006};
@@ -918,9 +1030,9 @@ struct j_drec_val
918 // uint8_t xfields[]; 1030 // uint8_t xfields[];
919 void Parse(const Byte *p) 1031 void Parse(const Byte *p)
920 { 1032 {
921 G64 (0, file_id); 1033 G64 (0, file_id)
922 G64 (8, date_added); 1034 G64 (8, date_added)
923 G16 (0x10, flags); 1035 G16 (0x10, flags)
924 } 1036 }
925}; 1037};
926 1038
@@ -959,8 +1071,8 @@ struct CItem
959#define UNIFIED_ID_SPACE_MARK 0x0800000000000000 1071#define UNIFIED_ID_SPACE_MARK 0x0800000000000000
960*/ 1072*/
961 1073
962typedef enum 1074//typedef enum
963{ 1075// {
964/* 1076/*
965INODE_IS_APFS_PRIVATE = 0x00000001, 1077INODE_IS_APFS_PRIVATE = 0x00000001,
966INODE_MAINTAIN_DIR_STATS = 0x00000002, 1078INODE_MAINTAIN_DIR_STATS = 0x00000002,
@@ -977,13 +1089,13 @@ INODE_ACTIVE_FILE_TRIMMED = 0x00000800,
977INODE_PINNED_TO_MAIN = 0x00001000, 1089INODE_PINNED_TO_MAIN = 0x00001000,
978INODE_PINNED_TO_TIER2 = 0x00002000, 1090INODE_PINNED_TO_TIER2 = 0x00002000,
979*/ 1091*/
980INODE_HAS_RSRC_FORK = 0x00004000, 1092// INODE_HAS_RSRC_FORK = 0x00004000,
981/* 1093/*
982INODE_NO_RSRC_FORK = 0x00008000, 1094INODE_NO_RSRC_FORK = 0x00008000,
983INODE_ALLOCATION_SPILLEDOVER = 0x00010000, 1095INODE_ALLOCATION_SPILLEDOVER = 0x00010000,
984INODE_FAST_PROMOTE = 0x00020000, 1096INODE_FAST_PROMOTE = 0x00020000,
985*/ 1097*/
986INODE_HAS_UNCOMPRESSED_SIZE = 0x00040000, 1098#define INODE_HAS_UNCOMPRESSED_SIZE 0x00040000
987/* 1099/*
988INODE_IS_PURGEABLE = 0x00080000, 1100INODE_IS_PURGEABLE = 0x00080000,
989INODE_WANTS_TO_BE_PURGEABLE = 0x00100000, 1101INODE_WANTS_TO_BE_PURGEABLE = 0x00100000,
@@ -1001,8 +1113,8 @@ INODE_CLONED_INTERNAL_FLAGS = \
1001 | INODE_HAS_FINDER_INFO \ 1113 | INODE_HAS_FINDER_INFO \
1002 | INODE_SNAPSHOT_COW_EXEMPTION), 1114 | INODE_SNAPSHOT_COW_EXEMPTION),
1003*/ 1115*/
1004} 1116// }
1005j_inode_flags; 1117// j_inode_flags;
1006 1118
1007 1119
1008/* 1120/*
@@ -1063,24 +1175,24 @@ static const char * const g_INODE_Flags[] =
1063 1175
1064// bsd stat.h 1176// bsd stat.h
1065/* 1177/*
1066#define MY__UF_SETTABLE 0x0000ffff // mask of owner changeable flags 1178#define MY_UF_SETTABLE 0x0000ffff // mask of owner changeable flags
1067#define MY__UF_NODUMP 0x00000001 // do not dump file 1179#define MY_UF_NODUMP 0x00000001 // do not dump file
1068#define MY__UF_IMMUTABLE 0x00000002 // file may not be changed 1180#define MY_UF_IMMUTABLE 0x00000002 // file may not be changed
1069#define MY__UF_APPEND 0x00000004 // writes to file may only append 1181#define MY_UF_APPEND 0x00000004 // writes to file may only append
1070#define MY__UF_OPAQUE 0x00000008 // directory is opaque wrt. union 1182#define MY_UF_OPAQUE 0x00000008 // directory is opaque wrt. union
1071#define MY__UF_NOUNLINK 0x00000010 // file entry may not be removed or renamed Not implement in MacOS 1183#define MY_UF_NOUNLINK 0x00000010 // file entry may not be removed or renamed Not implement in MacOS
1072#define MY__UF_COMPRESSED 0x00000020 // file entry is compressed 1184#define MY_UF_COMPRESSED 0x00000020 // file entry is compressed
1073#define MY__UF_TRACKED 0x00000040 // notify about file entry changes 1185#define MY_UF_TRACKED 0x00000040 // notify about file entry changes
1074#define MY__UF_DATAVAULT 0x00000080 // entitlement required for reading and writing 1186#define MY_UF_DATAVAULT 0x00000080 // entitlement required for reading and writing
1075#define MY__UF_HIDDEN 0x00008000 // file entry is hidden 1187#define MY_UF_HIDDEN 0x00008000 // file entry is hidden
1076 1188
1077#define MY__SF_SETTABLE 0xffff0000 // mask of superuser changeable flags 1189#define MY_SF_SETTABLE 0xffff0000 // mask of superuser changeable flags
1078#define MY__SF_ARCHIVED 0x00010000 // file is archived 1190#define MY_SF_ARCHIVED 0x00010000 // file is archived
1079#define MY__SF_IMMUTABLE 0x00020000 // file may not be changed 1191#define MY_SF_IMMUTABLE 0x00020000 // file may not be changed
1080#define MY__SF_APPEND 0x00040000 // writes to file may only append 1192#define MY_SF_APPEND 0x00040000 // writes to file may only append
1081#define MY__SF_RESTRICTED 0x00080000 // entitlement required for writing 1193#define MY_SF_RESTRICTED 0x00080000 // entitlement required for writing
1082#define MY__SF_NOUNLINK 0x00100000 // file entry may not be removed, renamed or used as mount point 1194#define MY_SF_NOUNLINK 0x00100000 // file entry may not be removed, renamed or used as mount point
1083#define MY__SF_SNAPSHOT 0x00200000 // snapshot inode 1195#define MY_SF_SNAPSHOT 0x00200000 // snapshot inode
1084Not implement in MacOS 1196Not implement in MacOS
1085*/ 1197*/
1086 1198
@@ -1142,11 +1254,11 @@ struct j_dstream
1142 1254
1143 void Parse(const Byte *p) 1255 void Parse(const Byte *p)
1144 { 1256 {
1145 G64 (0, size); 1257 G64 (0, size)
1146 G64 (0x8, alloced_size); 1258 G64 (0x8, alloced_size)
1147 G64 (0x10, default_crypto_id); 1259 G64 (0x10, default_crypto_id)
1148 G64 (0x18, total_bytes_written); 1260 G64 (0x18, total_bytes_written)
1149 G64 (0x20, total_bytes_read); 1261 G64 (0x20, total_bytes_read)
1150 } 1262 }
1151}; 1263};
1152 1264
@@ -1167,8 +1279,8 @@ struct j_file_extent_val
1167 1279
1168 void Parse(const Byte *p) 1280 void Parse(const Byte *p)
1169 { 1281 {
1170 G64 (0, len_and_flags); 1282 G64 (0, len_and_flags)
1171 G64 (0x8, phys_block_num); 1283 G64 (0x8, phys_block_num)
1172 // G64 (0x10, crypto_id); 1284 // G64 (0x10, crypto_id);
1173 } 1285 }
1174}; 1286};
@@ -1180,12 +1292,14 @@ struct CExtent
1180 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. 1292 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.
1181 // There are currently no flags defined 1293 // There are currently no flags defined
1182 UInt64 phys_block_num; // The physical block address that the extent starts at 1294 UInt64 phys_block_num; // The physical block address that the extent starts at
1295
1296 UInt64 GetEndOffset() const { return logical_offset + EXTENT_GET_LEN(len_and_flags); }
1183}; 1297};
1184 1298
1185 1299
1186typedef UInt32 MY__uid_t; 1300typedef UInt32 MY_uid_t;
1187typedef UInt32 MY__gid_t; 1301typedef UInt32 MY_gid_t;
1188typedef UInt16 MY__mode_t; 1302typedef UInt16 MY_mode_t;
1189 1303
1190 1304
1191typedef enum 1305typedef enum
@@ -1262,9 +1376,9 @@ struct CNode
1262 // cp_key_class_t default_protection_class; 1376 // cp_key_class_t default_protection_class;
1263 UInt32 write_generation_counter; 1377 UInt32 write_generation_counter;
1264 UInt32 bsd_flags; 1378 UInt32 bsd_flags;
1265 MY__uid_t owner; 1379 MY_uid_t owner;
1266 MY__gid_t group; 1380 MY_gid_t group;
1267 MY__mode_t mode; 1381 MY_mode_t mode;
1268 UInt16 pad1; 1382 UInt16 pad1;
1269 UInt64 uncompressed_size; 1383 UInt64 uncompressed_size;
1270 1384
@@ -1376,32 +1490,32 @@ struct CSmallNode
1376{ 1490{
1377 CRecordVector<CExtent> Extents; 1491 CRecordVector<CExtent> Extents;
1378 // UInt32 NumLinks; 1492 // UInt32 NumLinks;
1379 // CSmallNode(): NumLinks(0) {}; 1493 // CSmallNode(): NumLinks(0) {}
1380}; 1494};
1381 1495
1382static const unsigned k_SizeOf_j_inode_val = 0x5c; 1496static const unsigned k_SizeOf_j_inode_val = 0x5c;
1383 1497
1384void CNode::Parse(const Byte *p) 1498void CNode::Parse(const Byte *p)
1385{ 1499{
1386 G64 (0, parent_id); 1500 G64 (0, parent_id)
1387 G64 (0x8, private_id); 1501 G64 (0x8, private_id)
1388 G64 (0x10, create_time); 1502 G64 (0x10, create_time)
1389 G64 (0x18, mod_time); 1503 G64 (0x18, mod_time)
1390 G64 (0x20, change_time); 1504 G64 (0x20, change_time)
1391 G64 (0x28, access_time); 1505 G64 (0x28, access_time)
1392 G64 (0x30, internal_flags); 1506 G64 (0x30, internal_flags)
1393 { 1507 {
1394 G32 (0x38, nchildren); 1508 G32 (0x38, nchildren)
1395 // G32 (0x38, nlink); 1509 // G32 (0x38, nlink);
1396 } 1510 }
1397 // G32 (0x3c, default_protection_class); 1511 // G32 (0x3c, default_protection_class);
1398 G32 (0x40, write_generation_counter); 1512 G32 (0x40, write_generation_counter)
1399 G32 (0x44, bsd_flags); 1513 G32 (0x44, bsd_flags)
1400 G32 (0x48, owner); 1514 G32 (0x48, owner)
1401 G32 (0x4c, group); 1515 G32 (0x4c, group)
1402 G16 (0x50, mode); 1516 G16 (0x50, mode)
1403 // G16 (0x52, pad1); 1517 // G16 (0x52, pad1);
1404 G64 (0x54, uncompressed_size); 1518 G64 (0x54, uncompressed_size)
1405} 1519}
1406 1520
1407 1521
@@ -1414,10 +1528,10 @@ struct CRef
1414 #ifdef APFS_SHOW_ALT_STREAMS 1528 #ifdef APFS_SHOW_ALT_STREAMS
1415 unsigned AttrIndex; 1529 unsigned AttrIndex;
1416 bool IsAltStream() const { return IsViDef(AttrIndex); } 1530 bool IsAltStream() const { return IsViDef(AttrIndex); }
1417 unsigned GetAttrIndex() const { return AttrIndex; }; 1531 unsigned GetAttrIndex() const { return AttrIndex; }
1418 #else 1532 #else
1419 // bool IsAltStream() const { return false; } 1533 // bool IsAltStream() const { return false; }
1420 unsigned GetAttrIndex() const { return VI_MINUS1; }; 1534 unsigned GetAttrIndex() const { return VI_MINUS1; }
1421 #endif 1535 #endif
1422}; 1536};
1423 1537
@@ -1429,6 +1543,128 @@ struct CRef2
1429}; 1543};
1430 1544
1431 1545
1546struct CHashChunk
1547{
1548 UInt64 lba;
1549 UInt32 hashed_len; // the value is UInt16
1550 Byte hash[APFS_HASH_MAX_SIZE];
1551};
1552
1553typedef CRecordVector<CHashChunk> CStreamHashes;
1554
1555
1556Z7_CLASS_IMP_NOQIB_1(
1557 COutStreamWithHash
1558 , ISequentialOutStream
1559)
1560 bool _hashError;
1561 CAlignedBuffer1 _sha;
1562 CMyComPtr<ISequentialOutStream> _stream;
1563 const CStreamHashes *_hashes;
1564 unsigned _blockSizeLog;
1565 unsigned _chunkIndex;
1566 UInt32 _offsetInChunk;
1567 // UInt64 _size;
1568
1569 CSha256 *Sha() { return (CSha256 *)(void *)(Byte *)_sha; }
1570public:
1571 COutStreamWithHash(): _sha(sizeof(CSha256)) {}
1572
1573 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
1574 // void ReleaseStream() { _stream.Release(); }
1575 void Init(const CStreamHashes *hashes, unsigned blockSizeLog)
1576 {
1577 _hashes = hashes;
1578 _blockSizeLog = blockSizeLog;
1579 _chunkIndex = 0;
1580 _offsetInChunk = 0;
1581 _hashError = false;
1582 // _size = 0;
1583 }
1584 // UInt64 GetSize() const { return _size; }
1585 bool FinalCheck();
1586};
1587
1588
1589static bool Sha256_Final_and_CheckDigest(CSha256 *sha256, const Byte *digest)
1590{
1591 MY_ALIGN (16)
1592 UInt32 temp[SHA256_NUM_DIGEST_WORDS];
1593 Sha256_Final(sha256, (Byte *)temp);
1594 return memcmp(temp, digest, SHA256_DIGEST_SIZE) == 0;
1595}
1596
1597
1598Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize))
1599{
1600 HRESULT result = S_OK;
1601 if (_stream)
1602 result = _stream->Write(data, size, &size);
1603 if (processedSize)
1604 *processedSize = size;
1605 while (size != 0)
1606 {
1607 if (_hashError)
1608 break;
1609 if (_chunkIndex >= _hashes->Size())
1610 {
1611 _hashError = true;
1612 break;
1613 }
1614 if (_offsetInChunk == 0)
1615 Sha256_Init(Sha());
1616 const CHashChunk &chunk = (*_hashes)[_chunkIndex];
1617 /* (_blockSizeLog <= 16) && chunk.hashed_len is 16-bit.
1618 so we can use 32-bit chunkSize here */
1619 const UInt32 chunkSize = ((UInt32)chunk.hashed_len << _blockSizeLog);
1620 const UInt32 rem = chunkSize - _offsetInChunk;
1621 UInt32 cur = size;
1622 if (cur > rem)
1623 cur = (UInt32)rem;
1624 Sha256_Update(Sha(), (const Byte *)data, cur);
1625 data = (const void *)((const Byte *)data + cur);
1626 size -= cur;
1627 // _size += cur;
1628 _offsetInChunk += cur;
1629 if (chunkSize == _offsetInChunk)
1630 {
1631 if (!Sha256_Final_and_CheckDigest(Sha(), chunk.hash))
1632 _hashError = true;
1633 _offsetInChunk = 0;
1634 _chunkIndex++;
1635 }
1636 }
1637 return result;
1638}
1639
1640
1641bool COutStreamWithHash::FinalCheck()
1642{
1643 if (_hashError)
1644 return false;
1645
1646 if (_offsetInChunk != 0)
1647 {
1648 const CHashChunk &chunk = (*_hashes)[_chunkIndex];
1649 {
1650 const UInt32 chunkSize = ((UInt32)chunk.hashed_len << _blockSizeLog);
1651 const UInt32 rem = chunkSize - _offsetInChunk;
1652 Byte b = 0;
1653 for (UInt32 i = 0; i < rem; i++)
1654 Sha256_Update(Sha(), &b, 1);
1655 }
1656 if (!Sha256_Final_and_CheckDigest(Sha(), chunk.hash))
1657 _hashError = true;
1658 _offsetInChunk = 0;
1659 _chunkIndex++;
1660 }
1661 if (_chunkIndex != _hashes->Size())
1662 _hashError = true;
1663 return !_hashError;
1664}
1665
1666
1667
1432struct CVol 1668struct CVol
1433{ 1669{
1434 CObjectVector<CNode> Nodes; 1670 CObjectVector<CNode> Nodes;
@@ -1439,13 +1675,22 @@ struct CVol
1439 CObjectVector<CSmallNode> SmallNodes; 1675 CObjectVector<CSmallNode> SmallNodes;
1440 CRecordVector<UInt64> SmallNodeIDs; 1676 CRecordVector<UInt64> SmallNodeIDs;
1441 1677
1678 CObjectVector<CSmallNode> FEXT_Nodes;
1679 CRecordVector<UInt64> FEXT_NodeIDs;
1680
1681 CObjectVector<CStreamHashes> Hash_Vectors;
1682 CRecordVector<UInt64> Hash_IDs;
1683
1442 unsigned StartRef2Index; // ref2_Index for Refs[0] item 1684 unsigned StartRef2Index; // ref2_Index for Refs[0] item
1443 unsigned RootRef2Index; // ref2_Index of virtual root folder (Volume1) 1685 unsigned RootRef2Index; // ref2_Index of virtual root folder (Volume1)
1444 CApfs apfs; 1686 CApfs apfs;
1687 C_integrity_meta_phys integrity;
1688
1445 bool NodeNotFound; 1689 bool NodeNotFound;
1446 bool ThereAreUnlinkedNodes; 1690 bool ThereAreUnlinkedNodes;
1447 bool WrongInodeLink; 1691 bool WrongInodeLink;
1448 bool UnsupportedFeature; 1692 bool UnsupportedFeature;
1693 bool UnsupportedMethod;
1449 1694
1450 unsigned NumItems_In_PrivateDir; 1695 unsigned NumItems_In_PrivateDir;
1451 unsigned NumAltStreams; 1696 unsigned NumAltStreams;
@@ -1468,6 +1713,7 @@ struct CVol
1468 ThereAreUnlinkedNodes(false), 1713 ThereAreUnlinkedNodes(false),
1469 WrongInodeLink(false), 1714 WrongInodeLink(false),
1470 UnsupportedFeature(false), 1715 UnsupportedFeature(false),
1716 UnsupportedMethod(false),
1471 NumItems_In_PrivateDir(0), 1717 NumItems_In_PrivateDir(0),
1472 NumAltStreams(0) 1718 NumAltStreams(0)
1473 {} 1719 {}
@@ -1479,7 +1725,7 @@ static void ApfsTimeToFileTime(UInt64 apfsTime, FILETIME &ft, UInt32 &ns100)
1479 const UInt64 s = apfsTime / 1000000000; 1725 const UInt64 s = apfsTime / 1000000000;
1480 const UInt32 ns = (UInt32)(apfsTime % 1000000000); 1726 const UInt32 ns = (UInt32)(apfsTime % 1000000000);
1481 ns100 = (ns % 100); 1727 ns100 = (ns % 100);
1482 const UInt64 v = NWindows::NTime::UnixTime64_To_FileTime64(s) + ns / 100; 1728 const UInt64 v = NWindows::NTime::UnixTime64_To_FileTime64((Int64)s) + ns / 100;
1483 ft.dwLowDateTime = (DWORD)v; 1729 ft.dwLowDateTime = (DWORD)v;
1484 ft.dwHighDateTime = (DWORD)(v >> 32); 1730 ft.dwHighDateTime = (DWORD)(v >> 32);
1485} 1731}
@@ -1561,10 +1807,33 @@ void CVol::AddComment(UString &s) const
1561 1807
1562 AddComment_Name(s, "incompatible_features"); 1808 AddComment_Name(s, "incompatible_features");
1563 s += FlagsToString(g_APFS_INCOMPAT_Flags, 1809 s += FlagsToString(g_APFS_INCOMPAT_Flags,
1564 ARRAY_SIZE(g_APFS_INCOMPAT_Flags), 1810 Z7_ARRAY_SIZE(g_APFS_INCOMPAT_Flags),
1565 (UInt32)apfs.incompatible_features); 1811 (UInt32)apfs.incompatible_features);
1566 s.Add_LF(); 1812 s.Add_LF();
1567 1813
1814
1815 if (apfs.integrity_meta_oid != 0)
1816 {
1817 /*
1818 AddComment_Name(s, "im_version");
1819 s.Add_UInt32(integrity.im_version);
1820 s.Add_LF();
1821 */
1822 AddComment_Name(s, "im_flags");
1823 s.Add_UInt32(integrity.im_flags);
1824 s.Add_LF();
1825 AddComment_Name(s, "im_hash_type");
1826 const char *p = NULL;
1827 if (integrity.im_hash_type < Z7_ARRAY_SIZE(g_hash_types))
1828 p = g_hash_types[integrity.im_hash_type];
1829 if (p)
1830 s += p;
1831 else
1832 s.Add_UInt32(integrity.im_hash_type);
1833 s.Add_LF();
1834 }
1835
1836
1568 // AddComment_UInt64(s, "reserve_block_count", apfs.fs_reserve_block_count, false); 1837 // AddComment_UInt64(s, "reserve_block_count", apfs.fs_reserve_block_count, false);
1569 // AddComment_UInt64(s, "quota_block_count", apfs.fs_quota_block_count); 1838 // AddComment_UInt64(s, "quota_block_count", apfs.fs_quota_block_count);
1570 AddComment_UInt64(s, "fs_alloc_count", apfs.fs_alloc_count); 1839 AddComment_UInt64(s, "fs_alloc_count", apfs.fs_alloc_count);
@@ -1583,7 +1852,7 @@ void CVol::AddComment(UString &s) const
1583 AddComment_Time(s, "unmounted", apfs.unmount_time); 1852 AddComment_Time(s, "unmounted", apfs.unmount_time);
1584 AddComment_Time(s, "last_modified", apfs.last_mod_time); 1853 AddComment_Time(s, "last_modified", apfs.last_mod_time);
1585 AddComment_modified_by_t(s, "formatted_by", apfs.formatted_by); 1854 AddComment_modified_by_t(s, "formatted_by", apfs.formatted_by);
1586 for (unsigned i = 0; i < ARRAY_SIZE(apfs.modified_by); i++) 1855 for (unsigned i = 0; i < Z7_ARRAY_SIZE(apfs.modified_by); i++)
1587 { 1856 {
1588 const apfs_modified_by_t &v = apfs.modified_by[i]; 1857 const apfs_modified_by_t &v = apfs.modified_by[i];
1589 if (v.last_xid == 0 && v.timestamp == 0 && v.id[0] == 0) 1858 if (v.last_xid == 0 && v.timestamp == 0 && v.id[0] == 0)
@@ -1611,8 +1880,8 @@ struct omap_key
1611 xid_t xid; // The transaction identifier 1880 xid_t xid; // The transaction identifier
1612 void Parse(const Byte *p) 1881 void Parse(const Byte *p)
1613 { 1882 {
1614 G64o (0, oid); 1883 G64o (0, oid)
1615 G64x (8, xid); 1884 G64x (8, xid)
1616 } 1885 }
1617}; 1886};
1618 1887
@@ -1620,7 +1889,9 @@ struct omap_key
1620#define OMAP_VAL_DELETED (1 << 0) 1889#define OMAP_VAL_DELETED (1 << 0)
1621#define OMAP_VAL_SAVED (1 << 1) 1890#define OMAP_VAL_SAVED (1 << 1)
1622#define OMAP_VAL_ENCRYPTED (1 << 2) 1891#define OMAP_VAL_ENCRYPTED (1 << 2)
1892*/
1623#define OMAP_VAL_NOHEADER (1 << 3) 1893#define OMAP_VAL_NOHEADER (1 << 3)
1894/*
1624#define OMAP_VAL_CRYPTO_GENERATION (1 << 4) 1895#define OMAP_VAL_CRYPTO_GENERATION (1 << 4)
1625*/ 1896*/
1626 1897
@@ -1628,13 +1899,16 @@ struct omap_val
1628{ 1899{
1629 UInt32 flags; 1900 UInt32 flags;
1630 UInt32 size; 1901 UInt32 size;
1631 paddr_t paddr; 1902 // paddr_t paddr;
1903 paddr_t_unsigned paddr;
1904
1905 bool IsFlag_NoHeader() const { return (flags & OMAP_VAL_NOHEADER) != 0; }
1632 1906
1633 void Parse(const Byte *p) 1907 void Parse(const Byte *p)
1634 { 1908 {
1635 G32 (0, flags); 1909 G32 (0, flags)
1636 G32 (4, size); 1910 G32 (4, size)
1637 G64 (8, paddr); 1911 G64 (8, paddr)
1638 } 1912 }
1639}; 1913};
1640 1914
@@ -1710,6 +1984,7 @@ struct CDatabase
1710 bool HeadersError; 1984 bool HeadersError;
1711 bool ThereAreAltStreams; 1985 bool ThereAreAltStreams;
1712 bool UnsupportedFeature; 1986 bool UnsupportedFeature;
1987 bool UnsupportedMethod;
1713 1988
1714 CSuperBlock sb; 1989 CSuperBlock sb;
1715 1990
@@ -1726,8 +2001,9 @@ struct CDatabase
1726 void Clear() 2001 void Clear()
1727 { 2002 {
1728 HeadersError = false; 2003 HeadersError = false;
1729 UnsupportedFeature = false;
1730 ThereAreAltStreams = false; 2004 ThereAreAltStreams = false;
2005 UnsupportedFeature = false;
2006 UnsupportedMethod = false;
1731 2007
1732 ProgressVal_Cur = 0; 2008 ProgressVal_Cur = 0;
1733 ProgressVal_Prev = 0; 2009 ProgressVal_Prev = 0;
@@ -1742,8 +2018,9 @@ struct CDatabase
1742 2018
1743 HRESULT SeekReadBlock_FALSE(UInt64 oid, void *data); 2019 HRESULT SeekReadBlock_FALSE(UInt64 oid, void *data);
1744 void GetItemPath(unsigned index, const CNode *inode, NWindows::NCOM::CPropVariant &path) const; 2020 void GetItemPath(unsigned index, const CNode *inode, NWindows::NCOM::CPropVariant &path) const;
1745 HRESULT ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel); 2021 HRESULT ReadMap(UInt64 oid, bool noHeader, CVol *vol, const Byte *hash,
1746 HRESULT ReadObjectMap(UInt64 oid, CObjectMap &map); 2022 CMap &map, unsigned recurseLevel);
2023 HRESULT ReadObjectMap(UInt64 oid, CVol *vol, CObjectMap &map);
1747 HRESULT OpenVolume(const CObjectMap &omap, const oid_t fs_oid); 2024 HRESULT OpenVolume(const CObjectMap &omap, const oid_t fs_oid);
1748 HRESULT Open2(); 2025 HRESULT Open2();
1749 2026
@@ -1766,14 +2043,14 @@ HRESULT CDatabase::SeekReadBlock_FALSE(UInt64 oid, void *data)
1766 { 2043 {
1767 if (ProgressVal_Cur - ProgressVal_Prev >= (1 << 22)) 2044 if (ProgressVal_Cur - ProgressVal_Prev >= (1 << 22))
1768 { 2045 {
1769 RINOK(OpenCallback->SetCompleted(NULL, &ProgressVal_Cur)); 2046 RINOK(OpenCallback->SetCompleted(NULL, &ProgressVal_Cur))
1770 ProgressVal_Prev = ProgressVal_Cur; 2047 ProgressVal_Prev = ProgressVal_Cur;
1771 } 2048 }
1772 ProgressVal_Cur += sb.block_size; 2049 ProgressVal_Cur += sb.block_size;
1773 } 2050 }
1774 if (oid == 0 || oid >= sb.block_count) 2051 if (oid == 0 || oid >= sb.block_count)
1775 return S_FALSE; 2052 return S_FALSE;
1776 RINOK(OpenInStream->Seek(oid << sb.block_size_Log, STREAM_SEEK_SET, NULL)); 2053 RINOK(InStream_SeekSet(OpenInStream, oid << sb.block_size_Log))
1777 return ReadStream_FALSE(OpenInStream, data, sb.block_size); 2054 return ReadStream_FALSE(OpenInStream, data, sb.block_size);
1778} 2055}
1779 2056
@@ -1791,8 +2068,23 @@ API_FUNC_static_IsArc IsArc_APFS(const Byte *p, size_t size)
1791} 2068}
1792 2069
1793 2070
2071static bool CheckHash(unsigned hashAlgo, const Byte *data, size_t size, const Byte *digest)
2072{
2073 if (hashAlgo == APFS_HASH_SHA256)
2074 {
2075 MY_ALIGN (16)
2076 CSha256 sha;
2077 Sha256_Init(&sha);
2078 Sha256_Update(&sha, data, size);
2079 return Sha256_Final_and_CheckDigest(&sha, digest);
2080 }
2081 return true;
2082}
2083
1794 2084
1795HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel) 2085HRESULT CDatabase::ReadMap(UInt64 oid, bool noHeader,
2086 CVol *vol, const Byte *hash,
2087 CMap &map, unsigned recurseLevel)
1796{ 2088{
1797 // is it allowed to use big number of levels ? 2089 // is it allowed to use big number of levels ?
1798 if (recurseLevel > (1 << 10)) 2090 if (recurseLevel > (1 << 10))
@@ -1809,12 +2101,16 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1809 const Byte *buf; 2101 const Byte *buf;
1810 { 2102 {
1811 CByteBuffer &buf2 = Buffers[recurseLevel]; 2103 CByteBuffer &buf2 = Buffers[recurseLevel];
1812 RINOK(SeekReadBlock_FALSE(oid, buf2)); 2104 RINOK(SeekReadBlock_FALSE(oid, buf2))
1813 buf = buf2; 2105 buf = buf2;
1814 } 2106 }
1815 2107
2108 if (hash && vol)
2109 if (!CheckHash(vol->integrity.im_hash_type, buf, blockSize, hash))
2110 return S_FALSE;
2111
1816 CBTreeNodePhys bt; 2112 CBTreeNodePhys bt;
1817 if (!bt.Parse(buf, blockSize)) 2113 if (!bt.Parse(buf, blockSize, noHeader))
1818 return S_FALSE; 2114 return S_FALSE;
1819 2115
1820 map.NumNodes++; 2116 map.NumNodes++;
@@ -1829,14 +2125,16 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1829 - File-system records are sorted according to the rules listed in File-System Objects. 2125 - File-system records are sorted according to the rules listed in File-System Objects.
1830 */ 2126 */
1831 2127
1832 if (bt.o.subtype != map.Subtype) 2128 if (!noHeader)
2129 if (bt.ophys.subtype != map.Subtype)
1833 return S_FALSE; 2130 return S_FALSE;
1834 2131
1835 unsigned endLimit = blockSize; 2132 unsigned endLimit = blockSize;
1836 2133
1837 if (recurseLevel == 0) 2134 if (recurseLevel == 0)
1838 { 2135 {
1839 if (bt.o.GetType() != OBJECT_TYPE_BTREE) 2136 if (!noHeader)
2137 if (bt.ophys.GetType() != OBJECT_TYPE_BTREE)
1840 return S_FALSE; 2138 return S_FALSE;
1841 if ((bt.flags & BTNODE_ROOT) == 0) 2139 if ((bt.flags & BTNODE_ROOT) == 0)
1842 return S_FALSE; 2140 return S_FALSE;
@@ -1850,6 +2148,8 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1850 return S_FALSE; 2148 return S_FALSE;
1851 if (bti.Is_PHYSICAL() != map.IsPhysical) 2149 if (bti.Is_PHYSICAL() != map.IsPhysical)
1852 return S_FALSE; 2150 return S_FALSE;
2151 if (bti.Is_NOHEADER() != noHeader)
2152 return S_FALSE;
1853 // we don't allow volumes with big number of Keys 2153 // we don't allow volumes with big number of Keys
1854 const UInt32 kNumItemsMax = k_VectorSizeMax; 2154 const UInt32 kNumItemsMax = k_VectorSizeMax;
1855 if (map.bti.node_count > kNumItemsMax) 2155 if (map.bti.node_count > kNumItemsMax)
@@ -1859,7 +2159,8 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1859 } 2159 }
1860 else 2160 else
1861 { 2161 {
1862 if (bt.o.GetType() != OBJECT_TYPE_BTREE_NODE) 2162 if (!noHeader)
2163 if (bt.ophys.GetType() != OBJECT_TYPE_BTREE_NODE)
1863 return S_FALSE; 2164 return S_FALSE;
1864 if ((bt.flags & BTNODE_ROOT) != 0) 2165 if ((bt.flags & BTNODE_ROOT) != 0)
1865 return S_FALSE; 2166 return S_FALSE;
@@ -1925,7 +2226,9 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1925 const oid_t oidNext = Get64(p2); 2226 const oid_t oidNext = Get64(p2);
1926 if (map.bti.Is_PHYSICAL()) 2227 if (map.bti.Is_PHYSICAL())
1927 { 2228 {
1928 RINOK(ReadMap(oidNext, map, recurseLevel + 1)); 2229 RINOK(ReadMap(oidNext, noHeader, vol,
2230 NULL, /* hash */
2231 map, recurseLevel + 1))
1929 continue; 2232 continue;
1930 } 2233 }
1931 else 2234 else
@@ -1960,10 +2263,38 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1960 continue; 2263 continue;
1961 } 2264 }
1962 { 2265 {
1963 if (a.v.off < 8 || a.v.len != 8) 2266 if (a.v.len < 8)
1964 return S_FALSE; 2267 return S_FALSE;
2268
2269 const Byte *hashNew = NULL;
2270 oid_t oidNext = Get64(p2);
2271
2272 if (bt.Is_HASHED())
2273 {
2274 if (!vol)
2275 return S_FALSE;
2276 /*
2277 struct btn_index_node_val {
2278 oid_t binv_child_oid;
2279 uint8_t binv_child_hash[BTREE_NODE_HASH_SIZE_MAX];
2280 };
2281 */
2282 /* (a.v.len == 40) is possible if Is_HASHED()
2283 so there is hash (for example, 256-bit) after 64-bit id) */
2284 if (a.v.len != 8 + vol->integrity.HashSize)
2285 return S_FALSE;
2286 hashNew = p2 + 8;
2287 /* we need to add root_tree_oid here,
2288 but where it's defined in apfs specification ? */
2289 oidNext += vol->apfs.root_tree_oid;
2290 }
2291 else
2292 {
2293 if (a.v.len != 8)
2294 return S_FALSE;
2295 }
2296
1965 // value is only 64-bit for non leaf. 2297 // value is only 64-bit for non leaf.
1966 const oid_t oidNext = Get64(p2);
1967 2298
1968 if (map.bti.Is_PHYSICAL()) 2299 if (map.bti.Is_PHYSICAL())
1969 { 2300 {
@@ -1972,15 +2303,25 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1972 // RINOK(ReadMap(oidNext, map, recurseLevel + 1)); 2303 // RINOK(ReadMap(oidNext, map, recurseLevel + 1));
1973 // continue; 2304 // continue;
1974 } 2305 }
2306 /*
2307 else if (map.bti.Is_EPHEMERAL())
2308 {
2309 // Ephemeral objects are stored in memory while the container is mounted and in a checkpoint when the container isn't mounted
2310 // the code was not tested:
2311 return S_FALSE;
2312 }
2313 */
1975 else 2314 else
1976 { 2315 {
2316 /* nodes in the B-tree use virtual object identifiers to link to their child nodes. */
1977 const int index = map.Omap.FindKey(oidNext); 2317 const int index = map.Omap.FindKey(oidNext);
1978 if (index == -1) 2318 if (index == -1)
1979 return S_FALSE; 2319 return S_FALSE;
1980 const omap_val &ov = map.Omap.Vals[(unsigned)index]; 2320 const omap_val &ov = map.Omap.Vals[(unsigned)index];
1981 if (ov.size != blockSize) // change it : it must be multiple of 2321 if (ov.size != blockSize) // change it : it must be multiple of
1982 return S_FALSE; 2322 return S_FALSE;
1983 RINOK(ReadMap(ov.paddr, map, recurseLevel + 1)); 2323 RINOK(ReadMap(ov.paddr, ov.IsFlag_NoHeader(), vol, hashNew,
2324 map, recurseLevel + 1))
1984 continue; 2325 continue;
1985 } 2326 }
1986 } 2327 }
@@ -1996,19 +2337,23 @@ HRESULT CDatabase::ReadMap(UInt64 oid, CMap &map, unsigned recurseLevel)
1996 2337
1997 2338
1998 2339
1999HRESULT CDatabase::ReadObjectMap(UInt64 oid, CObjectMap &omap) 2340HRESULT CDatabase::ReadObjectMap(UInt64 oid, CVol *vol, CObjectMap &omap)
2000{ 2341{
2001 CByteBuffer buf; 2342 CByteBuffer buf;
2002 const size_t blockSize = sb.block_size; 2343 const size_t blockSize = sb.block_size;
2003 buf.Alloc(blockSize); 2344 buf.Alloc(blockSize);
2004 RINOK(SeekReadBlock_FALSE(oid, buf)); 2345 RINOK(SeekReadBlock_FALSE(oid, buf))
2005 C_omap_phys op; 2346 C_omap_phys op;
2006 if (!op.Parse(buf, blockSize, oid)) 2347 if (!op.Parse(buf, blockSize, oid))
2007 return S_FALSE; 2348 return S_FALSE;
2008 CMap map; 2349 CMap map;
2009 map.Subtype = OBJECT_TYPE_OMAP; 2350 map.Subtype = OBJECT_TYPE_OMAP;
2010 map.IsPhysical = true; 2351 map.IsPhysical = true;
2011 RINOK(ReadMap(op.tree_oid, map, 0)); 2352 RINOK(ReadMap(op.tree_oid,
2353 false /* noHeader */,
2354 vol,
2355 NULL, /* hash */
2356 map, 0))
2012 if (!omap.Parse(map.Pairs)) 2357 if (!omap.Parse(map.Pairs))
2013 return S_FALSE; 2358 return S_FALSE;
2014 return S_OK; 2359 return S_OK;
@@ -2022,7 +2367,7 @@ HRESULT CDatabase::Open2()
2022 CSuperBlock2 sb2; 2367 CSuperBlock2 sb2;
2023 { 2368 {
2024 Byte buf[kApfsHeaderSize]; 2369 Byte buf[kApfsHeaderSize];
2025 RINOK(ReadStream_FALSE(OpenInStream, buf, kApfsHeaderSize)); 2370 RINOK(ReadStream_FALSE(OpenInStream, buf, kApfsHeaderSize))
2026 if (!sb.Parse(buf)) 2371 if (!sb.Parse(buf))
2027 return S_FALSE; 2372 return S_FALSE;
2028 sb2.Parse(buf); 2373 sb2.Parse(buf);
@@ -2030,7 +2375,9 @@ HRESULT CDatabase::Open2()
2030 2375
2031 { 2376 {
2032 CObjectMap omap; 2377 CObjectMap omap;
2033 RINOK(ReadObjectMap(sb.omap_oid, omap)); 2378 RINOK(ReadObjectMap(sb.omap_oid,
2379 NULL, /* CVol */
2380 omap))
2034 unsigned numRefs = 0; 2381 unsigned numRefs = 0;
2035 for (unsigned i = 0; i < sb.max_file_systems; i++) 2382 for (unsigned i = 0; i < sb.max_file_systems; i++)
2036 { 2383 {
@@ -2038,7 +2385,7 @@ HRESULT CDatabase::Open2()
2038 if (oid == 0) 2385 if (oid == 0)
2039 continue; 2386 continue;
2040 // for (unsigned k = 0; k < 1; k++) // for debug 2387 // for (unsigned k = 0; k < 1; k++) // for debug
2041 RINOK(OpenVolume(omap, oid)); 2388 RINOK(OpenVolume(omap, oid))
2042 const unsigned a = Vols.Back().Refs.Size(); 2389 const unsigned a = Vols.Back().Refs.Size();
2043 numRefs += a; 2390 numRefs += a;
2044 if (numRefs < a) 2391 if (numRefs < a)
@@ -2104,7 +2451,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2104 if (ov.size != blockSize) // change it : it must be multiple of 2451 if (ov.size != blockSize) // change it : it must be multiple of
2105 return S_FALSE; 2452 return S_FALSE;
2106 buf.Alloc(blockSize); 2453 buf.Alloc(blockSize);
2107 RINOK(SeekReadBlock_FALSE(ov.paddr, buf)); 2454 RINOK(SeekReadBlock_FALSE(ov.paddr, buf))
2108 } 2455 }
2109 2456
2110 CVol &vol = Vols.AddNew(); 2457 CVol &vol = Vols.AddNew();
@@ -2113,14 +2460,107 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2113 if (!apfs.Parse(buf, blockSize)) 2460 if (!apfs.Parse(buf, blockSize))
2114 return S_FALSE; 2461 return S_FALSE;
2115 2462
2463 if (apfs.fext_tree_oid != 0)
2464 {
2465 if ((apfs.incompatible_features & APFS_INCOMPAT_SEALED_VOLUME) == 0)
2466 return S_FALSE;
2467 if ((apfs.fext_tree_type & OBJ_PHYSICAL) == 0)
2468 return S_FALSE;
2469 if ((apfs.fext_tree_type & OBJECT_TYPE_MASK) != OBJECT_TYPE_BTREE)
2470 return S_FALSE;
2471
2472 CMap map2;
2473 map2.Subtype = OBJECT_TYPE_FEXT_TREE;
2474 map2.IsPhysical = true;
2475
2476 RINOK(ReadMap(apfs.fext_tree_oid,
2477 false /* noHeader */,
2478 &vol,
2479 NULL, /* hash */
2480 map2, 0))
2481
2482 UInt64 prevId = 1;
2483
2484 FOR_VECTOR (i, map2.Pairs)
2485 {
2486 if (OpenCallback && (i & 0xffff) == 1)
2487 {
2488 const UInt64 numFiles = ProgressVal_NumFilesTotal +
2489 (vol.Items.Size() + vol.Nodes.Size()) / 2;
2490 RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur))
2491 }
2492 // The key half of a record from a file extent tree.
2493 // struct fext_tree_key
2494 const CKeyValPair &pair = map2.Pairs[i];
2495 if (pair.Key.Size() != 16)
2496 return S_FALSE;
2497 const Byte *p = pair.Key;
2498 const UInt64 id = GetUi64(p);
2499 if (id < prevId)
2500 return S_FALSE; // IDs must be sorted
2501 prevId = id;
2502
2503 CExtent ext;
2504 ext.logical_offset = GetUi64(p + 8);
2505 {
2506 if (pair.Val.Size() != 16)
2507 return S_FALSE;
2508 const Byte *p2 = pair.Val;
2509 ext.len_and_flags = GetUi64(p2);
2510 ext.phys_block_num = GetUi64(p2 + 8);
2511 }
2512
2513 PRF(printf("\n%6d: id=%6d logical_addr = %2d len_and_flags=%5x phys_block_num = %5d",
2514 i, (unsigned)id,
2515 (unsigned)ext.logical_offset,
2516 (unsigned)ext.len_and_flags,
2517 (unsigned)ext.phys_block_num));
2518
2519 if (vol.FEXT_NodeIDs.IsEmpty() ||
2520 vol.FEXT_NodeIDs.Back() != id)
2521 {
2522 vol.FEXT_NodeIDs.Add(id);
2523 vol.FEXT_Nodes.AddNew();
2524 }
2525 CRecordVector<CExtent> &extents = vol.FEXT_Nodes.Back().Extents;
2526 if (!extents.IsEmpty())
2527 if (ext.logical_offset != extents.Back().GetEndOffset())
2528 return S_FALSE;
2529 extents.Add(ext);
2530 continue;
2531 }
2532
2533 PRF(printf("\n\n"));
2534 }
2535
2116 /* For each volume, read the root file system tree's virtual object 2536 /* For each volume, read the root file system tree's virtual object
2117 identifier from the apfs_root_tree_oid field, 2537 identifier from the apfs_root_tree_oid field,
2118 and then look it up in the volume object map indicated 2538 and then look it up in the volume object map indicated
2119 by the omap_oid field. */ 2539 by the omap_oid field. */
2120 2540
2121 CMap map; 2541 CMap map;
2542 ReadObjectMap(apfs.omap_oid, &vol, map.Omap);
2543
2544 const Byte *hash_for_root = NULL;
2545
2546 if (apfs.integrity_meta_oid != 0)
2547 {
2548 if ((apfs.incompatible_features & APFS_INCOMPAT_SEALED_VOLUME) == 0)
2549 return S_FALSE;
2550 const int index = map.Omap.FindKey(apfs.integrity_meta_oid);
2551 if (index == -1)
2552 return S_FALSE;
2553 const omap_val &ov = map.Omap.Vals[(unsigned)index];
2554 if (ov.size != blockSize)
2555 return S_FALSE;
2556 RINOK(SeekReadBlock_FALSE(ov.paddr, buf))
2557 if (!vol.integrity.Parse(buf, blockSize, apfs.integrity_meta_oid))
2558 return S_FALSE;
2559 if (vol.integrity.im_hash_type != 0)
2560 hash_for_root = vol.integrity.Hash;
2561 }
2562
2122 { 2563 {
2123 ReadObjectMap(apfs.omap_oid, map.Omap);
2124 const int index = map.Omap.FindKey(apfs.root_tree_oid); 2564 const int index = map.Omap.FindKey(apfs.root_tree_oid);
2125 if (index == -1) 2565 if (index == -1)
2126 return S_FALSE; 2566 return S_FALSE;
@@ -2129,7 +2569,9 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2129 return S_FALSE; 2569 return S_FALSE;
2130 map.Subtype = OBJECT_TYPE_FSTREE; 2570 map.Subtype = OBJECT_TYPE_FSTREE;
2131 map.IsPhysical = false; 2571 map.IsPhysical = false;
2132 RINOK(ReadMap(ov.paddr, map, 0)); 2572 RINOK(ReadMap(ov.paddr, ov.IsFlag_NoHeader(),
2573 &vol, hash_for_root,
2574 map, 0))
2133 } 2575 }
2134 2576
2135 bool needParseAttr = false; 2577 bool needParseAttr = false;
@@ -2152,7 +2594,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2152 if (OpenCallback) 2594 if (OpenCallback)
2153 { 2595 {
2154 const UInt64 numFiles = ProgressVal_NumFilesTotal + numApfsItems; 2596 const UInt64 numFiles = ProgressVal_NumFilesTotal + numApfsItems;
2155 RINOK(OpenCallback->SetTotal(&numFiles, NULL)); 2597 RINOK(OpenCallback->SetTotal(&numFiles, NULL))
2156 } 2598 }
2157 } 2599 }
2158 2600
@@ -2165,7 +2607,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2165 { 2607 {
2166 const UInt64 numFiles = ProgressVal_NumFilesTotal + 2608 const UInt64 numFiles = ProgressVal_NumFilesTotal +
2167 (vol.Items.Size() + vol.Nodes.Size()) / 2; 2609 (vol.Items.Size() + vol.Nodes.Size()) / 2;
2168 RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur)); 2610 RINOK(OpenCallback->SetCompleted(&numFiles, &ProgressVal_Cur))
2169 } 2611 }
2170 2612
2171 const CKeyValPair &pair = map.Pairs[i]; 2613 const CKeyValPair &pair = map.Pairs[i];
@@ -2180,11 +2622,11 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2180 return S_FALSE; // IDs must be sorted 2622 return S_FALSE; // IDs must be sorted
2181 prevId = id; 2623 prevId = id;
2182 2624
2183 PRF(printf("\n%6d: id=%6d type = %2d", i, (unsigned)id, type)); 2625 PRF(printf("\n%6d: id=%6d type = %2d ", i, (unsigned)id, type));
2184 2626
2185 if (type == APFS_TYPE_INODE) 2627 if (type == APFS_TYPE_INODE)
2186 { 2628 {
2187 PRF(printf (" INODE")); 2629 PRF(printf("INODE"));
2188 if (pair.Key.Size() != 8 || 2630 if (pair.Key.Size() != 8 ||
2189 pair.Val.Size() < k_SizeOf_j_inode_val) 2631 pair.Val.Size() < k_SizeOf_j_inode_val)
2190 return S_FALSE; 2632 return S_FALSE;
@@ -2224,6 +2666,9 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2224 UInt32 offset = 4 + (UInt32)xf_num_exts * 4; 2666 UInt32 offset = 4 + (UInt32)xf_num_exts * 4;
2225 if (offset + xf_used_data != extraSize) 2667 if (offset + xf_used_data != extraSize)
2226 return S_FALSE; 2668 return S_FALSE;
2669
2670 PRF(printf(" parent_id = %d", (unsigned)inode.parent_id));
2671
2227 for (unsigned k = 0; k < xf_num_exts; k++) 2672 for (unsigned k = 0; k < xf_num_exts; k++)
2228 { 2673 {
2229 // struct x_field 2674 // struct x_field
@@ -2336,7 +2781,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2336 attr.Id = Get64(p4); 2781 attr.Id = Get64(p4);
2337 attr.dstream.Parse(p4 + 8); 2782 attr.dstream.Parse(p4 + 8);
2338 attr.dstream_defined = true; 2783 attr.dstream_defined = true;
2339 PRF(printf(" streamID=%d", (unsigned)attr.Id)); 2784 PRF(printf(" streamID=%d streamSize=%d", (unsigned)attr.Id, (unsigned)attr.dstream.size));
2340 } 2785 }
2341 else 2786 else
2342 { 2787 {
@@ -2386,7 +2831,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2386 const UInt32 refcnt = Get32(pair.Val); 2831 const UInt32 refcnt = Get32(pair.Val);
2387 2832
2388 // The data stream record can be deleted when its reference count reaches zero. 2833 // The data stream record can be deleted when its reference count reaches zero.
2389 PRF(printf(" refcnt = %8d", (unsigned)refcnt)); 2834 PRF(printf(" refcnt = %d", (unsigned)refcnt));
2390 2835
2391 if (vol.NodeIDs.IsEmpty()) 2836 if (vol.NodeIDs.IsEmpty())
2392 return S_FALSE; 2837 return S_FALSE;
@@ -2407,6 +2852,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2407 inode.refcnt_defined = true; 2852 inode.refcnt_defined = true;
2408 if (inode.refcnt != (UInt32)inode.nlink) 2853 if (inode.refcnt != (UInt32)inode.nlink)
2409 { 2854 {
2855 PRF(printf(" refcnt != nlink"));
2410 // is it possible ? 2856 // is it possible ?
2411 // return S_FALSE; 2857 // return S_FALSE;
2412 } 2858 }
@@ -2536,13 +2982,138 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2536 if (id == PRIV_DIR_INO_NUM) 2982 if (id == PRIV_DIR_INO_NUM)
2537 vol.NumItems_In_PrivateDir++; 2983 vol.NumItems_In_PrivateDir++;
2538 2984
2539 PRF(printf(" next=%6d flags=%2x %s", 2985 PRF(printf(" DIR_REC next=%6d flags=%2x %s",
2540 (unsigned)item.Val.file_id, 2986 (unsigned)item.Val.file_id,
2541 (unsigned)item.Val.flags, 2987 (unsigned)item.Val.flags,
2542 item.Name.Ptr())); 2988 item.Name.Ptr()));
2543 continue; 2989 continue;
2544 } 2990 }
2545 2991
2992 if (type == APFS_TYPE_FILE_INFO)
2993 {
2994 if (pair.Key.Size() != 16)
2995 return S_FALSE;
2996 // j_file_info_key
2997 const UInt64 info_and_lba = Get64(p + 8);
2998
2999 #define J_FILE_INFO_LBA_MASK 0x00ffffffffffffffUL
3000 // #define J_FILE_INFO_TYPE_MASK 0xff00000000000000UL
3001 #define J_FILE_INFO_TYPE_SHIFT 56
3002 #define APFS_FILE_INFO_DATA_HASH 1
3003
3004 const unsigned infoType = (unsigned)(info_and_lba >> J_FILE_INFO_TYPE_SHIFT);
3005 // address is a paddr_t
3006 const UInt64 lba = info_and_lba & J_FILE_INFO_LBA_MASK;
3007 // j_file_data_hash_val_t
3008 /* Use this field of the union if the type stored in the info_and_lba field of j_file_info_val_t is
3009 APFS_FILE_INFO_DATA_HASH */
3010 if (infoType != APFS_FILE_INFO_DATA_HASH)
3011 return S_FALSE;
3012 if (pair.Val.Size() != 3 + vol.integrity.HashSize)
3013 return S_FALSE;
3014 /*
3015 struct j_file_data_hash_val
3016 {
3017 UInt16 hashed_len; // The length, in blocks, of the data segment that was hashed.
3018 UInt8 hash_size; // must be consistent with integrity_meta_phys_t::im_hash_type
3019 UInt8 hash[0];
3020 }
3021 */
3022
3023 const unsigned hash_size = pair.Val[2];
3024 if (hash_size != vol.integrity.HashSize)
3025 return S_FALSE;
3026
3027 CHashChunk hr;
3028 hr.hashed_len = GetUi16(pair.Val);
3029 if (hr.hashed_len == 0)
3030 return S_FALSE;
3031 memcpy(hr.hash, (const Byte *)pair.Val + 3, vol.integrity.HashSize);
3032 // (hashed_len <= 4) : we have seen
3033 hr.lba = lba;
3034
3035 PRF(printf(" FILE_INFO lba = %6x, hashed_len=%6d",
3036 (unsigned)lba,
3037 (unsigned)hr.hashed_len));
3038
3039 if (vol.Hash_IDs.IsEmpty() || vol.Hash_IDs.Back() != id)
3040 {
3041 vol.Hash_Vectors.AddNew();
3042 vol.Hash_IDs.Add(id);
3043 }
3044 CStreamHashes &hashes = vol.Hash_Vectors.Back();
3045 if (hashes.Size() != 0)
3046 {
3047 const CHashChunk &hr_Back = hashes.Back();
3048 if (lba != hr_Back.lba + ((UInt64)hr_Back.hashed_len << sb.block_size_Log))
3049 return S_FALSE;
3050 }
3051 hashes.Add(hr);
3052 continue;
3053 }
3054
3055 if (type == APFS_TYPE_SNAP_METADATA)
3056 {
3057 if (pair.Key.Size() != 8)
3058 return S_FALSE;
3059 PRF(printf(" SNAP_METADATA"));
3060 // continue;
3061 }
3062
3063 /* SIBLING items are used, if there are more than one hard link to some inode
3064 key : value
3065 parent_id_1 DIR_REC : inode_id, name_1
3066 parent_id_2 DIR_REC : inode_id, name_2
3067 inode_id INODE : parent_id_1, name_1
3068 inode_id SIBLING_LINK sibling_id_1 : parent_id_1, name_1
3069 inode_id SIBLING_LINK sibling_id_2 : parent_id_2, name_2
3070 sibling_id_1 SIBLING_MAP : inode_id
3071 sibling_id_2 SIBLING_MAP : inode_id
3072 */
3073
3074 if (type == APFS_TYPE_SIBLING_LINK)
3075 {
3076 if (pair.Key.Size() != 16)
3077 return S_FALSE;
3078 if (pair.Val.Size() < 10 + 1)
3079 return S_FALSE;
3080 /*
3081 // struct j_sibling_key
3082 // The sibling's unique identifier.
3083 // This value matches the object identifier for the sibling map record
3084 const UInt64 sibling_id = Get64(p + 8);
3085 // struct j_sibling_val
3086 const Byte *v = pair.Val;
3087 const UInt64 parent_id = Get64(v); // The object identifier for the inode that's the parent directory.
3088 const unsigned name_len = Get16(v + 8); // len including the final null character
3089 if (10 + name_len != pair.Val.Size())
3090 return S_FALSE;
3091 if (v[10 + name_len - 1] != 0)
3092 return S_FALSE;
3093 AString name ((const char *)(v + 10));
3094 if (name.Len() != name_len - 1)
3095 return S_FALSE;
3096 PRF(printf(" SIBLING_LINK sibling_id = %6d : parent_id=%6d %s",
3097 (unsigned)sibling_id, (unsigned)parent_id, name.Ptr()));
3098 */
3099 continue;
3100 }
3101
3102 if (type == APFS_TYPE_SIBLING_MAP)
3103 {
3104 // struct j_sibling_map_key
3105 // The object identifier in the header is the sibling's unique identifier
3106 if (pair.Key.Size() != 8 || pair.Val.Size() != 8)
3107 return S_FALSE;
3108 /*
3109 // j_sibling_map_val
3110 // The inode number of the underlying file
3111 const UInt64 file_id = Get64(pair.Val);
3112 PRF(printf(" SIBLING_MAP : file_id = %d", (unsigned)file_id));
3113 */
3114 continue;
3115 }
3116
2546 UnsupportedFeature = true; 3117 UnsupportedFeature = true;
2547 // return S_FALSE; 3118 // return S_FALSE;
2548 } 3119 }
@@ -2596,7 +3167,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2596 3167
2597 RINOK(OpenCallback->SetCompleted( 3168 RINOK(OpenCallback->SetCompleted(
2598 &ProgressVal_NumFilesTotal, 3169 &ProgressVal_NumFilesTotal,
2599 &ProgressVal_Cur)); 3170 &ProgressVal_Cur))
2600 ProgressVal_Prev = ProgressVal_Cur; 3171 ProgressVal_Prev = ProgressVal_Cur;
2601 } 3172 }
2602 } 3173 }
@@ -2623,7 +3194,7 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2623 } 3194 }
2624 else 3195 else
2625 { 3196 {
2626 vol.UnsupportedFeature = true; 3197 vol.UnsupportedMethod = true;
2627 } 3198 }
2628 } 3199 }
2629 } 3200 }
@@ -2635,6 +3206,8 @@ HRESULT CDatabase::OpenVolume(const CObjectMap &omap, const oid_t fs_oid)
2635 HeadersError = true; 3206 HeadersError = true;
2636 if (vol.UnsupportedFeature) 3207 if (vol.UnsupportedFeature)
2637 UnsupportedFeature = true; 3208 UnsupportedFeature = true;
3209 if (vol.UnsupportedMethod)
3210 UnsupportedMethod = true;
2638 if (vol.NumAltStreams != 0) 3211 if (vol.NumAltStreams != 0)
2639 ThereAreAltStreams = true; 3212 ThereAreAltStreams = true;
2640 3213
@@ -2863,38 +3436,39 @@ HRESULT CVol::FillRefs()
2863 3436
2864 3437
2865 3438
2866class CHandler: 3439Z7_class_CHandler_final:
2867 public IInArchive, 3440 public IInArchive,
2868 public IArchiveGetRawProps, 3441 public IArchiveGetRawProps,
2869 public IInArchiveGetStream, 3442 public IInArchiveGetStream,
2870 public CMyUnknownImp, 3443 public CMyUnknownImp,
2871 public CDatabase 3444 public CDatabase
2872{ 3445{
3446 Z7_IFACES_IMP_UNK_3(
3447 IInArchive,
3448 IArchiveGetRawProps,
3449 IInArchiveGetStream)
3450
2873 CMyComPtr<IInStream> _stream; 3451 CMyComPtr<IInStream> _stream;
2874public: 3452 int FindHashIndex_for_Item(UInt32 index);
2875 MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream)
2876 INTERFACE_IInArchive(;)
2877 INTERFACE_IArchiveGetRawProps(;)
2878 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
2879}; 3453};
2880 3454
2881 3455
2882STDMETHODIMP CHandler::Open(IInStream *inStream, 3456Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
2883 const UInt64 * /* maxCheckStartPosition */, 3457 const UInt64 * /* maxCheckStartPosition */,
2884 IArchiveOpenCallback *callback) 3458 IArchiveOpenCallback *callback))
2885{ 3459{
2886 COM_TRY_BEGIN 3460 COM_TRY_BEGIN
2887 Close(); 3461 Close();
2888 OpenInStream = inStream; 3462 OpenInStream = inStream;
2889 OpenCallback = callback; 3463 OpenCallback = callback;
2890 RINOK(Open2()); 3464 RINOK(Open2())
2891 _stream = inStream; 3465 _stream = inStream;
2892 return S_OK; 3466 return S_OK;
2893 COM_TRY_END 3467 COM_TRY_END
2894} 3468}
2895 3469
2896 3470
2897STDMETHODIMP CHandler::Close() 3471Z7_COM7F_IMF(CHandler::Close())
2898{ 3472{
2899 _stream.Release(); 3473 _stream.Release();
2900 Clear(); 3474 Clear();
@@ -2971,7 +3545,7 @@ static void ApfsTimeToProp(UInt64 hfsTime, NWindows::NCOM::CPropVariant &prop)
2971} 3545}
2972 3546
2973 3547
2974STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 3548Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
2975{ 3549{
2976 COM_TRY_BEGIN 3550 COM_TRY_BEGIN
2977 NWindows::NCOM::CPropVariant prop; 3551 NWindows::NCOM::CPropVariant prop;
@@ -3006,6 +3580,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
3006 { 3580 {
3007 UInt32 flags = 0; 3581 UInt32 flags = 0;
3008 if (UnsupportedFeature) flags |= kpv_ErrorFlags_UnsupportedFeature; 3582 if (UnsupportedFeature) flags |= kpv_ErrorFlags_UnsupportedFeature;
3583 if (UnsupportedMethod) flags |= kpv_ErrorFlags_UnsupportedMethod;
3009 if (flags != 0) 3584 if (flags != 0)
3010 prop = flags; 3585 prop = flags;
3011 break; 3586 break;
@@ -3068,14 +3643,14 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
3068} 3643}
3069 3644
3070 3645
3071STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 3646Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
3072{ 3647{
3073 *numProps = 0; 3648 *numProps = 0;
3074 return S_OK; 3649 return S_OK;
3075} 3650}
3076 3651
3077 3652
3078STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 3653Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
3079{ 3654{
3080 *name = NULL; 3655 *name = NULL;
3081 *propID = 0; 3656 *propID = 0;
@@ -3083,7 +3658,7 @@ STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *pr
3083} 3658}
3084 3659
3085 3660
3086STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 3661Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
3087{ 3662{
3088 *parentType = NParentType::kDir; 3663 *parentType = NParentType::kDir;
3089 3664
@@ -3109,13 +3684,13 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
3109} 3684}
3110 3685
3111 3686
3112STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 3687Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
3113{ 3688{
3114 *data = NULL; 3689 *data = NULL;
3115 *dataSize = 0; 3690 *dataSize = 0;
3116 *propType = 0; 3691 *propType = 0;
3117 UNUSED_VAR(index); 3692 UNUSED_VAR(index)
3118 UNUSED_VAR(propID); 3693 UNUSED_VAR(propID)
3119 return S_OK; 3694 return S_OK;
3120} 3695}
3121 3696
@@ -3133,7 +3708,7 @@ static void AddNodeName(UString &s, const CNode &inode, UInt64 id)
3133 s.Add_UInt64(id); 3708 s.Add_UInt64(id);
3134 if (!inode.PrimaryName.IsEmpty()) 3709 if (!inode.PrimaryName.IsEmpty())
3135 { 3710 {
3136 s += '.'; 3711 s.Add_Dot();
3137 UString s2; 3712 UString s2;
3138 Utf8Name_to_InterName(inode.PrimaryName, s2); 3713 Utf8Name_to_InterName(inode.PrimaryName, s2);
3139 s += s2; 3714 s += s2;
@@ -3204,7 +3779,7 @@ void CDatabase::GetItemPath(unsigned index, const CNode *inode, NWindows::NCOM::
3204 3779
3205 3780
3206 3781
3207STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 3782Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
3208{ 3783{
3209 COM_TRY_BEGIN 3784 COM_TRY_BEGIN
3210 NWindows::NCOM::CPropVariant prop; 3785 NWindows::NCOM::CPropVariant prop;
@@ -3509,8 +4084,8 @@ UInt64 CDatabase::GetSize(const UInt32 index) const
3509} 4084}
3510 4085
3511 4086
3512STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 4087Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3513 Int32 testMode, IArchiveExtractCallback *extractCallback) 4088 Int32 testMode, IArchiveExtractCallback *extractCallback))
3514{ 4089{
3515 COM_TRY_BEGIN 4090 COM_TRY_BEGIN
3516 const bool allFilesMode = (numItems == (UInt32)(Int32)-1); 4091 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
@@ -3527,7 +4102,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3527 const UInt32 index = allFilesMode ? i : indices[i]; 4102 const UInt32 index = allFilesMode ? i : indices[i];
3528 totalSize += GetSize(index); 4103 totalSize += GetSize(index);
3529 } 4104 }
3530 RINOK(extractCallback->SetTotal(totalSize)); 4105 RINOK(extractCallback->SetTotal(totalSize))
3531 } 4106 }
3532 4107
3533 UInt64 currentTotalSize = 0, currentItemSize = 0; 4108 UInt64 currentTotalSize = 0, currentItemSize = 0;
@@ -3541,11 +4116,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3541 4116
3542 NHfs::CDecoder decoder; 4117 NHfs::CDecoder decoder;
3543 4118
3544 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) 4119 for (i = 0;; i++, currentTotalSize += currentItemSize)
3545 { 4120 {
3546 lps->InSize = currentTotalSize; 4121 lps->InSize = currentTotalSize;
3547 lps->OutSize = currentTotalSize; 4122 lps->OutSize = currentTotalSize;
3548 RINOK(lps->SetCur()); 4123 RINOK(lps->SetCur())
4124
4125 if (i >= numItems)
4126 break;
3549 4127
3550 const UInt32 index = allFilesMode ? i : indices[i]; 4128 const UInt32 index = allFilesMode ? i : indices[i];
3551 const CRef2 &ref2 = Refs2[index]; 4129 const CRef2 &ref2 = Refs2[index];
@@ -3558,12 +4136,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3558 const Int32 askMode = testMode ? 4136 const Int32 askMode = testMode ?
3559 NExtract::NAskMode::kTest : 4137 NExtract::NAskMode::kTest :
3560 NExtract::NAskMode::kExtract; 4138 NExtract::NAskMode::kExtract;
3561 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 4139 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
3562 4140
3563 if (IsViNotDef(ref2.RefIndex)) 4141 if (IsViNotDef(ref2.RefIndex))
3564 { 4142 {
3565 RINOK(extractCallback->PrepareOperation(askMode)); 4143 RINOK(extractCallback->PrepareOperation(askMode))
3566 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 4144 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
3567 continue; 4145 continue;
3568 } 4146 }
3569 4147
@@ -3580,13 +4158,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3580 4158
3581 if (isDir) 4159 if (isDir)
3582 { 4160 {
3583 RINOK(extractCallback->PrepareOperation(askMode)); 4161 RINOK(extractCallback->PrepareOperation(askMode))
3584 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 4162 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
3585 continue; 4163 continue;
3586 } 4164 }
3587 if (!testMode && !realOutStream) 4165 if (!testMode && !realOutStream)
3588 continue; 4166 continue;
3589 RINOK(extractCallback->PrepareOperation(askMode)); 4167 RINOK(extractCallback->PrepareOperation(askMode))
3590 int opRes = NExtract::NOperationResult::kDataError; 4168 int opRes = NExtract::NOperationResult::kDataError;
3591 4169
3592 if (IsViDef(ref.NodeIndex)) 4170 if (IsViDef(ref.NodeIndex))
@@ -3643,10 +4221,31 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3643 CMyComPtr<ISequentialInStream> inStream; 4221 CMyComPtr<ISequentialInStream> inStream;
3644 if (GetStream(index, &inStream) == S_OK && inStream) 4222 if (GetStream(index, &inStream) == S_OK && inStream)
3645 { 4223 {
3646 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 4224 COutStreamWithHash *hashStreamSpec = NULL;
4225 CMyComPtr<ISequentialOutStream> hashStream;
4226
4227 if (vol.integrity.Is_SHA256())
4228 {
4229 const int hashIndex = FindHashIndex_for_Item(index);
4230 if (hashIndex != -1)
4231 {
4232 hashStreamSpec = new COutStreamWithHash;
4233 hashStream = hashStreamSpec;
4234 hashStreamSpec->SetStream(realOutStream);
4235 hashStreamSpec->Init(&(vol.Hash_Vectors[(unsigned)hashIndex]), sb.block_size_Log);
4236 }
4237 }
4238
4239 RINOK(copyCoder->Code(inStream,
4240 hashStream ? hashStream : realOutStream, NULL, NULL, progress))
3647 opRes = NExtract::NOperationResult::kDataError; 4241 opRes = NExtract::NOperationResult::kDataError;
3648 if (copyCoderSpec->TotalSize == currentItemSize) 4242 if (copyCoderSpec->TotalSize == currentItemSize)
4243 {
3649 opRes = NExtract::NOperationResult::kOK; 4244 opRes = NExtract::NOperationResult::kOK;
4245 if (hashStream)
4246 if (!hashStreamSpec->FinalCheck())
4247 opRes = NExtract::NOperationResult::kCRCError;
4248 }
3650 else if (copyCoderSpec->TotalSize < currentItemSize) 4249 else if (copyCoderSpec->TotalSize < currentItemSize)
3651 opRes = NExtract::NOperationResult::kUnexpectedEnd; 4250 opRes = NExtract::NOperationResult::kUnexpectedEnd;
3652 } 4251 }
@@ -3654,21 +4253,61 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3654 } 4253 }
3655 4254
3656 realOutStream.Release(); 4255 realOutStream.Release();
3657 RINOK(extractCallback->SetOperationResult(opRes)); 4256 RINOK(extractCallback->SetOperationResult(opRes))
3658 } 4257 }
3659 return S_OK; 4258 return S_OK;
3660 COM_TRY_END 4259 COM_TRY_END
3661} 4260}
3662 4261
3663 4262
3664STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 4263Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
3665{ 4264{
3666 *numItems = Refs2.Size(); 4265 *numItems = Refs2.Size();
3667 return S_OK; 4266 return S_OK;
3668} 4267}
3669 4268
3670 4269
3671STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 4270int CHandler::FindHashIndex_for_Item(UInt32 index)
4271{
4272 const CRef2 &ref2 = Refs2[index];
4273 const CVol &vol = Vols[ref2.VolIndex];
4274 if (IsViNotDef(ref2.RefIndex))
4275 return -1;
4276
4277 const CRef &ref = vol.Refs[ref2.RefIndex];
4278 if (IsViNotDef(ref.NodeIndex))
4279 return -1;
4280 const CNode &inode = vol.Nodes[ref.NodeIndex];
4281
4282 unsigned attrIndex = ref.GetAttrIndex();
4283
4284 if (IsViNotDef(attrIndex)
4285 && !inode.dstream_defined
4286 && inode.IsSymLink())
4287 {
4288 attrIndex = inode.SymLinkIndex;
4289 if (IsViNotDef(attrIndex))
4290 return -1;
4291 }
4292
4293 if (IsViDef(attrIndex))
4294 {
4295 /* we have seen examples, where hash available for "com.apple.ResourceFork" stream.
4296 these hashes for "com.apple.ResourceFork" stream are for unpacked data.
4297 but the caller here needs packed data of stream. So we don't use hashes */
4298 return -1;
4299 }
4300 else
4301 {
4302 if (!inode.dstream_defined)
4303 return -1;
4304 const UInt64 id = vol.NodeIDs[ref.NodeIndex];
4305 return vol.Hash_IDs.FindInSorted(id);
4306 }
4307}
4308
4309
4310Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
3672{ 4311{
3673 *stream = NULL; 4312 *stream = NULL;
3674 4313
@@ -3708,9 +4347,15 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
3708 return S_OK; 4347 return S_OK;
3709 } 4348 }
3710 const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id); 4349 const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id);
3711 if (idIndex == -1) 4350 if (idIndex != -1)
3712 return S_FALSE; 4351 extents = &vol.SmallNodes[(unsigned)idIndex].Extents;
3713 extents = &vol.SmallNodes[(unsigned)idIndex].Extents; 4352 else
4353 {
4354 const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(attr.Id);
4355 if (fext_Index == -1)
4356 return S_FALSE;
4357 extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents;
4358 }
3714 rem = attr.dstream.size; 4359 rem = attr.dstream.size;
3715 } 4360 }
3716 else 4361 else
@@ -3720,16 +4365,21 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
3720 return S_FALSE; 4365 return S_FALSE;
3721 if (inode.IsDir()) 4366 if (inode.IsDir())
3722 return S_FALSE; 4367 return S_FALSE;
4368 extents = &inode.Extents;
3723 if (inode.dstream_defined) 4369 if (inode.dstream_defined)
3724 { 4370 {
3725 rem = inode.dstream.size; 4371 rem = inode.dstream.size;
4372 if (inode.Extents.Size() == 0)
4373 {
4374 const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(vol.NodeIDs[ref.NodeIndex]);
4375 if (fext_Index != -1)
4376 extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents;
4377 }
3726 } 4378 }
3727 else 4379 else
3728 { 4380 {
3729 // return S_FALSE; // check it !!! How zero size files are stored with dstream_defined? 4381 // return S_FALSE; // check it !!! How zero size files are stored with dstream_defined?
3730 } 4382 }
3731
3732 extents = &inode.Extents;
3733 } 4383 }
3734 return GetStream2(_stream, extents, rem, stream); 4384 return GetStream2(_stream, extents, rem, stream);
3735} 4385}
@@ -3755,13 +4405,20 @@ HRESULT CDatabase::GetAttrStream(IInStream *apfsInStream, const CVol &vol,
3755HRESULT CDatabase::GetAttrStream_dstream( IInStream *apfsInStream, const CVol &vol, 4405HRESULT CDatabase::GetAttrStream_dstream( IInStream *apfsInStream, const CVol &vol,
3756 const CAttr &attr, ISequentialInStream **stream) 4406 const CAttr &attr, ISequentialInStream **stream)
3757{ 4407{
3758 const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id); 4408 const CRecordVector<CExtent> *extents;
3759 if (idIndex == -1) 4409 {
3760 return S_FALSE; 4410 const int idIndex = vol.SmallNodeIDs.FindInSorted(attr.Id);
3761 return GetStream2(apfsInStream, 4411 if (idIndex != -1)
3762 &vol.SmallNodes[(unsigned)idIndex].Extents, 4412 extents = &vol.SmallNodes[(unsigned)idIndex].Extents;
3763 attr.dstream.size, 4413 else
3764 stream); 4414 {
4415 const int fext_Index = vol.FEXT_NodeIDs.FindInSorted(attr.Id);
4416 if (fext_Index == -1)
4417 return S_FALSE;
4418 extents = &vol.FEXT_Nodes[(unsigned)fext_Index].Extents;
4419 }
4420 }
4421 return GetStream2(apfsInStream, extents, attr.dstream.size, stream);
3765} 4422}
3766 4423
3767 4424
diff --git a/CPP/7zip/Archive/ApmHandler.cpp b/CPP/7zip/Archive/ApmHandler.cpp
index 73e5fcb..6770301 100644
--- a/CPP/7zip/Archive/ApmHandler.cpp
+++ b/CPP/7zip/Archive/ApmHandler.cpp
@@ -71,8 +71,10 @@ struct CItem
71 } 71 }
72}; 72};
73 73
74class CHandler: public CHandlerCont 74Z7_class_CHandler_final: public CHandlerCont
75{ 75{
76 Z7_IFACE_COM7_IMP(IInArchive_Cont)
77
76 CRecordVector<CItem> _items; 78 CRecordVector<CItem> _items;
77 unsigned _blockSizeLog; 79 unsigned _blockSizeLog;
78 UInt32 _numBlocks; 80 UInt32 _numBlocks;
@@ -82,16 +84,13 @@ class CHandler: public CHandlerCont
82 HRESULT ReadTables(IInStream *stream); 84 HRESULT ReadTables(IInStream *stream);
83 UInt64 BlocksToBytes(UInt32 i) const { return (UInt64)i << _blockSizeLog; } 85 UInt64 BlocksToBytes(UInt32 i) const { return (UInt64)i << _blockSizeLog; }
84 86
85 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const 87 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override
86 { 88 {
87 const CItem &item = _items[index]; 89 const CItem &item = _items[index];
88 pos = BlocksToBytes(item.StartBlock); 90 pos = BlocksToBytes(item.StartBlock);
89 size = BlocksToBytes(item.NumBlocks); 91 size = BlocksToBytes(item.NumBlocks);
90 return NExtract::NOperationResult::kOK; 92 return NExtract::NOperationResult::kOK;
91 } 93 }
92
93public:
94 INTERFACE_IInArchive_Cont(;)
95}; 94};
96 95
97static const UInt32 kSectorSize = 512; 96static const UInt32 kSectorSize = 512;
@@ -118,7 +117,7 @@ HRESULT CHandler::ReadTables(IInStream *stream)
118{ 117{
119 Byte buf[kSectorSize]; 118 Byte buf[kSectorSize];
120 { 119 {
121 RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); 120 RINOK(ReadStream_FALSE(stream, buf, kSectorSize))
122 if (buf[0] != kSig0 || buf[1] != kSig1) 121 if (buf[0] != kSig0 || buf[1] != kSig1)
123 return S_FALSE; 122 return S_FALSE;
124 UInt32 blockSize = Get16(buf + 2); 123 UInt32 blockSize = Get16(buf + 2);
@@ -136,14 +135,14 @@ HRESULT CHandler::ReadTables(IInStream *stream)
136 unsigned numSkips = (unsigned)1 << (_blockSizeLog - 9); 135 unsigned numSkips = (unsigned)1 << (_blockSizeLog - 9);
137 for (unsigned j = 1; j < numSkips; j++) 136 for (unsigned j = 1; j < numSkips; j++)
138 { 137 {
139 RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); 138 RINOK(ReadStream_FALSE(stream, buf, kSectorSize))
140 } 139 }
141 140
142 UInt32 numBlocksInMap = 0; 141 UInt32 numBlocksInMap = 0;
143 142
144 for (unsigned i = 0;;) 143 for (unsigned i = 0;;)
145 { 144 {
146 RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); 145 RINOK(ReadStream_FALSE(stream, buf, kSectorSize))
147 146
148 CItem item; 147 CItem item;
149 148
@@ -167,7 +166,7 @@ HRESULT CHandler::ReadTables(IInStream *stream)
167 _items.Add(item); 166 _items.Add(item);
168 for (unsigned j = 1; j < numSkips; j++) 167 for (unsigned j = 1; j < numSkips; j++)
169 { 168 {
170 RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); 169 RINOK(ReadStream_FALSE(stream, buf, kSectorSize))
171 } 170 }
172 if (++i == numBlocksInMap) 171 if (++i == numBlocksInMap)
173 break; 172 break;
@@ -178,17 +177,17 @@ HRESULT CHandler::ReadTables(IInStream *stream)
178 return S_OK; 177 return S_OK;
179} 178}
180 179
181STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */) 180Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */))
182{ 181{
183 COM_TRY_BEGIN 182 COM_TRY_BEGIN
184 Close(); 183 Close();
185 RINOK(ReadTables(stream)); 184 RINOK(ReadTables(stream))
186 _stream = stream; 185 _stream = stream;
187 return S_OK; 186 return S_OK;
188 COM_TRY_END 187 COM_TRY_END
189} 188}
190 189
191STDMETHODIMP CHandler::Close() 190Z7_COM7F_IMF(CHandler::Close())
192{ 191{
193 _isArc = false; 192 _isArc = false;
194 _phySize = 0; 193 _phySize = 0;
@@ -220,7 +219,7 @@ static AString GetString(const char *s)
220 return res; 219 return res;
221} 220}
222 221
223STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 222Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
224{ 223{
225 COM_TRY_BEGIN 224 COM_TRY_BEGIN
226 NCOM::CPropVariant prop; 225 NCOM::CPropVariant prop;
@@ -244,7 +243,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
244 } 243 }
245 } 244 }
246 if (mainIndex >= 0) 245 if (mainIndex >= 0)
247 prop = (UInt32)mainIndex; 246 prop = (UInt32)(Int32)mainIndex;
248 break; 247 break;
249 } 248 }
250 case kpidClusterSize: prop = (UInt32)1 << _blockSizeLog; break; 249 case kpidClusterSize: prop = (UInt32)1 << _blockSizeLog; break;
@@ -263,13 +262,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
263 COM_TRY_END 262 COM_TRY_END
264} 263}
265 264
266STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 265Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
267{ 266{
268 *numItems = _items.Size(); 267 *numItems = _items.Size();
269 return S_OK; 268 return S_OK;
270} 269}
271 270
272STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 271Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
273{ 272{
274 COM_TRY_BEGIN 273 COM_TRY_BEGIN
275 NCOM::CPropVariant prop; 274 NCOM::CPropVariant prop;
@@ -286,7 +285,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
286 type = "hfs"; 285 type = "hfs";
287 if (!type.IsEmpty()) 286 if (!type.IsEmpty())
288 { 287 {
289 s += '.'; 288 s.Add_Dot();
290 s += type; 289 s += type;
291 } 290 }
292 prop = s; 291 prop = s;
@@ -306,7 +305,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
306static const Byte k_Signature[] = { kSig0, kSig1 }; 305static const Byte k_Signature[] = { kSig0, kSig1 };
307 306
308REGISTER_ARC_I( 307REGISTER_ARC_I(
309 "APM", "apm", 0, 0xD4, 308 "APM", "apm", NULL, 0xD4,
310 k_Signature, 309 k_Signature,
311 0, 310 0,
312 0, 311 0,
diff --git a/CPP/7zip/Archive/ArHandler.cpp b/CPP/7zip/Archive/ArHandler.cpp
index 6cd72bb..07ecec6 100644
--- a/CPP/7zip/Archive/ArHandler.cpp
+++ b/CPP/7zip/Archive/ArHandler.cpp
@@ -56,10 +56,8 @@ BSD (Mac OS X) variant:
56*/ 56*/
57 57
58static const unsigned kSignatureLen = 8; 58static const unsigned kSignatureLen = 8;
59 59static const Byte kSignature[kSignatureLen] =
60#define SIGNATURE { '!', '<', 'a', 'r', 'c', 'h', '>', 0x0A } 60 { '!', '<', 'a', 'r', 'c', 'h', '>', 0x0A };
61
62static const Byte kSignature[kSignatureLen] = SIGNATURE;
63 61
64static const unsigned kNameSize = 16; 62static const unsigned kNameSize = 16;
65static const unsigned kTimeSize = 12; 63static const unsigned kTimeSize = 12;
@@ -136,16 +134,16 @@ public:
136 HRESULT Open(IInStream *inStream); 134 HRESULT Open(IInStream *inStream);
137 HRESULT SkipData(UInt64 dataSize) 135 HRESULT SkipData(UInt64 dataSize)
138 { 136 {
139 return m_Stream->Seek(dataSize + (dataSize & 1), STREAM_SEEK_CUR, &Position); 137 return m_Stream->Seek((Int64)(dataSize + (dataSize & 1)), STREAM_SEEK_CUR, &Position);
140 } 138 }
141}; 139};
142 140
143HRESULT CInArchive::Open(IInStream *inStream) 141HRESULT CInArchive::Open(IInStream *inStream)
144{ 142{
145 SubType = kSubType_None; 143 SubType = kSubType_None;
146 RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &Position)); 144 RINOK(InStream_GetPos(inStream, Position))
147 char signature[kSignatureLen]; 145 char signature[kSignatureLen];
148 RINOK(ReadStream_FALSE(inStream, signature, kSignatureLen)); 146 RINOK(ReadStream_FALSE(inStream, signature, kSignatureLen))
149 Position += kSignatureLen; 147 Position += kSignatureLen;
150 if (memcmp(signature, kSignature, kSignatureLen) != 0) 148 if (memcmp(signature, kSignature, kSignatureLen) != 0)
151 return S_FALSE; 149 return S_FALSE;
@@ -215,7 +213,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled)
215 size_t processedSize = sizeof(header); 213 size_t processedSize = sizeof(header);
216 item.HeaderPos = Position; 214 item.HeaderPos = Position;
217 item.HeaderSize = kHeaderSize; 215 item.HeaderSize = kHeaderSize;
218 RINOK(ReadStream(m_Stream, header, &processedSize)); 216 RINOK(ReadStream(m_Stream, header, &processedSize))
219 if (processedSize != sizeof(header)) 217 if (processedSize != sizeof(header))
220 return S_OK; 218 return S_OK;
221 if (header[kHeaderSize - 2] != 0x60 || 219 if (header[kHeaderSize - 2] != 0x60 ||
@@ -235,7 +233,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled)
235 cur[3] != 0) 233 cur[3] != 0)
236 { 234 {
237 // BSD variant 235 // BSD variant
238 RIF(DecimalToNumber32(cur + 3, kNameSize - 3 , longNameLen)); 236 RIF(DecimalToNumber32(cur + 3, kNameSize - 3 , longNameLen))
239 if (longNameLen >= (1 << 12)) 237 if (longNameLen >= (1 << 12))
240 longNameLen = 0; 238 longNameLen = 0;
241 } 239 }
@@ -247,11 +245,11 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled)
247 } 245 }
248 cur += kNameSize; 246 cur += kNameSize;
249 247
250 RIF(DecimalToNumber32(cur, kTimeSize, item.MTime)); cur += kTimeSize; 248 RIF(DecimalToNumber32(cur, kTimeSize, item.MTime)) cur += kTimeSize;
251 RIF(DecimalToNumber32(cur, kUserSize, item.User)); cur += kUserSize; 249 RIF(DecimalToNumber32(cur, kUserSize, item.User)) cur += kUserSize;
252 RIF(DecimalToNumber32(cur, kUserSize, item.Group)); cur += kUserSize; 250 RIF(DecimalToNumber32(cur, kUserSize, item.Group)) cur += kUserSize;
253 RIF(OctalToNumber32(cur, kModeSize, item.Mode)); cur += kModeSize; 251 RIF(OctalToNumber32(cur, kModeSize, item.Mode)) cur += kModeSize;
254 RIF(DecimalToNumber(cur, kSizeSize, item.Size)); cur += kSizeSize; 252 RIF(DecimalToNumber(cur, kSizeSize, item.Size)) cur += kSizeSize;
255 253
256 if (longNameLen != 0 && longNameLen <= item.Size) 254 if (longNameLen != 0 && longNameLen <= item.Size)
257 { 255 {
@@ -260,7 +258,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled)
260 char *s = item.Name.GetBuf(longNameLen); 258 char *s = item.Name.GetBuf(longNameLen);
261 HRESULT res = ReadStream(m_Stream, s, &processedSize); 259 HRESULT res = ReadStream(m_Stream, s, &processedSize);
262 item.Name.ReleaseBuf_CalcLen(longNameLen); 260 item.Name.ReleaseBuf_CalcLen(longNameLen);
263 RINOK(res); 261 RINOK(res)
264 if (processedSize != longNameLen) 262 if (processedSize != longNameLen)
265 return S_OK; 263 return S_OK;
266 item.Size -= longNameLen; 264 item.Size -= longNameLen;
@@ -272,11 +270,10 @@ HRESULT CInArchive::GetNextItem(CItem &item, bool &filled)
272 return S_OK; 270 return S_OK;
273} 271}
274 272
275class CHandler: 273
276 public IInArchive, 274Z7_CLASS_IMP_CHandler_IInArchive_1(
277 public IInArchiveGetStream, 275 IInArchiveGetStream
278 public CMyUnknownImp 276)
279{
280 CObjectVector<CItem> _items; 277 CObjectVector<CItem> _items;
281 CMyComPtr<IInStream> _stream; 278 CMyComPtr<IInStream> _stream;
282 Int32 _mainSubfile; 279 Int32 _mainSubfile;
@@ -289,7 +286,6 @@ class CHandler:
289 unsigned _numLibFiles; 286 unsigned _numLibFiles;
290 AString _errorMessage; 287 AString _errorMessage;
291 bool _isArc; 288 bool _isArc;
292
293 289
294 void UpdateErrorMessage(const char *s); 290 void UpdateErrorMessage(const char *s);
295 291
@@ -298,10 +294,6 @@ class CHandler:
298 int FindItem(UInt32 offset) const; 294 int FindItem(UInt32 offset) const;
299 HRESULT AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos); 295 HRESULT AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos);
300 HRESULT ParseLibSymbols(IInStream *stream, unsigned fileIndex); 296 HRESULT ParseLibSymbols(IInStream *stream, unsigned fileIndex);
301public:
302 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
303 INTERFACE_IInArchive(;)
304 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
305}; 297};
306 298
307void CHandler::UpdateErrorMessage(const char *s) 299void CHandler::UpdateErrorMessage(const char *s)
@@ -342,11 +334,11 @@ HRESULT CHandler::ParseLongNames(IInStream *stream)
342 const CItem &item = _items[fileIndex]; 334 const CItem &item = _items[fileIndex];
343 if (item.Size > ((UInt32)1 << 30)) 335 if (item.Size > ((UInt32)1 << 30))
344 return S_FALSE; 336 return S_FALSE;
345 RINOK(stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); 337 RINOK(InStream_SeekSet(stream, item.GetDataPos()))
346 const size_t size = (size_t)item.Size; 338 const size_t size = (size_t)item.Size;
347 339
348 CByteArr p(size); 340 CByteArr p(size);
349 RINOK(ReadStream_FALSE(stream, p, size)); 341 RINOK(ReadStream_FALSE(stream, p, size))
350 342
351 for (i = 0; i < _items.Size(); i++) 343 for (i = 0; i < _items.Size(); i++)
352 { 344 {
@@ -365,15 +357,15 @@ HRESULT CHandler::ParseLongNames(IInStream *stream)
365 { 357 {
366 if (pos >= size) 358 if (pos >= size)
367 return S_FALSE; 359 return S_FALSE;
368 char c = p[pos]; 360 const Byte c = p[pos];
369 if (c == 0 || c == 0x0A) 361 if (c == 0 || c == 0x0A)
370 break; 362 break;
371 pos++; 363 pos++;
372 } 364 }
373 item2.Name.SetFrom((const char *)(p + start), pos - start); 365 item2.Name.SetFrom((const char *)(p + start), (unsigned)(pos - start));
374 } 366 }
375 367
376 _longNames_FileIndex = fileIndex; 368 _longNames_FileIndex = (int)fileIndex;
377 return S_OK; 369 return S_OK;
378} 370}
379 371
@@ -399,7 +391,7 @@ void CHandler::ChangeDuplicateNames()
399 if (item.SameNameIndex < 0) 391 if (item.SameNameIndex < 0)
400 continue; 392 continue;
401 char sz[32]; 393 char sz[32];
402 ConvertUInt32ToString(item.SameNameIndex + 1, sz); 394 ConvertUInt32ToString((unsigned)item.SameNameIndex + 1, sz);
403 unsigned len = MyStringLen(sz); 395 unsigned len = MyStringLen(sz);
404 sz[len++] = '.'; 396 sz[len++] = '.';
405 sz[len] = 0; 397 sz[len] = 0;
@@ -412,10 +404,10 @@ int CHandler::FindItem(UInt32 offset) const
412 unsigned left = 0, right = _items.Size(); 404 unsigned left = 0, right = _items.Size();
413 while (left != right) 405 while (left != right)
414 { 406 {
415 unsigned mid = (left + right) / 2; 407 const unsigned mid = (left + right) / 2;
416 UInt64 midVal = _items[mid].HeaderPos; 408 const UInt64 midVal = _items[mid].HeaderPos;
417 if (offset == midVal) 409 if (offset == midVal)
418 return mid; 410 return (int)mid;
419 if (offset < midVal) 411 if (offset < midVal)
420 right = mid; 412 right = mid;
421 else 413 else
@@ -426,7 +418,7 @@ int CHandler::FindItem(UInt32 offset) const
426 418
427HRESULT CHandler::AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos) 419HRESULT CHandler::AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &pos)
428{ 420{
429 int fileIndex = FindItem(offset); 421 const int fileIndex = FindItem(offset);
430 if (fileIndex < (int)0) 422 if (fileIndex < (int)0)
431 return S_FALSE; 423 return S_FALSE;
432 424
@@ -439,7 +431,7 @@ HRESULT CHandler::AddFunc(UInt32 offset, const Byte *data, size_t size, size_t &
439 while (data[i++] != 0); 431 while (data[i++] != 0);
440 432
441 AString &s = _libFiles[_numLibFiles]; 433 AString &s = _libFiles[_numLibFiles];
442 const AString &name = _items[fileIndex].Name; 434 const AString &name = _items[(unsigned)fileIndex].Name;
443 s += name; 435 s += name;
444 if (!name.IsEmpty() && name.Back() == '/') 436 if (!name.IsEmpty() && name.Back() == '/')
445 s.DeleteBack(); 437 s.DeleteBack();
@@ -463,35 +455,35 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex)
463 if (item.Size > ((UInt32)1 << 30) || 455 if (item.Size > ((UInt32)1 << 30) ||
464 item.Size < 4) 456 item.Size < 4)
465 return S_OK; 457 return S_OK;
466 RINOK(stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); 458 RINOK(InStream_SeekSet(stream, item.GetDataPos()))
467 size_t size = (size_t)item.Size; 459 size_t size = (size_t)item.Size;
468 CByteArr p(size); 460 CByteArr p(size);
469 RINOK(ReadStream_FALSE(stream, p, size)); 461 RINOK(ReadStream_FALSE(stream, p, size))
470 462
471 size_t pos = 0; 463 size_t pos = 0;
472 464
473 if (item.Name != "/") 465 if (item.Name != "/")
474 { 466 {
475 // __.SYMDEF parsing (BSD) 467 // "__.SYMDEF" parsing (BSD)
476 unsigned be; 468 unsigned be;
477 for (be = 0; be < 2; be++) 469 for (be = 0; be < 2; be++)
478 { 470 {
479 UInt32 tableSize = Get32(p, be); 471 const UInt32 tableSize = Get32(p, be);
480 pos = 4; 472 pos = 4;
481 if (size - pos < tableSize || (tableSize & 7) != 0) 473 if (size - pos < tableSize || (tableSize & 7) != 0)
482 continue; 474 continue;
483 size_t namesStart = pos + tableSize; 475 size_t namesStart = pos + tableSize;
484 UInt32 namesSize = Get32(p + namesStart, be); 476 const UInt32 namesSize = Get32(p + namesStart, be);
485 namesStart += 4; 477 namesStart += 4;
486 if (namesStart > size || namesStart + namesSize != size) 478 if (namesStart > size || namesStart + namesSize != size)
487 continue; 479 continue;
488 480
489 UInt32 numSymbols = tableSize >> 3; 481 const UInt32 numSymbols = tableSize >> 3;
490 UInt32 i; 482 UInt32 i;
491 for (i = 0; i < numSymbols; i++, pos += 8) 483 for (i = 0; i < numSymbols; i++, pos += 8)
492 { 484 {
493 size_t namePos = Get32(p + pos, be); 485 size_t namePos = Get32(p + pos, be);
494 UInt32 offset = Get32(p + pos + 4, be); 486 const UInt32 offset = Get32(p + pos + 4, be);
495 if (AddFunc(offset, p + namesStart, namesSize, namePos) != S_OK) 487 if (AddFunc(offset, p + namesStart, namesSize, namePos) != S_OK)
496 break; 488 break;
497 } 489 }
@@ -509,7 +501,7 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex)
509 else if (_numLibFiles == 0) 501 else if (_numLibFiles == 0)
510 { 502 {
511 // archive symbol table (GNU) 503 // archive symbol table (GNU)
512 UInt32 numSymbols = GetBe32(p); 504 const UInt32 numSymbols = GetBe32(p);
513 pos = 4; 505 pos = 4;
514 if (numSymbols > (size - pos) / 4) 506 if (numSymbols > (size - pos) / 4)
515 return S_FALSE; 507 return S_FALSE;
@@ -517,15 +509,15 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex)
517 509
518 for (UInt32 i = 0; i < numSymbols; i++) 510 for (UInt32 i = 0; i < numSymbols; i++)
519 { 511 {
520 UInt32 offset = GetBe32(p + 4 + i * 4); 512 const UInt32 offset = GetBe32(p + 4 + i * 4);
521 RINOK(AddFunc(offset, p, size, pos)); 513 RINOK(AddFunc(offset, p, size, pos))
522 } 514 }
523 _type = kType_ALib; 515 _type = kType_ALib;
524 } 516 }
525 else 517 else
526 { 518 {
527 // Second linker file (Microsoft .lib) 519 // Second linker file (Microsoft .lib)
528 UInt32 numMembers = GetUi32(p); 520 const UInt32 numMembers = GetUi32(p);
529 pos = 4; 521 pos = 4;
530 if (numMembers > (size - pos) / 4) 522 if (numMembers > (size - pos) / 4)
531 return S_FALSE; 523 return S_FALSE;
@@ -533,7 +525,7 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex)
533 525
534 if (size - pos < 4) 526 if (size - pos < 4)
535 return S_FALSE; 527 return S_FALSE;
536 UInt32 numSymbols = GetUi32(p + pos); 528 const UInt32 numSymbols = GetUi32(p + pos);
537 pos += 4; 529 pos += 4;
538 if (numSymbols > (size - pos) / 2) 530 if (numSymbols > (size - pos) / 2)
539 return S_FALSE; 531 return S_FALSE;
@@ -543,48 +535,47 @@ HRESULT CHandler::ParseLibSymbols(IInStream *stream, unsigned fileIndex)
543 for (UInt32 i = 0; i < numSymbols; i++) 535 for (UInt32 i = 0; i < numSymbols; i++)
544 { 536 {
545 // index is 1-based. So 32-bit numSymbols field works as item[0] 537 // index is 1-based. So 32-bit numSymbols field works as item[0]
546 UInt32 index = GetUi16(p + indexStart + i * 2); 538 const UInt32 index = GetUi16(p + indexStart + i * 2);
547 if (index == 0 || index > numMembers) 539 if (index == 0 || index > numMembers)
548 return S_FALSE; 540 return S_FALSE;
549 UInt32 offset = GetUi32(p + index * 4); 541 const UInt32 offset = GetUi32(p + index * 4);
550 RINOK(AddFunc(offset, p, size, pos)); 542 RINOK(AddFunc(offset, p, size, pos))
551 } 543 }
552 _type = kType_Lib; 544 _type = kType_Lib;
553 } 545 }
554 // size can be 2-byte aligned in linux files 546 // size can be 2-byte aligned in linux files
555 if (pos != size && pos + (pos & 1) != size) 547 if (pos != size && pos + (pos & 1) != size)
556 return S_FALSE; 548 return S_FALSE;
557 item.TextFileIndex = _numLibFiles++; 549 item.TextFileIndex = (int)(_numLibFiles++);
558 return S_OK; 550 return S_OK;
559} 551}
560 552
561STDMETHODIMP CHandler::Open(IInStream *stream, 553Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
562 const UInt64 * /* maxCheckStartPosition */, 554 const UInt64 * /* maxCheckStartPosition */,
563 IArchiveOpenCallback *callback) 555 IArchiveOpenCallback *callback))
564{ 556{
565 COM_TRY_BEGIN 557 COM_TRY_BEGIN
566 { 558 {
567 Close(); 559 Close();
568 560
569 UInt64 fileSize = 0; 561 UInt64 fileSize;
570 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); 562 RINOK(InStream_AtBegin_GetSize(stream, fileSize))
571 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
572 563
573 CInArchive arc; 564 CInArchive arc;
574 RINOK(arc.Open(stream)); 565 RINOK(arc.Open(stream))
575 566
576 if (callback) 567 if (callback)
577 { 568 {
578 RINOK(callback->SetTotal(NULL, &fileSize)); 569 RINOK(callback->SetTotal(NULL, &fileSize))
579 UInt64 numFiles = _items.Size(); 570 const UInt64 numFiles = _items.Size();
580 RINOK(callback->SetCompleted(&numFiles, &arc.Position)); 571 RINOK(callback->SetCompleted(&numFiles, &arc.Position))
581 } 572 }
582 573
583 CItem item; 574 CItem item;
584 for (;;) 575 for (;;)
585 { 576 {
586 bool filled; 577 bool filled;
587 RINOK(arc.GetNextItem(item, filled)); 578 RINOK(arc.GetNextItem(item, filled))
588 if (!filled) 579 if (!filled)
589 break; 580 break;
590 _items.Add(item); 581 _items.Add(item);
@@ -592,7 +583,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
592 if (callback && (_items.Size() & 0xFF) == 0) 583 if (callback && (_items.Size() & 0xFF) == 0)
593 { 584 {
594 UInt64 numFiles = _items.Size(); 585 UInt64 numFiles = _items.Size();
595 RINOK(callback->SetCompleted(&numFiles, &arc.Position)); 586 RINOK(callback->SetCompleted(&numFiles, &arc.Position))
596 } 587 }
597 } 588 }
598 589
@@ -610,7 +601,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
610 if (ParseLongNames(stream) != S_OK) 601 if (ParseLongNames(stream) != S_OK)
611 UpdateErrorMessage("Long file names parsing error"); 602 UpdateErrorMessage("Long file names parsing error");
612 if (_longNames_FileIndex >= 0) 603 if (_longNames_FileIndex >= 0)
613 _items.Delete(_longNames_FileIndex); 604 _items.Delete((unsigned)_longNames_FileIndex);
614 605
615 if (!_items.IsEmpty() && _items[0].Name == "debian-binary") 606 if (!_items.IsEmpty() && _items[0].Name == "debian-binary")
616 { 607 {
@@ -651,7 +642,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
651 COM_TRY_END 642 COM_TRY_END
652} 643}
653 644
654STDMETHODIMP CHandler::Close() 645Z7_COM7F_IMF(CHandler::Close())
655{ 646{
656 _isArc = false; 647 _isArc = false;
657 _phySize = 0; 648 _phySize = 0;
@@ -672,13 +663,13 @@ STDMETHODIMP CHandler::Close()
672 return S_OK; 663 return S_OK;
673} 664}
674 665
675STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 666Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
676{ 667{
677 *numItems = _items.Size(); 668 *numItems = _items.Size();
678 return S_OK; 669 return S_OK;
679} 670}
680 671
681STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 672Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
682{ 673{
683 COM_TRY_BEGIN 674 COM_TRY_BEGIN
684 NCOM::CPropVariant prop; 675 NCOM::CPropVariant prop;
@@ -711,7 +702,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
711 COM_TRY_END 702 COM_TRY_END
712} 703}
713 704
714STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 705Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
715{ 706{
716 COM_TRY_BEGIN 707 COM_TRY_BEGIN
717 NWindows::NCOM::CPropVariant prop; 708 NWindows::NCOM::CPropVariant prop;
@@ -749,11 +740,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
749 COM_TRY_END 740 COM_TRY_END
750} 741}
751 742
752STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 743Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
753 Int32 testMode, IArchiveExtractCallback *extractCallback) 744 Int32 testMode, IArchiveExtractCallback *extractCallback))
754{ 745{
755 COM_TRY_BEGIN 746 COM_TRY_BEGIN
756 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 747 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
757 if (allFilesMode) 748 if (allFilesMode)
758 numItems = _items.Size(); 749 numItems = _items.Size();
759 if (numItems == 0) 750 if (numItems == 0)
@@ -785,23 +776,23 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
785 for (i = 0; i < numItems; i++) 776 for (i = 0; i < numItems; i++)
786 { 777 {
787 lps->InSize = lps->OutSize = currentTotalSize; 778 lps->InSize = lps->OutSize = currentTotalSize;
788 RINOK(lps->SetCur()); 779 RINOK(lps->SetCur())
789 CMyComPtr<ISequentialOutStream> realOutStream; 780 CMyComPtr<ISequentialOutStream> realOutStream;
790 Int32 askMode = testMode ? 781 const Int32 askMode = testMode ?
791 NExtract::NAskMode::kTest : 782 NExtract::NAskMode::kTest :
792 NExtract::NAskMode::kExtract; 783 NExtract::NAskMode::kExtract;
793 Int32 index = allFilesMode ? i : indices[i]; 784 const UInt32 index = allFilesMode ? i : indices[i];
794 const CItem &item = _items[index]; 785 const CItem &item = _items[index];
795 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 786 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
796 currentTotalSize += (item.TextFileIndex >= 0) ? 787 currentTotalSize += (item.TextFileIndex >= 0) ?
797 (UInt64)_libFiles[(unsigned)item.TextFileIndex].Len() : item.Size; 788 (UInt64)_libFiles[(unsigned)item.TextFileIndex].Len() : item.Size;
798 789
799 if (!testMode && !realOutStream) 790 if (!testMode && !realOutStream)
800 continue; 791 continue;
801 RINOK(extractCallback->PrepareOperation(askMode)); 792 RINOK(extractCallback->PrepareOperation(askMode))
802 if (testMode) 793 if (testMode)
803 { 794 {
804 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 795 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
805 continue; 796 continue;
806 } 797 }
807 bool isOk = true; 798 bool isOk = true;
@@ -809,25 +800,25 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
809 { 800 {
810 const AString &f = _libFiles[(unsigned)item.TextFileIndex]; 801 const AString &f = _libFiles[(unsigned)item.TextFileIndex];
811 if (realOutStream) 802 if (realOutStream)
812 RINOK(WriteStream(realOutStream, f, f.Len())); 803 RINOK(WriteStream(realOutStream, f, f.Len()))
813 } 804 }
814 else 805 else
815 { 806 {
816 RINOK(_stream->Seek(item.GetDataPos(), STREAM_SEEK_SET, NULL)); 807 RINOK(InStream_SeekSet(_stream, item.GetDataPos()))
817 streamSpec->Init(item.Size); 808 streamSpec->Init(item.Size);
818 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 809 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
819 isOk = (copyCoderSpec->TotalSize == item.Size); 810 isOk = (copyCoderSpec->TotalSize == item.Size);
820 } 811 }
821 realOutStream.Release(); 812 realOutStream.Release();
822 RINOK(extractCallback->SetOperationResult(isOk ? 813 RINOK(extractCallback->SetOperationResult(isOk ?
823 NExtract::NOperationResult::kOK: 814 NExtract::NOperationResult::kOK:
824 NExtract::NOperationResult::kDataError)); 815 NExtract::NOperationResult::kDataError))
825 } 816 }
826 return S_OK; 817 return S_OK;
827 COM_TRY_END 818 COM_TRY_END
828} 819}
829 820
830STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 821Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
831{ 822{
832 COM_TRY_BEGIN 823 COM_TRY_BEGIN
833 const CItem &item = _items[index]; 824 const CItem &item = _items[index];
@@ -843,7 +834,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
843} 834}
844 835
845REGISTER_ARC_I( 836REGISTER_ARC_I(
846 "Ar", "ar a deb udeb lib", 0, 0xEC, 837 "Ar", "ar a deb udeb lib", NULL, 0xEC,
847 kSignature, 838 kSignature,
848 0, 839 0,
849 0, 840 0,
diff --git a/CPP/7zip/Archive/Archive.def b/CPP/7zip/Archive/Archive.def
index 145516d..2ed6246 100644
--- a/CPP/7zip/Archive/Archive.def
+++ b/CPP/7zip/Archive/Archive.def
@@ -10,3 +10,5 @@ EXPORTS
10 10
11 SetLargePageMode PRIVATE 11 SetLargePageMode PRIVATE
12 SetCaseSensitive PRIVATE 12 SetCaseSensitive PRIVATE
13
14 GetModuleProp PRIVATE
diff --git a/CPP/7zip/Archive/Archive2.def b/CPP/7zip/Archive/Archive2.def
index c758274..f891ad3 100644
--- a/CPP/7zip/Archive/Archive2.def
+++ b/CPP/7zip/Archive/Archive2.def
@@ -17,3 +17,5 @@ EXPORTS
17 17
18 SetLargePageMode PRIVATE 18 SetLargePageMode PRIVATE
19 SetCaseSensitive PRIVATE 19 SetCaseSensitive PRIVATE
20
21 GetModuleProp PRIVATE
diff --git a/CPP/7zip/Archive/ArchiveExports.cpp b/CPP/7zip/Archive/ArchiveExports.cpp
index 8a441bc..4735fcf 100644
--- a/CPP/7zip/Archive/ArchiveExports.cpp
+++ b/CPP/7zip/Archive/ArchiveExports.cpp
@@ -10,7 +10,7 @@
10 10
11#include "../Common/RegisterArc.h" 11#include "../Common/RegisterArc.h"
12 12
13static const unsigned kNumArcsMax = 64; 13static const unsigned kNumArcsMax = 72;
14static unsigned g_NumArcs = 0; 14static unsigned g_NumArcs = 0;
15static unsigned g_DefaultArcIndex = 0; 15static unsigned g_DefaultArcIndex = 0;
16static const CArcInfo *g_Arcs[kNumArcsMax]; 16static const CArcInfo *g_Arcs[kNumArcsMax];
@@ -24,9 +24,10 @@ void RegisterArc(const CArcInfo *arcInfo) throw()
24 g_DefaultArcIndex = g_NumArcs; 24 g_DefaultArcIndex = g_NumArcs;
25 g_Arcs[g_NumArcs++] = arcInfo; 25 g_Arcs[g_NumArcs++] = arcInfo;
26 } 26 }
27 // else throw 1;
27} 28}
28 29
29DEFINE_GUID(CLSID_CArchiveHandler, 30Z7_DEFINE_GUID(CLSID_CArchiveHandler,
30 k_7zip_GUID_Data1, 31 k_7zip_GUID_Data1,
31 k_7zip_GUID_Data2, 32 k_7zip_GUID_Data2,
32 k_7zip_GUID_Data3_Common, 33 k_7zip_GUID_Data3_Common,
@@ -36,7 +37,7 @@ DEFINE_GUID(CLSID_CArchiveHandler,
36 37
37static inline HRESULT SetPropStrFromBin(const char *s, unsigned size, PROPVARIANT *value) 38static inline HRESULT SetPropStrFromBin(const char *s, unsigned size, PROPVARIANT *value)
38{ 39{
39 if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) 40 if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != NULL)
40 value->vt = VT_BSTR; 41 value->vt = VT_BSTR;
41 return S_OK; 42 return S_OK;
42} 43}
@@ -52,7 +53,7 @@ static int FindFormatCalssId(const GUID *clsid)
52 CLS_ARC_ID_ITEM(cls) = 0; 53 CLS_ARC_ID_ITEM(cls) = 0;
53 if (cls != CLSID_CArchiveHandler) 54 if (cls != CLSID_CArchiveHandler)
54 return -1; 55 return -1;
55 Byte id = CLS_ARC_ID_ITEM(*clsid); 56 const Byte id = CLS_ARC_ID_ITEM(*clsid);
56 for (unsigned i = 0; i < g_NumArcs; i++) 57 for (unsigned i = 0; i < g_NumArcs; i++)
57 if (g_Arcs[i]->Id == id) 58 if (g_Arcs[i]->Id == id)
58 return (int)i; 59 return (int)i;
@@ -64,11 +65,11 @@ STDAPI CreateArchiver(const GUID *clsid, const GUID *iid, void **outObject)
64{ 65{
65 COM_TRY_BEGIN 66 COM_TRY_BEGIN
66 { 67 {
67 int needIn = (*iid == IID_IInArchive); 68 const int needIn = (*iid == IID_IInArchive);
68 int needOut = (*iid == IID_IOutArchive); 69 const int needOut = (*iid == IID_IOutArchive);
69 if (!needIn && !needOut) 70 if (!needIn && !needOut)
70 return E_NOINTERFACE; 71 return E_NOINTERFACE;
71 int formatIndex = FindFormatCalssId(clsid); 72 const int formatIndex = FindFormatCalssId(clsid);
72 if (formatIndex < 0) 73 if (formatIndex < 0)
73 return CLASS_E_CLASSNOTAVAILABLE; 74 return CLASS_E_CLASSNOTAVAILABLE;
74 75
diff --git a/CPP/7zip/Archive/ArjHandler.cpp b/CPP/7zip/Archive/ArjHandler.cpp
index 125b9c2..2f982c4 100644
--- a/CPP/7zip/Archive/ArjHandler.cpp
+++ b/CPP/7zip/Archive/ArjHandler.cpp
@@ -31,10 +31,11 @@ static const unsigned kMatchMinLen = 3;
31 31
32static const UInt32 kWindowSize = 1 << 15; // must be >= (1 << 14) 32static const UInt32 kWindowSize = 1 << 15; // must be >= (1 << 14)
33 33
34class CCoder: 34
35 public ICompressCoder, 35Z7_CLASS_IMP_NOQIB_1(
36 public CMyUnknownImp 36 CCoder
37{ 37 , ICompressCoder
38)
38 CLzOutWindow _outWindow; 39 CLzOutWindow _outWindow;
39 NBitm::CDecoder<CInBuffer> _inBitStream; 40 NBitm::CDecoder<CInBuffer> _inBitStream;
40 41
@@ -50,16 +51,13 @@ class CCoder:
50 51
51 HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress); 52 HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress);
52public: 53public:
53 MY_UNKNOWN_IMP
54
55 bool FinishMode; 54 bool FinishMode;
56 CCoder(): FinishMode(false) {}
57 55
58 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, 56 CCoder(): FinishMode(false) {}
59 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
60 UInt64 GetInputProcessedSize() const { return _inBitStream.GetProcessedSize(); } 57 UInt64 GetInputProcessedSize() const { return _inBitStream.GetProcessedSize(); }
61}; 58};
62 59
60
63HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) 61HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
64{ 62{
65 const UInt32 kStep = 1 << 20; 63 const UInt32 kStep = 1 << 20;
@@ -76,7 +74,7 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
76 74
77 UInt64 packSize = _inBitStream.GetProcessedSize(); 75 UInt64 packSize = _inBitStream.GetProcessedSize();
78 UInt64 pos = _outWindow.GetProcessedSize(); 76 UInt64 pos = _outWindow.GetProcessedSize();
79 RINOK(progress->SetRatioInfo(&packSize, &pos)); 77 RINOK(progress->SetRatioInfo(&packSize, &pos))
80 next = 0; 78 next = 0;
81 if (rem > kStep) 79 if (rem > kStep)
82 next = rem - kStep; 80 next = rem - kStep;
@@ -152,8 +150,8 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
152 150
153 151
154 152
155STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 153Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
156 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 154 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
157{ 155{
158 try 156 try
159 { 157 {
@@ -367,10 +365,10 @@ HRESULT CArcHeader::Parse(const Byte *p, unsigned size)
367 // LastChapter = p[29]; 365 // LastChapter = p[29];
368 unsigned pos = headerSize; 366 unsigned pos = headerSize;
369 unsigned size1 = size - pos; 367 unsigned size1 = size - pos;
370 RINOK(ReadString(p + pos, size1, Name)); 368 RINOK(ReadString(p + pos, size1, Name))
371 pos += size1; 369 pos += size1;
372 size1 = size - pos; 370 size1 = size - pos;
373 RINOK(ReadString(p + pos, size1, Comment)); 371 RINOK(ReadString(p + pos, size1, Comment))
374 pos += size1; 372 pos += size1;
375 return S_OK; 373 return S_OK;
376} 374}
@@ -477,10 +475,10 @@ HRESULT CItem::Parse(const Byte *p, unsigned size)
477 475
478 unsigned pos = headerSize; 476 unsigned pos = headerSize;
479 unsigned size1 = size - pos; 477 unsigned size1 = size - pos;
480 RINOK(ReadString(p + pos, size1, Name)); 478 RINOK(ReadString(p + pos, size1, Name))
481 pos += size1; 479 pos += size1;
482 size1 = size - pos; 480 size1 = size - pos;
483 RINOK(ReadString(p + pos, size1, Comment)); 481 RINOK(ReadString(p + pos, size1, Comment))
484 pos += size1; 482 pos += size1;
485 483
486 return S_OK; 484 return S_OK;
@@ -570,7 +568,7 @@ HRESULT CArc::ReadBlock(bool &filled, CExtendedInfo *extendedInfo)
570 if (extendedInfo) 568 if (extendedInfo)
571 extendedInfo->Size += _blockSize; 569 extendedInfo->Size += _blockSize;
572 570
573 READ_STREAM(_block, readSize); 571 READ_STREAM(_block, readSize)
574 if (Get32(_block + _blockSize) != CrcCalc(_block, _blockSize)) 572 if (Get32(_block + _blockSize) != CrcCalc(_block, _blockSize))
575 { 573 {
576 if (extendedInfo) 574 if (extendedInfo)
@@ -591,28 +589,28 @@ HRESULT CArc::SkipExtendedHeaders(CExtendedInfo &extendedInfo)
591 for (UInt32 i = 0;; i++) 589 for (UInt32 i = 0;; i++)
592 { 590 {
593 bool filled; 591 bool filled;
594 RINOK(ReadBlock(filled, &extendedInfo)); 592 RINOK(ReadBlock(filled, &extendedInfo))
595 if (!filled) 593 if (!filled)
596 return S_OK; 594 return S_OK;
597 if (Callback && (i & 0xFF) == 0) 595 if (Callback && (i & 0xFF) == 0)
598 RINOK(Callback->SetCompleted(&NumFiles, &Processed)); 596 RINOK(Callback->SetCompleted(&NumFiles, &Processed))
599 } 597 }
600} 598}
601 599
602HRESULT CArc::Open() 600HRESULT CArc::Open()
603{ 601{
604 bool filled; 602 bool filled;
605 RINOK(ReadBlock(filled, NULL)); // (extendedInfo = NULL) 603 RINOK(ReadBlock(filled, NULL)) // (extendedInfo = NULL)
606 if (!filled) 604 if (!filled)
607 return S_FALSE; 605 return S_FALSE;
608 RINOK(Header.Parse(_block, _blockSize)); 606 RINOK(Header.Parse(_block, _blockSize))
609 IsArc = true; 607 IsArc = true;
610 return SkipExtendedHeaders(ExtendedInfo); 608 return SkipExtendedHeaders(ExtendedInfo);
611} 609}
612 610
613HRESULT CArc::GetNextItem(CItem &item, bool &filled) 611HRESULT CArc::GetNextItem(CItem &item, bool &filled)
614{ 612{
615 RINOK(ReadBlock(filled, NULL)); // (extendedInfo = NULL) 613 RINOK(ReadBlock(filled, NULL)) // (extendedInfo = NULL)
616 if (!filled) 614 if (!filled)
617 return S_OK; 615 return S_OK;
618 filled = false; 616 filled = false;
@@ -627,23 +625,18 @@ HRESULT CArc::GetNextItem(CItem &item, bool &filled)
627 extraData = GetUi32(_block + pos); 625 extraData = GetUi32(_block + pos);
628 */ 626 */
629 627
630 RINOK(SkipExtendedHeaders(item.ExtendedInfo)); 628 RINOK(SkipExtendedHeaders(item.ExtendedInfo))
631 filled = true; 629 filled = true;
632 return S_OK; 630 return S_OK;
633} 631}
634 632
635class CHandler: 633
636 public IInArchive, 634Z7_CLASS_IMP_CHandler_IInArchive_0
637 public CMyUnknownImp 635
638{
639 CObjectVector<CItem> _items; 636 CObjectVector<CItem> _items;
640 CMyComPtr<IInStream> _stream; 637 CMyComPtr<IInStream> _stream;
641 UInt64 _phySize; 638 UInt64 _phySize;
642 CArc _arc; 639 CArc _arc;
643public:
644 MY_UNKNOWN_IMP1(IInArchive)
645
646 INTERFACE_IInArchive(;)
647 640
648 HRESULT Open2(IInStream *inStream, IArchiveOpenCallback *callback); 641 HRESULT Open2(IInStream *inStream, IArchiveOpenCallback *callback);
649}; 642};
@@ -696,7 +689,7 @@ static void SetUnicodeString(const AString &s, NCOM::CPropVariant &prop)
696 prop = MultiByteToUnicodeString(s, CP_OEMCP); 689 prop = MultiByteToUnicodeString(s, CP_OEMCP);
697} 690}
698 691
699STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 692Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
700{ 693{
701 COM_TRY_BEGIN 694 COM_TRY_BEGIN
702 NCOM::CPropVariant prop; 695 NCOM::CPropVariant prop;
@@ -717,7 +710,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
717 case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break; 710 case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break;
718 case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break; 711 case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break;
719 case k_ErrorType_OK: 712 case k_ErrorType_OK:
720 default: 713 // default:
721 break; 714 break;
722 } 715 }
723 prop = v; 716 prop = v;
@@ -730,13 +723,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
730 COM_TRY_END 723 COM_TRY_END
731} 724}
732 725
733STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 726Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
734{ 727{
735 *numItems = _items.Size(); 728 *numItems = _items.Size();
736 return S_OK; 729 return S_OK;
737} 730}
738 731
739STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 732Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
740{ 733{
741 COM_TRY_BEGIN 734 COM_TRY_BEGIN
742 NCOM::CPropVariant prop; 735 NCOM::CPropVariant prop;
@@ -766,16 +759,15 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback)
766{ 759{
767 Close(); 760 Close();
768 761
769 UInt64 endPos = 0; 762 UInt64 endPos;
770 RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); 763 RINOK(InStream_AtBegin_GetSize(inStream, endPos))
771 RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL));
772 764
773 _arc.Stream = inStream; 765 _arc.Stream = inStream;
774 _arc.Callback = callback; 766 _arc.Callback = callback;
775 _arc.NumFiles = 0; 767 _arc.NumFiles = 0;
776 _arc.Processed = 0; 768 _arc.Processed = 0;
777 769
778 RINOK(_arc.Open()); 770 RINOK(_arc.Open())
779 771
780 _phySize = _arc.Processed; 772 _phySize = _arc.Processed;
781 if (_arc.Header.ArchiveSize != 0) 773 if (_arc.Header.ArchiveSize != 0)
@@ -787,7 +779,7 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback)
787 bool filled; 779 bool filled;
788 780
789 _arc.Error = k_ErrorType_OK; 781 _arc.Error = k_ErrorType_OK;
790 RINOK(_arc.GetNextItem(item, filled)); 782 RINOK(_arc.GetNextItem(item, filled))
791 783
792 if (_arc.Error != k_ErrorType_OK) 784 if (_arc.Error != k_ErrorType_OK)
793 break; 785 break;
@@ -811,20 +803,20 @@ HRESULT CHandler::Open2(IInStream *inStream, IArchiveOpenCallback *callback)
811 break; 803 break;
812 } 804 }
813 805
814 RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); 806 RINOK(InStream_SeekSet(inStream, pos))
815 _arc.NumFiles = _items.Size(); 807 _arc.NumFiles = _items.Size();
816 _arc.Processed = pos; 808 _arc.Processed = pos;
817 809
818 if (callback && (_items.Size() & 0xFF) == 0) 810 if (callback && (_items.Size() & 0xFF) == 0)
819 { 811 {
820 RINOK(callback->SetCompleted(&_arc.NumFiles, &_arc.Processed)); 812 RINOK(callback->SetCompleted(&_arc.NumFiles, &_arc.Processed))
821 } 813 }
822 } 814 }
823 return S_OK; 815 return S_OK;
824} 816}
825 817
826STDMETHODIMP CHandler::Open(IInStream *inStream, 818Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
827 const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) 819 const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback))
828{ 820{
829 COM_TRY_BEGIN 821 COM_TRY_BEGIN
830 HRESULT res; 822 HRESULT res;
@@ -840,7 +832,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
840 COM_TRY_END 832 COM_TRY_END
841} 833}
842 834
843STDMETHODIMP CHandler::Close() 835Z7_COM7F_IMF(CHandler::Close())
844{ 836{
845 _arc.Close(); 837 _arc.Close();
846 _phySize = 0; 838 _phySize = 0;
@@ -849,12 +841,12 @@ STDMETHODIMP CHandler::Close()
849 return S_OK; 841 return S_OK;
850} 842}
851 843
852STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 844Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
853 Int32 testMode, IArchiveExtractCallback *extractCallback) 845 Int32 testMode, IArchiveExtractCallback *extractCallback))
854{ 846{
855 COM_TRY_BEGIN 847 COM_TRY_BEGIN
856 UInt64 totalUnpacked = 0, totalPacked = 0; 848 UInt64 totalUnpacked = 0, totalPacked = 0;
857 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 849 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
858 if (allFilesMode) 850 if (allFilesMode)
859 numItems = _items.Size(); 851 numItems = _items.Size();
860 if (numItems == 0) 852 if (numItems == 0)
@@ -892,24 +884,24 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
892 { 884 {
893 lps->InSize = totalPacked; 885 lps->InSize = totalPacked;
894 lps->OutSize = totalUnpacked; 886 lps->OutSize = totalUnpacked;
895 RINOK(lps->SetCur()); 887 RINOK(lps->SetCur())
896 888
897 curUnpacked = curPacked = 0; 889 curUnpacked = curPacked = 0;
898 890
899 CMyComPtr<ISequentialOutStream> realOutStream; 891 CMyComPtr<ISequentialOutStream> realOutStream;
900 Int32 askMode = testMode ? 892 const Int32 askMode = testMode ?
901 NExtract::NAskMode::kTest : 893 NExtract::NAskMode::kTest :
902 NExtract::NAskMode::kExtract; 894 NExtract::NAskMode::kExtract;
903 Int32 index = allFilesMode ? i : indices[i]; 895 const UInt32 index = allFilesMode ? i : indices[i];
904 const CItem &item = _items[index]; 896 const CItem &item = _items[index];
905 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 897 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
906 898
907 if (item.IsDir()) 899 if (item.IsDir())
908 { 900 {
909 // if (!testMode) 901 // if (!testMode)
910 { 902 {
911 RINOK(extractCallback->PrepareOperation(askMode)); 903 RINOK(extractCallback->PrepareOperation(askMode))
912 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 904 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
913 } 905 }
914 continue; 906 continue;
915 } 907 }
@@ -917,7 +909,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
917 if (!testMode && !realOutStream) 909 if (!testMode && !realOutStream)
918 continue; 910 continue;
919 911
920 RINOK(extractCallback->PrepareOperation(askMode)); 912 RINOK(extractCallback->PrepareOperation(askMode))
921 curUnpacked = item.Size; 913 curUnpacked = item.Size;
922 curPacked = item.PackSize; 914 curPacked = item.PackSize;
923 915
@@ -930,8 +922,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
930 922
931 inStreamSpec->Init(item.PackSize); 923 inStreamSpec->Init(item.PackSize);
932 924
933 UInt64 pos; 925 RINOK(InStream_SeekSet(_stream, item.DataPosition))
934 _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos);
935 926
936 HRESULT result = S_OK; 927 HRESULT result = S_OK;
937 Int32 opRes = NExtract::NOperationResult::kOK; 928 Int32 opRes = NExtract::NOperationResult::kOK;
@@ -990,7 +981,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
990 opRes = NExtract::NOperationResult::kDataError; 981 opRes = NExtract::NOperationResult::kDataError;
991 else 982 else
992 { 983 {
993 RINOK(result); 984 RINOK(result)
994 opRes = (outStreamSpec->GetCRC() == item.FileCRC) ? 985 opRes = (outStreamSpec->GetCRC() == item.FileCRC) ?
995 NExtract::NOperationResult::kOK: 986 NExtract::NOperationResult::kOK:
996 NExtract::NOperationResult::kCRCError; 987 NExtract::NOperationResult::kCRCError;
@@ -998,7 +989,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
998 } 989 }
999 990
1000 outStream.Release(); 991 outStream.Release();
1001 RINOK(extractCallback->SetOperationResult(opRes)); 992 RINOK(extractCallback->SetOperationResult(opRes))
1002 } 993 }
1003 } 994 }
1004 995
@@ -1009,7 +1000,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1009static const Byte k_Signature[] = { kSig0, kSig1 }; 1000static const Byte k_Signature[] = { kSig0, kSig1 };
1010 1001
1011REGISTER_ARC_I( 1002REGISTER_ARC_I(
1012 "Arj", "arj", 0, 4, 1003 "Arj", "arj", NULL, 4,
1013 k_Signature, 1004 k_Signature,
1014 0, 1005 0,
1015 0, 1006 0,
diff --git a/CPP/7zip/Archive/Base64Handler.cpp b/CPP/7zip/Archive/Base64Handler.cpp
index 63b4552..5b06051 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)
207 { 207 {
208 if (size == 0) 208 if (size == 0)
209 return p; 209 return p;
210 UInt32 c = k_Base64Table[(Byte)(*p++)]; 210 const UInt32 c = k_Base64Table[(Byte)(*p++)];
211 size--; 211 size--;
212 if (c == k_Code_Space) 212 if (c == k_Code_Space)
213 continue; 213 continue;
@@ -225,7 +225,7 @@ Byte *Base64ToBin(Byte *dest, const char *src)
225 225
226 for (;;) 226 for (;;)
227 { 227 {
228 UInt32 c = k_Base64Table[(Byte)(*src++)]; 228 const UInt32 c = k_Base64Table[(Byte)(*src++)];
229 229
230 if (c < 64) 230 if (c < 64)
231 { 231 {
@@ -266,7 +266,7 @@ Byte *Base64ToBin(Byte *dest, const char *src)
266 266
267 for (;;) 267 for (;;)
268 { 268 {
269 Byte c = k_Base64Table[(Byte)(*src++)]; 269 const Byte c = k_Base64Table[(Byte)(*src++)];
270 if (c == k_Code_Space) 270 if (c == k_Code_Space)
271 continue; 271 continue;
272 if (c == k_Code_Zero) 272 if (c == k_Code_Zero)
@@ -279,18 +279,13 @@ Byte *Base64ToBin(Byte *dest, const char *src)
279namespace NArchive { 279namespace NArchive {
280namespace NBase64 { 280namespace NBase64 {
281 281
282class CHandler: 282Z7_CLASS_IMP_CHandler_IInArchive_0
283 public IInArchive, 283
284 public CMyUnknownImp
285{
286 bool _isArc; 284 bool _isArc;
287 UInt64 _phySize; 285 UInt64 _phySize;
288 size_t _size; 286 size_t _size;
289 EBase64Res _sres; 287 EBase64Res _sres;
290 CByteBuffer _data; 288 CByteBuffer _data;
291public:
292 MY_UNKNOWN_IMP1(IInArchive)
293 INTERFACE_IInArchive(;)
294}; 289};
295 290
296static const Byte kProps[] = 291static const Byte kProps[] =
@@ -302,13 +297,13 @@ static const Byte kProps[] =
302IMP_IInArchive_Props 297IMP_IInArchive_Props
303IMP_IInArchive_ArcProps_NO_Table 298IMP_IInArchive_ArcProps_NO_Table
304 299
305STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 300Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
306{ 301{
307 *numItems = 1; 302 *numItems = 1;
308 return S_OK; 303 return S_OK;
309} 304}
310 305
311STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 306Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
312{ 307{
313 NWindows::NCOM::CPropVariant prop; 308 NWindows::NCOM::CPropVariant prop;
314 switch (propID) 309 switch (propID)
@@ -328,7 +323,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
328 return S_OK; 323 return S_OK;
329} 324}
330 325
331STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 326Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
332{ 327{
333 // COM_TRY_BEGIN 328 // COM_TRY_BEGIN
334 NWindows::NCOM::CPropVariant prop; 329 NWindows::NCOM::CPropVariant prop;
@@ -349,22 +344,22 @@ static HRESULT ReadStream_OpenProgress(ISequentialInStream *stream, void *data,
349 while (size != 0) 344 while (size != 0)
350 { 345 {
351 const UInt32 kBlockSize = ((UInt32)1 << 24); 346 const UInt32 kBlockSize = ((UInt32)1 << 24);
352 UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; 347 const UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize;
353 UInt32 processedSizeLoc; 348 UInt32 processedSizeLoc;
354 RINOK(stream->Read(data, curSize, &processedSizeLoc)); 349 RINOK(stream->Read(data, curSize, &processedSizeLoc))
355 if (processedSizeLoc == 0) 350 if (processedSizeLoc == 0)
356 return E_FAIL; 351 return E_FAIL;
357 data = (void *)((Byte *)data + processedSizeLoc); 352 data = (void *)((Byte *)data + processedSizeLoc);
358 size -= processedSizeLoc; 353 size -= processedSizeLoc;
359 bytes += processedSizeLoc; 354 bytes += processedSizeLoc;
360 const UInt64 files = 1; 355 const UInt64 files = 1;
361 RINOK(openCallback->SetCompleted(&files, &bytes)); 356 RINOK(openCallback->SetCompleted(&files, &bytes))
362 } 357 }
363 return S_OK; 358 return S_OK;
364} 359}
365 360
366 361
367STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback) 362Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback))
368{ 363{
369 COM_TRY_BEGIN 364 COM_TRY_BEGIN
370 { 365 {
@@ -373,7 +368,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
373 const unsigned kStartSize = 1 << 12; 368 const unsigned kStartSize = 1 << 12;
374 _data.Alloc(kStartSize); 369 _data.Alloc(kStartSize);
375 size_t size = kStartSize; 370 size_t size = kStartSize;
376 RINOK(ReadStream(stream, _data, &size)); 371 RINOK(ReadStream(stream, _data, &size))
377 UInt32 isArcRes = IsArc_Base64(_data, size); 372 UInt32 isArcRes = IsArc_Base64(_data, size);
378 if (isArcRes == k_IsArc_Res_NO) 373 if (isArcRes == k_IsArc_Res_NO)
379 return S_FALSE; 374 return S_FALSE;
@@ -381,7 +376,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
381 _isArc = true; 376 _isArc = true;
382 377
383 UInt64 packSize64; 378 UInt64 packSize64;
384 RINOK(stream->Seek(0, STREAM_SEEK_END, &packSize64)); 379 RINOK(InStream_GetSize_SeekToEnd(stream, packSize64))
385 380
386 if (packSize64 == 0) 381 if (packSize64 == 0)
387 return S_FALSE; 382 return S_FALSE;
@@ -393,16 +388,16 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
393 388
394 for (;;) 389 for (;;)
395 { 390 {
396 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 391 RINOK(InStream_SeekSet(stream, 0))
397 392
398 _data.Alloc(curSize); 393 _data.Alloc(curSize);
399 RINOK(ReadStream_OpenProgress(stream, _data, curSize, openCallback)); 394 RINOK(ReadStream_OpenProgress(stream, _data, curSize, openCallback))
400 395
401 const Byte *srcEnd; 396 const Byte *srcEnd;
402 Byte *dest; 397 Byte *dest;
403 _sres = Base64ToBin(_data, curSize, &srcEnd, &dest); 398 _sres = Base64ToBin(_data, curSize, &srcEnd, &dest);
404 _size = dest - _data; 399 _size = (size_t)(dest - _data);
405 size_t mainSize = srcEnd - _data; 400 const size_t mainSize = (size_t)(srcEnd - _data);
406 _phySize = mainSize; 401 _phySize = mainSize;
407 if (_sres == k_Base64_RES_UnexpectedChar) 402 if (_sres == k_Base64_RES_UnexpectedChar)
408 break; 403 break;
@@ -431,7 +426,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
431 COM_TRY_END 426 COM_TRY_END
432} 427}
433 428
434STDMETHODIMP CHandler::Close() 429Z7_COM7F_IMF(CHandler::Close())
435{ 430{
436 _phySize = 0; 431 _phySize = 0;
437 _size = 0; 432 _size = 0;
@@ -442,19 +437,16 @@ STDMETHODIMP CHandler::Close()
442} 437}
443 438
444 439
445STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 440Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
446 Int32 testMode, IArchiveExtractCallback *extractCallback) 441 Int32 testMode, IArchiveExtractCallback *extractCallback))
447{ 442{
448 COM_TRY_BEGIN 443 COM_TRY_BEGIN
449 bool allFilesMode = (numItems == (UInt32)(Int32)-1);
450 if (allFilesMode)
451 numItems = 1;
452 if (numItems == 0) 444 if (numItems == 0)
453 return S_OK; 445 return S_OK;
454 if (numItems != 1 || *indices != 0) 446 if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0))
455 return E_INVALIDARG; 447 return E_INVALIDARG;
456 448
457 RINOK(extractCallback->SetTotal(_size)); 449 RINOK(extractCallback->SetTotal(_size))
458 450
459 CLocalProgress *lps = new CLocalProgress; 451 CLocalProgress *lps = new CLocalProgress;
460 CMyComPtr<ICompressProgressInfo> progress = lps; 452 CMyComPtr<ICompressProgressInfo> progress = lps;
@@ -462,14 +454,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
462 454
463 { 455 {
464 lps->InSize = lps->OutSize = 0; 456 lps->InSize = lps->OutSize = 0;
465 RINOK(lps->SetCur()); 457 RINOK(lps->SetCur())
466 458
467 CMyComPtr<ISequentialOutStream> realOutStream; 459 CMyComPtr<ISequentialOutStream> realOutStream;
468 Int32 askMode = testMode ? 460 const Int32 askMode = testMode ?
469 NExtract::NAskMode::kTest : 461 NExtract::NAskMode::kTest :
470 NExtract::NAskMode::kExtract; 462 NExtract::NAskMode::kExtract;
471 463
472 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 464 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
473 465
474 if (!testMode && !realOutStream) 466 if (!testMode && !realOutStream)
475 return S_OK; 467 return S_OK;
@@ -478,7 +470,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
478 470
479 if (realOutStream) 471 if (realOutStream)
480 { 472 {
481 RINOK(WriteStream(realOutStream, (const Byte *)_data, _size)); 473 RINOK(WriteStream(realOutStream, (const Byte *)_data, _size))
482 realOutStream.Release(); 474 realOutStream.Release();
483 } 475 }
484 476
@@ -492,7 +484,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
492 opRes = NExtract::NOperationResult::kDataError; 484 opRes = NExtract::NOperationResult::kDataError;
493 } 485 }
494 486
495 RINOK(extractCallback->SetOperationResult(opRes)); 487 RINOK(extractCallback->SetOperationResult(opRes))
496 } 488 }
497 489
498 lps->InSize = _phySize; 490 lps->InSize = _phySize;
@@ -503,9 +495,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
503} 495}
504 496
505REGISTER_ARC_I_NO_SIG( 497REGISTER_ARC_I_NO_SIG(
506 "Base64", "b64", 0, 0xC5, 498 "Base64", "b64", NULL, 0xC5,
507 0, 499 0,
508 NArcInfoFlags::kKeepName | NArcInfoFlags::kStartOpen | NArcInfoFlags::kByExtOnlyOpen, 500 NArcInfoFlags::kKeepName
501 | NArcInfoFlags::kStartOpen
502 | NArcInfoFlags::kByExtOnlyOpen,
509 IsArc_Base64) 503 IsArc_Base64)
510 504
511}} 505}}
diff --git a/CPP/7zip/Archive/Bz2Handler.cpp b/CPP/7zip/Archive/Bz2Handler.cpp
index c89a53c..994b1ad 100644
--- a/CPP/7zip/Archive/Bz2Handler.cpp
+++ b/CPP/7zip/Archive/Bz2Handler.cpp
@@ -20,13 +20,11 @@ using namespace NWindows;
20namespace NArchive { 20namespace NArchive {
21namespace NBz2 { 21namespace NBz2 {
22 22
23class CHandler: 23Z7_CLASS_IMP_CHandler_IInArchive_3(
24 public IInArchive, 24 IArchiveOpenSeq,
25 public IArchiveOpenSeq, 25 IOutArchive,
26 public IOutArchive, 26 ISetProperties
27 public ISetProperties, 27)
28 public CMyUnknownImp
29{
30 CMyComPtr<IInStream> _stream; 28 CMyComPtr<IInStream> _stream;
31 CMyComPtr<ISequentialInStream> _seqStream; 29 CMyComPtr<ISequentialInStream> _seqStream;
32 30
@@ -46,19 +44,6 @@ class CHandler:
46 UInt64 _numBlocks; 44 UInt64 _numBlocks;
47 45
48 CSingleMethodProps _props; 46 CSingleMethodProps _props;
49
50public:
51 MY_UNKNOWN_IMP4(
52 IInArchive,
53 IArchiveOpenSeq,
54 IOutArchive,
55 ISetProperties)
56 INTERFACE_IInArchive(;)
57 INTERFACE_IOutArchive(;)
58 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
59 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
60
61 CHandler() { }
62}; 47};
63 48
64static const Byte kProps[] = 49static const Byte kProps[] =
@@ -76,7 +61,7 @@ static const Byte kArcProps[] =
76IMP_IInArchive_Props 61IMP_IInArchive_Props
77IMP_IInArchive_ArcProps 62IMP_IInArchive_ArcProps
78 63
79STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 64Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
80{ 65{
81 NCOM::CPropVariant prop; 66 NCOM::CPropVariant prop;
82 switch (propID) 67 switch (propID)
@@ -88,7 +73,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
88 case kpidErrorFlags: 73 case kpidErrorFlags:
89 { 74 {
90 UInt32 v = 0; 75 UInt32 v = 0;
91 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 76 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
92 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; 77 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd;
93 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; 78 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd;
94 prop = v; 79 prop = v;
@@ -98,13 +83,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
98 return S_OK; 83 return S_OK;
99} 84}
100 85
101STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 86Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
102{ 87{
103 *numItems = 1; 88 *numItems = 1;
104 return S_OK; 89 return S_OK;
105} 90}
106 91
107STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 92Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
108{ 93{
109 NCOM::CPropVariant prop; 94 NCOM::CPropVariant prop;
110 switch (propID) 95 switch (propID)
@@ -133,13 +118,13 @@ API_FUNC_static_IsArc IsArc_BZip2(const Byte *p, size_t size)
133} 118}
134} 119}
135 120
136STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) 121Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *))
137{ 122{
138 COM_TRY_BEGIN 123 COM_TRY_BEGIN
139 Close(); 124 Close();
140 { 125 {
141 Byte buf[kSignatureCheckSize]; 126 Byte buf[kSignatureCheckSize];
142 RINOK(ReadStream_FALSE(stream, buf, kSignatureCheckSize)); 127 RINOK(ReadStream_FALSE(stream, buf, kSignatureCheckSize))
143 if (IsArc_BZip2(buf, kSignatureCheckSize) == k_IsArc_Res_NO) 128 if (IsArc_BZip2(buf, kSignatureCheckSize) == k_IsArc_Res_NO)
144 return S_FALSE; 129 return S_FALSE;
145 _isArc = true; 130 _isArc = true;
@@ -152,7 +137,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
152} 137}
153 138
154 139
155STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 140Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
156{ 141{
157 Close(); 142 Close();
158 _isArc = true; 143 _isArc = true;
@@ -160,7 +145,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
160 return S_OK; 145 return S_OK;
161} 146}
162 147
163STDMETHODIMP CHandler::Close() 148Z7_COM7F_IMF(CHandler::Close())
164{ 149{
165 _isArc = false; 150 _isArc = false;
166 _needSeekToStart = false; 151 _needSeekToStart = false;
@@ -180,8 +165,8 @@ STDMETHODIMP CHandler::Close()
180} 165}
181 166
182 167
183STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 168Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
184 Int32 testMode, IArchiveExtractCallback *extractCallback) 169 Int32 testMode, IArchiveExtractCallback *extractCallback))
185{ 170{
186 COM_TRY_BEGIN 171 COM_TRY_BEGIN
187 if (numItems == 0) 172 if (numItems == 0)
@@ -193,10 +178,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
193 extractCallback->SetTotal(_packSize); 178 extractCallback->SetTotal(_packSize);
194 179
195 CMyComPtr<ISequentialOutStream> realOutStream; 180 CMyComPtr<ISequentialOutStream> realOutStream;
196 Int32 askMode = testMode ? 181 const Int32 askMode = testMode ?
197 NExtract::NAskMode::kTest : 182 NExtract::NAskMode::kTest :
198 NExtract::NAskMode::kExtract; 183 NExtract::NAskMode::kExtract;
199 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 184 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
200 if (!testMode && !realOutStream) 185 if (!testMode && !realOutStream)
201 return S_OK; 186 return S_OK;
202 187
@@ -206,7 +191,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
206 { 191 {
207 if (!_stream) 192 if (!_stream)
208 return E_FAIL; 193 return E_FAIL;
209 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 194 RINOK(InStream_SeekToBegin(_stream))
210 } 195 }
211 else 196 else
212 _needSeekToStart = true; 197 _needSeekToStart = true;
@@ -216,8 +201,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
216 NCompress::NBZip2::CDecoder *decoderSpec = new NCompress::NBZip2::CDecoder; 201 NCompress::NBZip2::CDecoder *decoderSpec = new NCompress::NBZip2::CDecoder;
217 CMyComPtr<ICompressCoder> decoder = decoderSpec; 202 CMyComPtr<ICompressCoder> decoder = decoderSpec;
218 203
219 #ifndef _7ZIP_ST 204 #ifndef Z7_ST
220 RINOK(decoderSpec->SetNumberOfThreads(_props._numThreads)); 205 RINOK(decoderSpec->SetNumberOfThreads(_props._numThreads))
221 #endif 206 #endif
222 207
223 CDummyOutStream *outStreamSpec = new CDummyOutStream; 208 CDummyOutStream *outStreamSpec = new CDummyOutStream;
@@ -240,7 +225,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
240 lps->InSize = 0; 225 lps->InSize = 0;
241 lps->OutSize = 0; 226 lps->OutSize = 0;
242 227
243 HRESULT result = decoderSpec->Code(_seqStream, outStream, NULL, NULL, progress); 228 HRESULT result = decoder->Code(_seqStream, outStream, NULL, NULL, progress);
244 229
245 if (result != S_FALSE && result != S_OK) 230 if (result != S_FALSE && result != S_OK)
246 return result; 231 return result;
@@ -352,12 +337,13 @@ static HRESULT UpdateArchive(
352{ 337{
353 { 338 {
354 CMyComPtr<ISequentialInStream> fileInStream; 339 CMyComPtr<ISequentialInStream> fileInStream;
355 RINOK(updateCallback->GetStream(0, &fileInStream)); 340 RINOK(updateCallback->GetStream(0, &fileInStream))
356 if (!fileInStream) 341 if (!fileInStream)
357 return S_FALSE; 342 return S_FALSE;
358 { 343 {
359 CMyComPtr<IStreamGetSize> streamGetSize; 344 Z7_DECL_CMyComPtr_QI_FROM(
360 fileInStream.QueryInterface(IID_IStreamGetSize, &streamGetSize); 345 IStreamGetSize,
346 streamGetSize, fileInStream)
361 if (streamGetSize) 347 if (streamGetSize)
362 { 348 {
363 UInt64 size; 349 UInt64 size;
@@ -365,15 +351,15 @@ static HRESULT UpdateArchive(
365 unpackSize = size; 351 unpackSize = size;
366 } 352 }
367 } 353 }
368 RINOK(updateCallback->SetTotal(unpackSize)); 354 RINOK(updateCallback->SetTotal(unpackSize))
369 CLocalProgress *localProgressSpec = new CLocalProgress; 355 CLocalProgress *localProgressSpec = new CLocalProgress;
370 CMyComPtr<ICompressProgressInfo> localProgress = localProgressSpec; 356 CMyComPtr<ICompressProgressInfo> localProgress = localProgressSpec;
371 localProgressSpec->Init(updateCallback, true); 357 localProgressSpec->Init(updateCallback, true);
372 { 358 {
373 NCompress::NBZip2::CEncoder *encoderSpec = new NCompress::NBZip2::CEncoder; 359 NCompress::NBZip2::CEncoder *encoderSpec = new NCompress::NBZip2::CEncoder;
374 CMyComPtr<ICompressCoder> encoder = encoderSpec; 360 CMyComPtr<ICompressCoder> encoder = encoderSpec;
375 RINOK(props.SetCoderProps(encoderSpec, NULL)); 361 RINOK(props.SetCoderProps(encoderSpec, NULL))
376 RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, localProgress)); 362 RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, localProgress))
377 /* 363 /*
378 if (reportArcProp) 364 if (reportArcProp)
379 { 365 {
@@ -386,37 +372,42 @@ static HRESULT UpdateArchive(
386 return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); 372 return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK);
387} 373}
388 374
389STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 375Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType))
390{ 376{
391 *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType; 377 *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType;
392 // *timeType = NFileTimeType::kUnix; 378 // *timeType = NFileTimeType::kUnix;
393 return S_OK; 379 return S_OK;
394} 380}
395 381
396STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 382Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
397 IArchiveUpdateCallback *updateCallback) 383 IArchiveUpdateCallback *updateCallback))
398{ 384{
399 COM_TRY_BEGIN 385 COM_TRY_BEGIN
400 386
401 if (numItems != 1) 387 if (numItems != 1)
402 return E_INVALIDARG; 388 return E_INVALIDARG;
403 389
390 {
391 Z7_DECL_CMyComPtr_QI_FROM(
392 IStreamSetRestriction,
393 setRestriction, outStream)
394 if (setRestriction)
395 RINOK(setRestriction->SetRestriction(0, 0))
396 }
397
404 Int32 newData, newProps; 398 Int32 newData, newProps;
405 UInt32 indexInArchive; 399 UInt32 indexInArchive;
406 if (!updateCallback) 400 if (!updateCallback)
407 return E_FAIL; 401 return E_FAIL;
408 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); 402 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive))
409 403
410 /* 404 // Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, reportArcProp, updateCallback)
411 CMyComPtr<IArchiveUpdateCallbackArcProp> reportArcProp;
412 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp);
413 */
414 405
415 if (IntToBool(newProps)) 406 if (IntToBool(newProps))
416 { 407 {
417 { 408 {
418 NCOM::CPropVariant prop; 409 NCOM::CPropVariant prop;
419 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); 410 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop))
420 if (prop.vt != VT_EMPTY) 411 if (prop.vt != VT_EMPTY)
421 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) 412 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE)
422 return E_INVALIDARG; 413 return E_INVALIDARG;
@@ -428,14 +419,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
428 UInt64 size; 419 UInt64 size;
429 { 420 {
430 NCOM::CPropVariant prop; 421 NCOM::CPropVariant prop;
431 RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); 422 RINOK(updateCallback->GetProperty(0, kpidSize, &prop))
432 if (prop.vt != VT_UI8) 423 if (prop.vt != VT_UI8)
433 return E_INVALIDARG; 424 return E_INVALIDARG;
434 size = prop.uhVal.QuadPart; 425 size = prop.uhVal.QuadPart;
435 } 426 }
436 427
437 CMethodProps props2 = _props; 428 CMethodProps props2 = _props;
438 #ifndef _7ZIP_ST 429 #ifndef Z7_ST
439 props2.AddProp_NumThreads(_props._numThreads); 430 props2.AddProp_NumThreads(_props._numThreads);
440 #endif 431 #endif
441 432
@@ -449,8 +440,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
449 CMyComPtr<ICompressProgressInfo> progress = lps; 440 CMyComPtr<ICompressProgressInfo> progress = lps;
450 lps->Init(updateCallback, true); 441 lps->Init(updateCallback, true);
451 442
452 CMyComPtr<IArchiveUpdateCallbackFile> opCallback; 443 Z7_DECL_CMyComPtr_QI_FROM(
453 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); 444 IArchiveUpdateCallbackFile,
445 opCallback, updateCallback)
454 if (opCallback) 446 if (opCallback)
455 { 447 {
456 RINOK(opCallback->ReportOperation( 448 RINOK(opCallback->ReportOperation(
@@ -459,7 +451,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
459 } 451 }
460 452
461 if (_stream) 453 if (_stream)
462 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 454 RINOK(InStream_SeekToBegin(_stream))
463 455
464 return NCompress::CopyStream(_stream, outStream, progress); 456 return NCompress::CopyStream(_stream, outStream, progress);
465 457
@@ -468,7 +460,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
468 COM_TRY_END 460 COM_TRY_END
469} 461}
470 462
471STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 463Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
472{ 464{
473 return _props.SetProperties(names, values, numProps); 465 return _props.SetProperties(names, values, numProps);
474} 466}
diff --git a/CPP/7zip/Archive/Cab/CabBlockInStream.cpp b/CPP/7zip/Archive/Cab/CabBlockInStream.cpp
index c193434..dc767a4 100644
--- a/CPP/7zip/Archive/Cab/CabBlockInStream.cpp
+++ b/CPP/7zip/Archive/Cab/CabBlockInStream.cpp
@@ -18,7 +18,7 @@ bool CCabBlockInStream::Create()
18{ 18{
19 if (!_buf) 19 if (!_buf)
20 _buf = (Byte *)::MyAlloc(kBlockSize); 20 _buf = (Byte *)::MyAlloc(kBlockSize);
21 return _buf != 0; 21 return _buf != NULL;
22} 22}
23 23
24CCabBlockInStream::~CCabBlockInStream() 24CCabBlockInStream::~CCabBlockInStream()
@@ -60,7 +60,7 @@ HRESULT CCabBlockInStream::PreRead(ISequentialInStream *stream, UInt32 &packSize
60 unpackSize = GetUi16(header + 6); 60 unpackSize = GetUi16(header + 6);
61 if (packSize > kBlockSize - _size) 61 if (packSize > kBlockSize - _size)
62 return S_FALSE; 62 return S_FALSE;
63 RINOK(ReadStream_FALSE(stream, _buf + _size, packSize)); 63 RINOK(ReadStream_FALSE(stream, _buf + _size, packSize))
64 64
65 if (MsZip) 65 if (MsZip)
66 { 66 {
@@ -82,7 +82,7 @@ HRESULT CCabBlockInStream::PreRead(ISequentialInStream *stream, UInt32 &packSize
82 return S_OK; 82 return S_OK;
83} 83}
84 84
85STDMETHODIMP CCabBlockInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 85Z7_COM7F_IMF(CCabBlockInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
86{ 86{
87 if (size != 0) 87 if (size != 0)
88 { 88 {
diff --git a/CPP/7zip/Archive/Cab/CabBlockInStream.h b/CPP/7zip/Archive/Cab/CabBlockInStream.h
index af89abb..d14fff8 100644
--- a/CPP/7zip/Archive/Cab/CabBlockInStream.h
+++ b/CPP/7zip/Archive/Cab/CabBlockInStream.h
@@ -1,7 +1,7 @@
1// CabBlockInStream.h 1// CabBlockInStream.h
2 2
3#ifndef __CAB_BLOCK_IN_STREAM_H 3#ifndef ZIP7_INC_CAB_BLOCK_IN_STREAM_H
4#define __CAB_BLOCK_IN_STREAM_H 4#define ZIP7_INC_CAB_BLOCK_IN_STREAM_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../IStream.h" 7#include "../../IStream.h"
@@ -9,10 +9,10 @@
9namespace NArchive { 9namespace NArchive {
10namespace NCab { 10namespace NCab {
11 11
12class CCabBlockInStream: 12Z7_CLASS_IMP_NOQIB_1(
13 public ISequentialInStream, 13 CCabBlockInStream
14 public CMyUnknownImp 14 , ISequentialInStream
15{ 15)
16 Byte *_buf; 16 Byte *_buf;
17 UInt32 _size; 17 UInt32 _size;
18 UInt32 _pos; 18 UInt32 _pos;
@@ -21,9 +21,7 @@ public:
21 UInt32 ReservedSize; // < 256 21 UInt32 ReservedSize; // < 256
22 bool MsZip; 22 bool MsZip;
23 23
24 MY_UNKNOWN_IMP 24 CCabBlockInStream(): _buf(NULL), ReservedSize(0), MsZip(false) {}
25
26 CCabBlockInStream(): _buf(0), ReservedSize(0), MsZip(false) {}
27 ~CCabBlockInStream(); 25 ~CCabBlockInStream();
28 26
29 bool Create(); 27 bool Create();
@@ -34,8 +32,6 @@ public:
34 32
35 UInt32 GetPackSizeAvail() const { return _size - _pos; } 33 UInt32 GetPackSizeAvail() const { return _size - _pos; }
36 const Byte *GetData() const { return _buf + _pos; } 34 const Byte *GetData() const { return _buf + _pos; }
37
38 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
39}; 35};
40 36
41}} 37}}
diff --git a/CPP/7zip/Archive/Cab/CabHandler.cpp b/CPP/7zip/Archive/Cab/CabHandler.cpp
index 804c921..f015145 100644
--- a/CPP/7zip/Archive/Cab/CabHandler.cpp
+++ b/CPP/7zip/Archive/Cab/CabHandler.cpp
@@ -32,9 +32,9 @@ using namespace NWindows;
32namespace NArchive { 32namespace NArchive {
33namespace NCab { 33namespace NCab {
34 34
35// #define _CAB_DETAILS 35// #define CAB_DETAILS
36 36
37#ifdef _CAB_DETAILS 37#ifdef CAB_DETAILS
38enum 38enum
39{ 39{
40 kpidBlockReal = kpidUserDefined 40 kpidBlockReal = kpidUserDefined
@@ -49,7 +49,7 @@ static const Byte kProps[] =
49 kpidAttrib, 49 kpidAttrib,
50 kpidMethod, 50 kpidMethod,
51 kpidBlock 51 kpidBlock
52 #ifdef _CAB_DETAILS 52 #ifdef CAB_DETAILS
53 , 53 ,
54 // kpidBlockReal, // L"BlockReal", 54 // kpidBlockReal, // L"BlockReal",
55 kpidOffset, 55 kpidOffset,
@@ -83,7 +83,7 @@ static const unsigned kMethodNameBufSize = 32; // "Quantum:255"
83 83
84static void SetMethodName(char *s, unsigned method, unsigned param) 84static void SetMethodName(char *s, unsigned method, unsigned param)
85{ 85{
86 if (method < ARRAY_SIZE(kMethods)) 86 if (method < Z7_ARRAY_SIZE(kMethods))
87 { 87 {
88 s = MyStpCpy(s, kMethods[method]); 88 s = MyStpCpy(s, kMethods[method]);
89 if (method != NHeader::NMethod::kLZX && 89 if (method != NHeader::NMethod::kLZX &&
@@ -95,7 +95,7 @@ static void SetMethodName(char *s, unsigned method, unsigned param)
95 ConvertUInt32ToString(method, s); 95 ConvertUInt32ToString(method, s);
96} 96}
97 97
98STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 98Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
99{ 99{
100 COM_TRY_BEGIN 100 COM_TRY_BEGIN
101 NCOM::CPropVariant prop; 101 NCOM::CPropVariant prop;
@@ -267,7 +267,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
267 COM_TRY_END 267 COM_TRY_END
268} 268}
269 269
270STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 270Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
271{ 271{
272 COM_TRY_BEGIN 272 COM_TRY_BEGIN
273 NCOM::CPropVariant prop; 273 NCOM::CPropVariant prop;
@@ -305,7 +305,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
305 if (realFolderIndex >= 0) 305 if (realFolderIndex >= 0)
306 { 306 {
307 const CFolder &folder = db.Folders[(unsigned)realFolderIndex]; 307 const CFolder &folder = db.Folders[(unsigned)realFolderIndex];
308 char s[kMethodNameBufSize];; 308 char s[kMethodNameBufSize];
309 SetMethodName(s, folder.GetMethod(), folder.MethodMinor); 309 SetMethodName(s, folder.GetMethod(), folder.MethodMinor);
310 prop = s; 310 prop = s;
311 } 311 }
@@ -314,7 +314,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
314 314
315 case kpidBlock: prop.Set_Int32((Int32)m_Database.GetFolderIndex(&mvItem)); break; 315 case kpidBlock: prop.Set_Int32((Int32)m_Database.GetFolderIndex(&mvItem)); break;
316 316
317 #ifdef _CAB_DETAILS 317 #ifdef CAB_DETAILS
318 318
319 // case kpidBlockReal: prop = (UInt32)item.FolderIndex; break; 319 // case kpidBlockReal: prop = (UInt32)item.FolderIndex; break;
320 case kpidOffset: prop = (UInt32)item.Offset; break; 320 case kpidOffset: prop = (UInt32)item.Offset; break;
@@ -327,9 +327,9 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
327 COM_TRY_END 327 COM_TRY_END
328} 328}
329 329
330STDMETHODIMP CHandler::Open(IInStream *inStream, 330Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
331 const UInt64 *maxCheckStartPosition, 331 const UInt64 *maxCheckStartPosition,
332 IArchiveOpenCallback *callback) 332 IArchiveOpenCallback *callback))
333{ 333{
334 COM_TRY_BEGIN 334 COM_TRY_BEGIN
335 Close(); 335 Close();
@@ -418,7 +418,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
418 418
419 if (callback) 419 if (callback)
420 { 420 {
421 RINOK(callback->SetCompleted(&numItems, NULL)); 421 RINOK(callback->SetCompleted(&numItems, NULL))
422 } 422 }
423 423
424 nextStream = NULL; 424 nextStream = NULL;
@@ -471,7 +471,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
471 startVolName_was_Requested = true; 471 startVolName_was_Requested = true;
472 { 472 {
473 NCOM::CPropVariant prop; 473 NCOM::CPropVariant prop;
474 RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); 474 RINOK(openVolumeCallback->GetProperty(kpidName, &prop))
475 if (prop.vt == VT_BSTR) 475 if (prop.vt == VT_BSTR)
476 startVolName = prop.bstrVal; 476 startVolName = prop.bstrVal;
477 } 477 }
@@ -520,7 +520,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
520 return S_OK; 520 return S_OK;
521} 521}
522 522
523STDMETHODIMP CHandler::Close() 523Z7_COM7F_IMF(CHandler::Close())
524{ 524{
525 _errorMessage.Empty(); 525 _errorMessage.Empty();
526 _isArc = false; 526 _isArc = false;
@@ -534,15 +534,11 @@ STDMETHODIMP CHandler::Close()
534 return S_OK; 534 return S_OK;
535} 535}
536 536
537class CFolderOutStream:
538 public ISequentialOutStream,
539 public CMyUnknownImp
540{
541public:
542 MY_UNKNOWN_IMP
543 537
544 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); 538Z7_CLASS_IMP_NOQIB_1(
545private: 539 CFolderOutStream
540 , ISequentialOutStream
541)
546 const CMvDatabaseEx *m_Database; 542 const CMvDatabaseEx *m_Database;
547 const CRecordVector<bool> *m_ExtractStatuses; 543 const CRecordVector<bool> *m_ExtractStatuses;
548 544
@@ -681,10 +677,10 @@ HRESULT CFolderOutStream::OpenFile()
681 while (NumIdenticalFiles && !(*m_ExtractStatuses)[m_CurrentIndex]) 677 while (NumIdenticalFiles && !(*m_ExtractStatuses)[m_CurrentIndex])
682 { 678 {
683 CMyComPtr<ISequentialOutStream> stream; 679 CMyComPtr<ISequentialOutStream> stream;
684 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &stream, NExtract::NAskMode::kSkip)); 680 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &stream, NExtract::NAskMode::kSkip))
685 if (stream) 681 if (stream)
686 return E_FAIL; 682 return E_FAIL;
687 RINOK(m_ExtractCallback->PrepareOperation(NExtract::NAskMode::kSkip)); 683 RINOK(m_ExtractCallback->PrepareOperation(NExtract::NAskMode::kSkip))
688 m_CurrentIndex++; 684 m_CurrentIndex++;
689 m_FileIsOpen = true; 685 m_FileIsOpen = true;
690 CloseFile(); 686 CloseFile();
@@ -692,11 +688,11 @@ HRESULT CFolderOutStream::OpenFile()
692 } 688 }
693 } 689 }
694 690
695 Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? (m_TestMode ? 691 Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? m_TestMode ?
696 NExtract::NAskMode::kTest : 692 NExtract::NAskMode::kTest :
697 NExtract::NAskMode::kExtract) : 693 NExtract::NAskMode::kExtract :
698 NExtract::NAskMode::kSkip; 694 NExtract::NAskMode::kSkip;
699 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)); 695 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode))
700 if (!m_RealOutStream && !m_TestMode) 696 if (!m_RealOutStream && !m_TestMode)
701 askMode = NExtract::NAskMode::kSkip; 697 askMode = NExtract::NAskMode::kSkip;
702 return m_ExtractCallback->PrepareOperation(askMode); 698 return m_ExtractCallback->PrepareOperation(askMode);
@@ -716,14 +712,14 @@ HRESULT CFolderOutStream::WriteEmptyFiles()
716 return S_OK; 712 return S_OK;
717 HRESULT result = OpenFile(); 713 HRESULT result = OpenFile();
718 m_RealOutStream.Release(); 714 m_RealOutStream.Release();
719 RINOK(result); 715 RINOK(result)
720 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 716 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
721 } 717 }
722 return S_OK; 718 return S_OK;
723} 719}
724 720
725 721
726HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 722Z7_COM7F_IMF(CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
727{ 723{
728 // (data == NULL) means Error_Data for solid folder flushing 724 // (data == NULL) means Error_Data for solid folder flushing
729 COM_TRY_BEGIN 725 COM_TRY_BEGIN
@@ -777,7 +773,7 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed
777 773
778 if (m_RemainFileSize == 0) 774 if (m_RemainFileSize == 0)
779 { 775 {
780 RINOK(CloseFile()); 776 RINOK(CloseFile())
781 777
782 while (NumIdenticalFiles) 778 while (NumIdenticalFiles)
783 { 779 {
@@ -789,14 +785,14 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed
789 785
790 if (!TempBuf && TempBufMode && m_RealOutStream) 786 if (!TempBuf && TempBufMode && m_RealOutStream)
791 { 787 {
792 RINOK(CloseFileWithResOp(NExtract::NOperationResult::kUnsupportedMethod)); 788 RINOK(CloseFileWithResOp(NExtract::NOperationResult::kUnsupportedMethod))
793 } 789 }
794 else 790 else
795 { 791 {
796 RINOK(CloseFile()); 792 RINOK(CloseFile())
797 } 793 }
798 794
799 RINOK(result); 795 RINOK(result)
800 } 796 }
801 797
802 TempBufMode = false; 798 TempBufMode = false;
@@ -842,7 +838,7 @@ HRESULT CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processed
842 838
843 if (fileOffset == m_PosInFolder) 839 if (fileOffset == m_PosInFolder)
844 { 840 {
845 RINOK(OpenFile()); 841 RINOK(OpenFile())
846 m_FileIsOpen = true; 842 m_FileIsOpen = true;
847 m_CurrentIndex++; 843 m_CurrentIndex++;
848 m_IsOk = true; 844 m_IsOk = true;
@@ -860,11 +856,11 @@ HRESULT CFolderOutStream::FlushCorrupted(unsigned folderIndex)
860{ 856{
861 if (!NeedMoreWrite()) 857 if (!NeedMoreWrite())
862 { 858 {
863 CMyComPtr<IArchiveExtractCallbackMessage> callbackMessage; 859 CMyComPtr<IArchiveExtractCallbackMessage2> callbackMessage;
864 m_ExtractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage, &callbackMessage); 860 m_ExtractCallback.QueryInterface(IID_IArchiveExtractCallbackMessage2, &callbackMessage);
865 if (callbackMessage) 861 if (callbackMessage)
866 { 862 {
867 RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, NExtract::NOperationResult::kDataError)); 863 RINOK(callbackMessage->ReportExtractResult(NEventIndexType::kBlockIndex, folderIndex, NExtract::NOperationResult::kDataError))
868 } 864 }
869 return S_OK; 865 return S_OK;
870 } 866 }
@@ -878,7 +874,7 @@ HRESULT CFolderOutStream::FlushCorrupted(unsigned folderIndex)
878 if (size > remain) 874 if (size > remain)
879 size = (UInt32)remain; 875 size = (UInt32)remain;
880 UInt32 processedSizeLocal = 0; 876 UInt32 processedSizeLocal = 0;
881 RINOK(Write(NULL, size, &processedSizeLocal)); 877 RINOK(Write(NULL, size, &processedSizeLocal))
882 } 878 }
883} 879}
884 880
@@ -891,19 +887,18 @@ HRESULT CFolderOutStream::Unsupported()
891 if (result != S_FALSE && result != S_OK) 887 if (result != S_FALSE && result != S_OK)
892 return result; 888 return result;
893 m_RealOutStream.Release(); 889 m_RealOutStream.Release();
894 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 890 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
895 m_CurrentIndex++; 891 m_CurrentIndex++;
896 } 892 }
897 return S_OK; 893 return S_OK;
898} 894}
899 895
900 896
901STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 897Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
902 Int32 testModeSpec, IArchiveExtractCallback *extractCallback) 898 Int32 testModeSpec, IArchiveExtractCallback *extractCallback))
903{ 899{
904 COM_TRY_BEGIN 900 COM_TRY_BEGIN
905 901 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
906 bool allFilesMode = (numItems == (UInt32)(Int32)-1);
907 if (allFilesMode) 902 if (allFilesMode)
908 numItems = m_Database.Items.Size(); 903 numItems = m_Database.Items.Size();
909 if (numItems == 0) 904 if (numItems == 0)
@@ -964,45 +959,45 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
964 { 959 {
965 lps->OutSize = totalUnPacked; 960 lps->OutSize = totalUnPacked;
966 lps->InSize = totalPacked; 961 lps->InSize = totalPacked;
967 RINOK(lps->SetCur()); 962 RINOK(lps->SetCur())
968 963
969 if (i >= numItems) 964 if (i >= numItems)
970 break; 965 break;
971 966
972 unsigned index = allFilesMode ? i : indices[i]; 967 const unsigned index = allFilesMode ? i : indices[i];
973 968
974 const CMvItem &mvItem = m_Database.Items[index]; 969 const CMvItem &mvItem = m_Database.Items[index];
975 const CDatabaseEx &db = m_Database.Volumes[mvItem.VolumeIndex]; 970 const CDatabaseEx &db = m_Database.Volumes[mvItem.VolumeIndex];
976 unsigned itemIndex = mvItem.ItemIndex; 971 const unsigned itemIndex = mvItem.ItemIndex;
977 const CItem &item = db.Items[itemIndex]; 972 const CItem &item = db.Items[itemIndex];
978 973
979 i++; 974 i++;
980 if (item.IsDir()) 975 if (item.IsDir())
981 { 976 {
982 Int32 askMode = testMode ? 977 const Int32 askMode = testMode ?
983 NExtract::NAskMode::kTest : 978 NExtract::NAskMode::kTest :
984 NExtract::NAskMode::kExtract; 979 NExtract::NAskMode::kExtract;
985 CMyComPtr<ISequentialOutStream> realOutStream; 980 CMyComPtr<ISequentialOutStream> realOutStream;
986 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 981 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
987 RINOK(extractCallback->PrepareOperation(askMode)); 982 RINOK(extractCallback->PrepareOperation(askMode))
988 realOutStream.Release(); 983 realOutStream.Release();
989 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 984 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
990 continue; 985 continue;
991 } 986 }
992 987
993 int folderIndex = m_Database.GetFolderIndex(&mvItem); 988 const int folderIndex = m_Database.GetFolderIndex(&mvItem);
994 989
995 if (folderIndex < 0) 990 if (folderIndex < 0)
996 { 991 {
997 // If we need previous archive 992 // If we need previous archive
998 Int32 askMode= testMode ? 993 const Int32 askMode= testMode ?
999 NExtract::NAskMode::kTest : 994 NExtract::NAskMode::kTest :
1000 NExtract::NAskMode::kExtract; 995 NExtract::NAskMode::kExtract;
1001 CMyComPtr<ISequentialOutStream> realOutStream; 996 CMyComPtr<ISequentialOutStream> realOutStream;
1002 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 997 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1003 RINOK(extractCallback->PrepareOperation(askMode)); 998 RINOK(extractCallback->PrepareOperation(askMode))
1004 realOutStream.Release(); 999 realOutStream.Release();
1005 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError)); 1000 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError))
1006 continue; 1001 continue;
1007 } 1002 }
1008 1003
@@ -1017,12 +1012,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1017 1012
1018 for (; i < numItems; i++) 1013 for (; i < numItems; i++)
1019 { 1014 {
1020 unsigned indexNext = allFilesMode ? i : indices[i]; 1015 const unsigned indexNext = allFilesMode ? i : indices[i];
1021 const CMvItem &mvItem2 = m_Database.Items[indexNext]; 1016 const CMvItem &mvItem2 = m_Database.Items[indexNext];
1022 const CItem &item2 = m_Database.Volumes[mvItem2.VolumeIndex].Items[mvItem2.ItemIndex]; 1017 const CItem &item2 = m_Database.Volumes[mvItem2.VolumeIndex].Items[mvItem2.ItemIndex];
1023 if (item2.IsDir()) 1018 if (item2.IsDir())
1024 continue; 1019 continue;
1025 int newFolderIndex = m_Database.GetFolderIndex(&mvItem2); 1020 const int newFolderIndex = m_Database.GetFolderIndex(&mvItem2);
1026 1021
1027 if (newFolderIndex != folderIndex) 1022 if (newFolderIndex != folderIndex)
1028 break; 1023 break;
@@ -1086,11 +1081,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1086 1081
1087 if (res == E_INVALIDARG) 1082 if (res == E_INVALIDARG)
1088 { 1083 {
1089 RINOK(cabFolderOutStream->Unsupported()); 1084 RINOK(cabFolderOutStream->Unsupported())
1090 totalUnPacked += curUnpack; 1085 totalUnPacked += curUnpack;
1091 continue; 1086 continue;
1092 } 1087 }
1093 RINOK(res); 1088 RINOK(res)
1094 1089
1095 { 1090 {
1096 unsigned volIndex = mvItem.VolumeIndex; 1091 unsigned volIndex = mvItem.VolumeIndex;
@@ -1115,7 +1110,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1115 if (bl == 0) 1110 if (bl == 0)
1116 { 1111 {
1117 cabBlockInStreamSpec->ReservedSize = db2.ArcInfo.GetDataBlockReserveSize(); 1112 cabBlockInStreamSpec->ReservedSize = db2.ArcInfo.GetDataBlockReserveSize();
1118 RINOK(db2.Stream->Seek((Int64)(db2.StartPosition + folder2.DataStart), STREAM_SEEK_SET, NULL)); 1113 RINOK(InStream_SeekSet(db2.Stream, db2.StartPosition + folder2.DataStart))
1119 } 1114 }
1120 1115
1121 if (bl == folder2.NumDataBlocks) 1116 if (bl == folder2.NumDataBlocks)
@@ -1146,7 +1141,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1146 res = cabBlockInStreamSpec->PreRead(db2.Stream, packSize, unpackSize); 1141 res = cabBlockInStreamSpec->PreRead(db2.Stream, packSize, unpackSize);
1147 if (res == S_FALSE) 1142 if (res == S_FALSE)
1148 break; 1143 break;
1149 RINOK(res); 1144 RINOK(res)
1150 keepInputBuffer = (unpackSize == 0); 1145 keepInputBuffer = (unpackSize == 0);
1151 if (keepInputBuffer) 1146 if (keepInputBuffer)
1152 continue; 1147 continue;
@@ -1156,7 +1151,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1156 1151
1157 lps->OutSize = totalUnPacked2; 1152 lps->OutSize = totalUnPacked2;
1158 lps->InSize = totalPacked; 1153 lps->InSize = totalPacked;
1159 RINOK(lps->SetCur()); 1154 RINOK(lps->SetCur())
1160 1155
1161 const UInt32 kBlockSizeMax = (1 << 15); 1156 const UInt32 kBlockSizeMax = (1 << 15);
1162 1157
@@ -1230,7 +1225,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1230 if (res != S_OK) 1225 if (res != S_OK)
1231 { 1226 {
1232 if (res != S_FALSE) 1227 if (res != S_FALSE)
1233 RINOK(res); 1228 RINOK(res)
1234 break; 1229 break;
1235 } 1230 }
1236 1231
@@ -1239,13 +1234,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1239 1234
1240 if (res == S_OK) 1235 if (res == S_OK)
1241 { 1236 {
1242 RINOK(cabFolderOutStream->WriteEmptyFiles()); 1237 RINOK(cabFolderOutStream->WriteEmptyFiles())
1243 } 1238 }
1244 } 1239 }
1245 1240
1246 if (res != S_OK || cabFolderOutStream->NeedMoreWrite()) 1241 if (res != S_OK || cabFolderOutStream->NeedMoreWrite())
1247 { 1242 {
1248 RINOK(cabFolderOutStream->FlushCorrupted((unsigned)folderIndex2)); 1243 RINOK(cabFolderOutStream->FlushCorrupted((unsigned)folderIndex2))
1249 } 1244 }
1250 1245
1251 totalUnPacked += curUnpack; 1246 totalUnPacked += curUnpack;
@@ -1257,7 +1252,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1257} 1252}
1258 1253
1259 1254
1260STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1255Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1261{ 1256{
1262 *numItems = m_Database.Items.Size(); 1257 *numItems = m_Database.Items.Size();
1263 return S_OK; 1258 return S_OK;
diff --git a/CPP/7zip/Archive/Cab/CabHandler.h b/CPP/7zip/Archive/Cab/CabHandler.h
index 6f44b87..1e1811f 100644
--- a/CPP/7zip/Archive/Cab/CabHandler.h
+++ b/CPP/7zip/Archive/Cab/CabHandler.h
@@ -1,7 +1,7 @@
1// CabHandler.h 1// CabHandler.h
2 2
3#ifndef __CAB_HANDLER_H 3#ifndef ZIP7_INC_CAB_HANDLER_H
4#define __CAB_HANDLER_H 4#define ZIP7_INC_CAB_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -12,16 +12,8 @@
12namespace NArchive { 12namespace NArchive {
13namespace NCab { 13namespace NCab {
14 14
15class CHandler: 15Z7_CLASS_IMP_CHandler_IInArchive_0
16 public IInArchive,
17 public CMyUnknownImp
18{
19public:
20 MY_UNKNOWN_IMP1(IInArchive)
21 16
22 INTERFACE_IInArchive(;)
23
24private:
25 CMvDatabaseEx m_Database; 17 CMvDatabaseEx m_Database;
26 UString _errorMessage; 18 UString _errorMessage;
27 bool _isArc; 19 bool _isArc;
diff --git a/CPP/7zip/Archive/Cab/CabHeader.h b/CPP/7zip/Archive/Cab/CabHeader.h
index 2f2bd10..ecb9a87 100644
--- a/CPP/7zip/Archive/Cab/CabHeader.h
+++ b/CPP/7zip/Archive/Cab/CabHeader.h
@@ -1,7 +1,7 @@
1// Archive/CabHeader.h 1// Archive/CabHeader.h
2 2
3#ifndef __ARCHIVE_CAB_HEADER_H 3#ifndef ZIP7_INC_ARCHIVE_CAB_HEADER_H
4#define __ARCHIVE_CAB_HEADER_H 4#define ZIP7_INC_ARCHIVE_CAB_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
diff --git a/CPP/7zip/Archive/Cab/CabIn.cpp b/CPP/7zip/Archive/Cab/CabIn.cpp
index e11ce9d..fb69643 100644
--- a/CPP/7zip/Archive/Cab/CabIn.cpp
+++ b/CPP/7zip/Archive/Cab/CabIn.cpp
@@ -76,9 +76,9 @@ struct CSignatureFinder
76 const Byte *Signature; 76 const Byte *Signature;
77 UInt32 SignatureSize; 77 UInt32 SignatureSize;
78 78
79 UInt32 _HeaderSize; 79 UInt32 _headerSize;
80 UInt32 _AlignSize; 80 UInt32 _alignSize;
81 UInt32 _BufUseCapacity; 81 UInt32 _bufUseCapacity;
82 82
83 ISequentialInStream *Stream; 83 ISequentialInStream *Stream;
84 UInt64 Processed; // Global offset of start of Buf 84 UInt64 Processed; // Global offset of start of Buf
@@ -87,10 +87,10 @@ struct CSignatureFinder
87 87
88 UInt32 GetTotalCapacity(UInt32 basicSize, UInt32 headerSize) 88 UInt32 GetTotalCapacity(UInt32 basicSize, UInt32 headerSize)
89 { 89 {
90 _HeaderSize = headerSize; 90 _headerSize = headerSize;
91 for (_AlignSize = (1 << 5); _AlignSize < _HeaderSize; _AlignSize <<= 1); 91 for (_alignSize = (1 << 5); _alignSize < _headerSize; _alignSize <<= 1);
92 _BufUseCapacity = basicSize + _AlignSize; 92 _bufUseCapacity = basicSize + _alignSize;
93 return _BufUseCapacity + 16; 93 return _bufUseCapacity + 16;
94 } 94 }
95 95
96 /* 96 /*
@@ -108,7 +108,7 @@ HRESULT CSignatureFinder::Find()
108 { 108 {
109 Buf[End] = Signature[0]; // it's for fast search; 109 Buf[End] = Signature[0]; // it's for fast search;
110 110
111 while (End - Pos >= _HeaderSize) 111 while (End - Pos >= _headerSize)
112 { 112 {
113 const Byte *p = Buf + Pos; 113 const Byte *p = Buf + Pos;
114 Byte b = Signature[0]; 114 Byte b = Signature[0];
@@ -118,9 +118,9 @@ HRESULT CSignatureFinder::Find()
118 if (*p == b) { break; } p++; 118 if (*p == b) { break; } p++;
119 } 119 }
120 Pos = (UInt32)(p - Buf); 120 Pos = (UInt32)(p - Buf);
121 if (End - Pos < _HeaderSize) 121 if (End - Pos < _headerSize)
122 { 122 {
123 Pos = End - _HeaderSize + 1; 123 Pos = End - _headerSize + 1;
124 break; 124 break;
125 } 125 }
126 UInt32 i; 126 UInt32 i;
@@ -130,28 +130,28 @@ HRESULT CSignatureFinder::Find()
130 Pos++; 130 Pos++;
131 } 131 }
132 132
133 if (Pos >= _AlignSize) 133 if (Pos >= _alignSize)
134 { 134 {
135 UInt32 num = (Pos & ~(_AlignSize - 1)); 135 UInt32 num = (Pos & ~(_alignSize - 1));
136 Processed += num; 136 Processed += num;
137 Pos -= num; 137 Pos -= num;
138 End -= num; 138 End -= num;
139 memmove(Buf, Buf + num, End); 139 memmove(Buf, Buf + num, End);
140 } 140 }
141 UInt32 rem = _BufUseCapacity - End; 141 UInt32 rem = _bufUseCapacity - End;
142 if (SearchLimit) 142 if (SearchLimit)
143 { 143 {
144 if (Processed + Pos > *SearchLimit) 144 if (Processed + Pos > *SearchLimit)
145 return S_FALSE; 145 return S_FALSE;
146 UInt64 rem2 = *SearchLimit - (Processed + End) + _HeaderSize; 146 UInt64 rem2 = *SearchLimit - (Processed + End) + _headerSize;
147 if (rem > rem2) 147 if (rem > rem2)
148 rem = (UInt32)rem2; 148 rem = (UInt32)rem2;
149 } 149 }
150 150
151 UInt32 processedSize; 151 UInt32 processedSize;
152 if (Processed == 0 && rem == _BufUseCapacity - _HeaderSize) 152 if (Processed == 0 && rem == _bufUseCapacity - _headerSize)
153 rem -= _AlignSize; // to make reads more aligned. 153 rem -= _alignSize; // to make reads more aligned.
154 RINOK(Stream->Read(Buf + End, rem, &processedSize)); 154 RINOK(Stream->Read(Buf + End, rem, &processedSize))
155 if (processedSize == 0) 155 if (processedSize == 0)
156 return S_FALSE; 156 return S_FALSE;
157 End += processedSize; 157 End += processedSize;
@@ -189,7 +189,7 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
189 HeaderError = false; 189 HeaderError = false;
190 190
191 db.Clear(); 191 db.Clear();
192 RINOK(db.Stream->Seek(0, STREAM_SEEK_CUR, &db.StartPosition)); 192 RINOK(InStream_GetPos(db.Stream, db.StartPosition))
193 // UInt64 temp = db.StartPosition; 193 // UInt64 temp = db.StartPosition;
194 194
195 CByteBuffer buffer; 195 CByteBuffer buffer;
@@ -201,12 +201,12 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
201 201
202 // for (int iii = 0; iii < 10000; iii++) 202 // for (int iii = 0; iii < 10000; iii++)
203 { 203 {
204 // db.StartPosition = temp; RINOK(db.Stream->Seek(db.StartPosition, STREAM_SEEK_SET, NULL)); 204 // db.StartPosition = temp; RINOK(InStream_SeekSet(db.Stream, db.StartPosition))
205 205
206 const UInt32 kMainHeaderSize = 32; 206 const UInt32 kMainHeaderSize = 32;
207 Byte header[kMainHeaderSize]; 207 Byte header[kMainHeaderSize];
208 const UInt32 kBufSize = 1 << 15; 208 const UInt32 kBufSize = 1 << 15;
209 RINOK(ReadStream_FALSE(db.Stream, header, kMainHeaderSize)); 209 RINOK(ReadStream_FALSE(db.Stream, header, kMainHeaderSize))
210 if (memcmp(header, NHeader::kMarker, NHeader::kMarkerSize) == 0 && ai.Parse(header)) 210 if (memcmp(header, NHeader::kMarker, NHeader::kMarkerSize) == 0 && ai.Parse(header))
211 { 211 {
212 limitedStreamSpec = new CLimitedSequentialInStream; 212 limitedStreamSpec = new CLimitedSequentialInStream;
@@ -216,7 +216,7 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
216 buffer.Alloc(kBufSize); 216 buffer.Alloc(kBufSize);
217 memcpy(buffer, header, kMainHeaderSize); 217 memcpy(buffer, header, kMainHeaderSize);
218 UInt32 numProcessedBytes; 218 UInt32 numProcessedBytes;
219 RINOK(limitedStream->Read(buffer + kMainHeaderSize, kBufSize - kMainHeaderSize, &numProcessedBytes)); 219 RINOK(limitedStream->Read(buffer + kMainHeaderSize, kBufSize - kMainHeaderSize, &numProcessedBytes))
220 _inBuffer.SetBuf(buffer, (UInt32)kBufSize, kMainHeaderSize + numProcessedBytes, kMainHeaderSize); 220 _inBuffer.SetBuf(buffer, (UInt32)kBufSize, kMainHeaderSize + numProcessedBytes, kMainHeaderSize);
221 } 221 }
222 else 222 else
@@ -241,7 +241,7 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
241 241
242 for (;;) 242 for (;;)
243 { 243 {
244 RINOK(finder.Find()); 244 RINOK(finder.Find())
245 if (ai.Parse(finder.Buf + finder.Pos)) 245 if (ai.Parse(finder.Buf + finder.Pos))
246 { 246 {
247 db.StartPosition = finder.Processed + finder.Pos; 247 db.StartPosition = finder.Processed + finder.Pos;
@@ -311,7 +311,7 @@ HRESULT CInArchive::Open2(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
311 { 311 {
312 // printf("\n!!! Seek Error !!!!\n"); 312 // printf("\n!!! Seek Error !!!!\n");
313 // fflush(stdout); 313 // fflush(stdout);
314 RINOK(db.Stream->Seek((Int64)(db.StartPosition + ai.FileHeadersOffset), STREAM_SEEK_SET, NULL)); 314 RINOK(InStream_SeekSet(db.Stream, db.StartPosition + ai.FileHeadersOffset))
315 limitedStreamSpec->Init(ai.Size - ai.FileHeadersOffset); 315 limitedStreamSpec->Init(ai.Size - ai.FileHeadersOffset);
316 _inBuffer.Init(); 316 _inBuffer.Init();
317 } 317 }
@@ -357,7 +357,7 @@ HRESULT CInArchive::Open(CDatabaseEx &db, const UInt64 *searchHeaderSizeLimit)
357 357
358 358
359 359
360#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 360#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
361 361
362static int CompareMvItems(const CMvItem *p1, const CMvItem *p2, void *param) 362static int CompareMvItems(const CMvItem *p1, const CMvItem *p2, void *param)
363{ 363{
@@ -365,17 +365,17 @@ static int CompareMvItems(const CMvItem *p1, const CMvItem *p2, void *param)
365 const CDatabaseEx &db1 = mvDb.Volumes[p1->VolumeIndex]; 365 const CDatabaseEx &db1 = mvDb.Volumes[p1->VolumeIndex];
366 const CDatabaseEx &db2 = mvDb.Volumes[p2->VolumeIndex]; 366 const CDatabaseEx &db2 = mvDb.Volumes[p2->VolumeIndex];
367 const CItem &item1 = db1.Items[p1->ItemIndex]; 367 const CItem &item1 = db1.Items[p1->ItemIndex];
368 const CItem &item2 = db2.Items[p2->ItemIndex];; 368 const CItem &item2 = db2.Items[p2->ItemIndex];
369 bool isDir1 = item1.IsDir(); 369 bool isDir1 = item1.IsDir();
370 bool isDir2 = item2.IsDir(); 370 bool isDir2 = item2.IsDir();
371 if (isDir1 && !isDir2) return -1; 371 if (isDir1 && !isDir2) return -1;
372 if (isDir2 && !isDir1) return 1; 372 if (isDir2 && !isDir1) return 1;
373 int f1 = mvDb.GetFolderIndex(p1); 373 int f1 = mvDb.GetFolderIndex(p1);
374 int f2 = mvDb.GetFolderIndex(p2); 374 int f2 = mvDb.GetFolderIndex(p2);
375 RINOZ(MyCompare(f1, f2)); 375 RINOZ(MyCompare(f1, f2))
376 RINOZ(MyCompare(item1.Offset, item2.Offset)); 376 RINOZ(MyCompare(item1.Offset, item2.Offset))
377 RINOZ(MyCompare(item1.Size, item2.Size)); 377 RINOZ(MyCompare(item1.Size, item2.Size))
378 RINOZ(MyCompare(p1->VolumeIndex, p2->VolumeIndex)); 378 RINOZ(MyCompare(p1->VolumeIndex, p2->VolumeIndex))
379 return MyCompare(p1->ItemIndex, p2->ItemIndex); 379 return MyCompare(p1->ItemIndex, p2->ItemIndex);
380} 380}
381 381
@@ -387,7 +387,7 @@ bool CMvDatabaseEx::AreItemsEqual(unsigned i1, unsigned i2)
387 const CDatabaseEx &db1 = Volumes[p1->VolumeIndex]; 387 const CDatabaseEx &db1 = Volumes[p1->VolumeIndex];
388 const CDatabaseEx &db2 = Volumes[p2->VolumeIndex]; 388 const CDatabaseEx &db2 = Volumes[p2->VolumeIndex];
389 const CItem &item1 = db1.Items[p1->ItemIndex]; 389 const CItem &item1 = db1.Items[p1->ItemIndex];
390 const CItem &item2 = db2.Items[p2->ItemIndex];; 390 const CItem &item2 = db2.Items[p2->ItemIndex];
391 return GetFolderIndex(p1) == GetFolderIndex(p2) 391 return GetFolderIndex(p1) == GetFolderIndex(p2)
392 && item1.Offset == item2.Offset 392 && item1.Offset == item2.Offset
393 && item1.Size == item2.Size 393 && item1.Size == item2.Size
diff --git a/CPP/7zip/Archive/Cab/CabIn.h b/CPP/7zip/Archive/Cab/CabIn.h
index 39586d1..06aa34c 100644
--- a/CPP/7zip/Archive/Cab/CabIn.h
+++ b/CPP/7zip/Archive/Cab/CabIn.h
@@ -1,7 +1,7 @@
1// Archive/CabIn.h 1// Archive/CabIn.h
2 2
3#ifndef __ARCHIVE_CAB_IN_H 3#ifndef ZIP7_INC_ARCHIVE_CAB_IN_H
4#define __ARCHIVE_CAB_IN_H 4#define ZIP7_INC_ARCHIVE_CAB_IN_H
5 5
6#include "../../../Common/MyBuffer.h" 6#include "../../../Common/MyBuffer.h"
7#include "../../../Common/MyCom.h" 7#include "../../../Common/MyCom.h"
diff --git a/CPP/7zip/Archive/Cab/CabItem.h b/CPP/7zip/Archive/Cab/CabItem.h
index 9a912d5..b7e07d1 100644
--- a/CPP/7zip/Archive/Cab/CabItem.h
+++ b/CPP/7zip/Archive/Cab/CabItem.h
@@ -1,7 +1,7 @@
1// Archive/CabItem.h 1// Archive/CabItem.h
2 2
3#ifndef __ARCHIVE_CAB_ITEM_H 3#ifndef ZIP7_INC_ARCHIVE_CAB_ITEM_H
4#define __ARCHIVE_CAB_ITEM_H 4#define ZIP7_INC_ARCHIVE_CAB_ITEM_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/Archive/Cab/CabRegister.cpp b/CPP/7zip/Archive/Cab/CabRegister.cpp
index 0b5cc93..8f4f323 100644
--- a/CPP/7zip/Archive/Cab/CabRegister.cpp
+++ b/CPP/7zip/Archive/Cab/CabRegister.cpp
@@ -10,7 +10,7 @@ namespace NArchive {
10namespace NCab { 10namespace NCab {
11 11
12REGISTER_ARC_I( 12REGISTER_ARC_I(
13 "Cab", "cab", 0, 8, 13 "Cab", "cab", NULL, 8,
14 NHeader::kMarker, 14 NHeader::kMarker,
15 0, 15 0,
16 NArcInfoFlags::kFindSignature, 16 NArcInfoFlags::kFindSignature,
diff --git a/CPP/7zip/Archive/Cab/StdAfx.h b/CPP/7zip/Archive/Cab/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Cab/StdAfx.h
+++ b/CPP/7zip/Archive/Cab/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/Chm/ChmHandler.cpp b/CPP/7zip/Archive/Chm/ChmHandler.cpp
index 03e7ddd..38e2543 100644
--- a/CPP/7zip/Archive/Chm/ChmHandler.cpp
+++ b/CPP/7zip/Archive/Chm/ChmHandler.cpp
@@ -27,9 +27,9 @@ using namespace NTime;
27namespace NArchive { 27namespace NArchive {
28namespace NChm { 28namespace NChm {
29 29
30// #define _CHM_DETAILS 30// #define CHM_DETAILS
31 31
32#ifdef _CHM_DETAILS 32#ifdef CHM_DETAILS
33 33
34enum 34enum
35{ 35{
@@ -45,7 +45,7 @@ static const Byte kProps[] =
45 kpidMethod, 45 kpidMethod,
46 kpidBlock 46 kpidBlock
47 47
48 #ifdef _CHM_DETAILS 48 #ifdef CHM_DETAILS
49 , 49 ,
50 L"Section", kpidSection, 50 L"Section", kpidSection,
51 kpidOffset 51 kpidOffset
@@ -63,7 +63,7 @@ IMP_IInArchive_Props
63 63
64IMP_IInArchive_ArcProps_NO_Table 64IMP_IInArchive_ArcProps_NO_Table
65 65
66STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 66Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
67{ 67{
68 // COM_TRY_BEGIN 68 // COM_TRY_BEGIN
69 NCOM::CPropVariant prop; 69 NCOM::CPropVariant prop;
@@ -97,7 +97,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
97 // COM_TRY_END 97 // COM_TRY_END
98} 98}
99 99
100STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 100Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
101{ 101{
102 COM_TRY_BEGIN 102 COM_TRY_BEGIN
103 NCOM::CPropVariant prop; 103 NCOM::CPropVariant prop;
@@ -160,7 +160,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
160 prop = m_Database.GetFolder(index); 160 prop = m_Database.GetFolder(index);
161 break; 161 break;
162 162
163 #ifdef _CHM_DETAILS 163 #ifdef CHM_DETAILS
164 164
165 case kpidSection: prop = (UInt32)item.Section; break; 165 case kpidSection: prop = (UInt32)item.Section; break;
166 case kpidOffset: prop = (UInt32)item.Offset; break; 166 case kpidOffset: prop = (UInt32)item.Offset; break;
@@ -173,34 +173,10 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
173 COM_TRY_END 173 COM_TRY_END
174} 174}
175 175
176/*
177class CProgressImp: public CProgressVirt
178{
179 CMyComPtr<IArchiveOpenCallback> _callback;
180public:
181 STDMETHOD(SetTotal)(const UInt64 *numFiles);
182 STDMETHOD(SetCompleted)(const UInt64 *numFiles);
183 CProgressImp(IArchiveOpenCallback *callback): _callback(callback) {};
184};
185
186STDMETHODIMP CProgressImp::SetTotal(const UInt64 *numFiles)
187{
188 if (_callback)
189 return _callback->SetCompleted(numFiles, NULL);
190 return S_OK;
191}
192 176
193STDMETHODIMP CProgressImp::SetCompleted(const UInt64 *numFiles) 177Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
194{
195 if (_callback)
196 return _callback->SetCompleted(numFiles, NULL);
197 return S_OK;
198}
199*/
200
201STDMETHODIMP CHandler::Open(IInStream *inStream,
202 const UInt64 *maxCheckStartPosition, 178 const UInt64 *maxCheckStartPosition,
203 IArchiveOpenCallback * /* openArchiveCallback */) 179 IArchiveOpenCallback * /* openArchiveCallback */))
204{ 180{
205 COM_TRY_BEGIN 181 COM_TRY_BEGIN
206 Close(); 182 Close();
@@ -208,13 +184,13 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
208 { 184 {
209 CInArchive archive(_help2); 185 CInArchive archive(_help2);
210 // CProgressImp progressImp(openArchiveCallback); 186 // CProgressImp progressImp(openArchiveCallback);
211 HRESULT res = archive.Open(inStream, maxCheckStartPosition, m_Database); 187 const HRESULT res = archive.Open(inStream, maxCheckStartPosition, m_Database);
212 if (!archive.IsArc) m_ErrorFlags |= kpv_ErrorFlags_IsNotArc; 188 if (!archive.IsArc) m_ErrorFlags |= kpv_ErrorFlags_IsNotArc;
213 if (archive.HeadersError) m_ErrorFlags |= kpv_ErrorFlags_HeadersError; 189 if (archive.HeadersError) m_ErrorFlags |= kpv_ErrorFlags_HeadersError;
214 if (archive.UnexpectedEnd) m_ErrorFlags |= kpv_ErrorFlags_UnexpectedEnd; 190 if (archive.UnexpectedEnd) m_ErrorFlags |= kpv_ErrorFlags_UnexpectedEnd;
215 if (archive.UnsupportedFeature) m_ErrorFlags |= kpv_ErrorFlags_UnsupportedFeature; 191 if (archive.UnsupportedFeature) m_ErrorFlags |= kpv_ErrorFlags_UnsupportedFeature;
216 192
217 RINOK(res); 193 RINOK(res)
218 /* 194 /*
219 if (m_Database.LowLevel) 195 if (m_Database.LowLevel)
220 return S_FALSE; 196 return S_FALSE;
@@ -229,7 +205,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
229 COM_TRY_END 205 COM_TRY_END
230} 206}
231 207
232STDMETHODIMP CHandler::Close() 208Z7_COM7F_IMF(CHandler::Close())
233{ 209{
234 m_ErrorFlags = 0; 210 m_ErrorFlags = 0;
235 m_Database.Clear(); 211 m_Database.Clear();
@@ -237,15 +213,22 @@ STDMETHODIMP CHandler::Close()
237 return S_OK; 213 return S_OK;
238} 214}
239 215
240class CChmFolderOutStream: 216Z7_CLASS_IMP_NOQIB_1(
241 public ISequentialOutStream, 217 CChmFolderOutStream
242 public CMyUnknownImp 218 , ISequentialOutStream
243{ 219)
244public: 220 bool m_TestMode;
245 MY_UNKNOWN_IMP 221 bool m_IsOk;
222 bool m_FileIsOpen;
223 const CFilesDatabase *m_Database;
224 CMyComPtr<IArchiveExtractCallback> m_ExtractCallback;
225 CMyComPtr<ISequentialOutStream> m_RealOutStream;
226 UInt64 m_RemainFileSize;
246 227
228 HRESULT OpenFile();
229 HRESULT WriteEmptyFiles();
247 HRESULT Write2(const void *data, UInt32 size, UInt32 *processedSize, bool isOK); 230 HRESULT Write2(const void *data, UInt32 size, UInt32 *processedSize, bool isOK);
248 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); 231public:
249 232
250 UInt64 m_FolderSize; 233 UInt64 m_FolderSize;
251 UInt64 m_PosInFolder; 234 UInt64 m_PosInFolder;
@@ -255,19 +238,6 @@ public:
255 unsigned m_CurrentIndex; 238 unsigned m_CurrentIndex;
256 unsigned m_NumFiles; 239 unsigned m_NumFiles;
257 240
258private:
259 const CFilesDatabase *m_Database;
260 CMyComPtr<IArchiveExtractCallback> m_ExtractCallback;
261 bool m_TestMode;
262
263 bool m_IsOk;
264 bool m_FileIsOpen;
265 UInt64 m_RemainFileSize;
266 CMyComPtr<ISequentialOutStream> m_RealOutStream;
267
268 HRESULT OpenFile();
269 HRESULT WriteEmptyFiles();
270public:
271 void Init( 241 void Init(
272 const CFilesDatabase *database, 242 const CFilesDatabase *database,
273 IArchiveExtractCallback *extractCallback, 243 IArchiveExtractCallback *extractCallback,
@@ -290,12 +260,12 @@ void CChmFolderOutStream::Init(
290 260
291HRESULT CChmFolderOutStream::OpenFile() 261HRESULT CChmFolderOutStream::OpenFile()
292{ 262{
293 Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? (m_TestMode ? 263 Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? m_TestMode ?
294 NExtract::NAskMode::kTest : 264 NExtract::NAskMode::kTest :
295 NExtract::NAskMode::kExtract) : 265 NExtract::NAskMode::kExtract :
296 NExtract::NAskMode::kSkip; 266 NExtract::NAskMode::kSkip;
297 m_RealOutStream.Release(); 267 m_RealOutStream.Release();
298 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode)); 268 RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode))
299 if (!m_RealOutStream && !m_TestMode) 269 if (!m_RealOutStream && !m_TestMode)
300 askMode = NExtract::NAskMode::kSkip; 270 askMode = NExtract::NAskMode::kSkip;
301 return m_ExtractCallback->PrepareOperation(askMode); 271 return m_ExtractCallback->PrepareOperation(askMode);
@@ -307,13 +277,13 @@ HRESULT CChmFolderOutStream::WriteEmptyFiles()
307 return S_OK; 277 return S_OK;
308 for (; m_CurrentIndex < m_NumFiles; m_CurrentIndex++) 278 for (; m_CurrentIndex < m_NumFiles; m_CurrentIndex++)
309 { 279 {
310 UInt64 fileSize = m_Database->GetFileSize(m_StartIndex + m_CurrentIndex); 280 const UInt64 fileSize = m_Database->GetFileSize(m_StartIndex + m_CurrentIndex);
311 if (fileSize != 0) 281 if (fileSize != 0)
312 return S_OK; 282 return S_OK;
313 HRESULT result = OpenFile(); 283 const HRESULT result = OpenFile();
314 m_RealOutStream.Release(); 284 m_RealOutStream.Release();
315 RINOK(result); 285 RINOK(result)
316 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 286 RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
317 } 287 }
318 return S_OK; 288 return S_OK;
319} 289}
@@ -358,7 +328,7 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce
358 RINOK(m_ExtractCallback->SetOperationResult( 328 RINOK(m_ExtractCallback->SetOperationResult(
359 m_IsOk ? 329 m_IsOk ?
360 NExtract::NOperationResult::kOK: 330 NExtract::NOperationResult::kOK:
361 NExtract::NOperationResult::kDataError)); 331 NExtract::NOperationResult::kDataError))
362 m_FileIsOpen = false; 332 m_FileIsOpen = false;
363 } 333 }
364 if (realProcessed > 0) 334 if (realProcessed > 0)
@@ -395,7 +365,7 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce
395 365
396 if (fileOffset == m_PosInSection) 366 if (fileOffset == m_PosInSection)
397 { 367 {
398 RINOK(OpenFile()); 368 RINOK(OpenFile())
399 m_FileIsOpen = true; 369 m_FileIsOpen = true;
400 m_CurrentIndex++; 370 m_CurrentIndex++;
401 m_IsOk = true; 371 m_IsOk = true;
@@ -406,7 +376,7 @@ HRESULT CChmFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *proce
406 return WriteEmptyFiles(); 376 return WriteEmptyFiles();
407} 377}
408 378
409STDMETHODIMP CChmFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 379Z7_COM7F_IMF(CChmFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
410{ 380{
411 return Write2(data, size, processedSize, true); 381 return Write2(data, size, processedSize, true);
412} 382}
@@ -423,7 +393,7 @@ HRESULT CChmFolderOutStream::FlushCorrupted(UInt64 maxSize)
423 { 393 {
424 UInt32 size = (UInt32)MyMin(maxSize - m_PosInFolder, (UInt64)kBufferSize); 394 UInt32 size = (UInt32)MyMin(maxSize - m_PosInFolder, (UInt64)kBufferSize);
425 UInt32 processedSizeLocal = 0; 395 UInt32 processedSizeLocal = 0;
426 RINOK(Write2(buffer, size, &processedSizeLocal, false)); 396 RINOK(Write2(buffer, size, &processedSizeLocal, false))
427 if (processedSizeLocal == 0) 397 if (processedSizeLocal == 0)
428 return S_OK; 398 return S_OK;
429 } 399 }
@@ -431,11 +401,11 @@ HRESULT CChmFolderOutStream::FlushCorrupted(UInt64 maxSize)
431} 401}
432 402
433 403
434STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 404Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
435 Int32 testModeSpec, IArchiveExtractCallback *extractCallback) 405 Int32 testModeSpec, IArchiveExtractCallback *extractCallback))
436{ 406{
437 COM_TRY_BEGIN 407 COM_TRY_BEGIN
438 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 408 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
439 409
440 if (allFilesMode) 410 if (allFilesMode)
441 numItems = m_Database.NewFormat ? 1: 411 numItems = m_Database.NewFormat ? 1:
@@ -479,13 +449,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
479 lps->InSize = currentTotalSize; // Change it 449 lps->InSize = currentTotalSize; // Change it
480 lps->OutSize = currentTotalSize; 450 lps->OutSize = currentTotalSize;
481 451
482 RINOK(lps->SetCur()); 452 RINOK(lps->SetCur())
483 CMyComPtr<ISequentialOutStream> realOutStream; 453 CMyComPtr<ISequentialOutStream> realOutStream;
484 Int32 askMode= testMode ? 454 const Int32 askMode= testMode ?
485 NExtract::NAskMode::kTest : 455 NExtract::NAskMode::kTest :
486 NExtract::NAskMode::kExtract; 456 NExtract::NAskMode::kExtract;
487 Int32 index = allFilesMode ? i : indices[i]; 457 const UInt32 index = allFilesMode ? i : indices[i];
488 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 458 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
489 459
490 if (m_Database.NewFormat) 460 if (m_Database.NewFormat)
491 { 461 {
@@ -496,9 +466,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
496 if (!testMode) 466 if (!testMode)
497 { 467 {
498 UInt32 size = m_Database.NewFormatString.Len(); 468 UInt32 size = m_Database.NewFormatString.Len();
499 RINOK(WriteStream(realOutStream, (const char *)m_Database.NewFormatString, size)); 469 RINOK(WriteStream(realOutStream, (const char *)m_Database.NewFormatString, size))
500 } 470 }
501 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 471 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
502 continue; 472 continue;
503 } 473 }
504 474
@@ -508,27 +478,27 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
508 478
509 if (!testMode && !realOutStream) 479 if (!testMode && !realOutStream)
510 continue; 480 continue;
511 RINOK(extractCallback->PrepareOperation(askMode)); 481 RINOK(extractCallback->PrepareOperation(askMode))
512 if (item.Section != 0) 482 if (item.Section != 0)
513 { 483 {
514 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 484 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
515 continue; 485 continue;
516 } 486 }
517 487
518 if (testMode) 488 if (testMode)
519 { 489 {
520 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 490 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
521 continue; 491 continue;
522 } 492 }
523 493
524 RINOK(m_Stream->Seek(m_Database.ContentOffset + item.Offset, STREAM_SEEK_SET, NULL)); 494 RINOK(InStream_SeekSet(m_Stream, m_Database.ContentOffset + item.Offset))
525 streamSpec->Init(item.Size); 495 streamSpec->Init(item.Size);
526 496
527 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 497 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
528 realOutStream.Release(); 498 realOutStream.Release();
529 RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ? 499 RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ?
530 NExtract::NOperationResult::kOK: 500 NExtract::NOperationResult::kOK:
531 NExtract::NOperationResult::kDataError)); 501 NExtract::NOperationResult::kDataError))
532 } 502 }
533 return S_OK; 503 return S_OK;
534 } 504 }
@@ -537,7 +507,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
537 507
538 for (i = 0; i < numItems; i++) 508 for (i = 0; i < numItems; i++)
539 { 509 {
540 UInt32 index = allFilesMode ? i : indices[i]; 510 const UInt32 index = allFilesMode ? i : indices[i];
541 const CItem &item = m_Database.Items[m_Database.Indices[index]]; 511 const CItem &item = m_Database.Items[m_Database.Indices[index]];
542 const UInt64 sectionIndex = item.Section; 512 const UInt64 sectionIndex = item.Section;
543 if (item.IsDir() || item.Size == 0) 513 if (item.IsDir() || item.Size == 0)
@@ -564,11 +534,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
564 } 534 }
565 } 535 }
566 536
567 RINOK(extractCallback->SetTotal(currentTotalSize)); 537 RINOK(extractCallback->SetTotal(currentTotalSize))
568 538
569 NCompress::NLzx::CDecoder *lzxDecoderSpec = NULL; 539 NCompress::NLzx::CDecoder *lzxDecoderSpec = NULL;
570 CMyComPtr<IUnknown> lzxDecoder; 540 CMyComPtr<IUnknown> lzxDecoder;
571 CChmFolderOutStream *chmFolderOutStream = 0; 541 CChmFolderOutStream *chmFolderOutStream = NULL;
572 CMyComPtr<ISequentialOutStream> outStream; 542 CMyComPtr<ISequentialOutStream> outStream;
573 543
574 currentTotalSize = 0; 544 currentTotalSize = 0;
@@ -579,7 +549,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
579 549
580 for (i = 0;;) 550 for (i = 0;;)
581 { 551 {
582 RINOK(extractCallback->SetCompleted(&currentTotalSize)); 552 RINOK(extractCallback->SetCompleted(&currentTotalSize))
583 553
584 if (i >= numItems) 554 if (i >= numItems)
585 break; 555 break;
@@ -595,10 +565,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
595 if (item.IsDir()) 565 if (item.IsDir())
596 { 566 {
597 CMyComPtr<ISequentialOutStream> realOutStream; 567 CMyComPtr<ISequentialOutStream> realOutStream;
598 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 568 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
599 RINOK(extractCallback->PrepareOperation(askMode)); 569 RINOK(extractCallback->PrepareOperation(askMode))
600 realOutStream.Release(); 570 realOutStream.Release();
601 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 571 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
602 continue; 572 continue;
603 } 573 }
604 574
@@ -608,21 +578,21 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
608 if (item.Size == 0 || sectionIndex == 0) 578 if (item.Size == 0 || sectionIndex == 0)
609 { 579 {
610 CMyComPtr<ISequentialOutStream> realOutStream; 580 CMyComPtr<ISequentialOutStream> realOutStream;
611 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 581 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
612 if (!testMode && !realOutStream) 582 if (!testMode && !realOutStream)
613 continue; 583 continue;
614 RINOK(extractCallback->PrepareOperation(askMode)); 584 RINOK(extractCallback->PrepareOperation(askMode))
615 Int32 opRes = NExtract::NOperationResult::kOK; 585 Int32 opRes = NExtract::NOperationResult::kOK;
616 if (!testMode && item.Size != 0) 586 if (!testMode && item.Size != 0)
617 { 587 {
618 RINOK(m_Stream->Seek(m_Database.ContentOffset + item.Offset, STREAM_SEEK_SET, NULL)); 588 RINOK(InStream_SeekSet(m_Stream, m_Database.ContentOffset + item.Offset))
619 streamSpec->Init(item.Size); 589 streamSpec->Init(item.Size);
620 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 590 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
621 if (copyCoderSpec->TotalSize != item.Size) 591 if (copyCoderSpec->TotalSize != item.Size)
622 opRes = NExtract::NOperationResult::kDataError; 592 opRes = NExtract::NOperationResult::kDataError;
623 } 593 }
624 realOutStream.Release(); 594 realOutStream.Release();
625 RINOK(extractCallback->SetOperationResult(opRes)); 595 RINOK(extractCallback->SetOperationResult(opRes))
626 currentTotalSize += item.Size; 596 currentTotalSize += item.Size;
627 continue; 597 continue;
628 } 598 }
@@ -631,11 +601,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
631 { 601 {
632 // we must report error here; 602 // we must report error here;
633 CMyComPtr<ISequentialOutStream> realOutStream; 603 CMyComPtr<ISequentialOutStream> realOutStream;
634 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 604 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
635 if (!testMode && !realOutStream) 605 if (!testMode && !realOutStream)
636 continue; 606 continue;
637 RINOK(extractCallback->PrepareOperation(askMode)); 607 RINOK(extractCallback->PrepareOperation(askMode))
638 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kHeadersError)); 608 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kHeadersError))
639 continue; 609 continue;
640 } 610 }
641 611
@@ -644,11 +614,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
644 if (!section.IsLzx()) 614 if (!section.IsLzx())
645 { 615 {
646 CMyComPtr<ISequentialOutStream> realOutStream; 616 CMyComPtr<ISequentialOutStream> realOutStream;
647 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 617 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
648 if (!testMode && !realOutStream) 618 if (!testMode && !realOutStream)
649 continue; 619 continue;
650 RINOK(extractCallback->PrepareOperation(askMode)); 620 RINOK(extractCallback->PrepareOperation(askMode))
651 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 621 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
652 continue; 622 continue;
653 } 623 }
654 624
@@ -671,7 +641,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
671 UInt64 folderIndex = m_Database.GetFolder(index); 641 UInt64 folderIndex = m_Database.GetFolder(index);
672 642
673 const UInt64 compressedPos = m_Database.ContentOffset + section.Offset; 643 const UInt64 compressedPos = m_Database.ContentOffset + section.Offset;
674 RINOK(lzxDecoderSpec->SetParams_and_Alloc(lzxInfo.GetNumDictBits())); 644 RINOK(lzxDecoderSpec->SetParams_and_Alloc(lzxInfo.GetNumDictBits()))
675 645
676 const CItem *lastItem = &item; 646 const CItem *lastItem = &item;
677 extractStatuses.Clear(); 647 extractStatuses.Clear();
@@ -679,7 +649,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
679 649
680 for (;; folderIndex++) 650 for (;; folderIndex++)
681 { 651 {
682 RINOK(extractCallback->SetCompleted(&currentTotalSize)); 652 RINOK(extractCallback->SetCompleted(&currentTotalSize))
683 653
684 UInt64 startPos = lzxInfo.GetFolderPos(folderIndex); 654 UInt64 startPos = lzxInfo.GetFolderPos(folderIndex);
685 UInt64 finishPos = lastItem->Offset + lastItem->Size; 655 UInt64 finishPos = lastItem->Offset + lastItem->Size;
@@ -702,7 +672,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
702 const CItem &nextItem = m_Database.Items[m_Database.Indices[nextIndex]]; 672 const CItem &nextItem = m_Database.Items[m_Database.Indices[nextIndex]];
703 if (nextItem.Section != sectionIndex) 673 if (nextItem.Section != sectionIndex)
704 break; 674 break;
705 UInt64 nextFolderIndex = m_Database.GetFolder(nextIndex); 675 const UInt64 nextFolderIndex = m_Database.GetFolder(nextIndex);
706 if (nextFolderIndex != folderIndex) 676 if (nextFolderIndex != folderIndex)
707 break; 677 break;
708 for (index++; index < nextIndex; index++) 678 for (index++; index < nextIndex; index++)
@@ -734,7 +704,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
734 for (UInt32 b = 0; b < numBlocks; b++) 704 for (UInt32 b = 0; b < numBlocks; b++)
735 { 705 {
736 UInt64 completedSize = currentTotalSize + chmFolderOutStream->m_PosInSection - startPos; 706 UInt64 completedSize = currentTotalSize + chmFolderOutStream->m_PosInSection - startPos;
737 RINOK(extractCallback->SetCompleted(&completedSize)); 707 RINOK(extractCallback->SetCompleted(&completedSize))
738 UInt64 bCur = startBlock + b; 708 UInt64 bCur = startBlock + b;
739 if (bCur >= rt.ResetOffsets.Size()) 709 if (bCur >= rt.ResetOffsets.Size())
740 return E_FAIL; 710 return E_FAIL;
@@ -744,7 +714,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
744 714
745 // chm writes full blocks. So we don't need to use reduced size for last block 715 // chm writes full blocks. So we don't need to use reduced size for last block
746 716
747 RINOK(m_Stream->Seek(compressedPos + offset, STREAM_SEEK_SET, NULL)); 717 RINOK(InStream_SeekSet(m_Stream, compressedPos + offset))
748 streamSpec->SetStream(m_Stream); 718 streamSpec->SetStream(m_Stream);
749 streamSpec->Init(compressedSize); 719 streamSpec->Init(compressedSize);
750 720
@@ -777,7 +747,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
777 } 747 }
778 catch(...) 748 catch(...)
779 { 749 {
780 RINOK(chmFolderOutStream->FlushCorrupted(unPackSize)); 750 RINOK(chmFolderOutStream->FlushCorrupted(unPackSize))
781 } 751 }
782 752
783 currentTotalSize += folderSize; 753 currentTotalSize += folderSize;
@@ -790,9 +760,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
790 COM_TRY_END 760 COM_TRY_END
791} 761}
792 762
793STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 763Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
794{ 764{
795 *numItems = m_Database.NewFormat ? 1: 765 *numItems = m_Database.NewFormat ? 1:
796 (m_Database.LowLevel ? 766 (m_Database.LowLevel ?
797 m_Database.Items.Size(): 767 m_Database.Items.Size():
798 m_Database.Indices.Size()); 768 m_Database.Indices.Size());
@@ -805,7 +775,7 @@ static const Byte k_Signature[] = { 'I', 'T', 'S', 'F', 3, 0, 0, 0, 0x60, 0, 0,
805 775
806REGISTER_ARC_I_CLS( 776REGISTER_ARC_I_CLS(
807 CHandler(false), 777 CHandler(false),
808 "Chm", "chm chi chq chw", 0, 0xE9, 778 "Chm", "chm chi chq chw", NULL, 0xE9,
809 k_Signature, 779 k_Signature,
810 0, 780 0,
811 0, 781 0,
@@ -819,7 +789,7 @@ static const Byte k_Signature[] = { 'I', 'T', 'O', 'L', 'I', 'T', 'L', 'S', 1, 0
819 789
820REGISTER_ARC_I_CLS( 790REGISTER_ARC_I_CLS(
821 CHandler(true), 791 CHandler(true),
822 "Hxs", "hxs hxi hxr hxq hxw lit", 0, 0xCE, 792 "Hxs", "hxs hxi hxr hxq hxw lit", NULL, 0xCE,
823 k_Signature, 793 k_Signature,
824 0, 794 0,
825 NArcInfoFlags::kFindSignature, 795 NArcInfoFlags::kFindSignature,
diff --git a/CPP/7zip/Archive/Chm/ChmHandler.h b/CPP/7zip/Archive/Chm/ChmHandler.h
index 884f391..94821b2 100644
--- a/CPP/7zip/Archive/Chm/ChmHandler.h
+++ b/CPP/7zip/Archive/Chm/ChmHandler.h
@@ -1,7 +1,7 @@
1// ChmHandler.h 1// ChmHandler.h
2 2
3#ifndef __ARCHIVE_CHM_HANDLER_H 3#ifndef ZIP7_INC_ARCHIVE_CHM_HANDLER_H
4#define __ARCHIVE_CHM_HANDLER_H 4#define ZIP7_INC_ARCHIVE_CHM_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -12,22 +12,14 @@
12namespace NArchive { 12namespace NArchive {
13namespace NChm { 13namespace NChm {
14 14
15class CHandler: 15Z7_CLASS_IMP_CHandler_IInArchive_0
16 public IInArchive,
17 public CMyUnknownImp
18{
19public:
20 MY_UNKNOWN_IMP1(IInArchive)
21
22 INTERFACE_IInArchive(;)
23
24 bool _help2;
25 CHandler(bool help2): _help2(help2) {}
26 16
27private:
28 CFilesDatabase m_Database; 17 CFilesDatabase m_Database;
29 CMyComPtr<IInStream> m_Stream; 18 CMyComPtr<IInStream> m_Stream;
19 bool _help2;
30 UInt32 m_ErrorFlags; 20 UInt32 m_ErrorFlags;
21public:
22 CHandler(bool help2): _help2(help2) {}
31}; 23};
32 24
33}} 25}}
diff --git a/CPP/7zip/Archive/Chm/ChmIn.cpp b/CPP/7zip/Archive/Chm/ChmIn.cpp
index f4916b6..28d512d 100644
--- a/CPP/7zip/Archive/Chm/ChmIn.cpp
+++ b/CPP/7zip/Archive/Chm/ChmIn.cpp
@@ -10,6 +10,7 @@
10#include "../../../Common/UTFConvert.h" 10#include "../../../Common/UTFConvert.h"
11 11
12#include "../../Common/LimitedStreams.h" 12#include "../../Common/LimitedStreams.h"
13#include "../../Common/StreamUtils.h"
13 14
14#include "ChmIn.h" 15#include "ChmIn.h"
15 16
@@ -217,7 +218,7 @@ void CInArchive::ReadUString(unsigned size, UString &s)
217 218
218HRESULT CInArchive::ReadChunk(IInStream *inStream, UInt64 pos, UInt64 size) 219HRESULT CInArchive::ReadChunk(IInStream *inStream, UInt64 pos, UInt64 size)
219{ 220{
220 RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); 221 RINOK(InStream_SeekSet(inStream, pos))
221 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; 222 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
222 CMyComPtr<ISequentialInStream> limitedStream(streamSpec); 223 CMyComPtr<ISequentialInStream> limitedStream(streamSpec);
223 streamSpec->SetStream(inStream); 224 streamSpec->SetStream(inStream);
@@ -350,7 +351,7 @@ HRESULT CInArchive::OpenChm(IInStream *inStream, CDatabase &database)
350 return S_FALSE; 351 return S_FALSE;
351 if (offset == offsetLimit) 352 if (offset == offsetLimit)
352 break; 353 break;
353 RINOK(ReadDirEntry(database)); 354 RINOK(ReadDirEntry(database))
354 numItems++; 355 numItems++;
355 } 356 }
356 357
@@ -570,7 +571,7 @@ HRESULT CInArchive::OpenHelp2(IInStream *inStream, CDatabase &database)
570 } 571 }
571 else 572 else
572 { 573 {
573 RINOK(ReadDirEntry(database)); 574 RINOK(ReadDirEntry(database))
574 } 575 }
575 numItems++; 576 numItems++;
576 } 577 }
@@ -616,7 +617,7 @@ static AString GetSectionPrefix(const AString &name)
616 return s; 617 return s;
617} 618}
618 619
619#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 620#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
620 621
621static int CompareFiles(const unsigned *p1, const unsigned *p2, void *param) 622static int CompareFiles(const unsigned *p1, const unsigned *p2, void *param)
622{ 623{
@@ -634,9 +635,9 @@ static int CompareFiles(const unsigned *p1, const unsigned *p2, void *param)
634 } 635 }
635 else 636 else
636 { 637 {
637 RINOZ(MyCompare(item1.Section, item2.Section)); 638 RINOZ(MyCompare(item1.Section, item2.Section))
638 RINOZ(MyCompare(item1.Offset, item2.Offset)); 639 RINOZ(MyCompare(item1.Offset, item2.Offset))
639 RINOZ(MyCompare(item1.Size, item2.Size)); 640 RINOZ(MyCompare(item1.Size, item2.Size))
640 } 641 }
641 return MyCompare(*p1, *p2); 642 return MyCompare(*p1, *p2);
642} 643}
@@ -705,7 +706,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
705{ 706{
706 { 707 {
707 // The NameList file 708 // The NameList file
708 RINOK(DecompressStream(inStream, database, (AString)kNameList)); 709 RINOK(DecompressStream(inStream, database, (AString)kNameList))
709 /* UInt16 length = */ ReadUInt16(); 710 /* UInt16 length = */ ReadUInt16();
710 UInt16 numSections = ReadUInt16(); 711 UInt16 numSections = ReadUInt16();
711 for (unsigned i = 0; i < numSections; i++) 712 for (unsigned i = 0; i < numSections; i++)
@@ -740,7 +741,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
740 if (database.Help2Format) 741 if (database.Help2Format)
741 { 742 {
742 // Transform List 743 // Transform List
743 RINOK(DecompressStream(inStream, database, transformPrefix + kTransformList)); 744 RINOK(DecompressStream(inStream, database, transformPrefix + kTransformList))
744 if ((_chunkSize & 0xF) != 0) 745 if ((_chunkSize & 0xF) != 0)
745 return S_FALSE; 746 return S_FALSE;
746 unsigned numGuids = (unsigned)(_chunkSize / 0x10); 747 unsigned numGuids = (unsigned)(_chunkSize / 0x10);
@@ -762,7 +763,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
762 763
763 { 764 {
764 // Control Data 765 // Control Data
765 RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData)); 766 RINOK(DecompressStream(inStream, database, sectionPrefix + kControlData))
766 767
767 FOR_VECTOR (mi, section.Methods) 768 FOR_VECTOR (mi, section.Methods)
768 { 769 {
@@ -781,19 +782,19 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
781 782
782 { 783 {
783 // There is bug in VC6, if we use function call as parameter for inline function 784 // There is bug in VC6, if we use function call as parameter for inline function
784 UInt32 val32 = ReadUInt32(); 785 const UInt32 val32 = ReadUInt32();
785 int n = GetLog(val32); 786 const int n = GetLog(val32);
786 if (n < 0 || n > 16) 787 if (n < 0 || n > 16)
787 return S_FALSE; 788 return S_FALSE;
788 li.ResetIntervalBits = n; 789 li.ResetIntervalBits = (unsigned)n;
789 } 790 }
790 791
791 { 792 {
792 UInt32 val32 = ReadUInt32(); 793 const UInt32 val32 = ReadUInt32();
793 int n = GetLog(val32); 794 const int n = GetLog(val32);
794 if (n < 0 || n > 16) 795 if (n < 0 || n > 16)
795 return S_FALSE; 796 return S_FALSE;
796 li.WindowSizeBits = n; 797 li.WindowSizeBits = (unsigned)n;
797 } 798 }
798 799
799 li.CacheSize = ReadUInt32(); 800 li.CacheSize = ReadUInt32();
@@ -812,7 +813,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
812 813
813 { 814 {
814 // SpanInfo 815 // SpanInfo
815 RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo)); 816 RINOK(DecompressStream(inStream, database, sectionPrefix + kSpanInfo))
816 section.UncompressedSize = ReadUInt64(); 817 section.UncompressedSize = ReadUInt64();
817 } 818 }
818 819
@@ -824,7 +825,7 @@ HRESULT CInArchive::OpenHighLevel(IInStream *inStream, CFilesDatabase &database)
824 { 825 {
825 // ResetTable; 826 // ResetTable;
826 RINOK(DecompressStream(inStream, database, transformPrefix + 827 RINOK(DecompressStream(inStream, database, transformPrefix +
827 method.GetGuidString() + kResetTable)); 828 method.GetGuidString() + kResetTable))
828 CResetTable &rt = method.LzxInfo.ResetTable; 829 CResetTable &rt = method.LzxInfo.ResetTable;
829 830
830 if (_chunkSize < 4) 831 if (_chunkSize < 4)
@@ -906,7 +907,7 @@ HRESULT CInArchive::Open2(IInStream *inStream,
906 database.Help2Format = _help2; 907 database.Help2Format = _help2;
907 const UInt32 chmVersion = 3; 908 const UInt32 chmVersion = 3;
908 909
909 RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &database.StartPosition)); 910 RINOK(InStream_GetPos(inStream, database.StartPosition))
910 911
911 if (!_inBuffer.Create(1 << 14)) 912 if (!_inBuffer.Create(1 << 14))
912 return E_OUTOFMEMORY; 913 return E_OUTOFMEMORY;
@@ -942,7 +943,7 @@ HRESULT CInArchive::Open2(IInStream *inStream,
942 } 943 }
943 944
944 database.StartPosition += _inBuffer.GetProcessedSize() - kSignatureSize; 945 database.StartPosition += _inBuffer.GetProcessedSize() - kSignatureSize;
945 RINOK(OpenHelp2(inStream, database)); 946 RINOK(OpenHelp2(inStream, database))
946 if (database.NewFormat) 947 if (database.NewFormat)
947 return S_OK; 948 return S_OK;
948 } 949 }
@@ -952,7 +953,7 @@ HRESULT CInArchive::Open2(IInStream *inStream,
952 return S_FALSE; 953 return S_FALSE;
953 if (ReadUInt32() != chmVersion) 954 if (ReadUInt32() != chmVersion)
954 return S_FALSE; 955 return S_FALSE;
955 RINOK(OpenChm(inStream, database)); 956 RINOK(OpenChm(inStream, database))
956 } 957 }
957 958
958 959
@@ -969,7 +970,7 @@ HRESULT CInArchive::Open2(IInStream *inStream,
969 database.HighLevelClear(); 970 database.HighLevelClear();
970 return S_OK; 971 return S_OK;
971 } 972 }
972 RINOK(res); 973 RINOK(res)
973 if (!database.CheckSectionRefs()) 974 if (!database.CheckSectionRefs())
974 HeadersError = true; 975 HeadersError = true;
975 database.LowLevel = false; 976 database.LowLevel = false;
diff --git a/CPP/7zip/Archive/Chm/ChmIn.h b/CPP/7zip/Archive/Chm/ChmIn.h
index 2d77366..c01ef4d 100644
--- a/CPP/7zip/Archive/Chm/ChmIn.h
+++ b/CPP/7zip/Archive/Chm/ChmIn.h
@@ -1,7 +1,7 @@
1// Archive/ChmIn.h 1// Archive/ChmIn.h
2 2
3#ifndef __ARCHIVE_CHM_IN_H 3#ifndef ZIP7_INC_ARCHIVE_CHM_IN_H
4#define __ARCHIVE_CHM_IN_H 4#define ZIP7_INC_ARCHIVE_CHM_IN_H
5 5
6#include "../../../Common/MyBuffer.h" 6#include "../../../Common/MyBuffer.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
@@ -59,7 +59,7 @@ struct CDatabase
59 { 59 {
60 FOR_VECTOR (i, Items) 60 FOR_VECTOR (i, Items)
61 if (Items[i].Name == name) 61 if (Items[i].Name == name)
62 return i; 62 return (int)i;
63 return -1; 63 return -1;
64 } 64 }
65 65
diff --git a/CPP/7zip/Archive/Chm/StdAfx.h b/CPP/7zip/Archive/Chm/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Chm/StdAfx.h
+++ b/CPP/7zip/Archive/Chm/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/ComHandler.cpp b/CPP/7zip/Archive/ComHandler.cpp
index a1f643b..7aabd65 100644
--- a/CPP/7zip/Archive/ComHandler.cpp
+++ b/CPP/7zip/Archive/ComHandler.cpp
@@ -26,8 +26,8 @@
26namespace NArchive { 26namespace NArchive {
27namespace NCom { 27namespace NCom {
28 28
29#define SIGNATURE { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 } 29static const Byte kSignature[] =
30static const Byte kSignature[] = SIGNATURE; 30 { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 };
31 31
32enum EType 32enum EType
33{ 33{
@@ -120,6 +120,7 @@ public:
120 Int32 MainSubfile; 120 Int32 MainSubfile;
121 121
122 UInt64 PhySize; 122 UInt64 PhySize;
123 UInt64 PhySize_Aligned;
123 EType Type; 124 EType Type;
124 125
125 bool IsNotArcType() const 126 bool IsNotArcType() const
@@ -129,10 +130,12 @@ public:
129 Type != k_Type_Msp; 130 Type != k_Type_Msp;
130 } 131 }
131 132
132 void UpdatePhySize(UInt64 val) 133 void UpdatePhySize(UInt64 val, UInt64 val_Aligned)
133 { 134 {
134 if (PhySize < val) 135 if (PhySize < val)
135 PhySize = val; 136 PhySize = val;
137 if (PhySize_Aligned < val_Aligned)
138 PhySize_Aligned = val_Aligned;
136 } 139 }
137 HRESULT ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid); 140 HRESULT ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid);
138 HRESULT ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest); 141 HRESULT ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest);
@@ -165,14 +168,15 @@ public:
165 168
166HRESULT CDatabase::ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid) 169HRESULT CDatabase::ReadSector(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid)
167{ 170{
168 UpdatePhySize(((UInt64)sid + 2) << sectorSizeBits); 171 const UInt64 end = ((UInt64)sid + 2) << sectorSizeBits;
169 RINOK(inStream->Seek((((UInt64)sid + 1) << sectorSizeBits), STREAM_SEEK_SET, NULL)); 172 UpdatePhySize(end, end);
173 RINOK(InStream_SeekSet(inStream, (((UInt64)sid + 1) << sectorSizeBits)))
170 return ReadStream_FALSE(inStream, buf, (size_t)1 << sectorSizeBits); 174 return ReadStream_FALSE(inStream, buf, (size_t)1 << sectorSizeBits);
171} 175}
172 176
173HRESULT CDatabase::ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest) 177HRESULT CDatabase::ReadIDs(IInStream *inStream, Byte *buf, unsigned sectorSizeBits, UInt32 sid, UInt32 *dest)
174{ 178{
175 RINOK(ReadSector(inStream, buf, sectorSizeBits, sid)); 179 RINOK(ReadSector(inStream, buf, sectorSizeBits, sid))
176 UInt32 sectorSize = (UInt32)1 << sectorSizeBits; 180 UInt32 sectorSize = (UInt32)1 << sectorSizeBits;
177 for (UInt32 t = 0; t < sectorSize; t += 4) 181 for (UInt32 t = 0; t < sectorSize; t += 4)
178 *dest++ = Get32(buf + t); 182 *dest++ = Get32(buf + t);
@@ -205,6 +209,7 @@ void CItem::Parse(const Byte *p, bool mode64bit)
205void CDatabase::Clear() 209void CDatabase::Clear()
206{ 210{
207 PhySize = 0; 211 PhySize = 0;
212 PhySize_Aligned = 0;
208 213
209 Fat.Free(); 214 Fat.Free();
210 MiniSids.Free(); 215 MiniSids.Free();
@@ -227,14 +232,14 @@ HRESULT CDatabase::AddNode(int parent, UInt32 did)
227 CRef ref; 232 CRef ref;
228 ref.Parent = parent; 233 ref.Parent = parent;
229 ref.Did = did; 234 ref.Did = did;
230 int index = Refs.Add(ref); 235 const unsigned index = Refs.Add(ref);
231 if (Refs.Size() > Items.Size()) 236 if (Refs.Size() > Items.Size())
232 return S_FALSE; 237 return S_FALSE;
233 RINOK(AddNode(parent, item.LeftDid)); 238 RINOK(AddNode(parent, item.LeftDid))
234 RINOK(AddNode(parent, item.RightDid)); 239 RINOK(AddNode(parent, item.RightDid))
235 if (item.IsDir()) 240 if (item.IsDir())
236 { 241 {
237 RINOK(AddNode(index, item.SonDid)); 242 RINOK(AddNode((int)index, item.SonDid))
238 } 243 }
239 return S_OK; 244 return S_OK;
240} 245}
@@ -244,11 +249,11 @@ static UString CompoundNameToFileName(const UString &s)
244 UString res; 249 UString res;
245 for (unsigned i = 0; i < s.Len(); i++) 250 for (unsigned i = 0; i < s.Len(); i++)
246 { 251 {
247 wchar_t c = s[i]; 252 const wchar_t c = s[i];
248 if (c < 0x20) 253 if ((unsigned)(int)c < 0x20)
249 { 254 {
250 res += '['; 255 res += '[';
251 res.Add_UInt32(c); 256 res.Add_UInt32((UInt32)(unsigned)(int)c);
252 res += ']'; 257 res += ']';
253 } 258 }
254 else 259 else
@@ -360,7 +365,7 @@ UString CDatabase::GetItemPath(UInt32 index) const
360 if (!s.IsEmpty()) 365 if (!s.IsEmpty())
361 s.InsertAtFront(WCHAR_PATH_SEPARATOR); 366 s.InsertAtFront(WCHAR_PATH_SEPARATOR);
362 s.Insert(0, ConvertName(item.Name)); 367 s.Insert(0, ConvertName(item.Name));
363 index = ref.Parent; 368 index = (unsigned)ref.Parent;
364 } 369 }
365 return s; 370 return s;
366} 371}
@@ -371,11 +376,11 @@ HRESULT CDatabase::Update_PhySize_WithItem(unsigned index)
371 bool isLargeStream = (index == 0 || IsLargeStream(item.Size)); 376 bool isLargeStream = (index == 0 || IsLargeStream(item.Size));
372 if (!isLargeStream) 377 if (!isLargeStream)
373 return S_OK; 378 return S_OK;
374 unsigned bsLog = isLargeStream ? SectorSizeBits : MiniSectorSizeBits; 379 const unsigned bsLog = isLargeStream ? SectorSizeBits : MiniSectorSizeBits;
375 // streamSpec->Size = item.Size; 380 // streamSpec->Size = item.Size;
376 381
377 UInt32 clusterSize = (UInt32)1 << bsLog; 382 const UInt32 clusterSize = (UInt32)1 << bsLog;
378 UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; 383 const UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog;
379 if (numClusters64 >= ((UInt32)1 << 31)) 384 if (numClusters64 >= ((UInt32)1 << 31))
380 return S_FALSE; 385 return S_FALSE;
381 UInt32 sid = item.Sid; 386 UInt32 sid = item.Sid;
@@ -389,7 +394,13 @@ HRESULT CDatabase::Update_PhySize_WithItem(unsigned index)
389 { 394 {
390 if (sid >= FatSize) 395 if (sid >= FatSize)
391 return S_FALSE; 396 return S_FALSE;
392 UpdatePhySize(((UInt64)sid + 2) << bsLog); 397 UInt64 end = ((UInt64)sid + 1) << bsLog;
398 const UInt64 end_Aligned = end + clusterSize;
399 if (size < clusterSize)
400 end += size;
401 else
402 end = end_Aligned;
403 UpdatePhySize(end, end_Aligned);
393 sid = Fat[sid]; 404 sid = Fat[sid];
394 } 405 }
395 if (size <= clusterSize) 406 if (size <= clusterSize)
@@ -415,8 +426,8 @@ HRESULT CDatabase::Open(IInStream *inStream)
415 const UInt32 kHeaderSize = 512; 426 const UInt32 kHeaderSize = 512;
416 Byte p[kHeaderSize]; 427 Byte p[kHeaderSize];
417 PhySize = kHeaderSize; 428 PhySize = kHeaderSize;
418 RINOK(ReadStream_FALSE(inStream, p, kHeaderSize)); 429 RINOK(ReadStream_FALSE(inStream, p, kHeaderSize))
419 if (memcmp(p, kSignature, ARRAY_SIZE(kSignature)) != 0) 430 if (memcmp(p, kSignature, Z7_ARRAY_SIZE(kSignature)) != 0)
420 return S_FALSE; 431 return S_FALSE;
421 if (Get16(p + 0x1A) > 4) // majorVer 432 if (Get16(p + 0x1A) > 4) // majorVer
422 return S_FALSE; 433 return S_FALSE;
@@ -461,7 +472,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
461 UInt32 sid = Get32(p + 0x44); 472 UInt32 sid = Get32(p + 0x44);
462 for (UInt32 s = 0; s < numSectorsForBat; s++) 473 for (UInt32 s = 0; s < numSectorsForBat; s++)
463 { 474 {
464 RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, bat + i)); 475 RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, bat + i))
465 i += numSidsInSec - 1; 476 i += numSidsInSec - 1;
466 sid = bat[i]; 477 sid = bat[i];
467 } 478 }
@@ -474,7 +485,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
474 { 485 {
475 if (j >= numBatItems) 486 if (j >= numBatItems)
476 return S_FALSE; 487 return S_FALSE;
477 RINOK(ReadIDs(inStream, sect, sectorSizeBits, bat[j], Fat + i)); 488 RINOK(ReadIDs(inStream, sect, sectorSizeBits, bat[j], Fat + i))
478 } 489 }
479 FatSize = numFatItems = i; 490 FatSize = numFatItems = i;
480 } 491 }
@@ -490,7 +501,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
490 UInt32 sid = Get32(p + 0x3C); // short-sector table SID 501 UInt32 sid = Get32(p + 0x3C); // short-sector table SID
491 for (i = 0; i < numMatItems; i += numSidsInSec) 502 for (i = 0; i < numMatItems; i += numSidsInSec)
492 { 503 {
493 RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, Mat + i)); 504 RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, Mat + i))
494 if (sid >= numFatItems) 505 if (sid >= numFatItems)
495 return S_FALSE; 506 return S_FALSE;
496 sid = Fat[sid]; 507 sid = Fat[sid];
@@ -511,7 +522,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
511 if (used[sid]) 522 if (used[sid])
512 return S_FALSE; 523 return S_FALSE;
513 used[sid] = 1; 524 used[sid] = 1;
514 RINOK(ReadSector(inStream, sect, sectorSizeBits, sid)); 525 RINOK(ReadSector(inStream, sect, sectorSizeBits, sid))
515 for (UInt32 i = 0; i < sectSize; i += 128) 526 for (UInt32 i = 0; i < sectSize; i += 128)
516 { 527 {
517 CItem item; 528 CItem item;
@@ -563,7 +574,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
563 } 574 }
564 } 575 }
565 576
566 RINOK(AddNode(-1, root.SonDid)); 577 RINOK(AddNode(-1, root.SonDid))
567 578
568 unsigned numCabs = 0; 579 unsigned numCabs = 0;
569 580
@@ -584,7 +595,7 @@ HRESULT CDatabase::Open(IInStream *inStream)
584 ) 595 )
585 { 596 {
586 numCabs++; 597 numCabs++;
587 MainSubfile = i; 598 MainSubfile = (int)i;
588 } 599 }
589 } 600 }
590 } 601 }
@@ -599,6 +610,17 @@ HRESULT CDatabase::Open(IInStream *inStream)
599 } 610 }
600 } 611 }
601 { 612 {
613 if (PhySize != PhySize_Aligned)
614 {
615 /* some msi (in rare cases) have unaligned size of archive,
616 where there is no padding data after payload data in last cluster of archive */
617 UInt64 fileSize;
618 RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize))
619 if (PhySize != fileSize)
620 PhySize = PhySize_Aligned;
621 }
622 }
623 {
602 FOR_VECTOR (t, Items) 624 FOR_VECTOR (t, Items)
603 { 625 {
604 const CItem &item = Items[t]; 626 const CItem &item = Items[t];
@@ -634,17 +656,11 @@ HRESULT CDatabase::Open(IInStream *inStream)
634 return S_OK; 656 return S_OK;
635} 657}
636 658
637class CHandler: 659Z7_CLASS_IMP_CHandler_IInArchive_1(
638 public IInArchive, 660 IInArchiveGetStream
639 public IInArchiveGetStream, 661)
640 public CMyUnknownImp
641{
642 CMyComPtr<IInStream> _stream; 662 CMyComPtr<IInStream> _stream;
643 CDatabase _db; 663 CDatabase _db;
644public:
645 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
646 INTERFACE_IInArchive(;)
647 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
648}; 664};
649 665
650static const Byte kProps[] = 666static const Byte kProps[] =
@@ -666,7 +682,7 @@ static const Byte kArcProps[] =
666IMP_IInArchive_Props 682IMP_IInArchive_Props
667IMP_IInArchive_ArcProps 683IMP_IInArchive_ArcProps
668 684
669STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 685Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
670{ 686{
671 COM_TRY_BEGIN 687 COM_TRY_BEGIN
672 NWindows::NCOM::CPropVariant prop; 688 NWindows::NCOM::CPropVariant prop;
@@ -684,7 +700,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
684 COM_TRY_END 700 COM_TRY_END
685} 701}
686 702
687STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 703Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
688{ 704{
689 COM_TRY_BEGIN 705 COM_TRY_BEGIN
690 NWindows::NCOM::CPropVariant prop; 706 NWindows::NCOM::CPropVariant prop;
@@ -705,9 +721,9 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
705 COM_TRY_END 721 COM_TRY_END
706} 722}
707 723
708STDMETHODIMP CHandler::Open(IInStream *inStream, 724Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
709 const UInt64 * /* maxCheckStartPosition */, 725 const UInt64 * /* maxCheckStartPosition */,
710 IArchiveOpenCallback * /* openArchiveCallback */) 726 IArchiveOpenCallback * /* openArchiveCallback */))
711{ 727{
712 COM_TRY_BEGIN 728 COM_TRY_BEGIN
713 Close(); 729 Close();
@@ -722,18 +738,18 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
722 COM_TRY_END 738 COM_TRY_END
723} 739}
724 740
725STDMETHODIMP CHandler::Close() 741Z7_COM7F_IMF(CHandler::Close())
726{ 742{
727 _db.Clear(); 743 _db.Clear();
728 _stream.Release(); 744 _stream.Release();
729 return S_OK; 745 return S_OK;
730} 746}
731 747
732STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 748Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
733 Int32 testMode, IArchiveExtractCallback *extractCallback) 749 Int32 testMode, IArchiveExtractCallback *extractCallback))
734{ 750{
735 COM_TRY_BEGIN 751 COM_TRY_BEGIN
736 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 752 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
737 if (allFilesMode) 753 if (allFilesMode)
738 numItems = _db.Refs.Size(); 754 numItems = _db.Refs.Size();
739 if (numItems == 0) 755 if (numItems == 0)
@@ -746,7 +762,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
746 if (!item.IsDir()) 762 if (!item.IsDir())
747 totalSize += item.Size; 763 totalSize += item.Size;
748 } 764 }
749 RINOK(extractCallback->SetTotal(totalSize)); 765 RINOK(extractCallback->SetTotal(totalSize))
750 766
751 UInt64 totalPackSize; 767 UInt64 totalPackSize;
752 totalSize = totalPackSize = 0; 768 totalSize = totalPackSize = 0;
@@ -762,20 +778,20 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
762 { 778 {
763 lps->InSize = totalPackSize; 779 lps->InSize = totalPackSize;
764 lps->OutSize = totalSize; 780 lps->OutSize = totalSize;
765 RINOK(lps->SetCur()); 781 RINOK(lps->SetCur())
766 Int32 index = allFilesMode ? i : indices[i]; 782 const UInt32 index = allFilesMode ? i : indices[i];
767 const CItem &item = _db.Items[_db.Refs[index].Did]; 783 const CItem &item = _db.Items[_db.Refs[index].Did];
768 784
769 CMyComPtr<ISequentialOutStream> outStream; 785 CMyComPtr<ISequentialOutStream> outStream;
770 Int32 askMode = testMode ? 786 const Int32 askMode = testMode ?
771 NExtract::NAskMode::kTest : 787 NExtract::NAskMode::kTest :
772 NExtract::NAskMode::kExtract; 788 NExtract::NAskMode::kExtract;
773 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 789 RINOK(extractCallback->GetStream(index, &outStream, askMode))
774 790
775 if (item.IsDir()) 791 if (item.IsDir())
776 { 792 {
777 RINOK(extractCallback->PrepareOperation(askMode)); 793 RINOK(extractCallback->PrepareOperation(askMode))
778 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 794 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
779 continue; 795 continue;
780 } 796 }
781 797
@@ -784,7 +800,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
784 800
785 if (!testMode && !outStream) 801 if (!testMode && !outStream)
786 continue; 802 continue;
787 RINOK(extractCallback->PrepareOperation(askMode)); 803 RINOK(extractCallback->PrepareOperation(askMode))
788 Int32 res = NExtract::NOperationResult::kDataError; 804 Int32 res = NExtract::NOperationResult::kDataError;
789 CMyComPtr<ISequentialInStream> inStream; 805 CMyComPtr<ISequentialInStream> inStream;
790 HRESULT hres = GetStream(index, &inStream); 806 HRESULT hres = GetStream(index, &inStream);
@@ -794,45 +810,45 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
794 res = NExtract::NOperationResult::kUnsupportedMethod; 810 res = NExtract::NOperationResult::kUnsupportedMethod;
795 else 811 else
796 { 812 {
797 RINOK(hres); 813 RINOK(hres)
798 if (inStream) 814 if (inStream)
799 { 815 {
800 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 816 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
801 if (copyCoderSpec->TotalSize == item.Size) 817 if (copyCoderSpec->TotalSize == item.Size)
802 res = NExtract::NOperationResult::kOK; 818 res = NExtract::NOperationResult::kOK;
803 } 819 }
804 } 820 }
805 outStream.Release(); 821 outStream.Release();
806 RINOK(extractCallback->SetOperationResult(res)); 822 RINOK(extractCallback->SetOperationResult(res))
807 } 823 }
808 return S_OK; 824 return S_OK;
809 COM_TRY_END 825 COM_TRY_END
810} 826}
811 827
812STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 828Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
813{ 829{
814 *numItems = _db.Refs.Size(); 830 *numItems = _db.Refs.Size();
815 return S_OK; 831 return S_OK;
816} 832}
817 833
818STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 834Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
819{ 835{
820 COM_TRY_BEGIN 836 COM_TRY_BEGIN
821 *stream = 0; 837 *stream = NULL;
822 UInt32 itemIndex = _db.Refs[index].Did; 838 const UInt32 itemIndex = _db.Refs[index].Did;
823 const CItem &item = _db.Items[itemIndex]; 839 const CItem &item = _db.Items[itemIndex];
824 CClusterInStream *streamSpec = new CClusterInStream; 840 CClusterInStream *streamSpec = new CClusterInStream;
825 CMyComPtr<ISequentialInStream> streamTemp = streamSpec; 841 CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
826 streamSpec->Stream = _stream; 842 streamSpec->Stream = _stream;
827 streamSpec->StartOffset = 0; 843 streamSpec->StartOffset = 0;
828 844
829 bool isLargeStream = (itemIndex == 0 || _db.IsLargeStream(item.Size)); 845 const bool isLargeStream = (itemIndex == 0 || _db.IsLargeStream(item.Size));
830 int bsLog = isLargeStream ? _db.SectorSizeBits : _db.MiniSectorSizeBits; 846 const unsigned bsLog = isLargeStream ? _db.SectorSizeBits : _db.MiniSectorSizeBits;
831 streamSpec->BlockSizeLog = bsLog; 847 streamSpec->BlockSizeLog = bsLog;
832 streamSpec->Size = item.Size; 848 streamSpec->Size = item.Size;
833 849
834 UInt32 clusterSize = (UInt32)1 << bsLog; 850 const UInt32 clusterSize = (UInt32)1 << bsLog;
835 UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog; 851 const UInt64 numClusters64 = (item.Size + clusterSize - 1) >> bsLog;
836 if (numClusters64 >= ((UInt32)1 << 31)) 852 if (numClusters64 >= ((UInt32)1 << 31))
837 return E_NOTIMPL; 853 return E_NOTIMPL;
838 streamSpec->Vector.ClearAndReserve((unsigned)numClusters64); 854 streamSpec->Vector.ClearAndReserve((unsigned)numClusters64);
@@ -864,14 +880,14 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
864 } 880 }
865 if (sid != NFatID::kEndOfChain) 881 if (sid != NFatID::kEndOfChain)
866 return S_FALSE; 882 return S_FALSE;
867 RINOK(streamSpec->InitAndSeek()); 883 RINOK(streamSpec->InitAndSeek())
868 *stream = streamTemp.Detach(); 884 *stream = streamTemp.Detach();
869 return S_OK; 885 return S_OK;
870 COM_TRY_END 886 COM_TRY_END
871} 887}
872 888
873REGISTER_ARC_I( 889REGISTER_ARC_I(
874 "Compound", "msi msp doc xls ppt", 0, 0xE5, 890 "Compound", "msi msp doc xls ppt", NULL, 0xE5,
875 kSignature, 891 kSignature,
876 0, 892 0,
877 0, 893 0,
diff --git a/CPP/7zip/Archive/Common/CoderMixer2.cpp b/CPP/7zip/Archive/Common/CoderMixer2.cpp
index c8b67bd..b6ddeb8 100644
--- a/CPP/7zip/Archive/Common/CoderMixer2.cpp
+++ b/CPP/7zip/Archive/Common/CoderMixer2.cpp
@@ -6,7 +6,7 @@
6 6
7#ifdef USE_MIXER_ST 7#ifdef USE_MIXER_ST
8 8
9STDMETHODIMP CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 *processedSize) 9Z7_COM7F_IMF(CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 *processedSize))
10{ 10{
11 UInt32 realProcessed = 0; 11 UInt32 realProcessed = 0;
12 HRESULT result = S_OK; 12 HRESULT result = S_OK;
@@ -21,7 +21,7 @@ STDMETHODIMP CSequentialInStreamCalcSize::Read(void *data, UInt32 size, UInt32 *
21} 21}
22 22
23 23
24STDMETHODIMP COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *processedSize) 24Z7_COM7F_IMF(COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *processedSize))
25{ 25{
26 HRESULT result = S_OK; 26 HRESULT result = S_OK;
27 if (_stream) 27 if (_stream)
@@ -32,7 +32,7 @@ STDMETHODIMP COutStreamCalcSize::Write(const void *data, UInt32 size, UInt32 *pr
32 return result; 32 return result;
33} 33}
34 34
35STDMETHODIMP COutStreamCalcSize::OutStreamFinish() 35Z7_COM7F_IMF(COutStreamCalcSize::OutStreamFinish())
36{ 36{
37 HRESULT result = S_OK; 37 HRESULT result = S_OK;
38 if (_stream) 38 if (_stream)
@@ -73,7 +73,7 @@ HRESULT CCoder::CheckDataAfterEnd(bool &dataAfterEnd_Error /* , bool &InternalPa
73 if (getInStreamProcessedSize) 73 if (getInStreamProcessedSize)
74 { 74 {
75 UInt64 processed; 75 UInt64 processed;
76 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); 76 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed))
77 if (processed != (UInt64)(Int64)-1) 77 if (processed != (UInt64)(Int64)-1)
78 { 78 {
79 const UInt64 size = PackSizes[0]; 79 const UInt64 size = PackSizes[0];
@@ -97,7 +97,7 @@ HRESULT CCoder::CheckDataAfterEnd(bool &dataAfterEnd_Error /* , bool &InternalPa
97 if (!PackSizePointers[i]) 97 if (!PackSizePointers[i])
98 continue; 98 continue;
99 UInt64 processed; 99 UInt64 processed;
100 RINOK(getInStreamProcessedSize2->GetInStreamProcessedSize2(i, &processed)); 100 RINOK(getInStreamProcessedSize2->GetInStreamProcessedSize2(i, &processed))
101 if (processed != (UInt64)(Int64)-1) 101 if (processed != (UInt64)(Int64)-1)
102 { 102 {
103 const UInt64 size = PackSizes[i]; 103 const UInt64 size = PackSizes[i];
@@ -343,13 +343,11 @@ void CMixerST::AddCoder(const CCreatedCoder &cod)
343 { 343 {
344 IUnknown *unk = (cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2); 344 IUnknown *unk = (cod.Coder ? (IUnknown *)cod.Coder : (IUnknown *)cod.Coder2);
345 { 345 {
346 CMyComPtr<ISequentialInStream> s; 346 Z7_DECL_CMyComPtr_QI_FROM(ISequentialInStream, s, unk)
347 unk->QueryInterface(IID_ISequentialInStream, (void**)&s);
348 c2.CanRead = (s != NULL); 347 c2.CanRead = (s != NULL);
349 } 348 }
350 { 349 {
351 CMyComPtr<ISequentialOutStream> s; 350 Z7_DECL_CMyComPtr_QI_FROM(ISequentialOutStream, s, unk)
352 unk->QueryInterface(IID_ISequentialOutStream, (void**)&s);
353 c2.CanWrite = (s != NULL); 351 c2.CanWrite = (s != NULL);
354 } 352 }
355 } 353 }
@@ -382,8 +380,8 @@ HRESULT CMixerST::GetInStream2(
382 if (!seqInStream) 380 if (!seqInStream)
383 return E_NOTIMPL; 381 return E_NOTIMPL;
384 382
385 UInt32 numInStreams = EncodeMode ? 1 : coder.NumStreams; 383 const UInt32 numInStreams = EncodeMode ? 1 : coder.NumStreams;
386 UInt32 startIndex = EncodeMode ? coderIndex : _bi.Coder_to_Stream[coderIndex]; 384 const UInt32 startIndex = EncodeMode ? coderIndex : _bi.Coder_to_Stream[coderIndex];
387 385
388 bool isSet = false; 386 bool isSet = false;
389 387
@@ -394,8 +392,8 @@ HRESULT CMixerST::GetInStream2(
394 if (setStream) 392 if (setStream)
395 { 393 {
396 CMyComPtr<ISequentialInStream> seqInStream2; 394 CMyComPtr<ISequentialInStream> seqInStream2;
397 RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + 0, &seqInStream2)); 395 RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + 0, &seqInStream2))
398 RINOK(setStream->SetInStream(seqInStream2)); 396 RINOK(setStream->SetInStream(seqInStream2))
399 isSet = true; 397 isSet = true;
400 } 398 }
401 } 399 }
@@ -410,8 +408,8 @@ HRESULT CMixerST::GetInStream2(
410 for (UInt32 i = 0; i < numInStreams; i++) 408 for (UInt32 i = 0; i < numInStreams; i++)
411 { 409 {
412 CMyComPtr<ISequentialInStream> seqInStream2; 410 CMyComPtr<ISequentialInStream> seqInStream2;
413 RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + i, &seqInStream2)); 411 RINOK(GetInStream(inStreams, /* inSizes, */ startIndex + i, &seqInStream2))
414 RINOK(setStream2->SetInStream2(i, seqInStream2)); 412 RINOK(setStream2->SetInStream2(i, seqInStream2))
415 } 413 }
416 } 414 }
417 415
@@ -451,7 +449,7 @@ HRESULT CMixerST::GetInStream(
451 return E_INVALIDARG; 449 return E_INVALIDARG;
452 450
453 RINOK(GetInStream2(inStreams, /* inSizes, */ 451 RINOK(GetInStream2(inStreams, /* inSizes, */
454 _bi.Bonds[(unsigned)bond].Get_OutIndex(EncodeMode), &seqInStream)); 452 _bi.Bonds[(unsigned)bond].Get_OutIndex(EncodeMode), &seqInStream))
455 453
456 while (_binderStreams.Size() <= (unsigned)bond) 454 while (_binderStreams.Size() <= (unsigned)bond)
457 _binderStreams.AddNew(); 455 _binderStreams.AddNew();
@@ -504,7 +502,7 @@ HRESULT CMixerST::GetOutStream(
504 if (bond < 0) 502 if (bond < 0)
505 return E_INVALIDARG; 503 return E_INVALIDARG;
506 504
507 UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); 505 const UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode);
508 506
509 UInt32 coderIndex = inStreamIndex; 507 UInt32 coderIndex = inStreamIndex;
510 UInt32 coderStreamIndex = 0; 508 UInt32 coderStreamIndex = 0;
@@ -523,8 +521,8 @@ HRESULT CMixerST::GetOutStream(
523 if (!seqOutStream) 521 if (!seqOutStream)
524 return E_NOTIMPL; 522 return E_NOTIMPL;
525 523
526 UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; 524 const UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1;
527 UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; 525 const UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex;
528 526
529 bool isSet = false; 527 bool isSet = false;
530 528
@@ -535,8 +533,8 @@ HRESULT CMixerST::GetOutStream(
535 if (setOutStream) 533 if (setOutStream)
536 { 534 {
537 CMyComPtr<ISequentialOutStream> seqOutStream2; 535 CMyComPtr<ISequentialOutStream> seqOutStream2;
538 RINOK(GetOutStream(outStreams, /* outSizes, */ startIndex + 0, &seqOutStream2)); 536 RINOK(GetOutStream(outStreams, /* outSizes, */ startIndex + 0, &seqOutStream2))
539 RINOK(setOutStream->SetOutStream(seqOutStream2)); 537 RINOK(setOutStream->SetOutStream(seqOutStream2))
540 isSet = true; 538 isSet = true;
541 } 539 }
542 } 540 }
@@ -552,8 +550,8 @@ HRESULT CMixerST::GetOutStream(
552 for (UInt32 i = 0; i < numOutStreams; i++) 550 for (UInt32 i = 0; i < numOutStreams; i++)
553 { 551 {
554 CMyComPtr<ISequentialOutStream> seqOutStream2; 552 CMyComPtr<ISequentialOutStream> seqOutStream2;
555 RINOK(GetOutStream(outStreams, startIndex + i, &seqOutStream2)); 553 RINOK(GetOutStream(outStreams, startIndex + i, &seqOutStream2))
556 RINOK(setStream2->SetOutStream2(i, seqOutStream2)); 554 RINOK(setStream2->SetOutStream2(i, seqOutStream2))
557 } 555 }
558 */ 556 */
559 } 557 }
@@ -616,7 +614,7 @@ HRESULT CMixerST::FinishStream(UInt32 streamIndex)
616 if (bond < 0) 614 if (bond < 0)
617 return E_INVALIDARG; 615 return E_INVALIDARG;
618 616
619 UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode); 617 const UInt32 inStreamIndex = _bi.Bonds[(unsigned)bond].Get_InIndex(EncodeMode);
620 618
621 UInt32 coderIndex = inStreamIndex; 619 UInt32 coderIndex = inStreamIndex;
622 UInt32 coderStreamIndex = 0; 620 UInt32 coderStreamIndex = 0;
@@ -639,8 +637,8 @@ HRESULT CMixerST::FinishCoder(UInt32 coderIndex)
639{ 637{
640 CCoder &coder = _coders[coderIndex]; 638 CCoder &coder = _coders[coderIndex];
641 639
642 UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1; 640 const UInt32 numOutStreams = EncodeMode ? coder.NumStreams : 1;
643 UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex; 641 const UInt32 startIndex = EncodeMode ? _bi.Coder_to_Stream[coderIndex]: coderIndex;
644 642
645 HRESULT res = S_OK; 643 HRESULT res = S_OK;
646 for (unsigned i = 0; i < numOutStreams; i++) 644 for (unsigned i = 0; i < numOutStreams; i++)
@@ -671,7 +669,7 @@ void CMixerST::SelectMainCoder(bool useFirst)
671 if (coder.NumStreams != 1) 669 if (coder.NumStreams != 1)
672 break; 670 break;
673 671
674 UInt32 st = _bi.Coder_to_Stream[ci]; 672 const UInt32 st = _bi.Coder_to_Stream[ci];
675 if (_bi.IsStream_in_PackStreams(st)) 673 if (_bi.IsStream_in_PackStreams(st))
676 break; 674 break;
677 const int bond = _bi.FindBond_for_PackStream(st); 675 const int bond = _bi.FindBond_for_PackStream(st);
@@ -706,32 +704,32 @@ HRESULT CMixerST::Code(
706 dataAfterEnd_Error = false; 704 dataAfterEnd_Error = false;
707 705
708 _binderStreams.Clear(); 706 _binderStreams.Clear();
709 unsigned ci = MainCoderIndex; 707 const unsigned ci = MainCoderIndex;
710 708
711 const CCoder &mainCoder = _coders[MainCoderIndex]; 709 const CCoder &mainCoder = _coders[MainCoderIndex];
712 710
713 CObjectVector< CMyComPtr<ISequentialInStream> > seqInStreams; 711 CObjectVector< CMyComPtr<ISequentialInStream> > seqInStreams;
714 CObjectVector< CMyComPtr<ISequentialOutStream> > seqOutStreams; 712 CObjectVector< CMyComPtr<ISequentialOutStream> > seqOutStreams;
715 713
716 UInt32 numInStreams = EncodeMode ? 1 : mainCoder.NumStreams; 714 const UInt32 numInStreams = EncodeMode ? 1 : mainCoder.NumStreams;
717 UInt32 numOutStreams = !EncodeMode ? 1 : mainCoder.NumStreams; 715 const UInt32 numOutStreams = !EncodeMode ? 1 : mainCoder.NumStreams;
718 716
719 UInt32 startInIndex = EncodeMode ? ci : _bi.Coder_to_Stream[ci]; 717 const UInt32 startInIndex = EncodeMode ? ci : _bi.Coder_to_Stream[ci];
720 UInt32 startOutIndex = !EncodeMode ? ci : _bi.Coder_to_Stream[ci]; 718 const UInt32 startOutIndex = !EncodeMode ? ci : _bi.Coder_to_Stream[ci];
721 719
722 UInt32 i; 720 UInt32 i;
723 721
724 for (i = 0; i < numInStreams; i++) 722 for (i = 0; i < numInStreams; i++)
725 { 723 {
726 CMyComPtr<ISequentialInStream> seqInStream; 724 CMyComPtr<ISequentialInStream> seqInStream;
727 RINOK(GetInStream(inStreams, /* inSizes, */ startInIndex + i, &seqInStream)); 725 RINOK(GetInStream(inStreams, /* inSizes, */ startInIndex + i, &seqInStream))
728 seqInStreams.Add(seqInStream); 726 seqInStreams.Add(seqInStream);
729 } 727 }
730 728
731 for (i = 0; i < numOutStreams; i++) 729 for (i = 0; i < numOutStreams; i++)
732 { 730 {
733 CMyComPtr<ISequentialOutStream> seqOutStream; 731 CMyComPtr<ISequentialOutStream> seqOutStream;
734 RINOK(GetOutStream(outStreams, /* outSizes, */ startOutIndex + i, &seqOutStream)); 732 RINOK(GetOutStream(outStreams, /* outSizes, */ startOutIndex + i, &seqOutStream))
735 seqOutStreams.Add(seqOutStream); 733 seqOutStreams.Add(seqOutStream);
736 } 734 }
737 735
@@ -755,15 +753,19 @@ HRESULT CMixerST::Code(
755 CMyComPtr<ICompressInitEncoder> initEncoder; 753 CMyComPtr<ICompressInitEncoder> initEncoder;
756 coder.QueryInterface(IID_ICompressInitEncoder, (void **)&initEncoder); 754 coder.QueryInterface(IID_ICompressInitEncoder, (void **)&initEncoder);
757 if (initEncoder) 755 if (initEncoder)
758 RINOK(initEncoder->InitEncoder()); 756 {
757 RINOK(initEncoder->InitEncoder())
758 }
759 } 759 }
760 else 760 else
761 { 761 {
762 CMyComPtr<ICompressSetOutStreamSize> setOutStreamSize; 762 CMyComPtr<ICompressSetOutStreamSize> setOutStreamSize;
763 coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize); 763 coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize);
764 if (setOutStreamSize) 764 if (setOutStreamSize)
765 {
765 RINOK(setOutStreamSize->SetOutStreamSize( 766 RINOK(setOutStreamSize->SetOutStreamSize(
766 EncodeMode ? coder.PackSizePointers[0] : coder.UnpackSizePointer)); 767 EncodeMode ? coder.PackSizePointers[0] : coder.UnpackSizePointer))
768 }
767 } 769 }
768 } 770 }
769 771
@@ -811,7 +813,7 @@ HRESULT CMixerST::Code(
811 813
812 for (i = 0; i < _coders.Size(); i++) 814 for (i = 0; i < _coders.Size(); i++)
813 { 815 {
814 RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /*, InternalPackSizeError */)); 816 RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /*, InternalPackSizeError */))
815 } 817 }
816 818
817 return S_OK; 819 return S_OK;
@@ -834,7 +836,7 @@ HRESULT CMixerST::GetMainUnpackStream(
834 coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize); 836 coder.QueryInterface(IID_ICompressSetOutStreamSize, (void **)&setOutStreamSize);
835 if (setOutStreamSize) 837 if (setOutStreamSize)
836 { 838 {
837 RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer)); 839 RINOK(setOutStreamSize->SetOutStreamSize(coder.UnpackSizePointer))
838 } 840 }
839 } 841 }
840 842
@@ -919,7 +921,7 @@ HRESULT CMixerMT::SetBindInfo(const CBindInfo &bindInfo)
919 _streamBinders.Clear(); 921 _streamBinders.Clear();
920 FOR_VECTOR (i, _bi.Bonds) 922 FOR_VECTOR (i, _bi.Bonds)
921 { 923 {
922 // RINOK(_streamBinders.AddNew().CreateEvents()); 924 // RINOK(_streamBinders.AddNew().CreateEvents())
923 _streamBinders.AddNew(); 925 _streamBinders.AddNew();
924 } 926 }
925 return S_OK; 927 return S_OK;
@@ -946,7 +948,7 @@ HRESULT CMixerMT::ReInit2()
946{ 948{
947 FOR_VECTOR (i, _streamBinders) 949 FOR_VECTOR (i, _streamBinders)
948 { 950 {
949 RINOK(_streamBinders[i].Create_ReInit()); 951 RINOK(_streamBinders[i].Create_ReInit())
950 } 952 }
951 return S_OK; 953 return S_OK;
952} 954}
@@ -986,8 +988,8 @@ HRESULT CMixerMT::Init(ISequentialInStream * const *inStreams, ISequentialOutStr
986 988
987 UInt32 j; 989 UInt32 j;
988 990
989 unsigned numInStreams = EncodeMode ? 1 : csi.NumStreams; 991 const unsigned numInStreams = EncodeMode ? 1 : csi.NumStreams;
990 unsigned numOutStreams = EncodeMode ? csi.NumStreams : 1; 992 const unsigned numOutStreams = EncodeMode ? csi.NumStreams : 1;
991 993
992 coderInfo.InStreams.Clear(); 994 coderInfo.InStreams.Clear();
993 for (j = 0; j < numInStreams; j++) 995 for (j = 0; j < numInStreams; j++)
@@ -1102,8 +1104,8 @@ HRESULT CMixerMT::Code(
1102 if (wres != 0) 1104 if (wres != 0)
1103 return HRESULT_FROM_WIN32(wres); 1105 return HRESULT_FROM_WIN32(wres);
1104 1106
1105 RINOK(ReturnIfError(E_ABORT)); 1107 RINOK(ReturnIfError(E_ABORT))
1106 RINOK(ReturnIfError(E_OUTOFMEMORY)); 1108 RINOK(ReturnIfError(E_OUTOFMEMORY))
1107 1109
1108 for (i = 0; i < _coders.Size(); i++) 1110 for (i = 0; i < _coders.Size(); i++)
1109 { 1111 {
@@ -1115,7 +1117,7 @@ HRESULT CMixerMT::Code(
1115 return result; 1117 return result;
1116 } 1118 }
1117 1119
1118 RINOK(ReturnIfError(S_FALSE)); 1120 RINOK(ReturnIfError(S_FALSE))
1119 1121
1120 for (i = 0; i < _coders.Size(); i++) 1122 for (i = 0; i < _coders.Size(); i++)
1121 { 1123 {
@@ -1126,7 +1128,7 @@ HRESULT CMixerMT::Code(
1126 1128
1127 for (i = 0; i < _coders.Size(); i++) 1129 for (i = 0; i < _coders.Size(); i++)
1128 { 1130 {
1129 RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /* , InternalPackSizeError */)); 1131 RINOK(_coders[i].CheckDataAfterEnd(dataAfterEnd_Error /* , InternalPackSizeError */))
1130 } 1132 }
1131 1133
1132 return S_OK; 1134 return S_OK;
diff --git a/CPP/7zip/Archive/Common/CoderMixer2.h b/CPP/7zip/Archive/Common/CoderMixer2.h
index f099ac3..484a608 100644
--- a/CPP/7zip/Archive/Common/CoderMixer2.h
+++ b/CPP/7zip/Archive/Common/CoderMixer2.h
@@ -1,7 +1,7 @@
1// CoderMixer2.h 1// CoderMixer2.h
2 2
3#ifndef __CODER_MIXER2_H 3#ifndef ZIP7_INC_CODER_MIXER2_H
4#define __CODER_MIXER2_H 4#define ZIP7_INC_CODER_MIXER2_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyVector.h" 7#include "../../../Common/MyVector.h"
@@ -10,11 +10,11 @@
10 10
11#include "../../Common/CreateCoder.h" 11#include "../../Common/CreateCoder.h"
12 12
13#ifdef _7ZIP_ST 13#ifdef Z7_ST
14 #define USE_MIXER_ST 14 #define USE_MIXER_ST
15#else 15#else
16 #define USE_MIXER_MT 16 #define USE_MIXER_MT
17 #ifndef _SFX 17 #ifndef Z7_SFX
18 #define USE_MIXER_ST 18 #define USE_MIXER_ST
19 #endif 19 #endif
20#endif 20#endif
@@ -28,18 +28,13 @@
28 28
29#ifdef USE_MIXER_ST 29#ifdef USE_MIXER_ST
30 30
31class CSequentialInStreamCalcSize: 31Z7_CLASS_IMP_COM_1(
32 public ISequentialInStream, 32 CSequentialInStreamCalcSize
33 public CMyUnknownImp 33 , ISequentialInStream
34{ 34)
35public: 35 bool _wasFinished;
36 MY_UNKNOWN_IMP1(ISequentialInStream)
37
38 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
39private:
40 CMyComPtr<ISequentialInStream> _stream; 36 CMyComPtr<ISequentialInStream> _stream;
41 UInt64 _size; 37 UInt64 _size;
42 bool _wasFinished;
43public: 38public:
44 void SetStream(ISequentialInStream *stream) { _stream = stream; } 39 void SetStream(ISequentialInStream *stream) { _stream = stream; }
45 void Init() 40 void Init()
@@ -53,19 +48,14 @@ public:
53}; 48};
54 49
55 50
56class COutStreamCalcSize: 51Z7_CLASS_IMP_COM_2(
57 public ISequentialOutStream, 52 COutStreamCalcSize
58 public IOutStreamFinish, 53 , ISequentialOutStream
59 public CMyUnknownImp 54 , IOutStreamFinish
60{ 55)
61 CMyComPtr<ISequentialOutStream> _stream; 56 CMyComPtr<ISequentialOutStream> _stream;
62 UInt64 _size; 57 UInt64 _size;
63public: 58public:
64 MY_UNKNOWN_IMP2(ISequentialOutStream, IOutStreamFinish)
65
66 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
67 STDMETHOD(OutStreamFinish)();
68
69 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 59 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
70 void ReleaseStream() { _stream.Release(); } 60 void ReleaseStream() { _stream.Release(); }
71 void Init() { _size = 0; } 61 void Init() { _size = 0; }
@@ -122,7 +112,7 @@ struct CBindInfo
122 bool SetUnpackCoder() 112 bool SetUnpackCoder()
123 { 113 {
124 bool isOk = false; 114 bool isOk = false;
125 FOR_VECTOR(i, Coders) 115 FOR_VECTOR (i, Coders)
126 { 116 {
127 if (FindBond_for_UnpackStream(i) < 0) 117 if (FindBond_for_UnpackStream(i) < 0)
128 { 118 {
@@ -142,7 +132,7 @@ struct CBindInfo
142 132
143 int FindStream_in_PackStreams(UInt32 streamIndex) const 133 int FindStream_in_PackStreams(UInt32 streamIndex) const
144 { 134 {
145 FOR_VECTOR(i, PackStreams) 135 FOR_VECTOR (i, PackStreams)
146 if (PackStreams[i] == streamIndex) 136 if (PackStreams[i] == streamIndex)
147 return (int)i; 137 return (int)i;
148 return -1; 138 return -1;
@@ -189,11 +179,12 @@ struct CBindInfo
189 179
190class CCoder 180class CCoder
191{ 181{
192 CLASS_NO_COPY(CCoder); 182 Z7_CLASS_NO_COPY(CCoder)
193public: 183public:
194 CMyComPtr<ICompressCoder> Coder; 184 CMyComPtr<ICompressCoder> Coder;
195 CMyComPtr<ICompressCoder2> Coder2; 185 CMyComPtr<ICompressCoder2> Coder2;
196 UInt32 NumStreams; 186 UInt32 NumStreams;
187 bool Finish;
197 188
198 UInt64 UnpackSize; 189 UInt64 UnpackSize;
199 const UInt64 *UnpackSizePointer; 190 const UInt64 *UnpackSizePointer;
@@ -201,8 +192,6 @@ public:
201 CRecordVector<UInt64> PackSizes; 192 CRecordVector<UInt64> PackSizes;
202 CRecordVector<const UInt64 *> PackSizePointers; 193 CRecordVector<const UInt64 *> PackSizePointers;
203 194
204 bool Finish;
205
206 CCoder(): Finish(false) {} 195 CCoder(): Finish(false) {}
207 196
208 void SetCoderInfo(const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish); 197 void SetCoderInfo(const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish);
@@ -251,7 +240,7 @@ public:
251 // , InternalPackSizeError(false) 240 // , InternalPackSizeError(false)
252 {} 241 {}
253 242
254 virtual ~CMixer() {}; 243 virtual ~CMixer() {}
255 /* 244 /*
256 Sequence of calling: 245 Sequence of calling:
257 246
@@ -323,7 +312,8 @@ class CMixerST:
323 public CMixer, 312 public CMixer,
324 public CMyUnknownImp 313 public CMyUnknownImp
325{ 314{
326 CLASS_NO_COPY(CMixerST) 315 Z7_COM_UNKNOWN_IMP_0
316 Z7_CLASS_NO_COPY(CMixerST)
327 317
328 HRESULT GetInStream2(ISequentialInStream * const *inStreams, /* const UInt64 * const *inSizes, */ 318 HRESULT GetInStream2(ISequentialInStream * const *inStreams, /* const UInt64 * const *inSizes, */
329 UInt32 outStreamIndex, ISequentialInStream **inStreamRes); 319 UInt32 outStreamIndex, ISequentialInStream **inStreamRes);
@@ -340,23 +330,21 @@ public:
340 330
341 CObjectVector<CStBinderStream> _binderStreams; 331 CObjectVector<CStBinderStream> _binderStreams;
342 332
343 MY_UNKNOWN_IMP
344
345 CMixerST(bool encodeMode); 333 CMixerST(bool encodeMode);
346 ~CMixerST(); 334 ~CMixerST() Z7_DESTRUCTOR_override;
347 335
348 virtual void AddCoder(const CCreatedCoder &cod); 336 virtual void AddCoder(const CCreatedCoder &cod) Z7_override;
349 virtual CCoder &GetCoder(unsigned index); 337 virtual CCoder &GetCoder(unsigned index) Z7_override;
350 virtual void SelectMainCoder(bool useFirst); 338 virtual void SelectMainCoder(bool useFirst) Z7_override;
351 virtual HRESULT ReInit2(); 339 virtual HRESULT ReInit2() Z7_override;
352 virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) 340 virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) Z7_override
353 { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); } 341 { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); }
354 virtual HRESULT Code( 342 virtual HRESULT Code(
355 ISequentialInStream * const *inStreams, 343 ISequentialInStream * const *inStreams,
356 ISequentialOutStream * const *outStreams, 344 ISequentialOutStream * const *outStreams,
357 ICompressProgressInfo *progress, 345 ICompressProgressInfo *progress,
358 bool &dataAfterEnd_Error); 346 bool &dataAfterEnd_Error) Z7_override;
359 virtual UInt64 GetBondStreamSize(unsigned bondIndex) const; 347 virtual UInt64 GetBondStreamSize(unsigned bondIndex) const Z7_override;
360 348
361 HRESULT GetMainUnpackStream( 349 HRESULT GetMainUnpackStream(
362 ISequentialInStream * const *inStreams, 350 ISequentialInStream * const *inStreams,
@@ -372,12 +360,12 @@ public:
372 360
373class CCoderMT: public CCoder, public CVirtThread 361class CCoderMT: public CCoder, public CVirtThread
374{ 362{
375 CLASS_NO_COPY(CCoderMT) 363 Z7_CLASS_NO_COPY(CCoderMT)
376 CRecordVector<ISequentialInStream*> InStreamPointers; 364 CRecordVector<ISequentialInStream*> InStreamPointers;
377 CRecordVector<ISequentialOutStream*> OutStreamPointers; 365 CRecordVector<ISequentialOutStream*> OutStreamPointers;
378 366
379private: 367private:
380 void Execute(); 368 virtual void Execute() Z7_override;
381public: 369public:
382 bool EncodeMode; 370 bool EncodeMode;
383 HRESULT Result; 371 HRESULT Result;
@@ -397,7 +385,7 @@ public:
397 385
398 class CReleaser 386 class CReleaser
399 { 387 {
400 CLASS_NO_COPY(CReleaser) 388 Z7_CLASS_NO_COPY(CReleaser)
401 CCoderMT &_c; 389 CCoderMT &_c;
402 public: 390 public:
403 CReleaser(CCoderMT &c): _c(c) {} 391 CReleaser(CCoderMT &c): _c(c) {}
@@ -405,7 +393,14 @@ public:
405 }; 393 };
406 394
407 CCoderMT(): EncodeMode(false) {} 395 CCoderMT(): EncodeMode(false) {}
408 virtual ~CCoderMT() { CVirtThread::WaitThreadFinish(); } 396 ~CCoderMT() Z7_DESTRUCTOR_override
397 {
398 /* WaitThreadFinish() will be called in ~CVirtThread().
399 But we need WaitThreadFinish() call before CCoder destructor,
400 and before destructors of this class members.
401 */
402 CVirtThread::WaitThreadFinish();
403 }
409 404
410 void Code(ICompressProgressInfo *progress); 405 void Code(ICompressProgressInfo *progress);
411}; 406};
@@ -416,32 +411,31 @@ class CMixerMT:
416 public CMixer, 411 public CMixer,
417 public CMyUnknownImp 412 public CMyUnknownImp
418{ 413{
419 CLASS_NO_COPY(CMixerMT) 414 Z7_COM_UNKNOWN_IMP_0
415 Z7_CLASS_NO_COPY(CMixerMT)
420 416
421 CObjectVector<CStreamBinder> _streamBinders; 417 CObjectVector<CStreamBinder> _streamBinders;
422 418
423 HRESULT Init(ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams); 419 HRESULT Init(ISequentialInStream * const *inStreams, ISequentialOutStream * const *outStreams);
424 HRESULT ReturnIfError(HRESULT code); 420 HRESULT ReturnIfError(HRESULT code);
425 421
426 // virtual ~CMixerMT() {}; 422 // virtual ~CMixerMT() {}
427public: 423public:
428 CObjectVector<CCoderMT> _coders; 424 CObjectVector<CCoderMT> _coders;
429 425
430 MY_UNKNOWN_IMP 426 virtual HRESULT SetBindInfo(const CBindInfo &bindInfo) Z7_override;
431 427 virtual void AddCoder(const CCreatedCoder &cod) Z7_override;
432 virtual HRESULT SetBindInfo(const CBindInfo &bindInfo); 428 virtual CCoder &GetCoder(unsigned index) Z7_override;
433 virtual void AddCoder(const CCreatedCoder &cod); 429 virtual void SelectMainCoder(bool useFirst) Z7_override;
434 virtual CCoder &GetCoder(unsigned index); 430 virtual HRESULT ReInit2() Z7_override;
435 virtual void SelectMainCoder(bool useFirst); 431 virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish) Z7_override
436 virtual HRESULT ReInit2();
437 virtual void SetCoderInfo(unsigned coderIndex, const UInt64 *unpackSize, const UInt64 * const *packSizes, bool finish)
438 { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); } 432 { _coders[coderIndex].SetCoderInfo(unpackSize, packSizes, finish); }
439 virtual HRESULT Code( 433 virtual HRESULT Code(
440 ISequentialInStream * const *inStreams, 434 ISequentialInStream * const *inStreams,
441 ISequentialOutStream * const *outStreams, 435 ISequentialOutStream * const *outStreams,
442 ICompressProgressInfo *progress, 436 ICompressProgressInfo *progress,
443 bool &dataAfterEnd_Error); 437 bool &dataAfterEnd_Error) Z7_override;
444 virtual UInt64 GetBondStreamSize(unsigned bondIndex) const; 438 virtual UInt64 GetBondStreamSize(unsigned bondIndex) const Z7_override;
445 439
446 CMixerMT(bool encodeMode): CMixer(encodeMode) {} 440 CMixerMT(bool encodeMode): CMixer(encodeMode) {}
447}; 441};
diff --git a/CPP/7zip/Archive/Common/DummyOutStream.cpp b/CPP/7zip/Archive/Common/DummyOutStream.cpp
index 7c4f548..f48c32f 100644
--- a/CPP/7zip/Archive/Common/DummyOutStream.cpp
+++ b/CPP/7zip/Archive/Common/DummyOutStream.cpp
@@ -4,7 +4,7 @@
4 4
5#include "DummyOutStream.h" 5#include "DummyOutStream.h"
6 6
7STDMETHODIMP CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 7Z7_COM7F_IMF(CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
8{ 8{
9 UInt32 realProcessedSize = size; 9 UInt32 realProcessedSize = size;
10 HRESULT res = S_OK; 10 HRESULT res = S_OK;
diff --git a/CPP/7zip/Archive/Common/DummyOutStream.h b/CPP/7zip/Archive/Common/DummyOutStream.h
index b5a51fc..f884e13 100644
--- a/CPP/7zip/Archive/Common/DummyOutStream.h
+++ b/CPP/7zip/Archive/Common/DummyOutStream.h
@@ -1,24 +1,22 @@
1// DummyOutStream.h 1// DummyOutStream.h
2 2
3#ifndef __DUMMY_OUT_STREAM_H 3#ifndef ZIP7_INC_DUMMY_OUT_STREAM_H
4#define __DUMMY_OUT_STREAM_H 4#define ZIP7_INC_DUMMY_OUT_STREAM_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../../IStream.h" 8#include "../../IStream.h"
9 9
10class CDummyOutStream: 10Z7_CLASS_IMP_NOQIB_1(
11 public ISequentialOutStream, 11 CDummyOutStream
12 public CMyUnknownImp 12 , ISequentialOutStream
13{ 13)
14 CMyComPtr<ISequentialOutStream> _stream; 14 CMyComPtr<ISequentialOutStream> _stream;
15 UInt64 _size; 15 UInt64 _size;
16public: 16public:
17 void SetStream(ISequentialOutStream *outStream) { _stream = outStream; } 17 void SetStream(ISequentialOutStream *outStream) { _stream = outStream; }
18 void ReleaseStream() { _stream.Release(); } 18 void ReleaseStream() { _stream.Release(); }
19 void Init() { _size = 0; } 19 void Init() { _size = 0; }
20 MY_UNKNOWN_IMP
21 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
22 UInt64 GetSize() const { return _size; } 20 UInt64 GetSize() const { return _size; }
23}; 21};
24 22
diff --git a/CPP/7zip/Archive/Common/FindSignature.cpp b/CPP/7zip/Archive/Common/FindSignature.cpp
index fc952fa..6c6740f 100644
--- a/CPP/7zip/Archive/Common/FindSignature.cpp
+++ b/CPP/7zip/Archive/Common/FindSignature.cpp
@@ -16,7 +16,7 @@ HRESULT FindSignatureInStream(ISequentialInStream *stream,
16{ 16{
17 resPos = 0; 17 resPos = 0;
18 CByteBuffer byteBuffer2(signatureSize); 18 CByteBuffer byteBuffer2(signatureSize);
19 RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize)); 19 RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize))
20 20
21 if (memcmp(byteBuffer2, signature, signatureSize) == 0) 21 if (memcmp(byteBuffer2, signature, signatureSize) == 0)
22 return S_OK; 22 return S_OK;
@@ -29,23 +29,23 @@ HRESULT FindSignatureInStream(ISequentialInStream *stream,
29 resPos = 1; 29 resPos = 1;
30 for (;;) 30 for (;;)
31 { 31 {
32 if (limit != NULL) 32 if (limit)
33 if (resPos > *limit) 33 if (resPos > *limit)
34 return S_FALSE; 34 return S_FALSE;
35 do 35 do
36 { 36 {
37 UInt32 numReadBytes = kBufferSize - numPrevBytes; 37 const UInt32 numReadBytes = kBufferSize - numPrevBytes;
38 UInt32 processedSize; 38 UInt32 processedSize;
39 RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); 39 RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize))
40 numPrevBytes += processedSize; 40 numPrevBytes += processedSize;
41 if (processedSize == 0) 41 if (processedSize == 0)
42 return S_FALSE; 42 return S_FALSE;
43 } 43 }
44 while (numPrevBytes < signatureSize); 44 while (numPrevBytes < signatureSize);
45 UInt32 numTests = numPrevBytes - signatureSize + 1; 45 const UInt32 numTests = numPrevBytes - signatureSize + 1;
46 for (UInt32 pos = 0; pos < numTests; pos++) 46 for (UInt32 pos = 0; pos < numTests; pos++)
47 { 47 {
48 Byte b = signature[0]; 48 const Byte b = signature[0];
49 for (; buffer[pos] != b && pos < numTests; pos++); 49 for (; buffer[pos] != b && pos < numTests; pos++);
50 if (pos == numTests) 50 if (pos == numTests)
51 break; 51 break;
diff --git a/CPP/7zip/Archive/Common/FindSignature.h b/CPP/7zip/Archive/Common/FindSignature.h
index c359b9e..f0e6cdd 100644
--- a/CPP/7zip/Archive/Common/FindSignature.h
+++ b/CPP/7zip/Archive/Common/FindSignature.h
@@ -1,7 +1,7 @@
1// FindSignature.h 1// FindSignature.h
2 2
3#ifndef __FIND_SIGNATURE_H 3#ifndef ZIP7_INC_FIND_SIGNATURE_H
4#define __FIND_SIGNATURE_H 4#define ZIP7_INC_FIND_SIGNATURE_H
5 5
6#include "../../IStream.h" 6#include "../../IStream.h"
7 7
diff --git a/CPP/7zip/Archive/Common/HandlerOut.cpp b/CPP/7zip/Archive/Common/HandlerOut.cpp
index 1b9a93e..17fed67 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
88 88
89 if (name.IsPrefixedBy_Ascii_NoCase("mt")) 89 if (name.IsPrefixedBy_Ascii_NoCase("mt"))
90 { 90 {
91 #ifndef _7ZIP_ST 91 #ifndef Z7_ST
92 _numThreads = _numProcessors; 92 _numThreads = _numProcessors;
93 _numThreads_WasForced = false; 93 _numThreads_WasForced = false;
94 hres = ParseMtProp2(name.Ptr(2), value, _numThreads, _numThreads_WasForced); 94 hres = ParseMtProp2(name.Ptr(2), value, _numThreads, _numThreads_WasForced);
@@ -112,7 +112,7 @@ bool CCommonMethodProps::SetCommonProperty(const UString &name, const PROPVARIAN
112} 112}
113 113
114 114
115#ifndef EXTRACT_ONLY 115#ifndef Z7_EXTRACT_ONLY
116 116
117static void SetMethodProp32(CMethodProps &m, PROPID propID, UInt32 value) 117static void SetMethodProp32(CMethodProps &m, PROPID propID, UInt32 value)
118{ 118{
@@ -127,7 +127,7 @@ void CMultiMethodProps::SetGlobalLevelTo(COneMethodInfo &oneMethodInfo) const
127 SetMethodProp32(oneMethodInfo, NCoderPropID::kLevel, (UInt32)level); 127 SetMethodProp32(oneMethodInfo, NCoderPropID::kLevel, (UInt32)level);
128} 128}
129 129
130#ifndef _7ZIP_ST 130#ifndef Z7_ST
131 131
132static void SetMethodProp32_Replace(CMethodProps &m, PROPID propID, UInt32 value) 132static void SetMethodProp32_Replace(CMethodProps &m, PROPID propID, UInt32 value)
133{ 133{
@@ -151,7 +151,7 @@ void CMultiMethodProps::SetMethodThreadsTo_Replace(CMethodProps &oneMethodInfo,
151 SetMethodProp32_Replace(oneMethodInfo, NCoderPropID::kNumThreads, numThreads); 151 SetMethodProp32_Replace(oneMethodInfo, NCoderPropID::kNumThreads, numThreads);
152} 152}
153 153
154#endif // _7ZIP_ST 154#endif // Z7_ST
155 155
156 156
157void CMultiMethodProps::InitMulti() 157void CMultiMethodProps::InitMulti()
@@ -189,7 +189,7 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN
189 { 189 {
190 name.Delete(0, 2); 190 name.Delete(0, 2);
191 UInt32 v = 9; 191 UInt32 v = 9;
192 RINOK(ParsePropToUInt32(name, value, v)); 192 RINOK(ParsePropToUInt32(name, value, v))
193 _analysisLevel = (int)v; 193 _analysisLevel = (int)v;
194 return S_OK; 194 return S_OK;
195 } 195 }
@@ -208,13 +208,13 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN
208 } 208 }
209 209
210 UInt32 number; 210 UInt32 number;
211 unsigned index = ParseStringToUInt32(name, number); 211 const unsigned index = ParseStringToUInt32(name, number);
212 UString realName = name.Ptr(index); 212 const UString realName = name.Ptr(index);
213 if (index == 0) 213 if (index == 0)
214 { 214 {
215 if (name.IsEqualTo("f")) 215 if (name.IsEqualTo("f"))
216 { 216 {
217 HRESULT res = PROPVARIANT_to_bool(value, _autoFilter); 217 const HRESULT res = PROPVARIANT_to_bool(value, _autoFilter);
218 if (res == S_OK) 218 if (res == S_OK)
219 return res; 219 return res;
220 if (value.vt != VT_BSTR) 220 if (value.vt != VT_BSTR)
@@ -224,7 +224,7 @@ HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIAN
224 number = 0; 224 number = 0;
225 } 225 }
226 if (number > 64) 226 if (number > 64)
227 return E_FAIL; 227 return E_INVALIDARG;
228 for (unsigned j = _methods.Size(); j <= number; j++) 228 for (unsigned j = _methods.Size(); j <= number; j++)
229 _methods.AddNew(); 229 _methods.AddNew();
230 return _methods[number].ParseMethodFromPROPVARIANT(realName, value); 230 return _methods[number].ParseMethodFromPROPVARIANT(realName, value);
@@ -250,7 +250,7 @@ HRESULT CSingleMethodProps::SetProperty(const wchar_t *name2, const PROPVARIANT
250 if (name.IsPrefixedBy_Ascii_NoCase("x")) 250 if (name.IsPrefixedBy_Ascii_NoCase("x"))
251 { 251 {
252 UInt32 a = 9; 252 UInt32 a = 9;
253 RINOK(ParsePropToUInt32(name.Ptr(1), value, a)); 253 RINOK(ParsePropToUInt32(name.Ptr(1), value, a))
254 _level = a; 254 _level = a;
255 AddProp_Level(a); 255 AddProp_Level(a);
256 // processed = true; 256 // processed = true;
@@ -264,7 +264,7 @@ HRESULT CSingleMethodProps::SetProperty(const wchar_t *name2, const PROPVARIANT
264 return S_OK; 264 return S_OK;
265 } 265 }
266 } 266 }
267 RINOK(ParseMethodFromPROPVARIANT(name, value)); 267 RINOK(ParseMethodFromPROPVARIANT(name, value))
268 return S_OK; 268 return S_OK;
269} 269}
270 270
@@ -275,7 +275,7 @@ HRESULT CSingleMethodProps::SetProperties(const wchar_t * const *names, const PR
275 275
276 for (UInt32 i = 0; i < numProps; i++) 276 for (UInt32 i = 0; i < numProps; i++)
277 { 277 {
278 RINOK(SetProperty(names[i], values[i])); 278 RINOK(SetProperty(names[i], values[i]))
279 } 279 }
280 280
281 return S_OK; 281 return S_OK;
@@ -286,7 +286,7 @@ HRESULT CSingleMethodProps::SetProperties(const wchar_t * const *names, const PR
286 286
287static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest) 287static HRESULT PROPVARIANT_to_BoolPair(const PROPVARIANT &prop, CBoolPair &dest)
288{ 288{
289 RINOK(PROPVARIANT_to_bool(prop, dest.Val)); 289 RINOK(PROPVARIANT_to_bool(prop, dest.Val))
290 dest.Def = true; 290 dest.Def = true;
291 return S_OK; 291 return S_OK;
292} 292}
@@ -300,7 +300,7 @@ HRESULT CHandlerTimeOptions::Parse(const UString &name, const PROPVARIANT &prop,
300 if (name.IsPrefixedBy_Ascii_NoCase("tp")) 300 if (name.IsPrefixedBy_Ascii_NoCase("tp"))
301 { 301 {
302 UInt32 v = 0; 302 UInt32 v = 0;
303 RINOK(ParsePropToUInt32(name.Ptr(2), prop, v)); 303 RINOK(ParsePropToUInt32(name.Ptr(2), prop, v))
304 Prec = v; 304 Prec = v;
305 return S_OK; 305 return S_OK;
306 } 306 }
diff --git a/CPP/7zip/Archive/Common/HandlerOut.h b/CPP/7zip/Archive/Common/HandlerOut.h
index 41ee189..cfba46e 100644
--- a/CPP/7zip/Archive/Common/HandlerOut.h
+++ b/CPP/7zip/Archive/Common/HandlerOut.h
@@ -1,7 +1,7 @@
1// HandlerOut.h 1// HandlerOut.h
2 2
3#ifndef __HANDLER_OUT_H 3#ifndef ZIP7_INC_HANDLER_OUT_H
4#define __HANDLER_OUT_H 4#define ZIP7_INC_HANDLER_OUT_H
5 5
6#include "../../../Windows/System.h" 6#include "../../../Windows/System.h"
7 7
@@ -17,7 +17,7 @@ protected:
17 void InitCommon() 17 void InitCommon()
18 { 18 {
19 // _Write_MTime = true; 19 // _Write_MTime = true;
20 #ifndef _7ZIP_ST 20 #ifndef Z7_ST
21 _numProcessors = _numThreads = NWindows::NSystem::GetNumberOfProcessors(); 21 _numProcessors = _numThreads = NWindows::NSystem::GetNumberOfProcessors();
22 _numThreads_WasForced = false; 22 _numThreads_WasForced = false;
23 #endif 23 #endif
@@ -46,7 +46,7 @@ protected:
46 } 46 }
47 47
48public: 48public:
49 #ifndef _7ZIP_ST 49 #ifndef Z7_ST
50 UInt32 _numThreads; 50 UInt32 _numThreads;
51 UInt32 _numProcessors; 51 UInt32 _numProcessors;
52 bool _numThreads_WasForced; 52 bool _numThreads_WasForced;
@@ -63,7 +63,7 @@ public:
63}; 63};
64 64
65 65
66#ifndef EXTRACT_ONLY 66#ifndef Z7_EXTRACT_ONLY
67 67
68class CMultiMethodProps: public CCommonMethodProps 68class CMultiMethodProps: public CCommonMethodProps
69{ 69{
@@ -80,7 +80,7 @@ public:
80 80
81 void SetGlobalLevelTo(COneMethodInfo &oneMethodInfo) const; 81 void SetGlobalLevelTo(COneMethodInfo &oneMethodInfo) const;
82 82
83 #ifndef _7ZIP_ST 83 #ifndef Z7_ST
84 static void SetMethodThreadsTo_IfNotFinded(CMethodProps &props, UInt32 numThreads); 84 static void SetMethodThreadsTo_IfNotFinded(CMethodProps &props, UInt32 numThreads);
85 static void SetMethodThreadsTo_Replace(CMethodProps &props, UInt32 numThreads); 85 static void SetMethodThreadsTo_Replace(CMethodProps &props, UInt32 numThreads);
86 #endif 86 #endif
diff --git a/CPP/7zip/Archive/Common/InStreamWithCRC.cpp b/CPP/7zip/Archive/Common/InStreamWithCRC.cpp
index a2d6883..735d5d1 100644
--- a/CPP/7zip/Archive/Common/InStreamWithCRC.cpp
+++ b/CPP/7zip/Archive/Common/InStreamWithCRC.cpp
@@ -4,22 +4,33 @@
4 4
5#include "InStreamWithCRC.h" 5#include "InStreamWithCRC.h"
6 6
7STDMETHODIMP CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) 7Z7_COM7F_IMF(CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize))
8{ 8{
9 UInt32 realProcessed = 0; 9 UInt32 realProcessed = 0;
10 HRESULT result = S_OK; 10 HRESULT result = S_OK;
11 if (_stream) 11 if (size != 0)
12 result = _stream->Read(data, size, &realProcessed); 12 {
13 _size += realProcessed; 13 if (_stream)
14 if (size != 0 && realProcessed == 0) 14 result = _stream->Read(data, size, &realProcessed);
15 _wasFinished = true; 15 _size += realProcessed;
16 _crc = CrcUpdate(_crc, data, realProcessed); 16 if (realProcessed == 0)
17 _wasFinished = true;
18 else
19 _crc = CrcUpdate(_crc, data, realProcessed);
20 }
17 if (processedSize) 21 if (processedSize)
18 *processedSize = realProcessed; 22 *processedSize = realProcessed;
19 return result; 23 return result;
20} 24}
21 25
22STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) 26Z7_COM7F_IMF(CSequentialInStreamWithCRC::GetSize(UInt64 *size))
27{
28 *size = _fullSize;
29 return S_OK;
30}
31
32
33Z7_COM7F_IMF(CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize))
23{ 34{
24 UInt32 realProcessed = 0; 35 UInt32 realProcessed = 0;
25 HRESULT result = S_OK; 36 HRESULT result = S_OK;
@@ -36,7 +47,7 @@ STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSi
36 return result; 47 return result;
37} 48}
38 49
39STDMETHODIMP CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 50Z7_COM7F_IMF(CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
40{ 51{
41 if (seekOrigin != STREAM_SEEK_SET || offset != 0) 52 if (seekOrigin != STREAM_SEEK_SET || offset != 0)
42 return E_FAIL; 53 return E_FAIL;
diff --git a/CPP/7zip/Archive/Common/InStreamWithCRC.h b/CPP/7zip/Archive/Common/InStreamWithCRC.h
index 31b761e..2a91d76 100644
--- a/CPP/7zip/Archive/Common/InStreamWithCRC.h
+++ b/CPP/7zip/Archive/Common/InStreamWithCRC.h
@@ -1,7 +1,7 @@
1// InStreamWithCRC.h 1// InStreamWithCRC.h
2 2
3#ifndef __IN_STREAM_WITH_CRC_H 3#ifndef ZIP7_INC_IN_STREAM_WITH_CRC_H
4#define __IN_STREAM_WITH_CRC_H 4#define ZIP7_INC_IN_STREAM_WITH_CRC_H
5 5
6#include "../../../../C/7zCrc.h" 6#include "../../../../C/7zCrc.h"
7 7
@@ -9,26 +9,29 @@
9 9
10#include "../../IStream.h" 10#include "../../IStream.h"
11 11
12class CSequentialInStreamWithCRC: 12Z7_CLASS_IMP_NOQIB_2(
13 public ISequentialInStream, 13 CSequentialInStreamWithCRC
14 public CMyUnknownImp 14 , ISequentialInStream
15{ 15 , IStreamGetSize
16public: 16)
17 MY_UNKNOWN_IMP
18
19 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
20private:
21 CMyComPtr<ISequentialInStream> _stream; 17 CMyComPtr<ISequentialInStream> _stream;
22 UInt64 _size; 18 UInt64 _size;
23 UInt32 _crc; 19 UInt32 _crc;
24 bool _wasFinished; 20 bool _wasFinished;
21 UInt64 _fullSize;
25public: 22public:
26 void SetStream(ISequentialInStream *stream) { _stream = stream; } 23
24 CSequentialInStreamWithCRC():
25 _fullSize((UInt64)(Int64)-1)
26 {}
27
28 void SetStream(ISequentialInStream *stream) { _stream = stream; }
29 void SetFullSize(UInt64 fullSize) { _fullSize = fullSize; }
27 void Init() 30 void Init()
28 { 31 {
29 _size = 0; 32 _size = 0;
30 _wasFinished = false;
31 _crc = CRC_INIT_VAL; 33 _crc = CRC_INIT_VAL;
34 _wasFinished = false;
32 } 35 }
33 void ReleaseStream() { _stream.Release(); } 36 void ReleaseStream() { _stream.Release(); }
34 UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } 37 UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); }
@@ -36,22 +39,19 @@ public:
36 bool WasFinished() const { return _wasFinished; } 39 bool WasFinished() const { return _wasFinished; }
37}; 40};
38 41
39class CInStreamWithCRC:
40 public IInStream,
41 public CMyUnknownImp
42{
43public:
44 MY_UNKNOWN_IMP1(IInStream)
45 42
46 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 43Z7_CLASS_IMP_COM_1(
47 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); 44 CInStreamWithCRC,
48private: 45 IInStream
46)
47 Z7_IFACE_COM7_IMP(ISequentialInStream)
48
49 CMyComPtr<IInStream> _stream; 49 CMyComPtr<IInStream> _stream;
50 UInt64 _size; 50 UInt64 _size;
51 UInt32 _crc; 51 UInt32 _crc;
52 // bool _wasFinished; 52 // bool _wasFinished;
53public: 53public:
54 void SetStream(IInStream *stream) { _stream = stream; } 54 void SetStream(IInStream *stream) { _stream = stream; }
55 void Init() 55 void Init()
56 { 56 {
57 _size = 0; 57 _size = 0;
diff --git a/CPP/7zip/Archive/Common/ItemNameUtils.h b/CPP/7zip/Archive/Common/ItemNameUtils.h
index 3f5f4e8..8ab9b61 100644
--- a/CPP/7zip/Archive/Common/ItemNameUtils.h
+++ b/CPP/7zip/Archive/Common/ItemNameUtils.h
@@ -1,7 +1,7 @@
1// Archive/Common/ItemNameUtils.h 1// Archive/Common/ItemNameUtils.h
2 2
3#ifndef __ARCHIVE_ITEM_NAME_UTILS_H 3#ifndef ZIP7_INC_ARCHIVE_ITEM_NAME_UTILS_H
4#define __ARCHIVE_ITEM_NAME_UTILS_H 4#define ZIP7_INC_ARCHIVE_ITEM_NAME_UTILS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/Archive/Common/MultiStream.cpp b/CPP/7zip/Archive/Common/MultiStream.cpp
index 162fc92..5d357af 100644
--- a/CPP/7zip/Archive/Common/MultiStream.cpp
+++ b/CPP/7zip/Archive/Common/MultiStream.cpp
@@ -4,7 +4,7 @@
4 4
5#include "MultiStream.h" 5#include "MultiStream.h"
6 6
7STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) 7Z7_COM7F_IMF(CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize))
8{ 8{
9 if (processedSize) 9 if (processedSize)
10 *processedSize = 0; 10 *processedSize = 0;
@@ -23,10 +23,7 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize)
23 else if (_pos >= m.GlobalOffset + m.Size) 23 else if (_pos >= m.GlobalOffset + m.Size)
24 left = mid + 1; 24 left = mid + 1;
25 else 25 else
26 {
27 _streamIndex = mid;
28 break; 26 break;
29 }
30 mid = (left + right) / 2; 27 mid = (left + right) / 2;
31 } 28 }
32 _streamIndex = mid; 29 _streamIndex = mid;
@@ -36,12 +33,14 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize)
36 UInt64 localPos = _pos - s.GlobalOffset; 33 UInt64 localPos = _pos - s.GlobalOffset;
37 if (localPos != s.LocalPos) 34 if (localPos != s.LocalPos)
38 { 35 {
39 RINOK(s.Stream->Seek((Int64)localPos, STREAM_SEEK_SET, &s.LocalPos)); 36 RINOK(s.Stream->Seek((Int64)localPos, STREAM_SEEK_SET, &s.LocalPos))
40 } 37 }
41 UInt64 rem = s.Size - localPos; 38 {
42 if (size > rem) 39 const UInt64 rem = s.Size - localPos;
43 size = (UInt32)rem; 40 if (size > rem)
44 HRESULT result = s.Stream->Read(data, size, &size); 41 size = (UInt32)rem;
42 }
43 const HRESULT result = s.Stream->Read(data, size, &size);
45 _pos += size; 44 _pos += size;
46 s.LocalPos += size; 45 s.LocalPos += size;
47 if (processedSize) 46 if (processedSize)
@@ -49,7 +48,7 @@ STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize)
49 return result; 48 return result;
50} 49}
51 50
52STDMETHODIMP CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 51Z7_COM7F_IMF(CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
53{ 52{
54 switch (seekOrigin) 53 switch (seekOrigin)
55 { 54 {
@@ -72,6 +71,9 @@ class COutVolumeStream:
72 public ISequentialOutStream, 71 public ISequentialOutStream,
73 public CMyUnknownImp 72 public CMyUnknownImp
74{ 73{
74 Z7_COM_UNKNOWN_IMP_0
75 Z7_IFACE_COM7_IMP(ISequentialOutStream)
76
75 unsigned _volIndex; 77 unsigned _volIndex;
76 UInt64 _volSize; 78 UInt64 _volSize;
77 UInt64 _curPos; 79 UInt64 _curPos;
@@ -80,8 +82,6 @@ class COutVolumeStream:
80 CCRC _crc; 82 CCRC _crc;
81 83
82public: 84public:
83 MY_UNKNOWN_IMP
84
85 CFileItem _file; 85 CFileItem _file;
86 CUpdateOptions _options; 86 CUpdateOptions _options;
87 CMyComPtr<IArchiveUpdateCallback2> VolumeCallback; 87 CMyComPtr<IArchiveUpdateCallback2> VolumeCallback;
@@ -98,7 +98,6 @@ public:
98 } 98 }
99 99
100 HRESULT Flush(); 100 HRESULT Flush();
101 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
102}; 101};
103 102
104HRESULT COutVolumeStream::Flush() 103HRESULT COutVolumeStream::Flush()
@@ -107,7 +106,7 @@ HRESULT COutVolumeStream::Flush()
107 { 106 {
108 _file.UnPackSize = _curPos; 107 _file.UnPackSize = _curPos;
109 _file.FileCRC = _crc.GetDigest(); 108 _file.FileCRC = _crc.GetDigest();
110 RINOK(WriteVolumeHeader(_archive, _file, _options)); 109 RINOK(WriteVolumeHeader(_archive, _file, _options))
111 _archive.Close(); 110 _archive.Close();
112 _volumeStream.Release(); 111 _volumeStream.Release();
113 _file.StartPos += _file.UnPackSize; 112 _file.StartPos += _file.UnPackSize;
@@ -117,7 +116,10 @@ HRESULT COutVolumeStream::Flush()
117*/ 116*/
118 117
119/* 118/*
120STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 119
120#include "../../../Common/Defs.h"
121
122Z7_COM7F_IMF(COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
121{ 123{
122 if (processedSize) 124 if (processedSize)
123 *processedSize = 0; 125 *processedSize = 0;
@@ -126,8 +128,8 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce
126 if (_streamIndex >= Streams.Size()) 128 if (_streamIndex >= Streams.Size())
127 { 129 {
128 CSubStreamInfo subStream; 130 CSubStreamInfo subStream;
129 RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size)); 131 RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size))
130 RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream)); 132 RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream))
131 subStream.Pos = 0; 133 subStream.Pos = 0;
132 Streams.Add(subStream); 134 Streams.Add(subStream);
133 continue; 135 continue;
@@ -142,15 +144,15 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce
142 if (_offsetPos != subStream.Pos) 144 if (_offsetPos != subStream.Pos)
143 { 145 {
144 CMyComPtr<IOutStream> outStream; 146 CMyComPtr<IOutStream> outStream;
145 RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream)); 147 RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream))
146 RINOK(outStream->Seek(_offsetPos, STREAM_SEEK_SET, NULL)); 148 RINOK(outStream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL))
147 subStream.Pos = _offsetPos; 149 subStream.Pos = _offsetPos;
148 } 150 }
149 151
150 UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos); 152 const UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos);
151 UInt32 realProcessed; 153 UInt32 realProcessed;
152 RINOK(subStream.Stream->Write(data, curSize, &realProcessed)); 154 RINOK(subStream.Stream->Write(data, curSize, &realProcessed))
153 data = (void *)((Byte *)data + realProcessed); 155 data = (const void *)((const Byte *)data + realProcessed);
154 size -= realProcessed; 156 size -= realProcessed;
155 subStream.Pos += realProcessed; 157 subStream.Pos += realProcessed;
156 _offsetPos += realProcessed; 158 _offsetPos += realProcessed;
@@ -170,7 +172,7 @@ STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *proce
170 return S_OK; 172 return S_OK;
171} 173}
172 174
173STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 175Z7_COM7F_IMF(COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
174{ 176{
175 switch (seekOrigin) 177 switch (seekOrigin)
176 { 178 {
@@ -181,11 +183,11 @@ STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP
181 } 183 }
182 if (offset < 0) 184 if (offset < 0)
183 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 185 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
184 _absPos = offset; 186 _absPos = (UInt64)offset;
185 _offsetPos = _absPos; 187 _offsetPos = _absPos;
186 _streamIndex = 0; 188 _streamIndex = 0;
187 if (newPosition) 189 if (newPosition)
188 *newPosition = offset; 190 *newPosition = (UInt64)offset;
189 return S_OK; 191 return S_OK;
190} 192}
191*/ 193*/
diff --git a/CPP/7zip/Archive/Common/MultiStream.h b/CPP/7zip/Archive/Common/MultiStream.h
index c10cd45..e3096f5 100644
--- a/CPP/7zip/Archive/Common/MultiStream.h
+++ b/CPP/7zip/Archive/Common/MultiStream.h
@@ -1,20 +1,23 @@
1// MultiStream.h 1// MultiStream.h
2 2
3#ifndef __MULTI_STREAM_H 3#ifndef ZIP7_INC_MULTI_STREAM_H
4#define __MULTI_STREAM_H 4#define ZIP7_INC_MULTI_STREAM_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyVector.h" 7#include "../../../Common/MyVector.h"
8 8
9#include "../../IStream.h" 9#include "../../IStream.h"
10#include "../../Archive/IArchive.h"
10 11
11class CMultiStream: 12Z7_CLASS_IMP_COM_1(
12 public IInStream, 13 CMultiStream
13 public CMyUnknownImp 14 , IInStream
14{ 15)
16 Z7_IFACE_COM7_IMP(ISequentialInStream)
17
18 unsigned _streamIndex;
15 UInt64 _pos; 19 UInt64 _pos;
16 UInt64 _totalLength; 20 UInt64 _totalLength;
17 unsigned _streamIndex;
18 21
19public: 22public:
20 23
@@ -24,12 +27,12 @@ public:
24 UInt64 Size; 27 UInt64 Size;
25 UInt64 GlobalOffset; 28 UInt64 GlobalOffset;
26 UInt64 LocalPos; 29 UInt64 LocalPos;
27
28 CSubStreamInfo(): Size(0), GlobalOffset(0), LocalPos(0) {} 30 CSubStreamInfo(): Size(0), GlobalOffset(0), LocalPos(0) {}
29 }; 31 };
30 32
33 CMyComPtr<IArchiveUpdateCallbackFile> updateCallbackFile;
31 CObjectVector<CSubStreamInfo> Streams; 34 CObjectVector<CSubStreamInfo> Streams;
32 35
33 HRESULT Init() 36 HRESULT Init()
34 { 37 {
35 UInt64 total = 0; 38 UInt64 total = 0;
@@ -37,26 +40,27 @@ public:
37 { 40 {
38 CSubStreamInfo &s = Streams[i]; 41 CSubStreamInfo &s = Streams[i];
39 s.GlobalOffset = total; 42 s.GlobalOffset = total;
40 total += Streams[i].Size; 43 total += s.Size;
41 RINOK(s.Stream->Seek(0, STREAM_SEEK_CUR, &s.LocalPos)); 44 s.LocalPos = 0;
45 {
46 // it was already set to start
47 // RINOK(InStream_GetPos(s.Stream, s.LocalPos));
48 }
42 } 49 }
43 _totalLength = total; 50 _totalLength = total;
44 _pos = 0; 51 _pos = 0;
45 _streamIndex = 0; 52 _streamIndex = 0;
46 return S_OK; 53 return S_OK;
47 } 54 }
48
49 MY_UNKNOWN_IMP1(IInStream)
50
51 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
52 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
53}; 55};
54 56
55/* 57/*
56class COutMultiStream: 58Z7_CLASS_IMP_COM_1(
57 public IOutStream, 59 COutMultiStream,
58 public CMyUnknownImp 60 IOutStream
59{ 61)
62 Z7_IFACE_COM7_IMP(ISequentialOutStream)
63
60 unsigned _streamIndex; // required stream 64 unsigned _streamIndex; // required stream
61 UInt64 _offsetPos; // offset from start of _streamIndex index 65 UInt64 _offsetPos; // offset from start of _streamIndex index
62 UInt64 _absPos; 66 UInt64 _absPos;
@@ -78,11 +82,6 @@ public:
78 _absPos = 0; 82 _absPos = 0;
79 _length = 0; 83 _length = 0;
80 } 84 }
81
82 MY_UNKNOWN_IMP1(IOutStream)
83
84 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
85 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
86}; 85};
87*/ 86*/
88 87
diff --git a/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp b/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp
index f955c22..7dcd44a 100644
--- a/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp
+++ b/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp
@@ -4,7 +4,7 @@
4 4
5#include "OutStreamWithCRC.h" 5#include "OutStreamWithCRC.h"
6 6
7STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) 7Z7_COM7F_IMF(COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize))
8{ 8{
9 HRESULT result = S_OK; 9 HRESULT result = S_OK;
10 if (_stream) 10 if (_stream)
@@ -12,7 +12,7 @@ STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *pro
12 if (_calculate) 12 if (_calculate)
13 _crc = CrcUpdate(_crc, data, size); 13 _crc = CrcUpdate(_crc, data, size);
14 _size += size; 14 _size += size;
15 if (processedSize != NULL) 15 if (processedSize)
16 *processedSize = size; 16 *processedSize = size;
17 return result; 17 return result;
18} 18}
diff --git a/CPP/7zip/Archive/Common/OutStreamWithCRC.h b/CPP/7zip/Archive/Common/OutStreamWithCRC.h
index 09b899b..845146a 100644
--- a/CPP/7zip/Archive/Common/OutStreamWithCRC.h
+++ b/CPP/7zip/Archive/Common/OutStreamWithCRC.h
@@ -1,7 +1,7 @@
1// OutStreamWithCRC.h 1// OutStreamWithCRC.h
2 2
3#ifndef __OUT_STREAM_WITH_CRC_H 3#ifndef ZIP7_INC_OUT_STREAM_WITH_CRC_H
4#define __OUT_STREAM_WITH_CRC_H 4#define ZIP7_INC_OUT_STREAM_WITH_CRC_H
5 5
6#include "../../../../C/7zCrc.h" 6#include "../../../../C/7zCrc.h"
7 7
@@ -9,17 +9,15 @@
9 9
10#include "../../IStream.h" 10#include "../../IStream.h"
11 11
12class COutStreamWithCRC: 12Z7_CLASS_IMP_NOQIB_1(
13 public ISequentialOutStream, 13 COutStreamWithCRC
14 public CMyUnknownImp 14 , ISequentialOutStream
15{ 15)
16 CMyComPtr<ISequentialOutStream> _stream; 16 CMyComPtr<ISequentialOutStream> _stream;
17 UInt64 _size; 17 UInt64 _size;
18 UInt32 _crc; 18 UInt32 _crc;
19 bool _calculate; 19 bool _calculate;
20public: 20public:
21 MY_UNKNOWN_IMP
22 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
23 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 21 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
24 void ReleaseStream() { _stream.Release(); } 22 void ReleaseStream() { _stream.Release(); }
25 void Init(bool calculate = true) 23 void Init(bool calculate = true)
diff --git a/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp b/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp
index ac26edf..57c18ec 100644
--- a/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp
+++ b/CPP/7zip/Archive/Common/OutStreamWithSha1.cpp
@@ -4,7 +4,7 @@
4 4
5#include "OutStreamWithSha1.h" 5#include "OutStreamWithSha1.h"
6 6
7STDMETHODIMP COutStreamWithSha1::Write(const void *data, UInt32 size, UInt32 *processedSize) 7Z7_COM7F_IMF(COutStreamWithSha1::Write(const void *data, UInt32 size, UInt32 *processedSize))
8{ 8{
9 HRESULT result = S_OK; 9 HRESULT result = S_OK;
10 if (_stream) 10 if (_stream)
diff --git a/CPP/7zip/Archive/Common/OutStreamWithSha1.h b/CPP/7zip/Archive/Common/OutStreamWithSha1.h
index 5a7bfef..74bc53c 100644
--- a/CPP/7zip/Archive/Common/OutStreamWithSha1.h
+++ b/CPP/7zip/Archive/Common/OutStreamWithSha1.h
@@ -1,7 +1,7 @@
1// OutStreamWithSha1.h 1// OutStreamWithSha1.h
2 2
3#ifndef __OUT_STREAM_WITH_SHA1_H 3#ifndef ZIP7_INC_OUT_STREAM_WITH_SHA1_H
4#define __OUT_STREAM_WITH_SHA1_H 4#define ZIP7_INC_OUT_STREAM_WITH_SHA1_H
5 5
6#include "../../../../C/Sha1.h" 6#include "../../../../C/Sha1.h"
7 7
@@ -10,23 +10,19 @@
10 10
11#include "../../IStream.h" 11#include "../../IStream.h"
12 12
13class COutStreamWithSha1: 13Z7_CLASS_IMP_NOQIB_1(
14 public ISequentialOutStream, 14 COutStreamWithSha1
15 public CMyUnknownImp 15 , ISequentialOutStream
16{ 16)
17 CMyComPtr<ISequentialOutStream> _stream; 17 CMyComPtr<ISequentialOutStream> _stream;
18 UInt64 _size; 18 UInt64 _size;
19 // CSha1 _sha; 19 // CSha1 _sha;
20 bool _calculate; 20 bool _calculate;
21 CAlignedBuffer _sha; 21 CAlignedBuffer1 _sha;
22 22
23 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; } 23 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; }
24public: 24public:
25 MY_UNKNOWN_IMP
26
27 COutStreamWithSha1(): _sha(sizeof(CSha1)) {} 25 COutStreamWithSha1(): _sha(sizeof(CSha1)) {}
28
29 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
30 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 26 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
31 void ReleaseStream() { _stream.Release(); } 27 void ReleaseStream() { _stream.Release(); }
32 void Init(bool calculate = true) 28 void Init(bool calculate = true)
diff --git a/CPP/7zip/Archive/Common/ParseProperties.h b/CPP/7zip/Archive/Common/ParseProperties.h
index 1038a8c..4ec2e48 100644
--- a/CPP/7zip/Archive/Common/ParseProperties.h
+++ b/CPP/7zip/Archive/Common/ParseProperties.h
@@ -1,6 +1,6 @@
1// ParseProperties.h 1// ParseProperties.h
2 2
3#ifndef __PARSE_PROPERTIES_H 3#ifndef ZIP7_INC_PARSE_PROPERTIES_H
4#define __PARSE_PROPERTIES_H 4#define ZIP7_INC_PARSE_PROPERTIES_H
5 5
6#endif 6#endif
diff --git a/CPP/7zip/Archive/Common/StdAfx.h b/CPP/7zip/Archive/Common/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Common/StdAfx.h
+++ b/CPP/7zip/Archive/Common/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/CpioHandler.cpp b/CPP/7zip/Archive/CpioHandler.cpp
index b7e7564..872cea7 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;
44 44
45static const unsigned k_RecordSize_Max = k_HexRecord_Size; 45static const unsigned k_RecordSize_Max = k_HexRecord_Size;
46 46
47 /*
48 struct CBinRecord
49 {
50 unsigned short c_magic;
51 short c_dev;
52 unsigned short c_ino;
53 unsigned short c_mode;
54 unsigned short c_uid;
55 unsigned short c_gid;
56 unsigned short c_nlink;
57 short c_rdev;
58 unsigned short c_mtimes[2];
59 unsigned short c_namesize;
60 unsigned short c_filesizes[2];
61 };
62
63 struct CHexRecord
64 {
65 char Magic[6];
66 char inode[8];
67 char Mode[8];
68 char UID[8];
69 char GID[8];
70 char nlink[8];
71 char mtime[8];
72 char Size[8]; // must be 0 for FIFOs and directories
73 char DevMajor[8];
74 char DevMinor[8];
75 char RDevMajor[8]; //only valid for chr and blk special files
76 char RDevMinor[8]; //only valid for chr and blk special files
77 char NameSize[8]; // count includes terminating NUL in pathname
78 char ChkSum[8]; // 0 for "new" portable format; for CRC format the sum of all the bytes in the file
79 };
80*/
81
82enum EType 47enum EType
83{ 48{
84 k_Type_BinLe, 49 k_Type_BinLe,
@@ -99,114 +64,159 @@ static const char * const k_Types[] =
99 64
100struct CItem 65struct CItem
101{ 66{
102 AString Name;
103 UInt32 inode; 67 UInt32 inode;
68 unsigned MainIndex_ForInode;
104 UInt32 Mode; 69 UInt32 Mode;
105 UInt32 UID;
106 UInt32 GID;
107 UInt64 Size;
108 UInt32 MTime; 70 UInt32 MTime;
109
110 UInt32 NumLinks;
111 UInt32 DevMajor; 71 UInt32 DevMajor;
112 UInt32 DevMinor; 72 UInt32 DevMinor;
73 UInt64 Size;
74 AString Name;
75 UInt32 NumLinks;
76 UInt32 UID;
77 UInt32 GID;
113 UInt32 RDevMajor; 78 UInt32 RDevMajor;
114 UInt32 RDevMinor; 79 UInt32 RDevMinor;
115 UInt32 ChkSum; 80 UInt32 ChkSum;
116 81
117 UInt32 Align; 82 UInt32 AlignMask;
118 EType Type; 83 EType Type;
119 84
120 UInt32 HeaderSize; 85 UInt32 HeaderSize;
121 UInt64 HeaderPos; 86 UInt64 HeaderPos;
122 87
88 CByteBuffer Data; // for symlink
89
90
91 UInt32 GetAlignedSize(UInt32 size) const
92 {
93 return (size + AlignMask) & ~(UInt32)AlignMask;
94 }
95
96 UInt64 GetPackSize() const
97 {
98 const UInt64 alignMask64 = AlignMask;
99 return (Size + alignMask64) & ~(UInt64)alignMask64;
100 }
101
102 bool IsSame_inode_Dev(const CItem &item) const
103 {
104 return inode == item.inode
105 && DevMajor == item.DevMajor
106 && DevMinor == item.DevMinor;
107 }
108
123 bool IsBin() const { return Type == k_Type_BinLe || Type == k_Type_BinBe; } 109 bool IsBin() const { return Type == k_Type_BinLe || Type == k_Type_BinBe; }
124 bool IsCrcFormat() const { return Type == k_Type_HexCrc; } 110 bool IsCrcFormat() const { return Type == k_Type_HexCrc; }
125 bool IsDir() const { return MY_LIN_S_ISDIR(Mode); } 111 bool IsDir() const { return MY_LIN_S_ISDIR(Mode); }
112 bool Is_SymLink() const { return MY_LIN_S_ISLNK(Mode); }
126 bool IsTrailer() const { return strcmp(Name, kName_TRAILER) == 0; } 113 bool IsTrailer() const { return strcmp(Name, kName_TRAILER) == 0; }
127 UInt64 GetDataPosition() const { return HeaderPos + HeaderSize; } 114 UInt64 GetDataPosition() const { return HeaderPos + HeaderSize; }
128}; 115};
129 116
117
130enum EErrorType 118enum EErrorType
131{ 119{
132 k_ErrorType_OK, 120 k_ErrorType_OK,
121 k_ErrorType_BadSignature,
133 k_ErrorType_Corrupted, 122 k_ErrorType_Corrupted,
134 k_ErrorType_UnexpectedEnd 123 k_ErrorType_UnexpectedEnd
135}; 124};
136 125
126
137struct CInArchive 127struct CInArchive
138{ 128{
129 EErrorType errorType;
139 ISequentialInStream *Stream; 130 ISequentialInStream *Stream;
140 UInt64 Processed; 131 UInt64 Processed;
132 CItem item;
141 133
142 HRESULT Read(void *data, size_t *size); 134 HRESULT Read(void *data, size_t *size);
143 HRESULT GetNextItem(CItem &item, EErrorType &errorType); 135 HRESULT GetNextItem();
144}; 136};
145 137
146HRESULT CInArchive::Read(void *data, size_t *size) 138HRESULT CInArchive::Read(void *data, size_t *size)
147{ 139{
148 HRESULT res = ReadStream(Stream, data, size); 140 const HRESULT res = ReadStream(Stream, data, size);
149 Processed += *size; 141 Processed += *size;
150 return res; 142 return res;
151} 143}
152 144
153static bool ReadHex(const Byte *p, UInt32 &resVal) 145
146static bool CheckOctRecord(const Byte *p)
147{
148 for (unsigned i = 6; i < k_OctRecord_Size; i++)
149 {
150 const Byte c = p[i];
151 if (c < '0' || c > '7')
152 return false;
153 }
154 return true;
155}
156
157static bool CheckHexRecord(const Byte *p)
158{
159 for (unsigned i = 6; i < k_HexRecord_Size; i++)
160 {
161 const Byte c = p[i];
162 if ((c < '0' || c > '9') &&
163 (c < 'A' || c > 'F') &&
164 (c < 'a' || c > 'f'))
165 return false;
166 }
167 return true;
168}
169
170static UInt32 ReadHex(const Byte *p)
154{ 171{
155 char sz[16]; 172 char sz[16];
156 memcpy(sz, p, 8); 173 memcpy(sz, p, 8);
157 sz[8] = 0; 174 sz[8] = 0;
158 const char *end; 175 const char *end;
159 resVal = ConvertHexStringToUInt32(sz, &end); 176 return ConvertHexStringToUInt32(sz, &end);
160 return (unsigned)(end - sz) == 8;
161} 177}
162 178
163static bool ReadOct6(const Byte *p, UInt32 &resVal) 179static UInt32 ReadOct6(const Byte *p)
164{ 180{
165 char sz[16]; 181 char sz[16];
166 memcpy(sz, p, 6); 182 memcpy(sz, p, 6);
167 sz[6] = 0; 183 sz[6] = 0;
168 const char *end; 184 const char *end;
169 resVal = ConvertOctStringToUInt32(sz, &end); 185 return ConvertOctStringToUInt32(sz, &end);
170 return (unsigned)(end - sz) == 6;
171} 186}
172 187
173static bool ReadOct11(const Byte *p, UInt64 &resVal) 188static UInt64 ReadOct11(const Byte *p)
174{ 189{
175 char sz[16]; 190 char sz[16];
176 memcpy(sz, p, 11); 191 memcpy(sz, p, 11);
177 sz[11] = 0; 192 sz[11] = 0;
178 const char *end; 193 const char *end;
179 resVal = ConvertOctStringToUInt64(sz, &end); 194 return ConvertOctStringToUInt64(sz, &end);
180 return (unsigned)(end - sz) == 11;
181} 195}
182 196
183 197
184#define READ_HEX(y) { if (!ReadHex(p2, y)) return S_OK; p2 += 8; } 198#define READ_HEX( y, dest) dest = ReadHex (p + 6 + (y) * 8);
185#define READ_OCT_6(y) { if (!ReadOct6(p2, y)) return S_OK; p2 += 6; } 199#define READ_OCT_6( y, dest) dest = ReadOct6 (p + 6 + (y));
186#define READ_OCT_11(y) { if (!ReadOct11(p2, y)) return S_OK; p2 += 11; } 200#define READ_OCT_11( y, dest) dest = ReadOct11(p + 6 + (y));
187
188static UInt32 GetAlignedSize(UInt32 size, UInt32 align)
189{
190 while ((size & (align - 1)) != 0)
191 size++;
192 return size;
193}
194
195static UInt16 Get16(const Byte *p, bool be) { if (be) return GetBe16(p); return GetUi16(p); }
196static UInt32 Get32(const Byte *p, bool be) { return ((UInt32)Get16(p, be) << 16) + Get16(p + 2, be); }
197 201
198#define G16(offs, v) v = Get16(p + (offs), be) 202#define Get32spec(p) (((UInt32)GetUi16(p) << 16) + GetUi16(p + 2))
199#define G32(offs, v) v = Get32(p + (offs), be) 203#define G16(offs, v) v = GetUi16(p + (offs))
204#define G32(offs, v) v = Get32spec(p + (offs))
200 205
201static const unsigned kNameSizeMax = 1 << 12; 206static const unsigned kNameSizeMax = 1 << 12;
202 207
208
203API_FUNC_static_IsArc IsArc_Cpio(const Byte *p, size_t size) 209API_FUNC_static_IsArc IsArc_Cpio(const Byte *p, size_t size)
204{ 210{
205 if (size < k_BinRecord_Size) 211 if (size < k_BinRecord_Size)
206 return k_IsArc_Res_NEED_MORE; 212 return k_IsArc_Res_NEED_MORE;
207 213
214 UInt32 namePos;
208 UInt32 nameSize; 215 UInt32 nameSize;
209 UInt32 numLinks; 216 UInt32 mode;
217 UInt32 rDevMinor;
218 UInt32 rDevMajor = 0;
219
210 if (p[0] == '0') 220 if (p[0] == '0')
211 { 221 {
212 if (p[1] != '7' || 222 if (p[1] != '7' ||
@@ -214,94 +224,120 @@ API_FUNC_static_IsArc IsArc_Cpio(const Byte *p, size_t size)
214 p[3] != '7' || 224 p[3] != '7' ||
215 p[4] != '0') 225 p[4] != '0')
216 return k_IsArc_Res_NO; 226 return k_IsArc_Res_NO;
217 if (p[5] == '7') 227 if (p[5] == kMagicOct)
218 { 228 {
219 if (size < k_OctRecord_Size) 229 if (size < k_OctRecord_Size)
220 return k_IsArc_Res_NEED_MORE; 230 return k_IsArc_Res_NEED_MORE;
221 for (unsigned i = 6; i < k_OctRecord_Size; i++) 231 if (!CheckOctRecord(p))
222 { 232 return k_IsArc_Res_NO;
223 char c = p[i]; 233 READ_OCT_6 (2 * 6, mode)
224 if (c < '0' || c > '7') 234 READ_OCT_6 (6 * 6, rDevMinor)
225 return k_IsArc_Res_NO; 235 READ_OCT_6 (7 * 6 + 11, nameSize)
226 } 236 namePos = k_OctRecord_Size;
227 ReadOct6(p + 6 * 6, numLinks);
228 ReadOct6(p + 8 * 6 + 11, nameSize);
229 } 237 }
230 else if (p[5] == '1' || p[5] == '2') 238 else if (p[5] == kMagicHex || p[5] == kMagicHexCrc)
231 { 239 {
232 if (size < k_HexRecord_Size) 240 if (size < k_HexRecord_Size)
233 return k_IsArc_Res_NEED_MORE; 241 return k_IsArc_Res_NEED_MORE;
234 for (unsigned i = 6; i < k_HexRecord_Size; i++) 242 if (!CheckHexRecord(p))
235 { 243 return k_IsArc_Res_NO;
236 char c = p[i]; 244 READ_HEX (1, mode)
237 if ((c < '0' || c > '9') && 245 READ_HEX (9, rDevMajor)
238 (c < 'A' || c > 'F') && 246 READ_HEX (10, rDevMinor)
239 (c < 'a' || c > 'f')) 247 READ_HEX (11, nameSize)
240 return k_IsArc_Res_NO; 248 namePos = k_HexRecord_Size;
241 }
242 ReadHex(p + 6 + 4 * 8, numLinks);
243 ReadHex(p + 6 + 11 * 8, nameSize);
244 } 249 }
245 else 250 else
246 return k_IsArc_Res_NO; 251 return k_IsArc_Res_NO;
247 } 252 }
248 else 253 else
249 { 254 {
250 UInt32 rDevMinor;
251 if (p[0] == kMagicBin0 && p[1] == kMagicBin1) 255 if (p[0] == kMagicBin0 && p[1] == kMagicBin1)
252 { 256 {
253 numLinks = GetUi16(p + 12); 257 mode = GetUi16(p + 6);
254 rDevMinor = GetUi16(p + 14); 258 rDevMinor = GetUi16(p + 14);
255 nameSize = GetUi16(p + 20); 259 nameSize = GetUi16(p + 20);
256 } 260 }
257 else if (p[0] == kMagicBin1 && p[1] == kMagicBin0) 261 else if (p[0] == kMagicBin1 && p[1] == kMagicBin0)
258 { 262 {
259 numLinks = GetBe16(p + 12); 263 mode = GetBe16(p + 6);
260 rDevMinor = GetBe16(p + 14); 264 rDevMinor = GetBe16(p + 14);
261 nameSize = GetBe16(p + 20); 265 nameSize = GetBe16(p + 20);
262 } 266 }
263 else 267 else
264 return k_IsArc_Res_NO; 268 return k_IsArc_Res_NO;
269 namePos = k_BinRecord_Size;
270 }
265 271
266 if (rDevMinor != 0) 272 if (mode >= (1 << 16))
267 return k_IsArc_Res_NO; 273 return k_IsArc_Res_NO;
268 if (nameSize > (1 << 8)) 274
275 if (rDevMajor != 0 ||
276 rDevMinor != 0)
277 {
278 if (!MY_LIN_S_ISCHR(mode) &&
279 !MY_LIN_S_ISBLK(mode))
269 return k_IsArc_Res_NO; 280 return k_IsArc_Res_NO;
270 } 281 }
271 // 20.03: some cpio files have (numLinks == 0). 282
272 // if (numLinks == 0) return k_IsArc_Res_NO; 283 // nameSize must include the null byte
273 if (numLinks >= (1 << 10))
274 return k_IsArc_Res_NO;
275 if (nameSize == 0 || nameSize > kNameSizeMax) 284 if (nameSize == 0 || nameSize > kNameSizeMax)
276 return k_IsArc_Res_NO; 285 return k_IsArc_Res_NO;
286 {
287 unsigned lim = namePos + nameSize - 1;
288 if (lim >= size)
289 lim = (unsigned)size;
290 else if (p[lim] != 0)
291 return k_IsArc_Res_NO;
292 for (unsigned i = namePos; i < lim; i++)
293 if (p[i] == 0)
294 return k_IsArc_Res_NO;
295 }
296
277 return k_IsArc_Res_YES; 297 return k_IsArc_Res_YES;
278} 298}
279} 299}
280 300
301
281#define READ_STREAM(_dest_, _size_) \ 302#define READ_STREAM(_dest_, _size_) \
282 { size_t processed = (_size_); RINOK(Read(_dest_, &processed)); \ 303 { size_t processed = (_size_); RINOK(Read(_dest_, &processed)); \
283if (processed != (_size_)) { errorType = k_ErrorType_UnexpectedEnd; return S_OK; } } 304if (processed != (_size_)) { errorType = k_ErrorType_UnexpectedEnd; return S_OK; } }
284 305
285HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType) 306HRESULT CInArchive::GetNextItem()
286{ 307{
287 errorType = k_ErrorType_Corrupted; 308 errorType = k_ErrorType_BadSignature;
288 309
289 Byte p[k_RecordSize_Max]; 310 Byte p[k_RecordSize_Max];
290 311
291 READ_STREAM(p, k_BinRecord_Size) 312 READ_STREAM(p, k_BinRecord_Size)
292 313
293 UInt32 nameSize; 314 UInt32 nameSize;
315 UInt32 namePos;
316
317 /* we try to reduce probability of false detection,
318 so we check some fields for unuxpected values */
294 319
295 if (p[0] != '0') 320 if (p[0] != '0')
296 { 321 {
297 bool be; 322 if (p[0] == kMagicBin0 && p[1] == kMagicBin1) { item.Type = k_Type_BinLe; }
298 if (p[0] == kMagicBin0 && p[1] == kMagicBin1) { be = false; item.Type = k_Type_BinLe; } 323 else if (p[0] == kMagicBin1 && p[1] == kMagicBin0)
299 else if (p[0] == kMagicBin1 && p[1] == kMagicBin0) { be = true; item.Type = k_Type_BinBe; } 324 {
300 else return S_FALSE; 325 for (unsigned i = 2; i < k_BinRecord_Size; i += 2)
326 {
327 const Byte b = p[i];
328 p[i] = p[i + 1];
329 p[i + 1] = b;
330 }
331 item.Type = k_Type_BinBe;
332 }
333 else
334 return S_OK;
335
336 errorType = k_ErrorType_Corrupted;
301 337
302 item.Align = 2; 338 item.AlignMask = 2 - 1;
303 item.DevMajor = 0; 339 item.DevMajor = 0;
304 item.RDevMajor =0; 340 item.RDevMajor = 0;
305 item.ChkSum = 0; 341 item.ChkSum = 0;
306 342
307 G16(2, item.DevMinor); 343 G16(2, item.DevMinor);
@@ -315,13 +351,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType)
315 G16(20, nameSize); 351 G16(20, nameSize);
316 G32(22, item.Size); 352 G32(22, item.Size);
317 353
318 /* 354 namePos = k_BinRecord_Size;
319 if (item.RDevMinor != 0)
320 return S_FALSE;
321 */
322
323 item.HeaderSize = GetAlignedSize(nameSize + k_BinRecord_Size, item.Align);
324 nameSize = item.HeaderSize - k_BinRecord_Size;
325 } 355 }
326 else 356 else
327 { 357 {
@@ -329,104 +359,131 @@ HRESULT CInArchive::GetNextItem(CItem &item, EErrorType &errorType)
329 p[2] != '0' || 359 p[2] != '0' ||
330 p[3] != '7' || 360 p[3] != '7' ||
331 p[4] != '0') 361 p[4] != '0')
332 return S_FALSE; 362 return S_OK;
333 if (p[5] == kMagicOct) 363 if (p[5] == kMagicOct)
334 { 364 {
365 errorType = k_ErrorType_Corrupted;
366
335 item.Type = k_Type_Oct; 367 item.Type = k_Type_Oct;
336 READ_STREAM(p + k_BinRecord_Size, k_OctRecord_Size - k_BinRecord_Size) 368 READ_STREAM(p + k_BinRecord_Size, k_OctRecord_Size - k_BinRecord_Size)
337 item.Align = 1; 369 item.AlignMask = 1 - 1;
338 item.DevMajor = 0; 370 item.DevMajor = 0;
339 item.RDevMajor = 0; 371 item.RDevMajor = 0;
372 item.ChkSum = 0;
373
374 if (!CheckOctRecord(p))
375 return S_OK;
340 376
341 const Byte *p2 = p + 6; 377 READ_OCT_6 (0, item.DevMinor)
342 READ_OCT_6(item.DevMinor); 378 READ_OCT_6 (1 * 6, item.inode)
343 READ_OCT_6(item.inode); 379 READ_OCT_6 (2 * 6, item.Mode)
344 READ_OCT_6(item.Mode); 380 READ_OCT_6 (3 * 6, item.UID)
345 READ_OCT_6(item.UID); 381 READ_OCT_6 (4 * 6, item.GID)
346 READ_OCT_6(item.GID); 382 READ_OCT_6 (5 * 6, item.NumLinks)
347 READ_OCT_6(item.NumLinks); 383 READ_OCT_6 (6 * 6, item.RDevMinor)
348 READ_OCT_6(item.RDevMinor);
349 { 384 {
350 UInt64 mTime64; 385 UInt64 mTime64;
351 READ_OCT_11(mTime64); 386 READ_OCT_11 (7 * 6, mTime64)
352 item.MTime = 0; 387 item.MTime = 0;
353 if (mTime64 < (UInt32)(Int32)-1) 388 if (mTime64 <= (UInt32)(Int32)-1)
354 item.MTime = (UInt32)mTime64; 389 item.MTime = (UInt32)mTime64;
355 } 390 }
356 READ_OCT_6(nameSize); 391 READ_OCT_6 (7 * 6 + 11, nameSize)
357 READ_OCT_11(item.Size); // ????? 392 READ_OCT_11 (8 * 6 + 11, item.Size) // ?????
358 item.HeaderSize = GetAlignedSize(nameSize + k_OctRecord_Size, item.Align); 393
359 nameSize = item.HeaderSize - k_OctRecord_Size; 394 namePos = k_OctRecord_Size;
360 } 395 }
361 else 396 else
362 { 397 {
363 if (p[5] == kMagicHex) 398 if (p[5] == kMagicHex) item.Type = k_Type_Hex;
364 item.Type = k_Type_Hex; 399 else if (p[5] == kMagicHexCrc) item.Type = k_Type_HexCrc;
365 else if (p[5] == kMagicHexCrc) 400 else return S_OK;
366 item.Type = k_Type_HexCrc; 401
367 else 402 errorType = k_ErrorType_Corrupted;
368 return S_FALSE;
369 403
370 READ_STREAM(p + k_BinRecord_Size, k_HexRecord_Size - k_BinRecord_Size) 404 READ_STREAM(p + k_BinRecord_Size, k_HexRecord_Size - k_BinRecord_Size)
371 405
372 item.Align = 4; 406 if (!CheckHexRecord(p))
407 return S_OK;
373 408
374 const Byte *p2 = p + 6; 409 item.AlignMask = 4 - 1;
375 READ_HEX(item.inode); 410 READ_HEX (0, item.inode)
376 READ_HEX(item.Mode); 411 READ_HEX (1, item.Mode)
377 READ_HEX(item.UID); 412 READ_HEX (2, item.UID)
378 READ_HEX(item.GID); 413 READ_HEX (3, item.GID)
379 READ_HEX(item.NumLinks); 414 READ_HEX (4, item.NumLinks)
380 READ_HEX(item.MTime); 415 READ_HEX (5, item.MTime)
381 { 416 READ_HEX (6, item.Size)
382 UInt32 size32; 417 READ_HEX (7, item.DevMajor)
383 READ_HEX(size32); 418 READ_HEX (8, item.DevMinor)
384 item.Size = size32; 419 READ_HEX (9, item.RDevMajor)
385 } 420 READ_HEX (10, item.RDevMinor)
386 READ_HEX(item.DevMajor); 421 READ_HEX (11, nameSize)
387 READ_HEX(item.DevMinor); 422 READ_HEX (12, item.ChkSum)
388 READ_HEX(item.RDevMajor); 423
389 READ_HEX(item.RDevMinor); 424 if (item.Type == k_Type_Hex && item.ChkSum != 0)
390 READ_HEX(nameSize);
391 READ_HEX(item.ChkSum);
392 if (nameSize >= kNameSizeMax)
393 return S_OK; 425 return S_OK;
394 item.HeaderSize = GetAlignedSize(nameSize + k_HexRecord_Size, item.Align); 426
395 nameSize = item.HeaderSize - k_HexRecord_Size; 427 namePos = k_HexRecord_Size;
396 } 428 }
397 } 429 }
398 if (nameSize > kNameSizeMax) 430
399 return S_FALSE; 431 if (item.Mode >= (1 << 16))
400 if (nameSize == 0 || nameSize >= kNameSizeMax)
401 return S_OK; 432 return S_OK;
402 char *s = item.Name.GetBuf(nameSize); 433
403 size_t processedSize = nameSize; 434 if (item.RDevMinor != 0 ||
404 RINOK(Read(s, &processedSize)); 435 item.RDevMajor != 0)
405 item.Name.ReleaseBuf_CalcLen(nameSize); 436 {
406 if (processedSize != nameSize) 437 if (!MY_LIN_S_ISCHR(item.Mode) &&
438 !MY_LIN_S_ISBLK(item.Mode))
439 return S_OK;
440 }
441
442 // Size must be 0 for FIFOs and directories
443 if (item.IsDir() || MY_LIN_S_ISFIFO(item.Mode))
444 if (item.Size != 0)
445 return S_OK;
446
447 // nameSize must include the null byte
448 if (nameSize == 0 || nameSize > kNameSizeMax)
449 return S_OK;
450 item.HeaderSize = item.GetAlignedSize(namePos + nameSize);
451 const UInt32 rem = item.HeaderSize - namePos;
452 char *s = item.Name.GetBuf(rem);
453 size_t processedSize = rem;
454 RINOK(Read(s, &processedSize))
455 if (processedSize != rem)
407 { 456 {
457 item.Name.ReleaseBuf_SetEnd(0);
408 errorType = k_ErrorType_UnexpectedEnd; 458 errorType = k_ErrorType_UnexpectedEnd;
409 return S_OK; 459 return S_OK;
410 } 460 }
461 bool pad_error = false;
462 for (size_t i = nameSize; i < processedSize; i++)
463 if (s[i] != 0)
464 pad_error = true;
465 item.Name.ReleaseBuf_CalcLen(nameSize);
466 if (item.Name.Len() + 1 != nameSize || pad_error)
467 return S_OK;
411 errorType = k_ErrorType_OK; 468 errorType = k_ErrorType_OK;
412 return S_OK; 469 return S_OK;
413} 470}
414 471
415class CHandler: 472
416 public IInArchive, 473
417 public IInArchiveGetStream, 474Z7_CLASS_IMP_CHandler_IInArchive_1(
418 public CMyUnknownImp 475 IInArchiveGetStream
419{ 476)
420 CObjectVector<CItem> _items; 477 CObjectVector<CItem> _items;
421 CMyComPtr<IInStream> _stream; 478 CMyComPtr<IInStream> _stream;
422 UInt64 _phySize; 479 UInt64 _phySize;
423 EType _Type; 480 EType _type;
424 EErrorType _error; 481 EErrorType _error;
425 bool _isArc; 482 bool _isArc;
426public: 483 bool _moreThanOneHardLinks_Error;
427 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) 484 bool _numLinks_Error;
428 INTERFACE_IInArchive(;) 485 bool _pad_Error;
429 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); 486 bool _symLink_Error;
430}; 487};
431 488
432static const Byte kArcProps[] = 489static const Byte kArcProps[] =
@@ -439,22 +496,35 @@ static const Byte kProps[] =
439 kpidPath, 496 kpidPath,
440 kpidIsDir, 497 kpidIsDir,
441 kpidSize, 498 kpidSize,
499 kpidPackSize,
442 kpidMTime, 500 kpidMTime,
443 kpidPosixAttrib, 501 kpidPosixAttrib,
444 kpidLinks 502 kpidLinks,
503 kpidINode,
504 kpidUserId,
505 kpidGroupId,
506 kpidDevMajor,
507 kpidDevMinor,
508 kpidDeviceMajor,
509 kpidDeviceMinor,
510 kpidChecksum,
511 kpidSymLink,
512 kpidStreamId, // for debug
513 kpidOffset
445}; 514};
446 515
447IMP_IInArchive_Props 516IMP_IInArchive_Props
448IMP_IInArchive_ArcProps 517IMP_IInArchive_ArcProps
449 518
450STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 519Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
451{ 520{
452 COM_TRY_BEGIN 521 COM_TRY_BEGIN
453 NCOM::CPropVariant prop; 522 NCOM::CPropVariant prop;
454 switch (propID) 523 switch (propID)
455 { 524 {
456 case kpidSubType: prop = k_Types[(unsigned)_Type]; break; 525 case kpidSubType: prop = k_Types[(unsigned)_type]; break;
457 case kpidPhySize: prop = _phySize; break; 526 case kpidPhySize: prop = _phySize; break;
527 case kpidINode: prop = true; break;
458 case kpidErrorFlags: 528 case kpidErrorFlags:
459 { 529 {
460 UInt32 v = 0; 530 UInt32 v = 0;
@@ -463,14 +533,28 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
463 switch (_error) 533 switch (_error)
464 { 534 {
465 case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break; 535 case k_ErrorType_UnexpectedEnd: v |= kpv_ErrorFlags_UnexpectedEnd; break;
466 case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break; 536 case k_ErrorType_Corrupted: v |= kpv_ErrorFlags_HeadersError; break;
467 case k_ErrorType_OK: 537 case k_ErrorType_OK:
468 default: 538 case k_ErrorType_BadSignature:
539 // default:
469 break; 540 break;
470 } 541 }
471 prop = v; 542 prop = v;
472 break; 543 break;
473 } 544 }
545 case kpidWarningFlags:
546 {
547 UInt32 v = 0;
548 if (_moreThanOneHardLinks_Error)
549 v |= kpv_ErrorFlags_UnsupportedFeature; // kpv_ErrorFlags_HeadersError
550 if (_numLinks_Error
551 || _pad_Error
552 || _symLink_Error)
553 v |= kpv_ErrorFlags_HeadersError;
554 if (v != 0)
555 prop = v;
556 break;
557 }
474 } 558 }
475 prop.Detach(value); 559 prop.Detach(value);
476 return S_OK; 560 return S_OK;
@@ -478,22 +562,43 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
478} 562}
479 563
480 564
481STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 565static int CompareItems(const unsigned *p1, const unsigned *p2, void *param)
566{
567 const CObjectVector<CItem> &items = *(const CObjectVector<CItem> *)param;
568 const unsigned index1 = *p1;
569 const unsigned index2 = *p2;
570 const CItem &i1 = items[index1];
571 const CItem &i2 = items[index2];
572 if (i1.DevMajor < i2.DevMajor) return -1;
573 if (i1.DevMajor > i2.DevMajor) return 1;
574 if (i1.DevMinor < i2.DevMinor) return -1;
575 if (i1.DevMinor > i2.DevMinor) return 1;
576 if (i1.inode < i2.inode) return -1;
577 if (i1.inode > i2.inode) return 1;
578 if (i1.IsDir())
579 {
580 if (!i2.IsDir())
581 return -1;
582 }
583 else if (i2.IsDir())
584 return 1;
585 return MyCompare(index1, index2);
586}
587
588
589Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
482{ 590{
483 COM_TRY_BEGIN 591 COM_TRY_BEGIN
484 { 592 {
485 Close(); 593 Close();
486 594
487 UInt64 endPos = 0; 595 UInt64 endPos;
488 596 RINOK(InStream_AtBegin_GetSize(stream, endPos))
489 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos));
490 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
491 if (callback) 597 if (callback)
492 { 598 {
493 RINOK(callback->SetTotal(NULL, &endPos)); 599 RINOK(callback->SetTotal(NULL, &endPos))
494 } 600 }
495 601
496 _items.Clear();
497 CInArchive arc; 602 CInArchive arc;
498 603
499 arc.Stream = stream; 604 arc.Stream = stream;
@@ -501,70 +606,98 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
501 606
502 for (;;) 607 for (;;)
503 { 608 {
504 CItem item; 609 CItem &item = arc.item;
505 item.HeaderPos = arc.Processed; 610 item.HeaderPos = arc.Processed;
506 HRESULT result = arc.GetNextItem(item, _error); 611
507 if (result == S_FALSE) 612 RINOK(arc.GetNextItem())
508 return S_FALSE; 613
509 if (result != S_OK) 614 _error = arc.errorType;
510 return S_FALSE; 615
511 if (_error != k_ErrorType_OK) 616 if (_error != k_ErrorType_OK)
512 { 617 {
513 if (_error == k_ErrorType_Corrupted) 618 if (_error == k_ErrorType_BadSignature ||
619 _error == k_ErrorType_Corrupted)
514 arc.Processed = item.HeaderPos; 620 arc.Processed = item.HeaderPos;
515 break; 621 break;
516 } 622 }
623
517 if (_items.IsEmpty()) 624 if (_items.IsEmpty())
518 _Type = item.Type; 625 _type = item.Type;
519 else if (_items.Back().Type != item.Type) 626 else if (_items.Back().Type != item.Type)
520 { 627 {
521 _error = k_ErrorType_Corrupted; 628 _error = k_ErrorType_Corrupted;
522 arc.Processed = item.HeaderPos; 629 arc.Processed = item.HeaderPos;
523 break; 630 break;
524 } 631 }
632
525 if (item.IsTrailer()) 633 if (item.IsTrailer())
526 break; 634 break;
527 635
636 item.MainIndex_ForInode = _items.Size();
528 _items.Add(item); 637 _items.Add(item);
529 638
639 const UInt64 dataSize = item.GetPackSize();
640 arc.Processed += dataSize;
641 if (arc.Processed > endPos)
530 { 642 {
531 // archive.SkipDataRecords(item.Size, item.Align); 643 _error = k_ErrorType_UnexpectedEnd;
532 UInt64 dataSize = item.Size; 644 break;
533 UInt32 align = item.Align; 645 }
534 while ((dataSize & (align - 1)) != 0) 646
535 dataSize++; 647 if (item.Is_SymLink() && dataSize <= (1 << 12) && item.Size != 0)
536 648 {
537 // _error = k_ErrorType_UnexpectedEnd; break; 649 size_t cur = (size_t)dataSize;
538 650 CByteBuffer buf;
539 arc.Processed += dataSize; 651 buf.Alloc(cur);
540 if (arc.Processed > endPos) 652 RINOK(ReadStream(stream, buf, &cur))
653 if (cur != dataSize)
541 { 654 {
542 _error = k_ErrorType_UnexpectedEnd; 655 _error = k_ErrorType_UnexpectedEnd;
543 break; 656 break;
544 } 657 }
545 658 size_t i;
546 UInt64 newPostion; 659
547 RINOK(stream->Seek(dataSize, STREAM_SEEK_CUR, &newPostion)); 660 for (i = (size_t)item.Size; i < dataSize; i++)
548 if (arc.Processed != newPostion) 661 if (buf[i] != 0)
662 break;
663 if (i != dataSize)
664 _pad_Error = true;
665
666 for (i = 0; i < (size_t)item.Size; i++)
667 if (buf[i] == 0)
668 break;
669 if (i != (size_t)item.Size)
670 _symLink_Error = true;
671 else
672 _items.Back().Data.CopyFrom(buf, (size_t)item.Size);
673 }
674 else if (dataSize != 0)
675 {
676 UInt64 newPos;
677 RINOK(stream->Seek((Int64)dataSize, STREAM_SEEK_CUR, &newPos))
678 if (arc.Processed != newPos)
549 return E_FAIL; 679 return E_FAIL;
550 } 680 }
551 681
552 if (callback && (_items.Size() & 0xFF) == 0) 682 if (callback && (_items.Size() & 0xFFF) == 0)
553 { 683 {
554 UInt64 numFiles = _items.Size(); 684 const UInt64 numFiles = _items.Size();
555 RINOK(callback->SetCompleted(&numFiles, &item.HeaderPos)); 685 RINOK(callback->SetCompleted(&numFiles, &item.HeaderPos))
556 } 686 }
557 } 687 }
688
558 _phySize = arc.Processed; 689 _phySize = arc.Processed;
690 }
691
692 {
559 if (_error != k_ErrorType_OK) 693 if (_error != k_ErrorType_OK)
560 { 694 {
695 // we try to reduce probability of false detection
561 if (_items.Size() == 0) 696 if (_items.Size() == 0)
562 return S_FALSE; 697 return S_FALSE;
698 // bin file uses small signature. So we do additional check for single item case.
563 if (_items.Size() == 1 && _items[0].IsBin()) 699 if (_items.Size() == 1 && _items[0].IsBin())
564 {
565 // probably it's false detected archive. So we return error
566 return S_FALSE; 700 return S_FALSE;
567 }
568 } 701 }
569 else 702 else
570 { 703 {
@@ -574,16 +707,15 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
574 const unsigned kTailSize_MAX = 1 << 9; 707 const unsigned kTailSize_MAX = 1 << 9;
575 Byte buf[kTailSize_MAX]; 708 Byte buf[kTailSize_MAX];
576 709
577 unsigned pos = (unsigned)arc.Processed & (kTailSize_MAX - 1); 710 unsigned pos = (unsigned)_phySize & (kTailSize_MAX - 1);
578 if (pos != 0) // use this check to support 512 bytes alignment only 711 if (pos != 0) // use this check to support 512 bytes alignment only
579 for (;;) 712 for (;;)
580 { 713 {
581 unsigned rem = kTailSize_MAX - pos; 714 const unsigned rem = kTailSize_MAX - pos;
582 size_t processed = rem; 715 size_t processed = rem;
583 RINOK(ReadStream(stream, buf + pos, &processed)); 716 RINOK(ReadStream(stream, buf + pos, &processed))
584 if (processed != rem) 717 if (processed != rem)
585 break; 718 break;
586
587 for (; pos < kTailSize_MAX && buf[pos] == 0; pos++) 719 for (; pos < kTailSize_MAX && buf[pos] == 0; pos++)
588 {} 720 {}
589 if (pos != kTailSize_MAX) 721 if (pos != kTailSize_MAX)
@@ -596,32 +728,134 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
596 break; 728 break;
597 } 729 }
598 } 730 }
731 }
732
733 {
734 /* there was such cpio archive example with hard links:
735 {
736 all hard links (same dev/inode) are stored in neighboring items, and
737 (item.Size == 0) for non last hard link items
738 (item.Size != 0) for last hard link item
739 }
740 but here we sort items by (dev/inode) to support cases
741 where hard links (same dev/inode) are not stored in neighboring items.
742
743 // note: some cpio files have (numLinks == 0) ??
744 */
745
746 CUIntVector indices;
747 {
748 const unsigned numItems = _items.Size();
749 indices.ClearAndSetSize(numItems);
750 if (numItems != 0)
751 {
752 unsigned *vals = &indices[0];
753 for (unsigned i = 0; i < numItems; i++)
754 vals[i] = i;
755 indices.Sort(CompareItems, (void *)&_items);
756 }
757 }
758
759 /* Note: if cpio archive (maybe incorrect) contains
760 more then one non empty streams with identical inode number,
761 we want to extract all such data streams too.
762
763 So we place items with identical inode to groups:
764 all items in group will have same MainIndex_ForInode,
765 that is index of last item in group with (Size != 0).
766 Another (non last) items in group have (Size == 0).
767 If there are another hard links with same inode number
768 after (Size != 0) item, we place them to another next group(s).
769
770 Check it: maybe we should use single group for items
771 with identical inode instead, and ignore some extra data streams ?
772 */
599 773
600 _isArc = true; 774 for (unsigned i = 0; i < indices.Size();)
601 _stream = stream; 775 {
776 unsigned k;
777 {
778 const CItem &item_Base = _items[indices[i]];
779
780 if (item_Base.IsDir())
781 {
782 i++;
783 continue;
784 }
785
786 if (i != 0)
787 {
788 const CItem &item_Prev = _items[indices[i - 1]];
789 if (!item_Prev.IsDir())
790 if (item_Base.IsSame_inode_Dev(item_Prev))
791 _moreThanOneHardLinks_Error = true;
792 }
793
794 if (item_Base.Size != 0)
795 {
796 if (item_Base.NumLinks != 1)
797 _numLinks_Error = true;
798 i++;
799 continue;
800 }
801
802 for (k = i + 1; k < indices.Size();)
803 {
804 const CItem &item = _items[indices[k]];
805 if (item.IsDir())
806 break;
807 if (!item.IsSame_inode_Dev(item_Base))
808 break;
809 k++;
810 if (item.Size != 0)
811 break;
812 }
813 }
814
815 const unsigned numLinks = k - i;
816 for (;;)
817 {
818 CItem &item = _items[indices[i]];
819 if (item.NumLinks != numLinks)
820 _numLinks_Error = true;
821 if (++i == k)
822 break;
823 // if (item.Size == 0)
824 item.MainIndex_ForInode = indices[k - 1];
825 }
826 }
602 } 827 }
828
829 _isArc = true;
830 _stream = stream;
831
603 return S_OK; 832 return S_OK;
604 COM_TRY_END 833 COM_TRY_END
605} 834}
606 835
607STDMETHODIMP CHandler::Close() 836
837Z7_COM7F_IMF(CHandler::Close())
608{ 838{
609 _items.Clear(); 839 _items.Clear();
610 _stream.Release(); 840 _stream.Release();
611 _phySize = 0; 841 _phySize = 0;
612 _Type = k_Type_BinLe; 842 _type = k_Type_BinLe;
613 _isArc = false; 843 _isArc = false;
844 _moreThanOneHardLinks_Error = false;
845 _numLinks_Error = false;
846 _pad_Error = false;
847 _symLink_Error = false;
614 _error = k_ErrorType_OK; 848 _error = k_ErrorType_OK;
615 return S_OK; 849 return S_OK;
616} 850}
617 851
618STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 852Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
619{ 853{
620 *numItems = _items.Size(); 854 *numItems = _items.Size();
621 return S_OK; 855 return S_OK;
622} 856}
623 857
624STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 858Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
625{ 859{
626 COM_TRY_BEGIN 860 COM_TRY_BEGIN
627 NCOM::CPropVariant prop; 861 NCOM::CPropVariant prop;
@@ -645,10 +879,15 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
645 break; 879 break;
646 } 880 }
647 case kpidIsDir: prop = item.IsDir(); break; 881 case kpidIsDir: prop = item.IsDir(); break;
882
648 case kpidSize: 883 case kpidSize:
884 prop = (UInt64)_items[item.MainIndex_ForInode].Size;
885 break;
886
649 case kpidPackSize: 887 case kpidPackSize:
650 prop = (UInt64)item.Size; 888 prop = (UInt64)item.GetPackSize();
651 break; 889 break;
890
652 case kpidMTime: 891 case kpidMTime:
653 { 892 {
654 if (item.MTime != 0) 893 if (item.MTime != 0)
@@ -656,28 +895,69 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
656 break; 895 break;
657 } 896 }
658 case kpidPosixAttrib: prop = item.Mode; break; 897 case kpidPosixAttrib: prop = item.Mode; break;
898 case kpidINode: prop = item.inode; break;
899 case kpidStreamId:
900 if (!item.IsDir())
901 prop = (UInt32)item.MainIndex_ForInode;
902 break;
903 case kpidDevMajor: prop = (UInt32)item.DevMajor; break;
904 case kpidDevMinor: prop = (UInt32)item.DevMinor; break;
905
906 case kpidUserId: prop = item.UID; break;
907 case kpidGroupId: prop = item.GID; break;
908
909 case kpidSymLink:
910 if (item.Is_SymLink() && item.Data.Size() != 0)
911 {
912 AString s;
913 s.SetFrom_CalcLen((const char *)(const void *)(const Byte *)item.Data, (unsigned)item.Data.Size());
914 if (s.Len() == item.Data.Size())
915 {
916 UString u;
917 bool needConvert = true;
918 #ifdef _WIN32
919 // if (
920 ConvertUTF8ToUnicode(item.Name, u);
921 // )
922 needConvert = false;
923 #endif
924 if (needConvert)
925 u = MultiByteToUnicodeString(s, CP_OEMCP);
926 prop = u;
927 }
928 }
929 break;
930
659 case kpidLinks: prop = item.NumLinks; break; 931 case kpidLinks: prop = item.NumLinks; break;
660 /* 932 case kpidDeviceMajor:
661 case kpidinode: prop = item.inode; break; 933 // if (item.RDevMajor != 0)
662 case kpidiChkSum: prop = item.ChkSum; break; 934 prop = (UInt32)item.RDevMajor;
663 */ 935 break;
936 case kpidDeviceMinor:
937 // if (item.RDevMinor != 0)
938 prop = (UInt32)item.RDevMinor;
939 break;
940 case kpidChecksum:
941 if (item.IsCrcFormat())
942 prop = item.ChkSum;
943 break;
944 case kpidOffset: prop = item.GetDataPosition(); break;
664 } 945 }
665 prop.Detach(value); 946 prop.Detach(value);
666 return S_OK; 947 return S_OK;
667 COM_TRY_END 948 COM_TRY_END
668} 949}
669 950
670class COutStreamWithSum: 951
671 public ISequentialOutStream, 952Z7_CLASS_IMP_NOQIB_1(
672 public CMyUnknownImp 953 COutStreamWithSum
673{ 954 , ISequentialOutStream
955)
674 CMyComPtr<ISequentialOutStream> _stream; 956 CMyComPtr<ISequentialOutStream> _stream;
675 UInt64 _size; 957 UInt64 _size;
676 UInt32 _crc; 958 UInt32 _crc;
677 bool _calculate; 959 bool _calculate;
678public: 960public:
679 MY_UNKNOWN_IMP
680 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
681 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 961 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
682 void ReleaseStream() { _stream.Release(); } 962 void ReleaseStream() { _stream.Release(); }
683 void Init(bool calculate = true) 963 void Init(bool calculate = true)
@@ -692,7 +972,7 @@ public:
692 UInt32 GetCRC() const { return _crc; } 972 UInt32 GetCRC() const { return _crc; }
693}; 973};
694 974
695STDMETHODIMP COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *processedSize) 975Z7_COM7F_IMF(COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *processedSize))
696{ 976{
697 HRESULT result = S_OK; 977 HRESULT result = S_OK;
698 if (_stream) 978 if (_stream)
@@ -709,11 +989,11 @@ STDMETHODIMP COutStreamWithSum::Write(const void *data, UInt32 size, UInt32 *pro
709 return result; 989 return result;
710} 990}
711 991
712STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 992Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
713 Int32 testMode, IArchiveExtractCallback *extractCallback) 993 Int32 testMode, IArchiveExtractCallback *extractCallback))
714{ 994{
715 COM_TRY_BEGIN 995 COM_TRY_BEGIN
716 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 996 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
717 if (allFilesMode) 997 if (allFilesMode)
718 numItems = _items.Size(); 998 numItems = _items.Size();
719 if (numItems == 0) 999 if (numItems == 0)
@@ -721,11 +1001,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
721 UInt64 totalSize = 0; 1001 UInt64 totalSize = 0;
722 UInt32 i; 1002 UInt32 i;
723 for (i = 0; i < numItems; i++) 1003 for (i = 0; i < numItems; i++)
724 totalSize += _items[allFilesMode ? i : indices[i]].Size; 1004 {
725 extractCallback->SetTotal(totalSize); 1005 const UInt32 index = allFilesMode ? i : indices[i];
1006 const CItem &item2 = _items[index];
1007 const CItem &item = _items[item2.MainIndex_ForInode];
1008 totalSize += item.Size;
1009 }
1010 RINOK(extractCallback->SetTotal(totalSize))
726 1011
727 UInt64 currentTotalSize = 0;
728
729 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); 1012 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
730 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; 1013 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
731 1014
@@ -740,22 +1023,32 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
740 COutStreamWithSum *outStreamSumSpec = new COutStreamWithSum; 1023 COutStreamWithSum *outStreamSumSpec = new COutStreamWithSum;
741 CMyComPtr<ISequentialOutStream> outStreamSum(outStreamSumSpec); 1024 CMyComPtr<ISequentialOutStream> outStreamSum(outStreamSumSpec);
742 1025
743 for (i = 0; i < numItems; i++) 1026 UInt64 total_PackSize = 0;
1027 UInt64 total_UnpackSize = 0;
1028
1029 for (i = 0;; i++)
744 { 1030 {
745 lps->InSize = lps->OutSize = currentTotalSize; 1031 lps->InSize = total_PackSize;
746 RINOK(lps->SetCur()); 1032 lps->OutSize = total_UnpackSize;
1033 RINOK(lps->SetCur())
1034 if (i >= numItems)
1035 break;
747 CMyComPtr<ISequentialOutStream> outStream; 1036 CMyComPtr<ISequentialOutStream> outStream;
748 Int32 askMode = testMode ? 1037 const Int32 askMode = testMode ?
749 NExtract::NAskMode::kTest : 1038 NExtract::NAskMode::kTest :
750 NExtract::NAskMode::kExtract; 1039 NExtract::NAskMode::kExtract;
751 Int32 index = allFilesMode ? i : indices[i]; 1040 const UInt32 index = allFilesMode ? i : indices[i];
752 const CItem &item = _items[index]; 1041 const CItem &item2 = _items[index];
753 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 1042 const CItem &item = _items[item2.MainIndex_ForInode];
754 currentTotalSize += item.Size; 1043 RINOK(extractCallback->GetStream(index, &outStream, askMode))
755 if (item.IsDir()) 1044
1045 total_PackSize += item2.GetPackSize();
1046 total_UnpackSize += item.Size;
1047
1048 if (item2.IsDir())
756 { 1049 {
757 RINOK(extractCallback->PrepareOperation(askMode)); 1050 RINOK(extractCallback->PrepareOperation(askMode))
758 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1051 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
759 continue; 1052 continue;
760 } 1053 }
761 if (!testMode && !outStream) 1054 if (!testMode && !outStream)
@@ -764,10 +1057,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
764 outStreamSumSpec->SetStream(outStream); 1057 outStreamSumSpec->SetStream(outStream);
765 outStream.Release(); 1058 outStream.Release();
766 1059
767 RINOK(extractCallback->PrepareOperation(askMode)); 1060 RINOK(extractCallback->PrepareOperation(askMode))
768 RINOK(_stream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); 1061 RINOK(InStream_SeekSet(_stream, item.GetDataPosition()))
769 streamSpec->Init(item.Size); 1062 streamSpec->Init(item.Size);
770 RINOK(copyCoder->Code(inStream, outStreamSum, NULL, NULL, progress)); 1063 RINOK(copyCoder->Code(inStream, outStreamSum, NULL, NULL, progress))
771 outStreamSumSpec->ReleaseStream(); 1064 outStreamSumSpec->ReleaseStream();
772 Int32 res = NExtract::NOperationResult::kDataError; 1065 Int32 res = NExtract::NOperationResult::kDataError;
773 if (copyCoderSpec->TotalSize == item.Size) 1066 if (copyCoderSpec->TotalSize == item.Size)
@@ -776,16 +1069,17 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
776 if (item.IsCrcFormat() && item.ChkSum != outStreamSumSpec->GetCRC()) 1069 if (item.IsCrcFormat() && item.ChkSum != outStreamSumSpec->GetCRC())
777 res = NExtract::NOperationResult::kCRCError; 1070 res = NExtract::NOperationResult::kCRCError;
778 } 1071 }
779 RINOK(extractCallback->SetOperationResult(res)); 1072 RINOK(extractCallback->SetOperationResult(res))
780 } 1073 }
781 return S_OK; 1074 return S_OK;
782 COM_TRY_END 1075 COM_TRY_END
783} 1076}
784 1077
785STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 1078Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
786{ 1079{
787 COM_TRY_BEGIN 1080 COM_TRY_BEGIN
788 const CItem &item = _items[index]; 1081 const CItem &item2 = _items[index];
1082 const CItem &item = _items[item2.MainIndex_ForInode];
789 return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream); 1083 return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream);
790 COM_TRY_END 1084 COM_TRY_END
791} 1085}
@@ -796,7 +1090,7 @@ static const Byte k_Signature[] = {
796 2, kMagicBin1, kMagicBin0 }; 1090 2, kMagicBin1, kMagicBin0 };
797 1091
798REGISTER_ARC_I( 1092REGISTER_ARC_I(
799 "Cpio", "cpio", 0, 0xED, 1093 "Cpio", "cpio", NULL, 0xED,
800 k_Signature, 1094 k_Signature,
801 0, 1095 0,
802 NArcInfoFlags::kMultiSignature, 1096 NArcInfoFlags::kMultiSignature,
diff --git a/CPP/7zip/Archive/CramfsHandler.cpp b/CPP/7zip/Archive/CramfsHandler.cpp
index 0f12332..fd83f71 100644
--- a/CPP/7zip/Archive/CramfsHandler.cpp
+++ b/CPP/7zip/Archive/CramfsHandler.cpp
@@ -25,9 +25,8 @@
25namespace NArchive { 25namespace NArchive {
26namespace NCramfs { 26namespace NCramfs {
27 27
28#define SIGNATURE { 'C','o','m','p','r','e','s','s','e','d',' ','R','O','M','F','S' } 28static const Byte kSignature[] =
29 29 { 'C','o','m','p','r','e','s','s','e','d',' ','R','O','M','F','S' };
30static const Byte kSignature[] = SIGNATURE;
31 30
32static const UInt32 kArcSizeMax = (256 + 16) << 20; 31static const UInt32 kArcSizeMax = (256 + 16) << 20;
33static const UInt32 kNumFilesMax = (1 << 19); 32static const UInt32 kNumFilesMax = (1 << 19);
@@ -114,7 +113,7 @@ static UInt32 GetNameLen(const Byte *p, bool be)
114 if (be) 113 if (be)
115 return (p[8] & 0xFC); 114 return (p[8] & 0xFC);
116 else 115 else
117 return (p[8] & 0x3F) << 2; 116 return ((UInt32)p[8] & (UInt32)0x3F) << 2;
118} 117}
119 118
120static UInt32 GetOffset(const Byte *p, bool be) 119static UInt32 GetOffset(const Byte *p, bool be)
@@ -145,7 +144,7 @@ struct CHeader
145 144
146 bool Parse(const Byte *p) 145 bool Parse(const Byte *p)
147 { 146 {
148 if (memcmp(p + 16, kSignature, ARRAY_SIZE(kSignature)) != 0) 147 if (memcmp(p + 16, kSignature, Z7_ARRAY_SIZE(kSignature)) != 0)
149 return false; 148 return false;
150 switch (GetUi32(p)) 149 switch (GetUi32(p))
151 { 150 {
@@ -169,11 +168,11 @@ struct CHeader
169 unsigned GetMethod() const { return (unsigned)(Flags >> k_Flags_Method_Shift) & k_Flags_Method_Mask; } 168 unsigned GetMethod() const { return (unsigned)(Flags >> k_Flags_Method_Shift) & k_Flags_Method_Mask; }
170}; 169};
171 170
172class CHandler: 171
173 public IInArchive, 172
174 public IInArchiveGetStream, 173Z7_CLASS_IMP_CHandler_IInArchive_1(
175 public CMyUnknownImp 174 IInArchiveGetStream
176{ 175)
177 CRecordVector<CItem> _items; 176 CRecordVector<CItem> _items;
178 CMyComPtr<IInStream> _stream; 177 CMyComPtr<IInStream> _stream;
179 Byte *_data; 178 Byte *_data;
@@ -205,8 +204,8 @@ class CHandler:
205 204
206 HRESULT OpenDir(int parent, UInt32 baseOffsetBase, unsigned level); 205 HRESULT OpenDir(int parent, UInt32 baseOffsetBase, unsigned level);
207 HRESULT Open2(IInStream *inStream); 206 HRESULT Open2(IInStream *inStream);
208 AString GetPath(int index) const; 207 AString GetPath(unsigned index) const;
209 bool GetPackSize(int index, UInt32 &res) const; 208 bool GetPackSize(unsigned index, UInt32 &res) const;
210 void Free(); 209 void Free();
211 210
212 UInt32 GetNumBlocks(UInt32 size) const 211 UInt32 GetNumBlocks(UInt32 size) const
@@ -221,11 +220,8 @@ class CHandler:
221 } 220 }
222 221
223public: 222public:
224 CHandler(): _data(0) {} 223 CHandler(): _data(NULL) {}
225 ~CHandler() { Free(); } 224 ~CHandler() { Free(); }
226 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
227 INTERFACE_IInArchive(;)
228 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
229 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); 225 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize);
230}; 226};
231 227
@@ -291,7 +287,7 @@ HRESULT CHandler::OpenDir(int parent, UInt32 baseOffset, unsigned level)
291 unsigned endIndex = _items.Size(); 287 unsigned endIndex = _items.Size();
292 for (unsigned i = startIndex; i < endIndex; i++) 288 for (unsigned i = startIndex; i < endIndex; i++)
293 { 289 {
294 RINOK(OpenDir(i, _items[i].Offset, level + 1)); 290 RINOK(OpenDir((int)i, _items[i].Offset, level + 1))
295 } 291 }
296 return S_OK; 292 return S_OK;
297} 293}
@@ -299,7 +295,7 @@ HRESULT CHandler::OpenDir(int parent, UInt32 baseOffset, unsigned level)
299HRESULT CHandler::Open2(IInStream *inStream) 295HRESULT CHandler::Open2(IInStream *inStream)
300{ 296{
301 Byte buf[kHeaderSize]; 297 Byte buf[kHeaderSize];
302 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)); 298 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize))
303 if (!_h.Parse(buf)) 299 if (!_h.Parse(buf))
304 return S_FALSE; 300 return S_FALSE;
305 _method = k_Flags_Method_ZLIB; 301 _method = k_Flags_Method_ZLIB;
@@ -319,18 +315,18 @@ HRESULT CHandler::Open2(IInStream *inStream)
319 else 315 else
320 { 316 {
321 UInt64 size; 317 UInt64 size;
322 RINOK(inStream->Seek(0, STREAM_SEEK_END, &size)); 318 RINOK(InStream_GetSize_SeekToEnd(inStream, size))
323 if (size > kArcSizeMax) 319 if (size > kArcSizeMax)
324 size = kArcSizeMax; 320 size = kArcSizeMax;
325 _h.Size = (UInt32)size; 321 _h.Size = (UInt32)size;
326 RINOK(inStream->Seek(kHeaderSize, STREAM_SEEK_SET, NULL)); 322 RINOK(InStream_SeekSet(inStream, kHeaderSize))
327 } 323 }
328 _data = (Byte *)MidAlloc(_h.Size); 324 _data = (Byte *)MidAlloc(_h.Size);
329 if (_data == 0) 325 if (!_data)
330 return E_OUTOFMEMORY; 326 return E_OUTOFMEMORY;
331 memcpy(_data, buf, kHeaderSize); 327 memcpy(_data, buf, kHeaderSize);
332 size_t processed = _h.Size - kHeaderSize; 328 size_t processed = _h.Size - kHeaderSize;
333 RINOK(ReadStream(inStream, _data + kHeaderSize, &processed)); 329 RINOK(ReadStream(inStream, _data + kHeaderSize, &processed))
334 if (processed < kNodeSize) 330 if (processed < kNodeSize)
335 return S_FALSE; 331 return S_FALSE;
336 _size = kHeaderSize + (UInt32)processed; 332 _size = kHeaderSize + (UInt32)processed;
@@ -340,7 +336,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
340 _errorFlags = kpv_ErrorFlags_UnexpectedEnd; 336 _errorFlags = kpv_ErrorFlags_UnexpectedEnd;
341 else 337 else
342 { 338 {
343 SetUi32(_data + 0x20, 0); 339 SetUi32(_data + 0x20, 0)
344 if (CrcCalc(_data, _h.Size) != _h.Crc) 340 if (CrcCalc(_data, _h.Size) != _h.Crc)
345 { 341 {
346 _errorFlags = kpv_ErrorFlags_HeadersError; 342 _errorFlags = kpv_ErrorFlags_HeadersError;
@@ -351,7 +347,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
351 _items.ClearAndReserve(_h.NumFiles - 1); 347 _items.ClearAndReserve(_h.NumFiles - 1);
352 } 348 }
353 349
354 RINOK(OpenDir(-1, kHeaderSize, 0)); 350 RINOK(OpenDir(-1, kHeaderSize, 0))
355 351
356 if (!_h.IsVer2()) 352 if (!_h.IsVer2())
357 { 353 {
@@ -389,22 +385,23 @@ HRESULT CHandler::Open2(IInStream *inStream)
389 return S_OK; 385 return S_OK;
390} 386}
391 387
392AString CHandler::GetPath(int index) const 388AString CHandler::GetPath(unsigned index) const
393{ 389{
394 unsigned len = 0; 390 unsigned len = 0;
395 int indexMem = index; 391 unsigned indexMem = index;
396 do 392 for (;;)
397 { 393 {
398 const CItem &item = _items[index]; 394 const CItem &item = _items[index];
399 index = item.Parent;
400 const Byte *p = _data + item.Offset; 395 const Byte *p = _data + item.Offset;
401 unsigned size = GetNameLen(p, _h.be); 396 unsigned size = GetNameLen(p, _h.be);
402 p += kNodeSize; 397 p += kNodeSize;
403 unsigned i; 398 unsigned i;
404 for (i = 0; i < size && p[i]; i++); 399 for (i = 0; i < size && p[i]; i++);
405 len += i + 1; 400 len += i + 1;
401 index = (unsigned)item.Parent;
402 if (item.Parent < 0)
403 break;
406 } 404 }
407 while (index >= 0);
408 len--; 405 len--;
409 406
410 AString path; 407 AString path;
@@ -413,7 +410,6 @@ AString CHandler::GetPath(int index) const
413 for (;;) 410 for (;;)
414 { 411 {
415 const CItem &item = _items[index]; 412 const CItem &item = _items[index];
416 index = item.Parent;
417 const Byte *p = _data + item.Offset; 413 const Byte *p = _data + item.Offset;
418 unsigned size = GetNameLen(p, _h.be); 414 unsigned size = GetNameLen(p, _h.be);
419 p += kNodeSize; 415 p += kNodeSize;
@@ -421,41 +417,42 @@ AString CHandler::GetPath(int index) const
421 for (i = 0; i < size && p[i]; i++); 417 for (i = 0; i < size && p[i]; i++);
422 dest -= i; 418 dest -= i;
423 memcpy(dest, p, i); 419 memcpy(dest, p, i);
424 if (index < 0) 420 index = (unsigned)item.Parent;
421 if (item.Parent < 0)
425 break; 422 break;
426 *(--dest) = CHAR_PATH_SEPARATOR; 423 *(--dest) = CHAR_PATH_SEPARATOR;
427 } 424 }
428 return path; 425 return path;
429} 426}
430 427
431bool CHandler::GetPackSize(int index, UInt32 &res) const 428bool CHandler::GetPackSize(unsigned index, UInt32 &res) const
432{ 429{
433 res = 0; 430 res = 0;
434 const CItem &item = _items[index]; 431 const CItem &item = _items[index];
435 const Byte *p = _data + item.Offset; 432 const Byte *p = _data + item.Offset;
436 bool be = _h.be; 433 const bool be = _h.be;
437 UInt32 offset = GetOffset(p, be); 434 const UInt32 offset = GetOffset(p, be);
438 if (offset < kHeaderSize) 435 if (offset < kHeaderSize)
439 return false; 436 return false;
440 UInt32 numBlocks = GetNumBlocks(GetSize(p, be)); 437 const UInt32 numBlocks = GetNumBlocks(GetSize(p, be));
441 if (numBlocks == 0) 438 if (numBlocks == 0)
442 return true; 439 return true;
443 UInt32 start = offset + numBlocks * 4; 440 const UInt32 start = offset + numBlocks * 4;
444 if (start > _size) 441 if (start > _size)
445 return false; 442 return false;
446 UInt32 end = Get32(_data + start - 4); 443 const UInt32 end = Get32(_data + start - 4);
447 if (end < start) 444 if (end < start)
448 return false; 445 return false;
449 res = end - start; 446 res = end - start;
450 return true; 447 return true;
451} 448}
452 449
453STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */) 450Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* callback */))
454{ 451{
455 COM_TRY_BEGIN 452 COM_TRY_BEGIN
456 { 453 {
457 Close(); 454 Close();
458 RINOK(Open2(stream)); 455 RINOK(Open2(stream))
459 _isArc = true; 456 _isArc = true;
460 _stream = stream; 457 _stream = stream;
461 } 458 }
@@ -466,10 +463,10 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
466void CHandler::Free() 463void CHandler::Free()
467{ 464{
468 MidFree(_data); 465 MidFree(_data);
469 _data = 0; 466 _data = NULL;
470} 467}
471 468
472STDMETHODIMP CHandler::Close() 469Z7_COM7F_IMF(CHandler::Close())
473{ 470{
474 _isArc = false; 471 _isArc = false;
475 _phySize = 0; 472 _phySize = 0;
@@ -481,13 +478,13 @@ STDMETHODIMP CHandler::Close()
481 return S_OK; 478 return S_OK;
482} 479}
483 480
484STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 481Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
485{ 482{
486 *numItems = _items.Size(); 483 *numItems = _items.Size();
487 return S_OK; 484 return S_OK;
488} 485}
489 486
490STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 487Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
491{ 488{
492 COM_TRY_BEGIN 489 COM_TRY_BEGIN
493 NWindows::NCOM::CPropVariant prop; 490 NWindows::NCOM::CPropVariant prop;
@@ -523,7 +520,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
523 COM_TRY_END 520 COM_TRY_END
524} 521}
525 522
526STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 523Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
527{ 524{
528 COM_TRY_BEGIN 525 COM_TRY_BEGIN
529 NWindows::NCOM::CPropVariant prop; 526 NWindows::NCOM::CPropVariant prop;
@@ -554,7 +551,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
554 551
555class CCramfsInStream: public CCachedInStream 552class CCramfsInStream: public CCachedInStream
556{ 553{
557 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); 554 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) Z7_override;
558public: 555public:
559 CHandler *Handler; 556 CHandler *Handler;
560}; 557};
@@ -626,16 +623,16 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize)
626 } 623 }
627 _inStreamSpec->Init(_data + start, inSize); 624 _inStreamSpec->Init(_data + start, inSize);
628 _outStreamSpec->Init(dest, blockSize); 625 _outStreamSpec->Init(dest, blockSize);
629 RINOK(_zlibDecoder->Code(_inStream, _outStream, NULL, NULL, NULL)); 626 RINOK(_zlibDecoder->Code(_inStream, _outStream, NULL, NULL, NULL))
630 return (inSize == _zlibDecoderSpec->GetInputProcessedSize() && 627 return (inSize == _zlibDecoderSpec->GetInputProcessedSize() &&
631 _outStreamSpec->GetPos() == blockSize) ? S_OK : S_FALSE; 628 _outStreamSpec->GetPos() == blockSize) ? S_OK : S_FALSE;
632} 629}
633 630
634STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 631Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
635 Int32 testMode, IArchiveExtractCallback *extractCallback) 632 Int32 testMode, IArchiveExtractCallback *extractCallback))
636{ 633{
637 COM_TRY_BEGIN 634 COM_TRY_BEGIN
638 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 635 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
639 if (allFilesMode) 636 if (allFilesMode)
640 numItems = _items.Size(); 637 numItems = _items.Size();
641 if (numItems == 0) 638 if (numItems == 0)
@@ -665,20 +662,20 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
665 { 662 {
666 lps->InSize = totalPackSize; 663 lps->InSize = totalPackSize;
667 lps->OutSize = totalSize; 664 lps->OutSize = totalSize;
668 RINOK(lps->SetCur()); 665 RINOK(lps->SetCur())
669 CMyComPtr<ISequentialOutStream> outStream; 666 CMyComPtr<ISequentialOutStream> outStream;
670 Int32 askMode = testMode ? 667 const Int32 askMode = testMode ?
671 NExtract::NAskMode::kTest : 668 NExtract::NAskMode::kTest :
672 NExtract::NAskMode::kExtract; 669 NExtract::NAskMode::kExtract;
673 UInt32 index = allFilesMode ? i : indices[i]; 670 const UInt32 index = allFilesMode ? i : indices[i];
674 const CItem &item = _items[index]; 671 const CItem &item = _items[index];
675 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 672 RINOK(extractCallback->GetStream(index, &outStream, askMode))
676 const Byte *p = _data + item.Offset; 673 const Byte *p = _data + item.Offset;
677 674
678 if (IsDir(p, be)) 675 if (IsDir(p, be))
679 { 676 {
680 RINOK(extractCallback->PrepareOperation(askMode)); 677 RINOK(extractCallback->PrepareOperation(askMode))
681 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 678 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
682 continue; 679 continue;
683 } 680 }
684 UInt32 curSize = GetSize(p, be); 681 UInt32 curSize = GetSize(p, be);
@@ -689,7 +686,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
689 686
690 if (!testMode && !outStream) 687 if (!testMode && !outStream)
691 continue; 688 continue;
692 RINOK(extractCallback->PrepareOperation(askMode)); 689 RINOK(extractCallback->PrepareOperation(askMode))
693 690
694 UInt32 offset = GetOffset(p, be); 691 UInt32 offset = GetOffset(p, be);
695 if (offset < kHeaderSize) 692 if (offset < kHeaderSize)
@@ -705,7 +702,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
705 res = NExtract::NOperationResult::kUnsupportedMethod; 702 res = NExtract::NOperationResult::kUnsupportedMethod;
706 else 703 else
707 { 704 {
708 RINOK(hres); 705 RINOK(hres)
709 { 706 {
710 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); 707 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress);
711 if (hres == S_OK) 708 if (hres == S_OK)
@@ -720,14 +717,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
720 } 717 }
721 } 718 }
722 } 719 }
723 RINOK(extractCallback->SetOperationResult(res)); 720 RINOK(extractCallback->SetOperationResult(res))
724 } 721 }
725 722
726 return S_OK; 723 return S_OK;
727 COM_TRY_END 724 COM_TRY_END
728} 725}
729 726
730STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 727Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
731{ 728{
732 COM_TRY_BEGIN 729 COM_TRY_BEGIN
733 730
@@ -778,7 +775,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
778} 775}
779 776
780REGISTER_ARC_I( 777REGISTER_ARC_I(
781 "CramFS", "cramfs", 0, 0xD3, 778 "CramFS", "cramfs", NULL, 0xD3,
782 kSignature, 779 kSignature,
783 16, 780 16,
784 0, 781 0,
diff --git a/CPP/7zip/Archive/DeflateProps.h b/CPP/7zip/Archive/DeflateProps.h
index 9fd2c2e..666fb39 100644
--- a/CPP/7zip/Archive/DeflateProps.h
+++ b/CPP/7zip/Archive/DeflateProps.h
@@ -1,6 +1,6 @@
1// DeflateProps.h 1// DeflateProps.h
2 2
3#ifndef __DEFLATE_PROPS_H 3#ifndef ZIP7_INC_DEFLATE_PROPS_H
4#define __DEFLATE_PROPS_H 4#define ZIP7_INC_DEFLATE_PROPS_H
5 5
6#endif 6#endif
diff --git a/CPP/7zip/Archive/DllExports.cpp b/CPP/7zip/Archive/DllExports.cpp
index 7aee235..9def208 100644
--- a/CPP/7zip/Archive/DllExports.cpp
+++ b/CPP/7zip/Archive/DllExports.cpp
@@ -2,10 +2,11 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#if defined(_7ZIP_LARGE_PAGES) 5#if defined(Z7_LARGE_PAGES)
6#include "../../../C/Alloc.h" 6#include "../../../C/Alloc.h"
7#endif 7#endif
8 8
9#include "../../Common/MyWindows.h"
9#include "../../Common/MyInitGuid.h" 10#include "../../Common/MyInitGuid.h"
10 11
11#include "../../Common/ComTry.h" 12#include "../../Common/ComTry.h"
@@ -20,22 +21,23 @@
20 21
21#include "IArchive.h" 22#include "IArchive.h"
22 23
24static
23HINSTANCE g_hInstance; 25HINSTANCE g_hInstance;
24 26
25#define NT_CHECK_FAIL_ACTION return FALSE; 27#define NT_CHECK_FAIL_ACTION return FALSE;
26 28
27extern "C" 29extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/);
28BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) 30extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
29{ 31{
30 if (dwReason == DLL_PROCESS_ATTACH) 32 if (dwReason == DLL_PROCESS_ATTACH)
31 { 33 {
32 g_hInstance = hInstance; 34 g_hInstance = hInstance;
33 NT_CHECK; 35 NT_CHECK
34 } 36 }
35 return TRUE; 37 return TRUE;
36} 38}
37 39
38DEFINE_GUID(CLSID_CArchiveHandler, 40Z7_DEFINE_GUID(CLSID_CArchiveHandler,
39 k_7zip_GUID_Data1, 41 k_7zip_GUID_Data1,
40 k_7zip_GUID_Data2, 42 k_7zip_GUID_Data2,
41 k_7zip_GUID_Data3_Common, 43 k_7zip_GUID_Data3_Common,
@@ -50,7 +52,7 @@ STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject)
50 52
51STDAPI SetLargePageMode() 53STDAPI SetLargePageMode()
52{ 54{
53 #if defined(_7ZIP_LARGE_PAGES) 55 #if defined(Z7_LARGE_PAGES)
54 SetLargePageSize(); 56 SetLargePageSize();
55 #endif 57 #endif
56 return S_OK; 58 return S_OK;
@@ -64,7 +66,7 @@ STDAPI SetCaseSensitive(Int32 caseSensitive)
64 return S_OK; 66 return S_OK;
65} 67}
66 68
67#ifdef EXTERNAL_CODECS 69#ifdef Z7_EXTERNAL_CODECS
68 70
69CExternalCodecs g_ExternalCodecs; 71CExternalCodecs g_ExternalCodecs;
70 72
diff --git a/CPP/7zip/Archive/DllExports2.cpp b/CPP/7zip/Archive/DllExports2.cpp
index 1f71486..ae8d8ac 100644
--- a/CPP/7zip/Archive/DllExports2.cpp
+++ b/CPP/7zip/Archive/DllExports2.cpp
@@ -3,10 +3,9 @@
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../Common/MyWindows.h" 5#include "../../Common/MyWindows.h"
6
7#include "../../Common/MyInitGuid.h" 6#include "../../Common/MyInitGuid.h"
8 7
9#if defined(_7ZIP_LARGE_PAGES) 8#if defined(Z7_LARGE_PAGES)
10#include "../../../C/Alloc.h" 9#include "../../../C/Alloc.h"
11#endif 10#endif
12 11
@@ -29,6 +28,7 @@
29#define NT_CHECK_FAIL_ACTION return FALSE; 28#define NT_CHECK_FAIL_ACTION return FALSE;
30#endif 29#endif
31 30
31static
32HINSTANCE g_hInstance; 32HINSTANCE g_hInstance;
33 33
34extern "C" 34extern "C"
@@ -53,7 +53,7 @@ BOOL WINAPI DllMain(
53 { 53 {
54 // OutputDebugStringA("7z.dll DLL_PROCESS_ATTACH"); 54 // OutputDebugStringA("7z.dll DLL_PROCESS_ATTACH");
55 g_hInstance = (HINSTANCE)hInstance; 55 g_hInstance = (HINSTANCE)hInstance;
56 NT_CHECK; 56 NT_CHECK
57 } 57 }
58 /* 58 /*
59 if (dwReason == DLL_PROCESS_DETACH) 59 if (dwReason == DLL_PROCESS_DETACH)
@@ -80,7 +80,7 @@ static __attribute__((constructor)) void Init_ForceToUTF8()
80#endif // _WIN32 80#endif // _WIN32
81 81
82 82
83DEFINE_GUID(CLSID_CArchiveHandler, 83Z7_DEFINE_GUID(CLSID_CArchiveHandler,
84 k_7zip_GUID_Data1, 84 k_7zip_GUID_Data1,
85 k_7zip_GUID_Data2, 85 k_7zip_GUID_Data2,
86 k_7zip_GUID_Data3_Common, 86 k_7zip_GUID_Data3_Common,
@@ -94,7 +94,7 @@ STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject);
94STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject) 94STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject)
95{ 95{
96 // COM_TRY_BEGIN 96 // COM_TRY_BEGIN
97 *outObject = 0; 97 *outObject = NULL;
98 if (*iid == IID_ICompressCoder || 98 if (*iid == IID_ICompressCoder ||
99 *iid == IID_ICompressCoder2 || 99 *iid == IID_ICompressCoder2 ||
100 *iid == IID_ICompressFilter) 100 *iid == IID_ICompressFilter)
@@ -108,7 +108,7 @@ STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject)
108STDAPI SetLargePageMode(); 108STDAPI SetLargePageMode();
109STDAPI SetLargePageMode() 109STDAPI SetLargePageMode()
110{ 110{
111 #if defined(_7ZIP_LARGE_PAGES) 111 #if defined(Z7_LARGE_PAGES)
112 #ifdef _WIN32 112 #ifdef _WIN32
113 SetLargePageSize(); 113 SetLargePageSize();
114 #endif 114 #endif
@@ -143,7 +143,7 @@ STDAPI SetProperty(Int32 id, const PROPVARIANT *value)
143} 143}
144*/ 144*/
145 145
146#ifdef EXTERNAL_CODECS 146#ifdef Z7_EXTERNAL_CODECS
147 147
148CExternalCodecs g_ExternalCodecs; 148CExternalCodecs g_ExternalCodecs;
149 149
diff --git a/CPP/7zip/Archive/DmgHandler.cpp b/CPP/7zip/Archive/DmgHandler.cpp
index e6166f1..4bcb904 100644
--- a/CPP/7zip/Archive/DmgHandler.cpp
+++ b/CPP/7zip/Archive/DmgHandler.cpp
@@ -85,7 +85,7 @@ void CChecksum::Parse(const Byte *p)
85 Type = Get32(p); 85 Type = Get32(p);
86 NumBits = Get32(p + 4); 86 NumBits = Get32(p + 4);
87 memcpy(Data, p + 8, kChecksumSize_Max); 87 memcpy(Data, p + 8, kChecksumSize_Max);
88}; 88}
89 89
90struct CFile 90struct CFile
91{ 91{
@@ -132,11 +132,9 @@ struct CForkPair
132}; 132};
133 133
134 134
135class CHandler: 135Z7_CLASS_IMP_CHandler_IInArchive_1(
136 public IInArchive, 136 IInArchiveGetStream
137 public IInArchiveGetStream, 137)
138 public CMyUnknownImp
139{
140 CMyComPtr<IInStream> _inStream; 138 CMyComPtr<IInStream> _inStream;
141 CObjectVector<CFile> _files; 139 CObjectVector<CFile> _files;
142 bool _masterCrcError; 140 bool _masterCrcError;
@@ -156,10 +154,6 @@ class CHandler:
156 bool ParseBlob(const CByteBuffer &data); 154 bool ParseBlob(const CByteBuffer &data);
157 HRESULT Open2(IInStream *stream); 155 HRESULT Open2(IInStream *stream);
158 HRESULT Extract(IInStream *stream); 156 HRESULT Extract(IInStream *stream);
159public:
160 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
161 INTERFACE_IInArchive(;)
162 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
163}; 157};
164 158
165// that limit can be increased, if there are such dmg files 159// that limit can be increased, if there are such dmg files
@@ -248,7 +242,7 @@ static const CAppleName k_Names[] =
248 { false, NULL, "Patches" } 242 { false, NULL, "Patches" }
249}; 243};
250 244
251static const unsigned kNumAppleNames = ARRAY_SIZE(k_Names); 245static const unsigned kNumAppleNames = Z7_ARRAY_SIZE(k_Names);
252 246
253static const Byte kProps[] = 247static const Byte kProps[] =
254{ 248{
@@ -270,7 +264,7 @@ static const Byte kArcProps[] =
270 kpidComment 264 kpidComment
271}; 265};
272 266
273STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 267Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
274{ 268{
275 COM_TRY_BEGIN 269 COM_TRY_BEGIN
276 NWindows::NCOM::CPropVariant prop; 270 NWindows::NCOM::CPropVariant prop;
@@ -313,19 +307,19 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
313 if (appleName.IsFs) 307 if (appleName.IsFs)
314 { 308 {
315 numFS++; 309 numFS++;
316 mainIndex = i; 310 mainIndex = (int)i;
317 } 311 }
318 break; 312 break;
319 } 313 }
320 } 314 }
321 if (n == kNumAppleNames) 315 if (n == kNumAppleNames)
322 { 316 {
323 mainIndex = i; 317 mainIndex = (int)i;
324 numUnknown++; 318 numUnknown++;
325 } 319 }
326 } 320 }
327 if (numFS + numUnknown == 1) 321 if (numFS + numUnknown == 1)
328 prop = (UInt32)mainIndex; 322 prop = (UInt32)(Int32)mainIndex;
329 break; 323 break;
330 } 324 }
331 case kpidWarning: 325 case kpidWarning:
@@ -448,7 +442,7 @@ static int FindKeyPair(const CXmlItem &item, const char *key, const char *nextTa
448 { 442 {
449 const CXmlItem &si = item.SubItems[i]; 443 const CXmlItem &si = item.SubItems[i];
450 if (si.IsTagged("key") && si.GetSubString() == key && item.SubItems[i + 1].IsTagged(nextTag)) 444 if (si.IsTagged("key") && si.GetSubString() == key && item.SubItems[i + 1].IsTagged(nextTag))
451 return i + 1; 445 return (int)(i + 1);
452 } 446 }
453 return -1; 447 return -1;
454} 448}
@@ -467,7 +461,7 @@ static const Byte k_Signature[] = { 'k','o','l','y', 0, 0, 0, 4, 0, 0, 2, 0 };
467 461
468static inline bool IsKoly(const Byte *p) 462static inline bool IsKoly(const Byte *p)
469{ 463{
470 return memcmp(p, k_Signature, ARRAY_SIZE(k_Signature)) == 0; 464 return memcmp(p, k_Signature, Z7_ARRAY_SIZE(k_Signature)) == 0;
471 /* 465 /*
472 if (Get32(p) != 0x6B6F6C79) // "koly" signature 466 if (Get32(p) != 0x6B6F6C79) // "koly" signature
473 return false; 467 return false;
@@ -486,7 +480,7 @@ HRESULT CHandler::ReadData(IInStream *stream, const CForkPair &pair, CByteBuffer
486 if (size != pair.Len) 480 if (size != pair.Len)
487 return E_OUTOFMEMORY; 481 return E_OUTOFMEMORY;
488 buf.Alloc(size); 482 buf.Alloc(size);
489 RINOK(stream->Seek(_startPos + pair.Offset, STREAM_SEEK_SET, NULL)); 483 RINOK(InStream_SeekSet(stream, _startPos + pair.Offset))
490 return ReadStream_FALSE(stream, buf, size); 484 return ReadStream_FALSE(stream, buf, size);
491} 485}
492 486
@@ -564,14 +558,11 @@ HRESULT CHandler::Open2(IInStream *stream)
564 */ 558 */
565 559
566 _dataStartOffset = 0; 560 _dataStartOffset = 0;
567 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_startPos)); 561 UInt64 fileSize;
568 562 RINOK(InStream_GetPos_GetSize(stream, _startPos, fileSize))
569 UInt64 fileSize = 0;
570 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize));
571 RINOK(stream->Seek(_startPos, STREAM_SEEK_SET, NULL));
572 563
573 Byte buf[HEADER_SIZE]; 564 Byte buf[HEADER_SIZE];
574 RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)); 565 RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE))
575 566
576 UInt64 headerPos; 567 UInt64 headerPos;
577 bool startKolyMode = false; 568 bool startKolyMode = false;
@@ -595,8 +586,8 @@ HRESULT CHandler::Open2(IInStream *stream)
595 if (headerPos < HEADER_SIZE) 586 if (headerPos < HEADER_SIZE)
596 return S_FALSE; 587 return S_FALSE;
597 headerPos -= HEADER_SIZE; 588 headerPos -= HEADER_SIZE;
598 RINOK(stream->Seek(headerPos, STREAM_SEEK_SET, NULL)); 589 RINOK(InStream_SeekSet(stream, headerPos))
599 RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE)); 590 RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE))
600 if (!IsKoly(buf)) 591 if (!IsKoly(buf))
601 return S_FALSE; 592 return S_FALSE;
602 } 593 }
@@ -674,7 +665,7 @@ HRESULT CHandler::Open2(IInStream *stream)
674 #else 665 #else
675 CByteBuffer blobBuf; 666 CByteBuffer blobBuf;
676 #endif 667 #endif
677 RINOK(ReadData(stream, blobPair, blobBuf)); 668 RINOK(ReadData(stream, blobPair, blobBuf))
678 if (!ParseBlob(blobBuf)) 669 if (!ParseBlob(blobBuf))
679 _headersError = true; 670 _headersError = true;
680 } 671 }
@@ -704,7 +695,7 @@ HRESULT CHandler::Open2(IInStream *stream)
704 CByteBuffer rsrcBuf; 695 CByteBuffer rsrcBuf;
705 #endif 696 #endif
706 697
707 RINOK(ReadData(stream, rsrcPair, rsrcBuf)); 698 RINOK(ReadData(stream, rsrcPair, rsrcBuf))
708 699
709 const Byte *p = rsrcBuf; 700 const Byte *p = rsrcBuf;
710 UInt32 headSize = Get32(p + 0); 701 UInt32 headSize = Get32(p + 0);
@@ -803,7 +794,7 @@ HRESULT CHandler::Open2(IInStream *stream)
803 { 794 {
804 CFile &file = _files.AddNew(); 795 CFile &file = _files.AddNew();
805 file.Name = name; 796 file.Name = name;
806 RINOK(file.Parse(pBlock + 4, blockSize)); 797 RINOK(file.Parse(pBlock + 4, blockSize))
807 } 798 }
808 799
809 #ifdef DMG_SHOW_RAW 800 #ifdef DMG_SHOW_RAW
@@ -844,12 +835,12 @@ HRESULT CHandler::Open2(IInStream *stream)
844 if (size != xmlPair.Len) 835 if (size != xmlPair.Len)
845 return S_FALSE; 836 return S_FALSE;
846 837
847 RINOK(stream->Seek(_startPos + xmlPair.Offset, STREAM_SEEK_SET, NULL)); 838 RINOK(InStream_SeekSet(stream, _startPos + xmlPair.Offset))
848 839
849 CXml xml; 840 CXml xml;
850 { 841 {
851 CObjArray<char> xmlStr(size + 1); 842 CObjArray<char> xmlStr(size + 1);
852 RINOK(ReadStream_FALSE(stream, xmlStr, size)); 843 RINOK(ReadStream_FALSE(stream, xmlStr, size))
853 xmlStr[size] = 0; 844 xmlStr[size] = 0;
854 // if (strlen(xmlStr) != size) return S_FALSE; 845 // if (strlen(xmlStr) != size) return S_FALSE;
855 if (!xml.Parse(xmlStr)) 846 if (!xml.Parse(xmlStr))
@@ -916,7 +907,7 @@ HRESULT CHandler::Open2(IInStream *stream)
916 if (name) 907 if (name)
917 file.Name = *name; 908 file.Name = *name;
918 } 909 }
919 RINOK(file.Parse(rawBuf, destLen)); 910 RINOK(file.Parse(rawBuf, destLen))
920 } 911 }
921 } 912 }
922 913
@@ -941,9 +932,9 @@ HRESULT CHandler::Open2(IInStream *stream)
941 return S_OK; 932 return S_OK;
942} 933}
943 934
944STDMETHODIMP CHandler::Open(IInStream *stream, 935Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
945 const UInt64 * /* maxCheckStartPosition */, 936 const UInt64 * /* maxCheckStartPosition */,
946 IArchiveOpenCallback * /* openArchiveCallback */) 937 IArchiveOpenCallback * /* openArchiveCallback */))
947{ 938{
948 COM_TRY_BEGIN 939 COM_TRY_BEGIN
949 { 940 {
@@ -956,7 +947,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
956 COM_TRY_END 947 COM_TRY_END
957} 948}
958 949
959STDMETHODIMP CHandler::Close() 950Z7_COM7F_IMF(CHandler::Close())
960{ 951{
961 _phySize = 0; 952 _phySize = 0;
962 _inStream.Release(); 953 _inStream.Release();
@@ -970,7 +961,7 @@ STDMETHODIMP CHandler::Close()
970 return S_OK; 961 return S_OK;
971} 962}
972 963
973STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 964Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
974{ 965{
975 *numItems = _files.Size() 966 *numItems = _files.Size()
976 #ifdef DMG_SHOW_RAW 967 #ifdef DMG_SHOW_RAW
@@ -984,7 +975,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
984#define RAW_PREFIX "raw" STRING_PATH_SEPARATOR 975#define RAW_PREFIX "raw" STRING_PATH_SEPARATOR
985#endif 976#endif
986 977
987STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 978Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
988{ 979{
989 COM_TRY_BEGIN 980 COM_TRY_BEGIN
990 NWindows::NCOM::CPropVariant prop; 981 NWindows::NCOM::CPropVariant prop;
@@ -1054,7 +1045,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1054 if (pos1 >= 0) 1045 if (pos1 >= 0)
1055 { 1046 {
1056 pos1++; 1047 pos1++;
1057 int pos2 = item.Name.Find(')', pos1); 1048 const int pos2 = item.Name.Find(')', pos1);
1058 if (pos2 >= 0) 1049 if (pos2 >= 0)
1059 { 1050 {
1060 subName.SetFrom(item.Name.Ptr(pos1), pos2 - pos1); 1051 subName.SetFrom(item.Name.Ptr(pos1), pos2 - pos1);
@@ -1082,7 +1073,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1082 } 1073 }
1083 UString name2; 1074 UString name2;
1084 ConvertUTF8ToUnicode(subName, name2); 1075 ConvertUTF8ToUnicode(subName, name2);
1085 name += '.'; 1076 name.Add_Dot();
1086 name += name2; 1077 name += name2;
1087 } 1078 }
1088 else 1079 else
@@ -1111,10 +1102,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1111 COM_TRY_END 1102 COM_TRY_END
1112} 1103}
1113 1104
1114class CAdcDecoder: 1105
1115 public ICompressCoder, 1106Z7_CLASS_IMP_NOQIB_1(
1116 public CMyUnknownImp 1107 CAdcDecoder
1117{ 1108 , ICompressCoder
1109)
1118 CLzOutWindow m_OutWindowStream; 1110 CLzOutWindow m_OutWindowStream;
1119 CInBuffer m_InStream; 1111 CInBuffer m_InStream;
1120 1112
@@ -1126,7 +1118,7 @@ class CAdcDecoder:
1126 } 1118 }
1127 */ 1119 */
1128 1120
1129 class CCoderReleaser 1121 class CCoderReleaser Z7_final
1130 { 1122 {
1131 CAdcDecoder *m_Coder; 1123 CAdcDecoder *m_Coder;
1132 public: 1124 public:
@@ -1142,18 +1134,12 @@ class CAdcDecoder:
1142 friend class CCoderReleaser; 1134 friend class CCoderReleaser;
1143 1135
1144public: 1136public:
1145 MY_UNKNOWN_IMP 1137 HRESULT CodeReal(ISequentialInStream *inStream,
1146
1147 STDMETHOD(CodeReal)(ISequentialInStream *inStream,
1148 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
1149 ICompressProgressInfo *progress);
1150
1151 STDMETHOD(Code)(ISequentialInStream *inStream,
1152 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, 1138 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
1153 ICompressProgressInfo *progress); 1139 ICompressProgressInfo *progress);
1154}; 1140};
1155 1141
1156STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream, 1142HRESULT CAdcDecoder::CodeReal(ISequentialInStream *inStream,
1157 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, 1143 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
1158 ICompressProgressInfo *progress) 1144 ICompressProgressInfo *progress)
1159{ 1145{
@@ -1178,7 +1164,7 @@ STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream,
1178 if (pos > nextLimit && progress) 1164 if (pos > nextLimit && progress)
1179 { 1165 {
1180 UInt64 packSize = m_InStream.GetProcessedSize(); 1166 UInt64 packSize = m_InStream.GetProcessedSize();
1181 RINOK(progress->SetRatioInfo(&packSize, &pos)); 1167 RINOK(progress->SetRatioInfo(&packSize, &pos))
1182 nextLimit += kStep; 1168 nextLimit += kStep;
1183 } 1169 }
1184 Byte b; 1170 Byte b;
@@ -1231,9 +1217,9 @@ STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream,
1231 return m_OutWindowStream.Flush(); 1217 return m_OutWindowStream.Flush();
1232} 1218}
1233 1219
1234STDMETHODIMP CAdcDecoder::Code(ISequentialInStream *inStream, 1220Z7_COM7F_IMF(CAdcDecoder::Code(ISequentialInStream *inStream,
1235 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, 1221 ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
1236 ICompressProgressInfo *progress) 1222 ICompressProgressInfo *progress))
1237{ 1223{
1238 try { return CodeReal(inStream, outStream, inSize, outSize, progress);} 1224 try { return CodeReal(inStream, outStream, inSize, outSize, progress);}
1239 catch(const CInBufferException &e) { return e.ErrorCode; } 1225 catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -1247,11 +1233,11 @@ STDMETHODIMP CAdcDecoder::Code(ISequentialInStream *inStream,
1247 1233
1248 1234
1249 1235
1250STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1236Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1251 Int32 testMode, IArchiveExtractCallback *extractCallback) 1237 Int32 testMode, IArchiveExtractCallback *extractCallback))
1252{ 1238{
1253 COM_TRY_BEGIN 1239 COM_TRY_BEGIN
1254 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1240 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1255 if (allFilesMode) 1241 if (allFilesMode)
1256 numItems = _files.Size(); 1242 numItems = _files.Size();
1257 if (numItems == 0) 1243 if (numItems == 0)
@@ -1309,17 +1295,17 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1309 lps->OutSize = currentUnpTotal; 1295 lps->OutSize = currentUnpTotal;
1310 currentPackSize = 0; 1296 currentPackSize = 0;
1311 currentUnpSize = 0; 1297 currentUnpSize = 0;
1312 RINOK(lps->SetCur()); 1298 RINOK(lps->SetCur())
1313 CMyComPtr<ISequentialOutStream> realOutStream; 1299 CMyComPtr<ISequentialOutStream> realOutStream;
1314 Int32 askMode = testMode ? 1300 const Int32 askMode = testMode ?
1315 NExtract::NAskMode::kTest : 1301 NExtract::NAskMode::kTest :
1316 NExtract::NAskMode::kExtract; 1302 NExtract::NAskMode::kExtract;
1317 UInt32 index = allFilesMode ? i : indices[i]; 1303 const UInt32 index = allFilesMode ? i : indices[i];
1318 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1304 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1319 1305
1320 if (!testMode && !realOutStream) 1306 if (!testMode && !realOutStream)
1321 continue; 1307 continue;
1322 RINOK(extractCallback->PrepareOperation(askMode)); 1308 RINOK(extractCallback->PrepareOperation(askMode))
1323 1309
1324 1310
1325 COutStreamWithCRC *outCrcStreamSpec = new COutStreamWithCRC; 1311 COutStreamWithCRC *outCrcStreamSpec = new COutStreamWithCRC;
@@ -1359,7 +1345,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1359 { 1345 {
1360 lps->InSize = currentPackTotal + packPos; 1346 lps->InSize = currentPackTotal + packPos;
1361 lps->OutSize = currentUnpTotal + unpPos; 1347 lps->OutSize = currentUnpTotal + unpPos;
1362 RINOK(lps->SetCur()); 1348 RINOK(lps->SetCur())
1363 1349
1364 const CBlock &block = item.Blocks[j]; 1350 const CBlock &block = item.Blocks[j];
1365 if (!block.ThereAreDataInBlock()) 1351 if (!block.ThereAreDataInBlock())
@@ -1372,7 +1358,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1372 break; 1358 break;
1373 } 1359 }
1374 1360
1375 RINOK(_inStream->Seek(_startPos + _dataStartOffset + item.StartPos + block.PackPos, STREAM_SEEK_SET, NULL)); 1361 RINOK(InStream_SeekSet(_inStream, _startPos + _dataStartOffset + item.StartPos + block.PackPos))
1376 streamSpec->Init(block.PackSize); 1362 streamSpec->Init(block.PackSize);
1377 bool realMethod = true; 1363 bool realMethod = true;
1378 outStreamSpec->Init(block.UnpSize); 1364 outStreamSpec->Init(block.UnpSize);
@@ -1453,7 +1439,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1453 { 1439 {
1454 UInt64 rem = outStreamSpec->GetRem(); 1440 UInt64 rem = outStreamSpec->GetRem();
1455 UInt32 size = (UInt32)MyMin(rem, (UInt64)kZeroBufSize); 1441 UInt32 size = (UInt32)MyMin(rem, (UInt64)kZeroBufSize);
1456 RINOK(WriteStream(outStream, zeroBuf, size)); 1442 RINOK(WriteStream(outStream, zeroBuf, size))
1457 } 1443 }
1458 } 1444 }
1459 } 1445 }
@@ -1466,7 +1452,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1466 } 1452 }
1467 } 1453 }
1468 outStream.Release(); 1454 outStream.Release();
1469 RINOK(extractCallback->SetOperationResult(opRes)); 1455 RINOK(extractCallback->SetOperationResult(opRes))
1470 } 1456 }
1471 1457
1472 return S_OK; 1458 return S_OK;
@@ -1480,10 +1466,13 @@ struct CChunk
1480 CByteBuffer Buf; 1466 CByteBuffer Buf;
1481}; 1467};
1482 1468
1483class CInStream: 1469
1484 public IInStream, 1470Z7_CLASS_IMP_COM_1(
1485 public CMyUnknownImp 1471 CInStream
1486{ 1472 , IInStream
1473)
1474 Z7_IFACE_COM7_IMP(ISequentialInStream)
1475
1487 UInt64 _virtPos; 1476 UInt64 _virtPos;
1488 int _latestChunk; 1477 int _latestChunk;
1489 int _latestBlock; 1478 int _latestBlock;
@@ -1530,11 +1519,6 @@ public:
1530 outStream = outStreamSpec; 1519 outStream = outStreamSpec;
1531 return S_OK; 1520 return S_OK;
1532 } 1521 }
1533
1534 MY_UNKNOWN_IMP1(IInStream)
1535
1536 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
1537 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
1538}; 1522};
1539 1523
1540 1524
@@ -1553,7 +1537,7 @@ static unsigned FindBlock(const CRecordVector<CBlock> &blocks, UInt64 pos)
1553 } 1537 }
1554} 1538}
1555 1539
1556STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 1540Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
1557{ 1541{
1558 COM_TRY_BEGIN 1542 COM_TRY_BEGIN
1559 1543
@@ -1571,7 +1555,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1571 1555
1572 if (_latestBlock >= 0) 1556 if (_latestBlock >= 0)
1573 { 1557 {
1574 const CBlock &block = File->Blocks[_latestBlock]; 1558 const CBlock &block = File->Blocks[(unsigned)_latestBlock];
1575 if (_virtPos < block.UnpPos || (_virtPos - block.UnpPos) >= block.UnpSize) 1559 if (_virtPos < block.UnpPos || (_virtPos - block.UnpPos) >= block.UnpSize)
1576 _latestBlock = -1; 1560 _latestBlock = -1;
1577 } 1561 }
@@ -1590,7 +1574,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1590 break; 1574 break;
1591 1575
1592 if (i != _chunks.Size()) 1576 if (i != _chunks.Size())
1593 _latestChunk = i; 1577 _latestChunk = (int)i;
1594 else 1578 else
1595 { 1579 {
1596 const unsigned kNumChunksMax = 128; 1580 const unsigned kNumChunksMax = 128;
@@ -1620,7 +1604,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1620 1604
1621 outStreamSpec->Init(chunk.Buf, (size_t)block.UnpSize); 1605 outStreamSpec->Init(chunk.Buf, (size_t)block.UnpSize);
1622 1606
1623 RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos, STREAM_SEEK_SET, NULL)); 1607 RINOK(InStream_SeekSet(Stream, _startPos + File->StartPos + block.PackPos))
1624 1608
1625 limitedStreamSpec->Init(block.PackSize); 1609 limitedStreamSpec->Init(block.PackSize);
1626 HRESULT res = S_OK; 1610 HRESULT res = S_OK;
@@ -1681,17 +1665,17 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1681 return res; 1665 return res;
1682 if (block.Type != METHOD_COPY && outStreamSpec->GetPos() != block.UnpSize) 1666 if (block.Type != METHOD_COPY && outStreamSpec->GetPos() != block.UnpSize)
1683 return E_FAIL; 1667 return E_FAIL;
1684 chunk.BlockIndex = blockIndex; 1668 chunk.BlockIndex = (int)blockIndex;
1685 _latestChunk = chunkIndex; 1669 _latestChunk = (int)chunkIndex;
1686 } 1670 }
1687 1671
1688 _chunks[_latestChunk].AccessMark = _accessMark++; 1672 _chunks[_latestChunk].AccessMark = _accessMark++;
1689 } 1673 }
1690 1674
1691 _latestBlock = blockIndex; 1675 _latestBlock = (int)blockIndex;
1692 } 1676 }
1693 1677
1694 const CBlock &block = File->Blocks[_latestBlock]; 1678 const CBlock &block = File->Blocks[(unsigned)_latestBlock];
1695 const UInt64 offset = _virtPos - block.UnpPos; 1679 const UInt64 offset = _virtPos - block.UnpPos;
1696 const UInt64 rem = block.UnpSize - offset; 1680 const UInt64 rem = block.UnpSize - offset;
1697 if (size > rem) 1681 if (size > rem)
@@ -1701,7 +1685,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1701 1685
1702 if (block.Type == METHOD_COPY) 1686 if (block.Type == METHOD_COPY)
1703 { 1687 {
1704 RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos + offset, STREAM_SEEK_SET, NULL)); 1688 RINOK(InStream_SeekSet(Stream, _startPos + File->StartPos + block.PackPos + offset))
1705 res = Stream->Read(data, size, &size); 1689 res = Stream->Read(data, size, &size);
1706 } 1690 }
1707 else if (block.IsZeroMethod()) 1691 else if (block.IsZeroMethod())
@@ -1717,7 +1701,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1717 COM_TRY_END 1701 COM_TRY_END
1718} 1702}
1719 1703
1720STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 1704Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
1721{ 1705{
1722 switch (seekOrigin) 1706 switch (seekOrigin)
1723 { 1707 {
@@ -1728,13 +1712,13 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio
1728 } 1712 }
1729 if (offset < 0) 1713 if (offset < 0)
1730 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 1714 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
1731 _virtPos = offset; 1715 _virtPos = (UInt64)offset;
1732 if (newPosition) 1716 if (newPosition)
1733 *newPosition = offset; 1717 *newPosition = (UInt64)offset;
1734 return S_OK; 1718 return S_OK;
1735} 1719}
1736 1720
1737STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 1721Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
1738{ 1722{
1739 COM_TRY_BEGIN 1723 COM_TRY_BEGIN
1740 1724
@@ -1769,7 +1753,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
1769 1753
1770 spec->Stream = _inStream; 1754 spec->Stream = _inStream;
1771 spec->Size = spec->File->Size; 1755 spec->Size = spec->File->Size;
1772 RINOK(spec->InitAndSeek(_startPos + _dataStartOffset)); 1756 RINOK(spec->InitAndSeek(_startPos + _dataStartOffset))
1773 *stream = specStream.Detach(); 1757 *stream = specStream.Detach();
1774 return S_OK; 1758 return S_OK;
1775 1759
@@ -1777,7 +1761,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
1777} 1761}
1778 1762
1779REGISTER_ARC_I( 1763REGISTER_ARC_I(
1780 "Dmg", "dmg", 0, 0xE4, 1764 "Dmg", "dmg", NULL, 0xE4,
1781 k_Signature, 1765 k_Signature,
1782 0, 1766 0,
1783 NArcInfoFlags::kBackwardOpen | 1767 NArcInfoFlags::kBackwardOpen |
diff --git a/CPP/7zip/Archive/ElfHandler.cpp b/CPP/7zip/Archive/ElfHandler.cpp
index efcde95..7e1facc 100644
--- a/CPP/7zip/Archive/ElfHandler.cpp
+++ b/CPP/7zip/Archive/ElfHandler.cpp
@@ -156,18 +156,22 @@ bool CHeader::Parse(const Byte *p)
156 156
157#define PT_PHDR 6 157#define PT_PHDR 6
158 158
159static const char * const g_SegnmentTypes[] = 159static const CUInt32PCharPair g_SegnmentTypes[] =
160{ 160{
161 "Unused" 161 { 0, "Unused" },
162 , "Loadable segment" 162 { 1, "Loadable segment" },
163 , "Dynamic linking tables" 163 { 2, "Dynamic linking tables" },
164 , "Program interpreter path name" 164 { 3, "Program interpreter path name" },
165 , "Note section" 165 { 4, "Note section" },
166 , "SHLIB" 166 { 5, "SHLIB" },
167 , "Program header table" 167 { 6, "Program header table" },
168 , "TLS" 168 { 7, "TLS" },
169 { 0x6474e550, "GNU_EH_FRAME" },
170 { 0x6474e551, "GNU_STACK" },
171 { 0x6474e552, "GNU_RELRO" }
169}; 172};
170 173
174
171static const char * const g_SegmentFlags[] = 175static const char * const g_SegmentFlags[] =
172{ 176{
173 "Execute" 177 "Execute"
@@ -271,6 +275,7 @@ static const CUInt32PCharPair g_SectTypes[] =
271 { 16, "PREINIT_ARRAY" }, 275 { 16, "PREINIT_ARRAY" },
272 { 17, "GROUP" }, 276 { 17, "GROUP" },
273 { 18, "SYMTAB_SHNDX" }, 277 { 18, "SYMTAB_SHNDX" },
278
274 { 0x6ffffff5, "GNU_ATTRIBUTES" }, 279 { 0x6ffffff5, "GNU_ATTRIBUTES" },
275 { 0x6ffffff6, "GNU_HASH" }, 280 { 0x6ffffff6, "GNU_HASH" },
276 { 0x6ffffffd, "GNU_verdef" }, 281 { 0x6ffffffd, "GNU_verdef" },
@@ -654,11 +659,9 @@ static const char * const g_Types[] =
654 659
655 660
656 661
657class CHandler: 662Z7_CLASS_IMP_CHandler_IInArchive_1(
658 public IInArchive, 663 IArchiveAllowTail
659 public IArchiveAllowTail, 664)
660 public CMyUnknownImp
661{
662 CRecordVector<CSegment> _segments; 665 CRecordVector<CSegment> _segments;
663 CRecordVector<CSection> _sections; 666 CRecordVector<CSection> _sections;
664 CByteBuffer _namesData; 667 CByteBuffer _namesData;
@@ -671,10 +674,6 @@ class CHandler:
671 void GetSectionName(UInt32 index, NCOM::CPropVariant &prop, bool showNULL) const; 674 void GetSectionName(UInt32 index, NCOM::CPropVariant &prop, bool showNULL) const;
672 HRESULT Open2(IInStream *stream); 675 HRESULT Open2(IInStream *stream);
673public: 676public:
674 MY_UNKNOWN_IMP2(IInArchive, IArchiveAllowTail)
675 INTERFACE_IInArchive(;)
676 STDMETHOD(AllowTail)(Int32 allowTail);
677
678 CHandler(): _allowTail(false) {} 677 CHandler(): _allowTail(false) {}
679}; 678};
680 679
@@ -683,7 +682,7 @@ void CHandler::GetSectionName(UInt32 index, NCOM::CPropVariant &prop, bool showN
683 if (index >= _sections.Size()) 682 if (index >= _sections.Size())
684 return; 683 return;
685 const CSection &section = _sections[index]; 684 const CSection &section = _sections[index];
686 UInt32 offset = section.Name; 685 const UInt32 offset = section.Name;
687 if (index == SHN_UNDEF /* && section.Type == SHT_NULL && offset == 0 */) 686 if (index == SHN_UNDEF /* && section.Type == SHT_NULL && offset == 0 */)
688 { 687 {
689 if (showNULL) 688 if (showNULL)
@@ -732,7 +731,7 @@ static const CStatProp kProps[] =
732IMP_IInArchive_Props_WITH_NAME 731IMP_IInArchive_Props_WITH_NAME
733IMP_IInArchive_ArcProps 732IMP_IInArchive_ArcProps
734 733
735STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 734Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
736{ 735{
737 COM_TRY_BEGIN 736 COM_TRY_BEGIN
738 NCOM::CPropVariant prop; 737 NCOM::CPropVariant prop;
@@ -747,27 +746,27 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
747 case kpidCpu: 746 case kpidCpu:
748 { 747 {
749 AString s; 748 AString s;
750 if (_header.Machine < ARRAY_SIZE(g_Machines)) 749 if (_header.Machine < Z7_ARRAY_SIZE(g_Machines))
751 { 750 {
752 const char *name = g_Machines[_header.Machine]; 751 const char *name = g_Machines[_header.Machine];
753 if (name) 752 if (name)
754 s = name; 753 s = name;
755 } 754 }
756 if (s.IsEmpty()) 755 if (s.IsEmpty())
757 s = TypePairToString(g_MachinePairs, ARRAY_SIZE(g_MachinePairs), _header.Machine); 756 s = TypePairToString(g_MachinePairs, Z7_ARRAY_SIZE(g_MachinePairs), _header.Machine);
758 UInt32 flags = _header.Flags; 757 UInt32 flags = _header.Flags;
759 if (flags != 0) 758 if (flags != 0)
760 { 759 {
761 s.Add_Space(); 760 s.Add_Space();
762 if (_header.Machine == k_Machine_ARM) 761 if (_header.Machine == k_Machine_ARM)
763 { 762 {
764 s += FlagsToString(g_ARM_Flags, ARRAY_SIZE(g_ARM_Flags), flags & (((UInt32)1 << 24) - 1)); 763 s += FlagsToString(g_ARM_Flags, Z7_ARRAY_SIZE(g_ARM_Flags), flags & (((UInt32)1 << 24) - 1));
765 s += " ABI:"; 764 s += " ABI:";
766 s.Add_UInt32(flags >> 24); 765 s.Add_UInt32(flags >> 24);
767 } 766 }
768 else if (_header.Machine == k_Machine_MIPS) 767 else if (_header.Machine == k_Machine_MIPS)
769 { 768 {
770 UInt32 ver = flags >> 28; 769 const UInt32 ver = flags >> 28;
771 s += "v"; 770 s += "v";
772 s.Add_UInt32(ver); 771 s.Add_UInt32(ver);
773 flags &= (((UInt32)1 << 28) - 1); 772 flags &= (((UInt32)1 << 28) - 1);
@@ -781,7 +780,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
781 flags &= ~((UInt32)7 << 12); 780 flags &= ~((UInt32)7 << 12);
782 781
783 s.Add_Space(); 782 s.Add_Space();
784 s += FlagsToString(g_MIPS_Flags, ARRAY_SIZE(g_MIPS_Flags), flags); 783 s += FlagsToString(g_MIPS_Flags, Z7_ARRAY_SIZE(g_MIPS_Flags), flags);
785 } 784 }
786 else 785 else
787 { 786 {
@@ -822,7 +821,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
822 COM_TRY_END 821 COM_TRY_END
823} 822}
824 823
825STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 824Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
826{ 825{
827 COM_TRY_BEGIN 826 COM_TRY_BEGIN
828 NCOM::CPropVariant prop; 827 NCOM::CPropVariant prop;
@@ -843,7 +842,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
843 case kpidSize: 842 case kpidSize:
844 case kpidPackSize: prop = (UInt64)item.Size; break; 843 case kpidPackSize: prop = (UInt64)item.Size; break;
845 case kpidVirtualSize: prop = (UInt64)item.VSize; break; 844 case kpidVirtualSize: prop = (UInt64)item.VSize; break;
846 case kpidType: TYPE_TO_PROP(g_SegnmentTypes, item.Type, prop); break; 845 case kpidType: PAIR_TO_PROP(g_SegnmentTypes, item.Type, prop); break;
847 case kpidCharacts: FLAGS_TO_PROP(g_SegmentFlags, item.Flags, prop); break; 846 case kpidCharacts: FLAGS_TO_PROP(g_SegmentFlags, item.Flags, prop); break;
848 847
849 } 848 }
@@ -875,7 +874,7 @@ HRESULT CHandler::Open2(IInStream *stream)
875{ 874{
876 const UInt32 kStartSize = kHeaderSize64; 875 const UInt32 kStartSize = kHeaderSize64;
877 Byte h[kStartSize]; 876 Byte h[kStartSize];
878 RINOK(ReadStream_FALSE(stream, h, kStartSize)); 877 RINOK(ReadStream_FALSE(stream, h, kStartSize))
879 if (h[0] != 0x7F || h[1] != 'E' || h[2] != 'L' || h[3] != 'F') 878 if (h[0] != 0x7F || h[1] != 'E' || h[2] != 'L' || h[3] != 'F')
880 return S_FALSE; 879 return S_FALSE;
881 if (!_header.Parse(h)) 880 if (!_header.Parse(h))
@@ -894,14 +893,14 @@ HRESULT CHandler::Open2(IInStream *stream)
894 if (_header.NumSegments != 0) 893 if (_header.NumSegments != 0)
895 { 894 {
896 if (_header.ProgOffset > (UInt64)1 << 60) return S_FALSE; 895 if (_header.ProgOffset > (UInt64)1 << 60) return S_FALSE;
897 RINOK(stream->Seek(_header.ProgOffset, STREAM_SEEK_SET, NULL)); 896 RINOK(InStream_SeekSet(stream, _header.ProgOffset))
898 size_t size = (size_t)_header.SegmentEntrySize * _header.NumSegments; 897 const size_t size = (size_t)_header.SegmentEntrySize * _header.NumSegments;
899 898
900 CByteArr buf(size); 899 CByteArr buf(size);
901 900
902 RINOK(ReadStream_FALSE(stream, buf, size)); 901 RINOK(ReadStream_FALSE(stream, buf, size))
903 902
904 UInt64 total = _header.ProgOffset + size; 903 const UInt64 total = _header.ProgOffset + size;
905 if (_totalSize < total) 904 if (_totalSize < total)
906 _totalSize = total; 905 _totalSize = total;
907 906
@@ -923,12 +922,12 @@ HRESULT CHandler::Open2(IInStream *stream)
923 if (_header.NumSections != 0) 922 if (_header.NumSections != 0)
924 { 923 {
925 if (_header.SectOffset > (UInt64)1 << 60) return S_FALSE; 924 if (_header.SectOffset > (UInt64)1 << 60) return S_FALSE;
926 RINOK(stream->Seek(_header.SectOffset, STREAM_SEEK_SET, NULL)); 925 RINOK(InStream_SeekSet(stream, _header.SectOffset))
927 size_t size = (size_t)_header.SectionEntrySize * _header.NumSections; 926 size_t size = (size_t)_header.SectionEntrySize * _header.NumSections;
928 927
929 CByteArr buf(size); 928 CByteArr buf(size);
930 929
931 RINOK(ReadStream_FALSE(stream, buf, size)); 930 RINOK(ReadStream_FALSE(stream, buf, size))
932 931
933 UInt64 total = _header.SectOffset + size; 932 UInt64 total = _header.SectOffset + size;
934 if (_totalSize < total) 933 if (_totalSize < total)
@@ -957,14 +956,14 @@ HRESULT CHandler::Open2(IInStream *stream)
957 if (_header.NamesSectIndex < _sections.Size()) 956 if (_header.NamesSectIndex < _sections.Size())
958 { 957 {
959 const CSection &sect = _sections[_header.NamesSectIndex]; 958 const CSection &sect = _sections[_header.NamesSectIndex];
960 UInt64 size = sect.GetSize(); 959 const UInt64 size = sect.GetSize();
961 if (size != 0 960 if (size != 0
962 && size < ((UInt64)1 << 31) 961 && size < ((UInt64)1 << 31)
963 && (Int64)sect.Offset >= 0) 962 && (Int64)sect.Offset >= 0)
964 { 963 {
965 _namesData.Alloc((size_t)size); 964 _namesData.Alloc((size_t)size);
966 RINOK(stream->Seek(sect.Offset, STREAM_SEEK_SET, NULL)); 965 RINOK(InStream_SeekSet(stream, sect.Offset))
967 RINOK(ReadStream_FALSE(stream, _namesData, (size_t)size)); 966 RINOK(ReadStream_FALSE(stream, _namesData, (size_t)size))
968 } 967 }
969 } 968 }
970 969
@@ -979,7 +978,7 @@ HRESULT CHandler::Open2(IInStream *stream)
979 if (!_allowTail) 978 if (!_allowTail)
980 { 979 {
981 UInt64 fileSize; 980 UInt64 fileSize;
982 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); 981 RINOK(InStream_GetSize_SeekToEnd(stream, fileSize))
983 if (fileSize > _totalSize) 982 if (fileSize > _totalSize)
984 return S_FALSE; 983 return S_FALSE;
985 } 984 }
@@ -987,19 +986,19 @@ HRESULT CHandler::Open2(IInStream *stream)
987 return S_OK; 986 return S_OK;
988} 987}
989 988
990STDMETHODIMP CHandler::Open(IInStream *inStream, 989Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
991 const UInt64 * /* maxCheckStartPosition */, 990 const UInt64 * /* maxCheckStartPosition */,
992 IArchiveOpenCallback * /* openArchiveCallback */) 991 IArchiveOpenCallback * /* openArchiveCallback */))
993{ 992{
994 COM_TRY_BEGIN 993 COM_TRY_BEGIN
995 Close(); 994 Close();
996 RINOK(Open2(inStream)); 995 RINOK(Open2(inStream))
997 _inStream = inStream; 996 _inStream = inStream;
998 return S_OK; 997 return S_OK;
999 COM_TRY_END 998 COM_TRY_END
1000} 999}
1001 1000
1002STDMETHODIMP CHandler::Close() 1001Z7_COM7F_IMF(CHandler::Close())
1003{ 1002{
1004 _totalSize = 0; 1003 _totalSize = 0;
1005 _headersError = false; 1004 _headersError = false;
@@ -1011,17 +1010,17 @@ STDMETHODIMP CHandler::Close()
1011 return S_OK; 1010 return S_OK;
1012} 1011}
1013 1012
1014STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1013Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1015{ 1014{
1016 *numItems = _segments.Size() + _sections.Size(); 1015 *numItems = _segments.Size() + _sections.Size();
1017 return S_OK; 1016 return S_OK;
1018} 1017}
1019 1018
1020STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1019Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1021 Int32 testMode, IArchiveExtractCallback *extractCallback) 1020 Int32 testMode, IArchiveExtractCallback *extractCallback))
1022{ 1021{
1023 COM_TRY_BEGIN 1022 COM_TRY_BEGIN
1024 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1023 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1025 if (allFilesMode) 1024 if (allFilesMode)
1026 numItems = _segments.Size() + _sections.Size(); 1025 numItems = _segments.Size() + _sections.Size();
1027 if (numItems == 0) 1026 if (numItems == 0)
@@ -1030,7 +1029,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1030 UInt32 i; 1029 UInt32 i;
1031 for (i = 0; i < numItems; i++) 1030 for (i = 0; i < numItems; i++)
1032 { 1031 {
1033 UInt32 index = allFilesMode ? i : indices[i]; 1032 const UInt32 index = allFilesMode ? i : indices[i];
1034 totalSize += (index < _segments.Size()) ? 1033 totalSize += (index < _segments.Size()) ?
1035 _segments[index].Size : 1034 _segments[index].Size :
1036 _sections[index - _segments.Size()].GetSize(); 1035 _sections[index - _segments.Size()].GetSize();
@@ -1054,11 +1053,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1054 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) 1053 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
1055 { 1054 {
1056 lps->InSize = lps->OutSize = currentTotalSize; 1055 lps->InSize = lps->OutSize = currentTotalSize;
1057 RINOK(lps->SetCur()); 1056 RINOK(lps->SetCur())
1058 Int32 askMode = testMode ? 1057 const Int32 askMode = testMode ?
1059 NExtract::NAskMode::kTest : 1058 NExtract::NAskMode::kTest :
1060 NExtract::NAskMode::kExtract; 1059 NExtract::NAskMode::kExtract;
1061 UInt32 index = allFilesMode ? i : indices[i]; 1060 const UInt32 index = allFilesMode ? i : indices[i];
1062 UInt64 offset; 1061 UInt64 offset;
1063 if (index < _segments.Size()) 1062 if (index < _segments.Size())
1064 { 1063 {
@@ -1074,24 +1073,24 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1074 } 1073 }
1075 1074
1076 CMyComPtr<ISequentialOutStream> outStream; 1075 CMyComPtr<ISequentialOutStream> outStream;
1077 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 1076 RINOK(extractCallback->GetStream(index, &outStream, askMode))
1078 if (!testMode && !outStream) 1077 if (!testMode && !outStream)
1079 continue; 1078 continue;
1080 1079
1081 RINOK(extractCallback->PrepareOperation(askMode)); 1080 RINOK(extractCallback->PrepareOperation(askMode))
1082 RINOK(_inStream->Seek(offset, STREAM_SEEK_SET, NULL)); 1081 RINOK(InStream_SeekSet(_inStream, offset))
1083 streamSpec->Init(currentItemSize); 1082 streamSpec->Init(currentItemSize);
1084 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 1083 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
1085 outStream.Release(); 1084 outStream.Release();
1086 RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ? 1085 RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ?
1087 NExtract::NOperationResult::kOK: 1086 NExtract::NOperationResult::kOK:
1088 NExtract::NOperationResult::kDataError)); 1087 NExtract::NOperationResult::kDataError))
1089 } 1088 }
1090 return S_OK; 1089 return S_OK;
1091 COM_TRY_END 1090 COM_TRY_END
1092} 1091}
1093 1092
1094STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 1093Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail))
1095{ 1094{
1096 _allowTail = IntToBool(allowTail); 1095 _allowTail = IntToBool(allowTail);
1097 return S_OK; 1096 return S_OK;
@@ -1100,7 +1099,7 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail)
1100static const Byte k_Signature[] = { 0x7F, 'E', 'L', 'F' }; 1099static const Byte k_Signature[] = { 0x7F, 'E', 'L', 'F' };
1101 1100
1102REGISTER_ARC_I( 1101REGISTER_ARC_I(
1103 "ELF", "elf", 0, 0xDE, 1102 "ELF", "elf", NULL, 0xDE,
1104 k_Signature, 1103 k_Signature,
1105 0, 1104 0,
1106 NArcInfoFlags::kPreArc, 1105 NArcInfoFlags::kPreArc,
diff --git a/CPP/7zip/Archive/ExtHandler.cpp b/CPP/7zip/Archive/ExtHandler.cpp
index 01e12ed..f309485 100644
--- a/CPP/7zip/Archive/ExtHandler.cpp
+++ b/CPP/7zip/Archive/ExtHandler.cpp
@@ -353,7 +353,7 @@ static int inline GetLog(UInt32 num)
353{ 353{
354 for (unsigned i = 0; i < 32; i++) 354 for (unsigned i = 0; i < 32; i++)
355 if (((UInt32)1 << i) == num) 355 if (((UInt32)1 << i) == num)
356 return i; 356 return (int)i;
357 return -1; 357 return -1;
358} 358}
359 359
@@ -371,8 +371,8 @@ bool CHeader::Parse(const Byte *p)
371 if (GetUi16(p + 0x38) != 0xEF53) 371 if (GetUi16(p + 0x38) != 0xEF53)
372 return false; 372 return false;
373 373
374 LE_32 (0x18, BlockBits); 374 LE_32 (0x18, BlockBits)
375 LE_32 (0x1C, ClusterBits); 375 LE_32 (0x1C, ClusterBits)
376 376
377 if (ClusterBits != 0 && BlockBits != ClusterBits) 377 if (ClusterBits != 0 && BlockBits != ClusterBits)
378 return false; 378 return false;
@@ -381,22 +381,22 @@ bool CHeader::Parse(const Byte *p)
381 return false; 381 return false;
382 BlockBits += 10; 382 BlockBits += 10;
383 383
384 LE_32 (0x00, NumInodes); 384 LE_32 (0x00, NumInodes)
385 LE_32 (0x04, NumBlocks); 385 LE_32 (0x04, NumBlocks)
386 // LE_32 (0x08, NumBlocksSuper); 386 // LE_32 (0x08, NumBlocksSuper);
387 LE_32 (0x0C, NumFreeBlocks); 387 LE_32 (0x0C, NumFreeBlocks)
388 LE_32 (0x10, NumFreeInodes); 388 LE_32 (0x10, NumFreeInodes)
389 389
390 if (NumInodes < 2 || NumInodes <= NumFreeInodes) 390 if (NumInodes < 2 || NumInodes <= NumFreeInodes)
391 return false; 391 return false;
392 392
393 UInt32 FirstDataBlock; 393 UInt32 FirstDataBlock;
394 LE_32 (0x14, FirstDataBlock); 394 LE_32 (0x14, FirstDataBlock)
395 if (FirstDataBlock != (unsigned)(BlockBits == 10 ? 1 : 0)) 395 if (FirstDataBlock != (unsigned)(BlockBits == 10 ? 1 : 0))
396 return false; 396 return false;
397 397
398 LE_32 (0x20, BlocksPerGroup); 398 LE_32 (0x20, BlocksPerGroup)
399 LE_32 (0x24, ClustersPerGroup); 399 LE_32 (0x24, ClustersPerGroup)
400 400
401 if (BlocksPerGroup != ClustersPerGroup) 401 if (BlocksPerGroup != ClustersPerGroup)
402 return false; 402 return false;
@@ -408,13 +408,13 @@ bool CHeader::Parse(const Byte *p)
408 // return false; 408 // return false;
409 } 409 }
410 410
411 LE_32 (0x28, InodesPerGroup); 411 LE_32 (0x28, InodesPerGroup)
412 412
413 if (InodesPerGroup < 1 || InodesPerGroup > NumInodes) 413 if (InodesPerGroup < 1 || InodesPerGroup > NumInodes)
414 return false; 414 return false;
415 415
416 LE_32 (0x2C, MountTime); 416 LE_32 (0x2C, MountTime)
417 LE_32 (0x30, WriteTime); 417 LE_32 (0x30, WriteTime)
418 418
419 // LE_16 (0x34, NumMounts); 419 // LE_16 (0x34, NumMounts);
420 // LE_16 (0x36, NumMountsMax); 420 // LE_16 (0x36, NumMountsMax);
@@ -423,10 +423,10 @@ bool CHeader::Parse(const Byte *p)
423 // LE_16 (0x3C, Errors); 423 // LE_16 (0x3C, Errors);
424 // LE_16 (0x3E, MinorRevLevel); 424 // LE_16 (0x3E, MinorRevLevel);
425 425
426 LE_32 (0x40, LastCheckTime); 426 LE_32 (0x40, LastCheckTime)
427 // LE_32 (0x44, CheckInterval); 427 // LE_32 (0x44, CheckInterval);
428 LE_32 (0x48, CreatorOs); 428 LE_32 (0x48, CreatorOs)
429 LE_32 (0x4C, RevLevel); 429 LE_32 (0x4C, RevLevel)
430 430
431 // LE_16 (0x50, DefResUid); 431 // LE_16 (0x50, DefResUid);
432 // LE_16 (0x52, DefResGid); 432 // LE_16 (0x52, DefResGid);
@@ -436,8 +436,8 @@ bool CHeader::Parse(const Byte *p)
436 436
437 if (!IsOldRev()) 437 if (!IsOldRev())
438 { 438 {
439 LE_32 (0x54, FirstInode); 439 LE_32 (0x54, FirstInode)
440 LE_16 (0x58, InodeSize); 440 LE_16 (0x58, InodeSize)
441 if (FirstInode < k_INODE_GOOD_OLD_FIRST) 441 if (FirstInode < k_INODE_GOOD_OLD_FIRST)
442 return false; 442 return false;
443 if (InodeSize > ((UInt32)1 << BlockBits) 443 if (InodeSize > ((UInt32)1 << BlockBits)
@@ -446,10 +446,10 @@ bool CHeader::Parse(const Byte *p)
446 return false; 446 return false;
447 } 447 }
448 448
449 LE_16 (0x5A, BlockGroupNr); 449 LE_16 (0x5A, BlockGroupNr)
450 LE_32 (0x5C, FeatureCompat); 450 LE_32 (0x5C, FeatureCompat)
451 LE_32 (0x60, FeatureIncompat); 451 LE_32 (0x60, FeatureIncompat)
452 LE_32 (0x64, FeatureRoCompat); 452 LE_32 (0x64, FeatureRoCompat)
453 453
454 memcpy(Uuid, p + 0x68, sizeof(Uuid)); 454 memcpy(Uuid, p + 0x68, sizeof(Uuid));
455 memcpy(VolName, p + 0x78, sizeof(VolName)); 455 memcpy(VolName, p + 0x78, sizeof(VolName));
@@ -457,24 +457,24 @@ bool CHeader::Parse(const Byte *p)
457 457
458 // LE_32 (0xC8, BitmapAlgo); 458 // LE_32 (0xC8, BitmapAlgo);
459 459
460 LE_32 (0xE0, JournalInode); 460 LE_32 (0xE0, JournalInode)
461 461
462 LE_16 (0xFE, GdSize); 462 LE_16 (0xFE, GdSize)
463 463
464 LE_32 (0x108, CTime); 464 LE_32 (0x108, CTime)
465 465
466 if (Is64Bit()) 466 if (Is64Bit())
467 { 467 {
468 HI_32(0x150, NumBlocks); 468 HI_32(0x150, NumBlocks)
469 // HI_32(0x154, NumBlocksSuper); 469 // HI_32(0x154, NumBlocksSuper);
470 HI_32(0x158, NumFreeBlocks); 470 HI_32(0x158, NumFreeBlocks)
471 } 471 }
472 472
473 if (NumBlocks >= (UInt64)1 << (63 - BlockBits)) 473 if (NumBlocks >= (UInt64)1 << (63 - BlockBits))
474 return false; 474 return false;
475 475
476 476
477 LE_16(0x15C, MinExtraISize); 477 LE_16(0x15C, MinExtraISize)
478 // LE_16(0x15E, WantExtraISize); 478 // LE_16(0x15E, WantExtraISize);
479 // LE_32(0x160, Flags); 479 // LE_32(0x160, Flags);
480 // LE_16(0x164, RaidStride); 480 // LE_16(0x164, RaidStride);
@@ -484,7 +484,7 @@ bool CHeader::Parse(const Byte *p)
484 // LogGroupsPerFlex = p[0x174]; 484 // LogGroupsPerFlex = p[0x174];
485 // ChecksumType = p[0x175]; 485 // ChecksumType = p[0x175];
486 486
487 LE_64 (0x178, WrittenKB); 487 LE_64 (0x178, WrittenKB)
488 488
489 // LE_32(0x194, ErrorCount); 489 // LE_32(0x194, ErrorCount);
490 // LE_32(0x198, ErrorTime); 490 // LE_32(0x198, ErrorTime);
@@ -525,32 +525,32 @@ struct CGroupDescriptor
525 525
526void CGroupDescriptor::Parse(const Byte *p, unsigned size) 526void CGroupDescriptor::Parse(const Byte *p, unsigned size)
527{ 527{
528 LE_32 (0x00, BlockBitmap); 528 LE_32 (0x00, BlockBitmap)
529 LE_32 (0x04, InodeBitmap); 529 LE_32 (0x04, InodeBitmap)
530 LE_32 (0x08, InodeTable); 530 LE_32 (0x08, InodeTable)
531 LE_16 (0x0C, NumFreeBlocks); 531 LE_16 (0x0C, NumFreeBlocks)
532 LE_16 (0x0E, NumFreeInodes); 532 LE_16 (0x0E, NumFreeInodes)
533 LE_16 (0x10, DirCount); 533 LE_16 (0x10, DirCount)
534 LE_16 (0x12, Flags); 534 LE_16 (0x12, Flags)
535 LE_32 (0x14, ExcludeBitmap); 535 LE_32 (0x14, ExcludeBitmap)
536 LE_16 (0x18, BlockBitmap_Checksum); 536 LE_16 (0x18, BlockBitmap_Checksum)
537 LE_16 (0x1A, InodeBitmap_Checksum); 537 LE_16 (0x1A, InodeBitmap_Checksum)
538 LE_16 (0x1C, UnusedCount); 538 LE_16 (0x1C, UnusedCount)
539 LE_16 (0x1E, Checksum); 539 LE_16 (0x1E, Checksum)
540 540
541 if (size >= 64) 541 if (size >= 64)
542 { 542 {
543 p += 0x20; 543 p += 0x20;
544 HI_32 (0x00, BlockBitmap); 544 HI_32 (0x00, BlockBitmap)
545 HI_32 (0x04, InodeBitmap); 545 HI_32 (0x04, InodeBitmap)
546 HI_32 (0x08, InodeTable); 546 HI_32 (0x08, InodeTable)
547 HI_16 (0x0C, NumFreeBlocks); 547 HI_16 (0x0C, NumFreeBlocks)
548 HI_16 (0x0E, NumFreeInodes); 548 HI_16 (0x0E, NumFreeInodes)
549 HI_16 (0x10, DirCount); 549 HI_16 (0x10, DirCount)
550 HI_16 (0x12, UnusedCount); // instead of Flags 550 HI_16 (0x12, UnusedCount) // instead of Flags
551 HI_32 (0x14, ExcludeBitmap); 551 HI_32 (0x14, ExcludeBitmap)
552 HI_16 (0x18, BlockBitmap_Checksum); 552 HI_16 (0x18, BlockBitmap_Checksum)
553 HI_16 (0x1A, InodeBitmap_Checksum); 553 HI_16 (0x1A, InodeBitmap_Checksum)
554 // HI_16 (0x1C, Reserved); 554 // HI_16 (0x1C, Reserved);
555 } 555 }
556} 556}
@@ -567,9 +567,9 @@ struct CExtentTreeHeader
567 567
568 bool Parse(const Byte *p) 568 bool Parse(const Byte *p)
569 { 569 {
570 LE_16 (0x02, NumEntries); 570 LE_16 (0x02, NumEntries)
571 LE_16 (0x04, MaxEntries); 571 LE_16 (0x04, MaxEntries)
572 LE_16 (0x06, Depth); 572 LE_16 (0x06, Depth)
573 // LE_32 (0x08, Generation); 573 // LE_32 (0x08, Generation);
574 return Get16(p) == 0xF30A; // magic 574 return Get16(p) == 0xF30A; // magic
575 } 575 }
@@ -582,8 +582,8 @@ struct CExtentIndexNode
582 582
583 void Parse(const Byte *p) 583 void Parse(const Byte *p)
584 { 584 {
585 LE_32 (0x00, VirtBlock); 585 LE_32 (0x00, VirtBlock)
586 LE_32 (0x04, PhyLeaf); 586 LE_32 (0x04, PhyLeaf)
587 PhyLeaf |= (((UInt64)Get16(p + 8)) << 32); 587 PhyLeaf |= (((UInt64)Get16(p + 8)) << 32);
588 // unused 16-bit field (at offset 0x0A) can be not zero in some cases. Why? 588 // unused 16-bit field (at offset 0x0A) can be not zero in some cases. Why?
589 } 589 }
@@ -601,17 +601,17 @@ struct CExtent
601 601
602 void Parse(const Byte *p) 602 void Parse(const Byte *p)
603 { 603 {
604 LE_32 (0x00, VirtBlock); 604 LE_32 (0x00, VirtBlock)
605 LE_16 (0x04, Len); 605 LE_16 (0x04, Len)
606 IsInited = true; 606 IsInited = true;
607 if (Len > (UInt32)0x8000) 607 if (Len > (UInt32)0x8000)
608 { 608 {
609 IsInited = false; 609 IsInited = false;
610 Len = (UInt16)(Len - (UInt32)0x8000); 610 Len = (UInt16)(Len - (UInt32)0x8000);
611 } 611 }
612 LE_32 (0x08, PhyStart); 612 LE_32 (0x08, PhyStart)
613 UInt16 hi; 613 UInt16 hi;
614 LE_16 (0x06, hi); 614 LE_16 (0x06, hi)
615 PhyStart |= ((UInt64)hi << 32); 615 PhyStart |= ((UInt64)hi << 32);
616 } 616 }
617}; 617};
@@ -627,7 +627,7 @@ struct CExtTime
627struct CNode 627struct CNode
628{ 628{
629 Int32 ParentNode; // in _refs[], -1 if not dir 629 Int32 ParentNode; // in _refs[], -1 if not dir
630 int ItemIndex; // in _items[] 630 int ItemIndex; // in _items[] , (set as >=0 only for if (IsDir())
631 int SymLinkIndex; // in _symLinks[] 631 int SymLinkIndex; // in _symLinks[]
632 int DirIndex; // in _dirs[] 632 int DirIndex; // in _dirs[]
633 633
@@ -655,7 +655,7 @@ struct CNode
655 ParentNode(-1), 655 ParentNode(-1),
656 ItemIndex(-1), 656 ItemIndex(-1),
657 SymLinkIndex(-1), 657 SymLinkIndex(-1),
658 DirIndex(0), 658 DirIndex(-1),
659 NumLinksCalced(0) 659 NumLinksCalced(0)
660 {} 660 {}
661 661
@@ -679,18 +679,18 @@ bool CNode::Parse(const Byte *p, const CHeader &_h)
679 ChangeTime.Extra = 0; 679 ChangeTime.Extra = 0;
680 // DTime.Extra = 0; 680 // DTime.Extra = 0;
681 681
682 LE_16 (0x00, Mode); 682 LE_16 (0x00, Mode)
683 LE_16 (0x02, Uid); 683 LE_16 (0x02, Uid)
684 LE_32 (0x04, FileSize); 684 LE_32 (0x04, FileSize)
685 LE_32 (0x08, ATime.Val); 685 LE_32 (0x08, ATime.Val)
686 LE_32 (0x0C, ChangeTime.Val); 686 LE_32 (0x0C, ChangeTime.Val)
687 LE_32 (0x10, MTime.Val); 687 LE_32 (0x10, MTime.Val)
688 // LE_32 (0x14, DTime.Val); 688 // LE_32 (0x14, DTime.Val);
689 LE_16 (0x18, Gid); 689 LE_16 (0x18, Gid)
690 LE_16 (0x1A, NumLinks); 690 LE_16 (0x1A, NumLinks)
691 691
692 LE_32 (0x1C, NumBlocks); 692 LE_32 (0x1C, NumBlocks)
693 LE_32 (0x20, Flags); 693 LE_32 (0x20, Flags)
694 // LE_32 (0x24, Union osd1); 694 // LE_32 (0x24, Union osd1);
695 695
696 memcpy(Block, p + 0x28, kNodeBlockFieldSize); 696 memcpy(Block, p + 0x28, kNodeBlockFieldSize);
@@ -700,7 +700,7 @@ bool CNode::Parse(const Byte *p, const CHeader &_h)
700 700
701 { 701 {
702 UInt32 highSize; 702 UInt32 highSize;
703 LE_32 (0x6C, highSize); // In ext2/3 this field was named i_dir_acl 703 LE_32 (0x6C, highSize) // In ext2/3 this field was named i_dir_acl
704 704
705 if (IsRegular()) // do we need that check ? 705 if (IsRegular()) // do we need that check ?
706 FileSize |= ((UInt64)highSize << 32); 706 FileSize |= ((UInt64)highSize << 32);
@@ -718,11 +718,11 @@ bool CNode::Parse(const Byte *p, const CHeader &_h)
718 718
719 // ext4: 719 // ext4:
720 UInt32 numBlocksHigh; 720 UInt32 numBlocksHigh;
721 LE_16 (0x74, numBlocksHigh); 721 LE_16 (0x74, numBlocksHigh)
722 NumBlocks |= (UInt64)numBlocksHigh << 32; 722 NumBlocks |= (UInt64)numBlocksHigh << 32;
723 723
724 HI_16 (0x74 + 4, Uid); 724 HI_16 (0x74 + 4, Uid)
725 HI_16 (0x74 + 6, Gid); 725 HI_16 (0x74 + 6, Gid)
726 /* 726 /*
727 UInt32 checksum; 727 UInt32 checksum;
728 LE_16 (0x74 + 8, checksum); 728 LE_16 (0x74 + 8, checksum);
@@ -737,19 +737,19 @@ bool CNode::Parse(const Byte *p, const CHeader &_h)
737 // InodeSize is power of 2, so the following check is not required: 737 // InodeSize is power of 2, so the following check is not required:
738 // if (_h.InodeSize < 128 + 2) return false; 738 // if (_h.InodeSize < 128 + 2) return false;
739 UInt16 extra_isize; 739 UInt16 extra_isize;
740 LE_16 (0x80, extra_isize); 740 LE_16 (0x80, extra_isize)
741 if (128 + extra_isize > _h.InodeSize) 741 if (128 + extra_isize > _h.InodeSize)
742 return false; 742 return false;
743 if (extra_isize >= 0x1C) 743 if (extra_isize >= 0x1C)
744 { 744 {
745 // UInt16 checksumUpper; 745 // UInt16 checksumUpper;
746 // LE_16 (0x82, checksumUpper); 746 // LE_16 (0x82, checksumUpper);
747 LE_32 (0x84, ChangeTime.Extra); 747 LE_32 (0x84, ChangeTime.Extra)
748 LE_32 (0x88, MTime.Extra); 748 LE_32 (0x88, MTime.Extra)
749 LE_32 (0x8C, ATime.Extra); 749 LE_32 (0x8C, ATime.Extra)
750 LE_32 (0x90, CTime.Val); 750 LE_32 (0x90, CTime.Val)
751 LE_32 (0x94, CTime.Extra); 751 LE_32 (0x94, CTime.Extra)
752 // LE_32 (0x98, VersionHi); 752 // LE_32 (0x98, VersionHi)
753 } 753 }
754 } 754 }
755 755
@@ -786,7 +786,6 @@ struct CItem
786 786
787 bool IsDir() const { return Type == k_Type_DIR; } 787 bool IsDir() const { return Type == k_Type_DIR; }
788 // bool IsNotDir() const { return Type != k_Type_DIR && Type != k_Type_UNKNOWN; } 788 // bool IsNotDir() const { return Type != k_Type_DIR && Type != k_Type_UNKNOWN; }
789
790}; 789};
791 790
792 791
@@ -794,14 +793,12 @@ struct CItem
794static const unsigned kNumTreeLevelsMax = 6; // must be >= 3 793static const unsigned kNumTreeLevelsMax = 6; // must be >= 3
795 794
796 795
797class CHandler: 796Z7_CLASS_IMP_CHandler_IInArchive_2(
798 public IInArchive, 797 IArchiveGetRawProps,
799 public IArchiveGetRawProps, 798 IInArchiveGetStream
800 public IInArchiveGetStream, 799)
801 public CMyUnknownImp
802{
803 CObjectVector<CItem> _items; 800 CObjectVector<CItem> _items;
804 CIntVector _refs; 801 CIntVector _refs; // iNode -> (index in _nodes). if (_refs[iNode] < 0), that node is not filled
805 CRecordVector<CNode> _nodes; 802 CRecordVector<CNode> _nodes;
806 CObjectVector<CUIntVector> _dirs; // each CUIntVector contains indexes in _items[] only for dir items; 803 CObjectVector<CUIntVector> _dirs; // each CUIntVector contains indexes in _items[] only for dir items;
807 AStringVector _symLinks; 804 AStringVector _symLinks;
@@ -871,16 +868,6 @@ class CHandler:
871 868
872 void GetPath(unsigned index, AString &s) const; 869 void GetPath(unsigned index, AString &s) const;
873 bool GetPackSize(unsigned index, UInt64 &res) const; 870 bool GetPackSize(unsigned index, UInt64 &res) const;
874
875public:
876 CHandler() {}
877 ~CHandler() {}
878
879 MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream)
880
881 INTERFACE_IInArchive(;)
882 INTERFACE_IArchiveGetRawProps(;)
883 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
884}; 871};
885 872
886 873
@@ -892,7 +879,7 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
892 PRF(printf("\n\n========= node = %5d size = %5d", (unsigned)iNodeDir, (unsigned)size)); 879 PRF(printf("\n\n========= node = %5d size = %5d", (unsigned)iNodeDir, (unsigned)size));
893 880
894 CNode &nodeDir = _nodes[_refs[iNodeDir]]; 881 CNode &nodeDir = _nodes[_refs[iNodeDir]];
895 nodeDir.DirIndex = _dirs.Size(); 882 nodeDir.DirIndex = (int)_dirs.Size();
896 CUIntVector &dir = _dirs.AddNew(); 883 CUIntVector &dir = _dirs.AddNew();
897 int parentNode = -1; 884 int parentNode = -1;
898 885
@@ -905,11 +892,11 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
905 if (size < 8) 892 if (size < 8)
906 return S_FALSE; 893 return S_FALSE;
907 UInt32 iNode; 894 UInt32 iNode;
908 LE_32 (0x00, iNode); 895 LE_32 (0x00, iNode)
909 unsigned recLen; 896 unsigned recLen;
910 LE_16 (0x04, recLen); 897 LE_16 (0x04, recLen)
911 unsigned nameLen = p[6]; 898 const unsigned nameLen = p[6];
912 Byte type = p[7]; 899 const Byte type = p[7];
913 900
914 if (recLen > size) 901 if (recLen > size)
915 return S_FALSE; 902 return S_FALSE;
@@ -926,7 +913,7 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
926 else if (type != 0) 913 else if (type != 0)
927 return S_FALSE; 914 return S_FALSE;
928 915
929 item.ParentNode = iNodeDir; 916 item.ParentNode = (int)iNodeDir;
930 item.Node = iNode; 917 item.Node = iNode;
931 item.Name.SetFrom_CalcLen((const char *)(p + 8), nameLen); 918 item.Name.SetFrom_CalcLen((const char *)(p + 8), nameLen);
932 919
@@ -958,14 +945,14 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
958 continue; 945 continue;
959 } 946 }
960 947
961 int nodeIndex = _refs[iNode]; 948 const int nodeIndex = _refs[iNode];
962 if (nodeIndex < 0) 949 if (nodeIndex < 0)
963 return S_FALSE; 950 return S_FALSE;
964 CNode &node = _nodes[nodeIndex]; 951 CNode &node = _nodes[nodeIndex];
965 952
966 if (_h.IsThereFileType() && type != 0) 953 if (_h.IsThereFileType() && type != 0)
967 { 954 {
968 if (type >= ARRAY_SIZE(k_TypeToMode)) 955 if (type >= Z7_ARRAY_SIZE(k_TypeToMode))
969 return S_FALSE; 956 return S_FALSE;
970 if (k_TypeToMode[type] != (node.Mode & MY_LIN_S_IFMT)) 957 if (k_TypeToMode[type] != (node.Mode & MY_LIN_S_IFMT))
971 return S_FALSE; 958 return S_FALSE;
@@ -996,10 +983,10 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
996 if (iNode == iNodeDir && iNode != k_INODE_ROOT) 983 if (iNode == iNodeDir && iNode != k_INODE_ROOT)
997 return S_FALSE; 984 return S_FALSE;
998 985
999 parentNode = iNode; 986 parentNode = (int)iNode;
1000 987
1001 if (nodeDir.ParentNode < 0) 988 if (nodeDir.ParentNode < 0)
1002 nodeDir.ParentNode = iNode; 989 nodeDir.ParentNode = (int)iNode;
1003 else if ((unsigned)nodeDir.ParentNode != iNode) 990 else if ((unsigned)nodeDir.ParentNode != iNode)
1004 return S_FALSE; 991 return S_FALSE;
1005 992
@@ -1016,12 +1003,12 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
1016 if (node.IsDir()) 1003 if (node.IsDir())
1017 { 1004 {
1018 if (node.ParentNode < 0) 1005 if (node.ParentNode < 0)
1019 node.ParentNode = iNodeDir; 1006 node.ParentNode = (int)iNodeDir;
1020 else if ((unsigned)node.ParentNode != iNodeDir) 1007 else if ((unsigned)node.ParentNode != iNodeDir)
1021 return S_FALSE; 1008 return S_FALSE;
1022 const unsigned itemIndex = _items.Size(); 1009 const unsigned itemIndex = _items.Size();
1023 dir.Add(itemIndex); 1010 dir.Add(itemIndex);
1024 node.ItemIndex = itemIndex; 1011 node.ItemIndex = (int)itemIndex;
1025 } 1012 }
1026 1013
1027 _items.Add(item); 1014 _items.Add(item);
@@ -1034,6 +1021,13 @@ HRESULT CHandler::ParseDir(const Byte *p, size_t size, unsigned iNodeDir)
1034} 1021}
1035 1022
1036 1023
1024static int CompareItemsNames(const unsigned *p1, const unsigned *p2, void *param)
1025{
1026 const CObjectVector<CItem> &items = *(const CObjectVector<CItem> *)param;
1027 return strcmp(items[*p1].Name, items[*p2].Name);
1028}
1029
1030
1037int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) const 1031int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) const
1038{ 1032{
1039 unsigned pos = 0; 1033 unsigned pos = 0;
@@ -1054,7 +1048,7 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co
1054 while (pos != path.Len()) 1048 while (pos != path.Len())
1055 { 1049 {
1056 const CNode &node = _nodes[_refs[iNode]]; 1050 const CNode &node = _nodes[_refs[iNode]];
1057 int slash = path.Find('/', pos); 1051 const int slash = path.Find('/', pos);
1058 1052
1059 if (slash < 0) 1053 if (slash < 0)
1060 { 1054 {
@@ -1063,8 +1057,8 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co
1063 } 1057 }
1064 else 1058 else
1065 { 1059 {
1066 s.SetFrom(path.Ptr(pos), slash - pos); 1060 s.SetFrom(path.Ptr(pos), (unsigned)slash - pos);
1067 pos = slash + 1; 1061 pos = (unsigned)slash + 1;
1068 } 1062 }
1069 1063
1070 if (s[0] == '.') 1064 if (s[0] == '.')
@@ -1077,7 +1071,7 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co
1077 return -1; 1071 return -1;
1078 if (iNode == k_INODE_ROOT) 1072 if (iNode == k_INODE_ROOT)
1079 return -1; 1073 return -1;
1080 iNode = node.ParentNode; 1074 iNode = (unsigned)node.ParentNode;
1081 continue; 1075 continue;
1082 } 1076 }
1083 } 1077 }
@@ -1087,6 +1081,7 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co
1087 1081
1088 const CUIntVector &dir = _dirs[node.DirIndex]; 1082 const CUIntVector &dir = _dirs[node.DirIndex];
1089 1083
1084 /*
1090 for (unsigned i = 0;; i++) 1085 for (unsigned i = 0;; i++)
1091 { 1086 {
1092 if (i >= dir.Size()) 1087 if (i >= dir.Size())
@@ -1098,6 +1093,26 @@ int CHandler::FindTargetItem_for_SymLink(unsigned iNode, const AString &path) co
1098 break; 1093 break;
1099 } 1094 }
1100 } 1095 }
1096 */
1097
1098 unsigned left = 0, right = dir.Size();
1099 for (;;)
1100 {
1101 if (left == right)
1102 return -1;
1103 const unsigned mid = (unsigned)(((size_t)left + (size_t)right) / 2);
1104 const CItem &item = _items[dir[mid]];
1105 const int comp = strcmp(s, item.Name);
1106 if (comp == 0)
1107 {
1108 iNode = item.Node;
1109 break;
1110 }
1111 if (comp < 0)
1112 right = mid;
1113 else
1114 left = mid + 1;
1115 }
1101 } 1116 }
1102 1117
1103 return _nodes[_refs[iNode]].ItemIndex; 1118 return _nodes[_refs[iNode]].ItemIndex;
@@ -1110,7 +1125,7 @@ HRESULT CHandler::SeekAndRead(IInStream *inStream, UInt64 block, Byte *data, siz
1110 return S_FALSE; 1125 return S_FALSE;
1111 if (((size + ((size_t)1 << _h.BlockBits) - 1) >> _h.BlockBits) > _h.NumBlocks - block) 1126 if (((size + ((size_t)1 << _h.BlockBits) - 1) >> _h.BlockBits) > _h.NumBlocks - block)
1112 return S_FALSE; 1127 return S_FALSE;
1113 RINOK(inStream->Seek((UInt64)block << _h.BlockBits, STREAM_SEEK_SET, NULL)); 1128 RINOK(InStream_SeekSet(inStream, (UInt64)block << _h.BlockBits))
1114 _totalRead += size; 1129 _totalRead += size;
1115 return ReadStream_FALSE(inStream, data, size); 1130 return ReadStream_FALSE(inStream, data, size);
1116} 1131}
@@ -1123,7 +1138,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1123{ 1138{
1124 { 1139 {
1125 Byte buf[kHeaderSize]; 1140 Byte buf[kHeaderSize];
1126 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize)); 1141 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize))
1127 if (!_h.Parse(buf + kHeaderDataOffset)) 1142 if (!_h.Parse(buf + kHeaderDataOffset))
1128 return S_FALSE; 1143 return S_FALSE;
1129 if (_h.BlockGroupNr != 0) 1144 if (_h.BlockGroupNr != 0)
@@ -1135,7 +1150,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1135 1150
1136 unsigned numGroups; 1151 unsigned numGroups;
1137 { 1152 {
1138 UInt64 numGroups64 = _h.GetNumGroups(); 1153 const UInt64 numGroups64 = _h.GetNumGroups();
1139 if (numGroups64 > (UInt32)1 << 31) 1154 if (numGroups64 > (UInt32)1 << 31)
1140 return S_FALSE; 1155 return S_FALSE;
1141 numGroups = (unsigned)numGroups64; 1156 numGroups = (unsigned)numGroups64;
@@ -1154,11 +1169,11 @@ HRESULT CHandler::Open2(IInStream *inStream)
1154 1169
1155 if (_openCallback) 1170 if (_openCallback)
1156 { 1171 {
1157 RINOK(_openCallback->SetTotal(NULL, &_phySize)); 1172 RINOK(_openCallback->SetTotal(NULL, &_phySize))
1158 } 1173 }
1159 1174
1160 UInt64 fileSize = 0; 1175 UInt64 fileSize = 0;
1161 RINOK(inStream->Seek(0, STREAM_SEEK_END, &fileSize)); 1176 RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize))
1162 1177
1163 CRecordVector<CGroupDescriptor> groups; 1178 CRecordVector<CGroupDescriptor> groups;
1164 1179
@@ -1166,18 +1181,18 @@ HRESULT CHandler::Open2(IInStream *inStream)
1166 // ---------- Read groups ---------- 1181 // ---------- Read groups ----------
1167 1182
1168 CByteBuffer gdBuf; 1183 CByteBuffer gdBuf;
1169 size_t gdBufSize = (size_t)numGroups << gdBits; 1184 const size_t gdBufSize = (size_t)numGroups << gdBits;
1170 if ((gdBufSize >> gdBits) != numGroups) 1185 if ((gdBufSize >> gdBits) != numGroups)
1171 return S_FALSE; 1186 return S_FALSE;
1172 gdBuf.Alloc(gdBufSize); 1187 gdBuf.Alloc(gdBufSize);
1173 RINOK(SeekAndRead(inStream, (_h.BlockBits <= 10 ? 2 : 1), gdBuf, gdBufSize)); 1188 RINOK(SeekAndRead(inStream, (_h.BlockBits <= 10 ? 2 : 1), gdBuf, gdBufSize))
1174 1189
1175 for (unsigned i = 0; i < numGroups; i++) 1190 for (unsigned i = 0; i < numGroups; i++)
1176 { 1191 {
1177 CGroupDescriptor gd; 1192 CGroupDescriptor gd;
1178 1193
1179 const Byte *p = gdBuf + ((size_t)i << gdBits); 1194 const Byte *p = gdBuf + ((size_t)i << gdBits);
1180 unsigned gd_Size = (unsigned)1 << gdBits; 1195 const unsigned gd_Size = (unsigned)1 << gdBits;
1181 gd.Parse(p, gd_Size); 1196 gd.Parse(p, gd_Size);
1182 1197
1183 if (_h.UseMetadataChecksum()) 1198 if (_h.UseMetadataChecksum())
@@ -1188,7 +1203,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1188 { 1203 {
1189 UInt32 crc = Crc16Calc(_h.Uuid, sizeof(_h.Uuid)); 1204 UInt32 crc = Crc16Calc(_h.Uuid, sizeof(_h.Uuid));
1190 Byte i_le[4]; 1205 Byte i_le[4];
1191 SetUi32(i_le, i); 1206 SetUi32(i_le, i)
1192 crc = Crc16Update(crc, i_le, 4); 1207 crc = Crc16Update(crc, i_le, 4);
1193 crc = Crc16Update(crc, p, 32 - 2); 1208 crc = Crc16Update(crc, p, 32 - 2);
1194 if (gd_Size != 32) 1209 if (gd_Size != 32)
@@ -1250,8 +1265,8 @@ HRESULT CHandler::Open2(IInStream *inStream)
1250 1265
1251 PRF(printf("\n\ng%6d block = %6x\n", gi, (unsigned)gd.InodeTable)); 1266 PRF(printf("\n\ng%6d block = %6x\n", gi, (unsigned)gd.InodeTable));
1252 1267
1253 RINOK(SeekAndRead(inStream, gd.InodeBitmap, nodesMap, blockSize)); 1268 RINOK(SeekAndRead(inStream, gd.InodeBitmap, nodesMap, blockSize))
1254 RINOK(SeekAndRead(inStream, gd.InodeTable, nodesData, nodesDataSize)); 1269 RINOK(SeekAndRead(inStream, gd.InodeTable, nodesData, nodesDataSize))
1255 1270
1256 unsigned numEmpty_in_Map = 0; 1271 unsigned numEmpty_in_Map = 0;
1257 1272
@@ -1300,7 +1315,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1300 _refs.Add(-1); 1315 _refs.Add(-1);
1301 } 1316 }
1302 1317
1303 _refs.Add(_nodes.Add(node)); 1318 _refs.Add((int)_nodes.Add(node));
1304 } 1319 }
1305 1320
1306 1321
@@ -1336,7 +1351,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1336 1351
1337 FOR_VECTOR (i, _refs) 1352 FOR_VECTOR (i, _refs)
1338 { 1353 {
1339 int nodeIndex = _refs[i]; 1354 const int nodeIndex = _refs[i];
1340 { 1355 {
1341 if (nodeIndex < 0) 1356 if (nodeIndex < 0)
1342 continue; 1357 continue;
@@ -1344,7 +1359,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1344 if (!node.IsDir()) 1359 if (!node.IsDir())
1345 continue; 1360 continue;
1346 } 1361 }
1347 RINOK(ExtractNode(nodeIndex, dataBuf)); 1362 RINOK(ExtractNode((unsigned)nodeIndex, dataBuf))
1348 if (dataBuf.Size() == 0) 1363 if (dataBuf.Size() == 0)
1349 { 1364 {
1350 // _headersError = true; 1365 // _headersError = true;
@@ -1352,12 +1367,12 @@ HRESULT CHandler::Open2(IInStream *inStream)
1352 } 1367 }
1353 else 1368 else
1354 { 1369 {
1355 RINOK(ParseDir(dataBuf, dataBuf.Size(), i)); 1370 RINOK(ParseDir(dataBuf, dataBuf.Size(), i))
1356 } 1371 }
1357 RINOK(CheckProgress()); 1372 RINOK(CheckProgress())
1358 } 1373 }
1359 1374
1360 int ref = _refs[k_INODE_ROOT]; 1375 const int ref = _refs[k_INODE_ROOT];
1361 if (ref < 0 || _nodes[ref].ParentNode != k_INODE_ROOT) 1376 if (ref < 0 || _nodes[ref].ParentNode != k_INODE_ROOT)
1362 return S_FALSE; 1377 return S_FALSE;
1363 } 1378 }
@@ -1423,7 +1438,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1423 1438
1424 for (;;) 1439 for (;;)
1425 { 1440 {
1426 int nodeIndex = _refs[c]; 1441 const int nodeIndex = _refs[c];
1427 if (nodeIndex < 0) 1442 if (nodeIndex < 0)
1428 return S_FALSE; 1443 return S_FALSE;
1429 CNode &node = _nodes[nodeIndex]; 1444 CNode &node = _nodes[nodeIndex];
@@ -1435,12 +1450,12 @@ HRESULT CHandler::Open2(IInStream *inStream)
1435 break; 1450 break;
1436 } 1451 }
1437 1452
1438 UsedByNode[c] = i; 1453 UsedByNode[c] = (int)i;
1439 if (node.ParentNode < 0 || node.ParentNode == k_INODE_ROOT) 1454 if (node.ParentNode < 0 || node.ParentNode == k_INODE_ROOT)
1440 break; 1455 break;
1441 if ((unsigned)node.ParentNode == i) 1456 if ((unsigned)node.ParentNode == i)
1442 return S_FALSE; 1457 return S_FALSE;
1443 c = node.ParentNode; 1458 c = (unsigned)node.ParentNode;
1444 } 1459 }
1445 } 1460 }
1446 } 1461 }
@@ -1454,7 +1469,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1454 unsigned i; 1469 unsigned i;
1455 for (i = 0; i < _refs.Size(); i++) 1470 for (i = 0; i < _refs.Size(); i++)
1456 { 1471 {
1457 int nodeIndex = _refs[i]; 1472 const int nodeIndex = _refs[i];
1458 if (nodeIndex < 0) 1473 if (nodeIndex < 0)
1459 continue; 1474 continue;
1460 CNode &node = _nodes[nodeIndex]; 1475 CNode &node = _nodes[nodeIndex];
@@ -1462,32 +1477,37 @@ HRESULT CHandler::Open2(IInStream *inStream)
1462 continue; 1477 continue;
1463 if (node.FileSize > ((UInt32)1 << 14)) 1478 if (node.FileSize > ((UInt32)1 << 14))
1464 continue; 1479 continue;
1465 if (ExtractNode(nodeIndex, data) == S_OK && data.Size() != 0) 1480 if (ExtractNode((unsigned)nodeIndex, data) == S_OK && data.Size() != 0)
1466 { 1481 {
1467 s.SetFrom_CalcLen((const char *)(const Byte *)data, (unsigned)data.Size()); 1482 s.SetFrom_CalcLen((const char *)(const Byte *)data, (unsigned)data.Size());
1468 if (s.Len() == data.Size()) 1483 if (s.Len() == data.Size())
1469 node.SymLinkIndex = _symLinks.Add(s); 1484 node.SymLinkIndex = (int)_symLinks.Add(s);
1470 RINOK(CheckProgress()); 1485 RINOK(CheckProgress())
1471 } 1486 }
1472 } 1487 }
1473 1488
1489 for (i = 0; i < _dirs.Size(); i++)
1490 {
1491 _dirs[i].Sort(CompareItemsNames, (void *)&_items);
1492 }
1493
1474 unsigned prev = 0; 1494 unsigned prev = 0;
1475 unsigned complex = 0; 1495 unsigned complex = 0;
1476 1496
1477 for (i = 0; i < _items.Size(); i++) 1497 for (i = 0; i < _items.Size(); i++)
1478 { 1498 {
1479 CItem &item = _items[i]; 1499 CItem &item = _items[i];
1480 int sym = _nodes[_refs[item.Node]].SymLinkIndex; 1500 const int sym = _nodes[_refs[item.Node]].SymLinkIndex;
1481 if (sym >= 0 && item.ParentNode >= 0) 1501 if (sym >= 0 && item.ParentNode >= 0)
1482 { 1502 {
1483 item.SymLinkItemIndex = FindTargetItem_for_SymLink(item.ParentNode, _symLinks[sym]); 1503 item.SymLinkItemIndex = FindTargetItem_for_SymLink((unsigned)item.ParentNode, _symLinks[sym]);
1484 if (_openCallback) 1504 if (_openCallback)
1485 { 1505 {
1486 complex++; 1506 complex++;
1487 if (complex - prev >= (1 << 10)) 1507 if (complex - prev >= (1 << 10))
1488 { 1508 {
1489 RINOK(CheckProgress2());
1490 prev = complex; 1509 prev = complex;
1510 RINOK(CheckProgress2())
1491 } 1511 }
1492 } 1512 }
1493 } 1513 }
@@ -1502,7 +1522,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1502 1522
1503 FOR_VECTOR (i, _refs) 1523 FOR_VECTOR (i, _refs)
1504 { 1524 {
1505 int nodeIndex = _refs[i]; 1525 const int nodeIndex = _refs[i];
1506 if (nodeIndex < 0) 1526 if (nodeIndex < 0)
1507 continue; 1527 continue;
1508 const CNode &node = _nodes[nodeIndex]; 1528 const CNode &node = _nodes[nodeIndex];
@@ -1523,7 +1543,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1523 1543
1524 if (i < _h.FirstInode) 1544 if (i < _h.FirstInode)
1525 { 1545 {
1526 if (item.Node < ARRAY_SIZE(k_SysInode_Names)) 1546 if (item.Node < Z7_ARRAY_SIZE(k_SysInode_Names))
1527 item.Name = k_SysInode_Names[item.Node]; 1547 item.Name = k_SysInode_Names[item.Node];
1528 useSys = true; 1548 useSys = true;
1529 } 1549 }
@@ -1538,16 +1558,16 @@ HRESULT CHandler::Open2(IInStream *inStream)
1538 } 1558 }
1539 1559
1540 if (useSys) 1560 if (useSys)
1541 _auxSysIndex = _auxItems.Add((AString)"[SYS]"); 1561 _auxSysIndex = (int)_auxItems.Add((AString)"[SYS]");
1542 if (useUnknown) 1562 if (useUnknown)
1543 _auxUnknownIndex = _auxItems.Add((AString)"[UNKNOWN]"); 1563 _auxUnknownIndex = (int)_auxItems.Add((AString)"[UNKNOWN]");
1544 } 1564 }
1545 1565
1546 return S_OK; 1566 return S_OK;
1547} 1567}
1548 1568
1549 1569
1550STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 1570Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
1551{ 1571{
1552 COM_TRY_BEGIN 1572 COM_TRY_BEGIN
1553 { 1573 {
@@ -1590,7 +1610,7 @@ void CHandler::ClearRefs()
1590} 1610}
1591 1611
1592 1612
1593STDMETHODIMP CHandler::Close() 1613Z7_COM7F_IMF(CHandler::Close())
1594{ 1614{
1595 _totalRead = 0; 1615 _totalRead = 0;
1596 _totalReadPrev = 0; 1616 _totalReadPrev = 0;
@@ -1652,7 +1672,7 @@ void CHandler::GetPath(unsigned index, AString &s) const
1652 const CNode &node = _nodes[_refs[item.ParentNode]]; 1672 const CNode &node = _nodes[_refs[item.ParentNode]];
1653 if (node.ItemIndex < 0) 1673 if (node.ItemIndex < 0)
1654 return; 1674 return;
1655 index = node.ItemIndex; 1675 index = (unsigned)node.ItemIndex;
1656 1676
1657 if (s.Len() > ((UInt32)1 << 16)) 1677 if (s.Len() > ((UInt32)1 << 16))
1658 { 1678 {
@@ -1707,7 +1727,7 @@ bool CHandler::GetPackSize(unsigned index, UInt64 &totalPack) const
1707} 1727}
1708 1728
1709 1729
1710STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1730Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1711{ 1731{
1712 *numItems = _items.Size() + _auxItems.Size(); 1732 *numItems = _items.Size() + _auxItems.Size();
1713 return S_OK; 1733 return S_OK;
@@ -1797,7 +1817,7 @@ static void UnixTimeToProp(UInt32 val, NCOM::CPropVariant &prop)
1797 PropVariant_SetFrom_UnixTime(prop, val); 1817 PropVariant_SetFrom_UnixTime(prop, val);
1798} 1818}
1799 1819
1800STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1820Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1801{ 1821{
1802 COM_TRY_BEGIN 1822 COM_TRY_BEGIN
1803 1823
@@ -1869,7 +1889,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1869 case kpidErrorFlags: 1889 case kpidErrorFlags:
1870 { 1890 {
1871 UInt32 v = 0; 1891 UInt32 v = 0;
1872 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 1892 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
1873 if (_linksError) v |= kpv_ErrorFlags_HeadersError; 1893 if (_linksError) v |= kpv_ErrorFlags_HeadersError;
1874 if (_headersError) v |= kpv_ErrorFlags_HeadersError; 1894 if (_headersError) v |= kpv_ErrorFlags_HeadersError;
1875 if (!_stream && v == 0 && _isArc) 1895 if (!_stream && v == 0 && _isArc)
@@ -1903,22 +1923,22 @@ static const Byte kRawProps[] =
1903}; 1923};
1904*/ 1924*/
1905 1925
1906STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 1926Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
1907{ 1927{
1908 // *numProps = ARRAY_SIZE(kRawProps); 1928 // *numProps = Z7_ARRAY_SIZE(kRawProps);
1909 *numProps = 0; 1929 *numProps = 0;
1910 return S_OK; 1930 return S_OK;
1911} 1931}
1912 1932
1913STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 1933Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
1914{ 1934{
1915 // *propID = kRawProps[index]; 1935 // *propID = kRawProps[index];
1916 *propID = 0; 1936 *propID = 0;
1917 *name = 0; 1937 *name = NULL;
1918 return S_OK; 1938 return S_OK;
1919} 1939}
1920 1940
1921STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 1941Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
1922{ 1942{
1923 *parentType = NParentType::kDir; 1943 *parentType = NParentType::kDir;
1924 *parent = (UInt32)(Int32)-1; 1944 *parent = (UInt32)(Int32)-1;
@@ -1930,22 +1950,22 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
1930 1950
1931 if (item.ParentNode < 0) 1951 if (item.ParentNode < 0)
1932 { 1952 {
1933 int aux = GetParentAux(item); 1953 const int aux = GetParentAux(item);
1934 if (aux >= 0) 1954 if (aux >= 0)
1935 *parent = _items.Size() + aux; 1955 *parent = _items.Size() + (unsigned)aux;
1936 } 1956 }
1937 else 1957 else
1938 { 1958 {
1939 int itemIndex = _nodes[_refs[item.ParentNode]].ItemIndex; 1959 const int itemIndex = _nodes[_refs[item.ParentNode]].ItemIndex;
1940 if (itemIndex >= 0) 1960 if (itemIndex >= 0)
1941 *parent = itemIndex; 1961 *parent = (unsigned)itemIndex;
1942 } 1962 }
1943 1963
1944 return S_OK; 1964 return S_OK;
1945} 1965}
1946 1966
1947 1967
1948STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 1968Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
1949{ 1969{
1950 *data = NULL; 1970 *data = NULL;
1951 *dataSize = 0; 1971 *dataSize = 0;
@@ -2017,7 +2037,7 @@ static void ExtTimeToProp(const CExtTime &t, NCOM::CPropVariant &prop)
2017} 2037}
2018 2038
2019 2039
2020STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 2040Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
2021{ 2041{
2022 COM_TRY_BEGIN 2042 COM_TRY_BEGIN
2023 NCOM::CPropVariant prop; 2043 NCOM::CPropVariant prop;
@@ -2094,7 +2114,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2094 case kpidPosixAttrib: 2114 case kpidPosixAttrib:
2095 { 2115 {
2096 /* 2116 /*
2097 if (node.Type != 0 && node.Type < ARRAY_SIZE(k_TypeToMode)) 2117 if (node.Type != 0 && node.Type < Z7_ARRAY_SIZE(k_TypeToMode))
2098 prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type]; 2118 prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type];
2099 */ 2119 */
2100 prop = (UInt32)(node.Mode); 2120 prop = (UInt32)(node.Mode);
@@ -2137,10 +2157,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2137} 2157}
2138 2158
2139 2159
2140class CClusterInStream2: 2160Z7_CLASS_IMP_IInStream(CClusterInStream2
2141 public IInStream, 2161)
2142 public CMyUnknownImp
2143{
2144 UInt64 _virtPos; 2162 UInt64 _virtPos;
2145 UInt64 _physPos; 2163 UInt64 _physPos;
2146 UInt32 _curRem; 2164 UInt32 _curRem;
@@ -2150,7 +2168,7 @@ public:
2150 CMyComPtr<IInStream> Stream; 2168 CMyComPtr<IInStream> Stream;
2151 CRecordVector<UInt32> Vector; 2169 CRecordVector<UInt32> Vector;
2152 2170
2153 HRESULT SeekToPhys() { return Stream->Seek(_physPos, STREAM_SEEK_SET, NULL); } 2171 HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); }
2154 2172
2155 HRESULT InitAndSeek() 2173 HRESULT InitAndSeek()
2156 { 2174 {
@@ -2164,15 +2182,10 @@ public:
2164 } 2182 }
2165 return S_OK; 2183 return S_OK;
2166 } 2184 }
2167
2168 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
2169
2170 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
2171 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
2172}; 2185};
2173 2186
2174 2187
2175STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedSize) 2188Z7_COM7F_IMF(CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedSize))
2176{ 2189{
2177 if (processedSize) 2190 if (processedSize)
2178 *processedSize = 0; 2191 *processedSize = 0;
@@ -2209,7 +2222,7 @@ STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedS
2209 if (newPos != _physPos) 2222 if (newPos != _physPos)
2210 { 2223 {
2211 _physPos = newPos; 2224 _physPos = newPos;
2212 RINOK(SeekToPhys()); 2225 RINOK(SeekToPhys())
2213 } 2226 }
2214 2227
2215 _curRem = blockSize - offsetInBlock; 2228 _curRem = blockSize - offsetInBlock;
@@ -2229,7 +2242,7 @@ STDMETHODIMP CClusterInStream2::Read(void *data, UInt32 size, UInt32 *processedS
2229 return res; 2242 return res;
2230} 2243}
2231 2244
2232STDMETHODIMP CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 2245Z7_COM7F_IMF(CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
2233{ 2246{
2234 switch (seekOrigin) 2247 switch (seekOrigin)
2235 { 2248 {
@@ -2242,17 +2255,16 @@ STDMETHODIMP CClusterInStream2::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *ne
2242 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 2255 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
2243 if (_virtPos != (UInt64)offset) 2256 if (_virtPos != (UInt64)offset)
2244 _curRem = 0; 2257 _curRem = 0;
2245 _virtPos = offset; 2258 _virtPos = (UInt64)offset;
2246 if (newPosition) 2259 if (newPosition)
2247 *newPosition = offset; 2260 *newPosition = (UInt64)offset;
2248 return S_OK; 2261 return S_OK;
2249} 2262}
2250 2263
2251 2264
2252class CExtInStream: 2265Z7_CLASS_IMP_IInStream(
2253 public IInStream, 2266 CExtInStream
2254 public CMyUnknownImp 2267)
2255{
2256 UInt64 _virtPos; 2268 UInt64 _virtPos;
2257 UInt64 _phyPos; 2269 UInt64 _phyPos;
2258public: 2270public:
@@ -2261,21 +2273,15 @@ public:
2261 CMyComPtr<IInStream> Stream; 2273 CMyComPtr<IInStream> Stream;
2262 CRecordVector<CExtent> Extents; 2274 CRecordVector<CExtent> Extents;
2263 2275
2264 CExtInStream() {}
2265
2266 HRESULT StartSeek() 2276 HRESULT StartSeek()
2267 { 2277 {
2268 _virtPos = 0; 2278 _virtPos = 0;
2269 _phyPos = 0; 2279 _phyPos = 0;
2270 return Stream->Seek(_phyPos, STREAM_SEEK_SET, NULL); 2280 return InStream_SeekSet(Stream, _phyPos);
2271 } 2281 }
2272
2273 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
2274 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
2275 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
2276}; 2282};
2277 2283
2278STDMETHODIMP CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 2284Z7_COM7F_IMF(CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
2279{ 2285{
2280 if (processedSize) 2286 if (processedSize)
2281 *processedSize = 0; 2287 *processedSize = 0;
@@ -2328,18 +2334,18 @@ STDMETHODIMP CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
2328 return S_OK; 2334 return S_OK;
2329 } 2335 }
2330 2336
2331 UInt64 phyBlock = extent.PhyStart + bo; 2337 const UInt64 phyBlock = extent.PhyStart + bo;
2332 UInt64 phy = (phyBlock << BlockBits) + offset; 2338 const UInt64 phy = (phyBlock << BlockBits) + offset;
2333 2339
2334 if (phy != _phyPos) 2340 if (phy != _phyPos)
2335 { 2341 {
2336 RINOK(Stream->Seek(phy, STREAM_SEEK_SET, NULL)); 2342 RINOK(InStream_SeekSet(Stream, phy))
2337 _phyPos = phy; 2343 _phyPos = phy;
2338 } 2344 }
2339 2345
2340 UInt32 realProcessSize = 0; 2346 UInt32 realProcessSize = 0;
2341 2347
2342 HRESULT res = Stream->Read(data, size, &realProcessSize); 2348 const HRESULT res = Stream->Read(data, size, &realProcessSize);
2343 2349
2344 _phyPos += realProcessSize; 2350 _phyPos += realProcessSize;
2345 _virtPos += realProcessSize; 2351 _virtPos += realProcessSize;
@@ -2350,7 +2356,7 @@ STDMETHODIMP CExtInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
2350} 2356}
2351 2357
2352 2358
2353STDMETHODIMP CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 2359Z7_COM7F_IMF(CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
2354{ 2360{
2355 switch (seekOrigin) 2361 switch (seekOrigin)
2356 { 2362 {
@@ -2361,9 +2367,9 @@ STDMETHODIMP CExtInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosi
2361 } 2367 }
2362 if (offset < 0) 2368 if (offset < 0)
2363 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 2369 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
2364 _virtPos = offset; 2370 _virtPos = (UInt64)offset;
2365 if (newPosition) 2371 if (newPosition)
2366 *newPosition = offset; 2372 *newPosition = (UInt64)offset;
2367 return S_OK; 2373 return S_OK;
2368} 2374}
2369 2375
@@ -2377,7 +2383,7 @@ HRESULT CHandler::FillFileBlocks2(UInt32 block, unsigned level, unsigned numBloc
2377 2383
2378 PRF2(printf("\n level = %d, block = %7d", level, (unsigned)block)); 2384 PRF2(printf("\n level = %d, block = %7d", level, (unsigned)block));
2379 2385
2380 RINOK(SeekAndRead(_stream, block, tempBuf, blockSize)); 2386 RINOK(SeekAndRead(_stream, block, tempBuf, blockSize))
2381 2387
2382 const Byte *p = tempBuf; 2388 const Byte *p = tempBuf;
2383 size_t num = (size_t)1 << (_h.BlockBits - 2); 2389 size_t num = (size_t)1 << (_h.BlockBits - 2);
@@ -2408,7 +2414,7 @@ HRESULT CHandler::FillFileBlocks2(UInt32 block, unsigned level, unsigned numBloc
2408 return S_FALSE; 2414 return S_FALSE;
2409 } 2415 }
2410 2416
2411 RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks)); 2417 RINOK(FillFileBlocks2(val, level - 1, numBlocks, blocks))
2412 continue; 2418 continue;
2413 } 2419 }
2414 2420
@@ -2464,7 +2470,7 @@ HRESULT CHandler::FillFileBlocks(const Byte *p, unsigned numBlocks, CRecordVecto
2464 return S_FALSE; 2470 return S_FALSE;
2465 } 2471 }
2466 2472
2467 RINOK(FillFileBlocks2(val, level, numBlocks, blocks)); 2473 RINOK(FillFileBlocks2(val, level, numBlocks, blocks))
2468 } 2474 }
2469 2475
2470 return S_OK; 2476 return S_OK;
@@ -2560,8 +2566,8 @@ HRESULT CHandler::FillExtents(const Byte *p, size_t size, CRecordVector<CExtent>
2560 if (!UpdateExtents(extents, e.VirtBlock)) 2566 if (!UpdateExtents(extents, e.VirtBlock))
2561 return S_FALSE; 2567 return S_FALSE;
2562 2568
2563 RINOK(SeekAndRead(_stream, e.PhyLeaf, tempBuf, blockSize)); 2569 RINOK(SeekAndRead(_stream, e.PhyLeaf, tempBuf, blockSize))
2564 RINOK(FillExtents(tempBuf, blockSize, extents, eth.Depth)); 2570 RINOK(FillExtents(tempBuf, blockSize, extents, eth.Depth))
2565 } 2571 }
2566 2572
2567 return S_OK; 2573 return S_OK;
@@ -2610,7 +2616,7 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea
2610 streamSpec->Size = node.FileSize; 2616 streamSpec->Size = node.FileSize;
2611 streamSpec->Stream = _stream; 2617 streamSpec->Stream = _stream;
2612 2618
2613 RINOK(FillExtents(node.Block, kNodeBlockFieldSize, streamSpec->Extents, -1)); 2619 RINOK(FillExtents(node.Block, kNodeBlockFieldSize, streamSpec->Extents, -1))
2614 2620
2615 UInt32 end = 0; 2621 UInt32 end = 0;
2616 if (!streamSpec->Extents.IsEmpty()) 2622 if (!streamSpec->Extents.IsEmpty())
@@ -2621,7 +2627,7 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea
2621 // return S_FALSE; 2627 // return S_FALSE;
2622 } 2628 }
2623 2629
2624 RINOK(streamSpec->StartSeek()); 2630 RINOK(streamSpec->StartSeek())
2625 } 2631 }
2626 else 2632 else
2627 { 2633 {
@@ -2648,7 +2654,7 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea
2648 } 2654 }
2649 2655
2650 const unsigned specBits = (node.IsFlags_HUGE() ? 0 : _h.BlockBits - 9); 2656 const unsigned specBits = (node.IsFlags_HUGE() ? 0 : _h.BlockBits - 9);
2651 const UInt32 specMask = ((UInt32)1 << specBits) - 1;; 2657 const UInt32 specMask = ((UInt32)1 << specBits) - 1;
2652 if ((node.NumBlocks & specMask) != 0) 2658 if ((node.NumBlocks & specMask) != 0)
2653 return S_FALSE; 2659 return S_FALSE;
2654 const UInt64 numBlocks64_from_header = node.NumBlocks >> specBits; 2660 const UInt64 numBlocks64_from_header = node.NumBlocks >> specBits;
@@ -2670,7 +2676,7 @@ HRESULT CHandler::GetStream_Node(unsigned nodeIndex, ISequentialInStream **strea
2670 streamSpec->Size = node.FileSize; 2676 streamSpec->Size = node.FileSize;
2671 streamSpec->Stream = _stream; 2677 streamSpec->Stream = _stream;
2672 2678
2673 RINOK(FillFileBlocks(node.Block, numBlocks, streamSpec->Vector)); 2679 RINOK(FillFileBlocks(node.Block, numBlocks, streamSpec->Vector))
2674 streamSpec->InitAndSeek(); 2680 streamSpec->InitAndSeek();
2675 } 2681 }
2676 2682
@@ -2690,7 +2696,7 @@ HRESULT CHandler::ExtractNode(unsigned nodeIndex, CByteBuffer &data)
2690 if (size != node.FileSize) 2696 if (size != node.FileSize)
2691 return S_FALSE; 2697 return S_FALSE;
2692 CMyComPtr<ISequentialInStream> inSeqStream; 2698 CMyComPtr<ISequentialInStream> inSeqStream;
2693 RINOK(GetStream_Node(nodeIndex, &inSeqStream)); 2699 RINOK(GetStream_Node(nodeIndex, &inSeqStream))
2694 if (!inSeqStream) 2700 if (!inSeqStream)
2695 return S_FALSE; 2701 return S_FALSE;
2696 data.Alloc(size); 2702 data.Alloc(size);
@@ -2699,11 +2705,11 @@ HRESULT CHandler::ExtractNode(unsigned nodeIndex, CByteBuffer &data)
2699} 2705}
2700 2706
2701 2707
2702STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2708Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2703 Int32 testMode, IArchiveExtractCallback *extractCallback) 2709 Int32 testMode, IArchiveExtractCallback *extractCallback))
2704{ 2710{
2705 COM_TRY_BEGIN 2711 COM_TRY_BEGIN
2706 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 2712 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2707 if (allFilesMode) 2713 if (allFilesMode)
2708 numItems = _items.Size() + _auxItems.Size(); 2714 numItems = _items.Size() + _auxItems.Size();
2709 if (numItems == 0) 2715 if (numItems == 0)
@@ -2714,7 +2720,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2714 2720
2715 for (i = 0; i < numItems; i++) 2721 for (i = 0; i < numItems; i++)
2716 { 2722 {
2717 UInt32 index = allFilesMode ? i : indices[i]; 2723 const UInt32 index = allFilesMode ? i : indices[i];
2718 if (index >= _items.Size()) 2724 if (index >= _items.Size())
2719 continue; 2725 continue;
2720 const CItem &item = _items[index]; 2726 const CItem &item = _items[index];
@@ -2739,24 +2745,24 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2739 { 2745 {
2740 lps->InSize = totalPackSize; 2746 lps->InSize = totalPackSize;
2741 lps->OutSize = totalSize; 2747 lps->OutSize = totalSize;
2742 RINOK(lps->SetCur()); 2748 RINOK(lps->SetCur())
2743 2749
2744 if (i == numItems) 2750 if (i == numItems)
2745 break; 2751 break;
2746 2752
2747 CMyComPtr<ISequentialOutStream> outStream; 2753 CMyComPtr<ISequentialOutStream> outStream;
2748 Int32 askMode = testMode ? 2754 const Int32 askMode = testMode ?
2749 NExtract::NAskMode::kTest : 2755 NExtract::NAskMode::kTest :
2750 NExtract::NAskMode::kExtract; 2756 NExtract::NAskMode::kExtract;
2751 2757
2752 UInt32 index = allFilesMode ? i : indices[i]; 2758 const UInt32 index = allFilesMode ? i : indices[i];
2753 2759
2754 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 2760 RINOK(extractCallback->GetStream(index, &outStream, askMode))
2755 2761
2756 if (index >= _items.Size()) 2762 if (index >= _items.Size())
2757 { 2763 {
2758 RINOK(extractCallback->PrepareOperation(askMode)); 2764 RINOK(extractCallback->PrepareOperation(askMode))
2759 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2765 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2760 continue; 2766 continue;
2761 } 2767 }
2762 2768
@@ -2765,8 +2771,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2765 2771
2766 if (node.IsDir()) 2772 if (node.IsDir())
2767 { 2773 {
2768 RINOK(extractCallback->PrepareOperation(askMode)); 2774 RINOK(extractCallback->PrepareOperation(askMode))
2769 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2775 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2770 continue; 2776 continue;
2771 } 2777 }
2772 2778
@@ -2778,7 +2784,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2778 2784
2779 if (!testMode && !outStream) 2785 if (!testMode && !outStream)
2780 continue; 2786 continue;
2781 RINOK(extractCallback->PrepareOperation(askMode)); 2787 RINOK(extractCallback->PrepareOperation(askMode))
2782 2788
2783 int res = NExtract::NOperationResult::kDataError; 2789 int res = NExtract::NOperationResult::kDataError;
2784 { 2790 {
@@ -2792,7 +2798,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2792 } 2798 }
2793 else 2799 else
2794 { 2800 {
2795 RINOK(hres); 2801 RINOK(hres)
2796 { 2802 {
2797 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); 2803 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress);
2798 if (hres == S_OK) 2804 if (hres == S_OK)
@@ -2806,12 +2812,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2806 } 2812 }
2807 else if (hres != S_FALSE) 2813 else if (hres != S_FALSE)
2808 { 2814 {
2809 RINOK(hres); 2815 RINOK(hres)
2810 } 2816 }
2811 } 2817 }
2812 } 2818 }
2813 } 2819 }
2814 RINOK(extractCallback->SetOperationResult(res)); 2820 RINOK(extractCallback->SetOperationResult(res))
2815 } 2821 }
2816 2822
2817 return S_OK; 2823 return S_OK;
@@ -2819,12 +2825,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2819} 2825}
2820 2826
2821 2827
2822STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 2828Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
2823{ 2829{
2824 *stream = NULL; 2830 *stream = NULL;
2825 if (index >= _items.Size()) 2831 if (index >= _items.Size())
2826 return S_FALSE; 2832 return S_FALSE;
2827 return GetStream_Node(_refs[_items[index].Node], stream); 2833 return GetStream_Node((unsigned)_refs[_items[index].Node], stream);
2828} 2834}
2829 2835
2830 2836
@@ -2854,7 +2860,7 @@ API_FUNC_IsArc IsArc_Ext(const Byte *p, size_t size)
2854static const Byte k_Signature[] = { 0x53, 0xEF }; 2860static const Byte k_Signature[] = { 0x53, 0xEF };
2855 2861
2856REGISTER_ARC_I( 2862REGISTER_ARC_I(
2857 "Ext", "ext ext2 ext3 ext4 img", 0, 0xC7, 2863 "Ext", "ext ext2 ext3 ext4 img", NULL, 0xC7,
2858 k_Signature, 2864 k_Signature,
2859 0x438, 2865 0x438,
2860 0, 2866 0,
diff --git a/CPP/7zip/Archive/FatHandler.cpp b/CPP/7zip/Archive/FatHandler.cpp
index 826b4fd..4a843a8 100644
--- a/CPP/7zip/Archive/FatHandler.cpp
+++ b/CPP/7zip/Archive/FatHandler.cpp
@@ -134,15 +134,15 @@ bool CHeader::Parse(const Byte *p)
134 } 134 }
135 { 135 {
136 { 136 {
137 UInt32 val32 = Get16(p + 11); 137 const UInt32 val32 = Get16(p + 11);
138 int s = GetLog(val32); 138 const int s = GetLog(val32);
139 if (s < 9 || s > 12) 139 if (s < 9 || s > 12)
140 return false; 140 return false;
141 SectorSizeLog = (Byte)s; 141 SectorSizeLog = (Byte)s;
142 } 142 }
143 { 143 {
144 UInt32 val32 = p[13]; 144 const UInt32 val32 = p[13];
145 int s = GetLog(val32); 145 const int s = GetLog(val32);
146 if (s < 0) 146 if (s < 0)
147 return false; 147 return false;
148 SectorsPerClusterLog = (Byte)s; 148 SectorsPerClusterLog = (Byte)s;
@@ -161,10 +161,10 @@ bool CHeader::Parse(const Byte *p)
161 return false; 161 return false;
162 162
163 // we also support images that contain 0 in offset field. 163 // we also support images that contain 0 in offset field.
164 bool isOkOffset = (codeOffset == 0) 164 const bool isOkOffset = (codeOffset == 0)
165 || (codeOffset == (p[0] == 0xEB ? 2 : 3)); 165 || (codeOffset == (p[0] == 0xEB ? 2 : 3));
166 166
167 UInt16 numRootDirEntries = Get16(p + 17); 167 const UInt16 numRootDirEntries = Get16(p + 17);
168 if (numRootDirEntries == 0) 168 if (numRootDirEntries == 0)
169 { 169 {
170 if (codeOffset < 90 && !isOkOffset) 170 if (codeOffset < 90 && !isOkOffset)
@@ -178,7 +178,7 @@ bool CHeader::Parse(const Byte *p)
178 if (codeOffset < 62 - 24 && !isOkOffset) 178 if (codeOffset < 62 - 24 && !isOkOffset)
179 return false; 179 return false;
180 NumFatBits = 0; 180 NumFatBits = 0;
181 UInt32 mask = (1 << (SectorSizeLog - 5)) - 1; 181 const UInt32 mask = (1 << (SectorSizeLog - 5)) - 1;
182 if ((numRootDirEntries & mask) != 0) 182 if ((numRootDirEntries & mask) != 0)
183 return false; 183 return false;
184 NumRootDirSectors = (numRootDirEntries + mask) >> (SectorSizeLog - 5); 184 NumRootDirSectors = (numRootDirEntries + mask) >> (SectorSizeLog - 5);
@@ -187,8 +187,12 @@ bool CHeader::Parse(const Byte *p)
187 NumSectors = Get16(p + 19); 187 NumSectors = Get16(p + 19);
188 if (NumSectors == 0) 188 if (NumSectors == 0)
189 NumSectors = Get32(p + 32); 189 NumSectors = Get32(p + 32);
190 /*
191 // mkfs.fat could create fat32 image with 16-bit number of sectors.
192 // v23: we allow 16-bit value for number of sectors in fat32.
190 else if (IsFat32()) 193 else if (IsFat32())
191 return false; 194 return false;
195 */
192 196
193 MediaType = p[21]; 197 MediaType = p[21];
194 NumFatSectors = Get16(p + 22); 198 NumFatSectors = Get16(p + 22);
@@ -241,19 +245,18 @@ bool CHeader::Parse(const Byte *p)
241 DataSector = RootDirSector + NumRootDirSectors; 245 DataSector = RootDirSector + NumRootDirSectors;
242 if (NumSectors < DataSector) 246 if (NumSectors < DataSector)
243 return false; 247 return false;
244 UInt32 numDataSectors = NumSectors - DataSector; 248 const UInt32 numDataSectors = NumSectors - DataSector;
245 UInt32 numClusters = numDataSectors >> SectorsPerClusterLog; 249 const UInt32 numClusters = numDataSectors >> SectorsPerClusterLog;
246 250
247 BadCluster = 0x0FFFFFF7; 251 BadCluster = 0x0FFFFFF7;
248 if (numClusters < 0xFFF5) 252 // v23: we support unusual (< 0xFFF5) numClusters values in fat32 systems
253 if (NumFatBits != 32)
249 { 254 {
250 if (NumFatBits == 32) 255 if (numClusters >= 0xFFF5)
251 return false; 256 return false;
252 NumFatBits = (Byte)(numClusters < 0xFF5 ? 12 : 16); 257 NumFatBits = (Byte)(numClusters < 0xFF5 ? 12 : 16);
253 BadCluster &= ((1 << NumFatBits) - 1); 258 BadCluster &= ((1 << NumFatBits) - 1);
254 } 259 }
255 else if (NumFatBits != 32)
256 return false;
257 260
258 FatSize = numClusters + 2; 261 FatSize = numClusters + 2;
259 if (FatSize > BadCluster || CalcFatSizeInSectors() > NumFatSectors) 262 if (FatSize > BadCluster || CalcFatSizeInSectors() > NumFatSectors)
@@ -358,7 +361,7 @@ struct CDatabase
358 361
359 UInt64 PhySize; 362 UInt64 PhySize;
360 363
361 CDatabase(): Fat(0) {} 364 CDatabase(): Fat(NULL) {}
362 ~CDatabase() { ClearAndClose(); } 365 ~CDatabase() { ClearAndClose(); }
363 366
364 void Clear(); 367 void Clear();
@@ -366,7 +369,7 @@ struct CDatabase
366 HRESULT OpenProgressFat(bool changeTotal = true); 369 HRESULT OpenProgressFat(bool changeTotal = true);
367 HRESULT OpenProgress(); 370 HRESULT OpenProgress();
368 371
369 UString GetItemPath(Int32 index) const; 372 UString GetItemPath(UInt32 index) const;
370 HRESULT Open(); 373 HRESULT Open();
371 HRESULT ReadDir(Int32 parent, UInt32 cluster, unsigned level); 374 HRESULT ReadDir(Int32 parent, UInt32 cluster, unsigned level);
372 375
@@ -380,7 +383,7 @@ struct CDatabase
380 383
381HRESULT CDatabase::SeekToSector(UInt32 sector) 384HRESULT CDatabase::SeekToSector(UInt32 sector)
382{ 385{
383 return InStream->Seek((UInt64)sector << Header.SectorSizeLog, STREAM_SEEK_SET, NULL); 386 return InStream_SeekSet(InStream, (UInt64)sector << Header.SectorSizeLog);
384} 387}
385 388
386void CDatabase::Clear() 389void CDatabase::Clear()
@@ -392,7 +395,7 @@ void CDatabase::Clear()
392 395
393 Items.Clear(); 396 Items.Clear();
394 delete []Fat; 397 delete []Fat;
395 Fat = 0; 398 Fat = NULL;
396} 399}
397 400
398void CDatabase::ClearAndClose() 401void CDatabase::ClearAndClose()
@@ -409,7 +412,7 @@ HRESULT CDatabase::OpenProgressFat(bool changeTotal)
409 { 412 {
410 UInt64 numTotalBytes = (Header.CalcFatSizeInSectors() << Header.SectorSizeLog) + 413 UInt64 numTotalBytes = (Header.CalcFatSizeInSectors() << Header.SectorSizeLog) +
411 ((UInt64)(Header.FatSize - NumFreeClusters) << Header.ClusterSizeLog); 414 ((UInt64)(Header.FatSize - NumFreeClusters) << Header.ClusterSizeLog);
412 RINOK(OpenCallback->SetTotal(NULL, &numTotalBytes)); 415 RINOK(OpenCallback->SetTotal(NULL, &numTotalBytes))
413 } 416 }
414 return OpenCallback->SetCompleted(NULL, &NumCurUsedBytes); 417 return OpenCallback->SetCompleted(NULL, &NumCurUsedBytes);
415} 418}
@@ -422,14 +425,14 @@ HRESULT CDatabase::OpenProgress()
422 return OpenCallback->SetCompleted(&numItems, &NumCurUsedBytes); 425 return OpenCallback->SetCompleted(&numItems, &NumCurUsedBytes);
423} 426}
424 427
425UString CDatabase::GetItemPath(Int32 index) const 428UString CDatabase::GetItemPath(UInt32 index) const
426{ 429{
427 const CItem *item = &Items[index]; 430 const CItem *item = &Items[index];
428 UString name = item->GetName(); 431 UString name = item->GetName();
429 for (;;) 432 for (;;)
430 { 433 {
431 index = item->Parent; 434 index = (UInt32)item->Parent;
432 if (index < 0) 435 if (item->Parent < 0)
433 return name; 436 return name;
434 item = &Items[index]; 437 item = &Items[index];
435 name.InsertAtFront(WCHAR_PATH_SEPARATOR); 438 name.InsertAtFront(WCHAR_PATH_SEPARATOR);
@@ -464,7 +467,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level)
464 if (!clusterMode) 467 if (!clusterMode)
465 { 468 {
466 blockSize = Header.SectorSize(); 469 blockSize = Header.SectorSize();
467 RINOK(SeekToSector(Header.RootDirSector)); 470 RINOK(SeekToSector(Header.RootDirSector))
468 } 471 }
469 472
470 ByteBuf.Alloc(blockSize); 473 ByteBuf.Alloc(blockSize);
@@ -480,7 +483,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level)
480 483
481 if ((NumDirClusters & 0xFF) == 0) 484 if ((NumDirClusters & 0xFF) == 0)
482 { 485 {
483 RINOK(OpenProgress()); 486 RINOK(OpenProgress())
484 } 487 }
485 488
486 if (clusterMode) 489 if (clusterMode)
@@ -490,7 +493,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level)
490 if (!Header.IsValidCluster(cluster)) 493 if (!Header.IsValidCluster(cluster))
491 return S_FALSE; 494 return S_FALSE;
492 PRF(printf("\nCluster = %4X", cluster)); 495 PRF(printf("\nCluster = %4X", cluster));
493 RINOK(SeekToCluster(cluster)); 496 RINOK(SeekToCluster(cluster))
494 UInt32 newCluster = Fat[cluster]; 497 UInt32 newCluster = Fat[cluster];
495 if ((newCluster & kFatItemUsedByDirMask) != 0) 498 if ((newCluster & kFatItemUsedByDirMask) != 0)
496 return S_FALSE; 499 return S_FALSE;
@@ -502,7 +505,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level)
502 else if (sectorIndex++ >= Header.NumRootDirSectors) 505 else if (sectorIndex++ >= Header.NumRootDirSectors)
503 break; 506 break;
504 507
505 RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)); 508 RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize))
506 } 509 }
507 510
508 const Byte *p = ByteBuf + pos; 511 const Byte *p = ByteBuf + pos;
@@ -621,7 +624,7 @@ HRESULT CDatabase::ReadDir(Int32 parent, UInt32 cluster, unsigned level)
621 if (item.IsDir()) 624 if (item.IsDir())
622 { 625 {
623 PRF(printf("\n%S", GetItemPath(i))); 626 PRF(printf("\n%S", GetItemPath(i)));
624 RINOK(CDatabase::ReadDir(i, item.Cluster, level + 1)); 627 RINOK(CDatabase::ReadDir((int)i, item.Cluster, level + 1))
625 } 628 }
626 } 629 }
627 return S_OK; 630 return S_OK;
@@ -633,11 +636,11 @@ HRESULT CDatabase::Open()
633 bool numFreeClustersDefined = false; 636 bool numFreeClustersDefined = false;
634 { 637 {
635 Byte buf[kHeaderSize]; 638 Byte buf[kHeaderSize];
636 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); 639 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize))
637 if (!Header.Parse(buf)) 640 if (!Header.Parse(buf))
638 return S_FALSE; 641 return S_FALSE;
639 UInt64 fileSize; 642 UInt64 fileSize;
640 RINOK(InStream->Seek(0, STREAM_SEEK_END, &fileSize)); 643 RINOK(InStream_GetSize_SeekToEnd(InStream, fileSize))
641 644
642 /* we comment that check to support truncated images */ 645 /* we comment that check to support truncated images */
643 /* 646 /*
@@ -648,7 +651,7 @@ HRESULT CDatabase::Open()
648 if (Header.IsFat32()) 651 if (Header.IsFat32())
649 { 652 {
650 SeekToSector(Header.FsInfoSector); 653 SeekToSector(Header.FsInfoSector);
651 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); 654 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize))
652 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) 655 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA)
653 return S_FALSE; 656 return S_FALSE;
654 if (Get32(buf) == 0x41615252 && Get32(buf + 484) == 0x61417272) 657 if (Get32(buf) == 0x41615252 && Get32(buf + 484) == 0x61417272)
@@ -666,8 +669,8 @@ HRESULT CDatabase::Open()
666 CByteBuffer byteBuf; 669 CByteBuffer byteBuf;
667 Fat = new UInt32[Header.FatSize]; 670 Fat = new UInt32[Header.FatSize];
668 671
669 RINOK(OpenProgressFat()); 672 RINOK(OpenProgressFat())
670 RINOK(SeekToSector(Header.GetFatSector())); 673 RINOK(SeekToSector(Header.GetFatSector()))
671 if (Header.NumFatBits == 32) 674 if (Header.NumFatBits == 32)
672 { 675 {
673 const UInt32 kBufSize = (1 << 15); 676 const UInt32 kBufSize = (1 << 15);
@@ -679,7 +682,7 @@ HRESULT CDatabase::Open()
679 if (size > kBufSize32) 682 if (size > kBufSize32)
680 size = kBufSize32; 683 size = kBufSize32;
681 UInt32 readSize = Header.SizeToSectors(size * 4) << Header.SectorSizeLog; 684 UInt32 readSize = Header.SizeToSectors(size * 4) << Header.SectorSizeLog;
682 RINOK(ReadStream_FALSE(InStream, byteBuf, readSize)); 685 RINOK(ReadStream_FALSE(InStream, byteBuf, readSize))
683 NumCurUsedBytes += readSize; 686 NumCurUsedBytes += readSize;
684 687
685 const UInt32 *src = (const UInt32 *)(const void *)(const Byte *)byteBuf; 688 const UInt32 *src = (const UInt32 *)(const void *)(const Byte *)byteBuf;
@@ -701,7 +704,7 @@ HRESULT CDatabase::Open()
701 i += size; 704 i += size;
702 if ((i & 0xFFFFF) == 0) 705 if ((i & 0xFFFFF) == 0)
703 { 706 {
704 RINOK(OpenProgressFat(!numFreeClustersDefined)); 707 RINOK(OpenProgressFat(!numFreeClustersDefined))
705 } 708 }
706 } 709 }
707 } 710 }
@@ -711,7 +714,7 @@ HRESULT CDatabase::Open()
711 NumCurUsedBytes += kBufSize; 714 NumCurUsedBytes += kBufSize;
712 byteBuf.Alloc(kBufSize); 715 byteBuf.Alloc(kBufSize);
713 Byte *p = byteBuf; 716 Byte *p = byteBuf;
714 RINOK(ReadStream_FALSE(InStream, p, kBufSize)); 717 RINOK(ReadStream_FALSE(InStream, p, kBufSize))
715 UInt32 fatSize = Header.FatSize; 718 UInt32 fatSize = Header.FatSize;
716 UInt32 *fat = &Fat[0]; 719 UInt32 *fat = &Fat[0];
717 if (Header.NumFatBits == 16) 720 if (Header.NumFatBits == 16)
@@ -730,7 +733,7 @@ HRESULT CDatabase::Open()
730 } 733 }
731 } 734 }
732 735
733 RINOK(OpenProgressFat()); 736 RINOK(OpenProgressFat())
734 737
735 if ((Fat[0] & 0xFF) != Header.MediaType) 738 if ((Fat[0] & 0xFF) != Header.MediaType)
736 { 739 {
@@ -741,28 +744,27 @@ HRESULT CDatabase::Open()
741 return S_FALSE; 744 return S_FALSE;
742 } 745 }
743 746
744 RINOK(ReadDir(-1, Header.RootCluster, 0)); 747 RINOK(ReadDir(-1, Header.RootCluster, 0))
745 748
746 PhySize = Header.GetPhySize(); 749 PhySize = Header.GetPhySize();
747 return S_OK; 750 return S_OK;
748} 751}
749 752
750class CHandler: 753
754
755Z7_class_CHandler_final:
751 public IInArchive, 756 public IInArchive,
752 public IInArchiveGetStream, 757 public IInArchiveGetStream,
753 public CMyUnknownImp, 758 public CMyUnknownImp,
754 CDatabase 759 CDatabase
755{ 760{
756public: 761 Z7_IFACES_IMP_UNK_2(IInArchive, IInArchiveGetStream)
757 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
758 INTERFACE_IInArchive(;)
759 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
760}; 762};
761 763
762STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 764Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
763{ 765{
764 COM_TRY_BEGIN 766 COM_TRY_BEGIN
765 *stream = 0; 767 *stream = NULL;
766 const CItem &item = Items[index]; 768 const CItem &item = Items[index];
767 CClusterInStream *streamSpec = new CClusterInStream; 769 CClusterInStream *streamSpec = new CClusterInStream;
768 CMyComPtr<ISequentialInStream> streamTemp = streamSpec; 770 CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
@@ -796,7 +798,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
796 if (!Header.IsEocAndUnused(cluster)) 798 if (!Header.IsEocAndUnused(cluster))
797 return S_FALSE; 799 return S_FALSE;
798 } 800 }
799 RINOK(streamSpec->InitAndSeek()); 801 RINOK(streamSpec->InitAndSeek())
800 *stream = streamTemp.Detach(); 802 *stream = streamTemp.Detach();
801 return S_OK; 803 return S_OK;
802 COM_TRY_END 804 COM_TRY_END
@@ -873,7 +875,7 @@ static void StringToProp(const Byte *src, unsigned size, NWindows::NCOM::CPropVa
873#define STRING_TO_PROP(s, p) StringToProp(s, sizeof(s), prop) 875#define STRING_TO_PROP(s, p) StringToProp(s, sizeof(s), prop)
874*/ 876*/
875 877
876STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 878Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
877{ 879{
878 COM_TRY_BEGIN 880 COM_TRY_BEGIN
879 NWindows::NCOM::CPropVariant prop; 881 NWindows::NCOM::CPropVariant prop;
@@ -911,7 +913,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
911 COM_TRY_END 913 COM_TRY_END
912} 914}
913 915
914STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 916Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
915{ 917{
916 COM_TRY_BEGIN 918 COM_TRY_BEGIN
917 NWindows::NCOM::CPropVariant prop; 919 NWindows::NCOM::CPropVariant prop;
@@ -933,7 +935,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
933 COM_TRY_END 935 COM_TRY_END
934} 936}
935 937
936STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 938Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
937{ 939{
938 COM_TRY_BEGIN 940 COM_TRY_BEGIN
939 { 941 {
@@ -957,17 +959,17 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
957 COM_TRY_END 959 COM_TRY_END
958} 960}
959 961
960STDMETHODIMP CHandler::Close() 962Z7_COM7F_IMF(CHandler::Close())
961{ 963{
962 ClearAndClose(); 964 ClearAndClose();
963 return S_OK; 965 return S_OK;
964} 966}
965 967
966STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 968Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
967 Int32 testMode, IArchiveExtractCallback *extractCallback) 969 Int32 testMode, IArchiveExtractCallback *extractCallback))
968{ 970{
969 COM_TRY_BEGIN 971 COM_TRY_BEGIN
970 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 972 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
971 if (allFilesMode) 973 if (allFilesMode)
972 numItems = Items.Size(); 974 numItems = Items.Size();
973 if (numItems == 0) 975 if (numItems == 0)
@@ -980,7 +982,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
980 if (!item.IsDir()) 982 if (!item.IsDir())
981 totalSize += item.Size; 983 totalSize += item.Size;
982 } 984 }
983 RINOK(extractCallback->SetTotal(totalSize)); 985 RINOK(extractCallback->SetTotal(totalSize))
984 986
985 UInt64 totalPackSize; 987 UInt64 totalPackSize;
986 totalSize = totalPackSize = 0; 988 totalSize = totalPackSize = 0;
@@ -995,23 +997,25 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
995 CDummyOutStream *outStreamSpec = new CDummyOutStream; 997 CDummyOutStream *outStreamSpec = new CDummyOutStream;
996 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec); 998 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
997 999
998 for (i = 0; i < numItems; i++) 1000 for (i = 0;; i++)
999 { 1001 {
1000 lps->InSize = totalPackSize; 1002 lps->InSize = totalPackSize;
1001 lps->OutSize = totalSize; 1003 lps->OutSize = totalSize;
1002 RINOK(lps->SetCur()); 1004 RINOK(lps->SetCur())
1005 if (i == numItems)
1006 break;
1003 CMyComPtr<ISequentialOutStream> realOutStream; 1007 CMyComPtr<ISequentialOutStream> realOutStream;
1004 Int32 askMode = testMode ? 1008 const Int32 askMode = testMode ?
1005 NExtract::NAskMode::kTest : 1009 NExtract::NAskMode::kTest :
1006 NExtract::NAskMode::kExtract; 1010 NExtract::NAskMode::kExtract;
1007 Int32 index = allFilesMode ? i : indices[i]; 1011 const UInt32 index = allFilesMode ? i : indices[i];
1008 const CItem &item = Items[index]; 1012 const CItem &item = Items[index];
1009 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1013 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1010 1014
1011 if (item.IsDir()) 1015 if (item.IsDir())
1012 { 1016 {
1013 RINOK(extractCallback->PrepareOperation(askMode)); 1017 RINOK(extractCallback->PrepareOperation(askMode))
1014 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1018 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
1015 continue; 1019 continue;
1016 } 1020 }
1017 1021
@@ -1020,7 +1024,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1020 1024
1021 if (!testMode && !realOutStream) 1025 if (!testMode && !realOutStream)
1022 continue; 1026 continue;
1023 RINOK(extractCallback->PrepareOperation(askMode)); 1027 RINOK(extractCallback->PrepareOperation(askMode))
1024 1028
1025 outStreamSpec->SetStream(realOutStream); 1029 outStreamSpec->SetStream(realOutStream);
1026 realOutStream.Release(); 1030 realOutStream.Release();
@@ -1031,22 +1035,22 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1031 HRESULT hres = GetStream(index, &inStream); 1035 HRESULT hres = GetStream(index, &inStream);
1032 if (hres != S_FALSE) 1036 if (hres != S_FALSE)
1033 { 1037 {
1034 RINOK(hres); 1038 RINOK(hres)
1035 if (inStream) 1039 if (inStream)
1036 { 1040 {
1037 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 1041 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
1038 if (copyCoderSpec->TotalSize == item.Size) 1042 if (copyCoderSpec->TotalSize == item.Size)
1039 res = NExtract::NOperationResult::kOK; 1043 res = NExtract::NOperationResult::kOK;
1040 } 1044 }
1041 } 1045 }
1042 outStreamSpec->ReleaseStream(); 1046 outStreamSpec->ReleaseStream();
1043 RINOK(extractCallback->SetOperationResult(res)); 1047 RINOK(extractCallback->SetOperationResult(res))
1044 } 1048 }
1045 return S_OK; 1049 return S_OK;
1046 COM_TRY_END 1050 COM_TRY_END
1047} 1051}
1048 1052
1049STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1053Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1050{ 1054{
1051 *numItems = Items.Size(); 1055 *numItems = Items.Size();
1052 return S_OK; 1056 return S_OK;
@@ -1055,7 +1059,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
1055static const Byte k_Signature[] = { 0x55, 0xAA }; 1059static const Byte k_Signature[] = { 0x55, 0xAA };
1056 1060
1057REGISTER_ARC_I( 1061REGISTER_ARC_I(
1058 "FAT", "fat img", 0, 0xDA, 1062 "FAT", "fat img", NULL, 0xDA,
1059 k_Signature, 1063 k_Signature,
1060 0x1FE, 1064 0x1FE,
1061 0, 1065 0,
diff --git a/CPP/7zip/Archive/FlvHandler.cpp b/CPP/7zip/Archive/FlvHandler.cpp
index 97a7c26..1f746aa 100644
--- a/CPP/7zip/Archive/FlvHandler.cpp
+++ b/CPP/7zip/Archive/FlvHandler.cpp
@@ -64,11 +64,10 @@ struct CItem2
64 bool IsAudio() const { return Type == kType_Audio; } 64 bool IsAudio() const { return Type == kType_Audio; }
65}; 65};
66 66
67class CHandler: 67
68 public IInArchive, 68Z7_CLASS_IMP_CHandler_IInArchive_1(
69 public IInArchiveGetStream, 69 IInArchiveGetStream
70 public CMyUnknownImp 70)
71{
72 CMyComPtr<IInStream> _stream; 71 CMyComPtr<IInStream> _stream;
73 CObjectVector<CItem2> _items2; 72 CObjectVector<CItem2> _items2;
74 CByteBuffer _metadata; 73 CByteBuffer _metadata;
@@ -77,10 +76,6 @@ class CHandler:
77 76
78 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); 77 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback);
79 // AString GetComment(); 78 // AString GetComment();
80public:
81 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
82 INTERFACE_IInArchive(;)
83 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
84}; 79};
85 80
86static const Byte kProps[] = 81static const Byte kProps[] =
@@ -141,7 +136,7 @@ static const char * const g_Rates[4] =
141 , "44 kHz" 136 , "44 kHz"
142}; 137};
143 138
144STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 139Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
145{ 140{
146 NWindows::NCOM::CPropVariant prop; 141 NWindows::NCOM::CPropVariant prop;
147 const CItem2 &item = _items2[index]; 142 const CItem2 &item = _items2[index];
@@ -252,7 +247,7 @@ AString CHandler::GetComment()
252} 247}
253*/ 248*/
254 249
255STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 250Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
256{ 251{
257 // COM_TRY_BEGIN 252 // COM_TRY_BEGIN
258 NWindows::NCOM::CPropVariant prop; 253 NWindows::NCOM::CPropVariant prop;
@@ -271,7 +266,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
271{ 266{
272 const UInt32 kHeaderSize = 13; 267 const UInt32 kHeaderSize = 13;
273 Byte header[kHeaderSize]; 268 Byte header[kHeaderSize];
274 RINOK(ReadStream_FALSE(stream, header, kHeaderSize)); 269 RINOK(ReadStream_FALSE(stream, header, kHeaderSize))
275 if (header[0] != 'F' || 270 if (header[0] != 'F' ||
276 header[1] != 'L' || 271 header[1] != 'L' ||
277 header[2] != 'V' || 272 header[2] != 'V' ||
@@ -358,7 +353,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
358 item2.Props = props; 353 item2.Props = props;
359 item2.NumChunks = 1; 354 item2.NumChunks = 1;
360 item2.SameSubTypes = true; 355 item2.SameSubTypes = true;
361 lasts[item.Type] = _items2.Add(item2); 356 lasts[item.Type] = (int)_items2.Add(item2);
362 } 357 }
363 else 358 else
364 { 359 {
@@ -420,7 +415,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
420 return S_OK; 415 return S_OK;
421} 416}
422 417
423STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) 418Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback))
424{ 419{
425 COM_TRY_BEGIN 420 COM_TRY_BEGIN
426 Close(); 421 Close();
@@ -441,7 +436,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
441 COM_TRY_END 436 COM_TRY_END
442} 437}
443 438
444STDMETHODIMP CHandler::Close() 439Z7_COM7F_IMF(CHandler::Close())
445{ 440{
446 _phySize = 0; 441 _phySize = 0;
447 _stream.Release(); 442 _stream.Release();
@@ -450,17 +445,17 @@ STDMETHODIMP CHandler::Close()
450 return S_OK; 445 return S_OK;
451} 446}
452 447
453STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 448Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
454{ 449{
455 *numItems = _items2.Size(); 450 *numItems = _items2.Size();
456 return S_OK; 451 return S_OK;
457} 452}
458 453
459STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 454Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
460 Int32 testMode, IArchiveExtractCallback *extractCallback) 455 Int32 testMode, IArchiveExtractCallback *extractCallback))
461{ 456{
462 COM_TRY_BEGIN 457 COM_TRY_BEGIN
463 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 458 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
464 if (allFilesMode) 459 if (allFilesMode)
465 numItems = _items2.Size(); 460 numItems = _items2.Size();
466 if (numItems == 0) 461 if (numItems == 0)
@@ -480,32 +475,32 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
480 for (i = 0; i < numItems; i++) 475 for (i = 0; i < numItems; i++)
481 { 476 {
482 lps->InSize = lps->OutSize = totalSize; 477 lps->InSize = lps->OutSize = totalSize;
483 RINOK(lps->SetCur()); 478 RINOK(lps->SetCur())
484 CMyComPtr<ISequentialOutStream> outStream; 479 CMyComPtr<ISequentialOutStream> outStream;
485 Int32 askMode = testMode ? 480 const Int32 askMode = testMode ?
486 NExtract::NAskMode::kTest : 481 NExtract::NAskMode::kTest :
487 NExtract::NAskMode::kExtract; 482 NExtract::NAskMode::kExtract;
488 UInt32 index = allFilesMode ? i : indices[i]; 483 const UInt32 index = allFilesMode ? i : indices[i];
489 const CItem2 &item = _items2[index]; 484 const CItem2 &item = _items2[index];
490 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 485 RINOK(extractCallback->GetStream(index, &outStream, askMode))
491 totalSize += item.Size; 486 totalSize += item.Size;
492 if (!testMode && !outStream) 487 if (!testMode && !outStream)
493 continue; 488 continue;
494 RINOK(extractCallback->PrepareOperation(askMode)); 489 RINOK(extractCallback->PrepareOperation(askMode))
495 if (outStream) 490 if (outStream)
496 { 491 {
497 RINOK(WriteStream(outStream, item.BufSpec->Buf, item.BufSpec->Buf.Size())); 492 RINOK(WriteStream(outStream, item.BufSpec->Buf, item.BufSpec->Buf.Size()))
498 } 493 }
499 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 494 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
500 } 495 }
501 return S_OK; 496 return S_OK;
502 COM_TRY_END 497 COM_TRY_END
503} 498}
504 499
505STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 500Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
506{ 501{
507 COM_TRY_BEGIN 502 COM_TRY_BEGIN
508 *stream = 0; 503 *stream = NULL;
509 CBufInStream *streamSpec = new CBufInStream; 504 CBufInStream *streamSpec = new CBufInStream;
510 CMyComPtr<ISequentialInStream> streamTemp = streamSpec; 505 CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
511 streamSpec->Init(_items2[index].BufSpec); 506 streamSpec->Init(_items2[index].BufSpec);
@@ -517,7 +512,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
517static const Byte k_Signature[] = { 'F', 'L', 'V', 1, }; 512static const Byte k_Signature[] = { 'F', 'L', 'V', 1, };
518 513
519REGISTER_ARC_I( 514REGISTER_ARC_I(
520 "FLV", "flv", 0, 0xD6, 515 "FLV", "flv", NULL, 0xD6,
521 k_Signature, 516 k_Signature,
522 0, 517 0,
523 0, 518 0,
diff --git a/CPP/7zip/Archive/GptHandler.cpp b/CPP/7zip/Archive/GptHandler.cpp
index 0d2caa3..78c76cf 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);
30 30
31namespace NGpt { 31namespace NGpt {
32 32
33#define SIGNATURE { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T', 0, 0, 1, 0 }
34
35static const unsigned k_SignatureSize = 12; 33static const unsigned k_SignatureSize = 12;
36static const Byte k_Signature[k_SignatureSize] = SIGNATURE; 34static const Byte k_Signature[k_SignatureSize] =
35 { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T', 0, 0, 1, 0 };
37 36
38static const UInt32 kSectorSize = 512; 37static const UInt32 kSectorSize = 512;
39 38
@@ -93,29 +92,29 @@ struct CPartType
93 92
94static const CPartType kPartTypes[] = 93static const CPartType kPartTypes[] =
95{ 94{
96 // { 0x0, 0, "Unused" }, 95 // { 0x0, NULL, "Unused" },
97 96
98 { 0x21686148, 0, "BIOS Boot" }, 97 { 0x21686148, NULL, "BIOS Boot" },
99 98
100 { 0xC12A7328, 0, "EFI System" }, 99 { 0xC12A7328, NULL, "EFI System" },
101 { 0x024DEE41, 0, "MBR" }, 100 { 0x024DEE41, NULL, "MBR" },
102 101
103 { 0xE3C9E316, 0, "Windows MSR" }, 102 { 0xE3C9E316, NULL, "Windows MSR" },
104 { 0xEBD0A0A2, 0, "Windows BDP" }, 103 { 0xEBD0A0A2, NULL, "Windows BDP" },
105 { 0x5808C8AA, 0, "Windows LDM Metadata" }, 104 { 0x5808C8AA, NULL, "Windows LDM Metadata" },
106 { 0xAF9B60A0, 0, "Windows LDM Data" }, 105 { 0xAF9B60A0, NULL, "Windows LDM Data" },
107 { 0xDE94BBA4, 0, "Windows Recovery" }, 106 { 0xDE94BBA4, NULL, "Windows Recovery" },
108 // { 0x37AFFC90, 0, "IBM GPFS" }, 107 // { 0x37AFFC90, NULL, "IBM GPFS" },
109 // { 0xE75CAF8F, 0, "Windows Storage Spaces" }, 108 // { 0xE75CAF8F, NULL, "Windows Storage Spaces" },
110 109
111 { 0x0FC63DAF, 0, "Linux Data" }, 110 { 0x0FC63DAF, NULL, "Linux Data" },
112 { 0x0657FD6D, 0, "Linux Swap" }, 111 { 0x0657FD6D, NULL, "Linux Swap" },
113 112
114 { 0x83BD6B9D, 0, "FreeBSD Boot" }, 113 { 0x83BD6B9D, NULL, "FreeBSD Boot" },
115 { 0x516E7CB4, 0, "FreeBSD Data" }, 114 { 0x516E7CB4, NULL, "FreeBSD Data" },
116 { 0x516E7CB5, 0, "FreeBSD Swap" }, 115 { 0x516E7CB5, NULL, "FreeBSD Swap" },
117 { 0x516E7CB6, "ufs", "FreeBSD UFS" }, 116 { 0x516E7CB6, "ufs", "FreeBSD UFS" },
118 { 0x516E7CB8, 0, "FreeBSD Vinum" }, 117 { 0x516E7CB8, NULL, "FreeBSD Vinum" },
119 { 0x516E7CB8, "zfs", "FreeBSD ZFS" }, 118 { 0x516E7CB8, "zfs", "FreeBSD ZFS" },
120 119
121 { 0x48465300, "hfsx", "HFS+" }, 120 { 0x48465300, "hfsx", "HFS+" },
@@ -124,10 +123,10 @@ static const CPartType kPartTypes[] =
124 123
125static int FindPartType(const Byte *guid) 124static int FindPartType(const Byte *guid)
126{ 125{
127 UInt32 val = Get32(guid); 126 const UInt32 val = Get32(guid);
128 for (unsigned i = 0; i < ARRAY_SIZE(kPartTypes); i++) 127 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPartTypes); i++)
129 if (kPartTypes[i].Id == val) 128 if (kPartTypes[i].Id == val)
130 return i; 129 return (int)i;
131 return -1; 130 return -1;
132} 131}
133 132
@@ -139,8 +138,10 @@ static void RawLeGuidToString_Upper(const Byte *g, char *s)
139} 138}
140 139
141 140
142class CHandler: public CHandlerCont 141Z7_class_CHandler_final: public CHandlerCont
143{ 142{
143 Z7_IFACE_COM7_IMP(IInArchive_Cont)
144
144 CRecordVector<CPartition> _items; 145 CRecordVector<CPartition> _items;
145 UInt64 _totalSize; 146 UInt64 _totalSize;
146 Byte Guid[16]; 147 Byte Guid[16];
@@ -149,23 +150,20 @@ class CHandler: public CHandlerCont
149 150
150 HRESULT Open2(IInStream *stream); 151 HRESULT Open2(IInStream *stream);
151 152
152 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const 153 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override
153 { 154 {
154 const CPartition &item = _items[index]; 155 const CPartition &item = _items[index];
155 pos = item.GetPos(); 156 pos = item.GetPos();
156 size = item.GetSize(); 157 size = item.GetSize();
157 return NExtract::NOperationResult::kOK; 158 return NExtract::NOperationResult::kOK;
158 } 159 }
159
160public:
161 INTERFACE_IInArchive_Cont(;)
162}; 160};
163 161
164 162
165HRESULT CHandler::Open2(IInStream *stream) 163HRESULT CHandler::Open2(IInStream *stream)
166{ 164{
167 _buffer.Alloc(kSectorSize * 2); 165 _buffer.Alloc(kSectorSize * 2);
168 RINOK(ReadStream_FALSE(stream, _buffer, kSectorSize * 2)); 166 RINOK(ReadStream_FALSE(stream, _buffer, kSectorSize * 2))
169 167
170 const Byte *buf = _buffer; 168 const Byte *buf = _buffer;
171 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) 169 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA)
@@ -180,24 +178,24 @@ HRESULT CHandler::Open2(IInStream *stream)
180 if (headerSize > kSectorSize) 178 if (headerSize > kSectorSize)
181 return S_FALSE; 179 return S_FALSE;
182 UInt32 crc = Get32(buf + 0x10); 180 UInt32 crc = Get32(buf + 0x10);
183 SetUi32(_buffer + kSectorSize + 0x10, 0); 181 SetUi32(_buffer + kSectorSize + 0x10, 0)
184 if (CrcCalc(_buffer + kSectorSize, headerSize) != crc) 182 if (CrcCalc(_buffer + kSectorSize, headerSize) != crc)
185 return S_FALSE; 183 return S_FALSE;
186 } 184 }
187 // UInt32 reserved = Get32(buf + 0x14); 185 // UInt32 reserved = Get32(buf + 0x14);
188 UInt64 curLba = Get64(buf + 0x18); 186 const UInt64 curLba = Get64(buf + 0x18);
189 if (curLba != 1) 187 if (curLba != 1)
190 return S_FALSE; 188 return S_FALSE;
191 UInt64 backupLba = Get64(buf + 0x20); 189 const UInt64 backupLba = Get64(buf + 0x20);
192 // UInt64 firstUsableLba = Get64(buf + 0x28); 190 // UInt64 firstUsableLba = Get64(buf + 0x28);
193 // UInt64 lastUsableLba = Get64(buf + 0x30); 191 // UInt64 lastUsableLba = Get64(buf + 0x30);
194 memcpy(Guid, buf + 0x38, 16); 192 memcpy(Guid, buf + 0x38, 16);
195 UInt64 tableLba = Get64(buf + 0x48); 193 const UInt64 tableLba = Get64(buf + 0x48);
196 if (tableLba < 2) 194 if (tableLba < 2)
197 return S_FALSE; 195 return S_FALSE;
198 UInt32 numEntries = Get32(buf + 0x50); 196 const UInt32 numEntries = Get32(buf + 0x50);
199 UInt32 entrySize = Get32(buf + 0x54); // = 128 usually 197 const UInt32 entrySize = Get32(buf + 0x54); // = 128 usually
200 UInt32 entriesCrc = Get32(buf + 0x58); 198 const UInt32 entriesCrc = Get32(buf + 0x58);
201 199
202 if (entrySize < 128 200 if (entrySize < 128
203 || entrySize > (1 << 12) 201 || entrySize > (1 << 12)
@@ -206,12 +204,12 @@ HRESULT CHandler::Open2(IInStream *stream)
206 || tableLba >= ((UInt64)1 << (64 - 10))) 204 || tableLba >= ((UInt64)1 << (64 - 10)))
207 return S_FALSE; 205 return S_FALSE;
208 206
209 UInt32 tableSize = entrySize * numEntries; 207 const UInt32 tableSize = entrySize * numEntries;
210 UInt32 tableSizeAligned = (tableSize + kSectorSize - 1) & ~(kSectorSize - 1); 208 const UInt32 tableSizeAligned = (tableSize + kSectorSize - 1) & ~(kSectorSize - 1);
211 _buffer.Alloc(tableSizeAligned); 209 _buffer.Alloc(tableSizeAligned);
212 UInt64 tableOffset = tableLba * kSectorSize; 210 const UInt64 tableOffset = tableLba * kSectorSize;
213 RINOK(stream->Seek(tableOffset, STREAM_SEEK_SET, NULL)); 211 RINOK(InStream_SeekSet(stream, tableOffset))
214 RINOK(ReadStream_FALSE(stream, _buffer, tableSizeAligned)); 212 RINOK(ReadStream_FALSE(stream, _buffer, tableSizeAligned))
215 213
216 if (CrcCalc(_buffer, tableSize) != entriesCrc) 214 if (CrcCalc(_buffer, tableSize) != entriesCrc)
217 return S_FALSE; 215 return S_FALSE;
@@ -238,7 +236,7 @@ HRESULT CHandler::Open2(IInStream *stream)
238 236
239 { 237 {
240 UInt64 fileEnd; 238 UInt64 fileEnd;
241 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileEnd)); 239 RINOK(InStream_GetSize_SeekToEnd(stream, fileEnd))
242 240
243 if (_totalSize < fileEnd) 241 if (_totalSize < fileEnd)
244 { 242 {
@@ -246,7 +244,7 @@ HRESULT CHandler::Open2(IInStream *stream)
246 const UInt64 kRemMax = 1 << 22; 244 const UInt64 kRemMax = 1 << 22;
247 if (rem <= kRemMax) 245 if (rem <= kRemMax)
248 { 246 {
249 RINOK(stream->Seek(_totalSize, STREAM_SEEK_SET, NULL)); 247 RINOK(InStream_SeekSet(stream, _totalSize))
250 bool areThereNonZeros = false; 248 bool areThereNonZeros = false;
251 UInt64 numZeros = 0; 249 UInt64 numZeros = 0;
252 if (ReadZeroTail(stream, areThereNonZeros, numZeros, kRemMax) == S_OK) 250 if (ReadZeroTail(stream, areThereNonZeros, numZeros, kRemMax) == S_OK)
@@ -269,7 +267,7 @@ static bool IsNtfs(const Byte *p)
269{ 267{
270 if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA) 268 if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA)
271 return false; 269 return false;
272 if (memcmp(p + 3, k_NtfsSignature, ARRAY_SIZE(k_NtfsSignature)) != 0) 270 if (memcmp(p + 3, k_NtfsSignature, Z7_ARRAY_SIZE(k_NtfsSignature)) != 0)
273 return false; 271 return false;
274 switch (p[0]) 272 switch (p[0])
275 { 273 {
@@ -281,13 +279,13 @@ static bool IsNtfs(const Byte *p)
281} 279}
282 280
283 281
284STDMETHODIMP CHandler::Open(IInStream *stream, 282Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
285 const UInt64 * /* maxCheckStartPosition */, 283 const UInt64 * /* maxCheckStartPosition */,
286 IArchiveOpenCallback * /* openArchiveCallback */) 284 IArchiveOpenCallback * /* openArchiveCallback */))
287{ 285{
288 COM_TRY_BEGIN 286 COM_TRY_BEGIN
289 Close(); 287 Close();
290 RINOK(Open2(stream)); 288 RINOK(Open2(stream))
291 _stream = stream; 289 _stream = stream;
292 290
293 FOR_VECTOR (fileIndex, _items) 291 FOR_VECTOR (fileIndex, _items)
@@ -305,7 +303,9 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
305 if (t.Type && IsString1PrefixedByString2_NoCase_Ascii(t.Type, "Windows")) 303 if (t.Type && IsString1PrefixedByString2_NoCase_Ascii(t.Type, "Windows"))
306 { 304 {
307 CMyComPtr<ISequentialInStream> inStream; 305 CMyComPtr<ISequentialInStream> inStream;
308 if (GetStream(fileIndex, &inStream) == S_OK && inStream) 306 if (
307 // ((IInArchiveGetStream *)this)->
308 GetStream(fileIndex, &inStream) == S_OK && inStream)
309 { 309 {
310 Byte temp[k_Ntfs_Fat_HeaderSize]; 310 Byte temp[k_Ntfs_Fat_HeaderSize];
311 if (ReadStream_FAIL(inStream, temp, k_Ntfs_Fat_HeaderSize) == S_OK) 311 if (ReadStream_FAIL(inStream, temp, k_Ntfs_Fat_HeaderSize) == S_OK)
@@ -329,7 +329,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
329 COM_TRY_END 329 COM_TRY_END
330} 330}
331 331
332STDMETHODIMP CHandler::Close() 332Z7_COM7F_IMF(CHandler::Close())
333{ 333{
334 _totalSize = 0; 334 _totalSize = 0;
335 memset(Guid, 0, sizeof(Guid)); 335 memset(Guid, 0, sizeof(Guid));
@@ -356,7 +356,7 @@ static const Byte kArcProps[] =
356IMP_IInArchive_Props 356IMP_IInArchive_Props
357IMP_IInArchive_ArcProps 357IMP_IInArchive_ArcProps
358 358
359STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 359Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
360{ 360{
361 COM_TRY_BEGIN 361 COM_TRY_BEGIN
362 NCOM::CPropVariant prop; 362 NCOM::CPropVariant prop;
@@ -382,13 +382,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
382 COM_TRY_END 382 COM_TRY_END
383} 383}
384 384
385STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 385Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
386{ 386{
387 *numItems = _items.Size(); 387 *numItems = _items.Size();
388 return S_OK; 388 return S_OK;
389} 389}
390 390
391STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 391Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
392{ 392{
393 COM_TRY_BEGIN 393 COM_TRY_BEGIN
394 NCOM::CPropVariant prop; 394 NCOM::CPropVariant prop;
@@ -414,12 +414,12 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
414 } 414 }
415 if (!s2.IsEmpty()) 415 if (!s2.IsEmpty())
416 { 416 {
417 s += '.'; 417 s.Add_Dot();
418 s += s2; 418 s += s2;
419 } 419 }
420 } 420 }
421 { 421 {
422 s += '.'; 422 s.Add_Dot();
423 s += (item.Ext ? item.Ext : "img"); 423 s += (item.Ext ? item.Ext : "img");
424 } 424 }
425 prop = s; 425 prop = s;
diff --git a/CPP/7zip/Archive/GzHandler.cpp b/CPP/7zip/Archive/GzHandler.cpp
index 35e642e..ad9a074 100644
--- a/CPP/7zip/Archive/GzHandler.cpp
+++ b/CPP/7zip/Archive/GzHandler.cpp
@@ -354,7 +354,7 @@ HRESULT CItem::ReadHeader(NDecoder::CCOMCoder *stream)
354 // UInt32 crc = CRC_INIT_VAL; 354 // UInt32 crc = CRC_INIT_VAL;
355 Byte buf[10]; 355 Byte buf[10];
356 356
357 RINOK(ReadBytes(stream, buf, 10)); 357 RINOK(ReadBytes(stream, buf, 10))
358 358
359 if (buf[0] != kSignature_0 || 359 if (buf[0] != kSignature_0 ||
360 buf[1] != kSignature_1 || 360 buf[1] != kSignature_1 ||
@@ -374,22 +374,22 @@ HRESULT CItem::ReadHeader(NDecoder::CCOMCoder *stream)
374 if (ExtraFieldIsPresent()) 374 if (ExtraFieldIsPresent())
375 { 375 {
376 UInt32 xlen; 376 UInt32 xlen;
377 RINOK(ReadUInt16(stream, xlen /* , crc */)); 377 RINOK(ReadUInt16(stream, xlen /* , crc */))
378 RINOK(SkipBytes(stream, xlen)); 378 RINOK(SkipBytes(stream, xlen))
379 // Extra.SetCapacity(xlen); 379 // Extra.SetCapacity(xlen);
380 // RINOK(ReadStream_FALSE(stream, Extra, xlen)); 380 // RINOK(ReadStream_FALSE(stream, Extra, xlen));
381 // crc = CrcUpdate(crc, Extra, xlen); 381 // crc = CrcUpdate(crc, Extra, xlen);
382 } 382 }
383 if (NameIsPresent()) 383 if (NameIsPresent())
384 RINOK(ReadString(stream, Name, kNameMaxLen /* , crc */)); 384 RINOK(ReadString(stream, Name, kNameMaxLen /* , crc */))
385 if (CommentIsPresent()) 385 if (CommentIsPresent())
386 RINOK(ReadString(stream, Comment, kCommentMaxLen /* , crc */)); 386 RINOK(ReadString(stream, Comment, kCommentMaxLen /* , crc */))
387 387
388 if (HeaderCrcIsPresent()) 388 if (HeaderCrcIsPresent())
389 { 389 {
390 UInt32 headerCRC; 390 UInt32 headerCRC;
391 // UInt32 dummy = 0; 391 // UInt32 dummy = 0;
392 RINOK(ReadUInt16(stream, headerCRC /* , dummy */)); 392 RINOK(ReadUInt16(stream, headerCRC /* , dummy */))
393 /* 393 /*
394 if ((UInt16)CRC_GET_DIGEST(crc) != headerCRC) 394 if ((UInt16)CRC_GET_DIGEST(crc) != headerCRC)
395 return S_FALSE; 395 return S_FALSE;
@@ -401,7 +401,7 @@ HRESULT CItem::ReadHeader(NDecoder::CCOMCoder *stream)
401HRESULT CItem::ReadFooter1(NDecoder::CCOMCoder *stream) 401HRESULT CItem::ReadFooter1(NDecoder::CCOMCoder *stream)
402{ 402{
403 Byte buf[8]; 403 Byte buf[8];
404 RINOK(ReadBytes(stream, buf, 8)); 404 RINOK(ReadBytes(stream, buf, 8))
405 Crc = Get32(buf); 405 Crc = Get32(buf);
406 Size32 = Get32(buf + 4); 406 Size32 = Get32(buf + 4);
407 return stream->InputEofError() ? S_FALSE : S_OK; 407 return stream->InputEofError() ? S_FALSE : S_OK;
@@ -410,7 +410,7 @@ HRESULT CItem::ReadFooter1(NDecoder::CCOMCoder *stream)
410HRESULT CItem::ReadFooter2(ISequentialInStream *stream) 410HRESULT CItem::ReadFooter2(ISequentialInStream *stream)
411{ 411{
412 Byte buf[8]; 412 Byte buf[8];
413 RINOK(ReadStream_FALSE(stream, buf, 8)); 413 RINOK(ReadStream_FALSE(stream, buf, 8))
414 Crc = Get32(buf); 414 Crc = Get32(buf);
415 Size32 = Get32(buf + 4); 415 Size32 = Get32(buf + 4);
416 return S_OK; 416 return S_OK;
@@ -424,15 +424,15 @@ HRESULT CItem::WriteHeader(ISequentialOutStream *stream)
424 buf[2] = kSignature_2; 424 buf[2] = kSignature_2;
425 buf[3] = (Byte)(Flags & NFlags::kName); 425 buf[3] = (Byte)(Flags & NFlags::kName);
426 // buf[3] |= NFlags::kCrc; 426 // buf[3] |= NFlags::kCrc;
427 SetUi32(buf + 4, Time); 427 SetUi32(buf + 4, Time)
428 buf[8] = ExtraFlags; 428 buf[8] = ExtraFlags;
429 buf[9] = HostOS; 429 buf[9] = HostOS;
430 RINOK(WriteStream(stream, buf, 10)); 430 RINOK(WriteStream(stream, buf, 10))
431 // crc = CrcUpdate(CRC_INIT_VAL, buf, 10); 431 // crc = CrcUpdate(CRC_INIT_VAL, buf, 10);
432 if (NameIsPresent()) 432 if (NameIsPresent())
433 { 433 {
434 // crc = CrcUpdate(crc, (const char *)Name, Name.Len() + 1); 434 // crc = CrcUpdate(crc, (const char *)Name, Name.Len() + 1);
435 RINOK(WriteStream(stream, (const char *)Name, Name.Len() + 1)); 435 RINOK(WriteStream(stream, (const char *)Name, Name.Len() + 1))
436 } 436 }
437 // SetUi16(buf, (UInt16)CRC_GET_DIGEST(crc)); 437 // SetUi16(buf, (UInt16)CRC_GET_DIGEST(crc));
438 // RINOK(WriteStream(stream, buf, 2)); 438 // RINOK(WriteStream(stream, buf, 2));
@@ -442,18 +442,16 @@ HRESULT CItem::WriteHeader(ISequentialOutStream *stream)
442HRESULT CItem::WriteFooter(ISequentialOutStream *stream) 442HRESULT CItem::WriteFooter(ISequentialOutStream *stream)
443{ 443{
444 Byte buf[8]; 444 Byte buf[8];
445 SetUi32(buf, Crc); 445 SetUi32(buf, Crc)
446 SetUi32(buf + 4, Size32); 446 SetUi32(buf + 4, Size32)
447 return WriteStream(stream, buf, 8); 447 return WriteStream(stream, buf, 8);
448} 448}
449 449
450class CHandler: 450Z7_CLASS_IMP_CHandler_IInArchive_3(
451 public IInArchive, 451 IArchiveOpenSeq,
452 public IArchiveOpenSeq, 452 IOutArchive,
453 public IOutArchive, 453 ISetProperties
454 public ISetProperties, 454)
455 public CMyUnknownImp
456{
457 CItem _item; 455 CItem _item;
458 456
459 bool _isArc; 457 bool _isArc;
@@ -478,16 +476,6 @@ class CHandler:
478 CHandlerTimeOptions _timeOptions; 476 CHandlerTimeOptions _timeOptions;
479 477
480public: 478public:
481 MY_UNKNOWN_IMP4(
482 IInArchive,
483 IArchiveOpenSeq,
484 IOutArchive,
485 ISetProperties)
486 INTERFACE_IInArchive(;)
487 INTERFACE_IOutArchive(;)
488 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
489 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
490
491 CHandler(): 479 CHandler():
492 _isArc(false), 480 _isArc(false),
493 _decoderSpec(NULL) 481 _decoderSpec(NULL)
@@ -523,7 +511,7 @@ static const Byte kArcProps[] =
523IMP_IInArchive_Props 511IMP_IInArchive_Props
524IMP_IInArchive_ArcProps 512IMP_IInArchive_ArcProps
525 513
526STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 514Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
527{ 515{
528 COM_TRY_BEGIN 516 COM_TRY_BEGIN
529 NCOM::CPropVariant prop; 517 NCOM::CPropVariant prop;
@@ -557,13 +545,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
557} 545}
558 546
559 547
560STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 548Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
561{ 549{
562 *numItems = 1; 550 *numItems = 1;
563 return S_OK; 551 return S_OK;
564} 552}
565 553
566STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 554Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
567{ 555{
568 COM_TRY_BEGIN 556 COM_TRY_BEGIN
569 NCOM::CPropVariant prop; 557 NCOM::CPropVariant prop;
@@ -605,19 +593,17 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
605 COM_TRY_END 593 COM_TRY_END
606} 594}
607 595
608class CCompressProgressInfoImp: 596Z7_CLASS_IMP_COM_1(
609 public ICompressProgressInfo, 597 CCompressProgressInfoImp,
610 public CMyUnknownImp 598 ICompressProgressInfo
611{ 599)
612 CMyComPtr<IArchiveOpenCallback> Callback; 600 CMyComPtr<IArchiveOpenCallback> Callback;
613public: 601public:
614 UInt64 Offset; 602 UInt64 Offset;
615 MY_UNKNOWN_IMP1(ICompressProgressInfo)
616 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
617 void Init(IArchiveOpenCallback *callback) { Callback = callback; } 603 void Init(IArchiveOpenCallback *callback) { Callback = callback; }
618}; 604};
619 605
620STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) 606Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */))
621{ 607{
622 if (Callback) 608 if (Callback)
623 { 609 {
@@ -631,15 +617,15 @@ STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const
631/* 617/*
632*/ 618*/
633 619
634STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) 620Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *))
635{ 621{
636 COM_TRY_BEGIN 622 COM_TRY_BEGIN
637 RINOK(OpenSeq(stream)); 623 RINOK(OpenSeq(stream))
638 _isArc = false; 624 _isArc = false;
639 UInt64 endPos; 625 UInt64 endPos;
640 RINOK(stream->Seek(-8, STREAM_SEEK_END, &endPos)); 626 RINOK(stream->Seek(-8, STREAM_SEEK_END, &endPos))
641 _packSize = endPos + 8; 627 _packSize = endPos + 8;
642 RINOK(_item.ReadFooter2(stream)); 628 RINOK(_item.ReadFooter2(stream))
643 _stream = stream; 629 _stream = stream;
644 _isArc = true; 630 _isArc = true;
645 _needSeekToStart = true; 631 _needSeekToStart = true;
@@ -647,7 +633,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
647 COM_TRY_END 633 COM_TRY_END
648} 634}
649 635
650STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 636Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
651{ 637{
652 COM_TRY_BEGIN 638 COM_TRY_BEGIN
653 try 639 try
@@ -656,7 +642,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
656 CreateDecoder(); 642 CreateDecoder();
657 _decoderSpec->SetInStream(stream); 643 _decoderSpec->SetInStream(stream);
658 _decoderSpec->InitInStream(true); 644 _decoderSpec->InitInStream(true);
659 RINOK(_item.ReadHeader(_decoderSpec)); 645 RINOK(_item.ReadHeader(_decoderSpec))
660 if (_decoderSpec->InputEofError()) 646 if (_decoderSpec->InputEofError())
661 return S_FALSE; 647 return S_FALSE;
662 _headerSize = _decoderSpec->GetInputProcessedSize(); 648 _headerSize = _decoderSpec->GetInputProcessedSize();
@@ -667,7 +653,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
667 COM_TRY_END 653 COM_TRY_END
668} 654}
669 655
670STDMETHODIMP CHandler::Close() 656Z7_COM7F_IMF(CHandler::Close())
671{ 657{
672 _isArc = false; 658 _isArc = false;
673 _needSeekToStart = false; 659 _needSeekToStart = false;
@@ -687,8 +673,8 @@ STDMETHODIMP CHandler::Close()
687 return S_OK; 673 return S_OK;
688} 674}
689 675
690STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 676Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
691 Int32 testMode, IArchiveExtractCallback *extractCallback) 677 Int32 testMode, IArchiveExtractCallback *extractCallback))
692{ 678{
693 COM_TRY_BEGIN 679 COM_TRY_BEGIN
694 if (numItems == 0) 680 if (numItems == 0)
@@ -701,10 +687,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
701 // UInt64 currentTotalPacked = 0; 687 // UInt64 currentTotalPacked = 0;
702 // RINOK(extractCallback->SetCompleted(&currentTotalPacked)); 688 // RINOK(extractCallback->SetCompleted(&currentTotalPacked));
703 CMyComPtr<ISequentialOutStream> realOutStream; 689 CMyComPtr<ISequentialOutStream> realOutStream;
704 Int32 askMode = testMode ? 690 const Int32 askMode = testMode ?
705 NExtract::NAskMode::kTest : 691 NExtract::NAskMode::kTest :
706 NExtract::NAskMode::kExtract; 692 NExtract::NAskMode::kExtract;
707 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 693 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
708 if (!testMode && !realOutStream) 694 if (!testMode && !realOutStream)
709 return S_OK; 695 return S_OK;
710 696
@@ -728,7 +714,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
728 { 714 {
729 if (!_stream) 715 if (!_stream)
730 return E_FAIL; 716 return E_FAIL;
731 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 717 RINOK(InStream_SeekToBegin(_stream))
732 _decoderSpec->InitInStream(true); 718 _decoderSpec->InitInStream(true);
733 // printf("\nSeek"); 719 // printf("\nSeek");
734 } 720 }
@@ -754,7 +740,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
754 lps->InSize = packSize; 740 lps->InSize = packSize;
755 lps->OutSize = unpackedSize; 741 lps->OutSize = unpackedSize;
756 742
757 RINOK(lps->SetCur()); 743 RINOK(lps->SetCur())
758 744
759 CItem item; 745 CItem item;
760 746
@@ -954,14 +940,15 @@ static HRESULT UpdateArchive(
954 { 940 {
955 CMyComPtr<ISequentialInStream> fileInStream; 941 CMyComPtr<ISequentialInStream> fileInStream;
956 942
957 RINOK(updateCallback->GetStream(0, &fileInStream)); 943 RINOK(updateCallback->GetStream(0, &fileInStream))
958 944
959 if (!fileInStream) 945 if (!fileInStream)
960 return S_FALSE; 946 return S_FALSE;
961 947
962 { 948 {
963 CMyComPtr<IStreamGetProps> getProps; 949 Z7_DECL_CMyComPtr_QI_FROM(
964 fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); 950 IStreamGetProps,
951 getProps, fileInStream)
965 if (getProps) 952 if (getProps)
966 { 953 {
967 FILETIME mTime; 954 FILETIME mTime;
@@ -976,8 +963,8 @@ static HRESULT UpdateArchive(
976 } 963 }
977 964
978 UInt64 complexity = 0; 965 UInt64 complexity = 0;
979 RINOK(updateCallback->SetTotal(unpackSize)); 966 RINOK(updateCallback->SetTotal(unpackSize))
980 RINOK(updateCallback->SetCompleted(&complexity)); 967 RINOK(updateCallback->SetCompleted(&complexity))
981 968
982 CSequentialInStreamWithCRC *inStreamSpec = new CSequentialInStreamWithCRC; 969 CSequentialInStreamWithCRC *inStreamSpec = new CSequentialInStreamWithCRC;
983 CMyComPtr<ISequentialInStream> crcStream(inStreamSpec); 970 CMyComPtr<ISequentialInStream> crcStream(inStreamSpec);
@@ -994,17 +981,17 @@ static HRESULT UpdateArchive(
994 981
995 item.HostOS = kHostOS; 982 item.HostOS = kHostOS;
996 983
997 RINOK(item.WriteHeader(outStream)); 984 RINOK(item.WriteHeader(outStream))
998 985
999 NEncoder::CCOMCoder *deflateEncoderSpec = new NEncoder::CCOMCoder; 986 NEncoder::CCOMCoder *deflateEncoderSpec = new NEncoder::CCOMCoder;
1000 CMyComPtr<ICompressCoder> deflateEncoder = deflateEncoderSpec; 987 CMyComPtr<ICompressCoder> deflateEncoder = deflateEncoderSpec;
1001 RINOK(props.SetCoderProps(deflateEncoderSpec, NULL)); 988 RINOK(props.SetCoderProps(deflateEncoderSpec, NULL))
1002 RINOK(deflateEncoder->Code(crcStream, outStream, NULL, NULL, progress)); 989 RINOK(deflateEncoder->Code(crcStream, outStream, NULL, NULL, progress))
1003 990
1004 item.Crc = inStreamSpec->GetCRC(); 991 item.Crc = inStreamSpec->GetCRC();
1005 unpackSizeReal = inStreamSpec->GetSize(); 992 unpackSizeReal = inStreamSpec->GetSize();
1006 item.Size32 = (UInt32)unpackSizeReal; 993 item.Size32 = (UInt32)unpackSizeReal;
1007 RINOK(item.WriteFooter(outStream)); 994 RINOK(item.WriteFooter(outStream))
1008 } 995 }
1009 /* 996 /*
1010 if (reportArcProp) 997 if (reportArcProp)
@@ -1020,7 +1007,7 @@ static HRESULT UpdateArchive(
1020} 1007}
1021 1008
1022 1009
1023STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 1010Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType))
1024{ 1011{
1025 /* 1012 /*
1026 if (_item.Time != 0) 1013 if (_item.Time != 0)
@@ -1049,24 +1036,29 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType)
1049 return S_OK; 1036 return S_OK;
1050} 1037}
1051 1038
1052STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 1039Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
1053 IArchiveUpdateCallback *updateCallback) 1040 IArchiveUpdateCallback *updateCallback))
1054{ 1041{
1055 COM_TRY_BEGIN 1042 COM_TRY_BEGIN
1056 1043
1057 if (numItems != 1) 1044 if (numItems != 1)
1058 return E_INVALIDARG; 1045 return E_INVALIDARG;
1059 1046
1047 {
1048 Z7_DECL_CMyComPtr_QI_FROM(
1049 IStreamSetRestriction,
1050 setRestriction, outStream)
1051 if (setRestriction)
1052 RINOK(setRestriction->SetRestriction(0, 0))
1053 }
1054
1060 Int32 newData, newProps; 1055 Int32 newData, newProps;
1061 UInt32 indexInArchive; 1056 UInt32 indexInArchive;
1062 if (!updateCallback) 1057 if (!updateCallback)
1063 return E_FAIL; 1058 return E_FAIL;
1064 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); 1059 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive))
1065 1060
1066 /* 1061 // Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp, reportArcProp, updateCallback)
1067 CMyComPtr<IArchiveUpdateCallbackArcProp> reportArcProp;
1068 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp);
1069 */
1070 1062
1071 CItem newItem; 1063 CItem newItem;
1072 1064
@@ -1080,7 +1072,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1080 if (_timeOptions.Write_MTime.Val) 1072 if (_timeOptions.Write_MTime.Val)
1081 { 1073 {
1082 NCOM::CPropVariant prop; 1074 NCOM::CPropVariant prop;
1083 RINOK(updateCallback->GetProperty(0, kpidMTime, &prop)); 1075 RINOK(updateCallback->GetProperty(0, kpidMTime, &prop))
1084 if (prop.vt == VT_FILETIME) 1076 if (prop.vt == VT_FILETIME)
1085 NTime::FileTime_To_UnixTime(prop.filetime, newItem.Time); 1077 NTime::FileTime_To_UnixTime(prop.filetime, newItem.Time);
1086 else if (prop.vt == VT_EMPTY) 1078 else if (prop.vt == VT_EMPTY)
@@ -1090,7 +1082,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1090 } 1082 }
1091 { 1083 {
1092 NCOM::CPropVariant prop; 1084 NCOM::CPropVariant prop;
1093 RINOK(updateCallback->GetProperty(0, kpidPath, &prop)); 1085 RINOK(updateCallback->GetProperty(0, kpidPath, &prop))
1094 if (prop.vt == VT_BSTR) 1086 if (prop.vt == VT_BSTR)
1095 { 1087 {
1096 UString name = prop.bstrVal; 1088 UString name = prop.bstrVal;
@@ -1106,7 +1098,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1106 } 1098 }
1107 { 1099 {
1108 NCOM::CPropVariant prop; 1100 NCOM::CPropVariant prop;
1109 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); 1101 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop))
1110 if (prop.vt != VT_EMPTY) 1102 if (prop.vt != VT_EMPTY)
1111 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) 1103 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE)
1112 return E_INVALIDARG; 1104 return E_INVALIDARG;
@@ -1118,7 +1110,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1118 UInt64 size; 1110 UInt64 size;
1119 { 1111 {
1120 NCOM::CPropVariant prop; 1112 NCOM::CPropVariant prop;
1121 RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); 1113 RINOK(updateCallback->GetProperty(0, kpidSize, &prop))
1122 if (prop.vt != VT_UI8) 1114 if (prop.vt != VT_UI8)
1123 return E_INVALIDARG; 1115 return E_INVALIDARG;
1124 size = prop.uhVal.QuadPart; 1116 size = prop.uhVal.QuadPart;
@@ -1136,8 +1128,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1136 CMyComPtr<ICompressProgressInfo> progress = lps; 1128 CMyComPtr<ICompressProgressInfo> progress = lps;
1137 lps->Init(updateCallback, true); 1129 lps->Init(updateCallback, true);
1138 1130
1139 CMyComPtr<IArchiveUpdateCallbackFile> opCallback; 1131 Z7_DECL_CMyComPtr_QI_FROM(
1140 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); 1132 IArchiveUpdateCallbackFile,
1133 opCallback, updateCallback)
1141 if (opCallback) 1134 if (opCallback)
1142 { 1135 {
1143 RINOK(opCallback->ReportOperation( 1136 RINOK(opCallback->ReportOperation(
@@ -1153,7 +1146,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1153 newItem.WriteHeader(outStream); 1146 newItem.WriteHeader(outStream);
1154 offset += _headerSize; 1147 offset += _headerSize;
1155 } 1148 }
1156 RINOK(_stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL)); 1149 RINOK(InStream_SeekSet(_stream, offset))
1157 1150
1158 /* 1151 /*
1159 if (reportArcProp) 1152 if (reportArcProp)
@@ -1168,7 +1161,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1168 COM_TRY_END 1161 COM_TRY_END
1169} 1162}
1170 1163
1171STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 1164Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
1172{ 1165{
1173 _timeOptions.Init(); 1166 _timeOptions.Init();
1174 _props.Init(); 1167 _props.Init();
@@ -1182,7 +1175,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1182 const PROPVARIANT &value = values[i]; 1175 const PROPVARIANT &value = values[i];
1183 { 1176 {
1184 bool processed = false; 1177 bool processed = false;
1185 RINOK(_timeOptions.Parse(name, value, processed)); 1178 RINOK(_timeOptions.Parse(name, value, processed))
1186 if (processed) 1179 if (processed)
1187 { 1180 {
1188 if (_timeOptions.Write_CTime.Val || 1181 if (_timeOptions.Write_CTime.Val ||
@@ -1197,7 +1190,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1197 continue; 1190 continue;
1198 } 1191 }
1199 } 1192 }
1200 RINOK(_props.SetProperty(name, value)); 1193 RINOK(_props.SetProperty(name, value))
1201 } 1194 }
1202 return S_OK; 1195 return S_OK;
1203} 1196}
diff --git a/CPP/7zip/Archive/HandlerCont.cpp b/CPP/7zip/Archive/HandlerCont.cpp
index 3cbfdac..b4524a4 100644
--- a/CPP/7zip/Archive/HandlerCont.cpp
+++ b/CPP/7zip/Archive/HandlerCont.cpp
@@ -18,14 +18,14 @@ namespace NExt {
18API_FUNC_IsArc IsArc_Ext(const Byte *p, size_t size); 18API_FUNC_IsArc IsArc_Ext(const Byte *p, size_t size);
19} 19}
20 20
21STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems, 21Z7_COM7F_IMF(CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems,
22 Int32 testMode, IArchiveExtractCallback *extractCallback) 22 Int32 testMode, IArchiveExtractCallback *extractCallback))
23{ 23{
24 COM_TRY_BEGIN 24 COM_TRY_BEGIN
25 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 25 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
26 if (allFilesMode) 26 if (allFilesMode)
27 { 27 {
28 RINOK(GetNumberOfItems(&numItems)); 28 RINOK(GetNumberOfItems(&numItems))
29 } 29 }
30 if (numItems == 0) 30 if (numItems == 0)
31 return S_OK; 31 return S_OK;
@@ -56,14 +56,14 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems,
56 { 56 {
57 lps->InSize = totalSize; 57 lps->InSize = totalSize;
58 lps->OutSize = totalSize; 58 lps->OutSize = totalSize;
59 RINOK(lps->SetCur()); 59 RINOK(lps->SetCur())
60 CMyComPtr<ISequentialOutStream> outStream; 60 CMyComPtr<ISequentialOutStream> outStream;
61 Int32 askMode = testMode ? 61 const Int32 askMode = testMode ?
62 NExtract::NAskMode::kTest : 62 NExtract::NAskMode::kTest :
63 NExtract::NAskMode::kExtract; 63 NExtract::NAskMode::kExtract;
64 Int32 index = allFilesMode ? i : indices[i]; 64 const UInt32 index = allFilesMode ? i : indices[i];
65 65
66 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 66 RINOK(extractCallback->GetStream(index, &outStream, askMode))
67 67
68 UInt64 pos, size; 68 UInt64 pos, size;
69 int opRes = GetItem_ExtractInfo(index, pos, size); 69 int opRes = GetItem_ExtractInfo(index, pos, size);
@@ -71,14 +71,14 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems,
71 if (!testMode && !outStream) 71 if (!testMode && !outStream)
72 continue; 72 continue;
73 73
74 RINOK(extractCallback->PrepareOperation(askMode)); 74 RINOK(extractCallback->PrepareOperation(askMode))
75 75
76 if (opRes == NExtract::NOperationResult::kOK) 76 if (opRes == NExtract::NOperationResult::kOK)
77 { 77 {
78 RINOK(_stream->Seek(pos, STREAM_SEEK_SET, NULL)); 78 RINOK(InStream_SeekSet(_stream, pos))
79 streamSpec->Init(size); 79 streamSpec->Init(size);
80 80
81 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 81 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
82 82
83 opRes = NExtract::NOperationResult::kDataError; 83 opRes = NExtract::NOperationResult::kDataError;
84 84
@@ -89,14 +89,14 @@ STDMETHODIMP CHandlerCont::Extract(const UInt32 *indices, UInt32 numItems,
89 } 89 }
90 90
91 outStream.Release(); 91 outStream.Release();
92 RINOK(extractCallback->SetOperationResult(opRes)); 92 RINOK(extractCallback->SetOperationResult(opRes))
93 } 93 }
94 94
95 return S_OK; 95 return S_OK;
96 COM_TRY_END 96 COM_TRY_END
97} 97}
98 98
99STDMETHODIMP CHandlerCont::GetStream(UInt32 index, ISequentialInStream **stream) 99Z7_COM7F_IMF(CHandlerCont::GetStream(UInt32 index, ISequentialInStream **stream))
100{ 100{
101 COM_TRY_BEGIN 101 COM_TRY_BEGIN
102 *stream = NULL; 102 *stream = NULL;
@@ -114,7 +114,7 @@ CHandlerImg::CHandlerImg()
114 Clear_HandlerImg_Vars(); 114 Clear_HandlerImg_Vars();
115} 115}
116 116
117STDMETHODIMP CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 117Z7_COM7F_IMF(CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
118{ 118{
119 switch (seekOrigin) 119 switch (seekOrigin)
120 { 120 {
@@ -129,9 +129,9 @@ STDMETHODIMP CHandlerImg::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosit
129 *newPosition = _virtPos; 129 *newPosition = _virtPos;
130 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 130 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
131 } 131 }
132 _virtPos = offset; 132 _virtPos = (UInt64)offset;
133 if (newPosition) 133 if (newPosition)
134 *newPosition = offset; 134 *newPosition = (UInt64)offset;
135 return S_OK; 135 return S_OK;
136} 136}
137 137
@@ -171,9 +171,9 @@ void CHandlerImg::Clear_HandlerImg_Vars()
171 Reset_PosInArc(); 171 Reset_PosInArc();
172} 172}
173 173
174STDMETHODIMP CHandlerImg::Open(IInStream *stream, 174Z7_COM7F_IMF(CHandlerImg::Open(IInStream *stream,
175 const UInt64 * /* maxCheckStartPosition */, 175 const UInt64 * /* maxCheckStartPosition */,
176 IArchiveOpenCallback * openCallback) 176 IArchiveOpenCallback * openCallback))
177{ 177{
178 COM_TRY_BEGIN 178 COM_TRY_BEGIN
179 { 179 {
@@ -209,31 +209,26 @@ STDMETHODIMP CHandlerImg::Open(IInStream *stream,
209 COM_TRY_END 209 COM_TRY_END
210} 210}
211 211
212STDMETHODIMP CHandlerImg::GetNumberOfItems(UInt32 *numItems) 212Z7_COM7F_IMF(CHandlerImg::GetNumberOfItems(UInt32 *numItems))
213{ 213{
214 *numItems = 1; 214 *numItems = 1;
215 return S_OK; 215 return S_OK;
216} 216}
217 217
218 218
219class CHandlerImgProgress: 219Z7_CLASS_IMP_NOQIB_1(
220 public ICompressProgressInfo, 220 CHandlerImgProgress
221 public CMyUnknownImp 221 , ICompressProgressInfo
222{ 222)
223public: 223public:
224 CHandlerImg &Handler; 224 CHandlerImg &Handler;
225 CMyComPtr<ICompressProgressInfo> _ratioProgress; 225 CMyComPtr<ICompressProgressInfo> _ratioProgress;
226 226
227 CHandlerImgProgress(CHandlerImg &handler) : Handler(handler) {} 227 CHandlerImgProgress(CHandlerImg &handler) : Handler(handler) {}
228
229 // MY_UNKNOWN_IMP1(ICompressProgressInfo)
230 MY_UNKNOWN_IMP
231
232 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
233}; 228};
234 229
235 230
236STDMETHODIMP CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 231Z7_COM7F_IMF(CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
237{ 232{
238 UInt64 inSize2; 233 UInt64 inSize2;
239 if (Handler.Get_PackSizeProcessed(inSize2)) 234 if (Handler.Get_PackSizeProcessed(inSize2))
@@ -242,8 +237,8 @@ STDMETHODIMP CHandlerImgProgress::SetRatioInfo(const UInt64 *inSize, const UInt6
242} 237}
243 238
244 239
245STDMETHODIMP CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems, 240Z7_COM7F_IMF(CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems,
246 Int32 testMode, IArchiveExtractCallback *extractCallback) 241 Int32 testMode, IArchiveExtractCallback *extractCallback))
247{ 242{
248 COM_TRY_BEGIN 243 COM_TRY_BEGIN
249 if (numItems == 0) 244 if (numItems == 0)
@@ -251,15 +246,15 @@ STDMETHODIMP CHandlerImg::Extract(const UInt32 *indices, UInt32 numItems,
251 if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0)) 246 if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0))
252 return E_INVALIDARG; 247 return E_INVALIDARG;
253 248
254 RINOK(extractCallback->SetTotal(_size)); 249 RINOK(extractCallback->SetTotal(_size))
255 CMyComPtr<ISequentialOutStream> outStream; 250 CMyComPtr<ISequentialOutStream> outStream;
256 Int32 askMode = testMode ? 251 const Int32 askMode = testMode ?
257 NExtract::NAskMode::kTest : 252 NExtract::NAskMode::kTest :
258 NExtract::NAskMode::kExtract; 253 NExtract::NAskMode::kExtract;
259 RINOK(extractCallback->GetStream(0, &outStream, askMode)); 254 RINOK(extractCallback->GetStream(0, &outStream, askMode))
260 if (!testMode && !outStream) 255 if (!testMode && !outStream)
261 return S_OK; 256 return S_OK;
262 RINOK(extractCallback->PrepareOperation(askMode)); 257 RINOK(extractCallback->PrepareOperation(askMode))
263 258
264 int opRes = NExtract::NOperationResult::kDataError; 259 int opRes = NExtract::NOperationResult::kDataError;
265 260
@@ -332,7 +327,7 @@ HRESULT ReadZeroTail(ISequentialInStream *stream, bool &areThereNonZeros, UInt64
332 for (;;) 327 for (;;)
333 { 328 {
334 UInt32 size = 0; 329 UInt32 size = 0;
335 RINOK(stream->Read(buf, kBufSize, &size)); 330 RINOK(stream->Read(buf, kBufSize, &size))
336 if (size == 0) 331 if (size == 0)
337 return S_OK; 332 return S_OK;
338 for (UInt32 i = 0; i < size; i++) 333 for (UInt32 i = 0; i < size; i++)
diff --git a/CPP/7zip/Archive/HandlerCont.h b/CPP/7zip/Archive/HandlerCont.h
index 3c64592..2dd0529 100644
--- a/CPP/7zip/Archive/HandlerCont.h
+++ b/CPP/7zip/Archive/HandlerCont.h
@@ -1,7 +1,7 @@
1// HandlerCont.h 1// HandlerCont.h
2 2
3#ifndef __HANDLER_CONT_H 3#ifndef ZIP7_INC_HANDLER_CONT_H
4#define __HANDLER_CONT_H 4#define ZIP7_INC_HANDLER_CONT_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -9,62 +9,76 @@
9 9
10namespace NArchive { 10namespace NArchive {
11 11
12#define INTERFACE_IInArchive_Cont(x) \ 12#define Z7_IFACEM_IInArchive_Cont(x) \
13 STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; \ 13 x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) \
14 STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ 14 x(Close()) \
15 STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; \ 15 x(GetNumberOfItems(UInt32 *numItems)) \
16 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 16 x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
17 /* STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; */ \ 17 /* x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) */ \
18 STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 18 x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \
19 STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 19 x(GetNumberOfProperties(UInt32 *numProps)) \
20 STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 20 x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
21 STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 21 x(GetNumberOfArchiveProperties(UInt32 *numProps)) \
22 STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 22 x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
23 23
24 24
25// #define Z7_COM7F_PUREO(f) virtual Z7_COM7F_IMF(f) Z7_override =0;
26// #define Z7_COM7F_PUREO2(t, f) virtual Z7_COM7F_IMF2(t, f) Z7_override =0;
27
25class CHandlerCont: 28class CHandlerCont:
26 public IInArchive, 29 public IInArchive,
27 public IInArchiveGetStream, 30 public IInArchiveGetStream,
28 public CMyUnknownImp 31 public CMyUnknownImp
29{ 32{
33 Z7_COM_UNKNOWN_IMP_2(
34 IInArchive,
35 IInArchiveGetStream)
36 /*
37 Z7_IFACEM_IInArchive_Cont(Z7_COM7F_PUREO)
38 // Z7_IFACE_COM7_PURE(IInArchive_Cont)
39 */
40 Z7_COM7F_IMP(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback))
30protected: 41protected:
31 CMyComPtr<IInStream> _stream; 42 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
32 43
44 CMyComPtr<IInStream> _stream;
33 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const = 0; 45 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const = 0;
34
35public:
36 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
37 INTERFACE_IInArchive_Cont(PURE)
38
39 STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY;
40
41 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
42
43 // destructor must be virtual for this class 46 // destructor must be virtual for this class
44 virtual ~CHandlerCont() {} 47 virtual ~CHandlerCont() {}
45}; 48};
46 49
47 50
48 51
49#define INTERFACE_IInArchive_Img(x) \ 52#define Z7_IFACEM_IInArchive_Img(x) \
50 /* STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; */ \ 53 /* x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) */ \
51 STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ 54 x(Close()) \
52 /* STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; */ \ 55 /* x(GetNumberOfItems(UInt32 *numItems)) */ \
53 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 56 x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
54 /* STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; */ \ 57 /* x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) */ \
55 STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 58 x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \
56 STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 59 x(GetNumberOfProperties(UInt32 *numProps)) \
57 STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 60 x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
58 STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 61 x(GetNumberOfArchiveProperties(UInt32 *numProps)) \
59 STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 62 x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
60 63
61 64
62class CHandlerImg: 65class CHandlerImg:
63 public IInStream,
64 public IInArchive, 66 public IInArchive,
65 public IInArchiveGetStream, 67 public IInArchiveGetStream,
68 public IInStream,
66 public CMyUnknownImp 69 public CMyUnknownImp
67{ 70{
71 Z7_COM_UNKNOWN_IMP_3(
72 IInArchive,
73 IInArchiveGetStream,
74 IInStream)
75
76 Z7_COM7F_IMP(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback))
77 Z7_COM7F_IMP(GetNumberOfItems(UInt32 *numItems))
78 Z7_COM7F_IMP(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback))
79 Z7_IFACE_COM7_IMP(IInStream)
80 // Z7_IFACEM_IInArchive_Img(Z7_COM7F_PUREO)
81
68protected: 82protected:
69 UInt64 _virtPos; 83 UInt64 _virtPos;
70 UInt64 _posInArc; 84 UInt64 _posInArc;
@@ -107,18 +121,6 @@ public:
107 return false; 121 return false;
108 } 122 }
109 123
110 MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IInStream)
111 INTERFACE_IInArchive_Img(PURE)
112
113 STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback);
114 STDMETHOD(GetNumberOfItems)(UInt32 *numItems);
115 STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback);
116
117 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) = 0;
118
119 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) = 0;
120 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
121
122 CHandlerImg(); 124 CHandlerImg();
123 // destructor must be virtual for this class 125 // destructor must be virtual for this class
124 virtual ~CHandlerImg() {} 126 virtual ~CHandlerImg() {}
diff --git a/CPP/7zip/Archive/HfsHandler.cpp b/CPP/7zip/Archive/HfsHandler.cpp
index fa96b73..696ecd7 100644
--- a/CPP/7zip/Archive/HfsHandler.cpp
+++ b/CPP/7zip/Archive/HfsHandler.cpp
@@ -126,16 +126,16 @@ bool CFork::Check_NumBlocks() const
126struct CIdIndexPair 126struct CIdIndexPair
127{ 127{
128 UInt32 ID; 128 UInt32 ID;
129 int Index; 129 unsigned Index;
130 130
131 int Compare(const CIdIndexPair &a) const; 131 int Compare(const CIdIndexPair &a) const;
132}; 132};
133 133
134#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 134#define RINOZ(x) { const int _t_ = (x); if (_t_ != 0) return _t_; }
135 135
136int CIdIndexPair::Compare(const CIdIndexPair &a) const 136int CIdIndexPair::Compare(const CIdIndexPair &a) const
137{ 137{
138 RINOZ(MyCompare(ID, a.ID)); 138 RINOZ(MyCompare(ID, a.ID))
139 return MyCompare(Index, a.Index); 139 return MyCompare(Index, a.Index);
140} 140}
141 141
@@ -144,10 +144,10 @@ static int FindItemIndex(const CRecordVector<CIdIndexPair> &items, UInt32 id)
144 unsigned left = 0, right = items.Size(); 144 unsigned left = 0, right = items.Size();
145 while (left != right) 145 while (left != right)
146 { 146 {
147 unsigned mid = (left + right) / 2; 147 const unsigned mid = (left + right) / 2;
148 UInt32 midVal = items[mid].ID; 148 const UInt32 midVal = items[mid].ID;
149 if (id == midVal) 149 if (id == midVal)
150 return items[mid].Index; 150 return (int)items[mid].Index;
151 if (id < midVal) 151 if (id < midVal)
152 right = mid; 152 right = mid;
153 else 153 else
@@ -161,10 +161,10 @@ static int Find_in_IdExtents(const CObjectVector<CIdExtents> &items, UInt32 id)
161 unsigned left = 0, right = items.Size(); 161 unsigned left = 0, right = items.Size();
162 while (left != right) 162 while (left != right)
163 { 163 {
164 unsigned mid = (left + right) / 2; 164 const unsigned mid = (left + right) / 2;
165 UInt32 midVal = items[mid].ID; 165 const UInt32 midVal = items[mid].ID;
166 if (id == midVal) 166 if (id == midVal)
167 return mid; 167 return (int)mid;
168 if (id < midVal) 168 if (id < midVal)
169 right = mid; 169 right = mid;
170 else 170 else
@@ -244,6 +244,8 @@ static const UInt32 kMethod_COPY_RSRC = 10;
244// static const UInt32 kMethod_LZFSE_ATTR = 11; 244// static const UInt32 kMethod_LZFSE_ATTR = 11;
245static const UInt32 kMethod_LZFSE_RSRC = 12; 245static const UInt32 kMethod_LZFSE_RSRC = 12;
246 246
247// static const UInt32 kMethod_ZBM_RSRC = 14;
248
247static const char * const g_Methods[] = 249static const char * const g_Methods[] =
248{ 250{
249 NULL 251 NULL
@@ -259,6 +261,8 @@ static const char * const g_Methods[] =
259 , "COPY-rsrc" 261 , "COPY-rsrc"
260 , "LZFSE-attr" 262 , "LZFSE-attr"
261 , "LZFSE-rsrc" 263 , "LZFSE-rsrc"
264 , NULL
265 , "ZBM-rsrc"
262}; 266};
263 267
264 268
@@ -281,7 +285,9 @@ void CCompressHeader::Parse(const Byte *p, size_t dataSize)
281 if ( Method == kMethod_ZLIB_RSRC 285 if ( Method == kMethod_ZLIB_RSRC
282 || Method == kMethod_COPY_RSRC 286 || Method == kMethod_COPY_RSRC
283 || Method == kMethod_LZVN_RSRC 287 || Method == kMethod_LZVN_RSRC
284 || Method == kMethod_LZFSE_RSRC) 288 || Method == kMethod_LZFSE_RSRC
289 // || Method == kMethod_ZBM_RSRC // for debug
290 )
285 { 291 {
286 IsResource = true; 292 IsResource = true;
287 if (dataSize == 0) 293 if (dataSize == 0)
@@ -327,7 +333,7 @@ void CCompressHeader::MethodToProp(NWindows::NCOM::CPropVariant &prop) const
327 return; 333 return;
328 const UInt32 method = Method; 334 const UInt32 method = Method;
329 const char *p = NULL; 335 const char *p = NULL;
330 if (method < ARRAY_SIZE(g_Methods)) 336 if (method < Z7_ARRAY_SIZE(g_Methods))
331 p = g_Methods[method]; 337 p = g_Methods[method];
332 AString s; 338 AString s;
333 if (p) 339 if (p)
@@ -520,7 +526,7 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path)
520{ 526{
521 unsigned len = 0; 527 unsigned len = 0;
522 const unsigned kNumLevelsMax = (1 << 10); 528 const unsigned kNumLevelsMax = (1 << 10);
523 int cur = index; 529 unsigned cur = index;
524 unsigned i; 530 unsigned i;
525 531
526 for (i = 0; i < kNumLevelsMax; i++) 532 for (i = 0; i < kNumLevelsMax; i++)
@@ -537,8 +543,8 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path)
537 543
538 len += s->Len(); 544 len += s->Len();
539 len++; 545 len++;
540 cur = ref.Parent; 546 cur = (unsigned)ref.Parent;
541 if (cur < 0) 547 if (ref.Parent < 0)
542 break; 548 break;
543 } 549 }
544 550
@@ -580,7 +586,7 @@ void CDatabase::GetItemPath(unsigned index, NWindows::NCOM::CPropVariant &path)
580 if (len == 0) 586 if (len == 0)
581 break; 587 break;
582 p[--len] = delimChar; 588 p[--len] = delimChar;
583 cur = ref.Parent; 589 cur = (unsigned)ref.Parent;
584 } 590 }
585} 591}
586 592
@@ -607,10 +613,10 @@ HRESULT CDatabase::ReadFile(const CFork &fork, CByteBuffer &buf, IInStream *inSt
607 e.NumBlocks > fork.NumBlocks - curBlock || 613 e.NumBlocks > fork.NumBlocks - curBlock ||
608 e.NumBlocks > Header.NumBlocks - e.Pos) 614 e.NumBlocks > Header.NumBlocks - e.Pos)
609 return S_FALSE; 615 return S_FALSE;
610 RINOK(inStream->Seek(SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog), STREAM_SEEK_SET, NULL)); 616 RINOK(InStream_SeekSet(inStream, SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog)))
611 RINOK(ReadStream_FALSE(inStream, 617 RINOK(ReadStream_FALSE(inStream,
612 (Byte *)buf + ((size_t)curBlock << Header.BlockSizeLog), 618 (Byte *)buf + ((size_t)curBlock << Header.BlockSizeLog),
613 (size_t)e.NumBlocks << Header.BlockSizeLog)); 619 (size_t)e.NumBlocks << Header.BlockSizeLog))
614 curBlock += e.NumBlocks; 620 curBlock += e.NumBlocks;
615 } 621 }
616 return S_OK; 622 return S_OK;
@@ -733,13 +739,13 @@ HRESULT CDatabase::LoadExtentFile(const CFork &fork, IInStream *inStream, CObjec
733 if (fork.NumBlocks == 0) 739 if (fork.NumBlocks == 0)
734 return S_OK; 740 return S_OK;
735 CByteBuffer buf; 741 CByteBuffer buf;
736 RINOK(ReadFile(fork, buf, inStream)); 742 RINOK(ReadFile(fork, buf, inStream))
737 const Byte *p = (const Byte *)buf; 743 const Byte *p = (const Byte *)buf;
738 744
739 // CNodeDescriptor nodeDesc; 745 // CNodeDescriptor nodeDesc;
740 // nodeDesc.Parse(p); 746 // nodeDesc.Parse(p);
741 CHeaderRec hr; 747 CHeaderRec hr;
742 RINOK(hr.Parse2(buf)); 748 RINOK(hr.Parse2(buf))
743 749
744 UInt32 node = hr.FirstLeafNode; 750 UInt32 node = hr.FirstLeafNode;
745 if (node == 0) 751 if (node == 0)
@@ -872,13 +878,13 @@ HRESULT CDatabase::LoadAttrs(const CFork &fork, IInStream *inStream, IArchiveOpe
872 return S_OK; 878 return S_OK;
873 879
874 CByteBuffer AttrBuf; 880 CByteBuffer AttrBuf;
875 RINOK(ReadFile(fork, AttrBuf, inStream)); 881 RINOK(ReadFile(fork, AttrBuf, inStream))
876 const Byte *p = (const Byte *)AttrBuf; 882 const Byte *p = (const Byte *)AttrBuf;
877 883
878 // CNodeDescriptor nodeDesc; 884 // CNodeDescriptor nodeDesc;
879 // nodeDesc.Parse(p); 885 // nodeDesc.Parse(p);
880 CHeaderRec hr; 886 CHeaderRec hr;
881 RINOK(hr.Parse2(AttrBuf)); 887 RINOK(hr.Parse2(AttrBuf))
882 888
883 // CaseSensetive = (Header.IsHfsX() && hr.KeyCompareType == 0xBC); 889 // CaseSensetive = (Header.IsHfsX() && hr.KeyCompareType == 0xBC);
884 890
@@ -948,7 +954,7 @@ HRESULT CDatabase::LoadAttrs(const CFork &fork, IInStream *inStream, IArchiveOpe
948 if (progress && (Attrs.Size() & 0xFFF) == 0) 954 if (progress && (Attrs.Size() & 0xFFF) == 0)
949 { 955 {
950 const UInt64 numFiles = 0; 956 const UInt64 numFiles = 0;
951 RINOK(progress->SetCompleted(&numFiles, NULL)); 957 RINOK(progress->SetCompleted(&numFiles, NULL))
952 } 958 }
953 959
954 if (Attrs.Size() >= ((UInt32)1 << 31)) 960 if (Attrs.Size() >= ((UInt32)1 << 31))
@@ -1012,7 +1018,7 @@ bool CDatabase::Parse_decmpgfs(unsigned attrIndex, CItem &item, bool &skip)
1012 1018
1013 if (item.CompressHeader.IsCorrect) 1019 if (item.CompressHeader.IsCorrect)
1014 { 1020 {
1015 item.decmpfs_AttrIndex = attrIndex; 1021 item.decmpfs_AttrIndex = (int)attrIndex;
1016 skip = true; 1022 skip = true;
1017 if (item.CompressHeader.Method < sizeof(MethodsMask) * 8) 1023 if (item.CompressHeader.Method < sizeof(MethodsMask) * 8)
1018 MethodsMask |= ((UInt32)1 << item.CompressHeader.Method); 1024 MethodsMask |= ((UInt32)1 << item.CompressHeader.Method);
@@ -1025,13 +1031,13 @@ bool CDatabase::Parse_decmpgfs(unsigned attrIndex, CItem &item, bool &skip)
1025HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector<CIdExtents> *overflowExtentsArray, IInStream *inStream, IArchiveOpenCallback *progress) 1031HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector<CIdExtents> *overflowExtentsArray, IInStream *inStream, IArchiveOpenCallback *progress)
1026{ 1032{
1027 CByteBuffer buf; 1033 CByteBuffer buf;
1028 RINOK(ReadFile(fork, buf, inStream)); 1034 RINOK(ReadFile(fork, buf, inStream))
1029 const Byte *p = (const Byte *)buf; 1035 const Byte *p = (const Byte *)buf;
1030 1036
1031 // CNodeDescriptor nodeDesc; 1037 // CNodeDescriptor nodeDesc;
1032 // nodeDesc.Parse(p); 1038 // nodeDesc.Parse(p);
1033 CHeaderRec hr; 1039 CHeaderRec hr;
1034 RINOK(hr.Parse2(buf)); 1040 RINOK(hr.Parse2(buf))
1035 1041
1036 CRecordVector<CIdIndexPair> IdToIndexMap; 1042 CRecordVector<CIdIndexPair> IdToIndexMap;
1037 1043
@@ -1196,7 +1202,7 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector<CIdExtents
1196 if (progress && (Items.Size() & 0xFFF) == 0) 1202 if (progress && (Items.Size() & 0xFFF) == 0)
1197 { 1203 {
1198 const UInt64 numItems = Items.Size(); 1204 const UInt64 numItems = Items.Size();
1199 RINOK(progress->SetCompleted(&numItems, NULL)); 1205 RINOK(progress->SetCompleted(&numItems, NULL))
1200 } 1206 }
1201 } 1207 }
1202 node = desc.fLink; 1208 node = desc.fLink;
@@ -1265,7 +1271,7 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector<CIdExtents
1265 1271
1266 ThereAreAltStreams = true; 1272 ThereAreAltStreams = true;
1267 ref.AttrIndex = kAttrIndex_Resource; 1273 ref.AttrIndex = kAttrIndex_Resource;
1268 ref.Parent = Refs.Size() - 1; 1274 ref.Parent = (int)(Refs.Size() - 1);
1269 Refs.Add(ref); 1275 Refs.Add(ref);
1270 1276
1271 #endif 1277 #endif
@@ -1311,7 +1317,7 @@ HRESULT CDatabase::LoadCatalog(const CFork &fork, const CObjectVector<CIdExtents
1311 ThereAreAltStreams = true; 1317 ThereAreAltStreams = true;
1312 1318
1313 CRef ref; 1319 CRef ref;
1314 ref.AttrIndex = i; 1320 ref.AttrIndex = (int)i;
1315 ref.Parent = refIndex; 1321 ref.Parent = refIndex;
1316 ref.ItemIndex = Refs[refIndex].ItemIndex; 1322 ref.ItemIndex = Refs[refIndex].ItemIndex;
1317 Refs.Add(ref); 1323 Refs.Add(ref);
@@ -1352,7 +1358,7 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1352{ 1358{
1353 Clear(); 1359 Clear();
1354 Byte buf[kHfsHeaderSize]; 1360 Byte buf[kHfsHeaderSize];
1355 RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)); 1361 RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize))
1356 { 1362 {
1357 for (unsigned i = 0; i < kHeaderPadSize; i++) 1363 for (unsigned i = 0; i < kHeaderPadSize; i++)
1358 if (buf[i] != 0) 1364 if (buf[i] != 0)
@@ -1388,7 +1394,7 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1388 if (progress) 1394 if (progress)
1389 { 1395 {
1390 UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1; 1396 UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1;
1391 RINOK(progress->SetTotal(&numFiles, NULL)); 1397 RINOK(progress->SetTotal(&numFiles, NULL))
1392 } 1398 }
1393 h.NumFreeBlocks = Get16(p + 0x22); 1399 h.NumFreeBlocks = Get16(p + 0x22);
1394 */ 1400 */
@@ -1420,8 +1426,8 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1420 UInt64 phy = SpecOffset + ((UInt64)blockCount << h.BlockSizeLog); 1426 UInt64 phy = SpecOffset + ((UInt64)blockCount << h.BlockSizeLog);
1421 if (PhySize2 < phy) 1427 if (PhySize2 < phy)
1422 PhySize2 = phy; 1428 PhySize2 = phy;
1423 RINOK(inStream->Seek(SpecOffset, STREAM_SEEK_SET, NULL)); 1429 RINOK(InStream_SeekSet(inStream, SpecOffset))
1424 RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize)); 1430 RINOK(ReadStream_FALSE(inStream, buf, kHfsHeaderSize))
1425 } 1431 }
1426 1432
1427 if (p[0] != 'H' || (p[1] != '+' && p[1] != 'X')) 1433 if (p[0] != 'H' || (p[1] != '+' && p[1] != 'X'))
@@ -1446,12 +1452,12 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1446 h.NumFiles > ((UInt32)1 << 30)) 1452 h.NumFiles > ((UInt32)1 << 30))
1447 return S_FALSE; 1453 return S_FALSE;
1448 1454
1449 RINOK(inStream->Seek(0, STREAM_SEEK_END, &ArcFileSize)); 1455 RINOK(InStream_GetSize_SeekToEnd(inStream, ArcFileSize))
1450 1456
1451 if (progress) 1457 if (progress)
1452 { 1458 {
1453 const UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1; 1459 const UInt64 numFiles = (UInt64)h.NumFiles + h.NumFolders + 1;
1454 RINOK(progress->SetTotal(&numFiles, NULL)); 1460 RINOK(progress->SetTotal(&numFiles, NULL))
1455 } 1461 }
1456 1462
1457 UInt32 blockSize = Get32(p + 0x28); 1463 UInt32 blockSize = Get32(p + 0x28);
@@ -1504,10 +1510,10 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1504 else 1510 else
1505 { 1511 {
1506 if (attrFork.Size != 0) 1512 if (attrFork.Size != 0)
1507 RINOK(LoadAttrs(attrFork, inStream, progress)); 1513 RINOK(LoadAttrs(attrFork, inStream, progress))
1508 } 1514 }
1509 1515
1510 RINOK(LoadCatalog(catalogFork, overflowExtents, inStream, progress)); 1516 RINOK(LoadCatalog(catalogFork, overflowExtents, inStream, progress))
1511 1517
1512 PhySize = Header.GetPhySize(); 1518 PhySize = Header.GetPhySize();
1513 return S_OK; 1519 return S_OK;
@@ -1515,22 +1521,20 @@ HRESULT CDatabase::Open2(IInStream *inStream, IArchiveOpenCallback *progress)
1515 1521
1516 1522
1517 1523
1518class CHandler: 1524Z7_class_CHandler_final:
1519 public IInArchive, 1525 public IInArchive,
1520 public IArchiveGetRawProps, 1526 public IArchiveGetRawProps,
1521 public IInArchiveGetStream, 1527 public IInArchiveGetStream,
1522 public CMyUnknownImp, 1528 public CMyUnknownImp,
1523 public CDatabase 1529 public CDatabase
1524{ 1530{
1525 CMyComPtr<IInStream> _stream; 1531 Z7_IFACES_IMP_UNK_3(
1532 IInArchive,
1533 IArchiveGetRawProps,
1534 IInArchiveGetStream)
1526 1535
1536 CMyComPtr<IInStream> _stream;
1527 HRESULT GetForkStream(const CFork &fork, ISequentialInStream **stream); 1537 HRESULT GetForkStream(const CFork &fork, ISequentialInStream **stream);
1528
1529public:
1530 MY_UNKNOWN_IMP3(IInArchive, IArchiveGetRawProps, IInArchiveGetStream)
1531 INTERFACE_IInArchive(;)
1532 INTERFACE_IArchiveGetRawProps(;)
1533 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
1534}; 1538};
1535 1539
1536static const Byte kProps[] = 1540static const Byte kProps[] =
@@ -1576,7 +1580,7 @@ static void HfsTimeToProp(UInt32 hfsTime, NWindows::NCOM::CPropVariant &prop)
1576 prop.SetAsTimeFrom_FT_Prec(ft, k_PropVar_TimePrec_Base); 1580 prop.SetAsTimeFrom_FT_Prec(ft, k_PropVar_TimePrec_Base);
1577} 1581}
1578 1582
1579STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1583Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1580{ 1584{
1581 COM_TRY_BEGIN 1585 COM_TRY_BEGIN
1582 NWindows::NCOM::CPropVariant prop; 1586 NWindows::NCOM::CPropVariant prop;
@@ -1624,20 +1628,20 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1624 COM_TRY_END 1628 COM_TRY_END
1625} 1629}
1626 1630
1627STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 1631Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
1628{ 1632{
1629 *numProps = 0; 1633 *numProps = 0;
1630 return S_OK; 1634 return S_OK;
1631} 1635}
1632 1636
1633STDMETHODIMP CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 1637Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
1634{ 1638{
1635 *name = NULL; 1639 *name = NULL;
1636 *propID = 0; 1640 *propID = 0;
1637 return S_OK; 1641 return S_OK;
1638} 1642}
1639 1643
1640STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 1644Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
1641{ 1645{
1642 const CRef &ref = Refs[index]; 1646 const CRef &ref = Refs[index];
1643 *parentType = ref.IsAltStream() ? 1647 *parentType = ref.IsAltStream() ?
@@ -1647,7 +1651,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
1647 return S_OK; 1651 return S_OK;
1648} 1652}
1649 1653
1650STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 1654Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
1651{ 1655{
1652 *data = NULL; 1656 *data = NULL;
1653 *dataSize = 0; 1657 *dataSize = 0;
@@ -1675,7 +1679,7 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data
1675 return S_OK; 1679 return S_OK;
1676} 1680}
1677 1681
1678STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 1682Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
1679{ 1683{
1680 COM_TRY_BEGIN 1684 COM_TRY_BEGIN
1681 NWindows::NCOM::CPropVariant prop; 1685 NWindows::NCOM::CPropVariant prop;
@@ -1761,19 +1765,19 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1761 COM_TRY_END 1765 COM_TRY_END
1762} 1766}
1763 1767
1764STDMETHODIMP CHandler::Open(IInStream *inStream, 1768Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
1765 const UInt64 * /* maxCheckStartPosition */, 1769 const UInt64 * /* maxCheckStartPosition */,
1766 IArchiveOpenCallback *callback) 1770 IArchiveOpenCallback *callback))
1767{ 1771{
1768 COM_TRY_BEGIN 1772 COM_TRY_BEGIN
1769 Close(); 1773 Close();
1770 RINOK(Open2(inStream, callback)); 1774 RINOK(Open2(inStream, callback))
1771 _stream = inStream; 1775 _stream = inStream;
1772 return S_OK; 1776 return S_OK;
1773 COM_TRY_END 1777 COM_TRY_END
1774} 1778}
1775 1779
1776STDMETHODIMP CHandler::Close() 1780Z7_COM7F_IMF(CHandler::Close())
1777{ 1781{
1778 _stream.Release(); 1782 _stream.Release();
1779 Clear(); 1783 Clear();
@@ -1802,7 +1806,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1802 const size_t kBufSize = kCompressionBlockSize; 1806 const size_t kBufSize = kCompressionBlockSize;
1803 _buf.Alloc(kBufSize + 0x10); // we need 1 additional bytes for uncompressed chunk header 1807 _buf.Alloc(kBufSize + 0x10); // we need 1 additional bytes for uncompressed chunk header
1804 1808
1805 RINOK(ReadStream_FALSE(inStream, _buf, kHeaderSize)); 1809 RINOK(ReadStream_FALSE(inStream, _buf, kHeaderSize))
1806 Byte *buf = _buf; 1810 Byte *buf = _buf;
1807 const UInt32 dataPos = Get32(buf); 1811 const UInt32 dataPos = Get32(buf);
1808 const UInt32 mapPos = Get32(buf + 4); 1812 const UInt32 mapPos = Get32(buf + 4);
@@ -1837,7 +1841,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1837 1841
1838 _tableBuf.AllocAtLeast(tableSize); 1842 _tableBuf.AllocAtLeast(tableSize);
1839 1843
1840 RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)); 1844 RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize))
1841 const Byte *tableBuf = _tableBuf; 1845 const Byte *tableBuf = _tableBuf;
1842 1846
1843 UInt32 prev = 4 + tableSize; 1847 UInt32 prev = 4 + tableSize;
@@ -1878,7 +1882,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1878 if (size > kCompressionBlockSize + 1) 1882 if (size > kCompressionBlockSize + 1)
1879 return S_FALSE; 1883 return S_FALSE;
1880 1884
1881 RINOK(ReadStream_FALSE(inStream, buf, size)); 1885 RINOK(ReadStream_FALSE(inStream, buf, size))
1882 1886
1883 if ((buf[0] & 0xF) == 0xF) 1887 if ((buf[0] & 0xF) == 0xF)
1884 { 1888 {
@@ -1889,14 +1893,14 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1889 1893
1890 if (outStream) 1894 if (outStream)
1891 { 1895 {
1892 RINOK(WriteStream(outStream, buf, blockSize)); 1896 RINOK(WriteStream(outStream, buf + 1, blockSize))
1893 } 1897 }
1894 } 1898 }
1895 else 1899 else
1896 { 1900 {
1897 const UInt64 blockSize64 = blockSize; 1901 const UInt64 blockSize64 = blockSize;
1898 bufInStreamSpec->Init(buf, size); 1902 bufInStreamSpec->Init(buf, size);
1899 RINOK(_zlibDecoderSpec->Code(bufInStream, outStream, NULL, &blockSize64, NULL)); 1903 RINOK(_zlibDecoder->Code(bufInStream, outStream, NULL, &blockSize64, NULL))
1900 if (_zlibDecoderSpec->GetOutputProcessedSize() != blockSize) 1904 if (_zlibDecoderSpec->GetOutputProcessedSize() != blockSize)
1901 return S_FALSE; 1905 return S_FALSE;
1902 const UInt64 inSize = _zlibDecoderSpec->GetInputProcessedSize(); 1906 const UInt64 inSize = _zlibDecoderSpec->GetInputProcessedSize();
@@ -1928,7 +1932,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1928 if ((i & 0xFF) == 0) 1932 if ((i & 0xFF) == 0)
1929 { 1933 {
1930 const UInt64 progressPos = progressStart + outPos; 1934 const UInt64 progressPos = progressStart + outPos;
1931 RINOK(extractCallback->SetCompleted(&progressPos)); 1935 RINOK(extractCallback->SetCompleted(&progressPos))
1932 } 1936 }
1933 } 1937 }
1934 1938
@@ -1940,7 +1944,7 @@ HRESULT CDecoder::ExtractResourceFork_ZLIB(
1940 /* We check Resource Map 1944 /* We check Resource Map
1941 Are there HFS files with another values in Resource Map ??? */ 1945 Are there HFS files with another values in Resource Map ??? */
1942 1946
1943 RINOK(ReadStream_FALSE(inStream, buf, mapSize)); 1947 RINOK(ReadStream_FALSE(inStream, buf, mapSize))
1944 const UInt32 types = Get16(buf + 24); 1948 const UInt32 types = Get16(buf + 24);
1945 const UInt32 names = Get16(buf + 26); 1949 const UInt32 names = Get16(buf + 26);
1946 const UInt32 numTypes = Get16(buf + 28); 1950 const UInt32 numTypes = Get16(buf + 28);
@@ -1980,7 +1984,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
1980 if (tableSize > forkSize) 1984 if (tableSize > forkSize)
1981 return S_FALSE; 1985 return S_FALSE;
1982 _tableBuf.AllocAtLeast(tableSize); 1986 _tableBuf.AllocAtLeast(tableSize);
1983 RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize)); 1987 RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize))
1984 const Byte *tableBuf = _tableBuf; 1988 const Byte *tableBuf = _tableBuf;
1985 1989
1986 { 1990 {
@@ -2022,7 +2026,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
2022 if (size > kCompressionBlockSize + 1) 2026 if (size > kCompressionBlockSize + 1)
2023 return S_FALSE; 2027 return S_FALSE;
2024 2028
2025 RINOK(ReadStream_FALSE(inStream, _buf, size)); 2029 RINOK(ReadStream_FALSE(inStream, _buf, size))
2026 const Byte *buf = _buf; 2030 const Byte *buf = _buf;
2027 2031
2028 if (buf[0] == k_LZVN_Uncompressed_Marker) 2032 if (buf[0] == k_LZVN_Uncompressed_Marker)
@@ -2031,7 +2035,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
2031 return S_FALSE; 2035 return S_FALSE;
2032 if (outStream) 2036 if (outStream)
2033 { 2037 {
2034 RINOK(WriteStream(outStream, buf, blockSize)); 2038 RINOK(WriteStream(outStream, buf + 1, blockSize))
2035 } 2039 }
2036 } 2040 }
2037 else 2041 else
@@ -2039,7 +2043,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
2039 const UInt64 blockSize64 = blockSize; 2043 const UInt64 blockSize64 = blockSize;
2040 const UInt64 packSize64 = size; 2044 const UInt64 packSize64 = size;
2041 bufInStreamSpec->Init(buf, size); 2045 bufInStreamSpec->Init(buf, size);
2042 RINOK(_lzfseDecoderSpec->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL)); 2046 RINOK(_lzfseDecoder->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL))
2043 // in/out sizes were checked in Code() 2047 // in/out sizes were checked in Code()
2044 } 2048 }
2045 2049
@@ -2047,7 +2051,7 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
2047 if ((i & 0xFF) == 0) 2051 if ((i & 0xFF) == 0)
2048 { 2052 {
2049 const UInt64 progressPos = progressStart + outPos; 2053 const UInt64 progressPos = progressStart + outPos;
2050 RINOK(extractCallback->SetCompleted(&progressPos)); 2054 RINOK(extractCallback->SetCompleted(&progressPos))
2051 } 2055 }
2052 } 2056 }
2053 2057
@@ -2055,6 +2059,186 @@ HRESULT CDecoder::ExtractResourceFork_LZFSE(
2055} 2059}
2056 2060
2057 2061
2062/*
2063static UInt32 GetUi24(const Byte *p)
2064{
2065 return p[0] + ((UInt32)p[1] << 8) + ((UInt32)p[2] << 24);
2066}
2067
2068HRESULT CDecoder::ExtractResourceFork_ZBM(
2069 ISequentialInStream *inStream, ISequentialOutStream *outStream,
2070 UInt64 forkSize, UInt64 unpackSize,
2071 UInt64 progressStart, IArchiveExtractCallback *extractCallback)
2072{
2073 const UInt32 kNumBlocksMax = (UInt32)1 << 29;
2074 if (unpackSize >= (UInt64)kNumBlocksMax * kCompressionBlockSize)
2075 return S_FALSE;
2076 const UInt32 numBlocks = (UInt32)((unpackSize + kCompressionBlockSize - 1) / kCompressionBlockSize);
2077 const UInt32 numBlocks2 = numBlocks + 1;
2078 const UInt32 tableSize = (numBlocks2 << 2);
2079 if (tableSize > forkSize)
2080 return S_FALSE;
2081 _tableBuf.AllocAtLeast(tableSize);
2082 RINOK(ReadStream_FALSE(inStream, _tableBuf, tableSize));
2083 const Byte *tableBuf = _tableBuf;
2084
2085 {
2086 UInt32 prev = GetUi32(tableBuf);
2087 if (prev != tableSize)
2088 return S_FALSE;
2089 for (UInt32 i = 1; i < numBlocks2; i++)
2090 {
2091 const UInt32 offs = GetUi32(tableBuf + i * 4);
2092 if (offs <= prev)
2093 return S_FALSE;
2094 prev = offs;
2095 }
2096 if (prev != forkSize)
2097 return S_FALSE;
2098 }
2099
2100 const size_t kBufSize = kCompressionBlockSize;
2101 _buf.Alloc(kBufSize + 0x10); // we need 1 additional bytes for uncompressed chunk header
2102
2103 CBufInStream *bufInStreamSpec = new CBufInStream;
2104 CMyComPtr<ISequentialInStream> bufInStream = bufInStreamSpec;
2105
2106 UInt64 outPos = 0;
2107
2108 for (UInt32 i = 0; i < numBlocks; i++)
2109 {
2110 const UInt64 rem = unpackSize - outPos;
2111 if (rem == 0)
2112 return S_FALSE;
2113 UInt32 blockSize = kCompressionBlockSize;
2114 if (rem < kCompressionBlockSize)
2115 blockSize = (UInt32)rem;
2116
2117 const UInt32 size =
2118 GetUi32(tableBuf + i * 4 + 4) -
2119 GetUi32(tableBuf + i * 4);
2120
2121 // if (size > kCompressionBlockSize + 1)
2122 if (size > blockSize + 1)
2123 return S_FALSE; // we don't expect it, because encode will use uncompressed chunk
2124
2125 RINOK(ReadStream_FALSE(inStream, _buf, size));
2126 const Byte *buf = _buf;
2127
2128 // (size != 0)
2129 // if (size == 0) return S_FALSE;
2130
2131 if (buf[0] == 0xFF) // uncompressed marker
2132 {
2133 if (size != blockSize + 1)
2134 return S_FALSE;
2135 if (outStream)
2136 {
2137 RINOK(WriteStream(outStream, buf + 1, blockSize));
2138 }
2139 }
2140 else
2141 {
2142 if (size < 4)
2143 return S_FALSE;
2144 if (buf[0] != 'Z' ||
2145 buf[1] != 'B' ||
2146 buf[2] != 'M' ||
2147 buf[3] != 9)
2148 return S_FALSE;
2149 // for debug:
2150 unsigned packPos = 4;
2151 unsigned unpackPos = 0;
2152 unsigned packRem = size - packPos;
2153 for (;;)
2154 {
2155 if (packRem < 6)
2156 return S_FALSE;
2157 const UInt32 packSize = GetUi24(buf + packPos);
2158 const UInt32 chunkUnpackSize = GetUi24(buf + packPos + 3);
2159 if (packSize < 6)
2160 return S_FALSE;
2161 if (packSize > packRem)
2162 return S_FALSE;
2163 if (chunkUnpackSize > blockSize - unpackPos)
2164 return S_FALSE;
2165 packPos += packSize;
2166 packRem -= packSize;
2167 unpackPos += chunkUnpackSize;
2168 if (packSize == 6)
2169 {
2170 if (chunkUnpackSize != 0)
2171 return S_FALSE;
2172 break;
2173 }
2174 if (packSize >= chunkUnpackSize + 6)
2175 {
2176 if (packSize > chunkUnpackSize + 6)
2177 return S_FALSE;
2178 // uncompressed chunk;
2179 }
2180 else
2181 {
2182 // compressed chunk
2183 const Byte *t = buf + packPos - packSize + 6;
2184 UInt32 r = packSize - 6;
2185 if (r < 9)
2186 return S_FALSE;
2187 const UInt32 v0 = GetUi24(t);
2188 const UInt32 v1 = GetUi24(t + 3);
2189 const UInt32 v2 = GetUi24(t + 6);
2190 if (v0 > v1 || v1 > v2 || v2 > packSize)
2191 return S_FALSE;
2192 // here we need the code that will decompress ZBM chunk
2193 }
2194 }
2195
2196 if (unpackPos != blockSize)
2197 return S_FALSE;
2198
2199 UInt32 size1 = size;
2200 if (size1 > kCompressionBlockSize)
2201 {
2202 size1 = kCompressionBlockSize;
2203 // return S_FALSE;
2204 }
2205 if (outStream)
2206 {
2207 RINOK(WriteStream(outStream, buf, size1))
2208
2209 const UInt32 kTempSize = 1 << 16;
2210 Byte temp[kTempSize];
2211 memset(temp, 0, kTempSize);
2212
2213 for (UInt32 k = size1; k < kCompressionBlockSize; k++)
2214 {
2215 UInt32 cur = kCompressionBlockSize - k;
2216 if (cur > kTempSize)
2217 cur = kTempSize;
2218 RINOK(WriteStream(outStream, temp, cur))
2219 k += cur;
2220 }
2221 }
2222
2223 // const UInt64 blockSize64 = blockSize;
2224 // const UInt64 packSize64 = size;
2225 // bufInStreamSpec->Init(buf, size);
2226 // RINOK(_zbmDecoderSpec->Code(bufInStream, outStream, &packSize64, &blockSize64, NULL));
2227 // in/out sizes were checked in Code()
2228 }
2229
2230 outPos += blockSize;
2231 if ((i & 0xFF) == 0)
2232 {
2233 const UInt64 progressPos = progressStart + outPos;
2234 RINOK(extractCallback->SetCompleted(&progressPos));
2235 }
2236 }
2237
2238 return S_OK;
2239}
2240*/
2241
2058HRESULT CDecoder::Extract( 2242HRESULT CDecoder::Extract(
2059 ISequentialInStream *inStreamFork, ISequentialOutStream *realOutStream, 2243 ISequentialInStream *inStreamFork, ISequentialOutStream *realOutStream,
2060 UInt64 forkSize, 2244 UInt64 forkSize,
@@ -2070,7 +2254,7 @@ HRESULT CDecoder::Extract(
2070 const size_t packSize = data->Size() - compressHeader.DataPos; 2254 const size_t packSize = data->Size() - compressHeader.DataPos;
2071 if (realOutStream) 2255 if (realOutStream)
2072 { 2256 {
2073 RINOK(WriteStream(realOutStream, *data + compressHeader.DataPos, packSize)); 2257 RINOK(WriteStream(realOutStream, *data + compressHeader.DataPos, packSize))
2074 } 2258 }
2075 opRes = NExtract::NOperationResult::kOK; 2259 opRes = NExtract::NOperationResult::kOK;
2076 return S_OK; 2260 return S_OK;
@@ -2122,6 +2306,15 @@ HRESULT CDecoder::Extract(
2122 forkSize, compressHeader.UnpackSize, 2306 forkSize, compressHeader.UnpackSize,
2123 progressStart, extractCallback); 2307 progressStart, extractCallback);
2124 } 2308 }
2309 /*
2310 else if (compressHeader.Method == NHfs::kMethod_ZBM_RSRC)
2311 {
2312 hres = ExtractResourceFork_ZBM(
2313 inStreamFork, realOutStream,
2314 forkSize, compressHeader.UnpackSize,
2315 progressStart, extractCallback);
2316 }
2317 */
2125 else 2318 else
2126 { 2319 {
2127 opRes = NExtract::NOperationResult::kUnsupportedMethod; 2320 opRes = NExtract::NOperationResult::kUnsupportedMethod;
@@ -2134,8 +2327,8 @@ HRESULT CDecoder::Extract(
2134} 2327}
2135 2328
2136 2329
2137STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2330Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2138 Int32 testMode, IArchiveExtractCallback *extractCallback) 2331 Int32 testMode, IArchiveExtractCallback *extractCallback))
2139{ 2332{
2140 COM_TRY_BEGIN 2333 COM_TRY_BEGIN
2141 const bool allFilesMode = (numItems == (UInt32)(Int32)-1); 2334 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
@@ -2150,7 +2343,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2150 const CRef &ref = Refs[allFilesMode ? i : indices[i]]; 2343 const CRef &ref = Refs[allFilesMode ? i : indices[i]];
2151 totalSize += Get_UnpackSize_of_Ref(ref); 2344 totalSize += Get_UnpackSize_of_Ref(ref);
2152 } 2345 }
2153 RINOK(extractCallback->SetTotal(totalSize)); 2346 RINOK(extractCallback->SetTotal(totalSize))
2154 2347
2155 UInt64 currentTotalSize = 0, currentItemSize = 0; 2348 UInt64 currentTotalSize = 0, currentItemSize = 0;
2156 2349
@@ -2161,30 +2354,30 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2161 2354
2162 for (i = 0;; i++, currentTotalSize += currentItemSize) 2355 for (i = 0;; i++, currentTotalSize += currentItemSize)
2163 { 2356 {
2164 RINOK(extractCallback->SetCompleted(&currentTotalSize)); 2357 RINOK(extractCallback->SetCompleted(&currentTotalSize))
2165 if (i == numItems) 2358 if (i == numItems)
2166 break; 2359 break;
2167 UInt32 index = allFilesMode ? i : indices[i]; 2360 const UInt32 index = allFilesMode ? i : indices[i];
2168 const CRef &ref = Refs[index]; 2361 const CRef &ref = Refs[index];
2169 const CItem &item = Items[ref.ItemIndex]; 2362 const CItem &item = Items[ref.ItemIndex];
2170 currentItemSize = Get_UnpackSize_of_Ref(ref); 2363 currentItemSize = Get_UnpackSize_of_Ref(ref);
2171 2364
2172 CMyComPtr<ISequentialOutStream> realOutStream; 2365 CMyComPtr<ISequentialOutStream> realOutStream;
2173 Int32 askMode = testMode ? 2366 const Int32 askMode = testMode ?
2174 NExtract::NAskMode::kTest : 2367 NExtract::NAskMode::kTest :
2175 NExtract::NAskMode::kExtract; 2368 NExtract::NAskMode::kExtract;
2176 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 2369 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
2177 2370
2178 if (ref.IsItem() && item.IsDir()) 2371 if (ref.IsItem() && item.IsDir())
2179 { 2372 {
2180 RINOK(extractCallback->PrepareOperation(askMode)); 2373 RINOK(extractCallback->PrepareOperation(askMode))
2181 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2374 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2182 continue; 2375 continue;
2183 } 2376 }
2184 if (!testMode && !realOutStream) 2377 if (!testMode && !realOutStream)
2185 continue; 2378 continue;
2186 2379
2187 RINOK(extractCallback->PrepareOperation(askMode)); 2380 RINOK(extractCallback->PrepareOperation(askMode))
2188 2381
2189 UInt64 pos = 0; 2382 UInt64 pos = 0;
2190 int opRes = NExtract::NOperationResult::kDataError; 2383 int opRes = NExtract::NOperationResult::kDataError;
@@ -2203,7 +2396,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2203 RINOK(WriteStream(realOutStream, 2396 RINOK(WriteStream(realOutStream,
2204 // AttrBuf + attr.Pos, attr.Size 2397 // AttrBuf + attr.Pos, attr.Size
2205 attr.Data, attr.Data.Size() 2398 attr.Data, attr.Data.Size()
2206 )); 2399 ))
2207 } 2400 }
2208 } 2401 }
2209 } 2402 }
@@ -2258,7 +2451,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2258 if (fork->Size == pos) 2451 if (fork->Size == pos)
2259 break; 2452 break;
2260 const CExtent &e = fork->Extents[extentIndex]; 2453 const CExtent &e = fork->Extents[extentIndex];
2261 RINOK(_stream->Seek(SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog), STREAM_SEEK_SET, NULL)); 2454 RINOK(InStream_SeekSet(_stream, SpecOffset + ((UInt64)e.Pos << Header.BlockSizeLog)))
2262 UInt64 extentRem = (UInt64)e.NumBlocks << Header.BlockSizeLog; 2455 UInt64 extentRem = (UInt64)e.NumBlocks << Header.BlockSizeLog;
2263 while (extentRem != 0) 2456 while (extentRem != 0)
2264 { 2457 {
@@ -2275,7 +2468,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2275 cur = (size_t)rem; 2468 cur = (size_t)rem;
2276 if (cur > extentRem) 2469 if (cur > extentRem)
2277 cur = (size_t)extentRem; 2470 cur = (size_t)extentRem;
2278 RINOK(ReadStream(_stream, buf, &cur)); 2471 RINOK(ReadStream(_stream, buf, &cur))
2279 if (cur == 0) 2472 if (cur == 0)
2280 { 2473 {
2281 opRes = NExtract::NOperationResult::kDataError; 2474 opRes = NExtract::NOperationResult::kDataError;
@@ -2283,12 +2476,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2283 } 2476 }
2284 if (realOutStream) 2477 if (realOutStream)
2285 { 2478 {
2286 RINOK(WriteStream(realOutStream, buf, cur)); 2479 RINOK(WriteStream(realOutStream, buf, cur))
2287 } 2480 }
2288 pos += cur; 2481 pos += cur;
2289 extentRem -= cur; 2482 extentRem -= cur;
2290 const UInt64 processed = currentTotalSize + pos; 2483 const UInt64 processed = currentTotalSize + pos;
2291 RINOK(extractCallback->SetCompleted(&processed)); 2484 RINOK(extractCallback->SetCompleted(&processed))
2292 } 2485 }
2293 } 2486 }
2294 if (extentIndex != fork->Extents.Size() || fork->Size != pos) 2487 if (extentIndex != fork->Extents.Size() || fork->Size != pos)
@@ -2296,13 +2489,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2296 } 2489 }
2297 } 2490 }
2298 realOutStream.Release(); 2491 realOutStream.Release();
2299 RINOK(extractCallback->SetOperationResult(opRes)); 2492 RINOK(extractCallback->SetOperationResult(opRes))
2300 } 2493 }
2301 return S_OK; 2494 return S_OK;
2302 COM_TRY_END 2495 COM_TRY_END
2303} 2496}
2304 2497
2305STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 2498Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
2306{ 2499{
2307 *numItems = Refs.Size(); 2500 *numItems = Refs.Size();
2308 return S_OK; 2501 return S_OK;
@@ -2310,7 +2503,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
2310 2503
2311HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream) 2504HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream)
2312{ 2505{
2313 *stream = 0; 2506 *stream = NULL;
2314 2507
2315 if (!fork.IsOk(Header.BlockSizeLog)) 2508 if (!fork.IsOk(Header.BlockSizeLog))
2316 return S_FALSE; 2509 return S_FALSE;
@@ -2354,9 +2547,9 @@ HRESULT CHandler::GetForkStream(const CFork &fork, ISequentialInStream **stream)
2354 return S_OK; 2547 return S_OK;
2355} 2548}
2356 2549
2357STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 2550Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
2358{ 2551{
2359 *stream = 0; 2552 *stream = NULL;
2360 2553
2361 const CRef &ref = Refs[index]; 2554 const CRef &ref = Refs[index];
2362 const CFork *fork = NULL; 2555 const CFork *fork = NULL;
@@ -2388,7 +2581,7 @@ static const Byte k_Signature[] = {
2388 4, 'H', 'X', 0, 5 }; 2581 4, 'H', 'X', 0, 5 };
2389 2582
2390REGISTER_ARC_I( 2583REGISTER_ARC_I(
2391 "HFS", "hfs hfsx", 0, 0xE3, 2584 "HFS", "hfs hfsx", NULL, 0xE3,
2392 k_Signature, 2585 k_Signature,
2393 kHeaderPadSize, 2586 kHeaderPadSize,
2394 NArcInfoFlags::kMultiSignature, 2587 NArcInfoFlags::kMultiSignature,
diff --git a/CPP/7zip/Archive/HfsHandler.h b/CPP/7zip/Archive/HfsHandler.h
index 2461f6b..0006e12 100644
--- a/CPP/7zip/Archive/HfsHandler.h
+++ b/CPP/7zip/Archive/HfsHandler.h
@@ -1,7 +1,7 @@
1// HfsHandler.h 1// HfsHandler.h
2 2
3#ifndef __HFS_HANDLER_H 3#ifndef ZIP7_INC_HFS_HANDLER_H
4#define __HFS_HANDLER_H 4#define ZIP7_INC_HFS_HANDLER_H
5 5
6#include "../../Windows/PropVariant.h" 6#include "../../Windows/PropVariant.h"
7 7
@@ -67,6 +67,11 @@ class CDecoder
67 UInt64 forkSize, UInt64 unpackSize, 67 UInt64 forkSize, UInt64 unpackSize,
68 UInt64 progressStart, IArchiveExtractCallback *extractCallback); 68 UInt64 progressStart, IArchiveExtractCallback *extractCallback);
69 69
70 HRESULT ExtractResourceFork_ZBM(
71 ISequentialInStream *inStream, ISequentialOutStream *realOutStream,
72 UInt64 forkSize, UInt64 unpackSize,
73 UInt64 progressStart, IArchiveExtractCallback *extractCallback);
74
70public: 75public:
71 76
72 HRESULT Extract( 77 HRESULT Extract(
diff --git a/CPP/7zip/Archive/IArchive.h b/CPP/7zip/Archive/IArchive.h
index 9551dfa..3e68ac3 100644
--- a/CPP/7zip/Archive/IArchive.h
+++ b/CPP/7zip/Archive/IArchive.h
@@ -1,14 +1,21 @@
1// IArchive.h 1// IArchive.h
2 2
3#ifndef __IARCHIVE_H 3#ifndef ZIP7_INC_IARCHIVE_H
4#define __IARCHIVE_H 4#define ZIP7_INC_IARCHIVE_H
5 5
6#include "../IProgress.h" 6#include "../IProgress.h"
7#include "../IStream.h" 7#include "../IStream.h"
8#include "../PropID.h" 8#include "../PropID.h"
9 9
10#define ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 6, x) 10Z7_PURE_INTERFACES_BEGIN
11#define ARCHIVE_INTERFACE(i, x) ARCHIVE_INTERFACE_SUB(i, IUnknown, x) 11
12
13#define Z7_IFACE_CONSTR_ARCHIVE_SUB(i, base, n) \
14 Z7_DECL_IFACE_7ZIP_SUB(i, base, 6, n) \
15 { Z7_IFACE_COM7_PURE(i) };
16
17#define Z7_IFACE_CONSTR_ARCHIVE(i, n) \
18 Z7_IFACE_CONSTR_ARCHIVE_SUB(i, IUnknown, n)
12 19
13/* 20/*
14How the function in 7-Zip returns object for output parameter via pointer 21How the function in 7-Zip returns object for output parameter via pointer
@@ -81,11 +88,11 @@ namespace NArcInfoTimeFlags
81 const unsigned kTime_Prec_Default_num_bits = 5; 88 const unsigned kTime_Prec_Default_num_bits = 5;
82} 89}
83 90
84#define TIME_PREC_TO_ARC_FLAGS_MASK(x) \ 91#define TIME_PREC_TO_ARC_FLAGS_MASK(v) \
85 ((UInt32)1 << (NArcInfoTimeFlags::kTime_Prec_Mask_bit_index + (x))) 92 ((UInt32)1 << (NArcInfoTimeFlags::kTime_Prec_Mask_bit_index + (v)))
86 93
87#define TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(x) \ 94#define TIME_PREC_TO_ARC_FLAGS_TIME_DEFAULT(v) \
88 ((UInt32)(x) << NArcInfoTimeFlags::kTime_Prec_Default_bit_index) 95 ((UInt32)(v) << NArcInfoTimeFlags::kTime_Prec_Default_bit_index)
89 96
90namespace NArchive 97namespace NArchive
91{ 98{
@@ -136,6 +143,7 @@ namespace NArchive
136 kIsNotArc, 143 kIsNotArc,
137 kHeadersError, 144 kHeadersError,
138 kWrongPassword 145 kWrongPassword
146 // , kMemError
139 }; 147 };
140 } 148 }
141 } 149 }
@@ -166,14 +174,11 @@ namespace NArchive
166 } 174 }
167} 175}
168 176
169#define INTERFACE_IArchiveOpenCallback(x) \ 177#define Z7_IFACEM_IArchiveOpenCallback(x) \
170 STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes) x; \ 178 x(SetTotal(const UInt64 *files, const UInt64 *bytes)) \
171 STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes) x; \ 179 x(SetCompleted(const UInt64 *files, const UInt64 *bytes)) \
172 180
173ARCHIVE_INTERFACE(IArchiveOpenCallback, 0x10) 181Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenCallback, 0x10)
174{
175 INTERFACE_IArchiveOpenCallback(PURE);
176};
177 182
178/* 183/*
179IArchiveExtractCallback:: 184IArchiveExtractCallback::
@@ -224,57 +229,49 @@ SetOperationResult()
224 Int32 opRes (NExtract::NOperationResult) 229 Int32 opRes (NExtract::NOperationResult)
225*/ 230*/
226 231
227#define INTERFACE_IArchiveExtractCallback(x) \ 232// INTERFACE_IProgress(x)
228 INTERFACE_IProgress(x) \
229 STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) x; \
230 STDMETHOD(PrepareOperation)(Int32 askExtractMode) x; \
231 STDMETHOD(SetOperationResult)(Int32 opRes) x; \
232 233
233ARCHIVE_INTERFACE_SUB(IArchiveExtractCallback, IProgress, 0x20) 234#define Z7_IFACEM_IArchiveExtractCallback(x) \
234{ 235 x(GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode)) \
235 INTERFACE_IArchiveExtractCallback(PURE) 236 x(PrepareOperation(Int32 askExtractMode)) \
236}; 237 x(SetOperationResult(Int32 opRes)) \
238
239Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveExtractCallback, IProgress, 0x20)
237 240
238 241
239 242
240/* 243/*
241IArchiveExtractCallbackMessage can be requested from IArchiveExtractCallback object 244v23:
245IArchiveExtractCallbackMessage2 can be requested from IArchiveExtractCallback object
242 by Extract() or UpdateItems() functions to report about extracting errors 246 by Extract() or UpdateItems() functions to report about extracting errors
243ReportExtractResult() 247ReportExtractResult()
244 UInt32 indexType (NEventIndexType) 248 UInt32 indexType (NEventIndexType)
245 UInt32 index 249 UInt32 index
246 Int32 opRes (NExtract::NOperationResult) 250 Int32 opRes (NExtract::NOperationResult)
247*/ 251*/
252/*
253before v23:
254#define Z7_IFACEM_IArchiveExtractCallbackMessage(x) \
255 x(ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes))
256Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveExtractCallbackMessage, IProgress, 0x21)
257*/
258#define Z7_IFACEM_IArchiveExtractCallbackMessage2(x) \
259 x(ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes))
260Z7_IFACE_CONSTR_ARCHIVE(IArchiveExtractCallbackMessage2, 0x22)
248 261
249#define INTERFACE_IArchiveExtractCallbackMessage(x) \ 262#define Z7_IFACEM_IArchiveOpenVolumeCallback(x) \
250 STDMETHOD(ReportExtractResult)(UInt32 indexType, UInt32 index, Int32 opRes) x; \ 263 x(GetProperty(PROPID propID, PROPVARIANT *value)) \
251 264 x(GetStream(const wchar_t *name, IInStream **inStream))
252ARCHIVE_INTERFACE_SUB(IArchiveExtractCallbackMessage, IProgress, 0x21) 265Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenVolumeCallback, 0x30)
253{
254 INTERFACE_IArchiveExtractCallbackMessage(PURE)
255};
256
257 266
258#define INTERFACE_IArchiveOpenVolumeCallback(x) \
259 STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) x; \
260 STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream) x; \
261
262ARCHIVE_INTERFACE(IArchiveOpenVolumeCallback, 0x30)
263{
264 INTERFACE_IArchiveOpenVolumeCallback(PURE);
265};
266 267
268#define Z7_IFACEM_IInArchiveGetStream(x) \
269 x(GetStream(UInt32 index, ISequentialInStream **stream))
270Z7_IFACE_CONSTR_ARCHIVE(IInArchiveGetStream, 0x40)
267 271
268ARCHIVE_INTERFACE(IInArchiveGetStream, 0x40) 272#define Z7_IFACEM_IArchiveOpenSetSubArchiveName(x) \
269{ 273 x(SetSubArchiveName(const wchar_t *name))
270 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) PURE; 274Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenSetSubArchiveName, 0x50)
271};
272
273
274ARCHIVE_INTERFACE(IArchiveOpenSetSubArchiveName, 0x50)
275{
276 STDMETHOD(SetSubArchiveName)(const wchar_t *name) PURE;
277};
278 275
279 276
280/* 277/*
@@ -310,28 +307,25 @@ Notes:
310 Some IInArchive handlers will work incorrectly in that case. 307 Some IInArchive handlers will work incorrectly in that case.
311*/ 308*/
312 309
313#ifdef _MSC_VER 310#if defined(_MSC_VER) && !defined(__clang__)
314 #define MY_NO_THROW_DECL_ONLY throw() 311 #define MY_NO_THROW_DECL_ONLY Z7_COM7F_E
315#else 312#else
316 #define MY_NO_THROW_DECL_ONLY 313 #define MY_NO_THROW_DECL_ONLY
317#endif 314#endif
318 315
319#define INTERFACE_IInArchive(x) \ 316#define Z7_IFACEM_IInArchive(x) \
320 STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback) MY_NO_THROW_DECL_ONLY x; \ 317 x(Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback)) \
321 STDMETHOD(Close)() MY_NO_THROW_DECL_ONLY x; \ 318 x(Close()) \
322 STDMETHOD(GetNumberOfItems)(UInt32 *numItems) MY_NO_THROW_DECL_ONLY x; \ 319 x(GetNumberOfItems(UInt32 *numItems)) \
323 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 320 x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
324 STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) MY_NO_THROW_DECL_ONLY x; \ 321 x(Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback)) \
325 STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) MY_NO_THROW_DECL_ONLY x; \ 322 x(GetArchiveProperty(PROPID propID, PROPVARIANT *value)) \
326 STDMETHOD(GetNumberOfProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 323 x(GetNumberOfProperties(UInt32 *numProps)) \
327 STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 324 x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
328 STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProps) MY_NO_THROW_DECL_ONLY x; \ 325 x(GetNumberOfArchiveProperties(UInt32 *numProps)) \
329 STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) MY_NO_THROW_DECL_ONLY x; \ 326 x(GetArchivePropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
330 327
331ARCHIVE_INTERFACE(IInArchive, 0x60) 328Z7_IFACE_CONSTR_ARCHIVE(IInArchive, 0x60)
332{
333 INTERFACE_IInArchive(PURE)
334};
335 329
336namespace NParentType 330namespace NParentType
337{ 331{
@@ -340,7 +334,7 @@ namespace NParentType
340 kDir = 0, 334 kDir = 0,
341 kAltStream 335 kAltStream
342 }; 336 };
343}; 337}
344 338
345namespace NPropDataType 339namespace NPropDataType
346{ 340{
@@ -356,41 +350,36 @@ namespace NPropDataType
356 350
357 const UInt32 kUtf8z = kMask_Utf8 | kMask_ZeroEnd; 351 const UInt32 kUtf8z = kMask_Utf8 | kMask_ZeroEnd;
358 const UInt32 kUtf16z = kMask_Utf16 | kMask_ZeroEnd; 352 const UInt32 kUtf16z = kMask_Utf16 | kMask_ZeroEnd;
359}; 353}
360 354
361// UTF string (pointer to wchar_t) with zero end and little-endian. 355// UTF string (pointer to wchar_t) with zero end and little-endian.
362#define PROP_DATA_TYPE_wchar_t_PTR_Z_LE ((NPropDataType::kMask_Utf | NPropDataType::kMask_ZeroEnd) + (sizeof(wchar_t) >> 1)) 356#define PROP_DATA_TYPE_wchar_t_PTR_Z_LE ((NPropDataType::kMask_Utf | NPropDataType::kMask_ZeroEnd) + (sizeof(wchar_t) >> 1))
363 357
358
364/* 359/*
365GetRawProp: 360GetRawProp:
366 Result: 361 Result:
367 S_OK - even if property is not set 362 S_OK - even if property is not set
368*/ 363*/
369 364
370#define INTERFACE_IArchiveGetRawProps(x) \ 365#define Z7_IFACEM_IArchiveGetRawProps(x) \
371 STDMETHOD(GetParent)(UInt32 index, UInt32 *parent, UInt32 *parentType) x; \ 366 x(GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)) \
372 STDMETHOD(GetRawProp)(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) x; \ 367 x(GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) \
373 STDMETHOD(GetNumRawProps)(UInt32 *numProps) x; \ 368 x(GetNumRawProps(UInt32 *numProps)) \
374 STDMETHOD(GetRawPropInfo)(UInt32 index, BSTR *name, PROPID *propID) x; 369 x(GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
375 370
376ARCHIVE_INTERFACE(IArchiveGetRawProps, 0x70) 371Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetRawProps, 0x70)
377{
378 INTERFACE_IArchiveGetRawProps(PURE)
379};
380 372
381#define INTERFACE_IArchiveGetRootProps(x) \ 373#define Z7_IFACEM_IArchiveGetRootProps(x) \
382 STDMETHOD(GetRootProp)(PROPID propID, PROPVARIANT *value) x; \ 374 x(GetRootProp(PROPID propID, PROPVARIANT *value)) \
383 STDMETHOD(GetRootRawProp)(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) x; \ 375 x(GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)) \
384 376
385ARCHIVE_INTERFACE(IArchiveGetRootProps, 0x71) 377Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetRootProps, 0x71)
386{
387 INTERFACE_IArchiveGetRootProps(PURE)
388};
389 378
390ARCHIVE_INTERFACE(IArchiveOpenSeq, 0x61) 379#define Z7_IFACEM_IArchiveOpenSeq(x) \
391{ 380 x(OpenSeq(ISequentialInStream *stream)) \
392 STDMETHOD(OpenSeq)(ISequentialInStream *stream) PURE; 381
393}; 382Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpenSeq, 0x61)
394 383
395/* 384/*
396 OpenForSize 385 OpenForSize
@@ -416,12 +405,10 @@ Flags:
416 the handler can return S_OK, but it doesn't check even Signature. 405 the handler can return S_OK, but it doesn't check even Signature.
417 So next Extract can be called for that sequential stream. 406 So next Extract can be called for that sequential stream.
418*/ 407*/
419
420/* 408/*
421ARCHIVE_INTERFACE(IArchiveOpen2, 0x62) 409#define Z7_IFACEM_IArchiveOpen2(x) \
422{ 410 x(ArcOpen2(ISequentialInStream *stream, UInt32 flags, IArchiveOpenCallback *openCallback))
423 STDMETHOD(ArcOpen2)(ISequentialInStream *stream, UInt32 flags, IArchiveOpenCallback *openCallback) PURE; 411Z7_IFACE_CONSTR_ARCHIVE(IArchiveOpen2, 0x62)
424};
425*/ 412*/
426 413
427// ---------- UPDATE ---------- 414// ---------- UPDATE ----------
@@ -454,27 +441,21 @@ SetOperationResult()
454 Int32 opRes (NExtract::NOperationResult::kOK) 441 Int32 opRes (NExtract::NOperationResult::kOK)
455*/ 442*/
456 443
457#define INTERFACE_IArchiveUpdateCallback(x) \ 444// INTERFACE_IProgress(x)
458 INTERFACE_IProgress(x); \ 445#define Z7_IFACEM_IArchiveUpdateCallback(x) \
459 STDMETHOD(GetUpdateItemInfo)(UInt32 index, Int32 *newData, Int32 *newProps, UInt32 *indexInArchive) x; \ 446 x(GetUpdateItemInfo(UInt32 index, Int32 *newData, Int32 *newProps, UInt32 *indexInArchive)) \
460 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ 447 x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
461 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream) x; \ 448 x(GetStream(UInt32 index, ISequentialInStream **inStream)) \
462 STDMETHOD(SetOperationResult)(Int32 operationResult) x; \ 449 x(SetOperationResult(Int32 operationResult)) \
463 450
464ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback, IProgress, 0x80) 451Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveUpdateCallback, IProgress, 0x80)
465{
466 INTERFACE_IArchiveUpdateCallback(PURE);
467};
468 452
469#define INTERFACE_IArchiveUpdateCallback2(x) \ 453// INTERFACE_IArchiveUpdateCallback(x)
470 INTERFACE_IArchiveUpdateCallback(x) \ 454#define Z7_IFACEM_IArchiveUpdateCallback2(x) \
471 STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size) x; \ 455 x(GetVolumeSize(UInt32 index, UInt64 *size)) \
472 STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream) x; \ 456 x(GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)) \
473 457
474ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82) 458Z7_IFACE_CONSTR_ARCHIVE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82)
475{
476 INTERFACE_IArchiveUpdateCallback2(PURE);
477};
478 459
479namespace NUpdateNotifyOp 460namespace NUpdateNotifyOp
480{ 461{
@@ -493,7 +474,7 @@ namespace NUpdateNotifyOp
493 // , kOpFinished 474 // , kOpFinished
494 // , kNumDefined 475 // , kNumDefined
495 }; 476 };
496}; 477}
497 478
498/* 479/*
499IArchiveUpdateCallbackFile::ReportOperation 480IArchiveUpdateCallbackFile::ReportOperation
@@ -502,36 +483,26 @@ IArchiveUpdateCallbackFile::ReportOperation
502 UInt32 notifyOp (NUpdateNotifyOp) 483 UInt32 notifyOp (NUpdateNotifyOp)
503*/ 484*/
504 485
505#define INTERFACE_IArchiveUpdateCallbackFile(x) \ 486#define Z7_IFACEM_IArchiveUpdateCallbackFile(x) \
506 STDMETHOD(GetStream2)(UInt32 index, ISequentialInStream **inStream, UInt32 notifyOp) x; \ 487 x(GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 notifyOp)) \
507 STDMETHOD(ReportOperation)(UInt32 indexType, UInt32 index, UInt32 notifyOp) x; \ 488 x(ReportOperation(UInt32 indexType, UInt32 index, UInt32 notifyOp)) \
508 489
509ARCHIVE_INTERFACE(IArchiveUpdateCallbackFile, 0x83) 490Z7_IFACE_CONSTR_ARCHIVE(IArchiveUpdateCallbackFile, 0x83)
510{
511 INTERFACE_IArchiveUpdateCallbackFile(PURE);
512};
513 491
514 492
515#define INTERFACE_IArchiveGetDiskProperty(x) \ 493#define Z7_IFACEM_IArchiveGetDiskProperty(x) \
516 STDMETHOD(GetDiskProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ 494 x(GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
517 495
518ARCHIVE_INTERFACE(IArchiveGetDiskProperty, 0x84) 496Z7_IFACE_CONSTR_ARCHIVE(IArchiveGetDiskProperty, 0x84)
519{
520 INTERFACE_IArchiveGetDiskProperty(PURE);
521};
522 497
523/* 498/*
524#define INTERFACE_IArchiveUpdateCallbackArcProp(x) \ 499#define Z7_IFACEM_IArchiveUpdateCallbackArcProp(x) \
525 STDMETHOD(ReportProp)(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x; \ 500 x(ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value)) \
526 STDMETHOD(ReportRawProp)(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x; \ 501 x(ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType)) \
527 STDMETHOD(ReportFinished)(UInt32 indexType, UInt32 index, Int32 opRes) x; \ 502 x(ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes)) \
528 STDMETHOD(DoNeedArcProp)(PROPID propID, Int32 *answer) x; \ 503 x(DoNeedArcProp(PROPID propID, Int32 *answer)) \
529 504
530 505Z7_IFACE_CONSTR_ARCHIVE(IArchiveUpdateCallbackArcProp, 0x85)
531ARCHIVE_INTERFACE(IArchiveUpdateCallbackArcProp, 0x85)
532{
533 INTERFACE_IArchiveUpdateCallbackArcProp(PURE);
534};
535*/ 506*/
536 507
537/* 508/*
@@ -556,14 +527,11 @@ UpdateItems()
556*/ 527*/
557 528
558 529
559#define INTERFACE_IOutArchive(x) \ 530#define Z7_IFACEM_IOutArchive(x) \
560 STDMETHOD(UpdateItems)(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback) x; \ 531 x(UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback)) \
561 STDMETHOD(GetFileTimeType)(UInt32 *type) x; 532 x(GetFileTimeType(UInt32 *type))
562 533
563ARCHIVE_INTERFACE(IOutArchive, 0xA0) 534Z7_IFACE_CONSTR_ARCHIVE(IOutArchive, 0xA0)
564{
565 INTERFACE_IOutArchive(PURE)
566};
567 535
568 536
569/* 537/*
@@ -576,31 +544,26 @@ ISetProperties::SetProperties()
576 VT_BSTR 544 VT_BSTR
577*/ 545*/
578 546
579ARCHIVE_INTERFACE(ISetProperties, 0x03) 547#define Z7_IFACEM_ISetProperties(x) \
580{ 548 x(SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
581 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) PURE;
582};
583 549
584ARCHIVE_INTERFACE(IArchiveKeepModeForNextOpen, 0x04) 550Z7_IFACE_CONSTR_ARCHIVE(ISetProperties, 0x03)
585{ 551
586 STDMETHOD(KeepModeForNextOpen)() PURE; 552#define Z7_IFACEM_IArchiveKeepModeForNextOpen(x) \
587}; 553 x(KeepModeForNextOpen()) \
554
555Z7_IFACE_CONSTR_ARCHIVE(IArchiveKeepModeForNextOpen, 0x04)
588 556
589/* Exe handler: the handler for executable format (PE, ELF, Mach-O). 557/* Exe handler: the handler for executable format (PE, ELF, Mach-O).
590 SFX archive: executable stub + some tail data. 558 SFX archive: executable stub + some tail data.
591 before 9.31: exe handler didn't parse SFX archives as executable format. 559 before 9.31: exe handler didn't parse SFX archives as executable format.
592 for 9.31+: exe handler parses SFX archives as executable format, only if AllowTail(1) was called */ 560 for 9.31+: exe handler parses SFX archives as executable format, only if AllowTail(1) was called */
593 561
594ARCHIVE_INTERFACE(IArchiveAllowTail, 0x05) 562#define Z7_IFACEM_IArchiveAllowTail(x) \
595{ 563 x(AllowTail(Int32 allowTail)) \
596 STDMETHOD(AllowTail)(Int32 allowTail) PURE;
597};
598 564
565Z7_IFACE_CONSTR_ARCHIVE(IArchiveAllowTail, 0x05)
599 566
600#define IMP_IInArchive_GetProp(k) \
601 (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \
602 { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \
603 *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = 0; return S_OK; } \
604 567
605 568
606struct CStatProp 569struct CStatProp
@@ -616,46 +579,69 @@ namespace NCOM {
616BSTR AllocBstrFromAscii(const char *s) throw(); 579BSTR AllocBstrFromAscii(const char *s) throw();
617}} 580}}
618 581
619#define IMP_IInArchive_GetProp_WITH_NAME(k) \ 582
620 (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ 583#define IMP_IInArchive_GetProp_Base(fn, f, k) \
621 { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ 584 Z7_COM7F_IMF(CHandler::fn(UInt32 *numProps)) \
585 { *numProps = Z7_ARRAY_SIZE(k); return S_OK; } \
586 Z7_COM7F_IMF(CHandler::f(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
587 { if (index >= Z7_ARRAY_SIZE(k)) return E_INVALIDARG; \
588
589#define IMP_IInArchive_GetProp_NO_NAME(fn, f, k) \
590 IMP_IInArchive_GetProp_Base(fn, f, k) \
591 *propID = k[index]; \
592 *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; \
593 *name = NULL; return S_OK; } \
594
595#define IMP_IInArchive_GetProp_WITH_NAME(fn, f, k) \
596 IMP_IInArchive_GetProp_Base(fn, f, k) \
622 const CStatProp &prop = k[index]; \ 597 const CStatProp &prop = k[index]; \
623 *propID = (PROPID)prop.PropID; *varType = prop.vt; \ 598 *propID = (PROPID)prop.PropID; \
599 *varType = prop.vt; \
624 *name = NWindows::NCOM::AllocBstrFromAscii(prop.Name); return S_OK; } \ 600 *name = NWindows::NCOM::AllocBstrFromAscii(prop.Name); return S_OK; } \
625 601
602
626#define IMP_IInArchive_Props \ 603#define IMP_IInArchive_Props \
627 STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) \ 604 IMP_IInArchive_GetProp_NO_NAME(GetNumberOfProperties, GetPropertyInfo, kProps)
628 { *numProps = ARRAY_SIZE(kProps); return S_OK; } \
629 STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp(kProps)
630 605
631#define IMP_IInArchive_Props_WITH_NAME \ 606#define IMP_IInArchive_Props_WITH_NAME \
632 STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProps) \ 607 IMP_IInArchive_GetProp_WITH_NAME(GetNumberOfProperties, GetPropertyInfo, kProps)
633 { *numProps = ARRAY_SIZE(kProps); return S_OK; } \
634 STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kProps)
635
636 608
637#define IMP_IInArchive_ArcProps \ 609#define IMP_IInArchive_ArcProps \
638 STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ 610 IMP_IInArchive_GetProp_NO_NAME(GetNumberOfArchiveProperties, GetArchivePropertyInfo, kArcProps)
639 { *numProps = ARRAY_SIZE(kArcProps); return S_OK; } \
640 STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp(kArcProps)
641 611
642#define IMP_IInArchive_ArcProps_WITH_NAME \ 612#define IMP_IInArchive_ArcProps_WITH_NAME \
643 STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ 613 IMP_IInArchive_GetProp_WITH_NAME(GetNumberOfArchiveProperties, GetArchivePropertyInfo, kArcProps)
644 { *numProps = ARRAY_SIZE(kArcProps); return S_OK; } \
645 STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kArcProps)
646 614
647#define IMP_IInArchive_ArcProps_NO_Table \ 615#define IMP_IInArchive_ArcProps_NO_Table \
648 STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProps) \ 616 Z7_COM7F_IMF(CHandler::GetNumberOfArchiveProperties(UInt32 *numProps)) \
649 { *numProps = 0; return S_OK; } \ 617 { *numProps = 0; return S_OK; } \
650 STDMETHODIMP CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *) \ 618 Z7_COM7F_IMF(CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *)) \
651 { return E_NOTIMPL; } \ 619 { return E_NOTIMPL; } \
652 620
653#define IMP_IInArchive_ArcProps_NO \ 621#define IMP_IInArchive_ArcProps_NO \
654 IMP_IInArchive_ArcProps_NO_Table \ 622 IMP_IInArchive_ArcProps_NO_Table \
655 STDMETHODIMP CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value) \ 623 Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value)) \
656 { value->vt = VT_EMPTY; return S_OK; } 624 { value->vt = VT_EMPTY; return S_OK; }
657 625
658 626
627#define Z7_class_CHandler_final \
628 Z7_class_final(CHandler)
629
630
631#define Z7_CLASS_IMP_CHandler_IInArchive_0 \
632 Z7_CLASS_IMP_COM_1(CHandler, IInArchive)
633#define Z7_CLASS_IMP_CHandler_IInArchive_1(i1) \
634 Z7_CLASS_IMP_COM_2(CHandler, IInArchive, i1)
635#define Z7_CLASS_IMP_CHandler_IInArchive_2(i1, i2) \
636 Z7_CLASS_IMP_COM_3(CHandler, IInArchive, i1, i2)
637#define Z7_CLASS_IMP_CHandler_IInArchive_3(i1, i2, i3) \
638 Z7_CLASS_IMP_COM_4(CHandler, IInArchive, i1, i2, i3)
639#define Z7_CLASS_IMP_CHandler_IInArchive_4(i1, i2, i3, i4) \
640 Z7_CLASS_IMP_COM_5(CHandler, IInArchive, i1, i2, i3, i4)
641#define Z7_CLASS_IMP_CHandler_IInArchive_5(i1, i2, i3, i4, i5) \
642 Z7_CLASS_IMP_COM_6(CHandler, IInArchive, i1, i2, i3, i4, i5)
643
644
659 645
660#define k_IsArc_Res_NO 0 646#define k_IsArc_Res_NO 0
661#define k_IsArc_Res_YES 1 647#define k_IsArc_Res_YES 1
@@ -714,4 +700,5 @@ extern UInt32 g_ClientVersion;
714 NFileTimeType::kWindows)) 700 NFileTimeType::kWindows))
715*/ 701*/
716 702
703Z7_PURE_INTERFACES_END
717#endif 704#endif
diff --git a/CPP/7zip/Archive/IhexHandler.cpp b/CPP/7zip/Archive/IhexHandler.cpp
index 05453ee..badb559 100644
--- a/CPP/7zip/Archive/IhexHandler.cpp
+++ b/CPP/7zip/Archive/IhexHandler.cpp
@@ -27,10 +27,9 @@ struct CBlock
27 UInt32 Offset; 27 UInt32 Offset;
28}; 28};
29 29
30class CHandler: 30
31 public IInArchive, 31Z7_CLASS_IMP_CHandler_IInArchive_0
32 public CMyUnknownImp 32
33{
34 bool _isArc; 33 bool _isArc;
35 bool _needMoreInput; 34 bool _needMoreInput;
36 bool _dataError; 35 bool _dataError;
@@ -38,9 +37,6 @@ class CHandler:
38 UInt64 _phySize; 37 UInt64 _phySize;
39 38
40 CObjectVector<CBlock> _blocks; 39 CObjectVector<CBlock> _blocks;
41public:
42 MY_UNKNOWN_IMP1(IInArchive)
43 INTERFACE_IInArchive(;)
44}; 40};
45 41
46static const Byte kProps[] = 42static const Byte kProps[] =
@@ -53,13 +49,13 @@ static const Byte kProps[] =
53IMP_IInArchive_Props 49IMP_IInArchive_Props
54IMP_IInArchive_ArcProps_NO_Table 50IMP_IInArchive_ArcProps_NO_Table
55 51
56STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 52Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
57{ 53{
58 *numItems = _blocks.Size(); 54 *numItems = _blocks.Size();
59 return S_OK; 55 return S_OK;
60} 56}
61 57
62STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 58Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
63{ 59{
64 NWindows::NCOM::CPropVariant prop; 60 NWindows::NCOM::CPropVariant prop;
65 switch (propID) 61 switch (propID)
@@ -68,7 +64,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
68 case kpidErrorFlags: 64 case kpidErrorFlags:
69 { 65 {
70 UInt32 v = 0; 66 UInt32 v = 0;
71 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 67 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
72 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; 68 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd;
73 if (_dataError) v |= kpv_ErrorFlags_DataError; 69 if (_dataError) v |= kpv_ErrorFlags_DataError;
74 prop = v; 70 prop = v;
@@ -78,7 +74,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
78 return S_OK; 74 return S_OK;
79} 75}
80 76
81STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 77Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
82{ 78{
83 COM_TRY_BEGIN 79 COM_TRY_BEGIN
84 NWindows::NCOM::CPropVariant prop; 80 NWindows::NCOM::CPropVariant prop;
@@ -105,16 +101,16 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
105 101
106static inline int HexToByte(unsigned c) 102static inline int HexToByte(unsigned c)
107{ 103{
108 if (c >= '0' && c <= '9') return c - '0'; 104 if (c >= '0' && c <= '9') return (int)(c - '0');
109 if (c >= 'A' && c <= 'F') return c - 'A' + 10; 105 if (c >= 'A' && c <= 'F') return (int)(c - 'A' + 10);
110 if (c >= 'a' && c <= 'f') return c - 'a' + 10; 106 if (c >= 'a' && c <= 'f') return (int)(c - 'a' + 10);
111 return -1; 107 return -1;
112} 108}
113 109
114static int Parse(const Byte *p) 110static int Parse(const Byte *p)
115{ 111{
116 int c1 = HexToByte(p[0]); if (c1 < 0) return -1; 112 const int c1 = HexToByte(p[0]); if (c1 < 0) return -1;
117 int c2 = HexToByte(p[1]); if (c2 < 0) return -1; 113 const int c2 = HexToByte(p[1]); if (c2 < 0) return -1;
118 return (c1 << 4) | c2; 114 return (c1 << 4) | c2;
119} 115}
120 116
@@ -207,7 +203,7 @@ API_FUNC_static_IsArc IsArc_Ihex(const Byte *p, size_t size)
207 { 203 {
208 if (size == 0) 204 if (size == 0)
209 return k_IsArc_Res_NEED_MORE; 205 return k_IsArc_Res_NEED_MORE;
210 char b = *p++; 206 const Byte b = *p++;
211 size--; 207 size--;
212 if (IS_LINE_DELIMITER(b)) 208 if (IS_LINE_DELIMITER(b))
213 continue; 209 continue;
@@ -221,7 +217,7 @@ API_FUNC_static_IsArc IsArc_Ihex(const Byte *p, size_t size)
221} 217}
222} 218}
223 219
224STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) 220Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *))
225{ 221{
226 COM_TRY_BEGIN 222 COM_TRY_BEGIN
227 { 223 {
@@ -232,7 +228,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
232 Byte temp[kStartSize]; 228 Byte temp[kStartSize];
233 { 229 {
234 size_t size = kStartSize; 230 size_t size = kStartSize;
235 RINOK(ReadStream(stream, temp, &size)); 231 RINOK(ReadStream(stream, temp, &size))
236 UInt32 isArcRes = IsArc_Ihex(temp, size); 232 UInt32 isArcRes = IsArc_Ihex(temp, size);
237 if (isArcRes == k_IsArc_Res_NO) 233 if (isArcRes == k_IsArc_Res_NO)
238 return S_FALSE; 234 return S_FALSE;
@@ -241,7 +237,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
241 } 237 }
242 _isArc = true; 238 _isArc = true;
243 239
244 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 240 RINOK(InStream_SeekToBegin(stream))
245 CInBuffer s; 241 CInBuffer s;
246 if (!s.Create(1 << 15)) 242 if (!s.Create(1 << 15))
247 return E_OUTOFMEMORY; 243 return E_OUTOFMEMORY;
@@ -271,7 +267,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
271 _needMoreInput = true; 267 _needMoreInput = true;
272 return S_FALSE; 268 return S_FALSE;
273 } 269 }
274 int num = Parse(temp); 270 const int num = Parse(temp);
275 if (num < 0) 271 if (num < 0)
276 { 272 {
277 _dataError = true; 273 _dataError = true;
@@ -287,17 +283,17 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
287 return S_FALSE; 283 return S_FALSE;
288 } 284 }
289 285
290 unsigned sum = num; 286 unsigned sum = (unsigned)num;
291 for (size_t i = 0; i < numPairs; i++) 287 for (size_t i = 0; i < numPairs; i++)
292 { 288 {
293 int a = Parse(temp + i * 2); 289 const int a = Parse(temp + i * 2);
294 if (a < 0) 290 if (a < 0)
295 { 291 {
296 _dataError = true; 292 _dataError = true;
297 return S_FALSE; 293 return S_FALSE;
298 } 294 }
299 temp[i] = (Byte)a; 295 temp[i] = (Byte)a;
300 sum += a; 296 sum += (unsigned)a;
301 } 297 }
302 if ((sum & 0xFF) != 0) 298 if ((sum & 0xFF) != 0)
303 { 299 {
@@ -413,7 +409,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
413 COM_TRY_END 409 COM_TRY_END
414} 410}
415 411
416STDMETHODIMP CHandler::Close() 412Z7_COM7F_IMF(CHandler::Close())
417{ 413{
418 _phySize = 0; 414 _phySize = 0;
419 415
@@ -426,11 +422,11 @@ STDMETHODIMP CHandler::Close()
426} 422}
427 423
428 424
429STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 425Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
430 Int32 testMode, IArchiveExtractCallback *extractCallback) 426 Int32 testMode, IArchiveExtractCallback *extractCallback))
431{ 427{
432 COM_TRY_BEGIN 428 COM_TRY_BEGIN
433 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 429 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
434 if (allFilesMode) 430 if (allFilesMode)
435 numItems = _blocks.Size(); 431 numItems = _blocks.Size();
436 if (numItems == 0) 432 if (numItems == 0)
@@ -453,18 +449,18 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
453 { 449 {
454 currentItemSize = 0; 450 currentItemSize = 0;
455 lps->InSize = lps->OutSize = currentTotalSize; 451 lps->InSize = lps->OutSize = currentTotalSize;
456 RINOK(lps->SetCur()); 452 RINOK(lps->SetCur())
457 453
458 UInt32 index = allFilesMode ? i : indices[i]; 454 const UInt32 index = allFilesMode ? i : indices[i];
459 const CByteDynamicBuffer &data = _blocks[index].Data; 455 const CByteDynamicBuffer &data = _blocks[index].Data;
460 currentItemSize = data.GetPos(); 456 currentItemSize = data.GetPos();
461 457
462 CMyComPtr<ISequentialOutStream> realOutStream; 458 CMyComPtr<ISequentialOutStream> realOutStream;
463 Int32 askMode = testMode ? 459 const Int32 askMode = testMode ?
464 NExtract::NAskMode::kTest : 460 NExtract::NAskMode::kTest :
465 NExtract::NAskMode::kExtract; 461 NExtract::NAskMode::kExtract;
466 462
467 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 463 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
468 464
469 if (!testMode && !realOutStream) 465 if (!testMode && !realOutStream)
470 continue; 466 continue;
@@ -473,11 +469,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
473 469
474 if (realOutStream) 470 if (realOutStream)
475 { 471 {
476 RINOK(WriteStream(realOutStream, (const Byte *)data, data.GetPos())); 472 RINOK(WriteStream(realOutStream, (const Byte *)data, data.GetPos()))
477 } 473 }
478 474
479 realOutStream.Release(); 475 realOutStream.Release();
480 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 476 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
481 } 477 }
482 478
483 lps->InSize = lps->OutSize = currentTotalSize; 479 lps->InSize = lps->OutSize = currentTotalSize;
@@ -489,7 +485,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
489// k_Signature: { ':', '1' } 485// k_Signature: { ':', '1' }
490 486
491REGISTER_ARC_I_NO_SIG( 487REGISTER_ARC_I_NO_SIG(
492 "IHex", "ihex", 0, 0xCD, 488 "IHex", "ihex", NULL, 0xCD,
493 0, 489 0,
494 NArcInfoFlags::kStartOpen, 490 NArcInfoFlags::kStartOpen,
495 IsArc_Ihex) 491 IsArc_Ihex)
diff --git a/CPP/7zip/Archive/Iso/IsoHandler.cpp b/CPP/7zip/Archive/Iso/IsoHandler.cpp
index 8588a7c..0c63c71 100644
--- a/CPP/7zip/Archive/Iso/IsoHandler.cpp
+++ b/CPP/7zip/Archive/Iso/IsoHandler.cpp
@@ -8,6 +8,7 @@
8 8
9#include "../../Common/LimitedStreams.h" 9#include "../../Common/LimitedStreams.h"
10#include "../../Common/ProgressUtils.h" 10#include "../../Common/ProgressUtils.h"
11#include "../../Common/StreamUtils.h"
11 12
12#include "../../Compress/CopyCoder.h" 13#include "../../Compress/CopyCoder.h"
13 14
@@ -48,28 +49,28 @@ static const Byte kArcProps[] =
48IMP_IInArchive_Props 49IMP_IInArchive_Props
49IMP_IInArchive_ArcProps 50IMP_IInArchive_ArcProps
50 51
51STDMETHODIMP CHandler::Open(IInStream *stream, 52Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
52 const UInt64 * /* maxCheckStartPosition */, 53 const UInt64 * /* maxCheckStartPosition */,
53 IArchiveOpenCallback * /* openArchiveCallback */) 54 IArchiveOpenCallback * /* openArchiveCallback */))
54{ 55{
55 COM_TRY_BEGIN 56 COM_TRY_BEGIN
56 Close(); 57 Close();
57 { 58 {
58 RINOK(_archive.Open(stream)); 59 RINOK(_archive.Open(stream))
59 _stream = stream; 60 _stream = stream;
60 } 61 }
61 return S_OK; 62 return S_OK;
62 COM_TRY_END 63 COM_TRY_END
63} 64}
64 65
65STDMETHODIMP CHandler::Close() 66Z7_COM7F_IMF(CHandler::Close())
66{ 67{
67 _archive.Clear(); 68 _archive.Clear();
68 _stream.Release(); 69 _stream.Release();
69 return S_OK; 70 return S_OK;
70} 71}
71 72
72STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 73Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
73{ 74{
74 *numItems = _archive.Refs.Size() + _archive.BootEntries.Size(); 75 *numItems = _archive.Refs.Size() + _archive.BootEntries.Size();
75 return S_OK; 76 return S_OK;
@@ -100,7 +101,7 @@ static void AddErrorMessage(AString &s, const char *message)
100 s += message; 101 s += message;
101} 102}
102 103
103STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 104Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
104{ 105{
105 COM_TRY_BEGIN 106 COM_TRY_BEGIN
106 NCOM::CPropVariant prop; 107 NCOM::CPropVariant prop;
@@ -161,7 +162,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
161 COM_TRY_END 162 COM_TRY_END
162} 163}
163 164
164STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 165Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
165{ 166{
166 COM_TRY_BEGIN 167 COM_TRY_BEGIN
167 NCOM::CPropVariant prop; 168 NCOM::CPropVariant prop;
@@ -177,7 +178,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
177 if (_archive.BootEntries.Size() != 1) 178 if (_archive.BootEntries.Size() != 1)
178 { 179 {
179 s.Add_UInt32(index + 1); 180 s.Add_UInt32(index + 1);
180 s += '-'; 181 s.Add_Minus();
181 } 182 }
182 s += be.GetName(); 183 s += be.GetName();
183 prop = s; 184 prop = s;
@@ -303,11 +304,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
303 COM_TRY_END 304 COM_TRY_END
304} 305}
305 306
306STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 307Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
307 Int32 testMode, IArchiveExtractCallback *extractCallback) 308 Int32 testMode, IArchiveExtractCallback *extractCallback))
308{ 309{
309 COM_TRY_BEGIN 310 COM_TRY_BEGIN
310 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 311 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
311 if (allFilesMode) 312 if (allFilesMode)
312 numItems = _archive.Refs.Size(); 313 numItems = _archive.Refs.Size();
313 if (numItems == 0) 314 if (numItems == 0)
@@ -346,15 +347,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
346 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) 347 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
347 { 348 {
348 lps->InSize = lps->OutSize = currentTotalSize; 349 lps->InSize = lps->OutSize = currentTotalSize;
349 RINOK(lps->SetCur()); 350 RINOK(lps->SetCur())
350 currentItemSize = 0; 351 currentItemSize = 0;
351 CMyComPtr<ISequentialOutStream> realOutStream; 352 CMyComPtr<ISequentialOutStream> realOutStream;
352 Int32 askMode = testMode ? 353 const Int32 askMode = testMode ?
353 NExtract::NAskMode::kTest : 354 NExtract::NAskMode::kTest :
354 NExtract::NAskMode::kExtract; 355 NExtract::NAskMode::kExtract;
355 UInt32 index = allFilesMode ? i : indices[i]; 356 const UInt32 index = allFilesMode ? i : indices[i];
356 357
357 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 358 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
358 359
359 UInt64 blockIndex; 360 UInt64 blockIndex;
360 if (index < (UInt32)_archive.Refs.Size()) 361 if (index < (UInt32)_archive.Refs.Size())
@@ -363,8 +364,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
363 const CDir &item = ref.Dir->_subItems[ref.Index]; 364 const CDir &item = ref.Dir->_subItems[ref.Index];
364 if (item.IsDir()) 365 if (item.IsDir())
365 { 366 {
366 RINOK(extractCallback->PrepareOperation(askMode)); 367 RINOK(extractCallback->PrepareOperation(askMode))
367 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 368 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
368 continue; 369 continue;
369 } 370 }
370 currentItemSize = ref.TotalSize; 371 currentItemSize = ref.TotalSize;
@@ -382,7 +383,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
382 if (!testMode && !realOutStream) 383 if (!testMode && !realOutStream)
383 continue; 384 continue;
384 385
385 RINOK(extractCallback->PrepareOperation(askMode)); 386 RINOK(extractCallback->PrepareOperation(askMode))
386 387
387 bool isOK = true; 388 bool isOK = true;
388 if (index < (UInt32)_archive.Refs.Size()) 389 if (index < (UInt32)_archive.Refs.Size())
@@ -395,9 +396,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
395 if (item2.Size == 0) 396 if (item2.Size == 0)
396 continue; 397 continue;
397 lps->InSize = lps->OutSize = currentTotalSize + offset; 398 lps->InSize = lps->OutSize = currentTotalSize + offset;
398 RINOK(_stream->Seek((UInt64)item2.ExtentLocation * kBlockSize, STREAM_SEEK_SET, NULL)); 399 RINOK(InStream_SeekSet(_stream, (UInt64)item2.ExtentLocation * kBlockSize))
399 streamSpec->Init(item2.Size); 400 streamSpec->Init(item2.Size);
400 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 401 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
401 if (copyCoderSpec->TotalSize != item2.Size) 402 if (copyCoderSpec->TotalSize != item2.Size)
402 { 403 {
403 isOK = false; 404 isOK = false;
@@ -408,25 +409,25 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
408 } 409 }
409 else 410 else
410 { 411 {
411 RINOK(_stream->Seek((UInt64)blockIndex * kBlockSize, STREAM_SEEK_SET, NULL)); 412 RINOK(InStream_SeekSet(_stream, (UInt64)blockIndex * kBlockSize))
412 streamSpec->Init(currentItemSize); 413 streamSpec->Init(currentItemSize);
413 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 414 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
414 if (copyCoderSpec->TotalSize != currentItemSize) 415 if (copyCoderSpec->TotalSize != currentItemSize)
415 isOK = false; 416 isOK = false;
416 } 417 }
417 realOutStream.Release(); 418 realOutStream.Release();
418 RINOK(extractCallback->SetOperationResult(isOK ? 419 RINOK(extractCallback->SetOperationResult(isOK ?
419 NExtract::NOperationResult::kOK: 420 NExtract::NOperationResult::kOK:
420 NExtract::NOperationResult::kDataError)); 421 NExtract::NOperationResult::kDataError))
421 } 422 }
422 return S_OK; 423 return S_OK;
423 COM_TRY_END 424 COM_TRY_END
424} 425}
425 426
426STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 427Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
427{ 428{
428 COM_TRY_BEGIN 429 COM_TRY_BEGIN
429 *stream = 0; 430 *stream = NULL;
430 UInt64 blockIndex; 431 UInt64 blockIndex;
431 UInt64 currentItemSize; 432 UInt64 currentItemSize;
432 433
diff --git a/CPP/7zip/Archive/Iso/IsoHandler.h b/CPP/7zip/Archive/Iso/IsoHandler.h
index 1923784..507814a 100644
--- a/CPP/7zip/Archive/Iso/IsoHandler.h
+++ b/CPP/7zip/Archive/Iso/IsoHandler.h
@@ -1,29 +1,22 @@
1// IsoHandler.h 1// IsoHandler.h
2 2
3#ifndef __ISO_HANDLER_H 3#ifndef ZIP7_INC_ISO_HANDLER_H
4#define __ISO_HANDLER_H 4#define ZIP7_INC_ISO_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../IArchive.h" 8#include "../IArchive.h"
9 9
10#include "IsoIn.h" 10#include "IsoIn.h"
11#include "IsoItem.h"
12 11
13namespace NArchive { 12namespace NArchive {
14namespace NIso { 13namespace NIso {
15 14
16class CHandler: 15Z7_CLASS_IMP_CHandler_IInArchive_1(
17 public IInArchive, 16 IInArchiveGetStream
18 public IInArchiveGetStream, 17)
19 public CMyUnknownImp
20{
21 CMyComPtr<IInStream> _stream; 18 CMyComPtr<IInStream> _stream;
22 CInArchive _archive; 19 CInArchive _archive;
23public:
24 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
25 INTERFACE_IInArchive(;)
26 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
27}; 20};
28 21
29}} 22}}
diff --git a/CPP/7zip/Archive/Iso/IsoHeader.h b/CPP/7zip/Archive/Iso/IsoHeader.h
index e6a4d32..0b14c9f 100644
--- a/CPP/7zip/Archive/Iso/IsoHeader.h
+++ b/CPP/7zip/Archive/Iso/IsoHeader.h
@@ -1,7 +1,7 @@
1// Archive/IsoHeader.h 1// Archive/IsoHeader.h
2 2
3#ifndef __ARCHIVE_ISO_HEADER_H 3#ifndef ZIP7_INC_ARCHIVE_ISO_HEADER_H
4#define __ARCHIVE_ISO_HEADER_H 4#define ZIP7_INC_ARCHIVE_ISO_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
diff --git a/CPP/7zip/Archive/Iso/IsoIn.cpp b/CPP/7zip/Archive/Iso/IsoIn.cpp
index 6780235..1d3a42f 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)
48AString CBootInitialEntry::GetName() const 48AString CBootInitialEntry::GetName() const
49{ 49{
50 AString s (Bootable ? "Boot" : "NotBoot"); 50 AString s (Bootable ? "Boot" : "NotBoot");
51 s += '-'; 51 s.Add_Minus();
52 52
53 if (BootMediaType < ARRAY_SIZE(kMediaTypes)) 53 if (BootMediaType < Z7_ARRAY_SIZE(kMediaTypes))
54 s += kMediaTypes[BootMediaType]; 54 s += kMediaTypes[BootMediaType];
55 else 55 else
56 s.Add_UInt32(BootMediaType); 56 s.Add_UInt32(BootMediaType);
@@ -65,10 +65,10 @@ AString CBootInitialEntry::GetName() const
65 break; 65 break;
66 if (i == sizeof(VendorSpec)) 66 if (i == sizeof(VendorSpec))
67 { 67 {
68 s += '-'; 68 s.Add_Minus();
69 for (i = 1; i < sizeof(VendorSpec); i++) 69 for (i = 1; i < sizeof(VendorSpec); i++)
70 { 70 {
71 char c = VendorSpec[i]; 71 char c = (char)VendorSpec[i];
72 if (c == 0) 72 if (c == 0)
73 break; 73 break;
74 if (c == '\\' || c == '/') 74 if (c == '\\' || c == '/')
@@ -134,7 +134,7 @@ UInt16 CInArchive::ReadUInt16()
134 { 134 {
135 if (b[i] != b[3 - i]) 135 if (b[i] != b[3 - i])
136 IncorrectBigEndian = true; 136 IncorrectBigEndian = true;
137 val |= ((UInt16)(b[i]) << (8 * i)); 137 val |= ((UInt32)(b[i]) << (8 * i));
138 } 138 }
139 return (UInt16)val; 139 return (UInt16)val;
140} 140}
@@ -316,7 +316,9 @@ static inline bool CheckSignature(const Byte *sig, const Byte *data)
316 316
317void CInArchive::SeekToBlock(UInt32 blockIndex) 317void CInArchive::SeekToBlock(UInt32 blockIndex)
318{ 318{
319 HRESULT res = _stream->Seek((UInt64)blockIndex * VolDescs[MainVolDescIndex].LogicalBlockSize, STREAM_SEEK_SET, &_position); 319 const HRESULT res = _stream->Seek(
320 (Int64)((UInt64)blockIndex * VolDescs[MainVolDescIndex].LogicalBlockSize),
321 STREAM_SEEK_SET, &_position);
320 if (res != S_OK) 322 if (res != S_OK)
321 throw CSystemException(res); 323 throw CSystemException(res);
322 m_BufferPos = 0; 324 m_BufferPos = 0;
@@ -506,10 +508,10 @@ void CInArchive::ReadBootInfo()
506HRESULT CInArchive::Open2() 508HRESULT CInArchive::Open2()
507{ 509{
508 _position = 0; 510 _position = 0;
509 RINOK(_stream->Seek(0, STREAM_SEEK_END, &_fileSize)); 511 RINOK(InStream_GetSize_SeekToEnd(_stream, _fileSize))
510 if (_fileSize < kStartPos) 512 if (_fileSize < kStartPos)
511 return S_FALSE; 513 return S_FALSE;
512 RINOK(_stream->Seek(kStartPos, STREAM_SEEK_SET, &_position)); 514 RINOK(_stream->Seek(kStartPos, STREAM_SEEK_SET, &_position))
513 515
514 PhySize = _position; 516 PhySize = _position;
515 m_BufferPos = 0; 517 m_BufferPos = 0;
@@ -584,7 +586,7 @@ HRESULT CInArchive::Open2()
584 586
585 if (VolDescs.IsEmpty()) 587 if (VolDescs.IsEmpty())
586 return S_FALSE; 588 return S_FALSE;
587 for (MainVolDescIndex = VolDescs.Size() - 1; MainVolDescIndex > 0; MainVolDescIndex--) 589 for (MainVolDescIndex = (int)VolDescs.Size() - 1; MainVolDescIndex > 0; MainVolDescIndex--)
588 if (VolDescs[MainVolDescIndex].IsJoliet()) 590 if (VolDescs[MainVolDescIndex].IsJoliet())
589 break; 591 break;
590 /* FIXME: some volume can contain Rock Ridge, that is better than 592 /* FIXME: some volume can contain Rock Ridge, that is better than
@@ -627,10 +629,10 @@ HRESULT CInArchive::Open2()
627 const UInt64 kRemMax = 1 << 21; 629 const UInt64 kRemMax = 1 << 21;
628 if (rem <= kRemMax) 630 if (rem <= kRemMax)
629 { 631 {
630 RINOK(_stream->Seek(PhySize, STREAM_SEEK_SET, NULL)); 632 RINOK(InStream_SeekSet(_stream, PhySize))
631 bool areThereNonZeros = false; 633 bool areThereNonZeros = false;
632 UInt64 numZeros = 0; 634 UInt64 numZeros = 0;
633 RINOK(ReadZeroTail(_stream, areThereNonZeros, numZeros, kRemMax)); 635 RINOK(ReadZeroTail(_stream, areThereNonZeros, numZeros, kRemMax))
634 if (!areThereNonZeros) 636 if (!areThereNonZeros)
635 PhySize += numZeros; 637 PhySize += numZeros;
636 } 638 }
@@ -670,4 +672,22 @@ void CInArchive::Clear()
670 IsSusp = false; 672 IsSusp = false;
671} 673}
672 674
675
676UInt64 CInArchive::GetBootItemSize(unsigned index) const
677{
678 const CBootInitialEntry &be = BootEntries[index];
679 UInt64 size = be.GetSize();
680 if (be.BootMediaType == NBootMediaType::k1d2Floppy) size = 1200 << 10;
681 else if (be.BootMediaType == NBootMediaType::k1d44Floppy) size = 1440 << 10;
682 else if (be.BootMediaType == NBootMediaType::k2d88Floppy) size = 2880 << 10;
683 const UInt64 startPos = (UInt64)be.LoadRBA * kBlockSize;
684 if (startPos < _fileSize)
685 {
686 const UInt64 rem = _fileSize - startPos;
687 if (rem < size)
688 size = rem;
689 }
690 return size;
691}
692
673}} 693}}
diff --git a/CPP/7zip/Archive/Iso/IsoIn.h b/CPP/7zip/Archive/Iso/IsoIn.h
index a705b06..f3e4751 100644
--- a/CPP/7zip/Archive/Iso/IsoIn.h
+++ b/CPP/7zip/Archive/Iso/IsoIn.h
@@ -1,7 +1,7 @@
1// Archive/IsoIn.h 1// Archive/IsoIn.h
2 2
3#ifndef __ARCHIVE_ISO_IN_H 3#ifndef ZIP7_INC_ARCHIVE_ISO_IN_H
4#define __ARCHIVE_ISO_IN_H 4#define ZIP7_INC_ARCHIVE_ISO_IN_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -20,7 +20,7 @@ struct CDir: public CDirRecord
20 20
21 void Clear() 21 void Clear()
22 { 22 {
23 Parent = 0; 23 Parent = NULL;
24 _subItems.Clear(); 24 _subItems.Clear();
25 } 25 }
26 26
@@ -133,7 +133,7 @@ struct CDateTime
133 const bool res = NWindows::NTime::GetSecondsSince1601(Year, Month, Day, Hour, Minute, Second, v); 133 const bool res = NWindows::NTime::GetSecondsSince1601(Year, Month, Day, Hour, Minute, Second, v);
134 if (res) 134 if (res)
135 { 135 {
136 v -= (Int64)((Int32)GmtOffset * 15 * 60); 136 v = (UInt64)((Int64)v - (Int64)((Int32)GmtOffset * 15 * 60));
137 v *= 10000000; 137 v *= 10000000;
138 if (Hundredths < 100) 138 if (Hundredths < 100)
139 v += (UInt32)Hundredths * 100000; 139 v += (UInt32)Hundredths * 100000;
@@ -244,10 +244,6 @@ class CInArchive
244 244
245 UInt32 m_BufferPos; 245 UInt32 m_BufferPos;
246 246
247 CDir _rootDir;
248 bool _bootIsDefined;
249 CBootRecordDescriptor _bootDesc;
250
251 void Skip(size_t size); 247 void Skip(size_t size);
252 void SkipZeros(size_t size); 248 void SkipZeros(size_t size);
253 Byte ReadByte(); 249 Byte ReadByte();
@@ -285,17 +281,21 @@ public:
285 // UInt32 BlockSize; 281 // UInt32 BlockSize;
286 CObjectVector<CBootInitialEntry> BootEntries; 282 CObjectVector<CBootInitialEntry> BootEntries;
287 283
284private:
285 bool _bootIsDefined;
286public:
288 bool IsArc; 287 bool IsArc;
289 bool UnexpectedEnd; 288 bool UnexpectedEnd;
290 bool HeadersError; 289 bool HeadersError;
291 bool IncorrectBigEndian; 290 bool IncorrectBigEndian;
292 bool TooDeepDirs; 291 bool TooDeepDirs;
293 bool SelfLinkedDirs; 292 bool SelfLinkedDirs;
294 CRecordVector<UInt32> UniqStartLocations; 293 bool IsSusp;
294 unsigned SuspSkipSize;
295 295
296 Byte m_Buffer[kBlockSize]; 296 CRecordVector<UInt32> UniqStartLocations;
297 297
298 void UpdatePhySize(UInt32 blockIndex, UInt64 size) 298 void UpdatePhySize(const UInt32 blockIndex, const UInt64 size)
299 { 299 {
300 const UInt64 alignedSize = (size + kBlockSize - 1) & ~((UInt64)kBlockSize - 1); 300 const UInt64 alignedSize = (size + kBlockSize - 1) & ~((UInt64)kBlockSize - 1);
301 const UInt64 end = (UInt64)blockIndex * kBlockSize + alignedSize; 301 const UInt64 end = (UInt64)blockIndex * kBlockSize + alignedSize;
@@ -305,27 +305,12 @@ public:
305 305
306 bool IsJoliet() const { return VolDescs[MainVolDescIndex].IsJoliet(); } 306 bool IsJoliet() const { return VolDescs[MainVolDescIndex].IsJoliet(); }
307 307
308 UInt64 GetBootItemSize(int index) const 308 UInt64 GetBootItemSize(unsigned index) const;
309 {
310 const CBootInitialEntry &be = BootEntries[index];
311 UInt64 size = be.GetSize();
312 if (be.BootMediaType == NBootMediaType::k1d2Floppy)
313 size = (1200 << 10);
314 else if (be.BootMediaType == NBootMediaType::k1d44Floppy)
315 size = (1440 << 10);
316 else if (be.BootMediaType == NBootMediaType::k2d88Floppy)
317 size = (2880 << 10);
318 UInt64 startPos = (UInt64)be.LoadRBA * kBlockSize;
319 if (startPos < _fileSize)
320 {
321 if (_fileSize - startPos < size)
322 size = _fileSize - startPos;
323 }
324 return size;
325 }
326 309
327 bool IsSusp; 310private:
328 unsigned SuspSkipSize; 311 CDir _rootDir;
312 Byte m_Buffer[kBlockSize];
313 CBootRecordDescriptor _bootDesc;
329}; 314};
330 315
331}} 316}}
diff --git a/CPP/7zip/Archive/Iso/IsoItem.h b/CPP/7zip/Archive/Iso/IsoItem.h
index 8c2a725..9556805 100644
--- a/CPP/7zip/Archive/Iso/IsoItem.h
+++ b/CPP/7zip/Archive/Iso/IsoItem.h
@@ -1,7 +1,7 @@
1// Archive/IsoItem.h 1// Archive/IsoItem.h
2 2
3#ifndef __ARCHIVE_ISO_ITEM_H 3#ifndef ZIP7_INC_ARCHIVE_ISO_ITEM_H
4#define __ARCHIVE_ISO_ITEM_H 4#define ZIP7_INC_ARCHIVE_ISO_ITEM_H
5 5
6#include "../../../../C/CpuArch.h" 6#include "../../../../C/CpuArch.h"
7 7
@@ -31,7 +31,7 @@ struct CRecordingDateTime
31 const bool res = NWindows::NTime::GetSecondsSince1601(Year + 1900, Month, Day, Hour, Minute, Second, v); 31 const bool res = NWindows::NTime::GetSecondsSince1601(Year + 1900, Month, Day, Hour, Minute, Second, v);
32 if (res) 32 if (res)
33 { 33 {
34 v -= (Int64)((Int32)GmtOffset * 15 * 60); 34 v = (UInt64)((Int64)v - (Int64)((Int32)GmtOffset * 15 * 60));
35 v *= 10000000; 35 v *= 10000000;
36 prop.SetAsTimeFrom_Ft64_Prec(v, k_PropVar_TimePrec_Base); 36 prop.SetAsTimeFrom_Ft64_Prec(v, k_PropVar_TimePrec_Base);
37 } 37 }
@@ -101,29 +101,29 @@ struct CDirRecord
101 { 101 {
102 lenRes = 0; 102 lenRes = 0;
103 if (SystemUse.Size() < skipSize) 103 if (SystemUse.Size() < skipSize)
104 return 0; 104 return NULL;
105 const Byte *p = (const Byte *)SystemUse + skipSize; 105 const Byte *p = (const Byte *)SystemUse + skipSize;
106 unsigned rem = (unsigned)(SystemUse.Size() - skipSize); 106 unsigned rem = (unsigned)(SystemUse.Size() - skipSize);
107 while (rem >= 5) 107 while (rem >= 5)
108 { 108 {
109 unsigned len = p[2]; 109 unsigned len = p[2];
110 if (len < 3 || len > rem) 110 if (len < 3 || len > rem)
111 return 0; 111 return NULL;
112 if (p[0] == id0 && p[1] == id1 && p[3] == 1) 112 if (p[0] == id0 && p[1] == id1 && p[3] == 1)
113 { 113 {
114 if (len < 4) 114 if (len < 4)
115 return 0; // Check it 115 return NULL; // Check it
116 lenRes = len - 4; 116 lenRes = len - 4;
117 return p + 4; 117 return p + 4;
118 } 118 }
119 p += len; 119 p += len;
120 rem -= len; 120 rem -= len;
121 } 121 }
122 return 0; 122 return NULL;
123 } 123 }
124 124
125 125
126 const Byte* GetNameCur(bool checkSusp, int skipSize, unsigned &nameLenRes) const 126 const Byte* GetNameCur(bool checkSusp, unsigned skipSize, unsigned &nameLenRes) const
127 { 127 {
128 const Byte *res = NULL; 128 const Byte *res = NULL;
129 unsigned len = 0; 129 unsigned len = 0;
@@ -148,7 +148,7 @@ struct CDirRecord
148 } 148 }
149 149
150 150
151 bool GetSymLink(int skipSize, AString &link) const 151 bool GetSymLink(unsigned skipSize, AString &link) const
152 { 152 {
153 link.Empty(); 153 link.Empty();
154 const Byte *p = NULL; 154 const Byte *p = NULL;
@@ -185,13 +185,13 @@ struct CDirRecord
185 185
186 for (unsigned i = 0; i < cl; i++) 186 for (unsigned i = 0; i < cl; i++)
187 { 187 {
188 char c = p[i]; 188 const Byte c = p[i];
189 if (c == 0) 189 if (c == 0)
190 { 190 {
191 break; 191 break;
192 // return false; 192 // return false;
193 } 193 }
194 link += c; 194 link += (char)c;
195 } 195 }
196 196
197 p += cl; 197 p += cl;
@@ -220,7 +220,7 @@ struct CDirRecord
220 } 220 }
221 221
222 222
223 bool GetPx(int skipSize, unsigned pxType, UInt32 &val) const 223 bool GetPx(unsigned skipSize, unsigned pxType, UInt32 &val) const
224 { 224 {
225 val = 0; 225 val = 0;
226 const Byte *p = NULL; 226 const Byte *p = NULL;
@@ -229,7 +229,7 @@ struct CDirRecord
229 if (!p) 229 if (!p)
230 return false; 230 return false;
231 // px.Clear(); 231 // px.Clear();
232 if (len < ((unsigned)pxType + 1) * 8) 232 if (len < (pxType + 1) * 8)
233 return false; 233 return false;
234 234
235 return GetLe32Be32(p + pxType * 8, val); 235 return GetLe32Be32(p + pxType * 8, val);
@@ -302,7 +302,7 @@ struct CDirRecord
302 bool CheckSusp(unsigned &startPos) const 302 bool CheckSusp(unsigned &startPos) const
303 { 303 {
304 const Byte *p = (const Byte *)SystemUse; 304 const Byte *p = (const Byte *)SystemUse;
305 unsigned len = (int)SystemUse.Size(); 305 const size_t len = SystemUse.Size();
306 const unsigned kMinLen = 7; 306 const unsigned kMinLen = 7;
307 if (len < kMinLen) 307 if (len < kMinLen)
308 return false; 308 return false;
diff --git a/CPP/7zip/Archive/Iso/IsoRegister.cpp b/CPP/7zip/Archive/Iso/IsoRegister.cpp
index 0205238..41b56ba 100644
--- a/CPP/7zip/Archive/Iso/IsoRegister.cpp
+++ b/CPP/7zip/Archive/Iso/IsoRegister.cpp
@@ -12,7 +12,7 @@ namespace NIso {
12static const Byte k_Signature[] = { 'C', 'D', '0', '0', '1' }; 12static const Byte k_Signature[] = { 'C', 'D', '0', '0', '1' };
13 13
14REGISTER_ARC_I( 14REGISTER_ARC_I(
15 "Iso", "iso img", 0, 0xE7, 15 "Iso", "iso img", NULL, 0xE7,
16 k_Signature, 16 k_Signature,
17 NArchive::NIso::kStartPos + 1, 17 NArchive::NIso::kStartPos + 1,
18 0, 18 0,
diff --git a/CPP/7zip/Archive/Iso/StdAfx.h b/CPP/7zip/Archive/Iso/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Iso/StdAfx.h
+++ b/CPP/7zip/Archive/Iso/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/LpHandler.cpp b/CPP/7zip/Archive/LpHandler.cpp
index b2720f4..c1a76b4 100644
--- a/CPP/7zip/Archive/LpHandler.cpp
+++ b/CPP/7zip/Archive/LpHandler.cpp
@@ -59,9 +59,9 @@ static const unsigned kSectorSizeLog = 9;
59#define LP_METADATA_GEOMETRY_SIZE 4096 59#define LP_METADATA_GEOMETRY_SIZE 4096
60#define LP_METADATA_HEADER_MAGIC 0x414C5030 60#define LP_METADATA_HEADER_MAGIC 0x414C5030
61 61
62#define SIGNATURE { 0x67, 0x44, 0x6c, 0x61, 0x34, 0, 0, 0 }
63static const unsigned k_SignatureSize = 8; 62static const unsigned k_SignatureSize = 8;
64static const Byte k_Signature[k_SignatureSize] = SIGNATURE; 63static const Byte k_Signature[k_SignatureSize] =
64 { 0x67, 0x44, 0x6c, 0x61, 0x34, 0, 0, 0 };
65 65
66// The length (36) is the same as the maximum length of a GPT partition name. 66// The length (36) is the same as the maximum length of a GPT partition name.
67static const unsigned kNameLen = 36; 67static const unsigned kNameLen = 36;
@@ -103,9 +103,9 @@ struct CGeometry
103 103
104 bool Parse(const Byte *p) 104 bool Parse(const Byte *p)
105 { 105 {
106 G32 (40, metadata_max_size); 106 G32 (40, metadata_max_size)
107 G32 (44, metadata_slot_count); 107 G32 (44, metadata_slot_count)
108 G32 (48, logical_block_size); 108 G32 (48, logical_block_size)
109 if (metadata_slot_count == 0 || metadata_slot_count >= ((UInt32)1 << 20)) 109 if (metadata_slot_count == 0 || metadata_slot_count >= ((UInt32)1 << 20))
110 return false; 110 return false;
111 if (metadata_max_size == 0) 111 if (metadata_max_size == 0)
@@ -135,9 +135,9 @@ struct CDescriptor
135 135
136 void Parse(const Byte *p) 136 void Parse(const Byte *p)
137 { 137 {
138 G32 (0, offset); 138 G32 (0, offset)
139 G32 (4, num_entries); 139 G32 (4, num_entries)
140 G32 (8, entry_size); 140 G32 (8, entry_size)
141 } 141 }
142 142
143 bool CheckLimits(UInt32 limit) const 143 bool CheckLimits(UInt32 limit) const
@@ -208,10 +208,10 @@ struct CPartition
208 void Parse(const Byte *p) 208 void Parse(const Byte *p)
209 { 209 {
210 memcpy(name, p, kNameLen); 210 memcpy(name, p, kNameLen);
211 G32 (36, attributes); 211 G32 (36, attributes)
212 G32 (40, first_extent_index); 212 G32 (40, first_extent_index)
213 G32 (44, num_extents); 213 G32 (44, num_extents)
214 G32 (48, group_index); 214 G32 (48, group_index)
215 } 215 }
216 216
217 // calced properties: 217 // calced properties:
@@ -264,10 +264,10 @@ struct CExtent
264 264
265 void Parse(const Byte *p) 265 void Parse(const Byte *p)
266 { 266 {
267 G64 (0, num_sectors); 267 G64 (0, num_sectors)
268 G32 (8, target_type); 268 G32 (8, target_type)
269 G64 (12, target_data); 269 G64 (12, target_data)
270 G32 (20, target_source); 270 G32 (20, target_source)
271 } 271 }
272}; 272};
273 273
@@ -289,8 +289,8 @@ struct CGroup
289 void Parse(const Byte *p) 289 void Parse(const Byte *p)
290 { 290 {
291 memcpy(name, p, kNameLen); 291 memcpy(name, p, kNameLen);
292 G32 (36, flags); 292 G32 (36, flags)
293 G64 (40, maximum_size); 293 G64 (40, maximum_size)
294 } 294 }
295}; 295};
296 296
@@ -358,11 +358,11 @@ struct CDevice
358 void Parse(const Byte *p) 358 void Parse(const Byte *p)
359 { 359 {
360 memcpy(partition_name, p + 24, kNameLen); 360 memcpy(partition_name, p + 24, kNameLen);
361 G64 (0, first_logical_sector); 361 G64 (0, first_logical_sector)
362 G32 (8, alignment); 362 G32 (8, alignment)
363 G32 (12, alignment_offset); 363 G32 (12, alignment_offset)
364 G64 (16, size); 364 G64 (16, size)
365 G32 (60, flags); 365 G32 (60, flags)
366 } 366 }
367}; 367};
368 368
@@ -439,9 +439,9 @@ struct LpMetadataHeader
439 439
440 void Parse128(const Byte *p) 440 void Parse128(const Byte *p)
441 { 441 {
442 G32 (0, magic); 442 G32 (0, magic)
443 G16 (4, major_version); 443 G16 (4, major_version)
444 G16 (6, minor_version); 444 G16 (6, minor_version)
445 G32 (8, header_size) 445 G32 (8, header_size)
446 // Byte header_checksum[32]; 446 // Byte header_checksum[32];
447 G32 (44, tables_size) 447 G32 (44, tables_size)
@@ -479,11 +479,9 @@ static bool CheckSha256_csOffset(Byte *data, size_t size, unsigned hashOffset)
479 479
480 480
481 481
482class CHandler: 482Z7_CLASS_IMP_CHandler_IInArchive_1(
483 public IInArchive, 483 IInArchiveGetStream
484 public IInArchiveGetStream, 484)
485 public CMyUnknownImp
486{
487 CRecordVector<CPartition> _items; 485 CRecordVector<CPartition> _items;
488 CRecordVector<CExtent> Extents; 486 CRecordVector<CExtent> Extents;
489 487
@@ -505,11 +503,6 @@ class CHandler:
505 AString DeviceArcName; 503 AString DeviceArcName;
506 504
507 HRESULT Open2(IInStream *stream); 505 HRESULT Open2(IInStream *stream);
508
509public:
510 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
511 INTERFACE_IInArchive(;)
512 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
513}; 506};
514 507
515 508
@@ -533,10 +526,10 @@ static bool IsBufZero(const Byte *data, size_t size)
533 526
534HRESULT CHandler::Open2(IInStream *stream) 527HRESULT CHandler::Open2(IInStream *stream)
535{ 528{
536 RINOK(stream->Seek(LP_PARTITION_RESERVED_BYTES, STREAM_SEEK_SET, NULL)); 529 RINOK(InStream_SeekSet(stream, LP_PARTITION_RESERVED_BYTES))
537 { 530 {
538 Byte buf[k_Geometry_Size]; 531 Byte buf[k_Geometry_Size];
539 RINOK(ReadStream_FALSE(stream, buf, k_Geometry_Size)); 532 RINOK(ReadStream_FALSE(stream, buf, k_Geometry_Size))
540 if (memcmp(buf, k_Signature, k_SignatureSize) != 0) 533 if (memcmp(buf, k_Signature, k_SignatureSize) != 0)
541 return S_FALSE; 534 return S_FALSE;
542 if (!geom.Parse(buf)) 535 if (!geom.Parse(buf))
@@ -546,11 +539,11 @@ HRESULT CHandler::Open2(IInStream *stream)
546 } 539 }
547 540
548 CByteBuffer buffer; 541 CByteBuffer buffer;
549 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 542 RINOK(InStream_SeekToBegin(stream))
550 buffer.Alloc(LP_METADATA_GEOMETRY_SIZE * 2); 543 buffer.Alloc(LP_METADATA_GEOMETRY_SIZE * 2);
551 { 544 {
552 // buffer.Size() >= LP_PARTITION_RESERVED_BYTES 545 // buffer.Size() >= LP_PARTITION_RESERVED_BYTES
553 RINOK(ReadStream_FALSE(stream, buffer, LP_PARTITION_RESERVED_BYTES)); 546 RINOK(ReadStream_FALSE(stream, buffer, LP_PARTITION_RESERVED_BYTES))
554 if (!IsBufZero(buffer, LP_PARTITION_RESERVED_BYTES)) 547 if (!IsBufZero(buffer, LP_PARTITION_RESERVED_BYTES))
555 { 548 {
556 _headerWarning = true; 549 _headerWarning = true;
@@ -558,7 +551,7 @@ HRESULT CHandler::Open2(IInStream *stream)
558 } 551 }
559 } 552 }
560 553
561 RINOK(ReadStream_FALSE(stream, buffer, LP_METADATA_GEOMETRY_SIZE * 2)); 554 RINOK(ReadStream_FALSE(stream, buffer, LP_METADATA_GEOMETRY_SIZE * 2))
562 // we check that 2 copies of GEOMETRY are identical: 555 // we check that 2 copies of GEOMETRY are identical:
563 if (memcmp(buffer, buffer + LP_METADATA_GEOMETRY_SIZE, LP_METADATA_GEOMETRY_SIZE) != 0 556 if (memcmp(buffer, buffer + LP_METADATA_GEOMETRY_SIZE, LP_METADATA_GEOMETRY_SIZE) != 0
564 || !IsBufZero(buffer + k_Geometry_Size, LP_METADATA_GEOMETRY_SIZE - k_Geometry_Size)) 557 || !IsBufZero(buffer + k_Geometry_Size, LP_METADATA_GEOMETRY_SIZE - k_Geometry_Size))
@@ -567,7 +560,7 @@ HRESULT CHandler::Open2(IInStream *stream)
567 // return S_FALSE; 560 // return S_FALSE;
568 } 561 }
569 562
570 RINOK(ReadStream_FALSE(stream, buffer, k_LpMetadataHeader10_size)); 563 RINOK(ReadStream_FALSE(stream, buffer, k_LpMetadataHeader10_size))
571 LpMetadataHeader header; 564 LpMetadataHeader header;
572 header.Parse128(buffer); 565 header.Parse128(buffer);
573 if (header.magic != LP_METADATA_HEADER_MAGIC || 566 if (header.magic != LP_METADATA_HEADER_MAGIC ||
@@ -580,7 +573,7 @@ HRESULT CHandler::Open2(IInStream *stream)
580 if (header.header_size != k_LpMetadataHeader12_size) 573 if (header.header_size != k_LpMetadataHeader12_size)
581 return S_FALSE; 574 return S_FALSE;
582 RINOK(ReadStream_FALSE(stream, buffer + k_LpMetadataHeader10_size, 575 RINOK(ReadStream_FALSE(stream, buffer + k_LpMetadataHeader10_size,
583 header.header_size - k_LpMetadataHeader10_size)); 576 header.header_size - k_LpMetadataHeader10_size))
584 Flags = Get32(buffer + k_LpMetadataHeader10_size); 577 Flags = Get32(buffer + k_LpMetadataHeader10_size);
585 } 578 }
586 Major_version = header.major_version; 579 Major_version = header.major_version;
@@ -594,7 +587,7 @@ HRESULT CHandler::Open2(IInStream *stream)
594 return S_FALSE; 587 return S_FALSE;
595 588
596 buffer.AllocAtLeast(header.tables_size); 589 buffer.AllocAtLeast(header.tables_size);
597 RINOK(ReadStream_FALSE(stream, buffer, header.tables_size)); 590 RINOK(ReadStream_FALSE(stream, buffer, header.tables_size))
598 591
599 const UInt64 totalMetaSize = geom.GetTotalMetadataSize(); 592 const UInt64 totalMetaSize = geom.GetTotalMetadataSize();
600 // _headersSize = _totalSize; 593 // _headersSize = _totalSize;
@@ -733,13 +726,13 @@ HRESULT CHandler::Open2(IInStream *stream)
733} 726}
734 727
735 728
736STDMETHODIMP CHandler::Open(IInStream *stream, 729Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
737 const UInt64 * /* maxCheckStartPosition */, 730 const UInt64 * /* maxCheckStartPosition */,
738 IArchiveOpenCallback * /* openArchiveCallback */) 731 IArchiveOpenCallback * /* openArchiveCallback */))
739{ 732{
740 COM_TRY_BEGIN 733 COM_TRY_BEGIN
741 Close(); 734 Close();
742 RINOK(Open2(stream)); 735 RINOK(Open2(stream))
743 _stream = stream; 736 _stream = stream;
744 737
745 int mainFileIndex = -1; 738 int mainFileIndex = -1;
@@ -750,7 +743,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
750 CPartition &item = _items[fileIndex]; 743 CPartition &item = _items[fileIndex];
751 if (item.NumSectors != 0) 744 if (item.NumSectors != 0)
752 { 745 {
753 mainFileIndex = fileIndex; 746 mainFileIndex = (int)fileIndex;
754 numNonEmptyParts++; 747 numNonEmptyParts++;
755 CMyComPtr<ISequentialInStream> parseStream; 748 CMyComPtr<ISequentialInStream> parseStream;
756 if (GetStream(fileIndex, &parseStream) == S_OK && parseStream) 749 if (GetStream(fileIndex, &parseStream) == S_OK && parseStream)
@@ -775,7 +768,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
775} 768}
776 769
777 770
778STDMETHODIMP CHandler::Close() 771Z7_COM7F_IMF(CHandler::Close())
779{ 772{
780 _totalSize = 0; 773 _totalSize = 0;
781 // _usedSize = 0; 774 // _usedSize = 0;
@@ -818,7 +811,7 @@ static const Byte kArcProps[] =
818IMP_IInArchive_Props 811IMP_IInArchive_Props
819IMP_IInArchive_ArcProps 812IMP_IInArchive_ArcProps
820 813
821STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 814Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
822{ 815{
823 COM_TRY_BEGIN 816 COM_TRY_BEGIN
824 NCOM::CPropVariant prop; 817 NCOM::CPropVariant prop;
@@ -849,7 +842,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
849 { 842 {
850 AString s; 843 AString s;
851 s.Add_UInt32(Major_version); 844 s.Add_UInt32(Major_version);
852 s += '.'; 845 s.Add_Dot();
853 s.Add_UInt32(Minor_version); 846 s.Add_UInt32(Minor_version);
854 prop = s; 847 prop = s;
855 break; 848 break;
@@ -874,7 +867,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
874 if (Flags != 0) 867 if (Flags != 0)
875 { 868 {
876 s += "flags: "; 869 s += "flags: ";
877 s += FlagsToString(g_Header_Flags, ARRAY_SIZE(g_Header_Flags), Flags); 870 s += FlagsToString(g_Header_Flags, Z7_ARRAY_SIZE(g_Header_Flags), Flags);
878 s.Add_LF(); 871 s.Add_LF();
879 } 872 }
880 873
@@ -916,14 +909,14 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
916} 909}
917 910
918 911
919STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 912Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
920{ 913{
921 *numItems = _items.Size(); 914 *numItems = _items.Size();
922 return S_OK; 915 return S_OK;
923} 916}
924 917
925 918
926STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 919Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
927{ 920{
928 COM_TRY_BEGIN 921 COM_TRY_BEGIN
929 NCOM::CPropVariant prop; 922 NCOM::CPropVariant prop;
@@ -940,7 +933,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
940 s.Add_UInt32(index); 933 s.Add_UInt32(index);
941 if (item.num_extents != 0) 934 if (item.num_extents != 0)
942 { 935 {
943 s += '.'; 936 s.Add_Dot();
944 s += (item.Ext ? item.Ext : "img"); 937 s += (item.Ext ? item.Ext : "img");
945 } 938 }
946 prop = s; 939 prop = s;
@@ -971,7 +964,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
971 s += "group:"; 964 s += "group:";
972 s.Add_UInt32(item.group_index); 965 s.Add_UInt32(item.group_index);
973 s.Add_Space(); 966 s.Add_Space();
974 s += FlagsToString(g_PartitionAttr, ARRAY_SIZE(g_PartitionAttr), item.attributes); 967 s += FlagsToString(g_PartitionAttr, Z7_ARRAY_SIZE(g_PartitionAttr), item.attributes);
975 prop = s; 968 prop = s;
976 break; 969 break;
977 } 970 }
@@ -984,7 +977,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
984 977
985 978
986 979
987STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 980Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
988{ 981{
989 COM_TRY_BEGIN 982 COM_TRY_BEGIN
990 *stream = NULL; 983 *stream = NULL;
@@ -1093,8 +1086,8 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
1093} 1086}
1094 1087
1095 1088
1096STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1089Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1097 Int32 testMode, IArchiveExtractCallback *extractCallback) 1090 Int32 testMode, IArchiveExtractCallback *extractCallback))
1098{ 1091{
1099 COM_TRY_BEGIN 1092 COM_TRY_BEGIN
1100 const bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1093 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
@@ -1124,21 +1117,21 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1124 { 1117 {
1125 lps->InSize = totalSize; 1118 lps->InSize = totalSize;
1126 lps->OutSize = totalSize; 1119 lps->OutSize = totalSize;
1127 RINOK(lps->SetCur()); 1120 RINOK(lps->SetCur())
1128 CMyComPtr<ISequentialOutStream> outStream; 1121 CMyComPtr<ISequentialOutStream> outStream;
1129 const Int32 askMode = testMode ? 1122 const Int32 askMode = testMode ?
1130 NExtract::NAskMode::kTest : 1123 NExtract::NAskMode::kTest :
1131 NExtract::NAskMode::kExtract; 1124 NExtract::NAskMode::kExtract;
1132 const UInt32 index = allFilesMode ? i : indices[i]; 1125 const UInt32 index = allFilesMode ? i : indices[i];
1133 1126
1134 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 1127 RINOK(extractCallback->GetStream(index, &outStream, askMode))
1135 1128
1136 const UInt64 size = _items[index].GetSize(); 1129 const UInt64 size = _items[index].GetSize();
1137 totalSize += size; 1130 totalSize += size;
1138 if (!testMode && !outStream) 1131 if (!testMode && !outStream)
1139 continue; 1132 continue;
1140 1133
1141 RINOK(extractCallback->PrepareOperation(askMode)); 1134 RINOK(extractCallback->PrepareOperation(askMode))
1142 1135
1143 CMyComPtr<ISequentialInStream> inStream; 1136 CMyComPtr<ISequentialInStream> inStream;
1144 const HRESULT hres = GetStream(index, &inStream); 1137 const HRESULT hres = GetStream(index, &inStream);
@@ -1147,7 +1140,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1147 { 1140 {
1148 if (hres != S_OK) 1141 if (hres != S_OK)
1149 return hres; 1142 return hres;
1150 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 1143 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
1151 opRes = NExtract::NOperationResult::kDataError; 1144 opRes = NExtract::NOperationResult::kDataError;
1152 if (copyCoderSpec->TotalSize == size) 1145 if (copyCoderSpec->TotalSize == size)
1153 opRes = NExtract::NOperationResult::kOK; 1146 opRes = NExtract::NOperationResult::kOK;
@@ -1155,7 +1148,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1155 opRes = NExtract::NOperationResult::kUnexpectedEnd; 1148 opRes = NExtract::NOperationResult::kUnexpectedEnd;
1156 } 1149 }
1157 outStream.Release(); 1150 outStream.Release();
1158 RINOK(extractCallback->SetOperationResult(opRes)); 1151 RINOK(extractCallback->SetOperationResult(opRes))
1159 } 1152 }
1160 1153
1161 return S_OK; 1154 return S_OK;
diff --git a/CPP/7zip/Archive/LzhHandler.cpp b/CPP/7zip/Archive/LzhHandler.cpp
index 6711da6..9239afd 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)
51 return crc; 51 return crc;
52} 52}
53 53
54static class CLzhCrc16TableInit 54static struct CLzhCrc16TableInit
55{ 55{
56public:
57 CLzhCrc16TableInit() 56 CLzhCrc16TableInit()
58 { 57 {
59 for (UInt32 i = 0; i < 256; i++) 58 for (UInt32 i = 0; i < 256; i++)
@@ -176,7 +175,7 @@ struct CItem
176 { 175 {
177 FOR_VECTOR (i, Extensions) 176 FOR_VECTOR (i, Extensions)
178 if (Extensions[i].Type == type) 177 if (Extensions[i].Type == type)
179 return i; 178 return (int)i;
180 return -1; 179 return -1;
181 } 180 }
182 181
@@ -239,10 +238,10 @@ static const Byte *ReadString(const Byte *p, size_t size, AString &s)
239 s.Empty(); 238 s.Empty();
240 for (size_t i = 0; i < size; i++) 239 for (size_t i = 0; i < size; i++)
241 { 240 {
242 char c = p[i]; 241 const Byte c = p[i];
243 if (c == 0) 242 if (c == 0)
244 break; 243 break;
245 s += c; 244 s += (char)c;
246 } 245 }
247 return p + size; 246 return p + size;
248} 247}
@@ -271,7 +270,7 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite
271 270
272 Byte header[256]; 271 Byte header[256];
273 processedSize = kBasicPartSize; 272 processedSize = kBasicPartSize;
274 RINOK(ReadStream(stream, header, &processedSize)); 273 RINOK(ReadStream(stream, header, &processedSize))
275 if (processedSize != kBasicPartSize) 274 if (processedSize != kBasicPartSize)
276 return (startHeader[0] == 0) ? S_OK: S_FALSE; 275 return (startHeader[0] == 0) ? S_OK: S_FALSE;
277 276
@@ -294,11 +293,11 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite
294 headerSize = startHeader[0]; 293 headerSize = startHeader[0];
295 if (headerSize < kBasicPartSize) 294 if (headerSize < kBasicPartSize)
296 return S_FALSE; 295 return S_FALSE;
297 RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, headerSize - kBasicPartSize)); 296 RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, headerSize - kBasicPartSize))
298 if (startHeader[1] != CalcSum(header, headerSize)) 297 if (startHeader[1] != CalcSum(header, headerSize))
299 return S_FALSE; 298 return S_FALSE;
300 size_t nameLength = *p++; 299 const size_t nameLength = *p++;
301 if ((p - header) + nameLength + 2 > headerSize) 300 if ((size_t)(p - header) + nameLength + 2 > headerSize)
302 return S_FALSE; 301 return S_FALSE;
303 p = ReadString(p, nameLength, item.Name); 302 p = ReadString(p, nameLength, item.Name);
304 } 303 }
@@ -309,7 +308,7 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite
309 { 308 {
310 if (item.Level == 2) 309 if (item.Level == 2)
311 { 310 {
312 RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, 2)); 311 RINOK(ReadStream_FALSE(stream, header + kBasicPartSize, 2))
313 } 312 }
314 if ((size_t)(p - header) + 3 > headerSize) 313 if ((size_t)(p - header) + 3 > headerSize)
315 return S_FALSE; 314 return S_FALSE;
@@ -335,7 +334,7 @@ static HRESULT GetNextItem(ISequentialInStream *stream, bool &filled, CItem &ite
335 RINOK(ReadStream_FALSE(stream, (Byte *)ext.Data, nextSize)) 334 RINOK(ReadStream_FALSE(stream, (Byte *)ext.Data, nextSize))
336 item.Extensions.Add(ext); 335 item.Extensions.Add(ext);
337 Byte hdr2[2]; 336 Byte hdr2[2];
338 RINOK(ReadStream_FALSE(stream, hdr2, 2)); 337 RINOK(ReadStream_FALSE(stream, hdr2, 2))
339 ReadUInt16(hdr2, nextSize); 338 ReadUInt16(hdr2, nextSize);
340 } 339 }
341 } 340 }
@@ -380,15 +379,10 @@ static const Byte kProps[] =
380}; 379};
381 380
382 381
383class COutStreamWithCRC: 382Z7_CLASS_IMP_NOQIB_1(
384 public ISequentialOutStream, 383 COutStreamWithCRC
385 public CMyUnknownImp 384 , ISequentialOutStream
386{ 385)
387public:
388 MY_UNKNOWN_IMP
389
390 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
391private:
392 UInt32 _crc; 386 UInt32 _crc;
393 CMyComPtr<ISequentialOutStream> _stream; 387 CMyComPtr<ISequentialOutStream> _stream;
394public: 388public:
@@ -401,7 +395,7 @@ public:
401 UInt32 GetCRC() const { return _crc; } 395 UInt32 GetCRC() const { return _crc; }
402}; 396};
403 397
404STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) 398Z7_COM7F_IMF(COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize))
405{ 399{
406 HRESULT res = S_OK; 400 HRESULT res = S_OK;
407 if (_stream) 401 if (_stream)
@@ -419,18 +413,14 @@ struct CItemEx: public CItem
419}; 413};
420 414
421 415
422class CHandler: 416Z7_CLASS_IMP_CHandler_IInArchive_0
423 public IInArchive, 417
424 public CMyUnknownImp
425{
426 CObjectVector<CItemEx> _items; 418 CObjectVector<CItemEx> _items;
427 CMyComPtr<IInStream> _stream; 419 CMyComPtr<IInStream> _stream;
428 UInt64 _phySize; 420 UInt64 _phySize;
429 UInt32 _errorFlags; 421 UInt32 _errorFlags;
430 bool _isArc; 422 bool _isArc;
431public: 423public:
432 MY_UNKNOWN_IMP1(IInArchive)
433 INTERFACE_IInArchive(;)
434 CHandler(); 424 CHandler();
435}; 425};
436 426
@@ -439,13 +429,13 @@ IMP_IInArchive_ArcProps_NO_Table
439 429
440CHandler::CHandler() {} 430CHandler::CHandler() {}
441 431
442STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 432Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
443{ 433{
444 *numItems = _items.Size(); 434 *numItems = _items.Size();
445 return S_OK; 435 return S_OK;
446} 436}
447 437
448STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 438Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
449{ 439{
450 NCOM::CPropVariant prop; 440 NCOM::CPropVariant prop;
451 switch (propID) 441 switch (propID)
@@ -462,7 +452,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
462 return S_OK; 452 return S_OK;
463} 453}
464 454
465STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 455Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
466{ 456{
467 COM_TRY_BEGIN 457 COM_TRY_BEGIN
468 NCOM::CPropVariant prop; 458 NCOM::CPropVariant prop;
@@ -509,8 +499,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
509 COM_TRY_END 499 COM_TRY_END
510} 500}
511 501
512STDMETHODIMP CHandler::Open(IInStream *stream, 502Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
513 const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) 503 const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback))
514{ 504{
515 COM_TRY_BEGIN 505 COM_TRY_BEGIN
516 Close(); 506 Close();
@@ -518,18 +508,17 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
518 { 508 {
519 _items.Clear(); 509 _items.Clear();
520 510
521 UInt64 endPos = 0; 511 UInt64 endPos;
522 bool needSetTotal = true; 512 bool needSetTotal = true;
523 513
524 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); 514 RINOK(InStream_AtBegin_GetSize(stream, endPos))
525 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
526 515
527 for (;;) 516 for (;;)
528 { 517 {
529 CItemEx item; 518 CItemEx item;
530 bool filled; 519 bool filled;
531 HRESULT res = GetNextItem(stream, filled, item); 520 const HRESULT res = GetNextItem(stream, filled, item);
532 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &item.DataPosition)); 521 RINOK(InStream_GetPos(stream, item.DataPosition))
533 if (res == S_FALSE) 522 if (res == S_FALSE)
534 { 523 {
535 _errorFlags = kpv_ErrorFlags_HeadersError; 524 _errorFlags = kpv_ErrorFlags_HeadersError;
@@ -546,7 +535,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
546 _isArc = true; 535 _isArc = true;
547 536
548 UInt64 newPostion; 537 UInt64 newPostion;
549 RINOK(stream->Seek(item.PackSize, STREAM_SEEK_CUR, &newPostion)); 538 RINOK(stream->Seek(item.PackSize, STREAM_SEEK_CUR, &newPostion))
550 if (newPostion > endPos) 539 if (newPostion > endPos)
551 { 540 {
552 _phySize = endPos; 541 _phySize = endPos;
@@ -558,14 +547,14 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
558 { 547 {
559 if (needSetTotal) 548 if (needSetTotal)
560 { 549 {
561 RINOK(callback->SetTotal(NULL, &endPos)); 550 RINOK(callback->SetTotal(NULL, &endPos))
562 needSetTotal = false; 551 needSetTotal = false;
563 } 552 }
564 if (_items.Size() % 100 == 0) 553 if (_items.Size() % 100 == 0)
565 { 554 {
566 UInt64 numFiles = _items.Size(); 555 UInt64 numFiles = _items.Size();
567 UInt64 numBytes = item.DataPosition; 556 UInt64 numBytes = item.DataPosition;
568 RINOK(callback->SetCompleted(&numFiles, &numBytes)); 557 RINOK(callback->SetCompleted(&numFiles, &numBytes))
569 } 558 }
570 } 559 }
571 } 560 }
@@ -582,7 +571,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
582 return S_OK; 571 return S_OK;
583} 572}
584 573
585STDMETHODIMP CHandler::Close() 574Z7_COM7F_IMF(CHandler::Close())
586{ 575{
587 _isArc = false; 576 _isArc = false;
588 _phySize = 0; 577 _phySize = 0;
@@ -592,30 +581,28 @@ STDMETHODIMP CHandler::Close()
592 return S_OK; 581 return S_OK;
593} 582}
594 583
595STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 584Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
596 Int32 testModeSpec, IArchiveExtractCallback *extractCallback) 585 Int32 testMode, IArchiveExtractCallback *extractCallback))
597{ 586{
598 COM_TRY_BEGIN 587 COM_TRY_BEGIN
599 bool testMode = (testModeSpec != 0); 588 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
600 UInt64 totalUnPacked = 0, totalPacked = 0;
601 bool allFilesMode = (numItems == (UInt32)(Int32)-1);
602 if (allFilesMode) 589 if (allFilesMode)
603 numItems = _items.Size(); 590 numItems = _items.Size();
604 if (numItems == 0) 591 if (numItems == 0)
605 return S_OK; 592 return S_OK;
593 UInt64 totalUnPacked = 0 /* , totalPacked = 0 */;
606 UInt32 i; 594 UInt32 i;
607 for (i = 0; i < numItems; i++) 595 for (i = 0; i < numItems; i++)
608 { 596 {
609 const CItemEx &item = _items[allFilesMode ? i : indices[i]]; 597 const CItemEx &item = _items[allFilesMode ? i : indices[i]];
610 totalUnPacked += item.Size; 598 totalUnPacked += item.Size;
611 totalPacked += item.PackSize; 599 // totalPacked += item.PackSize;
612 } 600 }
613 RINOK(extractCallback->SetTotal(totalUnPacked)); 601 RINOK(extractCallback->SetTotal(totalUnPacked))
614 602
615 UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0;
616 UInt64 currentItemUnPacked, currentItemPacked; 603 UInt64 currentItemUnPacked, currentItemPacked;
617 604
618 NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; 605 NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = NULL;
619 CMyComPtr<ICompressCoder> lzhDecoder; 606 CMyComPtr<ICompressCoder> lzhDecoder;
620 // CMyComPtr<ICompressCoder> lzh1Decoder; 607 // CMyComPtr<ICompressCoder> lzh1Decoder;
621 // CMyComPtr<ICompressCoder> arj2Decoder; 608 // CMyComPtr<ICompressCoder> arj2Decoder;
@@ -631,30 +618,32 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
631 CMyComPtr<ISequentialInStream> inStream(streamSpec); 618 CMyComPtr<ISequentialInStream> inStream(streamSpec);
632 streamSpec->SetStream(_stream); 619 streamSpec->SetStream(_stream);
633 620
634 for (i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, 621 for (i = 0;; i++,
635 currentTotalPacked += currentItemPacked) 622 lps->OutSize += currentItemUnPacked,
623 lps->InSize += currentItemPacked)
636 { 624 {
637 currentItemUnPacked = 0; 625 currentItemUnPacked = 0;
638 currentItemPacked = 0; 626 currentItemPacked = 0;
639 627
640 lps->InSize = currentTotalPacked; 628 RINOK(lps->SetCur())
641 lps->OutSize = currentTotalUnPacked; 629
642 RINOK(lps->SetCur()); 630 if (i >= numItems)
631 break;
643 632
644 CMyComPtr<ISequentialOutStream> realOutStream; 633 CMyComPtr<ISequentialOutStream> realOutStream;
645 Int32 askMode; 634 const Int32 askMode = testMode ?
646 askMode = testMode ? NExtract::NAskMode::kTest : 635 NExtract::NAskMode::kTest :
647 NExtract::NAskMode::kExtract; 636 NExtract::NAskMode::kExtract;
648 Int32 index = allFilesMode ? i : indices[i]; 637 const UInt32 index = allFilesMode ? i : indices[i];
649 const CItemEx &item = _items[index]; 638 const CItemEx &item = _items[index];
650 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 639 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
651 640
652 if (item.IsDir()) 641 if (item.IsDir())
653 { 642 {
654 // if (!testMode) 643 // if (!testMode)
655 { 644 {
656 RINOK(extractCallback->PrepareOperation(askMode)); 645 RINOK(extractCallback->PrepareOperation(askMode))
657 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 646 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
658 } 647 }
659 continue; 648 continue;
660 } 649 }
@@ -662,7 +651,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
662 if (!testMode && !realOutStream) 651 if (!testMode && !realOutStream)
663 continue; 652 continue;
664 653
665 RINOK(extractCallback->PrepareOperation(askMode)); 654 RINOK(extractCallback->PrepareOperation(askMode))
666 currentItemUnPacked = item.Size; 655 currentItemUnPacked = item.Size;
667 currentItemPacked = item.PackSize; 656 currentItemPacked = item.PackSize;
668 657
@@ -672,8 +661,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
672 outStreamSpec->Init(realOutStream); 661 outStreamSpec->Init(realOutStream);
673 realOutStream.Release(); 662 realOutStream.Release();
674 663
675 UInt64 pos; 664 RINOK(InStream_SeekSet(_stream, item.DataPosition))
676 _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos);
677 665
678 streamSpec->Init(item.PackSize); 666 streamSpec->Init(item.PackSize);
679 667
@@ -720,13 +708,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
720 opRes = NExtract::NOperationResult::kDataError; 708 opRes = NExtract::NOperationResult::kDataError;
721 else 709 else
722 { 710 {
723 RINOK(res); 711 RINOK(res)
724 if (outStreamSpec->GetCRC() != item.CRC) 712 if (outStreamSpec->GetCRC() != item.CRC)
725 opRes = NExtract::NOperationResult::kCRCError; 713 opRes = NExtract::NOperationResult::kCRCError;
726 } 714 }
727 } 715 }
728 outStream.Release(); 716 outStream.Release();
729 RINOK(extractCallback->SetOperationResult(opRes)); 717 RINOK(extractCallback->SetOperationResult(opRes))
730 } 718 }
731 } 719 }
732 return S_OK; 720 return S_OK;
@@ -736,7 +724,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
736static const Byte k_Signature[] = { '-', 'l', 'h' }; 724static const Byte k_Signature[] = { '-', 'l', 'h' };
737 725
738REGISTER_ARC_I( 726REGISTER_ARC_I(
739 "Lzh", "lzh lha", 0, 6, 727 "Lzh", "lzh lha", NULL, 6,
740 k_Signature, 728 k_Signature,
741 2, 729 2,
742 0, 730 0,
diff --git a/CPP/7zip/Archive/LzmaHandler.cpp b/CPP/7zip/Archive/LzmaHandler.cpp
index ba547c8..11cb76e 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)
76 && CheckDicSize(LzmaProps + 1); 76 && CheckDicSize(LzmaProps + 1);
77} 77}
78 78
79class CDecoder 79class CDecoder Z7_final
80{ 80{
81 CMyComPtr<ISequentialOutStream> _bcjStream; 81 CMyComPtr<ISequentialOutStream> _bcjStream;
82 CFilterCoder *_filterCoder; 82 CFilterCoder *_filterCoder;
@@ -112,7 +112,7 @@ HRESULT CDecoder::Create(bool filteredMode, ISequentialInStream *inStream)
112 { 112 {
113 _filterCoder = new CFilterCoder(false); 113 _filterCoder = new CFilterCoder(false);
114 CMyComPtr<ICompressCoder> coder = _filterCoder; 114 CMyComPtr<ICompressCoder> coder = _filterCoder;
115 _filterCoder->Filter = new NCompress::NBcj::CCoder(false); 115 _filterCoder->Filter = new NCompress::NBcj::CCoder2(z7_BranchConvSt_X86_Dec);
116 _bcjStream = _filterCoder; 116 _bcjStream = _filterCoder;
117 } 117 }
118 } 118 }
@@ -131,15 +131,15 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream,
131 if (header.FilterID > 1) 131 if (header.FilterID > 1)
132 return E_NOTIMPL; 132 return E_NOTIMPL;
133 133
134 RINOK(_lzmaDecoderSpec->SetDecoderProperties2(header.LzmaProps, 5)); 134 RINOK(_lzmaDecoderSpec->SetDecoderProperties2(header.LzmaProps, 5))
135 135
136 bool filteredMode = (header.FilterID == 1); 136 bool filteredMode = (header.FilterID == 1);
137 137
138 if (filteredMode) 138 if (filteredMode)
139 { 139 {
140 RINOK(_filterCoder->SetOutStream(outStream)); 140 RINOK(_filterCoder->SetOutStream(outStream))
141 outStream = _bcjStream; 141 outStream = _bcjStream;
142 RINOK(_filterCoder->SetOutStreamSize(NULL)); 142 RINOK(_filterCoder->SetOutStreamSize(NULL))
143 } 143 }
144 144
145 const UInt64 *Size = header.HasSize() ? &header.Size : NULL; 145 const UInt64 *Size = header.HasSize() ? &header.Size : NULL;
@@ -157,7 +157,7 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream,
157 res = res2; 157 res = res2;
158 } 158 }
159 159
160 RINOK(res); 160 RINOK(res)
161 161
162 if (header.HasSize()) 162 if (header.HasSize())
163 if (_lzmaDecoderSpec->GetOutputProcessedSize() != header.Size) 163 if (_lzmaDecoderSpec->GetOutputProcessedSize() != header.Size)
@@ -167,11 +167,9 @@ HRESULT CDecoder::Code(const CHeader &header, ISequentialOutStream *outStream,
167} 167}
168 168
169 169
170class CHandler: 170Z7_CLASS_IMP_CHandler_IInArchive_1(
171 public IInArchive, 171 IArchiveOpenSeq
172 public IArchiveOpenSeq, 172)
173 public CMyUnknownImp
174{
175 CHeader _header; 173 CHeader _header;
176 bool _lzma86; 174 bool _lzma86;
177 CMyComPtr<IInStream> _stream; 175 CMyComPtr<IInStream> _stream;
@@ -181,36 +179,28 @@ class CHandler:
181 bool _needSeekToStart; 179 bool _needSeekToStart;
182 bool _dataAfterEnd; 180 bool _dataAfterEnd;
183 bool _needMoreInput; 181 bool _needMoreInput;
182 bool _unsupported;
183 bool _dataError;
184 184
185 bool _packSize_Defined; 185 bool _packSize_Defined;
186 bool _unpackSize_Defined; 186 bool _unpackSize_Defined;
187 bool _numStreams_Defined; 187 bool _numStreams_Defined;
188 188
189 bool _unsupported;
190 bool _dataError;
191
192 UInt64 _packSize; 189 UInt64 _packSize;
193 UInt64 _unpackSize; 190 UInt64 _unpackSize;
194 UInt64 _numStreams; 191 UInt64 _numStreams;
195 192
196 void GetMethod(NCOM::CPropVariant &prop); 193 void GetMethod(NCOM::CPropVariant &prop);
197 194
195 unsigned GetHeaderSize() const { return 5 + 8 + (_lzma86 ? 1 : 0); }
198public: 196public:
199 MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq)
200
201 INTERFACE_IInArchive(;)
202 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
203
204 CHandler(bool lzma86) { _lzma86 = lzma86; } 197 CHandler(bool lzma86) { _lzma86 = lzma86; }
205
206 unsigned GetHeaderSize() const { return 5 + 8 + (_lzma86 ? 1 : 0); }
207
208}; 198};
209 199
210IMP_IInArchive_Props 200IMP_IInArchive_Props
211IMP_IInArchive_ArcProps 201IMP_IInArchive_ArcProps
212 202
213STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 203Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
214{ 204{
215 NCOM::CPropVariant prop; 205 NCOM::CPropVariant prop;
216 switch (propID) 206 switch (propID)
@@ -222,7 +212,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
222 case kpidErrorFlags: 212 case kpidErrorFlags:
223 { 213 {
224 UInt32 v = 0; 214 UInt32 v = 0;
225 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 215 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
226 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; 216 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd;
227 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; 217 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd;
228 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; 218 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod;
@@ -235,7 +225,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
235 return S_OK; 225 return S_OK;
236} 226}
237 227
238STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 228Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
239{ 229{
240 *numItems = 1; 230 *numItems = 1;
241 return S_OK; 231 return S_OK;
@@ -244,7 +234,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
244 234
245static char * DictSizeToString(UInt32 val, char *s) 235static char * DictSizeToString(UInt32 val, char *s)
246{ 236{
247 for (unsigned i = 0; i <= 31; i++) 237 for (unsigned i = 0; i < 32; i++)
248 if (((UInt32)1 << i) == val) 238 if (((UInt32)1 << i) == val)
249 return ::ConvertUInt32ToString(i, s); 239 return ::ConvertUInt32ToString(i, s);
250 char c = 'b'; 240 char c = 'b';
@@ -290,7 +280,7 @@ void CHandler::GetMethod(NCOM::CPropVariant &prop)
290} 280}
291 281
292 282
293STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 283Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
294{ 284{
295 NCOM::CPropVariant prop; 285 NCOM::CPropVariant prop;
296 switch (propID) 286 switch (propID)
@@ -348,7 +338,7 @@ API_FUNC_static_IsArc IsArc_Lzma86(const Byte *p, size_t size)
348 338
349 339
350 340
351STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) 341Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *))
352{ 342{
353 Close(); 343 Close();
354 344
@@ -356,7 +346,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
356 const UInt32 kBufSize = 1 << 7; 346 const UInt32 kBufSize = 1 << 7;
357 Byte buf[kBufSize]; 347 Byte buf[kBufSize];
358 size_t processedSize = kBufSize; 348 size_t processedSize = kBufSize;
359 RINOK(ReadStream(inStream, buf, &processedSize)); 349 RINOK(ReadStream(inStream, buf, &processedSize))
360 if (processedSize < headerSize + 2) 350 if (processedSize < headerSize + 2)
361 return S_FALSE; 351 return S_FALSE;
362 if (!_header.Parse(buf, _lzma86)) 352 if (!_header.Parse(buf, _lzma86))
@@ -365,9 +355,9 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
365 if (start[0] != 0 /* || (start[1] & 0x80) != 0 */ ) // empty stream with EOS is not 0x80 355 if (start[0] != 0 /* || (start[1] & 0x80) != 0 */ ) // empty stream with EOS is not 0x80
366 return S_FALSE; 356 return S_FALSE;
367 357
368 RINOK(inStream->Seek(0, STREAM_SEEK_END, &_packSize)); 358 RINOK(InStream_GetSize_SeekToEnd(inStream, _packSize))
369 359
370 SizeT srcLen = processedSize - headerSize; 360 SizeT srcLen = (SizeT)processedSize - headerSize;
371 361
372 if (srcLen > 10 362 if (srcLen > 10
373 && _header.Size == 0 363 && _header.Size == 0
@@ -401,7 +391,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
401 return S_OK; 391 return S_OK;
402} 392}
403 393
404STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 394Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
405{ 395{
406 Close(); 396 Close();
407 _isArc = true; 397 _isArc = true;
@@ -409,41 +399,38 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
409 return S_OK; 399 return S_OK;
410} 400}
411 401
412STDMETHODIMP CHandler::Close() 402Z7_COM7F_IMF(CHandler::Close())
413{ 403{
414 _isArc = false; 404 _isArc = false;
415 _packSize_Defined = false; 405 _needSeekToStart = false;
416 _unpackSize_Defined = false;
417 _numStreams_Defined = false;
418
419 _dataAfterEnd = false; 406 _dataAfterEnd = false;
420 _needMoreInput = false; 407 _needMoreInput = false;
421 _unsupported = false; 408 _unsupported = false;
422 _dataError = false; 409 _dataError = false;
423 410
424 _packSize = 0; 411 _packSize_Defined = false;
412 _unpackSize_Defined = false;
413 _numStreams_Defined = false;
425 414
426 _needSeekToStart = false; 415 _packSize = 0;
427 416
428 _stream.Release(); 417 _stream.Release();
429 _seqStream.Release(); 418 _seqStream.Release();
430 return S_OK; 419 return S_OK;
431} 420}
432 421
433class CCompressProgressInfoImp: 422Z7_CLASS_IMP_COM_1(
434 public ICompressProgressInfo, 423 CCompressProgressInfoImp,
435 public CMyUnknownImp 424 ICompressProgressInfo
436{ 425)
437 CMyComPtr<IArchiveOpenCallback> Callback; 426 CMyComPtr<IArchiveOpenCallback> Callback;
438public: 427public:
439 UInt64 Offset; 428 UInt64 Offset;
440 429
441 MY_UNKNOWN_IMP1(ICompressProgressInfo)
442 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
443 void Init(IArchiveOpenCallback *callback) { Callback = callback; } 430 void Init(IArchiveOpenCallback *callback) { Callback = callback; }
444}; 431};
445 432
446STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) 433Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */))
447{ 434{
448 if (Callback) 435 if (Callback)
449 { 436 {
@@ -454,8 +441,8 @@ STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const
454 return S_OK; 441 return S_OK;
455} 442}
456 443
457STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 444Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
458 Int32 testMode, IArchiveExtractCallback *extractCallback) 445 Int32 testMode, IArchiveExtractCallback *extractCallback))
459{ 446{
460 COM_TRY_BEGIN 447 COM_TRY_BEGIN
461 448
@@ -469,10 +456,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
469 456
470 457
471 CMyComPtr<ISequentialOutStream> realOutStream; 458 CMyComPtr<ISequentialOutStream> realOutStream;
472 Int32 askMode = testMode ? 459 const Int32 askMode = testMode ?
473 NExtract::NAskMode::kTest : 460 NExtract::NAskMode::kTest :
474 NExtract::NAskMode::kExtract; 461 NExtract::NAskMode::kExtract;
475 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 462 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
476 if (!testMode && !realOutStream) 463 if (!testMode && !realOutStream)
477 return S_OK; 464 return S_OK;
478 465
@@ -492,14 +479,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
492 { 479 {
493 if (!_stream) 480 if (!_stream)
494 return E_FAIL; 481 return E_FAIL;
495 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 482 RINOK(InStream_SeekToBegin(_stream))
496 } 483 }
497 else 484 else
498 _needSeekToStart = true; 485 _needSeekToStart = true;
499 486
500 CDecoder decoder; 487 CDecoder decoder;
501 HRESULT result = decoder.Create(_lzma86, _seqStream); 488 HRESULT result = decoder.Create(_lzma86, _seqStream);
502 RINOK(result); 489 RINOK(result)
503 490
504 bool firstItem = true; 491 bool firstItem = true;
505 492
@@ -513,13 +500,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
513 { 500 {
514 lps->InSize = packSize; 501 lps->InSize = packSize;
515 lps->OutSize = unpackSize; 502 lps->OutSize = unpackSize;
516 RINOK(lps->SetCur()); 503 RINOK(lps->SetCur())
517 504
518 const UInt32 kBufSize = 1 + 5 + 8; 505 const UInt32 kBufSize = 1 + 5 + 8;
519 Byte buf[kBufSize]; 506 Byte buf[kBufSize];
520 const UInt32 headerSize = GetHeaderSize(); 507 const UInt32 headerSize = GetHeaderSize();
521 UInt32 processed; 508 UInt32 processed;
522 RINOK(decoder.ReadInput(buf, headerSize, &processed)); 509 RINOK(decoder.ReadInput(buf, headerSize, &processed))
523 if (processed != headerSize) 510 if (processed != headerSize)
524 { 511 {
525 if (processed != 0) 512 if (processed != 0)
@@ -549,7 +536,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
549 } 536 }
550 if (result == S_FALSE) 537 if (result == S_FALSE)
551 break; 538 break;
552 RINOK(result); 539 RINOK(result)
553 } 540 }
554 541
555 if (firstItem) 542 if (firstItem)
@@ -602,7 +589,7 @@ namespace NLzmaAr {
602 589
603REGISTER_ARC_I_CLS_NO_SIG( 590REGISTER_ARC_I_CLS_NO_SIG(
604 CHandler(false), 591 CHandler(false),
605 "lzma", "lzma", 0, 0xA, 592 "lzma", "lzma", NULL, 0xA,
606 0, 593 0,
607 NArcInfoFlags::kStartOpen | 594 NArcInfoFlags::kStartOpen |
608 NArcInfoFlags::kKeepName, 595 NArcInfoFlags::kKeepName,
@@ -614,7 +601,7 @@ namespace NLzma86Ar {
614 601
615REGISTER_ARC_I_CLS_NO_SIG( 602REGISTER_ARC_I_CLS_NO_SIG(
616 CHandler(true), 603 CHandler(true),
617 "lzma86", "lzma86", 0, 0xB, 604 "lzma86", "lzma86", NULL, 0xB,
618 0, 605 0,
619 NArcInfoFlags::kKeepName, 606 NArcInfoFlags::kKeepName,
620 IsArc_Lzma86) 607 IsArc_Lzma86)
diff --git a/CPP/7zip/Archive/MachoHandler.cpp b/CPP/7zip/Archive/MachoHandler.cpp
index bc8ba22..4920a04 100644
--- a/CPP/7zip/Archive/MachoHandler.cpp
+++ b/CPP/7zip/Archive/MachoHandler.cpp
@@ -95,6 +95,13 @@ static const char * const g_SectTypes[] =
95 , "GB_ZEROFILL" 95 , "GB_ZEROFILL"
96 , "INTERPOSING" 96 , "INTERPOSING"
97 , "16BYTE_LITERALS" 97 , "16BYTE_LITERALS"
98 , "DTRACE_DOF"
99 , "LAZY_DYLIB_SYMBOL_POINTERS"
100 , "THREAD_LOCAL_REGULAR"
101 , "THREAD_LOCAL_ZEROFILL"
102 , "THREAD_LOCAL_VARIABLES"
103 , "THREAD_LOCAL_VARIABLE_POINTERS"
104 , "THREAD_LOCAL_INIT_FUNCTION_POINTERS"
98}; 105};
99 106
100enum EFileType 107enum EFileType
@@ -157,7 +164,7 @@ static const char * const g_ArcFlags[] =
157}; 164};
158 165
159 166
160static const CUInt32PCharPair g_Flags[] = 167static const CUInt32PCharPair g_SectFlags[] =
161{ 168{
162 { 31, "PURE_INSTRUCTIONS" }, 169 { 31, "PURE_INSTRUCTIONS" },
163 { 30, "NO_TOC" }, 170 { 30, "NO_TOC" },
@@ -171,25 +178,54 @@ static const CUInt32PCharPair g_Flags[] =
171 { 8, "LOC_RELOC" } 178 { 8, "LOC_RELOC" }
172}; 179};
173 180
181
182// VM_PROT_*
183static const char * const g_SegmentProt[] =
184{
185 "READ"
186 , "WRITE"
187 , "EXECUTE"
188 /*
189 , "NO_CHANGE"
190 , "COPY"
191 , "TRUSTED"
192 , "IS_MASK"
193 */
194};
195
196// SG_*
197
198static const char * const g_SegmentFlags[] =
199{
200 "SG_HIGHVM"
201 , "SG_FVMLIB"
202 , "SG_NORELOC"
203 , "SG_PROTECTED_VERSION_1"
204 , "SG_READ_ONLY"
205};
206
174static const unsigned kNameSize = 16; 207static const unsigned kNameSize = 16;
175 208
176struct CSegment 209struct CSegment
177{ 210{
178 char Name[kNameSize]; 211 char Name[kNameSize];
212 UInt32 MaxProt;
213 UInt32 InitProt;
214 UInt32 Flags;
179}; 215};
180 216
181struct CSection 217struct CSection
182{ 218{
183 char Name[kNameSize]; 219 char Name[kNameSize];
184 char SegName[kNameSize]; 220 // char SegName[kNameSize];
185 UInt64 Va; 221 UInt64 Va;
186 UInt64 Pa; 222 UInt64 Pa;
187 UInt64 VSize; 223 UInt64 VSize;
188 UInt64 PSize; 224 UInt64 PSize;
189 225
226 UInt32 Align;
190 UInt32 Flags; 227 UInt32 Flags;
191 int SegmentIndex; 228 unsigned SegmentIndex;
192
193 bool IsDummy; 229 bool IsDummy;
194 230
195 CSection(): IsDummy(false) {} 231 CSection(): IsDummy(false) {}
@@ -198,11 +234,9 @@ struct CSection
198}; 234};
199 235
200 236
201class CHandler: 237Z7_CLASS_IMP_CHandler_IInArchive_1(
202 public IInArchive, 238 IArchiveAllowTail
203 public IArchiveAllowTail, 239)
204 public CMyUnknownImp
205{
206 CMyComPtr<IInStream> _inStream; 240 CMyComPtr<IInStream> _inStream;
207 CObjectVector<CSegment> _segments; 241 CObjectVector<CSegment> _segments;
208 CObjectVector<CSection> _sections; 242 CObjectVector<CSection> _sections;
@@ -218,9 +252,6 @@ class CHandler:
218 252
219 HRESULT Open2(ISequentialInStream *stream); 253 HRESULT Open2(ISequentialInStream *stream);
220public: 254public:
221 MY_UNKNOWN_IMP2(IInArchive, IArchiveAllowTail)
222 INTERFACE_IInArchive(;)
223 STDMETHOD(AllowTail)(Int32 allowTail);
224 CHandler(): _allowTail(false) {} 255 CHandler(): _allowTail(false) {}
225}; 256};
226 257
@@ -240,13 +271,14 @@ static const Byte kProps[] =
240 kpidPackSize, 271 kpidPackSize,
241 kpidCharacts, 272 kpidCharacts,
242 kpidOffset, 273 kpidOffset,
243 kpidVa 274 kpidVa,
275 kpidClusterSize // Align
244}; 276};
245 277
246IMP_IInArchive_Props 278IMP_IInArchive_Props
247IMP_IInArchive_ArcProps 279IMP_IInArchive_ArcProps
248 280
249STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 281Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
250{ 282{
251 COM_TRY_BEGIN 283 COM_TRY_BEGIN
252 CPropVariant prop; 284 CPropVariant prop;
@@ -256,35 +288,28 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
256 case kpidCpu: 288 case kpidCpu:
257 { 289 {
258 AString s; 290 AString s;
259 char temp[16]; 291 const UInt32 cpu = _cpuType & ~(UInt32)CPU_ARCH_ABI64;
260 UInt32 cpu = _cpuType & ~(UInt32)CPU_ARCH_ABI64;
261 UInt32 flag64 = _cpuType & (UInt32)CPU_ARCH_ABI64; 292 UInt32 flag64 = _cpuType & (UInt32)CPU_ARCH_ABI64;
262 { 293 {
263 const char *n = NULL; 294 s.Add_UInt32(cpu);
264 for (unsigned i = 0; i < ARRAY_SIZE(g_CpuPairs); i++) 295 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_CpuPairs); i++)
265 { 296 {
266 const CUInt32PCharPair &pair = g_CpuPairs[i]; 297 const CUInt32PCharPair &pair = g_CpuPairs[i];
267 if (pair.Value == cpu || pair.Value == _cpuType) 298 if (pair.Value == cpu || pair.Value == _cpuType)
268 { 299 {
269 if (pair.Value == _cpuType) 300 if (pair.Value == _cpuType)
270 flag64 = 0; 301 flag64 = 0;
271 n = pair.Name; 302 s = pair.Name;
272 break; 303 break;
273 } 304 }
274 } 305 }
275 if (!n)
276 {
277 ConvertUInt32ToString(cpu, temp);
278 n = temp;
279 }
280 s = n;
281 306
282 if (flag64 != 0) 307 if (flag64 != 0)
283 s += " 64-bit"; 308 s.Add_OptSpaced("64-bit");
284 else if ((_cpuSubType & CPU_SUBTYPE_LIB64) && _cpuType != CPU_TYPE_AMD64) 309 else if ((_cpuSubType & CPU_SUBTYPE_LIB64) && _cpuType != CPU_TYPE_AMD64)
285 s += " 64-bit-lib"; 310 s.Add_OptSpaced("64-bit-lib");
286 } 311 }
287 UInt32 t = _cpuSubType & ~(UInt32)CPU_SUBTYPE_LIB64; 312 const UInt32 t = _cpuSubType & ~(UInt32)CPU_SUBTYPE_LIB64;
288 if (t != 0 && (t != CPU_SUBTYPE_I386_ALL || cpu != CPU_TYPE_386)) 313 if (t != 0 && (t != CPU_SUBTYPE_I386_ALL || cpu != CPU_TYPE_386))
289 { 314 {
290 const char *n = NULL; 315 const char *n = NULL;
@@ -292,16 +317,14 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
292 { 317 {
293 if (t == CPU_SUBTYPE_POWERPC_970) 318 if (t == CPU_SUBTYPE_POWERPC_970)
294 n = "970"; 319 n = "970";
295 else if (t < ARRAY_SIZE(k_PowerPc_SubTypes)) 320 else if (t < Z7_ARRAY_SIZE(k_PowerPc_SubTypes))
296 n = k_PowerPc_SubTypes[t]; 321 n = k_PowerPc_SubTypes[t];
297 } 322 }
298 if (!n)
299 {
300 ConvertUInt32ToString(t, temp);
301 n = temp;
302 }
303 s.Add_Space(); 323 s.Add_Space();
304 s += n; 324 if (n)
325 s += n;
326 else
327 s.Add_UInt32(t);
305 } 328 }
306 prop = s; 329 prop = s;
307 break; 330 break;
@@ -309,8 +332,8 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
309 case kpidCharacts: 332 case kpidCharacts:
310 { 333 {
311 // TYPE_TO_PROP(g_FileTypes, _type, prop); break; 334 // TYPE_TO_PROP(g_FileTypes, _type, prop); break;
312 AString res (TypeToString(g_FileTypes, ARRAY_SIZE(g_FileTypes), _type)); 335 AString res (TypeToString(g_FileTypes, Z7_ARRAY_SIZE(g_FileTypes), _type));
313 AString s (FlagsToString(g_ArcFlags, ARRAY_SIZE(g_ArcFlags), _flags)); 336 const AString s (FlagsToString(g_ArcFlags, Z7_ARRAY_SIZE(g_ArcFlags), _flags));
314 if (!s.IsEmpty()) 337 if (!s.IsEmpty())
315 { 338 {
316 res.Add_Space(); 339 res.Add_Space();
@@ -343,16 +366,16 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
343 COM_TRY_END 366 COM_TRY_END
344} 367}
345 368
346static AString GetName(const char *name) 369static void AddName(AString &s, const char *name)
347{ 370{
348 char res[kNameSize + 1]; 371 char temp[kNameSize + 1];
349 memcpy(res, name, kNameSize); 372 memcpy(temp, name, kNameSize);
350 res[kNameSize] = 0; 373 temp[kNameSize] = 0;
351 return (AString)res; 374 s += temp;
352} 375}
353 376
354 377
355STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 378Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
356{ 379{
357 COM_TRY_BEGIN 380 COM_TRY_BEGIN
358 CPropVariant prop; 381 CPropVariant prop;
@@ -361,29 +384,75 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
361 { 384 {
362 case kpidPath: 385 case kpidPath:
363 { 386 {
364 AString s (GetName(_segments[item.SegmentIndex].Name)); 387 AString s;
388 AddName(s, _segments[item.SegmentIndex].Name);
365 if (!item.IsDummy) 389 if (!item.IsDummy)
366 s += GetName(item.Name); 390 {
391 // CSection::SegName and CSegment::Name are same in real cases.
392 // AddName(s, item.SegName);
393 AddName(s, item.Name);
394 }
367 prop = MultiByteToUnicodeString(s); 395 prop = MultiByteToUnicodeString(s);
368 break; 396 break;
369 } 397 }
370 case kpidSize: /* prop = (UInt64)item.VSize; break; */ 398 case kpidSize: /* prop = (UInt64)item.VSize; break; */
371 case kpidPackSize: prop = (UInt64)item.GetPackSize(); break; 399 case kpidPackSize: prop = (UInt64)item.GetPackSize(); break;
372 case kpidCharacts: 400 case kpidCharacts:
373 if (!item.IsDummy) 401 {
402 AString res;
374 { 403 {
375 AString res (TypeToString(g_SectTypes, ARRAY_SIZE(g_SectTypes), item.Flags & SECT_TYPE_MASK)); 404 if (!item.IsDummy)
376 AString s (FlagsToString(g_Flags, ARRAY_SIZE(g_Flags), item.Flags & SECT_ATTR_MASK));
377 if (!s.IsEmpty())
378 { 405 {
379 res.Add_Space(); 406 {
380 res += s; 407 const AString s (TypeToString(g_SectTypes, Z7_ARRAY_SIZE(g_SectTypes), item.Flags & SECT_TYPE_MASK));
408 if (!s.IsEmpty())
409 {
410 res.Add_OptSpaced("sect_type:");
411 res.Add_OptSpaced(s);
412 }
413 }
414 {
415 const AString s (FlagsToString(g_SectFlags, Z7_ARRAY_SIZE(g_SectFlags), item.Flags & SECT_ATTR_MASK));
416 if (!s.IsEmpty())
417 {
418 res.Add_OptSpaced("sect_flags:");
419 res.Add_OptSpaced(s);
420 }
421 }
422 }
423 const CSegment &seg = _segments[item.SegmentIndex];
424 {
425 const AString s (FlagsToString(g_SegmentFlags, Z7_ARRAY_SIZE(g_SegmentFlags), seg.Flags));
426 if (!s.IsEmpty())
427 {
428 res.Add_OptSpaced("seg_flags:");
429 res.Add_OptSpaced(s);
430 }
431 }
432 {
433 const AString s (FlagsToString(g_SegmentProt, Z7_ARRAY_SIZE(g_SegmentProt), seg.MaxProt));
434 if (!s.IsEmpty())
435 {
436 res.Add_OptSpaced("max_prot:");
437 res.Add_OptSpaced(s);
438 }
439 }
440 {
441 const AString s (FlagsToString(g_SegmentProt, Z7_ARRAY_SIZE(g_SegmentProt), seg.InitProt));
442 if (!s.IsEmpty())
443 {
444 res.Add_OptSpaced("init_prot:");
445 res.Add_OptSpaced(s);
446 }
381 } 447 }
382 prop = res;
383 } 448 }
449 if (!res.IsEmpty())
450 prop = res;
384 break; 451 break;
452 }
385 case kpidOffset: prop = item.Pa; break; 453 case kpidOffset: prop = item.Pa; break;
386 case kpidVa: prop = item.Va; break; 454 case kpidVa: prop = item.Va; break;
455 case kpidClusterSize: prop = (UInt32)1 << item.Align; break;
387 } 456 }
388 prop.Detach(value); 457 prop.Detach(value);
389 return S_OK; 458 return S_OK;
@@ -396,7 +465,7 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
396 const UInt32 kStartHeaderSize = 7 * 4; 465 const UInt32 kStartHeaderSize = 7 * 4;
397 466
398 Byte header[kStartHeaderSize]; 467 Byte header[kStartHeaderSize];
399 RINOK(ReadStream_FALSE(stream, header, kStartHeaderSize)); 468 RINOK(ReadStream_FALSE(stream, header, kStartHeaderSize))
400 bool be, mode64; 469 bool be, mode64;
401 switch (GetUi32(header)) 470 switch (GetUi32(header))
402 { 471 {
@@ -410,8 +479,8 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
410 _mode64 = mode64; 479 _mode64 = mode64;
411 _be = be; 480 _be = be;
412 481
413 UInt32 numCommands = Get32(header + 0x10, be); 482 const UInt32 numCommands = Get32(header + 0x10, be);
414 UInt32 commandsSize = Get32(header + 0x14, be); 483 const UInt32 commandsSize = Get32(header + 0x14, be);
415 484
416 if (numCommands == 0) 485 if (numCommands == 0)
417 return S_FALSE; 486 return S_FALSE;
@@ -443,7 +512,7 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
443 _headersSize = startHeaderSize + commandsSize; 512 _headersSize = startHeaderSize + commandsSize;
444 _totalSize = _headersSize; 513 _totalSize = _headersSize;
445 CByteArr buffer(_headersSize); 514 CByteArr buffer(_headersSize);
446 RINOK(ReadStream_FALSE(stream, buffer + kStartHeaderSize, _headersSize - kStartHeaderSize)); 515 RINOK(ReadStream_FALSE(stream, buffer + kStartHeaderSize, _headersSize - kStartHeaderSize))
447 const Byte *buf = buffer + startHeaderSize; 516 const Byte *buf = buffer + startHeaderSize;
448 size_t size = _headersSize - startHeaderSize; 517 size_t size = _headersSize - startHeaderSize;
449 for (UInt32 cmdIndex = 0; cmdIndex < numCommands; cmdIndex++) 518 for (UInt32 cmdIndex = 0; cmdIndex < numCommands; cmdIndex++)
@@ -489,6 +558,9 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
489 } 558 }
490 559
491 CSegment seg; 560 CSegment seg;
561 seg.MaxProt = Get32(buf + offs - 16, be);
562 seg.InitProt = Get32(buf + offs - 12, be);
563 seg.Flags = Get32(buf + offs - 4, be);
492 memcpy(seg.Name, buf + 8, kNameSize); 564 memcpy(seg.Name, buf + 8, kNameSize);
493 _segments.Add(seg); 565 _segments.Add(seg);
494 566
@@ -505,11 +577,12 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
505 sect.PSize = phSize; 577 sect.PSize = phSize;
506 sect.VSize = vmSize; 578 sect.VSize = vmSize;
507 sect.Pa = phAddr; 579 sect.Pa = phAddr;
580 sect.Align = 0;
508 sect.Flags = 0; 581 sect.Flags = 0;
509 } 582 }
510 else do 583 else do
511 { 584 {
512 UInt32 headSize = (cmd == CMD_SEGMENT_64) ? 0x50 : 0x44; 585 const UInt32 headSize = (cmd == CMD_SEGMENT_64) ? 0x50 : 0x44;
513 const Byte *p = buf + offs; 586 const Byte *p = buf + offs;
514 if (cmdSize - offs < headSize) 587 if (cmdSize - offs < headSize)
515 break; 588 break;
@@ -528,13 +601,16 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
528 f32Offset = 0x28; 601 f32Offset = 0x28;
529 } 602 }
530 sect.Pa = Get32(p + f32Offset, be); 603 sect.Pa = Get32(p + f32Offset, be);
531 sect.Flags = Get32(p + f32Offset + 10, be); 604 sect.Align = Get32(p + f32Offset + 4, be);
532 if (sect.Flags == SECT_ATTR_ZEROFILL) 605 // sect.reloff = Get32(p + f32Offset + 8, be);
606 // sect.nreloc = Get32(p + f32Offset + 12, be);
607 sect.Flags = Get32(p + f32Offset + 16, be);
608 if ((sect.Flags & SECT_TYPE_MASK) == SECT_ATTR_ZEROFILL)
533 sect.PSize = 0; 609 sect.PSize = 0;
534 else 610 else
535 sect.PSize = sect.VSize; 611 sect.PSize = sect.VSize;
536 memcpy(sect.Name, p, kNameSize); 612 memcpy(sect.Name, p, kNameSize);
537 memcpy(sect.SegName, p + kNameSize, kNameSize); 613 // memcpy(sect.SegName, p + kNameSize, kNameSize);
538 sect.SegmentIndex = _segments.Size() - 1; 614 sect.SegmentIndex = _segments.Size() - 1;
539 offs += headSize; 615 offs += headSize;
540 } 616 }
@@ -553,17 +629,17 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
553 return S_OK; 629 return S_OK;
554} 630}
555 631
556STDMETHODIMP CHandler::Open(IInStream *inStream, 632Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
557 const UInt64 * /* maxCheckStartPosition */, 633 const UInt64 * /* maxCheckStartPosition */,
558 IArchiveOpenCallback * /* openArchiveCallback */) 634 IArchiveOpenCallback * /* openArchiveCallback */))
559{ 635{
560 COM_TRY_BEGIN 636 COM_TRY_BEGIN
561 Close(); 637 Close();
562 RINOK(Open2(inStream)); 638 RINOK(Open2(inStream))
563 if (!_allowTail) 639 if (!_allowTail)
564 { 640 {
565 UInt64 fileSize; 641 UInt64 fileSize;
566 RINOK(inStream->Seek(0, STREAM_SEEK_END, &fileSize)); 642 RINOK(InStream_GetSize_SeekToEnd(inStream, fileSize))
567 if (fileSize > _totalSize) 643 if (fileSize > _totalSize)
568 return S_FALSE; 644 return S_FALSE;
569 } 645 }
@@ -572,7 +648,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
572 COM_TRY_END 648 COM_TRY_END
573} 649}
574 650
575STDMETHODIMP CHandler::Close() 651Z7_COM7F_IMF(CHandler::Close())
576{ 652{
577 _totalSize = 0; 653 _totalSize = 0;
578 _inStream.Release(); 654 _inStream.Release();
@@ -581,17 +657,17 @@ STDMETHODIMP CHandler::Close()
581 return S_OK; 657 return S_OK;
582} 658}
583 659
584STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 660Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
585{ 661{
586 *numItems = _sections.Size(); 662 *numItems = _sections.Size();
587 return S_OK; 663 return S_OK;
588} 664}
589 665
590STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 666Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
591 Int32 testMode, IArchiveExtractCallback *extractCallback) 667 Int32 testMode, IArchiveExtractCallback *extractCallback))
592{ 668{
593 COM_TRY_BEGIN 669 COM_TRY_BEGIN
594 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 670 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
595 if (allFilesMode) 671 if (allFilesMode)
596 numItems = _sections.Size(); 672 numItems = _sections.Size();
597 if (numItems == 0) 673 if (numItems == 0)
@@ -619,33 +695,33 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
619 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) 695 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
620 { 696 {
621 lps->InSize = lps->OutSize = currentTotalSize; 697 lps->InSize = lps->OutSize = currentTotalSize;
622 RINOK(lps->SetCur()); 698 RINOK(lps->SetCur())
623 Int32 askMode = testMode ? 699 const Int32 askMode = testMode ?
624 NExtract::NAskMode::kTest : 700 NExtract::NAskMode::kTest :
625 NExtract::NAskMode::kExtract; 701 NExtract::NAskMode::kExtract;
626 UInt32 index = allFilesMode ? i : indices[i]; 702 const UInt32 index = allFilesMode ? i : indices[i];
627 const CSection &item = _sections[index]; 703 const CSection &item = _sections[index];
628 currentItemSize = item.GetPackSize(); 704 currentItemSize = item.GetPackSize();
629 705
630 CMyComPtr<ISequentialOutStream> outStream; 706 CMyComPtr<ISequentialOutStream> outStream;
631 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 707 RINOK(extractCallback->GetStream(index, &outStream, askMode))
632 if (!testMode && !outStream) 708 if (!testMode && !outStream)
633 continue; 709 continue;
634 710
635 RINOK(extractCallback->PrepareOperation(askMode)); 711 RINOK(extractCallback->PrepareOperation(askMode))
636 RINOK(_inStream->Seek(item.Pa, STREAM_SEEK_SET, NULL)); 712 RINOK(InStream_SeekSet(_inStream, item.Pa))
637 streamSpec->Init(currentItemSize); 713 streamSpec->Init(currentItemSize);
638 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 714 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
639 outStream.Release(); 715 outStream.Release();
640 RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ? 716 RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ?
641 NExtract::NOperationResult::kOK: 717 NExtract::NOperationResult::kOK:
642 NExtract::NOperationResult::kDataError)); 718 NExtract::NOperationResult::kDataError))
643 } 719 }
644 return S_OK; 720 return S_OK;
645 COM_TRY_END 721 COM_TRY_END
646} 722}
647 723
648STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 724Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail))
649{ 725{
650 _allowTail = IntToBool(allowTail); 726 _allowTail = IntToBool(allowTail);
651 return S_OK; 727 return S_OK;
@@ -658,7 +734,7 @@ static const Byte k_Signature[] = {
658 4, 0xFE, 0xED, 0xFA, 0xCF }; 734 4, 0xFE, 0xED, 0xFA, 0xCF };
659 735
660REGISTER_ARC_I( 736REGISTER_ARC_I(
661 "MachO", "macho", 0, 0xDF, 737 "MachO", "macho", NULL, 0xDF,
662 k_Signature, 738 k_Signature,
663 0, 739 0,
664 NArcInfoFlags::kMultiSignature | 740 NArcInfoFlags::kMultiSignature |
diff --git a/CPP/7zip/Archive/MbrHandler.cpp b/CPP/7zip/Archive/MbrHandler.cpp
index 026696f..0d3611b 100644
--- a/CPP/7zip/Archive/MbrHandler.cpp
+++ b/CPP/7zip/Archive/MbrHandler.cpp
@@ -54,7 +54,7 @@ struct CChs
54 54
55// Chs in some MBRs contains only low bits of "Cyl number". So we disable check. 55// Chs in some MBRs contains only low bits of "Cyl number". So we disable check.
56/* 56/*
57#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 57#define RINOZ(x) { int _t_ = (x); if (_t_ != 0) return _t_; }
58static int CompareChs(const CChs &c1, const CChs &c2) 58static int CompareChs(const CChs &c1, const CChs &c2)
59{ 59{
60 RINOZ(MyCompare(c1.GetCyl(), c2.GetCyl())); 60 RINOZ(MyCompare(c1.GetCyl(), c2.GetCyl()));
@@ -67,9 +67,9 @@ void CChs::ToString(NCOM::CPropVariant &prop) const
67{ 67{
68 AString s; 68 AString s;
69 s.Add_UInt32(GetCyl()); 69 s.Add_UInt32(GetCyl());
70 s += '-'; 70 s.Add_Minus();
71 s.Add_UInt32(Head); 71 s.Add_UInt32(Head);
72 s += '-'; 72 s.Add_Minus();
73 s.Add_UInt32(GetSector()); 73 s.Add_UInt32(GetSector());
74 prop = s; 74 prop = s;
75} 75}
@@ -132,17 +132,25 @@ struct CPartType
132 132
133#define kFat "fat" 133#define kFat "fat"
134 134
135/*
136if we use "format" command in Windows 10 for existing partition:
137 - if we format to ExFAT, it sets type=7
138 - if we format to UDF, it doesn't change type from previous value.
139*/
140
141static const unsigned kType_Windows_NTFS = 7;
142
135static const CPartType kPartTypes[] = 143static const CPartType kPartTypes[] =
136{ 144{
137 { 0x01, kFat, "FAT12" }, 145 { 0x01, kFat, "FAT12" },
138 { 0x04, kFat, "FAT16 DOS 3.0+" }, 146 { 0x04, kFat, "FAT16 DOS 3.0+" },
139 { 0x05, 0, "Extended" }, 147 { 0x05, NULL, "Extended" },
140 { 0x06, kFat, "FAT16 DOS 3.31+" }, 148 { 0x06, kFat, "FAT16 DOS 3.31+" },
141 { 0x07, "ntfs", "NTFS" }, 149 { 0x07, "ntfs", "NTFS" },
142 { 0x0B, kFat, "FAT32" }, 150 { 0x0B, kFat, "FAT32" },
143 { 0x0C, kFat, "FAT32-LBA" }, 151 { 0x0C, kFat, "FAT32-LBA" },
144 { 0x0E, kFat, "FAT16-LBA" }, 152 { 0x0E, kFat, "FAT16-LBA" },
145 { 0x0F, 0, "Extended-LBA" }, 153 { 0x0F, NULL, "Extended-LBA" },
146 { 0x11, kFat, "FAT12-Hidden" }, 154 { 0x11, kFat, "FAT12-Hidden" },
147 { 0x14, kFat, "FAT16-Hidden < 32 MB" }, 155 { 0x14, kFat, "FAT16-Hidden < 32 MB" },
148 { 0x16, kFat, "FAT16-Hidden >= 32 MB" }, 156 { 0x16, kFat, "FAT16-Hidden >= 32 MB" },
@@ -150,23 +158,23 @@ static const CPartType kPartTypes[] =
150 { 0x1C, kFat, "FAT32-LBA-Hidden" }, 158 { 0x1C, kFat, "FAT32-LBA-Hidden" },
151 { 0x1E, kFat, "FAT16-LBA-WIN95-Hidden" }, 159 { 0x1E, kFat, "FAT16-LBA-WIN95-Hidden" },
152 { 0x27, "ntfs", "NTFS-WinRE" }, 160 { 0x27, "ntfs", "NTFS-WinRE" },
153 { 0x82, 0, "Solaris x86 / Linux swap" }, 161 { 0x82, NULL, "Solaris x86 / Linux swap" },
154 { 0x83, 0, "Linux" }, 162 { 0x83, NULL, "Linux" },
155 { 0x8E, "lvm", "Linux LVM" }, 163 { 0x8E, "lvm", "Linux LVM" },
156 { 0xA5, 0, "BSD slice" }, 164 { 0xA5, NULL, "BSD slice" },
157 { 0xBE, 0, "Solaris 8 boot" }, 165 { 0xBE, NULL, "Solaris 8 boot" },
158 { 0xBF, 0, "New Solaris x86" }, 166 { 0xBF, NULL, "New Solaris x86" },
159 { 0xC2, 0, "Linux-Hidden" }, 167 { 0xC2, NULL, "Linux-Hidden" },
160 { 0xC3, 0, "Linux swap-Hidden" }, 168 { 0xC3, NULL, "Linux swap-Hidden" },
161 { 0xEE, 0, "GPT" }, 169 { 0xEE, NULL, "GPT" },
162 { 0xEE, 0, "EFI" } 170 { 0xEE, NULL, "EFI" }
163}; 171};
164 172
165static int FindPartType(UInt32 type) 173static int FindPartType(UInt32 type)
166{ 174{
167 for (unsigned i = 0; i < ARRAY_SIZE(kPartTypes); i++) 175 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kPartTypes); i++)
168 if (kPartTypes[i].Id == type) 176 if (kPartTypes[i].Id == type)
169 return i; 177 return (int)i;
170 return -1; 178 return -1;
171} 179}
172 180
@@ -174,17 +182,27 @@ struct CItem
174{ 182{
175 bool IsReal; 183 bool IsReal;
176 bool IsPrim; 184 bool IsPrim;
185 bool WasParsed;
186 const char *FileSystem;
177 UInt64 Size; 187 UInt64 Size;
178 CPartition Part; 188 CPartition Part;
189
190 CItem():
191 WasParsed(false),
192 FileSystem(NULL)
193 {}
179}; 194};
180 195
181class CHandler: public CHandlerCont 196
197Z7_class_CHandler_final: public CHandlerCont
182{ 198{
199 Z7_IFACE_COM7_IMP(IInArchive_Cont)
200
183 CObjectVector<CItem> _items; 201 CObjectVector<CItem> _items;
184 UInt64 _totalSize; 202 UInt64 _totalSize;
185 CByteBuffer _buffer; 203 CByteBuffer _buffer;
186 204
187 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const 205 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override Z7_final
188 { 206 {
189 const CItem &item = _items[index]; 207 const CItem &item = _items[index];
190 pos = item.Part.GetPos(); 208 pos = item.Part.GetPos();
@@ -193,8 +211,6 @@ class CHandler: public CHandlerCont
193 } 211 }
194 212
195 HRESULT ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level); 213 HRESULT ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level);
196public:
197 INTERFACE_IInArchive_Cont(;)
198}; 214};
199 215
200HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level) 216HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsigned level)
@@ -212,8 +228,8 @@ HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsi
212 UInt64 newPos = (UInt64)lba << 9; 228 UInt64 newPos = (UInt64)lba << 9;
213 if (newPos + 512 > _totalSize) 229 if (newPos + 512 > _totalSize)
214 return S_FALSE; 230 return S_FALSE;
215 RINOK(stream->Seek(newPos, STREAM_SEEK_SET, NULL)); 231 RINOK(InStream_SeekSet(stream, newPos))
216 RINOK(ReadStream_FALSE(stream, buf, kSectorSize)); 232 RINOK(ReadStream_FALSE(stream, buf, kSectorSize))
217 233
218 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) 234 if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA)
219 return S_FALSE; 235 return S_FALSE;
@@ -293,14 +309,87 @@ HRESULT CHandler::ReadTables(IInStream *stream, UInt32 baseLba, UInt32 lba, unsi
293 return S_OK; 309 return S_OK;
294} 310}
295 311
296STDMETHODIMP CHandler::Open(IInStream *stream, 312
313static bool Is_Ntfs(const Byte *p)
314{
315 if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA)
316 return false;
317 // int codeOffset = 0;
318 switch (p[0])
319 {
320 case 0xE9: /* codeOffset = 3 + (Int16)Get16(p + 1); */ break;
321 case 0xEB: if (p[2] != 0x90) return false; /* codeOffset = 2 + (int)(signed char)p[1]; */ break;
322 default: return false;
323 }
324 return memcmp(p + 3, "NTFS ", 8) == 0;
325}
326
327static bool Is_ExFat(const Byte *p)
328{
329 if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA)
330 return false;
331 if (p[0] != 0xEB || p[1] != 0x76 || p[2] != 0x90)
332 return false;
333 return memcmp(p + 3, "EXFAT ", 8) == 0;
334}
335
336static bool AllAreZeros(const Byte *p, size_t size)
337{
338 for (size_t i = 0; i < size; i++)
339 if (p[i] != 0)
340 return false;
341 return true;
342}
343
344static const UInt32 k_Udf_StartPos = 0x8000;
345static const Byte k_Udf_Signature[] = { 0, 'B', 'E', 'A', '0', '1', 1, 0 };
346
347static bool Is_Udf(const Byte *p)
348{
349 return memcmp(p + k_Udf_StartPos, k_Udf_Signature, sizeof(k_Udf_Signature)) == 0;
350}
351
352
353static const char *GetFileSystem(
354 ISequentialInStream *stream, UInt64 partitionSize)
355{
356 const size_t kHeaderSize = 1 << 9;
357 if (partitionSize >= kHeaderSize)
358 {
359 Byte buf[kHeaderSize];
360 if (ReadStream_FAIL(stream, buf, kHeaderSize) == S_OK)
361 {
362 // NTFS is expected default filesystem for (Type == 7)
363 if (Is_Ntfs(buf))
364 return "NTFS";
365 if (Is_ExFat(buf))
366 return "exFAT";
367 const size_t kHeaderSize2 = k_Udf_StartPos + (1 << 9);
368 if (partitionSize >= kHeaderSize2)
369 {
370 if (AllAreZeros(buf, kHeaderSize))
371 {
372 CByteBuffer buffer(kHeaderSize2);
373 // memcpy(buffer, buf, kHeaderSize);
374 if (ReadStream_FAIL(stream, buffer + kHeaderSize, kHeaderSize2 - kHeaderSize) == S_OK)
375 if (Is_Udf(buffer))
376 return "UDF";
377 }
378 }
379 }
380 }
381 return NULL;
382}
383
384
385Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
297 const UInt64 * /* maxCheckStartPosition */, 386 const UInt64 * /* maxCheckStartPosition */,
298 IArchiveOpenCallback * /* openArchiveCallback */) 387 IArchiveOpenCallback * /* openArchiveCallback */))
299{ 388{
300 COM_TRY_BEGIN 389 COM_TRY_BEGIN
301 Close(); 390 Close();
302 RINOK(stream->Seek(0, STREAM_SEEK_END, &_totalSize)); 391 RINOK(InStream_GetSize_SeekToEnd(stream, _totalSize))
303 RINOK(ReadTables(stream, 0, 0, 0)); 392 RINOK(ReadTables(stream, 0, 0, 0))
304 if (_items.IsEmpty()) 393 if (_items.IsEmpty())
305 return S_FALSE; 394 return S_FALSE;
306 UInt32 lbaLimit = _items.Back().Part.GetLimit(); 395 UInt32 lbaLimit = _items.Back().Part.GetLimit();
@@ -313,12 +402,25 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
313 n.IsReal = false; 402 n.IsReal = false;
314 _items.Add(n); 403 _items.Add(n);
315 } 404 }
405
406 FOR_VECTOR (i, _items)
407 {
408 CItem &item = _items[i];
409 if (item.Part.Type != kType_Windows_NTFS)
410 continue;
411 if (InStream_SeekSet(stream, item.Part.GetPos()) != S_OK)
412 continue;
413 item.FileSystem = GetFileSystem(stream, item.Size);
414 item.WasParsed = true;
415 }
416
316 _stream = stream; 417 _stream = stream;
317 return S_OK; 418 return S_OK;
318 COM_TRY_END 419 COM_TRY_END
319} 420}
320 421
321STDMETHODIMP CHandler::Close() 422
423Z7_COM7F_IMF(CHandler::Close())
322{ 424{
323 _totalSize = 0; 425 _totalSize = 0;
324 _items.Clear(); 426 _items.Clear();
@@ -326,6 +428,7 @@ STDMETHODIMP CHandler::Close()
326 return S_OK; 428 return S_OK;
327} 429}
328 430
431
329enum 432enum
330{ 433{
331 kpidPrimary = kpidUserDefined, 434 kpidPrimary = kpidUserDefined,
@@ -347,7 +450,7 @@ static const CStatProp kProps[] =
347IMP_IInArchive_Props_WITH_NAME 450IMP_IInArchive_Props_WITH_NAME
348IMP_IInArchive_ArcProps_NO_Table 451IMP_IInArchive_ArcProps_NO_Table
349 452
350STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 453Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
351{ 454{
352 NCOM::CPropVariant prop; 455 NCOM::CPropVariant prop;
353 switch (propID) 456 switch (propID)
@@ -363,10 +466,10 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
363 mainIndex = -1; 466 mainIndex = -1;
364 break; 467 break;
365 } 468 }
366 mainIndex = i; 469 mainIndex = (int)i;
367 } 470 }
368 if (mainIndex >= 0) 471 if (mainIndex >= 0)
369 prop = (UInt32)mainIndex; 472 prop = (UInt32)(Int32)mainIndex;
370 break; 473 break;
371 } 474 }
372 case kpidPhySize: prop = _totalSize; break; 475 case kpidPhySize: prop = _totalSize; break;
@@ -375,13 +478,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
375 return S_OK; 478 return S_OK;
376} 479}
377 480
378STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 481Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
379{ 482{
380 *numItems = _items.Size(); 483 *numItems = _items.Size();
381 return S_OK; 484 return S_OK;
382} 485}
383 486
384STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 487Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
385{ 488{
386 COM_TRY_BEGIN 489 COM_TRY_BEGIN
387 NCOM::CPropVariant prop; 490 NCOM::CPropVariant prop;
@@ -396,11 +499,21 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
396 s.Add_UInt32(index); 499 s.Add_UInt32(index);
397 if (item.IsReal) 500 if (item.IsReal)
398 { 501 {
399 s += '.'; 502 s.Add_Dot();
400 const char *ext = NULL; 503 const char *ext = NULL;
401 int typeIndex = FindPartType(part.Type); 504 if (item.FileSystem)
402 if (typeIndex >= 0) 505 {
403 ext = kPartTypes[(unsigned)typeIndex].Ext; 506 ext = "";
507 AString fs (item.FileSystem);
508 fs.MakeLower_Ascii();
509 s += fs;
510 }
511 else if (!item.WasParsed)
512 {
513 const int typeIndex = FindPartType(part.Type);
514 if (typeIndex >= 0)
515 ext = kPartTypes[(unsigned)typeIndex].Ext;
516 }
404 if (!ext) 517 if (!ext)
405 ext = "img"; 518 ext = "img";
406 s += ext; 519 s += ext;
@@ -414,9 +527,18 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
414 char s[32]; 527 char s[32];
415 ConvertUInt32ToString(part.Type, s); 528 ConvertUInt32ToString(part.Type, s);
416 const char *res = s; 529 const char *res = s;
417 int typeIndex = FindPartType(part.Type); 530 if (item.FileSystem)
418 if (typeIndex >= 0 && kPartTypes[(unsigned)typeIndex].Name) 531 {
419 res = kPartTypes[(unsigned)typeIndex].Name; 532 // strcat(s, "-");
533 // strcpy(s, item.FileSystem);
534 res = item.FileSystem;
535 }
536 else if (!item.WasParsed)
537 {
538 const int typeIndex = FindPartType(part.Type);
539 if (typeIndex >= 0 && kPartTypes[(unsigned)typeIndex].Name)
540 res = kPartTypes[(unsigned)typeIndex].Name;
541 }
420 prop = res; 542 prop = res;
421 } 543 }
422 break; 544 break;
@@ -437,7 +559,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
437 // 2, { 0x55, 0x1FF }, 559 // 2, { 0x55, 0x1FF },
438 560
439REGISTER_ARC_I_NO_SIG( 561REGISTER_ARC_I_NO_SIG(
440 "MBR", "mbr", 0, 0xDB, 562 "MBR", "mbr", NULL, 0xDB,
441 0, 563 0,
442 NArcInfoFlags::kPureStartOpen, 564 NArcInfoFlags::kPureStartOpen,
443 NULL) 565 NULL)
diff --git a/CPP/7zip/Archive/MslzHandler.cpp b/CPP/7zip/Archive/MslzHandler.cpp
index 6f9057a..04549f8 100644
--- a/CPP/7zip/Archive/MslzHandler.cpp
+++ b/CPP/7zip/Archive/MslzHandler.cpp
@@ -21,11 +21,9 @@ namespace NMslz {
21 21
22static const UInt32 kUnpackSizeMax = 0xFFFFFFE0; 22static const UInt32 kUnpackSizeMax = 0xFFFFFFE0;
23 23
24class CHandler: 24Z7_CLASS_IMP_CHandler_IInArchive_1(
25 public IInArchive, 25 IArchiveOpenSeq
26 public IArchiveOpenSeq, 26)
27 public CMyUnknownImp
28{
29 CMyComPtr<IInStream> _inStream; 27 CMyComPtr<IInStream> _inStream;
30 CMyComPtr<ISequentialInStream> _seqStream; 28 CMyComPtr<ISequentialInStream> _seqStream;
31 29
@@ -43,10 +41,6 @@ class CHandler:
43 UString _name; 41 UString _name;
44 42
45 void ParseName(Byte replaceByte, IArchiveOpenCallback *callback); 43 void ParseName(Byte replaceByte, IArchiveOpenCallback *callback);
46public:
47 MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq)
48 INTERFACE_IInArchive(;)
49 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
50}; 44};
51 45
52static const Byte kProps[] = 46static const Byte kProps[] =
@@ -59,13 +53,13 @@ static const Byte kProps[] =
59IMP_IInArchive_Props 53IMP_IInArchive_Props
60IMP_IInArchive_ArcProps_NO_Table 54IMP_IInArchive_ArcProps_NO_Table
61 55
62STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 56Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
63{ 57{
64 *numItems = 1; 58 *numItems = 1;
65 return S_OK; 59 return S_OK;
66} 60}
67 61
68STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 62Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
69{ 63{
70 COM_TRY_BEGIN 64 COM_TRY_BEGIN
71 NWindows::NCOM::CPropVariant prop; 65 NWindows::NCOM::CPropVariant prop;
@@ -77,7 +71,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
77 case kpidErrorFlags: 71 case kpidErrorFlags:
78 { 72 {
79 UInt32 v = 0; 73 UInt32 v = 0;
80 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 74 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
81 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd; 75 if (_needMoreInput) v |= kpv_ErrorFlags_UnexpectedEnd;
82 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd; 76 if (_dataAfterEnd) v |= kpv_ErrorFlags_DataAfterEnd;
83 prop = v; 77 prop = v;
@@ -89,7 +83,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
89} 83}
90 84
91 85
92STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 86Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
93{ 87{
94 COM_TRY_BEGIN 88 COM_TRY_BEGIN
95 NWindows::NCOM::CPropVariant prop; 89 NWindows::NCOM::CPropVariant prop;
@@ -125,8 +119,7 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback)
125{ 119{
126 if (!callback) 120 if (!callback)
127 return; 121 return;
128 CMyComPtr<IArchiveOpenVolumeCallback> volumeCallback; 122 Z7_DECL_CMyComPtr_QI_FROM(IArchiveOpenVolumeCallback, volumeCallback, callback)
129 callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&volumeCallback);
130 if (!volumeCallback) 123 if (!volumeCallback)
131 return; 124 return;
132 125
@@ -146,13 +139,13 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback)
146 { 139 {
147 if (s.Len() < 3 || s[s.Len() - 3] != '.') 140 if (s.Len() < 3 || s[s.Len() - 3] != '.')
148 return; 141 return;
149 for (unsigned i = 0; i < ARRAY_SIZE(g_Exts); i++) 142 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Exts); i++)
150 { 143 {
151 const char *ext = g_Exts[i]; 144 const char *ext = g_Exts[i];
152 if (s[s.Len() - 2] == (Byte)ext[0] && 145 if (s[s.Len() - 2] == (Byte)ext[0] &&
153 s[s.Len() - 1] == (Byte)ext[1]) 146 s[s.Len() - 1] == (Byte)ext[1])
154 { 147 {
155 replaceByte = ext[2]; 148 replaceByte = (Byte)ext[2];
156 break; 149 break;
157 } 150 }
158 } 151 }
@@ -162,21 +155,21 @@ void CHandler::ParseName(Byte replaceByte, IArchiveOpenCallback *callback)
162 _name += (char)replaceByte; 155 _name += (char)replaceByte;
163} 156}
164 157
165STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, 158Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPosition */,
166 IArchiveOpenCallback *callback) 159 IArchiveOpenCallback *callback))
167{ 160{
168 COM_TRY_BEGIN 161 COM_TRY_BEGIN
169 { 162 {
170 Close(); 163 Close();
171 _needSeekToStart = true; 164 _needSeekToStart = true;
172 Byte buffer[kHeaderSize]; 165 Byte buffer[kHeaderSize];
173 RINOK(ReadStream_FALSE(stream, buffer, kHeaderSize)); 166 RINOK(ReadStream_FALSE(stream, buffer, kHeaderSize))
174 if (memcmp(buffer, kSignature, kSignatureSize) != 0) 167 if (memcmp(buffer, kSignature, kSignatureSize) != 0)
175 return S_FALSE; 168 return S_FALSE;
176 _unpackSize = GetUi32(buffer + 10); 169 _unpackSize = GetUi32(buffer + 10);
177 if (_unpackSize > kUnpackSizeMax) 170 if (_unpackSize > kUnpackSizeMax)
178 return S_FALSE; 171 return S_FALSE;
179 RINOK(stream->Seek(0, STREAM_SEEK_END, &_originalFileSize)); 172 RINOK(InStream_GetSize_SeekToEnd(stream, _originalFileSize))
180 _packSize = _originalFileSize; 173 _packSize = _originalFileSize;
181 174
182 ParseName(buffer[kSignatureSize], callback); 175 ParseName(buffer[kSignatureSize], callback);
@@ -190,7 +183,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 * /* maxCheckStartPo
190 COM_TRY_END 183 COM_TRY_END
191} 184}
192 185
193STDMETHODIMP CHandler::Close() 186Z7_COM7F_IMF(CHandler::Close())
194{ 187{
195 _originalFileSize = 0; 188 _originalFileSize = 0;
196 _packSize = 0; 189 _packSize = 0;
@@ -276,11 +269,11 @@ static HRESULT MslzDec(CInBuffer &inStream, ISequentialOutStream *outStream, UIn
276 } 269 }
277 270
278 if (outStream) 271 if (outStream)
279 RINOK(WriteStream(outStream, buf, dest & kMask)); 272 RINOK(WriteStream(outStream, buf, dest & kMask))
280 return S_OK; 273 return S_OK;
281} 274}
282 275
283STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 276Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
284{ 277{
285 COM_TRY_BEGIN 278 COM_TRY_BEGIN
286 Close(); 279 Close();
@@ -290,8 +283,8 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
290 COM_TRY_END 283 COM_TRY_END
291} 284}
292 285
293STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 286Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
294 Int32 testMode, IArchiveExtractCallback *extractCallback) 287 Int32 testMode, IArchiveExtractCallback *extractCallback))
295{ 288{
296 COM_TRY_BEGIN 289 COM_TRY_BEGIN
297 if (numItems == 0) 290 if (numItems == 0)
@@ -302,10 +295,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
302 // extractCallback->SetTotal(_unpackSize); 295 // extractCallback->SetTotal(_unpackSize);
303 296
304 CMyComPtr<ISequentialOutStream> realOutStream; 297 CMyComPtr<ISequentialOutStream> realOutStream;
305 Int32 askMode = testMode ? 298 const Int32 askMode = testMode ?
306 NExtract::NAskMode::kTest : 299 NExtract::NAskMode::kTest :
307 NExtract::NAskMode::kExtract; 300 NExtract::NAskMode::kExtract;
308 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 301 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
309 if (!testMode && !realOutStream) 302 if (!testMode && !realOutStream)
310 return S_OK; 303 return S_OK;
311 304
@@ -325,7 +318,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
325 { 318 {
326 if (!_inStream) 319 if (!_inStream)
327 return E_FAIL; 320 return E_FAIL;
328 RINOK(_inStream->Seek(0, STREAM_SEEK_SET, NULL)); 321 RINOK(InStream_SeekToBegin(_inStream))
329 } 322 }
330 else 323 else
331 _needSeekToStart = true; 324 _needSeekToStart = true;
@@ -388,7 +381,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
388} 381}
389 382
390REGISTER_ARC_I( 383REGISTER_ARC_I(
391 "MsLZ", "mslz", 0, 0xD5, 384 "MsLZ", "mslz", NULL, 0xD5,
392 kSignature, 385 kSignature,
393 0, 386 0,
394 0, 387 0,
diff --git a/CPP/7zip/Archive/MubHandler.cpp b/CPP/7zip/Archive/MubHandler.cpp
index c790265..7363b1b 100644
--- a/CPP/7zip/Archive/MubHandler.cpp
+++ b/CPP/7zip/Archive/MubHandler.cpp
@@ -3,6 +3,7 @@
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/CpuArch.h" 5#include "../../../C/CpuArch.h"
6#include "../../../C/SwapBytes.h"
6 7
7#include "../../Common/ComTry.h" 8#include "../../Common/ComTry.h"
8#include "../../Common/IntToString.h" 9#include "../../Common/IntToString.h"
@@ -15,15 +16,13 @@
15 16
16#include "HandlerCont.h" 17#include "HandlerCont.h"
17 18
18static UInt32 Get32(const Byte *p, bool be) { if (be) return GetBe32(p); return GetUi32(p); }
19
20using namespace NWindows; 19using namespace NWindows;
21using namespace NCOM; 20using namespace NCOM;
22 21
23namespace NArchive { 22namespace NArchive {
24namespace NMub { 23namespace NMub {
25 24
26#define MACH_CPU_ARCH_ABI64 (1 << 24) 25#define MACH_CPU_ARCH_ABI64 ((UInt32)1 << 24)
27#define MACH_CPU_TYPE_386 7 26#define MACH_CPU_TYPE_386 7
28#define MACH_CPU_TYPE_ARM 12 27#define MACH_CPU_TYPE_ARM 12
29#define MACH_CPU_TYPE_SPARC 14 28#define MACH_CPU_TYPE_SPARC 14
@@ -43,13 +42,15 @@ struct CItem
43 UInt32 SubType; 42 UInt32 SubType;
44 UInt32 Offset; 43 UInt32 Offset;
45 UInt32 Size; 44 UInt32 Size;
46 // UInt32 Align; 45 UInt32 Align;
47}; 46};
48 47
49static const UInt32 kNumFilesMax = 10; 48static const UInt32 kNumFilesMax = 6;
50 49
51class CHandler: public CHandlerCont 50Z7_class_CHandler_final: public CHandlerCont
52{ 51{
52 Z7_IFACE_COM7_IMP(IInArchive_Cont)
53
53 // UInt64 _startPos; 54 // UInt64 _startPos;
54 UInt64 _phySize; 55 UInt64 _phySize;
55 UInt32 _numItems; 56 UInt32 _numItems;
@@ -58,16 +59,13 @@ class CHandler: public CHandlerCont
58 59
59 HRESULT Open2(IInStream *stream); 60 HRESULT Open2(IInStream *stream);
60 61
61 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const 62 virtual int GetItem_ExtractInfo(UInt32 index, UInt64 &pos, UInt64 &size) const Z7_override
62 { 63 {
63 const CItem &item = _items[index]; 64 const CItem &item = _items[index];
64 pos = item.Offset; 65 pos = item.Offset;
65 size = item.Size; 66 size = item.Size;
66 return NExtract::NOperationResult::kOK; 67 return NExtract::NOperationResult::kOK;
67 } 68 }
68
69public:
70 INTERFACE_IInArchive_Cont(;)
71}; 69};
72 70
73static const Byte kArcProps[] = 71static const Byte kArcProps[] =
@@ -77,13 +75,16 @@ static const Byte kArcProps[] =
77 75
78static const Byte kProps[] = 76static const Byte kProps[] =
79{ 77{
80 kpidSize 78 kpidPath,
79 kpidSize,
80 kpidOffset,
81 kpidClusterSize // Align
81}; 82};
82 83
83IMP_IInArchive_Props 84IMP_IInArchive_Props
84IMP_IInArchive_ArcProps 85IMP_IInArchive_ArcProps
85 86
86STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 87Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
87{ 88{
88 PropVariant_Clear(value); 89 PropVariant_Clear(value);
89 switch (propID) 90 switch (propID)
@@ -94,7 +95,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
94 return S_OK; 95 return S_OK;
95} 96}
96 97
97STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 98Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
98{ 99{
99 PropVariant_Clear(value); 100 PropVariant_Clear(value);
100 const CItem &item = _items[index]; 101 const CItem &item = _items[index];
@@ -103,7 +104,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
103 case kpidExtension: 104 case kpidExtension:
104 { 105 {
105 char temp[32]; 106 char temp[32];
106 const char *ext = 0; 107 const char *ext = NULL;
107 switch (item.Type) 108 switch (item.Type)
108 { 109 {
109 case MACH_CPU_TYPE_386: ext = "x86"; break; 110 case MACH_CPU_TYPE_386: ext = "x86"; break;
@@ -117,13 +118,13 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
117 temp[0] = 'c'; 118 temp[0] = 'c';
118 temp[1] = 'p'; 119 temp[1] = 'p';
119 temp[2] = 'u'; 120 temp[2] = 'u';
120 ConvertUInt32ToString(item.Type & ~MACH_CPU_ARCH_ABI64, temp + 3); 121 char *p = ConvertUInt32ToString(item.Type & ~MACH_CPU_ARCH_ABI64, temp + 3);
121 if (item.Type & MACH_CPU_ARCH_ABI64) 122 if (item.Type & MACH_CPU_ARCH_ABI64)
122 MyStringCopy(temp + MyStringLen(temp), "_64"); 123 MyStringCopy(p, "_64");
123 break; 124 break;
124 } 125 }
125 if (ext) 126 if (ext)
126 strcpy(temp, ext); 127 MyStringCopy(temp, ext);
127 if (item.SubType != 0) 128 if (item.SubType != 0)
128 if ((item.Type != MACH_CPU_TYPE_386 && 129 if ((item.Type != MACH_CPU_TYPE_386 &&
129 item.Type != MACH_CPU_TYPE_AMD64) 130 item.Type != MACH_CPU_TYPE_AMD64)
@@ -140,32 +141,45 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
140 case kpidPackSize: 141 case kpidPackSize:
141 PropVarEm_Set_UInt64(value, item.Size); 142 PropVarEm_Set_UInt64(value, item.Size);
142 break; 143 break;
144 case kpidOffset:
145 PropVarEm_Set_UInt64(value, item.Offset);
146 break;
147 case kpidClusterSize:
148 PropVarEm_Set_UInt32(value, (UInt32)1 << item.Align);
149 break;
143 } 150 }
144 return S_OK; 151 return S_OK;
145} 152}
146 153
147HRESULT CHandler::Open2(IInStream *stream) 154HRESULT CHandler::Open2(IInStream *stream)
148{ 155{
149 // RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_startPos)); 156 // RINOK(InStream_GetPos(stream, _startPos));
150 157
151 const UInt32 kHeaderSize = 8; 158 const UInt32 kHeaderSize = 2;
152 const UInt32 kRecordSize = 5 * 4; 159 const UInt32 kRecordSize = 5;
153 const UInt32 kBufSize = kHeaderSize + kNumFilesMax * kRecordSize; 160 const UInt32 kBufSize = kHeaderSize + kNumFilesMax * kRecordSize;
154 Byte buf[kBufSize]; 161 UInt32 buf[kBufSize];
155 size_t processed = kBufSize; 162 size_t processed = kBufSize * 4;
156 RINOK(ReadStream(stream, buf, &processed)); 163 RINOK(ReadStream(stream, buf, &processed))
164 processed >>= 2;
157 if (processed < kHeaderSize) 165 if (processed < kHeaderSize)
158 return S_FALSE; 166 return S_FALSE;
159 167
160 bool be; 168 bool be;
161 switch (GetBe32(buf)) 169 switch (buf[0])
162 { 170 {
163 case 0xCAFEBABE: be = true; break; 171 case Z7_CONV_BE_TO_NATIVE_CONST32(0xCAFEBABE): be = true; break;
164 case 0xB9FAF10E: be = false; break; 172 case Z7_CONV_BE_TO_NATIVE_CONST32(0xB9FAF10E): be = false; break;
165 default: return S_FALSE; 173 default: return S_FALSE;
166 } 174 }
167 _bigEndian = be; 175 _bigEndian = be;
168 UInt32 num = Get32(buf + 4, be); 176 if (
177 #if defined(MY_CPU_BE)
178 !
179 #endif
180 be)
181 z7_SwapBytes4(&buf[1], processed - 1);
182 const UInt32 num = buf[1];
169 if (num > kNumFilesMax || processed < kHeaderSize + num * kRecordSize) 183 if (num > kNumFilesMax || processed < kHeaderSize + num * kRecordSize)
170 return S_FALSE; 184 return S_FALSE;
171 if (num == 0) 185 if (num == 0)
@@ -174,13 +188,14 @@ HRESULT CHandler::Open2(IInStream *stream)
174 188
175 for (UInt32 i = 0; i < num; i++) 189 for (UInt32 i = 0; i < num; i++)
176 { 190 {
177 const Byte *p = buf + kHeaderSize + i * kRecordSize; 191 const UInt32 *p = buf + kHeaderSize + i * kRecordSize;
178 CItem &sb = _items[i]; 192 CItem &sb = _items[i];
179 sb.Type = Get32(p, be); 193 sb.Type = p[0];
180 sb.SubType = Get32(p + 4, be); 194 sb.SubType = p[1];
181 sb.Offset = Get32(p + 8, be); 195 sb.Offset = p[2];
182 sb.Size = Get32(p + 12, be); 196 sb.Size = p[3];
183 UInt32 align = Get32(p + 16, be); 197 const UInt32 align = p[4];
198 sb.Align = align;
184 if (align > 31) 199 if (align > 31)
185 return S_FALSE; 200 return S_FALSE;
186 if (sb.Offset < kHeaderSize + num * kRecordSize) 201 if (sb.Offset < kHeaderSize + num * kRecordSize)
@@ -189,7 +204,7 @@ HRESULT CHandler::Open2(IInStream *stream)
189 (sb.SubType & ~MACH_CPU_SUBTYPE_LIB64) >= 0x100) 204 (sb.SubType & ~MACH_CPU_SUBTYPE_LIB64) >= 0x100)
190 return S_FALSE; 205 return S_FALSE;
191 206
192 UInt64 endPos = (UInt64)sb.Offset + sb.Size; 207 const UInt64 endPos = (UInt64)sb.Offset + sb.Size;
193 if (endPosMax < endPos) 208 if (endPosMax < endPos)
194 endPosMax = endPos; 209 endPosMax = endPos;
195 } 210 }
@@ -198,9 +213,9 @@ HRESULT CHandler::Open2(IInStream *stream)
198 return S_OK; 213 return S_OK;
199} 214}
200 215
201STDMETHODIMP CHandler::Open(IInStream *inStream, 216Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
202 const UInt64 * /* maxCheckStartPosition */, 217 const UInt64 * /* maxCheckStartPosition */,
203 IArchiveOpenCallback * /* openArchiveCallback */) 218 IArchiveOpenCallback * /* openArchiveCallback */))
204{ 219{
205 COM_TRY_BEGIN 220 COM_TRY_BEGIN
206 Close(); 221 Close();
@@ -215,7 +230,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
215 COM_TRY_END 230 COM_TRY_END
216} 231}
217 232
218STDMETHODIMP CHandler::Close() 233Z7_COM7F_IMF(CHandler::Close())
219{ 234{
220 _stream.Release(); 235 _stream.Release();
221 _numItems = 0; 236 _numItems = 0;
@@ -223,7 +238,7 @@ STDMETHODIMP CHandler::Close()
223 return S_OK; 238 return S_OK;
224} 239}
225 240
226STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 241Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
227{ 242{
228 *numItems = _numItems; 243 *numItems = _numItems;
229 return S_OK; 244 return S_OK;
@@ -236,7 +251,7 @@ static const Byte k_Signature[] = {
236 4, 0xB9, 0xFA, 0xF1, 0x0E }; 251 4, 0xB9, 0xFA, 0xF1, 0x0E };
237 252
238REGISTER_ARC_I( 253REGISTER_ARC_I(
239 "Mub", "mub", 0, 0xE2, 254 "Mub", "mub", NULL, 0xE2,
240 k_Signature, 255 k_Signature,
241 0, 256 0,
242 NArcInfoFlags::kMultiSignature, 257 NArcInfoFlags::kMultiSignature,
diff --git a/CPP/7zip/Archive/Nsis/NsisDecode.cpp b/CPP/7zip/Archive/Nsis/NsisDecode.cpp
index e282218..044de37 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)
40 40
41 if (!_codecInStream) 41 if (!_codecInStream)
42 { 42 {
43 switch (Method) 43 switch ((int)Method)
44 { 44 {
45 // case NMethodType::kCopy: return E_NOTIMPL; 45 // case NMethodType::kCopy: return E_NOTIMPL;
46 case NMethodType::kDeflate: 46 case NMethodType::kDeflate:
@@ -65,7 +65,7 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter)
65 if (FilterFlag) 65 if (FilterFlag)
66 { 66 {
67 Byte flag; 67 Byte flag;
68 RINOK(ReadStream_FALSE(inStream, &flag, 1)); 68 RINOK(ReadStream_FALSE(inStream, &flag, 1))
69 if (flag > 1) 69 if (flag > 1)
70 return E_NOTIMPL; 70 return E_NOTIMPL;
71 useFilter = (flag != 0); 71 useFilter = (flag != 0);
@@ -79,9 +79,9 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter)
79 { 79 {
80 _filter = new CFilterCoder(false); 80 _filter = new CFilterCoder(false);
81 _filterInStream = _filter; 81 _filterInStream = _filter;
82 _filter->Filter = new NCompress::NBcj::CCoder(false); 82 _filter->Filter = new NCompress::NBcj::CCoder2(z7_BranchConvSt_X86_Dec);
83 } 83 }
84 RINOK(_filter->SetInStream(_codecInStream)); 84 RINOK(_filter->SetInStream(_codecInStream))
85 _decoderInStream = _filterInStream; 85 _decoderInStream = _filterInStream;
86 } 86 }
87 87
@@ -89,8 +89,8 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter)
89 { 89 {
90 const unsigned kPropsSize = LZMA_PROPS_SIZE; 90 const unsigned kPropsSize = LZMA_PROPS_SIZE;
91 Byte props[kPropsSize]; 91 Byte props[kPropsSize];
92 RINOK(ReadStream_FALSE(inStream, props, kPropsSize)); 92 RINOK(ReadStream_FALSE(inStream, props, kPropsSize))
93 RINOK(_lzmaDecoder->SetDecoderProperties2((const Byte *)props, kPropsSize)); 93 RINOK(_lzmaDecoder->SetDecoderProperties2((const Byte *)props, kPropsSize))
94 } 94 }
95 95
96 { 96 {
@@ -98,7 +98,7 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter)
98 _codecInStream.QueryInterface(IID_ICompressSetInStream, &setInStream); 98 _codecInStream.QueryInterface(IID_ICompressSetInStream, &setInStream);
99 if (!setInStream) 99 if (!setInStream)
100 return E_NOTIMPL; 100 return E_NOTIMPL;
101 RINOK(setInStream->SetInStream(inStream)); 101 RINOK(setInStream->SetInStream(inStream))
102 } 102 }
103 103
104 { 104 {
@@ -106,12 +106,12 @@ HRESULT CDecoder::Init(ISequentialInStream *inStream, bool &useFilter)
106 _codecInStream.QueryInterface(IID_ICompressSetOutStreamSize, &setOutStreamSize); 106 _codecInStream.QueryInterface(IID_ICompressSetOutStreamSize, &setOutStreamSize);
107 if (!setOutStreamSize) 107 if (!setOutStreamSize)
108 return E_NOTIMPL; 108 return E_NOTIMPL;
109 RINOK(setOutStreamSize->SetOutStreamSize(NULL)); 109 RINOK(setOutStreamSize->SetOutStreamSize(NULL))
110 } 110 }
111 111
112 if (useFilter) 112 if (useFilter)
113 { 113 {
114 RINOK(_filter->SetOutStreamSize(NULL)); 114 RINOK(_filter->SetOutStreamSize(NULL))
115 } 115 }
116 116
117 return S_OK; 117 return S_OK;
@@ -130,14 +130,14 @@ HRESULT CDecoder::SetToPos(UInt64 pos, ICompressProgressInfo *progress)
130 while (StreamPos < pos) 130 while (StreamPos < pos)
131 { 131 {
132 size_t size = (size_t)MyMin(pos - StreamPos, (UInt64)Buffer.Size()); 132 size_t size = (size_t)MyMin(pos - StreamPos, (UInt64)Buffer.Size());
133 RINOK(Read(Buffer, &size)); 133 RINOK(Read(Buffer, &size))
134 if (size == 0) 134 if (size == 0)
135 return S_FALSE; 135 return S_FALSE;
136 StreamPos += size; 136 StreamPos += size;
137 offset += size; 137 offset += size;
138 138
139 const UInt64 inSize = GetInputProcessedSize() - inSizeStart; 139 const UInt64 inSize = GetInputProcessedSize() - inSizeStart;
140 RINOK(progress->SetRatioInfo(&inSize, &offset)); 140 RINOK(progress->SetRatioInfo(&inSize, &offset))
141 } 141 }
142 return S_OK; 142 return S_OK;
143} 143}
@@ -156,7 +156,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
156 { 156 {
157 Byte temp[4]; 157 Byte temp[4];
158 size_t processedSize = 4; 158 size_t processedSize = 4;
159 RINOK(Read(temp, &processedSize)); 159 RINOK(Read(temp, &processedSize))
160 StreamPos += processedSize; 160 StreamPos += processedSize;
161 if (processedSize != 4) 161 if (processedSize != 4)
162 return S_FALSE; 162 return S_FALSE;
@@ -171,7 +171,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
171 Byte temp[4]; 171 Byte temp[4];
172 { 172 {
173 size_t processedSize = 4; 173 size_t processedSize = 4;
174 RINOK(ReadStream(InputStream, temp, &processedSize)); 174 RINOK(ReadStream(InputStream, temp, &processedSize))
175 StreamPos += processedSize; 175 StreamPos += processedSize;
176 if (processedSize != 4) 176 if (processedSize != 4)
177 return S_FALSE; 177 return S_FALSE;
@@ -192,7 +192,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
192 { 192 {
193 UInt32 curSize = (UInt32)MyMin((size_t)size, Buffer.Size()); 193 UInt32 curSize = (UInt32)MyMin((size_t)size, Buffer.Size());
194 UInt32 processedSize; 194 UInt32 processedSize;
195 RINOK(InputStream->Read(Buffer, curSize, &processedSize)); 195 RINOK(InputStream->Read(Buffer, curSize, &processedSize))
196 if (processedSize == 0) 196 if (processedSize == 0)
197 return S_FALSE; 197 return S_FALSE;
198 if (outBuf) 198 if (outBuf)
@@ -202,8 +202,8 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
202 StreamPos += processedSize; 202 StreamPos += processedSize;
203 unpackSizeRes += processedSize; 203 unpackSizeRes += processedSize;
204 if (realOutStream) 204 if (realOutStream)
205 RINOK(WriteStream(realOutStream, Buffer, processedSize)); 205 RINOK(WriteStream(realOutStream, Buffer, processedSize))
206 RINOK(progress->SetRatioInfo(&offset, &offset)); 206 RINOK(progress->SetRatioInfo(&offset, &offset))
207 } 207 }
208 208
209 return S_OK; 209 return S_OK;
@@ -217,7 +217,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
217 limitedStreamSpec->Init(size); 217 limitedStreamSpec->Init(size);
218 { 218 {
219 bool useFilter; 219 bool useFilter;
220 RINOK(Init(limitedStream, useFilter)); 220 RINOK(Init(limitedStream, useFilter))
221 } 221 }
222 } 222 }
223 223
@@ -244,7 +244,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
244 size_t size = Buffer.Size(); 244 size_t size = Buffer.Size();
245 if (size > rem) 245 if (size > rem)
246 size = rem; 246 size = rem;
247 RINOK(Read(Buffer, &size)); 247 RINOK(Read(Buffer, &size))
248 if (size == 0) 248 if (size == 0)
249 { 249 {
250 if (unpackSizeDefined) 250 if (unpackSizeDefined)
@@ -277,7 +277,7 @@ HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unp
277 unpackSizeRes += (UInt32)size; 277 unpackSizeRes += (UInt32)size;
278 278
279 UInt64 outSize = offset; 279 UInt64 outSize = offset;
280 RINOK(progress->SetRatioInfo(&inSize, &outSize)); 280 RINOK(progress->SetRatioInfo(&inSize, &outSize))
281 if (realOutStream) 281 if (realOutStream)
282 { 282 {
283 res = WriteStream(realOutStream, Buffer, size); 283 res = WriteStream(realOutStream, Buffer, size);
diff --git a/CPP/7zip/Archive/Nsis/NsisDecode.h b/CPP/7zip/Archive/Nsis/NsisDecode.h
index 2153d78..1d08d01 100644
--- a/CPP/7zip/Archive/Nsis/NsisDecode.h
+++ b/CPP/7zip/Archive/Nsis/NsisDecode.h
@@ -1,7 +1,7 @@
1// NsisDecode.h 1// NsisDecode.h
2 2
3#ifndef __NSIS_DECODE_H 3#ifndef ZIP7_INC_NSIS_DECODE_H
4#define __NSIS_DECODE_H 4#define ZIP7_INC_NSIS_DECODE_H
5 5
6#include "../../../Common/MyBuffer.h" 6#include "../../../Common/MyBuffer.h"
7 7
@@ -82,7 +82,7 @@ public:
82 82
83 HRESULT Read(void *data, size_t *processedSize) 83 HRESULT Read(void *data, size_t *processedSize)
84 { 84 {
85 return ReadStream(_decoderInStream, data, processedSize);; 85 return ReadStream(_decoderInStream, data, processedSize);
86 } 86 }
87 87
88 88
diff --git a/CPP/7zip/Archive/Nsis/NsisHandler.cpp b/CPP/7zip/Archive/Nsis/NsisHandler.cpp
index aa0a917..7a512b7 100644
--- a/CPP/7zip/Archive/Nsis/NsisHandler.cpp
+++ b/CPP/7zip/Archive/Nsis/NsisHandler.cpp
@@ -61,22 +61,19 @@ IMP_IInArchive_Props
61IMP_IInArchive_ArcProps 61IMP_IInArchive_ArcProps
62 62
63 63
64static AString UInt32ToString(UInt32 val) 64static void AddDictProp(AString &s, UInt32 val)
65{ 65{
66 char s[16]; 66 for (unsigned i = 0; i < 32; i++)
67 ConvertUInt32ToString(val, s);
68 return (AString)s;
69}
70
71static AString GetStringForSizeValue(UInt32 val)
72{
73 for (int i = 31; i >= 0; i--)
74 if (((UInt32)1 << i) == val) 67 if (((UInt32)1 << i) == val)
75 return UInt32ToString(i); 68 {
69 s.Add_UInt32(i);
70 return;
71 }
76 char c = 'b'; 72 char c = 'b';
77 if ((val & ((1 << 20) - 1)) == 0) { val >>= 20; c = 'm'; } 73 if ((val & ((1 << 20) - 1)) == 0) { val >>= 20; c = 'm'; }
78 else if ((val & ((1 << 10) - 1)) == 0) { val >>= 10; c = 'k'; } 74 else if ((val & ((1 << 10) - 1)) == 0) { val >>= 10; c = 'k'; }
79 return UInt32ToString(val) + c; 75 s.Add_UInt32(val);
76 s += c;
80} 77}
81 78
82static AString GetMethod(bool useFilter, NMethodType::EEnum method, UInt32 dict) 79static AString GetMethod(bool useFilter, NMethodType::EEnum method, UInt32 dict)
@@ -87,11 +84,11 @@ static AString GetMethod(bool useFilter, NMethodType::EEnum method, UInt32 dict)
87 s += kBcjMethod; 84 s += kBcjMethod;
88 s.Add_Space(); 85 s.Add_Space();
89 } 86 }
90 s += ((unsigned)method < ARRAY_SIZE(kMethods)) ? kMethods[(unsigned)method] : kUnknownMethod; 87 s += ((unsigned)method < Z7_ARRAY_SIZE(kMethods)) ? kMethods[(unsigned)method] : kUnknownMethod;
91 if (method == NMethodType::kLZMA) 88 if (method == NMethodType::kLZMA)
92 { 89 {
93 s += ':'; 90 s += ':';
94 s += GetStringForSizeValue(dict); 91 AddDictProp(s, dict);
95 } 92 }
96 return s; 93 return s;
97} 94}
@@ -105,7 +102,7 @@ AString CHandler::GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt3
105 s += kBcjMethod; 102 s += kBcjMethod;
106 s.Add_Space(); 103 s.Add_Space();
107 } 104 }
108 s += (method < ARRAY_SIZE(kMethods)) ? kMethods[method] : kUnknownMethod; 105 s += (method < Z7_ARRAY_SIZE(kMethods)) ? kMethods[method] : kUnknownMethod;
109 if (method == NMethodType::kLZMA) 106 if (method == NMethodType::kLZMA)
110 { 107 {
111 s += ':'; 108 s += ':';
@@ -115,7 +112,7 @@ AString CHandler::GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt3
115} 112}
116*/ 113*/
117 114
118STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 115Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
119{ 116{
120 COM_TRY_BEGIN 117 COM_TRY_BEGIN
121 NCOM::CPropVariant prop; 118 NCOM::CPropVariant prop;
@@ -162,7 +159,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
162 if (!_archive.IsInstaller) 159 if (!_archive.IsInstaller)
163 { 160 {
164 if (!s.IsEmpty()) 161 if (!s.IsEmpty())
165 s += '.'; 162 s.Add_Dot();
166 s += "Uninstall"; 163 s += "Uninstall";
167 } 164 }
168 #endif 165 #endif
@@ -190,7 +187,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
190} 187}
191 188
192 189
193STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback * /* openArchiveCallback */) 190Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback * /* openArchiveCallback */))
194{ 191{
195 COM_TRY_BEGIN 192 COM_TRY_BEGIN
196 Close(); 193 Close();
@@ -215,18 +212,18 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *maxCheckStartPositi
215 COM_TRY_END 212 COM_TRY_END
216} 213}
217 214
218STDMETHODIMP CHandler::Close() 215Z7_COM7F_IMF(CHandler::Close())
219{ 216{
220 _archive.Clear(); 217 _archive.Clear();
221 _archive.Release(); 218 _archive.Release();
222 return S_OK; 219 return S_OK;
223} 220}
224 221
225STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 222Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
226{ 223{
227 *numItems = _archive.Items.Size() 224 *numItems = _archive.Items.Size()
228 #ifdef NSIS_SCRIPT 225 #ifdef NSIS_SCRIPT
229 + 1 + _archive.LicenseFiles.Size(); 226 + 1 + _archive.LicenseFiles.Size()
230 #endif 227 #endif
231 ; 228 ;
232 return S_OK; 229 return S_OK;
@@ -240,7 +237,7 @@ bool CHandler::GetUncompressedSize(unsigned index, UInt32 &size) const
240 size = item.Size; 237 size = item.Size;
241 else if (_archive.IsSolid && item.EstimatedSize_Defined) 238 else if (_archive.IsSolid && item.EstimatedSize_Defined)
242 size = item.EstimatedSize; 239 size = item.EstimatedSize;
243 else 240 else if (!item.IsEmptyFile)
244 return false; 241 return false;
245 return true; 242 return true;
246} 243}
@@ -272,7 +269,7 @@ bool CHandler::GetCompressedSize(unsigned index, UInt32 &size) const
272} 269}
273 270
274 271
275STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 272Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
276{ 273{
277 COM_TRY_BEGIN 274 COM_TRY_BEGIN
278 NCOM::CPropVariant prop; 275 NCOM::CPropVariant prop;
@@ -360,21 +357,21 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
360} 357}
361 358
362 359
363static bool UninstallerPatch(const Byte *p, size_t size, CByteBuffer &dest) 360static bool UninstallerPatch(const Byte *p, size_t size, Byte *dest, size_t destSize)
364{ 361{
365 for (;;) 362 for (;;)
366 { 363 {
367 if (size < 4) 364 if (size < 4)
368 return false; 365 return false;
369 UInt32 len = Get32(p); 366 const UInt32 len = Get32(p);
370 if (len == 0) 367 if (len == 0)
371 return size == 4; 368 return size == 4;
372 if (size < 8) 369 if (size < 8)
373 return false; 370 return false;
374 UInt32 offs = Get32(p + 4); 371 const UInt32 offs = Get32(p + 4);
375 p += 8; 372 p += 8;
376 size -= 8; 373 size -= 8;
377 if (size < len || offs > dest.Size() || len > dest.Size() - offs) 374 if (size < len || offs > destSize || len > destSize - offs)
378 return false; 375 return false;
379 memcpy(dest + offs, p, len); 376 memcpy(dest + offs, p, len);
380 p += len; 377 p += len;
@@ -383,11 +380,11 @@ static bool UninstallerPatch(const Byte *p, size_t size, CByteBuffer &dest)
383} 380}
384 381
385 382
386STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 383Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
387 Int32 testMode, IArchiveExtractCallback *extractCallback) 384 Int32 testMode, IArchiveExtractCallback *extractCallback))
388{ 385{
389 COM_TRY_BEGIN 386 COM_TRY_BEGIN
390 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 387 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
391 if (allFilesMode) 388 if (allFilesMode)
392 GetNumberOfItems(&numItems); 389 GetNumberOfItems(&numItems);
393 if (numItems == 0) 390 if (numItems == 0)
@@ -399,7 +396,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
399 UInt32 i; 396 UInt32 i;
400 for (i = 0; i < numItems; i++) 397 for (i = 0; i < numItems; i++)
401 { 398 {
402 UInt32 index = (allFilesMode ? i : indices[i]); 399 const UInt32 index = (allFilesMode ? i : indices[i]);
403 400
404 #ifdef NSIS_SCRIPT 401 #ifdef NSIS_SCRIPT
405 if (index >= _archive.Items.Size()) 402 if (index >= _archive.Items.Size())
@@ -436,8 +433,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
436 433
437 if (_archive.IsSolid) 434 if (_archive.IsSolid)
438 { 435 {
439 RINOK(_archive.SeekTo_DataStreamOffset()); 436 RINOK(_archive.SeekTo_DataStreamOffset())
440 RINOK(_archive.InitDecoder()); 437 RINOK(_archive.InitDecoder())
441 _archive.Decoder.StreamPos = 0; 438 _archive.Decoder.StreamPos = 0;
442 } 439 }
443 440
@@ -476,16 +473,16 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
476 473
477 curPacked = 0; 474 curPacked = 0;
478 curUnpacked = 0; 475 curUnpacked = 0;
479 RINOK(lps->SetCur()); 476 RINOK(lps->SetCur())
480 477
481 // RINOK(extractCallback->SetCompleted(&currentTotalSize)); 478 // RINOK(extractCallback->SetCompleted(&currentTotalSize))
482 CMyComPtr<ISequentialOutStream> realOutStream; 479 CMyComPtr<ISequentialOutStream> realOutStream;
483 Int32 askMode = testMode ? 480 const Int32 askMode = testMode ?
484 NExtract::NAskMode::kTest : 481 NExtract::NAskMode::kTest :
485 NExtract::NAskMode::kExtract; 482 NExtract::NAskMode::kExtract;
486 const UInt32 index = allFilesMode ? i : indices[i]; 483 const UInt32 index = allFilesMode ? i : indices[i];
487 484
488 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 485 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
489 486
490 bool dataError = false; 487 bool dataError = false;
491 488
@@ -511,9 +508,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
511 curUnpacked = size; 508 curUnpacked = size;
512 if (!testMode && !realOutStream) 509 if (!testMode && !realOutStream)
513 continue; 510 continue;
514 RINOK(extractCallback->PrepareOperation(askMode)); 511 RINOK(extractCallback->PrepareOperation(askMode))
515 if (realOutStream) 512 if (realOutStream)
516 RINOK(WriteStream(realOutStream, data, size)); 513 RINOK(WriteStream(realOutStream, data, size))
517 } 514 }
518 else 515 else
519 #endif 516 #endif
@@ -526,15 +523,20 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
526 if (!testMode && !realOutStream) 523 if (!testMode && !realOutStream)
527 continue; 524 continue;
528 525
529 RINOK(extractCallback->PrepareOperation(askMode)); 526 RINOK(extractCallback->PrepareOperation(askMode))
530 527
531 dataError = solidDataError; 528 dataError = solidDataError;
532 529
533 bool needDecompress = !solidDataError; 530 bool needDecompress = false;
534 if (needDecompress) 531
532 if (!item.IsEmptyFile)
535 { 533 {
536 if (testMode && _archive.IsSolid && _archive.GetPosOfSolidItem(index) == prevPos) 534 needDecompress = !solidDataError;
537 needDecompress = false; 535 if (needDecompress)
536 {
537 if (testMode && _archive.IsSolid && _archive.GetPosOfSolidItem(index) == prevPos)
538 needDecompress = false;
539 }
538 } 540 }
539 541
540 if (needDecompress) 542 if (needDecompress)
@@ -544,7 +546,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
544 546
545 if (!_archive.IsSolid) 547 if (!_archive.IsSolid)
546 { 548 {
547 RINOK(_archive.SeekToNonSolidItem(index)); 549 RINOK(_archive.SeekToNonSolidItem(index))
548 } 550 }
549 else 551 else
550 { 552 {
@@ -566,10 +568,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
566 } 568 }
567 else if (!testMode && i + 1 < numItems) 569 else if (!testMode && i + 1 < numItems)
568 { 570 {
569 UInt32 next = allFilesMode ? i + 1 : indices[i + 1]; 571 const UInt32 next = allFilesMode ? i + 1 : indices[i + 1];
570 if (next < _archive.Items.Size()) 572 if (next < _archive.Items.Size())
571 { 573 {
572 UInt64 nextPos = _archive.GetPosOfSolidItem(next); 574 // next cannot be IsEmptyFile
575 const UInt64 nextPos = _archive.GetPosOfSolidItem(next);
573 if (nextPos == pos) 576 if (nextPos == pos)
574 { 577 {
575 writeToTemp = true; 578 writeToTemp = true;
@@ -581,12 +584,16 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
581 prevPos = pos; 584 prevPos = pos;
582 } 585 }
583 586
587 /* nsis 3.08 can use (PatchSize == 0) for uninstaller without patched section */
588
589 const bool is_PatchedUninstaller = item.Is_PatchedUninstaller();
590
584 if (!dataError) 591 if (!dataError)
585 { 592 {
586 // UInt32 unpackSize = 0; 593 // UInt32 unpackSize = 0;
587 // bool unpackSize_Defined = false; 594 // bool unpackSize_Defined = false;
588 bool writeToTemp1 = writeToTemp; 595 bool writeToTemp1 = writeToTemp;
589 if (item.IsUninstaller) 596 if (is_PatchedUninstaller)
590 { 597 {
591 // unpackSize = item.PatchSize; 598 // unpackSize = item.PatchSize;
592 // unpackSize_Defined = true; 599 // unpackSize_Defined = true;
@@ -603,16 +610,16 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
603 610
604 if (readFromTemp) 611 if (readFromTemp)
605 { 612 {
606 if (realOutStream && !item.IsUninstaller) 613 if (realOutStream && !is_PatchedUninstaller)
607 RINOK(WriteStream(realOutStream, tempBuf, tempBuf.Size())); 614 RINOK(WriteStream(realOutStream, tempBuf, tempBuf.Size()))
608 } 615 }
609 else 616 else
610 { 617 {
611 UInt32 curUnpacked32 = 0; 618 UInt32 curUnpacked32 = 0;
612 HRESULT res = _archive.Decoder.Decode( 619 const HRESULT res = _archive.Decoder.Decode(
613 writeToTemp1 ? &tempBuf : NULL, 620 writeToTemp1 ? &tempBuf : NULL,
614 item.IsUninstaller, item.PatchSize, 621 is_PatchedUninstaller, item.PatchSize,
615 item.IsUninstaller ? NULL : (ISequentialOutStream *)realOutStream, 622 is_PatchedUninstaller ? NULL : (ISequentialOutStream *)realOutStream,
616 progress, 623 progress,
617 curPacked, curUnpacked32); 624 curPacked, curUnpacked32);
618 curUnpacked = curUnpacked32; 625 curUnpacked = curUnpacked32;
@@ -629,21 +636,20 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
629 } 636 }
630 } 637 }
631 638
632 if (!dataError && item.IsUninstaller) 639 if (!dataError && is_PatchedUninstaller)
633 { 640 {
634 if (_archive.ExeStub.Size() != 0) 641 if (_archive.ExeStub.Size() != 0)
635 { 642 {
636 CByteBuffer destBuf = _archive.ExeStub; 643 CByteBuffer destBuf = _archive.ExeStub;
637 dataError = !UninstallerPatch(tempBuf, tempBuf.Size(), destBuf); 644 dataError = !UninstallerPatch(tempBuf, tempBuf.Size(), destBuf, destBuf.Size());
638
639 if (realOutStream) 645 if (realOutStream)
640 RINOK(WriteStream(realOutStream, destBuf, destBuf.Size())); 646 RINOK(WriteStream(realOutStream, destBuf, destBuf.Size()))
641 } 647 }
642 648
643 if (readFromTemp) 649 if (readFromTemp)
644 { 650 {
645 if (realOutStream) 651 if (realOutStream)
646 RINOK(WriteStream(realOutStream, tempBuf2, tempBuf2.Size())); 652 RINOK(WriteStream(realOutStream, tempBuf2, tempBuf2.Size()))
647 } 653 }
648 else 654 else
649 { 655 {
@@ -652,10 +658,10 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
652 658
653 if (!_archive.IsSolid) 659 if (!_archive.IsSolid)
654 { 660 {
655 RINOK(_archive.SeekTo(_archive.GetPosOfNonSolidItem(index) + 4 + curPacked )); 661 RINOK(_archive.SeekTo(_archive.GetPosOfNonSolidItem(index) + 4 + curPacked ))
656 } 662 }
657 663
658 HRESULT res = _archive.Decoder.Decode( 664 const HRESULT res = _archive.Decoder.Decode(
659 writeToTemp ? &tempBuf2 : NULL, 665 writeToTemp ? &tempBuf2 : NULL,
660 false, 0, 666 false, 0,
661 realOutStream, 667 realOutStream,
@@ -679,7 +685,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
679 realOutStream.Release(); 685 realOutStream.Release();
680 RINOK(extractCallback->SetOperationResult(dataError ? 686 RINOK(extractCallback->SetOperationResult(dataError ?
681 NExtract::NOperationResult::kDataError : 687 NExtract::NOperationResult::kDataError :
682 NExtract::NOperationResult::kOK)); 688 NExtract::NOperationResult::kOK))
683 } 689 }
684 return S_OK; 690 return S_OK;
685 COM_TRY_END 691 COM_TRY_END
diff --git a/CPP/7zip/Archive/Nsis/NsisHandler.h b/CPP/7zip/Archive/Nsis/NsisHandler.h
index 1eb8b73..bb90bfe 100644
--- a/CPP/7zip/Archive/Nsis/NsisHandler.h
+++ b/CPP/7zip/Archive/Nsis/NsisHandler.h
@@ -1,7 +1,7 @@
1// NSisHandler.h 1// NSisHandler.h
2 2
3#ifndef __NSIS_HANDLER_H 3#ifndef ZIP7_INC_NSIS_HANDLER_H
4#define __NSIS_HANDLER_H 4#define ZIP7_INC_NSIS_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -14,10 +14,8 @@
14namespace NArchive { 14namespace NArchive {
15namespace NNsis { 15namespace NNsis {
16 16
17class CHandler: 17Z7_CLASS_IMP_CHandler_IInArchive_0
18 public IInArchive, 18
19 public CMyUnknownImp
20{
21 CInArchive _archive; 19 CInArchive _archive;
22 AString _methodString; 20 AString _methodString;
23 21
@@ -25,10 +23,6 @@ class CHandler:
25 bool GetCompressedSize(unsigned index, UInt32 &size) const; 23 bool GetCompressedSize(unsigned index, UInt32 &size) const;
26 24
27 // AString GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt32 dictionary) const; 25 // AString GetMethod(NMethodType::EEnum method, bool useItemFilter, UInt32 dictionary) const;
28public:
29 MY_UNKNOWN_IMP1(IInArchive)
30
31 INTERFACE_IInArchive(;)
32}; 26};
33 27
34}} 28}}
diff --git a/CPP/7zip/Archive/Nsis/NsisIn.cpp b/CPP/7zip/Archive/Nsis/NsisIn.cpp
index 4e2d7a9..05ebfd0 100644
--- a/CPP/7zip/Archive/Nsis/NsisIn.cpp
+++ b/CPP/7zip/Archive/Nsis/NsisIn.cpp
@@ -6,7 +6,6 @@
6#include "../../../Common/StringToInt.h" 6#include "../../../Common/StringToInt.h"
7 7
8#include "../../Common/LimitedStreams.h" 8#include "../../Common/LimitedStreams.h"
9#include "../../Common/StreamUtils.h"
10 9
11#include "NsisIn.h" 10#include "NsisIn.h"
12 11
@@ -32,7 +31,7 @@ static const unsigned kCmdSize = 4 + kNumCommandParams * 4;
32 31
33static const char * const kErrorStr = "$_ERROR_STR_"; 32static const char * const kErrorStr = "$_ERROR_STR_";
34 33
35#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 34#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
36 35
37 36
38/* There are several versions of NSIS: 37/* There are several versions of NSIS:
@@ -466,8 +465,8 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID)
466 } 465 }
467 strUsed[param] = 1; 466 strUsed[param] = 1;
468 467
469 UInt32 start = _stringsPos + (IsUnicode ? param * 2 : param); 468 const UInt32 start = _stringsPos + (IsUnicode ? param * 2 : param);
470 UInt32 offset = start + (IsUnicode ? 2 : 1); 469 const UInt32 offset = start + (IsUnicode ? 2 : 1);
471 { 470 {
472 FOR_VECTOR (i, LicenseFiles) 471 FOR_VECTOR (i, LicenseFiles)
473 { 472 {
@@ -484,16 +483,16 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID)
484 { 483 {
485 fileName += "\\license-"; 484 fileName += "\\license-";
486 // LangId_To_String(fileName, langID); 485 // LangId_To_String(fileName, langID);
487 UIntToString(fileName, langID); 486 UIntToString(fileName, (UInt32)langID);
488 } 487 }
489 else if (++_numRootLicenses > 1) 488 else if (++_numRootLicenses > 1)
490 { 489 {
491 fileName += '-'; 490 fileName.Add_Minus();
492 UIntToString(fileName, _numRootLicenses); 491 UIntToString(fileName, _numRootLicenses);
493 } 492 }
494 const Byte *sz = (_data + start); 493 const Byte *sz = (_data + start);
495 unsigned marker = IsUnicode ? Get16(sz) : *sz; 494 const unsigned marker = IsUnicode ? Get16(sz) : *sz;
496 bool isRTF = (marker == 2); 495 const bool isRTF = (marker == 2);
497 fileName += isRTF ? ".rtf" : ".txt"; // if (*sz == 1) it's text; 496 fileName += isRTF ? ".rtf" : ".txt"; // if (*sz == 1) it's text;
498 Script += fileName; 497 Script += fileName;
499 498
@@ -505,7 +504,7 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID)
505 else 504 else
506 { 505 {
507 sz += 2; 506 sz += 2;
508 UInt32 len = GetUi16Str_Len(sz); 507 const UInt32 len = GetUi16Str_Len(sz);
509 lic.Size = len * 2; 508 lic.Size = len * 2;
510 if (isRTF) 509 if (isRTF)
511 { 510 {
@@ -526,6 +525,26 @@ void CInArchive::AddLicense(UInt32 param, Int32 langID)
526#endif 525#endif
527 526
528 527
528#ifdef NSIS_SCRIPT
529#define Z7_NSIS_WIN_GENERIC_READ ((UInt32)1 << 31)
530#endif
531#define Z7_NSIS_WIN_GENERIC_WRITE ((UInt32)1 << 30)
532#ifdef NSIS_SCRIPT
533#define Z7_NSIS_WIN_GENERIC_EXECUTE ((UInt32)1 << 29)
534#define Z7_NSIS_WIN_GENERIC_ALL ((UInt32)1 << 28)
535#endif
536
537#ifdef NSIS_SCRIPT
538#define Z7_NSIS_WIN_CREATE_NEW 1
539#endif
540#define Z7_NSIS_WIN_CREATE_ALWAYS 2
541#ifdef NSIS_SCRIPT
542#define Z7_NSIS_WIN_OPEN_EXISTING 3
543#define Z7_NSIS_WIN_OPEN_ALWAYS 4
544#define Z7_NSIS_WIN_TRUNCATE_EXISTING 5
545#endif
546
547
529// #define kVar_CMDLINE 20 548// #define kVar_CMDLINE 20
530#define kVar_INSTDIR 21 549#define kVar_INSTDIR 21
531#define kVar_OUTDIR 22 550#define kVar_OUTDIR 22
@@ -562,9 +581,9 @@ static const char * const kVarStrings[] =
562 , "_OUTDIR" // NSIS 2.04+ 581 , "_OUTDIR" // NSIS 2.04+
563}; 582};
564 583
565static const unsigned kNumInternalVars = 20 + ARRAY_SIZE(kVarStrings); 584static const unsigned kNumInternalVars = 20 + Z7_ARRAY_SIZE(kVarStrings);
566 585
567#define GET_NUM_INTERNAL_VARS (IsNsis200 ? kNumInternalVars - 3 : IsNsis225 ? kNumInternalVars - 2 : kNumInternalVars); 586#define GET_NUM_INTERNAL_VARS (IsNsis200 ? kNumInternalVars - 3 : IsNsis225 ? kNumInternalVars - 2 : kNumInternalVars)
568 587
569void CInArchive::GetVar2(AString &res, UInt32 index) 588void CInArchive::GetVar2(AString &res, UInt32 index)
570{ 589{
@@ -643,7 +662,7 @@ void CInArchive::AddParam_UInt(UInt32 value)
643#define IS_NS_SPEC_CHAR(c) ((c) >= NS_CODE_SKIP) 662#define IS_NS_SPEC_CHAR(c) ((c) >= NS_CODE_SKIP)
644#define IS_PARK_SPEC_CHAR(c) ((c) >= PARK_CODE_SKIP && (c) <= PARK_CODE_LANG) 663#define IS_PARK_SPEC_CHAR(c) ((c) >= PARK_CODE_SKIP && (c) <= PARK_CODE_LANG)
645 664
646#define DECODE_NUMBER_FROM_2_CHARS(c0, c1) (((c0) & 0x7F) | (((unsigned)((c1) & 0x7F)) << 7)) 665#define DECODE_NUMBER_FROM_2_CHARS(c0, c1) (((unsigned)(c0) & 0x7F) | (((unsigned)((c1) & 0x7F)) << 7))
647#define CONVERT_NUMBER_NS_3_UNICODE(n) n = ((n & 0x7F) | (((n >> 8) & 0x7F) << 7)) 666#define CONVERT_NUMBER_NS_3_UNICODE(n) n = ((n & 0x7F) | (((n >> 8) & 0x7F) << 7))
648#define CONVERT_NUMBER_PARK(n) n &= 0x7FFF 667#define CONVERT_NUMBER_PARK(n) n &= 0x7FFF
649 668
@@ -738,7 +757,7 @@ void CInArchive::GetShellString(AString &s, unsigned index1, unsigned index2)
738 } 757 }
739 758
740 s += '$'; 759 s += '$';
741 if (index1 < ARRAY_SIZE(kShellStrings)) 760 if (index1 < Z7_ARRAY_SIZE(kShellStrings))
742 { 761 {
743 const char *sz = kShellStrings[index1]; 762 const char *sz = kShellStrings[index1];
744 if (sz) 763 if (sz)
@@ -747,7 +766,7 @@ void CInArchive::GetShellString(AString &s, unsigned index1, unsigned index2)
747 return; 766 return;
748 } 767 }
749 } 768 }
750 if (index2 < ARRAY_SIZE(kShellStrings)) 769 if (index2 < Z7_ARRAY_SIZE(kShellStrings))
751 { 770 {
752 const char *sz = kShellStrings[index2]; 771 const char *sz = kShellStrings[index2];
753 if (sz) 772 if (sz)
@@ -1151,7 +1170,7 @@ void CInArchive::ReadString2_Raw(UInt32 pos)
1151 Raw_AString.Empty(); 1170 Raw_AString.Empty();
1152 Raw_UString.Empty(); 1171 Raw_UString.Empty();
1153 if ((Int32)pos < 0) 1172 if ((Int32)pos < 0)
1154 Add_LangStr(Raw_AString, -((Int32)pos + 1)); 1173 Add_LangStr(Raw_AString, (UInt32)-((Int32)pos + 1));
1155 else if (pos >= NumStringChars) 1174 else if (pos >= NumStringChars)
1156 { 1175 {
1157 Raw_AString += kErrorStr; 1176 Raw_AString += kErrorStr;
@@ -1361,7 +1380,7 @@ void CInArchive::ReadString2(AString &s, UInt32 pos)
1361{ 1380{
1362 if ((Int32)pos < 0) 1381 if ((Int32)pos < 0)
1363 { 1382 {
1364 Add_LangStr(s, -((Int32)pos + 1)); 1383 Add_LangStr(s, (UInt32)-((Int32)pos + 1));
1365 return; 1384 return;
1366 } 1385 }
1367 1386
@@ -1537,7 +1556,7 @@ static const UInt32 CMD_REF_Leave = (1 << 4);
1537static const UInt32 CMD_REF_OnFunc = (1 << 5); 1556static const UInt32 CMD_REF_OnFunc = (1 << 5);
1538static const UInt32 CMD_REF_Section = (1 << 6); 1557static const UInt32 CMD_REF_Section = (1 << 6);
1539static const UInt32 CMD_REF_InitPluginDir = (1 << 7); 1558static const UInt32 CMD_REF_InitPluginDir = (1 << 7);
1540// static const UInt32 CMD_REF_Creator = (1 << 5); // _Pre is used instead 1559// static const UInt32 CMD_REF_Creator = (1 << 5); // CMD_REF_Pre is used instead
1541static const unsigned CMD_REF_OnFunc_NumShifts = 28; // it uses for onFunc too 1560static const unsigned CMD_REF_OnFunc_NumShifts = 28; // it uses for onFunc too
1542static const unsigned CMD_REF_Page_NumShifts = 16; // it uses for onFunc too 1561static const unsigned CMD_REF_Page_NumShifts = 16; // it uses for onFunc too
1543static const UInt32 CMD_REF_Page_Mask = 0x0FFF0000; 1562static const UInt32 CMD_REF_Page_Mask = 0x0FFF0000;
@@ -1617,7 +1636,7 @@ void CInArchive::Add_GotoVar(UInt32 param)
1617{ 1636{
1618 Space(); 1637 Space();
1619 if ((Int32)param < 0) 1638 if ((Int32)param < 0)
1620 Add_Var(-((Int32)param + 1)); 1639 Add_Var((UInt32)-((Int32)param + 1));
1621 else 1640 else
1622 Add_LabelName(param - 1); 1641 Add_LabelName(param - 1);
1623} 1642}
@@ -1647,8 +1666,8 @@ static bool NoLabels(const UInt32 *labels, UInt32 num)
1647 1666
1648static const char * const k_REBOOTOK = " /REBOOTOK"; 1667static const char * const k_REBOOTOK = " /REBOOTOK";
1649 1668
1650#define MY__MB_ABORTRETRYIGNORE 2 1669#define Z7_NSIS_WIN_MB_ABORTRETRYIGNORE 2
1651#define MY__MB_RETRYCANCEL 5 1670#define Z7_NSIS_WIN_MB_RETRYCANCEL 5
1652 1671
1653static const char * const k_MB_Buttons[] = 1672static const char * const k_MB_Buttons[] =
1654{ 1673{
@@ -1661,7 +1680,7 @@ static const char * const k_MB_Buttons[] =
1661 , "CANCELTRYCONTINUE" 1680 , "CANCELTRYCONTINUE"
1662}; 1681};
1663 1682
1664#define MY__MB_ICONSTOP (1 << 4) 1683#define Z7_NSIS_WIN_MB_ICONSTOP (1 << 4)
1665 1684
1666static const char * const k_MB_Icons[] = 1685static const char * const k_MB_Icons[] =
1667{ 1686{
@@ -1684,8 +1703,8 @@ static const char * const k_MB_Flags[] =
1684 // , "SERVICE_NOTIFICATION" // unsupported. That bit is used for NSIS purposes 1703 // , "SERVICE_NOTIFICATION" // unsupported. That bit is used for NSIS purposes
1685}; 1704};
1686 1705
1687#define MY__IDCANCEL 2 1706#define Z7_NSIS_WIN_IDCANCEL 2
1688#define MY__IDIGNORE 5 1707#define Z7_NSIS_WIN_IDIGNORE 5
1689 1708
1690static const char * const k_Button_IDs[] = 1709static const char * const k_Button_IDs[] =
1691{ 1710{
@@ -1706,7 +1725,7 @@ static const char * const k_Button_IDs[] =
1706void CInArchive::Add_ButtonID(UInt32 buttonID) 1725void CInArchive::Add_ButtonID(UInt32 buttonID)
1707{ 1726{
1708 Space(); 1727 Space();
1709 if (buttonID < ARRAY_SIZE(k_Button_IDs)) 1728 if (buttonID < Z7_ARRAY_SIZE(k_Button_IDs))
1710 Script += k_Button_IDs[buttonID]; 1729 Script += k_Button_IDs[buttonID];
1711 else 1730 else
1712 { 1731 {
@@ -1774,19 +1793,8 @@ void CNsis_CtlColors::Parse(const Byte *p, bool is64)
1774} 1793}
1775 1794
1776// Win32 constants 1795// Win32 constants
1777#define MY__TRANSPARENT 1 1796#define Z7_NSIS_WIN_TRANSPARENT 1
1778// #define MY__OPAQUE 2 1797// #define Z7_NSIS_WIN_OPAQUE 2
1779
1780#define MY__GENERIC_READ ((UInt32)1 << 31)
1781#define MY__GENERIC_WRITE ((UInt32)1 << 30)
1782#define MY__GENERIC_EXECUTE ((UInt32)1 << 29)
1783#define MY__GENERIC_ALL ((UInt32)1 << 28)
1784
1785#define MY__CREATE_NEW 1
1786#define MY__CREATE_ALWAYS 2
1787#define MY__OPEN_EXISTING 3
1788#define MY__OPEN_ALWAYS 4
1789#define MY__TRUNCATE_EXISTING 5
1790 1798
1791// text/bg colors 1799// text/bg colors
1792#define kColorsFlags_TEXT 1 1800#define kColorsFlags_TEXT 1
@@ -1821,12 +1829,12 @@ void CInArchive::Add_Color(UInt32 v)
1821 Add_Color2(v); 1829 Add_Color2(v);
1822} 1830}
1823 1831
1824#define MY__SW_HIDE 0 1832#define Z7_NSIS_WIN_SW_HIDE 0
1825#define MY__SW_SHOWNORMAL 1 1833#define Z7_NSIS_WIN_SW_SHOWNORMAL 1
1826 1834
1827#define MY__SW_SHOWMINIMIZED 2 1835#define Z7_NSIS_WIN_SW_SHOWMINIMIZED 2
1828#define MY__SW_SHOWMINNOACTIVE 7 1836#define Z7_NSIS_WIN_SW_SHOWMINNOACTIVE 7
1829#define MY__SW_SHOWNA 8 1837#define Z7_NSIS_WIN_SW_SHOWNA 8
1830 1838
1831static const char * const kShowWindow_Commands[] = 1839static const char * const kShowWindow_Commands[] =
1832{ 1840{
@@ -1846,7 +1854,7 @@ static const char * const kShowWindow_Commands[] =
1846 1854
1847static void Add_ShowWindow_Cmd_2(AString &s, UInt32 cmd) 1855static void Add_ShowWindow_Cmd_2(AString &s, UInt32 cmd)
1848{ 1856{
1849 if (cmd < ARRAY_SIZE(kShowWindow_Commands)) 1857 if (cmd < Z7_ARRAY_SIZE(kShowWindow_Commands))
1850 { 1858 {
1851 s += "SW_"; 1859 s += "SW_";
1852 s += kShowWindow_Commands[cmd]; 1860 s += kShowWindow_Commands[cmd];
@@ -1857,7 +1865,7 @@ static void Add_ShowWindow_Cmd_2(AString &s, UInt32 cmd)
1857 1865
1858void CInArchive::Add_ShowWindow_Cmd(UInt32 cmd) 1866void CInArchive::Add_ShowWindow_Cmd(UInt32 cmd)
1859{ 1867{
1860 if (cmd < ARRAY_SIZE(kShowWindow_Commands)) 1868 if (cmd < Z7_ARRAY_SIZE(kShowWindow_Commands))
1861 { 1869 {
1862 Script += "SW_"; 1870 Script += "SW_";
1863 Script += kShowWindow_Commands[cmd]; 1871 Script += kShowWindow_Commands[cmd];
@@ -1877,7 +1885,7 @@ void CInArchive::Add_TypeFromList(const char * const *table, unsigned tableSize,
1877 } 1885 }
1878} 1886}
1879 1887
1880#define ADD_TYPE_FROM_LIST(table, type) Add_TypeFromList(table, ARRAY_SIZE(table), type) 1888#define ADD_TYPE_FROM_LIST(table, type) Add_TypeFromList(table, Z7_ARRAY_SIZE(table), type)
1881 1889
1882enum 1890enum
1883{ 1891{
@@ -1894,7 +1902,7 @@ enum
1894 k_ExecFlags_rtl, 1902 k_ExecFlags_rtl,
1895 k_ExecFlags_ErrorLevel, 1903 k_ExecFlags_ErrorLevel,
1896 k_ExecFlags_RegView, 1904 k_ExecFlags_RegView,
1897 k_ExecFlags_DetailsPrint = 13, 1905 k_ExecFlags_DetailsPrint = 13
1898}; 1906};
1899 1907
1900// Names for NSIS exec_flags_t structure vars 1908// Names for NSIS exec_flags_t structure vars
@@ -2097,7 +2105,7 @@ void CSection::Parse(const Byte *p)
2097 StartCmdIndex = Get32(p + 12); 2105 StartCmdIndex = Get32(p + 12);
2098 NumCommands = Get32(p + 16); 2106 NumCommands = Get32(p + 16);
2099 SizeKB = Get32(p + 20); 2107 SizeKB = Get32(p + 20);
2100}; 2108}
2101 2109
2102// used for section->flags 2110// used for section->flags
2103#define SF_SELECTED (1 << 0) 2111#define SF_SELECTED (1 << 0)
@@ -2182,7 +2190,7 @@ bool CInArchive::PrintSectionBegin(const CSection &sect, unsigned index)
2182 { 2190 {
2183 TabString("SectionIn"); 2191 TabString("SectionIn");
2184 UInt32 instTypes = sect.InstallTypes; 2192 UInt32 instTypes = sect.InstallTypes;
2185 for (int i = 0; i < 32; i++, instTypes >>= 1) 2193 for (unsigned i = 0; i < 32; i++, instTypes >>= 1)
2186 if ((instTypes & 1) != 0) 2194 if ((instTypes & 1) != 0)
2187 { 2195 {
2188 AddParam_UInt(i + 1); 2196 AddParam_UInt(i + 1);
@@ -2270,7 +2278,7 @@ void CInArchive::MessageBox_MB_Part(UInt32 param)
2270 { 2278 {
2271 UInt32 v = param & 0xF; 2279 UInt32 v = param & 0xF;
2272 Script += " MB_"; 2280 Script += " MB_";
2273 if (v < ARRAY_SIZE(k_MB_Buttons)) 2281 if (v < Z7_ARRAY_SIZE(k_MB_Buttons))
2274 Script += k_MB_Buttons[v]; 2282 Script += k_MB_Buttons[v];
2275 else 2283 else
2276 { 2284 {
@@ -2283,7 +2291,7 @@ void CInArchive::MessageBox_MB_Part(UInt32 param)
2283 if (icon != 0) 2291 if (icon != 0)
2284 { 2292 {
2285 Script += "|MB_"; 2293 Script += "|MB_";
2286 if (icon < ARRAY_SIZE(k_MB_Icons) && k_MB_Icons[icon] != 0) 2294 if (icon < Z7_ARRAY_SIZE(k_MB_Icons) && k_MB_Icons[icon])
2287 Script += k_MB_Icons[icon]; 2295 Script += k_MB_Icons[icon];
2288 else 2296 else
2289 { 2297 {
@@ -2308,7 +2316,7 @@ void CInArchive::MessageBox_MB_Part(UInt32 param)
2308 else if (modal == 2) Script += "|MB_TASKMODAL"; 2316 else if (modal == 2) Script += "|MB_TASKMODAL";
2309 else if (modal == 3) Script += "|0x3000"; 2317 else if (modal == 3) Script += "|0x3000";
2310 UInt32 flags = (param >> 14); 2318 UInt32 flags = (param >> 14);
2311 for (unsigned i = 0; i < ARRAY_SIZE(k_MB_Flags); i++) 2319 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_MB_Flags); i++)
2312 if ((flags & (1 << i)) != 0) 2320 if ((flags & (1 << i)) != 0)
2313 { 2321 {
2314 Script += "|MB_"; 2322 Script += "|MB_";
@@ -2381,7 +2389,7 @@ AString CInArchive::GetFormatDescription() const
2381 if (BadCmd >= 0) 2389 if (BadCmd >= 0)
2382 { 2390 {
2383 AddString(s, "BadCmd="); 2391 AddString(s, "BadCmd=");
2384 UIntToString(s, BadCmd); 2392 UIntToString(s, (UInt32)BadCmd);
2385 } 2393 }
2386 return s; 2394 return s;
2387} 2395}
@@ -2455,7 +2463,7 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p)
2455 2463
2456 for (UInt32 kkk = 0; kkk < bh.Num; kkk++, p += kCmdSize) 2464 for (UInt32 kkk = 0; kkk < bh.Num; kkk++, p += kCmdSize)
2457 { 2465 {
2458 UInt32 id = GetCmd(Get32(p)); 2466 const UInt32 id = GetCmd(Get32(p));
2459 if (id >= kNumCmds) 2467 if (id >= kNumCmds)
2460 continue; 2468 continue;
2461 if (BadCmd >= 0 && id >= (unsigned)BadCmd) 2469 if (BadCmd >= 0 && id >= (unsigned)BadCmd)
@@ -2465,7 +2473,7 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p)
2465 { 2473 {
2466 if (id == EW_RESERVEDOPCODE) 2474 if (id == EW_RESERVEDOPCODE)
2467 { 2475 {
2468 BadCmd = id; 2476 BadCmd = (int)id;
2469 continue; 2477 continue;
2470 } 2478 }
2471 } 2479 }
@@ -2474,23 +2482,23 @@ void CInArchive::FindBadCmd(const CBlockHeader &bh, const Byte *p)
2474 // if (id == EW_GETLABELADDR || id == EW_GETFUNCTIONADDR) 2482 // if (id == EW_GETLABELADDR || id == EW_GETFUNCTIONADDR)
2475 if (id == EW_RESERVEDOPCODE || id == EW_GETOSINFO) 2483 if (id == EW_RESERVEDOPCODE || id == EW_GETOSINFO)
2476 { 2484 {
2477 BadCmd = id; 2485 BadCmd = (int)id;
2478 continue; 2486 continue;
2479 } 2487 }
2480 } 2488 }
2481 for (i = 6; i != 0; i--) 2489 for (i = 6; i != 0; i--)
2482 { 2490 {
2483 UInt32 param = Get32(p + i * 4); 2491 const UInt32 param = Get32(p + i * 4);
2484 if (param != 0) 2492 if (param != 0)
2485 break; 2493 break;
2486 } 2494 }
2487 if (id == EW_FINDPROC && i == 0) 2495 if (id == EW_FINDPROC && i == 0)
2488 { 2496 {
2489 BadCmd = id; 2497 BadCmd = (int)id;
2490 continue; 2498 continue;
2491 } 2499 }
2492 if (k_Commands[id].NumParams < i) 2500 if (k_Commands[id].NumParams < i)
2493 BadCmd = id; 2501 BadCmd = (int)id;
2494 } 2502 }
2495} 2503}
2496 2504
@@ -2770,13 +2778,13 @@ Int32 CInArchive::GetVarIndex(UInt32 strPos) const
2770 else if (c != NS_CODE_VAR) 2778 else if (c != NS_CODE_VAR)
2771 return -1; 2779 return -1;
2772 2780
2773 unsigned c0 = p[1]; 2781 const unsigned c0 = p[1];
2774 if (c0 == 0) 2782 if (c0 == 0)
2775 return -1; 2783 return -1;
2776 unsigned c1 = p[2]; 2784 const unsigned c1 = p[2];
2777 if (c1 == 0) 2785 if (c1 == 0)
2778 return -1; 2786 return -1;
2779 return DECODE_NUMBER_FROM_2_CHARS(c0, c1); 2787 return (Int32)DECODE_NUMBER_FROM_2_CHARS(c0, c1);
2780} 2788}
2781 2789
2782Int32 CInArchive::GetVarIndex(UInt32 strPos, UInt32 &resOffset) const 2790Int32 CInArchive::GetVarIndex(UInt32 strPos, UInt32 &resOffset) const
@@ -2870,18 +2878,18 @@ static bool IsAbsolutePath(const char *s)
2870void CInArchive::SetItemName(CItem &item, UInt32 strPos) 2878void CInArchive::SetItemName(CItem &item, UInt32 strPos)
2871{ 2879{
2872 ReadString2_Raw(strPos); 2880 ReadString2_Raw(strPos);
2873 bool isAbs = IsAbsolutePathVar(strPos); 2881 const bool isAbs = IsAbsolutePathVar(strPos);
2874 if (IsUnicode) 2882 if (IsUnicode)
2875 { 2883 {
2876 item.NameU = Raw_UString; 2884 item.NameU = Raw_UString;
2877 if (!isAbs && !IsAbsolutePath(Raw_UString)) 2885 if (!isAbs && !IsAbsolutePath(Raw_UString))
2878 item.Prefix = UPrefixes.Size() - 1; 2886 item.Prefix = (int)UPrefixes.Size() - 1;
2879 } 2887 }
2880 else 2888 else
2881 { 2889 {
2882 item.NameA = Raw_AString; 2890 item.NameA = Raw_AString;
2883 if (!isAbs && !IsAbsolutePath(Raw_AString)) 2891 if (!isAbs && !IsAbsolutePath(Raw_AString))
2884 item.Prefix = APrefixes.Size() - 1; 2892 item.Prefix = (int)APrefixes.Size() - 1;
2885 } 2893 }
2886} 2894}
2887 2895
@@ -2949,9 +2957,9 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
2949 for (int i = 0; i < 5; i++) 2957 for (int i = 0; i < 5; i++)
2950 params[i] = Get32(p + 44 + 4 * i); 2958 params[i] = Get32(p + 44 + 4 * i);
2951 2959
2952 SET_FUNC_REF(preFunc, CMD_REF_Pre); 2960 SET_FUNC_REF(preFunc, CMD_REF_Pre)
2953 SET_FUNC_REF(showFunc, CMD_REF_Show); 2961 SET_FUNC_REF(showFunc, CMD_REF_Show)
2954 SET_FUNC_REF(leaveFunc, CMD_REF_Leave); 2962 SET_FUNC_REF(leaveFunc, CMD_REF_Leave)
2955 2963
2956 if (wndProcID == PWP_COMPLETED) 2964 if (wndProcID == PWP_COMPLETED)
2957 CommentOpen(); 2965 CommentOpen();
@@ -2969,7 +2977,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
2969 else 2977 else
2970 s += IsInstaller ? "Page " : "UninstPage "; 2978 s += IsInstaller ? "Page " : "UninstPage ";
2971 2979
2972 if (wndProcID < ARRAY_SIZE(kPageTypes)) 2980 if (wndProcID < Z7_ARRAY_SIZE(kPageTypes))
2973 s += kPageTypes[wndProcID]; 2981 s += kPageTypes[wndProcID];
2974 else 2982 else
2975 Add_UInt(wndProcID); 2983 Add_UInt(wndProcID);
@@ -3189,11 +3197,11 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3189 } 3197 }
3190 */ 3198 */
3191 if (IsFunc(flg) 3199 if (IsFunc(flg)
3192 && bh.Num - kkk >= ARRAY_SIZE(k_InitPluginDir_Commands) 3200 && bh.Num - kkk >= Z7_ARRAY_SIZE(k_InitPluginDir_Commands)
3193 && CompareCommands(p, k_InitPluginDir_Commands, ARRAY_SIZE(k_InitPluginDir_Commands))) 3201 && CompareCommands(p, k_InitPluginDir_Commands, Z7_ARRAY_SIZE(k_InitPluginDir_Commands)))
3194 { 3202 {
3195 InitPluginsDir_Start = kkk; 3203 InitPluginsDir_Start = (int)kkk;
3196 InitPluginsDir_End = (int)(kkk + ARRAY_SIZE(k_InitPluginDir_Commands)); 3204 InitPluginsDir_End = (int)(kkk + Z7_ARRAY_SIZE(k_InitPluginDir_Commands));
3197 labels[kkk] |= CMD_REF_InitPluginDir; 3205 labels[kkk] |= CMD_REF_InitPluginDir;
3198 break; 3206 break;
3199 } 3207 }
@@ -3356,7 +3364,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3356 3364
3357 unsigned numSkipParams = 0; 3365 unsigned numSkipParams = 0;
3358 3366
3359 if (commandId < ARRAY_SIZE(k_Commands) && commandId < numSupportedCommands) 3367 if (commandId < Z7_ARRAY_SIZE(k_Commands) && commandId < numSupportedCommands)
3360 { 3368 {
3361 numSkipParams = k_Commands[commandId].NumParams; 3369 numSkipParams = k_Commands[commandId].NumParams;
3362 const char *sz = k_CommandNames[commandId]; 3370 const char *sz = k_CommandNames[commandId];
@@ -3505,9 +3513,9 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3505 UInt32 b1 = nsisMB >> 21; // NSIS 2.06+ 3513 UInt32 b1 = nsisMB >> 21; // NSIS 2.06+
3506 UInt32 b2 = nsisMB >> 20; // NSIS old 3514 UInt32 b2 = nsisMB >> 20; // NSIS old
3507 Int32 asf = (Int32)nsisMB; 3515 Int32 asf = (Int32)nsisMB;
3508 if (mb == (MY__MB_ABORTRETRYIGNORE | MY__MB_ICONSTOP) && (b1 == MY__IDIGNORE || b2 == MY__IDIGNORE)) 3516 if (mb == (Z7_NSIS_WIN_MB_ABORTRETRYIGNORE | Z7_NSIS_WIN_MB_ICONSTOP) && (b1 == Z7_NSIS_WIN_IDIGNORE || b2 == Z7_NSIS_WIN_IDIGNORE))
3509 asf = -1; 3517 asf = -1;
3510 else if (mb == (MY__MB_RETRYCANCEL | MY__MB_ICONSTOP) && (b1 == MY__IDCANCEL || b2 == MY__IDCANCEL)) 3518 else if (mb == (Z7_NSIS_WIN_MB_RETRYCANCEL | Z7_NSIS_WIN_MB_ICONSTOP) && (b1 == Z7_NSIS_WIN_IDCANCEL || b2 == Z7_NSIS_WIN_IDCANCEL))
3511 asf = -2; 3519 asf = -2;
3512 else 3520 else
3513 { 3521 {
@@ -3591,7 +3599,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3591 #ifdef NSIS_SCRIPT 3599 #ifdef NSIS_SCRIPT
3592 AddParam(params[0]); 3600 AddParam(params[0]);
3593 Space(); 3601 Space();
3594 FlagsToString2(s, g_WinAttrib, ARRAY_SIZE(g_WinAttrib), params[1]); 3602 FlagsToString2(s, g_WinAttrib, Z7_ARRAY_SIZE(g_WinAttrib), params[1]);
3595 #endif 3603 #endif
3596 break; 3604 break;
3597 } 3605 }
@@ -3603,7 +3611,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3603 NSIS installer uses alternative path, if main path 3611 NSIS installer uses alternative path, if main path
3604 from params[0] is not absolute path */ 3612 from params[0] is not absolute path */
3605 3613
3606 bool pathOk = (params[0] > 0) && IsGoodString(params[0]); 3614 const bool pathOk = (params[0] > 0) && IsGoodString(params[0]);
3607 3615
3608 if (!pathOk) 3616 if (!pathOk)
3609 { 3617 {
@@ -3613,9 +3621,11 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3613 break; 3621 break;
3614 } 3622 }
3615 3623
3624 #ifdef NSIS_SCRIPT
3625
3616 bool altPathOk = true; 3626 bool altPathOk = true;
3617 3627
3618 UInt32 altParam = params[3]; 3628 const UInt32 altParam = params[3];
3619 if (altParam != 0) 3629 if (altParam != 0)
3620 { 3630 {
3621 altPathOk = false; 3631 altPathOk = false;
@@ -3624,9 +3634,6 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3624 altPathOk = AreTwoParamStringsEqual(altParam + additional, params[0]); 3634 altPathOk = AreTwoParamStringsEqual(altParam + additional, params[0]);
3625 } 3635 }
3626 3636
3627
3628 #ifdef NSIS_SCRIPT
3629
3630 AddParam(params[0]); 3637 AddParam(params[0]);
3631 3638
3632 /* 3639 /*
@@ -3640,8 +3647,6 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3640 AddParam(params[3]); 3647 AddParam(params[3]);
3641 } 3648 }
3642 3649
3643 #endif
3644
3645 if (!altPathOk) 3650 if (!altPathOk)
3646 { 3651 {
3647 #ifdef NSIS_SCRIPT 3652 #ifdef NSIS_SCRIPT
@@ -3649,9 +3654,11 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3649 #endif 3654 #endif
3650 } 3655 }
3651 3656
3657 #endif
3658
3652 if (BadCmd >= 0 && BadCmd <= EW_WRITEUNINSTALLER) 3659 if (BadCmd >= 0 && BadCmd <= EW_WRITEUNINSTALLER)
3653 { 3660 {
3654 /* We don't cases with incorrect installer commands. 3661 /* We don't support cases with incorrect installer commands.
3655 Such bad installer item can break unpacking for other items. */ 3662 Such bad installer item can break unpacking for other items. */
3656 #ifdef NSIS_SCRIPT 3663 #ifdef NSIS_SCRIPT
3657 AddError("SKIP possible BadCmd"); 3664 AddError("SKIP possible BadCmd");
@@ -3659,13 +3666,23 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3659 break; 3666 break;
3660 } 3667 }
3661 3668
3662 CItem &item = Items.AddNew();; 3669 CItem &item = Items.AddNew();
3663 3670
3664 SetItemName(item, params[0]); 3671 SetItemName(item, params[0]);
3665 3672
3666 item.Pos = params[1]; 3673 item.Pos = params[1];
3667 item.PatchSize = params[2]; 3674 item.PatchSize = params[2];
3668 item.IsUninstaller = true; 3675 item.IsUninstaller = true;
3676 const UInt32 param3 = params[3];
3677 if (param3 != 0 && item.Prefix != -1)
3678 {
3679 /* (item.Prefix != -1) case means that param[0] path was not absolute.
3680 So we use params[3] in that case, as original nsis */
3681 SetItemName(item, param3);
3682 }
3683 /* UNINSTALLER file doesn't use directory prefixes.
3684 So we remove prefix: */
3685 item.Prefix = -1;
3669 3686
3670 /* 3687 /*
3671 // we can add second time to test the code 3688 // we can add second time to test the code
@@ -3834,12 +3851,12 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3834 3851
3835 s += "Call "; 3852 s += "Call ";
3836 if ((Int32)params[0] < 0) 3853 if ((Int32)params[0] < 0)
3837 Add_Var(-((Int32)params[0] + 1)); 3854 Add_Var((UInt32)-((Int32)params[0] + 1));
3838 else if (params[0] == 0) 3855 else if (params[0] == 0)
3839 s += '0'; 3856 s += '0';
3840 else 3857 else
3841 { 3858 {
3842 UInt32 val = params[0] - 1; 3859 const UInt32 val = params[0] - 1;
3843 if (params[1] == 1) // it's Call :Label 3860 if (params[1] == 1) // it's Call :Label
3844 { 3861 {
3845 s += ':'; 3862 s += ':';
@@ -3860,8 +3877,8 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3860 3877
3861 case EW_CHDETAILSVIEW: 3878 case EW_CHDETAILSVIEW:
3862 { 3879 {
3863 if (params[0] == MY__SW_SHOWNA && params[1] == MY__SW_HIDE) s += " show"; 3880 if (params[0] == Z7_NSIS_WIN_SW_SHOWNA && params[1] == Z7_NSIS_WIN_SW_HIDE) s += " show";
3864 else if (params[1] == MY__SW_SHOWNA && params[0] == MY__SW_HIDE) s += " hide"; 3881 else if (params[1] == Z7_NSIS_WIN_SW_SHOWNA && params[0] == Z7_NSIS_WIN_SW_HIDE) s += " hide";
3865 else 3882 else
3866 for (int i = 0; i < 2; i++) 3883 for (int i = 0; i < 2; i++)
3867 { 3884 {
@@ -3935,7 +3952,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
3935 Add_ExecFlags(params[2]); 3952 Add_ExecFlags(params[2]);
3936 Add_GotoVars2(&params[0]); 3953 Add_GotoVars2(&params[0]);
3937 /* 3954 /*
3938 static const unsigned kIfErrors = 2; 3955 const unsigned kIfErrors = 2;
3939 if (params[2] != kIfErrors && params[3] != 0xFFFFFFFF || 3956 if (params[2] != kIfErrors && params[3] != 0xFFFFFFFF ||
3940 params[2] == kIfErrors && params[3] != 0) 3957 params[2] == kIfErrors && params[3] != 0)
3941 { 3958 {
@@ -4244,7 +4261,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4244 4261
4245 AString bk; 4262 AString bk;
4246 bool bkc = false; 4263 bool bkc = false;
4247 if (colors.bkmode == MY__TRANSPARENT) 4264 if (colors.bkmode == Z7_NSIS_WIN_TRANSPARENT)
4248 bk += " transparent"; 4265 bk += " transparent";
4249 else if (colors.flags & kColorsFlags_BKB) 4266 else if (colors.flags & kColorsFlags_BKB)
4250 { 4267 {
@@ -4305,7 +4322,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4305 bool valDefined = false; 4322 bool valDefined = false;
4306 if (StringToUInt32(sw, val)) 4323 if (StringToUInt32(sw, val))
4307 { 4324 {
4308 if (val < ARRAY_SIZE(kShowWindow_Commands)) 4325 if (val < Z7_ARRAY_SIZE(kShowWindow_Commands))
4309 { 4326 {
4310 sw.Empty(); 4327 sw.Empty();
4311 sw += "${"; 4328 sw += "${";
@@ -4338,10 +4355,10 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4338 case EW_SHELLEXEC: 4355 case EW_SHELLEXEC:
4339 { 4356 {
4340 AddParams(params, 2); 4357 AddParams(params, 2);
4341 if (params[2] != 0 || params[3] != MY__SW_SHOWNORMAL) 4358 if (params[2] != 0 || params[3] != Z7_NSIS_WIN_SW_SHOWNORMAL)
4342 { 4359 {
4343 AddParam(params[2]); 4360 AddParam(params[2]);
4344 if (params[3] != MY__SW_SHOWNORMAL) 4361 if (params[3] != Z7_NSIS_WIN_SW_SHOWNORMAL)
4345 { 4362 {
4346 Space(); 4363 Space();
4347 Add_ShowWindow_Cmd(params[3]); 4364 Add_ShowWindow_Cmd(params[3]);
@@ -4442,8 +4459,8 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4442 UInt32 sw = (spec >> sw_shift) & sw_mask; 4459 UInt32 sw = (spec >> sw_shift) & sw_mask;
4443 Space(); 4460 Space();
4444 // NSIS encoder replaces these names: 4461 // NSIS encoder replaces these names:
4445 if (sw == MY__SW_SHOWMINNOACTIVE) 4462 if (sw == Z7_NSIS_WIN_SW_SHOWMINNOACTIVE)
4446 sw = MY__SW_SHOWMINIMIZED; 4463 sw = Z7_NSIS_WIN_SW_SHOWMINIMIZED;
4447 if (sw == 0) 4464 if (sw == 0)
4448 AddQuotes(); 4465 AddQuotes();
4449 else 4466 else
@@ -4467,7 +4484,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4467 if (modKey & 4) s += "ALT|"; 4484 if (modKey & 4) s += "ALT|";
4468 if (modKey & 8) s += "EXT|"; 4485 if (modKey & 8) s += "EXT|";
4469 4486
4470 static const unsigned kMy_VK_F1 = 0x70; 4487 const unsigned kMy_VK_F1 = 0x70;
4471 if (key >= kMy_VK_F1 && key <= kMy_VK_F1 + 23) 4488 if (key >= kMy_VK_F1 && key <= kMy_VK_F1 + 23)
4472 { 4489 {
4473 s += 'F'; 4490 s += 'F';
@@ -4559,7 +4576,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4559 4576
4560 case EW_WRITEREG: 4577 case EW_WRITEREG:
4561 { 4578 {
4562 const char *s2 = 0; 4579 const char *s2 = NULL;
4563 switch (params[4]) 4580 switch (params[4])
4564 { 4581 {
4565 case 1: s2 = "Str"; break; 4582 case 1: s2 = "Str"; break;
@@ -4642,20 +4659,42 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4642 break; 4659 break;
4643 } 4660 }
4644 4661
4662 #endif
4663
4645 case EW_FOPEN: 4664 case EW_FOPEN:
4646 { 4665 {
4666 /*
4667 the pattern for empty files is following:
4668 FileOpen $0 "file_name" w
4669 FileClose $0
4670 */
4671
4672 const UInt32 acc = params[1]; // dwDesiredAccess
4673 const UInt32 creat = params[2]; // dwCreationDisposition
4674 if (creat == Z7_NSIS_WIN_CREATE_ALWAYS && acc == Z7_NSIS_WIN_GENERIC_WRITE)
4675 {
4676 if (kkk + 1 < bh.Num)
4677 if (Get32(p + kCmdSize) == EW_FCLOSE)
4678 if (Get32(p + kCmdSize + 4) == params[0])
4679 {
4680 CItem &item = Items.AddNew();
4681 item.IsEmptyFile = true;
4682 SetItemName(item, params[3]);
4683 }
4684 }
4685
4686 #ifdef NSIS_SCRIPT
4687
4647 AddParam_Var(params[0]); 4688 AddParam_Var(params[0]);
4648 AddParam(params[3]); 4689 AddParam(params[3]);
4649 UInt32 acc = params[1]; // dwDesiredAccess
4650 UInt32 creat = params[2]; // dwCreationDisposition
4651 if (acc == 0 && creat == 0) 4690 if (acc == 0 && creat == 0)
4652 break; 4691 break;
4653 char cc = 0; 4692 char cc = 0;
4654 if (acc == MY__GENERIC_READ && creat == OPEN_EXISTING) 4693 if (creat == Z7_NSIS_WIN_OPEN_EXISTING && acc == Z7_NSIS_WIN_GENERIC_READ)
4655 cc = 'r'; 4694 cc = 'r';
4656 else if (creat == CREATE_ALWAYS && acc == MY__GENERIC_WRITE) 4695 else if (creat == Z7_NSIS_WIN_CREATE_ALWAYS && acc == Z7_NSIS_WIN_GENERIC_WRITE)
4657 cc = 'w'; 4696 cc = 'w';
4658 else if (creat == OPEN_ALWAYS && (acc == (MY__GENERIC_WRITE | MY__GENERIC_READ))) 4697 else if (creat == Z7_NSIS_WIN_OPEN_ALWAYS && (acc == (Z7_NSIS_WIN_GENERIC_WRITE | Z7_NSIS_WIN_GENERIC_READ)))
4659 cc = 'a'; 4698 cc = 'a';
4660 // cc = 0; 4699 // cc = 0;
4661 if (cc != 0) 4700 if (cc != 0)
@@ -4665,28 +4704,32 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4665 break; 4704 break;
4666 } 4705 }
4667 4706
4668 if (acc & MY__GENERIC_READ) s += " GENERIC_READ"; 4707 if (acc & Z7_NSIS_WIN_GENERIC_READ) s += " GENERIC_READ";
4669 if (acc & MY__GENERIC_WRITE) s += " GENERIC_WRITE"; 4708 if (acc & Z7_NSIS_WIN_GENERIC_WRITE) s += " GENERIC_WRITE";
4670 if (acc & MY__GENERIC_EXECUTE) s += " GENERIC_EXECUTE"; 4709 if (acc & Z7_NSIS_WIN_GENERIC_EXECUTE) s += " GENERIC_EXECUTE";
4671 if (acc & MY__GENERIC_ALL) s += " GENERIC_ALL"; 4710 if (acc & Z7_NSIS_WIN_GENERIC_ALL) s += " GENERIC_ALL";
4672 4711
4673 const char *s2 = NULL; 4712 const char *s2 = NULL;
4674 switch (creat) 4713 switch (creat)
4675 { 4714 {
4676 case MY__CREATE_NEW: s2 = "CREATE_NEW"; break; 4715 case Z7_NSIS_WIN_CREATE_NEW: s2 = "CREATE_NEW"; break;
4677 case MY__CREATE_ALWAYS: s2 = "CREATE_ALWAYS"; break; 4716 case Z7_NSIS_WIN_CREATE_ALWAYS: s2 = "CREATE_ALWAYS"; break;
4678 case MY__OPEN_EXISTING: s2 = "OPEN_EXISTING"; break; 4717 case Z7_NSIS_WIN_OPEN_EXISTING: s2 = "OPEN_EXISTING"; break;
4679 case MY__OPEN_ALWAYS: s2 = "OPEN_ALWAYS"; break; 4718 case Z7_NSIS_WIN_OPEN_ALWAYS: s2 = "OPEN_ALWAYS"; break;
4680 case MY__TRUNCATE_EXISTING: s2 = "TRUNCATE_EXISTING"; break; 4719 case Z7_NSIS_WIN_TRUNCATE_EXISTING: s2 = "TRUNCATE_EXISTING"; break;
4681 } 4720 }
4682 Space(); 4721 Space();
4683 if (s2) 4722 if (s2)
4684 s += s2; 4723 s += s2;
4685 else 4724 else
4686 Add_UInt(creat); 4725 Add_UInt(creat);
4726 #endif
4727
4687 break; 4728 break;
4688 } 4729 }
4689 4730
4731 #ifdef NSIS_SCRIPT
4732
4690 case EW_FPUTS: 4733 case EW_FPUTS:
4691 case EW_FPUTWS: 4734 case EW_FPUTWS:
4692 { 4735 {
@@ -4780,7 +4823,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4780 else 4823 else
4781 { 4824 {
4782 s += "Set"; 4825 s += "Set";
4783 UInt32 t = -(Int32)params[2] - 1; 4826 const UInt32 t = (UInt32)(-(Int32)params[2] - 1);
4784 Add_SectOp(t); 4827 Add_SectOp(t);
4785 AddParam(params[0]); 4828 AddParam(params[0]);
4786 AddParam(params[t == 0 ? 4 : 1]); 4829 AddParam(params[t == 0 ? 4 : 1]);
@@ -4793,7 +4836,7 @@ HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
4793 4836
4794 case EW_INSTTYPESET: 4837 case EW_INSTTYPESET:
4795 { 4838 {
4796 int numQwParams = 0; 4839 unsigned numQwParams = 0;
4797 const char *s2; 4840 const char *s2;
4798 if (params[3] == 0) 4841 if (params[3] == 0)
4799 { 4842 {
@@ -4952,7 +4995,18 @@ static int CompareItems(void *const *p1, void *const *p2, void *param)
4952{ 4995{
4953 const CItem &i1 = **(const CItem *const *)p1; 4996 const CItem &i1 = **(const CItem *const *)p1;
4954 const CItem &i2 = **(const CItem *const *)p2; 4997 const CItem &i2 = **(const CItem *const *)p2;
4955 RINOZ(MyCompare(i1.Pos, i2.Pos)); 4998 RINOZ(MyCompare(i1.Pos, i2.Pos))
4999
5000 /* In another code we check CItem::Pos after each solid item.
5001 So here we place empty files before all non empty files */
5002 if (i1.IsEmptyFile)
5003 {
5004 if (!i2.IsEmptyFile)
5005 return -1;
5006 }
5007 else if (i2.IsEmptyFile)
5008 return 1;
5009
4956 const CInArchive *inArchive = (const CInArchive *)param; 5010 const CInArchive *inArchive = (const CInArchive *)param;
4957 if (inArchive->IsUnicode) 5011 if (inArchive->IsUnicode)
4958 { 5012 {
@@ -4962,9 +5016,9 @@ static int CompareItems(void *const *p1, void *const *p2, void *param)
4962 if (i2.Prefix < 0) return 1; 5016 if (i2.Prefix < 0) return 1;
4963 RINOZ( 5017 RINOZ(
4964 inArchive->UPrefixes[i1.Prefix].Compare( 5018 inArchive->UPrefixes[i1.Prefix].Compare(
4965 inArchive->UPrefixes[i2.Prefix])); 5019 inArchive->UPrefixes[i2.Prefix]))
4966 } 5020 }
4967 RINOZ(i1.NameU.Compare(i2.NameU)); 5021 RINOZ(i1.NameU.Compare(i2.NameU))
4968 } 5022 }
4969 else 5023 else
4970 { 5024 {
@@ -4974,9 +5028,9 @@ static int CompareItems(void *const *p1, void *const *p2, void *param)
4974 if (i2.Prefix < 0) return 1; 5028 if (i2.Prefix < 0) return 1;
4975 RINOZ(strcmp( 5029 RINOZ(strcmp(
4976 inArchive->APrefixes[i1.Prefix], 5030 inArchive->APrefixes[i1.Prefix],
4977 inArchive->APrefixes[i2.Prefix])); 5031 inArchive->APrefixes[i2.Prefix]))
4978 } 5032 }
4979 RINOZ(strcmp(i1.NameA, i2.NameA)); 5033 RINOZ(strcmp(i1.NameA, i2.NameA))
4980 } 5034 }
4981 return 0; 5035 return 0;
4982} 5036}
@@ -4990,6 +5044,8 @@ HRESULT CInArchive::SortItems()
4990 for (i = 0; i + 1 < Items.Size(); i++) 5044 for (i = 0; i + 1 < Items.Size(); i++)
4991 { 5045 {
4992 const CItem &i1 = Items[i]; 5046 const CItem &i1 = Items[i];
5047 if (i1.IsEmptyFile)
5048 continue;
4993 const CItem &i2 = Items[i + 1]; 5049 const CItem &i2 = Items[i + 1];
4994 if (i1.Pos != i2.Pos) 5050 if (i1.Pos != i2.Pos)
4995 continue; 5051 continue;
@@ -5019,10 +5075,14 @@ HRESULT CInArchive::SortItems()
5019 for (i = 0; i < Items.Size(); i++) 5075 for (i = 0; i < Items.Size(); i++)
5020 { 5076 {
5021 CItem &item = Items[i]; 5077 CItem &item = Items[i];
5022 UInt32 curPos = item.Pos + 4; 5078 if (item.IsEmptyFile)
5079 continue;
5080 const UInt32 curPos = item.Pos + 4;
5023 for (unsigned nextIndex = i + 1; nextIndex < Items.Size(); nextIndex++) 5081 for (unsigned nextIndex = i + 1; nextIndex < Items.Size(); nextIndex++)
5024 { 5082 {
5025 UInt32 nextPos = Items[nextIndex].Pos; 5083 const CItem &nextItem = Items[nextIndex];
5084 // if (nextItem.IsEmptyFile) continue;
5085 const UInt32 nextPos = nextItem.Pos;
5026 if (curPos <= nextPos) 5086 if (curPos <= nextPos)
5027 { 5087 {
5028 item.EstimatedSize_Defined = true; 5088 item.EstimatedSize_Defined = true;
@@ -5037,11 +5097,13 @@ HRESULT CInArchive::SortItems()
5037 for (i = 0; i < Items.Size(); i++) 5097 for (i = 0; i < Items.Size(); i++)
5038 { 5098 {
5039 CItem &item = Items[i]; 5099 CItem &item = Items[i];
5040 RINOK(SeekToNonSolidItem(i)); 5100 if (item.IsEmptyFile)
5101 continue;
5102 RINOK(SeekToNonSolidItem(i))
5041 const UInt32 kSigSize = 4 + 1 + 1 + 4; // size,[flag],prop,dict 5103 const UInt32 kSigSize = 4 + 1 + 1 + 4; // size,[flag],prop,dict
5042 BYTE sig[kSigSize]; 5104 BYTE sig[kSigSize];
5043 size_t processedSize = kSigSize; 5105 size_t processedSize = kSigSize;
5044 RINOK(ReadStream(_stream, sig, &processedSize)); 5106 RINOK(ReadStream(_stream, sig, &processedSize))
5045 if (processedSize < 4) 5107 if (processedSize < 4)
5046 return S_FALSE; 5108 return S_FALSE;
5047 UInt32 size = Get32(sig); 5109 UInt32 size = Get32(sig);
@@ -5218,7 +5280,7 @@ HRESULT CInArchive::Parse()
5218 if (Method != NMethodType::kCopy) 5280 if (Method != NMethodType::kCopy)
5219 { 5281 {
5220 const char *m = NULL; 5282 const char *m = NULL;
5221 switch (Method) 5283 switch ((int)Method)
5222 { 5284 {
5223 case NMethodType::kDeflate: m = "zlib"; break; 5285 case NMethodType::kDeflate: m = "zlib"; break;
5224 case NMethodType::kBZip2: m = "bzip2"; break; 5286 case NMethodType::kBZip2: m = "bzip2"; break;
@@ -5451,7 +5513,7 @@ HRESULT CInArchive::Parse()
5451 if (val != 0) 5513 if (val != 0)
5452 { 5514 {
5453 Script += "LicenseLangString "; 5515 Script += "LicenseLangString ";
5454 Add_LangStr_Simple(licenseLangIndex); 5516 Add_LangStr_Simple((UInt32)licenseLangIndex);
5455 AddParam_UInt(langID); 5517 AddParam_UInt(langID);
5456 AddLicense(val, langID); 5518 AddLicense(val, langID);
5457 noParseStringIndexes.AddToUniqueSorted(val); 5519 noParseStringIndexes.AddToUniqueSorted(val);
@@ -5470,7 +5532,7 @@ HRESULT CInArchive::Parse()
5470 const UInt16 langID = Get16(p); 5532 const UInt16 langID = Get16(p);
5471 if (i == 0 || langID == 1033) 5533 if (i == 0 || langID == 1033)
5472 _mainLang = p + 10; 5534 _mainLang = p + 10;
5473 for (unsigned k = 0; k < ARRAY_SIZE(names) && k < numStrings; k++) 5535 for (unsigned k = 0; k < Z7_ARRAY_SIZE(names) && k < numStrings; k++)
5474 { 5536 {
5475 UInt32 v = Get32(p + 10 + k * 4); 5537 UInt32 v = Get32(p + 10 + k * 4);
5476 if (v != 0 && (langID == 1033 || names[k] == 0)) 5538 if (v != 0 && (langID == 1033 || names[k] == 0))
@@ -5567,7 +5629,7 @@ HRESULT CInArchive::Parse()
5567 } 5629 }
5568 5630
5569 onFuncOffset = paramsOffset + 40; 5631 onFuncOffset = paramsOffset + 40;
5570 numOnFunc = ARRAY_SIZE(kOnFunc); 5632 numOnFunc = Z7_ARRAY_SIZE(kOnFunc);
5571 if (bhPages.Offset == 276) 5633 if (bhPages.Offset == 276)
5572 numOnFunc--; 5634 numOnFunc--;
5573 p2 += 40 + numOnFunc * 4; 5635 p2 += 40 + numOnFunc * 4;
@@ -5629,7 +5691,7 @@ HRESULT CInArchive::Parse()
5629 5691
5630 #endif 5692 #endif
5631 5693
5632 RINOK(ReadEntries(bhEntries)); 5694 RINOK(ReadEntries(bhEntries))
5633 5695
5634 #ifdef NSIS_SCRIPT 5696 #ifdef NSIS_SCRIPT
5635 5697
@@ -5747,14 +5809,14 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size)
5747 5809
5748 if (IsSolid) 5810 if (IsSolid)
5749 { 5811 {
5750 RINOK(SeekTo_DataStreamOffset()); 5812 RINOK(SeekTo_DataStreamOffset())
5751 } 5813 }
5752 else 5814 else
5753 { 5815 {
5754 _headerIsCompressed = ((compressedHeaderSize & kMask_IsCompressed) != 0); 5816 _headerIsCompressed = ((compressedHeaderSize & kMask_IsCompressed) != 0);
5755 compressedHeaderSize &= ~kMask_IsCompressed; 5817 compressedHeaderSize &= ~kMask_IsCompressed;
5756 _nonSolidStartOffset = compressedHeaderSize; 5818 _nonSolidStartOffset = compressedHeaderSize;
5757 RINOK(SeekTo(DataStreamOffset + 4)); 5819 RINOK(SeekTo(DataStreamOffset + 4))
5758 } 5820 }
5759 5821
5760 if (FirstHeader.HeaderSize == 0) 5822 if (FirstHeader.HeaderSize == 0)
@@ -5775,12 +5837,12 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size)
5775 5837
5776 if (_headerIsCompressed) 5838 if (_headerIsCompressed)
5777 { 5839 {
5778 RINOK(Decoder.Init(_stream, UseFilter)); 5840 RINOK(Decoder.Init(_stream, UseFilter))
5779 if (IsSolid) 5841 if (IsSolid)
5780 { 5842 {
5781 size_t processedSize = 4; 5843 size_t processedSize = 4;
5782 Byte buf[4]; 5844 Byte buf[4];
5783 RINOK(Decoder.Read(buf, &processedSize)); 5845 RINOK(Decoder.Read(buf, &processedSize))
5784 if (processedSize != 4) 5846 if (processedSize != 4)
5785 return S_FALSE; 5847 return S_FALSE;
5786 if (Get32((const Byte *)buf) != FirstHeader.HeaderSize) 5848 if (Get32((const Byte *)buf) != FirstHeader.HeaderSize)
@@ -5788,7 +5850,7 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size)
5788 } 5850 }
5789 { 5851 {
5790 size_t processedSize = FirstHeader.HeaderSize; 5852 size_t processedSize = FirstHeader.HeaderSize;
5791 RINOK(Decoder.Read(_data, &processedSize)); 5853 RINOK(Decoder.Read(_data, &processedSize))
5792 if (processedSize != FirstHeader.HeaderSize) 5854 if (processedSize != FirstHeader.HeaderSize)
5793 return S_FALSE; 5855 return S_FALSE;
5794 } 5856 }
@@ -5800,7 +5862,7 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size)
5800 AfterHeaderSize = (1 << 12); 5862 AfterHeaderSize = (1 << 12);
5801 _afterHeader.Alloc(AfterHeaderSize); 5863 _afterHeader.Alloc(AfterHeaderSize);
5802 size_t processedSize = AfterHeaderSize; 5864 size_t processedSize = AfterHeaderSize;
5803 RINOK(Decoder.Read(_afterHeader, &processedSize)); 5865 RINOK(Decoder.Read(_afterHeader, &processedSize))
5804 AfterHeaderSize = (UInt32)processedSize; 5866 AfterHeaderSize = (UInt32)processedSize;
5805 } 5867 }
5806 #endif 5868 #endif
@@ -5808,7 +5870,7 @@ HRESULT CInArchive::Open2(const Byte *sig, size_t size)
5808 else 5870 else
5809 { 5871 {
5810 size_t processedSize = FirstHeader.HeaderSize; 5872 size_t processedSize = FirstHeader.HeaderSize;
5811 RINOK(ReadStream(_stream, (Byte *)_data, &processedSize)); 5873 RINOK(ReadStream(_stream, (Byte *)_data, &processedSize))
5812 if (processedSize < FirstHeader.HeaderSize) 5874 if (processedSize < FirstHeader.HeaderSize)
5813 return S_FALSE; 5875 return S_FALSE;
5814 } 5876 }
@@ -5892,7 +5954,7 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio
5892{ 5954{
5893 Clear(); 5955 Clear();
5894 5956
5895 RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &StartOffset)); 5957 RINOK(InStream_GetPos(inStream, StartOffset))
5896 5958
5897 const UInt32 kStartHeaderSize = 4 * 7; 5959 const UInt32 kStartHeaderSize = 4 * 7;
5898 const unsigned kStep = 512; // nsis start is aligned for 512 5960 const unsigned kStep = 512; // nsis start is aligned for 512
@@ -5904,7 +5966,7 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio
5904 for (;;) 5966 for (;;)
5905 { 5967 {
5906 bufSize = kStep; 5968 bufSize = kStep;
5907 RINOK(ReadStream(inStream, buf, &bufSize)); 5969 RINOK(ReadStream(inStream, buf, &bufSize))
5908 if (bufSize < kStartHeaderSize) 5970 if (bufSize < kStartHeaderSize)
5909 return S_FALSE; 5971 return S_FALSE;
5910 if (memcmp(buf + 4, kSignature, kSignatureSize) == 0) 5972 if (memcmp(buf + 4, kSignature, kSignatureSize) == 0)
@@ -5936,8 +5998,8 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio
5936 if (pos - posCur > (1 << 20)) 5998 if (pos - posCur > (1 << 20))
5937 break; 5999 break;
5938 bufSize = kStep; 6000 bufSize = kStep;
5939 RINOK(inStream->Seek(posCur, STREAM_SEEK_SET, NULL)); 6001 RINOK(InStream_SeekSet(inStream, posCur))
5940 RINOK(ReadStream(inStream, buf, &bufSize)); 6002 RINOK(ReadStream(inStream, buf, &bufSize))
5941 if (bufSize < kStep) 6003 if (bufSize < kStep)
5942 break; 6004 break;
5943 if (IsArc_Pe(buf, bufSize)) 6005 if (IsArc_Pe(buf, bufSize))
@@ -5949,8 +6011,8 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio
5949 6011
5950 // restore buf to nsis header 6012 // restore buf to nsis header
5951 bufSize = kStep; 6013 bufSize = kStep;
5952 RINOK(inStream->Seek(pos, STREAM_SEEK_SET, NULL)); 6014 RINOK(InStream_SeekSet(inStream, pos))
5953 RINOK(ReadStream(inStream, buf, &bufSize)); 6015 RINOK(ReadStream(inStream, buf, &bufSize))
5954 if (bufSize < kStartHeaderSize) 6016 if (bufSize < kStartHeaderSize)
5955 return S_FALSE; 6017 return S_FALSE;
5956 } 6018 }
@@ -5990,15 +6052,15 @@ HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *maxCheckStartPositio
5990 } 6052 }
5991 */ 6053 */
5992 6054
5993 RINOK(inStream->Seek(0, STREAM_SEEK_END, &_fileSize)); 6055 RINOK(InStream_GetSize_SeekToEnd(inStream, _fileSize))
5994 6056
5995 IsArc = true; 6057 IsArc = true;
5996 6058
5997 if (peSize != 0) 6059 if (peSize != 0)
5998 { 6060 {
5999 ExeStub.Alloc(peSize); 6061 ExeStub.Alloc(peSize);
6000 RINOK(inStream->Seek(pePos, STREAM_SEEK_SET, NULL)); 6062 RINOK(InStream_SeekSet(inStream, pePos))
6001 RINOK(ReadStream_FALSE(inStream, ExeStub, peSize)); 6063 RINOK(ReadStream_FALSE(inStream, ExeStub, peSize))
6002 } 6064 }
6003 6065
6004 HRESULT res = S_FALSE; 6066 HRESULT res = S_FALSE;
diff --git a/CPP/7zip/Archive/Nsis/NsisIn.h b/CPP/7zip/Archive/Nsis/NsisIn.h
index 1d92e12..bb8de62 100644
--- a/CPP/7zip/Archive/Nsis/NsisIn.h
+++ b/CPP/7zip/Archive/Nsis/NsisIn.h
@@ -1,7 +1,7 @@
1// NsisIn.h 1// NsisIn.h
2 2
3#ifndef __ARCHIVE_NSIS_IN_H 3#ifndef ZIP7_INC_ARCHIVE_NSIS_IN_H
4#define __ARCHIVE_NSIS_IN_H 4#define ZIP7_INC_ARCHIVE_NSIS_IN_H
5 5
6#include "../../../../C/CpuArch.h" 6#include "../../../../C/CpuArch.h"
7 7
@@ -11,6 +11,8 @@
11#include "../../../Common/StringConvert.h" 11#include "../../../Common/StringConvert.h"
12#include "../../../Common/UTFConvert.h" 12#include "../../../Common/UTFConvert.h"
13 13
14#include "../../Common/StreamUtils.h"
15
14#include "NsisDecode.h" 16#include "NsisDecode.h"
15 17
16/* If NSIS_SCRIPT is defined, it will decompile NSIS script to [NSIS].nsi file. 18/* If NSIS_SCRIPT is defined, it will decompile NSIS script to [NSIS].nsi file.
@@ -68,6 +70,7 @@ struct CBlockHeader
68 70
69struct CItem 71struct CItem
70{ 72{
73 bool IsEmptyFile;
71 bool IsCompressed; 74 bool IsCompressed;
72 bool Size_Defined; 75 bool Size_Defined;
73 bool CompressedSize_Defined; 76 bool CompressedSize_Defined;
@@ -77,7 +80,7 @@ struct CItem
77 // bool UseFilter; 80 // bool UseFilter;
78 81
79 UInt32 Attrib; 82 UInt32 Attrib;
80 UInt32 Pos; 83 UInt32 Pos; // = 0, if (IsEmptyFile == true)
81 UInt32 Size; 84 UInt32 Size;
82 UInt32 CompressedSize; 85 UInt32 CompressedSize;
83 UInt32 EstimatedSize; 86 UInt32 EstimatedSize;
@@ -89,7 +92,10 @@ struct CItem
89 AString NameA; 92 AString NameA;
90 UString NameU; 93 UString NameU;
91 94
95 bool Is_PatchedUninstaller() const { return PatchSize != 0; }
96
92 CItem(): 97 CItem():
98 IsEmptyFile(false),
93 IsCompressed(true), 99 IsCompressed(true),
94 Size_Defined(false), 100 Size_Defined(false),
95 CompressedSize_Defined(false), 101 CompressedSize_Defined(false),
@@ -354,7 +360,7 @@ public:
354 360
355 HRESULT SeekTo(UInt64 pos) 361 HRESULT SeekTo(UInt64 pos)
356 { 362 {
357 return _stream->Seek(pos, STREAM_SEEK_SET, NULL); 363 return InStream_SeekSet(_stream, pos);
358 } 364 }
359 365
360 HRESULT SeekTo_DataStreamOffset() 366 HRESULT SeekTo_DataStreamOffset()
@@ -433,7 +439,7 @@ public:
433 if (s[0] == L'\\') 439 if (s[0] == L'\\')
434 s.DeleteFrontal(1); 440 s.DeleteFrontal(1);
435 } 441 }
436 if (item.IsUninstaller && ExeStub.Size() == 0) 442 if (item.Is_PatchedUninstaller() && ExeStub.Size() == 0)
437 s += ".nsis"; 443 s += ".nsis";
438 return s; 444 return s;
439 } 445 }
diff --git a/CPP/7zip/Archive/Nsis/NsisRegister.cpp b/CPP/7zip/Archive/Nsis/NsisRegister.cpp
index 7230c3c..a500381 100644
--- a/CPP/7zip/Archive/Nsis/NsisRegister.cpp
+++ b/CPP/7zip/Archive/Nsis/NsisRegister.cpp
@@ -10,7 +10,7 @@ namespace NArchive {
10namespace NNsis { 10namespace NNsis {
11 11
12REGISTER_ARC_I( 12REGISTER_ARC_I(
13 "Nsis", "nsis", 0, 0x9, 13 "Nsis", "nsis", NULL, 0x9,
14 kSignature, 14 kSignature,
15 4, 15 4,
16 NArcInfoFlags::kFindSignature | 16 NArcInfoFlags::kFindSignature |
diff --git a/CPP/7zip/Archive/Nsis/StdAfx.h b/CPP/7zip/Archive/Nsis/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Nsis/StdAfx.h
+++ b/CPP/7zip/Archive/Nsis/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/NtfsHandler.cpp b/CPP/7zip/Archive/NtfsHandler.cpp
index 7d0c6f7..c13e0ca 100644
--- a/CPP/7zip/Archive/NtfsHandler.cpp
+++ b/CPP/7zip/Archive/NtfsHandler.cpp
@@ -47,9 +47,9 @@
47#define Get32(p) GetUi32(p) 47#define Get32(p) GetUi32(p)
48#define Get64(p) GetUi64(p) 48#define Get64(p) GetUi64(p)
49 49
50#define G16(p, dest) dest = Get16(p); 50#define G16(p, dest) dest = Get16(p)
51#define G32(p, dest) dest = Get32(p); 51#define G32(p, dest) dest = Get32(p)
52#define G64(p, dest) dest = Get64(p); 52#define G64(p, dest) dest = Get64(p)
53 53
54using namespace NWindows; 54using namespace NWindows;
55 55
@@ -114,11 +114,11 @@ bool CHeader::Parse(const Byte *p)
114 int t = GetLog(Get16(p + 11)); 114 int t = GetLog(Get16(p + 11));
115 if (t < 9 || t > 12) 115 if (t < 9 || t > 12)
116 return false; 116 return false;
117 SectorSizeLog = t; 117 SectorSizeLog = (unsigned)t;
118 t = GetLog(p[13]); 118 t = GetLog(p[13]);
119 if (t < 0) 119 if (t < 0)
120 return false; 120 return false;
121 sectorsPerClusterLog = t; 121 sectorsPerClusterLog = (unsigned)t;
122 ClusterSizeLog = SectorSizeLog + sectorsPerClusterLog; 122 ClusterSizeLog = SectorSizeLog + sectorsPerClusterLog;
123 if (ClusterSizeLog > 30) 123 if (ClusterSizeLog > 30)
124 return false; 124 return false;
@@ -173,6 +173,8 @@ struct CMftRef
173 UInt64 GetIndex() const { return Val & (((UInt64)1 << 48) - 1); } 173 UInt64 GetIndex() const { return Val & (((UInt64)1 << 48) - 1); }
174 UInt16 GetNumber() const { return (UInt16)(Val >> 48); } 174 UInt16 GetNumber() const { return (UInt16)(Val >> 48); }
175 bool IsBaseItself() const { return Val == 0; } 175 bool IsBaseItself() const { return Val == 0; }
176
177 CMftRef(): Val(0) {}
176}; 178};
177 179
178#define ATNAME(n) ATTR_TYPE_ ## n 180#define ATNAME(n) ATTR_TYPE_ ## n
@@ -233,6 +235,11 @@ struct CFileNameAttr
233 bool IsWin32() const { return (NameType == kFileNameType_Win32); } 235 bool IsWin32() const { return (NameType == kFileNameType_Win32); }
234 236
235 bool Parse(const Byte *p, unsigned size); 237 bool Parse(const Byte *p, unsigned size);
238
239 CFileNameAttr():
240 Attrib(0),
241 NameType(0)
242 {}
236}; 243};
237 244
238static void GetString(const Byte *p, unsigned len, UString2 &res) 245static void GetString(const Byte *p, unsigned len, UString2 &res)
@@ -292,8 +299,18 @@ struct CSiAttr
292 // UInt64 QuotaCharged; 299 // UInt64 QuotaCharged;
293 300
294 bool Parse(const Byte *p, unsigned size); 301 bool Parse(const Byte *p, unsigned size);
302
303 CSiAttr():
304 CTime(0),
305 MTime(0),
306 ThisRecMTime(0),
307 ATime(0),
308 Attrib(0),
309 SecurityId(0)
310 {}
295}; 311};
296 312
313
297bool CSiAttr::Parse(const Byte *p, unsigned size) 314bool CSiAttr::Parse(const Byte *p, unsigned size)
298{ 315{
299 if (size < 0x24) 316 if (size < 0x24)
@@ -382,13 +399,13 @@ struct CAttr
382 } 399 }
383}; 400};
384 401
385#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 402#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
386 403
387static int CompareAttr(void *const *elem1, void *const *elem2, void *) 404static int CompareAttr(void *const *elem1, void *const *elem2, void *)
388{ 405{
389 const CAttr &a1 = *(*((const CAttr *const *)elem1)); 406 const CAttr &a1 = *(*((const CAttr *const *)elem1));
390 const CAttr &a2 = *(*((const CAttr *const *)elem2)); 407 const CAttr &a2 = *(*((const CAttr *const *)elem2));
391 RINOZ(MyCompare(a1.Type, a2.Type)); 408 RINOZ(MyCompare(a1.Type, a2.Type))
392 if (a1.Name.IsEmpty()) 409 if (a1.Name.IsEmpty())
393 { 410 {
394 if (!a2.Name.IsEmpty()) 411 if (!a2.Name.IsEmpty())
@@ -398,7 +415,7 @@ static int CompareAttr(void *const *elem1, void *const *elem2, void *)
398 return 1; 415 return 1;
399 else 416 else
400 { 417 {
401 RINOZ(a1.Name.Compare(a2.Name.GetRawPtr())); 418 RINOZ(a1.Name.Compare(a2.Name.GetRawPtr()))
402 } 419 }
403 return MyCompare(a1.LowVcn, a2.LowVcn); 420 return MyCompare(a1.LowVcn, a2.LowVcn);
404} 421}
@@ -575,7 +592,7 @@ bool CAttr::ParseExtents(CRecordVector<CExtent> &extents, UInt64 numClustersMax,
575 } 592 }
576 p += num; 593 p += num;
577 size -= num; 594 size -= num;
578 lcn += v; 595 lcn = (UInt64)((Int64)lcn + v);
579 if (lcn > numClustersMax) 596 if (lcn > numClustersMax)
580 return false; 597 return false;
581 e.Phy = lcn; 598 e.Phy = lcn;
@@ -597,18 +614,20 @@ static const UInt64 kEmptyTag = (UInt64)(Int64)-1;
597static const unsigned kNumCacheChunksLog = 1; 614static const unsigned kNumCacheChunksLog = 1;
598static const size_t kNumCacheChunks = (size_t)1 << kNumCacheChunksLog; 615static const size_t kNumCacheChunks = (size_t)1 << kNumCacheChunksLog;
599 616
600class CInStream: 617Z7_CLASS_IMP_COM_1(
601 public IInStream, 618 CInStream
602 public CMyUnknownImp 619 , IInStream
603{ 620)
621 Z7_IFACE_COM7_IMP(ISequentialInStream)
622
604 UInt64 _virtPos; 623 UInt64 _virtPos;
605 UInt64 _physPos; 624 UInt64 _physPos;
606 UInt64 _curRem; 625 UInt64 _curRem;
607 bool _sparseMode; 626 bool _sparseMode;
608 627public:
609 628 bool InUse;
629private:
610 unsigned _chunkSizeLog; 630 unsigned _chunkSizeLog;
611 UInt64 _tags[kNumCacheChunks];
612 CByteBuffer _inBuf; 631 CByteBuffer _inBuf;
613 CByteBuffer _outBuf; 632 CByteBuffer _outBuf;
614public: 633public:
@@ -617,12 +636,13 @@ public:
617 unsigned BlockSizeLog; 636 unsigned BlockSizeLog;
618 unsigned CompressionUnit; 637 unsigned CompressionUnit;
619 CRecordVector<CExtent> Extents; 638 CRecordVector<CExtent> Extents;
620 bool InUse;
621 CMyComPtr<IInStream> Stream; 639 CMyComPtr<IInStream> Stream;
640private:
641 UInt64 _tags[kNumCacheChunks];
622 642
623 HRESULT SeekToPhys() { return Stream->Seek(_physPos, STREAM_SEEK_SET, NULL); } 643 HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); }
624
625 UInt32 GetCuSize() const { return (UInt32)1 << (BlockSizeLog + CompressionUnit); } 644 UInt32 GetCuSize() const { return (UInt32)1 << (BlockSizeLog + CompressionUnit); }
645public:
626 HRESULT InitAndSeek(unsigned compressionUnit) 646 HRESULT InitAndSeek(unsigned compressionUnit)
627 { 647 {
628 CompressionUnit = compressionUnit; 648 CompressionUnit = compressionUnit;
@@ -645,11 +665,6 @@ public:
645 _physPos = e.Phy << BlockSizeLog; 665 _physPos = e.Phy << BlockSizeLog;
646 return SeekToPhys(); 666 return SeekToPhys();
647 } 667 }
648
649 MY_UNKNOWN_IMP1(IInStream)
650
651 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
652 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
653}; 668};
654 669
655static size_t Lznt1Dec(Byte *dest, size_t outBufLim, size_t destLen, const Byte *src, size_t srcLen) 670static 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
737 return destSize; 752 return destSize;
738} 753}
739 754
740STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 755Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
741{ 756{
742 if (processedSize) 757 if (processedSize)
743 *processedSize = 0; 758 *processedSize = 0;
@@ -827,7 +842,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
827 if (newPos != _physPos) 842 if (newPos != _physPos)
828 { 843 {
829 _physPos = newPos; 844 _physPos = newPos;
830 RINOK(SeekToPhys()); 845 RINOK(SeekToPhys())
831 } 846 }
832 UInt64 next = Extents[i + 1].Virt; 847 UInt64 next = Extents[i + 1].Virt;
833 if (next > virtBlock2End) 848 if (next > virtBlock2End)
@@ -870,30 +885,30 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
870 break; 885 break;
871 if (e.Virt >= virtBlock2End) 886 if (e.Virt >= virtBlock2End)
872 return S_FALSE; 887 return S_FALSE;
873 UInt64 newPos = (e.Phy + (curVirt - e.Virt)) << BlockSizeLog; 888 const UInt64 newPos = (e.Phy + (curVirt - e.Virt)) << BlockSizeLog;
874 if (newPos != _physPos) 889 if (newPos != _physPos)
875 { 890 {
876 _physPos = newPos; 891 _physPos = newPos;
877 RINOK(SeekToPhys()); 892 RINOK(SeekToPhys())
878 } 893 }
879 UInt64 numChunks = Extents[i + 1].Virt - curVirt; 894 UInt64 numChunks = Extents[i + 1].Virt - curVirt;
880 if (curVirt + numChunks > virtBlock2End) 895 if (curVirt + numChunks > virtBlock2End)
881 numChunks = virtBlock2End - curVirt; 896 numChunks = virtBlock2End - curVirt;
882 size_t compressed = (size_t)numChunks << BlockSizeLog; 897 const size_t compressed = (size_t)numChunks << BlockSizeLog;
883 RINOK(ReadStream_FALSE(Stream, _inBuf + offs, compressed)); 898 RINOK(ReadStream_FALSE(Stream, _inBuf + offs, compressed))
884 curVirt += numChunks; 899 curVirt += numChunks;
885 _physPos += compressed; 900 _physPos += compressed;
886 offs += compressed; 901 offs += compressed;
887 } 902 }
888 903
889 size_t destLenMax = GetCuSize(); 904 const size_t destLenMax = GetCuSize();
890 size_t destLen = destLenMax; 905 size_t destLen = destLenMax;
891 const UInt64 rem = Size - (virtBlock2 << BlockSizeLog); 906 const UInt64 rem = Size - (virtBlock2 << BlockSizeLog);
892 if (destLen > rem) 907 if (destLen > rem)
893 destLen = (size_t)rem; 908 destLen = (size_t)rem;
894 909
895 Byte *dest = _outBuf + (cacheIndex << _chunkSizeLog); 910 Byte *dest = _outBuf + (cacheIndex << _chunkSizeLog);
896 size_t destSizeRes = Lznt1Dec(dest, destLenMax, destLen, _inBuf, offs); 911 const size_t destSizeRes = Lznt1Dec(dest, destLenMax, destLen, _inBuf, offs);
897 _tags[cacheIndex] = cacheTag; 912 _tags[cacheIndex] = cacheTag;
898 913
899 // some files in Vista have destSize > destLen 914 // some files in Vista have destSize > destLen
@@ -922,7 +937,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
922 return res; 937 return res;
923} 938}
924 939
925STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 940Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
926{ 941{
927 switch (seekOrigin) 942 switch (seekOrigin)
928 { 943 {
@@ -936,10 +951,10 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio
936 if (_virtPos != (UInt64)offset) 951 if (_virtPos != (UInt64)offset)
937 { 952 {
938 _curRem = 0; 953 _curRem = 0;
939 _virtPos = offset; 954 _virtPos = (UInt64)offset;
940 } 955 }
941 if (newPosition) 956 if (newPosition)
942 *newPosition = offset; 957 *newPosition = (UInt64)offset;
943 return S_OK; 958 return S_OK;
944} 959}
945 960
@@ -1002,6 +1017,15 @@ struct CDataRef
1002static const UInt32 kMagic_FILE = 0x454C4946; 1017static const UInt32 kMagic_FILE = 0x454C4946;
1003static const UInt32 kMagic_BAAD = 0x44414142; 1018static const UInt32 kMagic_BAAD = 0x44414142;
1004 1019
1020// 22.02: we support some rare case magic values:
1021static const UInt32 kMagic_INDX = 0x58444e49;
1022static const UInt32 kMagic_HOLE = 0x454c4f48;
1023static const UInt32 kMagic_RSTR = 0x52545352;
1024static const UInt32 kMagic_RCRD = 0x44524352;
1025static const UInt32 kMagic_CHKD = 0x444b4843;
1026static const UInt32 kMagic_FFFFFFFF = 0xFFFFFFFF;
1027
1028
1005struct CMftRec 1029struct CMftRec
1006{ 1030{
1007 UInt32 Magic; 1031 UInt32 Magic;
@@ -1033,7 +1057,7 @@ struct CMftRec
1033 { 1057 {
1034 const CFileNameAttr &next = FileNames[i]; 1058 const CFileNameAttr &next = FileNames[i];
1035 if (next.IsWin32() && cur.ParentDirRef.Val == next.ParentDirRef.Val) 1059 if (next.IsWin32() && cur.ParentDirRef.Val == next.ParentDirRef.Val)
1036 return i; 1060 return (int)i;
1037 } 1061 }
1038 return -1; 1062 return -1;
1039 } 1063 }
@@ -1046,7 +1070,7 @@ struct CMftRec
1046 { 1070 {
1047 const CFileNameAttr &next = FileNames[i]; 1071 const CFileNameAttr &next = FileNames[i];
1048 if (next.IsDos() && cur.ParentDirRef.Val == next.ParentDirRef.Val) 1072 if (next.IsDos() && cur.ParentDirRef.Val == next.ParentDirRef.Val)
1049 return i; 1073 return (int)i;
1050 } 1074 }
1051 return -1; 1075 return -1;
1052 } 1076 }
@@ -1078,9 +1102,25 @@ struct CMftRec
1078 1102
1079 bool Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 recNumber, CObjectVector<CAttr> *attrs); 1103 bool Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 recNumber, CObjectVector<CAttr> *attrs);
1080 1104
1081 bool IsEmpty() const { return (Magic <= 2); } 1105 bool Is_Magic_Empty() const
1082 bool IsFILE() const { return (Magic == kMagic_FILE); } 1106 {
1083 bool IsBAAD() const { return (Magic == kMagic_BAAD); } 1107 // what exact Magic values are possible for empty and unused records?
1108 const UInt32 k_Magic_Unused_MAX = 5; // 22.02
1109 return (Magic <= k_Magic_Unused_MAX);
1110 }
1111 bool Is_Magic_FILE() const { return (Magic == kMagic_FILE); }
1112 // bool Is_Magic_BAAD() const { return (Magic == kMagic_BAAD); }
1113 bool Is_Magic_CanIgnore() const
1114 {
1115 return Is_Magic_Empty()
1116 || Magic == kMagic_BAAD
1117 || Magic == kMagic_INDX
1118 || Magic == kMagic_HOLE
1119 || Magic == kMagic_RSTR
1120 || Magic == kMagic_RCRD
1121 || Magic == kMagic_CHKD
1122 || Magic == kMagic_FFFFFFFF;
1123 }
1084 1124
1085 bool InUse() const { return (Flags & 1) != 0; } 1125 bool InUse() const { return (Flags & 1) != 0; }
1086 bool IsDir() const { return (Flags & 2) != 0; } 1126 bool IsDir() const { return (Flags & 2) != 0; }
@@ -1092,7 +1132,11 @@ struct CMftRec
1092 1132
1093 UInt64 GetSize(unsigned dataIndex) const { return DataAttrs[DataRefs[dataIndex].Start].GetSize(); } 1133 UInt64 GetSize(unsigned dataIndex) const { return DataAttrs[DataRefs[dataIndex].Start].GetSize(); }
1094 1134
1095 CMftRec(): MyNumNameLinks(0), MyItemIndex(-1) {} 1135 CMftRec():
1136 SeqNumber(0),
1137 Flags(0),
1138 MyNumNameLinks(0),
1139 MyItemIndex(-1) {}
1096}; 1140};
1097 1141
1098void CMftRec::ParseDataNames() 1142void CMftRec::ParseDataNames()
@@ -1115,7 +1159,7 @@ void CMftRec::ParseDataNames()
1115HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex, 1159HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex,
1116 unsigned clusterSizeLog, UInt64 numPhysClusters, IInStream **destStream) const 1160 unsigned clusterSizeLog, UInt64 numPhysClusters, IInStream **destStream) const
1117{ 1161{
1118 *destStream = 0; 1162 *destStream = NULL;
1119 CBufferInStream *streamSpec = new CBufferInStream; 1163 CBufferInStream *streamSpec = new CBufferInStream;
1120 CMyComPtr<IInStream> streamTemp = streamSpec; 1164 CMyComPtr<IInStream> streamTemp = streamSpec;
1121 1165
@@ -1137,13 +1181,13 @@ HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex,
1137 return S_FALSE; 1181 return S_FALSE;
1138 CInStream *ss = new CInStream; 1182 CInStream *ss = new CInStream;
1139 CMyComPtr<IInStream> streamTemp2 = ss; 1183 CMyComPtr<IInStream> streamTemp2 = ss;
1140 RINOK(DataParseExtents(clusterSizeLog, DataAttrs, ref.Start, ref.Start + ref.Num, numPhysClusters, ss->Extents)); 1184 RINOK(DataParseExtents(clusterSizeLog, DataAttrs, ref.Start, ref.Start + ref.Num, numPhysClusters, ss->Extents))
1141 ss->Size = attr0.Size; 1185 ss->Size = attr0.Size;
1142 ss->InitializedSize = attr0.InitializedSize; 1186 ss->InitializedSize = attr0.InitializedSize;
1143 ss->Stream = mainStream; 1187 ss->Stream = mainStream;
1144 ss->BlockSizeLog = clusterSizeLog; 1188 ss->BlockSizeLog = clusterSizeLog;
1145 ss->InUse = InUse(); 1189 ss->InUse = InUse();
1146 RINOK(ss->InitAndSeek(attr0.CompressionUnit)); 1190 RINOK(ss->InitAndSeek(attr0.CompressionUnit))
1147 *destStream = streamTemp2.Detach(); 1191 *destStream = streamTemp2.Detach();
1148 return S_OK; 1192 return S_OK;
1149 } 1193 }
@@ -1189,9 +1233,8 @@ bool CMftRec::Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 r
1189 CObjectVector<CAttr> *attrs) 1233 CObjectVector<CAttr> *attrs)
1190{ 1234{
1191 G32(p, Magic); 1235 G32(p, Magic);
1192 if (!IsFILE()) 1236 if (!Is_Magic_FILE())
1193 return IsEmpty() || IsBAAD(); 1237 return Is_Magic_CanIgnore();
1194
1195 1238
1196 { 1239 {
1197 UInt32 usaOffset; 1240 UInt32 usaOffset;
@@ -1228,7 +1271,7 @@ bool CMftRec::Parse(Byte *p, unsigned sectorSizeLog, UInt32 numSectors, UInt32 r
1228 void *pp = p + (i << sectorSizeLog) - 2; 1271 void *pp = p + (i << sectorSizeLog) - 2;
1229 if (Get16(pp) != usn) 1272 if (Get16(pp) != usn)
1230 return false; 1273 return false;
1231 SetUi16(pp, Get16(p + usaOffset + i * 2)); 1274 SetUi16(pp, Get16(p + usaOffset + i * 2))
1232 } 1275 }
1233 } 1276 }
1234 1277
@@ -1455,7 +1498,7 @@ struct CDatabase
1455 1498
1456HRESULT CDatabase::SeekToCluster(UInt64 cluster) 1499HRESULT CDatabase::SeekToCluster(UInt64 cluster)
1457{ 1500{
1458 return InStream->Seek(cluster << Header.ClusterSizeLog, STREAM_SEEK_SET, NULL); 1501 return InStream_SeekSet(InStream, cluster << Header.ClusterSizeLog);
1459} 1502}
1460 1503
1461void CDatabase::Clear() 1504void CDatabase::Clear()
@@ -1702,14 +1745,14 @@ HRESULT CDatabase::Open()
1702 */ 1745 */
1703 1746
1704 { 1747 {
1705 static const UInt32 kHeaderSize = 512; 1748 const UInt32 kHeaderSize = 512;
1706 Byte buf[kHeaderSize]; 1749 Byte buf[kHeaderSize];
1707 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize)); 1750 RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize))
1708 if (!Header.Parse(buf)) 1751 if (!Header.Parse(buf))
1709 return S_FALSE; 1752 return S_FALSE;
1710 1753
1711 UInt64 fileSize; 1754 UInt64 fileSize;
1712 RINOK(InStream->Seek(0, STREAM_SEEK_END, &fileSize)); 1755 RINOK(InStream_GetSize_SeekToEnd(InStream, fileSize))
1713 PhySize = Header.GetPhySize_Clusters(); 1756 PhySize = Header.GetPhySize_Clusters();
1714 if (fileSize < PhySize) 1757 if (fileSize < PhySize)
1715 return S_FALSE; 1758 return S_FALSE;
@@ -1717,7 +1760,7 @@ HRESULT CDatabase::Open()
1717 UInt64 phySizeMax = Header.GetPhySize_Max(); 1760 UInt64 phySizeMax = Header.GetPhySize_Max();
1718 if (fileSize >= phySizeMax) 1761 if (fileSize >= phySizeMax)
1719 { 1762 {
1720 RINOK(InStream->Seek(Header.NumSectors << Header.SectorSizeLog, STREAM_SEEK_SET, NULL)); 1763 RINOK(InStream_SeekSet(InStream, Header.NumSectors << Header.SectorSizeLog))
1721 Byte buf2[kHeaderSize]; 1764 Byte buf2[kHeaderSize];
1722 if (ReadStream_FALSE(InStream, buf2, kHeaderSize) == S_OK) 1765 if (ReadStream_FALSE(InStream, buf2, kHeaderSize) == S_OK)
1723 { 1766 {
@@ -1737,14 +1780,14 @@ HRESULT CDatabase::Open()
1737 { 1780 {
1738 UInt32 blockSize = 1 << 12; 1781 UInt32 blockSize = 1 << 12;
1739 ByteBuf.Alloc(blockSize); 1782 ByteBuf.Alloc(blockSize);
1740 RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize)); 1783 RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize))
1741 1784
1742 { 1785 {
1743 UInt32 allocSize = Get32(ByteBuf + 0x1C); 1786 const UInt32 allocSize = Get32(ByteBuf + 0x1C);
1744 int t = GetLog(allocSize); 1787 const int t = GetLog(allocSize);
1745 if (t < (int)Header.SectorSizeLog) 1788 if (t < (int)Header.SectorSizeLog)
1746 return S_FALSE; 1789 return S_FALSE;
1747 RecSizeLog = t; 1790 RecSizeLog = (unsigned)t;
1748 if (RecSizeLog > 15) 1791 if (RecSizeLog > 15)
1749 return S_FALSE; 1792 return S_FALSE;
1750 } 1793 }
@@ -1752,12 +1795,12 @@ HRESULT CDatabase::Open()
1752 numSectorsInRec = 1 << (RecSizeLog - Header.SectorSizeLog); 1795 numSectorsInRec = 1 << (RecSizeLog - Header.SectorSizeLog);
1753 if (!mftRec.Parse(ByteBuf, Header.SectorSizeLog, numSectorsInRec, 0, NULL)) 1796 if (!mftRec.Parse(ByteBuf, Header.SectorSizeLog, numSectorsInRec, 0, NULL))
1754 return S_FALSE; 1797 return S_FALSE;
1755 if (!mftRec.IsFILE()) 1798 if (!mftRec.Is_Magic_FILE())
1756 return S_FALSE; 1799 return S_FALSE;
1757 mftRec.ParseDataNames(); 1800 mftRec.ParseDataNames();
1758 if (mftRec.DataRefs.IsEmpty()) 1801 if (mftRec.DataRefs.IsEmpty())
1759 return S_FALSE; 1802 return S_FALSE;
1760 RINOK(mftRec.GetStream(InStream, 0, Header.ClusterSizeLog, Header.NumClusters, &mftStream)); 1803 RINOK(mftRec.GetStream(InStream, 0, Header.ClusterSizeLog, Header.NumClusters, &mftStream))
1761 if (!mftStream) 1804 if (!mftStream)
1762 return S_FALSE; 1805 return S_FALSE;
1763 } 1806 }
@@ -1779,7 +1822,7 @@ HRESULT CDatabase::Open()
1779 return S_FALSE; 1822 return S_FALSE;
1780 if (OpenCallback) 1823 if (OpenCallback)
1781 { 1824 {
1782 RINOK(OpenCallback->SetTotal(&numFiles, &mftSize)); 1825 RINOK(OpenCallback->SetTotal(&numFiles, &mftSize))
1783 } 1826 }
1784 1827
1785 ByteBuf.Alloc(kBufSize); 1828 ByteBuf.Alloc(kBufSize);
@@ -1791,9 +1834,9 @@ HRESULT CDatabase::Open()
1791 if (OpenCallback) 1834 if (OpenCallback)
1792 { 1835 {
1793 const UInt64 numFiles = Recs.Size(); 1836 const UInt64 numFiles = Recs.Size();
1794 if ((numFiles & 0x3FF) == 0) 1837 if ((numFiles & 0x3FFF) == 0)
1795 { 1838 {
1796 RINOK(OpenCallback->SetCompleted(&numFiles, &pos64)); 1839 RINOK(OpenCallback->SetCompleted(&numFiles, &pos64))
1797 } 1840 }
1798 } 1841 }
1799 size_t readSize = kBufSize; 1842 size_t readSize = kBufSize;
@@ -1804,7 +1847,7 @@ HRESULT CDatabase::Open()
1804 } 1847 }
1805 if (readSize < recSize) 1848 if (readSize < recSize)
1806 break; 1849 break;
1807 RINOK(ReadStream_FALSE(mftStream, ByteBuf, readSize)); 1850 RINOK(ReadStream_FALSE(mftStream, ByteBuf, readSize))
1808 pos64 += readSize; 1851 pos64 += readSize;
1809 1852
1810 for (size_t i = 0; readSize >= recSize; i += recSize, readSize -= recSize) 1853 for (size_t i = 0; readSize >= recSize; i += recSize, readSize -= recSize)
@@ -1880,12 +1923,18 @@ HRESULT CDatabase::Open()
1880 for (i = 0; i < Recs.Size(); i++) 1923 for (i = 0; i < Recs.Size(); i++)
1881 { 1924 {
1882 CMftRec &rec = Recs[i]; 1925 CMftRec &rec = Recs[i];
1926 if (!rec.Is_Magic_FILE())
1927 continue;
1928
1883 if (!rec.BaseMftRef.IsBaseItself()) 1929 if (!rec.BaseMftRef.IsBaseItself())
1884 { 1930 {
1885 UInt64 refIndex = rec.BaseMftRef.GetIndex(); 1931 const UInt64 refIndex = rec.BaseMftRef.GetIndex();
1886 if (refIndex > (UInt32)Recs.Size()) 1932 if (refIndex >= Recs.Size())
1887 return S_FALSE; 1933 return S_FALSE;
1888 CMftRec &refRec = Recs[(unsigned)refIndex]; 1934 CMftRec &refRec = Recs[(unsigned)refIndex];
1935 if (!refRec.Is_Magic_FILE())
1936 continue;
1937
1889 bool moveAttrs = (refRec.SeqNumber == rec.BaseMftRef.GetNumber() && refRec.BaseMftRef.IsBaseItself()); 1938 bool moveAttrs = (refRec.SeqNumber == rec.BaseMftRef.GetNumber() && refRec.BaseMftRef.IsBaseItself());
1890 if (rec.InUse() && refRec.InUse()) 1939 if (rec.InUse() && refRec.InUse())
1891 { 1940 {
@@ -1900,12 +1949,17 @@ HRESULT CDatabase::Open()
1900 } 1949 }
1901 1950
1902 for (i = 0; i < Recs.Size(); i++) 1951 for (i = 0; i < Recs.Size(); i++)
1903 Recs[i].ParseDataNames(); 1952 {
1953 CMftRec &rec = Recs[i];
1954 if (!rec.Is_Magic_FILE())
1955 continue;
1956 rec.ParseDataNames();
1957 }
1904 1958
1905 for (i = 0; i < Recs.Size(); i++) 1959 for (i = 0; i < Recs.Size(); i++)
1906 { 1960 {
1907 CMftRec &rec = Recs[i]; 1961 CMftRec &rec = Recs[i];
1908 if (!rec.IsFILE() || !rec.BaseMftRef.IsBaseItself()) 1962 if (!rec.Is_Magic_FILE() || !rec.BaseMftRef.IsBaseItself())
1909 continue; 1963 continue;
1910 if (i < kNumSysRecs && !_showSystemFiles) 1964 if (i < kNumSysRecs && !_showSystemFiles)
1911 continue; 1965 continue;
@@ -1927,7 +1981,7 @@ HRESULT CDatabase::Open()
1927 FOR_VECTOR (di, rec.DataRefs) 1981 FOR_VECTOR (di, rec.DataRefs)
1928 if (rec.DataAttrs[rec.DataRefs[di].Start].Name.IsEmpty()) 1982 if (rec.DataAttrs[rec.DataRefs[di].Start].Name.IsEmpty())
1929 { 1983 {
1930 indexOfUnnamedStream = di; 1984 indexOfUnnamedStream = (int)di;
1931 break; 1985 break;
1932 } 1986 }
1933 } 1987 }
@@ -1985,14 +2039,14 @@ HRESULT CDatabase::Open()
1985 indexOfUnnamedStream); 2039 indexOfUnnamedStream);
1986 2040
1987 if (rec.MyItemIndex < 0) 2041 if (rec.MyItemIndex < 0)
1988 rec.MyItemIndex = Items.Size(); 2042 rec.MyItemIndex = (int)Items.Size();
1989 item.ParentHost = Items.Add(item); 2043 item.ParentHost = (int)Items.Add(item);
1990 2044
1991 /* we can use that code to reduce the number of alt streams: 2045 /* we can use that code to reduce the number of alt streams:
1992 it will not show how alt streams for hard links. */ 2046 it will not show how alt streams for hard links. */
1993 // if (!isMainName) continue; isMainName = false; 2047 // if (!isMainName) continue; isMainName = false;
1994 2048
1995 unsigned numAltStreams = 0; 2049 // unsigned numAltStreams = 0;
1996 2050
1997 FOR_VECTOR (di, rec.DataRefs) 2051 FOR_VECTOR (di, rec.DataRefs)
1998 { 2052 {
@@ -2010,9 +2064,9 @@ HRESULT CDatabase::Open()
2010 continue; 2064 continue;
2011 } 2065 }
2012 2066
2013 numAltStreams++; 2067 // numAltStreams++;
2014 ThereAreAltStreams = true; 2068 ThereAreAltStreams = true;
2015 item.DataIndex = di; 2069 item.DataIndex = (int)di;
2016 Items.Add(item); 2070 Items.Add(item);
2017 } 2071 }
2018 } 2072 }
@@ -2027,10 +2081,10 @@ HRESULT CDatabase::Open()
2027 if (attr.Name == L"$SDS") 2081 if (attr.Name == L"$SDS")
2028 { 2082 {
2029 CMyComPtr<IInStream> sdsStream; 2083 CMyComPtr<IInStream> sdsStream;
2030 RINOK(rec.GetStream(InStream, di, Header.ClusterSizeLog, Header.NumClusters, &sdsStream)); 2084 RINOK(rec.GetStream(InStream, (int)di, Header.ClusterSizeLog, Header.NumClusters, &sdsStream))
2031 if (sdsStream) 2085 if (sdsStream)
2032 { 2086 {
2033 UInt64 size64 = attr.GetSize(); 2087 const UInt64 size64 = attr.GetSize();
2034 if (size64 < (UInt32)1 << 29) 2088 if (size64 < (UInt32)1 << 29)
2035 { 2089 {
2036 size_t size = (size_t)size64; 2090 size_t size = (size_t)size64;
@@ -2060,7 +2114,7 @@ HRESULT CDatabase::Open()
2060 const CMftRec &rec = Recs[item.RecIndex]; 2114 const CMftRec &rec = Recs[item.RecIndex];
2061 const CFileNameAttr &fn = rec.FileNames[item.NameIndex]; 2115 const CFileNameAttr &fn = rec.FileNames[item.NameIndex];
2062 const CMftRef &parentDirRef = fn.ParentDirRef; 2116 const CMftRef &parentDirRef = fn.ParentDirRef;
2063 UInt64 refIndex = parentDirRef.GetIndex(); 2117 const UInt64 refIndex = parentDirRef.GetIndex();
2064 if (refIndex == kRecIndex_RootDir) 2118 if (refIndex == kRecIndex_RootDir)
2065 item.ParentFolder = -1; 2119 item.ParentFolder = -1;
2066 else 2120 else
@@ -2087,57 +2141,52 @@ HRESULT CDatabase::Open()
2087 unsigned virtIndex = Items.Size(); 2141 unsigned virtIndex = Items.Size();
2088 if (_showSystemFiles) 2142 if (_showSystemFiles)
2089 { 2143 {
2090 _systemFolderIndex = virtIndex++; 2144 _systemFolderIndex = (int)(virtIndex++);
2091 VirtFolderNames.Add(kVirtualFolder_System); 2145 VirtFolderNames.Add(kVirtualFolder_System);
2092 } 2146 }
2093 if (thereAreUnknownFolders_Normal) 2147 if (thereAreUnknownFolders_Normal)
2094 { 2148 {
2095 _lostFolderIndex_Normal = virtIndex++; 2149 _lostFolderIndex_Normal = (int)(virtIndex++);
2096 VirtFolderNames.Add(kVirtualFolder_Lost_Normal); 2150 VirtFolderNames.Add(kVirtualFolder_Lost_Normal);
2097 } 2151 }
2098 if (thereAreUnknownFolders_Deleted) 2152 if (thereAreUnknownFolders_Deleted)
2099 { 2153 {
2100 _lostFolderIndex_Deleted = virtIndex++; 2154 _lostFolderIndex_Deleted = (int)(virtIndex++);
2101 VirtFolderNames.Add(kVirtualFolder_Lost_Deleted); 2155 VirtFolderNames.Add(kVirtualFolder_Lost_Deleted);
2102 } 2156 }
2103 2157
2104 return S_OK; 2158 return S_OK;
2105} 2159}
2106 2160
2107class CHandler: 2161Z7_class_CHandler_final:
2108 public IInArchive, 2162 public IInArchive,
2109 public IArchiveGetRawProps, 2163 public IArchiveGetRawProps,
2110 public IInArchiveGetStream, 2164 public IInArchiveGetStream,
2111 public ISetProperties, 2165 public ISetProperties,
2112 public CMyUnknownImp, 2166 public CMyUnknownImp,
2113 CDatabase 2167 public CDatabase
2114{ 2168{
2115public: 2169 Z7_IFACES_IMP_UNK_4(
2116 MY_UNKNOWN_IMP4(
2117 IInArchive, 2170 IInArchive,
2118 IArchiveGetRawProps, 2171 IArchiveGetRawProps,
2119 IInArchiveGetStream, 2172 IInArchiveGetStream,
2120 ISetProperties) 2173 ISetProperties)
2121 INTERFACE_IInArchive(;)
2122 INTERFACE_IArchiveGetRawProps(;)
2123 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
2124 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
2125}; 2174};
2126 2175
2127STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 2176Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
2128{ 2177{
2129 *numProps = 2; 2178 *numProps = 2;
2130 return S_OK; 2179 return S_OK;
2131} 2180}
2132 2181
2133STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 2182Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
2134{ 2183{
2135 *name = NULL; 2184 *name = NULL;
2136 *propID = index == 0 ? kpidNtReparse : kpidNtSecure; 2185 *propID = index == 0 ? kpidNtReparse : kpidNtSecure;
2137 return S_OK; 2186 return S_OK;
2138} 2187}
2139 2188
2140STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 2189Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
2141{ 2190{
2142 *parentType = NParentType::kDir; 2191 *parentType = NParentType::kDir;
2143 int par = -1; 2192 int par = -1;
@@ -2167,7 +2216,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
2167 return S_OK; 2216 return S_OK;
2168} 2217}
2169 2218
2170STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 2219Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
2171{ 2220{
2172 *data = NULL; 2221 *data = NULL;
2173 *dataSize = 0; 2222 *dataSize = 0;
@@ -2236,10 +2285,10 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data
2236 return S_OK; 2285 return S_OK;
2237} 2286}
2238 2287
2239STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 2288Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
2240{ 2289{
2241 COM_TRY_BEGIN 2290 COM_TRY_BEGIN
2242 *stream = 0; 2291 *stream = NULL;
2243 if (index >= Items.Size()) 2292 if (index >= Items.Size())
2244 return S_OK; 2293 return S_OK;
2245 IInStream *stream2; 2294 IInStream *stream2;
@@ -2357,7 +2406,7 @@ static void NtfsTimeToProp(UInt64 t, NCOM::CPropVariant &prop)
2357 prop = ft; 2406 prop = ft;
2358} 2407}
2359 2408
2360STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 2409Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
2361{ 2410{
2362 COM_TRY_BEGIN 2411 COM_TRY_BEGIN
2363 NCOM::CPropVariant prop; 2412 NCOM::CPropVariant prop;
@@ -2415,7 +2464,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
2415 { 2464 {
2416 s.Add_Space(); 2465 s.Add_Space();
2417 s.Add_UInt32(vi.MajorVer); 2466 s.Add_UInt32(vi.MajorVer);
2418 s += '.'; 2467 s.Add_Dot();
2419 s.Add_UInt32(vi.MinorVer); 2468 s.Add_UInt32(vi.MinorVer);
2420 } 2469 }
2421 break; 2470 break;
@@ -2461,7 +2510,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
2461 COM_TRY_END 2510 COM_TRY_END
2462} 2511}
2463 2512
2464STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 2513Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
2465{ 2514{
2466 COM_TRY_BEGIN 2515 COM_TRY_BEGIN
2467 NCOM::CPropVariant prop; 2516 NCOM::CPropVariant prop;
@@ -2529,7 +2578,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2529 { 2578 {
2530 // const CMftRec &rec = Recs[item.RecIndex]; 2579 // const CMftRec &rec = Recs[item.RecIndex];
2531 // prop = ((UInt64)rec.SeqNumber << 48) | item.RecIndex; 2580 // prop = ((UInt64)rec.SeqNumber << 48) | item.RecIndex;
2532 prop = item.RecIndex; 2581 prop = (UInt32)item.RecIndex;
2533 break; 2582 break;
2534 } 2583 }
2535 case kpidStreamId: 2584 case kpidStreamId:
@@ -2622,7 +2671,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2622 if (!rec.IsDir() && rec.DataAttrs[rec.DataRefs[0].Start].Name.IsEmpty()) 2671 if (!rec.IsDir() && rec.DataAttrs[rec.DataRefs[0].Start].Name.IsEmpty())
2623 num--; 2672 num--;
2624 if (num > 0) 2673 if (num > 0)
2625 prop = num; 2674 prop = (UInt32)num;
2626 } 2675 }
2627 } 2676 }
2628 break; 2677 break;
@@ -2637,7 +2686,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2637 COM_TRY_END 2686 COM_TRY_END
2638} 2687}
2639 2688
2640STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 2689Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
2641{ 2690{
2642 COM_TRY_BEGIN 2691 COM_TRY_BEGIN
2643 { 2692 {
@@ -2661,17 +2710,17 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
2661 COM_TRY_END 2710 COM_TRY_END
2662} 2711}
2663 2712
2664STDMETHODIMP CHandler::Close() 2713Z7_COM7F_IMF(CHandler::Close())
2665{ 2714{
2666 ClearAndClose(); 2715 ClearAndClose();
2667 return S_OK; 2716 return S_OK;
2668} 2717}
2669 2718
2670STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2719Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2671 Int32 testMode, IArchiveExtractCallback *extractCallback) 2720 Int32 testMode, IArchiveExtractCallback *extractCallback))
2672{ 2721{
2673 COM_TRY_BEGIN 2722 COM_TRY_BEGIN
2674 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 2723 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2675 if (allFilesMode) 2724 if (allFilesMode)
2676 numItems = Items.Size(); 2725 numItems = Items.Size();
2677 if (numItems == 0) 2726 if (numItems == 0)
@@ -2680,15 +2729,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2680 UInt64 totalSize = 0; 2729 UInt64 totalSize = 0;
2681 for (i = 0; i < numItems; i++) 2730 for (i = 0; i < numItems; i++)
2682 { 2731 {
2683 UInt32 index = allFilesMode ? i : indices[i]; 2732 const UInt32 index = allFilesMode ? i : indices[i];
2684 if (index >= (UInt32)Items.Size()) 2733 if (index >= (UInt32)Items.Size())
2685 continue; 2734 continue;
2686 const CItem &item = Items[allFilesMode ? i : indices[i]]; 2735 const CItem &item = Items[allFilesMode ? i : indices[i]];
2687 const CMftRec &rec = Recs[item.RecIndex]; 2736 const CMftRec &rec = Recs[item.RecIndex];
2688 if (item.DataIndex >= 0) 2737 if (item.DataIndex >= 0)
2689 totalSize += rec.GetSize(item.DataIndex); 2738 totalSize += rec.GetSize((unsigned)item.DataIndex);
2690 } 2739 }
2691 RINOK(extractCallback->SetTotal(totalSize)); 2740 RINOK(extractCallback->SetTotal(totalSize))
2692 2741
2693 UInt64 totalPackSize; 2742 UInt64 totalPackSize;
2694 totalSize = totalPackSize = 0; 2743 totalSize = totalPackSize = 0;
@@ -2710,18 +2759,18 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2710 { 2759 {
2711 lps->InSize = totalPackSize; 2760 lps->InSize = totalPackSize;
2712 lps->OutSize = totalSize; 2761 lps->OutSize = totalSize;
2713 RINOK(lps->SetCur()); 2762 RINOK(lps->SetCur())
2714 CMyComPtr<ISequentialOutStream> realOutStream; 2763 CMyComPtr<ISequentialOutStream> realOutStream;
2715 Int32 askMode = testMode ? 2764 const Int32 askMode = testMode ?
2716 NExtract::NAskMode::kTest : 2765 NExtract::NAskMode::kTest :
2717 NExtract::NAskMode::kExtract; 2766 NExtract::NAskMode::kExtract;
2718 UInt32 index = allFilesMode ? i : indices[i]; 2767 const UInt32 index = allFilesMode ? i : indices[i];
2719 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 2768 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
2720 2769
2721 if (index >= (UInt32)Items.Size() || Items[index].IsDir()) 2770 if (index >= (UInt32)Items.Size() || Items[index].IsDir())
2722 { 2771 {
2723 RINOK(extractCallback->PrepareOperation(askMode)); 2772 RINOK(extractCallback->PrepareOperation(askMode))
2724 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2773 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2725 continue; 2774 continue;
2726 } 2775 }
2727 2776
@@ -2729,7 +2778,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2729 2778
2730 if (!testMode && !realOutStream) 2779 if (!testMode && !realOutStream)
2731 continue; 2780 continue;
2732 RINOK(extractCallback->PrepareOperation(askMode)); 2781 RINOK(extractCallback->PrepareOperation(askMode))
2733 2782
2734 outStreamSpec->SetStream(realOutStream); 2783 outStreamSpec->SetStream(realOutStream);
2735 realOutStream.Release(); 2784 realOutStream.Release();
@@ -2745,13 +2794,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2745 res = NExtract::NOperationResult::kUnsupportedMethod; 2794 res = NExtract::NOperationResult::kUnsupportedMethod;
2746 else 2795 else
2747 { 2796 {
2748 RINOK(hres); 2797 RINOK(hres)
2749 if (inStream) 2798 if (inStream)
2750 { 2799 {
2751 hres = copyCoder->Code(inStream, outStream, NULL, NULL, progress); 2800 hres = copyCoder->Code(inStream, outStream, NULL, NULL, progress);
2752 if (hres != S_OK && hres != S_FALSE) 2801 if (hres != S_OK && hres != S_FALSE)
2753 { 2802 {
2754 RINOK(hres); 2803 RINOK(hres)
2755 } 2804 }
2756 if (/* copyCoderSpec->TotalSize == item.GetSize() && */ hres == S_OK) 2805 if (/* copyCoderSpec->TotalSize == item.GetSize() && */ hres == S_OK)
2757 res = NExtract::NOperationResult::kOK; 2806 res = NExtract::NOperationResult::kOK;
@@ -2765,19 +2814,19 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2765 totalSize += data.GetSize(); 2814 totalSize += data.GetSize();
2766 } 2815 }
2767 outStreamSpec->ReleaseStream(); 2816 outStreamSpec->ReleaseStream();
2768 RINOK(extractCallback->SetOperationResult(res)); 2817 RINOK(extractCallback->SetOperationResult(res))
2769 } 2818 }
2770 return S_OK; 2819 return S_OK;
2771 COM_TRY_END 2820 COM_TRY_END
2772} 2821}
2773 2822
2774STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 2823Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
2775{ 2824{
2776 *numItems = Items.Size() + VirtFolderNames.Size(); 2825 *numItems = Items.Size() + VirtFolderNames.Size();
2777 return S_OK; 2826 return S_OK;
2778} 2827}
2779 2828
2780STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 2829Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
2781{ 2830{
2782 InitProps(); 2831 InitProps();
2783 2832
@@ -2788,11 +2837,11 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
2788 2837
2789 if (StringsAreEqualNoCase_Ascii(name, "ld")) 2838 if (StringsAreEqualNoCase_Ascii(name, "ld"))
2790 { 2839 {
2791 RINOK(PROPVARIANT_to_bool(prop, _showDeletedFiles)); 2840 RINOK(PROPVARIANT_to_bool(prop, _showDeletedFiles))
2792 } 2841 }
2793 else if (StringsAreEqualNoCase_Ascii(name, "ls")) 2842 else if (StringsAreEqualNoCase_Ascii(name, "ls"))
2794 { 2843 {
2795 RINOK(PROPVARIANT_to_bool(prop, _showSystemFiles)); 2844 RINOK(PROPVARIANT_to_bool(prop, _showSystemFiles))
2796 } 2845 }
2797 else 2846 else
2798 return E_INVALIDARG; 2847 return E_INVALIDARG;
@@ -2803,7 +2852,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
2803static const Byte k_Signature[] = { 'N', 'T', 'F', 'S', ' ', ' ', ' ', ' ', 0 }; 2852static const Byte k_Signature[] = { 'N', 'T', 'F', 'S', ' ', ' ', ' ', ' ', 0 };
2804 2853
2805REGISTER_ARC_I( 2854REGISTER_ARC_I(
2806 "NTFS", "ntfs img", 0, 0xD9, 2855 "NTFS", "ntfs img", NULL, 0xD9,
2807 k_Signature, 2856 k_Signature,
2808 3, 2857 3,
2809 0, 2858 0,
diff --git a/CPP/7zip/Archive/PeHandler.cpp b/CPP/7zip/Archive/PeHandler.cpp
index 34a38ac..9851ed3 100644
--- a/CPP/7zip/Archive/PeHandler.cpp
+++ b/CPP/7zip/Archive/PeHandler.cpp
@@ -28,9 +28,10 @@
28 28
29#define G16(offs, v) v = Get16(p + (offs)) 29#define G16(offs, v) v = Get16(p + (offs))
30#define G32(offs, v) v = Get32(p + (offs)) 30#define G32(offs, v) v = Get32(p + (offs))
31#define G32_signed(offs, v) v = (Int32)Get32(p + (offs))
31#define G64(offs, v) v = Get64(p + (offs)) 32#define G64(offs, v) v = Get64(p + (offs))
32 33
33#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 34#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
34 35
35using namespace NWindows; 36using namespace NWindows;
36 37
@@ -55,7 +56,7 @@ static HRESULT CalcCheckSum(ISequentialInStream *stream, UInt32 size, UInt32 exc
55 if (rem == 0) 56 if (rem == 0)
56 break; 57 break;
57 size_t processed = rem; 58 size_t processed = rem;
58 RINOK(ReadStream(stream, buf, &processed)); 59 RINOK(ReadStream(stream, buf, &processed))
59 60
60 for (unsigned j = 0; j < 4; j++) 61 for (unsigned j = 0; j < 4; j++)
61 { 62 {
@@ -258,9 +259,9 @@ struct COptHeader
258 259
259 int GetNumFileAlignBits() const 260 int GetNumFileAlignBits() const
260 { 261 {
261 for (unsigned i = 0; i <= 31; i++) 262 for (unsigned i = 0; i < 32; i++)
262 if (((UInt32)1 << i) == FileAlign) 263 if (((UInt32)1 << i) == FileAlign)
263 return i; 264 return (int)i;
264 return -1; 265 return -1;
265 } 266 }
266 267
@@ -339,6 +340,7 @@ bool COptHeader::Parse(const Byte *p, UInt32 size)
339 pos += 4; 340 pos += 4;
340 if (pos + 8 * NumDirItems > size) 341 if (pos + 8 * NumDirItems > size)
341 return false; 342 return false;
343 memset((void *)DirItems, 0, sizeof(DirItems));
342 for (UInt32 i = 0; i < NumDirItems && i < kNumDirItemsMax; i++) 344 for (UInt32 i = 0; i < NumDirItems && i < kNumDirItemsMax; i++)
343 DirItems[i].Parse(p + pos + i * 8); 345 DirItems[i].Parse(p + pos + i * 8);
344 return true; 346 return true;
@@ -377,7 +379,7 @@ struct CSection
377 379
378 int Compare(const CSection &s) const 380 int Compare(const CSection &s) const
379 { 381 {
380 RINOZ(MyCompare(Pa, s.Pa)); 382 RINOZ(MyCompare(Pa, s.Pa))
381 UInt32 size1 = GetSizeExtract(); 383 UInt32 size1 = GetSizeExtract();
382 UInt32 size2 = s.GetSizeExtract(); 384 UInt32 size2 = s.GetSizeExtract();
383 return MyCompare(size1, size2); 385 return MyCompare(size1, size2);
@@ -613,7 +615,7 @@ struct CTextFile
613 615
614 size_t FinalSize() const { return Buf.GetPos(); } 616 size_t FinalSize() const { return Buf.GetPos(); }
615 617
616 void AddChar(Byte c); 618 void AddChar(char c);
617 void AddWChar(UInt16 c); 619 void AddWChar(UInt16 c);
618 void AddWChar_Smart(UInt16 c); 620 void AddWChar_Smart(UInt16 c);
619 void NewLine(); 621 void NewLine();
@@ -638,17 +640,17 @@ struct CTextFile
638 } 640 }
639}; 641};
640 642
641void CTextFile::AddChar(Byte c) 643void CTextFile::AddChar(char c)
642{ 644{
643 Byte *p = Buf.GetCurPtrAndGrow(2); 645 Byte *p = Buf.GetCurPtrAndGrow(2);
644 p[0] = c; 646 p[0] = (Byte)c;
645 p[1] = 0; 647 p[1] = 0;
646} 648}
647 649
648void CTextFile::AddWChar(UInt16 c) 650void CTextFile::AddWChar(UInt16 c)
649{ 651{
650 Byte *p = Buf.GetCurPtrAndGrow(2); 652 Byte *p = Buf.GetCurPtrAndGrow(2);
651 SetUi16(p, c); 653 SetUi16(p, c)
652} 654}
653 655
654void CTextFile::AddWChar_Smart(UInt16 c) 656void CTextFile::AddWChar_Smart(UInt16 c)
@@ -743,12 +745,11 @@ struct CStringKeyValue
743 UString Value; 745 UString Value;
744}; 746};
745 747
746class CHandler: 748
747 public IInArchive, 749Z7_CLASS_IMP_CHandler_IInArchive_2(
748 public IInArchiveGetStream, 750 IInArchiveGetStream,
749 public IArchiveAllowTail, 751 IArchiveAllowTail
750 public CMyUnknownImp 752)
751{
752 CMyComPtr<IInStream> _stream; 753 CMyComPtr<IInStream> _stream;
753 CObjectVector<CSection> _sections; 754 CObjectVector<CSection> _sections;
754 CHeader _header; 755 CHeader _header;
@@ -770,6 +771,7 @@ class CHandler:
770 CUsedBitmap _usedRes; 771 CUsedBitmap _usedRes;
771 // bool _parseResources; 772 // bool _parseResources;
772 bool _checksumError; 773 bool _checksumError;
774 bool _sectionsError;
773 775
774 bool IsOpt() const { return _header.OptHeaderSize != 0; } 776 bool IsOpt() const { return _header.OptHeaderSize != 0; }
775 777
@@ -800,11 +802,6 @@ public:
800 _coffMode(coffMode), 802 _coffMode(coffMode),
801 _allowTail(coffMode) 803 _allowTail(coffMode)
802 {} 804 {}
803
804 MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IArchiveAllowTail)
805 INTERFACE_IInArchive(;)
806 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
807 STDMETHOD(AllowTail)(Int32 allowTail);
808}; 805};
809 806
810 807
@@ -888,7 +885,7 @@ static void TimeToProp(UInt32 unixTime, NCOM::CPropVariant &prop)
888 PropVariant_SetFrom_UnixTime(prop, unixTime); 885 PropVariant_SetFrom_UnixTime(prop, unixTime);
889} 886}
890 887
891STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 888Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
892{ 889{
893 COM_TRY_BEGIN 890 COM_TRY_BEGIN
894 NCOM::CPropVariant prop; 891 NCOM::CPropVariant prop;
@@ -911,6 +908,15 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
911 // case kpidError: 908 // case kpidError:
912 case kpidWarning: if (_checksumError) prop = "Checksum error"; break; 909 case kpidWarning: if (_checksumError) prop = "Checksum error"; break;
913 910
911 case kpidWarningFlags:
912 {
913 UInt32 v = 0;
914 if (_sectionsError) v |= kpv_ErrorFlags_HeadersError;
915 if (v != 0)
916 prop = v;
917 break;
918 }
919
914 case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _header.Machine, prop); break; 920 case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _header.Machine, prop); break;
915 case kpidMTime: 921 case kpidMTime:
916 case kpidCTime: TimeToProp(_header.Time, prop); break; 922 case kpidCTime: TimeToProp(_header.Time, prop); break;
@@ -1029,7 +1035,7 @@ void CHandler::AddLangPrefix(UString &s, UInt32 lang) const
1029 } 1035 }
1030} 1036}
1031 1037
1032STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 1038Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
1033{ 1039{
1034 COM_TRY_BEGIN 1040 COM_TRY_BEGIN
1035 NCOM::CPropVariant prop; 1041 NCOM::CPropVariant prop;
@@ -1081,7 +1087,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1081 AddLangPrefix(s, item.Lang); 1087 AddLangPrefix(s, item.Lang);
1082 { 1088 {
1083 const char *p = NULL; 1089 const char *p = NULL;
1084 if (item.Type < ARRAY_SIZE(g_ResTypes)) 1090 if (item.Type < Z7_ARRAY_SIZE(g_ResTypes))
1085 p = g_ResTypes[item.Type]; 1091 p = g_ResTypes[item.Type];
1086 if (p) 1092 if (p)
1087 s += p; 1093 s += p;
@@ -1109,7 +1115,14 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1109 const CSection &item = _sections[mixItem.SectionIndex]; 1115 const CSection &item = _sections[mixItem.SectionIndex];
1110 switch (propID) 1116 switch (propID)
1111 { 1117 {
1112 case kpidPath: prop = MultiByteToUnicodeString(item.Name); break; 1118 case kpidPath:
1119 {
1120 AString s = item.Name;
1121 s.Replace('/', '_');
1122 s.Replace('\\', '_');
1123 prop = MultiByteToUnicodeString(s);
1124 break;
1125 }
1113 case kpidSize: prop = (UInt64)item.PSize; break; 1126 case kpidSize: prop = (UInt64)item.PSize; break;
1114 case kpidPackSize: prop = (UInt64)item.PSize; break; 1127 case kpidPackSize: prop = (UInt64)item.PSize; break;
1115 case kpidVirtualSize: prop = (UInt64)item.VSize; break; 1128 case kpidVirtualSize: prop = (UInt64)item.VSize; break;
@@ -1122,8 +1135,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1122 if (item.IsRealSect) 1135 if (item.IsRealSect)
1123 { 1136 {
1124 UInt32 flags = item.Flags; 1137 UInt32 flags = item.Flags;
1125 const UInt32 MY__IMAGE_SCN_ALIGN_MASK = 0x00F00000; 1138 const UInt32 MY_IMAGE_SCN_ALIGN_MASK = 0x00F00000;
1126 AString s = FlagsToString(g_SectFlags, ARRAY_SIZE(g_SectFlags), item.Flags & ~MY__IMAGE_SCN_ALIGN_MASK); 1139 AString s = FlagsToString(g_SectFlags, Z7_ARRAY_SIZE(g_SectFlags), item.Flags & ~MY_IMAGE_SCN_ALIGN_MASK);
1127 const UInt32 align = ((flags >> 20) & 0xF); 1140 const UInt32 align = ((flags >> 20) & 0xF);
1128 if (align != 0) 1141 if (align != 0)
1129 { 1142 {
@@ -1185,8 +1198,8 @@ HRESULT CHandler::LoadDebugSections(IInStream *stream, bool &thereIsSection)
1185 CByteBuffer buffer(debugLink.Size); 1198 CByteBuffer buffer(debugLink.Size);
1186 Byte *buf = buffer; 1199 Byte *buf = buffer;
1187 1200
1188 RINOK(stream->Seek(pa, STREAM_SEEK_SET, NULL)); 1201 RINOK(InStream_SeekSet(stream, pa))
1189 RINOK(ReadStream_FALSE(stream, buf, debugLink.Size)); 1202 RINOK(ReadStream_FALSE(stream, buf, debugLink.Size))
1190 1203
1191 for (i = 0; i < numItems; i++) 1204 for (i = 0; i < numItems; i++)
1192 { 1205 {
@@ -1271,7 +1284,7 @@ bool CBitmapInfoHeader::Parse(const Byte *p, size_t size)
1271 if (size < kBitmapInfoHeader_Size || Get32(p) != kBitmapInfoHeader_Size) 1284 if (size < kBitmapInfoHeader_Size || Get32(p) != kBitmapInfoHeader_Size)
1272 return false; 1285 return false;
1273 G32( 4, XSize); 1286 G32( 4, XSize);
1274 G32( 8, YSize); 1287 G32_signed( 8, YSize);
1275 G16(12, Planes); 1288 G16(12, Planes);
1276 G16(14, BitCount); 1289 G16(14, BitCount);
1277 G32(16, Compression); 1290 G32(16, Compression);
@@ -1291,21 +1304,24 @@ static UInt32 SetBitmapHeader(Byte *dest, const Byte *src, UInt32 size)
1291 return 0; 1304 return 0;
1292 if (h.YSize < 0) 1305 if (h.YSize < 0)
1293 h.YSize = -h.YSize; 1306 h.YSize = -h.YSize;
1294 if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 || h.BitCount > 32) 1307 if (h.XSize > (1 << 26)
1308 || h.YSize > (1 << 26)
1309 || h.YSize < 0
1310 || h.Planes != 1 || h.BitCount > 32)
1295 return 0; 1311 return 0;
1296 if (h.SizeImage == 0) 1312 if (h.SizeImage == 0)
1297 { 1313 {
1298 if (h.Compression != 0) // BI_RGB 1314 if (h.Compression != 0) // BI_RGB
1299 return 0; 1315 return 0;
1300 h.SizeImage = GetImageSize(h.XSize, h.YSize, h.BitCount); 1316 h.SizeImage = GetImageSize(h.XSize, (UInt32)h.YSize, h.BitCount);
1301 } 1317 }
1302 UInt32 totalSize = kBmpHeaderSize + size; 1318 UInt32 totalSize = kBmpHeaderSize + size;
1303 UInt32 offBits = totalSize - h.SizeImage; 1319 UInt32 offBits = totalSize - h.SizeImage;
1304 // BITMAPFILEHEADER 1320 // BITMAPFILEHEADER
1305 SetUi16(dest, 0x4D42); 1321 SetUi16(dest, 0x4D42)
1306 SetUi32(dest + 2, totalSize); 1322 SetUi32(dest + 2, totalSize)
1307 SetUi32(dest + 6, 0); 1323 SetUi32(dest + 6, 0)
1308 SetUi32(dest + 10, offBits); 1324 SetUi32(dest + 10, offBits)
1309 return kBmpHeaderSize; 1325 return kBmpHeaderSize;
1310} 1326}
1311 1327
@@ -1316,11 +1332,14 @@ static UInt32 SetIconHeader(Byte *dest, const Byte *src, UInt32 size)
1316 return 0; 1332 return 0;
1317 if (h.YSize < 0) 1333 if (h.YSize < 0)
1318 h.YSize = -h.YSize; 1334 h.YSize = -h.YSize;
1319 if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 || 1335 if (h.XSize > (1 << 26)
1320 h.Compression != 0) // BI_RGB 1336 || h.YSize > (1 << 26)
1337 || h.YSize < 0
1338 || h.Planes != 1
1339 || h.Compression != 0) // BI_RGB
1321 return 0; 1340 return 0;
1322 1341
1323 UInt32 numBitCount = h.BitCount; 1342 const UInt32 numBitCount = h.BitCount;
1324 if (numBitCount != 1 && 1343 if (numBitCount != 1 &&
1325 numBitCount != 4 && 1344 numBitCount != 4 &&
1326 numBitCount != 8 && 1345 numBitCount != 8 &&
@@ -1341,29 +1360,29 @@ static UInt32 SetIconHeader(Byte *dest, const Byte *src, UInt32 size)
1341 // UInt32 imageSize = h.SizeImage; 1360 // UInt32 imageSize = h.SizeImage;
1342 // if (imageSize == 0) 1361 // if (imageSize == 0)
1343 // { 1362 // {
1344 UInt32 image1Size = GetImageSize(h.XSize, h.YSize, h.BitCount); 1363 const UInt32 image1Size = GetImageSize(h.XSize, (UInt32)h.YSize, h.BitCount);
1345 UInt32 image2Size = GetImageSize(h.XSize, h.YSize, 1); 1364 const UInt32 image2Size = GetImageSize(h.XSize, (UInt32)h.YSize, 1);
1346 imageSize = image1Size + image2Size; 1365 imageSize = image1Size + image2Size;
1347 // } 1366 // }
1348 UInt32 numColors = 0; 1367 UInt32 numColors = 0;
1349 if (numBitCount < 16) 1368 if (numBitCount < 16)
1350 numColors = 1 << numBitCount; 1369 numColors = 1 << numBitCount;
1351 1370
1352 SetUi16(dest, 0); // Reserved 1371 SetUi16(dest, 0) // Reserved
1353 SetUi16(dest + 2, 1); // RES_ICON 1372 SetUi16(dest + 2, 1) // RES_ICON
1354 SetUi16(dest + 4, 1); // ResCount 1373 SetUi16(dest + 4, 1) // ResCount
1355 1374
1356 dest[6] = (Byte)h.XSize; // Width 1375 dest[6] = (Byte)h.XSize; // Width
1357 dest[7] = (Byte)h.YSize; // Height 1376 dest[7] = (Byte)h.YSize; // Height
1358 dest[8] = (Byte)numColors; // ColorCount 1377 dest[8] = (Byte)numColors; // ColorCount
1359 dest[9] = 0; // Reserved 1378 dest[9] = 0; // Reserved
1360 1379
1361 SetUi32(dest + 10, 0); // Reserved1 / Reserved2 1380 SetUi32(dest + 10, 0) // Reserved1 / Reserved2
1362 1381
1363 UInt32 numQuadsBytes = numColors * 4; 1382 UInt32 numQuadsBytes = numColors * 4;
1364 UInt32 BytesInRes = kBitmapInfoHeader_Size + numQuadsBytes + imageSize; 1383 UInt32 BytesInRes = kBitmapInfoHeader_Size + numQuadsBytes + imageSize;
1365 SetUi32(dest + 14, BytesInRes); 1384 SetUi32(dest + 14, BytesInRes)
1366 SetUi32(dest + 18, kIconHeaderSize); 1385 SetUi32(dest + 18, kIconHeaderSize)
1367 1386
1368 /* 1387 /*
1369 Description = DWORDToString(xSize) + 1388 Description = DWORDToString(xSize) +
@@ -1500,9 +1519,9 @@ static void PrintVersion(CTextFile &f, UInt32 ms, UInt32 ls)
1500 1519
1501static void PrintVersion(UString &s, UInt32 ms, UInt32 ls) 1520static void PrintVersion(UString &s, UInt32 ms, UInt32 ls)
1502{ 1521{
1503 PrintUInt32(s, HIWORD(ms)); s += '.'; 1522 PrintUInt32(s, HIWORD(ms)); s.Add_Dot();
1504 PrintUInt32(s, LOWORD(ms)); s += '.'; 1523 PrintUInt32(s, LOWORD(ms)); s.Add_Dot();
1505 PrintUInt32(s, HIWORD(ls)); s += '.'; 1524 PrintUInt32(s, HIWORD(ls)); s.Add_Dot();
1506 PrintUInt32(s, LOWORD(ls)); 1525 PrintUInt32(s, LOWORD(ls));
1507} 1526}
1508 1527
@@ -1590,7 +1609,7 @@ static int FindKey(CObjectVector<CStringKeyValue> &v, const char *key)
1590{ 1609{
1591 FOR_VECTOR (i, v) 1610 FOR_VECTOR (i, v)
1592 if (v[i].Key.IsEqualTo(key)) 1611 if (v[i].Key.IsEqualTo(key))
1593 return i; 1612 return (int)i;
1594 return -1; 1613 return -1;
1595} 1614}
1596 1615
@@ -1642,7 +1661,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1642 f.AddString("FILEFLAGS "); 1661 f.AddString("FILEFLAGS ");
1643 { 1662 {
1644 bool wasPrinted = false; 1663 bool wasPrinted = false;
1645 for (unsigned i = 0; i < ARRAY_SIZE(k_VS_FileFlags); i++) 1664 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_VS_FileFlags); i++)
1646 { 1665 {
1647 if ((Flags & ((UInt32)1 << i)) != 0) 1666 if ((Flags & ((UInt32)1 << i)) != 0)
1648 { 1667 {
@@ -1653,7 +1672,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1653 wasPrinted = true; 1672 wasPrinted = true;
1654 } 1673 }
1655 } 1674 }
1656 UInt32 v = Flags & ~(((UInt32)1 << ARRAY_SIZE(k_VS_FileFlags)) - 1); 1675 UInt32 v = Flags & ~(((UInt32)1 << Z7_ARRAY_SIZE(k_VS_FileFlags)) - 1);
1657 if (v != 0 || !wasPrinted) 1676 if (v != 0 || !wasPrinted)
1658 { 1677 {
1659 if (wasPrinted) 1678 if (wasPrinted)
@@ -1666,7 +1685,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1666 // OS = 0x111230; 1685 // OS = 0x111230;
1667 f.AddString("FILEOS "); 1686 f.AddString("FILEOS ");
1668 unsigned i; 1687 unsigned i;
1669 for (i = 0; i < ARRAY_SIZE(k_VS_FileOS); i++) 1688 for (i = 0; i < Z7_ARRAY_SIZE(k_VS_FileOS); i++)
1670 { 1689 {
1671 const CUInt32PCharPair &pair = k_VS_FileOS[i]; 1690 const CUInt32PCharPair &pair = k_VS_FileOS[i];
1672 if (OS == pair.Value) 1691 if (OS == pair.Value)
@@ -1677,10 +1696,10 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1677 break; 1696 break;
1678 } 1697 }
1679 } 1698 }
1680 if (i == ARRAY_SIZE(k_VS_FileOS)) 1699 if (i == Z7_ARRAY_SIZE(k_VS_FileOS))
1681 { 1700 {
1682 UInt32 high = OS >> 16; 1701 UInt32 high = OS >> 16;
1683 if (high < ARRAY_SIZE(k_VS_FileOS_High)) 1702 if (high < Z7_ARRAY_SIZE(k_VS_FileOS_High))
1684 f.AddString(k_VS_FileOS_High[high]); 1703 f.AddString(k_VS_FileOS_High[high]);
1685 else 1704 else
1686 PrintHex(f, high << 16); 1705 PrintHex(f, high << 16);
@@ -1688,7 +1707,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1688 if (low != 0) 1707 if (low != 0)
1689 { 1708 {
1690 f.AddString(" | "); 1709 f.AddString(" | ");
1691 if (low < ARRAY_SIZE(k_VS_FileOS_Low)) 1710 if (low < Z7_ARRAY_SIZE(k_VS_FileOS_Low))
1692 f.AddString(k_VS_FileOS_Low[low]); 1711 f.AddString(k_VS_FileOS_Low[low]);
1693 else 1712 else
1694 PrintHex(f, low); 1713 PrintHex(f, low);
@@ -1697,7 +1716,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1697 f.NewLine(); 1716 f.NewLine();
1698 1717
1699 f.AddString("FILETYPE "); 1718 f.AddString("FILETYPE ");
1700 if (Type < ARRAY_SIZE(k_VS_FileType)) 1719 if (Type < Z7_ARRAY_SIZE(k_VS_FileType))
1701 f.AddString(k_VS_FileType[Type]); 1720 f.AddString(k_VS_FileType[Type]);
1702 else 1721 else
1703 PrintHex(f, Type); 1722 PrintHex(f, Type);
@@ -1707,7 +1726,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1707 bool needPrintSubType = true; 1726 bool needPrintSubType = true;
1708 if (Type == kMY_VFT_DRV) 1727 if (Type == kMY_VFT_DRV)
1709 { 1728 {
1710 if (Subtype != 0 && Subtype < ARRAY_SIZE(k_VS_FileSubType_DRV)) 1729 if (Subtype != 0 && Subtype < Z7_ARRAY_SIZE(k_VS_FileSubType_DRV))
1711 { 1730 {
1712 f.AddString("VFT2_DRV_"); 1731 f.AddString("VFT2_DRV_");
1713 f.AddString(k_VS_FileSubType_DRV[Subtype]); 1732 f.AddString(k_VS_FileSubType_DRV[Subtype]);
@@ -1716,7 +1735,7 @@ void CMy_VS_FIXEDFILEINFO::PrintToTextFile(CTextFile &f, CObjectVector<CStringKe
1716 } 1735 }
1717 else if (Type == kMY_VFT_FONT) 1736 else if (Type == kMY_VFT_FONT)
1718 { 1737 {
1719 if (Subtype != 0 && Subtype < ARRAY_SIZE(k_VS_FileSubType_FONT)) 1738 if (Subtype != 0 && Subtype < Z7_ARRAY_SIZE(k_VS_FileSubType_FONT))
1720 { 1739 {
1721 f.AddString(k_VS_FileSubType_FONT[Subtype]); 1740 f.AddString(k_VS_FileSubType_FONT[Subtype]);
1722 needPrintSubType = false; 1741 needPrintSubType = false;
@@ -1744,7 +1763,7 @@ static bool CompareWStrStrings(const Byte *p, const char *s)
1744 unsigned pos = 0; 1763 unsigned pos = 0;
1745 for (;;) 1764 for (;;)
1746 { 1765 {
1747 Byte c = *s++; 1766 const Byte c = (Byte)*s++;
1748 if (Get16(p + pos) != c) 1767 if (Get16(p + pos) != c)
1749 return false; 1768 return false;
1750 pos += 2; 1769 pos += 2;
@@ -1771,7 +1790,7 @@ static int Get_Utf16Str_Len_InBytes(const Byte *p, size_t size)
1771 if (pos + 1 >= size) 1790 if (pos + 1 >= size)
1772 return -1; 1791 return -1;
1773 if (Get16(p + pos) == 0) 1792 if (Get16(p + pos) == 0)
1774 return pos; 1793 return (int)pos;
1775 pos += 2; 1794 pos += 2;
1776 } 1795 }
1777} 1796}
@@ -1793,10 +1812,10 @@ bool CVersionBlock::Parse(const Byte *p, UInt32 size)
1793 default: return false; 1812 default: return false;
1794 } 1813 }
1795 StrSize = 0; 1814 StrSize = 0;
1796 int t = Get_Utf16Str_Len_InBytes(p + k_ResoureBlockHeader_Size, TotalLen - k_ResoureBlockHeader_Size); 1815 const int t = Get_Utf16Str_Len_InBytes(p + k_ResoureBlockHeader_Size, TotalLen - k_ResoureBlockHeader_Size);
1797 if (t < 0) 1816 if (t < 0)
1798 return false; 1817 return false;
1799 StrSize = t; 1818 StrSize = (unsigned)t;
1800 return true; 1819 return true;
1801} 1820}
1802 1821
@@ -1962,12 +1981,12 @@ static bool ParseVersion(const Byte *p, UInt32 size, CTextFile &f, CObjectVector
1962 { 1981 {
1963 f.AddChar(','); 1982 f.AddChar(',');
1964 f.AddSpaces((34 - (int)vb3.StrSize) / 2); 1983 f.AddSpaces((34 - (int)vb3.StrSize) / 2);
1965 int sLen = Get_Utf16Str_Len_InBytes(p + pos, endPos3 - pos); 1984 const int sLen = Get_Utf16Str_Len_InBytes(p + pos, endPos3 - pos);
1966 if (sLen < 0) 1985 if (sLen < 0)
1967 return false; 1986 return false;
1968 AddParamString(f, p + pos, (unsigned)sLen); 1987 AddParamString(f, p + pos, (unsigned)sLen);
1969 CopyToUString(p + pos, value); 1988 CopyToUString(p + pos, value);
1970 pos += sLen + 2; 1989 pos += (unsigned)sLen + 2;
1971 } 1990 }
1972 AddToUniqueUStringVector(keys, key, value); 1991 AddToUniqueUStringVector(keys, key, value);
1973 } 1992 }
@@ -2016,10 +2035,10 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2016 { 2035 {
2017 const UInt64 fileSize64 = fileSize; 2036 const UInt64 fileSize64 = fileSize;
2018 if (callback) 2037 if (callback)
2019 RINOK(callback->SetTotal(NULL, &fileSize64)); 2038 RINOK(callback->SetTotal(NULL, &fileSize64))
2020 } 2039 }
2021 2040
2022 RINOK(stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL)); 2041 RINOK(InStream_SeekSet(stream, sect.Pa))
2023 2042
2024 _buf.Alloc(fileSize); 2043 _buf.Alloc(fileSize);
2025 2044
@@ -2033,7 +2052,7 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2033 RINOK(callback->SetCompleted(NULL, &offset64)) 2052 RINOK(callback->SetCompleted(NULL, &offset64))
2034 } 2053 }
2035 size_t rem = MyMin(fileSize - pos, (size_t)(1 << 22)); 2054 size_t rem = MyMin(fileSize - pos, (size_t)(1 << 22));
2036 RINOK(ReadStream(stream, _buf + pos, &rem)); 2055 RINOK(ReadStream(stream, _buf + pos, &rem))
2037 if (rem == 0) 2056 if (rem == 0)
2038 { 2057 {
2039 if (pos < fileSizeMin) 2058 if (pos < fileSizeMin)
@@ -2049,7 +2068,7 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2049 2068
2050 _usedRes.Alloc(fileSize); 2069 _usedRes.Alloc(fileSize);
2051 CRecordVector<CTableItem> specItems; 2070 CRecordVector<CTableItem> specItems;
2052 RINOK(ReadTable(0, specItems)); 2071 RINOK(ReadTable(0, specItems))
2053 2072
2054 _oneLang = true; 2073 _oneLang = true;
2055 bool stringsOk = true; 2074 bool stringsOk = true;
@@ -2062,7 +2081,7 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2062 return S_FALSE; 2081 return S_FALSE;
2063 2082
2064 CRecordVector<CTableItem> specItems2; 2083 CRecordVector<CTableItem> specItems2;
2065 RINOK(ReadTable(item1.Offset & kMask, specItems2)); 2084 RINOK(ReadTable(item1.Offset & kMask, specItems2))
2066 2085
2067 FOR_VECTOR (j, specItems2) 2086 FOR_VECTOR (j, specItems2)
2068 { 2087 {
@@ -2071,7 +2090,7 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2071 return S_FALSE; 2090 return S_FALSE;
2072 2091
2073 CRecordVector<CTableItem> specItems3; 2092 CRecordVector<CTableItem> specItems3;
2074 RINOK(ReadTable(item2.Offset & kMask, specItems3)); 2093 RINOK(ReadTable(item2.Offset & kMask, specItems3))
2075 2094
2076 CResItem item; 2095 CResItem item;
2077 item.Type = item1.ID; 2096 item.Type = item1.ID;
@@ -2126,8 +2145,8 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2126 if (ParseVersion((const Byte *)_buf + offset, item.Size, f, _versionKeys)) 2145 if (ParseVersion((const Byte *)_buf + offset, item.Size, f, _versionKeys))
2127 { 2146 {
2128 CMixItem mixItem; 2147 CMixItem mixItem;
2129 mixItem.VersionIndex = _versionFiles.Size(); 2148 mixItem.VersionIndex = (int)_versionFiles.Size();
2130 mixItem.SectionIndex = sectionIndex; // check it !!!! 2149 mixItem.SectionIndex = (int)sectionIndex; // check it !!!!
2131 CByteBuffer_WithLang &vf = _versionFiles.AddNew(); 2150 CByteBuffer_WithLang &vf = _versionFiles.AddNew();
2132 vf.Lang = item.Lang; 2151 vf.Lang = item.Lang;
2133 vf.CopyFrom(f.Buf, f.Buf.GetPos()); 2152 vf.CopyFrom(f.Buf, f.Buf.GetPos());
@@ -2157,8 +2176,8 @@ HRESULT CHandler::OpenResources(unsigned sectionIndex, IInStream *stream, IArchi
2157 if (_strings[i].FinalSize() == 0) 2176 if (_strings[i].FinalSize() == 0)
2158 continue; 2177 continue;
2159 CMixItem mixItem; 2178 CMixItem mixItem;
2160 mixItem.StringIndex = i; 2179 mixItem.StringIndex = (int)i;
2161 mixItem.SectionIndex = sectionIndex; 2180 mixItem.SectionIndex = (int)sectionIndex;
2162 _mixItems.Add(mixItem); 2181 _mixItems.Add(mixItem);
2163 } 2182 }
2164 } 2183 }
@@ -2219,7 +2238,7 @@ bool CHeader::ParseCoff(const Byte *p)
2219 if (NumSections == 0 && OptHeaderSize == 0) 2238 if (NumSections == 0 && OptHeaderSize == 0)
2220 return false; 2239 return false;
2221 2240
2222 for (unsigned i = 0; i < ARRAY_SIZE(g_MachinePairs); i++) 2241 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_MachinePairs); i++)
2223 if (Machine == g_MachinePairs[i].Value) 2242 if (Machine == g_MachinePairs[i].Value)
2224 return true; 2243 return true;
2225 if (Machine == 0) 2244 if (Machine == 0)
@@ -2263,7 +2282,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2263 if (_coffMode) 2282 if (_coffMode)
2264 { 2283 {
2265 Byte h[kCoffHeaderSize]; 2284 Byte h[kCoffHeaderSize];
2266 RINOK(ReadStream_FALSE(stream, h, kCoffHeaderSize)); 2285 RINOK(ReadStream_FALSE(stream, h, kCoffHeaderSize))
2267 if (!_header.ParseCoff(h)) 2286 if (!_header.ParseCoff(h))
2268 return S_FALSE; 2287 return S_FALSE;
2269 } 2288 }
@@ -2272,7 +2291,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2272 UInt32 _peOffset; 2291 UInt32 _peOffset;
2273 { 2292 {
2274 Byte h[kStartSize]; 2293 Byte h[kStartSize];
2275 RINOK(ReadStream_FALSE(stream, h, kStartSize)); 2294 RINOK(ReadStream_FALSE(stream, h, kStartSize))
2276 if (h[0] != 'M' || h[1] != 'Z') 2295 if (h[0] != 'M' || h[1] != 'Z')
2277 return S_FALSE; 2296 return S_FALSE;
2278 /* most of PE files contain 0x0090 at offset 2. 2297 /* most of PE files contain 0x0090 at offset 2.
@@ -2285,8 +2304,8 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2285 } 2304 }
2286 { 2305 {
2287 Byte h[kPeHeaderSize]; 2306 Byte h[kPeHeaderSize];
2288 RINOK(stream->Seek(_peOffset, STREAM_SEEK_SET, NULL)); 2307 RINOK(InStream_SeekSet(stream, _peOffset))
2289 RINOK(ReadStream_FALSE(stream, h, kPeHeaderSize)); 2308 RINOK(ReadStream_FALSE(stream, h, kPeHeaderSize))
2290 if (!_header.ParsePe(h)) 2309 if (!_header.ParsePe(h))
2291 return S_FALSE; 2310 return S_FALSE;
2292 } 2311 }
@@ -2297,8 +2316,9 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2297 _totalSize = optStart + bufSize; 2316 _totalSize = optStart + bufSize;
2298 CByteBuffer buffer(bufSize); 2317 CByteBuffer buffer(bufSize);
2299 2318
2300 RINOK(ReadStream_FALSE(stream, buffer, bufSize)); 2319 RINOK(ReadStream_FALSE(stream, buffer, bufSize))
2301 2320
2321 // memset((void *)&_optHeader, 0, sizeof(_optHeader));
2302 if (_header.OptHeaderSize != 0) 2322 if (_header.OptHeaderSize != 0)
2303 if (!_optHeader.Parse(buffer, _header.OptHeaderSize)) 2323 if (!_optHeader.Parse(buffer, _header.OptHeaderSize))
2304 return S_FALSE; 2324 return S_FALSE;
@@ -2312,26 +2332,40 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2312 sect.IsRealSect = true; 2332 sect.IsRealSect = true;
2313 2333
2314 /* PE pre-file in .hxs file has errors: 2334 /* PE pre-file in .hxs file has errors:
2315 PSize of resource is larger tnan real size. 2335 PSize of resource is larger than real size.
2316 So it overlaps next ".its" section. 2336 So it overlaps next ".its" section.
2317 We correct it. */ 2337 7-zip before 22.02: we corrected it.
2338
2339 22.02: another bad case is possible in incorrect pe (exe) file:
2340 PSize in .rsrc section is correct,
2341 but next .reloc section has incorrect (Pa) that overlaps with .rsrc.
2342 */
2318 2343
2319 if (i > 0) 2344 if (i != 0)
2320 { 2345 {
2321 CSection &prev = _sections[i - 1]; 2346 const CSection &prev = _sections[i - 1];
2322 if (prev.Pa < sect.Pa && 2347 if (prev.Pa < sect.Pa
2323 prev.Pa + prev.PSize > sect.Pa && 2348 && prev.Pa + prev.PSize > sect.Pa
2324 sect.PSize > 0) 2349 && sect.PSize != 0
2350 && prev.PSize != 0)
2325 { 2351 {
2326 // printf("\n !!!! Section correction: %s\n ", prev.Name); 2352 _sectionsError = true;
2327 // fflush(stdout); 2353 // PRF(printf("\n !!!! Section correction: %s\n ", prev.Name));
2328 prev.PSize = sect.Pa - prev.Pa; 2354
2355 /* we corrected that case in 7-zip before 22.02: */
2356 // prev.PSize = sect.Pa - prev.Pa;
2357
2358 /* 22.02: here we can try to change bad section position to expected postion.
2359 but original Windows code probably will not do same things. */
2360 // if (prev.PSize <= sect.Va - prev.Va) sect.Pa = prev.Pa + prev.PSize;
2329 } 2361 }
2330 } 2362 }
2331 /* last ".its" section in hxs file has incorrect sect.PSize. 2363 /* last ".its" section in hxs file has incorrect sect.PSize.
2332 So we reduce it to real sect.VSize */ 2364 7-zip before 22.02: we reduced section to real sect.VSize */
2365 /*
2333 if (sect.VSize == 24 && sect.PSize == 512 && i == (unsigned)_header.NumSections - 1) 2366 if (sect.VSize == 24 && sect.PSize == 512 && i == (unsigned)_header.NumSections - 1)
2334 sect.PSize = sect.VSize; 2367 sect.PSize = sect.VSize;
2368 */
2335 } 2369 }
2336 2370
2337 for (i = 0; i < _sections.Size(); i++) 2371 for (i = 0; i < _sections.Size(); i++)
@@ -2340,7 +2374,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2340 bool thereISDebug = false; 2374 bool thereISDebug = false;
2341 if (IsOpt()) 2375 if (IsOpt())
2342 { 2376 {
2343 RINOK(LoadDebugSections(stream, thereISDebug)); 2377 RINOK(LoadDebugSections(stream, thereISDebug))
2344 2378
2345 const CDirLink &certLink = _optHeader.DirItems[kDirLink_Certificate]; 2379 const CDirLink &certLink = _optHeader.DirItems[kDirLink_Certificate];
2346 if (certLink.Size != 0) 2380 if (certLink.Size != 0)
@@ -2364,11 +2398,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2364 if (alignPos != 0) 2398 if (alignPos != 0)
2365 { 2399 {
2366 UInt32 size = kAlign - alignPos; 2400 UInt32 size = kAlign - alignPos;
2367 RINOK(stream->Seek(_totalSize, STREAM_SEEK_SET, NULL)); 2401 RINOK(InStream_SeekSet(stream, _totalSize))
2368 buffer.Alloc(kAlign); 2402 buffer.Alloc(kAlign);
2369 Byte *buf = buffer; 2403 Byte *buf = buffer;
2370 size_t processed = size; 2404 size_t processed = size;
2371 RINOK(ReadStream(stream, buf, &processed)); 2405 RINOK(ReadStream(stream, buf, &processed))
2372 2406
2373 /* 2407 /*
2374 if (processed != 0) 2408 if (processed != 0)
@@ -2395,9 +2429,9 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2395 if (_header.NumSymbols >= (1 << 24)) 2429 if (_header.NumSymbols >= (1 << 24))
2396 return S_FALSE; 2430 return S_FALSE;
2397 UInt32 size = _header.NumSymbols * 18; 2431 UInt32 size = _header.NumSymbols * 18;
2398 RINOK(stream->Seek((UInt64)_header.PointerToSymbolTable + size, STREAM_SEEK_SET, NULL)); 2432 RINOK(InStream_SeekSet(stream, (UInt64)_header.PointerToSymbolTable + size))
2399 Byte buf[4]; 2433 Byte buf[4];
2400 RINOK(ReadStream_FALSE(stream, buf, 4)); 2434 RINOK(ReadStream_FALSE(stream, buf, 4))
2401 UInt32 size2 = Get32(buf); 2435 UInt32 size2 = Get32(buf);
2402 if (size2 >= (1 << 28)) 2436 if (size2 >= (1 << 28))
2403 return S_FALSE; 2437 return S_FALSE;
@@ -2442,9 +2476,9 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2442 if (IsOpt()) 2476 if (IsOpt())
2443 if (_optHeader.CheckSum != 0) 2477 if (_optHeader.CheckSum != 0)
2444 { 2478 {
2445 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 2479 RINOK(InStream_SeekToBegin(stream))
2446 UInt32 checkSum = 0; 2480 UInt32 checkSum = 0;
2447 RINOK(CalcCheckSum(stream, _totalSize, optStart + k_CheckSum_Field_Offset, checkSum)); 2481 RINOK(CalcCheckSum(stream, _totalSize, optStart + k_CheckSum_Field_Offset, checkSum))
2448 _checksumError = (checkSum != _optHeader.CheckSum); 2482 _checksumError = (checkSum != _optHeader.CheckSum);
2449 } 2483 }
2450 2484
@@ -2452,13 +2486,13 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2452 if (!_allowTail) 2486 if (!_allowTail)
2453 { 2487 {
2454 UInt64 fileSize; 2488 UInt64 fileSize;
2455 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); 2489 RINOK(InStream_GetSize_SeekToEnd(stream, fileSize))
2456 if (fileSize > _totalSize) 2490 if (fileSize > _totalSize)
2457 return S_FALSE; 2491 return S_FALSE;
2458 } 2492 }
2459 2493
2460 bool _parseResources = true; 2494 bool _parseResources = true;
2461 // _parseResources = false; 2495 // _parseResources = false; // for debug
2462 2496
2463 UInt64 mainSize = 0, mainSize2 = 0; 2497 UInt64 mainSize = 0, mainSize2 = 0;
2464 2498
@@ -2482,15 +2516,15 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2482 if (item.Enabled) 2516 if (item.Enabled)
2483 { 2517 {
2484 CMixItem mixItem; 2518 CMixItem mixItem;
2485 mixItem.SectionIndex = i; 2519 mixItem.SectionIndex = (int)i;
2486 mixItem.ResourceIndex = j; 2520 mixItem.ResourceIndex = (int)j;
2487 if (item.IsRcDataOrUnknown()) 2521 if (item.IsRcDataOrUnknown())
2488 { 2522 {
2489 if (item.Size >= mainSize) 2523 if (item.Size >= mainSize)
2490 { 2524 {
2491 mainSize2 = mainSize; 2525 mainSize2 = mainSize;
2492 mainSize = item.Size; 2526 mainSize = item.Size;
2493 _mainSubfile = _mixItems.Size(); 2527 _mainSubfile = (Int32)(int)_mixItems.Size();
2494 } 2528 }
2495 else if (item.Size >= mainSize2) 2529 else if (item.Size >= mainSize2)
2496 mainSize2 = item.Size; 2530 mainSize2 = item.Size;
@@ -2538,14 +2572,14 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2538 { 2572 {
2539 mainSize2 = mainSize; 2573 mainSize2 = mainSize;
2540 mainSize = sect.PSize; 2574 mainSize = sect.PSize;
2541 _mainSubfile = _mixItems.Size(); 2575 _mainSubfile = (Int32)(int)_mixItems.Size();
2542 } 2576 }
2543 else if (sect.PSize >= mainSize2) 2577 else if (sect.PSize >= mainSize2)
2544 mainSize2 = sect.PSize; 2578 mainSize2 = sect.PSize;
2545 } 2579 }
2546 2580
2547 CMixItem mixItem; 2581 CMixItem mixItem;
2548 mixItem.SectionIndex = i; 2582 mixItem.SectionIndex = (int)i;
2549 _mixItems.Add(mixItem); 2583 _mixItems.Add(mixItem);
2550 } 2584 }
2551 2585
@@ -2557,7 +2591,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2557 const CMixItem &mixItem = _mixItems[i]; 2591 const CMixItem &mixItem = _mixItems[i];
2558 if (mixItem.StringIndex < 0 && mixItem.ResourceIndex < 0 && _sections[mixItem.SectionIndex].Name == "_winzip_") 2592 if (mixItem.StringIndex < 0 && mixItem.ResourceIndex < 0 && _sections[mixItem.SectionIndex].Name == "_winzip_")
2559 { 2593 {
2560 _mainSubfile = i; 2594 _mainSubfile = (Int32)(int)i;
2561 break; 2595 break;
2562 } 2596 }
2563 } 2597 }
@@ -2594,11 +2628,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
2594 return S_OK; 2628 return S_OK;
2595} 2629}
2596 2630
2597STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) 2631Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback))
2598{ 2632{
2599 COM_TRY_BEGIN 2633 COM_TRY_BEGIN
2600 Close(); 2634 Close();
2601 RINOK(Open2(inStream, callback)); 2635 RINOK(Open2(inStream, callback))
2602 _stream = inStream; 2636 _stream = inStream;
2603 return S_OK; 2637 return S_OK;
2604 COM_TRY_END 2638 COM_TRY_END
@@ -2617,10 +2651,11 @@ void CHandler::CloseResources()
2617 _versionKeys.Clear(); 2651 _versionKeys.Clear();
2618} 2652}
2619 2653
2620STDMETHODIMP CHandler::Close() 2654Z7_COM7F_IMF(CHandler::Close())
2621{ 2655{
2622 _totalSize = 0; 2656 _totalSize = 0;
2623 _checksumError = false; 2657 _checksumError = false;
2658 _sectionsError = false;
2624 _mainSubfile = -1; 2659 _mainSubfile = -1;
2625 2660
2626 _stream.Release(); 2661 _stream.Release();
@@ -2630,17 +2665,17 @@ STDMETHODIMP CHandler::Close()
2630 return S_OK; 2665 return S_OK;
2631} 2666}
2632 2667
2633STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 2668Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
2634{ 2669{
2635 *numItems = _mixItems.Size(); 2670 *numItems = _mixItems.Size();
2636 return S_OK; 2671 return S_OK;
2637} 2672}
2638 2673
2639STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2674Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2640 Int32 testMode, IArchiveExtractCallback *extractCallback) 2675 Int32 testMode, IArchiveExtractCallback *extractCallback))
2641{ 2676{
2642 COM_TRY_BEGIN 2677 COM_TRY_BEGIN
2643 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 2678 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2644 if (allFilesMode) 2679 if (allFilesMode)
2645 numItems = _mixItems.Size(); 2680 numItems = _mixItems.Size();
2646 if (numItems == 0) 2681 if (numItems == 0)
@@ -2680,14 +2715,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2680 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) 2715 for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
2681 { 2716 {
2682 lps->InSize = lps->OutSize = currentTotalSize; 2717 lps->InSize = lps->OutSize = currentTotalSize;
2683 RINOK(lps->SetCur()); 2718 RINOK(lps->SetCur())
2684 Int32 askMode = testMode ? 2719 const Int32 askMode = testMode ?
2685 NExtract::NAskMode::kTest : 2720 NExtract::NAskMode::kTest :
2686 NExtract::NAskMode::kExtract; 2721 NExtract::NAskMode::kExtract;
2687 UInt32 index = allFilesMode ? i : indices[i]; 2722 const UInt32 index = allFilesMode ? i : indices[i];
2688 2723
2689 CMyComPtr<ISequentialOutStream> outStream; 2724 CMyComPtr<ISequentialOutStream> outStream;
2690 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 2725 RINOK(extractCallback->GetStream(index, &outStream, askMode))
2691 const CMixItem &mixItem = _mixItems[index]; 2726 const CMixItem &mixItem = _mixItems[index];
2692 2727
2693 const CSection &sect = _sections[mixItem.SectionIndex]; 2728 const CSection &sect = _sections[mixItem.SectionIndex];
@@ -2699,9 +2734,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2699 if (!testMode && !outStream) 2734 if (!testMode && !outStream)
2700 continue; 2735 continue;
2701 2736
2702 RINOK(extractCallback->PrepareOperation(askMode)); 2737 RINOK(extractCallback->PrepareOperation(askMode))
2703 if (outStream) 2738 if (outStream)
2704 RINOK(WriteStream(outStream, item.Buf, item.FinalSize())); 2739 RINOK(WriteStream(outStream, item.Buf, item.FinalSize()))
2705 } 2740 }
2706 else if (mixItem.VersionIndex >= 0) 2741 else if (mixItem.VersionIndex >= 0)
2707 { 2742 {
@@ -2710,9 +2745,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2710 if (!testMode && !outStream) 2745 if (!testMode && !outStream)
2711 continue; 2746 continue;
2712 2747
2713 RINOK(extractCallback->PrepareOperation(askMode)); 2748 RINOK(extractCallback->PrepareOperation(askMode))
2714 if (outStream) 2749 if (outStream)
2715 RINOK(WriteStream(outStream, item, item.Size())); 2750 RINOK(WriteStream(outStream, item, item.Size()))
2716 } 2751 }
2717 else if (mixItem.ResourceIndex >= 0) 2752 else if (mixItem.ResourceIndex >= 0)
2718 { 2753 {
@@ -2721,15 +2756,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2721 if (!testMode && !outStream) 2756 if (!testMode && !outStream)
2722 continue; 2757 continue;
2723 2758
2724 RINOK(extractCallback->PrepareOperation(askMode)); 2759 RINOK(extractCallback->PrepareOperation(askMode))
2725 size_t offset = item.Offset - sect.Va; 2760 size_t offset = item.Offset - sect.Va;
2726 if (!CheckItem(sect, item, offset)) 2761 if (!CheckItem(sect, item, offset))
2727 isOk = false; 2762 isOk = false;
2728 else if (outStream) 2763 else if (outStream)
2729 { 2764 {
2730 if (item.HeaderSize != 0) 2765 if (item.HeaderSize != 0)
2731 RINOK(WriteStream(outStream, item.Header, item.HeaderSize)); 2766 RINOK(WriteStream(outStream, item.Header, item.HeaderSize))
2732 RINOK(WriteStream(outStream, _buf + offset, item.Size)); 2767 RINOK(WriteStream(outStream, _buf + offset, item.Size))
2733 } 2768 }
2734 } 2769 }
2735 else 2770 else
@@ -2738,26 +2773,26 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2738 if (!testMode && !outStream) 2773 if (!testMode && !outStream)
2739 continue; 2774 continue;
2740 2775
2741 RINOK(extractCallback->PrepareOperation(askMode)); 2776 RINOK(extractCallback->PrepareOperation(askMode))
2742 RINOK(_stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL)); 2777 RINOK(InStream_SeekSet(_stream, sect.Pa))
2743 streamSpec->Init(currentItemSize); 2778 streamSpec->Init(currentItemSize);
2744 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 2779 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
2745 isOk = (copyCoderSpec->TotalSize == currentItemSize); 2780 isOk = (copyCoderSpec->TotalSize == currentItemSize);
2746 } 2781 }
2747 2782
2748 outStream.Release(); 2783 outStream.Release();
2749 RINOK(extractCallback->SetOperationResult(isOk ? 2784 RINOK(extractCallback->SetOperationResult(isOk ?
2750 NExtract::NOperationResult::kOK : 2785 NExtract::NOperationResult::kOK :
2751 NExtract::NOperationResult::kDataError)); 2786 NExtract::NOperationResult::kDataError))
2752 } 2787 }
2753 return S_OK; 2788 return S_OK;
2754 COM_TRY_END 2789 COM_TRY_END
2755} 2790}
2756 2791
2757STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 2792Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
2758{ 2793{
2759 COM_TRY_BEGIN 2794 COM_TRY_BEGIN
2760 *stream = 0; 2795 *stream = NULL;
2761 2796
2762 const CMixItem &mixItem = _mixItems[index]; 2797 const CMixItem &mixItem = _mixItems[index];
2763 const CSection &sect = _sections[mixItem.SectionIndex]; 2798 const CSection &sect = _sections[mixItem.SectionIndex];
@@ -2804,7 +2839,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
2804 COM_TRY_END 2839 COM_TRY_END
2805} 2840}
2806 2841
2807STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 2842Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail))
2808{ 2843{
2809 _allowTail = IntToBool(allowTail); 2844 _allowTail = IntToBool(allowTail);
2810 return S_OK; 2845 return S_OK;
@@ -2813,7 +2848,7 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail)
2813static const Byte k_Signature[] = { 'M', 'Z' }; 2848static const Byte k_Signature[] = { 'M', 'Z' };
2814 2849
2815REGISTER_ARC_I( 2850REGISTER_ARC_I(
2816 "PE", "exe dll sys", 0, 0xDD, 2851 "PE", "exe dll sys", NULL, 0xDD,
2817 k_Signature, 2852 k_Signature,
2818 0, 2853 0,
2819 NArcInfoFlags::kPreArc, 2854 NArcInfoFlags::kPreArc,
@@ -2846,7 +2881,7 @@ REGISTER_ARC_I_CLS(
2846 2881
2847REGISTER_ARC_I_CLS_NO_SIG( 2882REGISTER_ARC_I_CLS_NO_SIG(
2848 NPe::CHandler(true), 2883 NPe::CHandler(true),
2849 "COFF", "obj", 0, 0xC6, 2884 "COFF", "obj", NULL, 0xC6,
2850 // k_Signature, 2885 // k_Signature,
2851 0, 2886 0,
2852 // NArcInfoFlags::kMultiSignature | 2887 // NArcInfoFlags::kMultiSignature |
@@ -2881,8 +2916,8 @@ static bool FindValue(const CUInt32PCharPair *pairs, unsigned num, UInt32 value)
2881 return false; 2916 return false;
2882} 2917}
2883 2918
2884#define MY_FIND_VALUE(pairs, val) FindValue(pairs, ARRAY_SIZE(pairs), val) 2919#define MY_FIND_VALUE(pairs, val) FindValue(pairs, Z7_ARRAY_SIZE(pairs), val)
2885#define MY_FIND_VALUE_2(strings, val) (val < ARRAY_SIZE(strings) && strings[val]) 2920#define MY_FIND_VALUE_2(strings, val) (val < Z7_ARRAY_SIZE(strings) && strings[val])
2886 2921
2887static const UInt32 kNumSection_MAX = 32; 2922static const UInt32 kNumSection_MAX = 32;
2888 2923
@@ -2988,12 +3023,11 @@ struct CSection
2988 } 3023 }
2989}; 3024};
2990 3025
2991class CHandler: 3026
2992 public IInArchive, 3027Z7_CLASS_IMP_CHandler_IInArchive_2(
2993 public IInArchiveGetStream, 3028 IInArchiveGetStream,
2994 public IArchiveAllowTail, 3029 IArchiveAllowTail
2995 public CMyUnknownImp 3030)
2996{
2997 CRecordVector<CSection> _items; 3031 CRecordVector<CSection> _items;
2998 CMyComPtr<IInStream> _stream; 3032 CMyComPtr<IInStream> _stream;
2999 UInt32 _totalSize; 3033 UInt32 _totalSize;
@@ -3002,10 +3036,6 @@ class CHandler:
3002 3036
3003 HRESULT Open2(IInStream *stream); 3037 HRESULT Open2(IInStream *stream);
3004public: 3038public:
3005 MY_UNKNOWN_IMP3(IInArchive, IInArchiveGetStream, IArchiveAllowTail)
3006 INTERFACE_IInArchive(;)
3007 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
3008 STDMETHOD(AllowTail)(Int32 allowTail);
3009 CHandler(): _allowTail(false) {} 3039 CHandler(): _allowTail(false) {}
3010}; 3040};
3011 3041
@@ -3036,7 +3066,7 @@ static const CStatProp kArcProps[] =
3036IMP_IInArchive_Props 3066IMP_IInArchive_Props
3037IMP_IInArchive_ArcProps_WITH_NAME 3067IMP_IInArchive_ArcProps_WITH_NAME
3038 3068
3039STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 3069Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
3040{ 3070{
3041 COM_TRY_BEGIN 3071 COM_TRY_BEGIN
3042 NCOM::CPropVariant prop; 3072 NCOM::CPropVariant prop;
@@ -3056,7 +3086,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
3056 COM_TRY_END 3086 COM_TRY_END
3057} 3087}
3058 3088
3059STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 3089Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
3060{ 3090{
3061 COM_TRY_BEGIN 3091 COM_TRY_BEGIN
3062 NCOM::CPropVariant prop; 3092 NCOM::CPropVariant prop;
@@ -3087,7 +3117,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
3087HRESULT CHandler::Open2(IInStream *stream) 3117HRESULT CHandler::Open2(IInStream *stream)
3088{ 3118{
3089 Byte h[kHeaderSize]; 3119 Byte h[kHeaderSize];
3090 RINOK(ReadStream_FALSE(stream, h, kHeaderSize)); 3120 RINOK(ReadStream_FALSE(stream, h, kHeaderSize))
3091 if (h[0] != 'V' || h[1] != 'Z') 3121 if (h[0] != 'V' || h[1] != 'Z')
3092 return S_FALSE; 3122 return S_FALSE;
3093 if (!_h.Parse(h)) 3123 if (!_h.Parse(h))
@@ -3095,7 +3125,7 @@ HRESULT CHandler::Open2(IInStream *stream)
3095 3125
3096 UInt32 headerSize = NPe::kSectionSize * (UInt32)_h.NumSections; 3126 UInt32 headerSize = NPe::kSectionSize * (UInt32)_h.NumSections;
3097 CByteArr buf(headerSize); 3127 CByteArr buf(headerSize);
3098 RINOK(ReadStream_FALSE(stream, buf, headerSize)); 3128 RINOK(ReadStream_FALSE(stream, buf, headerSize))
3099 headerSize += kHeaderSize; 3129 headerSize += kHeaderSize;
3100 3130
3101 _totalSize = headerSize; 3131 _totalSize = headerSize;
@@ -3117,7 +3147,7 @@ HRESULT CHandler::Open2(IInStream *stream)
3117 if (!_allowTail) 3147 if (!_allowTail)
3118 { 3148 {
3119 UInt64 fileSize; 3149 UInt64 fileSize;
3120 RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize)); 3150 RINOK(InStream_GetSize_SeekToEnd(stream, fileSize))
3121 if (fileSize > _totalSize) 3151 if (fileSize > _totalSize)
3122 return S_FALSE; 3152 return S_FALSE;
3123 } 3153 }
@@ -3125,9 +3155,9 @@ HRESULT CHandler::Open2(IInStream *stream)
3125 return S_OK; 3155 return S_OK;
3126} 3156}
3127 3157
3128STDMETHODIMP CHandler::Open(IInStream *inStream, 3158Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
3129 const UInt64 * /* maxCheckStartPosition */, 3159 const UInt64 * /* maxCheckStartPosition */,
3130 IArchiveOpenCallback * /* openArchiveCallback */) 3160 IArchiveOpenCallback * /* openArchiveCallback */))
3131{ 3161{
3132 COM_TRY_BEGIN 3162 COM_TRY_BEGIN
3133 Close(); 3163 Close();
@@ -3142,7 +3172,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
3142 COM_TRY_END 3172 COM_TRY_END
3143} 3173}
3144 3174
3145STDMETHODIMP CHandler::Close() 3175Z7_COM7F_IMF(CHandler::Close())
3146{ 3176{
3147 _totalSize = 0; 3177 _totalSize = 0;
3148 _stream.Release(); 3178 _stream.Release();
@@ -3150,17 +3180,17 @@ STDMETHODIMP CHandler::Close()
3150 return S_OK; 3180 return S_OK;
3151} 3181}
3152 3182
3153STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 3183Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
3154{ 3184{
3155 *numItems = _items.Size(); 3185 *numItems = _items.Size();
3156 return S_OK; 3186 return S_OK;
3157} 3187}
3158 3188
3159STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 3189Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3160 Int32 testMode, IArchiveExtractCallback *extractCallback) 3190 Int32 testMode, IArchiveExtractCallback *extractCallback))
3161{ 3191{
3162 COM_TRY_BEGIN 3192 COM_TRY_BEGIN
3163 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 3193 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
3164 if (allFilesMode) 3194 if (allFilesMode)
3165 numItems = _items.Size(); 3195 numItems = _items.Size();
3166 if (numItems == 0) 3196 if (numItems == 0)
@@ -3187,35 +3217,35 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
3187 for (i = 0; i < numItems; i++) 3217 for (i = 0; i < numItems; i++)
3188 { 3218 {
3189 lps->InSize = lps->OutSize = currentTotalSize; 3219 lps->InSize = lps->OutSize = currentTotalSize;
3190 RINOK(lps->SetCur()); 3220 RINOK(lps->SetCur())
3191 CMyComPtr<ISequentialOutStream> realOutStream; 3221 CMyComPtr<ISequentialOutStream> realOutStream;
3192 Int32 askMode = testMode ? 3222 const Int32 askMode = testMode ?
3193 NExtract::NAskMode::kTest : 3223 NExtract::NAskMode::kTest :
3194 NExtract::NAskMode::kExtract; 3224 NExtract::NAskMode::kExtract;
3195 UInt32 index = allFilesMode ? i : indices[i]; 3225 const UInt32 index = allFilesMode ? i : indices[i];
3196 const CSection &item = _items[index]; 3226 const CSection &item = _items[index];
3197 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 3227 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
3198 currentTotalSize += item.PSize; 3228 currentTotalSize += item.PSize;
3199 3229
3200 if (!testMode && !realOutStream) 3230 if (!testMode && !realOutStream)
3201 continue; 3231 continue;
3202 RINOK(extractCallback->PrepareOperation(askMode)); 3232 RINOK(extractCallback->PrepareOperation(askMode))
3203 int res = NExtract::NOperationResult::kDataError; 3233 int res = NExtract::NOperationResult::kDataError;
3204 3234
3205 RINOK(_stream->Seek(item.Pa, STREAM_SEEK_SET, NULL)); 3235 RINOK(InStream_SeekSet(_stream, item.Pa))
3206 streamSpec->Init(item.PSize); 3236 streamSpec->Init(item.PSize);
3207 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 3237 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
3208 if (copyCoderSpec->TotalSize == item.PSize) 3238 if (copyCoderSpec->TotalSize == item.PSize)
3209 res = NExtract::NOperationResult::kOK; 3239 res = NExtract::NOperationResult::kOK;
3210 3240
3211 realOutStream.Release(); 3241 realOutStream.Release();
3212 RINOK(extractCallback->SetOperationResult(res)); 3242 RINOK(extractCallback->SetOperationResult(res))
3213 } 3243 }
3214 return S_OK; 3244 return S_OK;
3215 COM_TRY_END 3245 COM_TRY_END
3216} 3246}
3217 3247
3218STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 3248Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
3219{ 3249{
3220 COM_TRY_BEGIN 3250 COM_TRY_BEGIN
3221 const CSection &item = _items[index]; 3251 const CSection &item = _items[index];
@@ -3223,7 +3253,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
3223 COM_TRY_END 3253 COM_TRY_END
3224} 3254}
3225 3255
3226STDMETHODIMP CHandler::AllowTail(Int32 allowTail) 3256Z7_COM7F_IMF(CHandler::AllowTail(Int32 allowTail))
3227{ 3257{
3228 _allowTail = IntToBool(allowTail); 3258 _allowTail = IntToBool(allowTail);
3229 return S_OK; 3259 return S_OK;
@@ -3232,7 +3262,7 @@ STDMETHODIMP CHandler::AllowTail(Int32 allowTail)
3232static const Byte k_Signature[] = { 'V', 'Z' }; 3262static const Byte k_Signature[] = { 'V', 'Z' };
3233 3263
3234REGISTER_ARC_I( 3264REGISTER_ARC_I(
3235 "TE", "te", 0, 0xCF, 3265 "TE", "te", NULL, 0xCF,
3236 k_Signature, 3266 k_Signature,
3237 0, 3267 0,
3238 NArcInfoFlags::kPreArc, 3268 NArcInfoFlags::kPreArc,
diff --git a/CPP/7zip/Archive/PpmdHandler.cpp b/CPP/7zip/Archive/PpmdHandler.cpp
index 101bfd9..e5c2f9b 100644
--- a/CPP/7zip/Archive/PpmdHandler.cpp
+++ b/CPP/7zip/Archive/PpmdHandler.cpp
@@ -33,13 +33,13 @@ struct CBuf
33{ 33{
34 Byte *Buf; 34 Byte *Buf;
35 35
36 CBuf(): Buf(0) {} 36 CBuf(): Buf(NULL) {}
37 ~CBuf() { ::MidFree(Buf); } 37 ~CBuf() { ::MidFree(Buf); }
38 bool Alloc() 38 bool Alloc()
39 { 39 {
40 if (!Buf) 40 if (!Buf)
41 Buf = (Byte *)::MidAlloc(kBufSize); 41 Buf = (Byte *)::MidAlloc(kBufSize);
42 return (Buf != 0); 42 return (Buf != NULL);
43 } 43 }
44}; 44};
45 45
@@ -59,13 +59,17 @@ struct CItem
59 unsigned Restor; 59 unsigned Restor;
60 60
61 HRESULT ReadHeader(ISequentialInStream *s, UInt32 &headerSize); 61 HRESULT ReadHeader(ISequentialInStream *s, UInt32 &headerSize);
62 bool IsSupported() const { return Ver == 7 || (Ver == 8 && Restor < PPMD8_RESTORE_METHOD_UNSUPPPORTED); } 62 bool IsSupported() const
63 {
64 return (Ver == 7 && Order >= PPMD7_MIN_ORDER)
65 || (Ver == 8 && Order >= PPMD8_MIN_ORDER && Restor < PPMD8_RESTORE_METHOD_UNSUPPPORTED);
66 }
63}; 67};
64 68
65HRESULT CItem::ReadHeader(ISequentialInStream *s, UInt32 &headerSize) 69HRESULT CItem::ReadHeader(ISequentialInStream *s, UInt32 &headerSize)
66{ 70{
67 Byte h[kHeaderSize]; 71 Byte h[kHeaderSize];
68 RINOK(ReadStream_FALSE(s, h, kHeaderSize)); 72 RINOK(ReadStream_FALSE(s, h, kHeaderSize))
69 if (GetUi32(h) != kSignature) 73 if (GetUi32(h) != kSignature)
70 return S_FALSE; 74 return S_FALSE;
71 Attrib = GetUi32(h + 4); 75 Attrib = GetUi32(h + 4);
@@ -92,11 +96,10 @@ HRESULT CItem::ReadHeader(ISequentialInStream *s, UInt32 &headerSize)
92 return res; 96 return res;
93} 97}
94 98
95class CHandler: 99
96 public IInArchive, 100Z7_CLASS_IMP_CHandler_IInArchive_1(
97 public IArchiveOpenSeq, 101 IArchiveOpenSeq
98 public CMyUnknownImp 102)
99{
100 CItem _item; 103 CItem _item;
101 UInt32 _headerSize; 104 UInt32 _headerSize;
102 bool _packSize_Defined; 105 bool _packSize_Defined;
@@ -104,11 +107,6 @@ class CHandler:
104 CMyComPtr<ISequentialInStream> _stream; 107 CMyComPtr<ISequentialInStream> _stream;
105 108
106 void GetVersion(NCOM::CPropVariant &prop); 109 void GetVersion(NCOM::CPropVariant &prop);
107
108public:
109 MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq)
110 INTERFACE_IInArchive(;)
111 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
112}; 110};
113 111
114static const Byte kProps[] = 112static const Byte kProps[] =
@@ -144,7 +142,7 @@ void CHandler::GetVersion(NCOM::CPropVariant &prop)
144 prop = s; 142 prop = s;
145} 143}
146 144
147STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 145Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
148{ 146{
149 NCOM::CPropVariant prop; 147 NCOM::CPropVariant prop;
150 switch (propID) 148 switch (propID)
@@ -157,13 +155,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
157} 155}
158 156
159 157
160STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 158Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
161{ 159{
162 *numItems = 1; 160 *numItems = 1;
163 return S_OK; 161 return S_OK;
164} 162}
165 163
166STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 164Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
167{ 165{
168 COM_TRY_BEGIN 166 COM_TRY_BEGIN
169 NCOM::CPropVariant prop; 167 NCOM::CPropVariant prop;
@@ -187,12 +185,12 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
187 COM_TRY_END 185 COM_TRY_END
188} 186}
189 187
190STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) 188Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *))
191{ 189{
192 return OpenSeq(stream); 190 return OpenSeq(stream);
193} 191}
194 192
195STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 193Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
196{ 194{
197 COM_TRY_BEGIN 195 COM_TRY_BEGIN
198 HRESULT res; 196 HRESULT res;
@@ -210,7 +208,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
210 COM_TRY_END 208 COM_TRY_END
211} 209}
212 210
213STDMETHODIMP CHandler::Close() 211Z7_COM7F_IMF(CHandler::Close())
214{ 212{
215 _packSize = 0; 213 _packSize = 0;
216 _packSize_Defined = false; 214 _packSize_Defined = false;
@@ -252,7 +250,7 @@ struct CPpmdCpp
252 if (Ver == 7) 250 if (Ver == 7)
253 Ppmd7_Init(&_ppmd7, order); 251 Ppmd7_Init(&_ppmd7, order);
254 else 252 else
255 Ppmd8_Init(&_ppmd8, order, restor);; 253 Ppmd8_Init(&_ppmd8, order, restor);
256 } 254 }
257 255
258 bool InitRc(CByteInBufWrap *inStream) 256 bool InitRc(CByteInBufWrap *inStream)
@@ -278,8 +276,8 @@ struct CPpmdCpp
278}; 276};
279 277
280 278
281STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 279Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
282 Int32 testMode, IArchiveExtractCallback *extractCallback) 280 Int32 testMode, IArchiveExtractCallback *extractCallback))
283{ 281{
284 if (numItems == 0) 282 if (numItems == 0)
285 return S_OK; 283 return S_OK;
@@ -288,12 +286,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
288 286
289 // extractCallback->SetTotal(_packSize); 287 // extractCallback->SetTotal(_packSize);
290 UInt64 currentTotalPacked = 0; 288 UInt64 currentTotalPacked = 0;
291 RINOK(extractCallback->SetCompleted(&currentTotalPacked)); 289 RINOK(extractCallback->SetCompleted(&currentTotalPacked))
292 CMyComPtr<ISequentialOutStream> realOutStream; 290 CMyComPtr<ISequentialOutStream> realOutStream;
293 Int32 askMode = testMode ? 291 const Int32 askMode = testMode ?
294 NExtract::NAskMode::kTest : 292 NExtract::NAskMode::kTest :
295 NExtract::NAskMode::kExtract; 293 NExtract::NAskMode::kExtract;
296 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 294 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
297 if (!testMode && !realOutStream) 295 if (!testMode && !realOutStream)
298 return S_OK; 296 return S_OK;
299 297
@@ -331,7 +329,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
331 { 329 {
332 lps->InSize = _packSize = inBuf.GetProcessed(); 330 lps->InSize = _packSize = inBuf.GetProcessed();
333 lps->OutSize = outSize; 331 lps->OutSize = outSize;
334 RINOK(lps->SetCur()); 332 RINOK(lps->SetCur())
335 333
336 size_t i; 334 size_t i;
337 int sym = 0; 335 int sym = 0;
@@ -363,7 +361,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
363 _packSize_Defined = true; 361 _packSize_Defined = true;
364 if (realOutStream) 362 if (realOutStream)
365 { 363 {
366 RINOK(WriteStream(realOutStream, outBuf.Buf, i)); 364 RINOK(WriteStream(realOutStream, outBuf.Buf, i))
367 } 365 }
368 366
369 if (inBuf.Extra) 367 if (inBuf.Extra)
@@ -380,7 +378,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
380 } 378 }
381 } 379 }
382 380
383 RINOK(inBuf.Res); 381 RINOK(inBuf.Res)
384 } 382 }
385 383
386 realOutStream.Release(); 384 realOutStream.Release();
@@ -391,7 +389,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
391static const Byte k_Signature[] = { 0x8F, 0xAF, 0xAC, 0x84 }; 389static const Byte k_Signature[] = { 0x8F, 0xAF, 0xAC, 0x84 };
392 390
393REGISTER_ARC_I( 391REGISTER_ARC_I(
394 "Ppmd", "pmd", 0, 0xD, 392 "Ppmd", "pmd", NULL, 0xD,
395 k_Signature, 393 k_Signature,
396 0, 394 0,
397 0, 395 0,
diff --git a/CPP/7zip/Archive/QcowHandler.cpp b/CPP/7zip/Archive/QcowHandler.cpp
index 4a795ec..5a80daa 100644
--- a/CPP/7zip/Archive/QcowHandler.cpp
+++ b/CPP/7zip/Archive/QcowHandler.cpp
@@ -28,9 +28,7 @@ using namespace NWindows;
28namespace NArchive { 28namespace NArchive {
29namespace NQcow { 29namespace NQcow {
30 30
31#define SIGNATURE { 'Q', 'F', 'I', 0xFB, 0, 0, 0 } 31static const Byte k_Signature[] = { 'Q', 'F', 'I', 0xFB, 0, 0, 0 };
32
33static const Byte k_Signature[] = SIGNATURE;
34 32
35/* 33/*
36VA to PA maps: 34VA to PA maps:
@@ -39,8 +37,12 @@ VA to PA maps:
39 low bits : _clusterBits 37 low bits : _clusterBits
40*/ 38*/
41 39
42class CHandler: public CHandlerImg 40Z7_class_CHandler_final: public CHandlerImg
43{ 41{
42 Z7_IFACE_COM7_IMP(IInArchive_Img)
43 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
44 Z7_IFACE_COM7_IMP(ISequentialInStream)
45
44 unsigned _clusterBits; 46 unsigned _clusterBits;
45 unsigned _numMidBits; 47 unsigned _numMidBits;
46 UInt64 _compressedFlag; 48 UInt64 _compressedFlag;
@@ -75,7 +77,7 @@ class CHandler: public CHandlerImg
75 HRESULT Seek2(UInt64 offset) 77 HRESULT Seek2(UInt64 offset)
76 { 78 {
77 _posInArc = offset; 79 _posInArc = offset;
78 return Stream->Seek(offset, STREAM_SEEK_SET, NULL); 80 return InStream_SeekSet(Stream, offset);
79 } 81 }
80 82
81 HRESULT InitAndSeek() 83 HRESULT InitAndSeek()
@@ -84,19 +86,13 @@ class CHandler: public CHandlerImg
84 return Seek2(0); 86 return Seek2(0);
85 } 87 }
86 88
87 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); 89 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override;
88
89public:
90 INTERFACE_IInArchive_Img(;)
91
92 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
93 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
94}; 90};
95 91
96 92
97static const UInt32 kEmptyDirItem = (UInt32)0 - 1; 93static const UInt32 kEmptyDirItem = (UInt32)0 - 1;
98 94
99STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 95Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
100{ 96{
101 if (processedSize) 97 if (processedSize)
102 *processedSize = 0; 98 *processedSize = 0;
@@ -190,14 +186,14 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
190 if (sectorOffset != _posInArc) 186 if (sectorOffset != _posInArc)
191 { 187 {
192 // printf("\nDeflate-Seek %12I64x %12I64x\n", sectorOffset, sectorOffset - _posInArc); 188 // printf("\nDeflate-Seek %12I64x %12I64x\n", sectorOffset, sectorOffset - _posInArc);
193 RINOK(Seek2(sectorOffset)); 189 RINOK(Seek2(sectorOffset))
194 } 190 }
195 if (_cacheCompressed.Size() < dataSize) 191 if (_cacheCompressed.Size() < dataSize)
196 return E_FAIL; 192 return E_FAIL;
197 const size_t dataSize3 = dataSize - _comprSize; 193 const size_t dataSize3 = dataSize - _comprSize;
198 size_t dataSize2 = dataSize3; 194 size_t dataSize2 = dataSize3;
199 // printf("\n\n=======\nReadStream = %6d _comprPos = %6d \n", (UInt32)dataSize2, (UInt32)_comprPos); 195 // printf("\n\n=======\nReadStream = %6d _comprPos = %6d \n", (UInt32)dataSize2, (UInt32)_comprPos);
200 RINOK(ReadStream(Stream, _cacheCompressed + _comprSize, &dataSize2)); 196 RINOK(ReadStream(Stream, _cacheCompressed + _comprSize, &dataSize2))
201 _posInArc += dataSize2; 197 _posInArc += dataSize2;
202 if (dataSize2 != dataSize3) 198 if (dataSize2 != dataSize3)
203 return E_FAIL; 199 return E_FAIL;
@@ -215,7 +211,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
215 211
216 // Do we need to use smaller block than clusterSize for last cluster? 212 // Do we need to use smaller block than clusterSize for last cluster?
217 const UInt64 blockSize64 = clusterSize; 213 const UInt64 blockSize64 = clusterSize;
218 HRESULT res = _deflateDecoderSpec->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); 214 HRESULT res = _deflateDecoder->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL);
219 215
220 /* 216 /*
221 if (_bufOutStreamSpec->GetPos() != clusterSize) 217 if (_bufOutStreamSpec->GetPos() != clusterSize)
@@ -227,7 +223,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
227 || _bufOutStreamSpec->GetPos() != clusterSize) 223 || _bufOutStreamSpec->GetPos() != clusterSize)
228 res = S_FALSE; 224 res = S_FALSE;
229 225
230 RINOK(res); 226 RINOK(res)
231 _cacheCluster = cluster; 227 _cacheCluster = cluster;
232 228
233 continue; 229 continue;
@@ -245,7 +241,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
245 if (v != _posInArc) 241 if (v != _posInArc)
246 { 242 {
247 // printf("\n%12I64x\n", v - _posInArc); 243 // printf("\n%12I64x\n", v - _posInArc);
248 RINOK(Seek2(v)); 244 RINOK(Seek2(v))
249 } 245 }
250 HRESULT res = Stream->Read(data, size, &size); 246 HRESULT res = Stream->Read(data, size, &size);
251 _posInArc += size; 247 _posInArc += size;
@@ -285,7 +281,7 @@ static const Byte kArcProps[] =
285IMP_IInArchive_Props 281IMP_IInArchive_Props
286IMP_IInArchive_ArcProps 282IMP_IInArchive_ArcProps
287 283
288STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 284Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
289{ 285{
290 COM_TRY_BEGIN 286 COM_TRY_BEGIN
291 NCOM::CPropVariant prop; 287 NCOM::CPropVariant prop;
@@ -322,7 +318,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
322 case kpidErrorFlags: 318 case kpidErrorFlags:
323 { 319 {
324 UInt32 v = 0; 320 UInt32 v = 0;
325 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 321 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
326 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; 322 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod;
327 // if (_headerError) v |= kpv_ErrorFlags_HeadersError; 323 // if (_headerError) v |= kpv_ErrorFlags_HeadersError;
328 if (!Stream && v == 0 && _isArc) 324 if (!Stream && v == 0 && _isArc)
@@ -339,7 +335,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
339} 335}
340 336
341 337
342STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 338Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
343{ 339{
344 COM_TRY_BEGIN 340 COM_TRY_BEGIN
345 NCOM::CPropVariant prop; 341 NCOM::CPropVariant prop;
@@ -361,7 +357,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
361{ 357{
362 const unsigned kHeaderSize = 18 * 4; 358 const unsigned kHeaderSize = 18 * 4;
363 Byte buf[kHeaderSize]; 359 Byte buf[kHeaderSize];
364 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); 360 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize))
365 361
366 if (memcmp(buf, k_Signature, 4) != 0) 362 if (memcmp(buf, k_Signature, 4) != 0)
367 return S_FALSE; 363 return S_FALSE;
@@ -423,7 +419,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
423 /* 419 /*
424 CByteBuffer refs; 420 CByteBuffer refs;
425 refs.Alloc(numBytes); 421 refs.Alloc(numBytes);
426 RINOK(stream->Seek(refOffset, STREAM_SEEK_SET, NULL)); 422 RINOK(InStream_SeekSet(stream, refOffset))
427 RINOK(ReadStream_FALSE(stream, refs, numBytes)); 423 RINOK(ReadStream_FALSE(stream, refs, numBytes));
428 */ 424 */
429 const UInt64 end = refOffset + numBytes; 425 const UInt64 end = refOffset + numBytes;
@@ -456,8 +452,8 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
456 if ((t1SizeBytes >> 3) != l1Size) 452 if ((t1SizeBytes >> 3) != l1Size)
457 return S_FALSE; 453 return S_FALSE;
458 table.Alloc(t1SizeBytes); 454 table.Alloc(t1SizeBytes);
459 RINOK(stream->Seek(l1Offset, STREAM_SEEK_SET, NULL)); 455 RINOK(InStream_SeekSet(stream, l1Offset))
460 RINOK(ReadStream_FALSE(stream, table, t1SizeBytes)); 456 RINOK(ReadStream_FALSE(stream, table, t1SizeBytes))
461 457
462 { 458 {
463 UInt64 end = l1Offset + t1SizeBytes; 459 UInt64 end = l1Offset + t1SizeBytes;
@@ -498,7 +494,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
498 if (openCallback) 494 if (openCallback)
499 { 495 {
500 const UInt64 totalBytes = (UInt64)numTables << (_numMidBits + 3); 496 const UInt64 totalBytes = (UInt64)numTables << (_numMidBits + 3);
501 RINOK(openCallback->SetTotal(NULL, &totalBytes)); 497 RINOK(openCallback->SetTotal(NULL, &totalBytes))
502 } 498 }
503 499
504 for (i = 0; i < l1Size; i++) 500 for (i = 0; i < l1Size; i++)
@@ -522,11 +518,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
522 if (openCallback && (tableOffset & 0xFFFFF) == 0) 518 if (openCallback && (tableOffset & 0xFFFFF) == 0)
523 { 519 {
524 const UInt64 numBytes = tableOffset; 520 const UInt64 numBytes = tableOffset;
525 RINOK(openCallback->SetCompleted(NULL, &numBytes)); 521 RINOK(openCallback->SetCompleted(NULL, &numBytes))
526 } 522 }
527 523
528 RINOK(stream->Seek(v, STREAM_SEEK_SET, NULL)); 524 RINOK(InStream_SeekSet(stream, v))
529 RINOK(ReadStream_FALSE(stream, buf2, midSize)); 525 RINOK(ReadStream_FALSE(stream, buf2, midSize))
530 526
531 const UInt64 end = v + midSize; 527 const UInt64 end = v + midSize;
532 if (_phySize < end) 528 if (_phySize < end)
@@ -596,7 +592,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
596} 592}
597 593
598 594
599STDMETHODIMP CHandler::Close() 595Z7_COM7F_IMF(CHandler::Close())
600{ 596{
601 _table.Free(); 597 _table.Free();
602 _dir.Free(); 598 _dir.Free();
@@ -617,7 +613,7 @@ STDMETHODIMP CHandler::Close()
617} 613}
618 614
619 615
620STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 616Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
621{ 617{
622 COM_TRY_BEGIN 618 COM_TRY_BEGIN
623 *stream = NULL; 619 *stream = NULL;
@@ -655,7 +651,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea
655 } 651 }
656 652
657 CMyComPtr<ISequentialInStream> streamTemp = this; 653 CMyComPtr<ISequentialInStream> streamTemp = this;
658 RINOK(InitAndSeek()); 654 RINOK(InitAndSeek())
659 *stream = streamTemp.Detach(); 655 *stream = streamTemp.Detach();
660 return S_OK; 656 return S_OK;
661 COM_TRY_END 657 COM_TRY_END
diff --git a/CPP/7zip/Archive/Rar/Rar5Handler.cpp b/CPP/7zip/Archive/Rar/Rar5Handler.cpp
index 563695f..87d11e7 100644
--- a/CPP/7zip/Archive/Rar/Rar5Handler.cpp
+++ b/CPP/7zip/Archive/Rar/Rar5Handler.cpp
@@ -45,9 +45,8 @@ namespace NRar5 {
45 45
46static const unsigned kMarkerSize = 8; 46static const unsigned kMarkerSize = 8;
47 47
48#define SIGNATURE { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0 } 48static const Byte kMarker[kMarkerSize] =
49 49 { 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0 };
50static const Byte kMarker[kMarkerSize] = SIGNATURE;
51 50
52static const size_t kCommentSize_Max = (size_t)1 << 16; 51static const size_t kCommentSize_Max = (size_t)1 << 16;
53 52
@@ -252,7 +251,7 @@ void CItem::PrintInfo(AString &s) const
252 rem++; 251 rem++;
253 252
254 s.Add_Space_if_NotEmpty(); 253 s.Add_Space_if_NotEmpty();
255 PrintType(s, g_ExtraTypes, ARRAY_SIZE(g_ExtraTypes), id); 254 PrintType(s, g_ExtraTypes, Z7_ARRAY_SIZE(g_ExtraTypes), id);
256 255
257 if (id == NExtraID::kTime) 256 if (id == NExtraID::kTime)
258 { 257 {
@@ -262,10 +261,10 @@ void CItem::PrintInfo(AString &s) const
262 if (num != 0) 261 if (num != 0)
263 { 262 {
264 s += ':'; 263 s += ':';
265 for (unsigned i = 0; i < ARRAY_SIZE(g_ExtraTimeFlags); i++) 264 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExtraTimeFlags); i++)
266 if ((flags & ((UInt64)1 << i)) != 0) 265 if ((flags & ((UInt64)1 << i)) != 0)
267 s += g_ExtraTimeFlags[i]; 266 s += g_ExtraTimeFlags[i];
268 flags &= ~(((UInt64)1 << ARRAY_SIZE(g_ExtraTimeFlags)) - 1); 267 flags &= ~(((UInt64)1 << Z7_ARRAY_SIZE(g_ExtraTimeFlags)) - 1);
269 if (flags != 0) 268 if (flags != 0)
270 { 269 {
271 s += '_'; 270 s += '_';
@@ -279,7 +278,7 @@ void CItem::PrintInfo(AString &s) const
279 if (linkInfo.Parse(Extra + offset, (unsigned)rem)) 278 if (linkInfo.Parse(Extra + offset, (unsigned)rem))
280 { 279 {
281 s += ':'; 280 s += ':';
282 PrintType(s, g_LinkTypes, ARRAY_SIZE(g_LinkTypes), linkInfo.Type); 281 PrintType(s, g_LinkTypes, Z7_ARRAY_SIZE(g_LinkTypes), linkInfo.Type);
283 UInt64 flags = linkInfo.Flags; 282 UInt64 flags = linkInfo.Flags;
284 if (flags != 0) 283 if (flags != 0)
285 { 284 {
@@ -349,12 +348,12 @@ bool CItem::FindExtra_Version(UInt64 &version) const
349bool CItem::FindExtra_Link(CLinkInfo &link) const 348bool CItem::FindExtra_Link(CLinkInfo &link) const
350{ 349{
351 unsigned size; 350 unsigned size;
352 int offset = FindExtra(NExtraID::kLink, size); 351 const int offset = FindExtra(NExtraID::kLink, size);
353 if (offset < 0) 352 if (offset < 0)
354 return false; 353 return false;
355 if (!link.Parse(Extra + (unsigned)offset, size)) 354 if (!link.Parse(Extra + (unsigned)offset, size))
356 return false; 355 return false;
357 link.NameOffset += offset; 356 link.NameOffset += (unsigned)offset;
358 return true; 357 return true;
359} 358}
360 359
@@ -481,10 +480,10 @@ bool CHash::Check(const CItem &item, NCrypto::NRar5::CDecoder *cryptoDecoderSpec
481} 480}
482 481
483 482
484class COutStreamWithHash: 483Z7_CLASS_IMP_NOQIB_1(
485 public ISequentialOutStream, 484 COutStreamWithHash
486 public CMyUnknownImp 485 , ISequentialOutStream
487{ 486)
488 ISequentialOutStream *_stream; 487 ISequentialOutStream *_stream;
489 UInt64 _pos; 488 UInt64 _pos;
490 UInt64 _size; 489 UInt64 _size;
@@ -495,8 +494,6 @@ public:
495 494
496 COutStreamWithHash(): _destBuf(NULL) {} 495 COutStreamWithHash(): _destBuf(NULL) {}
497 496
498 MY_UNKNOWN_IMP
499 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
500 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 497 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
501 void Init(const CItem &item, Byte *destBuf) 498 void Init(const CItem &item, Byte *destBuf)
502 { 499 {
@@ -516,7 +513,7 @@ public:
516}; 513};
517 514
518 515
519STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize) 516Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize))
520{ 517{
521 HRESULT result = S_OK; 518 HRESULT result = S_OK;
522 if (_size_Defined) 519 if (_size_Defined)
@@ -550,7 +547,7 @@ class CInArchive
550 NCrypto::NRar5::CDecoder *m_CryptoDecoderSpec; 547 NCrypto::NRar5::CDecoder *m_CryptoDecoderSpec;
551 CMyComPtr<ICompressFilter> m_CryptoDecoder; 548 CMyComPtr<ICompressFilter> m_CryptoDecoder;
552 549
553 CLASS_NO_COPY(CInArchive) 550 Z7_CLASS_NO_COPY(CInArchive)
554 551
555 HRESULT ReadStream_Check(void *data, size_t size); 552 HRESULT ReadStream_Check(void *data, size_t size);
556 553
@@ -591,7 +588,7 @@ public:
591static HRESULT MySetPassword(ICryptoGetTextPassword *getTextPassword, NCrypto::NRar5::CDecoder *cryptoDecoderSpec) 588static HRESULT MySetPassword(ICryptoGetTextPassword *getTextPassword, NCrypto::NRar5::CDecoder *cryptoDecoderSpec)
592{ 589{
593 CMyComBSTR_Wipe password; 590 CMyComBSTR_Wipe password;
594 RINOK(getTextPassword->CryptoGetTextPassword(&password)); 591 RINOK(getTextPassword->CryptoGetTextPassword(&password))
595 AString_Wipe utf8; 592 AString_Wipe utf8;
596 const unsigned kPasswordLen_MAX = 127; 593 const unsigned kPasswordLen_MAX = 127;
597 UString_Wipe unicode; 594 UString_Wipe unicode;
@@ -615,7 +612,7 @@ bool CInArchive::ReadVar(UInt64 &val)
615HRESULT CInArchive::ReadStream_Check(void *data, size_t size) 612HRESULT CInArchive::ReadStream_Check(void *data, size_t size)
616{ 613{
617 size_t size2 = size; 614 size_t size2 = size;
618 RINOK(ReadStream(_stream, data, &size2)); 615 RINOK(ReadStream(_stream, data, &size2))
619 if (size2 == size) 616 if (size2 == size)
620 return S_OK; 617 return S_OK;
621 UnexpectedEnd = true; 618 UnexpectedEnd = true;
@@ -637,23 +634,23 @@ HRESULT CInArchive::ReadBlockHeader(CHeader &h)
637 634
638 if (m_CryptoMode) 635 if (m_CryptoMode)
639 { 636 {
640 RINOK(ReadStream_Check(buf, kBufSize)); 637 RINOK(ReadStream_Check(buf, kBufSize))
641 memcpy(m_CryptoDecoderSpec->_iv, buf, AES_BLOCK_SIZE); 638 memcpy(m_CryptoDecoderSpec->_iv, buf, AES_BLOCK_SIZE);
642 RINOK(m_CryptoDecoderSpec->Init()); 639 RINOK(m_CryptoDecoderSpec->Init())
643 640
644 _buf.AllocAtLeast(1 << 12); 641 _buf.AllocAtLeast(1 << 12);
645 if (!(Byte *)_buf) 642 if (!(Byte *)_buf)
646 return E_OUTOFMEMORY; 643 return E_OUTOFMEMORY;
647 644
648 memcpy(_buf, buf + AES_BLOCK_SIZE, AES_BLOCK_SIZE); 645 memcpy(_buf, buf + AES_BLOCK_SIZE, AES_BLOCK_SIZE);
649 if (m_CryptoDecoderSpec->Filter(_buf, AES_BLOCK_SIZE) != AES_BLOCK_SIZE) 646 if (m_CryptoDecoder->Filter(_buf, AES_BLOCK_SIZE) != AES_BLOCK_SIZE)
650 return E_FAIL; 647 return E_FAIL;
651 memcpy(buf, _buf, AES_BLOCK_SIZE); 648 memcpy(buf, _buf, AES_BLOCK_SIZE);
652 filled = AES_BLOCK_SIZE; 649 filled = AES_BLOCK_SIZE;
653 } 650 }
654 else 651 else
655 { 652 {
656 RINOK(ReadStream_Check(buf, kStartSize)); 653 RINOK(ReadStream_Check(buf, kStartSize))
657 filled = kStartSize; 654 filled = kStartSize;
658 } 655 }
659 656
@@ -680,10 +677,10 @@ HRESULT CInArchive::ReadBlockHeader(CHeader &h)
680 677
681 size_t rem = allocSize - filled; 678 size_t rem = allocSize - filled;
682 AddToSeekValue(allocSize + (m_CryptoMode ? AES_BLOCK_SIZE : 0)); 679 AddToSeekValue(allocSize + (m_CryptoMode ? AES_BLOCK_SIZE : 0));
683 RINOK(ReadStream_Check(_buf + filled, rem)); 680 RINOK(ReadStream_Check(_buf + filled, rem))
684 if (m_CryptoMode) 681 if (m_CryptoMode)
685 { 682 {
686 if (m_CryptoDecoderSpec->Filter(_buf + filled, (UInt32)rem) != rem) 683 if (m_CryptoDecoder->Filter(_buf + filled, (UInt32)rem) != rem)
687 return E_FAIL; 684 return E_FAIL;
688 } 685 }
689 686
@@ -804,19 +801,19 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit,
804 UInt64 arcStartPos = StreamStartPosition; 801 UInt64 arcStartPos = StreamStartPosition;
805 { 802 {
806 Byte marker[kMarkerSize]; 803 Byte marker[kMarkerSize];
807 RINOK(ReadStream_FALSE(stream, marker, kMarkerSize)); 804 RINOK(ReadStream_FALSE(stream, marker, kMarkerSize))
808 if (memcmp(marker, kMarker, kMarkerSize) == 0) 805 if (memcmp(marker, kMarker, kMarkerSize) == 0)
809 Position += kMarkerSize; 806 Position += kMarkerSize;
810 else 807 else
811 { 808 {
812 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) 809 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0)
813 return S_FALSE; 810 return S_FALSE;
814 RINOK(stream->Seek(StreamStartPosition, STREAM_SEEK_SET, NULL)); 811 RINOK(InStream_SeekSet(stream, StreamStartPosition))
815 RINOK(FindSignatureInStream(stream, kMarker, kMarkerSize, 812 RINOK(FindSignatureInStream(stream, kMarker, kMarkerSize,
816 searchHeaderSizeLimit, arcStartPos)); 813 searchHeaderSizeLimit, arcStartPos))
817 arcStartPos += StreamStartPosition; 814 arcStartPos += StreamStartPosition;
818 Position = arcStartPos + kMarkerSize; 815 Position = arcStartPos + kMarkerSize;
819 RINOK(stream->Seek(Position, STREAM_SEEK_SET, NULL)); 816 RINOK(InStream_SeekSet(stream, Position))
820 } 817 }
821 } 818 }
822 819
@@ -824,7 +821,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit,
824 _stream = stream; 821 _stream = stream;
825 822
826 CHeader h; 823 CHeader h;
827 RINOK(ReadBlockHeader(h)); 824 RINOK(ReadBlockHeader(h))
828 info.IsEncrypted = false; 825 info.IsEncrypted = false;
829 826
830 if (h.Type == NHeaderType::kArcEncrypt) 827 if (h.Type == NHeaderType::kArcEncrypt)
@@ -843,9 +840,9 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit,
843 } 840 }
844 841
845 RINOK(m_CryptoDecoderSpec->SetDecoderProps( 842 RINOK(m_CryptoDecoderSpec->SetDecoderProps(
846 _buf + _bufPos, (unsigned)(_bufSize - _bufPos), false, false)); 843 _buf + _bufPos, (unsigned)(_bufSize - _bufPos), false, false))
847 844
848 RINOK(MySetPassword(getTextPassword, m_CryptoDecoderSpec)); 845 RINOK(MySetPassword(getTextPassword, m_CryptoDecoderSpec))
849 846
850 if (!m_CryptoDecoderSpec->CalcKey_and_CheckPassword()) 847 if (!m_CryptoDecoderSpec->CalcKey_and_CheckPassword())
851 { 848 {
@@ -853,7 +850,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit,
853 return S_FALSE; 850 return S_FALSE;
854 } 851 }
855 852
856 RINOK(ReadBlockHeader(h)); 853 RINOK(ReadBlockHeader(h))
857 } 854 }
858 855
859 if (h.Type != NHeaderType::kArc) 856 if (h.Type != NHeaderType::kArc)
@@ -1052,16 +1049,16 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool
1052 if (!lzCoder) 1049 if (!lzCoder)
1053 { 1050 {
1054 const UInt32 methodID = 0x40305; 1051 const UInt32 methodID = 0x40305;
1055 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodID, false, lzCoder)); 1052 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodID, false, lzCoder))
1056 if (!lzCoder) 1053 if (!lzCoder)
1057 return E_NOTIMPL; 1054 return E_NOTIMPL;
1058 } 1055 }
1059 1056
1060 CMyComPtr<ICompressSetDecoderProperties2> csdp; 1057 CMyComPtr<ICompressSetDecoderProperties2> csdp;
1061 RINOK(lzCoder.QueryInterface(IID_ICompressSetDecoderProperties2, &csdp)); 1058 RINOK(lzCoder.QueryInterface(IID_ICompressSetDecoderProperties2, &csdp))
1062 1059
1063 Byte props[2] = { (Byte)(item.GetDictSize()), (Byte)(isSolid ? 1 : 0) }; 1060 Byte props[2] = { (Byte)(item.GetDictSize()), (Byte)(isSolid ? 1 : 0) };
1064 RINOK(csdp->SetDecoderProperties2(props, 2)); 1061 RINOK(csdp->SetDecoderProperties2(props, 2))
1065 } 1062 }
1066 1063
1067 unsigned cryptoSize = 0; 1064 unsigned cryptoSize = 0;
@@ -1081,7 +1078,7 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool
1081 cryptoDecoder = cryptoDecoderSpec; 1078 cryptoDecoder = cryptoDecoderSpec;
1082 } 1079 }
1083 1080
1084 RINOK(cryptoDecoderSpec->SetDecoderProps(item.Extra + (unsigned)cryptoOffset, cryptoSize, true, item.IsService())); 1081 RINOK(cryptoDecoderSpec->SetDecoderProps(item.Extra + (unsigned)cryptoOffset, cryptoSize, true, item.IsService()))
1085 1082
1086 if (!getTextPassword) 1083 if (!getTextPassword)
1087 { 1084 {
@@ -1089,7 +1086,7 @@ HRESULT CUnpacker::Create(DECL_EXTERNAL_CODECS_LOC_VARS const CItem &item, bool
1089 return E_NOTIMPL; 1086 return E_NOTIMPL;
1090 } 1087 }
1091 1088
1092 RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec)); 1089 RINOK(MySetPassword(getTextPassword, cryptoDecoderSpec))
1093 1090
1094 if (!cryptoDecoderSpec->CalcKey_and_CheckPassword()) 1091 if (!cryptoDecoderSpec->CalcKey_and_CheckPassword())
1095 wrongPassword = True; 1092 wrongPassword = True;
@@ -1273,7 +1270,7 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS
1273 _buf.ChangeSize_KeepData(newSize, _offset); 1270 _buf.ChangeSize_KeepData(newSize, _offset);
1274 1271
1275 Byte *data = (Byte *)_buf + _offset; 1272 Byte *data = (Byte *)_buf + _offset;
1276 RINOK(ReadStream_FALSE(inStream, data, packSize)); 1273 RINOK(ReadStream_FALSE(inStream, data, packSize))
1277 1274
1278 _offset += packSize; 1275 _offset += packSize;
1279 1276
@@ -1293,7 +1290,7 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS
1293 if (_offset == 0) 1290 if (_offset == 0)
1294 { 1291 {
1295 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS 1292 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS
1296 item, item.PackSize, inStream, destBuf)); 1293 item, item.PackSize, inStream, destBuf))
1297 } 1294 }
1298 else 1295 else
1299 { 1296 {
@@ -1301,7 +1298,7 @@ HRESULT CTempBuf::Decode(DECL_EXTERNAL_CODECS_LOC_VARS
1301 CMyComPtr<ISequentialInStream> bufInStream = bufInStreamSpec; 1298 CMyComPtr<ISequentialInStream> bufInStream = bufInStreamSpec;
1302 bufInStreamSpec->Init(_buf, _offset); 1299 bufInStreamSpec->Init(_buf, _offset);
1303 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS 1300 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_LOC_VARS
1304 item, _offset, bufInStream, destBuf)); 1301 item, _offset, bufInStream, destBuf))
1305 } 1302 }
1306 } 1303 }
1307 } 1304 }
@@ -1367,12 +1364,12 @@ UInt64 CHandler::GetPackSize(unsigned refIndex) const
1367 size += item.PackSize; 1364 size += item.PackSize;
1368 if (item.NextItem < 0) 1365 if (item.NextItem < 0)
1369 return size; 1366 return size;
1370 index = item.NextItem; 1367 index = (unsigned)item.NextItem;
1371 } 1368 }
1372} 1369}
1373 1370
1374 1371
1375STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1372Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1376{ 1373{
1377 COM_TRY_BEGIN 1374 COM_TRY_BEGIN
1378 1375
@@ -1501,7 +1498,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1501} 1498}
1502 1499
1503 1500
1504STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1501Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1505{ 1502{
1506 *numItems = _refs.Size(); 1503 *numItems = _refs.Size();
1507 return S_OK; 1504 return S_OK;
@@ -1515,20 +1512,20 @@ static const Byte kRawProps[] =
1515}; 1512};
1516 1513
1517 1514
1518STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 1515Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
1519{ 1516{
1520 *numProps = ARRAY_SIZE(kRawProps); 1517 *numProps = Z7_ARRAY_SIZE(kRawProps);
1521 return S_OK; 1518 return S_OK;
1522} 1519}
1523 1520
1524STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 1521Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
1525{ 1522{
1526 *propID = kRawProps[index]; 1523 *propID = kRawProps[index];
1527 *name = 0; 1524 *name = NULL;
1528 return S_OK; 1525 return S_OK;
1529} 1526}
1530 1527
1531STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 1528Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
1532{ 1529{
1533 *parentType = NParentType::kDir; 1530 *parentType = NParentType::kDir;
1534 *parent = (UInt32)(Int32)-1; 1531 *parent = (UInt32)(Int32)-1;
@@ -1549,7 +1546,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
1549} 1546}
1550 1547
1551 1548
1552STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 1549Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
1553{ 1550{
1554 *data = NULL; 1551 *data = NULL;
1555 *dataSize = 0; 1552 *dataSize = 0;
@@ -1660,7 +1657,7 @@ static void TimeRecordToProp(const CItem &item, unsigned stampIndex, NCOM::CProp
1660} 1657}
1661 1658
1662 1659
1663STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 1660Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
1664{ 1661{
1665 COM_TRY_BEGIN 1662 COM_TRY_BEGIN
1666 1663
@@ -1680,7 +1677,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1680 AString s; 1677 AString s;
1681 if (ref.Parent >= 0) 1678 if (ref.Parent >= 0)
1682 { 1679 {
1683 CItem &mainItem = _items[_refs[ref.Parent].Item]; 1680 const CItem &mainItem = _items[_refs[ref.Parent].Item];
1684 s = mainItem.Name; 1681 s = mainItem.Name;
1685 } 1682 }
1686 1683
@@ -1856,7 +1853,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1856 1853
1857 if (flags != 0) 1854 if (flags != 0)
1858 { 1855 {
1859 AString s2 = FlagsToString(k_FileFlags, ARRAY_SIZE(k_FileFlags), flags); 1856 AString s2 = FlagsToString(k_FileFlags, Z7_ARRAY_SIZE(k_FileFlags), flags);
1860 if (!s2.IsEmpty()) 1857 if (!s2.IsEmpty())
1861 { 1858 {
1862 s.Add_OptSpaced(s2); 1859 s.Add_OptSpaced(s2);
@@ -1872,7 +1869,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
1872 1869
1873 1870
1874 case kpidHostOS: 1871 case kpidHostOS:
1875 if (item.HostOS < ARRAY_SIZE(kHostOS)) 1872 if (item.HostOS < Z7_ARRAY_SIZE(kHostOS))
1876 prop = kHostOS[(size_t)item.HostOS]; 1873 prop = kHostOS[(size_t)item.HostOS];
1877 else 1874 else
1878 prop = (UInt64)item.HostOS; 1875 prop = (UInt64)item.HostOS;
@@ -1933,24 +1930,24 @@ static int FindLink(const CHandler &handler, const CUIntVector &sorted,
1933 { 1930 {
1934 if (left > 0) 1931 if (left > 0)
1935 { 1932 {
1936 unsigned refIndex = sorted[left - 1]; 1933 const unsigned refIndex = sorted[left - 1];
1937 if (CompareItemsPaths(handler, index, refIndex, &s) == 0) 1934 if (CompareItemsPaths(handler, index, refIndex, &s) == 0)
1938 return refIndex; 1935 return (int)refIndex;
1939 } 1936 }
1940 if (right < sorted.Size()) 1937 if (right < sorted.Size())
1941 { 1938 {
1942 unsigned refIndex = sorted[right]; 1939 const unsigned refIndex = sorted[right];
1943 if (CompareItemsPaths(handler, index, refIndex, &s) == 0) 1940 if (CompareItemsPaths(handler, index, refIndex, &s) == 0)
1944 return refIndex; 1941 return (int)refIndex;
1945 } 1942 }
1946 return -1; 1943 return -1;
1947 } 1944 }
1948 1945
1949 unsigned mid = (left + right) / 2; 1946 const unsigned mid = (left + right) / 2;
1950 unsigned refIndex = sorted[mid]; 1947 const unsigned refIndex = sorted[mid];
1951 int compare = CompareItemsPaths2(handler, index, refIndex, &s); 1948 const int compare = CompareItemsPaths2(handler, index, refIndex, &s);
1952 if (compare == 0) 1949 if (compare == 0)
1953 return refIndex; 1950 return (int)refIndex;
1954 if (compare < 0) 1951 if (compare < 0)
1955 right = mid; 1952 right = mid;
1956 else 1953 else
@@ -2062,7 +2059,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2062 UString baseName; 2059 UString baseName;
2063 { 2060 {
2064 NCOM::CPropVariant prop; 2061 NCOM::CPropVariant prop;
2065 RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); 2062 RINOK(openVolumeCallback->GetProperty(kpidName, &prop))
2066 if (prop.vt != VT_BSTR) 2063 if (prop.vt != VT_BSTR)
2067 break; 2064 break;
2068 baseName = prop.bstrVal; 2065 baseName = prop.bstrVal;
@@ -2087,14 +2084,12 @@ HRESULT CHandler::Open2(IInStream *stream,
2087 } 2084 }
2088 2085
2089 UInt64 endPos = 0; 2086 UInt64 endPos = 0;
2090 RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &arch.StreamStartPosition)); 2087 RINOK(InStream_GetPos_GetSize(inStream, arch.StreamStartPosition, endPos))
2091 RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos));
2092 RINOK(inStream->Seek(arch.StreamStartPosition, STREAM_SEEK_SET, NULL));
2093 2088
2094 if (openCallback) 2089 if (openCallback)
2095 { 2090 {
2096 totalBytes += endPos; 2091 totalBytes += endPos;
2097 RINOK(openCallback->SetTotal(NULL, &totalBytes)); 2092 RINOK(openCallback->SetTotal(NULL, &totalBytes))
2098 } 2093 }
2099 2094
2100 CInArcInfo arcInfoOpen; 2095 CInArcInfo arcInfoOpen;
@@ -2136,7 +2131,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2136 break; 2131 break;
2137 } 2132 }
2138 2133
2139 RINOK(inStream->Seek(arch.Position, STREAM_SEEK_SET, NULL)); 2134 RINOK(InStream_SeekSet(inStream, arch.Position))
2140 2135
2141 { 2136 {
2142 CInArchive::CHeader h; 2137 CInArchive::CHeader h;
@@ -2168,11 +2163,11 @@ HRESULT CHandler::Open2(IInStream *stream,
2168 { 2163 {
2169 // for multivolume archives RAR can add ZERO bytes at the end for alignment. 2164 // for multivolume archives RAR can add ZERO bytes at the end for alignment.
2170 // We must skip these bytes to prevent phySize warning. 2165 // We must skip these bytes to prevent phySize warning.
2171 RINOK(inStream->Seek(arcInfo.EndPos, STREAM_SEEK_SET, NULL)); 2166 RINOK(InStream_SeekSet(inStream, arcInfo.EndPos))
2172 bool areThereNonZeros; 2167 bool areThereNonZeros;
2173 UInt64 numZeros; 2168 UInt64 numZeros;
2174 const UInt64 maxSize = 1 << 12; 2169 const UInt64 maxSize = 1 << 12;
2175 RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)); 2170 RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize))
2176 if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize) 2171 if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize)
2177 arcInfo.EndPos += numZeros; 2172 arcInfo.EndPos += numZeros;
2178 } 2173 }
@@ -2226,7 +2221,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2226 && item.GetMethod() == 0 2221 && item.GetMethod() == 0
2227 && !item.IsSplit()) 2222 && !item.IsSplit())
2228 { 2223 {
2229 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_VARS item, item.PackSize, inStream, _comment)); 2224 RINOK(unpacker.DecodeToBuf(EXTERNAL_CODECS_VARS item, item.PackSize, inStream, _comment))
2230 needAdd = false; 2225 needAdd = false;
2231 } 2226 }
2232 } 2227 }
@@ -2273,7 +2268,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2273 { 2268 {
2274 if (_acls.IsEmpty() || acl != _acls.Back()) 2269 if (_acls.IsEmpty() || acl != _acls.Back())
2275 _acls.Add(acl); 2270 _acls.Add(acl);
2276 mainItem.ACL = _acls.Size() - 1; 2271 mainItem.ACL = (int)_acls.Size() - 1;
2277 } 2272 }
2278 } 2273 }
2279 } 2274 }
@@ -2292,7 +2287,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2292 if (item.IsNextForItem(prevItem)) 2287 if (item.IsNextForItem(prevItem))
2293 { 2288 {
2294 ref2.Last = _items.Size(); 2289 ref2.Last = _items.Size();
2295 prevItem.NextItem = ref2.Last; 2290 prevItem.NextItem = (int)ref2.Last;
2296 needAdd = false; 2291 needAdd = false;
2297 } 2292 }
2298 } 2293 }
@@ -2302,9 +2297,9 @@ HRESULT CHandler::Open2(IInStream *stream,
2302 if (needAdd) 2297 if (needAdd)
2303 { 2298 {
2304 if (item.IsSplitAfter()) 2299 if (item.IsSplitAfter())
2305 prevSplitFile = _refs.Size(); 2300 prevSplitFile = (int)_refs.Size();
2306 if (!item.IsService()) 2301 if (!item.IsService())
2307 prevMainFile = _refs.Size(); 2302 prevMainFile = (int)_refs.Size();
2308 _refs.Add(ref); 2303 _refs.Add(ref);
2309 } 2304 }
2310 } 2305 }
@@ -2325,7 +2320,7 @@ HRESULT CHandler::Open2(IInStream *stream,
2325 { 2320 {
2326 UInt64 numFiles = _items.Size(); 2321 UInt64 numFiles = _items.Size();
2327 UInt64 numBytes = curBytes + item.DataPos; 2322 UInt64 numBytes = curBytes + item.DataPos;
2328 RINOK(openCallback->SetCompleted(&numFiles, &numBytes)); 2323 RINOK(openCallback->SetCompleted(&numFiles, &numBytes))
2329 } 2324 }
2330 2325
2331 if (!isOk_packSize) 2326 if (!isOk_packSize)
@@ -2353,9 +2348,9 @@ HRESULT CHandler::Open2(IInStream *stream,
2353} 2348}
2354 2349
2355 2350
2356STDMETHODIMP CHandler::Open(IInStream *stream, 2351Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
2357 const UInt64 *maxCheckStartPosition, 2352 const UInt64 *maxCheckStartPosition,
2358 IArchiveOpenCallback *openCallback) 2353 IArchiveOpenCallback *openCallback))
2359{ 2354{
2360 COM_TRY_BEGIN 2355 COM_TRY_BEGIN
2361 Close(); 2356 Close();
@@ -2363,7 +2358,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
2363 COM_TRY_END 2358 COM_TRY_END
2364} 2359}
2365 2360
2366STDMETHODIMP CHandler::Close() 2361Z7_COM7F_IMF(CHandler::Close())
2367{ 2362{
2368 COM_TRY_BEGIN 2363 COM_TRY_BEGIN
2369 _missingVolName.Empty(); 2364 _missingVolName.Empty();
@@ -2380,10 +2375,10 @@ STDMETHODIMP CHandler::Close()
2380} 2375}
2381 2376
2382 2377
2383class CVolsInStream: 2378Z7_CLASS_IMP_NOQIB_1(
2384 public ISequentialInStream, 2379 CVolsInStream
2385 public CMyUnknownImp 2380 , ISequentialInStream
2386{ 2381)
2387 UInt64 _rem; 2382 UInt64 _rem;
2388 ISequentialInStream *_stream; 2383 ISequentialInStream *_stream;
2389 const CObjectVector<CArc> *_arcs; 2384 const CObjectVector<CArc> *_arcs;
@@ -2394,22 +2389,19 @@ public:
2394private: 2389private:
2395 CHash _hash; 2390 CHash _hash;
2396public: 2391public:
2397 MY_UNKNOWN_IMP
2398 void Init(const CObjectVector<CArc> *arcs, 2392 void Init(const CObjectVector<CArc> *arcs,
2399 const CObjectVector<CItem> *items, 2393 const CObjectVector<CItem> *items,
2400 unsigned itemIndex) 2394 unsigned itemIndex)
2401 { 2395 {
2402 _arcs = arcs; 2396 _arcs = arcs;
2403 _items = items; 2397 _items = items;
2404 _itemIndex = itemIndex; 2398 _itemIndex = (int)itemIndex;
2405 _stream = NULL; 2399 _stream = NULL;
2406 CrcIsOK = true; 2400 CrcIsOK = true;
2407 } 2401 }
2408
2409 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
2410}; 2402};
2411 2403
2412STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 2404Z7_COM7F_IMF(CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
2413{ 2405{
2414 if (processedSize) 2406 if (processedSize)
2415 *processedSize = 0; 2407 *processedSize = 0;
@@ -2423,7 +2415,7 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
2423 break; 2415 break;
2424 const CItem &item = (*_items)[_itemIndex]; 2416 const CItem &item = (*_items)[_itemIndex];
2425 IInStream *s = (*_arcs)[item.VolIndex].Stream; 2417 IInStream *s = (*_arcs)[item.VolIndex].Stream;
2426 RINOK(s->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); 2418 RINOK(InStream_SeekSet(s, item.GetDataPosition()))
2427 _stream = s; 2419 _stream = s;
2428 if (CrcIsOK && item.IsSplitAfter()) 2420 if (CrcIsOK && item.IsSplitAfter())
2429 _hash.Init(item); 2421 _hash.Init(item);
@@ -2472,10 +2464,10 @@ static int FindLinkBuf(CObjectVector<CLinkFile> &linkFiles, unsigned index)
2472 { 2464 {
2473 if (left == right) 2465 if (left == right)
2474 return -1; 2466 return -1;
2475 unsigned mid = (left + right) / 2; 2467 const unsigned mid = (left + right) / 2;
2476 unsigned linkIndex = linkFiles[mid].Index; 2468 const unsigned linkIndex = linkFiles[mid].Index;
2477 if (index == linkIndex) 2469 if (index == linkIndex)
2478 return mid; 2470 return (int)mid;
2479 if (index < linkIndex) 2471 if (index < linkIndex)
2480 right = mid; 2472 right = mid;
2481 else 2473 else
@@ -2512,14 +2504,14 @@ static HRESULT CopyData_with_Progress(const Byte *data, size_t size,
2512 cur = kStepSize; 2504 cur = kStepSize;
2513 cur32 = (UInt32)cur; 2505 cur32 = (UInt32)cur;
2514 } 2506 }
2515 RINOK(outStream->Write(data + pos, cur32, &cur32)); 2507 RINOK(outStream->Write(data + pos, cur32, &cur32))
2516 if (cur32 == 0) 2508 if (cur32 == 0)
2517 return E_FAIL; 2509 return E_FAIL;
2518 pos += cur32; 2510 pos += cur32;
2519 if (progress) 2511 if (progress)
2520 { 2512 {
2521 UInt64 pos64 = pos; 2513 UInt64 pos64 = pos;
2522 RINOK(progress->SetRatioInfo(&pos64, &pos64)); 2514 RINOK(progress->SetRatioInfo(&pos64, &pos64))
2523 } 2515 }
2524 } 2516 }
2525 2517
@@ -2527,12 +2519,11 @@ static HRESULT CopyData_with_Progress(const Byte *data, size_t size,
2527} 2519}
2528 2520
2529 2521
2530STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2522Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2531 Int32 testMode, IArchiveExtractCallback *extractCallback) 2523 Int32 testMode, IArchiveExtractCallback *extractCallback))
2532{ 2524{
2533 COM_TRY_BEGIN 2525 COM_TRY_BEGIN
2534 2526 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2535 bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2536 if (allFilesMode) 2527 if (allFilesMode)
2537 numItems = _refs.Size(); 2528 numItems = _refs.Size();
2538 if (numItems == 0) 2529 if (numItems == 0)
@@ -2706,7 +2697,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2706 const CItem &linkItem = _items[_refs[(unsigned)linkIndex].Item]; 2697 const CItem &linkItem = _items[_refs[(unsigned)linkIndex].Item];
2707 if (!linkItem.IsSolid() || linkItem.Size > k_CopyLinkFile_MaxSize) 2698 if (!linkItem.IsSolid() || linkItem.Size > k_CopyLinkFile_MaxSize)
2708 continue; 2699 continue;
2709 int bufIndex = FindLinkBuf(linkFiles, linkIndex); 2700 const int bufIndex = FindLinkBuf(linkFiles, (unsigned)linkIndex);
2710 if (bufIndex < 0) 2701 if (bufIndex < 0)
2711 return E_FAIL; 2702 return E_FAIL;
2712 linkFiles[bufIndex].NumLinks++; 2703 linkFiles[bufIndex].NumLinks++;
@@ -2715,7 +2706,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2715 2706
2716 if (total != 0 || !isThereUndefinedSize) 2707 if (total != 0 || !isThereUndefinedSize)
2717 { 2708 {
2718 RINOK(extractCallback->SetTotal(total)); 2709 RINOK(extractCallback->SetTotal(total))
2719 } 2710 }
2720 } 2711 }
2721 2712
@@ -2745,7 +2736,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2745 totalPacked += curPackSize; 2736 totalPacked += curPackSize;
2746 lps->InSize = totalPacked; 2737 lps->InSize = totalPacked;
2747 lps->OutSize = totalUnpacked; 2738 lps->OutSize = totalUnpacked;
2748 RINOK(lps->SetCur()); 2739 RINOK(lps->SetCur())
2749 2740
2750 CMyComPtr<ISequentialOutStream> realOutStream; 2741 CMyComPtr<ISequentialOutStream> realOutStream;
2751 2742
@@ -2781,7 +2772,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2781 2772
2782 curPackSize = GetPackSize(index); 2773 curPackSize = GetPackSize(index);
2783 2774
2784 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 2775 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
2785 2776
2786 bool isSolid = false; 2777 bool isSolid = false;
2787 if (!item->IsService()) 2778 if (!item->IsService())
@@ -2793,8 +2784,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2793 2784
2794 if (item->IsDir()) 2785 if (item->IsDir())
2795 { 2786 {
2796 RINOK(extractCallback->PrepareOperation(askMode)); 2787 RINOK(extractCallback->PrepareOperation(askMode))
2797 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2788 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2798 continue; 2789 continue;
2799 } 2790 }
2800 2791
@@ -2815,12 +2806,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2815 curUnpackSize = lastItem2.Size; 2806 curUnpackSize = lastItem2.Size;
2816 else 2807 else
2817 curUnpackSize = 0; 2808 curUnpackSize = 0;
2818 curPackSize = GetPackSize(index2); 2809 curPackSize = GetPackSize((unsigned)index2);
2819 } 2810 }
2820 else 2811 else
2821 { 2812 {
2822 if ((unsigned)index2 < index) 2813 if ((unsigned)index2 < index)
2823 bufIndex = FindLinkBuf(linkFiles, index2); 2814 bufIndex = FindLinkBuf(linkFiles, (unsigned)index2);
2824 } 2815 }
2825 } 2816 }
2826 2817
@@ -2839,8 +2830,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2839 opRes = DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK); 2830 opRes = DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK);
2840 } 2831 }
2841 2832
2842 RINOK(extractCallback->PrepareOperation(askMode)); 2833 RINOK(extractCallback->PrepareOperation(askMode))
2843 RINOK(extractCallback->SetOperationResult(opRes)); 2834 RINOK(extractCallback->SetOperationResult(opRes))
2844 continue; 2835 continue;
2845 } 2836 }
2846 } 2837 }
@@ -2874,7 +2865,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2874 2865
2875 if (needCallback) 2866 if (needCallback)
2876 { 2867 {
2877 RINOK(extractCallback->PrepareOperation(askMode)); 2868 RINOK(extractCallback->PrepareOperation(askMode))
2878 } 2869 }
2879 2870
2880 if (bufIndex >= 0) 2871 if (bufIndex >= 0)
@@ -2889,7 +2880,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2889 if (needCallback) 2880 if (needCallback)
2890 if (realOutStream) 2881 if (realOutStream)
2891 { 2882 {
2892 RINOK(CopyData_with_Progress(linkFile.Data, linkFile.Data.Size(), realOutStream, progress)); 2883 RINOK(CopyData_with_Progress(linkFile.Data, linkFile.Data.Size(), realOutStream, progress))
2893 } 2884 }
2894 2885
2895 if (--linkFile.NumLinks == 0) 2886 if (--linkFile.NumLinks == 0)
@@ -2898,7 +2889,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2898 2889
2899 if (needCallback) 2890 if (needCallback)
2900 { 2891 {
2901 RINOK(extractCallback->SetOperationResult(DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK))); 2892 RINOK(extractCallback->SetOperationResult(DecoderRes_to_OpRes(linkFile.Res, linkFile.crcOK)))
2902 } 2893 }
2903 continue; 2894 continue;
2904 } 2895 }
@@ -2912,7 +2903,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2912 NExtract::NOperationResult::kUnsupportedMethod: 2903 NExtract::NOperationResult::kUnsupportedMethod:
2913 NExtract::NOperationResult::kOK; 2904 NExtract::NOperationResult::kOK;
2914 realOutStream.Release(); 2905 realOutStream.Release();
2915 RINOK(extractCallback->SetOperationResult(opRes)); 2906 RINOK(extractCallback->SetOperationResult(opRes))
2916 continue; 2907 continue;
2917 } 2908 }
2918 2909
@@ -2930,7 +2921,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2930 if (wrongPassword) 2921 if (wrongPassword)
2931 { 2922 {
2932 realOutStream.Release(); 2923 realOutStream.Release();
2933 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword)); 2924 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kWrongPassword))
2934 continue; 2925 continue;
2935 } 2926 }
2936 2927
@@ -2955,7 +2946,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2955 return result; 2946 return result;
2956 } 2947 }
2957 2948
2958 RINOK(extractCallback->SetOperationResult(opRes)); 2949 RINOK(extractCallback->SetOperationResult(opRes))
2959 } 2950 }
2960 2951
2961 { 2952 {
@@ -2973,7 +2964,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2973IMPL_ISetCompressCodecsInfo 2964IMPL_ISetCompressCodecsInfo
2974 2965
2975REGISTER_ARC_I( 2966REGISTER_ARC_I(
2976 "Rar5", "rar r00", 0, 0xCC, 2967 "Rar5", "rar r00", NULL, 0xCC,
2977 kMarker, 2968 kMarker,
2978 0, 2969 0,
2979 NArcInfoFlags::kFindSignature, 2970 NArcInfoFlags::kFindSignature,
@@ -2982,31 +2973,27 @@ REGISTER_ARC_I(
2982}} 2973}}
2983 2974
2984 2975
2985class CBlake2spHasher: 2976Z7_CLASS_IMP_COM_1(
2986 public IHasher, 2977 CBlake2spHasher
2987 public CMyUnknownImp 2978 , IHasher
2988{ 2979)
2989 CBlake2sp _blake; 2980 CBlake2sp _blake;
2990 Byte mtDummy[1 << 7];
2991
2992public: 2981public:
2982 Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field
2993 CBlake2spHasher() { Init(); } 2983 CBlake2spHasher() { Init(); }
2994
2995 MY_UNKNOWN_IMP
2996 INTERFACE_IHasher(;)
2997}; 2984};
2998 2985
2999STDMETHODIMP_(void) CBlake2spHasher::Init() throw() 2986Z7_COM7F_IMF2(void, CBlake2spHasher::Init())
3000{ 2987{
3001 Blake2sp_Init(&_blake); 2988 Blake2sp_Init(&_blake);
3002} 2989}
3003 2990
3004STDMETHODIMP_(void) CBlake2spHasher::Update(const void *data, UInt32 size) throw() 2991Z7_COM7F_IMF2(void, CBlake2spHasher::Update(const void *data, UInt32 size))
3005{ 2992{
3006 Blake2sp_Update(&_blake, (const Byte *)data, size); 2993 Blake2sp_Update(&_blake, (const Byte *)data, size);
3007} 2994}
3008 2995
3009STDMETHODIMP_(void) CBlake2spHasher::Final(Byte *digest) throw() 2996Z7_COM7F_IMF2(void, CBlake2spHasher::Final(Byte *digest))
3010{ 2997{
3011 Blake2sp_Final(&_blake, digest); 2998 Blake2sp_Final(&_blake, digest);
3012} 2999}
diff --git a/CPP/7zip/Archive/Rar/Rar5Handler.h b/CPP/7zip/Archive/Rar/Rar5Handler.h
index 3b3b940..72e1efc 100644
--- a/CPP/7zip/Archive/Rar/Rar5Handler.h
+++ b/CPP/7zip/Archive/Rar/Rar5Handler.h
@@ -1,7 +1,7 @@
1// Rar5Handler.h 1// Rar5Handler.h
2 2
3#ifndef __RAR5_HANDLER_H 3#ifndef ZIP7_INC_RAR5_HANDLER_H
4#define __RAR5_HANDLER_H 4#define ZIP7_INC_RAR5_HANDLER_H
5 5
6#include "../../../../C/Blake2.h" 6#include "../../../../C/Blake2.h"
7 7
@@ -374,12 +374,22 @@ struct CArc
374}; 374};
375 375
376 376
377class CHandler: 377class CHandler Z7_final:
378 public IInArchive, 378 public IInArchive,
379 public IArchiveGetRawProps, 379 public IArchiveGetRawProps,
380 PUBLIC_ISetCompressCodecsInfo 380 Z7_PUBLIC_ISetCompressCodecsInfo_IFEC
381 public CMyUnknownImp 381 public CMyUnknownImp
382{ 382{
383 Z7_COM_QI_BEGIN2(IInArchive)
384 Z7_COM_QI_ENTRY(IArchiveGetRawProps)
385 Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC
386 Z7_COM_QI_END
387 Z7_COM_ADDREF_RELEASE
388
389 Z7_IFACE_COM7_IMP(IInArchive)
390 Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
391 DECL_ISetCompressCodecsInfo
392
383public: 393public:
384 CRecordVector<CRefItem> _refs; 394 CRecordVector<CRefItem> _refs;
385 CObjectVector<CItem> _items; 395 CObjectVector<CItem> _items;
@@ -402,18 +412,6 @@ private:
402 HRESULT Open2(IInStream *stream, 412 HRESULT Open2(IInStream *stream,
403 const UInt64 *maxCheckStartPosition, 413 const UInt64 *maxCheckStartPosition,
404 IArchiveOpenCallback *openCallback); 414 IArchiveOpenCallback *openCallback);
405
406public:
407 MY_QUERYINTERFACE_BEGIN2(IInArchive)
408 MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps)
409 QUERY_ENTRY_ISetCompressCodecsInfo
410 MY_QUERYINTERFACE_END
411 MY_ADDREF_RELEASE
412
413 INTERFACE_IInArchive(;)
414 INTERFACE_IArchiveGetRawProps(;)
415
416 DECL_ISetCompressCodecsInfo
417}; 415};
418 416
419}} 417}}
diff --git a/CPP/7zip/Archive/Rar/RarHandler.cpp b/CPP/7zip/Archive/Rar/RarHandler.cpp
index ecadf85..9157acc 100644
--- a/CPP/7zip/Archive/Rar/RarHandler.cpp
+++ b/CPP/7zip/Archive/Rar/RarHandler.cpp
@@ -44,9 +44,8 @@ using namespace NWindows;
44namespace NArchive { 44namespace NArchive {
45namespace NRar { 45namespace NRar {
46 46
47#define SIGNATURE { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 } 47static const Byte kMarker[NHeader::kMarkerSize] =
48 48 { 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 };
49static const Byte kMarker[NHeader::kMarkerSize] = SIGNATURE;
50 49
51const unsigned kPasswordLen_MAX = 127; 50const unsigned kPasswordLen_MAX = 127;
52 51
@@ -184,35 +183,33 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
184{ 183{
185 HeaderErrorWarning = false; 184 HeaderErrorWarning = false;
186 m_CryptoMode = false; 185 m_CryptoMode = false;
187 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); 186 RINOK(InStream_GetPos_GetSize(stream, m_StreamStartPosition, ArcInfo.FileSize))
188 RINOK(stream->Seek(0, STREAM_SEEK_END, &ArcInfo.FileSize));
189 RINOK(stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL));
190 m_Position = m_StreamStartPosition; 187 m_Position = m_StreamStartPosition;
191 188
192 UInt64 arcStartPos = m_StreamStartPosition; 189 UInt64 arcStartPos = m_StreamStartPosition;
193 { 190 {
194 Byte marker[NHeader::kMarkerSize]; 191 Byte marker[NHeader::kMarkerSize];
195 RINOK(ReadStream_FALSE(stream, marker, NHeader::kMarkerSize)); 192 RINOK(ReadStream_FALSE(stream, marker, NHeader::kMarkerSize))
196 if (memcmp(marker, kMarker, NHeader::kMarkerSize) == 0) 193 if (memcmp(marker, kMarker, NHeader::kMarkerSize) == 0)
197 m_Position += NHeader::kMarkerSize; 194 m_Position += NHeader::kMarkerSize;
198 else 195 else
199 { 196 {
200 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0) 197 if (searchHeaderSizeLimit && *searchHeaderSizeLimit == 0)
201 return S_FALSE; 198 return S_FALSE;
202 RINOK(stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); 199 RINOK(InStream_SeekSet(stream, m_StreamStartPosition))
203 RINOK(FindSignatureInStream(stream, kMarker, NHeader::kMarkerSize, 200 RINOK(FindSignatureInStream(stream, kMarker, NHeader::kMarkerSize,
204 searchHeaderSizeLimit, arcStartPos)); 201 searchHeaderSizeLimit, arcStartPos))
205 m_Position = arcStartPos + NHeader::kMarkerSize; 202 m_Position = arcStartPos + NHeader::kMarkerSize;
206 RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL)); 203 RINOK(InStream_SeekSet(stream, m_Position))
207 } 204 }
208 } 205 }
209 Byte buf[NHeader::NArchive::kArchiveHeaderSize + 1]; 206 Byte buf[NHeader::NArchive::kArchiveHeaderSize + 1];
210 207
211 RINOK(ReadStream_FALSE(stream, buf, NHeader::NArchive::kArchiveHeaderSize)); 208 RINOK(ReadStream_FALSE(stream, buf, NHeader::NArchive::kArchiveHeaderSize))
212 AddToSeekValue(NHeader::NArchive::kArchiveHeaderSize); 209 AddToSeekValue(NHeader::NArchive::kArchiveHeaderSize);
213 210
214 211
215 UInt32 blockSize = Get16(buf + 5); 212 const UInt32 blockSize = Get16(buf + 5);
216 213
217 ArcInfo.EncryptVersion = 0; 214 ArcInfo.EncryptVersion = 0;
218 ArcInfo.Flags = Get16(buf + 3); 215 ArcInfo.Flags = Get16(buf + 3);
@@ -238,7 +235,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
238 235
239 size_t commentSize = blockSize - headerSize; 236 size_t commentSize = blockSize - headerSize;
240 _comment.Alloc(commentSize); 237 _comment.Alloc(commentSize);
241 RINOK(ReadStream_FALSE(stream, _comment, commentSize)); 238 RINOK(ReadStream_FALSE(stream, _comment, commentSize))
242 AddToSeekValue(commentSize); 239 AddToSeekValue(commentSize);
243 m_Stream = stream; 240 m_Stream = stream;
244 ArcInfo.StartPos = arcStartPos; 241 ArcInfo.StartPos = arcStartPos;
@@ -368,7 +365,7 @@ static int ReadTime(const Byte *p, unsigned size, Byte mask, CRarTime &rarTime)
368 return -1; 365 return -1;
369 for (unsigned i = 0; i < numDigits; i++) 366 for (unsigned i = 0; i < numDigits; i++)
370 rarTime.SubTime[3 - numDigits + i] = p[i]; 367 rarTime.SubTime[3 - numDigits + i] = p[i];
371 return numDigits; 368 return (int)numDigits;
372} 369}
373 370
374#define READ_TIME(_mask_, _ttt_) \ 371#define READ_TIME(_mask_, _ttt_) \
@@ -480,10 +477,10 @@ bool CInArchive::ReadHeaderReal(const Byte *p, unsigned size, CItem &item)
480 Byte cMask = (Byte)(b & 0xF); 477 Byte cMask = (Byte)(b & 0xF);
481 if ((mMask & 8) != 0) 478 if ((mMask & 8) != 0)
482 { 479 {
483 READ_TIME(mMask, item.MTime); 480 READ_TIME(mMask, item.MTime)
484 } 481 }
485 READ_TIME_2(cMask, item.CTimeDefined, item.CTime); 482 READ_TIME_2(cMask, item.CTimeDefined, item.CTime)
486 READ_TIME_2(aMask, item.ATimeDefined, item.ATime); 483 READ_TIME_2(aMask, item.ATimeDefined, item.ATime)
487 } 484 }
488 485
489 unsigned fileHeaderWithNameSize = 7 + (unsigned)(p - pStart); 486 unsigned fileHeaderWithNameSize = 7 + (unsigned)(p - pStart);
@@ -508,13 +505,13 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass
508 error = k_ErrorType_OK; 505 error = k_ErrorType_OK;
509 for (;;) 506 for (;;)
510 { 507 {
511 m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); 508 RINOK(InStream_SeekSet(m_Stream, m_Position))
512 ArcInfo.EndPos = m_Position; 509 ArcInfo.EndPos = m_Position;
513 if (!m_CryptoMode && (ArcInfo.Flags & 510 if (!m_CryptoMode && (ArcInfo.Flags &
514 NHeader::NArchive::kBlockHeadersAreEncrypted) != 0) 511 NHeader::NArchive::kBlockHeadersAreEncrypted) != 0)
515 { 512 {
516 m_CryptoMode = false; 513 m_CryptoMode = false;
517 if (getTextPassword == 0) 514 if (!getTextPassword)
518 { 515 {
519 error = k_ErrorType_DecryptionError; 516 error = k_ErrorType_DecryptionError;
520 return S_OK; // return S_FALSE; 517 return S_OK; // return S_FALSE;
@@ -565,9 +562,9 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass
565 if (!m_DecryptedDataAligned.IsAllocated()) 562 if (!m_DecryptedDataAligned.IsAllocated())
566 return E_OUTOFMEMORY; 563 return E_OUTOFMEMORY;
567 } 564 }
568 RINOK(m_RarAES->Init()); 565 RINOK(m_RarAES->Init())
569 size_t decryptedDataSizeT = kDecryptedBufferSize; 566 size_t decryptedDataSizeT = kDecryptedBufferSize;
570 RINOK(ReadStream(m_Stream, m_DecryptedDataAligned, &decryptedDataSizeT)); 567 RINOK(ReadStream(m_Stream, m_DecryptedDataAligned, &decryptedDataSizeT))
571 m_DecryptedDataSize = (UInt32)decryptedDataSizeT; 568 m_DecryptedDataSize = (UInt32)decryptedDataSizeT;
572 m_DecryptedDataSize = m_RarAES->Filter(m_DecryptedDataAligned, m_DecryptedDataSize); 569 m_DecryptedDataSize = m_RarAES->Filter(m_DecryptedDataAligned, m_DecryptedDataSize);
573 570
@@ -577,7 +574,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass
577 574
578 m_FileHeaderData.AllocAtLeast(7); 575 m_FileHeaderData.AllocAtLeast(7);
579 size_t processed = 7; 576 size_t processed = 7;
580 RINOK(ReadBytesSpec((Byte *)m_FileHeaderData, &processed)); 577 RINOK(ReadBytesSpec((Byte *)m_FileHeaderData, &processed))
581 if (processed != 7) 578 if (processed != 7)
582 { 579 {
583 if (processed != 0) 580 if (processed != 0)
@@ -715,7 +712,7 @@ HRESULT CInArchive::GetNextItem(CItem &item, ICryptoGetTextPassword *getTextPass
715 FinishCryptoBlock(); 712 FinishCryptoBlock();
716 m_CryptoMode = false; 713 m_CryptoMode = false;
717 // Move Position to compressed Data; 714 // Move Position to compressed Data;
718 m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); 715 RINOK(InStream_SeekSet(m_Stream, m_Position))
719 AddToSeekValue(item.PackSize); // m_Position points to next header; 716 AddToSeekValue(item.PackSize); // m_Position points to next header;
720 // if (okItem) 717 // if (okItem)
721 return S_OK; 718 return S_OK;
@@ -828,7 +825,7 @@ bool CHandler::IsSolid(unsigned refIndex) const
828 return item.IsSolid(); 825 return item.IsSolid();
829} 826}
830 827
831STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 828Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
832{ 829{
833 COM_TRY_BEGIN 830 COM_TRY_BEGIN
834 NCOM::CPropVariant prop; 831 NCOM::CPropVariant prop;
@@ -838,7 +835,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
838 case kpidSolid: prop = _arcInfo.IsSolid(); break; 835 case kpidSolid: prop = _arcInfo.IsSolid(); break;
839 case kpidCharacts: 836 case kpidCharacts:
840 { 837 {
841 AString s (FlagsToString(k_Flags, ARRAY_SIZE(k_Flags), _arcInfo.Flags)); 838 AString s (FlagsToString(k_Flags, Z7_ARRAY_SIZE(k_Flags), _arcInfo.Flags));
842 // FLAGS_TO_PROP(k_Flags, _arcInfo.Flags, prop); 839 // FLAGS_TO_PROP(k_Flags, _arcInfo.Flags, prop);
843 if (_arcInfo.Is_DataCRC_Defined()) 840 if (_arcInfo.Is_DataCRC_Defined())
844 { 841 {
@@ -935,7 +932,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
935 COM_TRY_END 932 COM_TRY_END
936} 933}
937 934
938STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 935Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
939{ 936{
940 *numItems = _refItems.Size(); 937 *numItems = _refItems.Size();
941 return S_OK; 938 return S_OK;
@@ -969,7 +966,7 @@ static void RarTimeToProp(const CRarTime &rarTime, NCOM::CPropVariant &prop)
969 */ 966 */
970} 967}
971 968
972STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 969Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
973{ 970{
974 COM_TRY_BEGIN 971 COM_TRY_BEGIN
975 NCOM::CPropVariant prop; 972 NCOM::CPropVariant prop;
@@ -1087,7 +1084,7 @@ HRESULT CHandler::Open2(IInStream *stream,
1087 UString baseName; 1084 UString baseName;
1088 { 1085 {
1089 NCOM::CPropVariant prop; 1086 NCOM::CPropVariant prop;
1090 RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); 1087 RINOK(openVolumeCallback->GetProperty(kpidName, &prop))
1091 if (prop.vt != VT_BSTR) 1088 if (prop.vt != VT_BSTR)
1092 break; 1089 break;
1093 baseName = prop.bstrVal; 1090 baseName = prop.bstrVal;
@@ -1119,16 +1116,15 @@ HRESULT CHandler::Open2(IInStream *stream,
1119 else 1116 else
1120 inStream = stream; 1117 inStream = stream;
1121 1118
1122 UInt64 endPos = 0; 1119 UInt64 endPos;
1123 RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); 1120 RINOK(InStream_AtBegin_GetSize(inStream, endPos))
1124 RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL));
1125 if (openCallback) 1121 if (openCallback)
1126 { 1122 {
1127 totalBytes += endPos; 1123 totalBytes += endPos;
1128 RINOK(openCallback->SetTotal(NULL, &totalBytes)); 1124 RINOK(openCallback->SetTotal(NULL, &totalBytes))
1129 } 1125 }
1130 1126
1131 RINOK(archive.Open(inStream, maxCheckStartPosition)); 1127 RINOK(archive.Open(inStream, maxCheckStartPosition))
1132 _isArc = true; 1128 _isArc = true;
1133 CItem item; 1129 CItem item;
1134 1130
@@ -1157,7 +1153,7 @@ HRESULT CHandler::Open2(IInStream *stream,
1157 1153
1158 // AddErrorMessage(errorMessageLoc); 1154 // AddErrorMessage(errorMessageLoc);
1159 } 1155 }
1160 RINOK(result); 1156 RINOK(result)
1161 1157
1162 if (!filled) 1158 if (!filled)
1163 { 1159 {
@@ -1169,11 +1165,11 @@ HRESULT CHandler::Open2(IInStream *stream,
1169 /* if there is recovery record for multivolume archive, 1165 /* if there is recovery record for multivolume archive,
1170 RAR adds 18 bytes (ZERO bytes) at the end for alignment. 1166 RAR adds 18 bytes (ZERO bytes) at the end for alignment.
1171 We must skip these bytes to prevent phySize warning. */ 1167 We must skip these bytes to prevent phySize warning. */
1172 RINOK(inStream->Seek(archive.ArcInfo.EndPos, STREAM_SEEK_SET, NULL)); 1168 RINOK(InStream_SeekSet(inStream, archive.ArcInfo.EndPos))
1173 bool areThereNonZeros; 1169 bool areThereNonZeros;
1174 UInt64 numZeros; 1170 UInt64 numZeros;
1175 const UInt64 maxSize = 1 << 12; 1171 const UInt64 maxSize = 1 << 12;
1176 RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize)); 1172 RINOK(ReadZeroTail(inStream, areThereNonZeros, numZeros, maxSize))
1177 if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize) 1173 if (!areThereNonZeros && numZeros != 0 && numZeros <= maxSize)
1178 archive.ArcInfo.EndPos += numZeros; 1174 archive.ArcInfo.EndPos += numZeros;
1179 } 1175 }
@@ -1210,7 +1206,7 @@ HRESULT CHandler::Open2(IInStream *stream,
1210 { 1206 {
1211 UInt64 numFiles = _items.Size(); 1207 UInt64 numFiles = _items.Size();
1212 UInt64 numBytes = curBytes + item.Position; 1208 UInt64 numBytes = curBytes + item.Position;
1213 RINOK(openCallback->SetCompleted(&numFiles, &numBytes)); 1209 RINOK(openCallback->SetCompleted(&numFiles, &numBytes))
1214 } 1210 }
1215 } 1211 }
1216 1212
@@ -1260,9 +1256,9 @@ HRESULT CHandler::Open2(IInStream *stream,
1260 return S_OK; 1256 return S_OK;
1261} 1257}
1262 1258
1263STDMETHODIMP CHandler::Open(IInStream *stream, 1259Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
1264 const UInt64 *maxCheckStartPosition, 1260 const UInt64 *maxCheckStartPosition,
1265 IArchiveOpenCallback *openCallback) 1261 IArchiveOpenCallback *openCallback))
1266{ 1262{
1267 COM_TRY_BEGIN 1263 COM_TRY_BEGIN
1268 Close(); 1264 Close();
@@ -1281,7 +1277,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
1281 COM_TRY_END 1277 COM_TRY_END
1282} 1278}
1283 1279
1284STDMETHODIMP CHandler::Close() 1280Z7_COM7F_IMF(CHandler::Close())
1285{ 1281{
1286 COM_TRY_BEGIN 1282 COM_TRY_BEGIN
1287 // _errorMessage.Empty(); 1283 // _errorMessage.Empty();
@@ -1303,10 +1299,10 @@ struct CMethodItem
1303}; 1299};
1304 1300
1305 1301
1306class CVolsInStream: 1302Z7_CLASS_IMP_NOQIB_1(
1307 public ISequentialInStream, 1303 CVolsInStream
1308 public CMyUnknownImp 1304 , ISequentialInStream
1309{ 1305)
1310 UInt64 _rem; 1306 UInt64 _rem;
1311 ISequentialInStream *_stream; 1307 ISequentialInStream *_stream;
1312 const CObjectVector<CArc> *_arcs; 1308 const CObjectVector<CArc> *_arcs;
@@ -1317,10 +1313,6 @@ class CVolsInStream:
1317 bool _calcCrc; 1313 bool _calcCrc;
1318 1314
1319public: 1315public:
1320 MY_UNKNOWN_IMP
1321
1322 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
1323
1324 void Init(const CObjectVector<CArc> *arcs, 1316 void Init(const CObjectVector<CArc> *arcs,
1325 const CObjectVector<CItem> *items, 1317 const CObjectVector<CItem> *items,
1326 const CRefItem &refItem) 1318 const CRefItem &refItem)
@@ -1337,7 +1329,7 @@ public:
1337}; 1329};
1338 1330
1339 1331
1340STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 1332Z7_COM7F_IMF(CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
1341{ 1333{
1342 if (processedSize) 1334 if (processedSize)
1343 *processedSize = 0; 1335 *processedSize = 0;
@@ -1357,7 +1349,7 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1357 // return S_FALSE; 1349 // return S_FALSE;
1358 } 1350 }
1359 IInStream *s = (*_arcs)[volIndex].Stream; 1351 IInStream *s = (*_arcs)[volIndex].Stream;
1360 RINOK(s->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); 1352 RINOK(InStream_SeekSet(s, item.GetDataPosition()))
1361 _stream = s; 1353 _stream = s;
1362 _calcCrc = (CrcIsOK && item.IsSplitAfter()); 1354 _calcCrc = (CrcIsOK && item.IsSplitAfter());
1363 _crc = CRC_INIT_VAL; 1355 _crc = CRC_INIT_VAL;
@@ -1397,16 +1389,16 @@ STDMETHODIMP CVolsInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
1397 return S_OK; 1389 return S_OK;
1398} 1390}
1399 1391
1400STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1392Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1401 Int32 testMode, IArchiveExtractCallback *extractCallback) 1393 Int32 testMode, IArchiveExtractCallback *extractCallback))
1402{ 1394{
1403 COM_TRY_BEGIN 1395 COM_TRY_BEGIN
1404 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 1396 CMyComPtr<ICryptoGetTextPassword> getTextPassword;
1405 UInt64 censoredTotalUnPacked = 0, 1397 UInt64 // censoredTotalUnPacked = 0,
1406 // censoredTotalPacked = 0, 1398 // censoredTotalPacked = 0,
1407 importantTotalUnPacked = 0; 1399 importantTotalUnPacked = 0;
1408 // importantTotalPacked = 0; 1400 // importantTotalPacked = 0;
1409 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1401 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1410 if (allFilesMode) 1402 if (allFilesMode)
1411 numItems = _refItems.Size(); 1403 numItems = _refItems.Size();
1412 if (numItems == 0) 1404 if (numItems == 0)
@@ -1426,7 +1418,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1426 const CItem &item = _items[refItem.ItemIndex + refItem.NumItems - 1]; 1418 const CItem &item = _items[refItem.ItemIndex + refItem.NumItems - 1];
1427 1419
1428 if (item.Is_Size_Defined()) 1420 if (item.Is_Size_Defined())
1429 censoredTotalUnPacked += item.Size; 1421 {
1422 // censoredTotalUnPacked += item.Size;
1423 }
1430 else 1424 else
1431 isThereUndefinedSize = true; 1425 isThereUndefinedSize = true;
1432 1426
@@ -1458,7 +1452,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1458 1452
1459 if (importantTotalUnPacked != 0 || !isThereUndefinedSize) 1453 if (importantTotalUnPacked != 0 || !isThereUndefinedSize)
1460 { 1454 {
1461 RINOK(extractCallback->SetTotal(importantTotalUnPacked)); 1455 RINOK(extractCallback->SetTotal(importantTotalUnPacked))
1462 } 1456 }
1463 1457
1464 UInt64 currentImportantTotalUnPacked = 0; 1458 UInt64 currentImportantTotalUnPacked = 0;
@@ -1494,7 +1488,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1494 { 1488 {
1495 lps->InSize = currentImportantTotalPacked; 1489 lps->InSize = currentImportantTotalPacked;
1496 lps->OutSize = currentImportantTotalUnPacked; 1490 lps->OutSize = currentImportantTotalUnPacked;
1497 RINOK(lps->SetCur()); 1491 RINOK(lps->SetCur())
1498 1492
1499 if (i >= importantIndexes.Size()) 1493 if (i >= importantIndexes.Size())
1500 break; 1494 break;
@@ -1528,14 +1522,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1528 if (item.IgnoreItem()) 1522 if (item.IgnoreItem())
1529 continue; 1523 continue;
1530 1524
1531 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1525 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1532 1526
1533 if (!IsSolid(index)) 1527 if (!IsSolid(index))
1534 solidStart = true; 1528 solidStart = true;
1535 if (item.IsDir()) 1529 if (item.IsDir())
1536 { 1530 {
1537 RINOK(extractCallback->PrepareOperation(askMode)); 1531 RINOK(extractCallback->PrepareOperation(askMode))
1538 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1532 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
1539 continue; 1533 continue;
1540 } 1534 }
1541 1535
@@ -1554,7 +1548,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1554 if (!realOutStream && !testMode) 1548 if (!realOutStream && !testMode)
1555 askMode = NExtract::NAskMode::kSkip; 1549 askMode = NExtract::NAskMode::kSkip;
1556 1550
1557 RINOK(extractCallback->PrepareOperation(askMode)); 1551 RINOK(extractCallback->PrepareOperation(askMode))
1558 1552
1559 COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; 1553 COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC;
1560 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec); 1554 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
@@ -1594,7 +1588,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1594 RINOK(rar3CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, 1588 RINOK(rar3CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2,
1595 &cryptoProperties)); 1589 &cryptoProperties));
1596 */ 1590 */
1597 RINOK(rar3CryptoDecoderSpec->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0)); 1591 RINOK(rar3CryptoDecoderSpec->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0))
1598 filterStreamSpec->Filter = rar3CryptoDecoder; 1592 filterStreamSpec->Filter = rar3CryptoDecoder;
1599 } 1593 }
1600 else if (item.UnPackVersion >= 20) 1594 else if (item.UnPackVersion >= 20)
@@ -1609,7 +1603,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1609 else 1603 else
1610 { 1604 {
1611 outStream.Release(); 1605 outStream.Release();
1612 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 1606 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
1613 continue; 1607 continue;
1614 } 1608 }
1615 1609
@@ -1621,14 +1615,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1621 if (!getTextPassword) 1615 if (!getTextPassword)
1622 { 1616 {
1623 outStream.Release(); 1617 outStream.Release();
1624 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 1618 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
1625 continue; 1619 continue;
1626 } 1620 }
1627 1621
1628 // if (getTextPassword) 1622 // if (getTextPassword)
1629 { 1623 {
1630 CMyComBSTR_Wipe password; 1624 CMyComBSTR_Wipe password;
1631 RINOK(getTextPassword->CryptoGetTextPassword(&password)); 1625 RINOK(getTextPassword->CryptoGetTextPassword(&password))
1632 1626
1633 if (item.UnPackVersion >= 29) 1627 if (item.UnPackVersion >= 29)
1634 { 1628 {
@@ -1710,13 +1704,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1710 methodID += 2; 1704 methodID += 2;
1711 else 1705 else
1712 methodID += 3; 1706 methodID += 3;
1713 RINOK(CreateCoder_Id(EXTERNAL_CODECS_VARS methodID, false, mi.Coder)); 1707 RINOK(CreateCoder_Id(EXTERNAL_CODECS_VARS methodID, false, mi.Coder))
1714 } 1708 }
1715 1709
1716 if (mi.Coder == 0) 1710 if (!mi.Coder)
1717 { 1711 {
1718 outStream.Release(); 1712 outStream.Release();
1719 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 1713 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
1720 continue; 1714 continue;
1721 } 1715 }
1722 1716
@@ -1726,7 +1720,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1726 1720
1727 CMyComPtr<ICompressSetDecoderProperties2> compressSetDecoderProperties; 1721 CMyComPtr<ICompressSetDecoderProperties2> compressSetDecoderProperties;
1728 RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2, 1722 RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2,
1729 &compressSetDecoderProperties)); 1723 &compressSetDecoderProperties))
1730 1724
1731 Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0); 1725 Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0);
1732 if (solidStart) 1726 if (solidStart)
@@ -1736,14 +1730,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1736 } 1730 }
1737 1731
1738 1732
1739 RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1)); 1733 RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1))
1740 1734
1741 commonCoder = decoder; 1735 commonCoder = decoder;
1742 break; 1736 break;
1743 } 1737 }
1744 default: 1738 default:
1745 outStream.Release(); 1739 outStream.Release();
1746 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod)); 1740 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnsupportedMethod))
1747 continue; 1741 continue;
1748 } 1742 }
1749 1743
@@ -1769,7 +1763,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1769 else 1763 else
1770 return result; 1764 return result;
1771 } 1765 }
1772 RINOK(extractCallback->SetOperationResult(opRes)); 1766 RINOK(extractCallback->SetOperationResult(opRes))
1773 } 1767 }
1774 1768
1775 return S_OK; 1769 return S_OK;
@@ -1779,7 +1773,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1779IMPL_ISetCompressCodecsInfo 1773IMPL_ISetCompressCodecsInfo
1780 1774
1781REGISTER_ARC_I( 1775REGISTER_ARC_I(
1782 "Rar", "rar r00", 0, 3, 1776 "Rar", "rar r00", NULL, 3,
1783 kMarker, 1777 kMarker,
1784 0, 1778 0,
1785 NArcInfoFlags::kFindSignature, 1779 NArcInfoFlags::kFindSignature,
diff --git a/CPP/7zip/Archive/Rar/RarHandler.h b/CPP/7zip/Archive/Rar/RarHandler.h
index a62b60c..c4d8450 100644
--- a/CPP/7zip/Archive/Rar/RarHandler.h
+++ b/CPP/7zip/Archive/Rar/RarHandler.h
@@ -1,7 +1,7 @@
1// RarHandler.h 1// RarHandler.h
2 2
3#ifndef __RAR_HANDLER_H 3#ifndef ZIP7_INC_RAR_HANDLER_H
4#define __RAR_HANDLER_H 4#define ZIP7_INC_RAR_HANDLER_H
5 5
6#include "../IArchive.h" 6#include "../IArchive.h"
7 7
@@ -67,11 +67,19 @@ struct CRefItem
67 unsigned NumItems; 67 unsigned NumItems;
68}; 68};
69 69
70class CHandler: 70class CHandler Z7_final:
71 public IInArchive, 71 public IInArchive,
72 PUBLIC_ISetCompressCodecsInfo 72 Z7_PUBLIC_ISetCompressCodecsInfo_IFEC
73 public CMyUnknownImp 73 public CMyUnknownImp
74{ 74{
75 Z7_COM_QI_BEGIN2(IInArchive)
76 Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC
77 Z7_COM_QI_END
78 Z7_COM_ADDREF_RELEASE
79
80 Z7_IFACE_COM7_IMP(IInArchive)
81 DECL_ISetCompressCodecsInfo
82
75 CRecordVector<CRefItem> _refItems; 83 CRecordVector<CRefItem> _refItems;
76 CObjectVector<CItem> _items; 84 CObjectVector<CItem> _items;
77 CObjectVector<CArc> _arcs; 85 CObjectVector<CArc> _arcs;
@@ -99,16 +107,6 @@ class CHandler:
99 HRESULT Open2(IInStream *stream, 107 HRESULT Open2(IInStream *stream,
100 const UInt64 *maxCheckStartPosition, 108 const UInt64 *maxCheckStartPosition,
101 IArchiveOpenCallback *openCallback); 109 IArchiveOpenCallback *openCallback);
102
103public:
104 MY_QUERYINTERFACE_BEGIN2(IInArchive)
105 QUERY_ENTRY_ISetCompressCodecsInfo
106 MY_QUERYINTERFACE_END
107 MY_ADDREF_RELEASE
108
109 INTERFACE_IInArchive(;)
110
111 DECL_ISetCompressCodecsInfo
112}; 110};
113 111
114}} 112}}
diff --git a/CPP/7zip/Archive/Rar/RarHeader.h b/CPP/7zip/Archive/Rar/RarHeader.h
index 30c53ec..031fea6 100644
--- a/CPP/7zip/Archive/Rar/RarHeader.h
+++ b/CPP/7zip/Archive/Rar/RarHeader.h
@@ -1,7 +1,7 @@
1// Archive/RarHeader.h 1// Archive/RarHeader.h
2 2
3#ifndef __ARCHIVE_RAR_HEADER_H 3#ifndef ZIP7_INC_ARCHIVE_RAR_HEADER_H
4#define __ARCHIVE_RAR_HEADER_H 4#define ZIP7_INC_ARCHIVE_RAR_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
diff --git a/CPP/7zip/Archive/Rar/RarItem.h b/CPP/7zip/Archive/Rar/RarItem.h
index 10e21c5..e1028ba 100644
--- a/CPP/7zip/Archive/Rar/RarItem.h
+++ b/CPP/7zip/Archive/Rar/RarItem.h
@@ -1,7 +1,7 @@
1// RarItem.h 1// RarItem.h
2 2
3#ifndef __ARCHIVE_RAR_ITEM_H 3#ifndef ZIP7_INC_ARCHIVE_RAR_ITEM_H
4#define __ARCHIVE_RAR_ITEM_H 4#define ZIP7_INC_ARCHIVE_RAR_ITEM_H
5 5
6#include "../../../Common/StringConvert.h" 6#include "../../../Common/StringConvert.h"
7 7
diff --git a/CPP/7zip/Archive/Rar/RarVol.h b/CPP/7zip/Archive/Rar/RarVol.h
index 2f5bbd3..9ee8e86 100644
--- a/CPP/7zip/Archive/Rar/RarVol.h
+++ b/CPP/7zip/Archive/Rar/RarVol.h
@@ -1,7 +1,7 @@
1// RarVol.h 1// RarVol.h
2 2
3#ifndef __ARCHIVE_RAR_VOL_H 3#ifndef ZIP7_INC_ARCHIVE_RAR_VOL_H
4#define __ARCHIVE_RAR_VOL_H 4#define ZIP7_INC_ARCHIVE_RAR_VOL_H
5 5
6#include "../../../Common/StringConvert.h" 6#include "../../../Common/StringConvert.h"
7 7
@@ -22,7 +22,7 @@ class CVolumeName
22 UString _changed; 22 UString _changed;
23 UString _after; 23 UString _after;
24public: 24public:
25 CVolumeName(): _needChangeForNext(true) {}; 25 CVolumeName(): _needChangeForNext(true) {}
26 26
27 bool InitName(const UString &name, bool newStyle = true) 27 bool InitName(const UString &name, bool newStyle = true)
28 { 28 {
@@ -52,7 +52,7 @@ public:
52 ext.IsEqualTo_Ascii_NoCase("r01")) 52 ext.IsEqualTo_Ascii_NoCase("r01"))
53 { 53 {
54 _changed = ext; 54 _changed = ext;
55 _before.SetFrom(name.Ptr(), dotPos + 1); 55 _before.SetFrom(name.Ptr(), (unsigned)dotPos + 1);
56 return true; 56 return true;
57 } 57 }
58 } 58 }
@@ -83,7 +83,7 @@ public:
83 83
84 _after.Empty(); 84 _after.Empty();
85 _before = base; 85 _before = base;
86 _before += '.'; 86 _before.Add_Dot();
87 _changed = "r00"; 87 _changed = "r00";
88 _needChangeForNext = false; 88 _needChangeForNext = false;
89 return true; 89 return true;
diff --git a/CPP/7zip/Archive/Rar/StdAfx.h b/CPP/7zip/Archive/Rar/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Rar/StdAfx.h
+++ b/CPP/7zip/Archive/Rar/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/RpmHandler.cpp b/CPP/7zip/Archive/RpmHandler.cpp
index 366f8ef..e05ac26 100644
--- a/CPP/7zip/Archive/RpmHandler.cpp
+++ b/CPP/7zip/Archive/RpmHandler.cpp
@@ -19,7 +19,7 @@
19 19
20#include "HandlerCont.h" 20#include "HandlerCont.h"
21 21
22// #define _SHOW_RPM_METADATA 22// #define Z7_RPM_SHOW_METADATA
23 23
24using namespace NWindows; 24using namespace NWindows;
25 25
@@ -169,7 +169,7 @@ struct CEntry
169}; 169};
170 170
171 171
172#ifdef _SHOW_RPM_METADATA 172#ifdef Z7_RPM_SHOW_METADATA
173struct CMetaFile 173struct CMetaFile
174{ 174{
175 UInt32 Tag; 175 UInt32 Tag;
@@ -178,8 +178,10 @@ struct CMetaFile
178}; 178};
179#endif 179#endif
180 180
181class CHandler: public CHandlerCont 181Z7_class_CHandler_final: public CHandlerCont
182{ 182{
183 Z7_IFACE_COM7_IMP(IInArchive_Cont)
184
183 UInt64 _headersSize; // is equal to start offset of payload data 185 UInt64 _headersSize; // is equal to start offset of payload data
184 UInt64 _payloadSize; 186 UInt64 _payloadSize;
185 UInt64 _size; 187 UInt64 _size;
@@ -207,7 +209,7 @@ class CHandler: public CHandlerCont
207 209
208 CLead _lead; 210 CLead _lead;
209 211
210 #ifdef _SHOW_RPM_METADATA 212 #ifdef Z7_RPM_SHOW_METADATA
211 AString _metadata; 213 AString _metadata;
212 CRecordVector<CMetaFile> _metaFiles; 214 CRecordVector<CMetaFile> _metaFiles;
213 #endif 215 #endif
@@ -234,15 +236,12 @@ class CHandler: public CHandlerCont
234 HRESULT ReadHeader(ISequentialInStream *stream, bool isMainHeader); 236 HRESULT ReadHeader(ISequentialInStream *stream, bool isMainHeader);
235 HRESULT Open2(ISequentialInStream *stream); 237 HRESULT Open2(ISequentialInStream *stream);
236 238
237 virtual int GetItem_ExtractInfo(UInt32 /* index */, UInt64 &pos, UInt64 &size) const 239 virtual int GetItem_ExtractInfo(UInt32 /* index */, UInt64 &pos, UInt64 &size) const Z7_override
238 { 240 {
239 pos = _headersSize; 241 pos = _headersSize;
240 size = _size; 242 size = _size;
241 return NExtract::NOperationResult::kOK; 243 return NExtract::NOperationResult::kOK;
242 } 244 }
243
244public:
245 INTERFACE_IInArchive_Cont(;)
246}; 245};
247 246
248static const Byte kArcProps[] = 247static const Byte kArcProps[] =
@@ -251,7 +250,7 @@ static const Byte kArcProps[] =
251 kpidCpu, 250 kpidCpu,
252 kpidHostOS, 251 kpidHostOS,
253 kpidCTime 252 kpidCTime
254 #ifdef _SHOW_RPM_METADATA 253 #ifdef Z7_RPM_SHOW_METADATA
255 , kpidComment 254 , kpidComment
256 #endif 255 #endif
257}; 256};
@@ -274,7 +273,7 @@ void CHandler::AddCPU(AString &s) const
274 { 273 {
275 if (_lead.Type == kRpmType_Bin) 274 if (_lead.Type == kRpmType_Bin)
276 { 275 {
277 if (_lead.Cpu < ARRAY_SIZE(k_CPUs)) 276 if (_lead.Cpu < Z7_ARRAY_SIZE(k_CPUs))
278 s += k_CPUs[_lead.Cpu]; 277 s += k_CPUs[_lead.Cpu];
279 else 278 else
280 s.Add_UInt32(_lead.Cpu); 279 s.Add_UInt32(_lead.Cpu);
@@ -290,19 +289,19 @@ AString CHandler::GetBaseName() const
290 s = _name; 289 s = _name;
291 if (!_version.IsEmpty()) 290 if (!_version.IsEmpty())
292 { 291 {
293 s += '-'; 292 s.Add_Minus();
294 s += _version; 293 s += _version;
295 } 294 }
296 if (!_release.IsEmpty()) 295 if (!_release.IsEmpty())
297 { 296 {
298 s += '-'; 297 s.Add_Minus();
299 s += _release; 298 s += _release;
300 } 299 }
301 } 300 }
302 else 301 else
303 s.SetFrom_CalcLen(_lead.Name, kNameSize); 302 s.SetFrom_CalcLen(_lead.Name, kNameSize);
304 303
305 s += '.'; 304 s.Add_Dot();
306 if (_lead.Type == kRpmType_Src) 305 if (_lead.Type == kRpmType_Src)
307 s += "src"; 306 s += "src";
308 else 307 else
@@ -316,7 +315,7 @@ void CHandler::AddSubFileExtension(AString &res) const
316 res += _format; 315 res += _format;
317 else 316 else
318 res += "cpio"; 317 res += "cpio";
319 res += '.'; 318 res.Add_Dot();
320 319
321 const char *s; 320 const char *s;
322 321
@@ -344,7 +343,7 @@ void CHandler::AddSubFileExtension(AString &res) const
344 res += s; 343 res += s;
345} 344}
346 345
347STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 346Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
348{ 347{
349 COM_TRY_BEGIN 348 COM_TRY_BEGIN
350 NCOM::CPropVariant prop; 349 NCOM::CPropVariant prop;
@@ -383,7 +382,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
383 break; 382 break;
384 } 383 }
385 384
386 #ifdef _SHOW_RPM_METADATA 385 #ifdef Z7_RPM_SHOW_METADATA
387 // case kpidComment: SetStringProp(_metadata, prop); break; 386 // case kpidComment: SetStringProp(_metadata, prop); break;
388 #endif 387 #endif
389 388
@@ -399,7 +398,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
399} 398}
400 399
401 400
402STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 401Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
403{ 402{
404 NWindows::NCOM::CPropVariant prop; 403 NWindows::NCOM::CPropVariant prop;
405 if (index == 0) 404 if (index == 0)
@@ -418,7 +417,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
418 case kpidPath: 417 case kpidPath:
419 { 418 {
420 AString s (GetBaseName()); 419 AString s (GetBaseName());
421 s += '.'; 420 s.Add_Dot();
422 AddSubFileExtension(s); 421 AddSubFileExtension(s);
423 SetStringProp(s, prop); 422 SetStringProp(s, prop);
424 break; 423 break;
@@ -432,7 +431,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
432 } 431 }
433 */ 432 */
434 } 433 }
435 #ifdef _SHOW_RPM_METADATA 434 #ifdef Z7_RPM_SHOW_METADATA
436 else 435 else
437 { 436 {
438 index--; 437 index--;
@@ -467,7 +466,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
467 return S_OK; 466 return S_OK;
468} 467}
469 468
470#ifdef _SHOW_RPM_METADATA 469#ifdef Z7_RPM_SHOW_METADATA
471static inline char GetHex(unsigned value) 470static inline char GetHex(unsigned value)
472{ 471{
473 return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10))); 472 return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10)));
@@ -480,7 +479,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
480 UInt32 dataLen; 479 UInt32 dataLen;
481 { 480 {
482 char buf[k_HeaderSig_Size]; 481 char buf[k_HeaderSig_Size];
483 RINOK(ReadStream_FALSE(stream, buf, k_HeaderSig_Size)); 482 RINOK(ReadStream_FALSE(stream, buf, k_HeaderSig_Size))
484 if (Get32(buf) != 0x8EADE801) // buf[3] = 0x01 - is version 483 if (Get32(buf) != 0x8EADE801) // buf[3] = 0x01 - is version
485 return S_FALSE; 484 return S_FALSE;
486 // reserved = Get32(buf + 4); 485 // reserved = Get32(buf + 4);
@@ -494,7 +493,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
494 if (headerSize < dataLen) 493 if (headerSize < dataLen)
495 return S_FALSE; 494 return S_FALSE;
496 CByteBuffer buffer(headerSize); 495 CByteBuffer buffer(headerSize);
497 RINOK(ReadStream_FALSE(stream, buffer, headerSize)); 496 RINOK(ReadStream_FALSE(stream, buffer, headerSize))
498 497
499 for (UInt32 i = 0; i < numEntries; i++) 498 for (UInt32 i = 0; i < numEntries; i++)
500 { 499 {
@@ -520,7 +519,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
520 } 519 }
521 else 520 else
522 { 521 {
523 #ifdef _SHOW_RPM_METADATA 522 #ifdef Z7_RPM_SHOW_METADATA
524 { 523 {
525 _metadata.Add_UInt32(entry.Tag); 524 _metadata.Add_UInt32(entry.Tag);
526 _metadata += ": "; 525 _metadata += ": ";
@@ -547,7 +546,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
547 case RPMTAG_PAYLOADCOMPRESSOR: _compressor = s; break; 546 case RPMTAG_PAYLOADCOMPRESSOR: _compressor = s; break;
548 } 547 }
549 548
550 #ifdef _SHOW_RPM_METADATA 549 #ifdef Z7_RPM_SHOW_METADATA
551 _metadata += s; 550 _metadata += s;
552 #endif 551 #endif
553 } 552 }
@@ -563,7 +562,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
563 _time_Defined = true; 562 _time_Defined = true;
564 } 563 }
565 564
566 #ifdef _SHOW_RPM_METADATA 565 #ifdef Z7_RPM_SHOW_METADATA
567 for (UInt32 t = 0; t < entry.Count; t++) 566 for (UInt32 t = 0; t < entry.Count; t++)
568 { 567 {
569 if (t != 0) 568 if (t != 0)
@@ -573,7 +572,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
573 #endif 572 #endif
574 } 573 }
575 574
576 #ifdef _SHOW_RPM_METADATA 575 #ifdef Z7_RPM_SHOW_METADATA
577 576
578 else if ( 577 else if (
579 entry.Type == k_EntryType_STRING_ARRAY || 578 entry.Type == k_EntryType_STRING_ARRAY ||
@@ -628,7 +627,7 @@ HRESULT CHandler::ReadHeader(ISequentialInStream *stream, bool isMainHeader)
628 #endif 627 #endif
629 } 628 }
630 629
631 #ifdef _SHOW_RPM_METADATA 630 #ifdef Z7_RPM_SHOW_METADATA
632 CMetaFile meta; 631 CMetaFile meta;
633 meta.Offset = entry.Offset; 632 meta.Offset = entry.Offset;
634 meta.Tag = entry.Tag; 633 meta.Tag = entry.Tag;
@@ -656,7 +655,7 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
656{ 655{
657 { 656 {
658 Byte buf[kLeadSize]; 657 Byte buf[kLeadSize];
659 RINOK(ReadStream_FALSE(stream, buf, kLeadSize)); 658 RINOK(ReadStream_FALSE(stream, buf, kLeadSize))
660 if (Get32(buf) != 0xEDABEEDB) 659 if (Get32(buf) != 0xEDABEEDB)
661 return S_FALSE; 660 return S_FALSE;
662 _lead.Parse(buf); 661 _lead.Parse(buf);
@@ -668,22 +667,22 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
668 667
669 if (_lead.SignatureType == RPMSIG_NONE) 668 if (_lead.SignatureType == RPMSIG_NONE)
670 { 669 {
671 ; 670
672 } 671 }
673 else if (_lead.SignatureType == RPMSIG_PGP262_1024) 672 else if (_lead.SignatureType == RPMSIG_PGP262_1024)
674 { 673 {
675 Byte temp[256]; 674 Byte temp[256];
676 RINOK(ReadStream_FALSE(stream, temp, sizeof(temp))); 675 RINOK(ReadStream_FALSE(stream, temp, sizeof(temp)))
677 } 676 }
678 else if (_lead.SignatureType == RPMSIG_HEADERSIG) 677 else if (_lead.SignatureType == RPMSIG_HEADERSIG)
679 { 678 {
680 RINOK(ReadHeader(stream, false)); 679 RINOK(ReadHeader(stream, false))
681 unsigned pos = (unsigned)_headersSize & 7; 680 unsigned pos = (unsigned)_headersSize & 7;
682 if (pos != 0) 681 if (pos != 0)
683 { 682 {
684 Byte temp[8]; 683 Byte temp[8];
685 unsigned num = 8 - pos; 684 unsigned num = 8 - pos;
686 RINOK(ReadStream_FALSE(stream, temp, num)); 685 RINOK(ReadStream_FALSE(stream, temp, num))
687 _headersSize += num; 686 _headersSize += num;
688 } 687 }
689 } 688 }
@@ -694,20 +693,20 @@ HRESULT CHandler::Open2(ISequentialInStream *stream)
694} 693}
695 694
696 695
697STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *) 696Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *))
698{ 697{
699 COM_TRY_BEGIN 698 COM_TRY_BEGIN
700 { 699 {
701 Close(); 700 Close();
702 RINOK(Open2(inStream)); 701 RINOK(Open2(inStream))
703 702
704 // start of payload is allowed to be unaligned 703 // start of payload is allowed to be unaligned
705 RINOK(ReadStream_FALSE(inStream, _payloadSig, sizeof(_payloadSig))); 704 RINOK(ReadStream_FALSE(inStream, _payloadSig, sizeof(_payloadSig)))
706 705
707 if (!_payloadSize_Defined) 706 if (!_payloadSize_Defined)
708 { 707 {
709 UInt64 endPos; 708 UInt64 endPos;
710 RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); 709 RINOK(InStream_GetSize_SeekToEnd(inStream, endPos))
711 _size = endPos - _headersSize; 710 _size = endPos - _headersSize;
712 } 711 }
713 _stream = inStream; 712 _stream = inStream;
@@ -716,7 +715,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
716 COM_TRY_END 715 COM_TRY_END
717} 716}
718 717
719STDMETHODIMP CHandler::Close() 718Z7_COM7F_IMF(CHandler::Close())
720{ 719{
721 _headersSize = 0; 720 _headersSize = 0;
722 _payloadSize = 0; 721 _payloadSize = 0;
@@ -738,7 +737,7 @@ STDMETHODIMP CHandler::Close()
738 _format.Empty(); 737 _format.Empty();
739 _compressor.Empty(); 738 _compressor.Empty();
740 739
741 #ifdef _SHOW_RPM_METADATA 740 #ifdef Z7_RPM_SHOW_METADATA
742 _metadata.Empty(); 741 _metadata.Empty();
743 _metaFiles.Size(); 742 _metaFiles.Size();
744 #endif 743 #endif
@@ -747,10 +746,10 @@ STDMETHODIMP CHandler::Close()
747 return S_OK; 746 return S_OK;
748} 747}
749 748
750STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 749Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
751{ 750{
752 *numItems = 1 751 *numItems = 1
753 #ifdef _SHOW_RPM_METADATA 752 #ifdef Z7_RPM_SHOW_METADATA
754 + _metaFiles.Size() 753 + _metaFiles.Size()
755 #endif 754 #endif
756 ; 755 ;
@@ -761,7 +760,7 @@ STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
761static const Byte k_Signature[] = { 0xED, 0xAB, 0xEE, 0xDB}; 760static const Byte k_Signature[] = { 0xED, 0xAB, 0xEE, 0xDB};
762 761
763REGISTER_ARC_I( 762REGISTER_ARC_I(
764 "Rpm", "rpm", 0, 0xEB, 763 "Rpm", "rpm", NULL, 0xEB,
765 k_Signature, 764 k_Signature,
766 0, 765 0,
767 0, 766 0,
diff --git a/CPP/7zip/Archive/SparseHandler.cpp b/CPP/7zip/Archive/SparseHandler.cpp
index 47e3ed8..ab76f32 100644
--- a/CPP/7zip/Archive/SparseHandler.cpp
+++ b/CPP/7zip/Archive/SparseHandler.cpp
@@ -42,11 +42,11 @@ struct CHeader
42 { 42 {
43 // G16 (4, major_version); 43 // G16 (4, major_version);
44 // G16 (6, minor_version); 44 // G16 (6, minor_version);
45 G16 (8, file_hdr_sz); 45 G16 (8, file_hdr_sz)
46 G16 (10, chunk_hdr_sz); 46 G16 (10, chunk_hdr_sz)
47 G32 (12, BlockSize); 47 G32 (12, BlockSize)
48 G32 (16, NumBlocks); 48 G32 (16, NumBlocks)
49 G32 (20, NumChunks); 49 G32 (20, NumChunks)
50 // G32 (24, image_checksum); 50 // G32 (24, image_checksum);
51 } 51 }
52}; 52};
@@ -58,9 +58,9 @@ struct CHeader
58#define CHUNK_TYPE_DONT_CARE 0xCAC3 58#define CHUNK_TYPE_DONT_CARE 0xCAC3
59#define CHUNK_TYPE_CRC32 0xCAC4 59#define CHUNK_TYPE_CRC32 0xCAC4
60 60
61#define MY__CHUNK_TYPE_FILL 0 61#define MY_CHUNK_TYPE_FILL 0
62#define MY__CHUNK_TYPE_DONT_CARE 1 62#define MY_CHUNK_TYPE_DONT_CARE 1
63#define MY__CHUNK_TYPE_RAW__START 2 63#define MY_CHUNK_TYPE_RAW_START 2
64 64
65static const char * const g_Methods[] = 65static const char * const g_Methods[] =
66{ 66{
@@ -82,8 +82,13 @@ struct CChunk
82static const Byte k_Signature[] = { 0x3a, 0xff, 0x26, 0xed, 1, 0 }; 82static const Byte k_Signature[] = { 0x3a, 0xff, 0x26, 0xed, 1, 0 };
83 83
84 84
85class CHandler: public CHandlerImg 85Z7_class_CHandler_final: public CHandlerImg
86{ 86{
87 Z7_IFACE_COM7_IMP(IInArchive_Img)
88
89 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
90 Z7_IFACE_COM7_IMP(ISequentialInStream)
91
87 CRecordVector<CChunk> Chunks; 92 CRecordVector<CChunk> Chunks;
88 UInt64 _virtSize_fromChunks; 93 UInt64 _virtSize_fromChunks;
89 unsigned _blockSizeLog; 94 unsigned _blockSizeLog;
@@ -101,7 +106,7 @@ class CHandler: public CHandlerImg
101 HRESULT Seek2(UInt64 offset) 106 HRESULT Seek2(UInt64 offset)
102 { 107 {
103 _posInArc = offset; 108 _posInArc = offset;
104 return Stream->Seek(offset, STREAM_SEEK_SET, NULL); 109 return InStream_SeekSet(Stream, offset);
105 } 110 }
106 111
107 void InitSeekPositions() 112 void InitSeekPositions()
@@ -115,25 +120,19 @@ class CHandler: public CHandlerImg
115 } 120 }
116 121
117 // virtual functions 122 // virtual functions
118 bool Init_PackSizeProcessed() 123 bool Init_PackSizeProcessed() Z7_override
119 { 124 {
120 _packSizeProcessed = 0; 125 _packSizeProcessed = 0;
121 return true; 126 return true;
122 } 127 }
123 bool Get_PackSizeProcessed(UInt64 &size) 128 bool Get_PackSizeProcessed(UInt64 &size) Z7_override
124 { 129 {
125 size = _packSizeProcessed; 130 size = _packSizeProcessed;
126 return true; 131 return true;
127 } 132 }
128 133
129 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); 134 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override;
130 HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &processed); 135 HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &processed);
131
132public:
133 INTERFACE_IInArchive_Img(;)
134
135 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
136 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
137}; 136};
138 137
139 138
@@ -154,7 +153,7 @@ static const Byte kArcProps[] =
154IMP_IInArchive_Props 153IMP_IInArchive_Props
155IMP_IInArchive_ArcProps 154IMP_IInArchive_ArcProps
156 155
157STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 156Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
158{ 157{
159 COM_TRY_BEGIN 158 COM_TRY_BEGIN
160 NCOM::CPropVariant prop; 159 NCOM::CPropVariant prop;
@@ -193,7 +192,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
193} 192}
194 193
195 194
196STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 195Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
197{ 196{
198 COM_TRY_BEGIN 197 COM_TRY_BEGIN
199 NCOM::CPropVariant prop; 198 NCOM::CPropVariant prop;
@@ -228,7 +227,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
228 CHeader h; 227 CHeader h;
229 { 228 {
230 Byte buf[kHeaderSize]; 229 Byte buf[kHeaderSize];
231 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); 230 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize))
232 if (memcmp(buf, k_Signature, 6) != 0) 231 if (memcmp(buf, k_Signature, 6) != 0)
233 return S_FALSE; 232 return S_FALSE;
234 h.Parse(buf); 233 h.Parse(buf);
@@ -262,13 +261,13 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
262 const UInt32 mask = ((UInt32)1 << 16) - 1; 261 const UInt32 mask = ((UInt32)1 << 16) - 1;
263 if ((i & mask) == mask && openCallback) 262 if ((i & mask) == mask && openCallback)
264 { 263 {
265 RINOK(openCallback->SetCompleted(NULL, &offset)); 264 RINOK(openCallback->SetCompleted(NULL, &offset))
266 } 265 }
267 } 266 }
268 Byte buf[kChunkHeaderSize]; 267 Byte buf[kChunkHeaderSize];
269 { 268 {
270 size_t processed = kChunkHeaderSize; 269 size_t processed = kChunkHeaderSize;
271 RINOK(ReadStream(stream, buf, &processed)); 270 RINOK(ReadStream(stream, buf, &processed))
272 if (kChunkHeaderSize != processed) 271 if (kChunkHeaderSize != processed)
273 { 272 {
274 offset += kChunkHeaderSize; 273 offset += kChunkHeaderSize;
@@ -301,7 +300,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
301 return S_FALSE; 300 return S_FALSE;
302 { 301 {
303 size_t processed = kFillSize; 302 size_t processed = kFillSize;
304 RINOK(ReadStream(stream, c.Fill, &processed)); 303 RINOK(ReadStream(stream, c.Fill, &processed))
305 if (kFillSize != processed) 304 if (kFillSize != processed)
306 break; 305 break;
307 } 306 }
@@ -316,15 +315,15 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
316 { 315 {
317 if (size != 0) 316 if (size != 0)
318 return S_FALSE; 317 return S_FALSE;
319 c.PhyOffset = MY__CHUNK_TYPE_DONT_CARE; 318 c.PhyOffset = MY_CHUNK_TYPE_DONT_CARE;
320 } 319 }
321 else if (type == CHUNK_TYPE_FILL) 320 else if (type == CHUNK_TYPE_FILL)
322 { 321 {
323 if (size != kFillSize) 322 if (size != kFillSize)
324 return S_FALSE; 323 return S_FALSE;
325 c.PhyOffset = MY__CHUNK_TYPE_FILL; 324 c.PhyOffset = MY_CHUNK_TYPE_FILL;
326 size_t processed = kFillSize; 325 size_t processed = kFillSize;
327 RINOK(ReadStream(stream, c.Fill, &processed)); 326 RINOK(ReadStream(stream, c.Fill, &processed))
328 if (kFillSize != processed) 327 if (kFillSize != processed)
329 break; 328 break;
330 } 329 }
@@ -343,7 +342,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
343 virtBlock += numBlocks; 342 virtBlock += numBlocks;
344 Chunks.AddInReserved(c); 343 Chunks.AddInReserved(c);
345 if (type == CHUNK_TYPE_RAW) 344 if (type == CHUNK_TYPE_RAW)
346 RINOK(stream->Seek(offset, STREAM_SEEK_SET, NULL)); 345 RINOK(InStream_SeekSet(stream, offset))
347 } 346 }
348 } 347 }
349 348
@@ -367,7 +366,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
367} 366}
368 367
369 368
370STDMETHODIMP CHandler::Close() 369Z7_COM7F_IMF(CHandler::Close())
371{ 370{
372 Chunks.Clear(); 371 Chunks.Clear();
373 _isArc = false; 372 _isArc = false;
@@ -388,7 +387,7 @@ STDMETHODIMP CHandler::Close()
388} 387}
389 388
390 389
391STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 390Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
392{ 391{
393 COM_TRY_BEGIN 392 COM_TRY_BEGIN
394 *stream = NULL; 393 *stream = NULL;
@@ -436,7 +435,7 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &proces
436} 435}
437 436
438 437
439STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 438Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
440{ 439{
441 if (processedSize) 440 if (processedSize)
442 *processedSize = 0; 441 *processedSize = 0;
@@ -486,7 +485,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
486 485
487 const UInt64 phyOffset = c.PhyOffset; 486 const UInt64 phyOffset = c.PhyOffset;
488 487
489 if (phyOffset >= MY__CHUNK_TYPE_RAW__START) 488 if (phyOffset >= MY_CHUNK_TYPE_RAW_START)
490 { 489 {
491 UInt32 processed = 0; 490 UInt32 processed = 0;
492 const HRESULT res = ReadPhy(phyOffset + offset, data, size, processed); 491 const HRESULT res = ReadPhy(phyOffset + offset, data, size, processed);
@@ -496,9 +495,9 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
496 return res; 495 return res;
497 } 496 }
498 497
499 unsigned b = 0; 498 Byte b = 0;
500 499
501 if (phyOffset == MY__CHUNK_TYPE_FILL) 500 if (phyOffset == MY_CHUNK_TYPE_FILL)
502 { 501 {
503 const Byte b0 = c.Fill [0]; 502 const Byte b0 = c.Fill [0];
504 const Byte b1 = c.Fill [1]; 503 const Byte b1 = c.Fill [1];
@@ -528,7 +527,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
528 } 527 }
529 b = b0; 528 b = b0;
530 } 529 }
531 else if (phyOffset != MY__CHUNK_TYPE_DONT_CARE) 530 else if (phyOffset != MY_CHUNK_TYPE_DONT_CARE)
532 return S_FALSE; 531 return S_FALSE;
533 532
534 memset(data, b, size); 533 memset(data, b, size);
diff --git a/CPP/7zip/Archive/SplitHandler.cpp b/CPP/7zip/Archive/SplitHandler.cpp
index 6bddfb8..ae7ca03 100644
--- a/CPP/7zip/Archive/SplitHandler.cpp
+++ b/CPP/7zip/Archive/SplitHandler.cpp
@@ -9,6 +9,7 @@
9 9
10#include "../Common/ProgressUtils.h" 10#include "../Common/ProgressUtils.h"
11#include "../Common/RegisterArc.h" 11#include "../Common/RegisterArc.h"
12#include "../Common/StreamUtils.h"
12 13
13#include "../Compress/CopyCoder.h" 14#include "../Compress/CopyCoder.h"
14 15
@@ -31,27 +32,22 @@ static const Byte kArcProps[] =
31 kpidTotalPhySize 32 kpidTotalPhySize
32}; 33};
33 34
34class CHandler: 35
35 public IInArchive, 36Z7_CLASS_IMP_CHandler_IInArchive_1(
36 public IInArchiveGetStream, 37 IInArchiveGetStream
37 public CMyUnknownImp 38)
38{
39 CObjectVector<CMyComPtr<IInStream> > _streams; 39 CObjectVector<CMyComPtr<IInStream> > _streams;
40 CRecordVector<UInt64> _sizes; 40 CRecordVector<UInt64> _sizes;
41 UString _subName; 41 UString _subName;
42 UInt64 _totalSize; 42 UInt64 _totalSize;
43 43
44 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); 44 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback);
45public:
46 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
47 INTERFACE_IInArchive(;)
48 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
49}; 45};
50 46
51IMP_IInArchive_Props 47IMP_IInArchive_Props
52IMP_IInArchive_ArcProps 48IMP_IInArchive_ArcProps
53 49
54STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 50Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
55{ 51{
56 NCOM::CPropVariant prop; 52 NCOM::CPropVariant prop;
57 switch (propID) 53 switch (propID)
@@ -121,27 +117,29 @@ struct CSeqName
121 } 117 }
122}; 118};
123 119
120
124HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 121HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
125{ 122{
126 Close(); 123 Close();
127 if (!callback) 124 if (!callback)
128 return S_FALSE; 125 return S_FALSE;
129 126
130 CMyComPtr<IArchiveOpenVolumeCallback> volumeCallback; 127 Z7_DECL_CMyComPtr_QI_FROM(
131 callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&volumeCallback); 128 IArchiveOpenVolumeCallback,
129 volumeCallback, callback)
132 if (!volumeCallback) 130 if (!volumeCallback)
133 return S_FALSE; 131 return S_FALSE;
134 132
135 UString name; 133 UString name;
136 { 134 {
137 NCOM::CPropVariant prop; 135 NCOM::CPropVariant prop;
138 RINOK(volumeCallback->GetProperty(kpidName, &prop)); 136 RINOK(volumeCallback->GetProperty(kpidName, &prop))
139 if (prop.vt != VT_BSTR) 137 if (prop.vt != VT_BSTR)
140 return S_FALSE; 138 return S_FALSE;
141 name = prop.bstrVal; 139 name = prop.bstrVal;
142 } 140 }
143 141
144 int dotPos = name.ReverseFind_Dot(); 142 const int dotPos = name.ReverseFind_Dot();
145 const UString prefix = name.Left((unsigned)(dotPos + 1)); 143 const UString prefix = name.Left((unsigned)(dotPos + 1));
146 const UString ext = name.Ptr((unsigned)(dotPos + 1)); 144 const UString ext = name.Ptr((unsigned)(dotPos + 1));
147 UString ext2 = ext; 145 UString ext2 = ext;
@@ -192,14 +190,13 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
192 { 190 {
193 /* 191 /*
194 NCOM::CPropVariant prop; 192 NCOM::CPropVariant prop;
195 RINOK(volumeCallback->GetProperty(kpidSize, &prop)); 193 RINOK(volumeCallback->GetProperty(kpidSize, &prop))
196 if (prop.vt != VT_UI8) 194 if (prop.vt != VT_UI8)
197 return E_INVALIDARG; 195 return E_INVALIDARG;
198 size = prop.uhVal.QuadPart; 196 size = prop.uhVal.QuadPart;
199 */ 197 */
200 RINOK(stream->Seek(0, STREAM_SEEK_END, &size));
201 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
202 } 198 }
199 RINOK(InStream_AtBegin_GetSize(stream, size))
203 200
204 _totalSize += size; 201 _totalSize += size;
205 _sizes.Add(size); 202 _sizes.Add(size);
@@ -207,7 +204,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
207 204
208 { 205 {
209 const UInt64 numFiles = _streams.Size(); 206 const UInt64 numFiles = _streams.Size();
210 RINOK(callback->SetCompleted(&numFiles, NULL)); 207 RINOK(callback->SetCompleted(&numFiles, NULL))
211 } 208 }
212 209
213 for (;;) 210 for (;;)
@@ -216,30 +213,20 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
216 if (!seqName.GetNextName(fullName)) 213 if (!seqName.GetNextName(fullName))
217 break; 214 break;
218 CMyComPtr<IInStream> nextStream; 215 CMyComPtr<IInStream> nextStream;
219 HRESULT result = volumeCallback->GetStream(fullName, &nextStream); 216 const HRESULT result = volumeCallback->GetStream(fullName, &nextStream);
220 if (result == S_FALSE) 217 if (result == S_FALSE)
221 break; 218 break;
222 if (result != S_OK) 219 if (result != S_OK)
223 return result; 220 return result;
224 if (!nextStream) 221 if (!nextStream)
225 break; 222 break;
226 { 223 RINOK(InStream_AtBegin_GetSize(nextStream, size))
227 /*
228 NCOM::CPropVariant prop;
229 RINOK(volumeCallback->GetProperty(kpidSize, &prop));
230 if (prop.vt != VT_UI8)
231 return E_INVALIDARG;
232 size = prop.uhVal.QuadPart;
233 */
234 RINOK(nextStream->Seek(0, STREAM_SEEK_END, &size));
235 RINOK(nextStream->Seek(0, STREAM_SEEK_SET, NULL));
236 }
237 _totalSize += size; 224 _totalSize += size;
238 _sizes.Add(size); 225 _sizes.Add(size);
239 _streams.Add(nextStream); 226 _streams.Add(nextStream);
240 { 227 {
241 const UInt64 numFiles = _streams.Size(); 228 const UInt64 numFiles = _streams.Size();
242 RINOK(callback->SetCompleted(&numFiles, NULL)); 229 RINOK(callback->SetCompleted(&numFiles, NULL))
243 } 230 }
244 } 231 }
245 232
@@ -251,17 +238,17 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
251 return S_OK; 238 return S_OK;
252} 239}
253 240
254STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 241Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
255{ 242{
256 COM_TRY_BEGIN 243 COM_TRY_BEGIN
257 HRESULT res = Open2(stream, callback); 244 const HRESULT res = Open2(stream, callback);
258 if (res != S_OK) 245 if (res != S_OK)
259 Close(); 246 Close();
260 return res; 247 return res;
261 COM_TRY_END 248 COM_TRY_END
262} 249}
263 250
264STDMETHODIMP CHandler::Close() 251Z7_COM7F_IMF(CHandler::Close())
265{ 252{
266 _totalSize = 0; 253 _totalSize = 0;
267 _subName.Empty(); 254 _subName.Empty();
@@ -270,13 +257,13 @@ STDMETHODIMP CHandler::Close()
270 return S_OK; 257 return S_OK;
271} 258}
272 259
273STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 260Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
274{ 261{
275 *numItems = _streams.IsEmpty() ? 0 : 1; 262 *numItems = _streams.IsEmpty() ? 0 : 1;
276 return S_OK; 263 return S_OK;
277} 264}
278 265
279STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 266Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
280{ 267{
281 NCOM::CPropVariant prop; 268 NCOM::CPropVariant prop;
282 switch (propID) 269 switch (propID)
@@ -291,8 +278,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
291 return S_OK; 278 return S_OK;
292} 279}
293 280
294STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 281Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
295 Int32 testMode, IArchiveExtractCallback *extractCallback) 282 Int32 testMode, IArchiveExtractCallback *extractCallback))
296{ 283{
297 COM_TRY_BEGIN 284 COM_TRY_BEGIN
298 if (numItems == 0) 285 if (numItems == 0)
@@ -301,15 +288,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
301 return E_INVALIDARG; 288 return E_INVALIDARG;
302 289
303 UInt64 currentTotalSize = 0; 290 UInt64 currentTotalSize = 0;
304 RINOK(extractCallback->SetTotal(_totalSize)); 291 RINOK(extractCallback->SetTotal(_totalSize))
305 CMyComPtr<ISequentialOutStream> outStream; 292 CMyComPtr<ISequentialOutStream> outStream;
306 Int32 askMode = testMode ? 293 const Int32 askMode = testMode ?
307 NExtract::NAskMode::kTest : 294 NExtract::NAskMode::kTest :
308 NExtract::NAskMode::kExtract; 295 NExtract::NAskMode::kExtract;
309 RINOK(extractCallback->GetStream(0, &outStream, askMode)); 296 RINOK(extractCallback->GetStream(0, &outStream, askMode))
310 if (!testMode && !outStream) 297 if (!testMode && !outStream)
311 return S_OK; 298 return S_OK;
312 RINOK(extractCallback->PrepareOperation(askMode)); 299 RINOK(extractCallback->PrepareOperation(askMode))
313 300
314 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; 301 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
315 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; 302 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
@@ -318,13 +305,15 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
318 CMyComPtr<ICompressProgressInfo> progress = lps; 305 CMyComPtr<ICompressProgressInfo> progress = lps;
319 lps->Init(extractCallback, false); 306 lps->Init(extractCallback, false);
320 307
321 FOR_VECTOR (i, _streams) 308 for (unsigned i = 0;; i++)
322 { 309 {
323 lps->InSize = lps->OutSize = currentTotalSize; 310 lps->InSize = lps->OutSize = currentTotalSize;
324 RINOK(lps->SetCur()); 311 RINOK(lps->SetCur())
312 if (i == _streams.Size())
313 break;
325 IInStream *inStream = _streams[i]; 314 IInStream *inStream = _streams[i];
326 RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); 315 RINOK(InStream_SeekToBegin(inStream))
327 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 316 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
328 currentTotalSize += copyCoderSpec->TotalSize; 317 currentTotalSize += copyCoderSpec->TotalSize;
329 } 318 }
330 outStream.Release(); 319 outStream.Release();
@@ -332,12 +321,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
332 COM_TRY_END 321 COM_TRY_END
333} 322}
334 323
335STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 324Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
336{ 325{
337 COM_TRY_BEGIN 326 COM_TRY_BEGIN
338 if (index != 0) 327 if (index != 0)
339 return E_INVALIDARG; 328 return E_INVALIDARG;
340 *stream = 0; 329 *stream = NULL;
341 CMultiStream *streamSpec = new CMultiStream; 330 CMultiStream *streamSpec = new CMultiStream;
342 CMyComPtr<ISequentialInStream> streamTemp = streamSpec; 331 CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
343 FOR_VECTOR (i, _streams) 332 FOR_VECTOR (i, _streams)
@@ -354,7 +343,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
354} 343}
355 344
356REGISTER_ARC_I_NO_SIG( 345REGISTER_ARC_I_NO_SIG(
357 "Split", "001", 0, 0xEA, 346 "Split", "001", NULL, 0xEA,
358 0, 347 0,
359 0, 348 0,
360 NULL) 349 NULL)
diff --git a/CPP/7zip/Archive/SquashfsHandler.cpp b/CPP/7zip/Archive/SquashfsHandler.cpp
index fe271bc..9c9ec03 100644
--- a/CPP/7zip/Archive/SquashfsHandler.cpp
+++ b/CPP/7zip/Archive/SquashfsHandler.cpp
@@ -49,13 +49,13 @@ static UInt64 Get64b(const Byte *p, bool be) { return be ? GetBe64(p) : GetUi64(
49#define Get32(p) Get32b(p, be) 49#define Get32(p) Get32b(p, be)
50#define Get64(p) Get64b(p, be) 50#define Get64(p) Get64b(p, be)
51 51
52#define LE_16(offs, dest) dest = GetUi16(p + (offs)); 52#define LE_16(offs, dest) dest = GetUi16(p + (offs))
53#define LE_32(offs, dest) dest = GetUi32(p + (offs)); 53#define LE_32(offs, dest) dest = GetUi32(p + (offs))
54#define LE_64(offs, dest) dest = GetUi64(p + (offs)); 54#define LE_64(offs, dest) dest = GetUi64(p + (offs))
55 55
56#define GET_16(offs, dest) dest = Get16(p + (offs)); 56#define GET_16(offs, dest) dest = Get16(p + (offs))
57#define GET_32(offs, dest) dest = Get32(p + (offs)); 57#define GET_32(offs, dest) dest = Get32(p + (offs))
58#define GET_64(offs, dest) dest = Get64(p + (offs)); 58#define GET_64(offs, dest) dest = Get64(p + (offs))
59 59
60static const UInt32 kSignature32_LE = 0x73717368; 60static const UInt32 kSignature32_LE = 0x73717368;
61static const UInt32 kSignature32_BE = 0x68737173; 61static const UInt32 kSignature32_BE = 0x68737173;
@@ -831,11 +831,10 @@ struct CFrag
831 UInt32 Size; 831 UInt32 Size;
832}; 832};
833 833
834class CHandler: 834
835 public IInArchive, 835Z7_CLASS_IMP_CHandler_IInArchive_1(
836 public IInArchiveGetStream, 836 IInArchiveGetStream
837 public CMyUnknownImp 837)
838{
839 CRecordVector<CItem> _items; 838 CRecordVector<CItem> _items;
840 CRecordVector<CNode> _nodes; 839 CRecordVector<CNode> _nodes;
841 CRecordVector<UInt32> _nodesPos; 840 CRecordVector<UInt32> _nodesPos;
@@ -893,7 +892,7 @@ class CHandler:
893 892
894 HRESULT Seek2(UInt64 offset) 893 HRESULT Seek2(UInt64 offset)
895 { 894 {
896 return _stream->Seek(offset, STREAM_SEEK_SET, NULL); 895 return InStream_SeekSet(_stream, offset);
897 } 896 }
898 897
899 HRESULT Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool *outBufWasWritten, UInt32 *outBufWasWrittenSize, 898 HRESULT Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool *outBufWasWritten, UInt32 *outBufWasWrittenSize,
@@ -906,8 +905,8 @@ class CHandler:
906 HRESULT ScanInodes(UInt64 ptr); 905 HRESULT ScanInodes(UInt64 ptr);
907 HRESULT ReadUids(UInt64 start, UInt32 num, CByteBuffer &ids); 906 HRESULT ReadUids(UInt64 start, UInt32 num, CByteBuffer &ids);
908 HRESULT Open2(IInStream *inStream); 907 HRESULT Open2(IInStream *inStream);
909 AString GetPath(int index) const; 908 AString GetPath(unsigned index) const;
910 bool GetPackSize(int index, UInt64 &res, bool fillOffsets); 909 bool GetPackSize(unsigned index, UInt64 &res, bool fillOffsets);
911 910
912public: 911public:
913 CHandler(); 912 CHandler();
@@ -916,13 +915,10 @@ public:
916 XzUnpacker_Free(&_xz); 915 XzUnpacker_Free(&_xz);
917 } 916 }
918 917
919 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
920 INTERFACE_IInArchive(;)
921 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
922
923 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); 918 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize);
924}; 919};
925 920
921
926CHandler::CHandler() 922CHandler::CHandler()
927{ 923{
928 XzUnpacker_Construct(&_xz, &g_Alloc); 924 XzUnpacker_Construct(&_xz, &g_Alloc);
@@ -1044,7 +1040,7 @@ static HRESULT LzoDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *src
1044 } 1040 }
1045 1041
1046 srcRem--; 1042 srcRem--;
1047 back = (b >> 2) + (*src++ << 2); 1043 back = (b >> 2) + ((UInt32)*src++ << 2);
1048 len = 2; 1044 len = 2;
1049 if (mode == 4) 1045 if (mode == 4)
1050 { 1046 {
@@ -1086,8 +1082,8 @@ static HRESULT LzoDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *src
1086 back += ((bOld & 8) << 11); 1082 back += ((bOld & 8) << 11);
1087 if (back == 0) 1083 if (back == 0)
1088 { 1084 {
1089 *destLen = dest - destStart; 1085 *destLen = (size_t)(dest - destStart);
1090 *srcLen = src - srcStart; 1086 *srcLen = (size_t)(src - srcStart);
1091 return S_OK; 1087 return S_OK;
1092 } 1088 }
1093 back += (1 << 14) - 1; 1089 back += (1 << 14) - 1;
@@ -1137,16 +1133,16 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool
1137 if (_h.SeveralMethods) 1133 if (_h.SeveralMethods)
1138 { 1134 {
1139 Byte b; 1135 Byte b;
1140 RINOK(ReadStream_FALSE(_stream, &b, 1)); 1136 RINOK(ReadStream_FALSE(_stream, &b, 1))
1141 RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)); 1137 RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL))
1142 method = (b == 0x5D ? kMethod_LZMA : kMethod_ZLIB); 1138 method = (b == 0x5D ? kMethod_LZMA : kMethod_ZLIB);
1143 } 1139 }
1144 1140
1145 if (method == kMethod_ZLIB && _needCheckLzma) 1141 if (method == kMethod_ZLIB && _needCheckLzma)
1146 { 1142 {
1147 Byte b; 1143 Byte b;
1148 RINOK(ReadStream_FALSE(_stream, &b, 1)); 1144 RINOK(ReadStream_FALSE(_stream, &b, 1))
1149 RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL)); 1145 RINOK(_stream->Seek(-1, STREAM_SEEK_CUR, NULL))
1150 if (b == 0) 1146 if (b == 0)
1151 { 1147 {
1152 _noPropsLZMA = true; 1148 _noPropsLZMA = true;
@@ -1162,7 +1158,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool
1162 _zlibDecoderSpec = new NCompress::NZlib::CDecoder(); 1158 _zlibDecoderSpec = new NCompress::NZlib::CDecoder();
1163 _zlibDecoder = _zlibDecoderSpec; 1159 _zlibDecoder = _zlibDecoderSpec;
1164 } 1160 }
1165 RINOK(_zlibDecoder->Code(_limitedInStream, outStream, NULL, NULL, NULL)); 1161 RINOK(_zlibDecoder->Code(_limitedInStream, outStream, NULL, NULL, NULL))
1166 if (inSize != _zlibDecoderSpec->GetInputProcessedSize()) 1162 if (inSize != _zlibDecoderSpec->GetInputProcessedSize())
1167 return S_FALSE; 1163 return S_FALSE;
1168 } 1164 }
@@ -1204,7 +1200,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool
1204 { 1200 {
1205 if (_inputBuffer.Size() < inSize) 1201 if (_inputBuffer.Size() < inSize)
1206 _inputBuffer.Alloc(inSize); 1202 _inputBuffer.Alloc(inSize);
1207 RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize)); 1203 RINOK(ReadStream_FALSE(_stream, _inputBuffer, inSize))
1208 1204
1209 Byte *dest = outBuf; 1205 Byte *dest = outBuf;
1210 if (!outBuf) 1206 if (!outBuf)
@@ -1218,7 +1214,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool
1218 1214
1219 if (method == kMethod_LZO) 1215 if (method == kMethod_LZO)
1220 { 1216 {
1221 RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen)); 1217 RINOK(LzoDecode(dest, &destLen, _inputBuffer, &srcLen))
1222 } 1218 }
1223 else if (method == kMethod_LZMA) 1219 else if (method == kMethod_LZMA)
1224 { 1220 {
@@ -1228,7 +1224,7 @@ HRESULT CHandler::Decompress(ISequentialOutStream *outStream, Byte *outBuf, bool
1228 if (_noPropsLZMA) 1224 if (_noPropsLZMA)
1229 { 1225 {
1230 props[0] = 0x5D; 1226 props[0] = 0x5D;
1231 SetUi32(&props[1], _h.BlockSize); 1227 SetUi32(&props[1], _h.BlockSize)
1232 } 1228 }
1233 else 1229 else
1234 { 1230 {
@@ -1289,7 +1285,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize)
1289 const unsigned offset = _h.NeedCheckData() ? 3 : 2; 1285 const unsigned offset = _h.NeedCheckData() ? 3 : 2;
1290 if (offset > packSize) 1286 if (offset > packSize)
1291 return S_FALSE; 1287 return S_FALSE;
1292 RINOK(ReadStream_FALSE(_stream, temp, offset)); 1288 RINOK(ReadStream_FALSE(_stream, temp, offset))
1293 // if (NeedCheckData && Major < 4) checkByte must be = 0xFF 1289 // if (NeedCheckData && Major < 4) checkByte must be = 0xFF
1294 const bool be = _h.be; 1290 const bool be = _h.be;
1295 UInt32 size = Get16(temp); 1291 UInt32 size = Get16(temp);
@@ -1303,7 +1299,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize)
1303 if (isCompressed) 1299 if (isCompressed)
1304 { 1300 {
1305 _limitedInStreamSpec->Init(size); 1301 _limitedInStreamSpec->Init(size);
1306 RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize)); 1302 RINOK(Decompress(_dynOutStream, NULL, NULL, NULL, size, kMetadataBlockSize))
1307 } 1303 }
1308 else 1304 else
1309 { 1305 {
@@ -1311,7 +1307,7 @@ HRESULT CHandler::ReadMetadataBlock(UInt32 &packSize)
1311 Byte *buf = _dynOutStreamSpec->GetBufPtrForWriting(size); 1307 Byte *buf = _dynOutStreamSpec->GetBufPtrForWriting(size);
1312 if (!buf) 1308 if (!buf)
1313 return E_OUTOFMEMORY; 1309 return E_OUTOFMEMORY;
1314 RINOK(ReadStream_FALSE(_stream, buf, size)); 1310 RINOK(ReadStream_FALSE(_stream, buf, size))
1315 _dynOutStreamSpec->UpdateSize(size); 1311 _dynOutStreamSpec->UpdateSize(size);
1316 } 1312 }
1317 return S_OK; 1313 return S_OK;
@@ -1330,7 +1326,7 @@ HRESULT CHandler::ReadData(CData &data, UInt64 start, UInt64 end)
1330 if (end < start || end - start >= ((UInt64)1 << 32)) 1326 if (end < start || end - start >= ((UInt64)1 << 32))
1331 return S_FALSE; 1327 return S_FALSE;
1332 const UInt32 size = (UInt32)(end - start); 1328 const UInt32 size = (UInt32)(end - start);
1333 RINOK(Seek2(start)); 1329 RINOK(Seek2(start))
1334 _dynOutStreamSpec->Init(); 1330 _dynOutStreamSpec->Init();
1335 UInt32 packPos = 0; 1331 UInt32 packPos = 0;
1336 while (packPos != size) 1332 while (packPos != size)
@@ -1340,7 +1336,7 @@ HRESULT CHandler::ReadData(CData &data, UInt64 start, UInt64 end)
1340 if (packPos > size) 1336 if (packPos > size)
1341 return S_FALSE; 1337 return S_FALSE;
1342 UInt32 packSize = size - packPos; 1338 UInt32 packSize = size - packPos;
1343 RINOK(ReadMetadataBlock(packSize)); 1339 RINOK(ReadMetadataBlock(packSize))
1344 { 1340 {
1345 const size_t tSize = _dynOutStreamSpec->GetSize(); 1341 const size_t tSize = _dynOutStreamSpec->GetSize();
1346 if (tSize != (UInt32)tSize) 1342 if (tSize != (UInt32)tSize)
@@ -1466,7 +1462,7 @@ HRESULT CHandler::OpenDir(int parent, UInt32 startBlock, UInt32 offset, unsigned
1466 UInt64 numFiles = _items.Size(); 1462 UInt64 numFiles = _items.Size();
1467 if ((numFiles & 0xFFFF) == 0) 1463 if ((numFiles & 0xFFFF) == 0)
1468 { 1464 {
1469 RINOK(_openCallback->SetCompleted(&numFiles, NULL)); 1465 RINOK(_openCallback->SetCompleted(&numFiles, NULL))
1470 } 1466 }
1471 } 1467 }
1472 1468
@@ -1521,13 +1517,13 @@ HRESULT CHandler::OpenDir(int parent, UInt32 startBlock, UInt32 offset, unsigned
1521 } 1517 }
1522 } 1518 }
1523 1519
1524 int startItemIndex = _items.Size() - tempItems.Size(); 1520 const unsigned startItemIndex = _items.Size() - tempItems.Size();
1525 FOR_VECTOR (i, tempItems) 1521 FOR_VECTOR (i, tempItems)
1526 { 1522 {
1527 const CTempItem &tempItem = tempItems[i]; 1523 const CTempItem &tempItem = tempItems[i];
1528 int index = startItemIndex + i; 1524 const unsigned index = startItemIndex + i;
1529 CItem &item = _items[index]; 1525 CItem &item = _items[index];
1530 RINOK(OpenDir(index, tempItem.StartBlock, tempItem.Offset, level + 1, item.Node)); 1526 RINOK(OpenDir((int)index, tempItem.StartBlock, tempItem.Offset, level + 1, item.Node))
1531 } 1527 }
1532 1528
1533 return S_OK; 1529 return S_OK;
@@ -1539,7 +1535,7 @@ HRESULT CHandler::ReadUids(UInt64 start, UInt32 num, CByteBuffer &ids)
1539 ids.Alloc(size); 1535 ids.Alloc(size);
1540 if (num == 0) 1536 if (num == 0)
1541 return S_OK; 1537 return S_OK;
1542 RINOK(Seek2(start)); 1538 RINOK(Seek2(start))
1543 return ReadStream_FALSE(_stream, ids, size); 1539 return ReadStream_FALSE(_stream, ids, size);
1544} 1540}
1545 1541
@@ -1547,7 +1543,7 @@ HRESULT CHandler::Open2(IInStream *inStream)
1547{ 1543{
1548 { 1544 {
1549 Byte buf[kHeaderSize3]; 1545 Byte buf[kHeaderSize3];
1550 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize3)); 1546 RINOK(ReadStream_FALSE(inStream, buf, kHeaderSize3))
1551 if (!_h.Parse(buf)) 1547 if (!_h.Parse(buf))
1552 return S_FALSE; 1548 return S_FALSE;
1553 if (!_h.IsSupported()) 1549 if (!_h.IsSupported())
@@ -1580,15 +1576,15 @@ HRESULT CHandler::Open2(IInStream *inStream)
1580 const UInt32 numBlocks = (_h.NumFrags + (1 << fragPtrsInBlockLog) - 1) >> fragPtrsInBlockLog; 1576 const UInt32 numBlocks = (_h.NumFrags + (1 << fragPtrsInBlockLog) - 1) >> fragPtrsInBlockLog;
1581 const size_t numBlocksBytes = (size_t)numBlocks << (2 + bigFrag); 1577 const size_t numBlocksBytes = (size_t)numBlocks << (2 + bigFrag);
1582 CByteBuffer data(numBlocksBytes); 1578 CByteBuffer data(numBlocksBytes);
1583 RINOK(Seek2(_h.FragTable)); 1579 RINOK(Seek2(_h.FragTable))
1584 RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes)); 1580 RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes))
1585 const bool be = _h.be; 1581 const bool be = _h.be;
1586 1582
1587 for (UInt32 i = 0; i < numBlocks; i++) 1583 for (UInt32 i = 0; i < numBlocks; i++)
1588 { 1584 {
1589 const UInt64 offset = bigFrag ? Get64(data + i * 8) : Get32(data + i * 4); 1585 const UInt64 offset = bigFrag ? Get64(data + i * 8) : Get32(data + i * 4);
1590 RINOK(Seek2(offset)); 1586 RINOK(Seek2(offset))
1591 RINOK(ReadMetadataBlock2()); 1587 RINOK(ReadMetadataBlock2())
1592 const UInt32 unpackSize = (UInt32)_dynOutStreamSpec->GetSize(); 1588 const UInt32 unpackSize = (UInt32)_dynOutStreamSpec->GetSize();
1593 if (unpackSize != kMetadataBlockSize) 1589 if (unpackSize != kMetadataBlockSize)
1594 if (i != numBlocks - 1 || unpackSize != ((_h.NumFrags << (3 + bigFrag)) & (kMetadataBlockSize - 1))) 1590 if (i != numBlocks - 1 || unpackSize != ((_h.NumFrags << (3 + bigFrag)) & (kMetadataBlockSize - 1)))
@@ -1617,8 +1613,8 @@ HRESULT CHandler::Open2(IInStream *inStream)
1617 return S_FALSE; 1613 return S_FALSE;
1618 } 1614 }
1619 1615
1620 RINOK(ReadData(_inodesData, _h.InodeTable, _h.DirTable)); 1616 RINOK(ReadData(_inodesData, _h.InodeTable, _h.DirTable))
1621 RINOK(ReadData(_dirs, _h.DirTable, _h.FragTable)); 1617 RINOK(ReadData(_dirs, _h.DirTable, _h.FragTable))
1622 1618
1623 UInt64 absOffset = _h.RootInode >> 16; 1619 UInt64 absOffset = _h.RootInode >> 16;
1624 if (absOffset >= ((UInt64)1 << 32)) 1620 if (absOffset >= ((UInt64)1 << 32))
@@ -1663,12 +1659,12 @@ HRESULT CHandler::Open2(IInStream *inStream)
1663 return S_FALSE; 1659 return S_FALSE;
1664 } 1660 }
1665 int rootNodeIndex; 1661 int rootNodeIndex;
1666 RINOK(OpenDir(-1, (UInt32)absOffset, (UInt32)_h.RootInode & 0xFFFF, 0, rootNodeIndex)); 1662 RINOK(OpenDir(-1, (UInt32)absOffset, (UInt32)_h.RootInode & 0xFFFF, 0, rootNodeIndex))
1667 1663
1668 if (_h.Major < 4) 1664 if (_h.Major < 4)
1669 { 1665 {
1670 RINOK(ReadUids(_h.UidTable, _h.NumUids, _uids)); 1666 RINOK(ReadUids(_h.UidTable, _h.NumUids, _uids))
1671 RINOK(ReadUids(_h.GidTable, _h.NumGids, _gids)); 1667 RINOK(ReadUids(_h.GidTable, _h.NumGids, _gids))
1672 } 1668 }
1673 else 1669 else
1674 { 1670 {
@@ -1677,29 +1673,29 @@ HRESULT CHandler::Open2(IInStream *inStream)
1677 1673
1678 const UInt32 numBlocks = (size + kMetadataBlockSize - 1) / kMetadataBlockSize; 1674 const UInt32 numBlocks = (size + kMetadataBlockSize - 1) / kMetadataBlockSize;
1679 const UInt32 numBlocksBytes = numBlocks << 3; 1675 const UInt32 numBlocksBytes = numBlocks << 3;
1680 CByteBuffer data; 1676 CByteBuffer data(numBlocksBytes);
1681 data.Alloc(numBlocksBytes); 1677 RINOK(Seek2(_h.UidTable))
1682 RINOK(Seek2(_h.UidTable)); 1678 RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes))
1683 RINOK(ReadStream_FALSE(inStream, data, numBlocksBytes));
1684 1679
1685 for (UInt32 i = 0; i < numBlocks; i++) 1680 for (UInt32 i = 0; i < numBlocks; i++)
1686 { 1681 {
1687 const UInt64 offset = GetUi64(data + i * 8); 1682 const UInt64 offset = GetUi64(data + i * 8);
1688 RINOK(Seek2(offset)); 1683 RINOK(Seek2(offset))
1689 // RINOK(ReadMetadataBlock(NULL, _uids + kMetadataBlockSize * i, packSize, unpackSize)); 1684 // RINOK(ReadMetadataBlock(NULL, _uids + kMetadataBlockSize * i, packSize, unpackSize));
1690 RINOK(ReadMetadataBlock2()); 1685 RINOK(ReadMetadataBlock2())
1691 const size_t unpackSize = _dynOutStreamSpec->GetSize(); 1686 const size_t unpackSize = _dynOutStreamSpec->GetSize();
1692 if (unpackSize != kMetadataBlockSize) 1687 const UInt32 remSize = (i == numBlocks - 1) ?
1693 if (i != numBlocks - 1 || unpackSize != (size & (kMetadataBlockSize - 1))) 1688 (size & (kMetadataBlockSize - 1)) : kMetadataBlockSize;
1694 return S_FALSE; 1689 if (unpackSize != remSize)
1695 memcpy(_uids + kMetadataBlockSize * i, _dynOutStreamSpec->GetBuffer(), unpackSize); 1690 return S_FALSE;
1691 memcpy(_uids + kMetadataBlockSize * i, _dynOutStreamSpec->GetBuffer(), remSize);
1696 } 1692 }
1697 } 1693 }
1698 1694
1699 { 1695 {
1700 const UInt32 alignSize = 1 << 12; 1696 const UInt32 alignSize = 1 << 12;
1701 Byte buf[alignSize]; 1697 Byte buf[alignSize];
1702 RINOK(Seek2(_h.Size)); 1698 RINOK(Seek2(_h.Size))
1703 UInt32 rem = (UInt32)(0 - _h.Size) & (alignSize - 1); 1699 UInt32 rem = (UInt32)(0 - _h.Size) & (alignSize - 1);
1704 _sizeCalculated = _h.Size; 1700 _sizeCalculated = _h.Size;
1705 if (rem != 0) 1701 if (rem != 0)
@@ -1716,23 +1712,24 @@ HRESULT CHandler::Open2(IInStream *inStream)
1716 return S_OK; 1712 return S_OK;
1717} 1713}
1718 1714
1719AString CHandler::GetPath(int index) const 1715AString CHandler::GetPath(unsigned index) const
1720{ 1716{
1721 unsigned len = 0; 1717 unsigned len = 0;
1722 int indexMem = index; 1718 const unsigned indexMem = index;
1723 const bool be = _h.be; 1719 const bool be = _h.be;
1724 do 1720 for (;;)
1725 { 1721 {
1726 const CItem &item = _items[index]; 1722 const CItem &item = _items[index];
1727 index = item.Parent;
1728 const Byte *p = _dirs.Data + item.Ptr; 1723 const Byte *p = _dirs.Data + item.Ptr;
1729 unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; 1724 const unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1;
1730 p += _h.GetFileNameOffset(); 1725 p += _h.GetFileNameOffset();
1731 unsigned i; 1726 unsigned i;
1732 for (i = 0; i < size && p[i]; i++); 1727 for (i = 0; i < size && p[i]; i++);
1733 len += i + 1; 1728 len += i + 1;
1729 index = (unsigned)item.Parent;
1730 if (item.Parent < 0)
1731 break;
1734 } 1732 }
1735 while (index >= 0);
1736 len--; 1733 len--;
1737 1734
1738 AString path; 1735 AString path;
@@ -1741,22 +1738,22 @@ AString CHandler::GetPath(int index) const
1741 for (;;) 1738 for (;;)
1742 { 1739 {
1743 const CItem &item = _items[index]; 1740 const CItem &item = _items[index];
1744 index = item.Parent;
1745 const Byte *p = _dirs.Data + item.Ptr; 1741 const Byte *p = _dirs.Data + item.Ptr;
1746 unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1; 1742 const unsigned size = (_h.IsOldVersion() ? (unsigned)p[2] : (unsigned)Get16(p + 6)) + 1;
1747 p += _h.GetFileNameOffset(); 1743 p += _h.GetFileNameOffset();
1748 unsigned i; 1744 unsigned i;
1749 for (i = 0; i < size && p[i]; i++); 1745 for (i = 0; i < size && p[i]; i++);
1750 dest -= i; 1746 dest -= i;
1751 memcpy(dest, p, i); 1747 memcpy(dest, p, i);
1752 if (index < 0) 1748 index = (unsigned)item.Parent;
1749 if (item.Parent < 0)
1753 break; 1750 break;
1754 *(--dest) = CHAR_PATH_SEPARATOR; 1751 *(--dest) = CHAR_PATH_SEPARATOR;
1755 } 1752 }
1756 return path; 1753 return path;
1757} 1754}
1758 1755
1759STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 1756Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
1760{ 1757{
1761 COM_TRY_BEGIN 1758 COM_TRY_BEGIN
1762 { 1759 {
@@ -1784,7 +1781,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
1784 COM_TRY_END 1781 COM_TRY_END
1785} 1782}
1786 1783
1787STDMETHODIMP CHandler::Close() 1784Z7_COM7F_IMF(CHandler::Close())
1788{ 1785{
1789 _openCodePage = CP_UTF8; 1786 _openCodePage = CP_UTF8;
1790 _sizeCalculated = 0; 1787 _sizeCalculated = 0;
@@ -1800,8 +1797,8 @@ STDMETHODIMP CHandler::Close()
1800 _inodesData.Clear(); 1797 _inodesData.Clear();
1801 _dirs.Clear(); 1798 _dirs.Clear();
1802 1799
1803 // _uids.Free(); 1800 _uids.Free();
1804 // _gids.Free();; 1801 _gids.Free();
1805 1802
1806 _cachedBlock.Free(); 1803 _cachedBlock.Free();
1807 ClearCache(); 1804 ClearCache();
@@ -1809,7 +1806,7 @@ STDMETHODIMP CHandler::Close()
1809 return S_OK; 1806 return S_OK;
1810} 1807}
1811 1808
1812bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets) 1809bool CHandler::GetPackSize(unsigned index, UInt64 &totalPack, bool fillOffsets)
1813{ 1810{
1814 totalPack = 0; 1811 totalPack = 0;
1815 const CItem &item = _items[index]; 1812 const CItem &item = _items[index];
@@ -1818,7 +1815,7 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets)
1818 const Byte *p = _inodesData.Data + ptr; 1815 const Byte *p = _inodesData.Data + ptr;
1819 const bool be = _h.be; 1816 const bool be = _h.be;
1820 1817
1821 UInt32 type = node.Type; 1818 const UInt32 type = node.Type;
1822 UInt32 offset; 1819 UInt32 offset;
1823 if (node.IsLink() || node.FileSize == 0) 1820 if (node.IsLink() || node.FileSize == 0)
1824 { 1821 {
@@ -1826,7 +1823,7 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets)
1826 return true; 1823 return true;
1827 } 1824 }
1828 1825
1829 UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h); 1826 const UInt32 numBlocks = (UInt32)node.GetNumBlocks(_h);
1830 1827
1831 if (fillOffsets) 1828 if (fillOffsets)
1832 { 1829 {
@@ -1896,13 +1893,13 @@ bool CHandler::GetPackSize(int index, UInt64 &totalPack, bool fillOffsets)
1896} 1893}
1897 1894
1898 1895
1899STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1896Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1900{ 1897{
1901 *numItems = _items.Size(); 1898 *numItems = _items.Size();
1902 return S_OK; 1899 return S_OK;
1903} 1900}
1904 1901
1905STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1902Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1906{ 1903{
1907 COM_TRY_BEGIN 1904 COM_TRY_BEGIN
1908 NWindows::NCOM::CPropVariant prop; 1905 NWindows::NCOM::CPropVariant prop;
@@ -1919,7 +1916,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1919 else 1916 else
1920 { 1917 {
1921 s = NULL; 1918 s = NULL;
1922 if (_h.Method < ARRAY_SIZE(k_Methods)) 1919 if (_h.Method < Z7_ARRAY_SIZE(k_Methods))
1923 s = k_Methods[_h.Method]; 1920 s = k_Methods[_h.Method];
1924 if (!s) 1921 if (!s)
1925 { 1922 {
@@ -1937,7 +1934,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1937 res += "-LZMA"; 1934 res += "-LZMA";
1938 res.Add_Space(); 1935 res.Add_Space();
1939 res.Add_UInt32(_h.Major); 1936 res.Add_UInt32(_h.Major);
1940 res += '.'; 1937 res.Add_Dot();
1941 res.Add_UInt32(_h.Minor); 1938 res.Add_UInt32(_h.Minor);
1942 prop = res; 1939 prop = res;
1943 break; 1940 break;
@@ -1979,7 +1976,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1979 COM_TRY_END 1976 COM_TRY_END
1980} 1977}
1981 1978
1982STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 1979Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
1983{ 1980{
1984 COM_TRY_BEGIN 1981 COM_TRY_BEGIN
1985 NWindows::NCOM::CPropVariant prop; 1982 NWindows::NCOM::CPropVariant prop;
@@ -2043,40 +2040,29 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2043 } 2040 }
2044 case kpidPosixAttrib: 2041 case kpidPosixAttrib:
2045 { 2042 {
2046 if (node.Type != 0 && node.Type < ARRAY_SIZE(k_TypeToMode)) 2043 if (node.Type != 0 && node.Type < Z7_ARRAY_SIZE(k_TypeToMode))
2047 prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type]; 2044 prop = (UInt32)(node.Mode & 0xFFF) | k_TypeToMode[node.Type];
2048 break; 2045 break;
2049 } 2046 }
2050 case kpidUserId: 2047 case kpidUserId:
2051 {
2052 const UInt32 offset = (UInt32)node.Uid * 4;
2053 if (offset < _uids.Size())
2054 prop = (UInt32)Get32(_uids + offset);
2055 break;
2056 }
2057 case kpidGroupId: 2048 case kpidGroupId:
2058 { 2049 {
2059 if (_h.Major < 4) 2050 UInt32 id = node.Uid;
2051 const CByteBuffer *ids = &_uids;
2052 if (propID == kpidGroupId)
2060 { 2053 {
2061 if (node.Gid == _h.GetSpecGuidIndex()) 2054 id = node.Gid;
2062 { 2055 if (_h.Major < 4)
2063 const UInt32 offset = (UInt32)node.Uid * 4;
2064 if (offset < _uids.Size())
2065 prop = (UInt32)Get32(_uids + offset);
2066 }
2067 else
2068 { 2056 {
2069 const UInt32 offset = (UInt32)node.Gid * 4; 2057 if (id == _h.GetSpecGuidIndex())
2070 if (offset < _gids.Size()) 2058 id = node.Uid;
2071 prop = (UInt32)Get32(_gids + offset); 2059 else
2060 ids = &_gids;
2072 } 2061 }
2073 } 2062 }
2074 else 2063 const UInt32 offset = (UInt32)id * 4;
2075 { 2064 if (offset < ids->Size())
2076 const UInt32 offset = (UInt32)node.Gid * 4; 2065 prop = (UInt32)Get32(*ids + offset);
2077 if (offset < _uids.Size())
2078 prop = (UInt32)Get32(_uids + offset);
2079 }
2080 break; 2066 break;
2081 } 2067 }
2082 /* 2068 /*
@@ -2093,7 +2079,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
2093 2079
2094class CSquashfsInStream: public CCachedInStream 2080class CSquashfsInStream: public CCachedInStream
2095{ 2081{
2096 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize); 2082 HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) Z7_override;
2097public: 2083public:
2098 CHandler *Handler; 2084 CHandler *Handler;
2099}; 2085};
@@ -2139,7 +2125,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize)
2139 packBlockSize != _cachedPackBlockSize) 2125 packBlockSize != _cachedPackBlockSize)
2140 { 2126 {
2141 ClearCache(); 2127 ClearCache();
2142 RINOK(Seek2(blockOffset)); 2128 RINOK(Seek2(blockOffset))
2143 _limitedInStreamSpec->Init(packBlockSize); 2129 _limitedInStreamSpec->Init(packBlockSize);
2144 2130
2145 if (compressed) 2131 if (compressed)
@@ -2148,7 +2134,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize)
2148 bool outBufWasWritten; 2134 bool outBufWasWritten;
2149 UInt32 outBufWasWrittenSize; 2135 UInt32 outBufWasWrittenSize;
2150 HRESULT res = Decompress(_outStream, _cachedBlock, &outBufWasWritten, &outBufWasWrittenSize, packBlockSize, _h.BlockSize); 2136 HRESULT res = Decompress(_outStream, _cachedBlock, &outBufWasWritten, &outBufWasWrittenSize, packBlockSize, _h.BlockSize);
2151 RINOK(res); 2137 RINOK(res)
2152 if (outBufWasWritten) 2138 if (outBufWasWritten)
2153 _cachedUnpackBlockSize = outBufWasWrittenSize; 2139 _cachedUnpackBlockSize = outBufWasWrittenSize;
2154 else 2140 else
@@ -2158,7 +2144,7 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize)
2158 { 2144 {
2159 if (packBlockSize > _h.BlockSize) 2145 if (packBlockSize > _h.BlockSize)
2160 return S_FALSE; 2146 return S_FALSE;
2161 RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize)); 2147 RINOK(ReadStream_FALSE(_limitedInStream, _cachedBlock, packBlockSize))
2162 _cachedUnpackBlockSize = packBlockSize; 2148 _cachedUnpackBlockSize = packBlockSize;
2163 } 2149 }
2164 _cachedBlockStartPos = blockOffset; 2150 _cachedBlockStartPos = blockOffset;
@@ -2171,11 +2157,11 @@ HRESULT CHandler::ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize)
2171 return S_OK; 2157 return S_OK;
2172} 2158}
2173 2159
2174STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 2160Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2175 Int32 testMode, IArchiveExtractCallback *extractCallback) 2161 Int32 testMode, IArchiveExtractCallback *extractCallback))
2176{ 2162{
2177 COM_TRY_BEGIN 2163 COM_TRY_BEGIN
2178 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 2164 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
2179 if (allFilesMode) 2165 if (allFilesMode)
2180 numItems = _items.Size(); 2166 numItems = _items.Size();
2181 if (numItems == 0) 2167 if (numItems == 0)
@@ -2204,21 +2190,21 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2204 { 2190 {
2205 lps->InSize = totalPackSize; 2191 lps->InSize = totalPackSize;
2206 lps->OutSize = totalSize; 2192 lps->OutSize = totalSize;
2207 RINOK(lps->SetCur()); 2193 RINOK(lps->SetCur())
2208 CMyComPtr<ISequentialOutStream> outStream; 2194 CMyComPtr<ISequentialOutStream> outStream;
2209 Int32 askMode = testMode ? 2195 const Int32 askMode = testMode ?
2210 NExtract::NAskMode::kTest : 2196 NExtract::NAskMode::kTest :
2211 NExtract::NAskMode::kExtract; 2197 NExtract::NAskMode::kExtract;
2212 UInt32 index = allFilesMode ? i : indices[i]; 2198 const UInt32 index = allFilesMode ? i : indices[i];
2213 const CItem &item = _items[index]; 2199 const CItem &item = _items[index];
2214 const CNode &node = _nodes[item.Node]; 2200 const CNode &node = _nodes[item.Node];
2215 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 2201 RINOK(extractCallback->GetStream(index, &outStream, askMode))
2216 // const Byte *p = _data + item.Offset; 2202 // const Byte *p = _data + item.Offset;
2217 2203
2218 if (node.IsDir()) 2204 if (node.IsDir())
2219 { 2205 {
2220 RINOK(extractCallback->PrepareOperation(askMode)); 2206 RINOK(extractCallback->PrepareOperation(askMode))
2221 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 2207 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
2222 continue; 2208 continue;
2223 } 2209 }
2224 UInt64 unpackSize = node.GetSize(); 2210 UInt64 unpackSize = node.GetSize();
@@ -2229,7 +2215,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2229 2215
2230 if (!testMode && !outStream) 2216 if (!testMode && !outStream)
2231 continue; 2217 continue;
2232 RINOK(extractCallback->PrepareOperation(askMode)); 2218 RINOK(extractCallback->PrepareOperation(askMode))
2233 2219
2234 int res = NExtract::NOperationResult::kDataError; 2220 int res = NExtract::NOperationResult::kDataError;
2235 { 2221 {
@@ -2243,7 +2229,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2243 } 2229 }
2244 else 2230 else
2245 { 2231 {
2246 RINOK(hres); 2232 RINOK(hres)
2247 { 2233 {
2248 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress); 2234 hres = copyCoder->Code(inSeqStream, outStream, NULL, NULL, progress);
2249 if (hres == S_OK) 2235 if (hres == S_OK)
@@ -2257,13 +2243,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2257 } 2243 }
2258 else if (hres != S_FALSE) 2244 else if (hres != S_FALSE)
2259 { 2245 {
2260 RINOK(hres); 2246 RINOK(hres)
2261 } 2247 }
2262 } 2248 }
2263 } 2249 }
2264 } 2250 }
2265 2251
2266 RINOK(extractCallback->SetOperationResult(res)); 2252 RINOK(extractCallback->SetOperationResult(res))
2267 } 2253 }
2268 2254
2269 return S_OK; 2255 return S_OK;
@@ -2271,7 +2257,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
2271} 2257}
2272 2258
2273 2259
2274STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 2260Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
2275{ 2261{
2276 COM_TRY_BEGIN 2262 COM_TRY_BEGIN
2277 2263
@@ -2331,7 +2317,7 @@ static const Byte k_Signature[] = {
2331 4, 'q', 's', 'h', 's' }; 2317 4, 'q', 's', 'h', 's' };
2332 2318
2333REGISTER_ARC_I( 2319REGISTER_ARC_I(
2334 "SquashFS", "squashfs", 0, 0xD2, 2320 "SquashFS", "squashfs", NULL, 0xD2,
2335 k_Signature, 2321 k_Signature,
2336 0, 2322 0,
2337 NArcInfoFlags::kMultiSignature, 2323 NArcInfoFlags::kMultiSignature,
diff --git a/CPP/7zip/Archive/StdAfx.h b/CPP/7zip/Archive/StdAfx.h
index 1cbd7fe..8086655 100644
--- a/CPP/7zip/Archive/StdAfx.h
+++ b/CPP/7zip/Archive/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../Common/Common.h" 9#include "../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/SwfHandler.cpp b/CPP/7zip/Archive/SwfHandler.cpp
index a5ff187..ab704b6 100644
--- a/CPP/7zip/Archive/SwfHandler.cpp
+++ b/CPP/7zip/Archive/SwfHandler.cpp
@@ -25,9 +25,9 @@
25 25
26#include "Common/DummyOutStream.h" 26#include "Common/DummyOutStream.h"
27 27
28// #define SWF_UPDATE 28// #define Z7_SWF_UPDATE
29 29
30#ifdef SWF_UPDATE 30#ifdef Z7_SWF_UPDATE
31 31
32#include "../Compress/LzmaEncoder.h" 32#include "../Compress/LzmaEncoder.h"
33#include "../Compress/ZlibEncoder.h" 33#include "../Compress/ZlibEncoder.h"
@@ -142,7 +142,7 @@ struct CItem
142 Buf[0] = SWF_COMPRESSED_LZMA; 142 Buf[0] = SWF_COMPRESSED_LZMA;
143 if (Buf[3] < SWF_MIN_COMPRESSED_LZMA_VER) 143 if (Buf[3] < SWF_MIN_COMPRESSED_LZMA_VER)
144 Buf[3] = SWF_MIN_COMPRESSED_LZMA_VER; 144 Buf[3] = SWF_MIN_COMPRESSED_LZMA_VER;
145 SetUi32(Buf + 8, packSize); 145 SetUi32(Buf + 8, packSize)
146 HeaderSize = kHeaderLzmaSize; 146 HeaderSize = kHeaderLzmaSize;
147 } 147 }
148 148
@@ -157,37 +157,37 @@ struct CItem
157 } 157 }
158}; 158};
159 159
160class CHandler: 160
161Z7_class_CHandler_final:
161 public IInArchive, 162 public IInArchive,
162 public IArchiveOpenSeq, 163 public IArchiveOpenSeq,
163 #ifdef SWF_UPDATE 164 #ifdef Z7_SWF_UPDATE
164 public IOutArchive, 165 public IOutArchive,
165 public ISetProperties, 166 public ISetProperties,
166 #endif 167 #endif
167 public CMyUnknownImp 168 public CMyUnknownImp
168{ 169{
170 #ifdef Z7_SWF_UPDATE
171 Z7_IFACES_IMP_UNK_4(IInArchive, IArchiveOpenSeq, IOutArchive, ISetProperties)
172 #else
173 Z7_IFACES_IMP_UNK_2(IInArchive, IArchiveOpenSeq)
174 #endif
175
169 CItem _item; 176 CItem _item;
170 UInt64 _packSize; 177 UInt64 _packSize;
171 bool _packSizeDefined; 178 bool _packSizeDefined;
172 CMyComPtr<ISequentialInStream> _seqStream; 179 CMyComPtr<ISequentialInStream> _seqStream;
173 CMyComPtr<IInStream> _stream; 180 CMyComPtr<IInStream> _stream;
174 181
175 #ifdef SWF_UPDATE 182 #ifdef Z7_SWF_UPDATE
176 CSingleMethodProps _props; 183 CSingleMethodProps _props;
177 bool _lzmaMode; 184 bool _lzmaMode;
178 #endif 185 #endif
179 186
180public: 187public:
181 #ifdef SWF_UPDATE 188 #ifdef Z7_SWF_UPDATE
182 MY_UNKNOWN_IMP4(IInArchive, IArchiveOpenSeq, IOutArchive, ISetProperties)
183 CHandler(): _lzmaMode(false) {} 189 CHandler(): _lzmaMode(false) {}
184 INTERFACE_IOutArchive(;)
185 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
186 #else
187 MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq)
188 #endif 190 #endif
189 INTERFACE_IInArchive(;)
190 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
191}; 191};
192 192
193static const Byte kProps[] = 193static const Byte kProps[] =
@@ -200,7 +200,7 @@ static const Byte kProps[] =
200IMP_IInArchive_Props 200IMP_IInArchive_Props
201IMP_IInArchive_ArcProps_NO_Table 201IMP_IInArchive_ArcProps_NO_Table
202 202
203STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 203Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
204{ 204{
205 NCOM::CPropVariant prop; 205 NCOM::CPropVariant prop;
206 switch (propID) 206 switch (propID)
@@ -212,7 +212,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
212 return S_OK; 212 return S_OK;
213} 213}
214 214
215STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 215Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
216{ 216{
217 *numItems = 1; 217 *numItems = 1;
218 return S_OK; 218 return S_OK;
@@ -222,7 +222,7 @@ static void DicSizeToString(char *s, UInt32 val)
222{ 222{
223 char c = 0; 223 char c = 0;
224 unsigned i; 224 unsigned i;
225 for (i = 0; i <= 31; i++) 225 for (i = 0; i < 32; i++)
226 if (((UInt32)1 << i) == val) 226 if (((UInt32)1 << i) == val)
227 { 227 {
228 val = i; 228 val = i;
@@ -240,7 +240,7 @@ static void DicSizeToString(char *s, UInt32 val)
240 s[pos] = 0; 240 s[pos] = 0;
241} 241}
242 242
243STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 243Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
244{ 244{
245 NWindows::NCOM::CPropVariant prop; 245 NWindows::NCOM::CPropVariant prop;
246 switch (propID) 246 switch (propID)
@@ -265,22 +265,22 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
265 return S_OK; 265 return S_OK;
266} 266}
267 267
268STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *) 268Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *))
269{ 269{
270 RINOK(OpenSeq(stream)); 270 RINOK(OpenSeq(stream))
271 _stream = stream; 271 _stream = stream;
272 return S_OK; 272 return S_OK;
273} 273}
274 274
275STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 275Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
276{ 276{
277 Close(); 277 Close();
278 RINOK(_item.ReadHeader(stream)); 278 RINOK(_item.ReadHeader(stream))
279 if (!_item.IsSwf()) 279 if (!_item.IsSwf())
280 return S_FALSE; 280 return S_FALSE;
281 if (_item.IsLzma()) 281 if (_item.IsLzma())
282 { 282 {
283 RINOK(ReadStream_FALSE(stream, _item.Buf + kHeaderBaseSize, kHeaderLzmaSize - kHeaderBaseSize)); 283 RINOK(ReadStream_FALSE(stream, _item.Buf + kHeaderBaseSize, kHeaderLzmaSize - kHeaderBaseSize))
284 _item.HeaderSize = kHeaderLzmaSize; 284 _item.HeaderSize = kHeaderLzmaSize;
285 _packSize = _item.GetLzmaPackSize(); 285 _packSize = _item.GetLzmaPackSize();
286 _packSizeDefined = true; 286 _packSizeDefined = true;
@@ -293,7 +293,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
293 return S_OK; 293 return S_OK;
294} 294}
295 295
296STDMETHODIMP CHandler::Close() 296Z7_COM7F_IMF(CHandler::Close())
297{ 297{
298 _packSize = 0; 298 _packSize = 0;
299 _packSizeDefined = false; 299 _packSizeDefined = false;
@@ -302,31 +302,29 @@ STDMETHODIMP CHandler::Close()
302 return S_OK; 302 return S_OK;
303} 303}
304 304
305class CCompressProgressInfoImp: 305Z7_CLASS_IMP_COM_1(
306 public ICompressProgressInfo, 306 CCompressProgressInfoImp,
307 public CMyUnknownImp 307 ICompressProgressInfo
308{ 308)
309 CMyComPtr<IArchiveOpenCallback> Callback; 309 CMyComPtr<IArchiveOpenCallback> Callback;
310public: 310public:
311 UInt64 Offset; 311 UInt64 Offset;
312 MY_UNKNOWN_IMP1(ICompressProgressInfo)
313 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
314 void Init(IArchiveOpenCallback *callback) { Callback = callback; } 312 void Init(IArchiveOpenCallback *callback) { Callback = callback; }
315}; 313};
316 314
317STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) 315Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */))
318{ 316{
319 if (Callback) 317 if (Callback)
320 { 318 {
321 UInt64 files = 0; 319 const UInt64 files = 0;
322 UInt64 value = Offset + *inSize; 320 const UInt64 value = Offset + *inSize;
323 return Callback->SetCompleted(&files, &value); 321 return Callback->SetCompleted(&files, &value);
324 } 322 }
325 return S_OK; 323 return S_OK;
326} 324}
327 325
328STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 326Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
329 Int32 testMode, IArchiveExtractCallback *extractCallback) 327 Int32 testMode, IArchiveExtractCallback *extractCallback))
330{ 328{
331 COM_TRY_BEGIN 329 COM_TRY_BEGIN
332 if (numItems == 0) 330 if (numItems == 0)
@@ -334,12 +332,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
334 if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0)) 332 if (numItems != (UInt32)(Int32)-1 && (numItems != 1 || indices[0] != 0))
335 return E_INVALIDARG; 333 return E_INVALIDARG;
336 334
337 extractCallback->SetTotal(_item.GetSize()); 335 RINOK(extractCallback->SetTotal(_item.GetSize()))
338 CMyComPtr<ISequentialOutStream> realOutStream; 336 CMyComPtr<ISequentialOutStream> realOutStream;
339 Int32 askMode = testMode ? 337 const Int32 askMode = testMode ?
340 NExtract::NAskMode::kTest : 338 NExtract::NAskMode::kTest :
341 NExtract::NAskMode::kExtract; 339 NExtract::NAskMode::kExtract;
342 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 340 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
343 if (!testMode && !realOutStream) 341 if (!testMode && !realOutStream)
344 return S_OK; 342 return S_OK;
345 343
@@ -357,12 +355,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
357 355
358 lps->InSize = _item.HeaderSize; 356 lps->InSize = _item.HeaderSize;
359 lps->OutSize = outStreamSpec->GetSize(); 357 lps->OutSize = outStreamSpec->GetSize();
360 RINOK(lps->SetCur()); 358 RINOK(lps->SetCur())
361 359
362 CItem item = _item; 360 CItem item = _item;
363 item.MakeUncompressed(); 361 item.MakeUncompressed();
364 if (_stream) 362 if (_stream)
365 RINOK(_stream->Seek(_item.HeaderSize, STREAM_SEEK_SET, NULL)); 363 RINOK(InStream_SeekSet(_stream, _item.HeaderSize))
366 NCompress::NZlib::CDecoder *_decoderZlibSpec = NULL; 364 NCompress::NZlib::CDecoder *_decoderZlibSpec = NULL;
367 NCompress::NLzma::CDecoder *_decoderLzmaSpec = NULL; 365 NCompress::NLzma::CDecoder *_decoderLzmaSpec = NULL;
368 CMyComPtr<ICompressCoder> _decoder; 366 CMyComPtr<ICompressCoder> _decoder;
@@ -400,11 +398,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
400 if (dicSize > (UInt32)unpackSize) 398 if (dicSize > (UInt32)unpackSize)
401 { 399 {
402 dicSize = (UInt32)unpackSize; 400 dicSize = (UInt32)unpackSize;
403 SetUi32(props + 1, dicSize); 401 SetUi32(props + 1, dicSize)
404 } 402 }
405 RINOK(_decoderLzmaSpec->SetDecoderProperties2(props, 5)); 403 RINOK(_decoderLzmaSpec->SetDecoderProperties2(props, 5))
406 } 404 }
407 RINOK(item.WriteHeader(outStream)); 405 RINOK(item.WriteHeader(outStream))
408 HRESULT result = _decoder->Code(inStream2, outStream, NULL, &unpackSize, progress); 406 HRESULT result = _decoder->Code(inStream2, outStream, NULL, &unpackSize, progress);
409 Int32 opRes = NExtract::NOperationResult::kDataError; 407 Int32 opRes = NExtract::NOperationResult::kDataError;
410 if (result == S_OK) 408 if (result == S_OK)
@@ -433,18 +431,18 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
433} 431}
434 432
435 433
436#ifdef SWF_UPDATE 434#ifdef Z7_SWF_UPDATE
437 435
438static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size, 436static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size,
439 bool lzmaMode, const CSingleMethodProps &props, 437 bool lzmaMode, const CSingleMethodProps &props,
440 IArchiveUpdateCallback *updateCallback) 438 IArchiveUpdateCallback *updateCallback)
441{ 439{
442 UInt64 complexity = 0; 440 UInt64 complexity = 0;
443 RINOK(updateCallback->SetTotal(size)); 441 RINOK(updateCallback->SetTotal(size))
444 RINOK(updateCallback->SetCompleted(&complexity)); 442 RINOK(updateCallback->SetCompleted(&complexity))
445 443
446 CMyComPtr<ISequentialInStream> fileInStream; 444 CMyComPtr<ISequentialInStream> fileInStream;
447 RINOK(updateCallback->GetStream(0, &fileInStream)); 445 RINOK(updateCallback->GetStream(0, &fileInStream))
448 446
449 /* 447 /*
450 CDummyOutStream *outStreamSpec = new CDummyOutStream; 448 CDummyOutStream *outStreamSpec = new CDummyOutStream;
@@ -455,10 +453,10 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size,
455 */ 453 */
456 454
457 CItem item; 455 CItem item;
458 HRESULT res = item.ReadHeader(fileInStream); 456 const HRESULT res = item.ReadHeader(fileInStream);
459 if (res == S_FALSE) 457 if (res == S_FALSE)
460 return E_INVALIDARG; 458 return E_INVALIDARG;
461 RINOK(res); 459 RINOK(res)
462 if (!item.IsSwf() || !item.IsUncompressed() || size != item.GetSize()) 460 if (!item.IsSwf() || !item.IsUncompressed() || size != item.GetSize())
463 return E_INVALIDARG; 461 return E_INVALIDARG;
464 462
@@ -473,39 +471,39 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size,
473 return E_NOTIMPL; 471 return E_NOTIMPL;
474 encoderLzmaSpec = new NCompress::NLzma::CEncoder; 472 encoderLzmaSpec = new NCompress::NLzma::CEncoder;
475 encoder = encoderLzmaSpec; 473 encoder = encoderLzmaSpec;
476 RINOK(props.SetCoderProps(encoderLzmaSpec, &size)); 474 RINOK(props.SetCoderProps(encoderLzmaSpec, &size))
477 item.MakeLzma((UInt32)0xFFFFFFFF); 475 item.MakeLzma((UInt32)0xFFFFFFFF);
478 CBufPtrSeqOutStream *propStreamSpec = new CBufPtrSeqOutStream; 476 CBufPtrSeqOutStream *propStreamSpec = new CBufPtrSeqOutStream;
479 CMyComPtr<ISequentialOutStream> propStream = propStreamSpec; 477 CMyComPtr<ISequentialOutStream> propStream = propStreamSpec;
480 propStreamSpec->Init(item.Buf + 12, 5); 478 propStreamSpec->Init(item.Buf + 12, 5);
481 RINOK(encoderLzmaSpec->WriteCoderProperties(propStream)); 479 RINOK(encoderLzmaSpec->WriteCoderProperties(propStream))
482 } 480 }
483 else 481 else
484 { 482 {
485 encoderZlibSpec = new NCompress::NZlib::CEncoder; 483 encoderZlibSpec = new NCompress::NZlib::CEncoder;
486 encoder = encoderZlibSpec; 484 encoder = encoderZlibSpec;
487 encoderZlibSpec->Create(); 485 encoderZlibSpec->Create();
488 RINOK(props.SetCoderProps(encoderZlibSpec->DeflateEncoderSpec, NULL)); 486 RINOK(props.SetCoderProps(encoderZlibSpec->DeflateEncoderSpec, NULL))
489 item.MakeZlib(); 487 item.MakeZlib();
490 } 488 }
491 RINOK(item.WriteHeader(outStream)); 489 RINOK(item.WriteHeader(outStream))
492 490
493 CLocalProgress *lps = new CLocalProgress; 491 CLocalProgress *lps = new CLocalProgress;
494 CMyComPtr<ICompressProgressInfo> progress = lps; 492 CMyComPtr<ICompressProgressInfo> progress = lps;
495 lps->Init(updateCallback, true); 493 lps->Init(updateCallback, true);
496 494
497 RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress)); 495 RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress))
498 UInt64 inputProcessed; 496 UInt64 inputProcessed;
499 if (lzmaMode) 497 if (lzmaMode)
500 { 498 {
501 UInt64 curPos = 0; 499 UInt64 curPos = 0;
502 RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &curPos)); 500 RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &curPos))
503 UInt64 packSize = curPos - kHeaderLzmaSize; 501 const UInt64 packSize = curPos - kHeaderLzmaSize;
504 if (packSize > (UInt32)0xFFFFFFFF) 502 if (packSize > (UInt32)0xFFFFFFFF)
505 return E_INVALIDARG; 503 return E_INVALIDARG;
506 item.MakeLzma((UInt32)packSize); 504 item.MakeLzma((UInt32)packSize);
507 RINOK(outSeekStream->Seek(0, STREAM_SEEK_SET, NULL)); 505 RINOK(outSeekStream->Seek(0, STREAM_SEEK_SET, NULL))
508 item.WriteHeader(outStream); 506 RINOK(item.WriteHeader(outStream))
509 inputProcessed = encoderLzmaSpec->GetInputProcessedSize(); 507 inputProcessed = encoderLzmaSpec->GetInputProcessedSize();
510 } 508 }
511 else 509 else
@@ -517,14 +515,14 @@ static HRESULT UpdateArchive(ISequentialOutStream *outStream, UInt64 size,
517 return updateCallback->SetOperationResult(NUpdate::NOperationResult::kOK); 515 return updateCallback->SetOperationResult(NUpdate::NOperationResult::kOK);
518} 516}
519 517
520STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 518Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType))
521{ 519{
522 *timeType = NFileTimeType::kUnix; 520 *timeType = NFileTimeType::kUnix;
523 return S_OK; 521 return S_OK;
524} 522}
525 523
526STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 524Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
527 IArchiveUpdateCallback *updateCallback) 525 IArchiveUpdateCallback *updateCallback))
528{ 526{
529 if (numItems != 1) 527 if (numItems != 1)
530 return E_INVALIDARG; 528 return E_INVALIDARG;
@@ -533,13 +531,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
533 UInt32 indexInArchive; 531 UInt32 indexInArchive;
534 if (!updateCallback) 532 if (!updateCallback)
535 return E_FAIL; 533 return E_FAIL;
536 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); 534 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive))
537 535
538 if (IntToBool(newProps)) 536 if (IntToBool(newProps))
539 { 537 {
540 { 538 {
541 NCOM::CPropVariant prop; 539 NCOM::CPropVariant prop;
542 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); 540 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop))
543 if (prop.vt == VT_BOOL) 541 if (prop.vt == VT_BOOL)
544 { 542 {
545 if (prop.boolVal != VARIANT_FALSE) 543 if (prop.boolVal != VARIANT_FALSE)
@@ -555,7 +553,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
555 UInt64 size; 553 UInt64 size;
556 { 554 {
557 NCOM::CPropVariant prop; 555 NCOM::CPropVariant prop;
558 RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); 556 RINOK(updateCallback->GetProperty(0, kpidSize, &prop))
559 if (prop.vt != VT_UI8) 557 if (prop.vt != VT_UI8)
560 return E_INVALIDARG; 558 return E_INVALIDARG;
561 size = prop.uhVal.QuadPart; 559 size = prop.uhVal.QuadPart;
@@ -571,17 +569,17 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
571 569
572 if (_stream) 570 if (_stream)
573 { 571 {
574 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 572 RINOK(InStream_SeekToBegin(_stream))
575 } 573 }
576 else 574 else
577 _item.WriteHeader(outStream); 575 _item.WriteHeader(outStream);
578 return NCompress::CopyStream(_seqStream, outStream, NULL); 576 return NCompress::CopyStream(_seqStream, outStream, NULL);
579} 577}
580 578
581STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 579Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
582{ 580{
583 _lzmaMode = false; 581 _lzmaMode = false;
584 RINOK(_props.SetProperties(names, values, numProps)); 582 RINOK(_props.SetProperties(names, values, numProps))
585 const AString &m = _props.MethodName; 583 const AString &m = _props.MethodName;
586 if (m.IsEqualTo_Ascii_NoCase("lzma")) 584 if (m.IsEqualTo_Ascii_NoCase("lzma"))
587 { 585 {
@@ -621,22 +619,16 @@ struct CTag
621 CByteBuffer Buf; 619 CByteBuffer Buf;
622}; 620};
623 621
624class CHandler: 622
625 public IInArchive, 623Z7_CLASS_IMP_CHandler_IInArchive_1(
626 public IArchiveOpenSeq, 624 IArchiveOpenSeq
627 public CMyUnknownImp 625)
628{
629 CObjectVector<CTag> _tags; 626 CObjectVector<CTag> _tags;
630 NSwfc::CItem _item; 627 NSwfc::CItem _item;
631 UInt64 _phySize; 628 UInt64 _phySize;
632 629
633 HRESULT OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *callback); 630 HRESULT OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *callback);
634 HRESULT OpenSeq2(ISequentialInStream *stream, IArchiveOpenCallback *callback); 631 HRESULT OpenSeq2(ISequentialInStream *stream, IArchiveOpenCallback *callback);
635public:
636 MY_UNKNOWN_IMP2(IInArchive, IArchiveOpenSeq)
637 INTERFACE_IInArchive(;)
638
639 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
640}; 632};
641 633
642static const Byte kProps[] = 634static const Byte kProps[] =
@@ -649,7 +641,7 @@ static const Byte kProps[] =
649IMP_IInArchive_Props 641IMP_IInArchive_Props
650IMP_IInArchive_ArcProps_NO_Table 642IMP_IInArchive_ArcProps_NO_Table
651 643
652STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 644Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
653{ 645{
654 NCOM::CPropVariant prop; 646 NCOM::CPropVariant prop;
655 switch (propID) 647 switch (propID)
@@ -662,7 +654,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
662} 654}
663 655
664 656
665STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 657Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
666{ 658{
667 *numItems = _tags.Size(); 659 *numItems = _tags.Size();
668 return S_OK; 660 return S_OK;
@@ -764,7 +756,7 @@ static const char * const g_TagDesc[92] =
764 , "DefineFont4" 756 , "DefineFont4"
765}; 757};
766 758
767STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 759Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
768{ 760{
769 NWindows::NCOM::CPropVariant prop; 761 NWindows::NCOM::CPropVariant prop;
770 const CTag &tag = _tags[index]; 762 const CTag &tag = _tags[index];
@@ -791,7 +783,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
791 return S_OK; 783 return S_OK;
792} 784}
793 785
794STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 786Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
795{ 787{
796 return OpenSeq2(stream, callback); 788 return OpenSeq2(stream, callback);
797} 789}
@@ -867,7 +859,7 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca
867 RINOK(_item.ReadHeader(stream)) 859 RINOK(_item.ReadHeader(stream))
868 if (!_item.IsSwf() || !_item.IsUncompressed()) 860 if (!_item.IsSwf() || !_item.IsUncompressed())
869 return S_FALSE; 861 return S_FALSE;
870 UInt32 uncompressedSize = _item.GetSize(); 862 const UInt32 uncompressedSize = _item.GetSize();
871 if (uncompressedSize > kFileSizeMax) 863 if (uncompressedSize > kFileSizeMax)
872 return S_FALSE; 864 return S_FALSE;
873 865
@@ -880,7 +872,7 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca
880 { 872 {
881 CBitReader br; 873 CBitReader br;
882 br.stream = &s; 874 br.stream = &s;
883 unsigned numBits = br.ReadBits(5); 875 const unsigned numBits = br.ReadBits(5);
884 /* UInt32 xMin = */ br.ReadBits(numBits); 876 /* UInt32 xMin = */ br.ReadBits(numBits);
885 /* UInt32 xMax = */ br.ReadBits(numBits); 877 /* UInt32 xMax = */ br.ReadBits(numBits);
886 /* UInt32 yMin = */ br.ReadBits(numBits); 878 /* UInt32 yMin = */ br.ReadBits(numBits);
@@ -893,14 +885,14 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca
893 UInt64 offsetPrev = 0; 885 UInt64 offsetPrev = 0;
894 for (;;) 886 for (;;)
895 { 887 {
896 UInt32 pair = Read16(s); 888 const UInt32 pair = Read16(s);
897 UInt32 type = pair >> 6; 889 const UInt32 type = pair >> 6;
898 UInt32 length = pair & 0x3F; 890 UInt32 length = pair & 0x3F;
899 if (length == 0x3F) 891 if (length == 0x3F)
900 length = Read32(s); 892 length = Read32(s);
901 if (type == 0) 893 if (type == 0)
902 break; 894 break;
903 UInt64 offset = s.GetProcessedSize() + NSwfc::kHeaderBaseSize + length; 895 const UInt64 offset = s.GetProcessedSize() + NSwfc::kHeaderBaseSize + length;
904 if (offset > uncompressedSize || _tags.Size() >= kNumTagsMax) 896 if (offset > uncompressedSize || _tags.Size() >= kNumTagsMax)
905 return S_FALSE; 897 return S_FALSE;
906 CTag &tag = _tags.AddNew(); 898 CTag &tag = _tags.AddNew();
@@ -910,8 +902,8 @@ HRESULT CHandler::OpenSeq3(ISequentialInStream *stream, IArchiveOpenCallback *ca
910 return S_FALSE; 902 return S_FALSE;
911 if (callback && offset >= offsetPrev + (1 << 20)) 903 if (callback && offset >= offsetPrev + (1 << 20))
912 { 904 {
913 UInt64 numItems = _tags.Size(); 905 const UInt64 numItems = _tags.Size();
914 RINOK(callback->SetCompleted(&numItems, &offset)); 906 RINOK(callback->SetCompleted(&numItems, &offset))
915 offsetPrev = offset; 907 offsetPrev = offset;
916 } 908 }
917 } 909 }
@@ -932,22 +924,22 @@ HRESULT CHandler::OpenSeq2(ISequentialInStream *stream, IArchiveOpenCallback *ca
932 return res; 924 return res;
933} 925}
934 926
935STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 927Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
936{ 928{
937 return OpenSeq2(stream, NULL); 929 return OpenSeq2(stream, NULL);
938} 930}
939 931
940STDMETHODIMP CHandler::Close() 932Z7_COM7F_IMF(CHandler::Close())
941{ 933{
942 _phySize = 0; 934 _phySize = 0;
943 return S_OK; 935 return S_OK;
944} 936}
945 937
946STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 938Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
947 Int32 testMode, IArchiveExtractCallback *extractCallback) 939 Int32 testMode, IArchiveExtractCallback *extractCallback))
948{ 940{
949 COM_TRY_BEGIN 941 COM_TRY_BEGIN
950 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 942 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
951 if (allFilesMode) 943 if (allFilesMode)
952 numItems = _tags.Size(); 944 numItems = _tags.Size();
953 if (numItems == 0) 945 if (numItems == 0)
@@ -956,7 +948,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
956 UInt32 i; 948 UInt32 i;
957 for (i = 0; i < numItems; i++) 949 for (i = 0; i < numItems; i++)
958 totalSize += _tags[allFilesMode ? i : indices[i]].Buf.Size(); 950 totalSize += _tags[allFilesMode ? i : indices[i]].Buf.Size();
959 extractCallback->SetTotal(totalSize); 951 RINOK(extractCallback->SetTotal(totalSize))
960 952
961 CLocalProgress *lps = new CLocalProgress; 953 CLocalProgress *lps = new CLocalProgress;
962 CMyComPtr<ICompressProgressInfo> progress = lps; 954 CMyComPtr<ICompressProgressInfo> progress = lps;
@@ -967,24 +959,24 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
967 for (i = 0; i < numItems; i++) 959 for (i = 0; i < numItems; i++)
968 { 960 {
969 lps->InSize = lps->OutSize = totalSize; 961 lps->InSize = lps->OutSize = totalSize;
970 RINOK(lps->SetCur()); 962 RINOK(lps->SetCur())
971 Int32 askMode = testMode ? 963 const Int32 askMode = testMode ?
972 NExtract::NAskMode::kTest : 964 NExtract::NAskMode::kTest :
973 NExtract::NAskMode::kExtract; 965 NExtract::NAskMode::kExtract;
974 UInt32 index = allFilesMode ? i : indices[i]; 966 const UInt32 index = allFilesMode ? i : indices[i];
975 const CByteBuffer &buf = _tags[index].Buf; 967 const CByteBuffer &buf = _tags[index].Buf;
976 totalSize += buf.Size(); 968 totalSize += buf.Size();
977 969
978 CMyComPtr<ISequentialOutStream> outStream; 970 CMyComPtr<ISequentialOutStream> outStream;
979 RINOK(extractCallback->GetStream(index, &outStream, askMode)); 971 RINOK(extractCallback->GetStream(index, &outStream, askMode))
980 if (!testMode && !outStream) 972 if (!testMode && !outStream)
981 continue; 973 continue;
982 974
983 RINOK(extractCallback->PrepareOperation(askMode)); 975 RINOK(extractCallback->PrepareOperation(askMode))
984 if (outStream) 976 if (outStream)
985 RINOK(WriteStream(outStream, buf, buf.Size())); 977 RINOK(WriteStream(outStream, buf, buf.Size()))
986 outStream.Release(); 978 outStream.Release();
987 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 979 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
988 } 980 }
989 return S_OK; 981 return S_OK;
990 COM_TRY_END 982 COM_TRY_END
@@ -993,7 +985,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
993static const Byte k_Signature[] = { 'F', 'W', 'S' }; 985static const Byte k_Signature[] = { 'F', 'W', 'S' };
994 986
995REGISTER_ARC_I( 987REGISTER_ARC_I(
996 "SWF", "swf", 0, 0xD7, 988 "SWF", "swf", NULL, 0xD7,
997 k_Signature, 989 k_Signature,
998 0, 990 0,
999 NArcInfoFlags::kKeepName, 991 NArcInfoFlags::kKeepName,
diff --git a/CPP/7zip/Archive/Tar/StdAfx.h b/CPP/7zip/Archive/Tar/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Tar/StdAfx.h
+++ b/CPP/7zip/Archive/Tar/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/Tar/TarHandler.cpp b/CPP/7zip/Archive/Tar/TarHandler.cpp
index bd04bd7..d7fe175 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";
67IMP_IInArchive_Props 67IMP_IInArchive_Props
68IMP_IInArchive_ArcProps 68IMP_IInArchive_ArcProps
69 69
70STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 70Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
71{ 71{
72 NCOM::CPropVariant prop; 72 NCOM::CPropVariant prop;
73 switch (propID) 73 switch (propID)
@@ -83,9 +83,9 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
83 { 83 {
84 case k_ErrorType_UnexpectedEnd: flags = kpv_ErrorFlags_UnexpectedEnd; break; 84 case k_ErrorType_UnexpectedEnd: flags = kpv_ErrorFlags_UnexpectedEnd; break;
85 case k_ErrorType_Corrupted: flags = kpv_ErrorFlags_HeadersError; break; 85 case k_ErrorType_Corrupted: flags = kpv_ErrorFlags_HeadersError; break;
86 // case k_ErrorType_OK: break; 86 case k_ErrorType_OK: break;
87 // case k_ErrorType_Warning: break; 87 // case k_ErrorType_Warning: break;
88 default: break; 88 // default: break;
89 } 89 }
90 if (flags != 0) 90 if (flags != 0)
91 prop = flags; 91 prop = flags;
@@ -206,10 +206,9 @@ AString CEncodingCharacts::GetCharactsString() const
206 206
207HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) 207HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
208{ 208{
209 UInt64 endPos = 0; 209 UInt64 endPos;
210 { 210 {
211 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); 211 RINOK(InStream_AtBegin_GetSize(stream, endPos))
212 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
213 } 212 }
214 213
215 _arc._phySize_Defined = true; 214 _arc._phySize_Defined = true;
@@ -224,7 +223,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
224 for (;;) 223 for (;;)
225 { 224 {
226 _arc.NumFiles = _items.Size(); 225 _arc.NumFiles = _items.Size();
227 RINOK(_arc.ReadItem(item)); 226 RINOK(_arc.ReadItem(item))
228 if (!_arc.filled) 227 if (!_arc.filled)
229 break; 228 break;
230 229
@@ -245,7 +244,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
245 244
246 _items.Add(item); 245 _items.Add(item);
247 246
248 RINOK(stream->Seek((Int64)item.Get_PackSize_Aligned(), STREAM_SEEK_CUR, &_arc._phySize)); 247 RINOK(stream->Seek((Int64)item.Get_PackSize_Aligned(), STREAM_SEEK_CUR, &_arc._phySize))
249 if (_arc._phySize > endPos) 248 if (_arc._phySize > endPos)
250 { 249 {
251 _arc._error = k_ErrorType_UnexpectedEnd; 250 _arc._error = k_ErrorType_UnexpectedEnd;
@@ -290,10 +289,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
290 _isArc = false; 289 _isArc = false;
291 return S_FALSE; 290 return S_FALSE;
292 } 291 }
293 CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback;
294 if (!callback) 292 if (!callback)
295 return S_FALSE; 293 return S_FALSE;
296 callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); 294 Z7_DECL_CMyComPtr_QI_FROM(
295 IArchiveOpenVolumeCallback,
296 openVolumeCallback, callback)
297 if (!openVolumeCallback) 297 if (!openVolumeCallback)
298 return S_FALSE; 298 return S_FALSE;
299 NCOM::CPropVariant prop; 299 NCOM::CPropVariant prop;
@@ -310,20 +310,20 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
310 return S_OK; 310 return S_OK;
311} 311}
312 312
313STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openArchiveCallback) 313Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openArchiveCallback))
314{ 314{
315 COM_TRY_BEGIN 315 COM_TRY_BEGIN
316 // for (int i = 0; i < 10; i++) // for debug 316 // for (int i = 0; i < 10; i++) // for debug
317 { 317 {
318 Close(); 318 Close();
319 RINOK(Open2(stream, openArchiveCallback)); 319 RINOK(Open2(stream, openArchiveCallback))
320 _stream = stream; 320 _stream = stream;
321 } 321 }
322 return S_OK; 322 return S_OK;
323 COM_TRY_END 323 COM_TRY_END
324} 324}
325 325
326STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 326Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
327{ 327{
328 Close(); 328 Close();
329 _seqStream = stream; 329 _seqStream = stream;
@@ -331,7 +331,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
331 return S_OK; 331 return S_OK;
332} 332}
333 333
334STDMETHODIMP CHandler::Close() 334Z7_COM7F_IMF(CHandler::Close())
335{ 335{
336 _isArc = false; 336 _isArc = false;
337 337
@@ -346,7 +346,7 @@ STDMETHODIMP CHandler::Close()
346 return S_OK; 346 return S_OK;
347} 347}
348 348
349STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 349Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
350{ 350{
351 *numItems = (_stream ? _items.Size() : (UInt32)(Int32)-1); 351 *numItems = (_stream ? _items.Size() : (UInt32)(Int32)-1);
352 return S_OK; 352 return S_OK;
@@ -367,7 +367,7 @@ HRESULT CHandler::SkipTo(UInt32 index)
367 if (_latestIsRead) 367 if (_latestIsRead)
368 { 368 {
369 const UInt64 packSize = _latestItem.Get_PackSize_Aligned(); 369 const UInt64 packSize = _latestItem.Get_PackSize_Aligned();
370 RINOK(copyCoderSpec->Code(_seqStream, NULL, &packSize, &packSize, NULL)); 370 RINOK(copyCoder->Code(_seqStream, NULL, &packSize, &packSize, NULL))
371 _arc._phySize += copyCoderSpec->TotalSize; 371 _arc._phySize += copyCoderSpec->TotalSize;
372 if (copyCoderSpec->TotalSize != packSize) 372 if (copyCoderSpec->TotalSize != packSize)
373 { 373 {
@@ -381,7 +381,7 @@ HRESULT CHandler::SkipTo(UInt32 index)
381 { 381 {
382 _arc.SeqStream = _seqStream; 382 _arc.SeqStream = _seqStream;
383 _arc.InStream = NULL; 383 _arc.InStream = NULL;
384 RINOK(_arc.ReadItem(_latestItem)); 384 RINOK(_arc.ReadItem(_latestItem))
385 if (!_arc.filled) 385 if (!_arc.filled)
386 { 386 {
387 _arc._phySize_Defined = true; 387 _arc._phySize_Defined = true;
@@ -407,6 +407,7 @@ void CHandler::TarStringToUnicode(const AString &s, NWindows::NCOM::CPropVariant
407} 407}
408 408
409 409
410// CPaxTime is defined (NumDigits >= 0)
410static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop) 411static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop)
411{ 412{
412 UInt64 v; 413 UInt64 v;
@@ -418,7 +419,7 @@ static void PaxTimeToProp(const CPaxTime &pt, NWindows::NCOM::CPropVariant &prop
418 ft.dwLowDateTime = (DWORD)v; 419 ft.dwLowDateTime = (DWORD)v;
419 ft.dwHighDateTime = (DWORD)(v >> 32); 420 ft.dwHighDateTime = (DWORD)(v >> 32);
420 prop.SetAsTimeFrom_FT_Prec_Ns100(ft, 421 prop.SetAsTimeFrom_FT_Prec_Ns100(ft,
421 k_PropVar_TimePrec_Base + pt.NumDigits, pt.Ns % 100); 422 k_PropVar_TimePrec_Base + (unsigned)pt.NumDigits, pt.Ns % 100);
422} 423}
423 424
424 425
@@ -469,7 +470,7 @@ static void AddSpecBools(AString &s, const char *name, bool b1, bool b2)
469} 470}
470 471
471 472
472STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 473Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
473{ 474{
474 COM_TRY_BEGIN 475 COM_TRY_BEGIN
475 NCOM::CPropVariant prop; 476 NCOM::CPropVariant prop;
@@ -483,7 +484,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
483 return E_INVALIDARG; 484 return E_INVALIDARG;
484 else 485 else
485 { 486 {
486 RINOK(SkipTo(index)); 487 RINOK(SkipTo(index))
487 item = &_latestItem; 488 item = &_latestItem;
488 } 489 }
489 } 490 }
@@ -665,8 +666,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
665} 666}
666 667
667 668
668HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, 669Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
669 Int32 testMode, IArchiveExtractCallback *extractCallback) 670 Int32 testMode, IArchiveExtractCallback *extractCallback))
670{ 671{
671 COM_TRY_BEGIN 672 COM_TRY_BEGIN
672 ISequentialInStream *stream = _seqStream; 673 ISequentialInStream *stream = _seqStream;
@@ -703,7 +704,7 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
703 { 704 {
704 lps->InSize = totalPackSize; 705 lps->InSize = totalPackSize;
705 lps->OutSize = totalSize; 706 lps->OutSize = totalSize;
706 RINOK(lps->SetCur()); 707 RINOK(lps->SetCur())
707 CMyComPtr<ISequentialOutStream> realOutStream; 708 CMyComPtr<ISequentialOutStream> realOutStream;
708 Int32 askMode = testMode ? 709 Int32 askMode = testMode ?
709 NExtract::NAskMode::kTest : 710 NExtract::NAskMode::kTest :
@@ -715,20 +716,20 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
715 HRESULT res = SkipTo(index); 716 HRESULT res = SkipTo(index);
716 if (res == E_INVALIDARG) 717 if (res == E_INVALIDARG)
717 break; 718 break;
718 RINOK(res); 719 RINOK(res)
719 item = &_latestItem; 720 item = &_latestItem;
720 } 721 }
721 else 722 else
722 item = &_items[index]; 723 item = &_items[index];
723 724
724 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 725 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
725 const UInt64 unpackSize = item->Get_UnpackSize(); 726 const UInt64 unpackSize = item->Get_UnpackSize();
726 totalSize += unpackSize; 727 totalSize += unpackSize;
727 totalPackSize += item->Get_PackSize_Aligned(); 728 totalPackSize += item->Get_PackSize_Aligned();
728 if (item->IsDir()) 729 if (item->IsDir())
729 { 730 {
730 RINOK(extractCallback->PrepareOperation(askMode)); 731 RINOK(extractCallback->PrepareOperation(askMode))
731 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 732 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
732 continue; 733 continue;
733 } 734 }
734 bool skipMode = false; 735 bool skipMode = false;
@@ -741,8 +742,8 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
741 if (item->IsHardLink() || 742 if (item->IsHardLink() ||
742 item->IsSymLink()) 743 item->IsSymLink())
743 { 744 {
744 RINOK(extractCallback->PrepareOperation(askMode)); 745 RINOK(extractCallback->PrepareOperation(askMode))
745 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 746 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
746 } 747 }
747 */ 748 */
748 continue; 749 continue;
@@ -750,7 +751,7 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
750 skipMode = true; 751 skipMode = true;
751 askMode = NExtract::NAskMode::kSkip; 752 askMode = NExtract::NAskMode::kSkip;
752 } 753 }
753 RINOK(extractCallback->PrepareOperation(askMode)); 754 RINOK(extractCallback->PrepareOperation(askMode))
754 755
755 outStreamSpec->SetStream(realOutStream); 756 outStreamSpec->SetStream(realOutStream);
756 realOutStream.Release(); 757 realOutStream.Release();
@@ -770,16 +771,16 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
770 { 771 {
771 if (item->Is_SymLink()) 772 if (item->Is_SymLink())
772 { 773 {
773 RINOK(WriteStream(outStreamSpec, (const char *)item->LinkName, item->LinkName.Len())); 774 RINOK(WriteStream(outStreamSpec, (const char *)item->LinkName, item->LinkName.Len()))
774 } 775 }
775 else 776 else
776 { 777 {
777 if (!seqMode) 778 if (!seqMode)
778 { 779 {
779 RINOK(_stream->Seek((Int64)item->Get_DataPos(), STREAM_SEEK_SET, NULL)); 780 RINOK(InStream_SeekSet(_stream, item->Get_DataPos()))
780 } 781 }
781 streamSpec->Init(item->Get_PackSize_Aligned()); 782 streamSpec->Init(item->Get_PackSize_Aligned());
782 RINOK(copyCoder->Code(inStream2, outStream, NULL, NULL, progress)); 783 RINOK(copyCoder->Code(inStream2, outStream, NULL, NULL, progress))
783 } 784 }
784 if (outStreamSpec->GetRem() != 0) 785 if (outStreamSpec->GetRem() != 0)
785 opRes = NExtract::NOperationResult::kDataError; 786 opRes = NExtract::NOperationResult::kDataError;
@@ -790,16 +791,16 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
790 _curIndex++; 791 _curIndex++;
791 } 792 }
792 outStreamSpec->ReleaseStream(); 793 outStreamSpec->ReleaseStream();
793 RINOK(extractCallback->SetOperationResult(opRes)); 794 RINOK(extractCallback->SetOperationResult(opRes))
794 } 795 }
795 return S_OK; 796 return S_OK;
796 COM_TRY_END 797 COM_TRY_END
797} 798}
798 799
799class CSparseStream: 800
800 public IInStream, 801Z7_CLASS_IMP_IInStream(
801 public CMyUnknownImp 802 CSparseStream
802{ 803)
803 UInt64 _phyPos; 804 UInt64 _phyPos;
804 UInt64 _virtPos; 805 UInt64 _virtPos;
805 bool _needStartSeek; 806 bool _needStartSeek;
@@ -810,10 +811,6 @@ public:
810 unsigned ItemIndex; 811 unsigned ItemIndex;
811 CRecordVector<UInt64> PhyOffsets; 812 CRecordVector<UInt64> PhyOffsets;
812 813
813 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
814 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
815 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
816
817 void Init() 814 void Init()
818 { 815 {
819 _virtPos = 0; 816 _virtPos = 0;
@@ -823,7 +820,7 @@ public:
823}; 820};
824 821
825 822
826STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize) 823Z7_COM7F_IMF(CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize))
827{ 824{
828 if (processedSize) 825 if (processedSize)
829 *processedSize = 0; 826 *processedSize = 0;
@@ -867,7 +864,7 @@ STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize)
867 UInt64 phyPos = PhyOffsets[left] + relat; 864 UInt64 phyPos = PhyOffsets[left] + relat;
868 if (_needStartSeek || _phyPos != phyPos) 865 if (_needStartSeek || _phyPos != phyPos)
869 { 866 {
870 RINOK(Handler->_stream->Seek((Int64)(item.Get_DataPos() + phyPos), STREAM_SEEK_SET, NULL)); 867 RINOK(InStream_SeekSet(Handler->_stream, (item.Get_DataPos() + phyPos)))
871 _needStartSeek = false; 868 _needStartSeek = false;
872 _phyPos = phyPos; 869 _phyPos = phyPos;
873 } 870 }
@@ -894,7 +891,7 @@ STDMETHODIMP CSparseStream::Read(void *data, UInt32 size, UInt32 *processedSize)
894 return res; 891 return res;
895} 892}
896 893
897STDMETHODIMP CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 894Z7_COM7F_IMF(CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
898{ 895{
899 switch (seekOrigin) 896 switch (seekOrigin)
900 { 897 {
@@ -911,7 +908,7 @@ STDMETHODIMP CSparseStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
911 return S_OK; 908 return S_OK;
912} 909}
913 910
914STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 911Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
915{ 912{
916 COM_TRY_BEGIN 913 COM_TRY_BEGIN
917 914
@@ -961,7 +958,7 @@ void CHandler::Init()
961} 958}
962 959
963 960
964STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 961Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
965{ 962{
966 Init(); 963 Init();
967 964
@@ -978,12 +975,12 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
978 { 975 {
979 // some clients write 'x' property. So we support it 976 // some clients write 'x' property. So we support it
980 UInt32 level = 0; 977 UInt32 level = 0;
981 RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)); 978 RINOK(ParsePropToUInt32(name.Ptr(1), prop, level))
982 } 979 }
983 else if (name.IsEqualTo("cp")) 980 else if (name.IsEqualTo("cp"))
984 { 981 {
985 UInt32 cp = CP_OEMCP; 982 UInt32 cp = CP_OEMCP;
986 RINOK(ParsePropToUInt32(L"", prop, cp)); 983 RINOK(ParsePropToUInt32(L"", prop, cp))
987 _forceCodePage = true; 984 _forceCodePage = true;
988 _curCodePage = _specifiedCodePage = cp; 985 _curCodePage = _specifiedCodePage = cp;
989 } 986 }
@@ -1036,7 +1033,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1036 } 1033 }
1037 */ 1034 */
1038 bool processed = false; 1035 bool processed = false;
1039 RINOK(_handlerTimeOptions.Parse(name, prop, processed)); 1036 RINOK(_handlerTimeOptions.Parse(name, prop, processed))
1040 if (processed) 1037 if (processed)
1041 continue; 1038 continue;
1042 return E_INVALIDARG; 1039 return E_INVALIDARG;
diff --git a/CPP/7zip/Archive/Tar/TarHandler.h b/CPP/7zip/Archive/Tar/TarHandler.h
index 44a9980..451c2fd 100644
--- a/CPP/7zip/Archive/Tar/TarHandler.h
+++ b/CPP/7zip/Archive/Tar/TarHandler.h
@@ -1,12 +1,10 @@
1// TarHandler.h 1// TarHandler.h
2 2
3#ifndef __TAR_HANDLER_H 3#ifndef ZIP7_INC_TAR_HANDLER_H
4#define __TAR_HANDLER_H 4#define ZIP7_INC_TAR_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../../../Windows/PropVariant.h"
9
10#include "../../Compress/CopyCoder.h" 8#include "../../Compress/CopyCoder.h"
11 9
12#include "../Common/HandlerOut.h" 10#include "../Common/HandlerOut.h"
@@ -16,14 +14,12 @@
16namespace NArchive { 14namespace NArchive {
17namespace NTar { 15namespace NTar {
18 16
19class CHandler: 17Z7_CLASS_IMP_CHandler_IInArchive_4(
20 public IInArchive, 18 IArchiveOpenSeq
21 public IArchiveOpenSeq, 19 , IInArchiveGetStream
22 public IInArchiveGetStream, 20 , ISetProperties
23 public ISetProperties, 21 , IOutArchive
24 public IOutArchive, 22)
25 public CMyUnknownImp
26{
27public: 23public:
28 CObjectVector<CItemEx> _items; 24 CObjectVector<CItemEx> _items;
29 CMyComPtr<IInStream> _stream; 25 CMyComPtr<IInStream> _stream;
@@ -53,20 +49,6 @@ private:
53 HRESULT SkipTo(UInt32 index); 49 HRESULT SkipTo(UInt32 index);
54 void TarStringToUnicode(const AString &s, NWindows::NCOM::CPropVariant &prop, bool toOs = false) const; 50 void TarStringToUnicode(const AString &s, NWindows::NCOM::CPropVariant &prop, bool toOs = false) const;
55public: 51public:
56 MY_UNKNOWN_IMP5(
57 IInArchive,
58 IArchiveOpenSeq,
59 IInArchiveGetStream,
60 ISetProperties,
61 IOutArchive
62 )
63
64 INTERFACE_IInArchive(;)
65 INTERFACE_IOutArchive(;)
66 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
67 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
68 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
69
70 void Init(); 52 void Init();
71 CHandler(); 53 CHandler();
72}; 54};
diff --git a/CPP/7zip/Archive/Tar/TarHandlerOut.cpp b/CPP/7zip/Archive/Tar/TarHandlerOut.cpp
index 53255e4..c93a86e 100644
--- a/CPP/7zip/Archive/Tar/TarHandlerOut.cpp
+++ b/CPP/7zip/Archive/Tar/TarHandlerOut.cpp
@@ -20,7 +20,7 @@ using namespace NWindows;
20namespace NArchive { 20namespace NArchive {
21namespace NTar { 21namespace NTar {
22 22
23STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 23Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type))
24{ 24{
25 UInt32 t = NFileTimeType::kUnix; 25 UInt32 t = NFileTimeType::kUnix;
26 const UInt32 prec = _handlerTimeOptions.Prec; 26 const UInt32 prec = _handlerTimeOptions.Prec;
@@ -55,7 +55,7 @@ HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PROPID pro
55 UINT codePage, unsigned utfFlags, bool convertSlash) 55 UINT codePage, unsigned utfFlags, bool convertSlash)
56{ 56{
57 NCOM::CPropVariant prop; 57 NCOM::CPropVariant prop;
58 RINOK(callback->GetProperty(index, propId, &prop)); 58 RINOK(callback->GetProperty(index, propId, &prop))
59 59
60 if (prop.vt == VT_BSTR) 60 if (prop.vt == VT_BSTR)
61 { 61 {
@@ -94,7 +94,7 @@ static HRESULT GetTime(UInt32 i, UInt32 pid, IArchiveUpdateCallback *callback,
94{ 94{
95 pt.Clear(); 95 pt.Clear();
96 NCOM::CPropVariant prop; 96 NCOM::CPropVariant prop;
97 RINOK(callback->GetProperty(i, pid, &prop)); 97 RINOK(callback->GetProperty(i, pid, &prop))
98 return Prop_To_PaxTime(prop, pt); 98 return Prop_To_PaxTime(prop, pt);
99} 99}
100 100
@@ -125,7 +125,7 @@ static HRESULT GetDevice(IArchiveUpdateCallback *callback, UInt32 i,
125{ 125{
126 defined = false; 126 defined = false;
127 NWindows::NCOM::CPropVariant prop; 127 NWindows::NCOM::CPropVariant prop;
128 RINOK(callback->GetProperty(i, pid, &prop)); 128 RINOK(callback->GetProperty(i, pid, &prop))
129 if (prop.vt == VT_EMPTY) 129 if (prop.vt == VT_EMPTY)
130 return S_OK; 130 return S_OK;
131 if (prop.vt == VT_UI4) 131 if (prop.vt == VT_UI4)
@@ -147,7 +147,7 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i,
147 bool isSet = false; 147 bool isSet = false;
148 { 148 {
149 NWindows::NCOM::CPropVariant prop; 149 NWindows::NCOM::CPropVariant prop;
150 RINOK(callback->GetProperty(i, pidId, &prop)); 150 RINOK(callback->GetProperty(i, pidId, &prop))
151 if (prop.vt == VT_UI4) 151 if (prop.vt == VT_UI4)
152 { 152 {
153 isSet = true; 153 isSet = true;
@@ -160,7 +160,7 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i,
160 } 160 }
161 { 161 {
162 NWindows::NCOM::CPropVariant prop; 162 NWindows::NCOM::CPropVariant prop;
163 RINOK(callback->GetProperty(i, pidName, &prop)); 163 RINOK(callback->GetProperty(i, pidName, &prop))
164 if (prop.vt == VT_BSTR) 164 if (prop.vt == VT_BSTR)
165 { 165 {
166 const UString s = prop.bstrVal; 166 const UString s = prop.bstrVal;
@@ -181,8 +181,8 @@ static HRESULT GetUser(IArchiveUpdateCallback *callback, UInt32 i,
181 181
182 182
183 183
184STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 184Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
185 IArchiveUpdateCallback *callback) 185 IArchiveUpdateCallback *callback))
186{ 186{
187 COM_TRY_BEGIN 187 COM_TRY_BEGIN
188 188
@@ -196,8 +196,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
196 /* 196 /*
197 // for debug only: 197 // for debug only:
198 unsigned utfFlags = 0; 198 unsigned utfFlags = 0;
199 utfFlags |= UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE; 199 utfFlags |= Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE;
200 utfFlags |= UTF_FLAG__TO_UTF8__SURROGATE_ERROR; 200 utfFlags |= Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR;
201 */ 201 */
202 202
203 for (UInt32 i = 0; i < numItems; i++) 203 for (UInt32 i = 0; i < numItems; i++)
@@ -210,7 +210,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
210 if (!callback) 210 if (!callback)
211 return E_FAIL; 211 return E_FAIL;
212 212
213 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); 213 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc))
214 214
215 ui.NewProps = IntToBool(newProps); 215 ui.NewProps = IntToBool(newProps);
216 ui.NewData = IntToBool(newData); 216 ui.NewData = IntToBool(newData);
@@ -221,7 +221,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
221 { 221 {
222 { 222 {
223 NCOM::CPropVariant prop; 223 NCOM::CPropVariant prop;
224 RINOK(callback->GetProperty(i, kpidIsDir, &prop)); 224 RINOK(callback->GetProperty(i, kpidIsDir, &prop))
225 if (prop.vt == VT_EMPTY) 225 if (prop.vt == VT_EMPTY)
226 ui.IsDir = false; 226 ui.IsDir = false;
227 else if (prop.vt != VT_BOOL) 227 else if (prop.vt != VT_BOOL)
@@ -232,7 +232,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
232 232
233 { 233 {
234 NCOM::CPropVariant prop; 234 NCOM::CPropVariant prop;
235 RINOK(callback->GetProperty(i, kpidPosixAttrib, &prop)); 235 RINOK(callback->GetProperty(i, kpidPosixAttrib, &prop))
236 if (prop.vt == VT_EMPTY) 236 if (prop.vt == VT_EMPTY)
237 ui.Mode = 237 ui.Mode =
238 MY_LIN_S_IRWXO 238 MY_LIN_S_IRWXO
@@ -255,25 +255,25 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
255 if (_handlerTimeOptions.Write_CTime.Val) 255 if (_handlerTimeOptions.Write_CTime.Val)
256 RINOK(GetTime(i, kpidCTime, callback, ui.PaxTimes.CTime)) 256 RINOK(GetTime(i, kpidCTime, callback, ui.PaxTimes.CTime))
257 257
258 RINOK(GetPropString(callback, i, kpidPath, ui.Name, codePage, utfFlags, true)); 258 RINOK(GetPropString(callback, i, kpidPath, ui.Name, codePage, utfFlags, true))
259 if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/') 259 if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/')
260 ui.Name += '/'; 260 ui.Name += '/';
261 // ui.Name += '/'; // for debug 261 // ui.Name += '/'; // for debug
262 262
263 if (_posixMode) 263 if (_posixMode)
264 { 264 {
265 RINOK(GetDevice(callback, i, kpidDeviceMajor, ui.DeviceMajor, ui.DeviceMajor_Defined)); 265 RINOK(GetDevice(callback, i, kpidDeviceMajor, ui.DeviceMajor, ui.DeviceMajor_Defined))
266 RINOK(GetDevice(callback, i, kpidDeviceMinor, ui.DeviceMinor, ui.DeviceMinor_Defined)); 266 RINOK(GetDevice(callback, i, kpidDeviceMinor, ui.DeviceMinor, ui.DeviceMinor_Defined))
267 } 267 }
268 268
269 RINOK(GetUser(callback, i, kpidUser, kpidUserId, ui.User, ui.UID, codePage, utfFlags)); 269 RINOK(GetUser(callback, i, kpidUser, kpidUserId, ui.User, ui.UID, codePage, utfFlags))
270 RINOK(GetUser(callback, i, kpidGroup, kpidGroupId, ui.Group, ui.GID, codePage, utfFlags)); 270 RINOK(GetUser(callback, i, kpidGroup, kpidGroupId, ui.Group, ui.GID, codePage, utfFlags))
271 } 271 }
272 272
273 if (IntToBool(newData)) 273 if (IntToBool(newData))
274 { 274 {
275 NCOM::CPropVariant prop; 275 NCOM::CPropVariant prop;
276 RINOK(callback->GetProperty(i, kpidSize, &prop)); 276 RINOK(callback->GetProperty(i, kpidSize, &prop))
277 if (prop.vt != VT_UI8) 277 if (prop.vt != VT_UI8)
278 return E_INVALIDARG; 278 return E_INVALIDARG;
279 ui.Size = prop.uhVal.QuadPart; 279 ui.Size = prop.uhVal.QuadPart;
diff --git a/CPP/7zip/Archive/Tar/TarHeader.cpp b/CPP/7zip/Archive/Tar/TarHeader.cpp
index f1efddb..deae357 100644
--- a/CPP/7zip/Archive/Tar/TarHeader.cpp
+++ b/CPP/7zip/Archive/Tar/TarHeader.cpp
@@ -20,7 +20,7 @@ namespace NFileHeader {
20 // 7-Zip used kUsTar_00 before 21.07: 20 // 7-Zip used kUsTar_00 before 21.07:
21 const char k_Posix_ustar_00[8] = { 'u', 's', 't', 'a', 'r', 0, '0', '0' } ; 21 const char k_Posix_ustar_00[8] = { 'u', 's', 't', 'a', 'r', 0, '0', '0' } ;
22 // GNU TAR uses such header: 22 // GNU TAR uses such header:
23 const char k_GNU_ustar__[8] = { 'u', 's', 't', 'a', 'r', ' ', ' ', 0 } ; 23 const char k_GNU_ustar[8] = { 'u', 's', 't', 'a', 'r', ' ', ' ', 0 } ;
24 } 24 }
25 25
26/* 26/*
diff --git a/CPP/7zip/Archive/Tar/TarHeader.h b/CPP/7zip/Archive/Tar/TarHeader.h
index 1af3093..aeccd28 100644
--- a/CPP/7zip/Archive/Tar/TarHeader.h
+++ b/CPP/7zip/Archive/Tar/TarHeader.h
@@ -1,7 +1,7 @@
1// Archive/TarHeader.h 1// Archive/TarHeader.h
2 2
3#ifndef __ARCHIVE_TAR_HEADER_H 3#ifndef ZIP7_INC_ARCHIVE_TAR_HEADER_H
4#define __ARCHIVE_TAR_HEADER_H 4#define ZIP7_INC_ARCHIVE_TAR_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
@@ -81,7 +81,7 @@ namespace NFileHeader
81 // extern const char * const kGNUTar; // = "GNUtar "; // 7 chars and a null 81 // extern const char * const kGNUTar; // = "GNUtar "; // 7 chars and a null
82 // extern const char * const kEmpty; // = "\0\0\0\0\0\0\0\0" 82 // extern const char * const kEmpty; // = "\0\0\0\0\0\0\0\0"
83 extern const char k_Posix_ustar_00[8]; 83 extern const char k_Posix_ustar_00[8];
84 extern const char k_GNU_ustar__[8]; 84 extern const char k_GNU_ustar[8];
85 } 85 }
86} 86}
87 87
diff --git a/CPP/7zip/Archive/Tar/TarIn.cpp b/CPP/7zip/Archive/Tar/TarIn.cpp
index 4fd8c5b..90b6f84 100644
--- a/CPP/7zip/Archive/Tar/TarIn.cpp
+++ b/CPP/7zip/Archive/Tar/TarIn.cpp
@@ -14,8 +14,8 @@
14 14
15#define NUM_UNROLL_BYTES (8 * 4) 15#define NUM_UNROLL_BYTES (8 * 4)
16 16
17MY_NO_INLINE static bool IsBufNonZero(const void *data, size_t size); 17Z7_NO_INLINE static bool IsBufNonZero(const void *data, size_t size);
18MY_NO_INLINE static bool IsBufNonZero(const void *data, size_t size) 18Z7_NO_INLINE static bool IsBufNonZero(const void *data, size_t size)
19{ 19{
20 const Byte *p = (const Byte *)data; 20 const Byte *p = (const Byte *)data;
21 21
@@ -159,7 +159,7 @@ API_FUNC_IsArc IsArc_Tar(const Byte *p2, size_t size)
159 159
160 UInt32 mode; 160 UInt32 mode;
161 // we allow empty Mode value for LongName prefix items 161 // we allow empty Mode value for LongName prefix items
162 CHECK(OctalToNumber32(p, mode, true)); p += 8; 162 CHECK(OctalToNumber32(p, mode, true)) p += 8;
163 163
164 // if (!OctalToNumber32(p, item.UID)) item.UID = 0; 164 // if (!OctalToNumber32(p, item.UID)) item.UID = 0;
165 p += 8; 165 p += 8;
@@ -170,9 +170,9 @@ API_FUNC_IsArc IsArc_Tar(const Byte *p2, size_t size)
170 Int64 time; 170 Int64 time;
171 UInt32 checkSum; 171 UInt32 checkSum;
172 bool isBin; 172 bool isBin;
173 CHECK(ParseSize(p, packSize, isBin)); p += 12; 173 CHECK(ParseSize(p, packSize, isBin)) p += 12;
174 CHECK(ParseInt64_MTime(p, time, isBin)); p += 12; 174 CHECK(ParseInt64_MTime(p, time, isBin)) p += 12;
175 CHECK(OctalToNumber32(p, checkSum)); 175 CHECK(OctalToNumber32(p, checkSum))
176 return k_IsArc_Res_YES; 176 return k_IsArc_Res_YES;
177} 177}
178 178
@@ -188,7 +188,7 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
188 for (;;) 188 for (;;)
189 { 189 {
190 size_t processedSize = NFileHeader::kRecordSize; 190 size_t processedSize = NFileHeader::kRecordSize;
191 RINOK(ReadStream(SeqStream, buf, &processedSize)); 191 RINOK(ReadStream(SeqStream, buf, &processedSize))
192 if (processedSize == 0) 192 if (processedSize == 0)
193 { 193 {
194 if (!thereAreEmptyRecords) 194 if (!thereAreEmptyRecords)
@@ -220,7 +220,7 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
220 thereAreEmptyRecords = true; 220 thereAreEmptyRecords = true;
221 if (OpenCallback) 221 if (OpenCallback)
222 { 222 {
223 RINOK(Progress(item, 0)); 223 RINOK(Progress(item, 0))
224 } 224 }
225 } 225 }
226 if (thereAreEmptyRecords) 226 if (thereAreEmptyRecords)
@@ -243,19 +243,19 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
243 */ 243 */
244 244
245 // we allow empty Mode value for LongName prefix items 245 // we allow empty Mode value for LongName prefix items
246 RIF(OctalToNumber32(p, item.Mode, true)); p += 8; 246 RIF(OctalToNumber32(p, item.Mode, true)) p += 8;
247 247
248 if (!OctalToNumber32(p, item.UID)) { item.UID = 0; } p += 8; 248 if (!OctalToNumber32(p, item.UID)) { item.UID = 0; } p += 8;
249 if (!OctalToNumber32(p, item.GID)) { item.GID = 0; } p += 8; 249 if (!OctalToNumber32(p, item.GID)) { item.GID = 0; } p += 8;
250 250
251 RIF(ParseSize(p, item.PackSize, item.PackSize_IsBin)); 251 RIF(ParseSize(p, item.PackSize, item.PackSize_IsBin))
252 item.Size = item.PackSize; 252 item.Size = item.PackSize;
253 item.Size_IsBin = item.PackSize_IsBin; 253 item.Size_IsBin = item.PackSize_IsBin;
254 p += 12; 254 p += 12;
255 RIF(ParseInt64_MTime(p, item.MTime, item.MTime_IsBin)); p += 12; 255 RIF(ParseInt64_MTime(p, item.MTime, item.MTime_IsBin)) p += 12;
256 256
257 UInt32 checkSum; 257 UInt32 checkSum;
258 RIF(OctalToNumber32(p, checkSum)); 258 RIF(OctalToNumber32(p, checkSum))
259 memset(p, ' ', 8); p += 8; 259 memset(p, ' ', 8); p += 8;
260 260
261 item.LinkFlag = *p++; 261 item.LinkFlag = *p++;
@@ -273,8 +273,8 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
273 ReadString(p, NFileHeader::kUserNameSize, item.User); p += NFileHeader::kUserNameSize; 273 ReadString(p, NFileHeader::kUserNameSize, item.User); p += NFileHeader::kUserNameSize;
274 ReadString(p, NFileHeader::kGroupNameSize, item.Group); p += NFileHeader::kGroupNameSize; 274 ReadString(p, NFileHeader::kGroupNameSize, item.Group); p += NFileHeader::kGroupNameSize;
275 275
276 item.DeviceMajor_Defined = (p[0] != 0); if (item.DeviceMajor_Defined) { RIF(OctalToNumber32(p, item.DeviceMajor)); } p += 8; 276 item.DeviceMajor_Defined = (p[0] != 0); if (item.DeviceMajor_Defined) { RIF(OctalToNumber32(p, item.DeviceMajor)) } p += 8;
277 item.DeviceMinor_Defined = (p[0] != 0); if (item.DeviceMinor_Defined) { RIF(OctalToNumber32(p, item.DeviceMinor)); } p += 8; 277 item.DeviceMinor_Defined = (p[0] != 0); if (item.DeviceMinor_Defined) { RIF(OctalToNumber32(p, item.DeviceMinor)) } p += 8;
278 278
279 if (p[0] != 0 279 if (p[0] != 0
280 && item.IsMagic_ustar_5chars() 280 && item.IsMagic_ustar_5chars()
@@ -338,7 +338,7 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
338 Byte isExtended = (Byte)buf[482]; 338 Byte isExtended = (Byte)buf[482];
339 if (isExtended != 0 && isExtended != 1) 339 if (isExtended != 0 && isExtended != 1)
340 return S_OK; 340 return S_OK;
341 RIF(ParseSize(buf + 483, item.Size, item.Size_IsBin)); 341 RIF(ParseSize(buf + 483, item.Size, item.Size_IsBin))
342 UInt64 min = 0; 342 UInt64 min = 0;
343 for (unsigned i = 0; i < 4; i++) 343 for (unsigned i = 0; i < 4; i++)
344 { 344 {
@@ -350,8 +350,8 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
350 break; 350 break;
351 } 351 }
352 CSparseBlock sb; 352 CSparseBlock sb;
353 RIF(ParseSize(p, sb.Offset)); 353 RIF(ParseSize(p, sb.Offset))
354 RIF(ParseSize(p + 12, sb.Size)); 354 RIF(ParseSize(p + 12, sb.Size))
355 item.SparseBlocks.Add(sb); 355 item.SparseBlocks.Add(sb);
356 if (sb.Offset < min || sb.Offset > item.Size) 356 if (sb.Offset < min || sb.Offset > item.Size)
357 return S_OK; 357 return S_OK;
@@ -367,7 +367,7 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
367 while (isExtended != 0) 367 while (isExtended != 0)
368 { 368 {
369 size_t processedSize = NFileHeader::kRecordSize; 369 size_t processedSize = NFileHeader::kRecordSize;
370 RINOK(ReadStream(SeqStream, buf, &processedSize)); 370 RINOK(ReadStream(SeqStream, buf, &processedSize))
371 if (processedSize != NFileHeader::kRecordSize) 371 if (processedSize != NFileHeader::kRecordSize)
372 { 372 {
373 error = k_ErrorType_UnexpectedEnd; 373 error = k_ErrorType_UnexpectedEnd;
@@ -378,7 +378,7 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
378 378
379 if (OpenCallback) 379 if (OpenCallback)
380 { 380 {
381 RINOK(Progress(item, 0)); 381 RINOK(Progress(item, 0))
382 } 382 }
383 383
384 isExtended = (Byte)buf[21 * 24]; 384 isExtended = (Byte)buf[21 * 24];
@@ -394,8 +394,8 @@ HRESULT CArchive::GetNextItemReal(CItemEx &item)
394 break; 394 break;
395 } 395 }
396 CSparseBlock sb; 396 CSparseBlock sb;
397 RIF(ParseSize(p, sb.Offset)); 397 RIF(ParseSize(p, sb.Offset))
398 RIF(ParseSize(p + 12, sb.Size)); 398 RIF(ParseSize(p + 12, sb.Size))
399 item.SparseBlocks.Add(sb); 399 item.SparseBlocks.Add(sb);
400 if (sb.Offset < min || sb.Offset > item.Size) 400 if (sb.Offset < min || sb.Offset > item.Size)
401 return S_OK; 401 return S_OK;
@@ -459,7 +459,7 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item,
459 error = k_ErrorType_UnexpectedEnd; 459 error = k_ErrorType_UnexpectedEnd;
460 return res; 460 return res;
461 } 461 }
462 RINOK(res); 462 RINOK(res)
463 463
464 packSize -= size; 464 packSize -= size;
465 465
@@ -492,7 +492,7 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item,
492 492
493 if (InStream) 493 if (InStream)
494 { 494 {
495 RINOK(InStream->Seek((Int64)packSize, STREAM_SEEK_CUR, NULL)); 495 RINOK(InStream->Seek((Int64)packSize, STREAM_SEEK_CUR, NULL))
496 return S_OK; 496 return S_OK;
497 } 497 }
498 const unsigned kBufSize = 1 << 15; 498 const unsigned kBufSize = 1 << 15;
@@ -502,7 +502,7 @@ HRESULT CArchive::ReadDataToBuffer(const CItemEx &item,
502 { 502 {
503 if (OpenCallback) 503 if (OpenCallback)
504 { 504 {
505 RINOK(Progress(item, pos)); 505 RINOK(Progress(item, pos))
506 } 506 }
507 507
508 unsigned size = kBufSize; 508 unsigned size = kBufSize;
@@ -590,8 +590,8 @@ static bool ParsePaxTime(const AString &src, CPaxTime &pt, bool &doubleTagError)
590 if (sec >= ((UInt64)1 << 63)) 590 if (sec >= ((UInt64)1 << 63))
591 return false; 591 return false;
592 if (isNegative) 592 if (isNegative)
593 sec = -(Int64)sec; 593 sec = (UInt64)-(Int64)sec;
594 pt.Sec = sec; 594 pt.Sec = (Int64)sec;
595 } 595 }
596 if (*end == 0) 596 if (*end == 0)
597 { 597 {
@@ -617,10 +617,10 @@ static bool ParsePaxTime(const AString &src, CPaxTime &pt, bool &doubleTagError)
617 if (i < kNsDigits) 617 if (i < kNsDigits)
618 { 618 {
619 ns *= 10; 619 ns *= 10;
620 ns += c - '0'; 620 ns += (unsigned)(c - '0');
621 } 621 }
622 } 622 }
623 pt.NumDigits = (i < kNsDigits ? i : kNsDigits); 623 pt.NumDigits = (int)(i < kNsDigits ? i : kNsDigits);
624 while (i < kNsDigits) 624 while (i < kNsDigits)
625 { 625 {
626 ns *= 10; 626 ns *= 10;
@@ -690,7 +690,7 @@ bool CPaxInfo::ParsePax(const CTempBuffer &tb, bool isFile)
690 return false; 690 return false;
691 691
692 name.SetFrom(s + offset, i - offset); 692 name.SetFrom(s + offset, i - offset);
693 val.SetFrom(s + i + 1, size - 1 - (i + 1)); 693 val.SetFrom(s + i + 1, (unsigned)(size - 1 - (i + 1)));
694 694
695 bool parsed = false; 695 bool parsed = false;
696 if (isFile) 696 if (isFile)
@@ -822,29 +822,34 @@ HRESULT CArchive::ReadItem2(CItemEx &item)
822 PaxBuf.Init(); 822 PaxBuf.Init();
823 PaxBuf_global.Init(); 823 PaxBuf_global.Init();
824 824
825 for (unsigned recordIndex = 0;; recordIndex++) 825 UInt64 numExtraRecords = 0;
826
827 for (;;)
826 { 828 {
827 if (OpenCallback) 829 if (OpenCallback)
828 { 830 {
829 RINOK(Progress(item, 0)); 831 RINOK(Progress(item, 0))
830 } 832 }
831 833
832 RINOK(GetNextItemReal(item)); 834 RINOK(GetNextItemReal(item))
833 835
834 // NumRecords++; 836 // NumRecords++;
835 837
836 if (!filled) 838 if (!filled)
837 { 839 {
838 if (error == k_ErrorType_OK) 840 if (error == k_ErrorType_OK)
839 if (item.LongName_WasUsed || 841 if (numExtraRecords != 0
840 item.LongLink_WasUsed || 842 || item.LongName_WasUsed
841 item.Num_Pax_Records != 0) 843 || item.LongLink_WasUsed
844 || item.Num_Pax_Records != 0)
842 error = k_ErrorType_Corrupted; 845 error = k_ErrorType_Corrupted;
846 return S_OK;
843 } 847 }
844
845 if (error != k_ErrorType_OK) 848 if (error != k_ErrorType_OK)
846 return S_OK; 849 return S_OK;
847 850
851 numExtraRecords++;
852
848 const char lf = item.LinkFlag; 853 const char lf = item.LinkFlag;
849 if (lf == NFileHeader::NLinkFlag::kGnu_LongName || 854 if (lf == NFileHeader::NLinkFlag::kGnu_LongName ||
850 lf == NFileHeader::NLinkFlag::kGnu_LongLink) 855 lf == NFileHeader::NLinkFlag::kGnu_LongLink)
@@ -874,7 +879,7 @@ HRESULT CArchive::ReadItem2(CItemEx &item)
874 */ 879 */
875 880
876 const unsigned kLongNameSizeMax = (unsigned)1 << 14; 881 const unsigned kLongNameSizeMax = (unsigned)1 << 14;
877 RINOK(ReadDataToBuffer(item, *tb, kLongNameSizeMax)); 882 RINOK(ReadDataToBuffer(item, *tb, kLongNameSizeMax))
878 if (error != k_ErrorType_OK) 883 if (error != k_ErrorType_OK)
879 return S_OK; 884 return S_OK;
880 885
@@ -921,7 +926,7 @@ HRESULT CArchive::ReadItem2(CItemEx &item)
921 926
922 CTempBuffer *tb = (lf == NFileHeader::NLinkFlag::kGlobal ? &PaxBuf_global : &PaxBuf); 927 CTempBuffer *tb = (lf == NFileHeader::NLinkFlag::kGlobal ? &PaxBuf_global : &PaxBuf);
923 928
924 RINOK(ReadDataToBuffer(item, *tb, kParsingPaxSizeMax)); 929 RINOK(ReadDataToBuffer(item, *tb, kParsingPaxSizeMax))
925 if (error != k_ErrorType_OK) 930 if (error != k_ErrorType_OK)
926 return S_OK; 931 return S_OK;
927 932
@@ -951,12 +956,19 @@ HRESULT CArchive::ReadItem2(CItemEx &item)
951 } 956 }
952 else 957 else
953 _is_PaxGlobal_Error = true; 958 _is_PaxGlobal_Error = true;
954 if (isStartHeader) 959
960 if (isStartHeader
961 && item.Num_Pax_Records == 1
962 && numExtraRecords == 1)
955 { 963 {
956 // we skip global pax header info after parsing 964 // we skip global pax header info after parsing
957 item.HeaderPos += item.HeaderSize; 965 item.HeaderPos += item.HeaderSize;
958 item.HeaderSize = 0; 966 item.HeaderSize = 0;
967 item.Num_Pax_Records = 0;
968 numExtraRecords = 0;
959 } 969 }
970 else
971 _is_PaxGlobal_Error = true;
960 } 972 }
961 continue; 973 continue;
962 } 974 }
@@ -1071,7 +1083,7 @@ HRESULT CArchive::ReadItem(CItemEx &item)
1071 if (error != k_ErrorType_OK) 1083 if (error != k_ErrorType_OK)
1072 _error = error; 1084 _error = error;
1073 1085
1074 RINOK(res); 1086 RINOK(res)
1075 1087
1076 if (filled) 1088 if (filled)
1077 { 1089 {
diff --git a/CPP/7zip/Archive/Tar/TarIn.h b/CPP/7zip/Archive/Tar/TarIn.h
index e99599a..8c69057 100644
--- a/CPP/7zip/Archive/Tar/TarIn.h
+++ b/CPP/7zip/Archive/Tar/TarIn.h
@@ -1,7 +1,7 @@
1// TarIn.h 1// TarIn.h
2 2
3#ifndef __ARCHIVE_TAR_IN_H 3#ifndef ZIP7_INC_ARCHIVE_TAR_IN_H
4#define __ARCHIVE_TAR_IN_H 4#define ZIP7_INC_ARCHIVE_TAR_IN_H
5 5
6#include "../IArchive.h" 6#include "../IArchive.h"
7 7
diff --git a/CPP/7zip/Archive/Tar/TarItem.h b/CPP/7zip/Archive/Tar/TarItem.h
index 738618f..2e12c9d 100644
--- a/CPP/7zip/Archive/Tar/TarItem.h
+++ b/CPP/7zip/Archive/Tar/TarItem.h
@@ -1,7 +1,7 @@
1// TarItem.h 1// TarItem.h
2 2
3#ifndef __ARCHIVE_TAR_ITEM_H 3#ifndef ZIP7_INC_ARCHIVE_TAR_ITEM_H
4#define __ARCHIVE_TAR_ITEM_H 4#define ZIP7_INC_ARCHIVE_TAR_ITEM_H
5 5
6#include "../../../Common/MyLinux.h" 6#include "../../../Common/MyLinux.h"
7#include "../../../Common/UTFConvert.h" 7#include "../../../Common/UTFConvert.h"
@@ -143,7 +143,7 @@ struct CItem
143 { 143 {
144 memcpy(Magic, posixMode ? 144 memcpy(Magic, posixMode ?
145 NFileHeader::NMagic::k_Posix_ustar_00 : 145 NFileHeader::NMagic::k_Posix_ustar_00 :
146 NFileHeader::NMagic::k_GNU_ustar__, 146 NFileHeader::NMagic::k_GNU_ustar,
147 8); 147 8);
148 } 148 }
149 149
@@ -172,7 +172,7 @@ struct CItem
172 172
173 void Set_LinkFlag_for_File(UInt32 mode) 173 void Set_LinkFlag_for_File(UInt32 mode)
174 { 174 {
175 Byte lf = NFileHeader::NLinkFlag::kNormal; 175 char lf = NFileHeader::NLinkFlag::kNormal;
176 if (MY_LIN_S_ISCHR(mode)) lf = NFileHeader::NLinkFlag::kCharacter; 176 if (MY_LIN_S_ISCHR(mode)) lf = NFileHeader::NLinkFlag::kCharacter;
177 else if (MY_LIN_S_ISBLK(mode)) lf = NFileHeader::NLinkFlag::kBlock; 177 else if (MY_LIN_S_ISBLK(mode)) lf = NFileHeader::NLinkFlag::kBlock;
178 else if (MY_LIN_S_ISFIFO(mode)) lf = NFileHeader::NLinkFlag::kFIFO; 178 else if (MY_LIN_S_ISFIFO(mode)) lf = NFileHeader::NLinkFlag::kFIFO;
@@ -225,7 +225,7 @@ struct CItem
225 bool IsMagic_ustar_5chars() const 225 bool IsMagic_ustar_5chars() const
226 { 226 {
227 for (unsigned i = 0; i < 5; i++) 227 for (unsigned i = 0; i < 5; i++)
228 if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar__[i]) 228 if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar[i])
229 return false; 229 return false;
230 return true; 230 return true;
231 } 231 }
@@ -241,7 +241,7 @@ struct CItem
241 bool IsMagic_GNU() const 241 bool IsMagic_GNU() const
242 { 242 {
243 for (unsigned i = 0; i < 8; i++) 243 for (unsigned i = 0; i < 8; i++)
244 if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar__[i]) 244 if (Magic[i] != NFileHeader::NMagic::k_GNU_ustar[i])
245 return false; 245 return false;
246 return true; 246 return true;
247 } 247 }
diff --git a/CPP/7zip/Archive/Tar/TarOut.cpp b/CPP/7zip/Archive/Tar/TarOut.cpp
index f73c625..26d0855 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)
60 } 60 }
61} 61}
62 62
63static void WriteOctal_12_Signed(char *s, Int64 val) 63static void WriteOctal_12_Signed(char *s, const Int64 val)
64{ 64{
65 if (val >= 0) 65 if (val >= 0)
66 { 66 {
@@ -68,10 +68,10 @@ static void WriteOctal_12_Signed(char *s, Int64 val)
68 return; 68 return;
69 } 69 }
70 s[0] = s[1] = s[2] = s[3] = (char)(Byte)0xFF; 70 s[0] = s[1] = s[2] = s[3] = (char)(Byte)0xFF;
71 WriteBin_64bit(s + 4, val); 71 WriteBin_64bit(s + 4, (UInt64)val);
72} 72}
73 73
74static void CopyString(char *dest, const AString &src, unsigned maxSize) 74static void CopyString(char *dest, const AString &src, const unsigned maxSize)
75{ 75{
76 unsigned len = src.Len(); 76 unsigned len = src.Len();
77 if (len == 0) 77 if (len == 0)
@@ -119,11 +119,11 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax
119 119
120 COPY_STRING_CHECK (cur, 120 COPY_STRING_CHECK (cur,
121 (!isPax && !Glob_Name.IsEmpty()) ? Glob_Name : item.Name, 121 (!isPax && !Glob_Name.IsEmpty()) ? Glob_Name : item.Name,
122 kNameSize); 122 kNameSize)
123 123
124 WRITE_OCTAL_8_CHECK (cur, item.Mode); cur += 8; // & k_7_oct_digits_Val_Max 124 WRITE_OCTAL_8_CHECK (cur, item.Mode) cur += 8; // & k_7_oct_digits_Val_Max
125 WRITE_OCTAL_8_CHECK (cur, item.UID); cur += 8; 125 WRITE_OCTAL_8_CHECK (cur, item.UID) cur += 8;
126 WRITE_OCTAL_8_CHECK (cur, item.GID); cur += 8; 126 WRITE_OCTAL_8_CHECK (cur, item.GID) cur += 8;
127 127
128 WriteOctal_12 (cur, /* zero_PackSize ? 0 : */ item.PackSize); cur += 12; 128 WriteOctal_12 (cur, /* zero_PackSize ? 0 : */ item.PackSize); cur += 12;
129 WriteOctal_12_Signed (cur, /* zero_MTime ? 0 : */ item.MTime); cur += 12; 129 WriteOctal_12_Signed (cur, /* zero_MTime ? 0 : */ item.MTime); cur += 12;
@@ -135,13 +135,13 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax
135 135
136 *cur++ = item.LinkFlag; 136 *cur++ = item.LinkFlag;
137 137
138 COPY_STRING_CHECK (cur, item.LinkName, kNameSize); 138 COPY_STRING_CHECK (cur, item.LinkName, kNameSize)
139 139
140 memcpy(cur, item.Magic, 8); 140 memcpy(cur, item.Magic, 8);
141 cur += 8; 141 cur += 8;
142 142
143 COPY_STRING_CHECK (cur, item.User, kUserNameSize); 143 COPY_STRING_CHECK (cur, item.User, kUserNameSize)
144 COPY_STRING_CHECK (cur, item.Group, kGroupNameSize); 144 COPY_STRING_CHECK (cur, item.Group, kGroupNameSize)
145 145
146 const bool needDevice = (IsPosixMode && !isPax); 146 const bool needDevice = (IsPosixMode && !isPax);
147 147
@@ -159,7 +159,7 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax
159 159
160 if (!isPax && !Prefix.IsEmpty()) 160 if (!isPax && !Prefix.IsEmpty())
161 { 161 {
162 COPY_STRING_CHECK (cur, Prefix, kPrefixSize); 162 COPY_STRING_CHECK (cur, Prefix, kPrefixSize)
163 } 163 }
164 164
165 if (item.Is_Sparse()) 165 if (item.Is_Sparse())
@@ -194,7 +194,7 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax
194 record[148 + 7] = ' '; // we need it, if we use binary init 194 record[148 + 7] = ' '; // we need it, if we use binary init
195 } 195 }
196 196
197 RINOK(Write_Data(record, kRecordSize)); 197 RINOK(Write_Data(record, kRecordSize))
198 198
199 if (item.Is_Sparse()) 199 if (item.Is_Sparse())
200 { 200 {
@@ -209,7 +209,7 @@ HRESULT COutArchive::WriteHeaderReal(const CItem &item, bool isPax
209 WriteOctal_12(p + 12, sb.Size); 209 WriteOctal_12(p + 12, sb.Size);
210 } 210 }
211 record[21 * 24] = (char)(i < item.SparseBlocks.Size() ? 1 : 0); 211 record[21 * 24] = (char)(i < item.SparseBlocks.Size() ? 1 : 0);
212 RINOK(Write_Data(record, kRecordSize)); 212 RINOK(Write_Data(record, kRecordSize))
213 } 213 }
214 } 214 }
215 215
@@ -237,11 +237,11 @@ static void AddPaxLine(AString &s, const char *name, const AString &val)
237 s.Add_LF(); 237 s.Add_LF();
238} 238}
239 239
240 240// pt is defined : (pt.NumDigits >= 0)
241static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt, 241static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt,
242 const CTimeOptions &options) 242 const CTimeOptions &options)
243{ 243{
244 unsigned numDigits = pt.NumDigits; 244 unsigned numDigits = (unsigned)pt.NumDigits;
245 if (numDigits > options.NumDigitsMax) 245 if (numDigits > options.NumDigitsMax)
246 numDigits = options.NumDigitsMax; 246 numDigits = options.NumDigitsMax;
247 247
@@ -265,14 +265,14 @@ static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt,
265 if (pt.Sec < 0) 265 if (pt.Sec < 0)
266 { 266 {
267 sec = -sec; 267 sec = -sec;
268 v += '-'; 268 v.Add_Minus();
269 if (ns != 0) 269 if (ns != 0)
270 { 270 {
271 ns = 1000*1000*1000 - ns; 271 ns = 1000*1000*1000 - ns;
272 sec--; 272 sec--;
273 } 273 }
274 } 274 }
275 v.Add_UInt64(sec); 275 v.Add_UInt64((UInt64)sec);
276 } 276 }
277 277
278 if (needNs) 278 if (needNs)
@@ -291,7 +291,7 @@ static void AddPaxTime(AString &s, const char *name, const CPaxTime &pt,
291 291
292 if (!d.IsEmpty()) 292 if (!d.IsEmpty())
293 { 293 {
294 v += '.'; 294 v.Add_Dot();
295 v += d; 295 v += d;
296 // v += "1234567009999"; // for debug 296 // v += "1234567009999"; // for debug
297 // for (int y = 0; y < 1000; y++) v += '8'; // for debug 297 // for (int y = 0; y < 1000; y++) v += '8'; // for debug
@@ -467,8 +467,8 @@ HRESULT COutArchive::WriteHeader(const CItem &item)
467 // mi.LinkFlag = 'Z'; // for debug 467 // mi.LinkFlag = 'Z'; // for debug
468 mi.PackSize = paxSize; 468 mi.PackSize = paxSize;
469 // for (unsigned y = 0; y < 1; y++) { // for debug 469 // for (unsigned y = 0; y < 1; y++) { // for debug
470 RINOK(WriteHeaderReal(mi, true)); // isPax 470 RINOK(WriteHeaderReal(mi, true)) // isPax
471 RINOK(Write_Data_And_Residual(s, paxSize)); 471 RINOK(Write_Data_And_Residual(s, paxSize))
472 // } // for debug 472 // } // for debug
473 /* 473 /*
474 we can send (zero_MTime) for compatibility with gnu tar output. 474 we can send (zero_MTime) for compatibility with gnu tar output.
@@ -538,8 +538,8 @@ HRESULT COutArchive::WriteHeader(const CItem &item)
538 const unsigned nameStreamSize = name->Len() + 1; 538 const unsigned nameStreamSize = name->Len() + 1;
539 mi.PackSize = nameStreamSize; 539 mi.PackSize = nameStreamSize;
540 // for (unsigned y = 0; y < 3; y++) { // for debug 540 // for (unsigned y = 0; y < 3; y++) { // for debug
541 RINOK(WriteHeaderReal(mi)); 541 RINOK(WriteHeaderReal(mi))
542 RINOK(Write_Data_And_Residual(name->Ptr(), nameStreamSize)); 542 RINOK(Write_Data_And_Residual(name->Ptr(), nameStreamSize))
543 // } 543 // }
544 544
545 // for debug 545 // for debug
@@ -615,7 +615,7 @@ HRESULT COutArchive::Write_AfterDataResidual(UInt64 dataSize)
615 615
616HRESULT COutArchive::Write_Data_And_Residual(const void *data, unsigned size) 616HRESULT COutArchive::Write_Data_And_Residual(const void *data, unsigned size)
617{ 617{
618 RINOK(Write_Data(data, size)); 618 RINOK(Write_Data(data, size))
619 return Write_AfterDataResidual(size); 619 return Write_AfterDataResidual(size);
620} 620}
621 621
@@ -636,7 +636,7 @@ HRESULT COutArchive::WriteFinishHeader()
636 636
637 for (unsigned i = 0; i < kNumFinishRecords; i++) 637 for (unsigned i = 0; i < kNumFinishRecords; i++)
638 { 638 {
639 RINOK(Write_Data(record, kRecordSize)); 639 RINOK(Write_Data(record, kRecordSize))
640 } 640 }
641 return S_OK; 641 return S_OK;
642} 642}
diff --git a/CPP/7zip/Archive/Tar/TarOut.h b/CPP/7zip/Archive/Tar/TarOut.h
index 34af20a..7b99c26 100644
--- a/CPP/7zip/Archive/Tar/TarOut.h
+++ b/CPP/7zip/Archive/Tar/TarOut.h
@@ -1,7 +1,7 @@
1// Archive/TarOut.h 1// Archive/TarOut.h
2 2
3#ifndef __ARCHIVE_TAR_OUT_H 3#ifndef ZIP7_INC_ARCHIVE_TAR_OUT_H
4#define __ARCHIVE_TAR_OUT_H 4#define ZIP7_INC_ARCHIVE_TAR_OUT_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
diff --git a/CPP/7zip/Archive/Tar/TarRegister.cpp b/CPP/7zip/Archive/Tar/TarRegister.cpp
index a78c376..709c191 100644
--- a/CPP/7zip/Archive/Tar/TarRegister.cpp
+++ b/CPP/7zip/Archive/Tar/TarRegister.cpp
@@ -12,7 +12,7 @@ namespace NTar {
12static const Byte k_Signature[] = { 'u', 's', 't', 'a', 'r' }; 12static const Byte k_Signature[] = { 'u', 's', 't', 'a', 'r' };
13 13
14REGISTER_ARC_IO( 14REGISTER_ARC_IO(
15 "tar", "tar ova", 0, 0xEE, 15 "tar", "tar ova", NULL, 0xEE,
16 k_Signature, 16 k_Signature,
17 NFileHeader::kUstarMagic_Offset, 17 NFileHeader::kUstarMagic_Offset,
18 NArcInfoFlags::kStartOpen 18 NArcInfoFlags::kStartOpen
diff --git a/CPP/7zip/Archive/Tar/TarUpdate.cpp b/CPP/7zip/Archive/Tar/TarUpdate.cpp
index caa0a82..0b348e9 100644
--- a/CPP/7zip/Archive/Tar/TarUpdate.cpp
+++ b/CPP/7zip/Archive/Tar/TarUpdate.cpp
@@ -8,6 +8,7 @@
8 8
9#include "../../Common/LimitedStreams.h" 9#include "../../Common/LimitedStreams.h"
10#include "../../Common/ProgressUtils.h" 10#include "../../Common/ProgressUtils.h"
11#include "../../Common/StreamUtils.h"
11 12
12#include "../../Compress/CopyCoder.h" 13#include "../../Compress/CopyCoder.h"
13 14
@@ -44,7 +45,7 @@ HRESULT Prop_To_PaxTime(const NWindows::NCOM::CPropVariant &prop, CPaxTime &pt)
44 const unsigned prec = prop.wReserved1; 45 const unsigned prec = prop.wReserved1;
45 if (prec >= k_PropVar_TimePrec_Base) 46 if (prec >= k_PropVar_TimePrec_Base)
46 { 47 {
47 pt.NumDigits = prec - k_PropVar_TimePrec_Base; 48 pt.NumDigits = (int)(prec - k_PropVar_TimePrec_Base);
48 if (prop.wReserved2 < 100) 49 if (prop.wReserved2 < 100)
49 ns += prop.wReserved2; 50 ns += prop.wReserved2;
50 } 51 }
@@ -58,7 +59,7 @@ static HRESULT GetTime(IStreamGetProp *getProp, UInt32 pid, CPaxTime &pt)
58{ 59{
59 pt.Clear(); 60 pt.Clear();
60 NWindows::NCOM::CPropVariant prop; 61 NWindows::NCOM::CPropVariant prop;
61 RINOK(getProp->GetProperty(pid, &prop)); 62 RINOK(getProp->GetProperty(pid, &prop))
62 return Prop_To_PaxTime(prop, pt); 63 return Prop_To_PaxTime(prop, pt);
63} 64}
64 65
@@ -73,7 +74,7 @@ static HRESULT GetUser(IStreamGetProp *getProp,
73 bool isSet = false; 74 bool isSet = false;
74 { 75 {
75 NWindows::NCOM::CPropVariant prop; 76 NWindows::NCOM::CPropVariant prop;
76 RINOK(getProp->GetProperty(pidId, &prop)); 77 RINOK(getProp->GetProperty(pidId, &prop))
77 if (prop.vt == VT_UI4) 78 if (prop.vt == VT_UI4)
78 { 79 {
79 isSet = true; 80 isSet = true;
@@ -85,7 +86,7 @@ static HRESULT GetUser(IStreamGetProp *getProp,
85 } 86 }
86 { 87 {
87 NWindows::NCOM::CPropVariant prop; 88 NWindows::NCOM::CPropVariant prop;
88 RINOK(getProp->GetProperty(pidName, &prop)); 89 RINOK(getProp->GetProperty(pidName, &prop))
89 if (prop.vt == VT_BSTR) 90 if (prop.vt == VT_BSTR)
90 { 91 {
91 const UString s = prop.bstrVal; 92 const UString s = prop.bstrVal;
@@ -133,7 +134,7 @@ static HRESULT GetDevice(IStreamGetProp *getProp,
133{ 134{
134 defined = false; 135 defined = false;
135 NWindows::NCOM::CPropVariant prop; 136 NWindows::NCOM::CPropVariant prop;
136 RINOK(getProp->GetProperty(pid, &prop)); 137 RINOK(getProp->GetProperty(pid, &prop))
137 if (prop.vt == VT_EMPTY) 138 if (prop.vt == VT_EMPTY)
138 return S_OK; 139 return S_OK;
139 if (prop.vt == VT_UI4) 140 if (prop.vt == VT_UI4)
@@ -158,8 +159,10 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
158 outArchive.IsPosixMode = options.PosixMode; 159 outArchive.IsPosixMode = options.PosixMode;
159 outArchive.TimeOptions = options.TimeOptions; 160 outArchive.TimeOptions = options.TimeOptions;
160 161
161 CMyComPtr<IOutStream> outSeekStream; 162 Z7_DECL_CMyComPtr_QI_FROM(IOutStream, outSeekStream, outStream)
162 outStream->QueryInterface(IID_IOutStream, (void **)&outSeekStream); 163 Z7_DECL_CMyComPtr_QI_FROM(IStreamSetRestriction, setRestriction, outStream)
164 Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackFile, opCallback, outStream)
165
163 if (outSeekStream) 166 if (outSeekStream)
164 { 167 {
165 /* 168 /*
@@ -169,12 +172,10 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
169 RINOK(outStream->Write(buf, sizeof(buf), NULL)); 172 RINOK(outStream->Write(buf, sizeof(buf), NULL));
170 */ 173 */
171 // we need real outArchive.Pos, if outSeekStream->SetSize() will be used. 174 // we need real outArchive.Pos, if outSeekStream->SetSize() will be used.
172 RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &outArchive.Pos)); 175 RINOK(outSeekStream->Seek(0, STREAM_SEEK_CUR, &outArchive.Pos))
173 } 176 }
174 177 if (setRestriction)
175 178 RINOK(setRestriction->SetRestriction(0, 0))
176 CMyComPtr<IArchiveUpdateCallbackFile> opCallback;
177 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback);
178 179
179 UInt64 complexity = 0; 180 UInt64 complexity = 0;
180 181
@@ -188,7 +189,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
188 complexity += inputItems[(unsigned)ui.IndexInArc].Get_FullSize_Aligned(); 189 complexity += inputItems[(unsigned)ui.IndexInArc].Get_FullSize_Aligned();
189 } 190 }
190 191
191 RINOK(updateCallback->SetTotal(complexity)); 192 RINOK(updateCallback->SetTotal(complexity))
192 193
193 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; 194 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
194 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; 195 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
@@ -198,7 +199,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
198 lps->Init(updateCallback, true); 199 lps->Init(updateCallback, true);
199 200
200 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; 201 CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
201 CMyComPtr<CLimitedSequentialInStream> inStreamLimited(streamSpec); 202 CMyComPtr<ISequentialInStream> inStreamLimited(streamSpec);
202 streamSpec->SetStream(inStream); 203 streamSpec->SetStream(inStream);
203 204
204 complexity = 0; 205 complexity = 0;
@@ -208,10 +209,14 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
208 for (i = 0;; i++) 209 for (i = 0;; i++)
209 { 210 {
210 lps->InSize = lps->OutSize = complexity; 211 lps->InSize = lps->OutSize = complexity;
211 RINOK(lps->SetCur()); 212 RINOK(lps->SetCur())
212 213
213 if (i == updateItems.Size()) 214 if (i == updateItems.Size())
215 {
216 if (outSeekStream && setRestriction)
217 RINOK(setRestriction->SetRestriction(0, 0))
214 return outArchive.WriteFinishHeader(); 218 return outArchive.WriteFinishHeader();
219 }
215 220
216 const CUpdateItem &ui = updateItems[i]; 221 const CUpdateItem &ui = updateItems[i];
217 CItem item; 222 CItem item;
@@ -253,7 +258,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
253 if (ui.NewData || ui.NewProps) 258 if (ui.NewData || ui.NewProps)
254 { 259 {
255 RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidSymLink, symLink, 260 RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidSymLink, symLink,
256 options.CodePage, options.UtfFlags, true)); 261 options.CodePage, options.UtfFlags, true))
257 if (!symLink.IsEmpty()) 262 if (!symLink.IsEmpty())
258 { 263 {
259 item.LinkFlag = NFileHeader::NLinkFlag::kSymLink; 264 item.LinkFlag = NFileHeader::NLinkFlag::kSymLink;
@@ -286,7 +291,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
286 needWrite = false; 291 needWrite = false;
287 else 292 else
288 { 293 {
289 RINOK(res); 294 RINOK(res)
290 295
291 if (!fileInStream) 296 if (!fileInStream)
292 { 297 {
@@ -295,9 +300,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
295 } 300 }
296 else 301 else
297 { 302 {
298 CMyComPtr<IStreamGetProps> getProps; 303 Z7_DECL_CMyComPtr_QI_FROM(IStreamGetProp, getProp, fileInStream)
299 CMyComPtr<IStreamGetProp> getProp;
300 fileInStream->QueryInterface(IID_IStreamGetProp, (void **)&getProp);
301 if (getProp) 304 if (getProp)
302 { 305 {
303 if (options.Write_MTime.Val) RINOK(GetTime(getProp, kpidMTime, item.PaxTimes.MTime)) 306 if (options.Write_MTime.Val) RINOK(GetTime(getProp, kpidMTime, item.PaxTimes.MTime))
@@ -312,23 +315,23 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
312 */ 315 */
313 bool defined = false; 316 bool defined = false;
314 UInt32 val = 0; 317 UInt32 val = 0;
315 RINOK(GetDevice(getProp, kpidDeviceMajor, val, defined)); 318 RINOK(GetDevice(getProp, kpidDeviceMajor, val, defined))
316 if (defined) 319 if (defined)
317 { 320 {
318 item.DeviceMajor = val; 321 item.DeviceMajor = val;
319 item.DeviceMajor_Defined = true; 322 item.DeviceMajor_Defined = true;
320 item.DeviceMinor = 0; 323 item.DeviceMinor = 0;
321 item.DeviceMinor_Defined = false; 324 item.DeviceMinor_Defined = false;
322 RINOK(GetDevice(getProp, kpidDeviceMinor, item.DeviceMinor, item.DeviceMinor_Defined)); 325 RINOK(GetDevice(getProp, kpidDeviceMinor, item.DeviceMinor, item.DeviceMinor_Defined))
323 } 326 }
324 } 327 }
325 328
326 RINOK(GetUser(getProp, kpidUser, kpidUserId, item.User, item.UID, options.CodePage, options.UtfFlags)); 329 RINOK(GetUser(getProp, kpidUser, kpidUserId, item.User, item.UID, options.CodePage, options.UtfFlags))
327 RINOK(GetUser(getProp, kpidGroup, kpidGroupId, item.Group, item.GID, options.CodePage, options.UtfFlags)); 330 RINOK(GetUser(getProp, kpidGroup, kpidGroupId, item.Group, item.GID, options.CodePage, options.UtfFlags))
328 331
329 { 332 {
330 NWindows::NCOM::CPropVariant prop; 333 NWindows::NCOM::CPropVariant prop;
331 RINOK(getProp->GetProperty(kpidPosixAttrib, &prop)); 334 RINOK(getProp->GetProperty(kpidPosixAttrib, &prop))
332 if (prop.vt == VT_EMPTY) 335 if (prop.vt == VT_EMPTY)
333 item.Mode = 336 item.Mode =
334 MY_LIN_S_IRWXO 337 MY_LIN_S_IRWXO
@@ -346,7 +349,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
346 349
347 { 350 {
348 NWindows::NCOM::CPropVariant prop; 351 NWindows::NCOM::CPropVariant prop;
349 RINOK(getProp->GetProperty(kpidSize, &prop)); 352 RINOK(getProp->GetProperty(kpidSize, &prop))
350 if (prop.vt != VT_UI8) 353 if (prop.vt != VT_UI8)
351 return E_INVALIDARG; 354 return E_INVALIDARG;
352 const UInt64 size = prop.uhVal.QuadPart; 355 const UInt64 size = prop.uhVal.QuadPart;
@@ -361,7 +364,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
361 } 364 }
362 else 365 else
363 { 366 {
364 fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); 367 Z7_DECL_CMyComPtr_QI_FROM(IStreamGetProps, getProps, fileInStream)
365 if (getProps) 368 if (getProps)
366 { 369 {
367 FILETIME mTime, aTime, cTime; 370 FILETIME mTime, aTime, cTime;
@@ -386,7 +389,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
386 // we must request kpidHardLink after updateCallback->GetStream() 389 // we must request kpidHardLink after updateCallback->GetStream()
387 AString hardLink; 390 AString hardLink;
388 RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidHardLink, hardLink, 391 RINOK(GetPropString(updateCallback, ui.IndexInClient, kpidHardLink, hardLink,
389 options.CodePage, options.UtfFlags, true)); 392 options.CodePage, options.UtfFlags, true))
390 if (!hardLink.IsEmpty()) 393 if (!hardLink.IsEmpty())
391 { 394 {
392 item.LinkFlag = NFileHeader::NLinkFlag::kHardLink; 395 item.LinkFlag = NFileHeader::NLinkFlag::kHardLink;
@@ -408,7 +411,11 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
408 { 411 {
409 const UInt64 headerPos = outArchive.Pos; 412 const UInt64 headerPos = outArchive.Pos;
410 // item.PackSize = ((UInt64)1 << 33); // for debug 413 // item.PackSize = ((UInt64)1 << 33); // for debug
411 RINOK(outArchive.WriteHeader(item)); 414
415 if (outSeekStream && setRestriction)
416 RINOK(setRestriction->SetRestriction(outArchive.Pos, (UInt64)(Int64)-1))
417
418 RINOK(outArchive.WriteHeader(item))
412 if (fileInStream) 419 if (fileInStream)
413 { 420 {
414 for (unsigned numPasses = 0;; numPasses++) 421 for (unsigned numPasses = 0;; numPasses++)
@@ -424,9 +431,9 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
424 } 431 }
425 432
426 const UInt64 dataPos = outArchive.Pos; 433 const UInt64 dataPos = outArchive.Pos;
427 RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress)); 434 RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress))
428 outArchive.Pos += copyCoderSpec->TotalSize; 435 outArchive.Pos += copyCoderSpec->TotalSize;
429 RINOK(outArchive.Write_AfterDataResidual(copyCoderSpec->TotalSize)); 436 RINOK(outArchive.Write_AfterDataResidual(copyCoderSpec->TotalSize))
430 437
431 // if (numPasses >= 10) // for debug 438 // if (numPasses >= 10) // for debug
432 if (copyCoderSpec->TotalSize == item.PackSize) 439 if (copyCoderSpec->TotalSize == item.PackSize)
@@ -442,11 +449,11 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
442 if (!outSeekStream) 449 if (!outSeekStream)
443 return E_FAIL; 450 return E_FAIL;
444 const UInt64 nextPos = outArchive.Pos; 451 const UInt64 nextPos = outArchive.Pos;
445 RINOK(outSeekStream->Seek(-(Int64)(nextPos - headerPos), STREAM_SEEK_CUR, NULL)); 452 RINOK(outSeekStream->Seek(-(Int64)(nextPos - headerPos), STREAM_SEEK_CUR, NULL))
446 outArchive.Pos = headerPos; 453 outArchive.Pos = headerPos;
447 item.PackSize = copyCoderSpec->TotalSize; 454 item.PackSize = copyCoderSpec->TotalSize;
448 455
449 RINOK(outArchive.WriteHeader(item)); 456 RINOK(outArchive.WriteHeader(item))
450 457
451 // if (numPasses >= 10) // for debug 458 // if (numPasses >= 10) // for debug
452 if (outArchive.Pos == dataPos) 459 if (outArchive.Pos == dataPos)
@@ -454,7 +461,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
454 const UInt64 alignedSize = nextPos - dataPos; 461 const UInt64 alignedSize = nextPos - dataPos;
455 if (alignedSize != 0) 462 if (alignedSize != 0)
456 { 463 {
457 RINOK(outSeekStream->Seek(alignedSize, STREAM_SEEK_CUR, NULL)); 464 RINOK(outSeekStream->Seek((Int64)alignedSize, STREAM_SEEK_CUR, NULL))
458 outArchive.Pos += alignedSize; 465 outArchive.Pos += alignedSize;
459 } 466 }
460 break; 467 break;
@@ -462,12 +469,11 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
462 469
463 // size of header was changed. 470 // size of header was changed.
464 // we remove data after header and try new attempt, if required 471 // we remove data after header and try new attempt, if required
465 CMyComPtr<IInStream> fileSeekStream; 472 Z7_DECL_CMyComPtr_QI_FROM(IInStream, fileSeekStream, fileInStream)
466 fileInStream->QueryInterface(IID_IInStream, (void **)&fileSeekStream);
467 if (!fileSeekStream) 473 if (!fileSeekStream)
468 return E_FAIL; 474 return E_FAIL;
469 RINOK(fileSeekStream->Seek(0, STREAM_SEEK_SET, NULL)); 475 RINOK(InStream_SeekToBegin(fileSeekStream))
470 RINOK(outSeekStream->SetSize(outArchive.Pos)); 476 RINOK(outSeekStream->SetSize(outArchive.Pos))
471 if (item.PackSize == 0) 477 if (item.PackSize == 0)
472 break; 478 break;
473 } 479 }
@@ -476,7 +482,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
476 482
477 complexity += item.PackSize; 483 complexity += item.PackSize;
478 fileInStream.Release(); 484 fileInStream.Release();
479 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 485 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
480 } 486 }
481 else 487 else
482 { 488 {
@@ -518,7 +524,7 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
518 item.UID = existItem.UID; 524 item.UID = existItem.UID;
519 item.GID = existItem.GID; 525 item.GID = existItem.GID;
520 526
521 RINOK(outArchive.WriteHeader(item)); 527 RINOK(outArchive.WriteHeader(item))
522 size = existItem.Get_PackSize_Aligned(); 528 size = existItem.Get_PackSize_Aligned();
523 pos = existItem.Get_DataPos(); 529 pos = existItem.Get_DataPos();
524 } 530 }
@@ -530,10 +536,12 @@ HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
530 536
531 if (size != 0) 537 if (size != 0)
532 { 538 {
533 RINOK(inStream->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); 539 RINOK(InStream_SeekSet(inStream, pos))
534 streamSpec->Init(size); 540 streamSpec->Init(size);
541 if (outSeekStream && setRestriction)
542 RINOK(setRestriction->SetRestriction(0, 0))
535 // 22.00 : we copy Residual data from old archive to new archive instead of zeroing 543 // 22.00 : we copy Residual data from old archive to new archive instead of zeroing
536 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); 544 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress))
537 if (copyCoderSpec->TotalSize != size) 545 if (copyCoderSpec->TotalSize != size)
538 return E_FAIL; 546 return E_FAIL;
539 outArchive.Pos += size; 547 outArchive.Pos += size;
diff --git a/CPP/7zip/Archive/Tar/TarUpdate.h b/CPP/7zip/Archive/Tar/TarUpdate.h
index ca0976d..f6c2e77 100644
--- a/CPP/7zip/Archive/Tar/TarUpdate.h
+++ b/CPP/7zip/Archive/Tar/TarUpdate.h
@@ -1,7 +1,7 @@
1// TarUpdate.h 1// TarUpdate.h
2 2
3#ifndef __TAR_UPDATE_H 3#ifndef ZIP7_INC_TAR_UPDATE_H
4#define __TAR_UPDATE_H 4#define ZIP7_INC_TAR_UPDATE_H
5 5
6#include "../IArchive.h" 6#include "../IArchive.h"
7 7
diff --git a/CPP/7zip/Archive/Udf/StdAfx.h b/CPP/7zip/Archive/Udf/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Udf/StdAfx.h
+++ b/CPP/7zip/Archive/Udf/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/Udf/UdfHandler.cpp b/CPP/7zip/Archive/Udf/UdfHandler.cpp
index 691199e..ae6113f 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
26 if (!NWindows::NTime::GetSecondsSince1601(t.GetYear(), d[4], d[5], d[6], d[7], d[8], numSecs)) 26 if (!NWindows::NTime::GetSecondsSince1601(t.GetYear(), d[4], d[5], d[6], d[7], d[8], numSecs))
27 return; 27 return;
28 if (t.IsLocal()) 28 if (t.IsLocal())
29 numSecs -= (Int64)((Int32)t.GetMinutesOffset() * 60); 29 numSecs = (UInt64)((Int64)numSecs - (Int64)((Int32)t.GetMinutesOffset() * 60));
30 const UInt32 m0 = d[9]; 30 const UInt32 m0 = d[9];
31 const UInt32 m1 = d[10]; 31 const UInt32 m1 = d[10];
32 const UInt32 m2 = d[11]; 32 const UInt32 m2 = d[11];
@@ -69,7 +69,7 @@ static const Byte kArcProps[] =
69IMP_IInArchive_Props 69IMP_IInArchive_Props
70IMP_IInArchive_ArcProps 70IMP_IInArchive_ArcProps
71 71
72STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 72Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
73{ 73{
74 COM_TRY_BEGIN 74 COM_TRY_BEGIN
75 NWindows::NCOM::CPropVariant prop; 75 NWindows::NCOM::CPropVariant prop;
@@ -144,15 +144,15 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
144 COM_TRY_END 144 COM_TRY_END
145} 145}
146 146
147class CProgressImp: public CProgressVirt 147class CProgressImp Z7_final: public CProgressVirt
148{ 148{
149 CMyComPtr<IArchiveOpenCallback> _callback; 149 CMyComPtr<IArchiveOpenCallback> _callback;
150 UInt64 _numFiles; 150 UInt64 _numFiles;
151 UInt64 _numBytes; 151 UInt64 _numBytes;
152public: 152public:
153 HRESULT SetTotal(UInt64 numBytes); 153 HRESULT SetTotal(UInt64 numBytes) Z7_override;
154 HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes); 154 HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) Z7_override;
155 HRESULT SetCompleted(); 155 HRESULT SetCompleted() Z7_override;
156 CProgressImp(IArchiveOpenCallback *callback): _callback(callback), _numFiles(0), _numBytes(0) {} 156 CProgressImp(IArchiveOpenCallback *callback): _callback(callback), _numFiles(0), _numBytes(0) {}
157}; 157};
158 158
@@ -177,13 +177,13 @@ HRESULT CProgressImp::SetCompleted()
177 return S_OK; 177 return S_OK;
178} 178}
179 179
180STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback) 180Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback))
181{ 181{
182 COM_TRY_BEGIN 182 COM_TRY_BEGIN
183 { 183 {
184 Close(); 184 Close();
185 CProgressImp progressImp(callback); 185 CProgressImp progressImp(callback);
186 RINOK(_archive.Open(stream, &progressImp)); 186 RINOK(_archive.Open(stream, &progressImp))
187 bool showVolName = (_archive.LogVols.Size() > 1); 187 bool showVolName = (_archive.LogVols.Size() > 1);
188 FOR_VECTOR (volIndex, _archive.LogVols) 188 FOR_VECTOR (volIndex, _archive.LogVols)
189 { 189 {
@@ -209,7 +209,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
209 COM_TRY_END 209 COM_TRY_END
210} 210}
211 211
212STDMETHODIMP CHandler::Close() 212Z7_COM7F_IMF(CHandler::Close())
213{ 213{
214 _inStream.Release(); 214 _inStream.Release();
215 _archive.Clear(); 215 _archive.Clear();
@@ -217,13 +217,13 @@ STDMETHODIMP CHandler::Close()
217 return S_OK; 217 return S_OK;
218} 218}
219 219
220STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 220Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
221{ 221{
222 *numItems = _refs2.Size(); 222 *numItems = _refs2.Size();
223 return S_OK; 223 return S_OK;
224} 224}
225 225
226STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 226Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
227{ 227{
228 COM_TRY_BEGIN 228 COM_TRY_BEGIN
229 NWindows::NCOM::CPropVariant prop; 229 NWindows::NCOM::CPropVariant prop;
@@ -258,9 +258,9 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
258 COM_TRY_END 258 COM_TRY_END
259} 259}
260 260
261STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 261Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
262{ 262{
263 *stream = 0; 263 *stream = NULL;
264 264
265 const CRef2 &ref2 = _refs2[index]; 265 const CRef2 &ref2 = _refs2[index];
266 const CLogVol &vol = _archive.LogVols[ref2.Vol]; 266 const CLogVol &vol = _archive.LogVols[ref2.Vol];
@@ -318,11 +318,11 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
318 return S_OK; 318 return S_OK;
319} 319}
320 320
321STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 321Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
322 Int32 testMode, IArchiveExtractCallback *extractCallback) 322 Int32 testMode, IArchiveExtractCallback *extractCallback))
323{ 323{
324 COM_TRY_BEGIN 324 COM_TRY_BEGIN
325 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 325 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
326 if (allFilesMode) 326 if (allFilesMode)
327 numItems = _refs2.Size(); 327 numItems = _refs2.Size();
328 if (numItems == 0) 328 if (numItems == 0)
@@ -357,14 +357,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
357 for (i = 0; i < numItems; i++) 357 for (i = 0; i < numItems; i++)
358 { 358 {
359 lps->InSize = lps->OutSize = currentTotalSize; 359 lps->InSize = lps->OutSize = currentTotalSize;
360 RINOK(lps->SetCur()); 360 RINOK(lps->SetCur())
361 CMyComPtr<ISequentialOutStream> realOutStream; 361 CMyComPtr<ISequentialOutStream> realOutStream;
362 Int32 askMode = testMode ? 362 const Int32 askMode = testMode ?
363 NExtract::NAskMode::kTest : 363 NExtract::NAskMode::kTest :
364 NExtract::NAskMode::kExtract; 364 NExtract::NAskMode::kExtract;
365 UInt32 index = allFilesMode ? i : indices[i]; 365 const UInt32 index = allFilesMode ? i : indices[i];
366 366
367 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 367 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
368 368
369 const CRef2 &ref2 = _refs2[index]; 369 const CRef2 &ref2 = _refs2[index];
370 const CRef &ref = _archive.LogVols[ref2.Vol].FileSets[ref2.Fs].Refs[ref2.Ref]; 370 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,
373 373
374 if (item.IsDir()) 374 if (item.IsDir())
375 { 375 {
376 RINOK(extractCallback->PrepareOperation(askMode)); 376 RINOK(extractCallback->PrepareOperation(askMode))
377 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 377 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
378 continue; 378 continue;
379 } 379 }
380 currentTotalSize += item.Size; 380 currentTotalSize += item.Size;
@@ -382,7 +382,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
382 if (!testMode && !realOutStream) 382 if (!testMode && !realOutStream)
383 continue; 383 continue;
384 384
385 RINOK(extractCallback->PrepareOperation(askMode)); 385 RINOK(extractCallback->PrepareOperation(askMode))
386 outStreamSpec->SetStream(realOutStream); 386 outStreamSpec->SetStream(realOutStream);
387 realOutStream.Release(); 387 realOutStream.Release();
388 outStreamSpec->Init(item.Size); 388 outStreamSpec->Init(item.Size);
@@ -395,13 +395,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
395 opRes = NExtract::NOperationResult::kDataError; 395 opRes = NExtract::NOperationResult::kDataError;
396 else 396 else
397 { 397 {
398 RINOK(copyCoder->Code(udfInStream, outStream, NULL, NULL, progress)); 398 RINOK(copyCoder->Code(udfInStream, outStream, NULL, NULL, progress))
399 opRes = outStreamSpec->IsFinishedOK() ? 399 opRes = outStreamSpec->IsFinishedOK() ?
400 NExtract::NOperationResult::kOK: 400 NExtract::NOperationResult::kOK:
401 NExtract::NOperationResult::kDataError; 401 NExtract::NOperationResult::kDataError;
402 } 402 }
403 outStreamSpec->ReleaseStream(); 403 outStreamSpec->ReleaseStream();
404 RINOK(extractCallback->SetOperationResult(opRes)); 404 RINOK(extractCallback->SetOperationResult(opRes))
405 } 405 }
406 return S_OK; 406 return S_OK;
407 COM_TRY_END 407 COM_TRY_END
@@ -410,12 +410,18 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
410static const UInt32 kIsoStartPos = 0x8000; 410static const UInt32 kIsoStartPos = 0x8000;
411 411
412// 5, { 0, 'N', 'S', 'R', '0' }, 412// 5, { 0, 'N', 'S', 'R', '0' },
413static const Byte k_Signature[] = { 1, 'C', 'D', '0', '0', '1' }; 413
414static const Byte k_Signature[] =
415{
416 8, 0, 'B', 'E', 'A', '0', '1', 1, 0,
417 6, 1, 'C', 'D', '0', '0', '1'
418};
414 419
415REGISTER_ARC_I( 420REGISTER_ARC_I(
416 "Udf", "udf iso img", 0, 0xE0, 421 "Udf", "udf iso img", NULL, 0xE0,
417 k_Signature, 422 k_Signature,
418 kIsoStartPos, 423 kIsoStartPos,
424 NArcInfoFlags::kMultiSignature |
419 NArcInfoFlags::kStartOpen, 425 NArcInfoFlags::kStartOpen,
420 IsArc_Udf) 426 IsArc_Udf)
421 427
diff --git a/CPP/7zip/Archive/Udf/UdfHandler.h b/CPP/7zip/Archive/Udf/UdfHandler.h
index 462faee..5426d06 100644
--- a/CPP/7zip/Archive/Udf/UdfHandler.h
+++ b/CPP/7zip/Archive/Udf/UdfHandler.h
@@ -1,7 +1,7 @@
1// UdfHandler.h 1// UdfHandler.h
2 2
3#ifndef __UDF_HANDLER_H 3#ifndef ZIP7_INC_UDF_HANDLER_H
4#define __UDF_HANDLER_H 4#define ZIP7_INC_UDF_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -19,18 +19,12 @@ struct CRef2
19 unsigned Ref; 19 unsigned Ref;
20}; 20};
21 21
22class CHandler: 22Z7_CLASS_IMP_CHandler_IInArchive_1(
23 public IInArchive, 23 IInArchiveGetStream
24 public IInArchiveGetStream, 24)
25 public CMyUnknownImp
26{
27 CRecordVector<CRef2> _refs2; 25 CRecordVector<CRef2> _refs2;
28 CMyComPtr<IInStream> _inStream; 26 CMyComPtr<IInStream> _inStream;
29 CInArchive _archive; 27 CInArchive _archive;
30public:
31 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
32 INTERFACE_IInArchive(;)
33 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
34}; 28};
35 29
36}} 30}}
diff --git a/CPP/7zip/Archive/Udf/UdfIn.cpp b/CPP/7zip/Archive/Udf/UdfIn.cpp
index 70496e4..13d84e0 100644
--- a/CPP/7zip/Archive/Udf/UdfIn.cpp
+++ b/CPP/7zip/Archive/Udf/UdfIn.cpp
@@ -27,9 +27,9 @@
27#define Get32(p) GetUi32(p) 27#define Get32(p) GetUi32(p)
28#define Get64(p) GetUi64(p) 28#define Get64(p) GetUi64(p)
29 29
30#define G16(_offs_, dest) dest = Get16(p + (_offs_)); 30#define G16(_offs_, dest) dest = Get16(p + (_offs_))
31#define G32(_offs_, dest) dest = Get32(p + (_offs_)); 31#define G32(_offs_, dest) dest = Get32(p + (_offs_))
32#define G64(_offs_, dest) dest = Get64(p + (_offs_)); 32#define G64(_offs_, dest) dest = Get64(p + (_offs_))
33 33
34namespace NArchive { 34namespace NArchive {
35namespace NUdf { 35namespace NUdf {
@@ -50,7 +50,7 @@ static const UInt64 kInlineExtentsSizeMax = (UInt64)1 << 33;
50#define kCrc16Poly 0x1021 50#define kCrc16Poly 0x1021
51static UInt16 g_Crc16Table[256]; 51static UInt16 g_Crc16Table[256];
52 52
53static void MY_FAST_CALL Crc16GenerateTable(void) 53static void Z7_FASTCALL Crc16GenerateTable(void)
54{ 54{
55 UInt32 i; 55 UInt32 i;
56 for (i = 0; i < 256; i++) 56 for (i = 0; i < 256; i++)
@@ -62,7 +62,7 @@ static void MY_FAST_CALL Crc16GenerateTable(void)
62 } 62 }
63} 63}
64 64
65static UInt32 MY_FAST_CALL Crc16Calc(const void *data, size_t size) 65static UInt32 Z7_FASTCALL Crc16Calc(const void *data, size_t size)
66{ 66{
67 UInt32 v = CRC16_INIT_VAL; 67 UInt32 v = CRC16_INIT_VAL;
68 const Byte *p = (const Byte *)data; 68 const Byte *p = (const Byte *)data;
@@ -176,7 +176,7 @@ void CRegId::AddUdfVersionTo(UString &s) const
176 char temp[16]; 176 char temp[16];
177 ConvertUInt32ToHex(major, temp); 177 ConvertUInt32ToHex(major, temp);
178 s += temp; 178 s += temp;
179 s += '.'; 179 s.Add_Dot();
180 ConvertUInt32ToHex8Digits(minor, temp); 180 ConvertUInt32ToHex8Digits(minor, temp);
181 s += &temp[8 - 2]; 181 s += &temp[8 - 2];
182 } 182 }
@@ -346,7 +346,7 @@ HRESULT CInArchive::Read(unsigned volIndex, unsigned partitionRef, UInt32 blockP
346 const CLogVol &vol = LogVols[volIndex]; 346 const CLogVol &vol = LogVols[volIndex];
347 const CPartition &partition = Partitions[vol.PartitionMaps[partitionRef].PartitionIndex]; 347 const CPartition &partition = Partitions[vol.PartitionMaps[partitionRef].PartitionIndex];
348 UInt64 offset = ((UInt64)partition.Pos << SecLogSize) + (UInt64)blockPos * vol.BlockSize; 348 UInt64 offset = ((UInt64)partition.Pos << SecLogSize) + (UInt64)blockPos * vol.BlockSize;
349 RINOK(_stream->Seek(offset, STREAM_SEEK_SET, NULL)); 349 RINOK(InStream_SeekSet(_stream, offset))
350 offset += len; 350 offset += len;
351 UpdatePhySize(offset); 351 UpdatePhySize(offset);
352 const HRESULT res = ReadStream_FALSE(_stream, buf, len); 352 const HRESULT res = ReadStream_FALSE(_stream, buf, len);
@@ -375,7 +375,7 @@ HRESULT CInArchive::ReadFromFile(unsigned volIndex, const CItem &item, CByteBuff
375 { 375 {
376 const CMyExtent &e = item.Extents[i]; 376 const CMyExtent &e = item.Extents[i];
377 const UInt32 len = e.GetLen(); 377 const UInt32 len = e.GetLen();
378 RINOK(Read(volIndex, e.PartitionRef, e.Pos, len, (Byte *)buf + pos)); 378 RINOK(Read(volIndex, e.PartitionRef, e.Pos, len, (Byte *)buf + pos))
379 pos += len; 379 pos += len;
380 } 380 }
381 return S_OK; 381 return S_OK;
@@ -447,6 +447,19 @@ void CItem::Parse(const Byte *p)
447 447
448 448
449// ECMA 4/14.4 449// ECMA 4/14.4
450// UDF 2.3.4
451
452/*
453File Characteristics:
454Deleted bit:
455 ECMA: If set to ONE, shall mean this File Identifier Descriptor
456 identifies a file that has been deleted;
457 UDF: If the space for the file or directory is deallocated,
458 the implementation shall set the ICB field to zero.
459 ECMA 167 4/8.6 requires that the File Identifiers of all FIDs in a directory shall be unique.
460 The implementations shall follow these rules when a Deleted bit is set:
461 rewrire the compression ID of the File Identifier: 8 -> 254, 16 -> 255.
462*/
450 463
451struct CFileId 464struct CFileId
452{ 465{
@@ -456,7 +469,10 @@ struct CFileId
456 CDString Id; 469 CDString Id;
457 CLongAllocDesc Icb; 470 CLongAllocDesc Icb;
458 471
459 bool IsItLinkParent() const { return (FileCharacteristics & FILEID_CHARACS_Parent) != 0; } 472 bool IsItLink_Dir () const { return (FileCharacteristics & FILEID_CHARACS_Dir) != 0; }
473 bool IsItLink_Deleted() const { return (FileCharacteristics & FILEID_CHARACS_Deleted) != 0; }
474 bool IsItLink_Parent () const { return (FileCharacteristics & FILEID_CHARACS_Parent) != 0; }
475
460 size_t Parse(const Byte *p, size_t size); 476 size_t Parse(const Byte *p, size_t size);
461}; 477};
462 478
@@ -466,10 +482,13 @@ size_t CFileId::Parse(const Byte *p, size_t size)
466 if (size < 38) 482 if (size < 38)
467 return 0; 483 return 0;
468 CTag tag; 484 CTag tag;
469 RINOK(tag.Parse(p, size)); 485 if (tag.Parse(p, size) != S_OK)
486 return 0;
470 if (tag.Id != DESC_TYPE_FileId) 487 if (tag.Id != DESC_TYPE_FileId)
471 return 0; 488 return 0;
472 // FileVersion = Get16(p + 16); 489 // FileVersion = Get16(p + 16);
490 // UDF: There shall be only one version of a file as specified below with the value being set to 1.
491
473 FileCharacteristics = p[18]; 492 FileCharacteristics = p[18];
474 const unsigned idLen = p[19]; 493 const unsigned idLen = p[19];
475 Icb.Parse(p + 20); 494 Icb.Parse(p + 20);
@@ -490,10 +509,10 @@ size_t CFileId::Parse(const Byte *p, size_t size)
490 509
491 510
492 511
493HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed) 512HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed)
494{ 513{
495 if (Files.Size() % 100 == 0) 514 if (Files.Size() % 100 == 0)
496 RINOK(_progress->SetCompleted(Files.Size(), _processedProgressBytes)); 515 RINOK(_progress->SetCompleted(Files.Size(), _processedProgressBytes))
497 if (numRecurseAllowed-- == 0) 516 if (numRecurseAllowed-- == 0)
498 return S_FALSE; 517 return S_FALSE;
499 CFile &file = Files.Back(); 518 CFile &file = Files.Back();
@@ -510,15 +529,15 @@ HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLon
510 { 529 {
511 if (value == kRecursedErrorValue) 530 if (value == kRecursedErrorValue)
512 return S_FALSE; 531 return S_FALSE;
513 file.ItemIndex = value; 532 file.ItemIndex = (int)(Int32)value;
514 } 533 }
515 else 534 else
516 { 535 {
517 value = Items.Size(); 536 value = Items.Size();
518 file.ItemIndex = (int)value; 537 file.ItemIndex = (int)(Int32)value;
519 if (partition.Map.Set(key, kRecursedErrorValue)) 538 if (partition.Map.Set(key, kRecursedErrorValue))
520 return S_FALSE; 539 return S_FALSE;
521 RINOK(ReadItem(volIndex, fsIndex, lad, numRecurseAllowed)); 540 RINOK(ReadItem(volIndex, (int)fsIndex, lad, isDir, numRecurseAllowed))
522 if (!partition.Map.Set(key, value)) 541 if (!partition.Map.Set(key, value))
523 return S_FALSE; 542 return S_FALSE;
524 } 543 }
@@ -528,7 +547,7 @@ HRESULT CInArchive::ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLon
528 547
529// (fsIndex = -1) means that it's metadata file 548// (fsIndex = -1) means that it's metadata file
530 549
531HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed) 550HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed)
532{ 551{
533 if (Items.Size() >= kNumItemsMax) 552 if (Items.Size() >= kNumItemsMax)
534 return S_FALSE; 553 return S_FALSE;
@@ -541,11 +560,11 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes
541 return S_FALSE; 560 return S_FALSE;
542 561
543 CByteBuffer buf(size); 562 CByteBuffer buf(size);
544 RINOK(ReadLad(volIndex, lad, buf)); 563 RINOK(ReadLad(volIndex, lad, buf))
545 564
546 CTag tag; 565 CTag tag;
547 const Byte *p = buf; 566 const Byte *p = buf;
548 RINOK(tag.Parse(p, size)); 567 RINOK(tag.Parse(p, size))
549 568
550 item.IsExtended = (tag.Id == DESC_TYPE_ExtendedFile); 569 item.IsExtended = (tag.Id == DESC_TYPE_ExtendedFile);
551 const size_t kExtendOffset = item.IsExtended ? 40 : 0; 570 const size_t kExtendOffset = item.IsExtended ? 40 : 0;
@@ -638,6 +657,9 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes
638 } 657 }
639 } 658 }
640 659
660 if (isDir != item.IcbTag.IsDir())
661 return S_FALSE;
662
641 if (item.IcbTag.IsDir()) 663 if (item.IcbTag.IsDir())
642 { 664 {
643 if (fsIndex < 0) 665 if (fsIndex < 0)
@@ -646,7 +668,7 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes
646 if (!item.CheckChunkSizes() || !CheckItemExtents(volIndex, item)) 668 if (!item.CheckChunkSizes() || !CheckItemExtents(volIndex, item))
647 return S_FALSE; 669 return S_FALSE;
648 CByteBuffer buf2; 670 CByteBuffer buf2;
649 RINOK(ReadFromFile(volIndex, item, buf2)); 671 RINOK(ReadFromFile(volIndex, item, buf2))
650 item.Size = 0; 672 item.Size = 0;
651 item.Extents.ClearAndFree(); 673 item.Extents.ClearAndFree();
652 item.InlineData.Free(); 674 item.InlineData.Free();
@@ -663,7 +685,10 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes
663 p2 += cur; 685 p2 += cur;
664 size2 -= cur; 686 size2 -= cur;
665 } 687 }
666 if (!fileId.IsItLinkParent()) 688 if (fileId.IsItLink_Parent())
689 continue;
690 if (fileId.IsItLink_Deleted())
691 continue;
667 { 692 {
668 CFile file; 693 CFile file;
669 // file.FileVersion = fileId.FileVersion; 694 // file.FileVersion = fileId.FileVersion;
@@ -679,7 +704,8 @@ HRESULT CInArchive::ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDes
679 if (Files.Size() >= kNumFilesMax) 704 if (Files.Size() >= kNumFilesMax)
680 return S_FALSE; 705 return S_FALSE;
681 Files.Add(file); 706 Files.Add(file);
682 RINOK(ReadFileItem(volIndex, fsIndex, fileId.Icb, numRecurseAllowed)); 707 RINOK(ReadFileItem(volIndex, (unsigned)fsIndex, fileId.Icb,
708 fileId.IsItLink_Dir(), numRecurseAllowed))
683 } 709 }
684 } 710 }
685 } 711 }
@@ -702,7 +728,7 @@ HRESULT CInArchive::FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int n
702{ 728{
703 if ((_numRefs & 0xFFF) == 0) 729 if ((_numRefs & 0xFFF) == 0)
704 { 730 {
705 RINOK(_progress->SetCompleted()); 731 RINOK(_progress->SetCompleted())
706 } 732 }
707 if (numRecurseAllowed-- == 0) 733 if (numRecurseAllowed-- == 0)
708 return S_FALSE; 734 return S_FALSE;
@@ -712,12 +738,12 @@ HRESULT CInArchive::FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int n
712 CRef ref; 738 CRef ref;
713 ref.FileIndex = fileIndex; 739 ref.FileIndex = fileIndex;
714 ref.Parent = parent; 740 ref.Parent = parent;
715 parent = fs.Refs.Size(); 741 parent = (int)fs.Refs.Size();
716 fs.Refs.Add(ref); 742 fs.Refs.Add(ref);
717 const CItem &item = Items[Files[fileIndex].ItemIndex]; 743 const CItem &item = Items[Files[fileIndex].ItemIndex];
718 FOR_VECTOR (i, item.SubFiles) 744 FOR_VECTOR (i, item.SubFiles)
719 { 745 {
720 RINOK(FillRefs(fs, item.SubFiles[i], parent, numRecurseAllowed)); 746 RINOK(FillRefs(fs, item.SubFiles[i], parent, numRecurseAllowed))
721 } 747 }
722 return S_OK; 748 return S_OK;
723} 749}
@@ -727,9 +753,9 @@ API_FUNC_IsArc IsArc_Udf(const Byte *p, size_t size)
727{ 753{
728 UInt32 res = k_IsArc_Res_NO; 754 UInt32 res = k_IsArc_Res_NO;
729 unsigned SecLogSize; 755 unsigned SecLogSize;
730 for (SecLogSize = 11;; SecLogSize -= 3) 756 for (SecLogSize = 11;; SecLogSize -= 2)
731 { 757 {
732 if (SecLogSize < 8) 758 if (SecLogSize < 9)
733 return res; 759 return res;
734 const UInt32 offset = (UInt32)256 << SecLogSize; 760 const UInt32 offset = (UInt32)256 << SecLogSize;
735 const UInt32 bufSize = (UInt32)1 << SecLogSize; 761 const UInt32 bufSize = (UInt32)1 << SecLogSize;
@@ -754,7 +780,7 @@ HRESULT CInArchive::Open2()
754{ 780{
755 Clear(); 781 Clear();
756 UInt64 fileSize; 782 UInt64 fileSize;
757 RINOK(_stream->Seek(0, STREAM_SEEK_END, &fileSize)); 783 RINOK(InStream_GetSize_SeekToEnd(_stream, fileSize))
758 FileSize = fileSize; 784 FileSize = fileSize;
759 785
760 // Some UDFs contain additional pad zeros (2 KB). 786 // Some UDFs contain additional pad zeros (2 KB).
@@ -765,7 +791,7 @@ HRESULT CInArchive::Open2()
765 const size_t kBufSize = 1 << 14; 791 const size_t kBufSize = 1 << 14;
766 Byte buf[kBufSize]; 792 Byte buf[kBufSize];
767 size_t readSize = (fileSize < kBufSize) ? (size_t)fileSize : kBufSize; 793 size_t readSize = (fileSize < kBufSize) ? (size_t)fileSize : kBufSize;
768 RINOK(_stream->Seek(fileSize - readSize, STREAM_SEEK_SET, NULL)); 794 RINOK(InStream_SeekSet(_stream, fileSize - readSize))
769 RINOK(ReadStream(_stream, buf, &readSize)); 795 RINOK(ReadStream(_stream, buf, &readSize));
770 size_t i = readSize; 796 size_t i = readSize;
771 for (;;) 797 for (;;)
@@ -785,20 +811,29 @@ HRESULT CInArchive::Open2()
785 extentVDS.Parse(buf + i + 16); 811 extentVDS.Parse(buf + i + 16);
786 */ 812 */
787 813
814 /*
815 An Anchor Volume Descriptor Pointer structure shall be recorded in at
816 least 2 of the following 3 locations on the media:
817 Logical Sector 256.
818 Logical Sector (N - 256).
819 N
820 */
821
788 const size_t kBufSize = 1 << 11; 822 const size_t kBufSize = 1 << 11;
789 Byte buf[kBufSize]; 823 Byte buf[kBufSize];
790 824
791 for (SecLogSize = 11;; SecLogSize -= 3) 825 for (SecLogSize = 11;; SecLogSize -= 2)
792 { 826 {
793 if (SecLogSize < 8) 827 // Windows 10 uses unusual (SecLogSize = 9)
828 if (SecLogSize < 9)
794 return S_FALSE; 829 return S_FALSE;
795 const UInt32 offset = (UInt32)256 << SecLogSize; 830 const UInt32 offset = (UInt32)256 << SecLogSize;
796 if (offset >= fileSize) 831 if (offset >= fileSize)
797 continue; 832 continue;
798 RINOK(_stream->Seek(offset, STREAM_SEEK_SET, NULL)); 833 RINOK(InStream_SeekSet(_stream, offset))
799 const size_t bufSize = (size_t)1 << SecLogSize; 834 const size_t bufSize = (size_t)1 << SecLogSize;
800 size_t readSize = bufSize; 835 size_t readSize = bufSize;
801 RINOK(ReadStream(_stream, buf, &readSize)); 836 RINOK(ReadStream(_stream, buf, &readSize))
802 if (readSize == bufSize) 837 if (readSize == bufSize)
803 { 838 {
804 CTag tag; 839 CTag tag;
@@ -834,15 +869,15 @@ HRESULT CInArchive::Open2()
834 const size_t bufSize = (size_t)1 << SecLogSize; 869 const size_t bufSize = (size_t)1 << SecLogSize;
835 { 870 {
836 const UInt64 offs = ((UInt64)extentVDS.Pos + location) << SecLogSize; 871 const UInt64 offs = ((UInt64)extentVDS.Pos + location) << SecLogSize;
837 RINOK(_stream->Seek(offs, STREAM_SEEK_SET, NULL)); 872 RINOK(InStream_SeekSet(_stream, offs))
838 const HRESULT res = ReadStream_FALSE(_stream, buf, bufSize); 873 const HRESULT res = ReadStream_FALSE(_stream, buf, bufSize);
839 if (res == S_FALSE && offs + bufSize > FileSize) 874 if (res == S_FALSE && offs + bufSize > FileSize)
840 UnexpectedEnd = true; 875 UnexpectedEnd = true;
841 RINOK(res); 876 RINOK(res)
842 } 877 }
843 878
844 CTag tag; 879 CTag tag;
845 RINOK(tag.Parse(buf, bufSize)); 880 RINOK(tag.Parse(buf, bufSize))
846 881
847 if (tag.Id == DESC_TYPE_Terminating) 882 if (tag.Id == DESC_TYPE_Terminating)
848 break; 883 break;
@@ -1086,14 +1121,26 @@ HRESULT CInArchive::Open2()
1086 RINOK(ReadItem(volIndex, 1121 RINOK(ReadItem(volIndex,
1087 -1, // (fsIndex = -1) means that it's metadata 1122 -1, // (fsIndex = -1) means that it's metadata
1088 lad, 1123 lad,
1089 1)); // numRecurseAllowed 1124 false, // isDir
1125 1)) // numRecurseAllowed
1090 } 1126 }
1091 { 1127 {
1092 const CItem &item = Items.Back(); 1128 const CItem &item = Items.Back();
1093 if (!CheckItemExtents(volIndex, item)) 1129 if (!CheckItemExtents(volIndex, item))
1094 return S_FALSE; 1130 return S_FALSE;
1095 if (item.Extents.Size() != 1) 1131 if (item.Extents.Size() != 1)
1096 return S_FALSE; 1132 {
1133 if (item.Extents.Size() < 1)
1134 return S_FALSE;
1135 /* Windows 10 writes empty record item.Extents[1].
1136 we ignore such extent here */
1137 for (unsigned k = 1; k < item.Extents.Size(); k++)
1138 {
1139 const CMyExtent &e = item.Extents[k];
1140 if (e.GetLen() != 0)
1141 return S_FALSE;
1142 }
1143 }
1097 1144
1098 const CMyExtent &e = item.Extents[0]; 1145 const CMyExtent &e = item.Extents[0];
1099 const CPartition &part = Partitions[pm.PartitionIndex]; 1146 const CPartition &part = Partitions[pm.PartitionIndex];
@@ -1126,7 +1173,7 @@ HRESULT CInArchive::Open2()
1126 } 1173 }
1127 } 1174 }
1128 1175
1129 RINOK(_progress->SetTotal(totalSize)); 1176 RINOK(_progress->SetTotal(totalSize))
1130 1177
1131 PRF(printf("\n Read files")); 1178 PRF(printf("\n Read files"));
1132 1179
@@ -1143,12 +1190,12 @@ HRESULT CInArchive::Open2()
1143 if (nextExtent.GetLen() < 512) 1190 if (nextExtent.GetLen() < 512)
1144 return S_FALSE; 1191 return S_FALSE;
1145 CByteBuffer buf2(nextExtent.GetLen()); 1192 CByteBuffer buf2(nextExtent.GetLen());
1146 RINOK(ReadLad(volIndex, nextExtent, buf2)); 1193 RINOK(ReadLad(volIndex, nextExtent, buf2))
1147 const Byte *p = buf2; 1194 const Byte *p = buf2;
1148 const size_t size = nextExtent.GetLen(); 1195 const size_t size = nextExtent.GetLen();
1149 1196
1150 CTag tag; 1197 CTag tag;
1151 RINOK(tag.Parse(p, size)); 1198 RINOK(tag.Parse(p, size))
1152 1199
1153 /* 1200 /*
1154 // commented in 22.01 1201 // commented in 22.01
@@ -1191,8 +1238,10 @@ HRESULT CInArchive::Open2()
1191 CFileSet &fs = vol.FileSets[fsIndex]; 1238 CFileSet &fs = vol.FileSets[fsIndex];
1192 const unsigned fileIndex = Files.Size(); 1239 const unsigned fileIndex = Files.Size();
1193 Files.AddNew(); 1240 Files.AddNew();
1194 RINOK(ReadFileItem(volIndex, fsIndex, fs.RootDirICB, kNumRecursionLevelsMax)); 1241 RINOK(ReadFileItem(volIndex, fsIndex, fs.RootDirICB,
1195 RINOK(FillRefs(fs, fileIndex, -1, kNumRecursionLevelsMax)); 1242 true, // isDir
1243 kNumRecursionLevelsMax))
1244 RINOK(FillRefs(fs, fileIndex, -1, kNumRecursionLevelsMax))
1196 } 1245 }
1197 } 1246 }
1198 1247
@@ -1248,7 +1297,7 @@ HRESULT CInArchive::Open2()
1248 UInt64 rem = fileSize - PhySize; 1297 UInt64 rem = fileSize - PhySize;
1249 const size_t secSize = (size_t)1 << SecLogSize; 1298 const size_t secSize = (size_t)1 << SecLogSize;
1250 1299
1251 RINOK(_stream->Seek(PhySize, STREAM_SEEK_SET, NULL)); 1300 RINOK(InStream_SeekSet(_stream, PhySize))
1252 1301
1253 // some UDF images contain ZEROs before "Anchor Volume Descriptor Pointer" at the end 1302 // some UDF images contain ZEROs before "Anchor Volume Descriptor Pointer" at the end
1254 1303
@@ -1261,7 +1310,7 @@ HRESULT CInArchive::Open2()
1261 if (readSize > rem) 1310 if (readSize > rem)
1262 readSize = (size_t)rem; 1311 readSize = (size_t)rem;
1263 1312
1264 RINOK(ReadStream(_stream, buf, &readSize)); 1313 RINOK(ReadStream(_stream, buf, &readSize))
1265 1314
1266 if (readSize == 0) 1315 if (readSize == 0)
1267 break; 1316 break;
@@ -1270,8 +1319,9 @@ HRESULT CInArchive::Open2()
1270 if (readSize == secSize /* && NoEndAnchor */) 1319 if (readSize == secSize /* && NoEndAnchor */)
1271 { 1320 {
1272 CTag tag; 1321 CTag tag;
1273 if (tag.Parse(buf, readSize) == S_OK && 1322 if (tag.Parse(buf, readSize) == S_OK
1274 tag.Id == DESC_TYPE_AnchorVolPtr) 1323 && tag.Id == DESC_TYPE_AnchorVolPtr
1324 && Get32(buf + 12) == (UInt32)((fileSize - rem) >> SecLogSize))
1275 { 1325 {
1276 NoEndAnchor = false; 1326 NoEndAnchor = false;
1277 rem -= readSize; 1327 rem -= readSize;
@@ -1443,7 +1493,7 @@ static const char * const g_OsIds_Unix[] =
1443 , "NetBSD" 1493 , "NetBSD"
1444}; 1494};
1445 1495
1446static void AddOs_Class_Id(UString &s, const char *p) 1496static void AddOs_Class_Id(UString &s, const Byte *p)
1447{ 1497{
1448 // UDF 2.1.5.3 Implementation Identifier Suffix 1498 // UDF 2.1.5.3 Implementation Identifier Suffix
1449 // Appendix 6.3 Operating System Identifiers. 1499 // Appendix 6.3 Operating System Identifiers.
@@ -1451,7 +1501,7 @@ static void AddOs_Class_Id(UString &s, const char *p)
1451 if (osClass != 0) 1501 if (osClass != 0)
1452 { 1502 {
1453 s += "::"; 1503 s += "::";
1454 s += TypeToString(g_OsClasses, ARRAY_SIZE(g_OsClasses), osClass); 1504 s += TypeToString(g_OsClasses, Z7_ARRAY_SIZE(g_OsClasses), osClass);
1455 } 1505 }
1456 const Byte osId = p[1]; 1506 const Byte osId = p[1];
1457 if (osId != 0) 1507 if (osId != 0)
@@ -1459,7 +1509,7 @@ static void AddOs_Class_Id(UString &s, const char *p)
1459 s += "::"; 1509 s += "::";
1460 if (osClass == 4) // unix 1510 if (osClass == 4) // unix
1461 { 1511 {
1462 s += TypeToString(g_OsIds_Unix, ARRAY_SIZE(g_OsIds_Unix), osId); 1512 s += TypeToString(g_OsIds_Unix, Z7_ARRAY_SIZE(g_OsIds_Unix), osId);
1463 } 1513 }
1464 else 1514 else
1465 s.Add_UInt32(osId); 1515 s.Add_UInt32(osId);
@@ -1552,7 +1602,7 @@ UString CInArchive::GetComment() const
1552 AddComment_RegId(s, "ContentsId", part.ContentsId); 1602 AddComment_RegId(s, "ContentsId", part.ContentsId);
1553 AddComment_RegId_Impl(s, "ImplementationId", part.ImplId); 1603 AddComment_RegId_Impl(s, "ImplementationId", part.ImplId);
1554 AddComment_PropName(s, "AccessType"); 1604 AddComment_PropName(s, "AccessType");
1555 s += TypeToString(g_PartitionTypes, ARRAY_SIZE(g_PartitionTypes), part.AccessType); 1605 s += TypeToString(g_PartitionTypes, Z7_ARRAY_SIZE(g_PartitionTypes), part.AccessType);
1556 s.Add_LF(); 1606 s.Add_LF();
1557 } 1607 }
1558 AddComment_UInt64(s, "Size", (UInt64)part.Len << SecLogSize); 1608 AddComment_UInt64(s, "Size", (UInt64)part.Len << SecLogSize);
@@ -1663,7 +1713,7 @@ UString CInArchive::GetItemPath(unsigned volIndex, unsigned fsIndex, unsigned re
1663 // we break on root file (that probably has empty name) 1713 // we break on root file (that probably has empty name)
1664 if (ref.Parent < 0) 1714 if (ref.Parent < 0)
1665 break; 1715 break;
1666 refIndex = ref.Parent; 1716 refIndex = (unsigned)ref.Parent;
1667 UpdateWithName(name, GetSpecName(Files[ref.FileIndex].GetName())); 1717 UpdateWithName(name, GetSpecName(Files[ref.FileIndex].GetName()));
1668 } 1718 }
1669 1719
diff --git a/CPP/7zip/Archive/Udf/UdfIn.h b/CPP/7zip/Archive/Udf/UdfIn.h
index d962e7d..9ccbf74 100644
--- a/CPP/7zip/Archive/Udf/UdfIn.h
+++ b/CPP/7zip/Archive/Udf/UdfIn.h
@@ -1,7 +1,7 @@
1// Archive/UdfIn.h -- UDF / ECMA-167 1// Archive/UdfIn.h -- UDF / ECMA-167
2 2
3#ifndef __ARCHIVE_UDF_IN_H 3#ifndef ZIP7_INC_ARCHIVE_UDF_IN_H
4#define __ARCHIVE_UDF_IN_H 4#define ZIP7_INC_ARCHIVE_UDF_IN_H
5 5
6#include "../../../Common/IntToString.h" 6#include "../../../Common/IntToString.h"
7#include "../../../Common/MyBuffer.h" 7#include "../../../Common/MyBuffer.h"
@@ -72,7 +72,7 @@ struct CRegId
72{ 72{
73 Byte Flags; 73 Byte Flags;
74 char Id[23]; 74 char Id[23];
75 char Suffix[8]; 75 Byte Suffix[8];
76 76
77 void Parse(const Byte *buf); 77 void Parse(const Byte *buf);
78 void AddCommentTo(UString &s) const; 78 void AddCommentTo(UString &s) const;
@@ -281,9 +281,15 @@ struct CIcbTag
281 void Parse(const Byte *p); 281 void Parse(const Byte *p);
282}; 282};
283 283
284
284// ECMA 4/14.4.3 285// ECMA 4/14.4.3
286// UDF 2.3.4.2 FileCharacteristics
287
285// const Byte FILEID_CHARACS_Existance = (1 << 0); 288// const Byte FILEID_CHARACS_Existance = (1 << 0);
286const Byte FILEID_CHARACS_Parent = (1 << 3); 289const Byte FILEID_CHARACS_Dir = (1 << 1);
290const Byte FILEID_CHARACS_Deleted = (1 << 2);
291const Byte FILEID_CHARACS_Parent = (1 << 3);
292// const Byte FILEID_CHARACS_Metadata = (1 << 4);
287 293
288struct CFile 294struct CFile
289{ 295{
@@ -423,13 +429,14 @@ struct CLogVol
423}; 429};
424 430
425 431
426 432Z7_PURE_INTERFACES_BEGIN
427struct CProgressVirt 433struct Z7_DECLSPEC_NOVTABLE CProgressVirt
428{ 434{
429 virtual HRESULT SetTotal(UInt64 numBytes) PURE; 435 virtual HRESULT SetTotal(UInt64 numBytes) =0; \
430 virtual HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) PURE; 436 virtual HRESULT SetCompleted(UInt64 numFiles, UInt64 numBytes) =0; \
431 virtual HRESULT SetCompleted() PURE; 437 virtual HRESULT SetCompleted() =0; \
432}; 438};
439Z7_PURE_INTERFACES_END
433 440
434class CInArchive 441class CInArchive
435{ 442{
@@ -467,8 +474,8 @@ private:
467 HRESULT ReadLad(unsigned volIndex, const CLongAllocDesc &lad, Byte *buf); 474 HRESULT ReadLad(unsigned volIndex, const CLongAllocDesc &lad, Byte *buf);
468 HRESULT ReadFromFile(unsigned volIndex, const CItem &item, CByteBuffer &buf); 475 HRESULT ReadFromFile(unsigned volIndex, const CItem &item, CByteBuffer &buf);
469 476
470 HRESULT ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed); 477 HRESULT ReadFileItem(unsigned volIndex, unsigned fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed);
471 HRESULT ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, int numRecurseAllowed); 478 HRESULT ReadItem(unsigned volIndex, int fsIndex, const CLongAllocDesc &lad, bool isDir, int numRecurseAllowed);
472 479
473 HRESULT Open2(); 480 HRESULT Open2();
474 HRESULT FillRefs(CFileSet &fs, unsigned fileIndex, int parent, int numRecurseAllowed); 481 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 67fe795..cd6fcbd 100644
--- a/CPP/7zip/Archive/UefiHandler.cpp
+++ b/CPP/7zip/Archive/UefiHandler.cpp
@@ -171,14 +171,14 @@ enum
171static const char *FindExt(const Byte *p, size_t size) 171static const char *FindExt(const Byte *p, size_t size)
172{ 172{
173 unsigned i; 173 unsigned i;
174 for (i = 0; i < ARRAY_SIZE(g_Sigs); i++) 174 for (i = 0; i < Z7_ARRAY_SIZE(g_Sigs); i++)
175 { 175 {
176 const CSigExtPair &pair = g_Sigs[i]; 176 const CSigExtPair &pair = g_Sigs[i];
177 if (size >= pair.sigSize) 177 if (size >= pair.sigSize)
178 if (memcmp(p, pair.sig, pair.sigSize) == 0) 178 if (memcmp(p, pair.sig, pair.sigSize) == 0)
179 break; 179 break;
180 } 180 }
181 if (i == ARRAY_SIZE(g_Sigs)) 181 if (i == Z7_ARRAY_SIZE(g_Sigs))
182 return NULL; 182 return NULL;
183 switch (i) 183 switch (i)
184 { 184 {
@@ -212,9 +212,9 @@ static bool AreGuidsEq(const Byte *p1, const Byte *p2)
212 212
213static int FindGuid(const Byte *p) 213static int FindGuid(const Byte *p)
214{ 214{
215 for (unsigned i = 0; i < ARRAY_SIZE(kGuids); i++) 215 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kGuids); i++)
216 if (AreGuidsEq(p, kGuids[i])) 216 if (AreGuidsEq(p, kGuids[i]))
217 return i; 217 return (int)i;
218 return -1; 218 return -1;
219} 219}
220 220
@@ -222,7 +222,7 @@ static bool IsFfs(const Byte *p)
222{ 222{
223 if (Get32(p + 0x28) != kFvSignature) 223 if (Get32(p + 0x28) != kFvSignature)
224 return false; 224 return false;
225 for (unsigned i = 0; i < ARRAY_SIZE(k_Guids_FS); i++) 225 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Guids_FS); i++)
226 if (AreGuidsEq(p + kFfsGuidOffset, k_Guids_FS[i])) 226 if (AreGuidsEq(p + kFfsGuidOffset, k_Guids_FS[i]))
227 return true; 227 return true;
228 return false; 228 return false;
@@ -396,7 +396,7 @@ static bool ParseDepedencyExpression(const Byte *p, UInt32 size, AString &res)
396 for (UInt32 i = 0; i < size;) 396 for (UInt32 i = 0; i < size;)
397 { 397 {
398 unsigned command = p[i++]; 398 unsigned command = p[i++];
399 if (command > ARRAY_SIZE(kExpressionCommands)) 399 if (command > Z7_ARRAY_SIZE(kExpressionCommands))
400 return false; 400 return false;
401 res += kExpressionCommands[command]; 401 res += kExpressionCommands[command];
402 if (command < 3) 402 if (command < 3)
@@ -437,9 +437,9 @@ static bool ParseUtf16zString2(const Byte *p, UInt32 size, AString &res)
437 return true; 437 return true;
438} 438}
439 439
440#define FLAGS_TO_STRING(pairs, value) FlagsToString(pairs, ARRAY_SIZE(pairs), value) 440#define FLAGS_TO_STRING(pairs, value) FlagsToString(pairs, Z7_ARRAY_SIZE(pairs), value)
441#define TYPE_TO_STRING(table, value) TypeToString(table, ARRAY_SIZE(table), value) 441#define TYPE_TO_STRING(table, value) TypeToString(table, Z7_ARRAY_SIZE(table), value)
442#define TYPE_PAIR_TO_STRING(table, value) TypePairToString(table, ARRAY_SIZE(table), value) 442#define TYPE_PAIR_TO_STRING(table, value) TypePairToString(table, Z7_ARRAY_SIZE(table), value)
443 443
444static const UInt32 kFileHeaderSize = 24; 444static const UInt32 kFileHeaderSize = 24;
445 445
@@ -559,8 +559,8 @@ public:
559 } 559 }
560}; 560};
561 561
562#define G32(_offs_, dest) dest = Get32(p + (_offs_)); 562#define G32(_offs_, dest) dest = Get32(p + (_offs_))
563#define G16(_offs_, dest) dest = Get16(p + (_offs_)); 563#define G16(_offs_, dest) dest = Get16(p + (_offs_))
564 564
565struct CCapsuleHeader 565struct CCapsuleHeader
566{ 566{
@@ -632,14 +632,14 @@ struct CItem
632 int Parent; 632 int Parent;
633 int Method; 633 int Method;
634 int NameIndex; 634 int NameIndex;
635 int NumChilds; 635 unsigned NumChilds;
636 bool IsDir; 636 bool IsDir;
637 bool Skip; 637 bool Skip;
638 bool ThereAreSubDirs; 638 bool ThereAreSubDirs;
639 bool ThereIsUniqueName; 639 bool ThereIsUniqueName;
640 bool KeepName; 640 bool KeepName;
641 641
642 int BufIndex; 642 unsigned BufIndex;
643 UInt32 Offset; 643 UInt32 Offset;
644 UInt32 Size; 644 UInt32 Size;
645 645
@@ -668,14 +668,14 @@ AString CItem::GetName(int numChildsInParent) const
668 return Name; 668 return Name;
669 char sz[32]; 669 char sz[32];
670 char sz2[32]; 670 char sz2[32];
671 ConvertUInt32ToString(NameIndex, sz); 671 ConvertUInt32ToString((unsigned)NameIndex, sz);
672 ConvertUInt32ToString(numChildsInParent - 1, sz2); 672 ConvertUInt32ToString((unsigned)numChildsInParent - 1, sz2);
673 int numZeros = (int)strlen(sz2) - (int)strlen(sz); 673 const int numZeros = (int)strlen(sz2) - (int)strlen(sz);
674 AString res; 674 AString res;
675 for (int i = 0; i < numZeros; i++) 675 for (int i = 0; i < numZeros; i++)
676 res += '0'; 676 res += '0';
677 res += sz; 677 res += sz;
678 res += '.'; 678 res.Add_Dot();
679 res += Name; 679 res += Name;
680 return res; 680 return res;
681} 681}
@@ -684,17 +684,16 @@ struct CItem2
684{ 684{
685 AString Name; 685 AString Name;
686 AString Characts; 686 AString Characts;
687 int MainIndex; 687 unsigned MainIndex;
688 int Parent; 688 int Parent;
689 689
690 CItem2(): Parent(-1) {} 690 CItem2(): Parent(-1) {}
691}; 691};
692 692
693class CHandler: 693
694 public IInArchive, 694Z7_CLASS_IMP_CHandler_IInArchive_1(
695 public IInArchiveGetStream, 695 IInArchiveGetStream
696 public CMyUnknownImp 696)
697{
698 CObjectVector<CItem> _items; 697 CObjectVector<CItem> _items;
699 CObjectVector<CItem2> _items2; 698 CObjectVector<CItem2> _items2;
700 CObjectVector<CByteBuffer> _bufs; 699 CObjectVector<CByteBuffer> _bufs;
@@ -708,20 +707,23 @@ class CHandler:
708 UInt64 _phySize; 707 UInt64 _phySize;
709 708
710 void AddCommentString(const char *name, UInt32 pos); 709 void AddCommentString(const char *name, UInt32 pos);
711 int AddItem(const CItem &item); 710 unsigned AddItem(const CItem &item);
712 int AddFileItemWithIndex(CItem &item); 711 unsigned AddFileItemWithIndex(CItem &item);
713 int AddDirItem(CItem &item); 712 unsigned AddDirItem(CItem &item);
714 unsigned AddBuf(size_t size); 713 unsigned AddBuf(size_t size);
715 714
716 HRESULT DecodeLzma(const Byte *data, size_t inputSize); 715 HRESULT DecodeLzma(const Byte *data, size_t inputSize);
717 716
718 HRESULT ParseSections(int bufIndex, UInt32 pos, UInt32 size, int parent, int method, unsigned level, bool &error); 717 HRESULT ParseSections(unsigned bufIndex, UInt32 pos,
718 UInt32 size,
719 int parent, int method, unsigned level,
720 bool &error);
719 721
720 HRESULT ParseIntelMe(int bufIndex, UInt32 posBase, 722 HRESULT ParseIntelMe(unsigned bufIndex, UInt32 posBase,
721 UInt32 exactSize, UInt32 limitSize, 723 UInt32 exactSize, UInt32 limitSize,
722 int parent, int method, unsigned level); 724 int parent, int method, unsigned level);
723 725
724 HRESULT ParseVolume(int bufIndex, UInt32 posBase, 726 HRESULT ParseVolume(unsigned bufIndex, UInt32 posBase,
725 UInt32 exactSize, UInt32 limitSize, 727 UInt32 exactSize, UInt32 limitSize,
726 int parent, int method, unsigned level); 728 int parent, int method, unsigned level);
727 729
@@ -730,11 +732,9 @@ class CHandler:
730 HRESULT Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback); 732 HRESULT Open2(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback);
731public: 733public:
732 CHandler(bool capsuleMode): _capsuleMode(capsuleMode) {} 734 CHandler(bool capsuleMode): _capsuleMode(capsuleMode) {}
733 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
734 INTERFACE_IInArchive(;)
735 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
736}; 735};
737 736
737
738static const Byte kProps[] = 738static const Byte kProps[] =
739{ 739{
740 kpidPath, 740 kpidPath,
@@ -755,7 +755,7 @@ static const Byte kArcProps[] =
755IMP_IInArchive_Props 755IMP_IInArchive_Props
756IMP_IInArchive_ArcProps 756IMP_IInArchive_ArcProps
757 757
758STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 758Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
759{ 759{
760 COM_TRY_BEGIN 760 COM_TRY_BEGIN
761 NWindows::NCOM::CPropVariant prop; 761 NWindows::NCOM::CPropVariant prop;
@@ -823,7 +823,7 @@ void CHandler::AddCommentString(const char *name, UInt32 pos)
823 _comment += s; 823 _comment += s;
824} 824}
825 825
826STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 826Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
827{ 827{
828 COM_TRY_BEGIN 828 COM_TRY_BEGIN
829 NWindows::NCOM::CPropVariant prop; 829 NWindows::NCOM::CPropVariant prop;
@@ -875,23 +875,23 @@ static void MyPrint(UInt32 posBase, UInt32 size, unsigned level, const char *nam
875 875
876 876
877 877
878int CHandler::AddItem(const CItem &item) 878unsigned CHandler::AddItem(const CItem &item)
879{ 879{
880 if (_items.Size() >= kNumFilesMax) 880 if (_items.Size() >= kNumFilesMax)
881 throw 2; 881 throw 2;
882 return _items.Add(item); 882 return _items.Add(item);
883} 883}
884 884
885int CHandler::AddFileItemWithIndex(CItem &item) 885unsigned CHandler::AddFileItemWithIndex(CItem &item)
886{ 886{
887 int nameIndex = _items.Size(); 887 unsigned nameIndex = _items.Size();
888 if (item.Parent >= 0) 888 if (item.Parent >= 0)
889 nameIndex = _items[item.Parent].NumChilds++; 889 nameIndex = _items[item.Parent].NumChilds++;
890 item.NameIndex = nameIndex; 890 item.NameIndex = (int)nameIndex;
891 return AddItem(item); 891 return AddItem(item);
892} 892}
893 893
894int CHandler::AddDirItem(CItem &item) 894unsigned CHandler::AddDirItem(CItem &item)
895{ 895{
896 if (item.Parent >= 0) 896 if (item.Parent >= 0)
897 _items[item.Parent].ThereAreSubDirs = true; 897 _items[item.Parent].ThereAreSubDirs = true;
@@ -936,7 +936,7 @@ HRESULT CHandler::DecodeLzma(const Byte *data, size_t inputSize)
936} 936}
937 937
938 938
939HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int parent, int method, unsigned level, bool &error) 939HRESULT CHandler::ParseSections(unsigned bufIndex, UInt32 posBase, UInt32 size, int parent, int method, unsigned level, bool &error)
940{ 940{
941 error = false; 941 error = false;
942 942
@@ -1010,14 +1010,14 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1010 if (compressionType == COMPRESSION_TYPE_NONE) 1010 if (compressionType == COMPRESSION_TYPE_NONE)
1011 { 1011 {
1012 bool error2; 1012 bool error2;
1013 RINOK(ParseSections(bufIndex, newOffset, newSectSize, parent, method, level, error2)); 1013 RINOK(ParseSections(bufIndex, newOffset, newSectSize, parent, method, level, error2))
1014 } 1014 }
1015 else if (compressionType == COMPRESSION_TYPE_LZH) 1015 else if (compressionType == COMPRESSION_TYPE_LZH)
1016 { 1016 {
1017 unsigned newBufIndex = AddBuf(uncompressedSize); 1017 unsigned newBufIndex = AddBuf(uncompressedSize);
1018 CByteBuffer &buf = _bufs[newBufIndex]; 1018 CByteBuffer &buf = _bufs[newBufIndex];
1019 1019
1020 NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; 1020 NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = NULL;
1021 CMyComPtr<ICompressCoder> lzhDecoder; 1021 CMyComPtr<ICompressCoder> lzhDecoder;
1022 1022
1023 lzhDecoderSpec = new NCompress::NLzh::NDecoder::CCoder; 1023 lzhDecoderSpec = new NCompress::NLzh::NDecoder::CCoder;
@@ -1066,11 +1066,11 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1066 if (res == S_OK) 1066 if (res == S_OK)
1067 break; 1067 break;
1068 } 1068 }
1069 RINOK(res); 1069 RINOK(res)
1070 } 1070 }
1071 1071
1072 bool error2; 1072 bool error2;
1073 RINOK(ParseSections(newBufIndex, 0, uncompressedSize, parent, compressionType, level, error2)); 1073 RINOK(ParseSections(newBufIndex, 0, uncompressedSize, parent, compressionType, level, error2))
1074 } 1074 }
1075 else 1075 else
1076 { 1076 {
@@ -1091,13 +1091,13 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1091 } 1091 }
1092 pStart += addSize; 1092 pStart += addSize;
1093 1093
1094 RINOK(DecodeLzma(pStart, newSectSize - addSize)); 1094 RINOK(DecodeLzma(pStart, newSectSize - addSize))
1095 const size_t lzmaUncompressedSize = _bufs.Back().Size(); 1095 const size_t lzmaUncompressedSize = _bufs.Back().Size();
1096 // if (lzmaUncompressedSize != uncompressedSize) 1096 // if (lzmaUncompressedSize != uncompressedSize)
1097 if (lzmaUncompressedSize < uncompressedSize) 1097 if (lzmaUncompressedSize < uncompressedSize)
1098 return S_FALSE; 1098 return S_FALSE;
1099 bool error2; 1099 bool error2;
1100 RINOK(ParseSections(_bufs.Size() - 1, 0, (UInt32)lzmaUncompressedSize, parent, compressionType, level, error2)); 1100 RINOK(ParseSections(_bufs.Size() - 1, 0, (UInt32)lzmaUncompressedSize, parent, compressionType, level, error2))
1101 } 1101 }
1102 _methodsMask |= (1 << compressionType); 1102 _methodsMask |= (1 << compressionType);
1103 } 1103 }
@@ -1108,15 +1108,15 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1108 if (sectSize < kHeaderSize) 1108 if (sectSize < kHeaderSize)
1109 return S_FALSE; 1109 return S_FALSE;
1110 item.SetGuid(p + 4); 1110 item.SetGuid(p + 4);
1111 UInt32 dataOffset = Get16(p + 4 + kGuidSize); 1111 const UInt32 dataOffset = Get16(p + 4 + kGuidSize);
1112 UInt32 attrib = Get16(p + 4 + kGuidSize + 2); 1112 const UInt32 attrib = Get16(p + 4 + kGuidSize + 2);
1113 if (dataOffset > sectSize || dataOffset < kHeaderSize) 1113 if (dataOffset > sectSize || dataOffset < kHeaderSize)
1114 return S_FALSE; 1114 return S_FALSE;
1115 UInt32 newSectSize = sectSize - dataOffset; 1115 UInt32 newSectSize = sectSize - dataOffset;
1116 item.Size = newSectSize; 1116 item.Size = newSectSize;
1117 UInt32 newOffset = posBase + pos + dataOffset; 1117 UInt32 newOffset = posBase + pos + dataOffset;
1118 item.Offset = newOffset; 1118 item.Offset = newOffset;
1119 UInt32 propsSize = dataOffset - kHeaderSize; 1119 const UInt32 propsSize = dataOffset - kHeaderSize;
1120 AddSpaceAndString(item.Characts, FLAGS_TO_STRING(g_GUIDED_SECTION_ATTRIBUTES, attrib)); 1120 AddSpaceAndString(item.Characts, FLAGS_TO_STRING(g_GUIDED_SECTION_ATTRIBUTES, attrib));
1121 1121
1122 bool needDir = true; 1122 bool needDir = true;
@@ -1129,7 +1129,7 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1129 // AddItem(item); 1129 // AddItem(item);
1130 const Byte *pStart = bufData + newOffset; 1130 const Byte *pStart = bufData + newOffset;
1131 // do we need correct pStart here for lzma steram offset? 1131 // do we need correct pStart here for lzma steram offset?
1132 RINOK(DecodeLzma(pStart, newSectSize)); 1132 RINOK(DecodeLzma(pStart, newSectSize))
1133 _methodsMask |= (1 << COMPRESSION_TYPE_LZMA); 1133 _methodsMask |= (1 << COMPRESSION_TYPE_LZMA);
1134 newBufIndex = _bufs.Size() - 1; 1134 newBufIndex = _bufs.Size() - 1;
1135 newOffset = 0; 1135 newOffset = 0;
@@ -1157,18 +1157,18 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1157 1157
1158 int newParent = parent; 1158 int newParent = parent;
1159 if (needDir) 1159 if (needDir)
1160 newParent = AddDirItem(item); 1160 newParent = (int)AddDirItem(item);
1161 bool error2; 1161 bool error2;
1162 RINOK(ParseSections(newBufIndex, newOffset, newSectSize, newParent, newMethod, level, error2)); 1162 RINOK(ParseSections(newBufIndex, newOffset, newSectSize, newParent, newMethod, level, error2))
1163 } 1163 }
1164 else if (type == SECTION_FIRMWARE_VOLUME_IMAGE) 1164 else if (type == SECTION_FIRMWARE_VOLUME_IMAGE)
1165 { 1165 {
1166 item.KeepName = false; 1166 item.KeepName = false;
1167 int newParent = AddDirItem(item); 1167 const int newParent = (int)AddDirItem(item);
1168 RINOK(ParseVolume(bufIndex, posBase + pos + 4, 1168 RINOK(ParseVolume(bufIndex, posBase + pos + 4,
1169 sectSize - 4, 1169 sectSize - 4,
1170 sectSize - 4, 1170 sectSize - 4,
1171 newParent, method, level)); 1171 newParent, method, level))
1172 } 1172 }
1173 else 1173 else
1174 { 1174 {
@@ -1185,11 +1185,11 @@ HRESULT CHandler::ParseSections(int bufIndex, UInt32 posBase, UInt32 size, int p
1185 { 1185 {
1186 needAdd = false; 1186 needAdd = false;
1187 item.Name = "vol"; 1187 item.Name = "vol";
1188 int newParent = AddDirItem(item); 1188 const unsigned newParent = AddDirItem(item);
1189 RINOK(ParseVolume(bufIndex, posBase + pos + 4 + kInsydeOffset, 1189 RINOK(ParseVolume(bufIndex, posBase + pos + 4 + kInsydeOffset,
1190 sectDataSize - kInsydeOffset, 1190 sectDataSize - kInsydeOffset,
1191 sectDataSize - kInsydeOffset, 1191 sectDataSize - kInsydeOffset,
1192 newParent, method, level)); 1192 (int)newParent, method, level))
1193 } 1193 }
1194 1194
1195 if (needAdd) 1195 if (needAdd)
@@ -1306,11 +1306,11 @@ bool CVolFfsHeader::Parse(const Byte *p)
1306 if (HeaderLen < kFvHeaderSize || (HeaderLen & 0x7) != 0 || VolSize < HeaderLen) 1306 if (HeaderLen < kFvHeaderSize || (HeaderLen & 0x7) != 0 || VolSize < HeaderLen)
1307 return false; 1307 return false;
1308 return true; 1308 return true;
1309}; 1309}
1310 1310
1311 1311
1312HRESULT CHandler::ParseVolume( 1312HRESULT CHandler::ParseVolume(
1313 int bufIndex, UInt32 posBase, 1313 unsigned bufIndex, UInt32 posBase,
1314 UInt32 exactSize, UInt32 limitSize, 1314 UInt32 exactSize, UInt32 limitSize,
1315 int parent, int method, unsigned level) 1315 int parent, int method, unsigned level)
1316{ 1316{
@@ -1382,7 +1382,7 @@ HRESULT CHandler::ParseVolume(
1382 UInt32 rem = (UInt32)ffsHeader.VolSize - pos; 1382 UInt32 rem = (UInt32)ffsHeader.VolSize - pos;
1383 if (rem < kFileHeaderSize) 1383 if (rem < kFileHeaderSize)
1384 break; 1384 break;
1385 pos = (pos + 7) & ~7; 1385 pos = (pos + 7) & ~7u;
1386 rem = (UInt32)ffsHeader.VolSize - pos; 1386 rem = (UInt32)ffsHeader.VolSize - pos;
1387 if (rem < kFileHeaderSize) 1387 if (rem < kFileHeaderSize)
1388 break; 1388 break;
@@ -1457,11 +1457,11 @@ HRESULT CHandler::ParseVolume(
1457 } 1457 }
1458 if (isVolume) 1458 if (isVolume)
1459 { 1459 {
1460 int newParent = AddDirItem(item); 1460 const unsigned newParent = AddDirItem(item);
1461 UInt32 limSize = fh.GetDataSize2(rem); 1461 const UInt32 limSize = fh.GetDataSize2(rem);
1462 // volume.VolSize > fh.Size for some UEFI archives (is it correct UEFI?) 1462 // volume.VolSize > fh.Size for some UEFI archives (is it correct UEFI?)
1463 // so we will check VolSize for limitSize instead. 1463 // so we will check VolSize for limitSize instead.
1464 RINOK(ParseVolume(bufIndex, offset, sectSize, limSize, newParent, method, level)); 1464 RINOK(ParseVolume(bufIndex, offset, sectSize, limSize, (int)newParent, method, level))
1465 } 1465 }
1466 else 1466 else
1467 AddItem(item); 1467 AddItem(item);
@@ -1477,9 +1477,9 @@ HRESULT CHandler::ParseVolume(
1477 else 1477 else
1478 */ 1478 */
1479 { 1479 {
1480 int newParent = AddDirItem(item); 1480 const unsigned newParent = AddDirItem(item);
1481 bool error2; 1481 bool error2;
1482 RINOK(ParseSections(bufIndex, offset, sectSize, newParent, method, level + 1, error2)); 1482 RINOK(ParseSections(bufIndex, offset, sectSize, (int)newParent, method, level + 1, error2))
1483 if (error2) 1483 if (error2)
1484 { 1484 {
1485 // in intel bio example: one FV_FILETYPE_FREEFORM file is wav file (not sections) 1485 // in intel bio example: one FV_FILETYPE_FREEFORM file is wav file (not sections)
@@ -1510,12 +1510,13 @@ static const char * const kRegionName[] =
1510 1510
1511 1511
1512HRESULT CHandler::ParseIntelMe( 1512HRESULT CHandler::ParseIntelMe(
1513 int bufIndex, UInt32 posBase, 1513 unsigned bufIndex, UInt32 posBase,
1514 UInt32 exactSize, UInt32 limitSize, 1514 UInt32 exactSize, UInt32 limitSize,
1515 int parent, int method, unsigned level) 1515 int parent, int method, unsigned /* level */)
1516{ 1516{
1517 UNUSED_VAR(limitSize) 1517 UNUSED_VAR(limitSize)
1518 level++; 1518 // level++;
1519
1519 const Byte *p = _bufs[bufIndex] + posBase; 1520 const Byte *p = _bufs[bufIndex] + posBase;
1520 if (exactSize < 16 + 16) 1521 if (exactSize < 16 + 16)
1521 return S_FALSE; 1522 return S_FALSE;
@@ -1581,7 +1582,7 @@ HRESULT CHandler::OpenCapsule(IInStream *stream)
1581{ 1582{
1582 const unsigned kHeaderSize = 80; 1583 const unsigned kHeaderSize = 80;
1583 Byte buf[kHeaderSize]; 1584 Byte buf[kHeaderSize];
1584 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); 1585 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize))
1585 if (!_h.Parse(buf)) 1586 if (!_h.Parse(buf))
1586 return S_FALSE; 1587 return S_FALSE;
1587 if (_h.CapsuleImageSize < kHeaderSize 1588 if (_h.CapsuleImageSize < kHeaderSize
@@ -1619,7 +1620,7 @@ HRESULT CHandler::OpenCapsule(IInStream *stream)
1619HRESULT CHandler::OpenFv(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback * /* callback */) 1620HRESULT CHandler::OpenFv(IInStream *stream, const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback * /* callback */)
1620{ 1621{
1621 Byte buf[kFvHeaderSize]; 1622 Byte buf[kFvHeaderSize];
1622 RINOK(ReadStream_FALSE(stream, buf, kFvHeaderSize)); 1623 RINOK(ReadStream_FALSE(stream, buf, kFvHeaderSize))
1623 if (!IsFfs(buf)) 1624 if (!IsFfs(buf))
1624 return S_FALSE; 1625 return S_FALSE;
1625 CVolFfsHeader ffsHeader; 1626 CVolFfsHeader ffsHeader;
@@ -1628,10 +1629,10 @@ HRESULT CHandler::OpenFv(IInStream *stream, const UInt64 * /* maxCheckStartPosit
1628 if (ffsHeader.VolSize > ((UInt32)1 << 30)) 1629 if (ffsHeader.VolSize > ((UInt32)1 << 30))
1629 return S_FALSE; 1630 return S_FALSE;
1630 _phySize = ffsHeader.VolSize; 1631 _phySize = ffsHeader.VolSize;
1631 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 1632 RINOK(InStream_SeekToBegin(stream))
1632 UInt32 fvSize32 = (UInt32)ffsHeader.VolSize; 1633 UInt32 fvSize32 = (UInt32)ffsHeader.VolSize;
1633 unsigned bufIndex = AddBuf(fvSize32); 1634 unsigned bufIndex = AddBuf(fvSize32);
1634 RINOK(ReadStream_FALSE(stream, _bufs[bufIndex], fvSize32)); 1635 RINOK(ReadStream_FALSE(stream, _bufs[bufIndex], fvSize32))
1635 return ParseVolume(bufIndex, 0, fvSize32, fvSize32, -1, -1, 0); 1636 return ParseVolume(bufIndex, 0, fvSize32, fvSize32, -1, -1, 0);
1636} 1637}
1637 1638
@@ -1640,14 +1641,14 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition,
1640{ 1641{
1641 if (_capsuleMode) 1642 if (_capsuleMode)
1642 { 1643 {
1643 RINOK(OpenCapsule(stream)); 1644 RINOK(OpenCapsule(stream))
1644 } 1645 }
1645 else 1646 else
1646 { 1647 {
1647 RINOK(OpenFv(stream, maxCheckStartPosition, callback)); 1648 RINOK(OpenFv(stream, maxCheckStartPosition, callback))
1648 } 1649 }
1649 1650
1650 unsigned num = _items.Size(); 1651 const unsigned num = _items.Size();
1651 CIntArr numChilds(num); 1652 CIntArr numChilds(num);
1652 1653
1653 unsigned i; 1654 unsigned i;
@@ -1657,7 +1658,7 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition,
1657 1658
1658 for (i = 0; i < num; i++) 1659 for (i = 0; i < num; i++)
1659 { 1660 {
1660 int parent = _items[i].Parent; 1661 const int parent = _items[i].Parent;
1661 if (parent >= 0) 1662 if (parent >= 0)
1662 numChilds[(unsigned)parent]++; 1663 numChilds[(unsigned)parent]++;
1663 } 1664 }
@@ -1665,7 +1666,7 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition,
1665 for (i = 0; i < num; i++) 1666 for (i = 0; i < num; i++)
1666 { 1667 {
1667 const CItem &item = _items[i]; 1668 const CItem &item = _items[i];
1668 int parent = item.Parent; 1669 const int parent = item.Parent;
1669 if (parent >= 0) 1670 if (parent >= 0)
1670 { 1671 {
1671 CItem &parentItem = _items[(unsigned)parent]; 1672 CItem &parentItem = _items[(unsigned)parent];
@@ -1718,7 +1719,7 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition,
1718 item2.Name = name; 1719 item2.Name = name;
1719 item2.Characts = characts2; 1720 item2.Characts = characts2;
1720 if (parent >= 0) 1721 if (parent >= 0)
1721 item2.Parent = mainToReduced[(unsigned)parent]; 1722 item2.Parent = (int)mainToReduced[(unsigned)parent];
1722 _items2.Add(item2); 1723 _items2.Add(item2);
1723 /* 1724 /*
1724 CItem2 item2; 1725 CItem2 item2;
@@ -1732,9 +1733,9 @@ HRESULT CHandler::Open2(IInStream *stream, const UInt64 *maxCheckStartPosition,
1732 return S_OK; 1733 return S_OK;
1733} 1734}
1734 1735
1735STDMETHODIMP CHandler::Open(IInStream *inStream, 1736Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
1736 const UInt64 *maxCheckStartPosition, 1737 const UInt64 *maxCheckStartPosition,
1737 IArchiveOpenCallback *callback) 1738 IArchiveOpenCallback *callback))
1738{ 1739{
1739 COM_TRY_BEGIN 1740 COM_TRY_BEGIN
1740 Close(); 1741 Close();
@@ -1747,7 +1748,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
1747 COM_TRY_END 1748 COM_TRY_END
1748} 1749}
1749 1750
1750STDMETHODIMP CHandler::Close() 1751Z7_COM7F_IMF(CHandler::Close())
1751{ 1752{
1752 _phySize = 0; 1753 _phySize = 0;
1753 _totalBufsSize = 0; 1754 _totalBufsSize = 0;
@@ -1761,17 +1762,17 @@ STDMETHODIMP CHandler::Close()
1761 return S_OK; 1762 return S_OK;
1762} 1763}
1763 1764
1764STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1765Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1765{ 1766{
1766 *numItems = _items2.Size(); 1767 *numItems = _items2.Size();
1767 return S_OK; 1768 return S_OK;
1768} 1769}
1769 1770
1770STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1771Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1771 Int32 testMode, IArchiveExtractCallback *extractCallback) 1772 Int32 testMode, IArchiveExtractCallback *extractCallback))
1772{ 1773{
1773 COM_TRY_BEGIN 1774 COM_TRY_BEGIN
1774 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1775 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1775 if (allFilesMode) 1776 if (allFilesMode)
1776 numItems = _items2.Size(); 1777 numItems = _items2.Size();
1777 if (numItems == 0) 1778 if (numItems == 0)
@@ -1794,22 +1795,22 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1794 for (i = 0; i < numItems; i++) 1795 for (i = 0; i < numItems; i++)
1795 { 1796 {
1796 lps->InSize = lps->OutSize = currentTotalSize; 1797 lps->InSize = lps->OutSize = currentTotalSize;
1797 RINOK(lps->SetCur()); 1798 RINOK(lps->SetCur())
1798 CMyComPtr<ISequentialOutStream> realOutStream; 1799 CMyComPtr<ISequentialOutStream> realOutStream;
1799 Int32 askMode = testMode ? 1800 const Int32 askMode = testMode ?
1800 NExtract::NAskMode::kTest : 1801 NExtract::NAskMode::kTest :
1801 NExtract::NAskMode::kExtract; 1802 NExtract::NAskMode::kExtract;
1802 UInt32 index = allFilesMode ? i : indices[i]; 1803 const UInt32 index = allFilesMode ? i : indices[i];
1803 const CItem &item = _items[_items2[index].MainIndex]; 1804 const CItem &item = _items[_items2[index].MainIndex];
1804 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1805 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1805 currentTotalSize += item.Size; 1806 currentTotalSize += item.Size;
1806 1807
1807 if (!testMode && !realOutStream) 1808 if (!testMode && !realOutStream)
1808 continue; 1809 continue;
1809 RINOK(extractCallback->PrepareOperation(askMode)); 1810 RINOK(extractCallback->PrepareOperation(askMode))
1810 if (testMode || item.IsDir) 1811 if (testMode || item.IsDir)
1811 { 1812 {
1812 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1813 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
1813 continue; 1814 continue;
1814 } 1815 }
1815 int res = NExtract::NOperationResult::kDataError; 1816 int res = NExtract::NOperationResult::kDataError;
@@ -1817,18 +1818,18 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1817 GetStream(index, &inStream); 1818 GetStream(index, &inStream);
1818 if (inStream) 1819 if (inStream)
1819 { 1820 {
1820 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); 1821 RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress))
1821 if (copyCoderSpec->TotalSize == item.Size) 1822 if (copyCoderSpec->TotalSize == item.Size)
1822 res = NExtract::NOperationResult::kOK; 1823 res = NExtract::NOperationResult::kOK;
1823 } 1824 }
1824 realOutStream.Release(); 1825 realOutStream.Release();
1825 RINOK(extractCallback->SetOperationResult(res)); 1826 RINOK(extractCallback->SetOperationResult(res))
1826 } 1827 }
1827 return S_OK; 1828 return S_OK;
1828 COM_TRY_END 1829 COM_TRY_END
1829} 1830}
1830 1831
1831STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 1832Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
1832{ 1833{
1833 COM_TRY_BEGIN 1834 COM_TRY_BEGIN
1834 const CItem &item = _items[_items2[index].MainIndex]; 1835 const CItem &item = _items[_items2[index].MainIndex];
@@ -1860,7 +1861,7 @@ static const Byte k_Capsule_Signatures[] =
1860 1861
1861REGISTER_ARC_I_CLS( 1862REGISTER_ARC_I_CLS(
1862 CHandler(true), 1863 CHandler(true),
1863 "UEFIc", "scap", 0, 0xD0, 1864 "UEFIc", "scap", NULL, 0xD0,
1864 k_Capsule_Signatures, 1865 k_Capsule_Signatures,
1865 0, 1866 0,
1866 NArcInfoFlags::kMultiSignature | 1867 NArcInfoFlags::kMultiSignature |
@@ -1880,7 +1881,7 @@ static const Byte k_FFS_Signatures[] =
1880 1881
1881REGISTER_ARC_I_CLS( 1882REGISTER_ARC_I_CLS(
1882 CHandler(false), 1883 CHandler(false),
1883 "UEFIf", "uefif", 0, 0xD1, 1884 "UEFIf", "uefif", NULL, 0xD1,
1884 k_FFS_Signatures, 1885 k_FFS_Signatures,
1885 kFfsGuidOffset, 1886 kFfsGuidOffset,
1886 NArcInfoFlags::kMultiSignature | 1887 NArcInfoFlags::kMultiSignature |
diff --git a/CPP/7zip/Archive/VdiHandler.cpp b/CPP/7zip/Archive/VdiHandler.cpp
index 7641cdc..a5a9332 100644
--- a/CPP/7zip/Archive/VdiHandler.cpp
+++ b/CPP/7zip/Archive/VdiHandler.cpp
@@ -26,9 +26,7 @@ using namespace NWindows;
26namespace NArchive { 26namespace NArchive {
27namespace NVdi { 27namespace NVdi {
28 28
29#define SIGNATURE { 0x7F, 0x10, 0xDA, 0xBE } 29static const Byte k_Signature[] = { 0x7F, 0x10, 0xDA, 0xBE };
30
31static const Byte k_Signature[] = SIGNATURE;
32 30
33static const unsigned k_ClusterBits = 20; 31static const unsigned k_ClusterBits = 20;
34static const UInt32 k_ClusterSize = (UInt32)1 << k_ClusterBits; 32static const UInt32 k_ClusterSize = (UInt32)1 << k_ClusterBits;
@@ -85,7 +83,7 @@ static bool IsEmptyGuid(const Byte *data)
85 83
86 84
87 85
88class CHandler: public CHandlerImg 86Z7_class_CHandler_final: public CHandlerImg
89{ 87{
90 UInt32 _dataOffset; 88 UInt32 _dataOffset;
91 CByteBuffer _table; 89 CByteBuffer _table;
@@ -99,7 +97,7 @@ class CHandler: public CHandlerImg
99 HRESULT Seek2(UInt64 offset) 97 HRESULT Seek2(UInt64 offset)
100 { 98 {
101 _posInArc = offset; 99 _posInArc = offset;
102 return Stream->Seek(offset, STREAM_SEEK_SET, NULL); 100 return InStream_SeekSet(Stream, offset);
103 } 101 }
104 102
105 HRESULT InitAndSeek() 103 HRESULT InitAndSeek()
@@ -108,17 +106,17 @@ class CHandler: public CHandlerImg
108 return Seek2(0); 106 return Seek2(0);
109 } 107 }
110 108
111 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); 109 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override;
112 110
113public: 111public:
114 INTERFACE_IInArchive_Img(;) 112 Z7_IFACE_COM7_IMP(IInArchive_Img)
115 113
116 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); 114 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
117 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 115 Z7_IFACE_COM7_IMP(ISequentialInStream)
118}; 116};
119 117
120 118
121STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 119Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
122{ 120{
123 if (processedSize) 121 if (processedSize)
124 *processedSize = 0; 122 *processedSize = 0;
@@ -152,7 +150,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
152 offset += lowBits; 150 offset += lowBits;
153 if (offset != _posInArc) 151 if (offset != _posInArc)
154 { 152 {
155 RINOK(Seek2(offset)); 153 RINOK(Seek2(offset))
156 } 154 }
157 HRESULT res = Stream->Read(data, size, &size); 155 HRESULT res = Stream->Read(data, size, &size);
158 _posInArc += size; 156 _posInArc += size;
@@ -189,7 +187,7 @@ static const Byte kArcProps[] =
189IMP_IInArchive_Props 187IMP_IInArchive_Props
190IMP_IInArchive_ArcProps 188IMP_IInArchive_ArcProps
191 189
192STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 190Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
193{ 191{
194 COM_TRY_BEGIN 192 COM_TRY_BEGIN
195 NCOM::CPropVariant prop; 193 NCOM::CPropVariant prop;
@@ -209,7 +207,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
209 case kpidErrorFlags: 207 case kpidErrorFlags:
210 { 208 {
211 UInt32 v = 0; 209 UInt32 v = 0;
212 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 210 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
213 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; 211 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod;
214 // if (_headerError) v |= kpv_ErrorFlags_HeadersError; 212 // if (_headerError) v |= kpv_ErrorFlags_HeadersError;
215 if (!Stream && v == 0 && _isArc) 213 if (!Stream && v == 0 && _isArc)
@@ -249,7 +247,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
249 char temp[64]; 247 char temp[64];
250 RawLeGuidToString_Braced(guid, temp); 248 RawLeGuidToString_Braced(guid, temp);
251 MyStringLower_Ascii(temp); 249 MyStringLower_Ascii(temp);
252 strcat(temp, ".vdi"); 250 MyStringCat(temp, ".vdi");
253 prop = temp; 251 prop = temp;
254 } 252 }
255 break; 253 break;
@@ -262,7 +260,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
262} 260}
263 261
264 262
265STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 263Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
266{ 264{
267 COM_TRY_BEGIN 265 COM_TRY_BEGIN
268 NCOM::CPropVariant prop; 266 NCOM::CPropVariant prop;
@@ -284,7 +282,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac
284{ 282{
285 const unsigned kHeaderSize = 512; 283 const unsigned kHeaderSize = 512;
286 Byte buf[kHeaderSize]; 284 Byte buf[kHeaderSize];
287 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); 285 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize))
288 286
289 if (memcmp(buf + 0x40, k_Signature, sizeof(k_Signature)) != 0) 287 if (memcmp(buf + 0x40, k_Signature, sizeof(k_Signature)) != 0)
290 return S_FALSE; 288 return S_FALSE;
@@ -378,8 +376,8 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac
378 } 376 }
379 377
380 _table.Alloc(numBytes); 378 _table.Alloc(numBytes);
381 RINOK(stream->Seek(tableOffset, STREAM_SEEK_SET, NULL)); 379 RINOK(InStream_SeekSet(stream, tableOffset))
382 RINOK(ReadStream_FALSE(stream, _table, numBytes)); 380 RINOK(ReadStream_FALSE(stream, _table, numBytes))
383 381
384 const Byte *data = _table; 382 const Byte *data = _table;
385 for (UInt32 i = 0; i < totalBlocks; i++) 383 for (UInt32 i = 0; i < totalBlocks; i++)
@@ -399,7 +397,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback * /* openCallbac
399} 397}
400 398
401 399
402STDMETHODIMP CHandler::Close() 400Z7_COM7F_IMF(CHandler::Close())
403{ 401{
404 _table.Free(); 402 _table.Free();
405 _phySize = 0; 403 _phySize = 0;
@@ -416,14 +414,14 @@ STDMETHODIMP CHandler::Close()
416} 414}
417 415
418 416
419STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 417Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
420{ 418{
421 COM_TRY_BEGIN 419 COM_TRY_BEGIN
422 *stream = NULL; 420 *stream = NULL;
423 if (_unsupported) 421 if (_unsupported)
424 return S_FALSE; 422 return S_FALSE;
425 CMyComPtr<ISequentialInStream> streamTemp = this; 423 CMyComPtr<ISequentialInStream> streamTemp = this;
426 RINOK(InitAndSeek()); 424 RINOK(InitAndSeek())
427 *stream = streamTemp.Detach(); 425 *stream = streamTemp.Detach();
428 return S_OK; 426 return S_OK;
429 COM_TRY_END 427 COM_TRY_END
diff --git a/CPP/7zip/Archive/VhdHandler.cpp b/CPP/7zip/Archive/VhdHandler.cpp
index 60bc3d3..e5bf997 100644
--- a/CPP/7zip/Archive/VhdHandler.cpp
+++ b/CPP/7zip/Archive/VhdHandler.cpp
@@ -18,18 +18,17 @@
18#define Get32(p) GetBe32(p) 18#define Get32(p) GetBe32(p)
19#define Get64(p) GetBe64(p) 19#define Get64(p) GetBe64(p)
20 20
21#define G32(_offs_, dest) dest = Get32(p + (_offs_)); 21#define G32(_offs_, dest) dest = Get32(p + (_offs_))
22#define G64(_offs_, dest) dest = Get64(p + (_offs_)); 22#define G64(_offs_, dest) dest = Get64(p + (_offs_))
23 23
24using namespace NWindows; 24using namespace NWindows;
25 25
26namespace NArchive { 26namespace NArchive {
27namespace NVhd { 27namespace NVhd {
28 28
29#define SIGNATURE { 'c', 'o', 'n', 'e', 'c', 't', 'i', 'x', 0, 0 }
30
31static const unsigned kSignatureSize = 10; 29static const unsigned kSignatureSize = 10;
32static const Byte kSignature[kSignatureSize] = SIGNATURE; 30static const Byte kSignature[kSignatureSize] =
31 { 'c', 'o', 'n', 'e', 'c', 't', 'i', 'x', 0, 0 };
33 32
34static const UInt32 kUnusedBlock = 0xFFFFFFFF; 33static const UInt32 kUnusedBlock = 0xFFFFFFFF;
35 34
@@ -74,7 +73,7 @@ struct CFooter
74 73
75void CFooter::AddTypeString(AString &s) const 74void CFooter::AddTypeString(AString &s) const
76{ 75{
77 if (Type < ARRAY_SIZE(kDiskTypes)) 76 if (Type < Z7_ARRAY_SIZE(kDiskTypes))
78 s += kDiskTypes[Type]; 77 s += kDiskTypes[Type];
79 else 78 else
80 s.Add_UInt32(Type); 79 s.Add_UInt32(Type);
@@ -214,7 +213,7 @@ bool CDynHeader::Parse(const Byte *p)
214 return CheckBlock(p, 1024, 0x24, 0x240 + 8 * 24); 213 return CheckBlock(p, 1024, 0x24, 0x240 + 8 * 24);
215} 214}
216 215
217class CHandler: public CHandlerImg 216Z7_class_CHandler_final: public CHandlerImg
218{ 217{
219 UInt64 _posInArcLimit; 218 UInt64 _posInArcLimit;
220 UInt64 _startOffset; 219 UInt64 _startOffset;
@@ -247,7 +246,6 @@ class CHandler: public CHandlerImg
247 _phySize = value; 246 _phySize = value;
248 } 247 }
249 248
250 void Reset_PosInArc() { _posInArc = (UInt64)0 - 1; }
251 HRESULT Seek2(UInt64 offset); 249 HRESULT Seek2(UInt64 offset);
252 HRESULT InitAndSeek(); 250 HRESULT InitAndSeek();
253 HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size); 251 HRESULT ReadPhy(UInt64 offset, void *data, UInt32 size);
@@ -303,26 +301,26 @@ class CHandler: public CHandlerImg
303 301
304 HRESULT Open3(); 302 HRESULT Open3();
305 HRESULT Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback *openArchiveCallback, unsigned level); 303 HRESULT Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback *openArchiveCallback, unsigned level);
306 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) 304 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) Z7_override
307 { 305 {
308 return Open2(stream, NULL, openArchiveCallback, 0); 306 return Open2(stream, NULL, openArchiveCallback, 0);
309 } 307 }
310 void CloseAtError(); 308 void CloseAtError() Z7_override;
311 309
312public: 310public:
313 INTERFACE_IInArchive_Img(;) 311 Z7_IFACE_COM7_IMP(IInArchive_Img)
314 312
315 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); 313 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
316 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 314 Z7_IFACE_COM7_IMP(ISequentialInStream)
317}; 315};
318 316
319HRESULT CHandler::Seek2(UInt64 offset) { return Stream->Seek(_startOffset + offset, STREAM_SEEK_SET, NULL); } 317HRESULT CHandler::Seek2(UInt64 offset) { return InStream_SeekSet(Stream, _startOffset + offset); }
320 318
321HRESULT CHandler::InitAndSeek() 319HRESULT CHandler::InitAndSeek()
322{ 320{
323 if (ParentStream) 321 if (ParentStream)
324 { 322 {
325 RINOK(Parent->InitAndSeek()); 323 RINOK(Parent->InitAndSeek())
326 } 324 }
327 _virtPos = _posInArc = 0; 325 _virtPos = _posInArc = 0;
328 BitMapTag = kUnusedBlock; 326 BitMapTag = kUnusedBlock;
@@ -337,7 +335,7 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size)
337 if (offset != _posInArc) 335 if (offset != _posInArc)
338 { 336 {
339 _posInArc = offset; 337 _posInArc = offset;
340 RINOK(Seek2(offset)); 338 RINOK(Seek2(offset))
341 } 339 }
342 HRESULT res = ReadStream_FALSE(Stream, data, size); 340 HRESULT res = ReadStream_FALSE(Stream, data, size);
343 if (res == S_OK) 341 if (res == S_OK)
@@ -352,10 +350,10 @@ HRESULT CHandler::Open3()
352 // Fixed archive uses only footer 350 // Fixed archive uses only footer
353 351
354 UInt64 startPos; 352 UInt64 startPos;
355 RINOK(Stream->Seek(0, STREAM_SEEK_CUR, &startPos)); 353 RINOK(InStream_GetPos(Stream, startPos))
356 _startOffset = startPos; 354 _startOffset = startPos;
357 Byte header[kHeaderSize]; 355 Byte header[kHeaderSize];
358 RINOK(ReadStream_FALSE(Stream, header, kHeaderSize)); 356 RINOK(ReadStream_FALSE(Stream, header, kHeaderSize))
359 bool headerIsOK = Footer.Parse(header); 357 bool headerIsOK = Footer.Parse(header);
360 _size = Footer.CurrentSize; 358 _size = Footer.CurrentSize;
361 359
@@ -372,15 +370,15 @@ HRESULT CHandler::Open3()
372 } 370 }
373 371
374 UInt64 fileSize; 372 UInt64 fileSize;
375 RINOK(Stream->Seek(0, STREAM_SEEK_END, &fileSize)); 373 RINOK(InStream_GetSize_SeekToEnd(Stream, fileSize))
376 if (fileSize < kHeaderSize) 374 if (fileSize < kHeaderSize)
377 return S_FALSE; 375 return S_FALSE;
378 376
379 const UInt32 kDynSize = 1024; 377 const UInt32 kDynSize = 1024;
380 Byte buf[kDynSize]; 378 Byte buf[kDynSize];
381 379
382 RINOK(Stream->Seek(fileSize - kHeaderSize, STREAM_SEEK_SET, NULL)); 380 RINOK(InStream_SeekSet(Stream, fileSize - kHeaderSize))
383 RINOK(ReadStream_FALSE(Stream, buf, kHeaderSize)); 381 RINOK(ReadStream_FALSE(Stream, buf, kHeaderSize))
384 382
385 if (!headerIsOK) 383 if (!headerIsOK)
386 { 384 {
@@ -389,6 +387,7 @@ HRESULT CHandler::Open3()
389 _size = Footer.CurrentSize; 387 _size = Footer.CurrentSize;
390 if (Footer.ThereIsDynamic()) 388 if (Footer.ThereIsDynamic())
391 return S_FALSE; // we can't open Dynamic Archive backward. 389 return S_FALSE; // we can't open Dynamic Archive backward.
390 // fixed archive
392 _posInArcLimit = Footer.CurrentSize; 391 _posInArcLimit = Footer.CurrentSize;
393 _phySize = Footer.CurrentSize + kHeaderSize; 392 _phySize = Footer.CurrentSize + kHeaderSize;
394 _startOffset = fileSize - kHeaderSize - Footer.CurrentSize; 393 _startOffset = fileSize - kHeaderSize - Footer.CurrentSize;
@@ -407,7 +406,7 @@ HRESULT CHandler::Open3()
407 _phySize = fileSize - _startOffset; 406 _phySize = fileSize - _startOffset;
408 } 407 }
409 408
410 RINOK(ReadPhy(Footer.DataOffset, buf, kDynSize)); 409 RINOK(ReadPhy(Footer.DataOffset, buf, kDynSize))
411 if (!Dyn.Parse(buf)) 410 if (!Dyn.Parse(buf))
412 return S_FALSE; 411 return S_FALSE;
413 412
@@ -430,7 +429,7 @@ HRESULT CHandler::Open3()
430 unsigned len = (locator.DataLen >> 1); 429 unsigned len = (locator.DataLen >> 1);
431 { 430 {
432 wchar_t *s = tempString.GetBuf(len); 431 wchar_t *s = tempString.GetBuf(len);
433 RINOK(ReadPhy(locator.DataOffset, nameBuf, locator.DataLen)); 432 RINOK(ReadPhy(locator.DataOffset, nameBuf, locator.DataLen))
434 unsigned j; 433 unsigned j;
435 for (j = 0; j < len; j++) 434 for (j = 0; j < len; j++)
436 { 435 {
@@ -467,7 +466,7 @@ HRESULT CHandler::Open3()
467 466
468 while ((UInt32)Bat.Size() < Dyn.NumBlocks) 467 while ((UInt32)Bat.Size() < Dyn.NumBlocks)
469 { 468 {
470 RINOK(ReadPhy(Dyn.TableOffset + (UInt64)Bat.Size() * 4, buf, kSectorSize)); 469 RINOK(ReadPhy(Dyn.TableOffset + (UInt64)Bat.Size() * 4, buf, kSectorSize))
471 UpdatePhySize(Dyn.TableOffset + kSectorSize); 470 UpdatePhySize(Dyn.TableOffset + kSectorSize);
472 for (UInt32 j = 0; j < kSectorSize; j += 4) 471 for (UInt32 j = 0; j < kSectorSize; j += 4)
473 { 472 {
@@ -495,7 +494,7 @@ HRESULT CHandler::Open3()
495 return S_OK; 494 return S_OK;
496 } 495 }
497 496
498 RINOK(ReadPhy(_phySize, buf, kHeaderSize)); 497 RINOK(ReadPhy(_phySize, buf, kHeaderSize))
499 if (memcmp(header, buf, kHeaderSize) == 0) 498 if (memcmp(header, buf, kHeaderSize) == 0)
500 { 499 {
501 _posInArcLimit = _phySize; 500 _posInArcLimit = _phySize;
@@ -511,7 +510,7 @@ HRESULT CHandler::Open3()
511 for (i = 0; i < kSectorSize && buf[i] == 0; i++); 510 for (i = 0; i < kSectorSize && buf[i] == 0; i++);
512 if (i == kSectorSize) 511 if (i == kSectorSize)
513 { 512 {
514 RINOK(ReadPhy(_phySize + kSectorSize, buf, kHeaderSize)); 513 RINOK(ReadPhy(_phySize + kSectorSize, buf, kHeaderSize))
515 if (memcmp(header, buf, kHeaderSize) == 0) 514 if (memcmp(header, buf, kHeaderSize) == 0)
516 { 515 {
517 _phySize += kSectorSize; 516 _phySize += kSectorSize;
@@ -527,7 +526,7 @@ HRESULT CHandler::Open3()
527 return S_OK; 526 return S_OK;
528} 527}
529 528
530STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 529Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
531{ 530{
532 if (processedSize) 531 if (processedSize)
533 *processedSize = 0; 532 *processedSize = 0;
@@ -540,9 +539,40 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
540 } 539 }
541 if (size == 0) 540 if (size == 0)
542 return S_OK; 541 return S_OK;
543 UInt32 blockIndex = (UInt32)(_virtPos >> Dyn.BlockSizeLog); 542
544 UInt32 blockSectIndex = Bat[blockIndex]; 543 if (Footer.IsFixed())
545 UInt32 blockSize = (UInt32)1 << Dyn.BlockSizeLog; 544 {
545 if (_virtPos > _posInArcLimit)
546 return S_FALSE;
547 {
548 const UInt64 rem = _posInArcLimit - _virtPos;
549 if (size > rem)
550 size = (UInt32)rem;
551 }
552 HRESULT res = S_OK;
553 if (_virtPos != _posInArc)
554 {
555 _posInArc = _virtPos;
556 res = Seek2(_virtPos);
557 }
558 if (res == S_OK)
559 {
560 UInt32 processedSize2 = 0;
561 res = Stream->Read(data, size, &processedSize2);
562 if (processedSize)
563 *processedSize = processedSize2;
564 _posInArc += processedSize2;
565 }
566 if (res != S_OK)
567 Reset_PosInArc();
568 return res;
569 }
570
571 const UInt32 blockIndex = (UInt32)(_virtPos >> Dyn.BlockSizeLog);
572 if (blockIndex >= Bat.Size())
573 return E_FAIL; // it's some unexpected case
574 const UInt32 blockSectIndex = Bat[blockIndex];
575 const UInt32 blockSize = (UInt32)1 << Dyn.BlockSizeLog;
546 UInt32 offsetInBlock = (UInt32)_virtPos & (blockSize - 1); 576 UInt32 offsetInBlock = (UInt32)_virtPos & (blockSize - 1);
547 size = MyMin(blockSize - offsetInBlock, size); 577 size = MyMin(blockSize - offsetInBlock, size);
548 578
@@ -551,7 +581,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
551 { 581 {
552 if (ParentStream) 582 if (ParentStream)
553 { 583 {
554 RINOK(ParentStream->Seek(_virtPos, STREAM_SEEK_SET, NULL)); 584 RINOK(InStream_SeekSet(ParentStream, _virtPos))
555 res = ParentStream->Read(data, size, &size); 585 res = ParentStream->Read(data, size, &size);
556 } 586 }
557 else 587 else
@@ -559,23 +589,23 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
559 } 589 }
560 else 590 else
561 { 591 {
562 UInt64 newPos = (UInt64)blockSectIndex << kSectorSize_Log; 592 const UInt64 newPos = (UInt64)blockSectIndex << kSectorSize_Log;
563 if (BitMapTag != blockIndex) 593 if (BitMapTag != blockIndex)
564 { 594 {
565 RINOK(ReadPhy(newPos, BitMap, (UInt32)BitMap.Size())); 595 RINOK(ReadPhy(newPos, BitMap, (UInt32)BitMap.Size()))
566 BitMapTag = blockIndex; 596 BitMapTag = blockIndex;
567 } 597 }
568 RINOK(ReadPhy(newPos + BitMap.Size() + offsetInBlock, data, size)); 598 RINOK(ReadPhy(newPos + BitMap.Size() + offsetInBlock, data, size))
569 for (UInt32 cur = 0; cur < size;) 599 for (UInt32 cur = 0; cur < size;)
570 { 600 {
571 const UInt32 rem = MyMin(0x200 - (offsetInBlock & 0x1FF), size - cur); 601 const UInt32 rem = MyMin(0x200 - (offsetInBlock & 0x1FF), size - cur);
572 UInt32 bmi = offsetInBlock >> kSectorSize_Log; 602 const UInt32 bmi = offsetInBlock >> kSectorSize_Log;
573 if (((BitMap[bmi >> 3] >> (7 - (bmi & 7))) & 1) == 0) 603 if (((BitMap[bmi >> 3] >> (7 - (bmi & 7))) & 1) == 0)
574 { 604 {
575 if (ParentStream) 605 if (ParentStream)
576 { 606 {
577 RINOK(ParentStream->Seek(_virtPos + cur, STREAM_SEEK_SET, NULL)); 607 RINOK(InStream_SeekSet(ParentStream, _virtPos + cur))
578 RINOK(ReadStream_FALSE(ParentStream, (Byte *)data + cur, rem)); 608 RINOK(ReadStream_FALSE(ParentStream, (Byte *)data + cur, rem))
579 } 609 }
580 else 610 else
581 { 611 {
@@ -651,10 +681,10 @@ static void StringToAString(char *dest, UInt32 val)
651{ 681{
652 for (int i = 24; i >= 0; i -= 8) 682 for (int i = 24; i >= 0; i -= 8)
653 { 683 {
654 Byte b = (Byte)((val >> i) & 0xFF); 684 const Byte b = (Byte)((val >> i) & 0xFF);
655 if (b < 0x20 || b > 0x7F) 685 if (b < 0x20 || b > 0x7F)
656 break; 686 break;
657 *dest++ = b; 687 *dest++ = (char)b;
658 } 688 }
659 *dest = 0; 689 *dest = 0;
660} 690}
@@ -669,7 +699,7 @@ static void ConvertByteToHex(unsigned value, char *s)
669 } 699 }
670} 700}
671 701
672STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 702Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
673{ 703{
674 COM_TRY_BEGIN 704 COM_TRY_BEGIN
675 NCOM::CPropVariant prop; 705 NCOM::CPropVariant prop;
@@ -705,7 +735,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
705 res.Trim(); 735 res.Trim();
706 res.Add_Space(); 736 res.Add_Space();
707 res.Add_UInt32(Footer.CreatorVersion >> 16); 737 res.Add_UInt32(Footer.CreatorVersion >> 16);
708 res += '.'; 738 res.Add_Dot();
709 res.Add_UInt32(Footer.CreatorVersion & 0xFFFF); 739 res.Add_UInt32(Footer.CreatorVersion & 0xFFFF);
710 prop = res; 740 prop = res;
711 break; 741 break;
@@ -776,7 +806,7 @@ HRESULT CHandler::Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback
776 if (level > (1 << 12)) // Maybe we need to increase that limit 806 if (level > (1 << 12)) // Maybe we need to increase that limit
777 return S_FALSE; 807 return S_FALSE;
778 808
779 RINOK(Open3()); 809 RINOK(Open3())
780 810
781 NumLevels = 1; 811 NumLevels = 1;
782 if (child && memcmp(child->Dyn.ParentId, Footer.Id, 16) != 0) 812 if (child && memcmp(child->Dyn.ParentId, Footer.Id, 16) != 0)
@@ -800,9 +830,10 @@ HRESULT CHandler::Open2(IInStream *stream, CHandler *child, IArchiveOpenCallback
800 830
801 Dyn.RelativeNameWasUsed = useRelative; 831 Dyn.RelativeNameWasUsed = useRelative;
802 832
803 CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback; 833 Z7_DECL_CMyComPtr_QI_FROM(
804 openArchiveCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); 834 IArchiveOpenVolumeCallback,
805 835 openVolumeCallback, openArchiveCallback)
836
806 if (openVolumeCallback) 837 if (openVolumeCallback)
807 { 838 {
808 CMyComPtr<IInStream> nextStream; 839 CMyComPtr<IInStream> nextStream;
@@ -881,13 +912,13 @@ void CHandler::CloseAtError()
881 // _unexpectedEnd = false; 912 // _unexpectedEnd = false;
882} 913}
883 914
884STDMETHODIMP CHandler::Close() 915Z7_COM7F_IMF(CHandler::Close())
885{ 916{
886 CloseAtError(); 917 CloseAtError();
887 return S_OK; 918 return S_OK;
888} 919}
889 920
890STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 921Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
891{ 922{
892 COM_TRY_BEGIN 923 COM_TRY_BEGIN
893 NCOM::CPropVariant prop; 924 NCOM::CPropVariant prop;
@@ -912,7 +943,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
912} 943}
913 944
914 945
915STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 946Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
916{ 947{
917 COM_TRY_BEGIN 948 COM_TRY_BEGIN
918 *stream = NULL; 949 *stream = NULL;
@@ -923,14 +954,14 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea
923 streamSpec->SetStream(Stream); 954 streamSpec->SetStream(Stream);
924 // fixme : check (startOffset = 0) 955 // fixme : check (startOffset = 0)
925 streamSpec->InitAndSeek(_startOffset, Footer.CurrentSize); 956 streamSpec->InitAndSeek(_startOffset, Footer.CurrentSize);
926 RINOK(streamSpec->SeekToStart()); 957 RINOK(streamSpec->SeekToStart())
927 *stream = streamTemp.Detach(); 958 *stream = streamTemp.Detach();
928 return S_OK; 959 return S_OK;
929 } 960 }
930 if (!Footer.ThereIsDynamic() || !AreParentsOK()) 961 if (!Footer.ThereIsDynamic() || !AreParentsOK())
931 return S_FALSE; 962 return S_FALSE;
932 CMyComPtr<ISequentialInStream> streamTemp = this; 963 CMyComPtr<ISequentialInStream> streamTemp = this;
933 RINOK(InitAndSeek()); 964 RINOK(InitAndSeek())
934 *stream = streamTemp.Detach(); 965 *stream = streamTemp.Detach();
935 return S_OK; 966 return S_OK;
936 COM_TRY_END 967 COM_TRY_END
diff --git a/CPP/7zip/Archive/VhdxHandler.cpp b/CPP/7zip/Archive/VhdxHandler.cpp
index 0fc83ac..e3ddedd 100644
--- a/CPP/7zip/Archive/VhdxHandler.cpp
+++ b/CPP/7zip/Archive/VhdxHandler.cpp
@@ -20,8 +20,8 @@
20#define Get32(p) GetUi32(p) 20#define Get32(p) GetUi32(p)
21#define Get64(p) GetUi64(p) 21#define Get64(p) GetUi64(p)
22 22
23#define G32(_offs_, dest) dest = Get32(p + (_offs_)); 23#define G32(_offs_, dest) dest = Get32(p + (_offs_))
24#define G64(_offs_, dest) dest = Get64(p + (_offs_)); 24#define G64(_offs_, dest) dest = Get64(p + (_offs_))
25 25
26using namespace NWindows; 26using namespace NWindows;
27 27
@@ -33,7 +33,7 @@ EXTERN_C_BEGIN
33 33
34static UInt32 g_Crc32c_Table[256]; 34static UInt32 g_Crc32c_Table[256];
35 35
36static void MY_FAST_CALL Crc32c_GenerateTable() 36static void Z7_FASTCALL Crc32c_GenerateTable()
37{ 37{
38 UInt32 i; 38 UInt32 i;
39 for (i = 0; i < 256; i++) 39 for (i = 0; i < 256; i++)
@@ -46,13 +46,24 @@ static void MY_FAST_CALL Crc32c_GenerateTable()
46 } 46 }
47} 47}
48 48
49UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table);
50 49
51#define CRC32C_INIT_VAL 0xFFFFFFFF 50#define CRC32C_INIT_VAL 0xFFFFFFFF
52 51
53static UInt32 MY_FAST_CALL Crc32c_Calc(const void *data, size_t size) 52#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
53
54// UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table);
55static UInt32 Z7_FASTCALL CrcUpdateT1_vhdx(UInt32 v, const void *data, size_t size, const UInt32 *table)
54{ 56{
55 return CrcUpdateT1(CRC32C_INIT_VAL, data, size, g_Crc32c_Table) ^ CRC32C_INIT_VAL; 57 const Byte *p = (const Byte *)data;
58 const Byte *pEnd = p + size;
59 for (; p != pEnd; p++)
60 v = CRC_UPDATE_BYTE_2(v, *p);
61 return v;
62}
63
64static UInt32 Z7_FASTCALL Crc32c_Calc(const void *data, size_t size)
65{
66 return CrcUpdateT1_vhdx(CRC32C_INIT_VAL, data, size, g_Crc32c_Table) ^ CRC32C_INIT_VAL;
56} 67}
57 68
58EXTERN_C_END 69EXTERN_C_END
@@ -61,12 +72,11 @@ EXTERN_C_END
61namespace NArchive { 72namespace NArchive {
62namespace NVhdx { 73namespace NVhdx {
63 74
64static struct C_CRC32c_TableInit { C_CRC32c_TableInit() { Crc32c_GenerateTable(); } } g__CRC32c_TableInit; 75static struct C_CRC32c_TableInit { C_CRC32c_TableInit() { Crc32c_GenerateTable(); } } g_CRC32c_TableInit;
65 76
66#define SIGNATURE { 'v', 'h', 'd', 'x', 'f', 'i', 'l', 'e' }
67
68static const unsigned kSignatureSize = 8; 77static const unsigned kSignatureSize = 8;
69static const Byte kSignature[kSignatureSize] = SIGNATURE; 78static const Byte kSignature[kSignatureSize] =
79 { 'v', 'h', 'd', 'x', 'f', 'i', 'l', 'e' };
70 80
71static const unsigned kBitmapSize_Log = 20; 81static const unsigned kBitmapSize_Log = 20;
72static const size_t kBitmapSize = (size_t)1 << kBitmapSize_Log; 82static const size_t kBitmapSize = (size_t)1 << kBitmapSize_Log;
@@ -105,7 +115,7 @@ static int DecodeFrom2HexChars(const wchar_t *s)
105{ 115{
106 const int v0 = HexToVal(s[0]); if (v0 < 0) return -1; 116 const int v0 = HexToVal(s[0]); if (v0 < 0) return -1;
107 const int v1 = HexToVal(s[1]); if (v1 < 0) return -1; 117 const int v1 = HexToVal(s[1]); if (v1 < 0) return -1;
108 return ((unsigned)v0 << 4) | (unsigned)v1; 118 return (int)(((unsigned)v0 << 4) | (unsigned)v1);
109} 119}
110 120
111 121
@@ -183,7 +193,7 @@ struct CHeader
183 if (!Guids[i].IsEqualTo(h.Guids[i])) 193 if (!Guids[i].IsEqualTo(h.Guids[i]))
184 return false; 194 return false;
185 return true; 195 return true;
186 }; 196 }
187 197
188 bool Parse(Byte *p); 198 bool Parse(Byte *p);
189}; 199};
@@ -195,7 +205,7 @@ bool CHeader::Parse(Byte *p)
195 if (Get32(p) != 0x64616568) // "head" 205 if (Get32(p) != 0x64616568) // "head"
196 return false; 206 return false;
197 const UInt32 crc = Get32(p + 4); 207 const UInt32 crc = Get32(p + 4);
198 SetUi32(p + 4, 0); 208 SetUi32(p + 4, 0)
199 if (Crc32c_Calc(p, kHeader2Size) != crc) 209 if (Crc32c_Calc(p, kHeader2Size) != crc)
200 return false; 210 return false;
201 G64(8, SequenceNumber); 211 G64(8, SequenceNumber);
@@ -277,7 +287,7 @@ bool CRegion::Parse(Byte *p)
277 if (Get32(p) != 0x69676572) // "regi" 287 if (Get32(p) != 0x69676572) // "regi"
278 return false; 288 return false;
279 const UInt32 crc = Get32(p + 4); 289 const UInt32 crc = Get32(p + 4);
280 SetUi32(p + 4, 0); 290 SetUi32(p + 4, 0)
281 const UInt32 crc_calced = Crc32c_Calc(p, kRegionSize); 291 const UInt32 crc_calced = Crc32c_Calc(p, kRegionSize);
282 if (crc_calced != crc) 292 if (crc_calced != crc)
283 return false; 293 return false;
@@ -372,7 +382,7 @@ bool CMetaEntry::Parse(const Byte *p)
372 if ((Flags1 & 3) != 0) // Reserved2 382 if ((Flags1 & 3) != 0) // Reserved2
373 return false; 383 return false;
374 return true; 384 return true;
375}; 385}
376 386
377 387
378struct CParentPair 388struct CParentPair
@@ -406,7 +416,7 @@ struct CMetaHeader
406 { 416 {
407 const CParentPair &pair = ParentPairs[i]; 417 const CParentPair &pair = ParentPairs[i];
408 if (pair.Key.IsEqualTo(name)) 418 if (pair.Key.IsEqualTo(name))
409 return i; 419 return (int)i;
410 } 420 }
411 return -1; 421 return -1;
412 } 422 }
@@ -628,7 +638,7 @@ struct CBat
628 638
629 639
630 640
631class CHandler: public CHandlerImg 641Z7_class_CHandler_final: public CHandlerImg
632{ 642{
633 UInt64 _phySize; 643 UInt64 _phySize;
634 644
@@ -657,11 +667,11 @@ class CHandler: public CHandlerImg
657 CMyComPtr<IInStream> ParentStream; 667 CMyComPtr<IInStream> ParentStream;
658 CHandler *Parent; 668 CHandler *Parent;
659 UString _errorMessage; 669 UString _errorMessage;
660 UString _Creator; 670 UString _creator;
661 671
662 bool _nonEmptyLog; 672 bool _nonEmptyLog;
663 bool _isDataContiguous; 673 bool _isDataContiguous;
664 // bool _BatOverlap; 674 // bool _batOverlap;
665 675
666 CGuid _parentGuid; 676 CGuid _parentGuid;
667 bool _parentGuid_IsDefined; 677 bool _parentGuid_IsDefined;
@@ -756,15 +766,15 @@ class CHandler: public CHandlerImg
756 bool CheckBat(); 766 bool CheckBat();
757 767
758 HRESULT Open3(); 768 HRESULT Open3();
759 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback); 769 HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCallback) Z7_override;
760 HRESULT OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen); 770 HRESULT OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen);
761 virtual void CloseAtError(); 771 virtual void CloseAtError() Z7_override;
762 772
763public: 773public:
764 INTERFACE_IInArchive_Img(;) 774 Z7_IFACE_COM7_IMP(IInArchive_Img)
765 775
766 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); 776 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
767 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 777 Z7_IFACE_COM7_IMP(ISequentialInStream)
768 778
769 CHandler(): 779 CHandler():
770 _child(NULL), 780 _child(NULL),
@@ -777,7 +787,7 @@ public:
777 787
778HRESULT CHandler::Seek2(UInt64 offset) 788HRESULT CHandler::Seek2(UInt64 offset)
779{ 789{
780 return Stream->Seek(offset, STREAM_SEEK_SET, NULL); 790 return InStream_SeekSet(Stream, offset);
781} 791}
782 792
783 793
@@ -833,8 +843,8 @@ HRESULT CHandler::ReadPhy(UInt64 offset, void *data, UInt32 size, UInt32 &proces
833#define SB_BLOCK_NOT_PRESENT 0 843#define SB_BLOCK_NOT_PRESENT 0
834#define SB_BLOCK_PRESENT 6 844#define SB_BLOCK_PRESENT 6
835 845
836#define BAT_GET_OFFSET(v) ((v) & ~(UInt64)0xFFFFF); 846#define BAT_GET_OFFSET(v) ((v) & ~(UInt64)0xFFFFF)
837#define BAT_GET_STATE(v) ((UInt32)(v) & 7); 847#define BAT_GET_STATE(v) ((UInt32)(v) & 7)
838 848
839/* The log contains only updates to metadata, bat and region tables 849/* The log contains only updates to metadata, bat and region tables
840 The log doesn't contain updates to start header, and 2 headers (first 192 KB of file). 850 The log doesn't contain updates to start header, and 2 headers (first 192 KB of file).
@@ -1154,10 +1164,10 @@ bool CHandler::CheckBat()
1154HRESULT CHandler::Open3() 1164HRESULT CHandler::Open3()
1155{ 1165{
1156 { 1166 {
1157 static const unsigned kHeaderSize = 512; // + 8 1167 const unsigned kHeaderSize = 512; // + 8
1158 Byte header[kHeaderSize]; 1168 Byte header[kHeaderSize];
1159 1169
1160 RINOK(Read_FALSE(header, kHeaderSize)); 1170 RINOK(Read_FALSE(header, kHeaderSize))
1161 1171
1162 if (memcmp(header, kSignature, kSignatureSize) != 0) 1172 if (memcmp(header, kSignature, kSignatureSize) != 0)
1163 return S_FALSE; 1173 return S_FALSE;
@@ -1168,7 +1178,7 @@ HRESULT CHandler::Open3()
1168 const wchar_t c = Get16(p + i); 1178 const wchar_t c = Get16(p + i);
1169 if (c < 0x20 || c > 0x7F) 1179 if (c < 0x20 || c > 0x7F)
1170 break; 1180 break;
1171 _Creator += c; 1181 _creator += c;
1172 } 1182 }
1173 } 1183 }
1174 1184
@@ -1178,8 +1188,8 @@ HRESULT CHandler::Open3()
1178 Byte header[kHeader2Size]; 1188 Byte header[kHeader2Size];
1179 for (unsigned i = 0; i < 2; i++) 1189 for (unsigned i = 0; i < 2; i++)
1180 { 1190 {
1181 RINOK(Seek2((1 << 16) * (1 + i))); 1191 RINOK(Seek2((1 << 16) * (1 + i)))
1182 RINOK(Read_FALSE(header, kHeader2Size)); 1192 RINOK(Read_FALSE(header, kHeader2Size))
1183 bool headerIsOK = headers[i].Parse(header); 1193 bool headerIsOK = headers[i].Parse(header);
1184 if (!headerIsOK) 1194 if (!headerIsOK)
1185 return S_FALSE; 1195 return S_FALSE;
@@ -1233,8 +1243,8 @@ HRESULT CHandler::Open3()
1233 { 1243 {
1234 CByteBuffer temp; 1244 CByteBuffer temp;
1235 temp.Alloc(kRegionSize * 2); 1245 temp.Alloc(kRegionSize * 2);
1236 RINOK(Seek2((1 << 16) * 3)); 1246 RINOK(Seek2((1 << 16) * 3))
1237 RINOK(Read_FALSE(temp, kRegionSize * 2)); 1247 RINOK(Read_FALSE(temp, kRegionSize * 2))
1238 unsigned numTables = 1; 1248 unsigned numTables = 1;
1239 if (memcmp(temp, temp + kRegionSize, kRegionSize) != 0) 1249 if (memcmp(temp, temp + kRegionSize, kRegionSize) != 0)
1240 { 1250 {
@@ -1249,7 +1259,7 @@ HRESULT CHandler::Open3()
1249 if (regions[i].Parse(temp)) 1259 if (regions[i].Parse(temp))
1250 { 1260 {
1251 if (correctRegionIndex < 0) 1261 if (correctRegionIndex < 0)
1252 correctRegionIndex = i; 1262 correctRegionIndex = (int)i;
1253 } 1263 }
1254 else 1264 else
1255 { 1265 {
@@ -1281,8 +1291,8 @@ HRESULT CHandler::Open3()
1281 // static const kMetaTableSize = 1 << 16; 1291 // static const kMetaTableSize = 1 << 16;
1282 CByteBuffer temp; 1292 CByteBuffer temp;
1283 { 1293 {
1284 RINOK(Seek2(e.Offset)); 1294 RINOK(Seek2(e.Offset))
1285 RINOK(ReadToBuf_FALSE(temp, e.Len)); 1295 RINOK(ReadToBuf_FALSE(temp, e.Len))
1286 } 1296 }
1287 if (!Meta.Parse(temp, temp.Size())) 1297 if (!Meta.Parse(temp, temp.Size()))
1288 return S_FALSE; 1298 return S_FALSE;
@@ -1297,15 +1307,15 @@ HRESULT CHandler::Open3()
1297 return S_FALSE; 1307 return S_FALSE;
1298 // UpdatePhySize(e.GetEndPos()); 1308 // UpdatePhySize(e.GetEndPos());
1299 { 1309 {
1300 RINOK(Seek2(e.Offset)); 1310 RINOK(Seek2(e.Offset))
1301 RINOK(ReadToBuf_FALSE(Bat.Data, e.Len)); 1311 RINOK(ReadToBuf_FALSE(Bat.Data, e.Len))
1302 } 1312 }
1303 if (!ParseBat()) 1313 if (!ParseBat())
1304 return S_FALSE; 1314 return S_FALSE;
1305 if (!CheckBat()) 1315 if (!CheckBat())
1306 { 1316 {
1307 AddErrorMessage("BAT overlap"); 1317 AddErrorMessage("BAT overlap");
1308 // _BatOverlap = true; 1318 // _batOverlap = true;
1309 // return S_FALSE; 1319 // return S_FALSE;
1310 } 1320 }
1311 } 1321 }
@@ -1327,13 +1337,13 @@ HRESULT CHandler::Open3()
1327 { 1337 {
1328 // absolute paths for parent stream can be rejected later in client callback 1338 // absolute paths for parent stream can be rejected later in client callback
1329 // the order of check by specification: 1339 // the order of check by specification:
1330 static const char * const g_ParentKeys[] = 1340 const char * const g_ParentKeys[] =
1331 { 1341 {
1332 "relative_path" // "..\..\path2\sub3\parent.vhdx" 1342 "relative_path" // "..\..\path2\sub3\parent.vhdx"
1333 , "volume_path" // "\\?\Volume{26A21BDA-A627-11D7-9931-806E6F6E6963}\path2\sub3\parent.vhdx") 1343 , "volume_path" // "\\?\Volume{26A21BDA-A627-11D7-9931-806E6F6E6963}\path2\sub3\parent.vhdx")
1334 , "absolute_win32_path" // "d:\path2\sub3\parent.vhdx" 1344 , "absolute_win32_path" // "d:\path2\sub3\parent.vhdx"
1335 }; 1345 };
1336 for (unsigned i = 0; i < ARRAY_SIZE(g_ParentKeys); i++) 1346 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ParentKeys); i++)
1337 { 1347 {
1338 const int index = Meta.FindParentKey(g_ParentKeys[i]); 1348 const int index = Meta.FindParentKey(g_ParentKeys[i]);
1339 if (index < 0) 1349 if (index < 0)
@@ -1368,7 +1378,7 @@ HRESULT CHandler::Open3()
1368 1378
1369 // _posInArc = 0; 1379 // _posInArc = 0;
1370 // Reset_PosInArc(); 1380 // Reset_PosInArc();
1371 // RINOK(Stream->Seek(0, STREAM_SEEK_SET, NULL)); 1381 // RINOK(InStream_SeekToBegin(Stream))
1372 1382
1373 return S_OK; 1383 return S_OK;
1374} 1384}
@@ -1384,7 +1394,7 @@ static struct CCounter { ~CCounter()
1384} } g_Counter; 1394} } g_Counter;
1385*/ 1395*/
1386 1396
1387STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 1397Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
1388{ 1398{
1389 // g_NumCalls++; 1399 // g_NumCalls++;
1390 if (processedSize) 1400 if (processedSize)
@@ -1489,7 +1499,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
1489 return S_FALSE; 1499 return S_FALSE;
1490 // if (ParentStream) 1500 // if (ParentStream)
1491 { 1501 {
1492 RINOK(ParentStream->Seek(_virtPos, STREAM_SEEK_SET, NULL)); 1502 RINOK(InStream_SeekSet(ParentStream, _virtPos))
1493 size_t processed = size; 1503 size_t processed = size;
1494 res = ReadStream(ParentStream, (Byte *)data, &processed); 1504 res = ReadStream(ParentStream, (Byte *)data, &processed);
1495 size = (UInt32)processed; 1505 size = (UInt32)processed;
@@ -1668,7 +1678,7 @@ void CHandler::AddComment(UString &s) const
1668 1678
1669 1679
1670 1680
1671STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1681Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1672{ 1682{
1673 COM_TRY_BEGIN 1683 COM_TRY_BEGIN
1674 NCOM::CPropVariant prop; 1684 NCOM::CPropVariant prop;
@@ -1735,8 +1745,8 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1735 } 1745 }
1736 case kpidCreatorApp: 1746 case kpidCreatorApp:
1737 { 1747 {
1738 if (!_Creator.IsEmpty()) 1748 if (!_creator.IsEmpty())
1739 prop = _Creator; 1749 prop = _creator;
1740 break; 1750 break;
1741 } 1751 }
1742 case kpidId: 1752 case kpidId:
@@ -1808,7 +1818,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCall
1808 if (_level >= (1 << 20)) 1818 if (_level >= (1 << 20))
1809 return S_FALSE; 1819 return S_FALSE;
1810 1820
1811 RINOK(Open3()); 1821 RINOK(Open3())
1812 1822
1813 NumLevels = 1; 1823 NumLevels = 1;
1814 PackSize_Total = GetPackSize(); 1824 PackSize_Total = GetPackSize();
@@ -1882,12 +1892,11 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openArchiveCall
1882HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen) 1892HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_parentFileWasOpen)
1883{ 1893{
1884 _parentFileWasOpen = false; 1894 _parentFileWasOpen = false;
1885 CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback; 1895 Z7_DECL_CMyComPtr_QI_FROM(
1886 openArchiveCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); 1896 IArchiveOpenVolumeCallback,
1887 1897 openVolumeCallback, openArchiveCallback)
1888 if (!openVolumeCallback) 1898 if (!openVolumeCallback)
1889 return S_FALSE; 1899 return S_FALSE;
1890
1891 { 1900 {
1892 CMyComPtr<IInStream> nextStream; 1901 CMyComPtr<IInStream> nextStream;
1893 HRESULT res = S_FALSE; 1902 HRESULT res = S_FALSE;
@@ -1961,7 +1970,7 @@ HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_p
1961 UInt64 numBytes = (UInt64)NumUsedBitMaps << kBitmapSize_Log; 1970 UInt64 numBytes = (UInt64)NumUsedBitMaps << kBitmapSize_Log;
1962 if (openArchiveCallback && numBytes != 0) 1971 if (openArchiveCallback && numBytes != 0)
1963 { 1972 {
1964 RINOK(openArchiveCallback->SetTotal(NULL, &numBytes)); 1973 RINOK(openArchiveCallback->SetTotal(NULL, &numBytes))
1965 } 1974 }
1966 numBytes = 0; 1975 numBytes = 0;
1967 for (size_t i = ChunkRatio; i < TotalBatEntries; i += ChunkRatio + 1) 1976 for (size_t i = ChunkRatio; i < TotalBatEntries; i += ChunkRatio + 1)
@@ -1975,12 +1984,12 @@ HRESULT CHandler::OpenParent(IArchiveOpenCallback *openArchiveCallback, bool &_p
1975 { 1984 {
1976 if (openArchiveCallback) 1985 if (openArchiveCallback)
1977 { 1986 {
1978 RINOK(openArchiveCallback->SetCompleted(NULL, &numBytes)); 1987 RINOK(openArchiveCallback->SetCompleted(NULL, &numBytes))
1979 } 1988 }
1980 numBytes += kBitmapSize; 1989 numBytes += kBitmapSize;
1981 buf.Alloc(kBitmapSize); 1990 buf.Alloc(kBitmapSize);
1982 RINOK(Seek2(offset)); 1991 RINOK(Seek2(offset))
1983 RINOK(Read_FALSE(buf, kBitmapSize)); 1992 RINOK(Read_FALSE(buf, kBitmapSize))
1984 /* 1993 /*
1985 for (unsigned i = 0; i < (1 << 20); i+=4) 1994 for (unsigned i = 0; i < (1 << 20); i+=4)
1986 { 1995 {
@@ -2018,11 +2027,11 @@ void CHandler::CloseAtError()
2018 Parent = NULL; 2027 Parent = NULL;
2019 ParentStream.Release(); 2028 ParentStream.Release();
2020 _errorMessage.Empty(); 2029 _errorMessage.Empty();
2021 _Creator.Empty(); 2030 _creator.Empty();
2022 _nonEmptyLog = false; 2031 _nonEmptyLog = false;
2023 _parentGuid_IsDefined = false; 2032 _parentGuid_IsDefined = false;
2024 _isDataContiguous = false; 2033 _isDataContiguous = false;
2025 // _BatOverlap = false; 2034 // _batOverlap = false;
2026 2035
2027 ParentNames.Clear(); 2036 ParentNames.Clear();
2028 ParentName_Used.Empty(); 2037 ParentName_Used.Empty();
@@ -2039,14 +2048,14 @@ void CHandler::CloseAtError()
2039 _isCyclic_or_CyclicParent = false; 2048 _isCyclic_or_CyclicParent = false;
2040} 2049}
2041 2050
2042STDMETHODIMP CHandler::Close() 2051Z7_COM7F_IMF(CHandler::Close())
2043{ 2052{
2044 CloseAtError(); 2053 CloseAtError();
2045 return S_OK; 2054 return S_OK;
2046} 2055}
2047 2056
2048 2057
2049STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 2058Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
2050{ 2059{
2051 COM_TRY_BEGIN 2060 COM_TRY_BEGIN
2052 NCOM::CPropVariant prop; 2061 NCOM::CPropVariant prop;
@@ -2064,7 +2073,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
2064} 2073}
2065 2074
2066 2075
2067STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 2076Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
2068{ 2077{
2069 COM_TRY_BEGIN 2078 COM_TRY_BEGIN
2070 *stream = NULL; 2079 *stream = NULL;
diff --git a/CPP/7zip/Archive/VmdkHandler.cpp b/CPP/7zip/Archive/VmdkHandler.cpp
index 40f5613..0a6b967 100644
--- a/CPP/7zip/Archive/VmdkHandler.cpp
+++ b/CPP/7zip/Archive/VmdkHandler.cpp
@@ -31,14 +31,12 @@ namespace NVmdk {
31#define Get32(p) GetUi32(p) 31#define Get32(p) GetUi32(p)
32#define Get64(p) GetUi64(p) 32#define Get64(p) GetUi64(p)
33 33
34#define LE_16(offs, dest) dest = Get16(p + (offs)); 34#define LE_16(offs, dest) dest = Get16(p + (offs))
35#define LE_32(offs, dest) dest = Get32(p + (offs)); 35#define LE_32(offs, dest) dest = Get32(p + (offs))
36#define LE_64(offs, dest) dest = Get64(p + (offs)); 36#define LE_64(offs, dest) dest = Get64(p + (offs))
37 37
38 38
39#define SIGNATURE { 'K', 'D', 'M', 'V' } 39static const Byte k_Signature[] = { 'K', 'D', 'M', 'V' };
40
41static const Byte k_Signature[] = SIGNATURE;
42 40
43static const UInt32 k_Flags_NL = (UInt32)1 << 0; 41static const UInt32 k_Flags_NL = (UInt32)1 << 0;
44// static const UInt32 k_Flags_RGD = (UInt32)1 << 1; 42// static const UInt32 k_Flags_RGD = (UInt32)1 << 1;
@@ -65,10 +63,10 @@ struct CHeader
65 UInt64 gdOffset; 63 UInt64 gdOffset;
66 UInt64 overHead; 64 UInt64 overHead;
67 65
68 bool Is_NL() const { return (flags & k_Flags_NL) != 0; }; 66 bool Is_NL() const { return (flags & k_Flags_NL) != 0; }
69 bool Is_ZeroGrain() const { return (flags & k_Flags_ZeroGrain) != 0; }; 67 bool Is_ZeroGrain() const { return (flags & k_Flags_ZeroGrain) != 0; }
70 bool Is_Compressed() const { return (flags & k_Flags_Compressed) != 0; }; 68 bool Is_Compressed() const { return (flags & k_Flags_Compressed) != 0; }
71 bool Is_Marker() const { return (flags & k_Flags_Marker) != 0; }; 69 bool Is_Marker() const { return (flags & k_Flags_Marker) != 0; }
72 70
73 bool Parse(const Byte *p); 71 bool Parse(const Byte *p);
74 72
@@ -165,7 +163,7 @@ static const char *SkipSpaces(const char *s)
165static const char *GetNextWord(const char *s, AString &dest) 163static const char *GetNextWord(const char *s, AString &dest)
166{ 164{
167 dest.Empty(); 165 dest.Empty();
168 SKIP_SPACES(s); 166 SKIP_SPACES(s)
169 const char *start = s; 167 const char *start = s;
170 for (;; s++) 168 for (;; s++)
171 { 169 {
@@ -180,7 +178,7 @@ static const char *GetNextWord(const char *s, AString &dest)
180 178
181static const char *GetNextNumber(const char *s, UInt64 &val) 179static const char *GetNextNumber(const char *s, UInt64 &val)
182{ 180{
183 SKIP_SPACES(s); 181 SKIP_SPACES(s)
184 if (*s == 0) 182 if (*s == 0)
185 return s; 183 return s;
186 const char *end; 184 const char *end;
@@ -228,7 +226,7 @@ bool CExtentInfo::Parse(const char *s)
228 if (Type.IsEmpty()) 226 if (Type.IsEmpty())
229 return false; 227 return false;
230 228
231 SKIP_SPACES(s); 229 SKIP_SPACES(s)
232 230
233 if (IsType_ZERO()) 231 if (IsType_ZERO())
234 return (*s == 0); 232 return (*s == 0);
@@ -243,7 +241,7 @@ bool CExtentInfo::Parse(const char *s)
243 FileName.SetFrom(s, (unsigned)(s2 - s)); 241 FileName.SetFrom(s, (unsigned)(s2 - s));
244 s = s2 + 1; 242 s = s2 + 1;
245 } 243 }
246 SKIP_SPACES(s); 244 SKIP_SPACES(s)
247 if (*s == 0) 245 if (*s == 0)
248 return true; 246 return true;
249 247
@@ -298,7 +296,7 @@ bool CDescriptor::Parse(const Byte *p, size_t size)
298 296
299 for (;;) 297 for (;;)
300 { 298 {
301 char c = 0; 299 Byte c = 0;
302 if (size != 0) 300 if (size != 0)
303 { 301 {
304 size--; 302 size--;
@@ -369,7 +367,7 @@ struct CExtent
369 367
370 UInt64 GetEndOffset() const { return StartOffset + NumBytes; } 368 UInt64 GetEndOffset() const { return StartOffset + NumBytes; }
371 369
372 bool IsVmdk() const { return !IsZero && !IsFlat; }; 370 bool IsVmdk() const { return !IsZero && !IsFlat; }
373 // if (IsOK && IsVmdk()), then VMDK header of this extent was read 371 // if (IsOK && IsVmdk()), then VMDK header of this extent was read
374 372
375 CExtent(): 373 CExtent():
@@ -403,7 +401,7 @@ struct CExtent
403 HRESULT Seek(UInt64 offset) 401 HRESULT Seek(UInt64 offset)
404 { 402 {
405 PosInArc = offset; 403 PosInArc = offset;
406 return Stream->Seek(offset, STREAM_SEEK_SET, NULL); 404 return InStream_SeekSet(Stream, offset);
407 } 405 }
408 406
409 HRESULT InitAndSeek() 407 HRESULT InitAndSeek()
@@ -422,7 +420,7 @@ struct CExtent
422}; 420};
423 421
424 422
425class CHandler: public CHandlerImg 423Z7_class_CHandler_final: public CHandlerImg
426{ 424{
427 bool _isArc; 425 bool _isArc;
428 bool _unsupported; 426 bool _unsupported;
@@ -461,17 +459,17 @@ class CHandler: public CHandlerImg
461 _virtPos = 0; 459 _virtPos = 0;
462 } 460 }
463 461
464 virtual HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback); 462 virtual HRESULT Open2(IInStream *stream, IArchiveOpenCallback *openCallback) Z7_override;
465 virtual void CloseAtError(); 463 virtual void CloseAtError() Z7_override;
466public: 464public:
467 INTERFACE_IInArchive_Img(;) 465 Z7_IFACE_COM7_IMP(IInArchive_Img)
468 466
469 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); 467 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
470 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 468 Z7_IFACE_COM7_IMP(ISequentialInStream)
471}; 469};
472 470
473 471
474STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize) 472Z7_COM7F_IMF(CHandler::Read(void *data, UInt32 size, UInt32 *processedSize))
475{ 473{
476 if (processedSize) 474 if (processedSize)
477 *processedSize = 0; 475 *processedSize = 0;
@@ -569,7 +567,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
569 UInt64 offset = extent.FlatOffset + vir; 567 UInt64 offset = extent.FlatOffset + vir;
570 if (offset != extent.PosInArc) 568 if (offset != extent.PosInArc)
571 { 569 {
572 RINOK(extent.Seek(offset)); 570 RINOK(extent.Seek(offset))
573 } 571 }
574 UInt32 size2 = 0; 572 UInt32 size2 = 0;
575 HRESULT res = extent.Stream->Read(data, size, &size2); 573 HRESULT res = extent.Stream->Read(data, size, &size2);
@@ -636,13 +634,13 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
636 if (offset != extent.PosInArc) 634 if (offset != extent.PosInArc)
637 { 635 {
638 // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc)); 636 // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc));
639 RINOK(extent.Seek(offset)); 637 RINOK(extent.Seek(offset))
640 } 638 }
641 639
642 const size_t kStartSize = 1 << 9; 640 const size_t kStartSize = 1 << 9;
643 { 641 {
644 size_t curSize = kStartSize; 642 size_t curSize = kStartSize;
645 RINOK(extent.Read(_cacheCompressed, &curSize)); 643 RINOK(extent.Read(_cacheCompressed, &curSize))
646 // _stream_PackSize += curSize; 644 // _stream_PackSize += curSize;
647 if (curSize != kStartSize) 645 if (curSize != kStartSize)
648 return S_FALSE; 646 return S_FALSE;
@@ -664,7 +662,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
664 return S_FALSE; 662 return S_FALSE;
665 size_t curSize = dataSize2 - kStartSize; 663 size_t curSize = dataSize2 - kStartSize;
666 const size_t curSize2 = curSize; 664 const size_t curSize2 = curSize;
667 RINOK(extent.Read(_cacheCompressed + kStartSize, &curSize)); 665 RINOK(extent.Read(_cacheCompressed + kStartSize, &curSize))
668 // _stream_PackSize += curSize; 666 // _stream_PackSize += curSize;
669 if (curSize != curSize2) 667 if (curSize != curSize2)
670 return S_FALSE; 668 return S_FALSE;
@@ -680,8 +678,8 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
680 _bufOutStreamSpec->Init(_cache, clusterSize); 678 _bufOutStreamSpec->Init(_cache, clusterSize);
681 679
682 // Do we need to use smaller block than clusterSize for last cluster? 680 // Do we need to use smaller block than clusterSize for last cluster?
683 UInt64 blockSize64 = clusterSize; 681 const UInt64 blockSize64 = clusterSize;
684 HRESULT res = _zlibDecoderSpec->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL); 682 HRESULT res = _zlibDecoder->Code(_bufInStream, _bufOutStream, NULL, &blockSize64, NULL);
685 683
686 /* 684 /*
687 if (_bufOutStreamSpec->GetPos() != clusterSize) 685 if (_bufOutStreamSpec->GetPos() != clusterSize)
@@ -699,7 +697,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
699 res = S_FALSE; 697 res = S_FALSE;
700 } 698 }
701 699
702 RINOK(res); 700 RINOK(res)
703 701
704 _cacheCluster = cluster; 702 _cacheCluster = cluster;
705 _cacheExtent = extentIndex; 703 _cacheExtent = extentIndex;
@@ -718,7 +716,7 @@ STDMETHODIMP CHandler::Read(void *data, UInt32 size, UInt32 *processedSize)
718 if (offset != extent.PosInArc) 716 if (offset != extent.PosInArc)
719 { 717 {
720 // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc)); 718 // printf("\n%12x %12x\n", (unsigned)offset, (unsigned)(offset - extent.PosInArc));
721 RINOK(extent.Seek(offset)); 719 RINOK(extent.Seek(offset))
722 } 720 }
723 UInt32 size2 = 0; 721 UInt32 size2 = 0;
724 HRESULT res = extent.Stream->Read(data, size, &size2); 722 HRESULT res = extent.Stream->Read(data, size, &size2);
@@ -762,6 +760,7 @@ static const Byte kProps[] =
762static const Byte kArcProps[] = 760static const Byte kArcProps[] =
763{ 761{
764 kpidNumVolumes, 762 kpidNumVolumes,
763 kpidTotalPhySize,
765 kpidMethod, 764 kpidMethod,
766 kpidClusterSize, 765 kpidClusterSize,
767 kpidHeadersSize, 766 kpidHeadersSize,
@@ -774,7 +773,7 @@ IMP_IInArchive_Props
774IMP_IInArchive_ArcProps 773IMP_IInArchive_ArcProps
775 774
776 775
777STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 776Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
778{ 777{
779 COM_TRY_BEGIN 778 COM_TRY_BEGIN
780 NCOM::CPropVariant prop; 779 NCOM::CPropVariant prop;
@@ -794,6 +793,17 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
794 { 793 {
795 case kpidMainSubfile: prop = (UInt32)0; break; 794 case kpidMainSubfile: prop = (UInt32)0; break;
796 case kpidPhySize: if (_phySize != 0) prop = _phySize; break; 795 case kpidPhySize: if (_phySize != 0) prop = _phySize; break;
796 case kpidTotalPhySize:
797 {
798 UInt64 sum = _phySize;
799 if (_isMultiVol)
800 {
801 FOR_VECTOR (i, _extents)
802 sum += _extents[i].PhySize;
803 }
804 prop = sum;
805 break;
806 }
797 case kpidClusterSize: prop = (UInt32)((UInt32)1 << _clusterBitsMax); break; 807 case kpidClusterSize: prop = (UInt32)((UInt32)1 << _clusterBitsMax); break;
798 case kpidHeadersSize: if (e) prop = (e->h.overHead << 9); break; 808 case kpidHeadersSize: if (e) prop = (e->h.overHead << 9); break;
799 case kpidMethod: 809 case kpidMethod:
@@ -896,7 +906,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
896 case kpidErrorFlags: 906 case kpidErrorFlags:
897 { 907 {
898 UInt32 v = 0; 908 UInt32 v = 0;
899 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;; 909 if (!_isArc) v |= kpv_ErrorFlags_IsNotArc;
900 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod; 910 if (_unsupported) v |= kpv_ErrorFlags_UnsupportedMethod;
901 if (_unsupportedSome) v |= kpv_ErrorFlags_UnsupportedMethod; 911 if (_unsupportedSome) v |= kpv_ErrorFlags_UnsupportedMethod;
902 if (_headerError) v |= kpv_ErrorFlags_HeadersError; 912 if (_headerError) v |= kpv_ErrorFlags_HeadersError;
@@ -913,7 +923,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
913} 923}
914 924
915 925
916STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 926Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
917{ 927{
918 COM_TRY_BEGIN 928 COM_TRY_BEGIN
919 NCOM::CPropVariant prop; 929 NCOM::CPropVariant prop;
@@ -962,9 +972,9 @@ static int inline GetLog(UInt64 num)
962HRESULT CExtent::ReadForHeader(IInStream *stream, UInt64 sector, void *data, size_t numSectors) 972HRESULT CExtent::ReadForHeader(IInStream *stream, UInt64 sector, void *data, size_t numSectors)
963{ 973{
964 sector <<= 9; 974 sector <<= 9;
965 RINOK(stream->Seek(sector, STREAM_SEEK_SET, NULL)); 975 RINOK(InStream_SeekSet(stream, sector))
966 size_t size = numSectors << 9; 976 size_t size = numSectors << 9;
967 RINOK(ReadStream_FALSE(stream, data, size)); 977 RINOK(ReadStream_FALSE(stream, data, size))
968 UInt64 end = sector + size; 978 UInt64 end = sector + size;
969 if (PhySize < end) 979 if (PhySize < end)
970 PhySize = end; 980 PhySize = end;
@@ -987,7 +997,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
987 const unsigned kSectoreSize = 512; 997 const unsigned kSectoreSize = 512;
988 Byte buf[kSectoreSize]; 998 Byte buf[kSectoreSize];
989 size_t headerSize = kSectoreSize; 999 size_t headerSize = kSectoreSize;
990 RINOK(ReadStream(stream, buf, &headerSize)); 1000 RINOK(ReadStream(stream, buf, &headerSize))
991 1001
992 if (headerSize < sizeof(k_Signature)) 1002 if (headerSize < sizeof(k_Signature))
993 return S_FALSE; 1003 return S_FALSE;
@@ -1003,13 +1013,13 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
1003 return S_FALSE; 1013 return S_FALSE;
1004 1014
1005 UInt64 endPos; 1015 UInt64 endPos;
1006 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); 1016 RINOK(InStream_GetSize_SeekToEnd(stream, endPos))
1007 if (endPos > (1 << 20)) 1017 if (endPos > (1 << 20))
1008 return S_FALSE; 1018 return S_FALSE;
1009 const size_t numBytes = (size_t)endPos; 1019 const size_t numBytes = (size_t)endPos;
1010 _descriptorBuf.Alloc(numBytes); 1020 _descriptorBuf.Alloc(numBytes);
1011 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); 1021 RINOK(InStream_SeekToBegin(stream))
1012 RINOK(ReadStream_FALSE(stream, _descriptorBuf, numBytes)); 1022 RINOK(ReadStream_FALSE(stream, _descriptorBuf, numBytes))
1013 1023
1014 if (!_descriptor.Parse(_descriptorBuf, _descriptorBuf.Size())) 1024 if (!_descriptor.Parse(_descriptorBuf, _descriptorBuf.Size()))
1015 return S_FALSE; 1025 return S_FALSE;
@@ -1046,7 +1056,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
1046 if (_descriptor.Extents.Size() > 1) 1056 if (_descriptor.Extents.Size() > 1)
1047 { 1057 {
1048 const UInt64 numFiles = _descriptor.Extents.Size(); 1058 const UInt64 numFiles = _descriptor.Extents.Size();
1049 RINOK(openCallback->SetTotal(&numFiles, NULL)); 1059 RINOK(openCallback->SetTotal(&numFiles, NULL))
1050 } 1060 }
1051 } 1061 }
1052 1062
@@ -1117,7 +1127,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
1117 stream = nextStream; 1127 stream = nextStream;
1118 1128
1119 headerSize = kSectoreSize; 1129 headerSize = kSectoreSize;
1120 RINOK(ReadStream(stream, buf, &headerSize)); 1130 RINOK(ReadStream(stream, buf, &headerSize))
1121 1131
1122 if (headerSize != kSectoreSize) 1132 if (headerSize != kSectoreSize)
1123 continue; 1133 continue;
@@ -1176,7 +1186,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
1176 _needDeflate = false; 1186 _needDeflate = false;
1177 _clusterBitsMax = 0; 1187 _clusterBitsMax = 0;
1178 1188
1179 unsigned numOKs = 0; 1189 // unsigned numOKs = 0;
1180 unsigned numUnsupported = 0; 1190 unsigned numUnsupported = 0;
1181 1191
1182 FOR_VECTOR (i, _extents) 1192 FOR_VECTOR (i, _extents)
@@ -1186,7 +1196,7 @@ HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *openCallback)
1186 numUnsupported++; 1196 numUnsupported++;
1187 if (!e.IsOK) 1197 if (!e.IsOK)
1188 continue; 1198 continue;
1189 numOKs++; 1199 // numOKs++;
1190 if (e.IsVmdk()) 1200 if (e.IsVmdk())
1191 { 1201 {
1192 if (e.NeedDeflate) 1202 if (e.NeedDeflate)
@@ -1212,7 +1222,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1212 h.descriptorSize > (1 << 10)) 1222 h.descriptorSize > (1 << 10))
1213 return S_FALSE; 1223 return S_FALSE;
1214 DescriptorBuf.Alloc((size_t)h.descriptorSize << 9); 1224 DescriptorBuf.Alloc((size_t)h.descriptorSize << 9);
1215 RINOK(ReadForHeader(stream, h.descriptorOffset, DescriptorBuf, (size_t)h.descriptorSize)); 1225 RINOK(ReadForHeader(stream, h.descriptorOffset, DescriptorBuf, (size_t)h.descriptorSize))
1216 if (h.descriptorOffset == 1 && h.Is_Marker() && Get64(DescriptorBuf) == 0) 1226 if (h.descriptorOffset == 1 && h.Is_Marker() && Get64(DescriptorBuf) == 0)
1217 { 1227 {
1218 // We check data as end marker. 1228 // We check data as end marker.
@@ -1231,7 +1241,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1231 { 1241 {
1232 // Grain Dir is at end of file 1242 // Grain Dir is at end of file
1233 UInt64 endPos; 1243 UInt64 endPos;
1234 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); 1244 RINOK(InStream_GetSize_SeekToEnd(stream, endPos))
1235 if ((endPos & 511) != 0) 1245 if ((endPos & 511) != 0)
1236 return S_FALSE; 1246 return S_FALSE;
1237 1247
@@ -1239,8 +1249,8 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1239 Byte buf2[kEndSize]; 1249 Byte buf2[kEndSize];
1240 if (endPos < kEndSize) 1250 if (endPos < kEndSize)
1241 return S_FALSE; 1251 return S_FALSE;
1242 RINOK(stream->Seek(endPos - kEndSize, STREAM_SEEK_SET, NULL)); 1252 RINOK(InStream_SeekSet(stream, endPos - kEndSize))
1243 RINOK(ReadStream_FALSE(stream, buf2, kEndSize)); 1253 RINOK(ReadStream_FALSE(stream, buf2, kEndSize))
1244 1254
1245 CHeader h2; 1255 CHeader h2;
1246 if (!h2.Parse(buf2 + 512)) 1256 if (!h2.Parse(buf2 + 512))
@@ -1260,7 +1270,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1260 PhySize = endPos; 1270 PhySize = endPos;
1261 } 1271 }
1262 1272
1263 int grainSize_Log = GetLog(h.grainSize); 1273 const int grainSize_Log = GetLog(h.grainSize);
1264 if (grainSize_Log < 3 || grainSize_Log > 30 - 9) // grain size must be >= 4 KB 1274 if (grainSize_Log < 3 || grainSize_Log > 30 - 9) // grain size must be >= 4 KB
1265 return S_FALSE; 1275 return S_FALSE;
1266 if (h.capacity >= ((UInt64)1 << (63 - 9))) 1276 if (h.capacity >= ((UInt64)1 << (63 - 9)))
@@ -1269,7 +1279,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1269 return S_FALSE; 1279 return S_FALSE;
1270 1280
1271 IsArc = true; 1281 IsArc = true;
1272 ClusterBits = (9 + grainSize_Log); 1282 ClusterBits = (9 + (unsigned)grainSize_Log);
1273 VirtSize = h.capacity << 9; 1283 VirtSize = h.capacity << 9;
1274 NeedDeflate = (h.algo >= 1); 1284 NeedDeflate = (h.algo >= 1);
1275 1285
@@ -1281,7 +1291,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1281 } 1291 }
1282 1292
1283 { 1293 {
1284 UInt64 overHeadBytes = h.overHead << 9; 1294 const UInt64 overHeadBytes = h.overHead << 9;
1285 if (PhySize < overHeadBytes) 1295 if (PhySize < overHeadBytes)
1286 PhySize = overHeadBytes; 1296 PhySize = overHeadBytes;
1287 } 1297 }
@@ -1290,8 +1300,8 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1290 if (h.Is_ZeroGrain()) 1300 if (h.Is_ZeroGrain())
1291 ZeroSector = 1; 1301 ZeroSector = 1;
1292 1302
1293 const UInt64 numSectorsPerGde = (UInt64)1 << (grainSize_Log + k_NumMidBits); 1303 const UInt64 numSectorsPerGde = (UInt64)1 << ((unsigned)grainSize_Log + k_NumMidBits);
1294 const UInt64 numGdeEntries = (h.capacity + numSectorsPerGde - 1) >> (grainSize_Log + k_NumMidBits); 1304 const UInt64 numGdeEntries = (h.capacity + numSectorsPerGde - 1) >> ((unsigned)grainSize_Log + k_NumMidBits);
1295 CByteBuffer table; 1305 CByteBuffer table;
1296 1306
1297 if (numGdeEntries != 0) 1307 if (numGdeEntries != 0)
@@ -1320,7 +1330,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1320 } 1330 }
1321 } 1331 }
1322 1332
1323 RINOK(ReadForHeader(stream, h.gdOffset, table, numSectors)); 1333 RINOK(ReadForHeader(stream, h.gdOffset, table, numSectors))
1324 } 1334 }
1325 1335
1326 const size_t clusterSize = (size_t)1 << ClusterBits; 1336 const size_t clusterSize = (size_t)1 << ClusterBits;
@@ -1332,12 +1342,12 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1332 complexity += (UInt64)numGdeEntries << (k_NumMidBits + 2); 1342 complexity += (UInt64)numGdeEntries << (k_NumMidBits + 2);
1333 { 1343 {
1334 const UInt64 numVols2 = numVols; 1344 const UInt64 numVols2 = numVols;
1335 RINOK(openCallback->SetTotal((numVols == 1) ? NULL : &numVols2, &complexity)); 1345 RINOK(openCallback->SetTotal((numVols == 1) ? NULL : &numVols2, &complexity))
1336 } 1346 }
1337 if (numVols != 1) 1347 if (numVols != 1)
1338 { 1348 {
1339 const UInt64 volIndex2 = volIndex; 1349 const UInt64 volIndex2 = volIndex;
1340 RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &complexityStart)); 1350 RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &complexityStart))
1341 } 1351 }
1342 } 1352 }
1343 1353
@@ -1360,7 +1370,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1360 { 1370 {
1361 const UInt64 comp = complexityStart + ((UInt64)i << (k_NumMidBits + 2)); 1371 const UInt64 comp = complexityStart + ((UInt64)i << (k_NumMidBits + 2));
1362 const UInt64 volIndex2 = volIndex; 1372 const UInt64 volIndex2 = volIndex;
1363 RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &comp)); 1373 RINOK(openCallback->SetCompleted(numVols == 1 ? NULL : &volIndex2, &comp))
1364 numProcessed_Prev = i; 1374 numProcessed_Prev = i;
1365 } 1375 }
1366 1376
@@ -1380,7 +1390,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1380 } 1390 }
1381 1391
1382 buf.Alloc(k_NumMidItems * 4); 1392 buf.Alloc(k_NumMidItems * 4);
1383 RINOK(ReadForHeader(stream, v, buf, k_NumSectors)); 1393 RINOK(ReadForHeader(stream, v, buf, k_NumSectors))
1384 } 1394 }
1385 1395
1386 for (size_t k = 0; k < k_NumMidItems; k++) 1396 for (size_t k = 0; k < k_NumMidItems; k++)
@@ -1427,7 +1437,7 @@ HRESULT CExtent::Open3(IInStream *stream, IArchiveOpenCallback *openCallback,
1427} 1437}
1428 1438
1429 1439
1430STDMETHODIMP CHandler::Close() 1440Z7_COM7F_IMF(CHandler::Close())
1431{ 1441{
1432 _phySize = 0; 1442 _phySize = 0;
1433 1443
@@ -1458,10 +1468,10 @@ STDMETHODIMP CHandler::Close()
1458} 1468}
1459 1469
1460 1470
1461STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream) 1471Z7_COM7F_IMF(CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream))
1462{ 1472{
1463 COM_TRY_BEGIN 1473 COM_TRY_BEGIN
1464 *stream = 0; 1474 *stream = NULL;
1465 1475
1466 if (_unsupported) 1476 if (_unsupported)
1467 return S_FALSE; 1477 return S_FALSE;
@@ -1496,7 +1506,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **strea
1496 1506
1497 FOR_VECTOR (i, _extents) 1507 FOR_VECTOR (i, _extents)
1498 { 1508 {
1499 RINOK(_extents[i].InitAndSeek()); 1509 RINOK(_extents[i].InitAndSeek())
1500 } 1510 }
1501 1511
1502 CMyComPtr<ISequentialInStream> streamTemp = this; 1512 CMyComPtr<ISequentialInStream> streamTemp = this;
diff --git a/CPP/7zip/Archive/Wim/StdAfx.h b/CPP/7zip/Archive/Wim/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Wim/StdAfx.h
+++ b/CPP/7zip/Archive/Wim/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/Wim/WimHandler.cpp b/CPP/7zip/Archive/Wim/WimHandler.cpp
index 3b39455..7f96dcc 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)
95} 95}
96 96
97 97
98STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 98Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
99{ 99{
100 COM_TRY_BEGIN 100 COM_TRY_BEGIN
101 NCOM::CPropVariant prop; 101 NCOM::CPropVariant prop;
@@ -124,7 +124,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
124 const CImageInfo &image2 = xml.Images[i]; 124 const CImageInfo &image2 = xml.Images[i];
125 if (image2.CTimeDefined) 125 if (image2.CTimeDefined)
126 if (index < 0 || ::CompareFileTime(&image2.CTime, &xml.Images[index].CTime) < 0) 126 if (index < 0 || ::CompareFileTime(&image2.CTime, &xml.Images[index].CTime) < 0)
127 index = i; 127 index = (int)i;
128 } 128 }
129 if (index >= 0) 129 if (index >= 0)
130 prop = xml.Images[index].CTime; 130 prop = xml.Images[index].CTime;
@@ -141,7 +141,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
141 const CImageInfo &image2 = xml.Images[i]; 141 const CImageInfo &image2 = xml.Images[i];
142 if (image2.MTimeDefined) 142 if (image2.MTimeDefined)
143 if (index < 0 || ::CompareFileTime(&image2.MTime, &xml.Images[index].MTime) > 0) 143 if (index < 0 || ::CompareFileTime(&image2.MTime, &xml.Images[index].MTime) > 0)
144 index = i; 144 index = (int)i;
145 } 145 }
146 if (index >= 0) 146 if (index >= 0)
147 prop = xml.Images[index].MTime; 147 prop = xml.Images[index].MTime;
@@ -170,11 +170,11 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
170 170
171 AString res; 171 AString res;
172 res.Add_UInt32(ver1); 172 res.Add_UInt32(ver1);
173 res += '.'; 173 res.Add_Dot();
174 res.Add_UInt32(ver2); 174 res.Add_UInt32(ver2);
175 if (ver3 != 0) 175 if (ver3 != 0)
176 { 176 {
177 res += '.'; 177 res.Add_Dot();
178 res.Add_UInt32(ver3); 178 res.Add_UInt32(ver3);
179 } 179 }
180 prop = res; 180 prop = res;
@@ -245,7 +245,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
245 if (h.PartNumber != 1) 245 if (h.PartNumber != 1)
246 { 246 {
247 s.Add_UInt32(h.PartNumber); 247 s.Add_UInt32(h.PartNumber);
248 s += '.'; 248 s.Add_Dot();
249 } 249 }
250 s += "swm"; 250 s += "swm";
251 prop = s; 251 prop = s;
@@ -267,7 +267,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
267 { 267 {
268 const CHeader &header = _volumes[_xmls[i].VolIndex].Header; 268 const CHeader &header = _volumes[_xmls[i].VolIndex].Header;
269 unsigned method = header.GetMethod(); 269 unsigned method = header.GetMethod();
270 if (method < ARRAY_SIZE(k_Methods)) 270 if (method < Z7_ARRAY_SIZE(k_Methods))
271 methodMask |= ((UInt32)1 << method); 271 methodMask |= ((UInt32)1 << method);
272 else 272 else
273 methodUnknown = method; 273 methodUnknown = method;
@@ -280,7 +280,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
280 280
281 unsigned numMethods = 0; 281 unsigned numMethods = 0;
282 282
283 for (unsigned i = 0; i < ARRAY_SIZE(k_Methods); i++) 283 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Methods); i++)
284 { 284 {
285 if (methodMask & ((UInt32)1 << i)) 285 if (methodMask & ((UInt32)1 << i))
286 { 286 {
@@ -365,8 +365,8 @@ static void MethodToProp(int method, int chunksSizeBits, NCOM::CPropVariant &pro
365 { 365 {
366 char temp[32]; 366 char temp[32];
367 367
368 if ((unsigned)method < ARRAY_SIZE(k_Methods)) 368 if ((unsigned)method < Z7_ARRAY_SIZE(k_Methods))
369 strcpy(temp, k_Methods[(unsigned)method]); 369 MyStringCopy(temp, k_Methods[(unsigned)method]);
370 else 370 else
371 ConvertUInt32ToString((UInt32)(unsigned)method, temp); 371 ConvertUInt32ToString((UInt32)(unsigned)method, temp);
372 372
@@ -382,7 +382,7 @@ static void MethodToProp(int method, int chunksSizeBits, NCOM::CPropVariant &pro
382} 382}
383 383
384 384
385STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 385Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
386{ 386{
387 COM_TRY_BEGIN 387 COM_TRY_BEGIN
388 NCOM::CPropVariant prop; 388 NCOM::CPropVariant prop;
@@ -423,7 +423,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
423 else 423 else
424 */ 424 */
425 AString s (FILES_DIR_NAME STRING_PATH_SEPARATOR); 425 AString s (FILES_DIR_NAME STRING_PATH_SEPARATOR);
426 s.Add_UInt32(item.StreamIndex); 426 s.Add_UInt32((UInt32)(Int32)item.StreamIndex);
427 prop = s; 427 prop = s;
428 } 428 }
429 break; 429 break;
@@ -434,7 +434,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
434 else 434 else
435 { 435 {
436 char sz[16]; 436 char sz[16];
437 ConvertUInt32ToString(item.StreamIndex, sz); 437 ConvertUInt32ToString((UInt32)(Int32)item.StreamIndex, sz);
438 /* 438 /*
439 AString s = sz; 439 AString s = sz;
440 while (s.Len() < _nameLenForStreams) 440 while (s.Len() < _nameLenForStreams)
@@ -558,7 +558,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
558 if (r.SolidIndex >= 0) 558 if (r.SolidIndex >= 0)
559 { 559 {
560 CSolid &ss = _db.Solids[r.SolidIndex]; 560 CSolid &ss = _db.Solids[r.SolidIndex];
561 MethodToProp(ss.Method, ss.ChunkSizeBits, prop); 561 MethodToProp(ss.Method, (int)ss.ChunkSizeBits, prop);
562 } 562 }
563 } 563 }
564 else 564 else
@@ -567,8 +567,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
567 int chunkSizeBits = -1; 567 int chunkSizeBits = -1;
568 if (r.IsCompressed()) 568 if (r.IsCompressed())
569 { 569 {
570 method = vol->Header.GetMethod(); 570 method = (int)vol->Header.GetMethod();
571 chunkSizeBits = vol->Header.ChunkSizeBits; 571 chunkSizeBits = (int)vol->Header.ChunkSizeBits;
572 } 572 }
573 MethodToProp(method, chunkSizeBits, prop); 573 MethodToProp(method, chunkSizeBits, prop);
574 } 574 }
@@ -620,7 +620,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
620 COM_TRY_END 620 COM_TRY_END
621} 621}
622 622
623STDMETHODIMP CHandler::GetRootProp(PROPID propID, PROPVARIANT *value) 623Z7_COM7F_IMF(CHandler::GetRootProp(PROPID propID, PROPVARIANT *value))
624{ 624{
625 // COM_TRY_BEGIN 625 // COM_TRY_BEGIN
626 NCOM::CPropVariant prop; 626 NCOM::CPropVariant prop;
@@ -670,9 +670,9 @@ HRESULT CHandler::GetSecurity(UInt32 realIndex, const void **data, UInt32 *dataS
670 return S_OK; 670 return S_OK;
671} 671}
672 672
673STDMETHODIMP CHandler::GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 673Z7_COM7F_IMF(CHandler::GetRootRawProp(PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
674{ 674{
675 *data = 0; 675 *data = NULL;
676 *dataSize = 0; 676 *dataSize = 0;
677 *propType = 0; 677 *propType = 0;
678 if (propID == kpidNtSecure && _db.Images.Size() != 0 && _db.NumExcludededItems != 0) 678 if (propID == kpidNtSecure && _db.Images.Size() != 0 && _db.NumExcludededItems != 0)
@@ -694,20 +694,20 @@ static const Byte kRawProps[] =
694}; 694};
695 695
696 696
697STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 697Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
698{ 698{
699 *numProps = ARRAY_SIZE(kRawProps); 699 *numProps = Z7_ARRAY_SIZE(kRawProps);
700 return S_OK; 700 return S_OK;
701} 701}
702 702
703STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 703Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
704{ 704{
705 *propID = kRawProps[index]; 705 *propID = kRawProps[index];
706 *name = 0; 706 *name = NULL;
707 return S_OK; 707 return S_OK;
708} 708}
709 709
710STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 710Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType))
711{ 711{
712 *parentType = NParentType::kDir; 712 *parentType = NParentType::kDir;
713 *parent = (UInt32)(Int32)-1; 713 *parent = (UInt32)(Int32)-1;
@@ -722,13 +722,13 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
722 if (item.Parent >= 0) 722 if (item.Parent >= 0)
723 { 723 {
724 if (_db.ExludedItem != item.Parent) 724 if (_db.ExludedItem != item.Parent)
725 *parent = _db.Items[item.Parent].IndexInSorted; 725 *parent = (unsigned)_db.Items[item.Parent].IndexInSorted;
726 } 726 }
727 else 727 else
728 { 728 {
729 CImage &image = _db.Images[item.ImageIndex]; 729 CImage &image = _db.Images[item.ImageIndex];
730 if (image.VirtualRootIndex >= 0) 730 if (image.VirtualRootIndex >= 0)
731 *parent = _db.SortedItems.Size() + _numXmlItems + image.VirtualRootIndex; 731 *parent = _db.SortedItems.Size() + _numXmlItems + (unsigned)image.VirtualRootIndex;
732 } 732 }
733 } 733 }
734 else 734 else
@@ -736,7 +736,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
736 return S_OK; 736 return S_OK;
737} 737}
738 738
739STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 739Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
740{ 740{
741 *data = NULL; 741 *data = NULL;
742 *dataSize = 0; 742 *dataSize = 0;
@@ -842,8 +842,8 @@ public:
842 { 842 {
843 int dotPos = name.ReverseFind_Dot(); 843 int dotPos = name.ReverseFind_Dot();
844 if (dotPos < 0) 844 if (dotPos < 0)
845 dotPos = name.Len(); 845 dotPos = (int)name.Len();
846 _before.SetFrom(name.Ptr(), dotPos); 846 _before.SetFrom(name.Ptr(), (unsigned)dotPos);
847 _after = name.Ptr(dotPos); 847 _after = name.Ptr(dotPos);
848 } 848 }
849 849
@@ -856,7 +856,7 @@ public:
856 } 856 }
857}; 857};
858 858
859STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) 859Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback))
860{ 860{
861 COM_TRY_BEGIN 861 COM_TRY_BEGIN
862 862
@@ -963,7 +963,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
963 numVolumes = header.NumParts; 963 numVolumes = header.NumParts;
964 { 964 {
965 NCOM::CPropVariant prop; 965 NCOM::CPropVariant prop;
966 RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); 966 RINOK(openVolumeCallback->GetProperty(kpidName, &prop))
967 if (prop.vt != VT_BSTR) 967 if (prop.vt != VT_BSTR)
968 break; 968 break;
969 seqName.InitName(prop.bstrVal); 969 seqName.InitName(prop.bstrVal);
@@ -971,7 +971,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
971 } 971 }
972 } 972 }
973 973
974 RINOK(_db.FillAndCheck(_volumes)); 974 RINOK(_db.FillAndCheck(_volumes))
975 int defaultImageIndex = (int)_defaultImageNumber - 1; 975 int defaultImageIndex = (int)_defaultImageNumber - 1;
976 976
977 bool showImageNumber = (_db.Images.Size() != 1 && defaultImageIndex < 0); 977 bool showImageNumber = (_db.Images.Size() != 1 && defaultImageIndex < 0);
@@ -983,8 +983,8 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
983 983
984 _showImageNumber = showImageNumber; 984 _showImageNumber = showImageNumber;
985 985
986 RINOK(_db.GenerateSortedItems(defaultImageIndex, showImageNumber)); 986 RINOK(_db.GenerateSortedItems(defaultImageIndex, showImageNumber))
987 RINOK(_db.ExtractReparseStreams(_volumes, callback)); 987 RINOK(_db.ExtractReparseStreams(_volumes, callback))
988 988
989 /* 989 /*
990 wchar_t sz[16]; 990 wchar_t sz[16];
@@ -1001,7 +1001,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
1001} 1001}
1002 1002
1003 1003
1004STDMETHODIMP CHandler::Close() 1004Z7_COM7F_IMF(CHandler::Close())
1005{ 1005{
1006 _firstVolumeIndex = -1; 1006 _firstVolumeIndex = -1;
1007 _phySize = 0; 1007 _phySize = 0;
@@ -1019,11 +1019,11 @@ STDMETHODIMP CHandler::Close()
1019} 1019}
1020 1020
1021 1021
1022STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1022Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1023 Int32 testMode, IArchiveExtractCallback *extractCallback) 1023 Int32 testMode, IArchiveExtractCallback *extractCallback))
1024{ 1024{
1025 COM_TRY_BEGIN 1025 COM_TRY_BEGIN
1026 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 1026 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1027 1027
1028 if (allFilesMode) 1028 if (allFilesMode)
1029 numItems = _db.SortedItems.Size() + _numXmlItems + _db.VirtualRoots.Size() + _numIgnoreItems; 1029 numItems = _db.SortedItems.Size() + _numXmlItems + _db.VirtualRoots.Size() + _numIgnoreItems;
@@ -1048,12 +1048,12 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1048 else 1048 else
1049 { 1049 {
1050 index -= _db.SortedItems.Size(); 1050 index -= _db.SortedItems.Size();
1051 if (index < (UInt32)_numXmlItems) 1051 if (index < _numXmlItems)
1052 totalSize += _xmls[index].Data.Size(); 1052 totalSize += _xmls[index].Data.Size();
1053 } 1053 }
1054 } 1054 }
1055 1055
1056 RINOK(extractCallback->SetTotal(totalSize)); 1056 RINOK(extractCallback->SetTotal(totalSize))
1057 1057
1058 UInt64 currentTotalUnPacked = 0; 1058 UInt64 currentTotalUnPacked = 0;
1059 UInt64 currentItemUnPacked; 1059 UInt64 currentItemUnPacked;
@@ -1074,36 +1074,36 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1074 lps->InSize = unpacker.TotalPacked; 1074 lps->InSize = unpacker.TotalPacked;
1075 lps->OutSize = currentTotalUnPacked; 1075 lps->OutSize = currentTotalUnPacked;
1076 1076
1077 RINOK(lps->SetCur()); 1077 RINOK(lps->SetCur())
1078 1078
1079 if (i >= numItems) 1079 if (i >= numItems)
1080 break; 1080 break;
1081 1081
1082 UInt32 index = allFilesMode ? i : indices[i]; 1082 UInt32 index = allFilesMode ? i : indices[i];
1083 Int32 askMode = testMode ? 1083 const Int32 askMode = testMode ?
1084 NExtract::NAskMode::kTest : 1084 NExtract::NAskMode::kTest :
1085 NExtract::NAskMode::kExtract; 1085 NExtract::NAskMode::kExtract;
1086 1086
1087 CMyComPtr<ISequentialOutStream> realOutStream; 1087 CMyComPtr<ISequentialOutStream> realOutStream;
1088 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1088 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1089 1089
1090 if (index >= _db.SortedItems.Size()) 1090 if (index >= _db.SortedItems.Size())
1091 { 1091 {
1092 if (!testMode && !realOutStream) 1092 if (!testMode && !realOutStream)
1093 continue; 1093 continue;
1094 RINOK(extractCallback->PrepareOperation(askMode)); 1094 RINOK(extractCallback->PrepareOperation(askMode))
1095 index -= _db.SortedItems.Size(); 1095 index -= _db.SortedItems.Size();
1096 if (index < (UInt32)_numXmlItems) 1096 if (index < _numXmlItems)
1097 { 1097 {
1098 const CByteBuffer &data = _xmls[index].Data; 1098 const CByteBuffer &data = _xmls[index].Data;
1099 currentItemUnPacked = data.Size(); 1099 currentItemUnPacked = data.Size();
1100 if (realOutStream) 1100 if (realOutStream)
1101 { 1101 {
1102 RINOK(WriteStream(realOutStream, (const Byte *)data, data.Size())); 1102 RINOK(WriteStream(realOutStream, (const Byte *)data, data.Size()))
1103 realOutStream.Release(); 1103 realOutStream.Release();
1104 } 1104 }
1105 } 1105 }
1106 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1106 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
1107 continue; 1107 continue;
1108 } 1108 }
1109 1109
@@ -1114,11 +1114,11 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1114 if (!item.IsDir) 1114 if (!item.IsDir)
1115 if (!testMode && !realOutStream) 1115 if (!testMode && !realOutStream)
1116 continue; 1116 continue;
1117 RINOK(extractCallback->PrepareOperation(askMode)); 1117 RINOK(extractCallback->PrepareOperation(askMode))
1118 realOutStream.Release(); 1118 realOutStream.Release();
1119 RINOK(extractCallback->SetOperationResult(!item.IsDir && _db.ItemHasStream(item) ? 1119 RINOK(extractCallback->SetOperationResult(!item.IsDir && _db.ItemHasStream(item) ?
1120 NExtract::NOperationResult::kDataError : 1120 NExtract::NOperationResult::kDataError :
1121 NExtract::NOperationResult::kOK)); 1121 NExtract::NOperationResult::kOK))
1122 continue; 1122 continue;
1123 } 1123 }
1124 1124
@@ -1128,7 +1128,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1128 1128
1129 if (!testMode && !realOutStream) 1129 if (!testMode && !realOutStream)
1130 continue; 1130 continue;
1131 RINOK(extractCallback->PrepareOperation(askMode)); 1131 RINOK(extractCallback->PrepareOperation(askMode))
1132 Int32 opRes = NExtract::NOperationResult::kOK; 1132 Int32 opRes = NExtract::NOperationResult::kOK;
1133 1133
1134 if (streamIndex != prevSuccessStreamIndex || realOutStream) 1134 if (streamIndex != prevSuccessStreamIndex || realOutStream)
@@ -1156,7 +1156,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1156 } 1156 }
1157 1157
1158 realOutStream.Release(); 1158 realOutStream.Release();
1159 RINOK(extractCallback->SetOperationResult(opRes)); 1159 RINOK(extractCallback->SetOperationResult(opRes))
1160 } 1160 }
1161 1161
1162 return S_OK; 1162 return S_OK;
@@ -1164,7 +1164,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1164} 1164}
1165 1165
1166 1166
1167STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1167Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1168{ 1168{
1169 *numItems = _db.SortedItems.Size() + 1169 *numItems = _db.SortedItems.Size() +
1170 _numXmlItems + 1170 _numXmlItems +
@@ -1180,7 +1180,7 @@ CHandler::CHandler()
1180 _xmlError = false; 1180 _xmlError = false;
1181} 1181}
1182 1182
1183STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 1183Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
1184{ 1184{
1185 InitDefaults(); 1185 InitDefaults();
1186 1186
@@ -1197,18 +1197,18 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1197 { 1197 {
1198 // some clients write 'x' property. So we support it 1198 // some clients write 'x' property. So we support it
1199 UInt32 level = 0; 1199 UInt32 level = 0;
1200 RINOK(ParsePropToUInt32(name.Ptr(1), prop, level)); 1200 RINOK(ParsePropToUInt32(name.Ptr(1), prop, level))
1201 } 1201 }
1202 else if (name.IsEqualTo("is")) 1202 else if (name.IsEqualTo("is"))
1203 { 1203 {
1204 RINOK(PROPVARIANT_to_bool(prop, _set_showImageNumber)); 1204 RINOK(PROPVARIANT_to_bool(prop, _set_showImageNumber))
1205 _set_use_ShowImageNumber = true; 1205 _set_use_ShowImageNumber = true;
1206 } 1206 }
1207 else if (name.IsEqualTo("im")) 1207 else if (name.IsEqualTo("im"))
1208 { 1208 {
1209 UInt32 image = 9; 1209 UInt32 image = 9;
1210 RINOK(ParsePropToUInt32(L"", prop, image)); 1210 RINOK(ParsePropToUInt32(L"", prop, image))
1211 _defaultImageNumber = image; 1211 _defaultImageNumber = (int)image;
1212 } 1212 }
1213 else if (name.IsPrefixedBy_Ascii_NoCase("mt")) 1213 else if (name.IsPrefixedBy_Ascii_NoCase("mt"))
1214 { 1214 {
@@ -1217,12 +1217,17 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1217 { 1217 {
1218 } 1218 }
1219 else 1219 else
1220 return E_INVALIDARG; 1220 {
1221 bool processed = false;
1222 RINOK(_timeOptions.Parse(name, prop, processed))
1223 if (!processed)
1224 return E_INVALIDARG;
1225 }
1221 } 1226 }
1222 return S_OK; 1227 return S_OK;
1223} 1228}
1224 1229
1225STDMETHODIMP CHandler::KeepModeForNextOpen() 1230Z7_COM7F_IMF(CHandler::KeepModeForNextOpen())
1226{ 1231{
1227 _keepMode_ShowImageNumber = _showImageNumber; 1232 _keepMode_ShowImageNumber = _showImageNumber;
1228 return S_OK; 1233 return S_OK;
diff --git a/CPP/7zip/Archive/Wim/WimHandler.h b/CPP/7zip/Archive/Wim/WimHandler.h
index 3ba88d2..60bb156 100644
--- a/CPP/7zip/Archive/Wim/WimHandler.h
+++ b/CPP/7zip/Archive/Wim/WimHandler.h
@@ -1,10 +1,12 @@
1// WimHandler.h 1// WimHandler.h
2 2
3#ifndef __ARCHIVE_WIM_HANDLER_H 3#ifndef ZIP7_INC_ARCHIVE_WIM_HANDLER_H
4#define __ARCHIVE_WIM_HANDLER_H 4#define ZIP7_INC_ARCHIVE_WIM_HANDLER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../Common/HandlerOut.h"
9
8#include "WimIn.h" 10#include "WimIn.h"
9 11
10namespace NArchive { 12namespace NArchive {
@@ -12,15 +14,13 @@ namespace NWim {
12 14
13static const Int32 kNumImagesMaxUpdate = (1 << 10); 15static const Int32 kNumImagesMaxUpdate = (1 << 10);
14 16
15class CHandler: 17Z7_CLASS_IMP_CHandler_IInArchive_5(
16 public IInArchive, 18 IArchiveGetRawProps
17 public IArchiveGetRawProps, 19 , IArchiveGetRootProps
18 public IArchiveGetRootProps, 20 , IArchiveKeepModeForNextOpen
19 public IArchiveKeepModeForNextOpen, 21 , ISetProperties
20 public ISetProperties, 22 , IOutArchive
21 public IOutArchive, 23)
22 public CMyUnknownImp
23{
24 CDatabase _db; 24 CDatabase _db;
25 UInt32 _version; 25 UInt32 _version;
26 bool _isOldVersion; 26 bool _isOldVersion;
@@ -49,11 +49,14 @@ class CHandler:
49 UInt64 _phySize; 49 UInt64 _phySize;
50 int _firstVolumeIndex; 50 int _firstVolumeIndex;
51 51
52 CHandlerTimeOptions _timeOptions;
53
52 void InitDefaults() 54 void InitDefaults()
53 { 55 {
54 _set_use_ShowImageNumber = false; 56 _set_use_ShowImageNumber = false;
55 _set_showImageNumber = false; 57 _set_showImageNumber = false;
56 _defaultImageNumber = -1; 58 _defaultImageNumber = -1;
59 _timeOptions.Init();
57 } 60 }
58 61
59 bool IsUpdateSupported() const 62 bool IsUpdateSupported() const
@@ -83,19 +86,6 @@ class CHandler:
83 HRESULT GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, FILETIME &ft); 86 HRESULT GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, FILETIME &ft);
84public: 87public:
85 CHandler(); 88 CHandler();
86 MY_UNKNOWN_IMP6(
87 IInArchive,
88 IArchiveGetRawProps,
89 IArchiveGetRootProps,
90 IArchiveKeepModeForNextOpen,
91 ISetProperties,
92 IOutArchive)
93 INTERFACE_IInArchive(;)
94 INTERFACE_IArchiveGetRawProps(;)
95 INTERFACE_IArchiveGetRootProps(;)
96 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
97 STDMETHOD(KeepModeForNextOpen)();
98 INTERFACE_IOutArchive(;)
99}; 89};
100 90
101}} 91}}
diff --git a/CPP/7zip/Archive/Wim/WimHandlerOut.cpp b/CPP/7zip/Archive/Wim/WimHandlerOut.cpp
index 5e8365a..5d9dea2 100644
--- a/CPP/7zip/Archive/Wim/WimHandlerOut.cpp
+++ b/CPP/7zip/Archive/Wim/WimHandlerOut.cpp
@@ -27,8 +27,25 @@ using namespace NWindows;
27namespace NArchive { 27namespace NArchive {
28namespace NWim { 28namespace NWim {
29 29
30static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const Byte *h, int streamIndexForInsert) 30static const unsigned k_NumSubVectors_Bits = 12; // must be <= 16
31
32struct CSortedIndex
33{
34 CObjectVector<CUIntVector> Vectors;
35
36 CSortedIndex()
37 {
38 const unsigned k_NumSubVectors = 1 << k_NumSubVectors_Bits;
39 Vectors.ClearAndReserve(k_NumSubVectors);
40 for (unsigned i = 0; i < k_NumSubVectors; i++)
41 Vectors.AddNew();
42 }
43};
44
45static int AddUniqHash(const CStreamInfo *streams, CSortedIndex &sorted2, const Byte *h, int streamIndexForInsert)
31{ 46{
47 const unsigned hash = (((unsigned)h[0] << 8) | (unsigned)h[1]) >> (16 - k_NumSubVectors_Bits);
48 CUIntVector &sorted = sorted2.Vectors[hash];
32 unsigned left = 0, right = sorted.Size(); 49 unsigned left = 0, right = sorted.Size();
33 while (left != right) 50 while (left != right)
34 { 51 {
@@ -42,7 +59,7 @@ static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const By
42 break; 59 break;
43 60
44 if (i == kHashSize) 61 if (i == kHashSize)
45 return index; 62 return (int)index;
46 63
47 if (h[i] < hash2[i]) 64 if (h[i] < hash2[i])
48 right = mid; 65 right = mid;
@@ -50,8 +67,8 @@ static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const By
50 left = mid + 1; 67 left = mid + 1;
51 } 68 }
52 69
53 if (streamIndexForInsert >= 0) 70 if (streamIndexForInsert != -1)
54 sorted.Insert(left, streamIndexForInsert); 71 sorted.Insert(left, (unsigned)streamIndexForInsert);
55 72
56 return -1; 73 return -1;
57} 74}
@@ -78,13 +95,13 @@ struct CMetaItem
78 FILETIME CTime; 95 FILETIME CTime;
79 FILETIME ATime; 96 FILETIME ATime;
80 FILETIME MTime; 97 FILETIME MTime;
81 UInt32 Attrib;
82 UInt64 FileID; 98 UInt64 FileID;
83 UInt64 VolID; 99 UInt64 VolID;
84 100
85 UString Name; 101 UString Name;
86 UString ShortName; 102 UString ShortName;
87 103
104 UInt32 Attrib;
88 int SecurityId; // -1: means no secutity ID 105 int SecurityId; // -1: means no secutity ID
89 bool IsDir; 106 bool IsDir;
90 bool Skip; 107 bool Skip;
@@ -97,12 +114,19 @@ struct CMetaItem
97 CMetaItem(): 114 CMetaItem():
98 UpdateIndex(-1) 115 UpdateIndex(-1)
99 , HashIndex(-1) 116 , HashIndex(-1)
117 , Size(0)
100 , FileID(0) 118 , FileID(0)
101 , VolID(0) 119 , VolID(0)
120 , Attrib(0)
102 , SecurityId(-1) 121 , SecurityId(-1)
122 , IsDir(false)
103 , Skip(false) 123 , Skip(false)
104 , NumSkipAltStreams(0) 124 , NumSkipAltStreams(0)
105 {} 125 {
126 FILETIME_Clear(CTime);
127 FILETIME_Clear(ATime);
128 FILETIME_Clear(MTime);
129 }
106}; 130};
107 131
108 132
@@ -128,7 +152,7 @@ static int AddToHardLinkList(const CObjectVector<CMetaItem> &metaItems, unsigned
128 const unsigned index = indexes[mid]; 152 const unsigned index = indexes[mid];
129 const int comp = Compare_HardLink_MetaItems(mi, metaItems[index]); 153 const int comp = Compare_HardLink_MetaItems(mi, metaItems[index]);
130 if (comp == 0) 154 if (comp == 0)
131 return index; 155 return (int)index;
132 if (comp < 0) 156 if (comp < 0)
133 right = mid; 157 right = mid;
134 else 158 else
@@ -220,7 +244,7 @@ bool CDir::FindDir(const CObjectVector<CMetaItem> &items, const UString &name, u
220} 244}
221 245
222 246
223STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 247Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type))
224{ 248{
225 *type = NFileTimeType::kWindows; 249 *type = NFileTimeType::kWindows;
226 return S_OK; 250 return S_OK;
@@ -229,8 +253,8 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type)
229 253
230HRESULT CHandler::GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value) 254HRESULT CHandler::GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value)
231{ 255{
232 if (arcIndex >= 0) 256 if (arcIndex != -1)
233 return GetProperty(arcIndex, propID, value); 257 return GetProperty((UInt32)arcIndex, propID, value);
234 return callback->GetProperty(callbackIndex, propID, value); 258 return callback->GetProperty(callbackIndex, propID, value);
235} 259}
236 260
@@ -239,7 +263,7 @@ HRESULT CHandler::GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex
239{ 263{
240 ft.dwLowDateTime = ft.dwHighDateTime = 0; 264 ft.dwLowDateTime = ft.dwHighDateTime = 0;
241 NCOM::CPropVariant prop; 265 NCOM::CPropVariant prop;
242 RINOK(GetOutProperty(callback, callbackIndex, arcIndex, propID, &prop)); 266 RINOK(GetOutProperty(callback, callbackIndex, arcIndex, propID, &prop))
243 if (prop.vt == VT_FILETIME) 267 if (prop.vt == VT_FILETIME)
244 ft = prop.filetime; 268 ft = prop.filetime;
245 else if (prop.vt != VT_EMPTY) 269 else if (prop.vt != VT_EMPTY)
@@ -256,7 +280,7 @@ static HRESULT GetRootTime(
256 NCOM::CPropVariant prop; 280 NCOM::CPropVariant prop;
257 if (callback) 281 if (callback)
258 { 282 {
259 RINOK(callback->GetRootProp(propID, &prop)); 283 RINOK(callback->GetRootProp(propID, &prop))
260 if (prop.vt == VT_FILETIME) 284 if (prop.vt == VT_FILETIME)
261 { 285 {
262 ft = prop.filetime; 286 ft = prop.filetime;
@@ -267,7 +291,7 @@ static HRESULT GetRootTime(
267 } 291 }
268 if (arcRoot) 292 if (arcRoot)
269 { 293 {
270 RINOK(arcRoot->GetRootProp(propID, &prop)); 294 RINOK(arcRoot->GetRootProp(propID, &prop))
271 if (prop.vt == VT_FILETIME) 295 if (prop.vt == VT_FILETIME)
272 { 296 {
273 ft = prop.filetime; 297 ft = prop.filetime;
@@ -285,29 +309,29 @@ static HRESULT GetRootTime(
285 309
286void CResource::WriteTo(Byte *p) const 310void CResource::WriteTo(Byte *p) const
287{ 311{
288 Set64(p, PackSize); 312 Set64(p, PackSize)
289 p[7] = Flags; 313 p[7] = Flags;
290 Set64(p + 8, Offset); 314 Set64(p + 8, Offset)
291 Set64(p + 16, UnpackSize); 315 Set64(p + 16, UnpackSize)
292} 316}
293 317
294 318
295void CHeader::WriteTo(Byte *p) const 319void CHeader::WriteTo(Byte *p) const
296{ 320{
297 memcpy(p, kSignature, kSignatureSize); 321 memcpy(p, kSignature, kSignatureSize);
298 Set32(p + 8, kHeaderSizeMax); 322 Set32(p + 8, kHeaderSizeMax)
299 Set32(p + 0xC, Version); 323 Set32(p + 0xC, Version)
300 Set32(p + 0x10, Flags); 324 Set32(p + 0x10, Flags)
301 Set32(p + 0x14, ChunkSize); 325 Set32(p + 0x14, ChunkSize)
302 memcpy(p + 0x18, Guid, 16); 326 memcpy(p + 0x18, Guid, 16);
303 Set16(p + 0x28, PartNumber); 327 Set16(p + 0x28, PartNumber)
304 Set16(p + 0x2A, NumParts); 328 Set16(p + 0x2A, NumParts)
305 Set32(p + 0x2C, NumImages); 329 Set32(p + 0x2C, NumImages)
306 OffsetResource.WriteTo(p + 0x30); 330 OffsetResource.WriteTo(p + 0x30);
307 XmlResource.WriteTo(p + 0x48); 331 XmlResource.WriteTo(p + 0x48);
308 MetadataResource.WriteTo(p + 0x60); 332 MetadataResource.WriteTo(p + 0x60);
309 IntegrityResource.WriteTo(p + 0x7C); 333 IntegrityResource.WriteTo(p + 0x7C);
310 Set32(p + 0x78, BootIndex); 334 Set32(p + 0x78, BootIndex)
311 memset(p + 0x94, 0, 60); 335 memset(p + 0x94, 0, 60);
312} 336}
313 337
@@ -315,25 +339,22 @@ void CHeader::WriteTo(Byte *p) const
315void CStreamInfo::WriteTo(Byte *p) const 339void CStreamInfo::WriteTo(Byte *p) const
316{ 340{
317 Resource.WriteTo(p); 341 Resource.WriteTo(p);
318 Set16(p + 0x18, PartNumber); 342 Set16(p + 0x18, PartNumber)
319 Set32(p + 0x1A, RefCount); 343 Set32(p + 0x1A, RefCount)
320 memcpy(p + 0x1E, Hash, kHashSize); 344 memcpy(p + 0x1E, Hash, kHashSize);
321} 345}
322 346
323 347
324class CInStreamWithSha1: 348Z7_CLASS_IMP_NOQIB_1(
325 public ISequentialInStream, 349 CInStreamWithSha1
326 public CMyUnknownImp 350 , ISequentialInStream
327{ 351)
328 CMyComPtr<ISequentialInStream> _stream; 352 CMyComPtr<ISequentialInStream> _stream;
329 UInt64 _size; 353 UInt64 _size;
330 // NCrypto::NSha1::CContext _sha; 354 // NCrypto::NSha1::CContext _sha;
331 CAlignedBuffer _sha; 355 CAlignedBuffer1 _sha;
332 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; } 356 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_sha; }
333public: 357public:
334 MY_UNKNOWN_IMP1(IInStream)
335 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
336
337 CInStreamWithSha1(): _sha(sizeof(CSha1)) {} 358 CInStreamWithSha1(): _sha(sizeof(CSha1)) {}
338 void SetStream(ISequentialInStream *stream) { _stream = stream; } 359 void SetStream(ISequentialInStream *stream) { _stream = stream; }
339 void Init() 360 void Init()
@@ -346,10 +367,10 @@ public:
346 void Final(Byte *digest) { Sha1_Final(Sha(), digest); } 367 void Final(Byte *digest) { Sha1_Final(Sha(), digest); }
347}; 368};
348 369
349STDMETHODIMP CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedSize) 370Z7_COM7F_IMF(CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedSize))
350{ 371{
351 UInt32 realProcessedSize; 372 UInt32 realProcessedSize;
352 HRESULT result = _stream->Read(data, size, &realProcessedSize); 373 const HRESULT result = _stream->Read(data, size, &realProcessedSize);
353 _size += realProcessedSize; 374 _size += realProcessedSize;
354 Sha1_Update(Sha(), (const Byte *)data, realProcessedSize); 375 Sha1_Update(Sha(), (const Byte *)data, realProcessedSize);
355 if (processedSize) 376 if (processedSize)
@@ -360,8 +381,8 @@ STDMETHODIMP CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedS
360 381
361static void SetFileTimeToMem(Byte *p, const FILETIME &ft) 382static void SetFileTimeToMem(Byte *p, const FILETIME &ft)
362{ 383{
363 Set32(p, ft.dwLowDateTime); 384 Set32(p, ft.dwLowDateTime)
364 Set32(p + 4, ft.dwHighDateTime); 385 Set32(p + 4, ft.dwHighDateTime)
365} 386}
366 387
367static size_t WriteItem_Dummy(const CMetaItem &item) 388static size_t WriteItem_Dummy(const CMetaItem &item)
@@ -372,15 +393,15 @@ static size_t WriteItem_Dummy(const CMetaItem &item)
372 // we write fileNameLen + 2 + 2 to be same as original WIM. 393 // we write fileNameLen + 2 + 2 to be same as original WIM.
373 unsigned fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2); 394 unsigned fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2);
374 395
375 unsigned shortNameLen = item.ShortName.Len() * 2; 396 const unsigned shortNameLen = item.ShortName.Len() * 2;
376 unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4); 397 const unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4);
377 398
378 size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7); 399 size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~(unsigned)7);
379 if (item.GetNumAltStreams() != 0) 400 if (item.GetNumAltStreams() != 0)
380 { 401 {
381 if (!item.IsDir) 402 if (!item.IsDir)
382 { 403 {
383 UInt32 curLen = (((0x26 + 0) + 6) & ~7); 404 const UInt32 curLen = (((0x26 + 0) + 6) & ~(unsigned)7);
384 totalLen += curLen; 405 totalLen += curLen;
385 } 406 }
386 FOR_VECTOR (i, item.AltStreams) 407 FOR_VECTOR (i, item.AltStreams)
@@ -390,7 +411,7 @@ static size_t WriteItem_Dummy(const CMetaItem &item)
390 continue; 411 continue;
391 fileNameLen = ss.Name.Len() * 2; 412 fileNameLen = ss.Name.Len() * 2;
392 fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2); 413 fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2);
393 UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7); 414 const UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~(unsigned)7);
394 totalLen += curLen; 415 totalLen += curLen;
395 } 416 }
396 } 417 }
@@ -407,12 +428,12 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte
407 unsigned shortNameLen = item.ShortName.Len() * 2; 428 unsigned shortNameLen = item.ShortName.Len() * 2;
408 unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4); 429 unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4);
409 430
410 size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7); 431 size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~(unsigned)7);
411 432
412 memset(p, 0, totalLen); 433 memset(p, 0, totalLen);
413 Set64(p, totalLen); 434 Set64(p, totalLen)
414 Set64(p + 8, item.Attrib); 435 Set64(p + 8, item.Attrib)
415 Set32(p + 0xC, (Int32)item.SecurityId); 436 Set32(p + 0xC, (UInt32)(Int32)item.SecurityId)
416 SetFileTimeToMem(p + 0x28, item.CTime); 437 SetFileTimeToMem(p + 0x28, item.CTime);
417 SetFileTimeToMem(p + 0x30, item.ATime); 438 SetFileTimeToMem(p + 0x30, item.ATime);
418 SetFileTimeToMem(p + 0x38, item.MTime); 439 SetFileTimeToMem(p + 0x38, item.MTime);
@@ -425,21 +446,21 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte
425 if (item.Reparse.Size() != 0) 446 if (item.Reparse.Size() != 0)
426 { 447 {
427 UInt32 tag = GetUi32(item.Reparse); 448 UInt32 tag = GetUi32(item.Reparse);
428 Set32(p + 0x58, tag); 449 Set32(p + 0x58, tag)
429 // Set32(p + 0x5C, 0); // probably it's always ZERO 450 // Set32(p + 0x5C, 0); // probably it's always ZERO
430 } 451 }
431 else if (item.FileID != 0) 452 else if (item.FileID != 0)
432 { 453 {
433 Set64(p + 0x58, item.FileID); 454 Set64(p + 0x58, item.FileID)
434 } 455 }
435 456
436 Set16(p + 0x62, (UInt16)shortNameLen); 457 Set16(p + 0x62, (UInt16)shortNameLen)
437 Set16(p + 0x64, (UInt16)fileNameLen); 458 Set16(p + 0x64, (UInt16)fileNameLen)
438 unsigned i; 459 unsigned i;
439 for (i = 0; i * 2 < fileNameLen; i++) 460 for (i = 0; i * 2 < fileNameLen; i++)
440 Set16(p + kDirRecordSize + i * 2, (UInt16)item.Name[i]); 461 Set16(p + kDirRecordSize + i * 2, (UInt16)item.Name[i])
441 for (i = 0; i * 2 < shortNameLen; i++) 462 for (i = 0; i * 2 < shortNameLen; i++)
442 Set16(p + kDirRecordSize + fileNameLen2 + i * 2, (UInt16)item.ShortName[i]); 463 Set16(p + kDirRecordSize + fileNameLen2 + i * 2, (UInt16)item.ShortName[i])
443 464
444 if (item.GetNumAltStreams() == 0) 465 if (item.GetNumAltStreams() == 0)
445 { 466 {
@@ -448,14 +469,14 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte
448 } 469 }
449 else 470 else
450 { 471 {
451 Set16(p + 0x60, (UInt16)(item.GetNumAltStreams() + (item.IsDir ? 0 : 1))); 472 Set16(p + 0x60, (UInt16)(item.GetNumAltStreams() + (item.IsDir ? 0 : 1)))
452 p += totalLen; 473 p += totalLen;
453 474
454 if (!item.IsDir) 475 if (!item.IsDir)
455 { 476 {
456 UInt32 curLen = (((0x26 + 0) + 6) & ~7); 477 const UInt32 curLen = (((0x26 + 0) + 6) & ~(unsigned)7);
457 memset(p, 0, curLen); 478 memset(p, 0, curLen);
458 Set64(p, curLen); 479 Set64(p, curLen)
459 if (item.HashIndex >= 0) 480 if (item.HashIndex >= 0)
460 memcpy(p + 0x10, streams[item.HashIndex].Hash, kHashSize); 481 memcpy(p + 0x10, streams[item.HashIndex].Hash, kHashSize);
461 totalLen += curLen; 482 totalLen += curLen;
@@ -470,15 +491,15 @@ static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte
470 491
471 fileNameLen = ss.Name.Len() * 2; 492 fileNameLen = ss.Name.Len() * 2;
472 fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2); 493 fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2);
473 UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7); 494 UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~(unsigned)7);
474 memset(p, 0, curLen); 495 memset(p, 0, curLen);
475 496
476 Set64(p, curLen); 497 Set64(p, curLen)
477 if (ss.HashIndex >= 0) 498 if (ss.HashIndex >= 0)
478 memcpy(p + 0x10, streams[ss.HashIndex].Hash, kHashSize); 499 memcpy(p + 0x10, streams[ss.HashIndex].Hash, kHashSize);
479 Set16(p + 0x24, (UInt16)fileNameLen); 500 Set16(p + 0x24, (UInt16)fileNameLen)
480 for (i = 0; i * 2 < fileNameLen; i++) 501 for (i = 0; i * 2 < fileNameLen; i++)
481 Set16(p + 0x26 + i * 2, (UInt16)ss.Name[i]); 502 Set16(p + 0x26 + i * 2, (UInt16)ss.Name[i])
482 totalLen += curLen; 503 totalLen += curLen;
483 p += curLen; 504 p += curLen;
484 } 505 }
@@ -529,7 +550,7 @@ void CDb::WriteTree(const CDir &tree, Byte *dest, size_t &pos) const
529 for (i = 0; i < tree.Dirs.Size(); i++) 550 for (i = 0; i < tree.Dirs.Size(); i++)
530 pos += WriteItem_Dummy(MetaItems[tree.Dirs[i].MetaIndex]); 551 pos += WriteItem_Dummy(MetaItems[tree.Dirs[i].MetaIndex]);
531 552
532 Set64(dest + pos, 0); 553 Set64(dest + pos, 0)
533 554
534 pos += 8; 555 pos += 8;
535 556
@@ -544,7 +565,7 @@ void CDb::WriteTree(const CDir &tree, Byte *dest, size_t &pos) const
544 posStart += len; 565 posStart += len;
545 if (needCreateTree) 566 if (needCreateTree)
546 { 567 {
547 Set64(dest + posStart - len + 0x10, pos); // subdirOffset 568 Set64(dest + posStart - len + 0x10, pos) // subdirOffset
548 WriteTree(subDir, dest, pos); 569 WriteTree(subDir, dest, pos);
549 } 570 }
550 } 571 }
@@ -557,18 +578,18 @@ void CDb::WriteOrderList(const CDir &tree)
557 { 578 {
558 const CMetaItem &mi = MetaItems[tree.MetaIndex]; 579 const CMetaItem &mi = MetaItems[tree.MetaIndex];
559 if (mi.UpdateIndex >= 0) 580 if (mi.UpdateIndex >= 0)
560 UpdateIndexes.Add(mi.UpdateIndex); 581 UpdateIndexes.Add((unsigned)mi.UpdateIndex);
561 FOR_VECTOR (si, mi.AltStreams) 582 FOR_VECTOR (si, mi.AltStreams)
562 UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex); 583 UpdateIndexes.Add((unsigned)mi.AltStreams[si].UpdateIndex);
563 } 584 }
564 585
565 unsigned i; 586 unsigned i;
566 for (i = 0; i < tree.Files.Size(); i++) 587 for (i = 0; i < tree.Files.Size(); i++)
567 { 588 {
568 const CMetaItem &mi = MetaItems[tree.Files[i]]; 589 const CMetaItem &mi = MetaItems[tree.Files[i]];
569 UpdateIndexes.Add(mi.UpdateIndex); 590 UpdateIndexes.Add((unsigned)mi.UpdateIndex);
570 FOR_VECTOR (si, mi.AltStreams) 591 FOR_VECTOR (si, mi.AltStreams)
571 UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex); 592 UpdateIndexes.Add((unsigned)mi.AltStreams[si].UpdateIndex);
572 } 593 }
573 594
574 for (i = 0; i < tree.Dirs.Size(); i++) 595 for (i = 0; i < tree.Dirs.Size(); i++)
@@ -696,7 +717,7 @@ void CHeader::SetDefaultFields(bool useLZX)
696static void AddTrees(CObjectVector<CDir> &trees, CObjectVector<CMetaItem> &metaItems, const CMetaItem &ri, int curTreeIndex) 717static void AddTrees(CObjectVector<CDir> &trees, CObjectVector<CMetaItem> &metaItems, const CMetaItem &ri, int curTreeIndex)
697{ 718{
698 while (curTreeIndex >= (int)trees.Size()) 719 while (curTreeIndex >= (int)trees.Size())
699 trees.AddNew().Dirs.AddNew().MetaIndex = metaItems.Add(ri); 720 trees.AddNew().Dirs.AddNew().MetaIndex = (int)metaItems.Add(ri);
700} 721}
701 722
702 723
@@ -704,7 +725,7 @@ static void AddTrees(CObjectVector<CDir> &trees, CObjectVector<CMetaItem> &metaI
704 725
705 726
706 727
707STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 numItems, IArchiveUpdateCallback *callback) 728Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 numItems, IArchiveUpdateCallback *callback))
708{ 729{
709 COM_TRY_BEGIN 730 COM_TRY_BEGIN
710 731
@@ -732,7 +753,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
732 return E_NOTIMPL; 753 return E_NOTIMPL;
733 754
734 CMyComPtr<IOutStream> outStream; 755 CMyComPtr<IOutStream> outStream;
735 RINOK(outSeqStream->QueryInterface(IID_IOutStream, (void **)&outStream)); 756 RINOK(outSeqStream->QueryInterface(IID_IOutStream, (void **)&outStream))
736 if (!outStream) 757 if (!outStream)
737 return E_NOTIMPL; 758 return E_NOTIMPL;
738 if (!callback) 759 if (!callback)
@@ -744,7 +765,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
744 CMetaItem ri; // default DIR item 765 CMetaItem ri; // default DIR item
745 FILETIME ftCur; 766 FILETIME ftCur;
746 NTime::GetCurUtcFileTime(ftCur); 767 NTime::GetCurUtcFileTime(ftCur);
747 ri.MTime = ri.ATime = ri.CTime = ftCur; 768 // ri.MTime = ri.ATime = ri.CTime = ftCur;
748 ri.Attrib = FILE_ATTRIBUTE_DIRECTORY; 769 ri.Attrib = FILE_ATTRIBUTE_DIRECTORY;
749 ri.IsDir = true; 770 ri.IsDir = true;
750 771
@@ -765,7 +786,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
765 { 786 {
766 UInt32 indexInArchive; 787 UInt32 indexInArchive;
767 Int32 newData, newProps; 788 Int32 newData, newProps;
768 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); 789 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive))
769 if (newProps == 0) 790 if (newProps == 0)
770 { 791 {
771 if (indexInArchive >= _db.SortedItems.Size()) 792 if (indexInArchive >= _db.SortedItems.Size())
@@ -791,7 +812,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
791 else 812 else
792 { 813 {
793 NCOM::CPropVariant prop; 814 NCOM::CPropVariant prop;
794 RINOK(callback->GetProperty(i, kpidPath, &prop)); 815 RINOK(callback->GetProperty(i, kpidPath, &prop))
795 816
796 if (prop.vt != VT_BSTR) 817 if (prop.vt != VT_BSTR)
797 return E_INVALIDARG; 818 return E_INVALIDARG;
@@ -851,11 +872,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
851 UInt32 propType = 0; 872 UInt32 propType = 0;
852 if (getRootProps) 873 if (getRootProps)
853 { 874 {
854 RINOK(getRootProps->GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)); 875 RINOK(getRootProps->GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType))
855 } 876 }
856 if (dataSize == 0 && isUpdate) 877 if (dataSize == 0 && isUpdate)
857 { 878 {
858 RINOK(GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType)); 879 RINOK(GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType))
859 } 880 }
860 if (dataSize != 0) 881 if (dataSize != 0)
861 { 882 {
@@ -864,21 +885,21 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
864 while (defaultImageIndex >= (int)secureBlocks.Size()) 885 while (defaultImageIndex >= (int)secureBlocks.Size())
865 secureBlocks.AddNew(); 886 secureBlocks.AddNew();
866 CUniqBlocks &secUniqBlocks = secureBlocks[defaultImageIndex]; 887 CUniqBlocks &secUniqBlocks = secureBlocks[defaultImageIndex];
867 rootItem.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize); 888 rootItem.SecurityId = (int)secUniqBlocks.AddUniq((const Byte *)data, dataSize);
868 } 889 }
869 } 890 }
870 891
871 IArchiveGetRootProps *thisGetRoot = isUpdate ? this : NULL; 892 IArchiveGetRootProps *thisGetRoot = isUpdate ? this : NULL;
872 893
873 RINOK(GetRootTime(getRootProps, thisGetRoot, kpidCTime, rootItem.CTime)); 894 if (_timeOptions.Write_CTime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidCTime, rootItem.CTime))
874 RINOK(GetRootTime(getRootProps, thisGetRoot, kpidATime, rootItem.ATime)); 895 if (_timeOptions.Write_ATime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidATime, rootItem.ATime))
875 RINOK(GetRootTime(getRootProps, thisGetRoot, kpidMTime, rootItem.MTime)); 896 if (_timeOptions.Write_MTime.Val) RINOK(GetRootTime(getRootProps, thisGetRoot, kpidMTime, rootItem.MTime))
876 897
877 { 898 {
878 NCOM::CPropVariant prop; 899 NCOM::CPropVariant prop;
879 if (getRootProps) 900 if (getRootProps)
880 { 901 {
881 RINOK(getRootProps->GetRootProp(kpidAttrib, &prop)); 902 RINOK(getRootProps->GetRootProp(kpidAttrib, &prop))
882 if (prop.vt == VT_UI4) 903 if (prop.vt == VT_UI4)
883 rootItem.Attrib = prop.ulVal; 904 rootItem.Attrib = prop.ulVal;
884 else if (prop.vt != VT_EMPTY) 905 else if (prop.vt != VT_EMPTY)
@@ -886,7 +907,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
886 } 907 }
887 if (prop.vt == VT_EMPTY && thisGetRoot) 908 if (prop.vt == VT_EMPTY && thisGetRoot)
888 { 909 {
889 RINOK(GetRootProp(kpidAttrib, &prop)); 910 RINOK(GetRootProp(kpidAttrib, &prop))
890 if (prop.vt == VT_UI4) 911 if (prop.vt == VT_UI4)
891 rootItem.Attrib = prop.ulVal; 912 rootItem.Attrib = prop.ulVal;
892 else if (prop.vt != VT_EMPTY) 913 else if (prop.vt != VT_EMPTY)
@@ -908,7 +929,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
908 CUpdateItem ui; 929 CUpdateItem ui;
909 UInt32 indexInArchive; 930 UInt32 indexInArchive;
910 Int32 newData, newProps; 931 Int32 newData, newProps;
911 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive)); 932 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive))
912 933
913 if (newData == 0 || newProps == 0) 934 if (newData == 0 || newProps == 0)
914 { 935 {
@@ -940,16 +961,16 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
940 } 961 }
941 962
942 if (newData == 0) 963 if (newData == 0)
943 ui.InArcIndex = indexInArchive; 964 ui.InArcIndex = (Int32)indexInArchive;
944 } 965 }
945 966
946 // we set arcIndex only if we must use old props 967 // we set arcIndex only if we must use old props
947 Int32 arcIndex = (newProps ? -1 : indexInArchive); 968 const Int32 arcIndex = (newProps ? -1 : (Int32)indexInArchive);
948 969
949 bool isDir = false; 970 bool isDir = false;
950 { 971 {
951 NCOM::CPropVariant prop; 972 NCOM::CPropVariant prop;
952 RINOK(GetOutProperty(callback, i, arcIndex, kpidIsDir, &prop)); 973 RINOK(GetOutProperty(callback, i, arcIndex, kpidIsDir, &prop))
953 if (prop.vt == VT_BOOL) 974 if (prop.vt == VT_BOOL)
954 isDir = (prop.boolVal != VARIANT_FALSE); 975 isDir = (prop.boolVal != VARIANT_FALSE);
955 else if (prop.vt != VT_EMPTY) 976 else if (prop.vt != VT_EMPTY)
@@ -959,7 +980,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
959 bool isAltStream = false; 980 bool isAltStream = false;
960 { 981 {
961 NCOM::CPropVariant prop; 982 NCOM::CPropVariant prop;
962 RINOK(GetOutProperty(callback, i, arcIndex, kpidIsAltStream, &prop)); 983 RINOK(GetOutProperty(callback, i, arcIndex, kpidIsAltStream, &prop))
963 if (prop.vt == VT_BOOL) 984 if (prop.vt == VT_BOOL)
964 isAltStream = (prop.boolVal != VARIANT_FALSE); 985 isAltStream = (prop.boolVal != VARIANT_FALSE);
965 else if (prop.vt != VT_EMPTY) 986 else if (prop.vt != VT_EMPTY)
@@ -986,11 +1007,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
986 1007
987 if (newData) 1008 if (newData)
988 { 1009 {
989 RINOK(callback->GetProperty(i, kpidSize, &prop)); 1010 RINOK(callback->GetProperty(i, kpidSize, &prop))
990 } 1011 }
991 else 1012 else
992 { 1013 {
993 RINOK(GetProperty(indexInArchive, kpidSize, &prop)); 1014 RINOK(GetProperty(indexInArchive, kpidSize, &prop))
994 } 1015 }
995 1016
996 if (prop.vt == VT_UI8) 1017 if (prop.vt == VT_UI8)
@@ -1002,7 +1023,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1002 { 1023 {
1003 NCOM::CPropVariant propPath; 1024 NCOM::CPropVariant propPath;
1004 const wchar_t *path = NULL; 1025 const wchar_t *path = NULL;
1005 RINOK(GetOutProperty(callback, i, arcIndex, kpidPath, &propPath)); 1026 RINOK(GetOutProperty(callback, i, arcIndex, kpidPath, &propPath))
1006 if (propPath.vt == VT_BSTR) 1027 if (propPath.vt == VT_BSTR)
1007 path = propPath.bstrVal; 1028 path = propPath.bstrVal;
1008 else if (propPath.vt != VT_EMPTY) 1029 else if (propPath.vt != VT_EMPTY)
@@ -1056,8 +1077,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1056 CAltStream ss; 1077 CAltStream ss;
1057 ss.Size = size; 1078 ss.Size = size;
1058 ss.Name = end + 1; 1079 ss.Name = end + 1;
1059 ss.UpdateIndex = db.UpdateItems.Size(); 1080 ss.UpdateIndex = (int)db.UpdateItems.Size();
1060 ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); 1081 ui.AltStreamIndex = (int)db.MetaItems[ui.MetaIndex].AltStreams.Add(ss);
1061 } 1082 }
1062 else if (c == WCHAR_PATH_SEPARATOR || c == L'/') 1083 else if (c == WCHAR_PATH_SEPARATOR || c == L'/')
1063 { 1084 {
@@ -1082,7 +1103,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1082 if (!curItem->FindDir(db.MetaItems, fileName, indexOfDir)) 1103 if (!curItem->FindDir(db.MetaItems, fileName, indexOfDir))
1083 { 1104 {
1084 CDir &dir = curItem->Dirs.InsertNew(indexOfDir); 1105 CDir &dir = curItem->Dirs.InsertNew(indexOfDir);
1085 dir.MetaIndex = db.MetaItems.Add(ri); 1106 dir.MetaIndex = (int)db.MetaItems.Add(ri);
1086 db.MetaItems.Back().Name = fileName; 1107 db.MetaItems.Back().Name = fileName;
1087 } 1108 }
1088 curItem = &curItem->Dirs[indexOfDir]; 1109 curItem = &curItem->Dirs[indexOfDir];
@@ -1121,7 +1142,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1121 // we want to support cases of c::substream, where c: is drive name 1142 // we want to support cases of c::substream, where c: is drive name
1122 if (colonPos == 1 && fileName[2] == L':' && IS_LETTER_CHAR(fileName[0])) 1143 if (colonPos == 1 && fileName[2] == L':' && IS_LETTER_CHAR(fileName[0]))
1123 colonPos = 2; 1144 colonPos = 2;
1124 const UString mainName = fileName.Left(colonPos); 1145 const UString mainName = fileName.Left((unsigned)colonPos);
1125 unsigned indexOfDir; 1146 unsigned indexOfDir;
1126 1147
1127 if (mainName.IsEmpty()) 1148 if (mainName.IsEmpty())
@@ -1132,11 +1153,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1132 { 1153 {
1133 for (int j = (int)curItem->Files.Size() - 1; j >= 0; j--) 1154 for (int j = (int)curItem->Files.Size() - 1; j >= 0; j--)
1134 { 1155 {
1135 int metaIndex = curItem->Files[j]; 1156 const unsigned metaIndex = curItem->Files[j];
1136 const CMetaItem &mi = db.MetaItems[metaIndex]; 1157 const CMetaItem &mi = db.MetaItems[metaIndex];
1137 if (CompareFileNames(mainName, mi.Name) == 0) 1158 if (CompareFileNames(mainName, mi.Name) == 0)
1138 { 1159 {
1139 ui.MetaIndex = metaIndex; 1160 ui.MetaIndex = (int)metaIndex;
1140 break; 1161 break;
1141 } 1162 }
1142 } 1163 }
@@ -1147,8 +1168,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1147 CAltStream ss; 1168 CAltStream ss;
1148 ss.Size = size; 1169 ss.Size = size;
1149 ss.Name = fileName.Ptr(colonPos + 1); 1170 ss.Name = fileName.Ptr(colonPos + 1);
1150 ss.UpdateIndex = db.UpdateItems.Size(); 1171 ss.UpdateIndex = (int)db.UpdateItems.Size();
1151 ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss); 1172 ui.AltStreamIndex = (int)db.MetaItems[ui.MetaIndex].AltStreams.Add(ss);
1152 } 1173 }
1153 } 1174 }
1154 } 1175 }
@@ -1158,7 +1179,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1158 { 1179 {
1159 if (!isRootImageDir) 1180 if (!isRootImageDir)
1160 { 1181 {
1161 ui.MetaIndex = db.MetaItems.Size(); 1182 ui.MetaIndex = (int)db.MetaItems.Size();
1162 db.MetaItems.AddNew(); 1183 db.MetaItems.AddNew();
1163 } 1184 }
1164 1185
@@ -1166,10 +1187,10 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1166 mi.Size = size; 1187 mi.Size = size;
1167 mi.IsDir = isDir; 1188 mi.IsDir = isDir;
1168 mi.Name = fileName; 1189 mi.Name = fileName;
1169 mi.UpdateIndex = db.UpdateItems.Size(); 1190 mi.UpdateIndex = (int)db.UpdateItems.Size();
1170 { 1191 {
1171 NCOM::CPropVariant prop; 1192 NCOM::CPropVariant prop;
1172 RINOK(GetOutProperty(callback, i, arcIndex, kpidAttrib, &prop)); 1193 RINOK(GetOutProperty(callback, i, arcIndex, kpidAttrib, &prop))
1173 if (prop.vt == VT_EMPTY) 1194 if (prop.vt == VT_EMPTY)
1174 mi.Attrib = 0; 1195 mi.Attrib = 0;
1175 else if (prop.vt == VT_UI4) 1196 else if (prop.vt == VT_UI4)
@@ -1179,13 +1200,17 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1179 if (isDir) 1200 if (isDir)
1180 mi.Attrib |= FILE_ATTRIBUTE_DIRECTORY; 1201 mi.Attrib |= FILE_ATTRIBUTE_DIRECTORY;
1181 } 1202 }
1182 RINOK(GetTime(callback, i, arcIndex, kpidCTime, mi.CTime)); 1203
1183 RINOK(GetTime(callback, i, arcIndex, kpidATime, mi.ATime)); 1204 if (arcIndex != -1 || _timeOptions.Write_CTime.Val)
1184 RINOK(GetTime(callback, i, arcIndex, kpidMTime, mi.MTime)); 1205 RINOK(GetTime(callback, i, arcIndex, kpidCTime, mi.CTime))
1206 if (arcIndex != -1 || _timeOptions.Write_ATime.Val)
1207 RINOK(GetTime(callback, i, arcIndex, kpidATime, mi.ATime))
1208 if (arcIndex != -1 || _timeOptions.Write_MTime.Val)
1209 RINOK(GetTime(callback, i, arcIndex, kpidMTime, mi.MTime))
1185 1210
1186 { 1211 {
1187 NCOM::CPropVariant prop; 1212 NCOM::CPropVariant prop;
1188 RINOK(GetOutProperty(callback, i, arcIndex, kpidShortName, &prop)); 1213 RINOK(GetOutProperty(callback, i, arcIndex, kpidShortName, &prop))
1189 if (prop.vt == VT_BSTR) 1214 if (prop.vt == VT_BSTR)
1190 mi.ShortName.SetFromBstr(prop.bstrVal); 1215 mi.ShortName.SetFromBstr(prop.bstrVal);
1191 else if (prop.vt != VT_EMPTY) 1216 else if (prop.vt != VT_EMPTY)
@@ -1208,7 +1233,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1208 1233
1209 if (arcIndex >= 0) 1234 if (arcIndex >= 0)
1210 { 1235 {
1211 GetRawProp(arcIndex, kpidNtSecure, &data, &dataSize, &propType); 1236 GetRawProp((UInt32)arcIndex, kpidNtSecure, &data, &dataSize, &propType);
1212 } 1237 }
1213 else 1238 else
1214 { 1239 {
@@ -1219,7 +1244,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1219 { 1244 {
1220 if (propType != NPropDataType::kRaw) 1245 if (propType != NPropDataType::kRaw)
1221 return E_FAIL; 1246 return E_FAIL;
1222 mi.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize); 1247 mi.SecurityId = (int)secUniqBlocks.AddUniq((const Byte *)data, dataSize);
1223 } 1248 }
1224 1249
1225 data = NULL; 1250 data = NULL;
@@ -1228,7 +1253,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1228 1253
1229 if (arcIndex >= 0) 1254 if (arcIndex >= 0)
1230 { 1255 {
1231 GetRawProp(arcIndex, kpidNtReparse, &data, &dataSize, &propType); 1256 GetRawProp((UInt32)arcIndex, kpidNtReparse, &data, &dataSize, &propType);
1232 } 1257 }
1233 else 1258 else
1234 { 1259 {
@@ -1254,7 +1279,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1254 curItem->Dirs.InsertNew(indexOfDir).MetaIndex = ui.MetaIndex; 1279 curItem->Dirs.InsertNew(indexOfDir).MetaIndex = ui.MetaIndex;
1255 } 1280 }
1256 else 1281 else
1257 curItem->Files.Add(ui.MetaIndex); 1282 curItem->Files.Add((unsigned)ui.MetaIndex);
1258 } 1283 }
1259 } 1284 }
1260 1285
@@ -1272,7 +1297,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1272 if (!isChangedImage[i]) 1297 if (!isChangedImage[i])
1273 numNewImages = i + 1; 1298 numNewImages = i + 1;
1274 1299
1275 AddTrees(trees, db.MetaItems, ri, numNewImages - 1); 1300 AddTrees(trees, db.MetaItems, ri, (int)numNewImages - 1);
1276 1301
1277 for (i = 0; i < trees.Size(); i++) 1302 for (i = 0; i < trees.Size(); i++)
1278 if (i >= isChangedImage.Size() || isChangedImage[i]) 1303 if (i >= isChangedImage.Size() || isChangedImage[i])
@@ -1354,7 +1379,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1354 complexity += rs.PackSize; 1379 complexity += rs.PackSize;
1355 } 1380 }
1356 1381
1357 RINOK(callback->SetTotal(complexity)); 1382 RINOK(callback->SetTotal(complexity))
1358 UInt64 totalComplexity = complexity; 1383 UInt64 totalComplexity = complexity;
1359 1384
1360 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; 1385 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
@@ -1381,10 +1406,15 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1381 header.ChunkSizeBits = srcHeader.ChunkSizeBits; 1406 header.ChunkSizeBits = srcHeader.ChunkSizeBits;
1382 } 1407 }
1383 1408
1409 CMyComPtr<IStreamSetRestriction> setRestriction;
1410 outSeqStream->QueryInterface(IID_IStreamSetRestriction, (void **)&setRestriction);
1411 if (setRestriction)
1412 RINOK(setRestriction->SetRestriction(0, kHeaderSizeMax))
1413
1384 { 1414 {
1385 Byte buf[kHeaderSizeMax]; 1415 Byte buf[kHeaderSizeMax];
1386 header.WriteTo(buf); 1416 header.WriteTo(buf);
1387 RINOK(WriteStream(outStream, buf, kHeaderSizeMax)); 1417 RINOK(WriteStream(outStream, buf, kHeaderSizeMax))
1388 } 1418 }
1389 1419
1390 UInt64 curPos = kHeaderSizeMax; 1420 UInt64 curPos = kHeaderSizeMax;
@@ -1393,7 +1423,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1393 CMyComPtr<ISequentialInStream> inShaStream = inShaStreamSpec; 1423 CMyComPtr<ISequentialInStream> inShaStream = inShaStreamSpec;
1394 1424
1395 CLimitedSequentialInStream *inStreamLimitedSpec = NULL; 1425 CLimitedSequentialInStream *inStreamLimitedSpec = NULL;
1396 CMyComPtr<CLimitedSequentialInStream> inStreamLimited; 1426 CMyComPtr<ISequentialInStream> inStreamLimited;
1397 if (_volumes.Size() == 2) 1427 if (_volumes.Size() == 2)
1398 { 1428 {
1399 inStreamLimitedSpec = new CLimitedSequentialInStream; 1429 inStreamLimitedSpec = new CLimitedSequentialInStream;
@@ -1403,7 +1433,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1403 1433
1404 1434
1405 CRecordVector<CStreamInfo> streams; 1435 CRecordVector<CStreamInfo> streams;
1406 CUIntVector sortedHashes; // indexes to streams, sorted by SHA1 1436 CSortedIndex sortedHashes; // indexes to streams, sorted by SHA1
1407 1437
1408 // ---------- Copy unchanged data streams ---------- 1438 // ---------- Copy unchanged data streams ----------
1409 1439
@@ -1415,7 +1445,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1415 const CStreamInfo &siOld = _db.DataStreams[i]; 1445 const CStreamInfo &siOld = _db.DataStreams[i];
1416 const CResource &rs = siOld.Resource; 1446 const CResource &rs = siOld.Resource;
1417 1447
1418 unsigned numRefs = streamsRefs[i]; 1448 const unsigned numRefs = streamsRefs[i];
1419 1449
1420 if (numRefs == 0) 1450 if (numRefs == 0)
1421 { 1451 {
@@ -1426,9 +1456,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1426 } 1456 }
1427 1457
1428 lps->InSize = lps->OutSize = complexity; 1458 lps->InSize = lps->OutSize = complexity;
1429 RINOK(lps->SetCur()); 1459 RINOK(lps->SetCur())
1430 1460
1431 int streamIndex = streams.Size(); 1461 const unsigned streamIndex = streams.Size();
1432 CStreamInfo s; 1462 CStreamInfo s;
1433 s.Resource = rs; 1463 s.Resource = rs;
1434 s.PartNumber = 1; 1464 s.PartNumber = 1;
@@ -1462,16 +1492,16 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1462 1492
1463 if (!rs.IsSolid() || rs.IsSolidSmall()) 1493 if (!rs.IsSolid() || rs.IsSolidSmall())
1464 { 1494 {
1465 int find = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, streamIndex); 1495 const int find = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, (int)streamIndex);
1466 if (find >= 0) 1496 if (find != -1)
1467 return E_FAIL; // two streams with same SHA-1 1497 return E_FAIL; // two streams with same SHA-1
1468 } 1498 }
1469 1499
1470 if (!rs.IsSolid() || rs.IsSolidBig()) 1500 if (!rs.IsSolid() || rs.IsSolidBig())
1471 { 1501 {
1472 RINOK(_volumes[siOld.PartNumber].Stream->Seek(rs.Offset, STREAM_SEEK_SET, NULL)); 1502 RINOK(InStream_SeekSet(_volumes[siOld.PartNumber].Stream, rs.Offset))
1473 inStreamLimitedSpec->Init(rs.PackSize); 1503 inStreamLimitedSpec->Init(rs.PackSize);
1474 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); 1504 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress))
1475 if (copyCoderSpec->TotalSize != rs.PackSize) 1505 if (copyCoderSpec->TotalSize != rs.PackSize)
1476 return E_FAIL; 1506 return E_FAIL;
1477 s.Resource.Offset = curPos; 1507 s.Resource.Offset = curPos;
@@ -1490,7 +1520,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1490 for (i = 0; i < db.UpdateIndexes.Size(); i++) 1520 for (i = 0; i < db.UpdateIndexes.Size(); i++)
1491 { 1521 {
1492 lps->InSize = lps->OutSize = complexity; 1522 lps->InSize = lps->OutSize = complexity;
1493 RINOK(lps->SetCur()); 1523 RINOK(lps->SetCur())
1494 const CUpdateItem &ui = db.UpdateItems[db.UpdateIndexes[i]]; 1524 const CUpdateItem &ui = db.UpdateItems[db.UpdateIndexes[i]];
1495 CMetaItem &mi = db.MetaItems[ui.MetaIndex]; 1525 CMetaItem &mi = db.MetaItems[ui.MetaIndex];
1496 UInt64 size = 0; 1526 UInt64 size = 0;
@@ -1534,9 +1564,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1534 1564
1535 const CStreamInfo &siOld = _db.DataStreams[item.StreamIndex]; 1565 const CStreamInfo &siOld = _db.DataStreams[item.StreamIndex];
1536 1566
1537 int index = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, -1); 1567 const int index = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, -1);
1538 // we must have written that stream already 1568 // we must have written that stream already
1539 if (index < 0) 1569 if (index == -1)
1540 return E_FAIL; 1570 return E_FAIL;
1541 1571
1542 if (ui.AltStreamIndex < 0) 1572 if (ui.AltStreamIndex < 0)
@@ -1562,7 +1592,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1562 } 1592 }
1563 else 1593 else
1564 { 1594 {
1565 RINOK(res); 1595 RINOK(res)
1566 1596
1567 int miIndex = -1; 1597 int miIndex = -1;
1568 1598
@@ -1581,23 +1611,23 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1581 if (getProps2->GetProps2(&props) == S_OK) 1611 if (getProps2->GetProps2(&props) == S_OK)
1582 { 1612 {
1583 mi.Attrib = props.Attrib; 1613 mi.Attrib = props.Attrib;
1584 mi.CTime = props.CTime; 1614 if (_timeOptions.Write_CTime.Val) mi.CTime = props.CTime;
1585 mi.ATime = props.ATime; 1615 if (_timeOptions.Write_ATime.Val) mi.ATime = props.ATime;
1586 mi.MTime = props.MTime; 1616 if (_timeOptions.Write_MTime.Val) mi.MTime = props.MTime;
1587 mi.FileID = props.FileID_Low; 1617 mi.FileID = props.FileID_Low;
1588 if (props.NumLinks <= 1) 1618 if (props.NumLinks <= 1)
1589 mi.FileID = 0; 1619 mi.FileID = 0;
1590 mi.VolID = props.VolID; 1620 mi.VolID = props.VolID;
1591 if (mi.FileID != 0) 1621 if (mi.FileID != 0)
1592 miIndex = AddToHardLinkList(db.MetaItems, ui.MetaIndex, hlIndexes); 1622 miIndex = AddToHardLinkList(db.MetaItems, (unsigned)ui.MetaIndex, hlIndexes);
1593 1623
1594 if (props.Size != size && props.Size != (UInt64)(Int64)-1) 1624 if (props.Size != size && props.Size != (UInt64)(Int64)-1)
1595 { 1625 {
1596 Int64 delta = (Int64)props.Size - (Int64)size; 1626 const Int64 delta = (Int64)props.Size - (Int64)size;
1597 Int64 newComplexity = totalComplexity + delta; 1627 const Int64 newComplexity = (Int64)totalComplexity + delta;
1598 if (newComplexity > 0) 1628 if (newComplexity > 0)
1599 { 1629 {
1600 totalComplexity = newComplexity; 1630 totalComplexity = (UInt64)newComplexity;
1601 callback->SetTotal(totalComplexity); 1631 callback->SetTotal(totalComplexity);
1602 } 1632 }
1603 mi.Size = props.Size; 1633 mi.Size = props.Size;
@@ -1620,19 +1650,19 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1620 return E_FAIL; 1650 return E_FAIL;
1621 NCrypto::NSha1::CContext sha1; 1651 NCrypto::NSha1::CContext sha1;
1622 sha1.Init(); 1652 sha1.Init();
1623 size_t packSize = mi.Reparse.Size() - 8; 1653 const size_t packSize = mi.Reparse.Size() - 8;
1624 sha1.Update((const Byte *)mi.Reparse + 8, packSize); 1654 sha1.Update((const Byte *)mi.Reparse + 8, packSize);
1625 Byte hash[kHashSize]; 1655 Byte hash[kHashSize];
1626 sha1.Final(hash); 1656 sha1.Final(hash);
1627 1657
1628 int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size()); 1658 int index = AddUniqHash(&streams.Front(), sortedHashes, hash, (int)streams.Size());
1629 1659
1630 if (index >= 0) 1660 if (index != -1)
1631 streams[index].RefCount++; 1661 streams[index].RefCount++;
1632 else 1662 else
1633 { 1663 {
1634 index = streams.Size(); 1664 index = (int)streams.Size();
1635 RINOK(WriteStream(outStream, (const Byte *)mi.Reparse + 8, packSize)); 1665 RINOK(WriteStream(outStream, (const Byte *)mi.Reparse + 8, packSize))
1636 CStreamInfo s; 1666 CStreamInfo s;
1637 s.Resource.PackSize = packSize; 1667 s.Resource.PackSize = packSize;
1638 s.Resource.Offset = curPos; 1668 s.Resource.Offset = curPos;
@@ -1655,6 +1685,10 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1655 else 1685 else
1656 { 1686 {
1657 inShaStreamSpec->SetStream(fileInStream); 1687 inShaStreamSpec->SetStream(fileInStream);
1688
1689 CMyComPtr<IInStream> inSeekStream;
1690 fileInStream.QueryInterface(IID_IInStream, (void **)&inSeekStream);
1691
1658 fileInStream.Release(); 1692 fileInStream.Release();
1659 inShaStreamSpec->Init(); 1693 inShaStreamSpec->Init();
1660 UInt64 offsetBlockSize = 0; 1694 UInt64 offsetBlockSize = 0;
@@ -1670,54 +1704,88 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1670 } 1704 }
1671 } 1705 }
1672 */ 1706 */
1707
1708 // 22.02: we use additional read-only pass to calculate SHA-1
1709 bool needWritePass = true;
1710 int index = -1;
1673 1711
1674 RINOK(copyCoder->Code(inShaStream, outStream, NULL, NULL, progress)); 1712 if (inSeekStream /* && !sortedHashes.IsEmpty() */)
1675 size = copyCoderSpec->TotalSize;
1676
1677 if (size != 0)
1678 { 1713 {
1679 Byte hash[kHashSize]; 1714 RINOK(copyCoder->Code(inShaStream, NULL, NULL, NULL, progress))
1680 UInt64 packSize = offsetBlockSize + size; 1715 size = copyCoderSpec->TotalSize;
1681 inShaStreamSpec->Final(hash); 1716 if (size == 0)
1682 1717 needWritePass = false;
1683 int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size());
1684
1685 if (index >= 0)
1686 {
1687 streams[index].RefCount++;
1688 outStream->Seek(-(Int64)packSize, STREAM_SEEK_CUR, &curPos);
1689 outStream->SetSize(curPos);
1690 }
1691 else 1718 else
1692 { 1719 {
1693 index = streams.Size(); 1720 Byte hash[kHashSize];
1694 CStreamInfo s; 1721 inShaStreamSpec->Final(hash);
1695 s.Resource.PackSize = packSize; 1722
1696 s.Resource.Offset = curPos; 1723 index = AddUniqHash(&streams.Front(), sortedHashes, hash, -1);
1697 s.Resource.UnpackSize = size; 1724 if (index != -1)
1698 s.Resource.Flags = 0; 1725 {
1699 /* 1726 streams[index].RefCount++;
1700 if (useResourceCompression) 1727 needWritePass = false;
1701 s.Resource.Flags = NResourceFlags::Compressed; 1728 }
1702 */ 1729 else
1703 s.PartNumber = 1; 1730 {
1704 s.RefCount = 1; 1731 RINOK(InStream_SeekToBegin(inSeekStream))
1705 memcpy(s.Hash, hash, kHashSize); 1732 inShaStreamSpec->Init();
1706 curPos += packSize; 1733 }
1707
1708 streams.Add(s);
1709 } 1734 }
1710 1735 }
1736
1737 if (needWritePass)
1738 {
1739 RINOK(copyCoder->Code(inShaStream, outStream, NULL, NULL, progress))
1740 size = copyCoderSpec->TotalSize;
1741 }
1742
1743 if (size != 0)
1744 {
1745 if (needWritePass)
1746 {
1747 Byte hash[kHashSize];
1748 const UInt64 packSize = offsetBlockSize + size;
1749 inShaStreamSpec->Final(hash);
1750
1751 index = AddUniqHash(&streams.Front(), sortedHashes, hash, (int)streams.Size());
1752
1753 if (index != -1)
1754 {
1755 streams[index].RefCount++;
1756 outStream->Seek(-(Int64)packSize, STREAM_SEEK_CUR, &curPos);
1757 outStream->SetSize(curPos);
1758 }
1759 else
1760 {
1761 index = (int)streams.Size();
1762 CStreamInfo s;
1763 s.Resource.PackSize = packSize;
1764 s.Resource.Offset = curPos;
1765 s.Resource.UnpackSize = size;
1766 s.Resource.Flags = 0;
1767 /*
1768 if (useResourceCompression)
1769 s.Resource.Flags = NResourceFlags::Compressed;
1770 */
1771 s.PartNumber = 1;
1772 s.RefCount = 1;
1773 memcpy(s.Hash, hash, kHashSize);
1774 curPos += packSize;
1775
1776 streams.Add(s);
1777 }
1778 } // needWritePass
1711 if (ui.AltStreamIndex < 0) 1779 if (ui.AltStreamIndex < 0)
1712 mi.HashIndex = index; 1780 mi.HashIndex = index;
1713 else 1781 else
1714 mi.AltStreams[ui.AltStreamIndex].HashIndex = index; 1782 mi.AltStreams[ui.AltStreamIndex].HashIndex = index;
1715 } 1783 } // (size != 0)
1716 } 1784 }
1717 } 1785 }
1718 fileInStream.Release(); 1786 fileInStream.Release();
1719 complexity += size; 1787 complexity += size;
1720 RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 1788 RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
1721 } 1789 }
1722 1790
1723 while (secureBlocks.Size() < numNewImages) 1791 while (secureBlocks.Size() < numNewImages)
@@ -1730,14 +1798,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1730 for (i = 0; i < numNewImages; i++) 1798 for (i = 0; i < numNewImages; i++)
1731 { 1799 {
1732 lps->InSize = lps->OutSize = complexity; 1800 lps->InSize = lps->OutSize = complexity;
1733 RINOK(lps->SetCur()); 1801 RINOK(lps->SetCur())
1734 if (i < isChangedImage.Size() && !isChangedImage[i]) 1802 if (i < isChangedImage.Size() && !isChangedImage[i])
1735 { 1803 {
1736 CStreamInfo s = _db.MetaStreams[i]; 1804 CStreamInfo s = _db.MetaStreams[i];
1737 1805
1738 RINOK(_volumes[1].Stream->Seek(s.Resource.Offset, STREAM_SEEK_SET, NULL)); 1806 RINOK(InStream_SeekSet(_volumes[1].Stream, s.Resource.Offset))
1739 inStreamLimitedSpec->Init(s.Resource.PackSize); 1807 inStreamLimitedSpec->Init(s.Resource.PackSize);
1740 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress)); 1808 RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress))
1741 if (copyCoderSpec->TotalSize != s.Resource.PackSize) 1809 if (copyCoderSpec->TotalSize != s.Resource.PackSize)
1742 return E_FAIL; 1810 return E_FAIL;
1743 1811
@@ -1774,14 +1842,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1774 1842
1775 CByteArr meta(pos); 1843 CByteArr meta(pos);
1776 1844
1777 Set32((Byte *)meta + 4, secBufs.Size()); // num security entries 1845 Set32((Byte *)meta + 4, secBufs.Size()) // num security entries
1778 pos = kSecuritySize; 1846 pos = kSecuritySize;
1779 1847
1780 if (secBufs.Size() == 0) 1848 if (secBufs.Size() == 0)
1781 { 1849 {
1782 // we can write 0 here only if there is no security data, imageX does it, 1850 // we can write 0 here only if there is no security data, imageX does it,
1783 // but some programs expect size = 8 1851 // but some programs expect size = 8
1784 Set32((Byte *)meta, 8); // size of security data 1852 Set32((Byte *)meta, 8) // size of security data
1785 // Set32((Byte *)meta, 0); 1853 // Set32((Byte *)meta, 0);
1786 } 1854 }
1787 else 1855 else
@@ -1789,7 +1857,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1789 unsigned k; 1857 unsigned k;
1790 for (k = 0; k < secBufs.Size(); k++, pos += 8) 1858 for (k = 0; k < secBufs.Size(); k++, pos += 8)
1791 { 1859 {
1792 Set64(meta + pos, secBufs[k].Size()); 1860 Set64(meta + pos, secBufs[k].Size())
1793 } 1861 }
1794 for (k = 0; k < secBufs.Size(); k++) 1862 for (k = 0; k < secBufs.Size(); k++)
1795 { 1863 {
@@ -1803,7 +1871,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1803 } 1871 }
1804 while ((pos & 7) != 0) 1872 while ((pos & 7) != 0)
1805 meta[pos++] = 0; 1873 meta[pos++] = 0;
1806 Set32((Byte *)meta, (UInt32)pos); // size of security data 1874 Set32((Byte *)meta, (UInt32)pos) // size of security data
1807 } 1875 }
1808 1876
1809 db.Hashes = &streams.Front(); 1877 db.Hashes = &streams.Front();
@@ -1833,14 +1901,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1833 header.BootIndex = _bootIndex; 1901 header.BootIndex = _bootIndex;
1834 } 1902 }
1835 1903
1836 RINOK(WriteStream(outStream, (const Byte *)meta, pos)); 1904 RINOK(WriteStream(outStream, (const Byte *)meta, pos))
1837 meta.Free(); 1905 meta.Free();
1838 curPos += pos; 1906 curPos += pos;
1839 } 1907 }
1840 } 1908 }
1841 1909
1842 lps->InSize = lps->OutSize = complexity; 1910 lps->InSize = lps->OutSize = complexity;
1843 RINOK(lps->SetCur()); 1911 RINOK(lps->SetCur())
1844 1912
1845 header.OffsetResource.UnpackSize = header.OffsetResource.PackSize = (UInt64)streams.Size() * kStreamInfoSize; 1913 header.OffsetResource.UnpackSize = header.OffsetResource.PackSize = (UInt64)streams.Size() * kStreamInfoSize;
1846 header.OffsetResource.Offset = curPos; 1914 header.OffsetResource.Offset = curPos;
@@ -1854,7 +1922,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1854 { 1922 {
1855 Byte buf[kStreamInfoSize]; 1923 Byte buf[kStreamInfoSize];
1856 streams[i].WriteTo(buf); 1924 streams[i].WriteTo(buf);
1857 RINOK(WriteStream(outStream, buf, kStreamInfoSize)); 1925 RINOK(WriteStream(outStream, buf, kStreamInfoSize))
1858 curPos += kStreamInfoSize; 1926 curPos += kStreamInfoSize;
1859 } 1927 }
1860 1928
@@ -1862,7 +1930,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1862 AddTagUInt64_ToString(xml, "TOTALBYTES", curPos); 1930 AddTagUInt64_ToString(xml, "TOTALBYTES", curPos);
1863 for (i = 0; i < trees.Size(); i++) 1931 for (i = 0; i < trees.Size(); i++)
1864 { 1932 {
1865 CDir &tree = trees[i]; 1933 const CDir &tree = trees[i];
1866 1934
1867 CXmlItem item; 1935 CXmlItem item;
1868 if (_xmls.Size() == 1) 1936 if (_xmls.Size() == 1)
@@ -1905,16 +1973,19 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1905 UString utf16; 1973 UString utf16;
1906 if (!ConvertUTF8ToUnicode(xml, utf16)) 1974 if (!ConvertUTF8ToUnicode(xml, utf16))
1907 return S_FALSE; 1975 return S_FALSE;
1908 xmlSize = (utf16.Len() + 1) * 2; 1976 xmlSize = ((size_t)utf16.Len() + 1) * 2;
1909 1977
1910 CByteArr xmlBuf(xmlSize); 1978 CByteArr xmlBuf(xmlSize);
1911 Set16((Byte *)xmlBuf, 0xFEFF); 1979 Set16((Byte *)xmlBuf, 0xFEFF)
1912 for (i = 0; i < (unsigned)utf16.Len(); i++) 1980 for (i = 0; i < (unsigned)utf16.Len(); i++)
1913 Set16((Byte *)xmlBuf + 2 + i * 2, (UInt16)utf16[i]); 1981 {
1914 RINOK(WriteStream(outStream, (const Byte *)xmlBuf, xmlSize)); 1982 Set16((Byte *)xmlBuf + 2 + (size_t)i * 2, (UInt16)utf16[i])
1983 }
1984 RINOK(WriteStream(outStream, (const Byte *)xmlBuf, xmlSize))
1915 } 1985 }
1916 1986
1917 header.XmlResource.UnpackSize = header.XmlResource.PackSize = xmlSize; 1987 header.XmlResource.UnpackSize =
1988 header.XmlResource.PackSize = xmlSize;
1918 header.XmlResource.Offset = curPos; 1989 header.XmlResource.Offset = curPos;
1919 header.XmlResource.Flags = NResourceFlags::kMetadata; 1990 header.XmlResource.Flags = NResourceFlags::kMetadata;
1920 1991
@@ -1923,9 +1994,14 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 nu
1923 { 1994 {
1924 Byte buf[kHeaderSizeMax]; 1995 Byte buf[kHeaderSizeMax];
1925 header.WriteTo(buf); 1996 header.WriteTo(buf);
1926 return WriteStream(outStream, buf, kHeaderSizeMax); 1997 RINOK(WriteStream(outStream, buf, kHeaderSizeMax))
1927 } 1998 }
1928 1999
2000 if (setRestriction)
2001 RINOK(setRestriction->SetRestriction(0, 0))
2002
2003 return S_OK;
2004
1929 COM_TRY_END 2005 COM_TRY_END
1930} 2006}
1931 2007
diff --git a/CPP/7zip/Archive/Wim/WimIn.cpp b/CPP/7zip/Archive/Wim/WimIn.cpp
index f805521..ff118d8 100644
--- a/CPP/7zip/Archive/Wim/WimIn.cpp
+++ b/CPP/7zip/Archive/Wim/WimIn.cpp
@@ -99,7 +99,7 @@ HRESULT CUnpacker::UnpackChunk(
99 if (!packBuf.Data) 99 if (!packBuf.Data)
100 return E_OUTOFMEMORY; 100 return E_OUTOFMEMORY;
101 101
102 RINOK(ReadStream_FALSE(inStream, packBuf.Data, inSize)); 102 RINOK(ReadStream_FALSE(inStream, packBuf.Data, inSize))
103 103
104 TotalPacked += inSize; 104 TotalPacked += inSize;
105 105
@@ -124,7 +124,7 @@ HRESULT CUnpacker::UnpackChunk(
124 else 124 else
125 { 125 {
126 res = lzmsDecoder->Code(packBuf.Data, inSize, unpackBuf.Data, outSize); 126 res = lzmsDecoder->Code(packBuf.Data, inSize, unpackBuf.Data, outSize);
127 unpackedSize = lzmsDecoder->GetUnpackSize();; 127 unpackedSize = lzmsDecoder->GetUnpackSize();
128 } 128 }
129 } 129 }
130 130
@@ -141,7 +141,7 @@ HRESULT CUnpacker::UnpackChunk(
141 141
142 if (outStream) 142 if (outStream)
143 { 143 {
144 RINOK(WriteStream(outStream, unpackBuf.Data, outSize)); 144 RINOK(WriteStream(outStream, unpackBuf.Data, outSize))
145 } 145 }
146 146
147 return res; 147 return res;
@@ -168,7 +168,7 @@ HRESULT CUnpacker::Unpack2(
168 CMyComPtr<ISequentialInStream> limitedStream = limitedStreamSpec; 168 CMyComPtr<ISequentialInStream> limitedStream = limitedStreamSpec;
169 limitedStreamSpec->SetStream(inStream); 169 limitedStreamSpec->SetStream(inStream);
170 170
171 RINOK(inStream->Seek(resource.Offset, STREAM_SEEK_SET, NULL)); 171 RINOK(InStream_SeekSet(inStream, resource.Offset))
172 if (resource.PackSize != resource.UnpackSize) 172 if (resource.PackSize != resource.UnpackSize)
173 return S_FALSE; 173 return S_FALSE;
174 174
@@ -221,7 +221,7 @@ HRESULT CUnpacker::Unpack2(
221 size_t cur = chunkSize - offsetInChunk; 221 size_t cur = chunkSize - offsetInChunk;
222 if (cur > rem) 222 if (cur > rem)
223 cur = (size_t)rem; 223 cur = (size_t)rem;
224 RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)); 224 RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur))
225 outProcessed += cur; 225 outProcessed += cur;
226 rem -= cur; 226 rem -= cur;
227 offsetInChunk = 0; 227 offsetInChunk = 0;
@@ -233,20 +233,20 @@ HRESULT CUnpacker::Unpack2(
233 if (rem == 0) 233 if (rem == 0)
234 return S_OK; 234 return S_OK;
235 235
236 UInt64 offset = ss.Chunks[chunkIndex]; 236 const UInt64 offset = ss.Chunks[chunkIndex];
237 UInt64 packSize = ss.GetChunkPackSize(chunkIndex); 237 const UInt64 packSize = ss.GetChunkPackSize(chunkIndex);
238 const CResource &rs = db->DataStreams[ss.StreamIndex].Resource; 238 const CResource &rs = db->DataStreams[ss.StreamIndex].Resource;
239 RINOK(inStream->Seek(rs.Offset + ss.HeadersSize + offset, STREAM_SEEK_SET, NULL)); 239 RINOK(InStream_SeekSet(inStream, rs.Offset + ss.HeadersSize + offset))
240 240
241 size_t cur = chunkSize; 241 size_t cur = chunkSize;
242 UInt64 unpackRem = ss.UnpackSize - ((UInt64)chunkIndex << chunkSizeBits); 242 const UInt64 unpackRem = ss.UnpackSize - ((UInt64)chunkIndex << chunkSizeBits);
243 if (cur > unpackRem) 243 if (cur > unpackRem)
244 cur = (size_t)unpackRem; 244 cur = (size_t)unpackRem;
245 245
246 _solidIndex = -1; 246 _solidIndex = -1;
247 _unpackedChunkIndex = 0; 247 _unpackedChunkIndex = 0;
248 248
249 HRESULT res = UnpackChunk(inStream, ss.Method, chunkSizeBits, (size_t)packSize, cur, NULL); 249 const HRESULT res = UnpackChunk(inStream, (unsigned)ss.Method, chunkSizeBits, (size_t)packSize, cur, NULL);
250 250
251 if (res != S_OK) 251 if (res != S_OK)
252 { 252 {
@@ -266,11 +266,11 @@ HRESULT CUnpacker::Unpack2(
266 if (cur > rem) 266 if (cur > rem)
267 cur = (size_t)rem; 267 cur = (size_t)rem;
268 268
269 RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur)); 269 RINOK(WriteStream(outStream, unpackBuf.Data + offsetInChunk, cur))
270 270
271 if (progress) 271 if (progress)
272 { 272 {
273 RINOK(progress->SetRatioInfo(&packProcessed, &outProcessed)); 273 RINOK(progress->SetRatioInfo(&packProcessed, &outProcessed))
274 packProcessed += packSize; 274 packProcessed += packSize;
275 outProcessed += cur; 275 outProcessed += cur;
276 } 276 }
@@ -311,8 +311,8 @@ HRESULT CUnpacker::Unpack2(
311 if (sizesBufSize != sizesBufSize64) 311 if (sizesBufSize != sizesBufSize64)
312 return E_OUTOFMEMORY; 312 return E_OUTOFMEMORY;
313 sizesBuf.AllocAtLeast(sizesBufSize); 313 sizesBuf.AllocAtLeast(sizesBufSize);
314 RINOK(inStream->Seek(baseOffset, STREAM_SEEK_SET, NULL)); 314 RINOK(InStream_SeekSet(inStream, baseOffset))
315 RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)); 315 RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize))
316 baseOffset += sizesBufSize64; 316 baseOffset += sizesBufSize64;
317 numChunks = (size_t)numChunks64; 317 numChunks = (size_t)numChunks64;
318 } 318 }
@@ -341,11 +341,11 @@ HRESULT CUnpacker::Unpack2(
341 if (inSize != inSize64) 341 if (inSize != inSize64)
342 return S_FALSE; 342 return S_FALSE;
343 343
344 RINOK(inStream->Seek(baseOffset + offset, STREAM_SEEK_SET, NULL)); 344 RINOK(InStream_SeekSet(inStream, baseOffset + offset))
345 345
346 if (progress) 346 if (progress)
347 { 347 {
348 RINOK(progress->SetRatioInfo(&offset, &outProcessed)); 348 RINOK(progress->SetRatioInfo(&offset, &outProcessed))
349 } 349 }
350 350
351 size_t outSize = (size_t)1 << chunkSizeBits; 351 size_t outSize = (size_t)1 << chunkSizeBits;
@@ -353,7 +353,7 @@ HRESULT CUnpacker::Unpack2(
353 if (outSize > rem) 353 if (outSize > rem)
354 outSize = (size_t)rem; 354 outSize = (size_t)rem;
355 355
356 RINOK(UnpackChunk(inStream, header.GetMethod(), chunkSizeBits, inSize, outSize, outStream)); 356 RINOK(UnpackChunk(inStream, header.GetMethod(), chunkSizeBits, inSize, outSize, outStream))
357 357
358 outProcessed += outSize; 358 outProcessed += outSize;
359 offset = nextOffset; 359 offset = nextOffset;
@@ -494,8 +494,8 @@ void CDatabase::GetItemName(unsigned index, NWindows::NCOM::CPropVariant &name)
494void CDatabase::GetItemPath(unsigned index1, bool showImageNumber, NWindows::NCOM::CPropVariant &path) const 494void CDatabase::GetItemPath(unsigned index1, bool showImageNumber, NWindows::NCOM::CPropVariant &path) const
495{ 495{
496 unsigned size = 0; 496 unsigned size = 0;
497 int index = index1; 497 int index = (int)index1;
498 int imageIndex = Items[index].ImageIndex; 498 const int imageIndex = Items[index].ImageIndex;
499 const CImage &image = Images[imageIndex]; 499 const CImage &image = Images[imageIndex];
500 500
501 unsigned newLevel = 0; 501 unsigned newLevel = 0;
@@ -545,7 +545,7 @@ void CDatabase::GetItemPath(unsigned index1, bool showImageNumber, NWindows::NCO
545 else if (needColon) 545 else if (needColon)
546 s[0] = L':'; 546 s[0] = L':';
547 547
548 index = index1; 548 index = (int)index1;
549 wchar_t separator = 0; 549 wchar_t separator = 0;
550 550
551 for (;;) 551 for (;;)
@@ -597,7 +597,7 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent)
597 if (OpenCallback && (Items.Size() & 0xFFFF) == 0) 597 if (OpenCallback && (Items.Size() & 0xFFFF) == 0)
598 { 598 {
599 UInt64 numFiles = Items.Size(); 599 UInt64 numFiles = Items.Size();
600 RINOK(OpenCallback->SetCompleted(&numFiles, NULL)); 600 RINOK(OpenCallback->SetCompleted(&numFiles, NULL))
601 } 601 }
602 602
603 const size_t rem = DirSize - pos; 603 const size_t rem = DirSize - pos;
@@ -664,7 +664,7 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent)
664 664
665 item.Offset = pos; 665 item.Offset = pos;
666 item.Parent = parent; 666 item.Parent = parent;
667 item.ImageIndex = Images.Size() - 1; 667 item.ImageIndex = (int)Images.Size() - 1;
668 668
669 const unsigned prevIndex = Items.Add(item); 669 const unsigned prevIndex = Items.Add(item);
670 670
@@ -677,7 +677,8 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent)
677 return S_FALSE; 677 return S_FALSE;
678 const Byte *p2 = DirData + pos; 678 const Byte *p2 = DirData + pos;
679 const UInt64 len2 = Get64(p2); 679 const UInt64 len2 = Get64(p2);
680 if ((len2 & align) != 0 || rem2 < len2 || len2 < (IsOldVersion ? 0x18 : 0x28)) 680 if ((len2 & align) != 0 || rem2 < len2
681 || len2 < (unsigned)(IsOldVersion ? 0x18 : 0x28))
681 return S_FALSE; 682 return S_FALSE;
682 683
683 DirProcessed += (size_t)len2; 684 DirProcessed += (size_t)len2;
@@ -742,8 +743,8 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent)
742 CItem item2; 743 CItem item2;
743 item2.Offset = pos; 744 item2.Offset = pos;
744 item2.IsAltStream = true; 745 item2.IsAltStream = true;
745 item2.Parent = prevIndex; 746 item2.Parent = (int)prevIndex;
746 item2.ImageIndex = Images.Size() - 1; 747 item2.ImageIndex = (int)Images.Size() - 1;
747 Items.Add(item2); 748 Items.Add(item2);
748 } 749 }
749 750
@@ -775,7 +776,7 @@ HRESULT CDatabase::ParseDirItem(size_t pos, int parent)
775 776
776 if (item.IsDir && subdirOffset != 0) 777 if (item.IsDir && subdirOffset != 0)
777 { 778 {
778 RINOK(ParseDirItem((size_t)subdirOffset, prevIndex)); 779 RINOK(ParseDirItem((size_t)subdirOffset, (int)prevIndex))
779 } 780 }
780 } 781 }
781} 782}
@@ -864,7 +865,7 @@ HRESULT CDatabase::ParseImageDirs(CByteBuffer &buf, int parent)
864 DirStartOffset = DirProcessed = pos; 865 DirStartOffset = DirProcessed = pos;
865 image.StartItem = Items.Size(); 866 image.StartItem = Items.Size();
866 867
867 RINOK(ParseDirItem(pos, parent)); 868 RINOK(ParseDirItem(pos, parent))
868 869
869 image.NumItems = Items.Size() - image.StartItem; 870 image.NumItems = Items.Size() - image.StartItem;
870 if (DirProcessed == DirSize) 871 if (DirProcessed == DirSize)
@@ -899,27 +900,27 @@ HRESULT CHeader::Parse(const Byte *p, UInt64 &phySize)
899 ChunkSizeBits = kChunkSizeBits; 900 ChunkSizeBits = kChunkSizeBits;
900 if (ChunkSize != 0) 901 if (ChunkSize != 0)
901 { 902 {
902 int log = GetLog(ChunkSize); 903 const int log = GetLog(ChunkSize);
903 if (log < 12) 904 if (log < 12)
904 return S_FALSE; 905 return S_FALSE;
905 ChunkSizeBits = log; 906 ChunkSizeBits = (unsigned)log;
906 } 907 }
907 } 908 }
908 909
909 _IsOldVersion = false; 910 _isOldVersion = false;
910 _IsNewVersion = false; 911 _isNewVersion = false;
911 912
912 if (IsSolidVersion()) 913 if (IsSolidVersion())
913 _IsNewVersion = true; 914 _isNewVersion = true;
914 else 915 else
915 { 916 {
916 if (Version < 0x010900) 917 if (Version < 0x010900)
917 return S_FALSE; 918 return S_FALSE;
918 _IsOldVersion = (Version <= 0x010A00); 919 _isOldVersion = (Version <= 0x010A00);
919 // We don't know details about 1.11 version. So we use headerSize to guess exact features. 920 // We don't know details about 1.11 version. So we use headerSize to guess exact features.
920 if (Version == 0x010B00 && headerSize == 0x60) 921 if (Version == 0x010B00 && headerSize == 0x60)
921 _IsOldVersion = true; 922 _isOldVersion = true;
922 _IsNewVersion = (Version >= 0x010D00); 923 _isNewVersion = (Version >= 0x010D00);
923 } 924 }
924 925
925 unsigned offset; 926 unsigned offset;
@@ -973,7 +974,7 @@ const Byte kSignature[kSignatureSize] = { 'M', 'S', 'W', 'I', 'M', 0, 0, 0 };
973HRESULT ReadHeader(IInStream *inStream, CHeader &h, UInt64 &phySize) 974HRESULT ReadHeader(IInStream *inStream, CHeader &h, UInt64 &phySize)
974{ 975{
975 Byte p[kHeaderSizeMax]; 976 Byte p[kHeaderSizeMax];
976 RINOK(ReadStream_FALSE(inStream, p, kHeaderSizeMax)); 977 RINOK(ReadStream_FALSE(inStream, p, kHeaderSizeMax))
977 if (memcmp(p, kSignature, kSignatureSize) != 0) 978 if (memcmp(p, kSignature, kSignatureSize) != 0)
978 return S_FALSE; 979 return S_FALSE;
979 return h.Parse(p, phySize); 980 return h.Parse(p, phySize);
@@ -985,7 +986,7 @@ static HRESULT ReadStreams(IInStream *inStream, const CHeader &h, CDatabase &db)
985 CByteBuffer offsetBuf; 986 CByteBuffer offsetBuf;
986 987
987 CUnpacker unpacker; 988 CUnpacker unpacker;
988 RINOK(unpacker.UnpackData(inStream, h.OffsetResource, h, NULL, offsetBuf, NULL)); 989 RINOK(unpacker.UnpackData(inStream, h.OffsetResource, h, NULL, offsetBuf, NULL))
989 990
990 const size_t streamInfoSize = h.IsOldVersion() ? kStreamInfoSize + 2 : kStreamInfoSize; 991 const size_t streamInfoSize = h.IsOldVersion() ? kStreamInfoSize + 2 : kStreamInfoSize;
991 { 992 {
@@ -1087,7 +1088,7 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems
1087 IsOldVersion = h.IsOldVersion(); 1088 IsOldVersion = h.IsOldVersion();
1088 IsOldVersion9 = (h.Version == 0x10900); 1089 IsOldVersion9 = (h.Version == 0x10900);
1089 1090
1090 RINOK(ReadStreams(inStream, h, *this)); 1091 RINOK(ReadStreams(inStream, h, *this))
1091 1092
1092 bool needBootMetadata = !h.MetadataResource.IsEmpty(); 1093 bool needBootMetadata = !h.MetadataResource.IsEmpty();
1093 unsigned numNonDeletedImages = 0; 1094 unsigned numNonDeletedImages = 0;
@@ -1101,14 +1102,14 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems
1101 if (h.PartNumber != 1 || si.PartNumber != h.PartNumber) 1102 if (h.PartNumber != 1 || si.PartNumber != h.PartNumber)
1102 continue; 1103 continue;
1103 1104
1104 const int userImage = Images.Size() + GetStartImageIndex(); 1105 const unsigned userImage = Images.Size() + GetStartImageIndex();
1105 CImage &image = Images.AddNew(); 1106 CImage &image = Images.AddNew();
1106 SetRootNames(image, userImage); 1107 SetRootNames(image, userImage);
1107 1108
1108 CByteBuffer &metadata = image.Meta; 1109 CByteBuffer &metadata = image.Meta;
1109 Byte hash[kHashSize]; 1110 Byte hash[kHashSize];
1110 1111
1111 RINOK(unpacker.UnpackData(inStream, si.Resource, h, this, metadata, hash)); 1112 RINOK(unpacker.UnpackData(inStream, si.Resource, h, this, metadata, hash))
1112 1113
1113 if (memcmp(hash, si.Hash, kHashSize) != 0 && 1114 if (memcmp(hash, si.Hash, kHashSize) != 0 &&
1114 !(h.IsOldVersion() && IsEmptySha(si.Hash))) 1115 !(h.IsOldVersion() && IsEmptySha(si.Hash)))
@@ -1119,7 +1120,7 @@ HRESULT CDatabase::Open(IInStream *inStream, const CHeader &h, unsigned numItems
1119 if (Items.IsEmpty()) 1120 if (Items.IsEmpty())
1120 Items.ClearAndReserve(numItemsReserve); 1121 Items.ClearAndReserve(numItemsReserve);
1121 1122
1122 RINOK(ParseImageDirs(metadata, -1)); 1123 RINOK(ParseImageDirs(metadata, -1))
1123 1124
1124 if (needBootMetadata) 1125 if (needBootMetadata)
1125 { 1126 {
@@ -1166,12 +1167,12 @@ bool CDatabase::ItemHasStream(const CItem &item) const
1166} 1167}
1167 1168
1168 1169
1169#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } 1170#define RINOZ(x) { int _tt_ = (x); if (_tt_ != 0) return _tt_; }
1170 1171
1171static int CompareStreamsByPos(const CStreamInfo *p1, const CStreamInfo *p2, void * /* param */) 1172static int CompareStreamsByPos(const CStreamInfo *p1, const CStreamInfo *p2, void * /* param */)
1172{ 1173{
1173 RINOZ(MyCompare(p1->PartNumber, p2->PartNumber)); 1174 RINOZ(MyCompare(p1->PartNumber, p2->PartNumber))
1174 RINOZ(MyCompare(p1->Resource.Offset, p2->Resource.Offset)); 1175 RINOZ(MyCompare(p1->Resource.Offset, p2->Resource.Offset))
1175 return MyCompare(p1->Resource.PackSize, p2->Resource.PackSize); 1176 return MyCompare(p1->Resource.PackSize, p2->Resource.PackSize);
1176} 1177}
1177 1178
@@ -1192,11 +1193,11 @@ static int FindId(const CStreamInfo *streams, const CUIntVector &sorted, UInt32
1192 unsigned left = 0, right = sorted.Size(); 1193 unsigned left = 0, right = sorted.Size();
1193 while (left != right) 1194 while (left != right)
1194 { 1195 {
1195 unsigned mid = (left + right) / 2; 1196 const unsigned mid = (left + right) / 2;
1196 unsigned streamIndex = sorted[mid]; 1197 const unsigned streamIndex = sorted[mid];
1197 UInt32 id2 = streams[streamIndex].Id; 1198 const UInt32 id2 = streams[streamIndex].Id;
1198 if (id == id2) 1199 if (id == id2)
1199 return streamIndex; 1200 return (int)streamIndex;
1200 if (id < id2) 1201 if (id < id2)
1201 right = mid; 1202 right = mid;
1202 else 1203 else
@@ -1210,15 +1211,15 @@ static int FindHash(const CStreamInfo *streams, const CUIntVector &sorted, const
1210 unsigned left = 0, right = sorted.Size(); 1211 unsigned left = 0, right = sorted.Size();
1211 while (left != right) 1212 while (left != right)
1212 { 1213 {
1213 unsigned mid = (left + right) / 2; 1214 const unsigned mid = (left + right) / 2;
1214 unsigned streamIndex = sorted[mid]; 1215 const unsigned streamIndex = sorted[mid];
1215 const Byte *hash2 = streams[streamIndex].Hash; 1216 const Byte *hash2 = streams[streamIndex].Hash;
1216 unsigned i; 1217 unsigned i;
1217 for (i = 0; i < kHashSize; i++) 1218 for (i = 0; i < kHashSize; i++)
1218 if (hash[i] != hash2[i]) 1219 if (hash[i] != hash2[i])
1219 break; 1220 break;
1220 if (i == kHashSize) 1221 if (i == kHashSize)
1221 return streamIndex; 1222 return (int)streamIndex;
1222 if (hash[i] < hash2[i]) 1223 if (hash[i] < hash2[i])
1223 right = mid; 1224 right = mid;
1224 else 1225 else
@@ -1237,8 +1238,8 @@ static int CompareItems(const unsigned *a1, const unsigned *a2, void *param)
1237 return i1.IsDir ? -1 : 1; 1238 return i1.IsDir ? -1 : 1;
1238 if (i1.IsAltStream != i2.IsAltStream) 1239 if (i1.IsAltStream != i2.IsAltStream)
1239 return i1.IsAltStream ? 1 : -1; 1240 return i1.IsAltStream ? 1 : -1;
1240 RINOZ(MyCompare(i1.StreamIndex, i2.StreamIndex)); 1241 RINOZ(MyCompare(i1.StreamIndex, i2.StreamIndex))
1241 RINOZ(MyCompare(i1.ImageIndex, i2.ImageIndex)); 1242 RINOZ(MyCompare(i1.ImageIndex, i2.ImageIndex))
1242 return MyCompare(i1.Offset, i2.Offset); 1243 return MyCompare(i1.Offset, i2.Offset);
1243} 1244}
1244 1245
@@ -1286,7 +1287,7 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1286 if (si.RefCount != 1) 1287 if (si.RefCount != 1)
1287 return S_FALSE; 1288 return S_FALSE;
1288 1289
1289 r.SolidIndex = Solids.Size(); 1290 r.SolidIndex = (int)Solids.Size();
1290 1291
1291 CSolid &ss = Solids.AddNew(); 1292 CSolid &ss = Solids.AddNew();
1292 ss.StreamIndex = k; 1293 ss.StreamIndex = k;
@@ -1300,8 +1301,8 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1300 1301
1301 const CVolume &vol = volumes[si.PartNumber]; 1302 const CVolume &vol = volumes[si.PartNumber];
1302 IInStream *inStream = vol.Stream; 1303 IInStream *inStream = vol.Stream;
1303 RINOK(inStream->Seek(r.Offset, STREAM_SEEK_SET, NULL)); 1304 RINOK(InStream_SeekSet(inStream, r.Offset))
1304 RINOK(ReadStream_FALSE(inStream, (Byte *)header, kSolidHeaderSize)); 1305 RINOK(ReadStream_FALSE(inStream, (Byte *)header, kSolidHeaderSize))
1305 1306
1306 ss.UnpackSize = GetUi64(header); 1307 ss.UnpackSize = GetUi64(header);
1307 1308
@@ -1313,11 +1314,11 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1313 return S_FALSE; 1314 return S_FALSE;
1314 1315
1315 const UInt32 solidChunkSize = GetUi32(header + 8); 1316 const UInt32 solidChunkSize = GetUi32(header + 8);
1316 int log = GetLog(solidChunkSize); 1317 const int log = GetLog(solidChunkSize);
1317 if (log < 8 || log > 31) 1318 if (log < 8 || log > 31)
1318 return S_FALSE; 1319 return S_FALSE;
1319 ss.ChunkSizeBits = log; 1320 ss.ChunkSizeBits = (unsigned)log;
1320 ss.Method = GetUi32(header + 12); 1321 ss.Method = (Int32)GetUi32(header + 12);
1321 1322
1322 UInt64 numChunks64 = (ss.UnpackSize + (((UInt32)1 << ss.ChunkSizeBits) - 1)) >> ss.ChunkSizeBits; 1323 UInt64 numChunks64 = (ss.UnpackSize + (((UInt32)1 << ss.ChunkSizeBits) - 1)) >> ss.ChunkSizeBits;
1323 UInt64 sizesBufSize64 = 4 * numChunks64; 1324 UInt64 sizesBufSize64 = 4 * numChunks64;
@@ -1327,7 +1328,7 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1327 return E_OUTOFMEMORY; 1328 return E_OUTOFMEMORY;
1328 sizesBuf.AllocAtLeast(sizesBufSize); 1329 sizesBuf.AllocAtLeast(sizesBufSize);
1329 1330
1330 RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize)); 1331 RINOK(ReadStream_FALSE(inStream, sizesBuf, sizesBufSize))
1331 1332
1332 size_t numChunks = (size_t)numChunks64; 1333 size_t numChunks = (size_t)numChunks64;
1333 ss.Chunks.Alloc(numChunks + 1); 1334 ss.Chunks.Alloc(numChunks + 1);
@@ -1381,14 +1382,14 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1381 CSolid &ss = Solids[solidIndex]; 1382 CSolid &ss = Solids[solidIndex];
1382 if (r.Offset < ss.SolidOffset) 1383 if (r.Offset < ss.SolidOffset)
1383 return S_FALSE; 1384 return S_FALSE;
1384 UInt64 relat = r.Offset - ss.SolidOffset; 1385 const UInt64 relat = r.Offset - ss.SolidOffset;
1385 if (relat > ss.UnpackSize) 1386 if (relat > ss.UnpackSize)
1386 return S_FALSE; 1387 return S_FALSE;
1387 if (r.PackSize > ss.UnpackSize - relat) 1388 if (r.PackSize > ss.UnpackSize - relat)
1388 return S_FALSE; 1389 return S_FALSE;
1389 r.SolidIndex = solidIndex; 1390 r.SolidIndex = (int)solidIndex;
1390 if (ss.FirstSmallStream < 0) 1391 if (ss.FirstSmallStream < 0)
1391 ss.FirstSmallStream = k; 1392 ss.FirstSmallStream = (int)k;
1392 1393
1393 sortedByHash.AddInReserved(k); 1394 sortedByHash.AddInReserved(k);
1394 // ss.NumRefs++; 1395 // ss.NumRefs++;
@@ -1542,7 +1543,7 @@ HRESULT CDatabase::FillAndCheck(const CObjectVector<CVolume> &volumes)
1542 { 1543 {
1543 CItem item; 1544 CItem item;
1544 item.Offset = 0; 1545 item.Offset = 0;
1545 item.StreamIndex = i; 1546 item.StreamIndex = (int)i;
1546 item.ImageIndex = -1; 1547 item.ImageIndex = -1;
1547 Items.Add(item); 1548 Items.Add(item);
1548 ThereAreDeletedStreams = true; 1549 ThereAreDeletedStreams = true;
@@ -1591,7 +1592,7 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber)
1591 1592
1592 if (NumExcludededItems != 0) 1593 if (NumExcludededItems != 0)
1593 { 1594 {
1594 ExludedItem = startItem; 1595 ExludedItem = (int)startItem;
1595 startItem += NumExcludededItems; 1596 startItem += NumExcludededItems;
1596 } 1597 }
1597 1598
@@ -1603,7 +1604,7 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber)
1603 1604
1604 SortedItems.Sort(CompareItems, this); 1605 SortedItems.Sort(CompareItems, this);
1605 for (i = 0; i < SortedItems.Size(); i++) 1606 for (i = 0; i < SortedItems.Size(); i++)
1606 Items[SortedItems[i]].IndexInSorted = i; 1607 Items[SortedItems[i]].IndexInSorted = (int)i;
1607 1608
1608 if (showImageNumber) 1609 if (showImageNumber)
1609 for (i = 0; i < Images.Size(); i++) 1610 for (i = 0; i < Images.Size(); i++)
@@ -1611,7 +1612,7 @@ HRESULT CDatabase::GenerateSortedItems(int imageIndex, bool showImageNumber)
1611 CImage &image = Images[i]; 1612 CImage &image = Images[i];
1612 if (image.NumEmptyRootItems != 0) 1613 if (image.NumEmptyRootItems != 0)
1613 continue; 1614 continue;
1614 image.VirtualRootIndex = VirtualRoots.Size(); 1615 image.VirtualRootIndex = (int)VirtualRoots.Size();
1615 VirtualRoots.Add(i); 1616 VirtualRoots.Add(i);
1616 } 1617 }
1617 1618
@@ -1681,7 +1682,7 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector<CVolume> &volumes,
1681 if ((unpacker.TotalPacked - totalPackedPrev) >= ((UInt32)1 << 16)) 1682 if ((unpacker.TotalPacked - totalPackedPrev) >= ((UInt32)1 << 16))
1682 { 1683 {
1683 UInt64 numFiles = Items.Size(); 1684 UInt64 numFiles = Items.Size();
1684 RINOK(openCallback->SetCompleted(&numFiles, &unpacker.TotalPacked)); 1685 RINOK(openCallback->SetCompleted(&numFiles, &unpacker.TotalPacked))
1685 totalPackedPrev = unpacker.TotalPacked; 1686 totalPackedPrev = unpacker.TotalPacked;
1686 } 1687 }
1687 } 1688 }
@@ -1715,7 +1716,7 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector<CVolume> &volumes,
1715 if (res == S_FALSE) 1716 if (res == S_FALSE)
1716 continue; 1717 continue;
1717 1718
1718 RINOK(res); 1719 RINOK(res)
1719 1720
1720 if (memcmp(digest, si.Hash, kHashSize) != 0 1721 if (memcmp(digest, si.Hash, kHashSize) != 0
1721 // && !(h.IsOldVersion() && IsEmptySha(si.Hash)) 1722 // && !(h.IsOldVersion() && IsEmptySha(si.Hash))
@@ -1729,11 +1730,11 @@ HRESULT CDatabase::ExtractReparseStreams(const CObjectVector<CVolume> &volumes,
1729 CByteBuffer &reparse = ReparseItems.AddNew(); 1730 CByteBuffer &reparse = ReparseItems.AddNew();
1730 reparse.Alloc(8 + buf.Size()); 1731 reparse.Alloc(8 + buf.Size());
1731 Byte *dest = (Byte *)reparse; 1732 Byte *dest = (Byte *)reparse;
1732 SetUi32(dest, tag); 1733 SetUi32(dest, tag)
1733 SetUi32(dest + 4, (UInt32)buf.Size()); 1734 SetUi32(dest + 4, (UInt32)buf.Size())
1734 if (buf.Size() != 0) 1735 if (buf.Size() != 0)
1735 memcpy(dest + 8, buf, buf.Size()); 1736 memcpy(dest + 8, buf, buf.Size());
1736 ItemToReparse[itemIndex] = ReparseItems.Size() - 1; 1737 ItemToReparse[itemIndex] = (int)ReparseItems.Size() - 1;
1737 } 1738 }
1738 1739
1739 return S_OK; 1740 return S_OK;
@@ -1856,7 +1857,7 @@ bool CWimXml::Parse()
1856 return false; 1857 return false;
1857 } 1858 }
1858 1859
1859 imageInfo.ItemIndexInXml = i; 1860 imageInfo.ItemIndexInXml = (int)i;
1860 Images.Add(imageInfo); 1861 Images.Add(imageInfo);
1861 } 1862 }
1862 1863
diff --git a/CPP/7zip/Archive/Wim/WimIn.h b/CPP/7zip/Archive/Wim/WimIn.h
index 9e835b0..3de8456 100644
--- a/CPP/7zip/Archive/Wim/WimIn.h
+++ b/CPP/7zip/Archive/Wim/WimIn.h
@@ -1,7 +1,7 @@
1// Archive/WimIn.h 1// Archive/WimIn.h
2 2
3#ifndef __ARCHIVE_WIM_IN_H 3#ifndef ZIP7_INC_ARCHIVE_WIM_IN_H
4#define __ARCHIVE_WIM_IN_H 4#define ZIP7_INC_ARCHIVE_WIM_IN_H
5 5
6#include "../../../../C/Alloc.h" 6#include "../../../../C/Alloc.h"
7 7
@@ -192,7 +192,7 @@ struct CSolid
192 192
193 UInt64 UnpackSize; 193 UInt64 UnpackSize;
194 int Method; 194 int Method;
195 int ChunkSizeBits; 195 unsigned ChunkSizeBits;
196 196
197 UInt64 HeadersSize; 197 UInt64 HeadersSize;
198 // size_t NumChunks; 198 // size_t NumChunks;
@@ -258,8 +258,8 @@ struct CHeader
258 UInt32 NumImages; 258 UInt32 NumImages;
259 UInt32 BootIndex; 259 UInt32 BootIndex;
260 260
261 bool _IsOldVersion; // 1.10- 261 bool _isOldVersion; // 1.10-
262 bool _IsNewVersion; // 1.13+ or 0.14 262 bool _isNewVersion; // 1.13+ or 0.14
263 263
264 CResource OffsetResource; 264 CResource OffsetResource;
265 CResource XmlResource; 265 CResource XmlResource;
@@ -295,8 +295,8 @@ struct CHeader
295 return mask; 295 return mask;
296 } 296 }
297 297
298 bool IsOldVersion() const { return _IsOldVersion; } 298 bool IsOldVersion() const { return _isOldVersion; }
299 bool IsNewVersion() const { return _IsNewVersion; } 299 bool IsNewVersion() const { return _isNewVersion; }
300 bool IsSolidVersion() const { return (Version == k_Version_Solid); } 300 bool IsSolidVersion() const { return (Version == k_Version_Solid); }
301 301
302 bool AreFromOnArchive(const CHeader &h) 302 bool AreFromOnArchive(const CHeader &h)
@@ -457,7 +457,7 @@ public:
457 bool RefCountError; 457 bool RefCountError;
458 bool HeadersError; 458 bool HeadersError;
459 459
460 bool GetStartImageIndex() const { return IsOldVersion9 ? 0 : 1; } 460 unsigned GetStartImageIndex() const { return IsOldVersion9 ? 0 : 1; }
461 unsigned GetDirAlignMask() const { return IsOldVersion9 ? 3 : 7; } 461 unsigned GetDirAlignMask() const { return IsOldVersion9 ? 3 : 7; }
462 462
463 // User Items can contain all images or just one image from all. 463 // 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 b5a1972..c03128f 100644
--- a/CPP/7zip/Archive/XarHandler.cpp
+++ b/CPP/7zip/Archive/XarHandler.cpp
@@ -103,11 +103,10 @@ struct CFile
103 } 103 }
104}; 104};
105 105
106class CHandler: 106
107 public IInArchive, 107Z7_CLASS_IMP_CHandler_IInArchive_1(
108 public IInArchiveGetStream, 108 IInArchiveGetStream
109 public CMyUnknownImp 109)
110{
111 UInt64 _dataStartPos; 110 UInt64 _dataStartPos;
112 CMyComPtr<IInStream> _inStream; 111 CMyComPtr<IInStream> _inStream;
113 CByteArr _xml; 112 CByteArr _xml;
@@ -120,10 +119,6 @@ class CHandler:
120 119
121 HRESULT Open2(IInStream *stream); 120 HRESULT Open2(IInStream *stream);
122 HRESULT Extract(IInStream *stream); 121 HRESULT Extract(IInStream *stream);
123public:
124 MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
125 INTERFACE_IInArchive(;)
126 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
127}; 122};
128 123
129static const Byte kArcProps[] = 124static const Byte kArcProps[] =
@@ -187,7 +182,7 @@ static UInt64 ParseTime(const CXmlItem &item, const char *name)
187 return numSecs * 10000000; 182 return numSecs * 10000000;
188} 183}
189 184
190static int HexToByte(unsigned char c) 185static int HexToByte(char c)
191{ 186{
192 if (c >= '0' && c <= '9') return c - '0'; 187 if (c >= '0' && c <= '9') return c - '0';
193 if (c >= 'A' && c <= 'F') return c - 'A' + 10; 188 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
@@ -197,7 +192,7 @@ static int HexToByte(unsigned char c)
197 192
198static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest) 193static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest)
199{ 194{
200 int index = item.FindSubTag(name); 195 const int index = item.FindSubTag(name);
201 if (index < 0) 196 if (index < 0)
202 return false; 197 return false;
203 const CXmlItem &checkItem = item.SubItems[index]; 198 const CXmlItem &checkItem = item.SubItems[index];
@@ -209,8 +204,8 @@ static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest)
209 return false; 204 return false;
210 for (unsigned i = 0; i < s.Len(); i += 2) 205 for (unsigned i = 0; i < s.Len(); i += 2)
211 { 206 {
212 int b0 = HexToByte(s[i]); 207 const int b0 = HexToByte(s[i]);
213 int b1 = HexToByte(s[i + 1]); 208 const int b1 = HexToByte(s[i + 1]);
214 if (b0 < 0 || b1 < 0) 209 if (b0 < 0 || b1 < 0)
215 return false; 210 return false;
216 digest[i / 2] = (Byte)((b0 << 4) | b1); 211 digest[i / 2] = (Byte)((b0 << 4) | b1);
@@ -228,7 +223,7 @@ static bool AddItem(const CXmlItem &item, CObjectVector<CFile> &files, int paren
228 { 223 {
229 CFile file; 224 CFile file;
230 file.Parent = parent; 225 file.Parent = parent;
231 parent = files.Size(); 226 parent = (int)files.Size();
232 file.Name = item.GetSubStringForTag("name"); 227 file.Name = item.GetSubStringForTag("name");
233 const AString type (item.GetSubStringForTag("type")); 228 const AString type (item.GetSubStringForTag("type"));
234 if (type == "directory") 229 if (type == "directory")
@@ -307,8 +302,7 @@ HRESULT CHandler::Open2(IInStream *stream)
307{ 302{
308 const UInt32 kHeaderSize = 0x1C; 303 const UInt32 kHeaderSize = 0x1C;
309 Byte buf[kHeaderSize]; 304 Byte buf[kHeaderSize];
310 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize)); 305 RINOK(ReadStream_FALSE(stream, buf, kHeaderSize))
311
312 UInt32 size = Get16(buf + 4); 306 UInt32 size = Get16(buf + 4);
313 // UInt32 ver = Get16(buf + 6); // == 1 307 // UInt32 ver = Get16(buf + 6); // == 1
314 if (Get32(buf) != 0x78617221 || size != kHeaderSize) 308 if (Get32(buf) != 0x78617221 || size != kHeaderSize)
@@ -341,7 +335,7 @@ HRESULT CHandler::Open2(IInStream *stream)
341 CMyComPtr<ISequentialOutStream> outStreamLim(outStreamLimSpec); 335 CMyComPtr<ISequentialOutStream> outStreamLim(outStreamLimSpec);
342 outStreamLimSpec->Init(_xml, (size_t)unpackSize); 336 outStreamLimSpec->Init(_xml, (size_t)unpackSize);
343 337
344 RINOK(zlibCoder->Code(inStreamLim, outStreamLim, NULL, NULL, NULL)); 338 RINOK(zlibCoder->Code(inStreamLim, outStreamLim, NULL, NULL, NULL))
345 339
346 if (outStreamLimSpec->GetPos() != (size_t)unpackSize) 340 if (outStreamLimSpec->GetPos() != (size_t)unpackSize)
347 return S_FALSE; 341 return S_FALSE;
@@ -370,7 +364,7 @@ HRESULT CHandler::Open2(IInStream *stream)
370 file.UpdateTotalPackSize(totalPackSize); 364 file.UpdateTotalPackSize(totalPackSize);
371 if (file.Name == "Payload" || file.Name == "Content") 365 if (file.Name == "Payload" || file.Name == "Content")
372 { 366 {
373 _mainSubfile = i; 367 _mainSubfile = (Int32)(int)i;
374 numMainFiles++; 368 numMainFiles++;
375 } 369 }
376 else if (file.Name == "PackageInfo") 370 else if (file.Name == "PackageInfo")
@@ -385,9 +379,9 @@ HRESULT CHandler::Open2(IInStream *stream)
385 return S_OK; 379 return S_OK;
386} 380}
387 381
388STDMETHODIMP CHandler::Open(IInStream *stream, 382Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
389 const UInt64 * /* maxCheckStartPosition */, 383 const UInt64 * /* maxCheckStartPosition */,
390 IArchiveOpenCallback * /* openArchiveCallback */) 384 IArchiveOpenCallback * /* openArchiveCallback */))
391{ 385{
392 COM_TRY_BEGIN 386 COM_TRY_BEGIN
393 { 387 {
@@ -400,7 +394,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
400 COM_TRY_END 394 COM_TRY_END
401} 395}
402 396
403STDMETHODIMP CHandler::Close() 397Z7_COM7F_IMF(CHandler::Close())
404{ 398{
405 _phySize = 0; 399 _phySize = 0;
406 _inStream.Release(); 400 _inStream.Release();
@@ -412,7 +406,7 @@ STDMETHODIMP CHandler::Close()
412 return S_OK; 406 return S_OK;
413} 407}
414 408
415STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 409Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
416{ 410{
417 *numItems = _files.Size() 411 *numItems = _files.Size()
418 #ifdef XAR_SHOW_RAW 412 #ifdef XAR_SHOW_RAW
@@ -443,7 +437,7 @@ static void Utf8StringToProp(const AString &s, NCOM::CPropVariant &prop)
443 } 437 }
444} 438}
445 439
446STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 440Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
447{ 441{
448 COM_TRY_BEGIN 442 COM_TRY_BEGIN
449 NCOM::CPropVariant prop; 443 NCOM::CPropVariant prop;
@@ -460,7 +454,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
460 COM_TRY_END 454 COM_TRY_END
461} 455}
462 456
463STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 457Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
464{ 458{
465 COM_TRY_BEGIN 459 COM_TRY_BEGIN
466 NCOM::CPropVariant prop; 460 NCOM::CPropVariant prop;
@@ -486,8 +480,8 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
486 case kpidPath: 480 case kpidPath:
487 { 481 {
488 AString path; 482 AString path;
489 int cur = index; 483 unsigned cur = index;
490 do 484 for (;;)
491 { 485 {
492 const CFile &item2 = _files[cur]; 486 const CFile &item2 = _files[cur];
493 if (!path.IsEmpty()) 487 if (!path.IsEmpty())
@@ -496,9 +490,10 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
496 path.Insert(0, "unknown"); 490 path.Insert(0, "unknown");
497 else 491 else
498 path.Insert(0, item2.Name); 492 path.Insert(0, item2.Name);
499 cur = item2.Parent; 493 cur = (unsigned)item2.Parent;
494 if (item2.Parent < 0)
495 break;
500 } 496 }
501 while (cur >= 0);
502 497
503 Utf8StringToProp(path, prop); 498 Utf8StringToProp(path, prop);
504 break; 499 break;
@@ -529,11 +524,11 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
529 COM_TRY_END 524 COM_TRY_END
530} 525}
531 526
532STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 527Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
533 Int32 testMode, IArchiveExtractCallback *extractCallback) 528 Int32 testMode, IArchiveExtractCallback *extractCallback))
534{ 529{
535 COM_TRY_BEGIN 530 COM_TRY_BEGIN
536 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 531 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
537 if (allFilesMode) 532 if (allFilesMode)
538 numItems = _files.Size(); 533 numItems = _files.Size();
539 if (numItems == 0) 534 if (numItems == 0)
@@ -597,28 +592,28 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
597 lps->OutSize = currentUnpTotal; 592 lps->OutSize = currentUnpTotal;
598 currentPackSize = 0; 593 currentPackSize = 0;
599 currentUnpSize = 0; 594 currentUnpSize = 0;
600 RINOK(lps->SetCur()); 595 RINOK(lps->SetCur())
601 CMyComPtr<ISequentialOutStream> realOutStream; 596 CMyComPtr<ISequentialOutStream> realOutStream;
602 Int32 askMode = testMode ? 597 const Int32 askMode = testMode ?
603 NExtract::NAskMode::kTest : 598 NExtract::NAskMode::kTest :
604 NExtract::NAskMode::kExtract; 599 NExtract::NAskMode::kExtract;
605 UInt32 index = allFilesMode ? i : indices[i]; 600 const UInt32 index = allFilesMode ? i : indices[i];
606 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 601 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
607 602
608 if (index < _files.Size()) 603 if (index < _files.Size())
609 { 604 {
610 const CFile &item = _files[index]; 605 const CFile &item = _files[index];
611 if (item.IsDir) 606 if (item.IsDir)
612 { 607 {
613 RINOK(extractCallback->PrepareOperation(askMode)); 608 RINOK(extractCallback->PrepareOperation(askMode))
614 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 609 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
615 continue; 610 continue;
616 } 611 }
617 } 612 }
618 613
619 if (!testMode && !realOutStream) 614 if (!testMode && !realOutStream)
620 continue; 615 continue;
621 RINOK(extractCallback->PrepareOperation(askMode)); 616 RINOK(extractCallback->PrepareOperation(askMode))
622 617
623 outStreamSha1Spec->SetStream(realOutStream); 618 outStreamSha1Spec->SetStream(realOutStream);
624 realOutStream.Release(); 619 realOutStream.Release();
@@ -629,7 +624,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
629 { 624 {
630 outStreamSha1Spec->Init(false); 625 outStreamSha1Spec->Init(false);
631 outStreamLimSpec->Init(_xmlLen); 626 outStreamLimSpec->Init(_xmlLen);
632 RINOK(WriteStream(outStream, _xml, _xmlLen)); 627 RINOK(WriteStream(outStream, _xml, _xmlLen))
633 currentPackSize = currentUnpSize = _xmlLen; 628 currentPackSize = currentUnpSize = _xmlLen;
634 } 629 }
635 else 630 else
@@ -641,7 +636,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
641 currentPackSize = item.PackSize; 636 currentPackSize = item.PackSize;
642 currentUnpSize = item.Size; 637 currentUnpSize = item.Size;
643 638
644 RINOK(_inStream->Seek(_dataStartPos + item.Offset, STREAM_SEEK_SET, NULL)); 639 RINOK(InStream_SeekSet(_inStream, _dataStartPos + item.Offset))
645 inStreamSpec->Init(item.PackSize); 640 inStreamSpec->Init(item.PackSize);
646 outStreamSha1Spec->Init(item.Sha1IsDefined); 641 outStreamSha1Spec->Init(item.Sha1IsDefined);
647 outStreamLimSpec->Init(item.Size); 642 outStreamLimSpec->Init(item.Size);
@@ -696,13 +691,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
696 } 691 }
697 } 692 }
698 outStreamSha1Spec->ReleaseStream(); 693 outStreamSha1Spec->ReleaseStream();
699 RINOK(extractCallback->SetOperationResult(opRes)); 694 RINOK(extractCallback->SetOperationResult(opRes))
700 } 695 }
701 return S_OK; 696 return S_OK;
702 COM_TRY_END 697 COM_TRY_END
703} 698}
704 699
705STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 700Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
706{ 701{
707 *stream = NULL; 702 *stream = NULL;
708 COM_TRY_BEGIN 703 COM_TRY_BEGIN
@@ -726,7 +721,7 @@ STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
726static const Byte k_Signature[] = { 'x', 'a', 'r', '!', 0, 0x1C }; 721static const Byte k_Signature[] = { 'x', 'a', 'r', '!', 0, 0x1C };
727 722
728REGISTER_ARC_I( 723REGISTER_ARC_I(
729 "Xar", "xar pkg xip", 0, 0xE1, 724 "Xar", "xar pkg xip", NULL, 0xE1,
730 k_Signature, 725 k_Signature,
731 0, 726 0,
732 0, 727 0,
diff --git a/CPP/7zip/Archive/XzHandler.cpp b/CPP/7zip/Archive/XzHandler.cpp
index d358ca5..976817c 100644
--- a/CPP/7zip/Archive/XzHandler.cpp
+++ b/CPP/7zip/Archive/XzHandler.cpp
@@ -43,24 +43,39 @@ struct CBlockInfo
43}; 43};
44 44
45 45
46class CHandler: 46Z7_class_CHandler_final:
47 public IInArchive, 47 public IInArchive,
48 public IArchiveOpenSeq, 48 public IArchiveOpenSeq,
49 public IInArchiveGetStream, 49 public IInArchiveGetStream,
50 public ISetProperties, 50 public ISetProperties,
51 51 #ifndef Z7_EXTRACT_ONLY
52 #ifndef EXTRACT_ONLY
53 public IOutArchive, 52 public IOutArchive,
54 #endif 53 #endif
55
56 public CMyUnknownImp, 54 public CMyUnknownImp,
57 55 #ifndef Z7_EXTRACT_ONLY
58 #ifndef EXTRACT_ONLY 56 public CMultiMethodProps
59 public CMultiMethodProps 57 #else
60 #else 58 public CCommonMethodProps
61 public CCommonMethodProps 59 #endif
62 #endif
63{ 60{
61 Z7_COM_QI_BEGIN2(IInArchive)
62 Z7_COM_QI_ENTRY(IArchiveOpenSeq)
63 Z7_COM_QI_ENTRY(IInArchiveGetStream)
64 Z7_COM_QI_ENTRY(ISetProperties)
65 #ifndef Z7_EXTRACT_ONLY
66 Z7_COM_QI_ENTRY(IOutArchive)
67 #endif
68 Z7_COM_QI_END
69 Z7_COM_ADDREF_RELEASE
70
71 Z7_IFACE_COM7_IMP(IInArchive)
72 Z7_IFACE_COM7_IMP(IArchiveOpenSeq)
73 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
74 Z7_IFACE_COM7_IMP(ISetProperties)
75 #ifndef Z7_EXTRACT_ONLY
76 Z7_IFACE_COM7_IMP(IOutArchive)
77 #endif
78
64 CXzStatInfo _stat; // it's stat from backward parsing 79 CXzStatInfo _stat; // it's stat from backward parsing
65 CXzStatInfo _stat2; // it's data from forward parsing, if the decoder was called 80 CXzStatInfo _stat2; // it's data from forward parsing, if the decoder was called
66 SRes _stat2_decode_SRes; 81 SRes _stat2_decode_SRes;
@@ -81,7 +96,7 @@ class CHandler:
81 AString _methodsString; 96 AString _methodsString;
82 97
83 98
84 #ifndef EXTRACT_ONLY 99 #ifndef Z7_EXTRACT_ONLY
85 100
86 UInt32 _filterId; 101 UInt32 _filterId;
87 UInt64 _numSolidBytes; 102 UInt64 _numSolidBytes;
@@ -89,7 +104,7 @@ class CHandler:
89 void InitXz() 104 void InitXz()
90 { 105 {
91 _filterId = 0; 106 _filterId = 0;
92 _numSolidBytes = XZ_PROPS__BLOCK_SIZE__AUTO; 107 _numSolidBytes = XZ_PROPS_BLOCK_SIZE_AUTO;
93 } 108 }
94 109
95 #endif 110 #endif
@@ -97,7 +112,7 @@ class CHandler:
97 112
98 void Init() 113 void Init()
99 { 114 {
100 #ifndef EXTRACT_ONLY 115 #ifndef Z7_EXTRACT_ONLY
101 InitXz(); 116 InitXz();
102 CMultiMethodProps::Init(); 117 CMultiMethodProps::Init();
103 #else 118 #else
@@ -114,7 +129,7 @@ class CHandler:
114 ISequentialOutStream *outStream, 129 ISequentialOutStream *outStream,
115 ICompressProgressInfo *progress) 130 ICompressProgressInfo *progress)
116 { 131 {
117 #ifndef _7ZIP_ST 132 #ifndef Z7_ST
118 decoder._numThreads = _numThreads; 133 decoder._numThreads = _numThreads;
119 #endif 134 #endif
120 decoder._memUsage = _memUsage_Decompress; 135 decoder._memUsage = _memUsage_Decompress;
@@ -140,25 +155,6 @@ class CHandler:
140 } 155 }
141 156
142public: 157public:
143 MY_QUERYINTERFACE_BEGIN2(IInArchive)
144 MY_QUERYINTERFACE_ENTRY(IArchiveOpenSeq)
145 MY_QUERYINTERFACE_ENTRY(IInArchiveGetStream)
146 MY_QUERYINTERFACE_ENTRY(ISetProperties)
147 #ifndef EXTRACT_ONLY
148 MY_QUERYINTERFACE_ENTRY(IOutArchive)
149 #endif
150 MY_QUERYINTERFACE_END
151 MY_ADDREF_RELEASE
152
153 INTERFACE_IInArchive(;)
154 STDMETHOD(OpenSeq)(ISequentialInStream *stream);
155 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
156 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
157
158 #ifndef EXTRACT_ONLY
159 INTERFACE_IOutArchive(;)
160 #endif
161
162 CBlockInfo *_blocks; 158 CBlockInfo *_blocks;
163 size_t _blocksArraySize; 159 size_t _blocksArraySize;
164 UInt64 _maxBlocksSize; 160 UInt64 _maxBlocksSize;
@@ -172,7 +168,7 @@ public:
172 168
173 HRESULT SeekToPackPos(UInt64 pos) 169 HRESULT SeekToPackPos(UInt64 pos)
174 { 170 {
175 return _stream->Seek((Int64)pos, STREAM_SEEK_SET, NULL); 171 return InStream_SeekSet(_stream, pos);
176 } 172 }
177}; 173};
178 174
@@ -181,7 +177,7 @@ CHandler::CHandler():
181 _blocks(NULL), 177 _blocks(NULL),
182 _blocksArraySize(0) 178 _blocksArraySize(0)
183{ 179{
184 #ifndef EXTRACT_ONLY 180 #ifndef Z7_EXTRACT_ONLY
185 InitXz(); 181 InitXz();
186 #endif 182 #endif
187} 183}
@@ -259,13 +255,14 @@ static const CMethodNamePair g_NamePairs[] =
259 { XZ_ID_ARM, "ARM" }, 255 { XZ_ID_ARM, "ARM" },
260 { XZ_ID_ARMT, "ARMT" }, 256 { XZ_ID_ARMT, "ARMT" },
261 { XZ_ID_SPARC, "SPARC" }, 257 { XZ_ID_SPARC, "SPARC" },
258 { XZ_ID_ARM64, "ARM64" },
262 { XZ_ID_LZMA2, "LZMA2" } 259 { XZ_ID_LZMA2, "LZMA2" }
263}; 260};
264 261
265static void AddMethodString(AString &s, const CXzFilter &f) 262static void AddMethodString(AString &s, const CXzFilter &f)
266{ 263{
267 const char *p = NULL; 264 const char *p = NULL;
268 for (unsigned i = 0; i < ARRAY_SIZE(g_NamePairs); i++) 265 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NamePairs); i++)
269 if (g_NamePairs[i].Id == f.id) 266 if (g_NamePairs[i].Id == f.id)
270 { 267 {
271 p = g_NamePairs[i].Name; 268 p = g_NamePairs[i].Name;
@@ -287,6 +284,8 @@ static void AddMethodString(AString &s, const CXzFilter &f)
287 Lzma2PropToString(s, f.props[0]); 284 Lzma2PropToString(s, f.props[0]);
288 else if (f.id == XZ_ID_Delta && f.propsSize == 1) 285 else if (f.id == XZ_ID_Delta && f.propsSize == 1)
289 s.Add_UInt32((UInt32)f.props[0] + 1); 286 s.Add_UInt32((UInt32)f.props[0] + 1);
287 else if (f.id == XZ_ID_ARM64 && f.propsSize == 1)
288 s.Add_UInt32((UInt32)f.props[0] + 16 + 2);
290 else 289 else
291 { 290 {
292 s += '['; 291 s += '[';
@@ -337,7 +336,7 @@ static void AddCheckString(AString &s, const CXzs &xzs)
337 } 336 }
338} 337}
339 338
340STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 339Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
341{ 340{
342 COM_TRY_BEGIN 341 COM_TRY_BEGIN
343 NCOM::CPropVariant prop; 342 NCOM::CPropVariant prop;
@@ -394,13 +393,13 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
394 COM_TRY_END 393 COM_TRY_END
395} 394}
396 395
397STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 396Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
398{ 397{
399 *numItems = 1; 398 *numItems = 1;
400 return S_OK; 399 return S_OK;
401} 400}
402 401
403STDMETHODIMP CHandler::GetProperty(UInt32, PROPID propID, PROPVARIANT *value) 402Z7_COM7F_IMF(CHandler::GetProperty(UInt32, PROPID propID, PROPVARIANT *value))
404{ 403{
405 COM_TRY_BEGIN 404 COM_TRY_BEGIN
406 const CXzStatInfo *stat = GetStat(); 405 const CXzStatInfo *stat = GetStat();
@@ -427,9 +426,9 @@ struct COpenCallbackWrap
427 void Init(IArchiveOpenCallback *progress); 426 void Init(IArchiveOpenCallback *progress);
428}; 427};
429 428
430static SRes OpenCallbackProgress(const ICompressProgress *pp, UInt64 inSize, UInt64 /* outSize */) 429static SRes OpenCallbackProgress(ICompressProgressPtr pp, UInt64 inSize, UInt64 /* outSize */)
431{ 430{
432 COpenCallbackWrap *p = CONTAINER_FROM_VTBL(pp, COpenCallbackWrap, vt); 431 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(COpenCallbackWrap)
433 if (p->OpenCallback) 432 if (p->OpenCallback)
434 p->Res = p->OpenCallback->SetCompleted(NULL, &inSize); 433 p->Res = p->OpenCallback->SetCompleted(NULL, &inSize);
435 return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS); 434 return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS);
@@ -551,10 +550,10 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal
551 } 550 }
552 } 551 }
553 552
554 RINOK(inStream->Seek(0, STREAM_SEEK_END, &_stat.InSize)); 553 RINOK(InStream_GetSize_SeekToEnd(inStream, _stat.InSize))
555 if (callback) 554 if (callback)
556 { 555 {
557 RINOK(callback->SetTotal(NULL, &_stat.InSize)); 556 RINOK(callback->SetTotal(NULL, &_stat.InSize))
558 } 557 }
559 558
560 CSeekInStreamWrap inStreamImp; 559 CSeekInStreamWrap inStreamImp;
@@ -569,7 +568,7 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal
569 return E_OUTOFMEMORY; 568 return E_OUTOFMEMORY;
570 569
571 lookStream.realStream = &inStreamImp.vt; 570 lookStream.realStream = &inStreamImp.vt;
572 LookToRead2_Init(&lookStream); 571 LookToRead2_INIT(&lookStream)
573 572
574 COpenCallbackWrap openWrap; 573 COpenCallbackWrap openWrap;
575 openWrap.Init(callback); 574 openWrap.Init(callback);
@@ -660,7 +659,7 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal
660 res = SZ_OK; 659 res = SZ_OK;
661 } 660 }
662 661
663 RINOK(SRes_to_Open_HRESULT(res)); 662 RINOK(SRes_to_Open_HRESULT(res))
664 663
665 _stream = inStream; 664 _stream = inStream;
666 _seqStream = inStream; 665 _seqStream = inStream;
@@ -670,7 +669,7 @@ HRESULT CHandler::Open2(IInStream *inStream, /* UInt32 flags, */ IArchiveOpenCal
670 669
671 670
672 671
673STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback) 672Z7_COM7F_IMF(CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback))
674{ 673{
675 COM_TRY_BEGIN 674 COM_TRY_BEGIN
676 { 675 {
@@ -680,7 +679,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCal
680 COM_TRY_END 679 COM_TRY_END
681} 680}
682 681
683STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream) 682Z7_COM7F_IMF(CHandler::OpenSeq(ISequentialInStream *stream))
684{ 683{
685 Close(); 684 Close();
686 _seqStream = stream; 685 _seqStream = stream;
@@ -689,7 +688,7 @@ STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
689 return S_OK; 688 return S_OK;
690} 689}
691 690
692STDMETHODIMP CHandler::Close() 691Z7_COM7F_IMF(CHandler::Close())
693{ 692{
694 XzStatInfo_Clear(&_stat); 693 XzStatInfo_Clear(&_stat);
695 XzStatInfo_Clear(&_stat2); 694 XzStatInfo_Clear(&_stat2);
@@ -738,12 +737,14 @@ CXzUnpackerCPP2::~CXzUnpackerCPP2()
738} 737}
739 738
740 739
741class CInStream: 740Z7_CLASS_IMP_COM_1(
742 public IInStream, 741 CInStream
743 public CMyUnknownImp 742 , IInStream
744{ 743)
745public: 744 Z7_IFACE_COM7_IMP(ISequentialInStream)
745
746 UInt64 _virtPos; 746 UInt64 _virtPos;
747public:
747 UInt64 Size; 748 UInt64 Size;
748 UInt64 _cacheStartPos; 749 UInt64 _cacheStartPos;
749 size_t _cacheSize; 750 size_t _cacheSize;
@@ -762,20 +763,15 @@ public:
762 CHandler *_handlerSpec; 763 CHandler *_handlerSpec;
763 CMyComPtr<IUnknown> _handler; 764 CMyComPtr<IUnknown> _handler;
764 765
765 MY_UNKNOWN_IMP1(IInStream) 766 // ~CInStream();
766
767 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
768 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
769
770 ~CInStream();
771}; 767};
772 768
773 769/*
774CInStream::~CInStream() 770CInStream::~CInStream()
775{ 771{
776 // _cache.Free(); 772 // _cache.Free();
777} 773}
778 774*/
779 775
780static size_t FindBlock(const CBlockInfo *blocks, size_t numBlocks, UInt64 pos) 776static size_t FindBlock(const CBlockInfo *blocks, size_t numBlocks, UInt64 pos)
781{ 777{
@@ -845,7 +841,7 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu,
845 841
846 ECoderStatus status; 842 ECoderStatus status;
847 843
848 SRes res = XzUnpacker_Code(&xzu.p, 844 const SRes res = XzUnpacker_Code(&xzu.p,
849 // dest + outPos, 845 // dest + outPos,
850 NULL, 846 NULL,
851 &outLen, 847 &outLen,
@@ -868,7 +864,7 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu,
868 864
869 packRem -= inLen; 865 packRem -= inLen;
870 866
871 BoolInt blockFinished = XzUnpacker_IsBlockFinished(&xzu.p); 867 const BoolInt blockFinished = XzUnpacker_IsBlockFinished(&xzu.p);
872 868
873 if ((inLen == 0 && outLen == 0) || blockFinished) 869 if ((inLen == 0 && outLen == 0) || blockFinished)
874 { 870 {
@@ -882,7 +878,7 @@ static HRESULT DecodeBlock(CXzUnpackerCPP2 &xzu,
882} 878}
883 879
884 880
885STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 881Z7_COM7F_IMF(CInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
886{ 882{
887 COM_TRY_BEGIN 883 COM_TRY_BEGIN
888 884
@@ -906,7 +902,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
906 902
907 if (_virtPos < _cacheStartPos || _virtPos >= _cacheStartPos + _cacheSize) 903 if (_virtPos < _cacheStartPos || _virtPos >= _cacheStartPos + _cacheSize)
908 { 904 {
909 size_t bi = FindBlock(_handlerSpec->_blocks, _handlerSpec->_blocksArraySize, _virtPos); 905 const size_t bi = FindBlock(_handlerSpec->_blocks, _handlerSpec->_blocksArraySize, _virtPos);
910 const CBlockInfo &block = _handlerSpec->_blocks[bi]; 906 const CBlockInfo &block = _handlerSpec->_blocks[bi];
911 const UInt64 unpackSize = _handlerSpec->_blocks[bi + 1].UnpackPos - block.UnpackPos; 907 const UInt64 unpackSize = _handlerSpec->_blocks[bi + 1].UnpackPos - block.UnpackPos;
912 if (_cache.Size() < unpackSize) 908 if (_cache.Size() < unpackSize)
@@ -914,16 +910,16 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
914 910
915 _cacheSize = 0; 911 _cacheSize = 0;
916 912
917 RINOK(_handlerSpec->SeekToPackPos(block.PackPos)); 913 RINOK(_handlerSpec->SeekToPackPos(block.PackPos))
918 RINOK(DecodeBlock(xz, _handlerSpec->_seqStream, block.StreamFlags, block.PackSize, 914 RINOK(DecodeBlock(xz, _handlerSpec->_seqStream, block.StreamFlags, block.PackSize,
919 (size_t)unpackSize, _cache)); 915 (size_t)unpackSize, _cache))
920 _cacheStartPos = block.UnpackPos; 916 _cacheStartPos = block.UnpackPos;
921 _cacheSize = (size_t)unpackSize; 917 _cacheSize = (size_t)unpackSize;
922 } 918 }
923 919
924 { 920 {
925 size_t offset = (size_t)(_virtPos - _cacheStartPos); 921 const size_t offset = (size_t)(_virtPos - _cacheStartPos);
926 size_t rem = _cacheSize - offset; 922 const size_t rem = _cacheSize - offset;
927 if (size > rem) 923 if (size > rem)
928 size = (UInt32)rem; 924 size = (UInt32)rem;
929 memcpy(data, _cache + offset, size); 925 memcpy(data, _cache + offset, size);
@@ -937,7 +933,7 @@ STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
937} 933}
938 934
939 935
940STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 936Z7_COM7F_IMF(CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
941{ 937{
942 switch (seekOrigin) 938 switch (seekOrigin)
943 { 939 {
@@ -958,7 +954,7 @@ STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPositio
958 954
959static const UInt64 kMaxBlockSize_for_GetStream = (UInt64)1 << 40; 955static const UInt64 kMaxBlockSize_for_GetStream = (UInt64)1 << 40;
960 956
961STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 957Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
962{ 958{
963 COM_TRY_BEGIN 959 COM_TRY_BEGIN
964 960
@@ -1024,8 +1020,8 @@ static Int32 Get_Extract_OperationResult(const NCompress::NXz::CDecoder &decoder
1024 1020
1025 1021
1026 1022
1027STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1023Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1028 Int32 testMode, IArchiveExtractCallback *extractCallback) 1024 Int32 testMode, IArchiveExtractCallback *extractCallback))
1029{ 1025{
1030 COM_TRY_BEGIN 1026 COM_TRY_BEGIN
1031 if (numItems == 0) 1027 if (numItems == 0)
@@ -1039,13 +1035,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1039 extractCallback->SetTotal(stat->InSize); 1035 extractCallback->SetTotal(stat->InSize);
1040 1036
1041 UInt64 currentTotalPacked = 0; 1037 UInt64 currentTotalPacked = 0;
1042 RINOK(extractCallback->SetCompleted(&currentTotalPacked)); 1038 RINOK(extractCallback->SetCompleted(&currentTotalPacked))
1043 CMyComPtr<ISequentialOutStream> realOutStream; 1039 CMyComPtr<ISequentialOutStream> realOutStream;
1044 Int32 askMode = testMode ? 1040 const Int32 askMode = testMode ?
1045 NExtract::NAskMode::kTest : 1041 NExtract::NAskMode::kTest :
1046 NExtract::NAskMode::kExtract; 1042 NExtract::NAskMode::kExtract;
1047 1043
1048 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 1044 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
1049 1045
1050 if (!testMode && !realOutStream) 1046 if (!testMode && !realOutStream)
1051 return S_OK; 1047 return S_OK;
@@ -1060,7 +1056,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1060 { 1056 {
1061 if (!_stream) 1057 if (!_stream)
1062 return E_FAIL; 1058 return E_FAIL;
1063 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 1059 RINOK(InStream_SeekToBegin(_stream))
1064 } 1060 }
1065 else 1061 else
1066 _needSeekToStart = true; 1062 _needSeekToStart = true;
@@ -1085,9 +1081,9 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1085 1081
1086 1082
1087 1083
1088#ifndef EXTRACT_ONLY 1084#ifndef Z7_EXTRACT_ONLY
1089 1085
1090STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 1086Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType))
1091{ 1087{
1092 *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType; 1088 *timeType = GET_FileTimeType_NotDefined_for_GetFileTimeType;
1093 // *timeType = NFileTimeType::kUnix; 1089 // *timeType = NFileTimeType::kUnix;
@@ -1095,8 +1091,8 @@ STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType)
1095} 1091}
1096 1092
1097 1093
1098STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 1094Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
1099 IArchiveUpdateCallback *updateCallback) 1095 IArchiveUpdateCallback *updateCallback))
1100{ 1096{
1101 COM_TRY_BEGIN 1097 COM_TRY_BEGIN
1102 1098
@@ -1111,17 +1107,25 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1111 if (numItems != 1) 1107 if (numItems != 1)
1112 return E_INVALIDARG; 1108 return E_INVALIDARG;
1113 1109
1110 {
1111 Z7_DECL_CMyComPtr_QI_FROM(
1112 IStreamSetRestriction,
1113 setRestriction, outStream)
1114 if (setRestriction)
1115 RINOK(setRestriction->SetRestriction(0, 0))
1116 }
1117
1114 Int32 newData, newProps; 1118 Int32 newData, newProps;
1115 UInt32 indexInArchive; 1119 UInt32 indexInArchive;
1116 if (!updateCallback) 1120 if (!updateCallback)
1117 return E_FAIL; 1121 return E_FAIL;
1118 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive)); 1122 RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProps, &indexInArchive))
1119 1123
1120 if (IntToBool(newProps)) 1124 if (IntToBool(newProps))
1121 { 1125 {
1122 { 1126 {
1123 NCOM::CPropVariant prop; 1127 NCOM::CPropVariant prop;
1124 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop)); 1128 RINOK(updateCallback->GetProperty(0, kpidIsDir, &prop))
1125 if (prop.vt != VT_EMPTY) 1129 if (prop.vt != VT_EMPTY)
1126 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE) 1130 if (prop.vt != VT_BOOL || prop.boolVal != VARIANT_FALSE)
1127 return E_INVALIDARG; 1131 return E_INVALIDARG;
@@ -1133,7 +1137,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1133 UInt64 dataSize; 1137 UInt64 dataSize;
1134 { 1138 {
1135 NCOM::CPropVariant prop; 1139 NCOM::CPropVariant prop;
1136 RINOK(updateCallback->GetProperty(0, kpidSize, &prop)); 1140 RINOK(updateCallback->GetProperty(0, kpidSize, &prop))
1137 if (prop.vt != VT_UI8) 1141 if (prop.vt != VT_UI8)
1138 return E_INVALIDARG; 1142 return E_INVALIDARG;
1139 dataSize = prop.uhVal.QuadPart; 1143 dataSize = prop.uhVal.QuadPart;
@@ -1151,11 +1155,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1151 /* 1155 /*
1152 { 1156 {
1153 NCOM::CPropVariant prop = (UInt64)dataSize; 1157 NCOM::CPropVariant prop = (UInt64)dataSize;
1154 RINOK(encoderSpec->SetCoderProp(NCoderPropID::kReduceSize, prop)); 1158 RINOK(encoderSpec->SetCoderProp(NCoderPropID::kReduceSize, prop))
1155 } 1159 }
1156 */ 1160 */
1157 1161
1158 #ifndef _7ZIP_ST 1162 #ifndef Z7_ST
1159 1163
1160 UInt32 numThreads = _numThreads; 1164 UInt32 numThreads = _numThreads;
1161 1165
@@ -1181,12 +1185,12 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1181 } 1185 }
1182 1186
1183 UInt64 cs = _numSolidBytes; 1187 UInt64 cs = _numSolidBytes;
1184 if (cs != XZ_PROPS__BLOCK_SIZE__AUTO) 1188 if (cs != XZ_PROPS_BLOCK_SIZE_AUTO)
1185 oneMethodInfo.AddProp_BlockSize2(cs); 1189 oneMethodInfo.AddProp_BlockSize2(cs);
1186 cs = oneMethodInfo.Get_Xz_BlockSize(); 1190 cs = oneMethodInfo.Get_Xz_BlockSize();
1187 1191
1188 if (cs != XZ_PROPS__BLOCK_SIZE__AUTO && 1192 if (cs != XZ_PROPS_BLOCK_SIZE_AUTO &&
1189 cs != XZ_PROPS__BLOCK_SIZE__SOLID) 1193 cs != XZ_PROPS_BLOCK_SIZE_SOLID)
1190 { 1194 {
1191 const UInt32 lzmaThreads = oneMethodInfo.Get_Lzma_NumThreads(); 1195 const UInt32 lzmaThreads = oneMethodInfo.Get_Lzma_NumThreads();
1192 const UInt32 numBlockThreads_Original = numThreads / lzmaThreads; 1196 const UInt32 numBlockThreads_Original = numThreads / lzmaThreads;
@@ -1218,16 +1222,16 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1218 } 1222 }
1219 xzProps.numTotalThreads = (int)numThreads; 1223 xzProps.numTotalThreads = (int)numThreads;
1220 1224
1221 #endif // _7ZIP_ST 1225 #endif // Z7_ST
1222 1226
1223 1227
1224 xzProps.blockSize = _numSolidBytes; 1228 xzProps.blockSize = _numSolidBytes;
1225 if (_numSolidBytes == XZ_PROPS__BLOCK_SIZE__SOLID) 1229 if (_numSolidBytes == XZ_PROPS_BLOCK_SIZE_SOLID)
1226 { 1230 {
1227 xzProps.lzma2Props.blockSize = LZMA2_ENC_PROPS__BLOCK_SIZE__SOLID; 1231 xzProps.lzma2Props.blockSize = LZMA2_ENC_PROPS_BLOCK_SIZE_SOLID;
1228 } 1232 }
1229 1233
1230 RINOK(encoderSpec->SetCheckSize(_crcSize)); 1234 RINOK(encoderSpec->SetCheckSize(_crcSize))
1231 1235
1232 { 1236 {
1233 CXzFilterProps &filter = xzProps.filterProps; 1237 CXzFilterProps &filter = xzProps.filterProps;
@@ -1262,13 +1266,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1262 FOR_VECTOR (j, m.Props) 1266 FOR_VECTOR (j, m.Props)
1263 { 1267 {
1264 const CProp &prop = m.Props[j]; 1268 const CProp &prop = m.Props[j];
1265 RINOK(encoderSpec->SetCoderProp(prop.Id, prop.Value)); 1269 RINOK(encoderSpec->SetCoderProp(prop.Id, prop.Value))
1266 } 1270 }
1267 } 1271 }
1268 1272
1269 { 1273 {
1270 CMyComPtr<ISequentialInStream> fileInStream; 1274 CMyComPtr<ISequentialInStream> fileInStream;
1271 RINOK(updateCallback->GetStream(0, &fileInStream)); 1275 RINOK(updateCallback->GetStream(0, &fileInStream))
1272 if (!fileInStream) 1276 if (!fileInStream)
1273 return S_FALSE; 1277 return S_FALSE;
1274 { 1278 {
@@ -1281,11 +1285,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1281 dataSize = size; 1285 dataSize = size;
1282 } 1286 }
1283 } 1287 }
1284 RINOK(updateCallback->SetTotal(dataSize)); 1288 RINOK(updateCallback->SetTotal(dataSize))
1285 CLocalProgress *lps = new CLocalProgress; 1289 CLocalProgress *lps = new CLocalProgress;
1286 CMyComPtr<ICompressProgressInfo> progress = lps; 1290 CMyComPtr<ICompressProgressInfo> progress = lps;
1287 lps->Init(updateCallback, true); 1291 lps->Init(updateCallback, true);
1288 RINOK(encoderSpec->Code(fileInStream, outStream, NULL, NULL, progress)); 1292 RINOK(encoder->Code(fileInStream, outStream, NULL, NULL, progress))
1289 } 1293 }
1290 1294
1291 return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK); 1295 return updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK);
@@ -1294,8 +1298,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1294 if (indexInArchive != 0) 1298 if (indexInArchive != 0)
1295 return E_INVALIDARG; 1299 return E_INVALIDARG;
1296 1300
1297 CMyComPtr<IArchiveUpdateCallbackFile> opCallback; 1301 Z7_DECL_CMyComPtr_QI_FROM(
1298 updateCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&opCallback); 1302 IArchiveUpdateCallbackFile,
1303 opCallback, updateCallback)
1299 if (opCallback) 1304 if (opCallback)
1300 { 1305 {
1301 RINOK(opCallback->ReportOperation(NEventIndexType::kInArcIndex, 0, NUpdateNotifyOp::kReplicate)) 1306 RINOK(opCallback->ReportOperation(NEventIndexType::kInArcIndex, 0, NUpdateNotifyOp::kReplicate))
@@ -1305,8 +1310,10 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1305 { 1310 {
1306 const CXzStatInfo *stat = GetStat(); 1311 const CXzStatInfo *stat = GetStat();
1307 if (stat) 1312 if (stat)
1308 RINOK(updateCallback->SetTotal(stat->InSize)); 1313 {
1309 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 1314 RINOK(updateCallback->SetTotal(stat->InSize))
1315 }
1316 RINOK(InStream_SeekToBegin(_stream))
1310 } 1317 }
1311 1318
1312 CLocalProgress *lps = new CLocalProgress; 1319 CLocalProgress *lps = new CLocalProgress;
@@ -1328,7 +1335,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value)
1328 if (name.IsEmpty()) 1335 if (name.IsEmpty())
1329 return E_INVALIDARG; 1336 return E_INVALIDARG;
1330 1337
1331 #ifndef EXTRACT_ONLY 1338 #ifndef Z7_EXTRACT_ONLY
1332 1339
1333 if (name[0] == L's') 1340 if (name[0] == L's')
1334 { 1341 {
@@ -1349,7 +1356,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value)
1349 } 1356 }
1350 if (!useStr) 1357 if (!useStr)
1351 { 1358 {
1352 _numSolidBytes = (isSolid ? XZ_PROPS__BLOCK_SIZE__SOLID : XZ_PROPS__BLOCK_SIZE__AUTO); 1359 _numSolidBytes = (isSolid ? XZ_PROPS_BLOCK_SIZE_SOLID : XZ_PROPS_BLOCK_SIZE_AUTO);
1353 return S_OK; 1360 return S_OK;
1354 } 1361 }
1355 } 1362 }
@@ -1375,7 +1382,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value)
1375 1382
1376 1383
1377 1384
1378STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 1385Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
1379{ 1386{
1380 COM_TRY_BEGIN 1387 COM_TRY_BEGIN
1381 1388
@@ -1383,15 +1390,15 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1383 1390
1384 for (UInt32 i = 0; i < numProps; i++) 1391 for (UInt32 i = 0; i < numProps; i++)
1385 { 1392 {
1386 RINOK(SetProperty(names[i], values[i])); 1393 RINOK(SetProperty(names[i], values[i]))
1387 } 1394 }
1388 1395
1389 #ifndef EXTRACT_ONLY 1396 #ifndef Z7_EXTRACT_ONLY
1390 1397
1391 if (!_filterMethod.MethodName.IsEmpty()) 1398 if (!_filterMethod.MethodName.IsEmpty())
1392 { 1399 {
1393 unsigned k; 1400 unsigned k;
1394 for (k = 0; k < ARRAY_SIZE(g_NamePairs); k++) 1401 for (k = 0; k < Z7_ARRAY_SIZE(g_NamePairs); k++)
1395 { 1402 {
1396 const CMethodNamePair &pair = g_NamePairs[k]; 1403 const CMethodNamePair &pair = g_NamePairs[k];
1397 if (StringsAreEqualNoCase_Ascii(_filterMethod.MethodName, pair.Name)) 1404 if (StringsAreEqualNoCase_Ascii(_filterMethod.MethodName, pair.Name))
@@ -1400,7 +1407,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
1400 break; 1407 break;
1401 } 1408 }
1402 } 1409 }
1403 if (k == ARRAY_SIZE(g_NamePairs)) 1410 if (k == Z7_ARRAY_SIZE(g_NamePairs))
1404 return E_INVALIDARG; 1411 return E_INVALIDARG;
1405 } 1412 }
1406 1413
diff --git a/CPP/7zip/Archive/XzHandler.h b/CPP/7zip/Archive/XzHandler.h
index 24e8eeb..4d09954 100644
--- a/CPP/7zip/Archive/XzHandler.h
+++ b/CPP/7zip/Archive/XzHandler.h
@@ -1,7 +1,7 @@
1// XzHandler.h 1// XzHandler.h
2 2
3#ifndef __XZ_HANDLER_H 3#ifndef ZIP7_INC_XZ_HANDLER_H
4#define __XZ_HANDLER_H 4#define ZIP7_INC_XZ_HANDLER_H
5 5
6namespace NArchive { 6namespace NArchive {
7namespace NXz { 7namespace NXz {
diff --git a/CPP/7zip/Archive/ZHandler.cpp b/CPP/7zip/Archive/ZHandler.cpp
index 2993436..18e712a 100644
--- a/CPP/7zip/Archive/ZHandler.cpp
+++ b/CPP/7zip/Archive/ZHandler.cpp
@@ -17,17 +17,12 @@
17namespace NArchive { 17namespace NArchive {
18namespace NZ { 18namespace NZ {
19 19
20class CHandler: 20Z7_CLASS_IMP_CHandler_IInArchive_0
21 public IInArchive, 21
22 public CMyUnknownImp
23{
24 CMyComPtr<IInStream> _stream; 22 CMyComPtr<IInStream> _stream;
25 UInt64 _packSize; 23 UInt64 _packSize;
26 // UInt64 _unpackSize; 24 // UInt64 _unpackSize;
27 // bool _unpackSize_Defined; 25 // bool _unpackSize_Defined;
28public:
29 MY_UNKNOWN_IMP1(IInArchive)
30 INTERFACE_IInArchive(;)
31}; 26};
32 27
33static const Byte kProps[] = 28static const Byte kProps[] =
@@ -38,13 +33,13 @@ static const Byte kProps[] =
38IMP_IInArchive_Props 33IMP_IInArchive_Props
39IMP_IInArchive_ArcProps_NO_Table 34IMP_IInArchive_ArcProps_NO_Table
40 35
41STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 36Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
42{ 37{
43 *numItems = 1; 38 *numItems = 1;
44 return S_OK; 39 return S_OK;
45} 40}
46 41
47STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 42Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
48{ 43{
49 NWindows::NCOM::CPropVariant prop; 44 NWindows::NCOM::CPropVariant prop;
50 switch (propID) 45 switch (propID)
@@ -55,7 +50,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
55 return S_OK; 50 return S_OK;
56} 51}
57 52
58STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) 53Z7_COM7F_IMF(CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value))
59{ 54{
60 NWindows::NCOM::CPropVariant prop; 55 NWindows::NCOM::CPropVariant prop;
61 switch (propID) 56 switch (propID)
@@ -68,22 +63,21 @@ STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIAN
68} 63}
69 64
70/* 65/*
71class CCompressProgressInfoImp: 66Z7_CLASS_IMP_COM_1(
72 public ICompressProgressInfo, 67 CCompressProgressInfoImp
73 public CMyUnknownImp 68 , ICompressProgressInfo
74{ 69)
75 CMyComPtr<IArchiveOpenCallback> Callback; 70 CMyComPtr<IArchiveOpenCallback> Callback;
76public: 71public:
77 MY_UNKNOWN_IMP1(ICompressProgressInfo)
78 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
79 void Init(IArchiveOpenCallback *callback) { Callback = callback; } 72 void Init(IArchiveOpenCallback *callback) { Callback = callback; }
80}; 73};
81 74
82STDMETHODIMP CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 75Z7_COM7F_IMF(CCompressProgressInfoImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
83{ 76{
77 outSize = outSize;
84 if (Callback) 78 if (Callback)
85 { 79 {
86 UInt64 files = 1; 80 const UInt64 files = 1;
87 return Callback->SetCompleted(&files, inSize); 81 return Callback->SetCompleted(&files, inSize);
88 } 82 }
89 return S_OK; 83 return S_OK;
@@ -102,23 +96,23 @@ API_FUNC_static_IsArc IsArc_Z(const Byte *p, size_t size)
102} 96}
103} 97}
104 98
105STDMETHODIMP CHandler::Open(IInStream *stream, 99Z7_COM7F_IMF(CHandler::Open(IInStream *stream,
106 const UInt64 * /* maxCheckStartPosition */, 100 const UInt64 * /* maxCheckStartPosition */,
107 IArchiveOpenCallback * /* openCallback */) 101 IArchiveOpenCallback * /* openCallback */))
108{ 102{
109 COM_TRY_BEGIN 103 COM_TRY_BEGIN
110 { 104 {
111 // RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_streamStartPosition)); 105 // RINOK(InStream_GetPos(stream, _streamStartPosition));
112 Byte buffer[NCompress::NZ::kRecommendedCheckSize]; 106 Byte buffer[NCompress::NZ::kRecommendedCheckSize];
113 // Byte buffer[1500]; 107 // Byte buffer[1500];
114 size_t size = NCompress::NZ::kRecommendedCheckSize; 108 size_t size = NCompress::NZ::kRecommendedCheckSize;
115 // size = 700; 109 // size = 700;
116 RINOK(ReadStream(stream, buffer, &size)); 110 RINOK(ReadStream(stream, buffer, &size))
117 if (!NCompress::NZ::CheckStream(buffer, size)) 111 if (!NCompress::NZ::CheckStream(buffer, size))
118 return S_FALSE; 112 return S_FALSE;
119 113
120 UInt64 endPos; 114 UInt64 endPos;
121 RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); 115 RINOK(InStream_GetSize_SeekToEnd(stream, endPos))
122 _packSize = endPos; 116 _packSize = endPos;
123 117
124 /* 118 /*
@@ -142,7 +136,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
142 UInt64 files = 1; 136 UInt64 files = 1;
143 RINOK(openCallback->SetTotal(&files, &endPos)); 137 RINOK(openCallback->SetTotal(&files, &endPos));
144 } 138 }
145 RINOK(stream->Seek(_streamStartPosition + kSignatureSize, STREAM_SEEK_SET, NULL)); 139 RINOK(InStream_SeekSet(stream, _streamStartPosition + kSignatureSize))
146 HRESULT res = decoder->Code(stream, outStream, NULL, NULL, openCallback ? compressProgress : NULL); 140 HRESULT res = decoder->Code(stream, outStream, NULL, NULL, openCallback ? compressProgress : NULL);
147 if (res != S_OK) 141 if (res != S_OK)
148 return S_FALSE; 142 return S_FALSE;
@@ -155,7 +149,7 @@ STDMETHODIMP CHandler::Open(IInStream *stream,
155 COM_TRY_END 149 COM_TRY_END
156} 150}
157 151
158STDMETHODIMP CHandler::Close() 152Z7_COM7F_IMF(CHandler::Close())
159{ 153{
160 _packSize = 0; 154 _packSize = 0;
161 // _unpackSize_Defined = false; 155 // _unpackSize_Defined = false;
@@ -164,8 +158,8 @@ STDMETHODIMP CHandler::Close()
164} 158}
165 159
166 160
167STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 161Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
168 Int32 testMode, IArchiveExtractCallback *extractCallback) 162 Int32 testMode, IArchiveExtractCallback *extractCallback))
169{ 163{
170 COM_TRY_BEGIN 164 COM_TRY_BEGIN
171 if (numItems == 0) 165 if (numItems == 0)
@@ -177,14 +171,14 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
177 171
178 UInt64 currentTotalPacked = 0; 172 UInt64 currentTotalPacked = 0;
179 173
180 RINOK(extractCallback->SetCompleted(&currentTotalPacked)); 174 RINOK(extractCallback->SetCompleted(&currentTotalPacked))
181 175
182 CMyComPtr<ISequentialOutStream> realOutStream; 176 CMyComPtr<ISequentialOutStream> realOutStream;
183 Int32 askMode = testMode ? 177 const Int32 askMode = testMode ?
184 NExtract::NAskMode::kTest : 178 NExtract::NAskMode::kTest :
185 NExtract::NAskMode::kExtract; 179 NExtract::NAskMode::kExtract;
186 180
187 RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); 181 RINOK(extractCallback->GetStream(0, &realOutStream, askMode))
188 182
189 if (!testMode && !realOutStream) 183 if (!testMode && !realOutStream)
190 return S_OK; 184 return S_OK;
@@ -201,7 +195,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
201 CMyComPtr<ICompressProgressInfo> progress = lps; 195 CMyComPtr<ICompressProgressInfo> progress = lps;
202 lps->Init(extractCallback, true); 196 lps->Init(extractCallback, true);
203 197
204 RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL)); 198 RINOK(InStream_SeekToBegin(_stream))
205 199
206 NCompress::NZ::CDecoder *decoderSpec = new NCompress::NZ::CDecoder; 200 NCompress::NZ::CDecoder *decoderSpec = new NCompress::NZ::CDecoder;
207 CMyComPtr<ICompressCoder> decoder = decoderSpec; 201 CMyComPtr<ICompressCoder> decoder = decoderSpec;
@@ -213,7 +207,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
213 opRes = NExtract::NOperationResult::kDataError; 207 opRes = NExtract::NOperationResult::kDataError;
214 else 208 else
215 { 209 {
216 RINOK(result); 210 RINOK(result)
217 opRes = NExtract::NOperationResult::kOK; 211 opRes = NExtract::NOperationResult::kOK;
218 } 212 }
219 } 213 }
diff --git a/CPP/7zip/Archive/Zip/StdAfx.h b/CPP/7zip/Archive/Zip/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Archive/Zip/StdAfx.h
+++ b/CPP/7zip/Archive/Zip/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Archive/Zip/ZipAddCommon.cpp b/CPP/7zip/Archive/Zip/ZipAddCommon.cpp
index 2bb57d5..8af84b4 100644
--- a/CPP/7zip/Archive/Zip/ZipAddCommon.cpp
+++ b/CPP/7zip/Archive/Zip/ZipAddCommon.cpp
@@ -30,31 +30,22 @@ namespace NZip {
30using namespace NFileHeader; 30using namespace NFileHeader;
31 31
32 32
33static const UInt32 kLzmaPropsSize = 5; 33static const unsigned kLzmaPropsSize = 5;
34static const UInt32 kLzmaHeaderSize = 4 + kLzmaPropsSize; 34static const unsigned kLzmaHeaderSize = 4 + kLzmaPropsSize;
35 35
36class CLzmaEncoder: 36Z7_CLASS_IMP_NOQIB_3(
37 public ICompressCoder, 37 CLzmaEncoder
38 public ICompressSetCoderProperties, 38 , ICompressCoder
39 public ICompressSetCoderPropertiesOpt, 39 , ICompressSetCoderProperties
40 public CMyUnknownImp 40 , ICompressSetCoderPropertiesOpt
41{ 41)
42public: 42public:
43 NCompress::NLzma::CEncoder *EncoderSpec; 43 NCompress::NLzma::CEncoder *EncoderSpec;
44 CMyComPtr<ICompressCoder> Encoder; 44 CMyComPtr<ICompressCoder> Encoder;
45 Byte Header[kLzmaHeaderSize]; 45 Byte Header[kLzmaHeaderSize];
46
47 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
48 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
49 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
50 STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
51
52 MY_UNKNOWN_IMP2(
53 ICompressSetCoderProperties,
54 ICompressSetCoderPropertiesOpt)
55}; 46};
56 47
57STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 48Z7_COM7F_IMF(CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
58{ 49{
59 if (!Encoder) 50 if (!Encoder)
60 { 51 {
@@ -64,8 +55,8 @@ STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPV
64 CBufPtrSeqOutStream *outStreamSpec = new CBufPtrSeqOutStream; 55 CBufPtrSeqOutStream *outStreamSpec = new CBufPtrSeqOutStream;
65 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec); 56 CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
66 outStreamSpec->Init(Header + 4, kLzmaPropsSize); 57 outStreamSpec->Init(Header + 4, kLzmaPropsSize);
67 RINOK(EncoderSpec->SetCoderProperties(propIDs, props, numProps)); 58 RINOK(EncoderSpec->SetCoderProperties(propIDs, props, numProps))
68 RINOK(EncoderSpec->WriteCoderProperties(outStream)); 59 RINOK(EncoderSpec->WriteCoderProperties(outStream))
69 if (outStreamSpec->GetPos() != kLzmaPropsSize) 60 if (outStreamSpec->GetPos() != kLzmaPropsSize)
70 return E_FAIL; 61 return E_FAIL;
71 Header[0] = MY_VER_MAJOR; 62 Header[0] = MY_VER_MAJOR;
@@ -75,15 +66,15 @@ STDMETHODIMP CLzmaEncoder::SetCoderProperties(const PROPID *propIDs, const PROPV
75 return S_OK; 66 return S_OK;
76} 67}
77 68
78STDMETHODIMP CLzmaEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 69Z7_COM7F_IMF(CLzmaEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
79{ 70{
80 return EncoderSpec->SetCoderPropertiesOpt(propIDs, props, numProps); 71 return EncoderSpec->SetCoderPropertiesOpt(propIDs, props, numProps);
81} 72}
82 73
83STDMETHODIMP CLzmaEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 74Z7_COM7F_IMF(CLzmaEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
84 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 75 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
85{ 76{
86 RINOK(WriteStream(outStream, Header, kLzmaHeaderSize)); 77 RINOK(WriteStream(outStream, Header, kLzmaHeaderSize))
87 return Encoder->Code(inStream, outStream, inSize, outSize, progress); 78 return Encoder->Code(inStream, outStream, inSize, outSize, progress);
88} 79}
89 80
@@ -120,7 +111,7 @@ HRESULT CAddCommon::CalcStreamCRC(ISequentialInStream *inStream, UInt32 &resultC
120 for (;;) 111 for (;;)
121 { 112 {
122 UInt32 processed; 113 UInt32 processed;
123 RINOK(inStream->Read(_buf, kBufSize, &processed)); 114 RINOK(inStream->Read(_buf, kBufSize, &processed))
124 if (processed == 0) 115 if (processed == 0)
125 { 116 {
126 resultCRC = CRC_GET_DIGEST(crc); 117 resultCRC = CRC_GET_DIGEST(crc);
@@ -148,9 +139,9 @@ HRESULT CAddCommon::Set_Pre_CompressionResult(bool inSeqMode, bool outSeqMode, U
148 if (opRes.PackSize < unpackSize) 139 if (opRes.PackSize < unpackSize)
149 opRes.PackSize = unpackSize; 140 opRes.PackSize = unpackSize;
150 141
151 Byte method = _options.MethodSequence[0]; 142 const Byte method = _options.MethodSequence[0];
152 143
153 if (method == NCompressionMethod::kStore && !_options.PasswordIsDefined) 144 if (method == NCompressionMethod::kStore && !_options.Password_Defined)
154 opRes.PackSize = unpackSize; 145 opRes.PackSize = unpackSize;
155 146
156 opRes.CRC = 0; 147 opRes.CRC = 0;
@@ -160,7 +151,7 @@ HRESULT CAddCommon::Set_Pre_CompressionResult(bool inSeqMode, bool outSeqMode, U
160 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; 151 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default;
161 opRes.DescriptorMode = outSeqMode; 152 opRes.DescriptorMode = outSeqMode;
162 153
163 if (_options.PasswordIsDefined) 154 if (_options.Password_Defined)
164 { 155 {
165 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; 156 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto;
166 if (_options.IsAesMode) 157 if (_options.IsAesMode)
@@ -202,10 +193,11 @@ HRESULT CAddCommon::Compress(
202 DECL_EXTERNAL_CODECS_LOC_VARS 193 DECL_EXTERNAL_CODECS_LOC_VARS
203 ISequentialInStream *inStream, IOutStream *outStream, 194 ISequentialInStream *inStream, IOutStream *outStream,
204 bool inSeqMode, bool outSeqMode, 195 bool inSeqMode, bool outSeqMode,
205 UInt32 fileTime, UInt64 expectedDataSize, 196 UInt32 fileTime,
197 UInt64 expectedDataSize, bool expectedDataSize_IsConfirmed,
206 ICompressProgressInfo *progress, CCompressingResult &opRes) 198 ICompressProgressInfo *progress, CCompressingResult &opRes)
207{ 199{
208 opRes.LzmaEos = false; 200 // opRes.LzmaEos = false;
209 201
210 if (!inStream) 202 if (!inStream)
211 { 203 {
@@ -229,9 +221,11 @@ HRESULT CAddCommon::Compress(
229 } 221 }
230 222
231 inSecCrcStreamSpec->SetStream(inStream); 223 inSecCrcStreamSpec->SetStream(inStream);
232 inSecCrcStreamSpec->Init(); 224 inSecCrcStreamSpec->SetFullSize(expectedDataSize_IsConfirmed ? expectedDataSize : (UInt64)(Int64)-1);
225 // inSecCrcStreamSpec->Init();
233 226
234 unsigned numTestMethods = _options.MethodSequence.Size(); 227 unsigned numTestMethods = _options.MethodSequence.Size();
228 // numTestMethods != 0
235 229
236 bool descriptorMode = outSeqMode; 230 bool descriptorMode = outSeqMode;
237 231
@@ -240,7 +234,7 @@ HRESULT CAddCommon::Compress(
240 // The descriptor allows to use ZipCrypto check field without CRC (InfoZip's modification). 234 // The descriptor allows to use ZipCrypto check field without CRC (InfoZip's modification).
241 235
242 if (!outSeqMode) 236 if (!outSeqMode)
243 if (inSeqMode && _options.PasswordIsDefined && !_options.IsAesMode) 237 if (inSeqMode && _options.Password_Defined && !_options.IsAesMode)
244 descriptorMode = true; 238 descriptorMode = true;
245 opRes.DescriptorMode = descriptorMode; 239 opRes.DescriptorMode = descriptorMode;
246 240
@@ -251,28 +245,27 @@ HRESULT CAddCommon::Compress(
251 UInt32 crc = 0; 245 UInt32 crc = 0;
252 bool crc_IsCalculated = false; 246 bool crc_IsCalculated = false;
253 247
254 Byte method = 0;
255 CFilterCoder::C_OutStream_Releaser outStreamReleaser; 248 CFilterCoder::C_OutStream_Releaser outStreamReleaser;
256 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; 249 // opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default;
257 250
258 for (unsigned i = 0; i < numTestMethods; i++) 251 for (unsigned i = 0; i < numTestMethods; i++)
259 { 252 {
260 opRes.LzmaEos = false; 253 inSecCrcStreamSpec->Init();
261 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default; 254
262
263 if (i != 0) 255 if (i != 0)
264 { 256 {
265 if (inStream2) 257 // if (inStream2)
266 { 258 {
267 inSecCrcStreamSpec->Init(); 259 RINOK(InStream_SeekToBegin(inStream2))
268 RINOK(inStream2->Seek(0, STREAM_SEEK_SET, NULL));
269 } 260 }
270 261 RINOK(outStream->Seek(0, STREAM_SEEK_SET, NULL))
271 RINOK(outStream->SetSize(0)); 262 RINOK(outStream->SetSize(0))
272 RINOK(outStream->Seek(0, STREAM_SEEK_SET, NULL));
273 } 263 }
274 264
275 method = _options.MethodSequence[i]; 265 opRes.LzmaEos = false;
266 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_Default;
267
268 const Byte method = _options.MethodSequence[i];
276 if (method == NCompressionMethod::kStore && descriptorMode) 269 if (method == NCompressionMethod::kStore && descriptorMode)
277 { 270 {
278 // we still can create descriptor_mode archives with "Store" method, but they are not good for 100% 271 // we still can create descriptor_mode archives with "Store" method, but they are not good for 100%
@@ -281,7 +274,7 @@ HRESULT CAddCommon::Compress(
281 274
282 bool needCode = true; 275 bool needCode = true;
283 276
284 if (_options.PasswordIsDefined) 277 if (_options.Password_Defined)
285 { 278 {
286 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto; 279 opRes.ExtractVersion = NCompressionMethod::kExtractVersion_ZipCrypto;
287 280
@@ -298,9 +291,9 @@ HRESULT CAddCommon::Compress(
298 { 291 {
299 _cryptoStreamSpec->Filter = _filterAesSpec = new NCrypto::NWzAes::CEncoder; 292 _cryptoStreamSpec->Filter = _filterAesSpec = new NCrypto::NWzAes::CEncoder;
300 _filterAesSpec->SetKeyMode(_options.AesKeyMode); 293 _filterAesSpec->SetKeyMode(_options.AesKeyMode);
301 RINOK(_filterAesSpec->CryptoSetPassword((const Byte *)(const char *)_options.Password, _options.Password.Len())); 294 RINOK(_filterAesSpec->CryptoSetPassword((const Byte *)(const char *)_options.Password, _options.Password.Len()))
302 } 295 }
303 RINOK(_filterAesSpec->WriteHeader(outStream)); 296 RINOK(_filterAesSpec->WriteHeader(outStream))
304 } 297 }
305 else 298 else
306 { 299 {
@@ -321,26 +314,26 @@ HRESULT CAddCommon::Compress(
321 { 314 {
322 if (!crc_IsCalculated) 315 if (!crc_IsCalculated)
323 { 316 {
324 RINOK(CalcStreamCRC(inStream, crc)); 317 RINOK(CalcStreamCRC(inStream, crc))
325 crc_IsCalculated = true; 318 crc_IsCalculated = true;
326 RINOK(inStream2->Seek(0, STREAM_SEEK_SET, NULL)); 319 RINOK(InStream_SeekToBegin(inStream2))
327 inSecCrcStreamSpec->Init(); 320 inSecCrcStreamSpec->Init();
328 } 321 }
329 check = (crc >> 16); 322 check = (crc >> 16);
330 } 323 }
331 324
332 RINOK(_filterSpec->WriteHeader_Check16(outStream, (UInt16)check)); 325 RINOK(_filterSpec->WriteHeader_Check16(outStream, (UInt16)check))
333 } 326 }
334 327
335 if (method == NCompressionMethod::kStore) 328 if (method == NCompressionMethod::kStore)
336 { 329 {
337 needCode = false; 330 needCode = false;
338 RINOK(_cryptoStreamSpec->Code(inCrcStream, outStream, NULL, NULL, progress)); 331 RINOK(_cryptoStreamSpec->Code(inCrcStream, outStream, NULL, NULL, progress))
339 } 332 }
340 else 333 else
341 { 334 {
342 RINOK(_cryptoStreamSpec->SetOutStream(outStream)); 335 RINOK(_cryptoStreamSpec->SetOutStream(outStream))
343 RINOK(_cryptoStreamSpec->InitEncoder()); 336 RINOK(_cryptoStreamSpec->InitEncoder())
344 outStreamReleaser.FilterCoder = _cryptoStreamSpec; 337 outStreamReleaser.FilterCoder = _cryptoStreamSpec;
345 } 338 }
346 } 339 }
@@ -357,11 +350,11 @@ HRESULT CAddCommon::Compress(
357 _copyCoder = _copyCoderSpec; 350 _copyCoder = _copyCoderSpec;
358 } 351 }
359 CMyComPtr<ISequentialOutStream> outStreamNew; 352 CMyComPtr<ISequentialOutStream> outStreamNew;
360 if (_options.PasswordIsDefined) 353 if (_options.Password_Defined)
361 outStreamNew = _cryptoStream; 354 outStreamNew = _cryptoStream;
362 else 355 else
363 outStreamNew = outStream; 356 outStreamNew = outStream;
364 RINOK(_copyCoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)); 357 RINOK(_copyCoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress))
365 break; 358 break;
366 } 359 }
367 360
@@ -406,7 +399,7 @@ HRESULT CAddCommon::Compress(
406 } 399 }
407 RINOK(CreateCoder_Id( 400 RINOK(CreateCoder_Id(
408 EXTERNAL_CODECS_LOC_VARS 401 EXTERNAL_CODECS_LOC_VARS
409 methodId, true, _compressEncoder)); 402 methodId, true, _compressEncoder))
410 if (!_compressEncoder) 403 if (!_compressEncoder)
411 return E_NOTIMPL; 404 return E_NOTIMPL;
412 405
@@ -428,7 +421,7 @@ HRESULT CAddCommon::Compress(
428 COneMethodInfo *oneMethodMain = &_options._methods[0]; 421 COneMethodInfo *oneMethodMain = &_options._methods[0];
429 422
430 RINOK(oneMethodMain->SetCoderProps(setCoderProps, 423 RINOK(oneMethodMain->SetCoderProps(setCoderProps,
431 _options._dataSizeReduceDefined ? &_options._dataSizeReduce : NULL)); 424 _options.DataSizeReduce_Defined ? &_options.DataSizeReduce : NULL))
432 } 425 }
433 } 426 }
434 } 427 }
@@ -440,7 +433,7 @@ HRESULT CAddCommon::Compress(
440 opRes.LzmaEos = _isLzmaEos; 433 opRes.LzmaEos = _isLzmaEos;
441 434
442 CMyComPtr<ISequentialOutStream> outStreamNew; 435 CMyComPtr<ISequentialOutStream> outStreamNew;
443 if (_options.PasswordIsDefined) 436 if (_options.Password_Defined)
444 outStreamNew = _cryptoStream; 437 outStreamNew = _cryptoStream;
445 else 438 else
446 outStreamNew = outStream; 439 outStreamNew = outStream;
@@ -452,41 +445,45 @@ HRESULT CAddCommon::Compress(
452 _compressEncoder->QueryInterface(IID_ICompressSetCoderPropertiesOpt, (void **)&optProps); 445 _compressEncoder->QueryInterface(IID_ICompressSetCoderPropertiesOpt, (void **)&optProps);
453 if (optProps) 446 if (optProps)
454 { 447 {
455 PROPID propID = NCoderPropID::kExpectedDataSize; 448 const PROPID propID = NCoderPropID::kExpectedDataSize;
456 NWindows::NCOM::CPropVariant prop = (UInt64)expectedDataSize; 449 NWindows::NCOM::CPropVariant prop = (UInt64)expectedDataSize;
457 RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1)); 450 RINOK(optProps->SetCoderPropertiesOpt(&propID, &prop, 1))
458 } 451 }
459 } 452 }
460 453
461 try { 454 try {
462 RINOK(_compressEncoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress)); 455 RINOK(_compressEncoder->Code(inCrcStream, outStreamNew, NULL, NULL, progress))
463 } catch (...) { return E_FAIL; } 456 } catch (...) { return E_FAIL; }
464 break; 457 break;
465 } 458 }
466 } // switch end 459 } // switch end
467 460
468 if (_options.PasswordIsDefined) 461 if (_options.Password_Defined)
469 { 462 {
470 RINOK(_cryptoStreamSpec->OutStreamFinish()); 463 RINOK(_cryptoStreamSpec->OutStreamFinish())
471 } 464 }
472 } 465 }
473 466
474 if (_options.PasswordIsDefined) 467 if (_options.Password_Defined)
475 { 468 {
476 if (_options.IsAesMode) 469 if (_options.IsAesMode)
477 { 470 {
478 RINOK(_filterAesSpec->WriteFooter(outStream)); 471 RINOK(_filterAesSpec->WriteFooter(outStream))
479 } 472 }
480 } 473 }
481 474
482 RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &opRes.PackSize)); 475 RINOK(outStream->Seek(0, STREAM_SEEK_CUR, &opRes.PackSize))
483 476
484 { 477 {
485 opRes.CRC = inSecCrcStreamSpec->GetCRC(); 478 opRes.CRC = inSecCrcStreamSpec->GetCRC();
486 opRes.UnpackSize = inSecCrcStreamSpec->GetSize(); 479 opRes.UnpackSize = inSecCrcStreamSpec->GetSize();
480 opRes.Method = method;
487 } 481 }
488 482
489 if (_options.PasswordIsDefined) 483 if (!inSecCrcStreamSpec->WasFinished())
484 return E_FAIL;
485
486 if (_options.Password_Defined)
490 { 487 {
491 if (opRes.PackSize < opRes.UnpackSize + 488 if (opRes.PackSize < opRes.UnpackSize +
492 (_options.IsAesMode ? _filterAesSpec->GetAddPackSize() : NCrypto::NZip::kHeaderSize)) 489 (_options.IsAesMode ? _filterAesSpec->GetAddPackSize() : NCrypto::NZip::kHeaderSize))
@@ -496,8 +493,6 @@ HRESULT CAddCommon::Compress(
496 break; 493 break;
497 } 494 }
498 495
499
500 opRes.Method = method;
501 return S_OK; 496 return S_OK;
502} 497}
503 498
diff --git a/CPP/7zip/Archive/Zip/ZipAddCommon.h b/CPP/7zip/Archive/Zip/ZipAddCommon.h
index 0aa44ad..051915c 100644
--- a/CPP/7zip/Archive/Zip/ZipAddCommon.h
+++ b/CPP/7zip/Archive/Zip/ZipAddCommon.h
@@ -1,7 +1,7 @@
1// ZipAddCommon.h 1// ZipAddCommon.h
2 2
3#ifndef __ZIP_ADD_COMMON_H 3#ifndef ZIP7_INC_ZIP_ADD_COMMON_H
4#define __ZIP_ADD_COMMON_H 4#define ZIP7_INC_ZIP_ADD_COMMON_H
5 5
6#include "../../ICoder.h" 6#include "../../ICoder.h"
7#include "../../IProgress.h" 7#include "../../IProgress.h"
@@ -68,7 +68,8 @@ public:
68 DECL_EXTERNAL_CODECS_LOC_VARS 68 DECL_EXTERNAL_CODECS_LOC_VARS
69 ISequentialInStream *inStream, IOutStream *outStream, 69 ISequentialInStream *inStream, IOutStream *outStream,
70 bool inSeqMode, bool outSeqMode, 70 bool inSeqMode, bool outSeqMode,
71 UInt32 fileTime, UInt64 expectedDataSize, 71 UInt32 fileTime,
72 UInt64 expectedDataSize, bool expectedDataSize_IsConfirmed,
72 ICompressProgressInfo *progress, CCompressingResult &opRes); 73 ICompressProgressInfo *progress, CCompressingResult &opRes);
73}; 74};
74 75
diff --git a/CPP/7zip/Archive/Zip/ZipCompressionMode.h b/CPP/7zip/Archive/Zip/ZipCompressionMode.h
index 842991c..8974261 100644
--- a/CPP/7zip/Archive/Zip/ZipCompressionMode.h
+++ b/CPP/7zip/Archive/Zip/ZipCompressionMode.h
@@ -1,11 +1,11 @@
1// CompressionMode.h 1// CompressionMode.h
2 2
3#ifndef __ZIP_COMPRESSION_MODE_H 3#ifndef ZIP7_INC_ZIP_COMPRESSION_MODE_H
4#define __ZIP_COMPRESSION_MODE_H 4#define ZIP7_INC_ZIP_COMPRESSION_MODE_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
8#ifndef _7ZIP_ST 8#ifndef Z7_ST
9#include "../../../Windows/System.h" 9#include "../../../Windows/System.h"
10#endif 10#endif
11 11
@@ -34,20 +34,26 @@ struct CBaseProps: public CMultiMethodProps
34struct CCompressionMethodMode: public CBaseProps 34struct CCompressionMethodMode: public CBaseProps
35{ 35{
36 CRecordVector<Byte> MethodSequence; 36 CRecordVector<Byte> MethodSequence;
37 bool PasswordIsDefined;
38 AString Password; // _Wipe 37 AString Password; // _Wipe
38 bool Password_Defined;
39 bool Force_SeqOutMode;
40 bool DataSizeReduce_Defined;
41 UInt64 DataSizeReduce;
39 42
40 UInt64 _dataSizeReduce; 43 bool IsRealAesMode() const { return Password_Defined && IsAesMode; }
41 bool _dataSizeReduceDefined;
42
43 bool IsRealAesMode() const { return PasswordIsDefined && IsAesMode; }
44 44
45 CCompressionMethodMode(): PasswordIsDefined(false) 45 CCompressionMethodMode()
46 { 46 {
47 _dataSizeReduceDefined = false; 47 Password_Defined = false;
48 _dataSizeReduce = 0; 48 Force_SeqOutMode = false;
49 DataSizeReduce_Defined = false;
50 DataSizeReduce = 0;
49 } 51 }
50 52
53#ifdef Z7_CPP_IS_SUPPORTED_default
54 CCompressionMethodMode(const CCompressionMethodMode &) = default;
55 CCompressionMethodMode& operator =(const CCompressionMethodMode &) = default;
56#endif
51 ~CCompressionMethodMode() { Password.Wipe_and_Empty(); } 57 ~CCompressionMethodMode() { Password.Wipe_and_Empty(); }
52}; 58};
53 59
diff --git a/CPP/7zip/Archive/Zip/ZipHandler.cpp b/CPP/7zip/Archive/Zip/ZipHandler.cpp
index 1b3985f..5f022cc 100644
--- a/CPP/7zip/Archive/Zip/ZipHandler.cpp
+++ b/CPP/7zip/Archive/Zip/ZipHandler.cpp
@@ -19,7 +19,7 @@
19 19
20#include "../../Compress/CopyCoder.h" 20#include "../../Compress/CopyCoder.h"
21 21
22#ifdef EXTERNAL_CODECS 22#ifdef Z7_EXTERNAL_CODECS
23#ifndef SUPPORT_LZFSE 23#ifndef SUPPORT_LZFSE
24#define SUPPORT_LZFSE 24#define SUPPORT_LZFSE
25#endif 25#endif
@@ -92,18 +92,20 @@ const char * const kMethodNames1[kNumMethodNames1] =
92 , "BZip2" 92 , "BZip2"
93 , NULL 93 , NULL
94 , "LZMA" 94 , "LZMA"
95 /*
95 , NULL 96 , NULL
96 , NULL 97 , NULL
97 , NULL 98 , NULL
98 , NULL 99 , NULL
99 , NULL 100 , NULL
100 , "zstd-pk" 101 , "zstd-pk" // deprecated
102 */
101}; 103};
102 104
103 105
104const char * const kMethodNames2[kNumMethodNames2] = 106const char * const kMethodNames2[kNumMethodNames2] =
105{ 107{
106 "zstd-wz" 108 "zstd"
107 , "MP3" 109 , "MP3"
108 , "xz" 110 , "xz"
109 , "Jpeg" 111 , "Jpeg"
@@ -129,6 +131,7 @@ static const CUInt32PCharPair g_HeaderCharacts[] =
129{ 131{
130 { 0, "Encrypt" }, 132 { 0, "Encrypt" },
131 { 3, "Descriptor" }, 133 { 3, "Descriptor" },
134 // { 4, "Enhanced" },
132 // { 5, "Patched" }, 135 // { 5, "Patched" },
133 { 6, kMethod_StrongCrypto }, 136 { 6, kMethod_StrongCrypto },
134 { 11, "UTF8" }, 137 { 11, "UTF8" },
@@ -221,7 +224,7 @@ static AString BytesToString(const CByteBuffer &data)
221IMP_IInArchive_Props 224IMP_IInArchive_Props
222IMP_IInArchive_ArcProps 225IMP_IInArchive_ArcProps
223 226
224STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 227Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
225{ 228{
226 COM_TRY_BEGIN 229 COM_TRY_BEGIN
227 NWindows::NCOM::CPropVariant prop; 230 NWindows::NCOM::CPropVariant prop;
@@ -343,7 +346,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
343 COM_TRY_END 346 COM_TRY_END
344} 347}
345 348
346STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 349Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
347{ 350{
348 *numItems = m_Items.Size(); 351 *numItems = m_Items.Size();
349 return S_OK; 352 return S_OK;
@@ -377,7 +380,7 @@ static bool NtfsUnixTimeToProp(bool fromCentral,
377} 380}
378 381
379 382
380STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 383Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
381{ 384{
382 COM_TRY_BEGIN 385 COM_TRY_BEGIN
383 NWindows::NCOM::CPropVariant prop; 386 NWindows::NCOM::CPropVariant prop;
@@ -521,7 +524,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
521 if (extra.GetWzAes(aesField)) 524 if (extra.GetWzAes(aesField))
522 { 525 {
523 m += kMethod_AES; 526 m += kMethod_AES;
524 m += '-'; 527 m.Add_Minus();
525 m.Add_UInt32(((unsigned)aesField.Strength + 1) * 64); 528 m.Add_UInt32(((unsigned)aesField.Strength + 1) * 64);
526 id = aesField.Method; 529 id = aesField.Method;
527 isWzAes = true; 530 isWzAes = true;
@@ -537,7 +540,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
537 f.AlgId = 0; 540 f.AlgId = 0;
538 if (extra.GetStrongCrypto(f)) 541 if (extra.GetStrongCrypto(f))
539 { 542 {
540 const char *s = FindNameForId(k_StrongCryptoPairs, ARRAY_SIZE(k_StrongCryptoPairs), f.AlgId); 543 const char *s = FindNameForId(k_StrongCryptoPairs, Z7_ARRAY_SIZE(k_StrongCryptoPairs), f.AlgId);
541 if (s) 544 if (s)
542 m += s; 545 m += s;
543 else 546 else
@@ -629,7 +632,7 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
629 632
630 if (flags != 0) 633 if (flags != 0)
631 { 634 {
632 AString s2 = FlagsToString(g_HeaderCharacts, ARRAY_SIZE(g_HeaderCharacts), flags); 635 const AString s2 = FlagsToString(g_HeaderCharacts, Z7_ARRAY_SIZE(g_HeaderCharacts), flags);
633 if (!s2.IsEmpty()) 636 if (!s2.IsEmpty())
634 { 637 {
635 if (!s.IsEmpty()) 638 if (!s.IsEmpty())
@@ -690,13 +693,13 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
690 693
691 694
692/* 695/*
693STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 696Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps)
694{ 697{
695 *numProps = 0; 698 *numProps = 0;
696 return S_OK; 699 return S_OK;
697} 700}
698 701
699STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 702Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)
700{ 703{
701 UNUSED_VAR(index); 704 UNUSED_VAR(index);
702 *propID = 0; 705 *propID = 0;
@@ -704,7 +707,7 @@ STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID)
704 return S_OK; 707 return S_OK;
705} 708}
706 709
707STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType) 710Z7_COM7F_IMF(CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentType)
708{ 711{
709 *parentType = NParentType::kDir; 712 *parentType = NParentType::kDir;
710 *parent = (UInt32)(Int32)-1; 713 *parent = (UInt32)(Int32)-1;
@@ -720,7 +723,7 @@ STDMETHODIMP CHandler::GetParent(UInt32 index, UInt32 *parent, UInt32 *parentTyp
720 return S_OK; 723 return S_OK;
721} 724}
722 725
723STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 726Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType)
724{ 727{
725 UNUSED_VAR(index); 728 UNUSED_VAR(index);
726 UNUSED_VAR(propID); 729 UNUSED_VAR(propID);
@@ -767,13 +770,16 @@ void CHandler::MarkAltStreams(CObjectVector<CItemEx> &items)
767} 770}
768*/ 771*/
769 772
770STDMETHODIMP CHandler::Open(IInStream *inStream, 773Z7_COM7F_IMF(CHandler::Open(IInStream *inStream,
771 const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback) 774 const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback))
772{ 775{
773 COM_TRY_BEGIN 776 COM_TRY_BEGIN
774 try 777 try
775 { 778 {
776 Close(); 779 Close();
780 m_Archive.Force_ReadLocals_Mode = _force_OpenSeq;
781 // m_Archive.Disable_VolsRead = _force_OpenSeq;
782 // m_Archive.Disable_FindMarker = _force_OpenSeq;
777 HRESULT res = m_Archive.Open(inStream, maxCheckStartPosition, callback, m_Items); 783 HRESULT res = m_Archive.Open(inStream, maxCheckStartPosition, callback, m_Items);
778 if (res != S_OK) 784 if (res != S_OK)
779 { 785 {
@@ -787,7 +793,7 @@ STDMETHODIMP CHandler::Open(IInStream *inStream,
787 COM_TRY_END 793 COM_TRY_END
788} 794}
789 795
790STDMETHODIMP CHandler::Close() 796Z7_COM7F_IMF(CHandler::Close())
791{ 797{
792 m_Items.Clear(); 798 m_Items.Clear();
793 m_Archive.Close(); 799 m_Archive.Close();
@@ -795,25 +801,16 @@ STDMETHODIMP CHandler::Close()
795} 801}
796 802
797 803
798class CLzmaDecoder: 804Z7_CLASS_IMP_NOQIB_3(
799 public ICompressCoder, 805 CLzmaDecoder
800 public ICompressSetFinishMode, 806 , ICompressCoder
801 public ICompressGetInStreamProcessedSize, 807 , ICompressSetFinishMode
802 public CMyUnknownImp 808 , ICompressGetInStreamProcessedSize
803{ 809)
804public: 810public:
805 NCompress::NLzma::CDecoder *DecoderSpec; 811 NCompress::NLzma::CDecoder *DecoderSpec;
806 CMyComPtr<ICompressCoder> Decoder; 812 CMyComPtr<ICompressCoder> Decoder;
807 813
808 MY_UNKNOWN_IMP2(
809 ICompressSetFinishMode,
810 ICompressGetInStreamProcessedSize)
811
812 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
813 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
814 STDMETHOD(SetFinishMode)(UInt32 finishMode);
815 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
816
817 CLzmaDecoder(); 814 CLzmaDecoder();
818}; 815};
819 816
@@ -825,14 +822,14 @@ CLzmaDecoder::CLzmaDecoder()
825 822
826static const unsigned kZipLzmaPropsSize = 4 + LZMA_PROPS_SIZE; 823static const unsigned kZipLzmaPropsSize = 4 + LZMA_PROPS_SIZE;
827 824
828HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 825Z7_COM7F_IMF(CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
829 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 826 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
830{ 827{
831 Byte buf[kZipLzmaPropsSize]; 828 Byte buf[kZipLzmaPropsSize];
832 RINOK(ReadStream_FALSE(inStream, buf, kZipLzmaPropsSize)); 829 RINOK(ReadStream_FALSE(inStream, buf, kZipLzmaPropsSize))
833 if (buf[2] != LZMA_PROPS_SIZE || buf[3] != 0) 830 if (buf[2] != LZMA_PROPS_SIZE || buf[3] != 0)
834 return E_NOTIMPL; 831 return E_NOTIMPL;
835 RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, LZMA_PROPS_SIZE)); 832 RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, LZMA_PROPS_SIZE))
836 UInt64 inSize2 = 0; 833 UInt64 inSize2 = 0;
837 if (inSize) 834 if (inSize)
838 { 835 {
@@ -844,13 +841,13 @@ HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *
844 return Decoder->Code(inStream, outStream, inSize ? &inSize2 : NULL, outSize, progress); 841 return Decoder->Code(inStream, outStream, inSize ? &inSize2 : NULL, outSize, progress);
845} 842}
846 843
847STDMETHODIMP CLzmaDecoder::SetFinishMode(UInt32 finishMode) 844Z7_COM7F_IMF(CLzmaDecoder::SetFinishMode(UInt32 finishMode))
848{ 845{
849 DecoderSpec->FinishStream = (finishMode != 0); 846 DecoderSpec->FinishStream = (finishMode != 0);
850 return S_OK; 847 return S_OK;
851} 848}
852 849
853STDMETHODIMP CLzmaDecoder::GetInStreamProcessedSize(UInt64 *value) 850Z7_COM7F_IMF(CLzmaDecoder::GetInStreamProcessedSize(UInt64 *value))
854{ 851{
855 *value = DecoderSpec->GetInputProcessedSize() + kZipLzmaPropsSize; 852 *value = DecoderSpec->GetInputProcessedSize() + kZipLzmaPropsSize;
856 return S_OK; 853 return S_OK;
@@ -888,11 +885,11 @@ class CZipDecoder
888 CLzmaDecoder *lzmaDecoderSpec; 885 CLzmaDecoder *lzmaDecoderSpec;
889public: 886public:
890 CZipDecoder(): 887 CZipDecoder():
891 _zipCryptoDecoderSpec(0), 888 _zipCryptoDecoderSpec(NULL),
892 _pkAesDecoderSpec(0), 889 _pkAesDecoderSpec(NULL),
893 _wzAesDecoderSpec(0), 890 _wzAesDecoderSpec(NULL),
894 filterStreamSpec(0), 891 filterStreamSpec(NULL),
895 lzmaDecoderSpec(0) 892 lzmaDecoderSpec(NULL)
896 {} 893 {}
897 894
898 HRESULT Decode( 895 HRESULT Decode(
@@ -901,7 +898,7 @@ public:
901 ISequentialOutStream *realOutStream, 898 ISequentialOutStream *realOutStream,
902 IArchiveExtractCallback *extractCallback, 899 IArchiveExtractCallback *extractCallback,
903 ICompressProgressInfo *compressProgress, 900 ICompressProgressInfo *compressProgress,
904 #ifndef _7ZIP_ST 901 #ifndef Z7_ST
905 UInt32 numThreads, UInt64 memUsage, 902 UInt32 numThreads, UInt64 memUsage,
906 #endif 903 #endif
907 Int32 &res); 904 Int32 &res);
@@ -919,7 +916,7 @@ static HRESULT SkipStreamData(ISequentialInStream *stream,
919 for (;;) 916 for (;;)
920 { 917 {
921 size_t size = kBufSize; 918 size_t size = kBufSize;
922 RINOK(ReadStream(stream, buf, &size)); 919 RINOK(ReadStream(stream, buf, &size))
923 if (size == 0) 920 if (size == 0)
924 return S_OK; 921 return S_OK;
925 thereAreData = true; 922 thereAreData = true;
@@ -927,25 +924,23 @@ static HRESULT SkipStreamData(ISequentialInStream *stream,
927 if ((packSize - prev) >= (1 << 22)) 924 if ((packSize - prev) >= (1 << 22))
928 { 925 {
929 prev = packSize; 926 prev = packSize;
930 RINOK(progress->SetRatioInfo(&packSize, &unpackSize)); 927 RINOK(progress->SetRatioInfo(&packSize, &unpackSize))
931 } 928 }
932 } 929 }
933} 930}
934 931
935 932
936 933
937class COutStreamWithPadPKCS7: 934Z7_CLASS_IMP_NOQIB_1(
938 public ISequentialOutStream, 935 COutStreamWithPadPKCS7
939 public CMyUnknownImp 936 , ISequentialOutStream
940{ 937)
941 CMyComPtr<ISequentialOutStream> _stream; 938 CMyComPtr<ISequentialOutStream> _stream;
942 UInt64 _size; 939 UInt64 _size;
943 UInt64 _padPos; 940 UInt64 _padPos;
944 UInt32 _padSize; 941 UInt32 _padSize;
945 bool _padFailure; 942 bool _padFailure;
946public: 943public:
947 MY_UNKNOWN_IMP
948 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
949 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 944 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
950 void ReleaseStream() { _stream.Release(); } 945 void ReleaseStream() { _stream.Release(); }
951 946
@@ -962,7 +957,7 @@ public:
962}; 957};
963 958
964 959
965STDMETHODIMP COutStreamWithPadPKCS7::Write(const void *data, UInt32 size, UInt32 *processedSize) 960Z7_COM7F_IMF(COutStreamWithPadPKCS7::Write(const void *data, UInt32 size, UInt32 *processedSize))
966{ 961{
967 UInt32 written = 0; 962 UInt32 written = 0;
968 HRESULT result = S_OK; 963 HRESULT result = S_OK;
@@ -1003,7 +998,7 @@ HRESULT CZipDecoder::Decode(
1003 ISequentialOutStream *realOutStream, 998 ISequentialOutStream *realOutStream,
1004 IArchiveExtractCallback *extractCallback, 999 IArchiveExtractCallback *extractCallback,
1005 ICompressProgressInfo *compressProgress, 1000 ICompressProgressInfo *compressProgress,
1006 #ifndef _7ZIP_ST 1001 #ifndef Z7_ST
1007 UInt32 numThreads, UInt64 memUsage, 1002 UInt32 numThreads, UInt64 memUsage,
1008 #endif 1003 #endif
1009 Int32 &res) 1004 Int32 &res)
@@ -1074,7 +1069,7 @@ HRESULT CZipDecoder::Decode(
1074 return S_OK; 1069 return S_OK;
1075 packSize -= NCrypto::NWzAes::kMacSize; 1070 packSize -= NCrypto::NWzAes::kMacSize;
1076 } 1071 }
1077 RINOK(archive.GetItemStream(item, true, packStream)); 1072 RINOK(archive.GetItemStream(item, true, packStream))
1078 if (!packStream) 1073 if (!packStream)
1079 { 1074 {
1080 res = NExtract::NOperationResult::kUnavailable; 1075 res = NExtract::NOperationResult::kUnavailable;
@@ -1126,7 +1121,7 @@ HRESULT CZipDecoder::Decode(
1126 } 1121 }
1127 1122
1128 CMyComPtr<ICryptoSetPassword> cryptoSetPassword; 1123 CMyComPtr<ICryptoSetPassword> cryptoSetPassword;
1129 RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)); 1124 RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword))
1130 if (!cryptoSetPassword) 1125 if (!cryptoSetPassword)
1131 return E_FAIL; 1126 return E_FAIL;
1132 1127
@@ -1136,12 +1131,12 @@ HRESULT CZipDecoder::Decode(
1136 if (getTextPassword) 1131 if (getTextPassword)
1137 { 1132 {
1138 CMyComBSTR_Wipe password; 1133 CMyComBSTR_Wipe password;
1139 RINOK(getTextPassword->CryptoGetTextPassword(&password)); 1134 RINOK(getTextPassword->CryptoGetTextPassword(&password))
1140 AString_Wipe charPassword; 1135 AString_Wipe charPassword;
1141 if (password) 1136 if (password)
1142 { 1137 {
1143 /* 1138 /*
1144 // 22.00: do we need UTF-8 passwords here ? 1139 // 22.00: do we need UTF-8 passwords here ?
1145 if (item.IsUtf8()) // 22.00 1140 if (item.IsUtf8()) // 22.00
1146 { 1141 {
1147 // throw 1; 1142 // throw 1;
@@ -1226,7 +1221,7 @@ HRESULT CZipDecoder::Decode(
1226 szMethodID = kMethodId_ZipBase + (Byte)id; 1221 szMethodID = kMethodId_ZipBase + (Byte)id;
1227 } 1222 }
1228 1223
1229 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS szMethodID, false, mi.Coder)); 1224 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS szMethodID, false, mi.Coder))
1230 1225
1231 if (!mi.Coder) 1226 if (!mi.Coder)
1232 { 1227 {
@@ -1241,13 +1236,13 @@ HRESULT CZipDecoder::Decode(
1241 ICompressCoder *coder = mi.Coder; 1236 ICompressCoder *coder = mi.Coder;
1242 1237
1243 1238
1244 #ifndef _7ZIP_ST 1239 #ifndef Z7_ST
1245 { 1240 {
1246 CMyComPtr<ICompressSetCoderMt> setCoderMt; 1241 CMyComPtr<ICompressSetCoderMt> setCoderMt;
1247 coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); 1242 coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt);
1248 if (setCoderMt) 1243 if (setCoderMt)
1249 { 1244 {
1250 RINOK(setCoderMt->SetNumberOfThreads(numThreads)); 1245 RINOK(setCoderMt->SetNumberOfThreads(numThreads))
1251 } 1246 }
1252 } 1247 }
1253 // if (memUsage != 0) 1248 // if (memUsage != 0)
@@ -1256,7 +1251,7 @@ HRESULT CZipDecoder::Decode(
1256 coder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit); 1251 coder->QueryInterface(IID_ICompressSetMemLimit, (void **)&setMemLimit);
1257 if (setMemLimit) 1252 if (setMemLimit)
1258 { 1253 {
1259 RINOK(setMemLimit->SetMemLimit(memUsage)); 1254 RINOK(setMemLimit->SetMemLimit(memUsage))
1260 } 1255 }
1261 } 1256 }
1262 #endif 1257 #endif
@@ -1267,7 +1262,7 @@ HRESULT CZipDecoder::Decode(
1267 if (setDecoderProperties) 1262 if (setDecoderProperties)
1268 { 1263 {
1269 Byte properties = (Byte)item.Flags; 1264 Byte properties = (Byte)item.Flags;
1270 RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)); 1265 RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1))
1271 } 1266 }
1272 } 1267 }
1273 1268
@@ -1363,7 +1358,7 @@ HRESULT CZipDecoder::Decode(
1363 coder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); 1358 coder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode);
1364 if (setFinishMode) 1359 if (setFinishMode)
1365 { 1360 {
1366 RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))); 1361 RINOK(setFinishMode->SetFinishMode(BoolToUInt(true)))
1367 } 1362 }
1368 1363
1369 const UInt64 coderPackSize = limitedStreamSpec->GetRem(); 1364 const UInt64 coderPackSize = limitedStreamSpec->GetRem();
@@ -1421,12 +1416,12 @@ HRESULT CZipDecoder::Decode(
1421 { 1416 {
1422 readFromFilter = true; 1417 readFromFilter = true;
1423 inStreamReleaser.FilterCoder = filterStreamSpec; 1418 inStreamReleaser.FilterCoder = filterStreamSpec;
1424 RINOK(filterStreamSpec->SetInStream(inStream)); 1419 RINOK(filterStreamSpec->SetInStream(inStream))
1425 1420
1426 /* IFilter::Init() does nothing in all zip crypto filters. 1421 /* IFilter::Init() does nothing in all zip crypto filters.
1427 So we can call any Initialize function in CFilterCoder. */ 1422 So we can call any Initialize function in CFilterCoder. */
1428 1423
1429 RINOK(filterStreamSpec->Init_NoSubFilterInit()); 1424 RINOK(filterStreamSpec->Init_NoSubFilterInit())
1430 // RINOK(filterStreamSpec->SetOutStreamSize(NULL)); 1425 // RINOK(filterStreamSpec->SetOutStreamSize(NULL));
1431 } 1426 }
1432 1427
@@ -1448,7 +1443,7 @@ HRESULT CZipDecoder::Decode(
1448 if (getInStreamProcessedSize && setFinishMode) 1443 if (getInStreamProcessedSize && setFinishMode)
1449 { 1444 {
1450 UInt64 processed; 1445 UInt64 processed;
1451 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); 1446 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed))
1452 if (processed != (UInt64)(Int64)-1) 1447 if (processed != (UInt64)(Int64)-1)
1453 { 1448 {
1454 if (pkAesMode) 1449 if (pkAesMode)
@@ -1474,7 +1469,7 @@ HRESULT CZipDecoder::Decode(
1474 UInt32 processedSize = 0; 1469 UInt32 processedSize = 0;
1475 if (readInStream) 1470 if (readInStream)
1476 { 1471 {
1477 RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize)); 1472 RINOK(readInStream->ReadUnusedFromInBuf(buf, kBufSize, &processedSize))
1478 } 1473 }
1479 if (processedSize > padSize) 1474 if (processedSize > padSize)
1480 dataAfterEnd = true; 1475 dataAfterEnd = true;
@@ -1532,7 +1527,7 @@ HRESULT CZipDecoder::Decode(
1532 return S_OK; 1527 return S_OK;
1533 } 1528 }
1534 1529
1535 RINOK(result); 1530 RINOK(result)
1536 } 1531 }
1537 1532
1538 bool crcOK = true; 1533 bool crcOK = true;
@@ -1600,66 +1595,59 @@ HRESULT CZipDecoder::Decode(
1600} 1595}
1601 1596
1602 1597
1603STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1598Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1604 Int32 testMode, IArchiveExtractCallback *extractCallback) 1599 Int32 testMode, IArchiveExtractCallback *extractCallback))
1605{ 1600{
1606 COM_TRY_BEGIN 1601 COM_TRY_BEGIN
1607 CZipDecoder myDecoder; 1602 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1608 UInt64 totalUnPacked = 0, totalPacked = 0;
1609 bool allFilesMode = (numItems == (UInt32)(Int32)-1);
1610 if (allFilesMode) 1603 if (allFilesMode)
1611 numItems = m_Items.Size(); 1604 numItems = m_Items.Size();
1612 if (numItems == 0) 1605 if (numItems == 0)
1613 return S_OK; 1606 return S_OK;
1607 UInt64 total = 0; // , totalPacked = 0;
1614 UInt32 i; 1608 UInt32 i;
1615 for (i = 0; i < numItems; i++) 1609 for (i = 0; i < numItems; i++)
1616 { 1610 {
1617 const CItemEx &item = m_Items[allFilesMode ? i : indices[i]]; 1611 const CItemEx &item = m_Items[allFilesMode ? i : indices[i]];
1618 totalUnPacked += item.Size; 1612 total += item.Size;
1619 totalPacked += item.PackSize; 1613 // totalPacked += item.PackSize;
1620 } 1614 }
1621 RINOK(extractCallback->SetTotal(totalUnPacked)); 1615 RINOK(extractCallback->SetTotal(total))
1622 1616
1623 UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; 1617 CZipDecoder myDecoder;
1624 UInt64 currentItemUnPacked, currentItemPacked; 1618 UInt64 cur_Unpacked, cur_Packed;
1625 1619
1626 CLocalProgress *lps = new CLocalProgress; 1620 CLocalProgress *lps = new CLocalProgress;
1627 CMyComPtr<ICompressProgressInfo> progress = lps; 1621 CMyComPtr<ICompressProgressInfo> progress = lps;
1628 lps->Init(extractCallback, false); 1622 lps->Init(extractCallback, false);
1629 1623
1630 for (i = 0; i < numItems; i++, 1624 for (i = 0;; i++,
1631 currentTotalUnPacked += currentItemUnPacked, 1625 lps->OutSize += cur_Unpacked,
1632 currentTotalPacked += currentItemPacked) 1626 lps->InSize += cur_Packed)
1633 { 1627 {
1634 currentItemUnPacked = 0; 1628 RINOK(lps->SetCur())
1635 currentItemPacked = 0; 1629 if (i >= numItems)
1636 1630 return S_OK;
1637 lps->InSize = currentTotalPacked; 1631 const UInt32 index = allFilesMode ? i : indices[i];
1638 lps->OutSize = currentTotalUnPacked; 1632 CItemEx item = m_Items[index];
1639 RINOK(lps->SetCur()); 1633 cur_Unpacked = item.Size;
1634 cur_Packed = item.PackSize;
1640 1635
1641 CMyComPtr<ISequentialOutStream> realOutStream; 1636 const bool isLocalOffsetOK = m_Archive.IsLocalOffsetOK(item);
1642 Int32 askMode = testMode ? 1637 const bool skip = !isLocalOffsetOK && !item.IsDir();
1638 const Int32 askMode = skip ?
1639 NExtract::NAskMode::kSkip : testMode ?
1643 NExtract::NAskMode::kTest : 1640 NExtract::NAskMode::kTest :
1644 NExtract::NAskMode::kExtract; 1641 NExtract::NAskMode::kExtract;
1645 UInt32 index = allFilesMode ? i : indices[i];
1646 1642
1647 CItemEx item = m_Items[index]; 1643 CMyComPtr<ISequentialOutStream> realOutStream;
1648 bool isLocalOffsetOK = m_Archive.IsLocalOffsetOK(item); 1644 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1649 bool skip = !isLocalOffsetOK && !item.IsDir();
1650 if (skip)
1651 askMode = NExtract::NAskMode::kSkip;
1652
1653 currentItemUnPacked = item.Size;
1654 currentItemPacked = item.PackSize;
1655
1656 RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
1657 1645
1658 if (!isLocalOffsetOK) 1646 if (!isLocalOffsetOK)
1659 { 1647 {
1660 RINOK(extractCallback->PrepareOperation(askMode)); 1648 RINOK(extractCallback->PrepareOperation(askMode))
1661 realOutStream.Release(); 1649 realOutStream.Release();
1662 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnavailable)); 1650 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnavailable))
1663 continue; 1651 continue;
1664 } 1652 }
1665 1653
@@ -1668,30 +1656,30 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1668 if (!item.FromLocal) 1656 if (!item.FromLocal)
1669 { 1657 {
1670 bool isAvail = true; 1658 bool isAvail = true;
1671 HRESULT res = m_Archive.ReadLocalItemAfterCdItem(item, isAvail, headersError); 1659 const HRESULT hres = m_Archive.Read_LocalItem_After_CdItem(item, isAvail, headersError);
1672 if (res == S_FALSE) 1660 if (hres == S_FALSE)
1673 { 1661 {
1674 if (item.IsDir() || realOutStream || testMode) 1662 if (item.IsDir() || realOutStream || testMode)
1675 { 1663 {
1676 RINOK(extractCallback->PrepareOperation(askMode)); 1664 RINOK(extractCallback->PrepareOperation(askMode))
1677 realOutStream.Release(); 1665 realOutStream.Release();
1678 RINOK(extractCallback->SetOperationResult( 1666 RINOK(extractCallback->SetOperationResult(
1679 isAvail ? 1667 isAvail ?
1680 NExtract::NOperationResult::kHeadersError : 1668 NExtract::NOperationResult::kHeadersError :
1681 NExtract::NOperationResult::kUnavailable)); 1669 NExtract::NOperationResult::kUnavailable))
1682 } 1670 }
1683 continue; 1671 continue;
1684 } 1672 }
1685 RINOK(res); 1673 RINOK(hres)
1686 } 1674 }
1687 1675
1688 if (item.IsDir()) 1676 if (item.IsDir())
1689 { 1677 {
1690 // if (!testMode) 1678 // if (!testMode)
1691 { 1679 {
1692 RINOK(extractCallback->PrepareOperation(askMode)); 1680 RINOK(extractCallback->PrepareOperation(askMode))
1693 realOutStream.Release(); 1681 realOutStream.Release();
1694 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); 1682 RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK))
1695 } 1683 }
1696 continue; 1684 continue;
1697 } 1685 }
@@ -1699,19 +1687,19 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1699 if (!testMode && !realOutStream) 1687 if (!testMode && !realOutStream)
1700 continue; 1688 continue;
1701 1689
1702 RINOK(extractCallback->PrepareOperation(askMode)); 1690 RINOK(extractCallback->PrepareOperation(askMode))
1703 1691
1704 Int32 res; 1692 Int32 res;
1705 HRESULT hres = myDecoder.Decode( 1693 const HRESULT hres = myDecoder.Decode(
1706 EXTERNAL_CODECS_VARS 1694 EXTERNAL_CODECS_VARS
1707 m_Archive, item, realOutStream, extractCallback, 1695 m_Archive, item, realOutStream, extractCallback,
1708 progress, 1696 progress,
1709 #ifndef _7ZIP_ST 1697 #ifndef Z7_ST
1710 _props._numThreads, _props._memUsage_Decompress, 1698 _props._numThreads, _props._memUsage_Decompress,
1711 #endif 1699 #endif
1712 res); 1700 res);
1713 1701
1714 RINOK(hres); 1702 RINOK(hres)
1715 realOutStream.Release(); 1703 realOutStream.Release();
1716 1704
1717 if (res == NExtract::NOperationResult::kOK && headersError) 1705 if (res == NExtract::NOperationResult::kOK && headersError)
@@ -1720,9 +1708,6 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1720 RINOK(extractCallback->SetOperationResult(res)) 1708 RINOK(extractCallback->SetOperationResult(res))
1721 } 1709 }
1722 1710
1723 lps->InSize = currentTotalPacked;
1724 lps->OutSize = currentTotalUnPacked;
1725 return lps->SetCur();
1726 COM_TRY_END 1711 COM_TRY_END
1727} 1712}
1728 1713
diff --git a/CPP/7zip/Archive/Zip/ZipHandler.h b/CPP/7zip/Archive/Zip/ZipHandler.h
index a70a1a7..1f38bff 100644
--- a/CPP/7zip/Archive/Zip/ZipHandler.h
+++ b/CPP/7zip/Archive/Zip/ZipHandler.h
@@ -1,7 +1,7 @@
1// Zip/Handler.h 1// Zip/Handler.h
2 2
3#ifndef __ZIP_HANDLER_H 3#ifndef ZIP7_INC_ZIP_HANDLER_H
4#define __ZIP_HANDLER_H 4#define ZIP7_INC_ZIP_HANDLER_H
5 5
6#include "../../../Common/DynamicBuffer.h" 6#include "../../../Common/DynamicBuffer.h"
7#include "../../ICoder.h" 7#include "../../ICoder.h"
@@ -23,46 +23,43 @@ extern const char * const kMethodNames1[kNumMethodNames1];
23extern const char * const kMethodNames2[kNumMethodNames2]; 23extern const char * const kMethodNames2[kNumMethodNames2];
24 24
25 25
26class CHandler: 26class CHandler Z7_final:
27 public IInArchive, 27 public IInArchive,
28 // public IArchiveGetRawProps, 28 // public IArchiveGetRawProps,
29 public IOutArchive, 29 public IOutArchive,
30 public ISetProperties, 30 public ISetProperties,
31 PUBLIC_ISetCompressCodecsInfo 31 Z7_PUBLIC_ISetCompressCodecsInfo_IFEC
32 public CMyUnknownImp 32 public CMyUnknownImp
33{ 33{
34public: 34 Z7_COM_QI_BEGIN2(IInArchive)
35 MY_QUERYINTERFACE_BEGIN2(IInArchive) 35 // Z7_COM_QI_ENTRY(IArchiveGetRawProps)
36 // MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) 36 Z7_COM_QI_ENTRY(IOutArchive)
37 MY_QUERYINTERFACE_ENTRY(IOutArchive) 37 Z7_COM_QI_ENTRY(ISetProperties)
38 MY_QUERYINTERFACE_ENTRY(ISetProperties) 38 Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC
39 QUERY_ENTRY_ISetCompressCodecsInfo 39 Z7_COM_QI_END
40 MY_QUERYINTERFACE_END 40 Z7_COM_ADDREF_RELEASE
41 MY_ADDREF_RELEASE 41
42 42 Z7_IFACE_COM7_IMP(IInArchive)
43 INTERFACE_IInArchive(;) 43 // Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
44 // INTERFACE_IArchiveGetRawProps(;) 44 Z7_IFACE_COM7_IMP(IOutArchive)
45 INTERFACE_IOutArchive(;) 45 Z7_IFACE_COM7_IMP(ISetProperties)
46
47 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
48
49 DECL_ISetCompressCodecsInfo 46 DECL_ISetCompressCodecsInfo
50 47
51 CHandler();
52private: 48private:
53 CObjectVector<CItemEx> m_Items; 49 CObjectVector<CItemEx> m_Items;
54 CInArchive m_Archive; 50 CInArchive m_Archive;
55 51
56 CBaseProps _props; 52 CBaseProps _props;
53 CHandlerTimeOptions TimeOptions;
57 54
58 int m_MainMethod; 55 int m_MainMethod;
59 bool m_ForceAesMode; 56 bool m_ForceAesMode;
60 57
61 CHandlerTimeOptions TimeOptions;
62
63 bool _removeSfxBlock; 58 bool _removeSfxBlock;
64 bool m_ForceLocal; 59 bool m_ForceLocal;
65 bool m_ForceUtf8; 60 bool m_ForceUtf8;
61 bool _force_SeqOutMode; // for creation
62 bool _force_OpenSeq;
66 bool _forceCodePage; 63 bool _forceCodePage;
67 UInt32 _specifiedCodePage; 64 UInt32 _specifiedCodePage;
68 65
@@ -71,13 +68,15 @@ private:
71 void InitMethodProps() 68 void InitMethodProps()
72 { 69 {
73 _props.Init(); 70 _props.Init();
74 m_MainMethod = -1;
75 m_ForceAesMode = false;
76 TimeOptions.Init(); 71 TimeOptions.Init();
77 TimeOptions.Prec = k_PropVar_TimePrec_0; 72 TimeOptions.Prec = k_PropVar_TimePrec_0;
73 m_MainMethod = -1;
74 m_ForceAesMode = false;
78 _removeSfxBlock = false; 75 _removeSfxBlock = false;
79 m_ForceLocal = false; 76 m_ForceLocal = false;
80 m_ForceUtf8 = false; 77 m_ForceUtf8 = false;
78 _force_SeqOutMode = false;
79 _force_OpenSeq = false;
81 _forceCodePage = false; 80 _forceCodePage = false;
82 _specifiedCodePage = CP_OEMCP; 81 _specifiedCodePage = CP_OEMCP;
83 } 82 }
@@ -85,6 +84,9 @@ private:
85 // void MarkAltStreams(CObjectVector<CItemEx> &items); 84 // void MarkAltStreams(CObjectVector<CItemEx> &items);
86 85
87 HRESULT GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value); 86 HRESULT GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value);
87
88public:
89 CHandler();
88}; 90};
89 91
90}} 92}}
diff --git a/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp b/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp
index 77a71df..19699b5 100644
--- a/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp
+++ b/CPP/7zip/Archive/Zip/ZipHandlerOut.cpp
@@ -28,7 +28,7 @@ using namespace NTime;
28namespace NArchive { 28namespace NArchive {
29namespace NZip { 29namespace NZip {
30 30
31STDMETHODIMP CHandler::GetFileTimeType(UInt32 *timeType) 31Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *timeType))
32{ 32{
33 *timeType = TimeOptions.Prec; 33 *timeType = TimeOptions.Prec;
34 return S_OK; 34 return S_OK;
@@ -79,7 +79,7 @@ static HRESULT GetTime(IArchiveUpdateCallback *callback, unsigned index, PROPID
79{ 79{
80 filetime.dwHighDateTime = filetime.dwLowDateTime = 0; 80 filetime.dwHighDateTime = filetime.dwLowDateTime = 0;
81 NCOM::CPropVariant prop; 81 NCOM::CPropVariant prop;
82 RINOK(callback->GetProperty(index, propID, &prop)); 82 RINOK(callback->GetProperty(index, propID, &prop))
83 if (prop.vt == VT_FILETIME) 83 if (prop.vt == VT_FILETIME)
84 filetime = prop.filetime; 84 filetime = prop.filetime;
85 else if (prop.vt != VT_EMPTY) 85 else if (prop.vt != VT_EMPTY)
@@ -88,8 +88,8 @@ static HRESULT GetTime(IArchiveUpdateCallback *callback, unsigned index, PROPID
88} 88}
89 89
90 90
91STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 91Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
92 IArchiveUpdateCallback *callback) 92 IArchiveUpdateCallback *callback))
93{ 93{
94 COM_TRY_BEGIN2 94 COM_TRY_BEGIN2
95 95
@@ -122,7 +122,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
122 if (!callback) 122 if (!callback)
123 return E_FAIL; 123 return E_FAIL;
124 124
125 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); 125 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc))
126 126
127 name.Empty(); 127 name.Empty();
128 ui.Clear(); 128 ui.Clear();
@@ -147,7 +147,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
147 { 147 {
148 { 148 {
149 NCOM::CPropVariant prop; 149 NCOM::CPropVariant prop;
150 RINOK(callback->GetProperty(i, kpidAttrib, &prop)); 150 RINOK(callback->GetProperty(i, kpidAttrib, &prop))
151 if (prop.vt == VT_EMPTY) 151 if (prop.vt == VT_EMPTY)
152 ui.Attrib = 0; 152 ui.Attrib = 0;
153 else if (prop.vt != VT_UI4) 153 else if (prop.vt != VT_UI4)
@@ -158,7 +158,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
158 158
159 { 159 {
160 NCOM::CPropVariant prop; 160 NCOM::CPropVariant prop;
161 RINOK(callback->GetProperty(i, kpidPath, &prop)); 161 RINOK(callback->GetProperty(i, kpidPath, &prop))
162 if (prop.vt == VT_EMPTY) 162 if (prop.vt == VT_EMPTY)
163 { 163 {
164 // name.Empty(); 164 // name.Empty();
@@ -171,7 +171,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
171 171
172 { 172 {
173 NCOM::CPropVariant prop; 173 NCOM::CPropVariant prop;
174 RINOK(callback->GetProperty(i, kpidIsDir, &prop)); 174 RINOK(callback->GetProperty(i, kpidIsDir, &prop))
175 if (prop.vt == VT_EMPTY) 175 if (prop.vt == VT_EMPTY)
176 ui.IsDir = false; 176 ui.IsDir = false;
177 else if (prop.vt != VT_BOOL) 177 else if (prop.vt != VT_BOOL)
@@ -219,9 +219,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
219 } 219 }
220 */ 220 */
221 221
222 if (TimeOptions.Write_MTime.Val) RINOK (GetTime (callback, i, kpidMTime, ui.Ntfs_MTime)); 222 if (TimeOptions.Write_MTime.Val) RINOK (GetTime (callback, i, kpidMTime, ui.Ntfs_MTime))
223 if (TimeOptions.Write_ATime.Val) RINOK (GetTime (callback, i, kpidATime, ui.Ntfs_ATime)); 223 if (TimeOptions.Write_ATime.Val) RINOK (GetTime (callback, i, kpidATime, ui.Ntfs_ATime))
224 if (TimeOptions.Write_CTime.Val) RINOK (GetTime (callback, i, kpidCTime, ui.Ntfs_CTime)); 224 if (TimeOptions.Write_CTime.Val) RINOK (GetTime (callback, i, kpidCTime, ui.Ntfs_CTime))
225 225
226 if (TimeOptions.Prec != k_PropVar_TimePrec_DOS) 226 if (TimeOptions.Prec != k_PropVar_TimePrec_DOS)
227 { 227 {
@@ -325,7 +325,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
325 325
326 { 326 {
327 NCOM::CPropVariant prop; 327 NCOM::CPropVariant prop;
328 RINOK(callback->GetProperty(i, kpidComment, &prop)); 328 RINOK(callback->GetProperty(i, kpidComment, &prop))
329 if (prop.vt == VT_EMPTY) 329 if (prop.vt == VT_EMPTY)
330 { 330 {
331 // ui.Comment.Free(); 331 // ui.Comment.Free();
@@ -374,7 +374,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
374 if (!ui.IsDir) 374 if (!ui.IsDir)
375 { 375 {
376 NCOM::CPropVariant prop; 376 NCOM::CPropVariant prop;
377 RINOK(callback->GetProperty(i, kpidSize, &prop)); 377 RINOK(callback->GetProperty(i, kpidSize, &prop))
378 if (prop.vt != VT_UI8) 378 if (prop.vt != VT_UI8)
379 return E_INVALIDARG; 379 return E_INVALIDARG;
380 size = prop.uhVal.QuadPart; 380 size = prop.uhVal.QuadPart;
@@ -396,18 +396,18 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
396 } 396 }
397 CCompressionMethodMode options; 397 CCompressionMethodMode options;
398 (CBaseProps &)options = _props; 398 (CBaseProps &)options = _props;
399 options._dataSizeReduce = largestSize; 399 options.DataSizeReduce = largestSize;
400 options._dataSizeReduceDefined = largestSizeDefined; 400 options.DataSizeReduce_Defined = largestSizeDefined;
401 401
402 options.PasswordIsDefined = false; 402 options.Password_Defined = false;
403 options.Password.Wipe_and_Empty(); 403 options.Password.Wipe_and_Empty();
404 if (getTextPassword) 404 if (getTextPassword)
405 { 405 {
406 CMyComBSTR_Wipe password; 406 CMyComBSTR_Wipe password;
407 Int32 passwordIsDefined; 407 Int32 passwordIsDefined;
408 RINOK(getTextPassword->CryptoGetTextPassword2(&passwordIsDefined, &password)); 408 RINOK(getTextPassword->CryptoGetTextPassword2(&passwordIsDefined, &password))
409 options.PasswordIsDefined = IntToBool(passwordIsDefined); 409 options.Password_Defined = IntToBool(passwordIsDefined);
410 if (options.PasswordIsDefined) 410 if (options.Password_Defined)
411 { 411 {
412 if (!m_ForceAesMode) 412 if (!m_ForceAesMode)
413 options.IsAesMode = thereAreAesUpdates; 413 options.IsAesMode = thereAreAesUpdates;
@@ -439,8 +439,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
439 { 439 {
440 CMethodId methodId; 440 CMethodId methodId;
441 UInt32 numStreams; 441 UInt32 numStreams;
442 bool isFilter;
442 if (FindMethod_Index(EXTERNAL_CODECS_VARS methodName, true, 443 if (FindMethod_Index(EXTERNAL_CODECS_VARS methodName, true,
443 methodId, numStreams) < 0) 444 methodId, numStreams, isFilter) < 0)
444 return E_NOTIMPL; 445 return E_NOTIMPL;
445 if (numStreams != 1) 446 if (numStreams != 1)
446 return E_NOTIMPL; 447 return E_NOTIMPL;
@@ -472,6 +473,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
472 if (mainMethod != NFileHeader::NCompressionMethod::kStore) 473 if (mainMethod != NFileHeader::NCompressionMethod::kStore)
473 options.MethodSequence.Add(NFileHeader::NCompressionMethod::kStore); 474 options.MethodSequence.Add(NFileHeader::NCompressionMethod::kStore);
474 475
476 options.Force_SeqOutMode = _force_SeqOutMode;
477
475 CUpdateOptions uo; 478 CUpdateOptions uo;
476 uo.Write_MTime = TimeOptions.Write_MTime.Val; 479 uo.Write_MTime = TimeOptions.Write_MTime.Val;
477 uo.Write_ATime = TimeOptions.Write_ATime.Val; 480 uo.Write_ATime = TimeOptions.Write_ATime.Val;
@@ -493,7 +496,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
493 496
494 497
495 498
496STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 499Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
497{ 500{
498 InitMethodProps(); 501 InitMethodProps();
499 502
@@ -540,26 +543,34 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
540 543
541 else if (name.IsEqualTo("cl")) 544 else if (name.IsEqualTo("cl"))
542 { 545 {
543 RINOK(PROPVARIANT_to_bool(prop, m_ForceLocal)); 546 RINOK(PROPVARIANT_to_bool(prop, m_ForceLocal))
544 if (m_ForceLocal) 547 if (m_ForceLocal)
545 m_ForceUtf8 = false; 548 m_ForceUtf8 = false;
546 } 549 }
547 else if (name.IsEqualTo("cu")) 550 else if (name.IsEqualTo("cu"))
548 { 551 {
549 RINOK(PROPVARIANT_to_bool(prop, m_ForceUtf8)); 552 RINOK(PROPVARIANT_to_bool(prop, m_ForceUtf8))
550 if (m_ForceUtf8) 553 if (m_ForceUtf8)
551 m_ForceLocal = false; 554 m_ForceLocal = false;
552 } 555 }
553 else if (name.IsEqualTo("cp")) 556 else if (name.IsEqualTo("cp"))
554 { 557 {
555 UInt32 cp = CP_OEMCP; 558 UInt32 cp = CP_OEMCP;
556 RINOK(ParsePropToUInt32(L"", prop, cp)); 559 RINOK(ParsePropToUInt32(L"", prop, cp))
557 _forceCodePage = true; 560 _forceCodePage = true;
558 _specifiedCodePage = cp; 561 _specifiedCodePage = cp;
559 } 562 }
560 else if (name.IsEqualTo("rsfx")) 563 else if (name.IsEqualTo("rsfx"))
561 { 564 {
562 RINOK(PROPVARIANT_to_bool(prop, _removeSfxBlock)); 565 RINOK(PROPVARIANT_to_bool(prop, _removeSfxBlock))
566 }
567 else if (name.IsEqualTo("rws"))
568 {
569 RINOK(PROPVARIANT_to_bool(prop, _force_SeqOutMode))
570 }
571 else if (name.IsEqualTo("ros"))
572 {
573 RINOK(PROPVARIANT_to_bool(prop, _force_OpenSeq))
563 } 574 }
564 else 575 else
565 { 576 {
@@ -573,10 +584,10 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
573 else 584 else
574 { 585 {
575 bool processed = false; 586 bool processed = false;
576 RINOK(TimeOptions.Parse(name, prop, processed)); 587 RINOK(TimeOptions.Parse(name, prop, processed))
577 if (!processed) 588 if (!processed)
578 { 589 {
579 RINOK(_props.SetProperty(name, prop)); 590 RINOK(_props.SetProperty(name, prop))
580 } 591 }
581 } 592 }
582 // RINOK(_props.MethodInfo.ParseParamsFromPROPVARIANT(name, prop)); 593 // RINOK(_props.MethodInfo.ParseParamsFromPROPVARIANT(name, prop));
diff --git a/CPP/7zip/Archive/Zip/ZipHeader.h b/CPP/7zip/Archive/Zip/ZipHeader.h
index 34fa359..038d49d 100644
--- a/CPP/7zip/Archive/Zip/ZipHeader.h
+++ b/CPP/7zip/Archive/Zip/ZipHeader.h
@@ -1,7 +1,7 @@
1// ZipHeader.h 1// ZipHeader.h
2 2
3#ifndef __ARCHIVE_ZIP_HEADER_H 3#ifndef ZIP7_INC_ARCHIVE_ZIP_HEADER_H
4#define __ARCHIVE_ZIP_HEADER_H 4#define ZIP7_INC_ARCHIVE_ZIP_HEADER_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7 7
diff --git a/CPP/7zip/Archive/Zip/ZipIn.cpp b/CPP/7zip/Archive/Zip/ZipIn.cpp
index f2b69a9..4236df7 100644
--- a/CPP/7zip/Archive/Zip/ZipIn.cpp
+++ b/CPP/7zip/Archive/Zip/ZipIn.cpp
@@ -11,8 +11,6 @@
11 11
12#include "../../../Windows/PropVariant.h" 12#include "../../../Windows/PropVariant.h"
13 13
14#include "../../Common/StreamUtils.h"
15
16#include "../IArchive.h" 14#include "../IArchive.h"
17 15
18#include "ZipIn.h" 16#include "ZipIn.h"
@@ -28,9 +26,38 @@
28namespace NArchive { 26namespace NArchive {
29namespace NZip { 27namespace NZip {
30 28
31// (kBufferSize >= kDataDescriptorSize64 + 4) 29/* we try to use same size of Buffer (1 << 17) for all tasks.
30 it allow to avoid reallocations and cache clearing. */
31
32static const size_t kSeqBufferSize = (size_t)1 << 17;
32 33
33static const size_t kSeqBufferSize = (size_t)1 << 14; 34/*
35Open()
36{
37 _inBufMode = false;
38 ReadVols()
39 FindCd();
40 TryEcd64()
41 SeekToVol()
42 FindMarker()
43 _inBufMode = true;
44 ReadHeaders()
45 _inBufMode = false;
46 ReadCd()
47 FindCd()
48 TryEcd64()
49 TryReadCd()
50 {
51 SeekToVol();
52 _inBufMode = true;
53 }
54 _inBufMode = true;
55 ReadLocals()
56 ReadCdItem()
57 ....
58}
59FindCd() writes to Buffer without touching (_inBufMode)
60*/
34 61
35/* 62/*
36 if (not defined ZIP_SELF_CHECK) : it reads CD and if error in first pass CD reading, it reads LOCALS-CD-MODE 63 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)
187 return Stream->Seek((Int64)offset, STREAM_SEEK_SET, &_streamPos); 214 return Stream->Seek((Int64)offset, STREAM_SEEK_SET, &_streamPos);
188} 215}
189 216
217
218/* SeekToVol() will keep the cached mode, if new volIndex is
219 same Vols.StreamIndex volume, and offset doesn't go out of cached region */
220
190HRESULT CInArchive::SeekToVol(int volIndex, UInt64 offset) 221HRESULT CInArchive::SeekToVol(int volIndex, UInt64 offset)
191{ 222{
192 if (volIndex != Vols.StreamIndex) 223 if (volIndex != Vols.StreamIndex)
193 { 224 {
194 InitBuf();
195 if (IsMultiVol && volIndex >= 0) 225 if (IsMultiVol && volIndex >= 0)
196 { 226 {
197 if ((unsigned)volIndex >= Vols.Streams.Size()) 227 if ((unsigned)volIndex >= Vols.Streams.Size())
@@ -221,12 +251,29 @@ HRESULT CInArchive::SeekToVol(int volIndex, UInt64 offset)
221 return S_OK; 251 return S_OK;
222 } 252 }
223 } 253 }
224 InitBuf();
225 } 254 }
255 InitBuf();
226 return Seek_SavePos(offset); 256 return Seek_SavePos(offset);
227} 257}
228 258
229 259
260HRESULT CInArchive::AllocateBuffer(size_t size)
261{
262 if (size <= Buffer.Size())
263 return S_OK;
264 /* in cached mode virtual_pos is not equal to phy_pos (_streamPos)
265 so we change _streamPos and do Seek() to virtual_pos before cache clearing */
266 if (_bufPos != _bufCached)
267 {
268 RINOK(Seek_SavePos(GetVirtStreamPos()))
269 }
270 InitBuf();
271 Buffer.AllocAtLeast(size);
272 if (!Buffer.IsAllocated())
273 return E_OUTOFMEMORY;
274 return S_OK;
275}
276
230// ---------- ReadFromCache ---------- 277// ---------- ReadFromCache ----------
231// reads from cache and from Stream 278// reads from cache and from Stream
232// move to next volume can be allowed if (CanStartNewVol) and only before first byte reading 279// 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)
465 { 512 {
466 if (extraSize < 4) 513 if (extraSize < 4)
467 { 514 {
468 // 7-Zip before 9.31 created incorrect WsAES Extra in folder's local headers. 515 // 7-Zip before 9.31 created incorrect WzAES Extra in folder's local headers.
469 // so we return k_IsArc_Res_YES to support such archives. 516 // so we return k_IsArc_Res_YES to support such archives.
470 // return k_IsArc_Res_NO; // do we need to support such extra ? 517 // return k_IsArc_Res_NO; // do we need to support such extra ?
471 return k_IsArc_Res_YES; 518 return k_IsArc_Res_YES;
@@ -508,20 +555,46 @@ static UInt32 IsArc_Zip_2(const Byte *p, size_t size, bool isFinal)
508 555
509 556
510 557
511MY_NO_INLINE 558/* FindPK_4() is allowed to access data up to and including &limit[3].
512static const Byte *FindPK(const Byte *p, const Byte *limit) 559 limit[4] access is not allowed.
560 return:
561 (return_ptr < limit) : "PK" was found at (return_ptr)
562 (return_ptr >= limit) : limit was reached or crossed. So no "PK" found before limit
563*/
564Z7_NO_INLINE
565static const Byte *FindPK_4(const Byte *p, const Byte *limit)
513{ 566{
514 for (;;) 567 for (;;)
515 { 568 {
516 for (;;) 569 for (;;)
517 { 570 {
518 Byte b0; 571 if (p >= limit)
519 b0 = p[0]; if (p >= limit) return p; p++; if (b0 == 0x50) break; 572 return limit;
520 b0 = p[0]; if (p >= limit) return p; p++; if (b0 == 0x50) break; 573 Byte b = p[1];
574 if (b == 0x4B) { if (p[0] == 0x50) { return p; } p += 1; break; }
575 if (b == 0x50) { if (p[2] == 0x4B) { return p + 1; } p += 2; break; }
576 b = p[3];
577 p += 4;
578 if (b == 0x4B) { if (p[-2]== 0x50) { return p - 2; } p -= 1; break; }
579 if (b == 0x50) { if (p[0] == 0x4B) { return p - 1; } break; }
580 }
581 }
582 /*
583 for (;;)
584 {
585 for (;;)
586 {
587 if (p >= limit)
588 return limit;
589 if (*p++ == 0x50) break;
590 if (*p++ == 0x50) break;
591 if (*p++ == 0x50) break;
592 if (*p++ == 0x50) break;
521 } 593 }
522 if (p[0] == 0x4B) 594 if (*p == 0x4B)
523 return p - 1; 595 return p - 1;
524 } 596 }
597 */
525} 598}
526 599
527 600
@@ -554,7 +627,7 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
554 if (searchLimit && *searchLimit == 0) 627 if (searchLimit && *searchLimit == 0)
555 { 628 {
556 Byte startBuf[kMarkerSize]; 629 Byte startBuf[kMarkerSize];
557 RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)); 630 RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize))
558 631
559 UInt32 marker = Get32(startBuf); 632 UInt32 marker = Get32(startBuf);
560 _signature = marker; 633 _signature = marker;
@@ -562,7 +635,7 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
562 if ( marker == NSignature::kNoSpan 635 if ( marker == NSignature::kNoSpan
563 || marker == NSignature::kSpan) 636 || marker == NSignature::kSpan)
564 { 637 {
565 RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize)); 638 RINOK(ReadFromCache_FALSE(startBuf, kMarkerSize))
566 _signature = Get32(startBuf); 639 _signature = Get32(startBuf);
567 } 640 }
568 641
@@ -579,16 +652,12 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
579 return S_OK; 652 return S_OK;
580 } 653 }
581 654
582 const size_t kCheckSize = (size_t)1 << 16; // must be smaller than kBufSize 655 // zip specification: (_zip_header_size < (1 << 16))
583 const size_t kBufSize = (size_t)1 << 17; // must be larger than kCheckSize 656 // so we need such size to check header
657 const size_t kCheckSize = (size_t)1 << 16;
658 const size_t kBufSize = (size_t)1 << 17; // (kBufSize must be > kCheckSize)
584 659
585 if (Buffer.Size() < kBufSize) 660 RINOK(AllocateBuffer(kBufSize))
586 {
587 InitBuf();
588 Buffer.AllocAtLeast(kBufSize);
589 if (!Buffer.IsAllocated())
590 return E_OUTOFMEMORY;
591 }
592 661
593 _inBufMode = true; 662 _inBufMode = true;
594 663
@@ -596,12 +665,13 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
596 665
597 for (;;) 666 for (;;)
598 { 667 {
599 RINOK(LookAhead(kBufSize)); 668 RINOK(LookAhead(kBufSize))
600 669
601 const size_t avail = GetAvail(); 670 const size_t avail = GetAvail();
602 671
603 size_t limitPos; 672 size_t limitPos;
604 const bool isFinished = (avail != kBufSize); 673 // (avail > kBufSize) is possible, if (Buffer.Size() > kBufSize)
674 const bool isFinished = (avail < kBufSize);
605 if (isFinished) 675 if (isFinished)
606 { 676 {
607 const unsigned kMinAllowed = 4; 677 const unsigned kMinAllowed = 4;
@@ -618,7 +688,7 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
618 if (!s.Stream) 688 if (!s.Stream)
619 break; 689 break;
620 690
621 RINOK(s.SeekToStart()); 691 RINOK(s.SeekToStart())
622 692
623 InitBuf(); 693 InitBuf();
624 Vols.StreamIndex++; 694 Vols.StreamIndex++;
@@ -651,11 +721,15 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
651 721
652 for (;; p++) 722 for (;; p++)
653 { 723 {
654 p = FindPK(p, limit); 724 p = FindPK_4(p, limit);
655 if (p >= limit) 725 if (p >= limit)
656 break; 726 break;
657 const size_t rem = (size_t)(pStart + avail - p); 727 size_t rem = (size_t)(pStart + avail - p);
658 UInt32 res = IsArc_Zip_2(p, rem, isFinished); 728 /* 22.02 : we limit check size with kCheckSize to be consistent for
729 any different combination of _bufPos in Buffer and size of Buffer. */
730 if (rem > kCheckSize)
731 rem = kCheckSize;
732 const UInt32 res = IsArc_Zip_2(p, rem, isFinished);
659 if (res != k_IsArc_Res_NO) 733 if (res != k_IsArc_Res_NO)
660 { 734 {
661 if (rem < kMarkerSize) 735 if (rem < kMarkerSize)
@@ -689,7 +763,7 @@ HRESULT CInArchive::FindMarker(const UInt64 *searchLimit)
689 { 763 {
690 progressPrev = _cnt; 764 progressPrev = _cnt;
691 // const UInt64 numFiles64 = 0; 765 // const UInt64 numFiles64 = 0;
692 RINOK(Callback->SetCompleted(NULL, &_cnt)); 766 RINOK(Callback->SetCompleted(NULL, &_cnt))
693 } 767 }
694 } 768 }
695 769
@@ -734,6 +808,8 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished)
734 return S_OK; 808 return S_OK;
735 } 809 }
736 810
811 // cache is empty
812
737 if (!IsMultiVol) 813 if (!IsMultiVol)
738 { 814 {
739 _cnt += offset; 815 _cnt += offset;
@@ -767,7 +843,7 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished)
767 _cnt += offset; 843 _cnt += offset;
768 return Stream->Seek((Int64)offset, STREAM_SEEK_CUR, &_streamPos); 844 return Stream->Seek((Int64)offset, STREAM_SEEK_CUR, &_streamPos);
769 } 845 }
770 RINOK(Seek_SavePos(s.Size)); 846 RINOK(Seek_SavePos(s.Size))
771 offset -= rem; 847 offset -= rem;
772 _cnt += rem; 848 _cnt += rem;
773 } 849 }
@@ -787,7 +863,7 @@ HRESULT CInArchive::IncreaseRealPosition(UInt64 offset, bool &isFinished)
787 return S_OK; 863 return S_OK;
788 } 864 }
789 Stream = s2.Stream; 865 Stream = s2.Stream;
790 RINOK(Seek_SavePos(0)); 866 RINOK(Seek_SavePos(0))
791 } 867 }
792} 868}
793 869
@@ -847,7 +923,7 @@ HRESULT CInArchive::LookAhead(size_t minRequired)
847 if (!s.Stream) 923 if (!s.Stream)
848 return S_OK; 924 return S_OK;
849 925
850 RINOK(s.SeekToStart()); 926 RINOK(s.SeekToStart())
851 927
852 Vols.StreamIndex++; 928 Vols.StreamIndex++;
853 _streamPos = 0; 929 _streamPos = 0;
@@ -957,7 +1033,7 @@ HRESULT CInArchive::Skip64(UInt64 num, unsigned numFiles)
957 if (Callback) 1033 if (Callback)
958 { 1034 {
959 const UInt64 numFiles64 = numFiles; 1035 const UInt64 numFiles64 = numFiles;
960 RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); 1036 RINOK(Callback->SetCompleted(&numFiles64, &_cnt))
961 } 1037 }
962 } 1038 }
963} 1039}
@@ -1000,6 +1076,7 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo
1000 const UInt32 pair = ReadUInt32(); 1076 const UInt32 pair = ReadUInt32();
1001 subBlock.ID = (pair & 0xFFFF); 1077 subBlock.ID = (pair & 0xFFFF);
1002 unsigned size = (unsigned)(pair >> 16); 1078 unsigned size = (unsigned)(pair >> 16);
1079 // const unsigned origSize = size;
1003 1080
1004 extraSize -= 4; 1081 extraSize -= 4;
1005 1082
@@ -1068,13 +1145,15 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo
1068 } 1145 }
1069 } 1146 }
1070 1147
1148 // we can ignore errors, when some zip archiver still write all fields to zip64 extra in local header
1149 // if (&& (cdItem || !isOK || origSize != 8 * 3 + 4 || size != 8 * 1 + 4))
1071 if (!isOK || size != 0) 1150 if (!isOK || size != 0)
1072 { 1151 {
1073 HeadersWarning = true; 1152 HeadersWarning = true;
1074 extra.Error = true; 1153 extra.Error = true;
1075 extra.IsZip64_Error = true; 1154 extra.IsZip64_Error = true;
1076 Skip(size);
1077 } 1155 }
1156 Skip(size);
1078 } 1157 }
1079 else 1158 else
1080 { 1159 {
@@ -1092,7 +1171,7 @@ bool CInArchive::ReadExtra(const CLocalItem &item, unsigned extraSize, CExtraBlo
1092 { 1171 {
1093 ExtraMinorError = true; 1172 ExtraMinorError = true;
1094 extra.MinorError = true; 1173 extra.MinorError = true;
1095 // 7-Zip before 9.31 created incorrect WsAES Extra in folder's local headers. 1174 // 7-Zip before 9.31 created incorrect WzAES Extra in folder's local headers.
1096 // so we don't return false, but just set warning flag 1175 // so we don't return false, but just set warning flag
1097 // return false; 1176 // return false;
1098 Skip(extraSize); 1177 Skip(extraSize);
@@ -1184,9 +1263,10 @@ static bool FlagsAreSame(const CItem &i1, const CItem &i2_cd)
1184 mask &= 0x7FFF; 1263 mask &= 0x7FFF;
1185 } 1264 }
1186 1265
1187 // we can ignore utf8 flag, if name is ascii 1266 // we can ignore utf8 flag, if name is ascii, or if only cdItem has utf8 flag
1188 if (mask & NFileHeader::NFlags::kUtf8) 1267 if (mask & NFileHeader::NFlags::kUtf8)
1189 if (i1.Name.IsAscii() && i2_cd.Name.IsAscii()) 1268 if ((i1.Name.IsAscii() && i2_cd.Name.IsAscii())
1269 || (i2_cd.Flags & NFileHeader::NFlags::kUtf8))
1190 mask &= ~NFileHeader::NFlags::kUtf8; 1270 mask &= ~NFileHeader::NFlags::kUtf8;
1191 1271
1192 // some bad archive in rare case can use descriptor without descriptor flag in Central Dir 1272 // 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)
1270} 1350}
1271 1351
1272 1352
1273HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool &headersError) 1353HRESULT CInArchive::Read_LocalItem_After_CdItem(CItemEx &item, bool &isAvail, bool &headersError)
1274{ 1354{
1275 InitBuf();
1276 _inBufMode = false;
1277
1278 isAvail = true; 1355 isAvail = true;
1279 headersError = false; 1356 headersError = false;
1280 if (item.FromLocal) 1357 if (item.FromLocal)
@@ -1315,13 +1392,16 @@ HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool
1315 } 1392 }
1316 } 1393 }
1317 1394
1318 RINOK(Seek_SavePos(offset)); 1395 _inBufMode = false;
1319 1396 RINOK(Seek_SavePos(offset))
1320 /*
1321 // we can check buf mode
1322 InitBuf(); 1397 InitBuf();
1398 /*
1399 // we can use buf mode with small buffer to reduce
1400 // the number of Read() calls in ReadLocalItem()
1323 _inBufMode = true; 1401 _inBufMode = true;
1324 Buffer.AllocAtLeast(1 << 10); 1402 Buffer.Alloc(1 << 10);
1403 if (!Buffer.IsAllocated())
1404 return E_OUTOFMEMORY;
1325 */ 1405 */
1326 1406
1327 CItemEx localItem; 1407 CItemEx localItem;
@@ -1405,7 +1485,7 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles)
1405 1485
1406 // size_t processedSize; 1486 // size_t processedSize;
1407 CanStartNewVol = true; 1487 CanStartNewVol = true;
1408 RINOK(LookAhead(descriptorSize4)); 1488 RINOK(LookAhead(descriptorSize4))
1409 const size_t avail = GetAvail(); 1489 const size_t avail = GetAvail();
1410 1490
1411 if (avail < descriptorSize4) 1491 if (avail < descriptorSize4)
@@ -1429,7 +1509,7 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles)
1429 // descriptor signature field is Info-ZIP's extension to pkware Zip specification. 1509 // descriptor signature field is Info-ZIP's extension to pkware Zip specification.
1430 // New ZIP specification also allows descriptorSignature. 1510 // New ZIP specification also allows descriptorSignature.
1431 1511
1432 p = FindPK(p, limit + 1); 1512 p = FindPK_4(p, limit + 1);
1433 if (p > limit) 1513 if (p > limit)
1434 break; 1514 break;
1435 1515
@@ -1487,7 +1567,7 @@ HRESULT CInArchive::FindDescriptor(CItemEx &item, unsigned numFiles)
1487 { 1567 {
1488 progressPrev = _cnt; 1568 progressPrev = _cnt;
1489 const UInt64 numFiles64 = numFiles; 1569 const UInt64 numFiles64 = numFiles;
1490 RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); 1570 RINOK(Callback->SetCompleted(&numFiles64, &_cnt))
1491 } 1571 }
1492 } 1572 }
1493} 1573}
@@ -1501,7 +1581,7 @@ HRESULT CInArchive::CheckDescriptor(const CItemEx &item)
1501 // pkzip's version without descriptor signature is not supported 1581 // pkzip's version without descriptor signature is not supported
1502 1582
1503 bool isFinished = false; 1583 bool isFinished = false;
1504 RINOK(IncreaseRealPosition(item.PackSize, isFinished)); 1584 RINOK(IncreaseRealPosition(item.PackSize, isFinished))
1505 if (isFinished) 1585 if (isFinished)
1506 return S_FALSE; 1586 return S_FALSE;
1507 1587
@@ -1548,7 +1628,7 @@ HRESULT CInArchive::CheckDescriptor(const CItemEx &item)
1548} 1628}
1549 1629
1550 1630
1551HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) 1631HRESULT CInArchive::Read_LocalItem_After_CdItem_Full(CItemEx &item)
1552{ 1632{
1553 if (item.FromLocal) 1633 if (item.FromLocal)
1554 return S_OK; 1634 return S_OK;
@@ -1556,7 +1636,7 @@ HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item)
1556 { 1636 {
1557 bool isAvail = true; 1637 bool isAvail = true;
1558 bool headersError = false; 1638 bool headersError = false;
1559 RINOK(ReadLocalItemAfterCdItem(item, isAvail, headersError)); 1639 RINOK(Read_LocalItem_After_CdItem(item, isAvail, headersError))
1560 if (headersError) 1640 if (headersError)
1561 return S_FALSE; 1641 return S_FALSE;
1562 if (item.HasDescriptor()) 1642 if (item.HasDescriptor())
@@ -1606,14 +1686,22 @@ HRESULT CInArchive::ReadCdItem(CItemEx &item)
1606} 1686}
1607 1687
1608 1688
1689/*
1690TryEcd64()
1691 (_inBufMode == false) is expected here
1692 so TryEcd64() can't change the Buffer.
1693 if (Ecd64 is not covered by cached region),
1694 TryEcd64() can change cached region ranges (_bufCached, _bufPos) and _streamPos.
1695*/
1696
1609HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo) 1697HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo)
1610{ 1698{
1611 if (offset >= ((UInt64)1 << 63)) 1699 if (offset >= ((UInt64)1 << 63))
1612 return S_FALSE; 1700 return S_FALSE;
1613 Byte buf[kEcd64_FullSize]; 1701 Byte buf[kEcd64_FullSize];
1614 1702
1615 RINOK(SeekToVol(Vols.StreamIndex, offset)); 1703 RINOK(SeekToVol(Vols.StreamIndex, offset))
1616 RINOK(ReadFromCache_FALSE(buf, kEcd64_FullSize)); 1704 RINOK(ReadFromCache_FALSE(buf, kEcd64_FullSize))
1617 1705
1618 if (Get32(buf) != NSignature::kEcd64) 1706 if (Get32(buf) != NSignature::kEcd64)
1619 return S_FALSE; 1707 return S_FALSE;
@@ -1625,6 +1713,9 @@ HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo)
1625} 1713}
1626 1714
1627 1715
1716/* FindCd() doesn't use previous cached region,
1717 but it uses Buffer. So it sets new cached region */
1718
1628HRESULT CInArchive::FindCd(bool checkOffsetMode) 1719HRESULT CInArchive::FindCd(bool checkOffsetMode)
1629{ 1720{
1630 CCdInfo &cdInfo = Vols.ecd; 1721 CCdInfo &cdInfo = Vols.ecd;
@@ -1635,7 +1726,7 @@ HRESULT CInArchive::FindCd(bool checkOffsetMode)
1635 // So here we don't use cache data from previous operations . 1726 // So here we don't use cache data from previous operations .
1636 1727
1637 InitBuf(); 1728 InitBuf();
1638 RINOK(Stream->Seek(0, STREAM_SEEK_END, &endPos)); 1729 RINOK(InStream_GetSize_SeekToEnd(Stream, endPos))
1639 _streamPos = endPos; 1730 _streamPos = endPos;
1640 1731
1641 // const UInt32 kBufSizeMax2 = ((UInt32)1 << 16) + kEcdSize + kEcd64Locator_Size + kEcd64_FullSize; 1732 // const UInt32 kBufSizeMax2 = ((UInt32)1 << 16) + kEcdSize + kEcd64Locator_Size + kEcd64_FullSize;
@@ -1646,15 +1737,9 @@ HRESULT CInArchive::FindCd(bool checkOffsetMode)
1646 return S_FALSE; 1737 return S_FALSE;
1647 // CByteArr byteBuffer(bufSize); 1738 // CByteArr byteBuffer(bufSize);
1648 1739
1649 if (Buffer.Size() < kBufSizeMax) 1740 RINOK(AllocateBuffer(kBufSizeMax))
1650 {
1651 // InitBuf();
1652 Buffer.AllocAtLeast(kBufSizeMax);
1653 if (!Buffer.IsAllocated())
1654 return E_OUTOFMEMORY;
1655 }
1656 1741
1657 RINOK(Seek_SavePos(endPos - bufSize)); 1742 RINOK(Seek_SavePos(endPos - bufSize))
1658 1743
1659 size_t processed = bufSize; 1744 size_t processed = bufSize;
1660 HRESULT res = ReadStream(Stream, Buffer, &processed); 1745 HRESULT res = ReadStream(Stream, Buffer, &processed);
@@ -1799,14 +1884,14 @@ HRESULT CInArchive::TryReadCd(CObjectVector<CItemEx> &items, const CCdInfo &cdIn
1799 // _startLocalFromCd_Disk = (UInt32)(Int32)-1; 1884 // _startLocalFromCd_Disk = (UInt32)(Int32)-1;
1800 // _startLocalFromCd_Offset = (UInt64)(Int64)-1; 1885 // _startLocalFromCd_Offset = (UInt64)(Int64)-1;
1801 1886
1802 RINOK(SeekToVol(IsMultiVol ? (int)cdInfo.CdDisk : -1, cdOffset)); 1887 RINOK(SeekToVol(IsMultiVol ? (int)cdInfo.CdDisk : -1, cdOffset))
1803 1888
1804 _inBufMode = true; 1889 _inBufMode = true;
1805 _cnt = 0; 1890 _cnt = 0;
1806 1891
1807 if (Callback) 1892 if (Callback)
1808 { 1893 {
1809 RINOK(Callback->SetTotal(&cdInfo.NumEntries, IsMultiVol ? &Vols.TotalBytesSize : NULL)); 1894 RINOK(Callback->SetTotal(&cdInfo.NumEntries, IsMultiVol ? &Vols.TotalBytesSize : NULL))
1810 } 1895 }
1811 UInt64 numFileExpected = cdInfo.NumEntries; 1896 UInt64 numFileExpected = cdInfo.NumEntries;
1812 const UInt64 *totalFilesPtr = &numFileExpected; 1897 const UInt64 *totalFilesPtr = &numFileExpected;
@@ -1820,7 +1905,7 @@ HRESULT CInArchive::TryReadCd(CObjectVector<CItemEx> &items, const CCdInfo &cdIn
1820 CanStartNewVol = false; 1905 CanStartNewVol = false;
1821 { 1906 {
1822 CItemEx cdItem; 1907 CItemEx cdItem;
1823 RINOK(ReadCdItem(cdItem)); 1908 RINOK(ReadCdItem(cdItem))
1824 1909
1825 /* 1910 /*
1826 if (cdItem.Disk < _startLocalFromCd_Disk || 1911 if (cdItem.Disk < _startLocalFromCd_Disk ||
@@ -1854,10 +1939,10 @@ HRESULT CInArchive::TryReadCd(CObjectVector<CItemEx> &items, const CCdInfo &cdIn
1854 else 1939 else
1855 while (numFiles > numFileExpected) 1940 while (numFiles > numFileExpected)
1856 numFileExpected += (UInt32)1 << 16; 1941 numFileExpected += (UInt32)1 << 16;
1857 RINOK(Callback->SetTotal(totalFilesPtr, NULL)); 1942 RINOK(Callback->SetTotal(totalFilesPtr, NULL))
1858 } 1943 }
1859 1944
1860 RINOK(Callback->SetCompleted(&numFiles, &_cnt)); 1945 RINOK(Callback->SetCompleted(&numFiles, &_cnt))
1861 } 1946 }
1862 } 1947 }
1863 1948
@@ -1900,7 +1985,7 @@ HRESULT CInArchive::ReadCd(CObjectVector<CItemEx> &items, UInt32 &cdDisk, UInt64
1900 1985
1901 if (!Vols.ecd_wasRead) 1986 if (!Vols.ecd_wasRead)
1902 { 1987 {
1903 RINOK(FindCd(checkOffsetMode)); 1988 RINOK(FindCd(checkOffsetMode))
1904 } 1989 }
1905 1990
1906 CCdInfo &cdInfo = Vols.ecd; 1991 CCdInfo &cdInfo = Vols.ecd;
@@ -2004,7 +2089,7 @@ HRESULT CInArchive::ReadLocals(CObjectVector<CItemEx> &items)
2004 2089
2005 if (Callback) 2090 if (Callback)
2006 { 2091 {
2007 RINOK(Callback->SetTotal(NULL, IsMultiVol ? &Vols.TotalBytesSize : NULL)); 2092 RINOK(Callback->SetTotal(NULL, IsMultiVol ? &Vols.TotalBytesSize : NULL))
2008 } 2093 }
2009 2094
2010 while (_signature == NSignature::kLocalFileHeader) 2095 while (_signature == NSignature::kLocalFileHeader)
@@ -2023,14 +2108,14 @@ HRESULT CInArchive::ReadLocals(CObjectVector<CItemEx> &items)
2023 2108
2024 if (item.HasDescriptor()) 2109 if (item.HasDescriptor())
2025 { 2110 {
2026 RINOK(FindDescriptor(item, items.Size())); 2111 RINOK(FindDescriptor(item, items.Size()))
2027 isFinished = !item.DescriptorWasRead; 2112 isFinished = !item.DescriptorWasRead;
2028 } 2113 }
2029 else 2114 else
2030 { 2115 {
2031 if (item.PackSize >= ((UInt64)1 << 62)) 2116 if (item.PackSize >= ((UInt64)1 << 62))
2032 throw CUnexpectEnd(); 2117 throw CUnexpectEnd();
2033 RINOK(IncreaseRealPosition(item.PackSize, isFinished)); 2118 RINOK(IncreaseRealPosition(item.PackSize, isFinished))
2034 } 2119 }
2035 2120
2036 items.Add(item); 2121 items.Add(item);
@@ -2054,7 +2139,7 @@ HRESULT CInArchive::ReadLocals(CObjectVector<CItemEx> &items)
2054 { 2139 {
2055 progressPrev = _cnt; 2140 progressPrev = _cnt;
2056 const UInt64 numFiles = items.Size(); 2141 const UInt64 numFiles = items.Size();
2057 RINOK(Callback->SetCompleted(&numFiles, &_cnt)); 2142 RINOK(Callback->SetCompleted(&numFiles, &_cnt))
2058 } 2143 }
2059 } 2144 }
2060 2145
@@ -2072,7 +2157,7 @@ HRESULT CVols::ParseArcName(IArchiveOpenVolumeCallback *volCallback)
2072 UString name; 2157 UString name;
2073 { 2158 {
2074 NWindows::NCOM::CPropVariant prop; 2159 NWindows::NCOM::CPropVariant prop;
2075 RINOK(volCallback->GetProperty(kpidName, &prop)); 2160 RINOK(volCallback->GetProperty(kpidName, &prop))
2076 if (prop.vt != VT_BSTR) 2161 if (prop.vt != VT_BSTR)
2077 return S_OK; 2162 return S_OK;
2078 name = prop.bstrVal; 2163 name = prop.bstrVal;
@@ -2235,11 +2320,8 @@ HRESULT CInArchive::ReadVols2(IArchiveOpenVolumeCallback *volCallback,
2235 } 2320 }
2236 } 2321 }
2237 2322
2238 UInt64 size; 2323 UInt64 pos, size;
2239 UInt64 pos; 2324 RINOK(InStream_GetPos_GetSize(stream, pos, size))
2240 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &pos));
2241 RINOK(stream->Seek(0, STREAM_SEEK_END, &size));
2242 RINOK(stream->Seek((Int64)pos, STREAM_SEEK_SET, NULL));
2243 2325
2244 while (i >= Vols.Streams.Size()) 2326 while (i >= Vols.Streams.Size())
2245 Vols.Streams.AddNew(); 2327 Vols.Streams.AddNew();
@@ -2270,7 +2352,7 @@ HRESULT CInArchive::ReadVols()
2270 if (!volCallback) 2352 if (!volCallback)
2271 return S_OK; 2353 return S_OK;
2272 2354
2273 RINOK(Vols.ParseArcName(volCallback)); 2355 RINOK(Vols.ParseArcName(volCallback))
2274 2356
2275 // const int startZIndex = Vols.StartVolIndex; 2357 // const int startZIndex = Vols.StartVolIndex;
2276 2358
@@ -2324,7 +2406,7 @@ HRESULT CInArchive::ReadVols()
2324 if (cdDisk != zipDisk) 2406 if (cdDisk != zipDisk)
2325 { 2407 {
2326 // get volumes required for cd. 2408 // get volumes required for cd.
2327 RINOK(ReadVols2(volCallback, (unsigned)cdDisk, zipDisk, zipDisk, 0, numMissingVols)); 2409 RINOK(ReadVols2(volCallback, (unsigned)cdDisk, zipDisk, zipDisk, 0, numMissingVols))
2328 if (numMissingVols != 0) 2410 if (numMissingVols != 0)
2329 { 2411 {
2330 // cdOK = false; 2412 // cdOK = false;
@@ -2352,7 +2434,7 @@ HRESULT CInArchive::ReadVols()
2352 { 2434 {
2353 // get volumes that were no requested still 2435 // get volumes that were no requested still
2354 const unsigned kNumMissingVolsMax = 1 << 12; 2436 const unsigned kNumMissingVolsMax = 1 << 12;
2355 RINOK(ReadVols2(volCallback, 0, cdDisk < 0 ? -1 : cdDisk, zipDisk, kNumMissingVolsMax, numMissingVols)); 2437 RINOK(ReadVols2(volCallback, 0, cdDisk < 0 ? -1 : cdDisk, zipDisk, kNumMissingVolsMax, numMissingVols))
2356 } 2438 }
2357 2439
2358 // if (Vols.StartVolIndex >= 0) 2440 // if (Vols.StartVolIndex >= 0)
@@ -2364,7 +2446,7 @@ HRESULT CInArchive::ReadVols()
2364 || !Vols.Streams[(unsigned)Vols.StartVolIndex].Stream) 2446 || !Vols.Streams[(unsigned)Vols.StartVolIndex].Stream)
2365 { 2447 {
2366 // we get volumes starting from StartVolIndex, if they we not requested before know the volume index (if FindCd() was ok) 2448 // we get volumes starting from StartVolIndex, if they we not requested before know the volume index (if FindCd() was ok)
2367 RINOK(ReadVols2(volCallback, (unsigned)Vols.StartVolIndex, zipDisk, zipDisk, 0, numMissingVols)); 2449 RINOK(ReadVols2(volCallback, (unsigned)Vols.StartVolIndex, zipDisk, zipDisk, 0, numMissingVols))
2368 } 2450 }
2369 } 2451 }
2370 2452
@@ -2377,7 +2459,7 @@ HRESULT CInArchive::ReadVols()
2377 if (zipDisk >= 0) 2459 if (zipDisk >= 0)
2378 { 2460 {
2379 // we create item in Streams for ZipStream, if we know the volume index (if FindCd() was ok) 2461 // we create item in Streams for ZipStream, if we know the volume index (if FindCd() was ok)
2380 RINOK(ReadVols2(volCallback, (unsigned)zipDisk, zipDisk + 1, zipDisk, 0, numMissingVols)); 2462 RINOK(ReadVols2(volCallback, (unsigned)zipDisk, zipDisk + 1, zipDisk, 0, numMissingVols))
2381 } 2463 }
2382 } 2464 }
2383 2465
@@ -2428,7 +2510,7 @@ HRESULT CVols::Read(void *data, UInt32 size, UInt32 *processedSize)
2428 return S_FALSE; 2510 return S_FALSE;
2429 if (NeedSeek) 2511 if (NeedSeek)
2430 { 2512 {
2431 RINOK(s.SeekToStart()); 2513 RINOK(s.SeekToStart())
2432 NeedSeek = false; 2514 NeedSeek = false;
2433 } 2515 }
2434 UInt32 realProcessedSize = 0; 2516 UInt32 realProcessedSize = 0;
@@ -2444,7 +2526,7 @@ HRESULT CVols::Read(void *data, UInt32 size, UInt32 *processedSize)
2444 } 2526 }
2445} 2527}
2446 2528
2447STDMETHODIMP CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize) 2529Z7_COM7F_IMF(CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize))
2448{ 2530{
2449 return Vols->Read(data, size, processedSize); 2531 return Vols->Read(data, size, processedSize);
2450} 2532}
@@ -2458,14 +2540,10 @@ STDMETHODIMP CVolStream::Read(void *data, UInt32 size, UInt32 *processedSize)
2458 2540
2459HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items) 2541HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2460{ 2542{
2461 if (Buffer.Size() < kSeqBufferSize) 2543 // buffer that can be used for cd reading
2462 { 2544 RINOK(AllocateBuffer(kSeqBufferSize))
2463 InitBuf();
2464 Buffer.AllocAtLeast(kSeqBufferSize);
2465 if (!Buffer.IsAllocated())
2466 return E_OUTOFMEMORY;
2467 }
2468 2545
2546 // here we can read small records. So we switch off _inBufMode.
2469 _inBufMode = false; 2547 _inBufMode = false;
2470 2548
2471 HRESULT res = S_OK; 2549 HRESULT res = S_OK;
@@ -2488,6 +2566,13 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2488 2566
2489 UInt64 cdAbsOffset = 0; // absolute cd offset, for LOCALS-CD-MODE only. 2567 UInt64 cdAbsOffset = 0; // absolute cd offset, for LOCALS-CD-MODE only.
2490 2568
2569if (Force_ReadLocals_Mode)
2570{
2571 IsArc = true;
2572 res = S_FALSE; // we will use LOCALS-CD-MODE mode
2573}
2574else
2575{
2491 if (!MarkerIsFound || !MarkerIsSafe) 2576 if (!MarkerIsFound || !MarkerIsSafe)
2492 { 2577 {
2493 IsArc = true; 2578 IsArc = true;
@@ -2497,7 +2582,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2497 else if (res != S_FALSE) 2582 else if (res != S_FALSE)
2498 return res; 2583 return res;
2499 } 2584 }
2500 else 2585 else // (MarkerIsFound && MarkerIsSafe)
2501 { 2586 {
2502 2587
2503 // _signature must be kLocalFileHeader or kEcd or kEcd64 2588 // _signature must be kLocalFileHeader or kEcd or kEcd64
@@ -2528,7 +2613,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2528 return S_FALSE; 2613 return S_FALSE;
2529 } 2614 }
2530 2615
2531 RINOK(Skip64(recordSize - kEcd64_MainSize, 0)); 2616 RINOK(Skip64(recordSize - kEcd64_MainSize, 0))
2532 } 2617 }
2533 2618
2534 ReadSignature(); 2619 ReadSignature();
@@ -2568,7 +2653,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2568 ArcInfo.Base = (Int64)ArcInfo.MarkerPos; 2653 ArcInfo.Base = (Int64)ArcInfo.MarkerPos;
2569 IsArc = true; // check it: we need more tests? 2654 IsArc = true; // check it: we need more tests?
2570 2655
2571 RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2)); 2656 RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2))
2572 ReadSignature(); 2657 ReadSignature();
2573 } 2658 }
2574 else 2659 else
@@ -2650,8 +2735,9 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2650 } 2735 }
2651 } 2736 }
2652 } 2737 }
2653 } 2738 } // (MarkerIsFound && MarkerIsSafe)
2654 2739
2740} // (!onlyLocalsMode)
2655 2741
2656 2742
2657 CObjectVector<CItemEx> cdItems; 2743 CObjectVector<CItemEx> cdItems;
@@ -2676,17 +2762,20 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2676 HeadersWarning = false; 2762 HeadersWarning = false;
2677 ExtraMinorError = false; 2763 ExtraMinorError = false;
2678 2764
2679 // we can use any mode: with buffer and without buffer 2765 /* we can use any mode: with buffer and without buffer
2680 // without buffer : skips packed data : fast for big files : slow for small files 2766 without buffer : skips packed data : fast for big files : slow for small files
2681 // with buffer : reads packed data : slow for big files : fast for small files 2767 with buffer : reads packed data : slow for big files : fast for small files
2682 2768 Buffer mode is more effective. */
2683 _inBufMode = false; 2769 // _inBufMode = false;
2684 // _inBufMode = true; 2770 _inBufMode = true;
2685 2771 // we could change the buffer size here, if we want smaller Buffer.
2686 InitBuf(); 2772 // RINOK(ReAllocateBuffer(kSeqBufferSize));
2773 // InitBuf()
2687 2774
2688 ArcInfo.Base = 0; 2775 ArcInfo.Base = 0;
2689 2776
2777 if (!Disable_FindMarker)
2778 {
2690 if (!MarkerIsFound) 2779 if (!MarkerIsFound)
2691 { 2780 {
2692 if (!IsMultiVol) 2781 if (!IsMultiVol)
@@ -2695,7 +2784,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2695 return S_FALSE; 2784 return S_FALSE;
2696 // if (StartParsingVol == 0) and we didn't find marker, we use default zero marker. 2785 // if (StartParsingVol == 0) and we didn't find marker, we use default zero marker.
2697 // so we suppose that there is no sfx stub 2786 // so we suppose that there is no sfx stub
2698 RINOK(SeekToVol(0, ArcInfo.MarkerPos2)); 2787 RINOK(SeekToVol(0, ArcInfo.MarkerPos2))
2699 } 2788 }
2700 else 2789 else
2701 { 2790 {
@@ -2710,17 +2799,16 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2710 */ 2799 */
2711 ArcInfo.Base = (Int64)ArcInfo.MarkerPos2; 2800 ArcInfo.Base = (Int64)ArcInfo.MarkerPos2;
2712 } 2801 }
2713 2802 RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2))
2714 RINOK(SeekToVol(ArcInfo.MarkerVolIndex, ArcInfo.MarkerPos2));
2715 } 2803 }
2716 2804 }
2717 _cnt = 0; 2805 _cnt = 0;
2718 2806
2719 ReadSignature(); 2807 ReadSignature();
2720 2808
2721 LocalsWereRead = true; 2809 LocalsWereRead = true;
2722 2810
2723 RINOK(ReadLocals(items)); 2811 RINOK(ReadLocals(items))
2724 2812
2725 if (_signature != NSignature::kCentralFileHeader) 2813 if (_signature != NSignature::kCentralFileHeader)
2726 { 2814 {
@@ -2775,14 +2863,14 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2775 { 2863 {
2776 CItemEx cdItem; 2864 CItemEx cdItem;
2777 2865
2778 RINOK(ReadCdItem(cdItem)); 2866 RINOK(ReadCdItem(cdItem))
2779 2867
2780 cdItems.Add(cdItem); 2868 cdItems.Add(cdItem);
2781 if (Callback && (cdItems.Size() & 0xFFF) == 0) 2869 if (Callback && (cdItems.Size() & 0xFFF) == 0)
2782 { 2870 {
2783 const UInt64 numFiles = items.Size(); 2871 const UInt64 numFiles = items.Size();
2784 const UInt64 numBytes = _cnt; 2872 const UInt64 numBytes = _cnt;
2785 RINOK(Callback->SetCompleted(&numFiles, &numBytes)); 2873 RINOK(Callback->SetCompleted(&numFiles, &numBytes))
2786 } 2874 }
2787 ReadSignature(); 2875 ReadSignature();
2788 if (_signature != NSignature::kCentralFileHeader) 2876 if (_signature != NSignature::kCentralFileHeader)
@@ -2842,7 +2930,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2842 cdInfo.ParseEcd64e(buf); 2930 cdInfo.ParseEcd64e(buf);
2843 } 2931 }
2844 2932
2845 RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size())); 2933 RINOK(Skip64(recordSize - kEcd64_MainSize, items.Size()))
2846 } 2934 }
2847 2935
2848 2936
@@ -2886,12 +2974,12 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
2886 ecd.Parse(buf); 2974 ecd.Parse(buf);
2887 } 2975 }
2888 2976
2889 COPY_ECD_ITEM_16(ThisDisk); 2977 COPY_ECD_ITEM_16(ThisDisk)
2890 COPY_ECD_ITEM_16(CdDisk); 2978 COPY_ECD_ITEM_16(CdDisk)
2891 COPY_ECD_ITEM_16(NumEntries_in_ThisDisk); 2979 COPY_ECD_ITEM_16(NumEntries_in_ThisDisk)
2892 COPY_ECD_ITEM_16(NumEntries); 2980 COPY_ECD_ITEM_16(NumEntries)
2893 COPY_ECD_ITEM_32(Size); 2981 COPY_ECD_ITEM_32(Size)
2894 COPY_ECD_ITEM_32(Offset); 2982 COPY_ECD_ITEM_32(Offset)
2895 2983
2896 bool cdOK = true; 2984 bool cdOK = true;
2897 2985
@@ -3040,7 +3128,7 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
3040 if ((i & 0x3FFF) == 0) 3128 if ((i & 0x3FFF) == 0)
3041 { 3129 {
3042 const UInt64 numFiles64 = items.Size() + items2.Size(); 3130 const UInt64 numFiles64 = items.Size() + items2.Size();
3043 RINOK(Callback->SetCompleted(&numFiles64, &_cnt)); 3131 RINOK(Callback->SetCompleted(&numFiles64, &_cnt))
3044 } 3132 }
3045 3133
3046 const CItemEx &cdItem = cdItems[i]; 3134 const CItemEx &cdItem = cdItems[i];
@@ -3093,6 +3181,9 @@ HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items)
3093 item.ExternalAttrib = cdItem.ExternalAttrib; 3181 item.ExternalAttrib = cdItem.ExternalAttrib;
3094 item.Comment = cdItem.Comment; 3182 item.Comment = cdItem.Comment;
3095 item.FromCentral = cdItem.FromCentral; 3183 item.FromCentral = cdItem.FromCentral;
3184 // 22.02: we force utf8 flag, if central header has utf8 flag
3185 if (cdItem.Flags & NFileHeader::NFlags::kUtf8)
3186 item.Flags |= NFileHeader::NFlags::kUtf8;
3096 } 3187 }
3097 3188
3098 FOR_VECTOR (k, items2) 3189 FOR_VECTOR (k, items2)
@@ -3175,8 +3266,8 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3175 Close(); 3266 Close();
3176 3267
3177 UInt64 startPos; 3268 UInt64 startPos;
3178 RINOK(stream->Seek(0, STREAM_SEEK_CUR, &startPos)); 3269 RINOK(InStream_GetPos(stream, startPos))
3179 RINOK(stream->Seek(0, STREAM_SEEK_END, &ArcInfo.FileEndPos)); 3270 RINOK(InStream_GetSize_SeekToEnd(stream, ArcInfo.FileEndPos))
3180 _streamPos = ArcInfo.FileEndPos; 3271 _streamPos = ArcInfo.FileEndPos;
3181 3272
3182 StartStream = stream; 3273 StartStream = stream;
@@ -3187,18 +3278,30 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3187 3278
3188 bool volWasRequested = false; 3279 bool volWasRequested = false;
3189 3280
3281 if (!Disable_VolsRead)
3190 if (callback 3282 if (callback
3191 && (startPos == 0 || !searchLimit || *searchLimit != 0)) 3283 && (startPos == 0 || !searchLimit || *searchLimit != 0))
3192 { 3284 {
3193 // we try to read volumes only if it's first call (offset == 0) or scan is allowed. 3285 // we try to read volumes only if it's first call (offset == 0) or scan is allowed.
3194 volWasRequested = true; 3286 volWasRequested = true;
3195 RINOK(ReadVols()); 3287 RINOK(ReadVols())
3196 } 3288 }
3197 3289
3290 if (Disable_FindMarker)
3291 {
3292 RINOK(SeekToVol(-1, startPos))
3293 StreamRef = stream;
3294 Stream = stream;
3295 MarkerIsFound = true;
3296 MarkerIsSafe = true;
3297 ArcInfo.MarkerPos = startPos;
3298 ArcInfo.MarkerPos2 = startPos;
3299 }
3300 else
3198 if (IsMultiVol && Vols.StartParsingVol == 0 && (unsigned)Vols.StartParsingVol < Vols.Streams.Size()) 3301 if (IsMultiVol && Vols.StartParsingVol == 0 && (unsigned)Vols.StartParsingVol < Vols.Streams.Size())
3199 { 3302 {
3200 // only StartParsingVol = 0 is safe search. 3303 // only StartParsingVol = 0 is safe search.
3201 RINOK(SeekToVol(0, 0)); 3304 RINOK(SeekToVol(0, 0))
3202 // if (Stream) 3305 // if (Stream)
3203 { 3306 {
3204 // UInt64 limit = 1 << 22; // for sfx 3307 // UInt64 limit = 1 << 22; // for sfx
@@ -3222,11 +3325,11 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3222 && (unsigned)Vols.StartParsingVol < Vols.Streams.Size() 3325 && (unsigned)Vols.StartParsingVol < Vols.Streams.Size()
3223 && Vols.Streams[(unsigned)Vols.StartParsingVol].Stream) 3326 && Vols.Streams[(unsigned)Vols.StartParsingVol].Stream)
3224 { 3327 {
3225 RINOK(SeekToVol(Vols.StartParsingVol, Vols.StreamIndex == Vols.StartVolIndex ? startPos : 0)); 3328 RINOK(SeekToVol(Vols.StartParsingVol, Vols.StreamIndex == Vols.StartVolIndex ? startPos : 0))
3226 } 3329 }
3227 else 3330 else
3228 { 3331 {
3229 RINOK(SeekToVol(-1, startPos)); 3332 RINOK(SeekToVol(-1, startPos))
3230 } 3333 }
3231 3334
3232 // UInt64 limit = 1 << 22; 3335 // UInt64 limit = 1 << 22;
@@ -3242,8 +3345,8 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3242 else if (!IsMultiVol) 3345 else if (!IsMultiVol)
3243 { 3346 {
3244 /* 3347 /*
3245 // if (startPos != 0), probably CD copuld be already tested with another call with (startPos == 0). 3348 // if (startPos != 0), probably CD could be already tested with another call with (startPos == 0).
3246 // so we don't want to try to open CD again in that ase. 3349 // so we don't want to try to open CD again in that case.
3247 if (startPos != 0) 3350 if (startPos != 0)
3248 return res; 3351 return res;
3249 // we can try to open CD, if there is no Marker and (startPos == 0). 3352 // 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,
3254 3357
3255 if (ArcInfo.IsSpanMode && !volWasRequested) 3358 if (ArcInfo.IsSpanMode && !volWasRequested)
3256 { 3359 {
3257 RINOK(ReadVols()); 3360 RINOK(ReadVols())
3258 if (IsMultiVol && MarkerIsFound && ArcInfo.MarkerVolIndex < 0) 3361 if (IsMultiVol && MarkerIsFound && ArcInfo.MarkerVolIndex < 0)
3259 ArcInfo.MarkerVolIndex = Vols.StartVolIndex; 3362 ArcInfo.MarkerVolIndex = Vols.StartVolIndex;
3260 } 3363 }
@@ -3271,7 +3374,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3271 Stream = Vols.Streams[(unsigned)Vols.StartVolIndex].Stream; 3374 Stream = Vols.Streams[(unsigned)Vols.StartVolIndex].Stream;
3272 if (Stream) 3375 if (Stream)
3273 { 3376 {
3274 RINOK(Seek_SavePos(curPos)); 3377 RINOK(Seek_SavePos(curPos))
3275 } 3378 }
3276 else 3379 else
3277 IsMultiVol = false; 3380 IsMultiVol = false;
@@ -3287,7 +3390,7 @@ HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchLimit,
3287 Stream = StartStream; 3390 Stream = StartStream;
3288 Vols.StreamIndex = -1; 3391 Vols.StreamIndex = -1;
3289 InitBuf(); 3392 InitBuf();
3290 RINOK(Seek_SavePos(curPos)); 3393 RINOK(Seek_SavePos(curPos))
3291 } 3394 }
3292 3395
3293 ArcInfo.MarkerVolIndex = -1; 3396 ArcInfo.MarkerVolIndex = -1;
@@ -3356,7 +3459,7 @@ HRESULT CInArchive::GetItemStream(const CItemEx &item, bool seekPackData, CMyCom
3356 if (UseDisk_in_SingleVol && item.Disk != EcdVolIndex) 3459 if (UseDisk_in_SingleVol && item.Disk != EcdVolIndex)
3357 return S_OK; 3460 return S_OK;
3358 pos = (UInt64)((Int64)pos + ArcInfo.Base); 3461 pos = (UInt64)((Int64)pos + ArcInfo.Base);
3359 RINOK(StreamRef->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); 3462 RINOK(InStream_SeekSet(StreamRef, pos))
3360 stream = StreamRef; 3463 stream = StreamRef;
3361 return S_OK; 3464 return S_OK;
3362 } 3465 }
@@ -3367,7 +3470,7 @@ HRESULT CInArchive::GetItemStream(const CItemEx &item, bool seekPackData, CMyCom
3367 IInStream *str2 = Vols.Streams[item.Disk].Stream; 3470 IInStream *str2 = Vols.Streams[item.Disk].Stream;
3368 if (!str2) 3471 if (!str2)
3369 return S_OK; 3472 return S_OK;
3370 RINOK(str2->Seek((Int64)pos, STREAM_SEEK_SET, NULL)); 3473 RINOK(InStream_SeekSet(str2, pos))
3371 3474
3372 Vols.NeedSeek = false; 3475 Vols.NeedSeek = false;
3373 Vols.StreamIndex = (int)item.Disk; 3476 Vols.StreamIndex = (int)item.Disk;
diff --git a/CPP/7zip/Archive/Zip/ZipIn.h b/CPP/7zip/Archive/Zip/ZipIn.h
index 1498afe..bea26dc 100644
--- a/CPP/7zip/Archive/Zip/ZipIn.h
+++ b/CPP/7zip/Archive/Zip/ZipIn.h
@@ -1,11 +1,12 @@
1// Archive/ZipIn.h 1// Archive/ZipIn.h
2 2
3#ifndef __ZIP_IN_H 3#ifndef ZIP7_INC_ZIP_IN_H
4#define __ZIP_IN_H 4#define ZIP7_INC_ZIP_IN_H
5 5
6#include "../../../Common/MyBuffer2.h" 6#include "../../../Common/MyBuffer2.h"
7#include "../../../Common/MyCom.h" 7#include "../../../Common/MyCom.h"
8 8
9#include "../../Common/StreamUtils.h"
9#include "../../IStream.h" 10#include "../../IStream.h"
10 11
11#include "ZipHeader.h" 12#include "ZipHeader.h"
@@ -154,7 +155,7 @@ struct CVols
154 CMyComPtr<IInStream> Stream; 155 CMyComPtr<IInStream> Stream;
155 UInt64 Size; 156 UInt64 Size;
156 157
157 HRESULT SeekToStart() const { return Stream->Seek(0, STREAM_SEEK_SET, NULL); } 158 HRESULT SeekToStart() const { return InStream_SeekToBegin(Stream); }
158 159
159 CSubStreamInfo(): Size(0) {} 160 CSubStreamInfo(): Size(0) {}
160 }; 161 };
@@ -233,16 +234,12 @@ struct CVols
233}; 234};
234 235
235 236
236class CVolStream: 237Z7_CLASS_IMP_COM_1(
237 public ISequentialInStream, 238 CVolStream
238 public CMyUnknownImp 239 , ISequentialInStream
239{ 240)
240public: 241public:
241 CVols *Vols; 242 CVols *Vols;
242
243 MY_UNKNOWN_IMP1(ISequentialInStream)
244
245 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
246}; 243};
247 244
248 245
@@ -269,6 +266,8 @@ class CInArchive
269 _cnt += skip; 266 _cnt += skip;
270 } 267 }
271 268
269 HRESULT AllocateBuffer(size_t size);
270
272 UInt64 GetVirtStreamPos() { return _streamPos - _bufCached + _bufPos; } 271 UInt64 GetVirtStreamPos() { return _streamPos - _bufCached + _bufPos; }
273 272
274 bool _inBufMode; 273 bool _inBufMode;
@@ -353,12 +352,19 @@ public:
353 UInt32 EcdVolIndex; 352 UInt32 EcdVolIndex;
354 353
355 CVols Vols; 354 CVols Vols;
355
356 bool Force_ReadLocals_Mode;
357 bool Disable_VolsRead;
358 bool Disable_FindMarker;
356 359
357 CInArchive(): 360 CInArchive():
358 IsArcOpen(false), 361 IsArcOpen(false),
359 Stream(NULL), 362 Stream(NULL),
360 StartStream(NULL), 363 StartStream(NULL),
361 Callback(NULL) 364 Callback(NULL),
365 Force_ReadLocals_Mode(false),
366 Disable_VolsRead(false),
367 Disable_FindMarker(false)
362 {} 368 {}
363 369
364 UInt64 GetPhySize() const 370 UInt64 GetPhySize() const
@@ -412,8 +418,8 @@ public:
412 418
413 419
414 HRESULT CheckDescriptor(const CItemEx &item); 420 HRESULT CheckDescriptor(const CItemEx &item);
415 HRESULT ReadLocalItemAfterCdItem(CItemEx &item, bool &isAvail, bool &headersError); 421 HRESULT Read_LocalItem_After_CdItem(CItemEx &item, bool &isAvail, bool &headersError);
416 HRESULT ReadLocalItemAfterCdItemFull(CItemEx &item); 422 HRESULT Read_LocalItem_After_CdItem_Full(CItemEx &item);
417 423
418 HRESULT GetItemStream(const CItemEx &item, bool seekPackData, CMyComPtr<ISequentialInStream> &stream); 424 HRESULT GetItemStream(const CItemEx &item, bool seekPackData, CMyComPtr<ISequentialInStream> &stream);
419 425
diff --git a/CPP/7zip/Archive/Zip/ZipItem.cpp b/CPP/7zip/Archive/Zip/ZipItem.cpp
index cffbb78..a77643b 100644
--- a/CPP/7zip/Archive/Zip/ZipItem.cpp
+++ b/CPP/7zip/Archive/Zip/ZipItem.cpp
@@ -45,7 +45,7 @@ static const CUInt32PCharPair g_ExtraTypes[] =
45 45
46void CExtraSubBlock::PrintInfo(AString &s) const 46void CExtraSubBlock::PrintInfo(AString &s) const
47{ 47{
48 for (unsigned i = 0; i < ARRAY_SIZE(g_ExtraTypes); i++) 48 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ExtraTypes); i++)
49 { 49 {
50 const CUInt32PCharPair &pair = g_ExtraTypes[i]; 50 const CUInt32PCharPair &pair = g_ExtraTypes[i];
51 if (pair.Value == ID) 51 if (pair.Value == ID)
diff --git a/CPP/7zip/Archive/Zip/ZipItem.h b/CPP/7zip/Archive/Zip/ZipItem.h
index 934d7ec..4a25de3 100644
--- a/CPP/7zip/Archive/Zip/ZipItem.h
+++ b/CPP/7zip/Archive/Zip/ZipItem.h
@@ -1,7 +1,7 @@
1// Archive/ZipItem.h 1// Archive/ZipItem.h
2 2
3#ifndef __ARCHIVE_ZIP_ITEM_H 3#ifndef ZIP7_INC_ARCHIVE_ZIP_ITEM_H
4#define __ARCHIVE_ZIP_ITEM_H 4#define ZIP7_INC_ARCHIVE_ZIP_ITEM_H
5 5
6#include "../../../../C/CpuArch.h" 6#include "../../../../C/CpuArch.h"
7 7
diff --git a/CPP/7zip/Archive/Zip/ZipOut.cpp b/CPP/7zip/Archive/Zip/ZipOut.cpp
index 8f3f43b..63f1a71 100644
--- a/CPP/7zip/Archive/Zip/ZipOut.cpp
+++ b/CPP/7zip/Archive/Zip/ZipOut.cpp
@@ -12,6 +12,20 @@
12namespace NArchive { 12namespace NArchive {
13namespace NZip { 13namespace NZip {
14 14
15HRESULT COutArchive::ClearRestriction()
16{
17 if (SetRestriction)
18 return SetRestriction->SetRestriction(0, 0);
19 return S_OK;
20}
21
22HRESULT COutArchive::SetRestrictionFromCurrent()
23{
24 if (SetRestriction)
25 return SetRestriction->SetRestriction(m_Base + m_CurPos, (UInt64)(Int64)-1);
26 return S_OK;
27}
28
15HRESULT COutArchive::Create(IOutStream *outStream) 29HRESULT COutArchive::Create(IOutStream *outStream)
16{ 30{
17 m_CurPos = 0; 31 m_CurPos = 0;
@@ -97,7 +111,7 @@ void COutArchive::WriteCommonItemInfo(const CLocalItem &item, bool isZip64)
97} 111}
98 112
99 113
100#define WRITE_32_VAL_SPEC(__v, __isZip64) Write32((__isZip64) ? 0xFFFFFFFF : (UInt32)(__v)); 114#define WRITE_32_VAL_SPEC(_v_, _isZip64_) Write32((_isZip64_) ? 0xFFFFFFFF : (UInt32)(_v_));
101 115
102 116
103void COutArchive::WriteUtfName(const CItemOut &item) 117void COutArchive::WriteUtfName(const CItemOut &item)
@@ -192,8 +206,8 @@ void COutArchive::WriteLocalHeader(CItemOut &item, bool needCheck)
192 size = 0; 206 size = 0;
193 } 207 }
194 208
195 WRITE_32_VAL_SPEC(packSize, isZip64); 209 WRITE_32_VAL_SPEC(packSize, isZip64)
196 WRITE_32_VAL_SPEC(size, isZip64); 210 WRITE_32_VAL_SPEC(size, isZip64)
197 211
198 Write16((UInt16)item.Name.Len()); 212 Write16((UInt16)item.Name.Len());
199 213
@@ -249,19 +263,19 @@ void COutArchive::WriteLocalHeader_Replace(CItemOut &item)
249void COutArchive::WriteDescriptor(const CItemOut &item) 263void COutArchive::WriteDescriptor(const CItemOut &item)
250{ 264{
251 Byte buf[kDataDescriptorSize64]; 265 Byte buf[kDataDescriptorSize64];
252 SetUi32(buf, NSignature::kDataDescriptor); 266 SetUi32(buf, NSignature::kDataDescriptor)
253 SetUi32(buf + 4, item.Crc); 267 SetUi32(buf + 4, item.Crc)
254 unsigned descriptorSize; 268 unsigned descriptorSize;
255 if (m_IsZip64) 269 if (m_IsZip64)
256 { 270 {
257 SetUi64(buf + 8, item.PackSize); 271 SetUi64(buf + 8, item.PackSize)
258 SetUi64(buf + 16, item.Size); 272 SetUi64(buf + 16, item.Size)
259 descriptorSize = kDataDescriptorSize64; 273 descriptorSize = kDataDescriptorSize64;
260 } 274 }
261 else 275 else
262 { 276 {
263 SetUi32(buf + 8, (UInt32)item.PackSize); 277 SetUi32(buf + 8, (UInt32)item.PackSize)
264 SetUi32(buf + 12, (UInt32)item.Size); 278 SetUi32(buf + 12, (UInt32)item.Size)
265 descriptorSize = kDataDescriptorSize32; 279 descriptorSize = kDataDescriptorSize32;
266 } 280 }
267 WriteBytes(buf, descriptorSize); 281 WriteBytes(buf, descriptorSize);
@@ -283,8 +297,8 @@ void COutArchive::WriteCentralHeader(const CItemOut &item)
283 WriteCommonItemInfo(item, isZip64); 297 WriteCommonItemInfo(item, isZip64);
284 Write32(item.Crc); 298 Write32(item.Crc);
285 299
286 WRITE_32_VAL_SPEC(item.PackSize, isPack64); 300 WRITE_32_VAL_SPEC(item.PackSize, isPack64)
287 WRITE_32_VAL_SPEC(item.Size, isUnPack64); 301 WRITE_32_VAL_SPEC(item.Size, isUnPack64)
288 302
289 Write16((UInt16)item.Name.Len()); 303 Write16((UInt16)item.Name.Len());
290 304
@@ -306,10 +320,10 @@ void COutArchive::WriteCentralHeader(const CItemOut &item)
306 const UInt16 commentSize = (UInt16)item.Comment.Size(); 320 const UInt16 commentSize = (UInt16)item.Comment.Size();
307 321
308 Write16(commentSize); 322 Write16(commentSize);
309 Write16(0); // DiskNumberStart; 323 Write16(0); // DiskNumberStart
310 Write16(item.InternalAttrib); 324 Write16(item.InternalAttrib);
311 Write32(item.ExternalAttrib); 325 Write32(item.ExternalAttrib);
312 WRITE_32_VAL_SPEC(item.LocalHeaderPos, isPosition64); 326 WRITE_32_VAL_SPEC(item.LocalHeaderPos, isPosition64)
313 WriteBytes((const char *)item.Name, item.Name.Len()); 327 WriteBytes((const char *)item.Name, item.Name.Len());
314 328
315 if (isZip64) 329 if (isZip64)
@@ -332,8 +346,10 @@ void COutArchive::WriteCentralHeader(const CItemOut &item)
332 WriteBytes(item.Comment, commentSize); 346 WriteBytes(item.Comment, commentSize);
333} 347}
334 348
335void COutArchive::WriteCentralDir(const CObjectVector<CItemOut> &items, const CByteBuffer *comment) 349HRESULT COutArchive::WriteCentralDir(const CObjectVector<CItemOut> &items, const CByteBuffer *comment)
336{ 350{
351 RINOK(ClearRestriction())
352
337 const UInt64 cdOffset = GetCurPos(); 353 const UInt64 cdOffset = GetCurPos();
338 FOR_VECTOR (i, items) 354 FOR_VECTOR (i, items)
339 WriteCentralHeader(items[i]); 355 WriteCentralHeader(items[i]);
@@ -357,8 +373,8 @@ void COutArchive::WriteCentralDir(const CObjectVector<CItemOut> &items, const CB
357 373
358 Write16(45); // made by version 374 Write16(45); // made by version
359 Write16(45); // extract version 375 Write16(45); // extract version
360 Write32(0); // ThisDiskNumber = 0; 376 Write32(0); // ThisDiskNumber
361 Write32(0); // StartCentralDirectoryDiskNumber;; 377 Write32(0); // StartCentralDirectoryDiskNumber
362 Write64((UInt64)items.Size()); 378 Write64((UInt64)items.Size());
363 Write64((UInt64)items.Size()); 379 Write64((UInt64)items.Size());
364 Write64((UInt64)cdSize); 380 Write64((UInt64)cdSize);
@@ -373,19 +389,20 @@ void COutArchive::WriteCentralDir(const CObjectVector<CItemOut> &items, const CB
373 } 389 }
374 390
375 Write32(NSignature::kEcd); 391 Write32(NSignature::kEcd);
376 Write16(0); // ThisDiskNumber = 0; 392 Write16(0); // ThisDiskNumber
377 Write16(0); // StartCentralDirectoryDiskNumber; 393 Write16(0); // StartCentralDirectoryDiskNumber
378 Write16((UInt16)(items64 ? 0xFFFF: items.Size())); 394 Write16((UInt16)(items64 ? 0xFFFF: items.Size()));
379 Write16((UInt16)(items64 ? 0xFFFF: items.Size())); 395 Write16((UInt16)(items64 ? 0xFFFF: items.Size()));
380 396
381 WRITE_32_VAL_SPEC(cdSize, cdSize64); 397 WRITE_32_VAL_SPEC(cdSize, cdSize64)
382 WRITE_32_VAL_SPEC(cdOffset, cdOffset64); 398 WRITE_32_VAL_SPEC(cdOffset, cdOffset64)
383 399
384 const UInt16 commentSize = (UInt16)(comment ? comment->Size() : 0); 400 const UInt16 commentSize = (UInt16)(comment ? comment->Size() : 0);
385 Write16((UInt16)commentSize); 401 Write16((UInt16)commentSize);
386 if (commentSize != 0) 402 if (commentSize != 0)
387 WriteBytes((const Byte *)*comment, commentSize); 403 WriteBytes((const Byte *)*comment, commentSize);
388 m_OutBuffer.FlushWithCheck(); 404 m_OutBuffer.FlushWithCheck();
405 return S_OK;
389} 406}
390 407
391void COutArchive::CreateStreamForCompressing(CMyComPtr<IOutStream> &outStream) 408void COutArchive::CreateStreamForCompressing(CMyComPtr<IOutStream> &outStream)
diff --git a/CPP/7zip/Archive/Zip/ZipOut.h b/CPP/7zip/Archive/Zip/ZipOut.h
index a645d67..e9b2abb 100644
--- a/CPP/7zip/Archive/Zip/ZipOut.h
+++ b/CPP/7zip/Archive/Zip/ZipOut.h
@@ -1,7 +1,7 @@
1// ZipOut.h 1// ZipOut.h
2 2
3#ifndef __ZIP_OUT_H 3#ifndef ZIP7_INC_ZIP_OUT_H
4#define __ZIP_OUT_H 4#define ZIP7_INC_ZIP_OUT_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -74,6 +74,10 @@ class COutArchive
74 74
75 void SeekToCurPos(); 75 void SeekToCurPos();
76public: 76public:
77 CMyComPtr<IStreamSetRestriction> SetRestriction;
78
79 HRESULT ClearRestriction();
80 HRESULT SetRestrictionFromCurrent();
77 HRESULT Create(IOutStream *outStream); 81 HRESULT Create(IOutStream *outStream);
78 82
79 UInt64 GetCurPos() const { return m_CurPos; } 83 UInt64 GetCurPos() const { return m_CurPos; }
@@ -88,7 +92,7 @@ public:
88 92
89 void WriteDescriptor(const CItemOut &item); 93 void WriteDescriptor(const CItemOut &item);
90 94
91 void WriteCentralDir(const CObjectVector<CItemOut> &items, const CByteBuffer *comment); 95 HRESULT WriteCentralDir(const CObjectVector<CItemOut> &items, const CByteBuffer *comment);
92 96
93 void CreateStreamForCompressing(CMyComPtr<IOutStream> &outStream); 97 void CreateStreamForCompressing(CMyComPtr<IOutStream> &outStream);
94 void CreateStreamForCopying(CMyComPtr<ISequentialOutStream> &outStream); 98 void CreateStreamForCopying(CMyComPtr<ISequentialOutStream> &outStream);
diff --git a/CPP/7zip/Archive/Zip/ZipRegister.cpp b/CPP/7zip/Archive/Zip/ZipRegister.cpp
index 3ad4715..c17a1a3 100644
--- a/CPP/7zip/Archive/Zip/ZipRegister.cpp
+++ b/CPP/7zip/Archive/Zip/ZipRegister.cpp
@@ -17,7 +17,7 @@ static const Byte k_Signature[] = {
17 6, 0x50, 0x4B, 0x30, 0x30, 0x50, 0x4B }; // NoSpan 17 6, 0x50, 0x4B, 0x30, 0x30, 0x50, 0x4B }; // NoSpan
18 18
19REGISTER_ARC_IO( 19REGISTER_ARC_IO(
20 "zip", "zip z01 zipx jar xpi odt ods docx xlsx epub ipa apk appx", 0, 1, 20 "zip", "zip z01 zipx jar xpi odt ods docx xlsx epub ipa apk appx", NULL, 1,
21 k_Signature, 21 k_Signature,
22 0, 22 0,
23 NArcInfoFlags::kFindSignature 23 NArcInfoFlags::kFindSignature
diff --git a/CPP/7zip/Archive/Zip/ZipUpdate.cpp b/CPP/7zip/Archive/Zip/ZipUpdate.cpp
index 7f13071..e6d881c 100644
--- a/CPP/7zip/Archive/Zip/ZipUpdate.cpp
+++ b/CPP/7zip/Archive/Zip/ZipUpdate.cpp
@@ -2,6 +2,15 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5// #define DEBUG_CACHE
6
7#ifdef DEBUG_CACHE
8#include <stdio.h>
9 #define PRF(x) x
10#else
11 #define PRF(x)
12#endif
13
5#include "../../../../C/Alloc.h" 14#include "../../../../C/Alloc.h"
6 15
7#include "../../../Common/AutoPtr.h" 16#include "../../../Common/AutoPtr.h"
@@ -15,12 +24,13 @@
15#include "../../Common/LimitedStreams.h" 24#include "../../Common/LimitedStreams.h"
16#include "../../Common/OutMemStream.h" 25#include "../../Common/OutMemStream.h"
17#include "../../Common/ProgressUtils.h" 26#include "../../Common/ProgressUtils.h"
18#ifndef _7ZIP_ST 27#ifndef Z7_ST
19#include "../../Common/ProgressMt.h" 28#include "../../Common/ProgressMt.h"
20#endif 29#endif
21#include "../../Common/StreamUtils.h" 30#include "../../Common/StreamUtils.h"
22 31
23#include "../../Compress/CopyCoder.h" 32#include "../../Compress/CopyCoder.h"
33// #include "../../Compress/ZstdEncoderProps.h"
24 34
25#include "ZipAddCommon.h" 35#include "ZipAddCommon.h"
26#include "ZipOut.h" 36#include "ZipOut.h"
@@ -107,7 +117,7 @@ static void SetFileHeader(
107 item.ExtractVersion.HostOS = kExtractHostOS; 117 item.ExtractVersion.HostOS = kExtractHostOS;
108 118
109 item.InternalAttrib = 0; // test it 119 item.InternalAttrib = 0; // test it
110 item.SetEncrypted(!isDir && options.PasswordIsDefined); 120 item.SetEncrypted(!isDir && options.Password_Defined);
111 item.SetDescriptorMode(useDescriptor); 121 item.SetDescriptorMode(useDescriptor);
112 122
113 if (isDir) 123 if (isDir)
@@ -156,7 +166,7 @@ static void SetItemInfoFromCompressingResult(const CCompressingResult &compressi
156} 166}
157 167
158 168
159#ifndef _7ZIP_ST 169#ifndef Z7_ST
160 170
161struct CMtSem 171struct CMtSem
162{ 172{
@@ -191,7 +201,7 @@ static THREAD_FUNC_DECL CoderThread(void *threadCoderInfo);
191 201
192struct CThreadInfo 202struct CThreadInfo
193{ 203{
194 DECL_EXTERNAL_CODECS_LOC_VARS2; 204 DECL_EXTERNAL_CODECS_LOC_VARS_DECL
195 205
196 NWindows::CThread Thread; 206 NWindows::CThread Thread;
197 NWindows::NSynchronization::CAutoResetEvent CompressEvent; 207 NWindows::NSynchronization::CAutoResetEvent CompressEvent;
@@ -211,19 +221,24 @@ struct CThreadInfo
211 HRESULT Result; 221 HRESULT Result;
212 CCompressingResult CompressingResult; 222 CCompressingResult CompressingResult;
213 223
224 bool IsFree;
214 bool InSeqMode; 225 bool InSeqMode;
215 bool OutSeqMode; 226 bool OutSeqMode;
216 bool IsFree; 227 bool ExpectedDataSize_IsConfirmed;
228
217 UInt32 UpdateIndex; 229 UInt32 UpdateIndex;
218 UInt32 FileTime; 230 UInt32 FileTime;
219 UInt64 ExpectedDataSize; 231 UInt64 ExpectedDataSize;
220 232
221 CThreadInfo(): 233 CThreadInfo():
234 MtSem(NULL),
222 ExitThread(false), 235 ExitThread(false),
223 ProgressSpec(NULL), 236 ProgressSpec(NULL),
224 OutStreamSpec(NULL), 237 OutStreamSpec(NULL),
238 IsFree(true),
225 InSeqMode(false), 239 InSeqMode(false),
226 OutSeqMode(false), 240 OutSeqMode(false),
241 ExpectedDataSize_IsConfirmed(false),
227 FileTime(0), 242 FileTime(0),
228 ExpectedDataSize((UInt64)(Int64)-1) 243 ExpectedDataSize((UInt64)(Int64)-1)
229 {} 244 {}
@@ -270,6 +285,7 @@ void CThreadInfo::WaitAndCode()
270 EXTERNAL_CODECS_LOC_VARS 285 EXTERNAL_CODECS_LOC_VARS
271 InStream, OutStream, 286 InStream, OutStream,
272 InSeqMode, OutSeqMode, FileTime, ExpectedDataSize, 287 InSeqMode, OutSeqMode, FileTime, ExpectedDataSize,
288 ExpectedDataSize_IsConfirmed,
273 Progress, CompressingResult); 289 Progress, CompressingResult);
274 290
275 if (Result == S_OK && Progress) 291 if (Result == S_OK && Progress)
@@ -313,7 +329,7 @@ class CMemRefs
313public: 329public:
314 CMemBlockManagerMt *Manager; 330 CMemBlockManagerMt *Manager;
315 CObjectVector<CMemBlocks2> Refs; 331 CObjectVector<CMemBlocks2> Refs;
316 CMemRefs(CMemBlockManagerMt *manager): Manager(manager) {} ; 332 CMemRefs(CMemBlockManagerMt *manager): Manager(manager) {}
317 ~CMemRefs() 333 ~CMemRefs()
318 { 334 {
319 FOR_VECTOR (i, Refs) 335 FOR_VECTOR (i, Refs)
@@ -321,10 +337,11 @@ public:
321 } 337 }
322}; 338};
323 339
324class CMtProgressMixer2: 340
325 public ICompressProgressInfo, 341Z7_CLASS_IMP_NOQIB_1(
326 public CMyUnknownImp 342 CMtProgressMixer2
327{ 343 , ICompressProgressInfo
344)
328 UInt64 ProgressOffset; 345 UInt64 ProgressOffset;
329 UInt64 InSizes[2]; 346 UInt64 InSizes[2];
330 UInt64 OutSizes[2]; 347 UInt64 OutSizes[2];
@@ -333,12 +350,10 @@ class CMtProgressMixer2:
333 bool _inSizeIsMain; 350 bool _inSizeIsMain;
334public: 351public:
335 NWindows::NSynchronization::CCriticalSection CriticalSection; 352 NWindows::NSynchronization::CCriticalSection CriticalSection;
336 MY_UNKNOWN_IMP
337 void Create(IProgress *progress, bool inSizeIsMain); 353 void Create(IProgress *progress, bool inSizeIsMain);
338 void SetProgressOffset(UInt64 progressOffset); 354 void SetProgressOffset(UInt64 progressOffset);
339 void SetProgressOffset_NoLock(UInt64 progressOffset); 355 void SetProgressOffset_NoLock(UInt64 progressOffset);
340 HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize); 356 HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize);
341 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
342}; 357};
343 358
344void CMtProgressMixer2::Create(IProgress *progress, bool inSizeIsMain) 359void CMtProgressMixer2::Create(IProgress *progress, bool inSizeIsMain)
@@ -367,7 +382,7 @@ HRESULT CMtProgressMixer2::SetRatioInfo(unsigned index, const UInt64 *inSize, co
367 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); 382 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
368 if (index == 0 && RatioProgress) 383 if (index == 0 && RatioProgress)
369 { 384 {
370 RINOK(RatioProgress->SetRatioInfo(inSize, outSize)); 385 RINOK(RatioProgress->SetRatioInfo(inSize, outSize))
371 } 386 }
372 if (inSize) 387 if (inSize)
373 InSizes[index] = *inSize; 388 InSizes[index] = *inSize;
@@ -379,21 +394,20 @@ HRESULT CMtProgressMixer2::SetRatioInfo(unsigned index, const UInt64 *inSize, co
379 return Progress->SetCompleted(&v); 394 return Progress->SetCompleted(&v);
380} 395}
381 396
382STDMETHODIMP CMtProgressMixer2::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 397Z7_COM7F_IMF(CMtProgressMixer2::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
383{ 398{
384 return SetRatioInfo(0, inSize, outSize); 399 return SetRatioInfo(0, inSize, outSize);
385} 400}
386 401
387class CMtProgressMixer: 402
388 public ICompressProgressInfo, 403Z7_CLASS_IMP_NOQIB_1(
389 public CMyUnknownImp 404 CMtProgressMixer
390{ 405 , ICompressProgressInfo
406)
391public: 407public:
392 CMtProgressMixer2 *Mixer2; 408 CMtProgressMixer2 *Mixer2;
393 CMyComPtr<ICompressProgressInfo> RatioProgress; 409 CMyComPtr<ICompressProgressInfo> RatioProgress;
394 void Create(IProgress *progress, bool inSizeIsMain); 410 void Create(IProgress *progress, bool inSizeIsMain);
395 MY_UNKNOWN_IMP
396 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
397}; 411};
398 412
399void CMtProgressMixer::Create(IProgress *progress, bool inSizeIsMain) 413void CMtProgressMixer::Create(IProgress *progress, bool inSizeIsMain)
@@ -403,7 +417,7 @@ void CMtProgressMixer::Create(IProgress *progress, bool inSizeIsMain)
403 Mixer2->Create(progress, inSizeIsMain); 417 Mixer2->Create(progress, inSizeIsMain);
404} 418}
405 419
406STDMETHODIMP CMtProgressMixer::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 420Z7_COM7F_IMF(CMtProgressMixer::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
407{ 421{
408 return Mixer2->SetRatioInfo(1, inSize, outSize); 422 return Mixer2->SetRatioInfo(1, inSize, outSize);
409} 423}
@@ -431,6 +445,8 @@ static HRESULT UpdateItemOldData(
431 445
432 UInt64 rangeSize; 446 UInt64 rangeSize;
433 447
448 RINOK(archive.ClearRestriction())
449
434 if (ui.NewProps) 450 if (ui.NewProps)
435 { 451 {
436 if (item.HasDescriptor()) 452 if (item.HasDescriptor())
@@ -456,7 +472,7 @@ static HRESULT UpdateItemOldData(
456 472
457 CMyComPtr<ISequentialInStream> packStream; 473 CMyComPtr<ISequentialInStream> packStream;
458 474
459 RINOK(inArchive->GetItemStream(itemEx, ui.NewProps, packStream)); 475 RINOK(inArchive->GetItemStream(itemEx, ui.NewProps, packStream))
460 if (!packStream) 476 if (!packStream)
461 return E_NOTIMPL; 477 return E_NOTIMPL;
462 478
@@ -470,11 +486,13 @@ static HRESULT UpdateItemOldData(
470} 486}
471 487
472 488
473static void WriteDirHeader(COutArchive &archive, const CCompressionMethodMode *options, 489static HRESULT WriteDirHeader(COutArchive &archive, const CCompressionMethodMode *options,
474 const CUpdateItem &ui, CItemOut &item) 490 const CUpdateItem &ui, CItemOut &item)
475{ 491{
476 SetFileHeader(*options, ui, false, item); 492 SetFileHeader(*options, ui, false, item);
493 RINOK(archive.ClearRestriction())
477 archive.WriteLocalHeader(item); 494 archive.WriteLocalHeader(item);
495 return S_OK;
478} 496}
479 497
480 498
@@ -485,37 +503,55 @@ static void UpdatePropsFromStream(
485{ 503{
486 CMyComPtr<IStreamGetProps> getProps; 504 CMyComPtr<IStreamGetProps> getProps;
487 fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); 505 fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps);
488 if (!getProps) 506 UInt64 size = (UInt64)(Int64)-1;
489 return; 507 bool size_WasSet = false;
490
491 FILETIME cTime, aTime, mTime;
492 UInt64 size;
493 UInt32 attrib;
494 if (getProps->GetProps(&size, &cTime, &aTime, &mTime, &attrib) != S_OK)
495 return;
496 508
497 if (size != item.Size && size != (UInt64)(Int64)-1) 509 if (getProps)
498 { 510 {
499 const Int64 newComplexity = (Int64)totalComplexity + ((Int64)size - (Int64)item.Size); 511 FILETIME cTime, aTime, mTime;
500 if (newComplexity > 0) 512 UInt32 attrib;
513 if (getProps->GetProps(&size, &cTime, &aTime, &mTime, &attrib) == S_OK)
501 { 514 {
502 totalComplexity = (UInt64)newComplexity; 515 if (options.Write_MTime)
503 updateCallback->SetTotal(totalComplexity); 516 if (!FILETIME_IsZero(mTime))
517 {
518 item.Ntfs_MTime = mTime;
519 NTime::UtcFileTime_To_LocalDosTime(mTime, item.Time);
520 }
521
522 if (options.Write_CTime) if (!FILETIME_IsZero(cTime)) item.Ntfs_CTime = cTime;
523 if (options.Write_ATime) if (!FILETIME_IsZero(aTime)) item.Ntfs_ATime = aTime;
524
525 item.Attrib = attrib;
526 size_WasSet = true;
504 } 527 }
505 item.Size = size;
506 } 528 }
507 529
508 if (options.Write_MTime) 530 if (!size_WasSet)
509 if (!FILETIME_IsZero(mTime)) 531 {
532 CMyComPtr<IStreamGetSize> streamGetSize;
533 fileInStream->QueryInterface(IID_IStreamGetSize, (void **)&streamGetSize);
534 if (streamGetSize)
510 { 535 {
511 item.Ntfs_MTime = mTime; 536 if (streamGetSize->GetSize(&size) == S_OK)
512 NTime::UtcFileTime_To_LocalDosTime(mTime, item.Time); 537 size_WasSet = true;
513 } 538 }
539 }
514 540
515 if (options.Write_CTime) if (!FILETIME_IsZero(cTime)) item.Ntfs_CTime = cTime; 541 if (size_WasSet && size != (UInt64)(Int64)-1)
516 if (options.Write_ATime) if (!FILETIME_IsZero(aTime)) item.Ntfs_ATime = aTime; 542 {
517 543 item.Size_WasSetFromStream = true;
518 item.Attrib = attrib; 544 if (size != item.Size)
545 {
546 const Int64 newComplexity = (Int64)totalComplexity + ((Int64)size - (Int64)item.Size);
547 if (newComplexity > 0)
548 {
549 totalComplexity = (UInt64)newComplexity;
550 updateCallback->SetTotal(totalComplexity);
551 }
552 item.Size = size;
553 }
554 }
519} 555}
520 556
521 557
@@ -613,7 +649,7 @@ static HRESULT Update2St(
613 { 649 {
614 lps->InSize = unpackSizeTotal; 650 lps->InSize = unpackSizeTotal;
615 lps->OutSize = packSizeTotal; 651 lps->OutSize = packSizeTotal;
616 RINOK(lps->SetCur()); 652 RINOK(lps->SetCur())
617 CUpdateItem &ui = updateItems[itemIndex]; 653 CUpdateItem &ui = updateItems[itemIndex];
618 CItemEx itemEx; 654 CItemEx itemEx;
619 CItemOut item; 655 CItemOut item;
@@ -623,7 +659,7 @@ static HRESULT Update2St(
623 // Note: for (ui.NewProps && !ui.NewData) it copies Props from old archive, 659 // Note: for (ui.NewProps && !ui.NewData) it copies Props from old archive,
624 // But we will rewrite all important properties later. But we can keep some properties like Comment 660 // But we will rewrite all important properties later. But we can keep some properties like Comment
625 itemEx = inputItems[(unsigned)ui.IndexInArc]; 661 itemEx = inputItems[(unsigned)ui.IndexInArc];
626 if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) 662 if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK)
627 return E_NOTIMPL; 663 return E_NOTIMPL;
628 (CItem &)item = itemEx; 664 (CItem &)item = itemEx;
629 } 665 }
@@ -634,7 +670,7 @@ static HRESULT Update2St(
634 bool isDir = ui.IsDir; 670 bool isDir = ui.IsDir;
635 if (isDir) 671 if (isDir)
636 { 672 {
637 WriteDirHeader(archive, options, ui, item); 673 RINOK(WriteDirHeader(archive, options, ui, item))
638 } 674 }
639 else 675 else
640 { 676 {
@@ -644,10 +680,10 @@ static HRESULT Update2St(
644 if (res == S_FALSE) 680 if (res == S_FALSE)
645 { 681 {
646 lps->ProgressOffset += ui.Size; 682 lps->ProgressOffset += ui.Size;
647 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 683 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
648 continue; 684 continue;
649 } 685 }
650 RINOK(res); 686 RINOK(res)
651 if (!fileInStream) 687 if (!fileInStream)
652 return E_INVALIDARG; 688 return E_INVALIDARG;
653 689
@@ -667,7 +703,7 @@ static HRESULT Update2St(
667 RINOK(compressor.Set_Pre_CompressionResult( 703 RINOK(compressor.Set_Pre_CompressionResult(
668 inSeqMode, outSeqMode, 704 inSeqMode, outSeqMode,
669 ui.Size, 705 ui.Size,
670 compressingResult)); 706 compressingResult))
671 707
672 SetFileHeader(*options, ui, compressingResult.DescriptorMode, item); 708 SetFileHeader(*options, ui, compressingResult.DescriptorMode, item);
673 709
@@ -675,6 +711,7 @@ static HRESULT Update2St(
675 711
676 SetItemInfoFromCompressingResult(compressingResult, options->IsRealAesMode(), options->AesKeyMode, item); 712 SetItemInfoFromCompressingResult(compressingResult, options->IsRealAesMode(), options->AesKeyMode, item);
677 713
714 RINOK(archive.SetRestrictionFromCurrent())
678 archive.WriteLocalHeader(item); 715 archive.WriteLocalHeader(item);
679 716
680 CMyComPtr<IOutStream> outStream; 717 CMyComPtr<IOutStream> outStream;
@@ -684,8 +721,9 @@ static HRESULT Update2St(
684 EXTERNAL_CODECS_LOC_VARS 721 EXTERNAL_CODECS_LOC_VARS
685 fileInStream, outStream, 722 fileInStream, outStream,
686 inSeqMode, outSeqMode, 723 inSeqMode, outSeqMode,
687 ui.Time, ui.Size, 724 ui.Time,
688 progress, compressingResult)); 725 ui.Size, ui.Size_WasSetFromStream,
726 progress, compressingResult))
689 727
690 if (item.HasDescriptor() != compressingResult.DescriptorMode) 728 if (item.HasDescriptor() != compressingResult.DescriptorMode)
691 return E_FAIL; 729 return E_FAIL;
@@ -695,7 +733,7 @@ static HRESULT Update2St(
695 archive.WriteLocalHeader_Replace(item); 733 archive.WriteLocalHeader_Replace(item);
696 } 734 }
697 // if (reportArcProp) RINOK(ReportProps(reportArcProp, ui.IndexInClient, item, options->IsRealAesMode())) 735 // if (reportArcProp) RINOK(ReportProps(reportArcProp, ui.IndexInClient, item, options->IsRealAesMode()))
698 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 736 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
699 unpackSizeTotal += item.Size; 737 unpackSizeTotal += item.Size;
700 packSizeTotal += item.PackSize; 738 packSizeTotal += item.PackSize;
701 } 739 }
@@ -705,7 +743,7 @@ static HRESULT Update2St(
705 UInt64 complexity = 0; 743 UInt64 complexity = 0;
706 lps->SendRatio = false; 744 lps->SendRatio = false;
707 745
708 RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)); 746 RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity))
709 747
710 lps->SendRatio = true; 748 lps->SendRatio = true;
711 lps->ProgressOffset += complexity; 749 lps->ProgressOffset += complexity;
@@ -717,9 +755,9 @@ static HRESULT Update2St(
717 755
718 lps->InSize = unpackSizeTotal; 756 lps->InSize = unpackSizeTotal;
719 lps->OutSize = packSizeTotal; 757 lps->OutSize = packSizeTotal;
720 RINOK(lps->SetCur()); 758 RINOK(lps->SetCur())
721 759
722 archive.WriteCentralDir(items, comment); 760 RINOK(archive.WriteCentralDir(items, comment))
723 761
724 /* 762 /*
725 CTotalStats stat; 763 CTotalStats stat;
@@ -733,6 +771,130 @@ static HRESULT Update2St(
733 return lps->SetCur(); 771 return lps->SetCur();
734} 772}
735 773
774#ifndef Z7_ST
775
776
777static const size_t kBlockSize = 1 << 16;
778// kMemPerThread must be >= kBlockSize
779//
780static const size_t kMemPerThread = (size_t)sizeof(size_t) << 23;
781// static const size_t kMemPerThread = (size_t)sizeof(size_t) << 16; // for debug
782// static const size_t kMemPerThread = (size_t)1 << 16; // for debug
783
784/*
785in:
786 nt_Zip >= 1: the starting maximum number of ZIP threads for search
787out:
788 nt_Zip: calculated number of ZIP threads
789 returns: calculated number of ZSTD threads
790*/
791/*
792static UInt32 CalcThreads_for_ZipZstd(CZstdEncProps *zstdProps,
793 UInt64 memLimit, UInt32 totalThreads,
794 UInt32 &nt_Zip)
795{
796 for (; nt_Zip > 1; nt_Zip--)
797 {
798 UInt64 mem1 = memLimit / nt_Zip;
799 if (mem1 <= kMemPerThread)
800 continue;
801 mem1 -= kMemPerThread;
802 UInt32 n_ZSTD = ZstdEncProps_GetNumThreads_for_MemUsageLimit(
803 zstdProps, mem1, totalThreads / nt_Zip);
804 // we don't allow (nbWorkers == 1) here
805 if (n_ZSTD <= 1)
806 n_ZSTD = 0;
807 zstdProps->nbWorkers = n_ZSTD;
808 mem1 = ZstdEncProps_GetMemUsage(zstdProps);
809 if ((mem1 + kMemPerThread) * nt_Zip <= memLimit)
810 return n_ZSTD;
811 }
812 return ZstdEncProps_GetNumThreads_for_MemUsageLimit(
813 zstdProps, memLimit, totalThreads);
814}
815
816
817static UInt32 SetZstdThreads(
818 const CCompressionMethodMode &options,
819 COneMethodInfo *oneMethodMain,
820 UInt32 numThreads,
821 UInt32 numZipThreads_limit,
822 UInt64 numFilesToCompress,
823 UInt64 numBytesToCompress)
824{
825 NCompress::NZstd::CEncoderProps encoderProps;
826 RINOK(encoderProps.SetFromMethodProps(*oneMethodMain));
827 CZstdEncProps &zstdProps = encoderProps.EncProps;
828 ZstdEncProps_NormalizeFull(&zstdProps);
829 if (oneMethodMain->FindProp(NCoderPropID::kNumThreads) >= 0)
830 {
831 // threads for ZSTD are fixed
832 if (zstdProps.nbWorkers > 1)
833 numThreads /= zstdProps.nbWorkers;
834 if (numThreads > numZipThreads_limit)
835 numThreads = numZipThreads_limit;
836 if (options._memUsage_WasSet
837 && !options._numThreads_WasForced)
838 {
839 const UInt64 mem1 = ZstdEncProps_GetMemUsage(&zstdProps);
840 const UInt64 numZipThreads = options._memUsage_Compress / (mem1 + kMemPerThread);
841 if (numThreads > numZipThreads)
842 numThreads = (UInt32)numZipThreads;
843 }
844 return numThreads;
845 }
846 {
847 // threads for ZSTD are not fixed
848
849 // calculate estimated required number of ZST threads per file size statistics
850 UInt32 t = MY_ZSTDMT_NBWORKERS_MAX;
851 {
852 UInt64 averageNumberOfBlocks = 0;
853 const UInt64 averageSize = numBytesToCompress / numFilesToCompress;
854 const UInt64 jobSize = zstdProps.jobSize;
855 if (jobSize != 0)
856 averageNumberOfBlocks = averageSize / jobSize + 0;
857 if (t > averageNumberOfBlocks)
858 t = (UInt32)averageNumberOfBlocks;
859 }
860 if (t > numThreads)
861 t = numThreads;
862
863 // calculate the nuber of zip threads
864 UInt32 numZipThreads = numThreads;
865 if (t > 1)
866 numZipThreads = numThreads / t;
867 if (numZipThreads > numZipThreads_limit)
868 numZipThreads = numZipThreads_limit;
869 if (numZipThreads < 1)
870 numZipThreads = 1;
871 {
872 // recalculate the number of ZSTD threads via the number of ZIP threads
873 const UInt32 t2 = numThreads / numZipThreads;
874 if (t < t2)
875 t = t2;
876 }
877
878 if (options._memUsage_WasSet
879 && !options._numThreads_WasForced)
880 {
881 t = CalcThreads_for_ZipZstd(&zstdProps,
882 options._memUsage_Compress, numThreads, numZipThreads);
883 numThreads = numZipThreads;
884 }
885 // we don't use (nbWorkers = 1) here
886 if (t <= 1)
887 t = 0;
888 oneMethodMain->AddProp_NumThreads(t);
889 return numThreads;
890 }
891}
892*/
893
894#endif
895
896
897
736 898
737static HRESULT Update2( 899static HRESULT Update2(
738 DECL_EXTERNAL_CODECS_LOC_VARS 900 DECL_EXTERNAL_CODECS_LOC_VARS
@@ -755,8 +917,10 @@ static HRESULT Update2(
755 917
756 bool unknownComplexity = false; 918 bool unknownComplexity = false;
757 UInt64 complexity = 0; 919 UInt64 complexity = 0;
920 #ifndef Z7_ST
758 UInt64 numFilesToCompress = 0; 921 UInt64 numFilesToCompress = 0;
759 UInt64 numBytesToCompress = 0; 922 UInt64 numBytesToCompress = 0;
923 #endif
760 924
761 unsigned i; 925 unsigned i;
762 926
@@ -769,8 +933,10 @@ static HRESULT Update2(
769 unknownComplexity = true; 933 unknownComplexity = true;
770 else 934 else
771 complexity += ui.Size; 935 complexity += ui.Size;
936 #ifndef Z7_ST
772 numBytesToCompress += ui.Size; 937 numBytesToCompress += ui.Size;
773 numFilesToCompress++; 938 numFilesToCompress++;
939 #endif
774 /* 940 /*
775 if (ui.Commented) 941 if (ui.Commented)
776 complexity += ui.CommentRange.Size; 942 complexity += ui.CommentRange.Size;
@@ -779,7 +945,7 @@ static HRESULT Update2(
779 else 945 else
780 { 946 {
781 CItemEx inputItem = inputItems[(unsigned)ui.IndexInArc]; 947 CItemEx inputItem = inputItems[(unsigned)ui.IndexInArc];
782 if (inArchive->ReadLocalItemAfterCdItemFull(inputItem) != S_OK) 948 if (inArchive->Read_LocalItem_After_CdItem_Full(inputItem) != S_OK)
783 return E_NOTIMPL; 949 return E_NOTIMPL;
784 complexity += inputItem.GetLocalFullSize(); 950 complexity += inputItem.GetLocalFullSize();
785 // complexity += inputItem.GetCentralExtraPlusCommentSize(); 951 // complexity += inputItem.GetCentralExtraPlusCommentSize();
@@ -831,10 +997,22 @@ static HRESULT Update2(
831 } 997 }
832 998
833 999
834 #ifndef _7ZIP_ST 1000 #ifndef Z7_ST
835 1001
836 UInt32 numThreads = options._numThreads; 1002 UInt32 numThreads = options._numThreads;
837 1003
1004 UInt32 numZipThreads_limit = numThreads;
1005 if (numZipThreads_limit > numFilesToCompress)
1006 numZipThreads_limit = (UInt32)numFilesToCompress;
1007
1008 if (numZipThreads_limit > 1)
1009 {
1010 const unsigned numFiles_OPEN_MAX = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks();
1011 // printf("\nzip:numFiles_OPEN_MAX =%d\n", (unsigned)numFiles_OPEN_MAX);
1012 if (numZipThreads_limit > numFiles_OPEN_MAX)
1013 numZipThreads_limit = (UInt32)numFiles_OPEN_MAX;
1014 }
1015
838 { 1016 {
839 const UInt32 kNumMaxThreads = 1017 const UInt32 kNumMaxThreads =
840 #ifdef _WIN32 1018 #ifdef _WIN32
@@ -849,11 +1027,13 @@ static HRESULT Update2(
849 if (numThreads > MAXIMUM_WAIT_OBJECTS) // is 64 in Windows 1027 if (numThreads > MAXIMUM_WAIT_OBJECTS) // is 64 in Windows
850 numThreads = MAXIMUM_WAIT_OBJECTS; 1028 numThreads = MAXIMUM_WAIT_OBJECTS;
851 */ 1029 */
1030
1031
1032 /*
1033 // zstd supports (numThreads == 0);
852 if (numThreads < 1) 1034 if (numThreads < 1)
853 numThreads = 1; 1035 numThreads = 1;
854 1036 */
855 const size_t kMemPerThread = (size_t)sizeof(size_t) << 23;
856 const size_t kBlockSize = 1 << 16;
857 1037
858 bool mtMode = (numThreads > 1); 1038 bool mtMode = (numThreads > 1);
859 1039
@@ -864,21 +1044,46 @@ static HRESULT Update2(
864 1044
865 if (!mtMode) 1045 if (!mtMode)
866 { 1046 {
1047 // if (oneMethodMain) {
1048 /*
1049 if (method == NFileHeader::NCompressionMethod::kZstdWz)
1050 {
1051 if (oneMethodMain->FindProp(NCoderPropID::kNumThreads) < 0)
1052 {
1053 // numZstdThreads was not forced in oneMethodMain
1054 if (numThreads >= 1
1055 && options._memUsage_WasSet
1056 && !options._numThreads_WasForced)
1057 {
1058 NCompress::NZstd::CEncoderProps encoderProps;
1059 RINOK(encoderProps.SetFromMethodProps(*oneMethodMain))
1060 CZstdEncProps &zstdProps = encoderProps.EncProps;
1061 ZstdEncProps_NormalizeFull(&zstdProps);
1062 numThreads = ZstdEncProps_GetNumThreads_for_MemUsageLimit(
1063 &zstdProps, options._memUsage_Compress, numThreads);
1064 // we allow (nbWorkers = 1) here.
1065 }
1066 oneMethodMain->AddProp_NumThreads(numThreads);
1067 }
1068 } // kZstdWz
1069 */
1070 // } // oneMethodMain
1071
867 FOR_VECTOR (mi, options2._methods) 1072 FOR_VECTOR (mi, options2._methods)
868 { 1073 {
869 COneMethodInfo &onem = options2._methods[mi]; 1074 COneMethodInfo &onem = options2._methods[mi];
870 1075
871 if (onem.FindProp(NCoderPropID::kNumThreads) < 0) 1076 if (onem.FindProp(NCoderPropID::kNumThreads) < 0)
872 { 1077 {
873 // fixme: we should check the number of threads for xz mehod also 1078 // fixme: we should check the number of threads for xz method also
874 // fixed for 9.31. bzip2 default is just one thread. 1079 // fixed for 9.31. bzip2 default is just one thread.
875 onem.AddProp_NumThreads(numThreads); 1080 onem.AddProp_NumThreads(numThreads);
876 } 1081 }
877 } 1082 }
878 } 1083 }
879 else 1084 else // mtMode
880 { 1085 {
881 if (method == NFileHeader::NCompressionMethod::kStore && !options.PasswordIsDefined) 1086 if (method == NFileHeader::NCompressionMethod::kStore && !options.Password_Defined)
882 numThreads = 1; 1087 numThreads = 1;
883 1088
884 if (oneMethodMain) 1089 if (oneMethodMain)
@@ -925,6 +1130,15 @@ static HRESULT Update2(
925 } 1130 }
926 numThreads /= (unsigned)numXzThreads; 1131 numThreads /= (unsigned)numXzThreads;
927 } 1132 }
1133 /*
1134 else if (method == NFileHeader::NCompressionMethod::kZstdWz)
1135 {
1136 numThreads = SetZstdThreads(options,
1137 oneMethodMain, numThreads,
1138 numZipThreads_limit,
1139 numFilesToCompress, numBytesToCompress);
1140 }
1141 */
928 else if ( 1142 else if (
929 method == NFileHeader::NCompressionMethod::kDeflate 1143 method == NFileHeader::NCompressionMethod::kDeflate
930 || method == NFileHeader::NCompressionMethod::kDeflate64 1144 || method == NFileHeader::NCompressionMethod::kDeflate64
@@ -964,8 +1178,8 @@ static HRESULT Update2(
964 } 1178 }
965 } // (oneMethodMain) 1179 } // (oneMethodMain)
966 1180
967 if (numThreads > numFilesToCompress) 1181 if (numThreads > numZipThreads_limit)
968 numThreads = (UInt32)numFilesToCompress; 1182 numThreads = numZipThreads_limit;
969 if (numThreads <= 1) 1183 if (numThreads <= 1)
970 { 1184 {
971 mtMode = false; 1185 mtMode = false;
@@ -989,13 +1203,15 @@ static HRESULT Update2(
989 ); 1203 );
990 1204
991 1205
992 #ifndef _7ZIP_ST 1206 #ifndef Z7_ST
993 1207
994 /* 1208 /*
995 CTotalStats stat; 1209 CTotalStats stat;
996 stat.Size = 0; 1210 stat.Size = 0;
997 stat.PackSize = 0; 1211 stat.PackSize = 0;
998 */ 1212 */
1213 if (numThreads < 1)
1214 numThreads = 1;
999 1215
1000 CObjectVector<CItemOut> items; 1216 CObjectVector<CItemOut> items;
1001 1217
@@ -1022,7 +1238,7 @@ static HRESULT Update2(
1022 CUIntVector threadIndices; // list threads in order of updateItems 1238 CUIntVector threadIndices; // list threads in order of updateItems
1023 1239
1024 { 1240 {
1025 RINOK(memManager.AllocateSpaceAlways((size_t)numThreads * (kMemPerThread / kBlockSize))); 1241 RINOK(memManager.AllocateSpaceAlways((size_t)numThreads * (kMemPerThread / kBlockSize)))
1026 for (i = 0; i < updateItems.Size(); i++) 1242 for (i = 0; i < updateItems.Size(); i++)
1027 refs.Refs.Add(CMemBlocks2()); 1243 refs.Refs.Add(CMemBlocks2());
1028 1244
@@ -1035,25 +1251,20 @@ static HRESULT Update2(
1035 for (i = 0; i < numThreads; i++) 1251 for (i = 0; i < numThreads; i++)
1036 { 1252 {
1037 CThreadInfo &threadInfo = threads.Threads[i]; 1253 CThreadInfo &threadInfo = threads.Threads[i];
1038 threadInfo.SetOptions(options2); ; 1254 threadInfo.ThreadIndex = i;
1039 #ifdef EXTERNAL_CODECS 1255 threadInfo.SetOptions(options2);
1040 threadInfo.__externalCodecs = __externalCodecs; 1256 #ifdef Z7_EXTERNAL_CODECS
1257 threadInfo._externalCodecs = _externalCodecs;
1041 #endif 1258 #endif
1042 RINOK(threadInfo.CreateEvents()); 1259 RINOK(threadInfo.CreateEvents())
1043 threadInfo.OutStreamSpec = new COutMemStream(&memManager); 1260 threadInfo.OutStreamSpec = new COutMemStream(&memManager);
1044 RINOK(threadInfo.OutStreamSpec->CreateEvents(SYNC_WFMO(&memManager.Synchro))); 1261 RINOK(threadInfo.OutStreamSpec->CreateEvents(SYNC_WFMO(&memManager.Synchro)))
1045 threadInfo.OutStream = threadInfo.OutStreamSpec; 1262 threadInfo.OutStream = threadInfo.OutStreamSpec;
1046 threadInfo.IsFree = true;
1047 threadInfo.ProgressSpec = new CMtCompressProgress(); 1263 threadInfo.ProgressSpec = new CMtCompressProgress();
1048 threadInfo.Progress = threadInfo.ProgressSpec; 1264 threadInfo.Progress = threadInfo.ProgressSpec;
1049 threadInfo.ProgressSpec->Init(&mtCompressProgressMixer, i); 1265 threadInfo.ProgressSpec->Init(&mtCompressProgressMixer, i);
1050 threadInfo.InSeqMode = false;
1051 threadInfo.OutSeqMode = false;
1052 threadInfo.FileTime = 0;
1053 threadInfo.ExpectedDataSize = (UInt64)(Int64)-1;
1054 threadInfo.ThreadIndex = i;
1055 threadInfo.MtSem = &mtSem; 1266 threadInfo.MtSem = &mtSem;
1056 RINOK(threadInfo.CreateThread()); 1267 RINOK(threadInfo.CreateThread())
1057 } 1268 }
1058 } 1269 }
1059 1270
@@ -1084,7 +1295,7 @@ static HRESULT Update2(
1084 else 1295 else
1085 { 1296 {
1086 itemEx = inputItems[(unsigned)ui.IndexInArc]; 1297 itemEx = inputItems[(unsigned)ui.IndexInArc];
1087 if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) 1298 if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK)
1088 return E_NOTIMPL; 1299 return E_NOTIMPL;
1089 (CItem &)item = itemEx; 1300 (CItem &)item = itemEx;
1090 if (item.IsDir() != ui.IsDir) 1301 if (item.IsDir() != ui.IsDir)
@@ -1105,15 +1316,15 @@ static HRESULT Update2(
1105 complexity += ui.Size; 1316 complexity += ui.Size;
1106 complexity += kLocalHeaderSize; 1317 complexity += kLocalHeaderSize;
1107 mtProgressMixerSpec->Mixer2->SetProgressOffset_NoLock(complexity); 1318 mtProgressMixerSpec->Mixer2->SetProgressOffset_NoLock(complexity);
1108 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 1319 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
1109 memRef2.Skip = true; 1320 memRef2.Skip = true;
1110 continue; 1321 continue;
1111 } 1322 }
1112 RINOK(res); 1323 RINOK(res)
1113 if (!fileInStream) 1324 if (!fileInStream)
1114 return E_INVALIDARG; 1325 return E_INVALIDARG;
1115 UpdatePropsFromStream(updateOptions, ui, fileInStream, updateCallback, totalComplexity); 1326 UpdatePropsFromStream(updateOptions, ui, fileInStream, updateCallback, totalComplexity);
1116 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 1327 RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
1117 } 1328 }
1118 1329
1119 UInt32 k; 1330 UInt32 k;
@@ -1151,6 +1362,7 @@ static HRESULT Update2(
1151 threadInfo.OutSeqMode = outSeqMode; 1362 threadInfo.OutSeqMode = outSeqMode;
1152 threadInfo.FileTime = ui.Time; // FileTime is used for ZipCrypto only in seqMode 1363 threadInfo.FileTime = ui.Time; // FileTime is used for ZipCrypto only in seqMode
1153 threadInfo.ExpectedDataSize = ui.Size; 1364 threadInfo.ExpectedDataSize = ui.Size;
1365 threadInfo.ExpectedDataSize_IsConfirmed = ui.Size_WasSetFromStream;
1154 1366
1155 threadInfo.CompressEvent.Set(); 1367 threadInfo.CompressEvent.Set();
1156 1368
@@ -1175,7 +1387,7 @@ static HRESULT Update2(
1175 if (!ui.NewProps || !ui.NewData) 1387 if (!ui.NewProps || !ui.NewData)
1176 { 1388 {
1177 itemEx = inputItems[(unsigned)ui.IndexInArc]; 1389 itemEx = inputItems[(unsigned)ui.IndexInArc];
1178 if (inArchive->ReadLocalItemAfterCdItemFull(itemEx) != S_OK) 1390 if (inArchive->Read_LocalItem_After_CdItem_Full(itemEx) != S_OK)
1179 return E_NOTIMPL; 1391 return E_NOTIMPL;
1180 (CItem &)item = itemEx; 1392 (CItem &)item = itemEx;
1181 } 1393 }
@@ -1187,7 +1399,7 @@ static HRESULT Update2(
1187 1399
1188 if (isDir) 1400 if (isDir)
1189 { 1401 {
1190 WriteDirHeader(archive, &options, ui, item); 1402 RINOK(WriteDirHeader(archive, &options, ui, item))
1191 } 1403 }
1192 else 1404 else
1193 { 1405 {
@@ -1206,12 +1418,21 @@ static HRESULT Update2(
1206 1418
1207 SetItemInfoFromCompressingResult(memRef.CompressingResult, 1419 SetItemInfoFromCompressingResult(memRef.CompressingResult,
1208 options.IsRealAesMode(), options.AesKeyMode, item); 1420 options.IsRealAesMode(), options.AesKeyMode, item);
1421 RINOK(archive.ClearRestriction())
1209 archive.WriteLocalHeader(item); 1422 archive.WriteLocalHeader(item);
1210 // RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 1423 // RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK));
1211 CMyComPtr<ISequentialOutStream> outStream; 1424 CMyComPtr<ISequentialOutStream> outStream;
1212 archive.CreateStreamForCopying(outStream); 1425 archive.CreateStreamForCopying(outStream);
1213 memRef.WriteToStream(memManager.GetBlockSize(), outStream); 1426 memRef.WriteToStream(memManager.GetBlockSize(), outStream);
1214 archive.MoveCurPos(item.PackSize); 1427 // v23: we fixed the bug: we need to write descriptor also
1428 if (item.HasDescriptor())
1429 {
1430 /* that function doesn't rewrite local header, if item.HasDescriptor().
1431 it just writes descriptor */
1432 archive.WriteLocalHeader_Replace(item);
1433 }
1434 else
1435 archive.MoveCurPos(item.PackSize);
1215 memRef.FreeOpt(&memManager); 1436 memRef.FreeOpt(&memManager);
1216 /* 1437 /*
1217 if (reportArcProp) 1438 if (reportArcProp)
@@ -1237,7 +1458,7 @@ static HRESULT Update2(
1237 RINOK(compressor.Set_Pre_CompressionResult( 1458 RINOK(compressor.Set_Pre_CompressionResult(
1238 memRef.InSeqMode, outSeqMode, 1459 memRef.InSeqMode, outSeqMode,
1239 ui.Size, 1460 ui.Size,
1240 compressingResult)); 1461 compressingResult))
1241 1462
1242 memRef.PreDescriptorMode = compressingResult.DescriptorMode; 1463 memRef.PreDescriptorMode = compressingResult.DescriptorMode;
1243 SetFileHeader(options, ui, compressingResult.DescriptorMode, item); 1464 SetFileHeader(options, ui, compressingResult.DescriptorMode, item);
@@ -1245,6 +1466,7 @@ static HRESULT Update2(
1245 SetItemInfoFromCompressingResult(compressingResult, options.IsRealAesMode(), options.AesKeyMode, item); 1466 SetItemInfoFromCompressingResult(compressingResult, options.IsRealAesMode(), options.AesKeyMode, item);
1246 1467
1247 // file Size can be 64-bit !!! 1468 // file Size can be 64-bit !!!
1469 RINOK(archive.SetRestrictionFromCurrent())
1248 archive.WriteLocalHeader(item); 1470 archive.WriteLocalHeader(item);
1249 } 1471 }
1250 1472
@@ -1270,7 +1492,7 @@ static HRESULT Update2(
1270 CThreadInfo &threadInfo = threads.Threads[(unsigned)ti]; 1492 CThreadInfo &threadInfo = threads.Threads[(unsigned)ti];
1271 threadInfo.InStream.Release(); 1493 threadInfo.InStream.Release();
1272 threadInfo.IsFree = true; 1494 threadInfo.IsFree = true;
1273 RINOK(threadInfo.Result); 1495 RINOK(threadInfo.Result)
1274 1496
1275 unsigned t = 0; 1497 unsigned t = 0;
1276 1498
@@ -1293,7 +1515,7 @@ static HRESULT Update2(
1293 if (memRef.PreDescriptorMode != threadInfo.CompressingResult.DescriptorMode) 1515 if (memRef.PreDescriptorMode != threadInfo.CompressingResult.DescriptorMode)
1294 return E_FAIL; 1516 return E_FAIL;
1295 1517
1296 RINOK(threadInfo.OutStreamSpec->WriteToRealStream()); 1518 RINOK(threadInfo.OutStreamSpec->WriteToRealStream())
1297 threadInfo.OutStreamSpec->ReleaseOutStream(); 1519 threadInfo.OutStreamSpec->ReleaseOutStream();
1298 SetFileHeader(options, ui, threadInfo.CompressingResult.DescriptorMode, item); 1520 SetFileHeader(options, ui, threadInfo.CompressingResult.DescriptorMode, item);
1299 SetItemInfoFromCompressingResult(threadInfo.CompressingResult, 1521 SetItemInfoFromCompressingResult(threadInfo.CompressingResult,
@@ -1324,7 +1546,7 @@ static HRESULT Update2(
1324 } 1546 }
1325 else 1547 else
1326 { 1548 {
1327 RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity)); 1549 RINOK(UpdateItemOldData(archive, inArchive, itemEx, ui, item, progress, opCallback, complexity))
1328 } 1550 }
1329 1551
1330 items.Add(item); 1552 items.Add(item);
@@ -1333,9 +1555,9 @@ static HRESULT Update2(
1333 itemIndex++; 1555 itemIndex++;
1334 } 1556 }
1335 1557
1336 RINOK(mtCompressProgressMixer.SetRatioInfo(0, NULL, NULL)); 1558 RINOK(mtCompressProgressMixer.SetRatioInfo(0, NULL, NULL))
1337 1559
1338 archive.WriteCentralDir(items, comment); 1560 RINOK(archive.WriteCentralDir(items, comment))
1339 1561
1340 /* 1562 /*
1341 if (reportArcProp) 1563 if (reportArcProp)
@@ -1351,15 +1573,61 @@ static HRESULT Update2(
1351 #endif 1573 #endif
1352} 1574}
1353 1575
1576/*
1577// we need CSeekOutStream, if we need Seek(0, STREAM_SEEK_CUR) for seqential stream
1578Z7_CLASS_IMP_COM_1(
1579 CSeekOutStream
1580 , IOutStream
1581)
1582 Z7_IFACE_COM7_IMP(ISequentialOutStream)
1583
1584 CMyComPtr<ISequentialOutStream> _seqStream;
1585 UInt64 _size;
1586public:
1587 void Init(ISequentialOutStream *seqStream)
1588 {
1589 _size = 0;
1590 _seqStream = seqStream;
1591 }
1592};
1593
1594Z7_COM7F_IMF(CSeekOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
1595{
1596 UInt32 realProcessedSize;
1597 const HRESULT result = _seqStream->Write(data, size, &realProcessedSize);
1598 _size += realProcessedSize;
1599 if (processedSize)
1600 *processedSize = realProcessedSize;
1601 return result;
1602}
1603
1604Z7_COM7F_IMF(CSeekOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
1605{
1606 if (seekOrigin != STREAM_SEEK_CUR || offset != 0)
1607 return E_NOTIMPL;
1608 if (newPosition)
1609 *newPosition = (UInt64)_size;
1610 return S_OK;
1611}
1612
1613Z7_COM7F_IMF(CSeekOutStream::SetSize(UInt64 newSize))
1614{
1615 UNUSED_VAR(newSize)
1616 return E_NOTIMPL;
1617}
1618*/
1354 1619
1355static const size_t kCacheBlockSize = (1 << 20); 1620static const size_t kCacheBlockSize = (1 << 20);
1356static const size_t kCacheSize = (kCacheBlockSize << 2); 1621static const size_t kCacheSize = (kCacheBlockSize << 2);
1357static const size_t kCacheMask = (kCacheSize - 1); 1622static const size_t kCacheMask = (kCacheSize - 1);
1358 1623
1359class CCacheOutStream: 1624Z7_CLASS_IMP_NOQIB_2(
1360 public IOutStream, 1625 CCacheOutStream
1361 public CMyUnknownImp 1626 , IOutStream
1362{ 1627 , IStreamSetRestriction
1628)
1629 Z7_IFACE_COM7_IMP(ISequentialOutStream)
1630
1363 CMyComPtr<IOutStream> _stream; 1631 CMyComPtr<IOutStream> _stream;
1364 CMyComPtr<ISequentialOutStream> _seqStream; 1632 CMyComPtr<ISequentialOutStream> _seqStream;
1365 Byte *_cache; 1633 Byte *_cache;
@@ -1369,26 +1637,29 @@ class CCacheOutStream:
1369 UInt64 _phySize; // <= _virtSize 1637 UInt64 _phySize; // <= _virtSize
1370 UInt64 _cachedPos; // (_cachedPos + _cachedSize) <= _virtSize 1638 UInt64 _cachedPos; // (_cachedPos + _cachedSize) <= _virtSize
1371 size_t _cachedSize; 1639 size_t _cachedSize;
1640 HRESULT _hres;
1641
1642 UInt64 _restrict_begin;
1643 UInt64 _restrict_end;
1644 UInt64 _restrict_phy; // begin
1645 CMyComPtr<IStreamSetRestriction> _setRestriction;
1372 1646
1373 HRESULT MyWrite(size_t size); 1647 HRESULT MyWrite(size_t size);
1374 HRESULT MyWriteBlock() 1648 HRESULT MyWriteBlock()
1375 { 1649 {
1376 return MyWrite(kCacheBlockSize - ((size_t)_cachedPos & (kCacheBlockSize - 1))); 1650 return MyWrite(kCacheBlockSize - ((size_t)_cachedPos & (kCacheBlockSize - 1)));
1377 } 1651 }
1652 HRESULT WriteNonRestrictedBlocks();
1378 HRESULT FlushCache(); 1653 HRESULT FlushCache();
1379public: 1654public:
1380 CCacheOutStream(): _cache(NULL) {} 1655 CCacheOutStream(): _cache(NULL) {}
1381 ~CCacheOutStream(); 1656 ~CCacheOutStream();
1382 bool Allocate(); 1657 bool Allocate();
1383 HRESULT Init(ISequentialOutStream *seqStream, IOutStream *stream); 1658 HRESULT Init(ISequentialOutStream *seqStream, IOutStream *stream, IStreamSetRestriction *setRestriction);
1384 1659 HRESULT FinalFlush();
1385 MY_UNKNOWN_IMP
1386
1387 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
1388 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
1389 STDMETHOD(SetSize)(UInt64 newSize);
1390}; 1660};
1391 1661
1662
1392bool CCacheOutStream::Allocate() 1663bool CCacheOutStream::Allocate()
1393{ 1664{
1394 if (!_cache) 1665 if (!_cache)
@@ -1396,40 +1667,59 @@ bool CCacheOutStream::Allocate()
1396 return (_cache != NULL); 1667 return (_cache != NULL);
1397} 1668}
1398 1669
1399HRESULT CCacheOutStream::Init(ISequentialOutStream *seqStream, IOutStream *stream) 1670HRESULT CCacheOutStream::Init(ISequentialOutStream *seqStream, IOutStream *stream, IStreamSetRestriction *setRestriction)
1400{ 1671{
1672 _cachedPos = 0;
1673 _cachedSize = 0;
1674 _hres = S_OK;
1675 _restrict_begin = 0;
1676 _restrict_end = 0;
1677 _restrict_phy = 0;
1401 _virtPos = 0; 1678 _virtPos = 0;
1402 _phyPos = 0;
1403 _virtSize = 0; 1679 _virtSize = 0;
1404 _seqStream = seqStream; 1680 _seqStream = seqStream;
1405 _stream = stream; 1681 _stream = stream;
1682 _setRestriction = setRestriction;
1406 if (_stream) 1683 if (_stream)
1407 { 1684 {
1408 RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &_virtPos)); 1685 RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &_virtPos))
1409 RINOK(_stream->Seek(0, STREAM_SEEK_END, &_virtSize)); 1686 RINOK(_stream->Seek(0, STREAM_SEEK_END, &_virtSize))
1410 RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, &_virtPos)); 1687 RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, &_virtPos))
1411 } 1688 }
1412 _phyPos = _virtPos; 1689 _phyPos = _virtPos;
1413 _phySize = _virtSize; 1690 _phySize = _virtSize;
1414 _cachedPos = 0;
1415 _cachedSize = 0;
1416 return S_OK; 1691 return S_OK;
1417} 1692}
1418 1693
1694
1695/* it writes up to (size) bytes from cache.
1696 (size > _cachedSize) is allowed */
1697
1419HRESULT CCacheOutStream::MyWrite(size_t size) 1698HRESULT CCacheOutStream::MyWrite(size_t size)
1420{ 1699{
1700 PRF(printf("\n-- CCacheOutStream::MyWrite %u\n", (unsigned)size));
1701 if (_hres != S_OK)
1702 return _hres;
1421 while (size != 0 && _cachedSize != 0) 1703 while (size != 0 && _cachedSize != 0)
1422 { 1704 {
1423 if (_phyPos != _cachedPos) 1705 if (_phyPos != _cachedPos)
1424 { 1706 {
1425 if (!_stream) 1707 if (!_stream)
1426 return E_FAIL; 1708 return E_FAIL;
1427 RINOK(_stream->Seek((Int64)_cachedPos, STREAM_SEEK_SET, &_phyPos)); 1709 _hres = _stream->Seek((Int64)_cachedPos, STREAM_SEEK_SET, &_phyPos);
1710 RINOK(_hres)
1711 if (_phyPos != _cachedPos)
1712 {
1713 _hres = E_FAIL;
1714 return _hres;
1715 }
1428 } 1716 }
1429 size_t pos = (size_t)_cachedPos & kCacheMask; 1717 const size_t pos = (size_t)_cachedPos & kCacheMask;
1430 size_t curSize = MyMin(kCacheSize - pos, _cachedSize); 1718 size_t curSize = kCacheSize - pos;
1719 curSize = MyMin(curSize, _cachedSize);
1431 curSize = MyMin(curSize, size); 1720 curSize = MyMin(curSize, size);
1432 RINOK(WriteStream(_seqStream, _cache + pos, curSize)); 1721 _hres = WriteStream(_seqStream, _cache + pos, curSize);
1722 RINOK(_hres)
1433 _phyPos += curSize; 1723 _phyPos += curSize;
1434 if (_phySize < _phyPos) 1724 if (_phySize < _phyPos)
1435 _phySize = _phyPos; 1725 _phySize = _phyPos;
@@ -1437,112 +1727,131 @@ HRESULT CCacheOutStream::MyWrite(size_t size)
1437 _cachedSize -= curSize; 1727 _cachedSize -= curSize;
1438 size -= curSize; 1728 size -= curSize;
1439 } 1729 }
1730
1731 if (_setRestriction)
1732 if (_restrict_begin == _restrict_end || _cachedPos <= _restrict_begin)
1733 if (_restrict_phy < _cachedPos)
1734 {
1735 _restrict_phy = _cachedPos;
1736 return _setRestriction->SetRestriction(_cachedPos, (UInt64)(Int64)-1);
1737 }
1440 return S_OK; 1738 return S_OK;
1441} 1739}
1442 1740
1741
1742HRESULT CCacheOutStream::WriteNonRestrictedBlocks()
1743{
1744 for (;;)
1745 {
1746 const size_t size = kCacheBlockSize - ((size_t)_cachedPos & (kCacheBlockSize - 1));
1747 if (_cachedSize < size)
1748 break;
1749 if (_restrict_begin != _restrict_end && _cachedPos + size > _restrict_begin)
1750 break;
1751 RINOK(MyWrite(size))
1752 }
1753 return S_OK;
1754}
1755
1756
1443HRESULT CCacheOutStream::FlushCache() 1757HRESULT CCacheOutStream::FlushCache()
1444{ 1758{
1445 return MyWrite(_cachedSize); 1759 return MyWrite(_cachedSize);
1446} 1760}
1447 1761
1448CCacheOutStream::~CCacheOutStream() 1762HRESULT CCacheOutStream::FinalFlush()
1449{ 1763{
1450 FlushCache(); 1764 _restrict_begin = 0;
1451 if (_stream) 1765 _restrict_end = 0;
1766 RINOK(FlushCache())
1767 if (_stream && _hres == S_OK)
1452 { 1768 {
1453 if (_virtSize != _phySize) 1769 if (_virtSize != _phySize)
1454 _stream->SetSize(_virtSize); 1770 {
1771 // it's unexpected
1772 RINOK(_stream->SetSize(_virtSize))
1773 }
1455 if (_virtPos != _phyPos) 1774 if (_virtPos != _phyPos)
1456 _stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, NULL); 1775 {
1776 RINOK(_stream->Seek((Int64)_virtPos, STREAM_SEEK_SET, NULL))
1777 }
1457 } 1778 }
1779 return S_OK;
1780}
1781
1782
1783CCacheOutStream::~CCacheOutStream()
1784{
1458 ::MidFree(_cache); 1785 ::MidFree(_cache);
1459} 1786}
1460 1787
1461STDMETHODIMP CCacheOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 1788
1789Z7_COM7F_IMF(CCacheOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
1462{ 1790{
1791 PRF(printf("\n-- CCacheOutStream::Write %u\n", (unsigned)size));
1792
1463 if (processedSize) 1793 if (processedSize)
1464 *processedSize = 0; 1794 *processedSize = 0;
1465 if (size == 0) 1795 if (size == 0)
1466 return S_OK; 1796 return S_OK;
1797 if (_hres != S_OK)
1798 return _hres;
1467 1799
1468 UInt64 zerosStart = _virtPos;
1469 if (_cachedSize != 0) 1800 if (_cachedSize != 0)
1801 if (_virtPos < _cachedPos ||
1802 _virtPos > _cachedPos + _cachedSize)
1470 { 1803 {
1471 if (_virtPos < _cachedPos) 1804 RINOK(FlushCache())
1472 {
1473 RINOK(FlushCache());
1474 }
1475 else
1476 {
1477 UInt64 cachedEnd = _cachedPos + _cachedSize;
1478 if (cachedEnd < _virtPos)
1479 {
1480 if (cachedEnd < _phySize)
1481 {
1482 RINOK(FlushCache());
1483 }
1484 else
1485 zerosStart = cachedEnd;
1486 }
1487 }
1488 } 1805 }
1489 1806
1490 if (_cachedSize == 0 && _phySize < _virtPos) 1807 // ---------- Writing data to cache ----------
1491 _cachedPos = zerosStart = _phySize;
1492
1493 if (zerosStart != _virtPos)
1494 {
1495 // write zeros to [cachedEnd ... _virtPos)
1496
1497 for (;;)
1498 {
1499 UInt64 cachedEnd = _cachedPos + _cachedSize;
1500 size_t endPos = (size_t)cachedEnd & kCacheMask;
1501 size_t curSize = kCacheSize - endPos;
1502 if (curSize > _virtPos - cachedEnd)
1503 curSize = (size_t)(_virtPos - cachedEnd);
1504 if (curSize == 0)
1505 break;
1506 while (curSize > (kCacheSize - _cachedSize))
1507 {
1508 RINOK(MyWriteBlock());
1509 }
1510 memset(_cache + endPos, 0, curSize);
1511 _cachedSize += curSize;
1512 }
1513 }
1514 1808
1515 if (_cachedSize == 0) 1809 if (_cachedSize == 0)
1516 _cachedPos = _virtPos; 1810 _cachedPos = _virtPos;
1517 1811
1518 size_t pos = (size_t)_virtPos & kCacheMask; 1812 const size_t pos = (size_t)_virtPos & kCacheMask;
1519 size = (UInt32)MyMin((size_t)size, kCacheSize - pos); 1813 size = (UInt32)MyMin((size_t)size, kCacheSize - pos);
1520 UInt64 cachedEnd = _cachedPos + _cachedSize; 1814 const UInt64 cachedEnd = _cachedPos + _cachedSize;
1521 if (_virtPos != cachedEnd) // _virtPos < cachedEnd 1815
1816 // (_virtPos >= _cachedPos) (_virtPos <= cachedEnd)
1817
1818 if (_virtPos != cachedEnd)
1819 {
1820 // _virtPos < cachedEnd
1821 // we rewrite only existing data in cache. So _cachedSize will be not changed
1522 size = (UInt32)MyMin((size_t)size, (size_t)(cachedEnd - _virtPos)); 1822 size = (UInt32)MyMin((size_t)size, (size_t)(cachedEnd - _virtPos));
1823 }
1523 else 1824 else
1524 { 1825 {
1525 // _virtPos == cachedEnd 1826 // _virtPos == cachedEnd
1827 // so we need to add new data to the end of cache
1526 if (_cachedSize == kCacheSize) 1828 if (_cachedSize == kCacheSize)
1527 { 1829 {
1528 RINOK(MyWriteBlock()); 1830 // cache is full. So we flush part of cache
1831 RINOK(MyWriteBlock())
1529 } 1832 }
1530 size_t startPos = (size_t)_cachedPos & kCacheMask; 1833 // _cachedSize != kCacheSize
1834 // so we have some space for new data in cache
1835 const size_t startPos = (size_t)_cachedPos & kCacheMask;
1836 // we don't allow new data to overwrite old start data in cache.
1531 if (startPos > pos) 1837 if (startPos > pos)
1532 size = (UInt32)MyMin((size_t)size, (size_t)(startPos - pos)); 1838 size = (UInt32)MyMin((size_t)size, (size_t)(startPos - pos));
1533 _cachedSize += size; 1839 _cachedSize += size;
1534 } 1840 }
1841
1535 memcpy(_cache + pos, data, size); 1842 memcpy(_cache + pos, data, size);
1536 if (processedSize) 1843 if (processedSize)
1537 *processedSize = size; 1844 *processedSize = size;
1538 _virtPos += size; 1845 _virtPos += size;
1539 if (_virtSize < _virtPos) 1846 if (_virtSize < _virtPos)
1540 _virtSize = _virtPos; 1847 _virtSize = _virtPos;
1541 return S_OK; 1848 return WriteNonRestrictedBlocks();
1542} 1849}
1543 1850
1544STDMETHODIMP CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 1851
1852Z7_COM7F_IMF(CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
1545{ 1853{
1854 PRF(printf("\n-- CCacheOutStream::Seek seekOrigin=%d Seek =%u\n", seekOrigin, (unsigned)offset));
1546 switch (seekOrigin) 1855 switch (seekOrigin)
1547 { 1856 {
1548 case STREAM_SEEK_SET: break; 1857 case STREAM_SEEK_SET: break;
@@ -1558,27 +1867,58 @@ STDMETHODIMP CCacheOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP
1558 return S_OK; 1867 return S_OK;
1559} 1868}
1560 1869
1561STDMETHODIMP CCacheOutStream::SetSize(UInt64 newSize) 1870
1871Z7_COM7F_IMF(CCacheOutStream::SetSize(UInt64 newSize))
1562{ 1872{
1873 if (_hres != S_OK)
1874 return _hres;
1563 _virtSize = newSize; 1875 _virtSize = newSize;
1564 if (newSize < _phySize) 1876
1565 {
1566 if (!_stream)
1567 return E_NOTIMPL;
1568 RINOK(_stream->SetSize(newSize));
1569 _phySize = newSize;
1570 }
1571 if (newSize <= _cachedPos) 1877 if (newSize <= _cachedPos)
1572 { 1878 {
1573 _cachedSize = 0; 1879 _cachedSize = 0;
1574 _cachedPos = newSize; 1880 _cachedPos = newSize;
1575 } 1881 }
1576 if (newSize < _cachedPos + _cachedSize) 1882 else
1577 _cachedSize = (size_t)(newSize - _cachedPos); 1883 {
1884 // newSize > _cachedPos
1885 const UInt64 offset = newSize - _cachedPos;
1886 if (offset <= _cachedSize)
1887 {
1888 _cachedSize = (size_t)offset;
1889 if (_phySize <= newSize)
1890 return S_OK;
1891 }
1892 else
1893 {
1894 // newSize > _cachedPos + _cachedSize
1895 // So we flush cache
1896 RINOK(FlushCache())
1897 }
1898 }
1899
1900 if (newSize != _phySize)
1901 {
1902 if (!_stream)
1903 return E_NOTIMPL;
1904 _hres = _stream->SetSize(newSize);
1905 RINOK(_hres)
1906 _phySize = newSize;
1907 }
1578 return S_OK; 1908 return S_OK;
1579} 1909}
1580 1910
1581 1911
1912Z7_COM7F_IMF(CCacheOutStream::SetRestriction(UInt64 begin, UInt64 end))
1913{
1914 PRF(printf("\n============ CCacheOutStream::SetRestriction %u, %u\n", (unsigned)begin, (unsigned)end));
1915 _restrict_begin = begin;
1916 _restrict_end = end;
1917 return WriteNonRestrictedBlocks();
1918}
1919
1920
1921
1582HRESULT Update( 1922HRESULT Update(
1583 DECL_EXTERNAL_CODECS_LOC_VARS 1923 DECL_EXTERNAL_CODECS_LOC_VARS
1584 const CObjectVector<CItemEx> &inputItems, 1924 const CObjectVector<CItemEx> &inputItems,
@@ -1589,21 +1929,36 @@ HRESULT Update(
1589 const CCompressionMethodMode &compressionMethodMode, 1929 const CCompressionMethodMode &compressionMethodMode,
1590 IArchiveUpdateCallback *updateCallback) 1930 IArchiveUpdateCallback *updateCallback)
1591{ 1931{
1932 /*
1933 // it was tested before
1592 if (inArchive) 1934 if (inArchive)
1593 { 1935 {
1594 if (!inArchive->CanUpdate()) 1936 if (!inArchive->CanUpdate())
1595 return E_NOTIMPL; 1937 return E_NOTIMPL;
1596 } 1938 }
1939 */
1597 1940
1941 CMyComPtr<IStreamSetRestriction> setRestriction;
1942 seqOutStream->QueryInterface(IID_IStreamSetRestriction, (void **)&setRestriction);
1943 if (setRestriction)
1944 {
1945 RINOK(setRestriction->SetRestriction(0, 0))
1946 }
1598 1947
1599 CMyComPtr<IOutStream> outStream; 1948 CMyComPtr<IOutStream> outStream;
1949 CCacheOutStream *cacheStream;
1600 bool outSeqMode; 1950 bool outSeqMode;
1951
1601 { 1952 {
1602 CMyComPtr<IOutStream> outStreamReal; 1953 CMyComPtr<IOutStream> outStreamReal;
1603 seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStreamReal); 1954
1604 if (!outStreamReal) 1955 if (!compressionMethodMode.Force_SeqOutMode)
1605 { 1956 {
1606 // return E_NOTIMPL; 1957 seqOutStream->QueryInterface(IID_IOutStream, (void **)&outStreamReal);
1958 /*
1959 if (!outStreamReal)
1960 return E_NOTIMPL;
1961 */
1607 } 1962 }
1608 1963
1609 if (inArchive) 1964 if (inArchive)
@@ -1611,42 +1966,62 @@ HRESULT Update(
1611 if (!inArchive->IsMultiVol && inArchive->ArcInfo.Base > 0 && !removeSfx) 1966 if (!inArchive->IsMultiVol && inArchive->ArcInfo.Base > 0 && !removeSfx)
1612 { 1967 {
1613 IInStream *baseStream = inArchive->GetBaseStream(); 1968 IInStream *baseStream = inArchive->GetBaseStream();
1614 RINOK(baseStream->Seek(0, STREAM_SEEK_SET, NULL)); 1969 RINOK(InStream_SeekToBegin(baseStream))
1615 RINOK(NCompress::CopyStream_ExactSize(baseStream, seqOutStream, (UInt64)inArchive->ArcInfo.Base, NULL)); 1970 RINOK(NCompress::CopyStream_ExactSize(baseStream, seqOutStream, (UInt64)inArchive->ArcInfo.Base, NULL))
1616 } 1971 }
1617 } 1972 }
1618 1973
1619 CCacheOutStream *cacheStream = new CCacheOutStream(); 1974 // bool use_cacheStream = true;
1620 outStream = cacheStream; 1975 // if (use_cacheStream)
1621 if (!cacheStream->Allocate()) 1976 {
1622 return E_OUTOFMEMORY; 1977 cacheStream = new CCacheOutStream();
1623 RINOK(cacheStream->Init(seqOutStream, outStreamReal)); 1978 outStream = cacheStream;
1979 if (!cacheStream->Allocate())
1980 return E_OUTOFMEMORY;
1981 RINOK(cacheStream->Init(seqOutStream, outStreamReal, setRestriction))
1982 setRestriction.Release();
1983 setRestriction = cacheStream;
1984 }
1985 /*
1986 else if (!outStreamReal)
1987 {
1988 CSeekOutStream *seekOutStream = new CSeekOutStream();
1989 outStream = seekOutStream;
1990 seekOutStream->Init(seqOutStream);
1991 }
1992 else
1993 outStream = outStreamReal;
1994 */
1624 outSeqMode = (outStreamReal == NULL); 1995 outSeqMode = (outStreamReal == NULL);
1625 } 1996 }
1626 1997
1627 COutArchive outArchive; 1998 COutArchive outArchive;
1628 RINOK(outArchive.Create(outStream)); 1999 outArchive.SetRestriction = setRestriction;
2000
2001 RINOK(outArchive.Create(outStream))
1629 2002
1630 if (inArchive) 2003 if (inArchive)
1631 { 2004 {
1632 if (!inArchive->IsMultiVol && (Int64)inArchive->ArcInfo.MarkerPos2 > inArchive->ArcInfo.Base) 2005 if (!inArchive->IsMultiVol && (Int64)inArchive->ArcInfo.MarkerPos2 > inArchive->ArcInfo.Base)
1633 { 2006 {
1634 IInStream *baseStream = inArchive->GetBaseStream(); 2007 IInStream *baseStream = inArchive->GetBaseStream();
1635 RINOK(baseStream->Seek(inArchive->ArcInfo.Base, STREAM_SEEK_SET, NULL)); 2008 RINOK(InStream_SeekSet(baseStream, (UInt64)inArchive->ArcInfo.Base))
1636 const UInt64 embStubSize = (UInt64)((Int64)inArchive->ArcInfo.MarkerPos2 - inArchive->ArcInfo.Base); 2009 const UInt64 embStubSize = (UInt64)((Int64)inArchive->ArcInfo.MarkerPos2 - inArchive->ArcInfo.Base);
1637 RINOK(NCompress::CopyStream_ExactSize(baseStream, outStream, embStubSize, NULL)); 2010 RINOK(NCompress::CopyStream_ExactSize(baseStream, outStream, embStubSize, NULL))
1638 outArchive.MoveCurPos(embStubSize); 2011 outArchive.MoveCurPos(embStubSize);
1639 } 2012 }
1640 } 2013 }
1641 2014
1642 return Update2( 2015 RINOK (Update2(
1643 EXTERNAL_CODECS_LOC_VARS 2016 EXTERNAL_CODECS_LOC_VARS
1644 outArchive, inArchive, 2017 outArchive, inArchive,
1645 inputItems, updateItems, 2018 inputItems, updateItems,
1646 updateOptions, 2019 updateOptions,
1647 compressionMethodMode, outSeqMode, 2020 compressionMethodMode, outSeqMode,
1648 inArchive ? &inArchive->ArcInfo.Comment : NULL, 2021 inArchive ? &inArchive->ArcInfo.Comment : NULL,
1649 updateCallback); 2022 updateCallback))
2023
2024 return cacheStream->FinalFlush();
1650} 2025}
1651 2026
1652}} 2027}}
diff --git a/CPP/7zip/Archive/Zip/ZipUpdate.h b/CPP/7zip/Archive/Zip/ZipUpdate.h
index d1e3534..13ecd9c 100644
--- a/CPP/7zip/Archive/Zip/ZipUpdate.h
+++ b/CPP/7zip/Archive/Zip/ZipUpdate.h
@@ -1,7 +1,7 @@
1// ZipUpdate.h 1// ZipUpdate.h
2 2
3#ifndef __ZIP_UPDATE_H 3#ifndef ZIP7_INC_ZIP_UPDATE_H
4#define __ZIP_UPDATE_H 4#define ZIP7_INC_ZIP_UPDATE_H
5 5
6#include "../../ICoder.h" 6#include "../../ICoder.h"
7#include "../IArchive.h" 7#include "../IArchive.h"
@@ -20,8 +20,8 @@ struct CUpdateRange
20 UInt64 Position; 20 UInt64 Position;
21 UInt64 Size; 21 UInt64 Size;
22 22
23 // CUpdateRange() {}; 23 // CUpdateRange() {}
24 CUpdateRange(UInt64 position, UInt64 size): Position(position), Size(size) {}; 24 CUpdateRange(UInt64 position, UInt64 size): Position(position), Size(size) {}
25}; 25};
26*/ 26*/
27 27
@@ -34,6 +34,7 @@ struct CUpdateItem
34 bool Write_UnixTime; 34 bool Write_UnixTime;
35 // bool Write_UnixTime_ATime; 35 // bool Write_UnixTime_ATime;
36 bool IsUtf8; 36 bool IsUtf8;
37 bool Size_WasSetFromStream;
37 // bool IsAltStream; 38 // bool IsAltStream;
38 int IndexInArc; 39 int IndexInArc;
39 unsigned IndexInClient; 40 unsigned IndexInClient;
@@ -57,6 +58,7 @@ struct CUpdateItem
57 Write_UnixTime = false; 58 Write_UnixTime = false;
58 59
59 IsUtf8 = false; 60 IsUtf8 = false;
61 Size_WasSetFromStream = false;
60 // IsAltStream = false; 62 // IsAltStream = false;
61 Time = 0; 63 Time = 0;
62 Size = 0; 64 Size = 0;
@@ -74,6 +76,7 @@ struct CUpdateItem
74 Write_NtfsTime(false), 76 Write_NtfsTime(false),
75 Write_UnixTime(false), 77 Write_UnixTime(false),
76 IsUtf8(false), 78 IsUtf8(false),
79 Size_WasSetFromStream(false),
77 // IsAltStream(false), 80 // IsAltStream(false),
78 Time(0), 81 Time(0),
79 Size(0) 82 Size(0)
diff --git a/CPP/7zip/Bundles/Alone/Alone.dsp b/CPP/7zip/Bundles/Alone/Alone.dsp
index 84d3cdf..65c81c4 100644
--- a/CPP/7zip/Bundles/Alone/Alone.dsp
+++ b/CPP/7zip/Bundles/Alone/Alone.dsp
@@ -44,7 +44,7 @@ RSC=rc.exe
44# PROP Ignore_Export_Lib 0 44# PROP Ignore_Export_Lib 0
45# PROP Target_Dir "" 45# PROP Target_Dir ""
46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c 46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
47# 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 47# 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
48# ADD BASE RSC /l 0x419 /d "NDEBUG" 48# ADD BASE RSC /l 0x419 /d "NDEBUG"
49# ADD RSC /l 0x419 /d "NDEBUG" 49# ADD RSC /l 0x419 /d "NDEBUG"
50BSC32=bscmake.exe 50BSC32=bscmake.exe
@@ -69,7 +69,7 @@ LINK32=link.exe
69# PROP Ignore_Export_Lib 0 69# PROP Ignore_Export_Lib 0
70# PROP Target_Dir "" 70# PROP Target_Dir ""
71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c 71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
72# 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 72# 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
73# SUBTRACT CPP /WX 73# SUBTRACT CPP /WX
74# ADD BASE RSC /l 0x419 /d "_DEBUG" 74# ADD BASE RSC /l 0x419 /d "_DEBUG"
75# ADD RSC /l 0x419 /d "_DEBUG" 75# ADD RSC /l 0x419 /d "_DEBUG"
@@ -94,8 +94,8 @@ LINK32=link.exe
94# PROP Intermediate_Dir "ReleaseU" 94# PROP Intermediate_Dir "ReleaseU"
95# PROP Ignore_Export_Lib 0 95# PROP Ignore_Export_Lib 0
96# PROP Target_Dir "" 96# PROP Target_Dir ""
97# 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 97# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /Yu"StdAfx.h" /FD /c
98# 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 98# 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
99# ADD BASE RSC /l 0x419 /d "NDEBUG" 99# ADD BASE RSC /l 0x419 /d "NDEBUG"
100# ADD RSC /l 0x419 /d "NDEBUG" 100# ADD RSC /l 0x419 /d "NDEBUG"
101BSC32=bscmake.exe 101BSC32=bscmake.exe
@@ -121,8 +121,8 @@ LINK32=link.exe
121# PROP Intermediate_Dir "DebugU" 121# PROP Intermediate_Dir "DebugU"
122# PROP Ignore_Export_Lib 0 122# PROP Ignore_Export_Lib 0
123# PROP Target_Dir "" 123# PROP Target_Dir ""
124# 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 124# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c
125# 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 125# 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
126# ADD BASE RSC /l 0x419 /d "_DEBUG" 126# ADD BASE RSC /l 0x419 /d "_DEBUG"
127# ADD RSC /l 0x419 /d "_DEBUG" 127# ADD RSC /l 0x419 /d "_DEBUG"
128BSC32=bscmake.exe 128BSC32=bscmake.exe
@@ -722,6 +722,14 @@ SOURCE=..\..\Common\MethodProps.h
722# End Source File 722# End Source File
723# Begin Source File 723# Begin Source File
724 724
725SOURCE=..\..\Common\MultiOutStream.cpp
726# End Source File
727# Begin Source File
728
729SOURCE=..\..\Common\MultiOutStream.h
730# End Source File
731# Begin Source File
732
725SOURCE=..\..\Common\OffsetStream.cpp 733SOURCE=..\..\Common\OffsetStream.cpp
726# End Source File 734# End Source File
727# Begin Source File 735# Begin Source File
@@ -2311,6 +2319,10 @@ SOURCE=..\..\..\..\C\7zVersion.h
2311# End Source File 2319# End Source File
2312# Begin Source File 2320# Begin Source File
2313 2321
2322SOURCE=..\..\..\..\C\7zWindows.h
2323# End Source File
2324# Begin Source File
2325
2314SOURCE=..\..\..\..\C\Aes.c 2326SOURCE=..\..\..\..\C\Aes.c
2315 2327
2316!IF "$(CFG)" == "Alone - Win32 Release" 2328!IF "$(CFG)" == "Alone - Win32 Release"
@@ -3163,6 +3175,34 @@ SOURCE=..\..\..\..\C\Sort.h
3163# End Source File 3175# End Source File
3164# Begin Source File 3176# Begin Source File
3165 3177
3178SOURCE=..\..\..\..\C\SwapBytes.c
3179
3180!IF "$(CFG)" == "Alone - Win32 Release"
3181
3182# ADD CPP /O2
3183# SUBTRACT CPP /YX /Yc /Yu
3184
3185!ELSEIF "$(CFG)" == "Alone - Win32 Debug"
3186
3187# SUBTRACT CPP /YX /Yc /Yu
3188
3189!ELSEIF "$(CFG)" == "Alone - Win32 ReleaseU"
3190
3191# SUBTRACT CPP /YX /Yc /Yu
3192
3193!ELSEIF "$(CFG)" == "Alone - Win32 DebugU"
3194
3195# SUBTRACT CPP /YX /Yc /Yu
3196
3197!ENDIF
3198
3199# End Source File
3200# Begin Source File
3201
3202SOURCE=..\..\..\..\C\SwapBytes.h
3203# End Source File
3204# Begin Source File
3205
3166SOURCE=..\..\..\..\C\Threads.c 3206SOURCE=..\..\..\..\C\Threads.c
3167 3207
3168!IF "$(CFG)" == "Alone - Win32 Release" 3208!IF "$(CFG)" == "Alone - Win32 Release"
diff --git a/CPP/7zip/Bundles/Alone/StdAfx.h b/CPP/7zip/Bundles/Alone/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Alone/StdAfx.h
+++ b/CPP/7zip/Bundles/Alone/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Alone/makefile b/CPP/7zip/Bundles/Alone/makefile
index cc4b29e..bad953a 100644
--- a/CPP/7zip/Bundles/Alone/makefile
+++ b/CPP/7zip/Bundles/Alone/makefile
@@ -56,6 +56,7 @@ WIN_OBJS = \
56 $O\MemBlocks.obj \ 56 $O\MemBlocks.obj \
57 $O\MethodId.obj \ 57 $O\MethodId.obj \
58 $O\MethodProps.obj \ 58 $O\MethodProps.obj \
59 $O\MultiOutStream.obj \
59 $O\OffsetStream.obj \ 60 $O\OffsetStream.obj \
60 $O\OutBuffer.obj \ 61 $O\OutBuffer.obj \
61 $O\OutMemStream.obj \ 62 $O\OutMemStream.obj \
@@ -209,6 +210,7 @@ C_OBJS = \
209 $O\Ppmd8Dec.obj \ 210 $O\Ppmd8Dec.obj \
210 $O\Ppmd8Enc.obj \ 211 $O\Ppmd8Enc.obj \
211 $O\Sort.obj \ 212 $O\Sort.obj \
213 $O\SwapBytes.obj \
212 $O\Threads.obj \ 214 $O\Threads.obj \
213 $O\Xz.obj \ 215 $O\Xz.obj \
214 $O\XzDec.obj \ 216 $O\XzDec.obj \
diff --git a/CPP/7zip/Bundles/Alone/makefile.gcc b/CPP/7zip/Bundles/Alone/makefile.gcc
index 20d6a86..cb7e828 100644
--- a/CPP/7zip/Bundles/Alone/makefile.gcc
+++ b/CPP/7zip/Bundles/Alone/makefile.gcc
@@ -24,7 +24,7 @@ endif
24 24
25ifdef ST_MODE 25ifdef ST_MODE
26 26
27LOCAL_FLAGS_ST = -D_7ZIP_ST 27LOCAL_FLAGS_ST = -DZ7_ST
28 28
29ifdef IS_MINGW 29ifdef IS_MINGW
30MT_OBJS = \ 30MT_OBJS = \
@@ -53,9 +53,9 @@ LOCAL_FLAGS_SYS =
53ifdef IS_MINGW 53ifdef IS_MINGW
54 54
55LOCAL_FLAGS_SYS = \ 55LOCAL_FLAGS_SYS = \
56 -D_7ZIP_LARGE_PAGES \ 56 -DZ7_LARGE_PAGES \
57 -DWIN_LONG_PATH \ 57 -DZ7_LONG_PATH \
58 -DSUPPORT_DEVICE_FILE \ 58 -DZ7_DEVICE_FILE \
59 59
60SYS_OBJS = \ 60SYS_OBJS = \
61 $O/FileSystem.o \ 61 $O/FileSystem.o \
@@ -164,6 +164,7 @@ WIN_OBJS = \
164 $O/LimitedStreams.o \ 164 $O/LimitedStreams.o \
165 $O/MethodId.o \ 165 $O/MethodId.o \
166 $O/MethodProps.o \ 166 $O/MethodProps.o \
167 $O/MultiOutStream.o \
167 $O/OffsetStream.o \ 168 $O/OffsetStream.o \
168 $O/OutBuffer.o \ 169 $O/OutBuffer.o \
169 $O/ProgressUtils.o \ 170 $O/ProgressUtils.o \
@@ -309,6 +310,7 @@ C_OBJS = \
309 $O/Ppmd8Dec.o \ 310 $O/Ppmd8Dec.o \
310 $O/Ppmd8Enc.o \ 311 $O/Ppmd8Enc.o \
311 $O/Sort.o \ 312 $O/Sort.o \
313 $O/SwapBytes.o \
312 $O/Xz.o \ 314 $O/Xz.o \
313 $O/XzDec.o \ 315 $O/XzDec.o \
314 $O/XzEnc.o \ 316 $O/XzEnc.o \
@@ -325,7 +327,7 @@ C_OBJS = \
325 $O/Sha1Opt.o \ 327 $O/Sha1Opt.o \
326 328
327OBJS = \ 329OBJS = \
328 $(LZMA_DEC_OPT_OBJS) \ 330 $(LZMA_DEC_OPT_OBJS) \
329 $(C_OBJS) \ 331 $(C_OBJS) \
330 $(MT_OBJS) \ 332 $(MT_OBJS) \
331 $(SYS_OBJS) \ 333 $(SYS_OBJS) \
diff --git a/CPP/7zip/Bundles/Alone2/StdAfx.h b/CPP/7zip/Bundles/Alone2/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Alone2/StdAfx.h
+++ b/CPP/7zip/Bundles/Alone2/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Alone2/makefile b/CPP/7zip/Bundles/Alone2/makefile
index 357e78e..4cb7718 100644
--- a/CPP/7zip/Bundles/Alone2/makefile
+++ b/CPP/7zip/Bundles/Alone2/makefile
@@ -1,7 +1,7 @@
1PROG = 7zz.exe 1PROG = 7zz.exe
2# USE_C_AES = 1 2# USE_C_AES = 1
3# USE_C_SHA = 1 3# USE_C_SHA = 1
4CFLAGS = $(CFLAGS) -DPROG_VARIANT_Z 4CFLAGS = $(CFLAGS) -DZ7_PROG_VARIANT_Z
5 5
6!include "../Format7zF/Arc.mak" 6!include "../Format7zF/Arc.mak"
7!include "../../UI/Console/Console.mak" 7!include "../../UI/Console/Console.mak"
@@ -24,5 +24,6 @@ WIN_OBJS = $(WIN_OBJS) \
247ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ 247ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \
25 $O\FilePathAutoRename.obj \ 25 $O\FilePathAutoRename.obj \
26 $O\FileStreams.obj \ 26 $O\FileStreams.obj \
27 $O\MultiOutStream.obj \
27 28
28!include "../../7zip.mak" 29!include "../../7zip.mak"
diff --git a/CPP/7zip/Bundles/Alone2/makefile.gcc b/CPP/7zip/Bundles/Alone2/makefile.gcc
index 49f9fd0..f767b0d 100644
--- a/CPP/7zip/Bundles/Alone2/makefile.gcc
+++ b/CPP/7zip/Bundles/Alone2/makefile.gcc
@@ -4,7 +4,7 @@ PROG = 7zz
4# USE_ASM = 1 4# USE_ASM = 1
5# ST_MODE = 1 5# ST_MODE = 1
6 6
7CONSOLE_VARIANT_FLAGS=-DPROG_VARIANT_Z 7CONSOLE_VARIANT_FLAGS=-DZ7_PROG_VARIANT_Z
8 8
9include ../Format7zF/Arc_gcc.mak 9include ../Format7zF/Arc_gcc.mak
10 10
@@ -20,9 +20,9 @@ endif
20ifdef IS_MINGW 20ifdef IS_MINGW
21 21
22LOCAL_FLAGS_SYS = \ 22LOCAL_FLAGS_SYS = \
23 -D_7ZIP_LARGE_PAGES \ 23 -DZ7_LARGE_PAGES \
24 -DWIN_LONG_PATH \ 24 -DZ7_LONG_PATH \
25 -DSUPPORT_DEVICE_FILE \ 25 -DZ7_DEVICE_FILE \
26 26
27SYS_OBJS = \ 27SYS_OBJS = \
28 $O/FileSystem.o \ 28 $O/FileSystem.o \
@@ -95,6 +95,7 @@ WIN_OBJS_2 = \
957ZIP_COMMON_OBJS_2 = \ 957ZIP_COMMON_OBJS_2 = \
96 $O/FilePathAutoRename.o \ 96 $O/FilePathAutoRename.o \
97 $O/FileStreams.o \ 97 $O/FileStreams.o \
98 $O/MultiOutStream.o \
98 99
99OBJS = \ 100OBJS = \
100 $(ARC_OBJS) \ 101 $(ARC_OBJS) \
diff --git a/CPP/7zip/Bundles/Alone7z/Alone.dsp b/CPP/7zip/Bundles/Alone7z/Alone.dsp
index 217e6d6..ef4ec60 100644
--- a/CPP/7zip/Bundles/Alone7z/Alone.dsp
+++ b/CPP/7zip/Bundles/Alone7z/Alone.dsp
@@ -44,7 +44,7 @@ RSC=rc.exe
44# PROP Ignore_Export_Lib 0 44# PROP Ignore_Export_Lib 0
45# PROP Target_Dir "" 45# PROP Target_Dir ""
46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c 46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
47# 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 47# 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
48# ADD BASE RSC /l 0x419 /d "NDEBUG" 48# ADD BASE RSC /l 0x419 /d "NDEBUG"
49# ADD RSC /l 0x419 /d "NDEBUG" 49# ADD RSC /l 0x419 /d "NDEBUG"
50BSC32=bscmake.exe 50BSC32=bscmake.exe
@@ -69,7 +69,7 @@ LINK32=link.exe
69# PROP Ignore_Export_Lib 0 69# PROP Ignore_Export_Lib 0
70# PROP Target_Dir "" 70# PROP Target_Dir ""
71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c 71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
72# 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 72# 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
73# ADD BASE RSC /l 0x419 /d "_DEBUG" 73# ADD BASE RSC /l 0x419 /d "_DEBUG"
74# ADD RSC /l 0x419 /d "_DEBUG" 74# ADD RSC /l 0x419 /d "_DEBUG"
75BSC32=bscmake.exe 75BSC32=bscmake.exe
@@ -93,8 +93,8 @@ LINK32=link.exe
93# PROP Intermediate_Dir "ReleaseU" 93# PROP Intermediate_Dir "ReleaseU"
94# PROP Ignore_Export_Lib 0 94# PROP Ignore_Export_Lib 0
95# PROP Target_Dir "" 95# PROP Target_Dir ""
96# 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 96# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /Yu"StdAfx.h" /FD /c
97# 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 97# 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
98# ADD BASE RSC /l 0x419 /d "NDEBUG" 98# ADD BASE RSC /l 0x419 /d "NDEBUG"
99# ADD RSC /l 0x419 /d "NDEBUG" 99# ADD RSC /l 0x419 /d "NDEBUG"
100BSC32=bscmake.exe 100BSC32=bscmake.exe
@@ -120,8 +120,8 @@ LINK32=link.exe
120# PROP Intermediate_Dir "DebugU" 120# PROP Intermediate_Dir "DebugU"
121# PROP Ignore_Export_Lib 0 121# PROP Ignore_Export_Lib 0
122# PROP Target_Dir "" 122# PROP Target_Dir ""
123# 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 123# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c
124# 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 124# 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
125# ADD BASE RSC /l 0x419 /d "_DEBUG" 125# ADD BASE RSC /l 0x419 /d "_DEBUG"
126# ADD RSC /l 0x419 /d "_DEBUG" 126# ADD RSC /l 0x419 /d "_DEBUG"
127BSC32=bscmake.exe 127BSC32=bscmake.exe
@@ -144,10 +144,6 @@ LINK32=link.exe
144# PROP Default_Filter "" 144# PROP Default_Filter ""
145# Begin Source File 145# Begin Source File
146 146
147SOURCE=..\..\UI\Console\ArError.h
148# End Source File
149# Begin Source File
150
151SOURCE=..\..\UI\Console\BenchCon.cpp 147SOURCE=..\..\UI\Console\BenchCon.cpp
152# End Source File 148# End Source File
153# Begin Source File 149# Begin Source File
@@ -270,6 +266,10 @@ SOURCE=..\..\..\Common\CommandLineParser.h
270# End Source File 266# End Source File
271# Begin Source File 267# Begin Source File
272 268
269SOURCE=..\..\..\Common\Common.h
270# End Source File
271# Begin Source File
272
273SOURCE=..\..\..\Common\ComTry.h 273SOURCE=..\..\..\Common\ComTry.h
274# End Source File 274# End Source File
275# Begin Source File 275# Begin Source File
@@ -318,6 +318,14 @@ SOURCE=..\..\..\Common\LzFindPrepare.cpp
318# End Source File 318# End Source File
319# Begin Source File 319# Begin Source File
320 320
321SOURCE=..\..\..\Common\MyBuffer.h
322# End Source File
323# Begin Source File
324
325SOURCE=..\..\..\Common\MyBuffer2.h
326# End Source File
327# Begin Source File
328
321SOURCE=..\..\..\Common\MyCom.h 329SOURCE=..\..\..\Common\MyCom.h
322# End Source File 330# End Source File
323# Begin Source File 331# Begin Source File
@@ -342,6 +350,10 @@ SOURCE=..\..\..\Common\MyString.h
342# End Source File 350# End Source File
343# Begin Source File 351# Begin Source File
344 352
353SOURCE=..\..\..\Common\MyTypes.h
354# End Source File
355# Begin Source File
356
345SOURCE=..\..\..\Common\MyUnknown.h 357SOURCE=..\..\..\Common\MyUnknown.h
346# End Source File 358# End Source File
347# Begin Source File 359# Begin Source File
@@ -526,6 +538,10 @@ SOURCE=..\..\..\Windows\MemoryLock.h
526# End Source File 538# End Source File
527# Begin Source File 539# Begin Source File
528 540
541SOURCE=..\..\..\Windows\NtCheck.h
542# End Source File
543# Begin Source File
544
529SOURCE=..\..\..\Windows\PropVariant.cpp 545SOURCE=..\..\..\Windows\PropVariant.cpp
530# End Source File 546# End Source File
531# Begin Source File 547# Begin Source File
@@ -550,10 +566,6 @@ SOURCE=..\..\..\Windows\Registry.h
550# End Source File 566# End Source File
551# Begin Source File 567# Begin Source File
552 568
553SOURCE=..\..\..\Windows\Synchronization.cpp
554# End Source File
555# Begin Source File
556
557SOURCE=..\..\..\Windows\Synchronization.h 569SOURCE=..\..\..\Windows\Synchronization.h
558# End Source File 570# End Source File
559# Begin Source File 571# Begin Source File
@@ -678,6 +690,14 @@ SOURCE=..\..\Common\MethodProps.h
678# End Source File 690# End Source File
679# Begin Source File 691# Begin Source File
680 692
693SOURCE=..\..\Common\MultiOutStream.cpp
694# End Source File
695# Begin Source File
696
697SOURCE=..\..\Common\MultiOutStream.h
698# End Source File
699# Begin Source File
700
681SOURCE=..\..\Common\OffsetStream.cpp 701SOURCE=..\..\Common\OffsetStream.cpp
682# End Source File 702# End Source File
683# Begin Source File 703# Begin Source File
@@ -798,10 +818,6 @@ SOURCE=..\..\Compress\ByteSwap.cpp
798# End Source File 818# End Source File
799# Begin Source File 819# Begin Source File
800 820
801SOURCE=..\..\Compress\ByteSwap.h
802# End Source File
803# Begin Source File
804
805SOURCE=..\..\Compress\CopyCoder.cpp 821SOURCE=..\..\Compress\CopyCoder.cpp
806# End Source File 822# End Source File
807# Begin Source File 823# Begin Source File
@@ -1122,6 +1138,10 @@ SOURCE=..\..\UI\Common\EnumDirItems.h
1122# End Source File 1138# End Source File
1123# Begin Source File 1139# Begin Source File
1124 1140
1141SOURCE=..\..\UI\Common\ExitCode.h
1142# End Source File
1143# Begin Source File
1144
1125SOURCE=..\..\UI\Common\Extract.cpp 1145SOURCE=..\..\UI\Common\Extract.cpp
1126# End Source File 1146# End Source File
1127# Begin Source File 1147# Begin Source File
@@ -1246,7 +1266,7 @@ SOURCE=..\..\ICoder.h
1246# End Source File 1266# End Source File
1247# Begin Source File 1267# Begin Source File
1248 1268
1249SOURCE=..\..\IMyUnknown.h 1269SOURCE=..\..\IDecl.h
1250# End Source File 1270# End Source File
1251# Begin Source File 1271# Begin Source File
1252 1272
@@ -1473,6 +1493,10 @@ SOURCE=..\..\..\..\C\7zTypes.h
1473# End Source File 1493# End Source File
1474# Begin Source File 1494# Begin Source File
1475 1495
1496SOURCE=..\..\..\..\C\7zWindows.h
1497# End Source File
1498# Begin Source File
1499
1476SOURCE=..\..\..\..\C\Aes.c 1500SOURCE=..\..\..\..\C\Aes.c
1477 1501
1478!IF "$(CFG)" == "Alone - Win32 Release" 1502!IF "$(CFG)" == "Alone - Win32 Release"
@@ -1605,6 +1629,10 @@ SOURCE=..\..\..\..\C\BraIA64.c
1605# End Source File 1629# End Source File
1606# Begin Source File 1630# Begin Source File
1607 1631
1632SOURCE=..\..\..\..\C\Compiler.h
1633# End Source File
1634# Begin Source File
1635
1608SOURCE=..\..\..\..\C\CpuArch.c 1636SOURCE=..\..\..\..\C\CpuArch.c
1609 1637
1610!IF "$(CFG)" == "Alone - Win32 Release" 1638!IF "$(CFG)" == "Alone - Win32 Release"
@@ -1902,6 +1930,10 @@ SOURCE=..\..\..\..\C\MtDec.h
1902# End Source File 1930# End Source File
1903# Begin Source File 1931# Begin Source File
1904 1932
1933SOURCE=..\..\..\..\C\RotateDefs.h
1934# End Source File
1935# Begin Source File
1936
1905SOURCE=..\..\..\..\C\Sha256.c 1937SOURCE=..\..\..\..\C\Sha256.c
1906 1938
1907!IF "$(CFG)" == "Alone - Win32 Release" 1939!IF "$(CFG)" == "Alone - Win32 Release"
@@ -1935,6 +1967,34 @@ SOURCE=..\..\..\..\C\Sha256Opt.c
1935# End Source File 1967# End Source File
1936# Begin Source File 1968# Begin Source File
1937 1969
1970SOURCE=..\..\..\..\C\SwapBytes.c
1971
1972!IF "$(CFG)" == "Alone - Win32 Release"
1973
1974# ADD CPP /O2
1975# SUBTRACT CPP /YX /Yc /Yu
1976
1977!ELSEIF "$(CFG)" == "Alone - Win32 Debug"
1978
1979# SUBTRACT CPP /YX /Yc /Yu
1980
1981!ELSEIF "$(CFG)" == "Alone - Win32 ReleaseU"
1982
1983# SUBTRACT CPP /YX /Yc /Yu
1984
1985!ELSEIF "$(CFG)" == "Alone - Win32 DebugU"
1986
1987# SUBTRACT CPP /YX /Yc /Yu
1988
1989!ENDIF
1990
1991# End Source File
1992# Begin Source File
1993
1994SOURCE=..\..\..\..\C\SwapBytes.h
1995# End Source File
1996# Begin Source File
1997
1938SOURCE=..\..\..\..\C\Threads.c 1998SOURCE=..\..\..\..\C\Threads.c
1939# SUBTRACT CPP /YX /Yc /Yu 1999# SUBTRACT CPP /YX /Yc /Yu
1940# End Source File 2000# End Source File
diff --git a/CPP/7zip/Bundles/Alone7z/StdAfx.h b/CPP/7zip/Bundles/Alone7z/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Alone7z/StdAfx.h
+++ b/CPP/7zip/Bundles/Alone7z/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Alone7z/makefile b/CPP/7zip/Bundles/Alone7z/makefile
index f87684c..1f857c5 100644
--- a/CPP/7zip/Bundles/Alone7z/makefile
+++ b/CPP/7zip/Bundles/Alone7z/makefile
@@ -1,8 +1,9 @@
1PROG = 7zr.exe 1PROG = 7zr.exe
2 2
3# USE_C_AES = 1 3# USE_C_AES = 1
4# USE_C_SHA = 1
4 5
5CFLAGS = $(CFLAGS) -DPROG_VARIANT_R 6CFLAGS = $(CFLAGS) -DZ7_PROG_VARIANT_R
6 7
7COMMON_OBJS = \ 8COMMON_OBJS = \
8 $O\CommandLineParser.obj \ 9 $O\CommandLineParser.obj \
@@ -38,7 +39,6 @@ WIN_OBJS = \
38 $O\PropVariant.obj \ 39 $O\PropVariant.obj \
39 $O\PropVariantConv.obj \ 40 $O\PropVariantConv.obj \
40 $O\Registry.obj \ 41 $O\Registry.obj \
41 $O\Synchronization.obj \
42 $O\System.obj \ 42 $O\System.obj \
43 $O\SystemInfo.obj \ 43 $O\SystemInfo.obj \
44 $O\TimeUtils.obj \ 44 $O\TimeUtils.obj \
@@ -54,6 +54,7 @@ WIN_OBJS = \
54 $O\LimitedStreams.obj \ 54 $O\LimitedStreams.obj \
55 $O\MethodId.obj \ 55 $O\MethodId.obj \
56 $O\MethodProps.obj \ 56 $O\MethodProps.obj \
57 $O\MultiOutStream.obj \
57 $O\OffsetStream.obj \ 58 $O\OffsetStream.obj \
58 $O\OutBuffer.obj \ 59 $O\OutBuffer.obj \
59 $O\ProgressUtils.obj \ 60 $O\ProgressUtils.obj \
@@ -143,6 +144,7 @@ C_OBJS = \
143 $O\MtCoder.obj \ 144 $O\MtCoder.obj \
144 $O\MtDec.obj \ 145 $O\MtDec.obj \
145 $O\Sort.obj \ 146 $O\Sort.obj \
147 $O\SwapBytes.obj \
146 $O\Threads.obj \ 148 $O\Threads.obj \
147 $O\Xz.obj \ 149 $O\Xz.obj \
148 $O\XzDec.obj \ 150 $O\XzDec.obj \
diff --git a/CPP/7zip/Bundles/Alone7z/makefile.gcc b/CPP/7zip/Bundles/Alone7z/makefile.gcc
index f11fcde..6d92c19 100644
--- a/CPP/7zip/Bundles/Alone7z/makefile.gcc
+++ b/CPP/7zip/Bundles/Alone7z/makefile.gcc
@@ -1,6 +1,6 @@
1PROG = 7zr 1PROG = 7zr
2 2
3CONSOLE_VARIANT_FLAGS=-DPROG_VARIANT_R 3CONSOLE_VARIANT_FLAGS=-DZ7_PROG_VARIANT_R
4 4
5# IS_X64 = 1 5# IS_X64 = 1
6# USE_ASM = 1 6# USE_ASM = 1
@@ -24,7 +24,7 @@ MT_OBJS =
24 24
25ifdef ST_MODE 25ifdef ST_MODE
26 26
27LOCAL_FLAGS_ST = -D_7ZIP_ST 27LOCAL_FLAGS_ST = -DZ7_ST
28 28
29ifdef IS_MINGW 29ifdef IS_MINGW
30MT_OBJS = \ 30MT_OBJS = \
@@ -38,7 +38,6 @@ MT_OBJS = \
38 $O/LzFindMt.o \ 38 $O/LzFindMt.o \
39 $O/LzFindOpt.o \ 39 $O/LzFindOpt.o \
40 $O/StreamBinder.o \ 40 $O/StreamBinder.o \
41 $O/Synchronization.o \
42 $O/VirtThread.o \ 41 $O/VirtThread.o \
43 $O/Threads.o \ 42 $O/Threads.o \
44 43
@@ -53,9 +52,9 @@ LOCAL_FLAGS_SYS =
53ifdef IS_MINGW 52ifdef IS_MINGW
54 53
55LOCAL_FLAGS_SYS = \ 54LOCAL_FLAGS_SYS = \
56 -D_7ZIP_LARGE_PAGES \ 55 -DZ7_LARGE_PAGES \
57 -DWIN_LONG_PATH \ 56 -DZ7_LONG_PATH \
58 -DSUPPORT_DEVICE_FILE \ 57 -DZ7_DEVICE_FILE \
59 58
60SYS_OBJS = \ 59SYS_OBJS = \
61 $O/FileSystem.o \ 60 $O/FileSystem.o \
@@ -76,8 +75,6 @@ LOCAL_FLAGS = \
76 $(LOCAL_FLAGS_ST) \ 75 $(LOCAL_FLAGS_ST) \
77 $(LOCAL_FLAGS_SYS) \ 76 $(LOCAL_FLAGS_SYS) \
78 77
79# -D_LZMA_PROB32
80
81 78
82CONSOLE_OBJS = \ 79CONSOLE_OBJS = \
83 $O/BenchCon.o \ 80 $O/BenchCon.o \
@@ -160,6 +157,7 @@ WIN_OBJS = \
160 $O/LimitedStreams.o \ 157 $O/LimitedStreams.o \
161 $O/MethodId.o \ 158 $O/MethodId.o \
162 $O/MethodProps.o \ 159 $O/MethodProps.o \
160 $O/MultiOutStream.o \
163 $O/OffsetStream.o \ 161 $O/OffsetStream.o \
164 $O/OutBuffer.o \ 162 $O/OutBuffer.o \
165 $O/ProgressUtils.o \ 163 $O/ProgressUtils.o \
@@ -246,7 +244,7 @@ C_OBJS = \
246 $O/MtDec.o \ 244 $O/MtDec.o \
247 $O/Sha256.o \ 245 $O/Sha256.o \
248 $O/Sha256Opt.o \ 246 $O/Sha256Opt.o \
249 $O/Sort.o \ 247 $O/SwapBytes.o \
250 $O/Xz.o \ 248 $O/Xz.o \
251 $O/XzDec.o \ 249 $O/XzDec.o \
252 $O/XzEnc.o \ 250 $O/XzEnc.o \
@@ -260,7 +258,7 @@ C_OBJS = \
260 258
261 259
262OBJS = \ 260OBJS = \
263 $(LZMA_DEC_OPT_OBJS) \ 261 $(LZMA_DEC_OPT_OBJS) \
264 $(C_OBJS) \ 262 $(C_OBJS) \
265 $(MT_OBJS) \ 263 $(MT_OBJS) \
266 $(SYS_OBJS) \ 264 $(SYS_OBJS) \
diff --git a/CPP/7zip/Bundles/Fm/FM.dsp b/CPP/7zip/Bundles/Fm/FM.dsp
index 54efba9..402dd2c 100644
--- a/CPP/7zip/Bundles/Fm/FM.dsp
+++ b/CPP/7zip/Bundles/Fm/FM.dsp
@@ -45,7 +45,7 @@ RSC=rc.exe
45# PROP Ignore_Export_Lib 0 45# PROP Ignore_Export_Lib 0
46# PROP Target_Dir "" 46# PROP Target_Dir ""
47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c 47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
48# 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 48# 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
49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
51# ADD BASE RSC /l 0x419 /d "NDEBUG" 51# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -72,7 +72,7 @@ LINK32=link.exe
72# PROP Ignore_Export_Lib 0 72# PROP Ignore_Export_Lib 0
73# PROP Target_Dir "" 73# PROP Target_Dir ""
74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c 74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
75# 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 75# 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
76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
78# ADD BASE RSC /l 0x419 /d "_DEBUG" 78# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -99,7 +99,7 @@ LINK32=link.exe
99# PROP Ignore_Export_Lib 0 99# PROP Ignore_Export_Lib 0
100# PROP Target_Dir "" 100# PROP Target_Dir ""
101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c 101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c
102# 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 102# 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
103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
105# ADD BASE RSC /l 0x419 /d "NDEBUG" 105# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -127,7 +127,7 @@ LINK32=link.exe
127# PROP Ignore_Export_Lib 0 127# PROP Ignore_Export_Lib 0
128# PROP Target_Dir "" 128# PROP Target_Dir ""
129# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c 129# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c
130# 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 130# 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
131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
133# ADD BASE RSC /l 0x419 /d "_DEBUG" 133# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -849,6 +849,14 @@ SOURCE=..\..\Common\MethodProps.h
849# End Source File 849# End Source File
850# Begin Source File 850# Begin Source File
851 851
852SOURCE=..\..\Common\MultiOutStream.cpp
853# End Source File
854# Begin Source File
855
856SOURCE=..\..\Common\MultiOutStream.h
857# End Source File
858# Begin Source File
859
852SOURCE=..\..\Common\OutBuffer.cpp 860SOURCE=..\..\Common\OutBuffer.cpp
853# End Source File 861# End Source File
854# Begin Source File 862# Begin Source File
@@ -947,10 +955,19 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c
947# End Source File 955# End Source File
948# Begin Source File 956# Begin Source File
949 957
958SOURCE=..\..\..\..\C\7zStream.c
959# SUBTRACT CPP /YX /Yc /Yu
960# End Source File
961# Begin Source File
962
950SOURCE=..\..\..\..\C\7zTypes.h 963SOURCE=..\..\..\..\C\7zTypes.h
951# End Source File 964# End Source File
952# Begin Source File 965# Begin Source File
953 966
967SOURCE=..\..\..\..\C\7zWindows.h
968# End Source File
969# Begin Source File
970
954SOURCE=..\..\..\..\C\Alloc.c 971SOURCE=..\..\..\..\C\Alloc.c
955# SUBTRACT CPP /YX /Yc /Yu 972# SUBTRACT CPP /YX /Yc /Yu
956# End Source File 973# End Source File
@@ -960,6 +977,10 @@ SOURCE=..\..\..\..\C\Alloc.h
960# End Source File 977# End Source File
961# Begin Source File 978# Begin Source File
962 979
980SOURCE=..\..\..\..\C\Compiler.h
981# End Source File
982# Begin Source File
983
963SOURCE=..\..\..\..\C\CpuArch.c 984SOURCE=..\..\..\..\C\CpuArch.c
964 985
965!IF "$(CFG)" == "FM - Win32 Release" 986!IF "$(CFG)" == "FM - Win32 Release"
diff --git a/CPP/7zip/Bundles/Fm/StdAfx.h b/CPP/7zip/Bundles/Fm/StdAfx.h
index 15fd136..4f27255 100644
--- a/CPP/7zip/Bundles/Fm/StdAfx.h
+++ b/CPP/7zip/Bundles/Fm/StdAfx.h
@@ -1,16 +1,6 @@
1// stdafx.h 1// StdAfx.h
2
3#ifndef __STDAFX_H
4#define __STDAFX_H
5
6// #define _WIN32_WINNT 0x0400
7#define _WIN32_WINNT 0x0500
8#define WINVER _WIN32_WINNT
9
10#include "../../../Common/Common.h"
11
12#include <CommCtrl.h>
13#include <ShlObj.h>
14#include <Shlwapi.h>
15 2
3#if _MSC_VER >= 1800
4#pragma warning(disable : 4464) // relative include path contains '..'
16#endif 5#endif
6#include "../../UI/FileManager/StdAfx.h"
diff --git a/CPP/7zip/Bundles/Fm/makefile b/CPP/7zip/Bundles/Fm/makefile
index 33813e8..33b5320 100644
--- a/CPP/7zip/Bundles/Fm/makefile
+++ b/CPP/7zip/Bundles/Fm/makefile
@@ -1,5 +1,7 @@
1PROG = 7zFM.exe 1PROG = 7zFM.exe
2 2
3CFLAGS = $(CFLAGS) -DZ7_LARGE_PAGES
4
3!include "../Format7zF/Arc.mak" 5!include "../Format7zF/Arc.mak"
4 6
5!include "../../UI/FileManager/FM.mak" 7!include "../../UI/FileManager/FM.mak"
@@ -36,6 +38,7 @@ WIN_CTRL_OBJS = \
367ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \ 387ZIP_COMMON_OBJS = $(7ZIP_COMMON_OBJS) \
37 $O\FilePathAutoRename.obj \ 39 $O\FilePathAutoRename.obj \
38 $O\FileStreams.obj \ 40 $O\FileStreams.obj \
41 $O\MultiOutStream.obj \
39 42
40UI_COMMON_OBJS = \ 43UI_COMMON_OBJS = \
41 $O\ArchiveExtractCallback.obj \ 44 $O\ArchiveExtractCallback.obj \
diff --git a/CPP/7zip/Bundles/Format7z/StdAfx.h b/CPP/7zip/Bundles/Format7z/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Format7z/StdAfx.h
+++ b/CPP/7zip/Bundles/Format7z/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Format7z/makefile b/CPP/7zip/Bundles/Format7z/makefile
index 7276f17..d20a3c1 100644
--- a/CPP/7zip/Bundles/Format7z/makefile
+++ b/CPP/7zip/Bundles/Format7z/makefile
@@ -1,8 +1,8 @@
1PROG = 7za.dll 1PROG = 7za.dll
2DEF_FILE = ../../Archive/Archive2.def 2DEF_FILE = ../../Archive/Archive2.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DDEFLATE_EXTRACT_ONLY \ 4 -DZ7_DEFLATE_EXTRACT_ONLY \
5 -DBZIP2_EXTRACT_ONLY \ 5 -DZ7_BZIP2_EXTRACT_ONLY \
6 6
7COMMON_OBJS = \ 7COMMON_OBJS = \
8 $O\CRC.obj \ 8 $O\CRC.obj \
@@ -111,6 +111,7 @@ CRYPTO_OBJS = \
111 $O\RandGen.obj \ 111 $O\RandGen.obj \
112 112
113C_OBJS = \ 113C_OBJS = \
114 $O\7zStream.obj \
114 $O\Alloc.obj \ 115 $O\Alloc.obj \
115 $O\Bcj2.obj \ 116 $O\Bcj2.obj \
116 $O\Bcj2Enc.obj \ 117 $O\Bcj2Enc.obj \
@@ -134,6 +135,7 @@ C_OBJS = \
134 $O\Ppmd7Dec.obj \ 135 $O\Ppmd7Dec.obj \
135 $O\Ppmd7Enc.obj \ 136 $O\Ppmd7Enc.obj \
136 $O\Sort.obj \ 137 $O\Sort.obj \
138 $O\SwapBytes.obj \
137 $O\Threads.obj \ 139 $O\Threads.obj \
138 140
139!include "../../Aes.mak" 141!include "../../Aes.mak"
diff --git a/CPP/7zip/Bundles/Format7zExtract/StdAfx.h b/CPP/7zip/Bundles/Format7zExtract/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Format7zExtract/StdAfx.h
+++ b/CPP/7zip/Bundles/Format7zExtract/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Format7zExtract/makefile b/CPP/7zip/Bundles/Format7zExtract/makefile
index 9b4831a..4e2ed3e 100644
--- a/CPP/7zip/Bundles/Format7zExtract/makefile
+++ b/CPP/7zip/Bundles/Format7zExtract/makefile
@@ -1,7 +1,7 @@
1PROG = 7zxa.dll 1PROG = 7zxa.dll
2DEF_FILE = ../../Archive/Archive2.def 2DEF_FILE = ../../Archive/Archive2.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DEXTRACT_ONLY \ 4 -DZ7_EXTRACT_ONLY \
5 5
6COMMON_OBJS = \ 6COMMON_OBJS = \
7 $O\CRC.obj \ 7 $O\CRC.obj \
@@ -91,6 +91,7 @@ CRYPTO_OBJS = \
91 $O\MyAesReg.obj \ 91 $O\MyAesReg.obj \
92 92
93C_OBJS = \ 93C_OBJS = \
94 $O\7zStream.obj \
94 $O\Alloc.obj \ 95 $O\Alloc.obj \
95 $O\Bcj2.obj \ 96 $O\Bcj2.obj \
96 $O\Bra.obj \ 97 $O\Bra.obj \
@@ -104,6 +105,7 @@ C_OBJS = \
104 $O\MtDec.obj \ 105 $O\MtDec.obj \
105 $O\Ppmd7.obj \ 106 $O\Ppmd7.obj \
106 $O\Ppmd7Dec.obj \ 107 $O\Ppmd7Dec.obj \
108 $O\SwapBytes.obj \
107 $O\Threads.obj \ 109 $O\Threads.obj \
108 110
109!include "../../Aes.mak" 111!include "../../Aes.mak"
diff --git a/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h b/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h
+++ b/CPP/7zip/Bundles/Format7zExtractR/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Format7zExtractR/makefile b/CPP/7zip/Bundles/Format7zExtractR/makefile
index 756c8ae..50b84d8 100644
--- a/CPP/7zip/Bundles/Format7zExtractR/makefile
+++ b/CPP/7zip/Bundles/Format7zExtractR/makefile
@@ -1,8 +1,8 @@
1PROG = 7zxr.dll 1PROG = 7zxr.dll
2DEF_FILE = ../../Archive/Archive2.def 2DEF_FILE = ../../Archive/Archive2.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DEXTRACT_ONLY \ 4 -DZ7_EXTRACT_ONLY \
5 -D_NO_CRYPTO 5 -DZ7_NO_CRYPTO
6 6
7COMMON_OBJS = \ 7COMMON_OBJS = \
8 $O\CRC.obj \ 8 $O\CRC.obj \
@@ -77,6 +77,7 @@ COMPRESS_OBJS = \
77 $O\LzmaRegister.obj \ 77 $O\LzmaRegister.obj \
78 78
79C_OBJS = \ 79C_OBJS = \
80 $O\7zStream.obj \
80 $O\Alloc.obj \ 81 $O\Alloc.obj \
81 $O\Bcj2.obj \ 82 $O\Bcj2.obj \
82 $O\Bra.obj \ 83 $O\Bra.obj \
@@ -88,6 +89,7 @@ C_OBJS = \
88 $O\Lzma2DecMt.obj \ 89 $O\Lzma2DecMt.obj \
89 $O\LzmaDec.obj \ 90 $O\LzmaDec.obj \
90 $O\MtDec.obj \ 91 $O\MtDec.obj \
92 $O\SwapBytes.obj \
91 $O\Threads.obj \ 93 $O\Threads.obj \
92 94
93!include "../../Crc.mak" 95!include "../../Crc.mak"
diff --git a/CPP/7zip/Bundles/Format7zF/Arc.mak b/CPP/7zip/Bundles/Format7zF/Arc.mak
index 209aea3..37b400e 100644
--- a/CPP/7zip/Bundles/Format7zF/Arc.mak
+++ b/CPP/7zip/Bundles/Format7zF/Arc.mak
@@ -111,7 +111,6 @@ AR_COMMON_OBJS = \
111 $O\HandlerOut.obj \ 111 $O\HandlerOut.obj \
112 $O\ParseProperties.obj \ 112 $O\ParseProperties.obj \
113 113
114
1157Z_OBJS = \ 1147Z_OBJS = \
116 $O\7zCompressionMode.obj \ 115 $O\7zCompressionMode.obj \
117 $O\7zDecode.obj \ 116 $O\7zDecode.obj \
@@ -235,7 +234,6 @@ COMPRESS_OBJS = \
235 $O\ZlibEncoder.obj \ 234 $O\ZlibEncoder.obj \
236 $O\ZDecoder.obj \ 235 $O\ZDecoder.obj \
237 236
238
239CRYPTO_OBJS = \ 237CRYPTO_OBJS = \
240 $O\7zAes.obj \ 238 $O\7zAes.obj \
241 $O\7zAesRegister.obj \ 239 $O\7zAesRegister.obj \
@@ -252,7 +250,6 @@ CRYPTO_OBJS = \
252 $O\ZipCrypto.obj \ 250 $O\ZipCrypto.obj \
253 $O\ZipStrong.obj \ 251 $O\ZipStrong.obj \
254 252
255
256C_OBJS = \ 253C_OBJS = \
257 $O\7zBuf2.obj \ 254 $O\7zBuf2.obj \
258 $O\7zStream.obj \ 255 $O\7zStream.obj \
@@ -284,6 +281,7 @@ C_OBJS = \
284 $O\Ppmd8Dec.obj \ 281 $O\Ppmd8Dec.obj \
285 $O\Ppmd8Enc.obj \ 282 $O\Ppmd8Enc.obj \
286 $O\Sort.obj \ 283 $O\Sort.obj \
284 $O\SwapBytes.obj \
287 $O\Threads.obj \ 285 $O\Threads.obj \
288 $O\Xz.obj \ 286 $O\Xz.obj \
289 $O\XzDec.obj \ 287 $O\XzDec.obj \
diff --git a/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak b/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak
index 1292dd8..404d917 100644
--- a/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak
+++ b/CPP/7zip/Bundles/Format7zF/Arc_gcc.mak
@@ -14,7 +14,7 @@ endif
14 14
15ifdef ST_MODE 15ifdef ST_MODE
16 16
17LOCAL_FLAGS_ST = -D_7ZIP_ST 17LOCAL_FLAGS_ST = -DZ7_ST
18 18
19ifdef IS_MINGW 19ifdef IS_MINGW
20MT_OBJS = \ 20MT_OBJS = \
@@ -351,6 +351,7 @@ C_OBJS = \
351 $O/Sha256Opt.o \ 351 $O/Sha256Opt.o \
352 $O/Sha1.o \ 352 $O/Sha1.o \
353 $O/Sha1Opt.o \ 353 $O/Sha1Opt.o \
354 $O/SwapBytes.o \
354 355
355ARC_OBJS = \ 356ARC_OBJS = \
356 $(LZMA_DEC_OPT_OBJS) \ 357 $(LZMA_DEC_OPT_OBJS) \
@@ -358,6 +359,7 @@ ARC_OBJS = \
358 $(MT_OBJS) \ 359 $(MT_OBJS) \
359 $(COMMON_OBJS) \ 360 $(COMMON_OBJS) \
360 $(WIN_OBJS) \ 361 $(WIN_OBJS) \
362 $(7ZIP_COMMON_OBJS) \
361 $(AR_OBJS) \ 363 $(AR_OBJS) \
362 $(AR_COMMON_OBJS) \ 364 $(AR_COMMON_OBJS) \
363 $(7Z_OBJS) \ 365 $(7Z_OBJS) \
@@ -373,5 +375,5 @@ ARC_OBJS = \
373 $(ZIP_OBJS) \ 375 $(ZIP_OBJS) \
374 $(COMPRESS_OBJS) \ 376 $(COMPRESS_OBJS) \
375 $(CRYPTO_OBJS) \ 377 $(CRYPTO_OBJS) \
376 $(7ZIP_COMMON_OBJS) \
377 378
379# 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 bd2ed44..a0c5d83 100644
--- a/CPP/7zip/Bundles/Format7zF/Format7z.dsp
+++ b/CPP/7zip/Bundles/Format7zF/Format7z.dsp
@@ -43,7 +43,7 @@ RSC=rc.exe
43# PROP Ignore_Export_Lib 1 43# PROP Ignore_Export_Lib 1
44# PROP Target_Dir "" 44# PROP Target_Dir ""
45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c 45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "MY7Z_EXPORTS" /YX /FD /c
46# 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 46# 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
47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
49# ADD BASE RSC /l 0x419 /d "NDEBUG" 49# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -70,7 +70,7 @@ LINK32=link.exe
70# PROP Ignore_Export_Lib 1 70# PROP Ignore_Export_Lib 1
71# PROP Target_Dir "" 71# PROP Target_Dir ""
72# 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 72# 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
73# 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 73# 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
74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
76# ADD BASE RSC /l 0x419 /d "_DEBUG" 76# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -235,6 +235,10 @@ SOURCE=..\..\..\Common\Common.h
235# End Source File 235# End Source File
236# Begin Source File 236# Begin Source File
237 237
238SOURCE=..\..\..\Common\ComTry.h
239# End Source File
240# Begin Source File
241
238SOURCE=..\..\..\Common\CRC.cpp 242SOURCE=..\..\..\Common\CRC.cpp
239# End Source File 243# End Source File
240# Begin Source File 244# Begin Source File
@@ -1634,6 +1638,14 @@ SOURCE=..\..\..\..\C\7zTypes.h
1634# End Source File 1638# End Source File
1635# Begin Source File 1639# Begin Source File
1636 1640
1641SOURCE=..\..\..\..\C\7zVersion.h
1642# End Source File
1643# Begin Source File
1644
1645SOURCE=..\..\..\..\C\7zWindows.h
1646# End Source File
1647# Begin Source File
1648
1637SOURCE=..\..\..\..\C\Aes.c 1649SOURCE=..\..\..\..\C\Aes.c
1638 1650
1639!IF "$(CFG)" == "7z - Win32 Release" 1651!IF "$(CFG)" == "7z - Win32 Release"
@@ -2214,7 +2226,23 @@ SOURCE=..\..\..\..\C\Sort.h
2214# End Source File 2226# End Source File
2215# Begin Source File 2227# Begin Source File
2216 2228
2217SOURCE=..\..\..\..\C\StdAfx.h 2229SOURCE=..\..\..\..\C\SwapBytes.c
2230
2231!IF "$(CFG)" == "7z - Win32 Release"
2232
2233# ADD CPP /O2
2234# SUBTRACT CPP /YX /Yc /Yu
2235
2236!ELSEIF "$(CFG)" == "7z - Win32 Debug"
2237
2238# SUBTRACT CPP /YX /Yc /Yu
2239
2240!ENDIF
2241
2242# End Source File
2243# Begin Source File
2244
2245SOURCE=..\..\..\..\C\SwapBytes.h
2218# End Source File 2246# End Source File
2219# Begin Source File 2247# Begin Source File
2220 2248
@@ -2993,6 +3021,10 @@ SOURCE=..\..\IStream.h
2993# End Source File 3021# End Source File
2994# Begin Source File 3022# Begin Source File
2995 3023
3024SOURCE=..\..\MyVersion.h
3025# End Source File
3026# Begin Source File
3027
2996SOURCE=..\..\PropID.h 3028SOURCE=..\..\PropID.h
2997# End Source File 3029# End Source File
2998# End Group 3030# End Group
@@ -3037,6 +3069,14 @@ SOURCE=..\..\..\Windows\FileName.h
3037# End Source File 3069# End Source File
3038# Begin Source File 3070# Begin Source File
3039 3071
3072SOURCE=..\..\..\Windows\Handle.h
3073# End Source File
3074# Begin Source File
3075
3076SOURCE=..\..\..\Windows\NtCheck.h
3077# End Source File
3078# Begin Source File
3079
3040SOURCE=..\..\..\Windows\PropVariant.cpp 3080SOURCE=..\..\..\Windows\PropVariant.cpp
3041# End Source File 3081# End Source File
3042# Begin Source File 3082# Begin Source File
diff --git a/CPP/7zip/Bundles/Format7zF/StdAfx.h b/CPP/7zip/Bundles/Format7zF/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Format7zF/StdAfx.h
+++ b/CPP/7zip/Bundles/Format7zF/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Format7zF/makefile b/CPP/7zip/Bundles/Format7zF/makefile
index 97318dc..3487596 100644
--- a/CPP/7zip/Bundles/Format7zF/makefile
+++ b/CPP/7zip/Bundles/Format7zF/makefile
@@ -1,10 +1,11 @@
1PROG = 7z.dll 1PROG = 7z.dll
2# USE_C_LZFINDOPT = 1
2DEF_FILE = ../../Archive/Archive2.def 3DEF_FILE = ../../Archive/Archive2.def
3CFLAGS = $(CFLAGS) \ 4CFLAGS = $(CFLAGS) \
4 -DEXTERNAL_CODECS \ 5 -DZ7_EXTERNAL_CODECS \
5 6
6!IFNDEF UNDER_CE 7!IFNDEF UNDER_CE
7CFLAGS = $(CFLAGS) -D_7ZIP_LARGE_PAGES 8CFLAGS = $(CFLAGS) -DZ7_LARGE_PAGES
8!ENDIF 9!ENDIF
9 10
10!include "Arc.mak" 11!include "Arc.mak"
diff --git a/CPP/7zip/Bundles/Format7zF/makefile.gcc b/CPP/7zip/Bundles/Format7zF/makefile.gcc
index e468d7c..fc65795 100644
--- a/CPP/7zip/Bundles/Format7zF/makefile.gcc
+++ b/CPP/7zip/Bundles/Format7zF/makefile.gcc
@@ -20,7 +20,7 @@ endif
20ifdef IS_MINGW 20ifdef IS_MINGW
21 21
22LOCAL_FLAGS_WIN = \ 22LOCAL_FLAGS_WIN = \
23 -D_7ZIP_LARGE_PAGES \ 23 -DZ7_LARGE_PAGES \
24 $(LOCAL_FLAGS_ST) \ 24 $(LOCAL_FLAGS_ST) \
25 25
26SYS_OBJS = \ 26SYS_OBJS = \
@@ -34,7 +34,7 @@ SYS_OBJS = \
34endif 34endif
35 35
36LOCAL_FLAGS = \ 36LOCAL_FLAGS = \
37 -DEXTERNAL_CODECS \ 37 -DZ7_EXTERNAL_CODECS \
38 $(LOCAL_FLAGS_WIN) \ 38 $(LOCAL_FLAGS_WIN) \
39 $(LOCAL_FLAGS_ST) \ 39 $(LOCAL_FLAGS_ST) \
40 40
diff --git a/CPP/7zip/Bundles/Format7zR/StdAfx.h b/CPP/7zip/Bundles/Format7zR/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/Format7zR/StdAfx.h
+++ b/CPP/7zip/Bundles/Format7zR/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/Format7zR/makefile b/CPP/7zip/Bundles/Format7zR/makefile
index c223715..2449755 100644
--- a/CPP/7zip/Bundles/Format7zR/makefile
+++ b/CPP/7zip/Bundles/Format7zR/makefile
@@ -1,7 +1,7 @@
1PROG = 7zra.dll 1PROG = 7zra.dll
2DEF_FILE = ../../Archive/Archive2.def 2DEF_FILE = ../../Archive/Archive2.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -D_NO_CRYPTO 4 -DZ7_NO_CRYPTO
5 5
6COMMON_OBJS = \ 6COMMON_OBJS = \
7 $O\CRC.obj \ 7 $O\CRC.obj \
@@ -92,6 +92,7 @@ COMPRESS_OBJS = \
92 $O\LzmaRegister.obj \ 92 $O\LzmaRegister.obj \
93 93
94C_OBJS = \ 94C_OBJS = \
95 $O\7zStream.obj \
95 $O\Alloc.obj \ 96 $O\Alloc.obj \
96 $O\Bcj2.obj \ 97 $O\Bcj2.obj \
97 $O\Bcj2Enc.obj \ 98 $O\Bcj2Enc.obj \
@@ -109,6 +110,7 @@ C_OBJS = \
109 $O\LzmaEnc.obj \ 110 $O\LzmaEnc.obj \
110 $O\MtCoder.obj \ 111 $O\MtCoder.obj \
111 $O\MtDec.obj \ 112 $O\MtDec.obj \
113 $O\SwapBytes.obj \
112 $O\Threads.obj \ 114 $O\Threads.obj \
113 115
114!include "../../Crc.mak" 116!include "../../Crc.mak"
diff --git a/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp b/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp
index 71436f6..ac1334f 100644
--- a/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp
+++ b/CPP/7zip/Bundles/LzmaCon/LzmaAlone.cpp
@@ -1,11 +1,9 @@
1// LzmaAlone.cpp 1 // LzmaAlone.cpp
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5// #include <stdio.h> 5// #include <stdio.h>
6 6
7#include "../../../../C/CpuArch.h"
8
9#if (defined(_WIN32) || defined(OS2) || defined(MSDOS)) && !defined(UNDER_CE) 7#if (defined(_WIN32) || defined(OS2) || defined(MSDOS)) && !defined(UNDER_CE)
10#include <fcntl.h> 8#include <fcntl.h>
11#include <io.h> 9#include <io.h>
@@ -14,16 +12,17 @@
14#define MY_SET_BINARY_MODE(file) 12#define MY_SET_BINARY_MODE(file)
15#endif 13#endif
16 14
17#include "../../../Common/MyWindows.h" 15#include "../../../../C/CpuArch.h"
18#include "../../../Common/MyInitGuid.h"
19
20#include "../../../../C/7zVersion.h" 16#include "../../../../C/7zVersion.h"
21#include "../../../../C/Alloc.h" 17#include "../../../../C/Alloc.h"
22#include "../../../../C/Lzma86.h" 18#include "../../../../C/Lzma86.h"
23 19
20#include "../../../Common/MyWindows.h"
21#include "../../../Common/MyInitGuid.h"
22
24#include "../../../Windows/NtCheck.h" 23#include "../../../Windows/NtCheck.h"
25 24
26#ifndef _7ZIP_ST 25#ifndef Z7_ST
27#include "../../../Windows/System.h" 26#include "../../../Windows/System.h"
28#endif 27#endif
29 28
@@ -41,6 +40,8 @@
41#include "../../UI/Console/BenchCon.h" 40#include "../../UI/Console/BenchCon.h"
42#include "../../UI/Console/ConsoleClose.h" 41#include "../../UI/Console/ConsoleClose.h"
43 42
43extern
44bool g_LargePagesMode;
44bool g_LargePagesMode = false; 45bool g_LargePagesMode = false;
45 46
46using namespace NCommandLineParser; 47using namespace NCommandLineParser;
@@ -219,20 +220,17 @@ static void PrintHelp()
219 Print(kHelpString); 220 Print(kHelpString);
220} 221}
221 222
222class CProgressPrint: 223
223 public ICompressProgressInfo, 224Z7_CLASS_IMP_COM_1(
224 public CMyUnknownImp 225 CProgressPrint,
225{ 226 ICompressProgressInfo
227)
226 UInt64 _size1; 228 UInt64 _size1;
227 UInt64 _size2; 229 UInt64 _size2;
228public: 230public:
229 CProgressPrint(): _size1(0), _size2(0) {} 231 CProgressPrint(): _size1(0), _size2(0) {}
230 232
231 void ClosePrint(); 233 void ClosePrint();
232
233 MY_UNKNOWN_IMP1(ICompressProgressInfo)
234
235 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
236}; 234};
237 235
238#define BACK_STR \ 236#define BACK_STR \
@@ -248,7 +246,7 @@ void CProgressPrint::ClosePrint()
248 Print(kBackSpaces); 246 Print(kBackSpaces);
249} 247}
250 248
251STDMETHODIMP CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 249Z7_COM7F_IMF(CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
252{ 250{
253 if (NConsoleClose::TestBreakSignal()) 251 if (NConsoleClose::TestBreakSignal())
254 return E_ABORT; 252 return E_ABORT;
@@ -272,7 +270,7 @@ STDMETHODIMP CProgressPrint::SetRatioInfo(const UInt64 *inSize, const UInt64 *ou
272} 270}
273 271
274 272
275MY_ATTR_NORETURN 273Z7_ATTR_NORETURN
276static void IncorrectCommand() 274static void IncorrectCommand()
277{ 275{
278 throw "Incorrect command"; 276 throw "Incorrect command";
@@ -316,7 +314,7 @@ static int Error_HRESULT(const char *s, HRESULT res)
316 else 314 else
317 { 315 {
318 char temp[32]; 316 char temp[32];
319 ConvertUInt32ToHex(res, temp); 317 ConvertUInt32ToHex((UInt32)res, temp);
320 PrintErr("Error code = 0x"); 318 PrintErr("Error code = 0x");
321 PrintErr_LF(temp); 319 PrintErr_LF(temp);
322 } 320 }
@@ -357,7 +355,7 @@ static int main2(int numArgs, const char *args[])
357 CParser parser; 355 CParser parser;
358 try 356 try
359 { 357 {
360 if (!parser.ParseStrings(kSwitchForms, ARRAY_SIZE(kSwitchForms), commandStrings)) 358 if (!parser.ParseStrings(kSwitchForms, Z7_ARRAY_SIZE(kSwitchForms), commandStrings))
361 { 359 {
362 PrintError2(parser.ErrorMessage, parser.ErrorLine); 360 PrintError2(parser.ErrorMessage, parser.ErrorLine);
363 return 1; 361 return 1;
@@ -414,7 +412,7 @@ static int main2(int numArgs, const char *args[])
414 412
415 UInt32 numThreads = (UInt32)(Int32)-1; 413 UInt32 numThreads = (UInt32)(Int32)-1;
416 414
417 #ifndef _7ZIP_ST 415 #ifndef Z7_ST
418 416
419 if (parser[NKey::kMultiThread].ThereIs) 417 if (parser[NKey::kMultiThread].ThereIs)
420 { 418 {
@@ -676,7 +674,7 @@ static int main2(int numArgs, const char *args[])
676 NCoderPropID::kMatchFinderCycles, 674 NCoderPropID::kMatchFinderCycles,
677 }; 675 };
678 676
679 const unsigned kNumPropsMax = ARRAY_SIZE(propIDs); 677 const unsigned kNumPropsMax = Z7_ARRAY_SIZE(propIDs);
680 678
681 PROPVARIANT props[kNumPropsMax]; 679 PROPVARIANT props[kNumPropsMax];
682 for (int p = 0; p < 6; p++) 680 for (int p = 0; p < 6; p++)
@@ -757,7 +755,7 @@ static int main2(int numArgs, const char *args[])
757 throw "SetDecoderProperties error"; 755 throw "SetDecoderProperties error";
758 756
759 UInt64 unpackSize = 0; 757 UInt64 unpackSize = 0;
760 for (int i = 0; i < 8; i++) 758 for (unsigned i = 0; i < 8; i++)
761 unpackSize |= ((UInt64)header[kPropertiesSize + i]) << (8 * i); 759 unpackSize |= ((UInt64)header[kPropertiesSize + i]) << (8 * i);
762 760
763 bool unpackSizeDefined = (unpackSize != (UInt64)(Int64)-1); 761 bool unpackSizeDefined = (unpackSize != (UInt64)(Int64)-1);
@@ -792,7 +790,7 @@ static int main2(int numArgs, const char *args[])
792 return 0; 790 return 0;
793} 791}
794 792
795int MY_CDECL main(int numArgs, const char *args[]) 793int Z7_CDECL main(int numArgs, const char *args[])
796{ 794{
797 NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter; 795 NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter;
798 796
diff --git a/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp b/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp
index d7326ef..5a8911b 100644
--- a/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp
+++ b/CPP/7zip/Bundles/LzmaCon/LzmaCon.dsp
@@ -132,6 +132,10 @@ SOURCE=..\..\..\Windows\FileIO.h
132# End Source File 132# End Source File
133# Begin Source File 133# Begin Source File
134 134
135SOURCE=..\..\..\Windows\NtCheck.h
136# End Source File
137# Begin Source File
138
135SOURCE=..\..\..\Windows\PropVariant.cpp 139SOURCE=..\..\..\Windows\PropVariant.cpp
136# End Source File 140# End Source File
137# Begin Source File 141# Begin Source File
@@ -148,14 +152,6 @@ SOURCE=..\..\..\Windows\Registry.h
148# End Source File 152# End Source File
149# Begin Source File 153# Begin Source File
150 154
151SOURCE=..\..\..\Windows\Synchronization.cpp
152# End Source File
153# Begin Source File
154
155SOURCE=..\..\..\Windows\Synchronization.h
156# End Source File
157# Begin Source File
158
159SOURCE=..\..\..\Windows\System.cpp 155SOURCE=..\..\..\Windows\System.cpp
160# End Source File 156# End Source File
161# Begin Source File 157# Begin Source File
@@ -188,6 +184,10 @@ SOURCE=..\..\..\Common\CommandLineParser.h
188# End Source File 184# End Source File
189# Begin Source File 185# Begin Source File
190 186
187SOURCE=..\..\..\Common\Common.h
188# End Source File
189# Begin Source File
190
191SOURCE=..\..\..\Common\ComTry.h 191SOURCE=..\..\..\Common\ComTry.h
192# End Source File 192# End Source File
193# Begin Source File 193# Begin Source File
@@ -216,10 +216,26 @@ SOURCE=..\..\..\Common\LzFindPrepare.cpp
216# End Source File 216# End Source File
217# Begin Source File 217# Begin Source File
218 218
219SOURCE=..\..\..\Common\MyBuffer.h
220# End Source File
221# Begin Source File
222
223SOURCE=..\..\..\Common\MyBuffer2.h
224# End Source File
225# Begin Source File
226
219SOURCE=..\..\..\Common\MyCom.h 227SOURCE=..\..\..\Common\MyCom.h
220# End Source File 228# End Source File
221# Begin Source File 229# Begin Source File
222 230
231SOURCE=..\..\..\Common\MyInitGuid.h
232# End Source File
233# Begin Source File
234
235SOURCE=..\..\..\Common\MyLinux.h
236# End Source File
237# Begin Source File
238
223SOURCE=..\..\..\Common\MyString.cpp 239SOURCE=..\..\..\Common\MyString.cpp
224# End Source File 240# End Source File
225# Begin Source File 241# Begin Source File
@@ -228,6 +244,10 @@ SOURCE=..\..\..\Common\MyString.h
228# End Source File 244# End Source File
229# Begin Source File 245# Begin Source File
230 246
247SOURCE=..\..\..\Common\MyTypes.h
248# End Source File
249# Begin Source File
250
231SOURCE=..\..\..\Common\MyUnknown.h 251SOURCE=..\..\..\Common\MyUnknown.h
232# End Source File 252# End Source File
233# Begin Source File 253# Begin Source File
@@ -274,6 +294,14 @@ SOURCE=..\..\..\Common\StringToInt.h
274 294
275SOURCE=..\..\..\Common\Types.h 295SOURCE=..\..\..\Common\Types.h
276# End Source File 296# End Source File
297# Begin Source File
298
299SOURCE=..\..\..\Common\Wildcard.cpp
300# End Source File
301# Begin Source File
302
303SOURCE=..\..\..\Common\Wildcard.h
304# End Source File
277# End Group 305# End Group
278# Begin Group "7zip Common" 306# Begin Group "7zip Common"
279 307
@@ -346,14 +374,6 @@ SOURCE=..\..\UI\Common\Bench.cpp
346 374
347SOURCE=..\..\UI\Common\Bench.h 375SOURCE=..\..\UI\Common\Bench.h
348# End Source File 376# End Source File
349# Begin Source File
350
351SOURCE=..\..\UI\Common\LoadCodecs.cpp
352# End Source File
353# Begin Source File
354
355SOURCE=..\..\UI\Common\LoadCodecs.h
356# End Source File
357# End Group 377# End Group
358# Begin Group "Console" 378# Begin Group "Console"
359 379
@@ -398,21 +418,16 @@ SOURCE=..\..\..\..\C\7zTypes.h
398# End Source File 418# End Source File
399# Begin Source File 419# Begin Source File
400 420
401SOURCE=..\..\..\..\C\Alloc.c 421SOURCE=..\..\..\..\C\7zWindows.h
402# SUBTRACT CPP /YX /Yc /Yu
403# End Source File
404# Begin Source File
405
406SOURCE=..\..\..\..\C\Alloc.h
407# End Source File 422# End Source File
408# Begin Source File 423# Begin Source File
409 424
410SOURCE=..\..\..\..\C\Bra.c 425SOURCE=..\..\..\..\C\Alloc.c
411# SUBTRACT CPP /YX /Yc /Yu 426# SUBTRACT CPP /YX /Yc /Yu
412# End Source File 427# End Source File
413# Begin Source File 428# Begin Source File
414 429
415SOURCE=..\..\..\..\C\Bra.h 430SOURCE=..\..\..\..\C\Alloc.h
416# End Source File 431# End Source File
417# Begin Source File 432# Begin Source File
418 433
@@ -421,8 +436,7 @@ SOURCE=..\..\..\..\C\Bra86.c
421# End Source File 436# End Source File
422# Begin Source File 437# Begin Source File
423 438
424SOURCE=..\..\..\..\C\BraIA64.c 439SOURCE=..\..\..\..\C\Compiler.h
425# SUBTRACT CPP /YX /Yc /Yu
426# End Source File 440# End Source File
427# Begin Source File 441# Begin Source File
428 442
@@ -502,6 +516,22 @@ SOURCE=..\..\..\..\C\Threads.c
502SOURCE=..\..\..\..\C\Threads.h 516SOURCE=..\..\..\..\C\Threads.h
503# End Source File 517# End Source File
504# End Group 518# End Group
519# Begin Group "7zip"
520
521# PROP Default_Filter ""
522# Begin Source File
523
524SOURCE=..\..\ICoder.h
525# End Source File
526# Begin Source File
527
528SOURCE=..\..\IDecl.h
529# End Source File
530# Begin Source File
531
532SOURCE=..\..\IProgress.h
533# End Source File
534# End Group
505# Begin Source File 535# Begin Source File
506 536
507SOURCE=.\LzmaAlone.cpp 537SOURCE=.\LzmaAlone.cpp
diff --git a/CPP/7zip/Bundles/LzmaCon/StdAfx.h b/CPP/7zip/Bundles/LzmaCon/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/LzmaCon/StdAfx.h
+++ b/CPP/7zip/Bundles/LzmaCon/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/LzmaCon/makefile b/CPP/7zip/Bundles/LzmaCon/makefile
index 5e53327..f303c31 100644
--- a/CPP/7zip/Bundles/LzmaCon/makefile
+++ b/CPP/7zip/Bundles/LzmaCon/makefile
@@ -1,6 +1,9 @@
1PROG = lzma.exe 1PROG = lzma.exe
2MY_CONSOLE = 1 2MY_CONSOLE = 1
3 3
4# CFLAGS = $(CFLAGS) -DZ7_ST
5
6
4CURRENT_OBJS = \ 7CURRENT_OBJS = \
5 $O\LzmaAlone.obj \ 8 $O\LzmaAlone.obj \
6 9
@@ -20,6 +23,7 @@ COMMON_OBJS = \
20 $O\NewHandler.obj \ 23 $O\NewHandler.obj \
21 $O\StringConvert.obj \ 24 $O\StringConvert.obj \
22 $O\StringToInt.obj \ 25 $O\StringToInt.obj \
26 $O\Wildcard.obj \
23 27
24WIN_OBJS = \ 28WIN_OBJS = \
25 $O\FileIO.obj \ 29 $O\FileIO.obj \
diff --git a/CPP/7zip/Bundles/LzmaCon/makefile.gcc b/CPP/7zip/Bundles/LzmaCon/makefile.gcc
index e45ebb6..dd19a0e 100644
--- a/CPP/7zip/Bundles/LzmaCon/makefile.gcc
+++ b/CPP/7zip/Bundles/LzmaCon/makefile.gcc
@@ -21,7 +21,7 @@ endif
21 21
22ifdef ST_MODE 22ifdef ST_MODE
23 23
24LOCAL_FLAGS_ST = -D_7ZIP_ST 24LOCAL_FLAGS_ST = -DZ7_ST
25 25
26else 26else
27 27
@@ -72,6 +72,7 @@ COMMON_OBJS = \
72 $O/StringConvert.o \ 72 $O/StringConvert.o \
73 $O/StringToInt.o \ 73 $O/StringToInt.o \
74 $O/UTFConvert.o \ 74 $O/UTFConvert.o \
75 $O/Wildcard.o \
75 76
76WIN_OBJS = \ 77WIN_OBJS = \
77 $O/FileIO.o \ 78 $O/FileIO.o \
@@ -110,7 +111,7 @@ C_OBJS = \
110 $O/Lzma86Enc.o \ 111 $O/Lzma86Enc.o \
111 112
112OBJS = \ 113OBJS = \
113 $(LZMA_DEC_OPT_OBJS) \ 114 $(LZMA_DEC_OPT_OBJS) \
114 $(C_OBJS) \ 115 $(C_OBJS) \
115 $(MT_OBJS) \ 116 $(MT_OBJS) \
116 $(SYS_OBJS) \ 117 $(SYS_OBJS) \
diff --git a/CPP/7zip/Bundles/SFXCon/SFXCon.dsp b/CPP/7zip/Bundles/SFXCon/SFXCon.dsp
index 87e27c4..1bb063d 100644
--- a/CPP/7zip/Bundles/SFXCon/SFXCon.dsp
+++ b/CPP/7zip/Bundles/SFXCon/SFXCon.dsp
@@ -42,7 +42,7 @@ RSC=rc.exe
42# PROP Ignore_Export_Lib 0 42# PROP Ignore_Export_Lib 0
43# PROP Target_Dir "" 43# PROP Target_Dir ""
44# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c 44# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
45# 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 45# 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
46# ADD BASE RSC /l 0x419 /d "NDEBUG" 46# ADD BASE RSC /l 0x419 /d "NDEBUG"
47# ADD RSC /l 0x419 /d "NDEBUG" 47# ADD RSC /l 0x419 /d "NDEBUG"
48BSC32=bscmake.exe 48BSC32=bscmake.exe
@@ -67,7 +67,7 @@ LINK32=link.exe
67# PROP Ignore_Export_Lib 0 67# PROP Ignore_Export_Lib 0
68# PROP Target_Dir "" 68# PROP Target_Dir ""
69# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c 69# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
70# 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 70# 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
71# ADD BASE RSC /l 0x419 /d "_DEBUG" 71# ADD BASE RSC /l 0x419 /d "_DEBUG"
72# ADD RSC /l 0x419 /d "_DEBUG" 72# ADD RSC /l 0x419 /d "_DEBUG"
73BSC32=bscmake.exe 73BSC32=bscmake.exe
@@ -257,6 +257,10 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp
257# End Source File 257# End Source File
258# Begin Source File 258# Begin Source File
259 259
260SOURCE=..\..\Compress\Bcj2Coder.h
261# End Source File
262# Begin Source File
263
260SOURCE=..\..\Compress\Bcj2Register.cpp 264SOURCE=..\..\Compress\Bcj2Register.cpp
261# End Source File 265# End Source File
262# Begin Source File 266# Begin Source File
@@ -265,6 +269,10 @@ SOURCE=..\..\Compress\BcjCoder.cpp
265# End Source File 269# End Source File
266# Begin Source File 270# Begin Source File
267 271
272SOURCE=..\..\Compress\BcjCoder.h
273# End Source File
274# Begin Source File
275
268SOURCE=..\..\Compress\BcjRegister.cpp 276SOURCE=..\..\Compress\BcjRegister.cpp
269# End Source File 277# End Source File
270# Begin Source File 278# Begin Source File
@@ -285,6 +293,10 @@ SOURCE=..\..\Compress\CopyCoder.cpp
285# End Source File 293# End Source File
286# Begin Source File 294# Begin Source File
287 295
296SOURCE=..\..\Compress\CopyCoder.h
297# End Source File
298# Begin Source File
299
288SOURCE=..\..\Compress\CopyRegister.cpp 300SOURCE=..\..\Compress\CopyRegister.cpp
289# End Source File 301# End Source File
290# Begin Source File 302# Begin Source File
@@ -309,6 +321,10 @@ SOURCE=..\..\Compress\LzmaDecoder.cpp
309# End Source File 321# End Source File
310# Begin Source File 322# Begin Source File
311 323
324SOURCE=..\..\Compress\LzmaDecoder.h
325# End Source File
326# Begin Source File
327
312SOURCE=..\..\Compress\LzmaRegister.cpp 328SOURCE=..\..\Compress\LzmaRegister.cpp
313# End Source File 329# End Source File
314# Begin Source File 330# Begin Source File
@@ -317,6 +333,10 @@ SOURCE=..\..\Compress\PpmdDecoder.cpp
317# End Source File 333# End Source File
318# Begin Source File 334# Begin Source File
319 335
336SOURCE=..\..\Compress\PpmdDecoder.h
337# End Source File
338# Begin Source File
339
320SOURCE=..\..\Compress\PpmdRegister.cpp 340SOURCE=..\..\Compress\PpmdRegister.cpp
321# End Source File 341# End Source File
322# End Group 342# End Group
@@ -441,6 +461,10 @@ SOURCE=..\..\..\Common\CommandLineParser.h
441# End Source File 461# End Source File
442# Begin Source File 462# Begin Source File
443 463
464SOURCE=..\..\..\Common\Common.h
465# End Source File
466# Begin Source File
467
444SOURCE=..\..\..\Common\CRC.cpp 468SOURCE=..\..\..\Common\CRC.cpp
445# End Source File 469# End Source File
446# Begin Source File 470# Begin Source File
@@ -457,6 +481,18 @@ SOURCE=..\..\..\Common\IntToString.h
457# End Source File 481# End Source File
458# Begin Source File 482# Begin Source File
459 483
484SOURCE=..\..\..\Common\MyBuffer.h
485# End Source File
486# Begin Source File
487
488SOURCE=..\..\..\Common\MyBuffer2.h
489# End Source File
490# Begin Source File
491
492SOURCE=..\..\..\Common\MyCom.h
493# End Source File
494# Begin Source File
495
460SOURCE=..\..\..\Common\MyString.cpp 496SOURCE=..\..\..\Common\MyString.cpp
461# End Source File 497# End Source File
462# Begin Source File 498# Begin Source File
@@ -759,6 +795,19 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c
759# End Source File 795# End Source File
760# Begin Source File 796# Begin Source File
761 797
798SOURCE=..\..\..\..\C\7zStream.c
799# SUBTRACT CPP /YX /Yc /Yu
800# End Source File
801# Begin Source File
802
803SOURCE=..\..\..\..\C\7zTypes.h
804# End Source File
805# Begin Source File
806
807SOURCE=..\..\..\..\C\7zWindows.h
808# End Source File
809# Begin Source File
810
762SOURCE=..\..\..\..\C\Aes.c 811SOURCE=..\..\..\..\C\Aes.c
763# SUBTRACT CPP /YX /Yc /Yu 812# SUBTRACT CPP /YX /Yc /Yu
764# End Source File 813# End Source File
@@ -810,11 +859,19 @@ SOURCE=..\..\..\..\C\BraIA64.c
810# End Source File 859# End Source File
811# Begin Source File 860# Begin Source File
812 861
862SOURCE=..\..\..\..\C\Compiler.h
863# End Source File
864# Begin Source File
865
813SOURCE=..\..\..\..\C\CpuArch.c 866SOURCE=..\..\..\..\C\CpuArch.c
814# SUBTRACT CPP /YX /Yc /Yu 867# SUBTRACT CPP /YX /Yc /Yu
815# End Source File 868# End Source File
816# Begin Source File 869# Begin Source File
817 870
871SOURCE=..\..\..\..\C\CpuArch.h
872# End Source File
873# Begin Source File
874
818SOURCE=..\..\..\..\C\Delta.c 875SOURCE=..\..\..\..\C\Delta.c
819# SUBTRACT CPP /YX /Yc /Yu 876# SUBTRACT CPP /YX /Yc /Yu
820# End Source File 877# End Source File
@@ -825,7 +882,18 @@ SOURCE=..\..\..\..\C\Delta.h
825# Begin Source File 882# Begin Source File
826 883
827SOURCE=..\..\..\..\C\DllSecur.c 884SOURCE=..\..\..\..\C\DllSecur.c
885
886!IF "$(CFG)" == "SFXCon - Win32 Release"
887
888# ADD CPP /O2
889# SUBTRACT CPP /YX /Yc /Yu
890
891!ELSEIF "$(CFG)" == "SFXCon - Win32 Debug"
892
828# SUBTRACT CPP /YX /Yc /Yu 893# SUBTRACT CPP /YX /Yc /Yu
894
895!ENDIF
896
829# End Source File 897# End Source File
830# Begin Source File 898# Begin Source File
831 899
@@ -905,13 +973,33 @@ SOURCE=..\..\..\..\C\Threads.c
905SOURCE=..\..\..\..\C\Threads.h 973SOURCE=..\..\..\..\C\Threads.h
906# End Source File 974# End Source File
907# End Group 975# End Group
976# Begin Group "7zip"
977
978# PROP Default_Filter ""
908# Begin Source File 979# Begin Source File
909 980
910SOURCE=.\7z.ico 981SOURCE=..\..\Archive\IArchive.h
911# End Source File 982# End Source File
912# Begin Source File 983# Begin Source File
913 984
914SOURCE=..\..\Archive\IArchive.h 985SOURCE=..\..\ICoder.h
986# End Source File
987# Begin Source File
988
989SOURCE=..\..\IDecl.h
990# End Source File
991# Begin Source File
992
993SOURCE=..\..\IPassword.h
994# End Source File
995# Begin Source File
996
997SOURCE=..\..\IProgress.h
998# End Source File
999# End Group
1000# Begin Source File
1001
1002SOURCE=.\7z.ico
915# End Source File 1003# End Source File
916# Begin Source File 1004# Begin Source File
917 1005
diff --git a/CPP/7zip/Bundles/SFXCon/SfxCon.cpp b/CPP/7zip/Bundles/SFXCon/SfxCon.cpp
index cfa1ee7..cfce24d 100644
--- a/CPP/7zip/Bundles/SFXCon/SfxCon.cpp
+++ b/CPP/7zip/Bundles/SFXCon/SfxCon.cpp
@@ -3,9 +3,9 @@
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../../C/CpuArch.h" 5#include "../../../../C/CpuArch.h"
6#include "../../../../C/DllSecur.h"
6 7
7#include "../../../Common/MyWindows.h" 8#include "../../../Common/MyWindows.h"
8
9#include "../../../Common/MyInitGuid.h" 9#include "../../../Common/MyInitGuid.h"
10 10
11#include "../../../Common/CommandLineParser.h" 11#include "../../../Common/CommandLineParser.h"
@@ -28,7 +28,6 @@
28 28
29#include "../../MyVersion.h" 29#include "../../MyVersion.h"
30 30
31#include "../../../../C/DllSecur.h"
32 31
33using namespace NWindows; 32using namespace NWindows;
34using namespace NFile; 33using namespace NFile;
@@ -36,8 +35,12 @@ using namespace NDir;
36using namespace NCommandLineParser; 35using namespace NCommandLineParser;
37 36
38#ifdef _WIN32 37#ifdef _WIN32
39HINSTANCE g_hInstance = 0; 38extern
39HINSTANCE g_hInstance;
40HINSTANCE g_hInstance = NULL;
40#endif 41#endif
42extern
43int g_CodePage;
41int g_CodePage = -1; 44int g_CodePage = -1;
42extern CStdOutStream *g_StdStream; 45extern CStdOutStream *g_StdStream;
43 46
@@ -184,14 +187,14 @@ static void PrintHelp(void)
184 g_StdOut << kHelpString; 187 g_StdOut << kHelpString;
185} 188}
186 189
187MY_ATTR_NORETURN 190Z7_ATTR_NORETURN
188static void ShowMessageAndThrowException(const char *message, NExitCode::EEnum code) 191static void ShowMessageAndThrowException(const char *message, NExitCode::EEnum code)
189{ 192{
190 g_StdOut << message << endl; 193 g_StdOut << message << endl;
191 throw code; 194 throw code;
192} 195}
193 196
194MY_ATTR_NORETURN 197Z7_ATTR_NORETURN
195static void PrintHelpAndExit() // yyy 198static void PrintHelpAndExit() // yyy
196{ 199{
197 PrintHelp(); 200 PrintHelp();
@@ -370,12 +373,12 @@ int Main2(
370 } 373 }
371 } 374 }
372 375
373 bool yesToAll = parser[NKey::kYes].ThereIs; 376 const bool yesToAll = parser[NKey::kYes].ThereIs;
374 377
375 // NExtractMode::EEnum extractMode; 378 // NExtractMode::EEnum extractMode;
376 // bool isExtractGroupCommand = command.IsFromExtractGroup(extractMode); 379 // bool isExtractGroupCommand = command.IsFromExtractGroup(extractMode);
377 380
378 bool passwordEnabled = parser[NKey::kPassword].ThereIs; 381 const bool passwordEnabled = parser[NKey::kPassword].ThereIs;
379 382
380 UString password; 383 UString password;
381 if (passwordEnabled) 384 if (passwordEnabled)
@@ -403,7 +406,7 @@ int Main2(
403 406
404 CCodecs *codecs = new CCodecs; 407 CCodecs *codecs = new CCodecs;
405 CMyComPtr< 408 CMyComPtr<
406 #ifdef EXTERNAL_CODECS 409 #ifdef Z7_EXTERNAL_CODECS
407 ICompressCodecsInfo 410 ICompressCodecsInfo
408 #else 411 #else
409 IUnknown 412 IUnknown
@@ -421,7 +424,7 @@ int Main2(
421 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs; 424 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs;
422 ecs->Init(g_StdStream, &g_StdErr, g_StdStream); 425 ecs->Init(g_StdStream, &g_StdErr, g_StdStream);
423 426
424 #ifndef _NO_CRYPTO 427 #ifndef Z7_NO_CRYPTO
425 ecs->PasswordIsDefined = passwordEnabled; 428 ecs->PasswordIsDefined = passwordEnabled;
426 ecs->Password = password; 429 ecs->Password = password;
427 #endif 430 #endif
@@ -430,7 +433,7 @@ int Main2(
430 COpenCallbackConsole openCallback; 433 COpenCallbackConsole openCallback;
431 openCallback.Init(g_StdStream, g_StdStream); 434 openCallback.Init(g_StdStream, g_StdStream);
432 435
433 #ifndef _NO_CRYPTO 436 #ifndef Z7_NO_CRYPTO
434 openCallback.PasswordIsDefined = passwordEnabled; 437 openCallback.PasswordIsDefined = passwordEnabled;
435 openCallback.Password = password; 438 openCallback.Password = password;
436 #endif 439 #endif
@@ -452,22 +455,33 @@ int Main2(
452 codecs, CObjectVector<COpenType>(), CIntVector(), 455 codecs, CObjectVector<COpenType>(), CIntVector(),
453 v1, v2, 456 v1, v2,
454 wildcardCensorHead, 457 wildcardCensorHead,
455 eo, ecs, ecs, 458 eo,
459 ecs, ecs, ecs,
456 // NULL, // hash 460 // NULL, // hash
457 errorMessage, stat); 461 errorMessage, stat);
462
463 ecs->ClosePercents();
464
458 if (!errorMessage.IsEmpty()) 465 if (!errorMessage.IsEmpty())
459 { 466 {
460 (*g_StdStream) << endl << "Error: " << errorMessage;; 467 (*g_StdStream) << endl << "Error: " << errorMessage;
461 if (result == S_OK) 468 if (result == S_OK)
462 result = E_FAIL; 469 result = E_FAIL;
463 } 470 }
464 471
465 if (ecs->NumArcsWithError != 0 || ecs->NumFileErrors != 0) 472 if ( 0 != ecs->NumCantOpenArcs
473 || 0 != ecs->NumArcsWithError
474 || 0 != ecs->NumFileErrors
475 || 0 != ecs->NumOpenArcErrors)
466 { 476 {
477 if (ecs->NumCantOpenArcs != 0)
478 (*g_StdStream) << endl << "Can't open as archive" << endl;
467 if (ecs->NumArcsWithError != 0) 479 if (ecs->NumArcsWithError != 0)
468 (*g_StdStream) << endl << "Archive Errors" << endl; 480 (*g_StdStream) << endl << "Archive Errors" << endl;
469 if (ecs->NumFileErrors != 0) 481 if (ecs->NumFileErrors != 0)
470 (*g_StdStream) << endl << "Sub items Errors: " << ecs->NumFileErrors << endl; 482 (*g_StdStream) << endl << "Sub items Errors: " << ecs->NumFileErrors << endl;
483 if (ecs->NumOpenArcErrors != 0)
484 (*g_StdStream) << endl << "Open Errors: " << ecs->NumOpenArcErrors << endl;
471 return NExitCode::kFatalError; 485 return NExitCode::kFatalError;
472 } 486 }
473 if (result != S_OK) 487 if (result != S_OK)
@@ -489,7 +503,7 @@ int Main2(
489 wildcardCensorHead, 503 wildcardCensorHead,
490 true, // enableHeaders 504 true, // enableHeaders
491 false, // techMode 505 false, // techMode
492 #ifndef _NO_CRYPTO 506 #ifndef Z7_NO_CRYPTO
493 passwordEnabled, password, 507 passwordEnabled, password,
494 #endif 508 #endif
495 numErrors, numWarnings); 509 numErrors, numWarnings);
diff --git a/CPP/7zip/Bundles/SFXCon/StdAfx.h b/CPP/7zip/Bundles/SFXCon/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/Bundles/SFXCon/StdAfx.h
+++ b/CPP/7zip/Bundles/SFXCon/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Bundles/SFXCon/makefile b/CPP/7zip/Bundles/SFXCon/makefile
index 633bd77..51aaf51 100644
--- a/CPP/7zip/Bundles/SFXCon/makefile
+++ b/CPP/7zip/Bundles/SFXCon/makefile
@@ -3,9 +3,9 @@ MY_CONSOLE = 1
3MY_FIXED = 1 3MY_FIXED = 1
4 4
5CFLAGS = $(CFLAGS) \ 5CFLAGS = $(CFLAGS) \
6 -DEXTRACT_ONLY \ 6 -DZ7_EXTRACT_ONLY \
7 -DNO_READ_FROM_CODER \ 7 -DZ7_NO_READ_FROM_CODER \
8 -D_SFX \ 8 -DZ7_SFX \
9 9
10CURRENT_OBJS = \ 10CURRENT_OBJS = \
11 $O\SfxCon.obj \ 11 $O\SfxCon.obj \
@@ -109,6 +109,7 @@ CRYPTO_OBJS = \
109 $O\MyAes.obj \ 109 $O\MyAes.obj \
110 110
111C_OBJS = \ 111C_OBJS = \
112 $O\7zStream.obj \
112 $O\Alloc.obj \ 113 $O\Alloc.obj \
113 $O\Bcj2.obj \ 114 $O\Bcj2.obj \
114 $O\Bra.obj \ 115 $O\Bra.obj \
diff --git a/CPP/7zip/Bundles/SFXCon/makefile.gcc b/CPP/7zip/Bundles/SFXCon/makefile.gcc
index 551b3e1..9278502 100644
--- a/CPP/7zip/Bundles/SFXCon/makefile.gcc
+++ b/CPP/7zip/Bundles/SFXCon/makefile.gcc
@@ -22,7 +22,7 @@ endif
22 22
23ifdef ST_MODE 23ifdef ST_MODE
24 24
25LOCAL_FLAGS_ST = -D_7ZIP_ST 25LOCAL_FLAGS_ST = -DZ7_ST
26 26
27ifdef IS_MINGW 27ifdef IS_MINGW
28MT_OBJS = \ 28MT_OBJS = \
@@ -63,9 +63,9 @@ endif
63LOCAL_FLAGS = \ 63LOCAL_FLAGS = \
64 $(LOCAL_FLAGS_ST) \ 64 $(LOCAL_FLAGS_ST) \
65 $(LOCAL_FLAGS_SYS) \ 65 $(LOCAL_FLAGS_SYS) \
66 -DEXTRACT_ONLY \ 66 -DZ7_EXTRACT_ONLY \
67 -DNO_READ_FROM_CODER \ 67 -DZ7_NO_READ_FROM_CODER \
68 -D_SFX \ 68 -DZ7_SFX \
69 69
70 70
71CURRENT_OBJS = \ 71CURRENT_OBJS = \
@@ -172,6 +172,7 @@ CRYPTO_OBJS = \
172 $O/MyAes.o \ 172 $O/MyAes.o \
173 173
174C_OBJS = \ 174C_OBJS = \
175 $O/7zStream.o \
175 $O/Alloc.o \ 176 $O/Alloc.o \
176 $O/Bcj2.o \ 177 $O/Bcj2.o \
177 $O/Bra.o \ 178 $O/Bra.o \
@@ -179,7 +180,6 @@ C_OBJS = \
179 $O/BraIA64.o \ 180 $O/BraIA64.o \
180 $O/CpuArch.o \ 181 $O/CpuArch.o \
181 $O/Delta.o \ 182 $O/Delta.o \
182 \
183 $O/Lzma2Dec.o \ 183 $O/Lzma2Dec.o \
184 $O/Lzma2DecMt.o \ 184 $O/Lzma2DecMt.o \
185 $O/LzmaDec.o \ 185 $O/LzmaDec.o \
@@ -194,7 +194,7 @@ C_OBJS = \
194 $O/AesOpt.o \ 194 $O/AesOpt.o \
195 195
196OBJS = \ 196OBJS = \
197 $(LZMA_DEC_OPT_OBJS) \ 197 $(LZMA_DEC_OPT_OBJS) \
198 $(C_OBJS) \ 198 $(C_OBJS) \
199 $(MT_OBJS) \ 199 $(MT_OBJS) \
200 $(SYS_OBJS) \ 200 $(SYS_OBJS) \
diff --git a/CPP/7zip/Bundles/SFXCon/resource.rc b/CPP/7zip/Bundles/SFXCon/resource.rc
index 58331b8..6576212 100644
--- a/CPP/7zip/Bundles/SFXCon/resource.rc
+++ b/CPP/7zip/Bundles/SFXCon/resource.rc
@@ -2,4 +2,8 @@
2 2
3MY_VERSION_INFO_APP("7z Console SFX", "7z.sfx") 3MY_VERSION_INFO_APP("7z Console SFX", "7z.sfx")
4 4
5101 ICON "7z.ico" \ No newline at end of file 5101 ICON "7z.ico"
6
7#ifndef UNDER_CE
81 24 MOVEABLE PURE "../../UI/Console/Console.manifest"
9#endif
diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp
index 8eaeabe..9d632ee 100644
--- a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp
+++ b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.cpp
@@ -63,7 +63,7 @@ HRESULT CExtractCallbackImp::Open_Finished()
63 return S_OK; 63 return S_OK;
64} 64}
65 65
66STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) 66Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 size))
67{ 67{
68 #ifndef _NO_PROGRESS 68 #ifndef _NO_PROGRESS
69 ProgressDialog.Sync.SetProgress(size, 0); 69 ProgressDialog.Sync.SetProgress(size, 0);
@@ -71,10 +71,10 @@ STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size)
71 return S_OK; 71 return S_OK;
72} 72}
73 73
74STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) 74Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *completeValue))
75{ 75{
76 #ifndef _NO_PROGRESS 76 #ifndef _NO_PROGRESS
77 RINOK(ProgressDialog.Sync.ProcessStopAndPause()); 77 RINOK(ProgressDialog.Sync.ProcessStopAndPause())
78 if (completeValue != NULL) 78 if (completeValue != NULL)
79 ProgressDialog.Sync.SetPos(*completeValue); 79 ProgressDialog.Sync.SetPos(*completeValue);
80 #endif 80 #endif
@@ -92,8 +92,8 @@ void CExtractCallbackImp::CreateComplexDirectory(const UStringVector &dirPathPar
92 } 92 }
93} 93}
94 94
95STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index, 95Z7_COM7F_IMF(CExtractCallbackImp::GetStream(UInt32 index,
96 ISequentialOutStream **outStream, Int32 askExtractMode) 96 ISequentialOutStream **outStream, Int32 askExtractMode))
97{ 97{
98 #ifndef _NO_PROGRESS 98 #ifndef _NO_PROGRESS
99 if (ProgressDialog.Sync.GetStopped()) 99 if (ProgressDialog.Sync.GetStopped())
@@ -104,7 +104,7 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index,
104 UString fullPath; 104 UString fullPath;
105 { 105 {
106 NCOM::CPropVariant prop; 106 NCOM::CPropVariant prop;
107 RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)); 107 RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop))
108 if (prop.vt == VT_EMPTY) 108 if (prop.vt == VT_EMPTY)
109 fullPath = _itemDefaultName; 109 fullPath = _itemDefaultName;
110 else 110 else
@@ -119,7 +119,7 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index,
119 if (askExtractMode == NArchive::NExtract::NAskMode::kExtract) 119 if (askExtractMode == NArchive::NExtract::NAskMode::kExtract)
120 { 120 {
121 NCOM::CPropVariant prop; 121 NCOM::CPropVariant prop;
122 RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)); 122 RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop))
123 if (prop.vt == VT_EMPTY) 123 if (prop.vt == VT_EMPTY)
124 _processedFileInfo.Attributes = _defaultAttributes; 124 _processedFileInfo.Attributes = _defaultAttributes;
125 else 125 else
@@ -129,18 +129,18 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index,
129 _processedFileInfo.Attributes = prop.ulVal; 129 _processedFileInfo.Attributes = prop.ulVal;
130 } 130 }
131 131
132 RINOK(_archiveHandler->GetProperty(index, kpidIsDir, &prop)); 132 RINOK(_archiveHandler->GetProperty(index, kpidIsDir, &prop))
133 _processedFileInfo.IsDir = VARIANT_BOOLToBool(prop.boolVal); 133 _processedFileInfo.IsDir = VARIANT_BOOLToBool(prop.boolVal);
134 134
135 bool isAnti = false; 135 bool isAnti = false;
136 { 136 {
137 NCOM::CPropVariant propTemp; 137 NCOM::CPropVariant propTemp;
138 RINOK(_archiveHandler->GetProperty(index, kpidIsAnti, &propTemp)); 138 RINOK(_archiveHandler->GetProperty(index, kpidIsAnti, &propTemp))
139 if (propTemp.vt == VT_BOOL) 139 if (propTemp.vt == VT_BOOL)
140 isAnti = VARIANT_BOOLToBool(propTemp.boolVal); 140 isAnti = VARIANT_BOOLToBool(propTemp.boolVal);
141 } 141 }
142 142
143 RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)); 143 RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop))
144 switch (prop.vt) 144 switch (prop.vt)
145 { 145 {
146 case VT_EMPTY: _processedFileInfo.MTime = _defaultMTime; break; 146 case VT_EMPTY: _processedFileInfo.MTime = _defaultMTime; break;
@@ -207,13 +207,13 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UInt32 index,
207 return S_OK; 207 return S_OK;
208} 208}
209 209
210STDMETHODIMP CExtractCallbackImp::PrepareOperation(Int32 askExtractMode) 210Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(Int32 askExtractMode))
211{ 211{
212 _extractMode = (askExtractMode == NArchive::NExtract::NAskMode::kExtract); 212 _extractMode = (askExtractMode == NArchive::NExtract::NAskMode::kExtract);
213 return S_OK; 213 return S_OK;
214} 214}
215 215
216STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResult) 216Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResult))
217{ 217{
218 switch (resultEOperationResult) 218 switch (resultEOperationResult)
219 { 219 {
@@ -237,7 +237,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 resultEOperationResul
237 if (_outFileStream != NULL) 237 if (_outFileStream != NULL)
238 { 238 {
239 _outFileStreamSpec->SetMTime(&_processedFileInfo.MTime); 239 _outFileStreamSpec->SetMTime(&_processedFileInfo.MTime);
240 RINOK(_outFileStreamSpec->Close()); 240 RINOK(_outFileStreamSpec->Close())
241 } 241 }
242 _outFileStream.Release(); 242 _outFileStream.Release();
243 if (_extractMode) 243 if (_extractMode)
diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h
index cfbc5c0..b9377ae 100644
--- a/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h
+++ b/CPP/7zip/Bundles/SFXSetup/ExtractCallbackSfx.h
@@ -1,7 +1,7 @@
1// ExtractCallbackSfx.h 1// ExtractCallbackSfx.h
2 2
3#ifndef __EXTRACT_CALLBACK_SFX_H 3#ifndef ZIP7_INC_EXTRACT_CALLBACK_SFX_H
4#define __EXTRACT_CALLBACK_SFX_H 4#define ZIP7_INC_EXTRACT_CALLBACK_SFX_H
5 5
6#include "resource.h" 6#include "resource.h"
7 7
@@ -19,19 +19,16 @@
19#endif 19#endif
20#include "../../UI/Common/ArchiveOpenCallback.h" 20#include "../../UI/Common/ArchiveOpenCallback.h"
21 21
22class CExtractCallbackImp: 22class CExtractCallbackImp Z7_final:
23 public IArchiveExtractCallback, 23 public IArchiveExtractCallback,
24 public IOpenCallbackUI, 24 public IOpenCallbackUI,
25 public CMyUnknownImp 25 public CMyUnknownImp
26{ 26{
27public: 27 Z7_COM_UNKNOWN_IMP_0
28 28 Z7_IFACE_COM7_IMP(IProgress)
29 MY_UNKNOWN_IMP 29 Z7_IFACE_COM7_IMP(IArchiveExtractCallback)
30 30 Z7_IFACE_IMP(IOpenCallbackUI)
31 INTERFACE_IArchiveExtractCallback(;)
32 INTERFACE_IOpenCallbackUI(;)
33 31
34private:
35 CMyComPtr<IInArchive> _archiveHandler; 32 CMyComPtr<IInArchive> _archiveHandler;
36 FString _directoryPath; 33 FString _directoryPath;
37 UString _filePath; 34 UString _filePath;
@@ -70,7 +67,7 @@ public:
70 #ifndef _NO_PROGRESS 67 #ifndef _NO_PROGRESS
71 HRESULT StartProgressDialog(const UString &title, NWindows::CThread &thread) 68 HRESULT StartProgressDialog(const UString &title, NWindows::CThread &thread)
72 { 69 {
73 ProgressDialog.Create(title, thread, 0); 70 ProgressDialog.Create(title, thread, NULL);
74 { 71 {
75 ProgressDialog.SetText(LangString(IDS_PROGRESS_EXTRACTING)); 72 ProgressDialog.SetText(LangString(IDS_PROGRESS_EXTRACTING));
76 } 73 }
@@ -78,7 +75,7 @@ public:
78 ProgressDialog.Show(SW_SHOWNORMAL); 75 ProgressDialog.Show(SW_SHOWNORMAL);
79 return S_OK; 76 return S_OK;
80 } 77 }
81 virtual ~CExtractCallbackImp() { ProgressDialog.Destroy(); } 78 ~CExtractCallbackImp() { ProgressDialog.Destroy(); }
82 #endif 79 #endif
83 80
84}; 81};
diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp
index 71b65c6..73ccff1 100644
--- a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp
+++ b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.cpp
@@ -64,18 +64,14 @@ struct CThreadExtracting
64 64
65 if (!CreateComplexDir(dirPath)) 65 if (!CreateComplexDir(dirPath))
66 { 66 {
67 ErrorMessage = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, 67 ErrorMessage = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, fs2us(dirPath));
68 #ifdef LANG
69 0x02000603,
70 #endif
71 fs2us(dirPath));
72 Result = E_FAIL; 68 Result = E_FAIL;
73 return; 69 return;
74 } 70 }
75 71
76 ExtractCallbackSpec->Init(ArchiveLink.GetArchive(), dirPath, (UString)"Default", fi.MTime, 0); 72 ExtractCallbackSpec->Init(ArchiveLink.GetArchive(), dirPath, (UString)"Default", fi.MTime, 0);
77 73
78 Result = ArchiveLink.GetArchive()->Extract(0, (UInt32)(Int32)-1 , BoolToInt(false), ExtractCallback); 74 Result = ArchiveLink.GetArchive()->Extract(NULL, (UInt32)(Int32)-1 , BoolToInt(false), ExtractCallback);
79 } 75 }
80 76
81 void Process() 77 void Process()
@@ -116,7 +112,9 @@ HRESULT ExtractArchive(CCodecs *codecs, const FString &fileName, const FString &
116 { 112 {
117 t.ExtractCallbackSpec->ProgressDialog.IconID = IDI_ICON; 113 t.ExtractCallbackSpec->ProgressDialog.IconID = IDI_ICON;
118 NWindows::CThread thread; 114 NWindows::CThread thread;
119 RINOK(thread.Create(CThreadExtracting::MyThreadFunction, &t)); 115 const WRes wres = thread.Create(CThreadExtracting::MyThreadFunction, &t);
116 if (wres != 0)
117 return HRESULT_FROM_WIN32(wres);
120 118
121 UString title; 119 UString title;
122 LangString(IDS_PROGRESS_EXTRACTING, title); 120 LangString(IDS_PROGRESS_EXTRACTING, title);
diff --git a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h
index 295d77b..b7f7965 100644
--- a/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h
+++ b/CPP/7zip/Bundles/SFXSetup/ExtractEngine.h
@@ -1,7 +1,7 @@
1// ExtractEngine.h 1// ExtractEngine.h
2 2
3#ifndef __EXTRACT_ENGINE_H 3#ifndef ZIP7_INC_EXTRACT_ENGINE_H
4#define __EXTRACT_ENGINE_H 4#define ZIP7_INC_EXTRACT_ENGINE_H
5 5
6#include "../../UI/Common/LoadCodecs.h" 6#include "../../UI/Common/LoadCodecs.h"
7 7
diff --git a/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp b/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp
index 754cc0e..cf96460 100644
--- a/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp
+++ b/CPP/7zip/Bundles/SFXSetup/SFXSetup.dsp
@@ -44,7 +44,7 @@ RSC=rc.exe
44# PROP Ignore_Export_Lib 0 44# PROP Ignore_Export_Lib 0
45# PROP Target_Dir "" 45# PROP Target_Dir ""
46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c 46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
47# 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 47# 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
48# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 48# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
49# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD BASE RSC /l 0x419 /d "NDEBUG" 50# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -71,7 +71,7 @@ LINK32=link.exe
71# PROP Ignore_Export_Lib 0 71# PROP Ignore_Export_Lib 0
72# PROP Target_Dir "" 72# PROP Target_Dir ""
73# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c 73# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
74# 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 74# 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
75# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 75# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
76# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD BASE RSC /l 0x419 /d "_DEBUG" 77# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -97,8 +97,8 @@ LINK32=link.exe
97# PROP Intermediate_Dir "ReleaseD" 97# PROP Intermediate_Dir "ReleaseD"
98# PROP Ignore_Export_Lib 0 98# PROP Ignore_Export_Lib 0
99# PROP Target_Dir "" 99# PROP Target_Dir ""
100# 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 100# 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
101# 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 101# 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
102# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 102# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
103# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD BASE RSC /l 0x419 /d "NDEBUG" 104# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -221,6 +221,10 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp
221# End Source File 221# End Source File
222# Begin Source File 222# Begin Source File
223 223
224SOURCE=..\..\Compress\Bcj2Coder.h
225# End Source File
226# Begin Source File
227
224SOURCE=..\..\Compress\Bcj2Register.cpp 228SOURCE=..\..\Compress\Bcj2Register.cpp
225# End Source File 229# End Source File
226# Begin Source File 230# Begin Source File
@@ -229,6 +233,10 @@ SOURCE=..\..\Compress\BcjCoder.cpp
229# End Source File 233# End Source File
230# Begin Source File 234# Begin Source File
231 235
236SOURCE=..\..\Compress\BcjCoder.h
237# End Source File
238# Begin Source File
239
232SOURCE=..\..\Compress\BcjRegister.cpp 240SOURCE=..\..\Compress\BcjRegister.cpp
233# End Source File 241# End Source File
234# Begin Source File 242# Begin Source File
@@ -249,6 +257,10 @@ SOURCE=..\..\Compress\CopyCoder.cpp
249# End Source File 257# End Source File
250# Begin Source File 258# Begin Source File
251 259
260SOURCE=..\..\Compress\CopyCoder.h
261# End Source File
262# Begin Source File
263
252SOURCE=..\..\Compress\CopyRegister.cpp 264SOURCE=..\..\Compress\CopyRegister.cpp
253# End Source File 265# End Source File
254# Begin Source File 266# Begin Source File
@@ -289,6 +301,10 @@ SOURCE=..\..\..\Common\CommandLineParser.h
289# End Source File 301# End Source File
290# Begin Source File 302# Begin Source File
291 303
304SOURCE=..\..\..\Common\Common.h
305# End Source File
306# Begin Source File
307
292SOURCE=..\..\..\Common\CRC.cpp 308SOURCE=..\..\..\Common\CRC.cpp
293# End Source File 309# End Source File
294# Begin Source File 310# Begin Source File
@@ -305,6 +321,10 @@ SOURCE=..\..\..\Common\IntToString.h
305# End Source File 321# End Source File
306# Begin Source File 322# Begin Source File
307 323
324SOURCE=..\..\..\Common\MyCom.h
325# End Source File
326# Begin Source File
327
308SOURCE=..\..\..\Common\MyString.cpp 328SOURCE=..\..\..\Common\MyString.cpp
309# End Source File 329# End Source File
310# Begin Source File 330# Begin Source File
@@ -464,7 +484,7 @@ SOURCE=..\..\..\Windows\Window.cpp
464SOURCE=..\..\..\Windows\Window.h 484SOURCE=..\..\..\Windows\Window.h
465# End Source File 485# End Source File
466# End Group 486# End Group
467# Begin Group "7z Common" 487# Begin Group "7zip Common"
468 488
469# PROP Default_Filter "" 489# PROP Default_Filter ""
470# Begin Source File 490# Begin Source File
@@ -667,6 +687,19 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c
667# End Source File 687# End Source File
668# Begin Source File 688# Begin Source File
669 689
690SOURCE=..\..\..\..\C\7zStream.c
691# SUBTRACT CPP /YX /Yc /Yu
692# End Source File
693# Begin Source File
694
695SOURCE=..\..\..\..\C\7zTypes.h
696# End Source File
697# Begin Source File
698
699SOURCE=..\..\..\..\C\7zWindows.h
700# End Source File
701# Begin Source File
702
670SOURCE=..\..\..\..\C\Alloc.c 703SOURCE=..\..\..\..\C\Alloc.c
671# SUBTRACT CPP /YX /Yc /Yu 704# SUBTRACT CPP /YX /Yc /Yu
672# End Source File 705# End Source File
@@ -704,6 +737,10 @@ SOURCE=..\..\..\..\C\BraIA64.c
704# End Source File 737# End Source File
705# Begin Source File 738# Begin Source File
706 739
740SOURCE=..\..\..\..\C\Compiler.h
741# End Source File
742# Begin Source File
743
707SOURCE=..\..\..\..\C\CpuArch.c 744SOURCE=..\..\..\..\C\CpuArch.c
708# SUBTRACT CPP /YX /Yc /Yu 745# SUBTRACT CPP /YX /Yc /Yu
709# End Source File 746# End Source File
@@ -775,6 +812,30 @@ SOURCE=..\..\..\..\C\Threads.c
775SOURCE=..\..\..\..\C\Threads.h 812SOURCE=..\..\..\..\C\Threads.h
776# End Source File 813# End Source File
777# End Group 814# End Group
815# Begin Group "7zip"
816
817# PROP Default_Filter ""
818# Begin Source File
819
820SOURCE=..\..\Archive\IArchive.h
821# End Source File
822# Begin Source File
823
824SOURCE=..\..\ICoder.h
825# End Source File
826# Begin Source File
827
828SOURCE=..\..\IDecl.h
829# End Source File
830# Begin Source File
831
832SOURCE=..\..\IPassword.h
833# End Source File
834# Begin Source File
835
836SOURCE=..\..\IProgress.h
837# End Source File
838# End Group
778# Begin Source File 839# Begin Source File
779 840
780SOURCE=.\ExtractCallbackSfx.cpp 841SOURCE=.\ExtractCallbackSfx.cpp
diff --git a/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp b/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp
index 86b4f0f..47d7966 100644
--- a/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp
+++ b/CPP/7zip/Bundles/SFXSetup/SfxSetup.cpp
@@ -2,8 +2,9 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../../C/DllSecur.h"
6 6
7#include "../../../Common/MyWindows.h"
7#include "../../../Common/MyInitGuid.h" 8#include "../../../Common/MyInitGuid.h"
8 9
9#include "../../../Common/CommandLineParser.h" 10#include "../../../Common/CommandLineParser.h"
@@ -23,19 +24,19 @@
23 24
24#include "ExtractEngine.h" 25#include "ExtractEngine.h"
25 26
26#include "../../../../C/DllSecur.h"
27
28#include "resource.h" 27#include "resource.h"
29 28
30using namespace NWindows; 29using namespace NWindows;
31using namespace NFile; 30using namespace NFile;
32using namespace NDir; 31using namespace NDir;
33 32
33extern
34HINSTANCE g_hInstance;
34HINSTANCE g_hInstance; 35HINSTANCE g_hInstance;
35 36
36static CFSTR const kTempDirPrefix = FTEXT("7zS"); 37static CFSTR const kTempDirPrefix = FTEXT("7zS");
37 38
38#define _SHELL_EXECUTE 39#define MY_SHELL_EXECUTE
39 40
40static bool ReadDataString(CFSTR fileName, LPCSTR startID, 41static bool ReadDataString(CFSTR fileName, LPCSTR startID,
41 LPCSTR endID, AString &stringResult) 42 LPCSTR endID, AString &stringResult)
@@ -73,10 +74,10 @@ static bool ReadDataString(CFSTR fileName, LPCSTR startID,
73 break; 74 break;
74 if (memcmp(buffer + pos, endID, signatureEndSize) == 0) 75 if (memcmp(buffer + pos, endID, signatureEndSize) == 0)
75 return true; 76 return true;
76 char b = buffer[pos]; 77 const Byte b = buffer[pos];
77 if (b == 0) 78 if (b == 0)
78 return false; 79 return false;
79 stringResult += b; 80 stringResult += (char)b;
80 pos++; 81 pos++;
81 } 82 }
82 else 83 else
@@ -101,13 +102,13 @@ static bool ReadDataString(CFSTR fileName, LPCSTR startID,
101static char kStartID[] = { ',','!','@','I','n','s','t','a','l','l','@','!','U','T','F','-','8','!', 0 }; 102static char kStartID[] = { ',','!','@','I','n','s','t','a','l','l','@','!','U','T','F','-','8','!', 0 };
102static char kEndID[] = { ',','!','@','I','n','s','t','a','l','l','E','n','d','@','!', 0 }; 103static char kEndID[] = { ',','!','@','I','n','s','t','a','l','l','E','n','d','@','!', 0 };
103 104
104struct CInstallIDInit 105static struct CInstallIDInit
105{ 106{
106 CInstallIDInit() 107 CInstallIDInit()
107 { 108 {
108 kStartID[0] = ';'; 109 kStartID[0] = ';';
109 kEndID[0] = ';'; 110 kEndID[0] = ';';
110 }; 111 }
111} g_CInstallIDInit; 112} g_CInstallIDInit;
112 113
113 114
@@ -118,11 +119,11 @@ struct CInstallIDInit
118static void ShowErrorMessageSpec(const UString &name) 119static void ShowErrorMessageSpec(const UString &name)
119{ 120{
120 UString message = NError::MyFormatMessage(::GetLastError()); 121 UString message = NError::MyFormatMessage(::GetLastError());
121 int pos = message.Find(L"%1"); 122 const int pos = message.Find(L"%1");
122 if (pos >= 0) 123 if (pos >= 0)
123 { 124 {
124 message.Delete(pos, 2); 125 message.Delete((unsigned)pos, 2);
125 message.Insert(pos, name); 126 message.Insert((unsigned)pos, name);
126 } 127 }
127 ShowErrorMessage(NULL, message); 128 ShowErrorMessage(NULL, message);
128} 129}
@@ -146,7 +147,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
146 // InitCommonControls(); 147 // InitCommonControls();
147 148
148 UString archiveName, switches; 149 UString archiveName, switches;
149 #ifdef _SHELL_EXECUTE 150 #ifdef MY_SHELL_EXECUTE
150 UString executeFile, executeParameters; 151 UString executeFile, executeParameters;
151 #endif 152 #endif
152 NCommandLineParser::SplitCommandLine(GetCommandLineW(), archiveName, switches); 153 NCommandLineParser::SplitCommandLine(GetCommandLineW(), archiveName, switches);
@@ -183,23 +184,23 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
183 ShowErrorMessage(L"Config failed"); 184 ShowErrorMessage(L"Config failed");
184 return 1; 185 return 1;
185 } 186 }
186 UString friendlyName = GetTextConfigValue(pairs, "Title"); 187 const UString friendlyName = GetTextConfigValue(pairs, "Title");
187 UString installPrompt = GetTextConfigValue(pairs, "BeginPrompt"); 188 const UString installPrompt = GetTextConfigValue(pairs, "BeginPrompt");
188 UString progress = GetTextConfigValue(pairs, "Progress"); 189 const UString progress = GetTextConfigValue(pairs, "Progress");
189 if (progress.IsEqualTo_Ascii_NoCase("no")) 190 if (progress.IsEqualTo_Ascii_NoCase("no"))
190 showProgress = false; 191 showProgress = false;
191 int index = FindTextConfigItem(pairs, "Directory"); 192 const int index = FindTextConfigItem(pairs, "Directory");
192 if (index >= 0) 193 if (index >= 0)
193 dirPrefix = pairs[index].String; 194 dirPrefix = pairs[index].String;
194 if (!installPrompt.IsEmpty() && !assumeYes) 195 if (!installPrompt.IsEmpty() && !assumeYes)
195 { 196 {
196 if (MessageBoxW(0, installPrompt, friendlyName, MB_YESNO | 197 if (MessageBoxW(NULL, installPrompt, friendlyName, MB_YESNO |
197 MB_ICONQUESTION) != IDYES) 198 MB_ICONQUESTION) != IDYES)
198 return 0; 199 return 0;
199 } 200 }
200 appLaunched = GetTextConfigValue(pairs, "RunProgram"); 201 appLaunched = GetTextConfigValue(pairs, "RunProgram");
201 202
202 #ifdef _SHELL_EXECUTE 203 #ifdef MY_SHELL_EXECUTE
203 executeFile = GetTextConfigValue(pairs, "ExecuteFile"); 204 executeFile = GetTextConfigValue(pairs, "ExecuteFile");
204 executeParameters = GetTextConfigValue(pairs, "ExecuteParameters"); 205 executeParameters = GetTextConfigValue(pairs, "ExecuteParameters");
205 #endif 206 #endif
@@ -216,7 +217,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
216 CCodecs *codecs = new CCodecs; 217 CCodecs *codecs = new CCodecs;
217 CMyComPtr<IUnknown> compressCodecsInfo = codecs; 218 CMyComPtr<IUnknown> compressCodecsInfo = codecs;
218 { 219 {
219 HRESULT result = codecs->Load(); 220 const HRESULT result = codecs->Load();
220 if (result != S_OK) 221 if (result != S_OK)
221 { 222 {
222 ShowErrorMessage(L"Cannot load codecs"); 223 ShowErrorMessage(L"Cannot load codecs");
@@ -245,7 +246,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
245 { 246 {
246 if (errorMessage.IsEmpty()) 247 if (errorMessage.IsEmpty())
247 errorMessage = NError::MyFormatMessage(result); 248 errorMessage = NError::MyFormatMessage(result);
248 ::MessageBoxW(0, errorMessage, NWindows::MyLoadString(IDS_EXTRACTION_ERROR_TITLE), MB_ICONERROR); 249 ::MessageBoxW(NULL, errorMessage, NWindows::MyLoadString(IDS_EXTRACTION_ERROR_TITLE), MB_ICONERROR);
249 } 250 }
250 } 251 }
251 return 1; 252 return 1;
@@ -258,8 +259,8 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
258 return 1; 259 return 1;
259 #endif 260 #endif
260 261
261 HANDLE hProcess = 0; 262 HANDLE hProcess = NULL;
262#ifdef _SHELL_EXECUTE 263#ifdef MY_SHELL_EXECUTE
263 if (!executeFile.IsEmpty()) 264 if (!executeFile.IsEmpty())
264 { 265 {
265 CSysString filePath (GetSystemString(executeFile)); 266 CSysString filePath (GetSystemString(executeFile));
@@ -280,7 +281,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
280 executeParameters += switches; 281 executeParameters += switches;
281 } 282 }
282 283
283 CSysString parametersSys (GetSystemString(executeParameters)); 284 const CSysString parametersSys (GetSystemString(executeParameters));
284 if (parametersSys.IsEmpty()) 285 if (parametersSys.IsEmpty())
285 execInfo.lpParameters = NULL; 286 execInfo.lpParameters = NULL;
286 else 287 else
@@ -288,7 +289,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
288 289
289 execInfo.lpDirectory = NULL; 290 execInfo.lpDirectory = NULL;
290 execInfo.nShow = SW_SHOWNORMAL; 291 execInfo.nShow = SW_SHOWNORMAL;
291 execInfo.hProcess = 0; 292 execInfo.hProcess = NULL;
292 /* BOOL success = */ ::ShellExecuteEx(&execInfo); 293 /* BOOL success = */ ::ShellExecuteEx(&execInfo);
293 UINT32 result = (UINT32)(UINT_PTR)execInfo.hInstApp; 294 UINT32 result = (UINT32)(UINT_PTR)execInfo.hInstApp;
294 if (result <= 32) 295 if (result <= 32)
@@ -319,7 +320,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
319 appLaunched.Replace(L"%%T" WSTRING_PATH_SEPARATOR, fs2us(s2)); 320 appLaunched.Replace(L"%%T" WSTRING_PATH_SEPARATOR, fs2us(s2));
320 } 321 }
321 322
322 UString appNameForError = appLaunched; // actually we need to rtemove parameters also 323 const UString appNameForError = appLaunched; // actually we need to rtemove parameters also
323 324
324 appLaunched.Replace(L"%%T", fs2us(tempDirPath)); 325 appLaunched.Replace(L"%%T", fs2us(tempDirPath));
325 326
@@ -330,20 +331,21 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
330 } 331 }
331 STARTUPINFO startupInfo; 332 STARTUPINFO startupInfo;
332 startupInfo.cb = sizeof(startupInfo); 333 startupInfo.cb = sizeof(startupInfo);
333 startupInfo.lpReserved = 0; 334 startupInfo.lpReserved = NULL;
334 startupInfo.lpDesktop = 0; 335 startupInfo.lpDesktop = NULL;
335 startupInfo.lpTitle = 0; 336 startupInfo.lpTitle = NULL;
336 startupInfo.dwFlags = 0; 337 startupInfo.dwFlags = 0;
337 startupInfo.cbReserved2 = 0; 338 startupInfo.cbReserved2 = 0;
338 startupInfo.lpReserved2 = 0; 339 startupInfo.lpReserved2 = NULL;
339 340
340 PROCESS_INFORMATION processInformation; 341 PROCESS_INFORMATION processInformation;
341 342
342 CSysString appLaunchedSys (GetSystemString(dirPrefix + appLaunched)); 343 const CSysString appLaunchedSys (GetSystemString(dirPrefix + appLaunched));
343 344
344 BOOL createResult = CreateProcess(NULL, (LPTSTR)(LPCTSTR)appLaunchedSys, 345 const BOOL createResult = CreateProcess(NULL,
345 NULL, NULL, FALSE, 0, NULL, NULL /*tempDir.GetPath() */, 346 appLaunchedSys.Ptr_non_const(),
346 &startupInfo, &processInformation); 347 NULL, NULL, FALSE, 0, NULL, NULL /*tempDir.GetPath() */,
348 &startupInfo, &processInformation);
347 if (createResult == 0) 349 if (createResult == 0)
348 { 350 {
349 if (!assumeYes) 351 if (!assumeYes)
@@ -357,7 +359,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
357 ::CloseHandle(processInformation.hThread); 359 ::CloseHandle(processInformation.hThread);
358 hProcess = processInformation.hProcess; 360 hProcess = processInformation.hProcess;
359 } 361 }
360 if (hProcess != 0) 362 if (hProcess)
361 { 363 {
362 WaitForSingleObject(hProcess, INFINITE); 364 WaitForSingleObject(hProcess, INFINITE);
363 ::CloseHandle(hProcess); 365 ::CloseHandle(hProcess);
diff --git a/CPP/7zip/Bundles/SFXSetup/StdAfx.h b/CPP/7zip/Bundles/SFXSetup/StdAfx.h
index 37bbd0c..4f27255 100644
--- a/CPP/7zip/Bundles/SFXSetup/StdAfx.h
+++ b/CPP/7zip/Bundles/SFXSetup/StdAfx.h
@@ -1,13 +1,6 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#if _MSC_VER >= 1800
4#define __STDAFX_H 4#pragma warning(disable : 4464) // relative include path contains '..'
5
6#include "../../../Common/Common.h"
7
8#include <commctrl.h>
9
10// #define printf(x) NO_PRINTF_(x)
11// #define sprintf(x) NO_SPRINTF_(x)
12
13#endif 5#endif
6#include "../../UI/FileManager/StdAfx.h"
diff --git a/CPP/7zip/Bundles/SFXSetup/makefile b/CPP/7zip/Bundles/SFXSetup/makefile
index 9fddbc0..ea0ece2 100644
--- a/CPP/7zip/Bundles/SFXSetup/makefile
+++ b/CPP/7zip/Bundles/SFXSetup/makefile
@@ -2,11 +2,11 @@ PROG = 7zS.sfx
2MY_FIXED = 1 2MY_FIXED = 1
3 3
4CFLAGS = $(CFLAGS) \ 4CFLAGS = $(CFLAGS) \
5 -DNO_REGISTRY \ 5 -DZ7_NO_REGISTRY \
6 -DEXTRACT_ONLY \ 6 -DZ7_EXTRACT_ONLY \
7 -DNO_READ_FROM_CODER \ 7 -DZ7_NO_READ_FROM_CODER \
8 -D_SFX \ 8 -DZ7_SFX \
9 -D_NO_CRYPTO \ 9 -DZ7_NO_CRYPTO \
10 10
11CURRENT_OBJS = \ 11CURRENT_OBJS = \
12 $O\SfxSetup.obj \ 12 $O\SfxSetup.obj \
@@ -97,6 +97,7 @@ COMPRESS_OBJS = \
97 $O\LzmaRegister.obj \ 97 $O\LzmaRegister.obj \
98 98
99C_OBJS = \ 99C_OBJS = \
100 $O\7zStream.obj \
100 $O\Alloc.obj \ 101 $O\Alloc.obj \
101 $O\Bcj2.obj \ 102 $O\Bcj2.obj \
102 $O\Bra.obj \ 103 $O\Bra.obj \
diff --git a/CPP/7zip/Bundles/SFXWin/SFXWin.dsp b/CPP/7zip/Bundles/SFXWin/SFXWin.dsp
index 8e1a70d..65cf0bf 100644
--- a/CPP/7zip/Bundles/SFXWin/SFXWin.dsp
+++ b/CPP/7zip/Bundles/SFXWin/SFXWin.dsp
@@ -44,7 +44,7 @@ RSC=rc.exe
44# PROP Ignore_Export_Lib 0 44# PROP Ignore_Export_Lib 0
45# PROP Target_Dir "" 45# PROP Target_Dir ""
46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c 46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
47# 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 47# 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
48# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 48# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
49# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD BASE RSC /l 0x419 /d "NDEBUG" 50# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -71,7 +71,7 @@ LINK32=link.exe
71# PROP Ignore_Export_Lib 0 71# PROP Ignore_Export_Lib 0
72# PROP Target_Dir "" 72# PROP Target_Dir ""
73# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c 73# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
74# 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 74# 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
75# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 75# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
76# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD BASE RSC /l 0x419 /d "_DEBUG" 77# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -97,8 +97,8 @@ LINK32=link.exe
97# PROP Intermediate_Dir "SFXWin___Win32_ReleaseD" 97# PROP Intermediate_Dir "SFXWin___Win32_ReleaseD"
98# PROP Ignore_Export_Lib 0 98# PROP Ignore_Export_Lib 0
99# PROP Target_Dir "" 99# PROP Target_Dir ""
100# 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 100# 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
101# 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 101# 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
102# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 102# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
103# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD BASE RSC /l 0x419 /d "NDEBUG" 104# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -221,6 +221,10 @@ SOURCE=..\..\Compress\Bcj2Coder.cpp
221# End Source File 221# End Source File
222# Begin Source File 222# Begin Source File
223 223
224SOURCE=..\..\Compress\Bcj2Coder.h
225# End Source File
226# Begin Source File
227
224SOURCE=..\..\Compress\Bcj2Register.cpp 228SOURCE=..\..\Compress\Bcj2Register.cpp
225# End Source File 229# End Source File
226# Begin Source File 230# Begin Source File
@@ -229,6 +233,10 @@ SOURCE=..\..\Compress\BcjCoder.cpp
229# End Source File 233# End Source File
230# Begin Source File 234# Begin Source File
231 235
236SOURCE=..\..\Compress\BcjCoder.h
237# End Source File
238# Begin Source File
239
232SOURCE=..\..\Compress\BcjRegister.cpp 240SOURCE=..\..\Compress\BcjRegister.cpp
233# End Source File 241# End Source File
234# Begin Source File 242# Begin Source File
@@ -249,6 +257,10 @@ SOURCE=..\..\Compress\CopyCoder.cpp
249# End Source File 257# End Source File
250# Begin Source File 258# Begin Source File
251 259
260SOURCE=..\..\Compress\CopyCoder.h
261# End Source File
262# Begin Source File
263
252SOURCE=..\..\Compress\CopyRegister.cpp 264SOURCE=..\..\Compress\CopyRegister.cpp
253# End Source File 265# End Source File
254# Begin Source File 266# Begin Source File
@@ -277,6 +289,10 @@ SOURCE=..\..\Compress\PpmdDecoder.cpp
277# End Source File 289# End Source File
278# Begin Source File 290# Begin Source File
279 291
292SOURCE=..\..\Compress\PpmdDecoder.h
293# End Source File
294# Begin Source File
295
280SOURCE=..\..\Compress\PpmdRegister.cpp 296SOURCE=..\..\Compress\PpmdRegister.cpp
281# End Source File 297# End Source File
282# End Group 298# End Group
@@ -677,6 +693,10 @@ SOURCE=..\..\..\Common\CommandLineParser.h
677# End Source File 693# End Source File
678# Begin Source File 694# Begin Source File
679 695
696SOURCE=..\..\..\Common\Common.h
697# End Source File
698# Begin Source File
699
680SOURCE=..\..\..\Common\CRC.cpp 700SOURCE=..\..\..\Common\CRC.cpp
681# End Source File 701# End Source File
682# Begin Source File 702# Begin Source File
@@ -851,6 +871,15 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c
851# End Source File 871# End Source File
852# Begin Source File 872# Begin Source File
853 873
874SOURCE=..\..\..\..\C\7zStream.c
875# SUBTRACT CPP /YX /Yc /Yu
876# End Source File
877# Begin Source File
878
879SOURCE=..\..\..\..\C\7zWindows.h
880# End Source File
881# Begin Source File
882
854SOURCE=..\..\..\..\C\Aes.c 883SOURCE=..\..\..\..\C\Aes.c
855# SUBTRACT CPP /YX /Yc /Yu 884# SUBTRACT CPP /YX /Yc /Yu
856# End Source File 885# End Source File
@@ -902,6 +931,10 @@ SOURCE=..\..\..\..\C\BraIA64.c
902# End Source File 931# End Source File
903# Begin Source File 932# Begin Source File
904 933
934SOURCE=..\..\..\..\C\Compiler.h
935# End Source File
936# Begin Source File
937
905SOURCE=..\..\..\..\C\CpuArch.c 938SOURCE=..\..\..\..\C\CpuArch.c
906# SUBTRACT CPP /YX /Yc /Yu 939# SUBTRACT CPP /YX /Yc /Yu
907# End Source File 940# End Source File
@@ -993,13 +1026,33 @@ SOURCE=..\..\..\..\C\Threads.c
993SOURCE=..\..\..\..\C\Threads.h 1026SOURCE=..\..\..\..\C\Threads.h
994# End Source File 1027# End Source File
995# End Group 1028# End Group
1029# Begin Group "7zip"
1030
1031# PROP Default_Filter ""
996# Begin Source File 1032# Begin Source File
997 1033
998SOURCE=.\7z.ico 1034SOURCE=..\..\Archive\IArchive.h
999# End Source File 1035# End Source File
1000# Begin Source File 1036# Begin Source File
1001 1037
1002SOURCE=.\7z1.ico 1038SOURCE=..\..\ICoder.h
1039# End Source File
1040# Begin Source File
1041
1042SOURCE=..\..\IDecl.h
1043# End Source File
1044# Begin Source File
1045
1046SOURCE=..\..\IPassword.h
1047# End Source File
1048# Begin Source File
1049
1050SOURCE=..\..\IProgress.h
1051# End Source File
1052# End Group
1053# Begin Source File
1054
1055SOURCE=.\7z.ico
1003# End Source File 1056# End Source File
1004# Begin Source File 1057# Begin Source File
1005 1058
diff --git a/CPP/7zip/Bundles/SFXWin/SfxWin.cpp b/CPP/7zip/Bundles/SFXWin/SfxWin.cpp
index 23beade..3e1880e 100644
--- a/CPP/7zip/Bundles/SFXWin/SfxWin.cpp
+++ b/CPP/7zip/Bundles/SFXWin/SfxWin.cpp
@@ -4,7 +4,13 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#if defined(__MINGW32__) || defined(__MINGW64__)
8#include <shlwapi.h>
9#else
7#include <Shlwapi.h> 10#include <Shlwapi.h>
11#endif
12
13#include "../../../../C/DllSecur.h"
8 14
9#include "../../../Common/MyInitGuid.h" 15#include "../../../Common/MyInitGuid.h"
10 16
@@ -28,33 +34,36 @@
28#include "../../UI/GUI/ExtractGUI.h" 34#include "../../UI/GUI/ExtractGUI.h"
29#include "../../UI/GUI/ExtractRes.h" 35#include "../../UI/GUI/ExtractRes.h"
30 36
31#include "../../../../C/DllSecur.h"
32
33using namespace NWindows; 37using namespace NWindows;
34using namespace NFile; 38using namespace NFile;
35using namespace NDir; 39using namespace NDir;
36 40
41extern
42HINSTANCE g_hInstance;
37HINSTANCE g_hInstance; 43HINSTANCE g_hInstance;
38 44
39#ifndef UNDER_CE 45#ifndef UNDER_CE
40 46
47static
41DWORD g_ComCtl32Version; 48DWORD g_ComCtl32Version;
42 49
43static DWORD GetDllVersion(LPCTSTR dllName) 50static DWORD GetDllVersion(LPCTSTR dllName)
44{ 51{
45 DWORD dwVersion = 0; 52 DWORD dwVersion = 0;
46 HINSTANCE hinstDll = LoadLibrary(dllName); 53 const HINSTANCE hinstDll = LoadLibrary(dllName);
47 if (hinstDll) 54 if (hinstDll)
48 { 55 {
49 DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); 56 const
50 if (pDllGetVersion) 57 DLLGETVERSIONPROC func_DllGetVersion = Z7_GET_PROC_ADDRESS(
58 DLLGETVERSIONPROC, hinstDll, "DllGetVersion");
59 if (func_DllGetVersion)
51 { 60 {
52 DLLVERSIONINFO dvi; 61 DLLVERSIONINFO dvi;
53 ZeroMemory(&dvi, sizeof(dvi)); 62 ZeroMemory(&dvi, sizeof(dvi));
54 dvi.cbSize = sizeof(dvi); 63 dvi.cbSize = sizeof(dvi);
55 HRESULT hr = (*pDllGetVersion)(&dvi); 64 const HRESULT hr = func_DllGetVersion(&dvi);
56 if (SUCCEEDED(hr)) 65 if (SUCCEEDED(hr))
57 dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); 66 dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion);
58 } 67 }
59 FreeLibrary(hinstDll); 68 FreeLibrary(hinstDll);
60 } 69 }
@@ -63,6 +72,8 @@ static DWORD GetDllVersion(LPCTSTR dllName)
63 72
64#endif 73#endif
65 74
75extern
76bool g_LVN_ITEMACTIVATE_Support;
66bool g_LVN_ITEMACTIVATE_Support = true; 77bool g_LVN_ITEMACTIVATE_Support = true;
67 78
68static const wchar_t * const kUnknownExceptionMessage = L"ERROR: Unknown Error!"; 79static const wchar_t * const kUnknownExceptionMessage = L"ERROR: Unknown Error!";
@@ -101,7 +112,7 @@ static int APIENTRY WinMain2()
101 const UString &s = commandStrings[i]; 112 const UString &s = commandStrings[i];
102 if (s.Len() > 1 && s[0] == '-') 113 if (s.Len() > 1 && s[0] == '-')
103 { 114 {
104 wchar_t c = MyCharLower_Ascii(s[1]); 115 const wchar_t c = MyCharLower_Ascii(s[1]);
105 if (c == 'y') 116 if (c == 'y')
106 { 117 {
107 assumeYes = true; 118 assumeYes = true;
@@ -152,7 +163,7 @@ static int APIENTRY WinMain2()
152 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs; 163 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs;
153 ecs->Init(); 164 ecs->Init();
154 165
155 #ifndef _NO_CRYPTO 166 #ifndef Z7_NO_CRYPTO
156 ecs->PasswordIsDefined = !password.IsEmpty(); 167 ecs->PasswordIsDefined = !password.IsEmpty();
157 ecs->Password = password; 168 ecs->Password = password;
158 #endif 169 #endif
diff --git a/CPP/7zip/Bundles/SFXWin/StdAfx.h b/CPP/7zip/Bundles/SFXWin/StdAfx.h
index 975a17e..4f27255 100644
--- a/CPP/7zip/Bundles/SFXWin/StdAfx.h
+++ b/CPP/7zip/Bundles/SFXWin/StdAfx.h
@@ -1,14 +1,6 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#if _MSC_VER >= 1800
4#define __STDAFX_H 4#pragma warning(disable : 4464) // relative include path contains '..'
5
6#include "../../../Common/Common.h"
7
8#include <commctrl.h>
9#include <ShlObj.h>
10
11// #define printf(x) NO_PRINTF_(x)
12// #define sprintf(x) NO_SPRINTF_(x)
13
14#endif 5#endif
6#include "../../UI/FileManager/StdAfx.h"
diff --git a/CPP/7zip/Bundles/SFXWin/makefile b/CPP/7zip/Bundles/SFXWin/makefile
index 0ed36f8..69a8553 100644
--- a/CPP/7zip/Bundles/SFXWin/makefile
+++ b/CPP/7zip/Bundles/SFXWin/makefile
@@ -2,10 +2,10 @@ PROG = 7z.sfx
2MY_FIXED = 1 2MY_FIXED = 1
3 3
4CFLAGS = $(CFLAGS) \ 4CFLAGS = $(CFLAGS) \
5 -DNO_REGISTRY \ 5 -DZ7_NO_REGISTRY \
6 -DEXTRACT_ONLY \ 6 -DZ7_EXTRACT_ONLY \
7 -DNO_READ_FROM_CODER \ 7 -DZ7_NO_READ_FROM_CODER \
8 -D_SFX \ 8 -DZ7_SFX \
9 9
10!IFDEF UNDER_CE 10!IFDEF UNDER_CE
11LIBS = $(LIBS) ceshell.lib Commctrl.lib 11LIBS = $(LIBS) ceshell.lib Commctrl.lib
@@ -131,6 +131,7 @@ CRYPTO_OBJS = \
131 $O\MyAes.obj \ 131 $O\MyAes.obj \
132 132
133C_OBJS = \ 133C_OBJS = \
134 $O\7zStream.obj \
134 $O\Alloc.obj \ 135 $O\Alloc.obj \
135 $O\Bcj2.obj \ 136 $O\Bcj2.obj \
136 $O\Bra.obj \ 137 $O\Bra.obj \
diff --git a/CPP/7zip/Bundles/SFXWin/resource.rc b/CPP/7zip/Bundles/SFXWin/resource.rc
index 91292b2..3b2217a 100644
--- a/CPP/7zip/Bundles/SFXWin/resource.rc
+++ b/CPP/7zip/Bundles/SFXWin/resource.rc
@@ -48,3 +48,8 @@ STRINGTABLE DISCARDABLE
48BEGIN 48BEGIN
49 IDS_PROP_MTIME "Modified" 49 IDS_PROP_MTIME "Modified"
50END 50END
51
52
53#ifndef UNDER_CE
541 24 MOVEABLE PURE "../../UI/GUI/7zG.exe.manifest"
55#endif
diff --git a/CPP/7zip/Common/CWrappers.cpp b/CPP/7zip/Common/CWrappers.cpp
index ee4c36a..346774e 100644
--- a/CPP/7zip/Common/CWrappers.cpp
+++ b/CPP/7zip/Common/CWrappers.cpp
@@ -57,9 +57,9 @@ HRESULT SResToHRESULT(SRes res) throw()
57#define CONVERT_PR_VAL(x) (x == PROGRESS_UNKNOWN_VALUE ? NULL : &x) 57#define CONVERT_PR_VAL(x) (x == PROGRESS_UNKNOWN_VALUE ? NULL : &x)
58 58
59 59
60static SRes CompressProgress(const ICompressProgress *pp, UInt64 inSize, UInt64 outSize) throw() 60static SRes CompressProgress(ICompressProgressPtr pp, UInt64 inSize, UInt64 outSize) throw()
61{ 61{
62 CCompressProgressWrap *p = CONTAINER_FROM_VTBL(pp, CCompressProgressWrap, vt); 62 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CCompressProgressWrap)
63 p->Res = p->Progress->SetRatioInfo(CONVERT_PR_VAL(inSize), CONVERT_PR_VAL(outSize)); 63 p->Res = p->Progress->SetRatioInfo(CONVERT_PR_VAL(inSize), CONVERT_PR_VAL(outSize));
64 return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS); 64 return HRESULT_To_SRes(p->Res, SZ_ERROR_PROGRESS);
65} 65}
@@ -73,9 +73,9 @@ void CCompressProgressWrap::Init(ICompressProgressInfo *progress) throw()
73 73
74static const UInt32 kStreamStepSize = (UInt32)1 << 31; 74static const UInt32 kStreamStepSize = (UInt32)1 << 31;
75 75
76static SRes MyRead(const ISeqInStream *pp, void *data, size_t *size) throw() 76static SRes MyRead(ISeqInStreamPtr pp, void *data, size_t *size) throw()
77{ 77{
78 CSeqInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeqInStreamWrap, vt); 78 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqInStreamWrap)
79 UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize); 79 UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize);
80 p->Res = (p->Stream->Read(data, curSize, &curSize)); 80 p->Res = (p->Stream->Read(data, curSize, &curSize));
81 *size = curSize; 81 *size = curSize;
@@ -85,9 +85,9 @@ static SRes MyRead(const ISeqInStream *pp, void *data, size_t *size) throw()
85 return HRESULT_To_SRes(p->Res, SZ_ERROR_READ); 85 return HRESULT_To_SRes(p->Res, SZ_ERROR_READ);
86} 86}
87 87
88static size_t MyWrite(const ISeqOutStream *pp, const void *data, size_t size) throw() 88static size_t MyWrite(ISeqOutStreamPtr pp, const void *data, size_t size) throw()
89{ 89{
90 CSeqOutStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeqOutStreamWrap, vt); 90 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeqOutStreamWrap)
91 if (p->Stream) 91 if (p->Stream)
92 { 92 {
93 p->Res = WriteStream(p->Stream, data, size); 93 p->Res = WriteStream(p->Stream, data, size);
@@ -118,20 +118,23 @@ void CSeqOutStreamWrap::Init(ISequentialOutStream *stream) throw()
118} 118}
119 119
120 120
121static SRes InStreamWrap_Read(const ISeekInStream *pp, void *data, size_t *size) throw() 121static SRes InStreamWrap_Read(ISeekInStreamPtr pp, void *data, size_t *size) throw()
122{ 122{
123 CSeekInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeekInStreamWrap, vt); 123 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeekInStreamWrap)
124 UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize); 124 UInt32 curSize = ((*size < kStreamStepSize) ? (UInt32)*size : kStreamStepSize);
125 p->Res = p->Stream->Read(data, curSize, &curSize); 125 p->Res = p->Stream->Read(data, curSize, &curSize);
126 *size = curSize; 126 *size = curSize;
127 return (p->Res == S_OK) ? SZ_OK : SZ_ERROR_READ; 127 return (p->Res == S_OK) ? SZ_OK : SZ_ERROR_READ;
128} 128}
129 129
130static SRes InStreamWrap_Seek(const ISeekInStream *pp, Int64 *offset, ESzSeek origin) throw() 130static SRes InStreamWrap_Seek(ISeekInStreamPtr pp, Int64 *offset, ESzSeek origin) throw()
131{ 131{
132 CSeekInStreamWrap *p = CONTAINER_FROM_VTBL(pp, CSeekInStreamWrap, vt); 132 Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CSeekInStreamWrap)
133 UInt32 moveMethod; 133 UInt32 moveMethod;
134 switch (origin) 134 /* we need (int)origin to eliminate the clang warning:
135 default label in switch which covers all enumeration values
136 [-Wcovered-switch-default */
137 switch ((int)origin)
135 { 138 {
136 case SZ_SEEK_SET: moveMethod = STREAM_SEEK_SET; break; 139 case SZ_SEEK_SET: moveMethod = STREAM_SEEK_SET; break;
137 case SZ_SEEK_CUR: moveMethod = STREAM_SEEK_CUR; break; 140 case SZ_SEEK_CUR: moveMethod = STREAM_SEEK_CUR; break;
@@ -188,15 +191,18 @@ Byte CByteInBufWrap::ReadByteFromNewBlock() throw()
188 return 0; 191 return 0;
189} 192}
190 193
191static Byte Wrap_ReadByte(const IByteIn *pp) throw() 194// #pragma GCC diagnostic ignored "-Winvalid-offsetof"
195
196static Byte Wrap_ReadByte(IByteInPtr pp) throw()
192{ 197{
193 CByteInBufWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CByteInBufWrap, vt); 198 CByteInBufWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteInBufWrap, vt);
199 // Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteInBufWrap)
194 if (p->Cur != p->Lim) 200 if (p->Cur != p->Lim)
195 return *p->Cur++; 201 return *p->Cur++;
196 return p->ReadByteFromNewBlock(); 202 return p->ReadByteFromNewBlock();
197} 203}
198 204
199CByteInBufWrap::CByteInBufWrap(): Buf(NULL) 205CByteInBufWrap::CByteInBufWrap() throw(): Buf(NULL)
200{ 206{
201 vt.Read = Wrap_ReadByte; 207 vt.Read = Wrap_ReadByte;
202} 208}
@@ -227,7 +233,7 @@ bool CLookToSequentialWrap::Alloc(UInt32 size) throw()
227/* 233/*
228EXTERN_C_BEGIN 234EXTERN_C_BEGIN
229 235
230void CLookToSequentialWrap_Look(ILookInSeqStream *pp) 236void CLookToSequentialWrap_Look(ILookInSeqStreamPtr pp)
231{ 237{
232 CLookToSequentialWrap *p = (CLookToSequentialWrap *)pp->Obj; 238 CLookToSequentialWrap *p = (CLookToSequentialWrap *)pp->Obj;
233 239
@@ -281,9 +287,10 @@ HRESULT CByteOutBufWrap::Flush() throw()
281 return Res; 287 return Res;
282} 288}
283 289
284static void Wrap_WriteByte(const IByteOut *pp, Byte b) throw() 290static void Wrap_WriteByte(IByteOutPtr pp, Byte b) throw()
285{ 291{
286 CByteOutBufWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CByteOutBufWrap, vt); 292 CByteOutBufWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteOutBufWrap, vt);
293 // Z7_CONTAINER_FROM_VTBL_TO_DECL_VAR_pp_vt_p(CByteOutBufWrap)
287 Byte *dest = p->Cur; 294 Byte *dest = p->Cur;
288 *dest = b; 295 *dest = b;
289 p->Cur = ++dest; 296 p->Cur = ++dest;
@@ -317,16 +324,16 @@ bool CLookOutWrap::Alloc(size_t size) throw()
317 return (Buf != NULL); 324 return (Buf != NULL);
318} 325}
319 326
320static size_t LookOutWrap_GetOutBuf(const ILookOutStream *pp, void **buf) throw() 327static size_t LookOutWrap_GetOutBuf(ILookOutStreamPtr pp, void **buf) throw()
321{ 328{
322 CLookOutWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); 329 CLookOutWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt);
323 *buf = p->Buf; 330 *buf = p->Buf;
324 return p->Size; 331 return p->Size;
325} 332}
326 333
327static size_t LookOutWrap_Write(const ILookOutStream *pp, size_t size) throw() 334static size_t LookOutWrap_Write(ILookOutStreamPtr pp, size_t size) throw()
328{ 335{
329 CLookOutWrap *p = CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt); 336 CLookOutWrap *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CLookOutWrap, vt);
330 if (p->Res == S_OK && size != 0) 337 if (p->Res == S_OK && size != 0)
331 { 338 {
332 p->Res = WriteStream(p->Stream, p->Buf, size); 339 p->Res = WriteStream(p->Stream, p->Buf, size);
diff --git a/CPP/7zip/Common/CWrappers.h b/CPP/7zip/Common/CWrappers.h
index e7196a5..6c10a5c 100644
--- a/CPP/7zip/Common/CWrappers.h
+++ b/CPP/7zip/Common/CWrappers.h
@@ -1,7 +1,7 @@
1// CWrappers.h 1// CWrappers.h
2 2
3#ifndef __C_WRAPPERS_H 3#ifndef ZIP7_INC_C_WRAPPERS_H
4#define __C_WRAPPERS_H 4#define ZIP7_INC_C_WRAPPERS_H
5 5
6#include "../ICoder.h" 6#include "../ICoder.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
@@ -63,7 +63,7 @@ struct CByteInBufWrap
63 bool Extra; 63 bool Extra;
64 HRESULT Res; 64 HRESULT Res;
65 65
66 CByteInBufWrap(); 66 CByteInBufWrap() throw();
67 ~CByteInBufWrap() { Free(); } 67 ~CByteInBufWrap() { Free(); }
68 void Free() throw(); 68 void Free() throw();
69 bool Alloc(UInt32 size) throw(); 69 bool Alloc(UInt32 size) throw();
diff --git a/CPP/7zip/Common/CreateCoder.cpp b/CPP/7zip/Common/CreateCoder.cpp
index 872f17f..bf7b04e 100644
--- a/CPP/7zip/Common/CreateCoder.cpp
+++ b/CPP/7zip/Common/CreateCoder.cpp
@@ -19,11 +19,11 @@ const CCodecInfo *g_Codecs[];
19const CCodecInfo *g_Codecs[kNumCodecsMax]; 19const CCodecInfo *g_Codecs[kNumCodecsMax];
20 20
21// We use g_ExternalCodecs in other stages. 21// We use g_ExternalCodecs in other stages.
22#ifdef EXTERNAL_CODECS 22#ifdef Z7_EXTERNAL_CODECS
23/* 23/*
24extern CExternalCodecs g_ExternalCodecs; 24extern CExternalCodecs g_ExternalCodecs;
25#define CHECK_GLOBAL_CODECS \ 25#define CHECK_GLOBAL_CODECS \
26 if (!__externalCodecs || !__externalCodecs->IsSet()) __externalCodecs = &g_ExternalCodecs; 26 if (!_externalCodecs || !_externalCodecs->IsSet()) _externalCodecs = &g_ExternalCodecs;
27*/ 27*/
28#define CHECK_GLOBAL_CODECS 28#define CHECK_GLOBAL_CODECS
29#endif 29#endif
@@ -50,12 +50,12 @@ void RegisterHasher(const CHasherInfo *hashInfo) throw()
50} 50}
51 51
52 52
53#ifdef EXTERNAL_CODECS 53#ifdef Z7_EXTERNAL_CODECS
54 54
55static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, UInt32 &res) 55static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, UInt32 &res)
56{ 56{
57 NWindows::NCOM::CPropVariant prop; 57 NWindows::NCOM::CPropVariant prop;
58 RINOK(codecsInfo->GetProperty(index, propID, &prop)); 58 RINOK(codecsInfo->GetProperty(index, propID, &prop))
59 if (prop.vt == VT_EMPTY) 59 if (prop.vt == VT_EMPTY)
60 res = 1; 60 res = 1;
61 else if (prop.vt == VT_UI4) 61 else if (prop.vt == VT_UI4)
@@ -68,7 +68,7 @@ static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index
68static HRESULT ReadIsAssignedProp(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, bool &res) 68static HRESULT ReadIsAssignedProp(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, bool &res)
69{ 69{
70 NWindows::NCOM::CPropVariant prop; 70 NWindows::NCOM::CPropVariant prop;
71 RINOK(codecsInfo->GetProperty(index, propID, &prop)); 71 RINOK(codecsInfo->GetProperty(index, propID, &prop))
72 if (prop.vt == VT_EMPTY) 72 if (prop.vt == VT_EMPTY)
73 res = true; 73 res = true;
74 else if (prop.vt == VT_BOOL) 74 else if (prop.vt == VT_BOOL)
@@ -89,13 +89,13 @@ HRESULT CExternalCodecs::Load()
89 89
90 UString s; 90 UString s;
91 UInt32 num; 91 UInt32 num;
92 RINOK(GetCodecs->GetNumMethods(&num)); 92 RINOK(GetCodecs->GetNumMethods(&num))
93 93
94 for (UInt32 i = 0; i < num; i++) 94 for (UInt32 i = 0; i < num; i++)
95 { 95 {
96 NWindows::NCOM::CPropVariant prop; 96 NWindows::NCOM::CPropVariant prop;
97 97
98 RINOK(GetCodecs->GetProperty(i, NMethodPropID::kID, &prop)); 98 RINOK(GetCodecs->GetProperty(i, NMethodPropID::kID, &prop))
99 if (prop.vt != VT_UI8) 99 if (prop.vt != VT_UI8)
100 continue; // old Interface 100 continue; // old Interface
101 info.Id = prop.uhVal.QuadPart; 101 info.Id = prop.uhVal.QuadPart;
@@ -103,22 +103,22 @@ HRESULT CExternalCodecs::Load()
103 prop.Clear(); 103 prop.Clear();
104 104
105 info.Name.Empty(); 105 info.Name.Empty();
106 RINOK(GetCodecs->GetProperty(i, NMethodPropID::kName, &prop)); 106 RINOK(GetCodecs->GetProperty(i, NMethodPropID::kName, &prop))
107 if (prop.vt == VT_BSTR) 107 if (prop.vt == VT_BSTR)
108 info.Name.SetFromWStr_if_Ascii(prop.bstrVal); 108 info.Name.SetFromWStr_if_Ascii(prop.bstrVal);
109 else if (prop.vt != VT_EMPTY) 109 else if (prop.vt != VT_EMPTY)
110 continue; 110 continue;
111 111
112 RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kPackStreams, info.NumStreams)); 112 RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kPackStreams, info.NumStreams))
113 { 113 {
114 UInt32 numUnpackStreams = 1; 114 UInt32 numUnpackStreams = 1;
115 RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kUnpackStreams, numUnpackStreams)); 115 RINOK(ReadNumberOfStreams(GetCodecs, i, NMethodPropID::kUnpackStreams, numUnpackStreams))
116 if (numUnpackStreams != 1) 116 if (numUnpackStreams != 1)
117 continue; 117 continue;
118 } 118 }
119 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned)); 119 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned))
120 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned)); 120 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned))
121 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kIsFilter, info.IsFilter)); 121 RINOK(ReadIsAssignedProp(GetCodecs, i, NMethodPropID::kIsFilter, info.IsFilter))
122 122
123 Codecs.Add(info); 123 Codecs.Add(info);
124 } 124 }
@@ -133,7 +133,7 @@ HRESULT CExternalCodecs::Load()
133 { 133 {
134 NWindows::NCOM::CPropVariant prop; 134 NWindows::NCOM::CPropVariant prop;
135 135
136 RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kID, &prop)); 136 RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kID, &prop))
137 if (prop.vt != VT_UI8) 137 if (prop.vt != VT_UI8)
138 continue; 138 continue;
139 info.Id = prop.uhVal.QuadPart; 139 info.Id = prop.uhVal.QuadPart;
@@ -141,7 +141,7 @@ HRESULT CExternalCodecs::Load()
141 prop.Clear(); 141 prop.Clear();
142 142
143 info.Name.Empty(); 143 info.Name.Empty();
144 RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kName, &prop)); 144 RINOK(GetHashers->GetHasherProp(i, NMethodPropID::kName, &prop))
145 if (prop.vt == VT_BSTR) 145 if (prop.vt == VT_BSTR)
146 info.Name.SetFromWStr_if_Ascii(prop.bstrVal); 146 info.Name.SetFromWStr_if_Ascii(prop.bstrVal);
147 else if (prop.vt != VT_EMPTY) 147 else if (prop.vt != VT_EMPTY)
@@ -162,7 +162,8 @@ int FindMethod_Index(
162 const AString &name, 162 const AString &name,
163 bool encode, 163 bool encode,
164 CMethodId &methodId, 164 CMethodId &methodId,
165 UInt32 &numStreams) 165 UInt32 &numStreams,
166 bool &isFilter)
166{ 167{
167 unsigned i; 168 unsigned i;
168 for (i = 0; i < g_NumCodecs; i++) 169 for (i = 0; i < g_NumCodecs; i++)
@@ -173,23 +174,25 @@ int FindMethod_Index(
173 { 174 {
174 methodId = codec.Id; 175 methodId = codec.Id;
175 numStreams = codec.NumStreams; 176 numStreams = codec.NumStreams;
177 isFilter = codec.IsFilter;
176 return (int)i; 178 return (int)i;
177 } 179 }
178 } 180 }
179 181
180 #ifdef EXTERNAL_CODECS 182 #ifdef Z7_EXTERNAL_CODECS
181 183
182 CHECK_GLOBAL_CODECS 184 CHECK_GLOBAL_CODECS
183 185
184 if (__externalCodecs) 186 if (_externalCodecs)
185 for (i = 0; i < __externalCodecs->Codecs.Size(); i++) 187 for (i = 0; i < _externalCodecs->Codecs.Size(); i++)
186 { 188 {
187 const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; 189 const CCodecInfoEx &codec = _externalCodecs->Codecs[i];
188 if ((encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned) 190 if ((encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned)
189 && StringsAreEqualNoCase_Ascii(name, codec.Name)) 191 && StringsAreEqualNoCase_Ascii(name, codec.Name))
190 { 192 {
191 methodId = codec.Id; 193 methodId = codec.Id;
192 numStreams = codec.NumStreams; 194 numStreams = codec.NumStreams;
195 isFilter = codec.IsFilter;
193 return (int)(g_NumCodecs + i); 196 return (int)(g_NumCodecs + i);
194 } 197 }
195 } 198 }
@@ -212,14 +215,14 @@ static int FindMethod_Index(
212 return (int)i; 215 return (int)i;
213 } 216 }
214 217
215 #ifdef EXTERNAL_CODECS 218 #ifdef Z7_EXTERNAL_CODECS
216 219
217 CHECK_GLOBAL_CODECS 220 CHECK_GLOBAL_CODECS
218 221
219 if (__externalCodecs) 222 if (_externalCodecs)
220 for (i = 0; i < __externalCodecs->Codecs.Size(); i++) 223 for (i = 0; i < _externalCodecs->Codecs.Size(); i++)
221 { 224 {
222 const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; 225 const CCodecInfoEx &codec = _externalCodecs->Codecs[i];
223 if (codec.Id == methodId && (encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned)) 226 if (codec.Id == methodId && (encode ? codec.EncoderIsAssigned : codec.DecoderIsAssigned))
224 return (int)(g_NumCodecs + i); 227 return (int)(g_NumCodecs + i);
225 } 228 }
@@ -248,14 +251,14 @@ bool FindMethod(
248 } 251 }
249 } 252 }
250 253
251 #ifdef EXTERNAL_CODECS 254 #ifdef Z7_EXTERNAL_CODECS
252 255
253 CHECK_GLOBAL_CODECS 256 CHECK_GLOBAL_CODECS
254 257
255 if (__externalCodecs) 258 if (_externalCodecs)
256 for (i = 0; i < __externalCodecs->Codecs.Size(); i++) 259 for (i = 0; i < _externalCodecs->Codecs.Size(); i++)
257 { 260 {
258 const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; 261 const CCodecInfoEx &codec = _externalCodecs->Codecs[i];
259 if (methodId == codec.Id) 262 if (methodId == codec.Id)
260 { 263 {
261 name = codec.Name; 264 name = codec.Name;
@@ -284,14 +287,14 @@ bool FindHashMethod(
284 } 287 }
285 } 288 }
286 289
287 #ifdef EXTERNAL_CODECS 290 #ifdef Z7_EXTERNAL_CODECS
288 291
289 CHECK_GLOBAL_CODECS 292 CHECK_GLOBAL_CODECS
290 293
291 if (__externalCodecs) 294 if (_externalCodecs)
292 for (i = 0; i < __externalCodecs->Hashers.Size(); i++) 295 for (i = 0; i < _externalCodecs->Hashers.Size(); i++)
293 { 296 {
294 const CHasherInfoEx &codec = __externalCodecs->Hashers[i]; 297 const CHasherInfoEx &codec = _externalCodecs->Hashers[i];
295 if (StringsAreEqualNoCase_Ascii(name, codec.Name)) 298 if (StringsAreEqualNoCase_Ascii(name, codec.Name))
296 { 299 {
297 methodId = codec.Id; 300 methodId = codec.Id;
@@ -313,13 +316,13 @@ void GetHashMethods(
313 for (i = 0; i < g_NumHashers; i++) 316 for (i = 0; i < g_NumHashers; i++)
314 methods[i] = (*g_Hashers[i]).Id; 317 methods[i] = (*g_Hashers[i]).Id;
315 318
316 #ifdef EXTERNAL_CODECS 319 #ifdef Z7_EXTERNAL_CODECS
317 320
318 CHECK_GLOBAL_CODECS 321 CHECK_GLOBAL_CODECS
319 322
320 if (__externalCodecs) 323 if (_externalCodecs)
321 for (i = 0; i < __externalCodecs->Hashers.Size(); i++) 324 for (i = 0; i < _externalCodecs->Hashers.Size(); i++)
322 methods.Add(__externalCodecs->Hashers[i].Id); 325 methods.Add(_externalCodecs->Hashers[i].Id);
323 326
324 #endif 327 #endif
325} 328}
@@ -364,17 +367,17 @@ HRESULT CreateCoder_Index(
364 } 367 }
365 } 368 }
366 369
367 #ifdef EXTERNAL_CODECS 370 #ifdef Z7_EXTERNAL_CODECS
368 371
369 CHECK_GLOBAL_CODECS 372 CHECK_GLOBAL_CODECS
370 373
371 if (__externalCodecs) 374 if (_externalCodecs)
372 { 375 {
373 i -= g_NumCodecs; 376 i -= g_NumCodecs;
374 cod.IsExternal = true; 377 cod.IsExternal = true;
375 if (i < __externalCodecs->Codecs.Size()) 378 if (i < _externalCodecs->Codecs.Size())
376 { 379 {
377 const CCodecInfoEx &codec = __externalCodecs->Codecs[i]; 380 const CCodecInfoEx &codec = _externalCodecs->Codecs[i];
378 // if (codec.Id == methodId) 381 // if (codec.Id == methodId)
379 { 382 {
380 if (encode) 383 if (encode)
@@ -383,15 +386,15 @@ HRESULT CreateCoder_Index(
383 { 386 {
384 if (codec.NumStreams == 1) 387 if (codec.NumStreams == 1)
385 { 388 {
386 HRESULT res = __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder, (void **)&cod.Coder); 389 const HRESULT res = _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder, (void **)&cod.Coder);
387 if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE) 390 if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE)
388 return res; 391 return res;
389 if (cod.Coder) 392 if (cod.Coder)
390 return res; 393 return res;
391 return __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter); 394 return _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter);
392 } 395 }
393 cod.NumStreams = codec.NumStreams; 396 cod.NumStreams = codec.NumStreams;
394 return __externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); 397 return _externalCodecs->GetCodecs->CreateEncoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2);
395 } 398 }
396 } 399 }
397 else 400 else
@@ -399,15 +402,15 @@ HRESULT CreateCoder_Index(
399 { 402 {
400 if (codec.NumStreams == 1) 403 if (codec.NumStreams == 1)
401 { 404 {
402 HRESULT res = __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder, (void **)&cod.Coder); 405 const HRESULT res = _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder, (void **)&cod.Coder);
403 if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE) 406 if (res != S_OK && res != E_NOINTERFACE && res != CLASS_E_CLASSNOTAVAILABLE)
404 return res; 407 return res;
405 if (cod.Coder) 408 if (cod.Coder)
406 return res; 409 return res;
407 return __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter); 410 return _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter);
408 } 411 }
409 cod.NumStreams = codec.NumStreams; 412 cod.NumStreams = codec.NumStreams;
410 return __externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2); 413 return _externalCodecs->GetCodecs->CreateDecoder(i, &IID_ICompressCoder2, (void **)&cod.Coder2);
411 } 414 }
412 } 415 }
413 } 416 }
@@ -424,7 +427,7 @@ HRESULT CreateCoder_Index(
424 CCreatedCoder &cod) 427 CCreatedCoder &cod)
425{ 428{
426 CMyComPtr<ICompressFilter> filter; 429 CMyComPtr<ICompressFilter> filter;
427 HRESULT res = CreateCoder_Index( 430 const HRESULT res = CreateCoder_Index(
428 EXTERNAL_CODECS_LOC_VARS 431 EXTERNAL_CODECS_LOC_VARS
429 index, encode, 432 index, encode,
430 filter, cod); 433 filter, cod);
@@ -447,7 +450,7 @@ HRESULT CreateCoder_Id(
447 CMyComPtr<ICompressFilter> &filter, 450 CMyComPtr<ICompressFilter> &filter,
448 CCreatedCoder &cod) 451 CCreatedCoder &cod)
449{ 452{
450 int index = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS methodId, encode); 453 const int index = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS methodId, encode);
451 if (index < 0) 454 if (index < 0)
452 return S_OK; 455 return S_OK;
453 return CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)index, encode, filter, cod); 456 return CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)index, encode, filter, cod);
@@ -460,7 +463,7 @@ HRESULT CreateCoder_Id(
460 CCreatedCoder &cod) 463 CCreatedCoder &cod)
461{ 464{
462 CMyComPtr<ICompressFilter> filter; 465 CMyComPtr<ICompressFilter> filter;
463 HRESULT res = CreateCoder_Id( 466 const HRESULT res = CreateCoder_Id(
464 EXTERNAL_CODECS_LOC_VARS 467 EXTERNAL_CODECS_LOC_VARS
465 methodId, encode, 468 methodId, encode,
466 filter, cod); 469 filter, cod);
@@ -483,7 +486,7 @@ HRESULT CreateCoder_Id(
483 CMyComPtr<ICompressCoder> &coder) 486 CMyComPtr<ICompressCoder> &coder)
484{ 487{
485 CCreatedCoder cod; 488 CCreatedCoder cod;
486 HRESULT res = CreateCoder_Id( 489 const HRESULT res = CreateCoder_Id(
487 EXTERNAL_CODECS_LOC_VARS 490 EXTERNAL_CODECS_LOC_VARS
488 methodId, encode, 491 methodId, encode,
489 cod); 492 cod);
@@ -524,18 +527,18 @@ HRESULT CreateHasher(
524 } 527 }
525 } 528 }
526 529
527 #ifdef EXTERNAL_CODECS 530 #ifdef Z7_EXTERNAL_CODECS
528 531
529 CHECK_GLOBAL_CODECS 532 CHECK_GLOBAL_CODECS
530 533
531 if (!hasher && __externalCodecs) 534 if (!hasher && _externalCodecs)
532 for (i = 0; i < __externalCodecs->Hashers.Size(); i++) 535 for (i = 0; i < _externalCodecs->Hashers.Size(); i++)
533 { 536 {
534 const CHasherInfoEx &codec = __externalCodecs->Hashers[i]; 537 const CHasherInfoEx &codec = _externalCodecs->Hashers[i];
535 if (codec.Id == methodId) 538 if (codec.Id == methodId)
536 { 539 {
537 name = codec.Name; 540 name = codec.Name;
538 return __externalCodecs->GetHashers->CreateHasher((UInt32)i, &hasher); 541 return _externalCodecs->GetHashers->CreateHasher((UInt32)i, &hasher);
539 } 542 }
540 } 543 }
541 544
diff --git a/CPP/7zip/Common/CreateCoder.h b/CPP/7zip/Common/CreateCoder.h
index 24e6b66..709fe83 100644
--- a/CPP/7zip/Common/CreateCoder.h
+++ b/CPP/7zip/Common/CreateCoder.h
@@ -1,7 +1,7 @@
1// CreateCoder.h 1// CreateCoder.h
2 2
3#ifndef __CREATE_CODER_H 3#ifndef ZIP7_INC_CREATE_CODER_H
4#define __CREATE_CODER_H 4#define ZIP7_INC_CREATE_CODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7#include "../../Common/MyString.h" 7#include "../../Common/MyString.h"
@@ -11,10 +11,10 @@
11#include "MethodId.h" 11#include "MethodId.h"
12 12
13/* 13/*
14 if EXTERNAL_CODECS is not defined, the code supports only codecs that 14 if Z7_EXTERNAL_CODECS is not defined, the code supports only codecs that
15 are statically linked at compile-time and link-time. 15 are statically linked at compile-time and link-time.
16 16
17 if EXTERNAL_CODECS is defined, the code supports also codecs from another 17 if Z7_EXTERNAL_CODECS is defined, the code supports also codecs from another
18 executable modules, that can be linked dynamically at run-time: 18 executable modules, that can be linked dynamically at run-time:
19 - EXE module can use codecs from external DLL files. 19 - EXE module can use codecs from external DLL files.
20 - DLL module can use codecs from external EXE and DLL files. 20 - DLL module can use codecs from external EXE and DLL files.
@@ -26,7 +26,7 @@
26 2) External codecs 26 2) External codecs
27*/ 27*/
28 28
29#ifdef EXTERNAL_CODECS 29#ifdef Z7_EXTERNAL_CODECS
30 30
31struct CCodecInfoEx 31struct CCodecInfoEx
32{ 32{
@@ -46,13 +46,17 @@ struct CHasherInfoEx
46 AString Name; 46 AString Name;
47}; 47};
48 48
49#define PUBLIC_ISetCompressCodecsInfo public ISetCompressCodecsInfo, 49#define Z7_PUBLIC_ISetCompressCodecsInfo_IFEC \
50#define QUERY_ENTRY_ISetCompressCodecsInfo MY_QUERYINTERFACE_ENTRY(ISetCompressCodecsInfo) 50 public ISetCompressCodecsInfo,
51#define DECL_ISetCompressCodecsInfo STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo); 51#define Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC \
52#define IMPL_ISetCompressCodecsInfo2(x) \ 52 Z7_COM_QI_ENTRY(ISetCompressCodecsInfo)
53STDMETHODIMP x::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo) { \ 53#define DECL_ISetCompressCodecsInfo \
54 COM_TRY_BEGIN __externalCodecs.GetCodecs = compressCodecsInfo; return __externalCodecs.Load(); COM_TRY_END } 54 Z7_COM7F_IMP(SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo))
55#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler) 55#define IMPL_ISetCompressCodecsInfo2(cls) \
56 Z7_COM7F_IMF(cls::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo)) \
57 { COM_TRY_BEGIN _externalCodecs.GetCodecs = compressCodecsInfo; \
58 return _externalCodecs.Load(); COM_TRY_END }
59#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler)
56 60
57struct CExternalCodecs 61struct CExternalCodecs
58{ 62{
@@ -83,26 +87,27 @@ struct CExternalCodecs
83 87
84extern CExternalCodecs g_ExternalCodecs; 88extern CExternalCodecs g_ExternalCodecs;
85 89
86#define EXTERNAL_CODECS_VARS2 (__externalCodecs.IsSet() ? &__externalCodecs : &g_ExternalCodecs) 90#define EXTERNAL_CODECS_VARS2 (_externalCodecs.IsSet() ? &_externalCodecs : &g_ExternalCodecs)
87#define EXTERNAL_CODECS_VARS2_L (&__externalCodecs) 91#define EXTERNAL_CODECS_VARS2_L (&_externalCodecs)
88#define EXTERNAL_CODECS_VARS2_G (&g_ExternalCodecs) 92#define EXTERNAL_CODECS_VARS2_G (&g_ExternalCodecs)
89 93
90#define DECL_EXTERNAL_CODECS_VARS CExternalCodecs __externalCodecs; 94#define DECL_EXTERNAL_CODECS_VARS CExternalCodecs _externalCodecs;
91 95
92#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2, 96#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2,
93#define EXTERNAL_CODECS_VARS_L EXTERNAL_CODECS_VARS2_L, 97#define EXTERNAL_CODECS_VARS_L EXTERNAL_CODECS_VARS2_L,
94#define EXTERNAL_CODECS_VARS_G EXTERNAL_CODECS_VARS2_G, 98#define EXTERNAL_CODECS_VARS_G EXTERNAL_CODECS_VARS2_G,
95 99
96#define DECL_EXTERNAL_CODECS_LOC_VARS2 const CExternalCodecs *__externalCodecs 100#define DECL_EXTERNAL_CODECS_LOC_VARS2 const CExternalCodecs *_externalCodecs
97#define EXTERNAL_CODECS_LOC_VARS2 __externalCodecs 101#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2,
102#define DECL_EXTERNAL_CODECS_LOC_VARS_DECL DECL_EXTERNAL_CODECS_LOC_VARS2;
98 103
99#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2, 104#define EXTERNAL_CODECS_LOC_VARS2 _externalCodecs
100#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2, 105#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2,
101 106
102#else 107#else
103 108
104#define PUBLIC_ISetCompressCodecsInfo 109#define Z7_PUBLIC_ISetCompressCodecsInfo_IFEC
105#define QUERY_ENTRY_ISetCompressCodecsInfo 110#define Z7_COM_QI_ENTRY_ISetCompressCodecsInfo_IFEC
106#define DECL_ISetCompressCodecsInfo 111#define DECL_ISetCompressCodecsInfo
107#define IMPL_ISetCompressCodecsInfo 112#define IMPL_ISetCompressCodecsInfo
108#define EXTERNAL_CODECS_VARS2 113#define EXTERNAL_CODECS_VARS2
@@ -111,8 +116,9 @@ extern CExternalCodecs g_ExternalCodecs;
111#define EXTERNAL_CODECS_VARS_L 116#define EXTERNAL_CODECS_VARS_L
112#define EXTERNAL_CODECS_VARS_G 117#define EXTERNAL_CODECS_VARS_G
113#define DECL_EXTERNAL_CODECS_LOC_VARS2 118#define DECL_EXTERNAL_CODECS_LOC_VARS2
114#define EXTERNAL_CODECS_LOC_VARS2
115#define DECL_EXTERNAL_CODECS_LOC_VARS 119#define DECL_EXTERNAL_CODECS_LOC_VARS
120#define DECL_EXTERNAL_CODECS_LOC_VARS_DECL
121#define EXTERNAL_CODECS_LOC_VARS2
116#define EXTERNAL_CODECS_LOC_VARS 122#define EXTERNAL_CODECS_LOC_VARS
117 123
118#endif 124#endif
@@ -122,7 +128,8 @@ int FindMethod_Index(
122 const AString &name, 128 const AString &name,
123 bool encode, 129 bool encode,
124 CMethodId &methodId, 130 CMethodId &methodId,
125 UInt32 &numStreams); 131 UInt32 &numStreams,
132 bool &isFilter);
126 133
127bool FindMethod( 134bool FindMethod(
128 DECL_EXTERNAL_CODECS_LOC_VARS 135 DECL_EXTERNAL_CODECS_LOC_VARS
diff --git a/CPP/7zip/Common/FilePathAutoRename.h b/CPP/7zip/Common/FilePathAutoRename.h
index 7b57659..ac36882 100644
--- a/CPP/7zip/Common/FilePathAutoRename.h
+++ b/CPP/7zip/Common/FilePathAutoRename.h
@@ -1,7 +1,7 @@
1// FilePathAutoRename.h 1// FilePathAutoRename.h
2 2
3#ifndef __FILE_PATH_AUTO_RENAME_H 3#ifndef ZIP7_INC_FILE_PATH_AUTO_RENAME_H
4#define __FILE_PATH_AUTO_RENAME_H 4#define ZIP7_INC_FILE_PATH_AUTO_RENAME_H
5 5
6#include "../../Common/MyString.h" 6#include "../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/Common/FileStreams.cpp b/CPP/7zip/Common/FileStreams.cpp
index 0349e90..4298636 100644
--- a/CPP/7zip/Common/FileStreams.cpp
+++ b/CPP/7zip/Common/FileStreams.cpp
@@ -12,17 +12,19 @@
12#include <pwd.h> 12#include <pwd.h>
13 13
14// for major()/minor(): 14// for major()/minor():
15#if defined(__FreeBSD__) || defined(BSD)
16#include <sys/types.h> 15#include <sys/types.h>
16#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__)
17#else 17#else
18#ifndef major
18#include <sys/sysmacros.h> 19#include <sys/sysmacros.h>
19#endif 20#endif
20
21#endif 21#endif
22 22
23#endif // _WIN32
24
23#include "../../Windows/FileFind.h" 25#include "../../Windows/FileFind.h"
24 26
25#ifdef SUPPORT_DEVICE_FILE 27#ifdef Z7_DEVICE_FILE
26#include "../../../C/Alloc.h" 28#include "../../../C/Alloc.h"
27#include "../../Common/Defs.h" 29#include "../../Common/Defs.h"
28#endif 30#endif
@@ -47,15 +49,15 @@ static inline HRESULT ConvertBoolToHRESULT(bool result)
47} 49}
48 50
49 51
50#ifdef SUPPORT_DEVICE_FILE 52#ifdef Z7_DEVICE_FILE
51static const UInt32 kClusterSize = 1 << 18; 53static const UInt32 kClusterSize = 1 << 18;
52#endif 54#endif
53 55
54CInFileStream::CInFileStream(): 56CInFileStream::CInFileStream():
55 #ifdef SUPPORT_DEVICE_FILE 57 #ifdef Z7_DEVICE_FILE
56 VirtPos(0), 58 VirtPos(0),
57 PhyPos(0), 59 PhyPos(0),
58 Buf(0), 60 Buf(NULL),
59 BufSize(0), 61 BufSize(0),
60 #endif 62 #endif
61 #ifndef _WIN32 63 #ifndef _WIN32
@@ -73,7 +75,7 @@ CInFileStream::CInFileStream():
73 75
74CInFileStream::~CInFileStream() 76CInFileStream::~CInFileStream()
75{ 77{
76 #ifdef SUPPORT_DEVICE_FILE 78 #ifdef Z7_DEVICE_FILE
77 MidFree(Buf); 79 MidFree(Buf);
78 #endif 80 #endif
79 81
@@ -81,11 +83,11 @@ CInFileStream::~CInFileStream()
81 Callback->InFileStream_On_Destroy(this, CallbackRef); 83 Callback->InFileStream_On_Destroy(this, CallbackRef);
82} 84}
83 85
84STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) 86Z7_COM7F_IMF(CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize))
85{ 87{
86 #ifdef USE_WIN_FILE 88 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
87 89
88 #ifdef SUPPORT_DEVICE_FILE 90 #ifdef Z7_DEVICE_FILE
89 if (processedSize) 91 if (processedSize)
90 *processedSize = 0; 92 *processedSize = 0;
91 if (size == 0) 93 if (size == 0)
@@ -96,7 +98,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
96 { 98 {
97 if (VirtPos >= File.Size) 99 if (VirtPos >= File.Size)
98 return VirtPos == File.Size ? S_OK : E_FAIL; 100 return VirtPos == File.Size ? S_OK : E_FAIL;
99 UInt64 rem = File.Size - VirtPos; 101 const UInt64 rem = File.Size - VirtPos;
100 if (size > rem) 102 if (size > rem)
101 size = (UInt32)rem; 103 size = (UInt32)rem;
102 } 104 }
@@ -104,13 +106,13 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
104 { 106 {
105 const UInt32 mask = kClusterSize - 1; 107 const UInt32 mask = kClusterSize - 1;
106 const UInt64 mask2 = ~(UInt64)mask; 108 const UInt64 mask2 = ~(UInt64)mask;
107 UInt64 alignedPos = VirtPos & mask2; 109 const UInt64 alignedPos = VirtPos & mask2;
108 if (BufSize > 0 && BufStartPos == alignedPos) 110 if (BufSize > 0 && BufStartPos == alignedPos)
109 { 111 {
110 UInt32 pos = (UInt32)VirtPos & mask; 112 const UInt32 pos = (UInt32)VirtPos & mask;
111 if (pos >= BufSize) 113 if (pos >= BufSize)
112 return S_OK; 114 return S_OK;
113 UInt32 rem = MyMin(BufSize - pos, size); 115 const UInt32 rem = MyMin(BufSize - pos, size);
114 memcpy(data, Buf + pos, rem); 116 memcpy(data, Buf + pos, rem);
115 VirtPos += rem; 117 VirtPos += rem;
116 if (processedSize) 118 if (processedSize)
@@ -119,7 +121,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
119 } 121 }
120 122
121 bool useBuf = false; 123 bool useBuf = false;
122 if ((VirtPos & mask) != 0 || ((ptrdiff_t)data & mask) != 0 ) 124 if ((VirtPos & mask) != 0 || ((size_t)(ptrdiff_t)data & mask) != 0 )
123 useBuf = true; 125 useBuf = true;
124 else 126 else
125 { 127 {
@@ -138,7 +140,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
138 if (alignedPos != PhyPos) 140 if (alignedPos != PhyPos)
139 { 141 {
140 UInt64 realNewPosition; 142 UInt64 realNewPosition;
141 bool result = File.Seek((Int64)alignedPos, FILE_BEGIN, realNewPosition); 143 const bool result = File.Seek((Int64)alignedPos, FILE_BEGIN, realNewPosition);
142 if (!result) 144 if (!result)
143 return ConvertBoolToHRESULT(result); 145 return ConvertBoolToHRESULT(result);
144 PhyPos = realNewPosition; 146 PhyPos = realNewPosition;
@@ -155,7 +157,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
155 if (!Buf) 157 if (!Buf)
156 return E_OUTOFMEMORY; 158 return E_OUTOFMEMORY;
157 } 159 }
158 bool result = File.Read1(Buf, readSize, BufSize); 160 const bool result = File.Read1(Buf, readSize, BufSize);
159 if (!result) 161 if (!result)
160 return ConvertBoolToHRESULT(result); 162 return ConvertBoolToHRESULT(result);
161 163
@@ -180,7 +182,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
180 if (processedSize) 182 if (processedSize)
181 *processedSize = realProcessedSize; 183 *processedSize = realProcessedSize;
182 184
183 #ifdef SUPPORT_DEVICE_FILE 185 #ifdef Z7_DEVICE_FILE
184 VirtPos += realProcessedSize; 186 VirtPos += realProcessedSize;
185 PhyPos += realProcessedSize; 187 PhyPos += realProcessedSize;
186 #endif 188 #endif
@@ -188,7 +190,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
188 if (result) 190 if (result)
189 return S_OK; 191 return S_OK;
190 192
191 #else // USE_WIN_FILE 193 #else // Z7_FILE_STREAMS_USE_WIN_FILE
192 194
193 if (processedSize) 195 if (processedSize)
194 *processedSize = 0; 196 *processedSize = 0;
@@ -199,7 +201,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
199 *processedSize = (UInt32)res; 201 *processedSize = (UInt32)res;
200 return S_OK; 202 return S_OK;
201 } 203 }
202 #endif // USE_WIN_FILE 204 #endif // Z7_FILE_STREAMS_USE_WIN_FILE
203 205
204 { 206 {
205 const DWORD error = ::GetLastError(); 207 const DWORD error = ::GetLastError();
@@ -212,7 +214,7 @@ STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
212} 214}
213 215
214#ifdef UNDER_CE 216#ifdef UNDER_CE
215STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) 217Z7_COM7F_IMF(CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize))
216{ 218{
217 size_t s2 = fread(data, 1, size, stdin); 219 size_t s2 = fread(data, 1, size, stdin);
218 int error = ferror(stdin); 220 int error = ferror(stdin);
@@ -223,7 +225,7 @@ STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSi
223 return E_FAIL; 225 return E_FAIL;
224} 226}
225#else 227#else
226STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize) 228Z7_COM7F_IMF(CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize))
227{ 229{
228 #ifdef _WIN32 230 #ifdef _WIN32
229 231
@@ -259,14 +261,14 @@ STDMETHODIMP CStdInFileStream::Read(void *data, UInt32 size, UInt32 *processedSi
259 261
260#endif 262#endif
261 263
262STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 264Z7_COM7F_IMF(CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
263{ 265{
264 if (seekOrigin >= 3) 266 if (seekOrigin >= 3)
265 return STG_E_INVALIDFUNCTION; 267 return STG_E_INVALIDFUNCTION;
266 268
267 #ifdef USE_WIN_FILE 269 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
268 270
269 #ifdef SUPPORT_DEVICE_FILE 271 #ifdef Z7_DEVICE_FILE
270 if (File.IsDeviceFile && (File.SizeDefined || seekOrigin != STREAM_SEEK_END)) 272 if (File.IsDeviceFile && (File.SizeDefined || seekOrigin != STREAM_SEEK_END))
271 { 273 {
272 switch (seekOrigin) 274 switch (seekOrigin)
@@ -293,7 +295,7 @@ STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
293 in case of error. So we don't need additional code below */ 295 in case of error. So we don't need additional code below */
294 // if (!result) { realNewPosition = 0; File.GetPosition(realNewPosition); } 296 // if (!result) { realNewPosition = 0; File.GetPosition(realNewPosition); }
295 297
296 #ifdef SUPPORT_DEVICE_FILE 298 #ifdef Z7_DEVICE_FILE
297 PhyPos = VirtPos = realNewPosition; 299 PhyPos = VirtPos = realNewPosition;
298 #endif 300 #endif
299 301
@@ -319,17 +321,19 @@ STDMETHODIMP CInFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
319 #endif 321 #endif
320} 322}
321 323
322STDMETHODIMP CInFileStream::GetSize(UInt64 *size) 324Z7_COM7F_IMF(CInFileStream::GetSize(UInt64 *size))
323{ 325{
324 return ConvertBoolToHRESULT(File.GetLength(*size)); 326 return ConvertBoolToHRESULT(File.GetLength(*size));
325} 327}
326 328
327#ifdef USE_WIN_FILE 329#ifdef Z7_FILE_STREAMS_USE_WIN_FILE
328 330
329STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) 331Z7_COM7F_IMF(CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib))
330{ 332{
331 if (!_info_WasLoaded) 333 if (!_info_WasLoaded)
332 RINOK(ReloadProps()); 334 {
335 RINOK(ReloadProps())
336 }
333 const BY_HANDLE_FILE_INFORMATION &info = _info; 337 const BY_HANDLE_FILE_INFORMATION &info = _info;
334 /* 338 /*
335 BY_HANDLE_FILE_INFORMATION info; 339 BY_HANDLE_FILE_INFORMATION info;
@@ -346,10 +350,12 @@ STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aT
346 } 350 }
347} 351}
348 352
349STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props) 353Z7_COM7F_IMF(CInFileStream::GetProps2(CStreamFileProps *props))
350{ 354{
351 if (!_info_WasLoaded) 355 if (!_info_WasLoaded)
352 RINOK(ReloadProps()); 356 {
357 RINOK(ReloadProps())
358 }
353 const BY_HANDLE_FILE_INFORMATION &info = _info; 359 const BY_HANDLE_FILE_INFORMATION &info = _info;
354 /* 360 /*
355 BY_HANDLE_FILE_INFORMATION info; 361 BY_HANDLE_FILE_INFORMATION info;
@@ -370,17 +376,19 @@ STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props)
370 } 376 }
371} 377}
372 378
373STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) 379Z7_COM7F_IMF(CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value))
374{ 380{
375 if (!_info_WasLoaded) 381 if (!_info_WasLoaded)
376 RINOK(ReloadProps()); 382 {
383 RINOK(ReloadProps())
384 }
377 385
378 if (!_info_WasLoaded) 386 if (!_info_WasLoaded)
379 return S_OK; 387 return S_OK;
380 388
381 NWindows::NCOM::CPropVariant prop; 389 NWindows::NCOM::CPropVariant prop;
382 390
383 #ifdef SUPPORT_DEVICE_FILE 391 #ifdef Z7_DEVICE_FILE
384 if (File.IsDeviceFile) 392 if (File.IsDeviceFile)
385 { 393 {
386 switch (propID) 394 switch (propID)
@@ -436,9 +444,9 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)
436} 444}
437 445
438 446
439STDMETHODIMP CInFileStream::ReloadProps() 447Z7_COM7F_IMF(CInFileStream::ReloadProps())
440{ 448{
441 #ifdef SUPPORT_DEVICE_FILE 449 #ifdef Z7_DEVICE_FILE
442 if (File.IsDeviceFile) 450 if (File.IsDeviceFile)
443 { 451 {
444 memset(&_info, 0, sizeof(_info)); 452 memset(&_info, 0, sizeof(_info));
@@ -461,10 +469,12 @@ STDMETHODIMP CInFileStream::ReloadProps()
461 469
462#elif !defined(_WIN32) 470#elif !defined(_WIN32)
463 471
464STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) 472Z7_COM7F_IMF(CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib))
465{ 473{
466 if (!_info_WasLoaded) 474 if (!_info_WasLoaded)
467 RINOK(ReloadProps()); 475 {
476 RINOK(ReloadProps())
477 }
468 const struct stat &st = _info; 478 const struct stat &st = _info;
469 /* 479 /*
470 struct stat st; 480 struct stat st;
@@ -483,10 +493,12 @@ STDMETHODIMP CInFileStream::GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aT
483 493
484// #include <stdio.h> 494// #include <stdio.h>
485 495
486STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props) 496Z7_COM7F_IMF(CInFileStream::GetProps2(CStreamFileProps *props))
487{ 497{
488 if (!_info_WasLoaded) 498 if (!_info_WasLoaded)
489 RINOK(ReloadProps()); 499 {
500 RINOK(ReloadProps())
501 }
490 const struct stat &st = _info; 502 const struct stat &st = _info;
491 /* 503 /*
492 struct stat st; 504 struct stat st;
@@ -521,10 +533,12 @@ STDMETHODIMP CInFileStream::GetProps2(CStreamFileProps *props)
521 return S_OK; 533 return S_OK;
522} 534}
523 535
524STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value) 536Z7_COM7F_IMF(CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value))
525{ 537{
526 if (!_info_WasLoaded) 538 if (!_info_WasLoaded)
527 RINOK(ReloadProps()); 539 {
540 RINOK(ReloadProps())
541 }
528 542
529 if (!_info_WasLoaded) 543 if (!_info_WasLoaded)
530 return S_OK; 544 return S_OK;
@@ -544,6 +558,11 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)
544 case kpidMTime: PropVariant_SetFrom_FiTime(prop, ST_MTIME(st)); break; 558 case kpidMTime: PropVariant_SetFrom_FiTime(prop, ST_MTIME(st)); break;
545 case kpidPosixAttrib: prop = (UInt32)st.st_mode; break; 559 case kpidPosixAttrib: prop = (UInt32)st.st_mode; break;
546 560
561 #if defined(__APPLE__)
562 #pragma GCC diagnostic push
563 #pragma GCC diagnostic ignored "-Wsign-conversion"
564 #endif
565
547 case kpidDeviceMajor: 566 case kpidDeviceMajor:
548 { 567 {
549 // printf("\nst.st_rdev = %d\n", st.st_rdev); 568 // printf("\nst.st_rdev = %d\n", st.st_rdev);
@@ -563,6 +582,10 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)
563 // prop = (UInt32)123456789; // for debug 582 // prop = (UInt32)123456789; // for debug
564 break; 583 break;
565 584
585 #if defined(__APPLE__)
586 #pragma GCC diagnostic pop
587 #endif
588
566 /* 589 /*
567 case kpidDevice: 590 case kpidDevice:
568 if (S_ISCHR(st.st_mode) || 591 if (S_ISCHR(st.st_mode) ||
@@ -632,7 +655,7 @@ STDMETHODIMP CInFileStream::GetProperty(PROPID propID, PROPVARIANT *value)
632} 655}
633 656
634 657
635STDMETHODIMP CInFileStream::ReloadProps() 658Z7_COM7F_IMF(CInFileStream::ReloadProps())
636{ 659{
637 _info_WasLoaded = (File.my_fstat(&_info) == 0); 660 _info_WasLoaded = (File.my_fstat(&_info) == 0);
638 if (!_info_WasLoaded) 661 if (!_info_WasLoaded)
@@ -653,9 +676,9 @@ HRESULT COutFileStream::Close()
653 return ConvertBoolToHRESULT(File.Close()); 676 return ConvertBoolToHRESULT(File.Close());
654} 677}
655 678
656STDMETHODIMP COutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 679Z7_COM7F_IMF(COutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
657{ 680{
658 #ifdef USE_WIN_FILE 681 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
659 682
660 UInt32 realProcessedSize; 683 UInt32 realProcessedSize;
661 const bool result = File.Write(data, size, realProcessedSize); 684 const bool result = File.Write(data, size, realProcessedSize);
@@ -680,12 +703,12 @@ STDMETHODIMP COutFileStream::Write(const void *data, UInt32 size, UInt32 *proces
680 #endif 703 #endif
681} 704}
682 705
683STDMETHODIMP COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 706Z7_COM7F_IMF(COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
684{ 707{
685 if (seekOrigin >= 3) 708 if (seekOrigin >= 3)
686 return STG_E_INVALIDFUNCTION; 709 return STG_E_INVALIDFUNCTION;
687 710
688 #ifdef USE_WIN_FILE 711 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
689 712
690 UInt64 realNewPosition = 0; 713 UInt64 realNewPosition = 0;
691 const bool result = File.Seek(offset, seekOrigin, realNewPosition); 714 const bool result = File.Seek(offset, seekOrigin, realNewPosition);
@@ -705,7 +728,7 @@ STDMETHODIMP COutFileStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo
705 #endif 728 #endif
706} 729}
707 730
708STDMETHODIMP COutFileStream::SetSize(UInt64 newSize) 731Z7_COM7F_IMF(COutFileStream::SetSize(UInt64 newSize))
709{ 732{
710 return ConvertBoolToHRESULT(File.SetLength_KeepPosition(newSize)); 733 return ConvertBoolToHRESULT(File.SetLength_KeepPosition(newSize));
711} 734}
@@ -717,7 +740,7 @@ HRESULT COutFileStream::GetSize(UInt64 *size)
717 740
718#ifdef UNDER_CE 741#ifdef UNDER_CE
719 742
720STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 743Z7_COM7F_IMF(CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
721{ 744{
722 size_t s2 = fwrite(data, 1, size, stdout); 745 size_t s2 = fwrite(data, 1, size, stdout);
723 if (processedSize) 746 if (processedSize)
@@ -727,7 +750,7 @@ STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *pro
727 750
728#else 751#else
729 752
730STDMETHODIMP CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 753Z7_COM7F_IMF(CStdOutFileStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
731{ 754{
732 if (processedSize) 755 if (processedSize)
733 *processedSize = 0; 756 *processedSize = 0;
diff --git a/CPP/7zip/Common/FileStreams.h b/CPP/7zip/Common/FileStreams.h
index f2c19ee..7e1b086 100644
--- a/CPP/7zip/Common/FileStreams.h
+++ b/CPP/7zip/Common/FileStreams.h
@@ -1,10 +1,10 @@
1// FileStreams.h 1// FileStreams.h
2 2
3#ifndef __FILE_STREAMS_H 3#ifndef ZIP7_INC_FILE_STREAMS_H
4#define __FILE_STREAMS_H 4#define ZIP7_INC_FILE_STREAMS_H
5 5
6#ifdef _WIN32 6#ifdef _WIN32
7#define USE_WIN_FILE 7#define Z7_FILE_STREAMS_USE_WIN_FILE
8#endif 8#endif
9 9
10#include "../../Common/MyCom.h" 10#include "../../Common/MyCom.h"
@@ -18,13 +18,27 @@
18 18
19 19
20class CInFileStream; 20class CInFileStream;
21struct IInFileStream_Callback 21
22Z7_PURE_INTERFACES_BEGIN
23DECLARE_INTERFACE(IInFileStream_Callback)
22{ 24{
23 virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error) = 0; 25 virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error) = 0;
24 virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val) = 0; 26 virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val) = 0;
25}; 27};
26 28Z7_PURE_INTERFACES_END
27class CInFileStream: 29
30
31/*
32Z7_CLASS_IMP_COM_5(
33 CInFileStream
34 , IInStream
35 , IStreamGetSize
36 , IStreamGetProps
37 , IStreamGetProps2
38 , IStreamGetProp
39)
40*/
41Z7_class_final(CInFileStream) :
28 public IInStream, 42 public IInStream,
29 public IStreamGetSize, 43 public IStreamGetSize,
30 public IStreamGetProps, 44 public IStreamGetProps,
@@ -32,12 +46,30 @@ class CInFileStream:
32 public IStreamGetProp, 46 public IStreamGetProp,
33 public CMyUnknownImp 47 public CMyUnknownImp
34{ 48{
49 Z7_COM_UNKNOWN_IMP_5(
50 IInStream,
51 IStreamGetSize,
52 IStreamGetProps,
53 IStreamGetProps2,
54 IStreamGetProp)
55
56 Z7_IFACE_COM7_IMP(ISequentialInStream)
57 Z7_IFACE_COM7_IMP(IInStream)
58public:
59 Z7_IFACE_COM7_IMP(IStreamGetSize)
60private:
61 Z7_IFACE_COM7_IMP(IStreamGetProps)
62public:
63 Z7_IFACE_COM7_IMP(IStreamGetProps2)
64 Z7_IFACE_COM7_IMP(IStreamGetProp)
65
66private:
35 NWindows::NFile::NIO::CInFile File; 67 NWindows::NFile::NIO::CInFile File;
36public: 68public:
37 69
38 #ifdef USE_WIN_FILE 70 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
39 71
40 #ifdef SUPPORT_DEVICE_FILE 72 #ifdef Z7_DEVICE_FILE
41 UInt64 VirtPos; 73 UInt64 VirtPos;
42 UInt64 PhyPos; 74 UInt64 PhyPos;
43 UInt64 BufStartPos; 75 UInt64 BufStartPos;
@@ -64,9 +96,8 @@ public:
64 IInFileStream_Callback *Callback; 96 IInFileStream_Callback *Callback;
65 UINT_PTR CallbackRef; 97 UINT_PTR CallbackRef;
66 98
67 virtual ~CInFileStream();
68
69 CInFileStream(); 99 CInFileStream();
100 ~CInFileStream();
70 101
71 void Set_PreserveATime(bool v) 102 void Set_PreserveATime(bool v)
72 { 103 {
@@ -89,44 +120,25 @@ public:
89 _info_WasLoaded = false; 120 _info_WasLoaded = false;
90 return File.OpenShared(fileName, shareForWrite); 121 return File.OpenShared(fileName, shareForWrite);
91 } 122 }
92
93 MY_QUERYINTERFACE_BEGIN2(IInStream)
94 MY_QUERYINTERFACE_ENTRY(IStreamGetSize)
95 MY_QUERYINTERFACE_ENTRY(IStreamGetProps)
96 MY_QUERYINTERFACE_ENTRY(IStreamGetProps2)
97 MY_QUERYINTERFACE_ENTRY(IStreamGetProp)
98 MY_QUERYINTERFACE_END
99 MY_ADDREF_RELEASE
100
101 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
102 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
103
104 STDMETHOD(GetSize)(UInt64 *size);
105 STDMETHOD(GetProps)(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib);
106 STDMETHOD(GetProps2)(CStreamFileProps *props);
107 STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value);
108 STDMETHOD(ReloadProps)();
109}; 123};
110 124
111class CStdInFileStream:
112 public ISequentialInStream,
113 public CMyUnknownImp
114{
115public:
116 MY_UNKNOWN_IMP
117 125
118 virtual ~CStdInFileStream() {} 126Z7_CLASS_IMP_NOQIB_1(
119 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 127 CStdInFileStream
128 , ISequentialInStream
129)
120}; 130};
121 131
122class COutFileStream: 132
123 public IOutStream, 133Z7_CLASS_IMP_COM_1(
124 public CMyUnknownImp 134 COutFileStream
125{ 135 , IOutStream
136)
137 Z7_IFACE_COM7_IMP(ISequentialOutStream)
126public: 138public:
139
127 NWindows::NFile::NIO::COutFile File; 140 NWindows::NFile::NIO::COutFile File;
128 141
129 virtual ~COutFileStream() {}
130 bool Create(CFSTR fileName, bool createAlways) 142 bool Create(CFSTR fileName, bool createAlways)
131 { 143 {
132 ProcessedSize = 0; 144 ProcessedSize = 0;
@@ -148,15 +160,9 @@ public:
148 } 160 }
149 bool SetMTime(const CFiTime *mTime) { return File.SetMTime(mTime); } 161 bool SetMTime(const CFiTime *mTime) { return File.SetMTime(mTime); }
150 162
151 MY_UNKNOWN_IMP1(IOutStream)
152
153 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
154 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
155 STDMETHOD(SetSize)(UInt64 newSize);
156
157 bool SeekToBegin_bool() 163 bool SeekToBegin_bool()
158 { 164 {
159 #ifdef USE_WIN_FILE 165 #ifdef Z7_FILE_STREAMS_USE_WIN_FILE
160 return File.SeekToBegin(); 166 return File.SeekToBegin();
161 #else 167 #else
162 return File.seekToBegin() == 0; 168 return File.seekToBegin() == 0;
@@ -166,18 +172,15 @@ public:
166 HRESULT GetSize(UInt64 *size); 172 HRESULT GetSize(UInt64 *size);
167}; 173};
168 174
169class CStdOutFileStream: 175
170 public ISequentialOutStream, 176Z7_CLASS_IMP_NOQIB_1(
171 public CMyUnknownImp 177 CStdOutFileStream
172{ 178 , ISequentialOutStream
179)
173 UInt64 _size; 180 UInt64 _size;
174public: 181public:
175 MY_UNKNOWN_IMP
176
177 UInt64 GetSize() const { return _size; } 182 UInt64 GetSize() const { return _size; }
178 CStdOutFileStream(): _size(0) {} 183 CStdOutFileStream(): _size(0) {}
179 virtual ~CStdOutFileStream() {}
180 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
181}; 184};
182 185
183#endif 186#endif
diff --git a/CPP/7zip/Common/FilterCoder.cpp b/CPP/7zip/Common/FilterCoder.cpp
index fb99f61..8d7e0dc 100644
--- a/CPP/7zip/Common/FilterCoder.cpp
+++ b/CPP/7zip/Common/FilterCoder.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5// #include <stdio.h>
6
5#include "../../Common/Defs.h" 7#include "../../Common/Defs.h"
6 8
7#include "FilterCoder.h" 9#include "FilterCoder.h"
@@ -33,13 +35,17 @@ void CAlignedMidBuffer::AllocAligned(size_t size)
33 35
34 Some filters (BCJ and others) don't process data at the end of stream in some cases. 36 Some filters (BCJ and others) don't process data at the end of stream in some cases.
35 So the encoder and decoder write such last bytes without change. 37 So the encoder and decoder write such last bytes without change.
38
39 Most filters process all data, if we send aligned size to filter.
40 But BCJ filter can process up 4 bytes less than sent size.
41 And ARMT filter can process 2 bytes less than sent size.
36*/ 42*/
37 43
38 44
39static const UInt32 kBufSize = 1 << 20; 45static const UInt32 kBufSize = 1 << 21;
40 46
41STDMETHODIMP CFilterCoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSize = size; return S_OK; } 47Z7_COM7F_IMF(CFilterCoder::SetInBufSize(UInt32 , UInt32 size)) { _inBufSize = size; return S_OK; }
42STDMETHODIMP CFilterCoder::SetOutBufSize(UInt32 , UInt32 size) { _outBufSize = size; return S_OK; } 48Z7_COM7F_IMF(CFilterCoder::SetOutBufSize(UInt32 , UInt32 size)) { _outBufSize = size; return S_OK; }
43 49
44HRESULT CFilterCoder::Alloc() 50HRESULT CFilterCoder::Alloc()
45{ 51{
@@ -51,6 +57,7 @@ HRESULT CFilterCoder::Alloc()
51 size &= ~(UInt32)(kMinSize - 1); 57 size &= ~(UInt32)(kMinSize - 1);
52 if (size < kMinSize) 58 if (size < kMinSize)
53 size = kMinSize; 59 size = kMinSize;
60 // size = (1 << 12); // + 117; // for debug
54 if (!_buf || _bufSize != size) 61 if (!_buf || _bufSize != size)
55 { 62 {
56 AllocAligned(size); 63 AllocAligned(size);
@@ -63,7 +70,7 @@ HRESULT CFilterCoder::Alloc()
63 70
64HRESULT CFilterCoder::Init_and_Alloc() 71HRESULT CFilterCoder::Init_and_Alloc()
65{ 72{
66 RINOK(Filter->Init()); 73 RINOK(Filter->Init())
67 return Alloc(); 74 return Alloc();
68} 75}
69 76
@@ -72,78 +79,197 @@ CFilterCoder::CFilterCoder(bool encodeMode):
72 _inBufSize(kBufSize), 79 _inBufSize(kBufSize),
73 _outBufSize(kBufSize), 80 _outBufSize(kBufSize),
74 _encodeMode(encodeMode), 81 _encodeMode(encodeMode),
75 _outSizeIsDefined(false), 82 _outSize_Defined(false),
76 _outSize(0), 83 _outSize(0),
77 _nowPos64(0) 84 _nowPos64(0)
78 {} 85 {}
79 86
80CFilterCoder::~CFilterCoder()
81{
82}
83 87
84STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 88Z7_COM7F_IMF(CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
85 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 89 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
86{ 90{
87 RINOK(Init_and_Alloc()); 91 RINOK(Init_and_Alloc())
88 92
93 /*
94 It's expected that BCJ/ARMT filter can process up to 4 bytes less
95 than sent data size. For such BCJ/ARMT cases with non-filtered data we:
96 - write some filtered data to output stream
97 - move non-written data (filtered and non-filtered data) to start of buffer
98 - read more new data from input stream to position after end of non-filtered data
99 - call Filter() for concatenated data in buffer.
100
101 For all cases, even for cases with partial filtering (BCJ/ARMT),
102 we try to keep real/virtual alignment for all operations
103 (memmove, Read(), Filter(), Write()).
104 We use (kAlignSize=64) alignmnent that is larger than (16-bytes)
105 required for AES filter alignment.
106
107 AES-CBC uses 16-bytes blocks, that is simple case for processing here,
108 if we call Filter() for aligned size for all calls except of last call (last block).
109 And now there are no filters that use blocks with non-power2 size,
110 but we try to support such non-power2 filters too here at Code().
111 */
112
89 UInt64 prev = 0; 113 UInt64 prev = 0;
90 UInt64 nowPos64 = 0; 114 UInt64 nowPos64 = 0;
91 bool inputFinished = false; 115 bool inputFinished = false;
92 UInt32 pos = 0; 116 UInt32 readPos = 0;
117 UInt32 filterPos = 0;
93 118
94 while (!outSize || nowPos64 < *outSize) 119 while (!outSize || nowPos64 < *outSize)
95 { 120 {
121 HRESULT hres = S_OK;
96 if (!inputFinished) 122 if (!inputFinished)
97 { 123 {
98 size_t processedSize = _bufSize - pos; 124 size_t processedSize = _bufSize - readPos;
99 RINOK(ReadStream(inStream, _buf + pos, &processedSize)); 125 /* for AES filters we need at least max(16, kAlignSize) bytes in buffer.
100 pos += (UInt32)processedSize; 126 But we try to read full buffer to reduce the number of Filter() and Write() calls.
101 inputFinished = (pos != _bufSize); 127 */
128 hres = ReadStream(inStream, _buf + readPos, &processedSize);
129 readPos += (UInt32)processedSize;
130 inputFinished = (readPos != _bufSize);
131 if (hres != S_OK)
132 {
133 // do we need to stop encoding after reading error?
134 // if (_encodeMode) return hres;
135 inputFinished = true;
136 }
137 }
138
139 if (readPos == 0)
140 return hres;
141
142 /* we set (needMoreInput = true), if it's block-filter (like AES-CBC)
143 that needs more data for current block filtering:
144 We read full input buffer with Read(), and _bufSize is aligned,
145 So the possible cases when we set (needMoreInput = true) are:
146 1) decode : filter needs more data after the end of input stream.
147 another cases are possible for non-power2-block-filter,
148 because buffer size is not aligned for filter_non_power2_block_size:
149 2) decode/encode : filter needs more data from non-finished input stream
150 3) encode : filter needs more space for zeros after the end of input stream
151 */
152 bool needMoreInput = false;
153
154 while (readPos != filterPos)
155 {
156 /* Filter() is allowed to process part of data.
157 Here we use the loop to filter as max as possible.
158 when we call Filter(data, size):
159 if (size < 16), AES-CTR filter uses internal 16-byte buffer.
160 new (since v23.00) AES-CTR filter allows (size < 16) for non-last block,
161 but it will work less efficiently than calls with aligned (size).
162 We still support old (before v23.00) AES-CTR filters here.
163 We have aligned (size) for AES-CTR, if it's not last block.
164 We have aligned (readPos) for any filter, if (!inputFinished).
165 We also meet the requirements for (data) pointer in Filter() call:
166 {
167 (virtual_stream_offset % aligment_size) == (data_ptr % aligment_size)
168 (aligment_size == 2^N)
169 (aligment_size >= 16)
170 }
171 */
172 const UInt32 cur = Filter->Filter(_buf + filterPos, readPos - filterPos);
173 if (cur == 0)
174 break;
175 const UInt32 f = filterPos + cur;
176 if (cur > readPos - filterPos)
177 {
178 // AES-CBC
179 if (hres != S_OK)
180 break;
181
182 if (!_encodeMode
183 || cur > _bufSize - filterPos
184 || !inputFinished)
185 {
186 /* (cur > _bufSize - filterPos) is unexpected for AES filter, if _bufSize is multiply of 16.
187 But we support this case, if some future filter will use block with non-power2-size.
188 */
189 needMoreInput = true;
190 break;
191 }
192
193 /* (_encodeMode && inputFinished).
194 We add zero bytes as pad in current block after the end of read data. */
195 Byte *buf = _buf;
196 do
197 buf[readPos] = 0;
198 while (++readPos != f);
199 // (readPos) now is (size_of_real_input_data + size_of_zero_pad)
200 if (cur != Filter->Filter(buf + filterPos, cur))
201 return E_FAIL;
202 }
203 filterPos = f;
102 } 204 }
103 205
104 if (pos == 0) 206 UInt32 size = filterPos;
105 return S_OK; 207 if (hres == S_OK)
208 {
209 /* If we need more Read() or Filter() calls, then we need to Write()
210 some data and move unwritten data to get additional space in buffer.
211 We try to keep alignment for data moves, Read(), Filter() and Write() calls.
212 */
213 const UInt32 kAlignSize = 1 << 6;
214 const UInt32 alignedFiltered = filterPos & ~(kAlignSize - 1);
215 if (inputFinished)
216 {
217 if (!needMoreInput)
218 size = readPos; // for risc/bcj filters in last block we write data after filterPos.
219 else if (_encodeMode)
220 size = alignedFiltered; // for non-power2-block-encode-filter
221 }
222 else
223 size = alignedFiltered;
224 }
106 225
107 UInt32 filtered = Filter->Filter(_buf, pos);
108
109 if (filtered > pos)
110 { 226 {
111 // AES 227 UInt32 writeSize = size;
112 if (!inputFinished || filtered > _bufSize) 228 if (outSize)
113 return E_FAIL; 229 {
230 const UInt64 rem = *outSize - nowPos64;
231 if (writeSize > rem)
232 writeSize = (UInt32)rem;
233 }
234 RINOK(WriteStream(outStream, _buf, writeSize))
235 nowPos64 += writeSize;
236 }
237
238 if (hres != S_OK)
239 return hres;
240
241 if (inputFinished)
242 {
243 if (readPos == size)
244 return hres;
114 if (!_encodeMode) 245 if (!_encodeMode)
246 {
247 // block-decode-filter (AES-CBS) has non-full last block
248 // we don't want unaligned data move for more iterations with this error case.
115 return S_FALSE; 249 return S_FALSE;
116 250 }
117 Byte *buf = _buf;
118 do
119 buf[pos] = 0;
120 while (++pos != filtered);
121
122 if (filtered != Filter->Filter(buf, filtered))
123 return E_FAIL;
124 } 251 }
125 252
126 UInt32 size = (filtered != 0 ? filtered : pos); 253 if (size == 0)
127 if (outSize)
128 { 254 {
129 const UInt64 remSize = *outSize - nowPos64; 255 // it's unexpected that we have no any move in this iteration.
130 if (size > remSize) 256 return E_FAIL;
131 size = (UInt32)remSize;
132 } 257 }
133 258 // if (size != 0)
134 RINOK(WriteStream(outStream, _buf, size)); 259 {
135 nowPos64 += size; 260 if (filterPos < size)
136 261 return E_FAIL; // filterPos = 0; else
137 if (filtered == 0) 262 filterPos -= size;
138 return S_OK; 263 readPos -= size;
139 pos -= filtered; 264 if (readPos != 0)
140 for (UInt32 i = 0; i < pos; i++) 265 memmove(_buf, _buf + size, readPos);
141 _buf[i] = _buf[filtered++]; 266 }
267 // printf("\nnowPos64=%x, readPos=%x, filterPos=%x\n", (unsigned)nowPos64, (unsigned)readPos, (unsigned)filterPos);
142 268
143 if (progress && (nowPos64 - prev) >= (1 << 22)) 269 if (progress && (nowPos64 - prev) >= (1 << 22))
144 { 270 {
145 prev = nowPos64; 271 prev = nowPos64;
146 RINOK(progress->SetRatioInfo(&nowPos64, &nowPos64)); 272 RINOK(progress->SetRatioInfo(&nowPos64, &nowPos64))
147 } 273 }
148 } 274 }
149 275
@@ -154,13 +280,13 @@ STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, ISequentialOutStr
154 280
155// ---------- Write to Filter ---------- 281// ---------- Write to Filter ----------
156 282
157STDMETHODIMP CFilterCoder::SetOutStream(ISequentialOutStream *outStream) 283Z7_COM7F_IMF(CFilterCoder::SetOutStream(ISequentialOutStream *outStream))
158{ 284{
159 _outStream = outStream; 285 _outStream = outStream;
160 return S_OK; 286 return S_OK;
161} 287}
162 288
163STDMETHODIMP CFilterCoder::ReleaseOutStream() 289Z7_COM7F_IMF(CFilterCoder::ReleaseOutStream())
164{ 290{
165 _outStream.Release(); 291 _outStream.Release();
166 return S_OK; 292 return S_OK;
@@ -171,9 +297,9 @@ HRESULT CFilterCoder::Flush2()
171 while (_convSize != 0) 297 while (_convSize != 0)
172 { 298 {
173 UInt32 num = _convSize; 299 UInt32 num = _convSize;
174 if (_outSizeIsDefined) 300 if (_outSize_Defined)
175 { 301 {
176 UInt64 rem = _outSize - _nowPos64; 302 const UInt64 rem = _outSize - _nowPos64;
177 if (num > rem) 303 if (num > rem)
178 num = (UInt32)rem; 304 num = (UInt32)rem;
179 if (num == 0) 305 if (num == 0)
@@ -181,21 +307,23 @@ HRESULT CFilterCoder::Flush2()
181 } 307 }
182 308
183 UInt32 processed = 0; 309 UInt32 processed = 0;
184 HRESULT res = _outStream->Write(_buf + _convPos, num, &processed); 310 const HRESULT res = _outStream->Write(_buf + _convPos, num, &processed);
185 if (processed == 0) 311 if (processed == 0)
186 return res != S_OK ? res : E_FAIL; 312 return res != S_OK ? res : E_FAIL;
187 313
188 _convPos += processed; 314 _convPos += processed;
189 _convSize -= processed; 315 _convSize -= processed;
190 _nowPos64 += processed; 316 _nowPos64 += processed;
191 RINOK(res); 317 RINOK(res)
192 } 318 }
193 319
194 if (_convPos != 0) 320 const UInt32 convPos = _convPos;
321 if (convPos != 0)
195 { 322 {
196 UInt32 num = _bufPos - _convPos; 323 const UInt32 num = _bufPos - convPos;
324 Byte *buf = _buf;
197 for (UInt32 i = 0; i < num; i++) 325 for (UInt32 i = 0; i < num; i++)
198 _buf[i] = _buf[_convPos + i]; 326 buf[i] = buf[convPos + i];
199 _bufPos = num; 327 _bufPos = num;
200 _convPos = 0; 328 _convPos = 0;
201 } 329 }
@@ -203,14 +331,14 @@ HRESULT CFilterCoder::Flush2()
203 return S_OK; 331 return S_OK;
204} 332}
205 333
206STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize) 334Z7_COM7F_IMF(CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize))
207{ 335{
208 if (processedSize) 336 if (processedSize)
209 *processedSize = 0; 337 *processedSize = 0;
210 338
211 while (size != 0) 339 while (size != 0)
212 { 340 {
213 RINOK(Flush2()); 341 RINOK(Flush2())
214 342
215 // _convSize is 0 343 // _convSize is 0
216 // _convPos is 0 344 // _convPos is 0
@@ -245,20 +373,22 @@ STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processe
245 return S_OK; 373 return S_OK;
246} 374}
247 375
248STDMETHODIMP CFilterCoder::OutStreamFinish() 376Z7_COM7F_IMF(CFilterCoder::OutStreamFinish())
249{ 377{
250 for (;;) 378 for (;;)
251 { 379 {
252 RINOK(Flush2()); 380 RINOK(Flush2())
253 if (_bufPos == 0) 381 if (_bufPos == 0)
254 break; 382 break;
255 _convSize = Filter->Filter(_buf, _bufPos); 383 const UInt32 convSize = Filter->Filter(_buf, _bufPos);
256 if (_convSize == 0) 384 _convSize = convSize;
257 _convSize = _bufPos; 385 UInt32 bufPos = _bufPos;
258 else if (_convSize > _bufPos) 386 if (convSize == 0)
387 _convSize = bufPos;
388 else if (convSize > bufPos)
259 { 389 {
260 // AES 390 // AES
261 if (_convSize > _bufSize) 391 if (convSize > _bufSize)
262 { 392 {
263 _convSize = 0; 393 _convSize = 0;
264 return E_FAIL; 394 return E_FAIL;
@@ -268,9 +398,11 @@ STDMETHODIMP CFilterCoder::OutStreamFinish()
268 _convSize = 0; 398 _convSize = 0;
269 return S_FALSE; 399 return S_FALSE;
270 } 400 }
271 for (; _bufPos < _convSize; _bufPos++) 401 Byte *buf = _buf;
272 _buf[_bufPos] = 0; 402 for (; bufPos < convSize; bufPos++)
273 _convSize = Filter->Filter(_buf, _bufPos); 403 buf[bufPos] = 0;
404 _bufPos = bufPos;
405 _convSize = Filter->Filter(_buf, bufPos);
274 if (_convSize != _bufPos) 406 if (_convSize != _bufPos)
275 return E_FAIL; 407 return E_FAIL;
276 } 408 }
@@ -285,7 +417,7 @@ STDMETHODIMP CFilterCoder::OutStreamFinish()
285 417
286// ---------- Init functions ---------- 418// ---------- Init functions ----------
287 419
288STDMETHODIMP CFilterCoder::InitEncoder() 420Z7_COM7F_IMF(CFilterCoder::InitEncoder())
289{ 421{
290 InitSpecVars(); 422 InitSpecVars();
291 return Init_and_Alloc(); 423 return Init_and_Alloc();
@@ -297,33 +429,33 @@ HRESULT CFilterCoder::Init_NoSubFilterInit()
297 return Alloc(); 429 return Alloc();
298} 430}
299 431
300STDMETHODIMP CFilterCoder::SetOutStreamSize(const UInt64 *outSize) 432Z7_COM7F_IMF(CFilterCoder::SetOutStreamSize(const UInt64 *outSize))
301{ 433{
302 InitSpecVars(); 434 InitSpecVars();
303 if (outSize) 435 if (outSize)
304 { 436 {
305 _outSize = *outSize; 437 _outSize = *outSize;
306 _outSizeIsDefined = true; 438 _outSize_Defined = true;
307 } 439 }
308 return Init_and_Alloc(); 440 return Init_and_Alloc();
309} 441}
310 442
311// ---------- Read from Filter ---------- 443// ---------- Read from Filter ----------
312 444
313STDMETHODIMP CFilterCoder::SetInStream(ISequentialInStream *inStream) 445Z7_COM7F_IMF(CFilterCoder::SetInStream(ISequentialInStream *inStream))
314{ 446{
315 _inStream = inStream; 447 _inStream = inStream;
316 return S_OK; 448 return S_OK;
317} 449}
318 450
319STDMETHODIMP CFilterCoder::ReleaseInStream() 451Z7_COM7F_IMF(CFilterCoder::ReleaseInStream())
320{ 452{
321 _inStream.Release(); 453 _inStream.Release();
322 return S_OK; 454 return S_OK;
323} 455}
324 456
325 457
326STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) 458Z7_COM7F_IMF(CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize))
327{ 459{
328 if (processedSize) 460 if (processedSize)
329 *processedSize = 0; 461 *processedSize = 0;
@@ -334,9 +466,9 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
334 { 466 {
335 if (size > _convSize) 467 if (size > _convSize)
336 size = _convSize; 468 size = _convSize;
337 if (_outSizeIsDefined) 469 if (_outSize_Defined)
338 { 470 {
339 UInt64 rem = _outSize - _nowPos64; 471 const UInt64 rem = _outSize - _nowPos64;
340 if (size > rem) 472 if (size > rem)
341 size = (UInt32)rem; 473 size = (UInt32)rem;
342 } 474 }
@@ -349,46 +481,51 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
349 break; 481 break;
350 } 482 }
351 483
352 if (_convPos != 0) 484 const UInt32 convPos = _convPos;
485 if (convPos != 0)
353 { 486 {
354 UInt32 num = _bufPos - _convPos; 487 const UInt32 num = _bufPos - convPos;
488 Byte *buf = _buf;
355 for (UInt32 i = 0; i < num; i++) 489 for (UInt32 i = 0; i < num; i++)
356 _buf[i] = _buf[_convPos + i]; 490 buf[i] = buf[convPos + i];
357 _bufPos = num; 491 _bufPos = num;
358 _convPos = 0; 492 _convPos = 0;
359 } 493 }
360 494
361 { 495 {
362 size_t readSize = _bufSize - _bufPos; 496 size_t readSize = _bufSize - _bufPos;
363 HRESULT res = ReadStream(_inStream, _buf + _bufPos, &readSize); 497 const HRESULT res = ReadStream(_inStream, _buf + _bufPos, &readSize);
364 _bufPos += (UInt32)readSize; 498 _bufPos += (UInt32)readSize;
365 RINOK(res); 499 RINOK(res)
366 } 500 }
367 501
368 _convSize = Filter->Filter(_buf, _bufPos); 502 const UInt32 convSize = Filter->Filter(_buf, _bufPos);
503 _convSize = convSize;
369 504
370 if (_convSize == 0) 505 UInt32 bufPos = _bufPos;
506
507 if (convSize == 0)
371 { 508 {
372 if (_bufPos == 0) 509 if (bufPos == 0)
373 break; 510 break;
374 // BCJ 511 // BCJ
375 _convSize = _bufPos; 512 _convSize = bufPos;
376 continue; 513 continue;
377 } 514 }
378 515
379 if (_convSize > _bufPos) 516 if (convSize > bufPos)
380 { 517 {
381 // AES 518 // AES
382 if (_convSize > _bufSize) 519 if (convSize > _bufSize)
383 return E_FAIL; 520 return E_FAIL;
384 if (!_encodeMode) 521 if (!_encodeMode)
385 return S_FALSE; 522 return S_FALSE;
386 523 Byte *buf = _buf;
387 do 524 do
388 _buf[_bufPos] = 0; 525 buf[bufPos] = 0;
389 while (++_bufPos != _convSize); 526 while (++bufPos != convSize);
390 527 _bufPos = bufPos;
391 _convSize = Filter->Filter(_buf, _convSize); 528 _convSize = Filter->Filter(_buf, convSize);
392 if (_convSize != _bufPos) 529 if (_convSize != _bufPos)
393 return E_FAIL; 530 return E_FAIL;
394 } 531 }
@@ -398,39 +535,43 @@ STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
398} 535}
399 536
400 537
401#ifndef _NO_CRYPTO 538#ifndef Z7_NO_CRYPTO
402 539
403STDMETHODIMP CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size) 540Z7_COM7F_IMF(CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size))
404 { return _SetPassword->CryptoSetPassword(data, size); } 541 { return _setPassword->CryptoSetPassword(data, size); }
405 542
406STDMETHODIMP CFilterCoder::SetKey(const Byte *data, UInt32 size) 543Z7_COM7F_IMF(CFilterCoder::SetKey(const Byte *data, UInt32 size))
407 { return _CryptoProperties->SetKey(data, size); } 544 { return _cryptoProperties->SetKey(data, size); }
408 545
409STDMETHODIMP CFilterCoder::SetInitVector(const Byte *data, UInt32 size) 546Z7_COM7F_IMF(CFilterCoder::SetInitVector(const Byte *data, UInt32 size))
410 { return _CryptoProperties->SetInitVector(data, size); } 547 { return _cryptoProperties->SetInitVector(data, size); }
411 548
412#endif 549#endif
413 550
414 551
415#ifndef EXTRACT_ONLY 552#ifndef Z7_EXTRACT_ONLY
553
554Z7_COM7F_IMF(CFilterCoder::SetCoderProperties(const PROPID *propIDs,
555 const PROPVARIANT *properties, UInt32 numProperties))
556 { return _setCoderProperties->SetCoderProperties(propIDs, properties, numProperties); }
416 557
417STDMETHODIMP CFilterCoder::SetCoderProperties(const PROPID *propIDs, 558Z7_COM7F_IMF(CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream))
418 const PROPVARIANT *properties, UInt32 numProperties) 559 { return _writeCoderProperties->WriteCoderProperties(outStream); }
419 { return _SetCoderProperties->SetCoderProperties(propIDs, properties, numProperties); }
420 560
421STDMETHODIMP CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream) 561Z7_COM7F_IMF(CFilterCoder::SetCoderPropertiesOpt(const PROPID *propIDs,
422 { return _WriteCoderProperties->WriteCoderProperties(outStream); } 562 const PROPVARIANT *properties, UInt32 numProperties))
563 { return _setCoderPropertiesOpt->SetCoderPropertiesOpt(propIDs, properties, numProperties); }
423 564
424/* 565/*
425STDMETHODIMP CFilterCoder::ResetSalt() 566Z7_COM7F_IMF(CFilterCoder::ResetSalt()
426 { return _CryptoResetSalt->ResetSalt(); } 567 { return _cryptoResetSalt->ResetSalt(); }
427*/ 568*/
428 569
429STDMETHODIMP CFilterCoder::ResetInitVector() 570Z7_COM7F_IMF(CFilterCoder::ResetInitVector())
430 { return _CryptoResetInitVector->ResetInitVector(); } 571 { return _cryptoResetInitVector->ResetInitVector(); }
431 572
432#endif 573#endif
433 574
434 575
435STDMETHODIMP CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size) 576Z7_COM7F_IMF(CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size))
436 { return _SetDecoderProperties2->SetDecoderProperties2(data, size); } 577 { return _setDecoderProperties2->SetDecoderProperties2(data, size); }
diff --git a/CPP/7zip/Common/FilterCoder.h b/CPP/7zip/Common/FilterCoder.h
index 6668fdb..3a588fd 100644
--- a/CPP/7zip/Common/FilterCoder.h
+++ b/CPP/7zip/Common/FilterCoder.h
@@ -1,18 +1,18 @@
1// FilterCoder.h 1// FilterCoder.h
2 2
3#ifndef __FILTER_CODER_H 3#ifndef ZIP7_INC_FILTER_CODER_H
4#define __FILTER_CODER_H 4#define ZIP7_INC_FILTER_CODER_H
5 5
6#include "../../../C/Alloc.h" 6#include "../../../C/Alloc.h"
7 7
8#include "../../Common/MyCom.h" 8#include "../../Common/MyCom.h"
9#include "../ICoder.h" 9#include "../ICoder.h"
10 10
11#ifndef _NO_CRYPTO 11#ifndef Z7_NO_CRYPTO
12#include "../IPassword.h" 12#include "../IPassword.h"
13#endif 13#endif
14 14
15#define MY_QUERYINTERFACE_ENTRY_AG(i, sub0, sub) else if (iid == IID_ ## i) \ 15#define Z7_COM_QI_ENTRY_AG(i, sub0, sub) else if (iid == IID_ ## i) \
16 { if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \ 16 { if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \
17 *outObject = (void *)(i *)this; } 17 *outObject = (void *)(i *)this; }
18 18
@@ -26,7 +26,8 @@ struct CAlignedMidBuffer
26 void AllocAligned(size_t size); 26 void AllocAligned(size_t size);
27}; 27};
28 28
29class CFilterCoder: 29
30class CFilterCoder Z7_final :
30 public ICompressCoder, 31 public ICompressCoder,
31 32
32 public ICompressSetOutStreamSize, 33 public ICompressSetOutStreamSize,
@@ -41,14 +42,15 @@ class CFilterCoder:
41 42
42 public ICompressSetBufSize, 43 public ICompressSetBufSize,
43 44
44 #ifndef _NO_CRYPTO 45 #ifndef Z7_NO_CRYPTO
45 public ICryptoSetPassword, 46 public ICryptoSetPassword,
46 public ICryptoProperties, 47 public ICryptoProperties,
47 #endif 48 #endif
48 49
49 #ifndef EXTRACT_ONLY 50 #ifndef Z7_EXTRACT_ONLY
50 public ICompressSetCoderProperties, 51 public ICompressSetCoderProperties,
51 public ICompressWriteCoderProperties, 52 public ICompressWriteCoderProperties,
53 public ICompressSetCoderPropertiesOpt,
52 // public ICryptoResetSalt, 54 // public ICryptoResetSalt,
53 public ICryptoResetInitVector, 55 public ICryptoResetInitVector,
54 #endif 56 #endif
@@ -62,7 +64,7 @@ class CFilterCoder:
62 UInt32 _outBufSize; 64 UInt32 _outBufSize;
63 65
64 bool _encodeMode; 66 bool _encodeMode;
65 bool _outSizeIsDefined; 67 bool _outSize_Defined;
66 UInt64 _outSize; 68 UInt64 _outSize;
67 UInt64 _nowPos64; 69 UInt64 _nowPos64;
68 70
@@ -78,7 +80,7 @@ class CFilterCoder:
78 _convPos = 0; 80 _convPos = 0;
79 _convSize = 0; 81 _convSize = 0;
80 82
81 _outSizeIsDefined = false; 83 _outSize_Defined = false;
82 _outSize = 0; 84 _outSize = 0;
83 _nowPos64 = 0; 85 _nowPos64 = 0;
84 } 86 }
@@ -87,117 +89,111 @@ class CFilterCoder:
87 HRESULT Init_and_Alloc(); 89 HRESULT Init_and_Alloc();
88 HRESULT Flush2(); 90 HRESULT Flush2();
89 91
90 #ifndef _NO_CRYPTO 92 #ifndef Z7_NO_CRYPTO
91 CMyComPtr<ICryptoSetPassword> _SetPassword; 93 CMyComPtr<ICryptoSetPassword> _setPassword;
92 CMyComPtr<ICryptoProperties> _CryptoProperties; 94 CMyComPtr<ICryptoProperties> _cryptoProperties;
93 #endif 95 #endif
94 96
95 #ifndef EXTRACT_ONLY 97 #ifndef Z7_EXTRACT_ONLY
96 CMyComPtr<ICompressSetCoderProperties> _SetCoderProperties; 98 CMyComPtr<ICompressSetCoderProperties> _setCoderProperties;
97 CMyComPtr<ICompressWriteCoderProperties> _WriteCoderProperties; 99 CMyComPtr<ICompressWriteCoderProperties> _writeCoderProperties;
98 // CMyComPtr<ICryptoResetSalt> _CryptoResetSalt; 100 CMyComPtr<ICompressSetCoderPropertiesOpt> _setCoderPropertiesOpt;
99 CMyComPtr<ICryptoResetInitVector> _CryptoResetInitVector; 101 // CMyComPtr<ICryptoResetSalt> _cryptoResetSalt;
102 CMyComPtr<ICryptoResetInitVector> _cryptoResetInitVector;
100 #endif 103 #endif
101 104
102 CMyComPtr<ICompressSetDecoderProperties2> _SetDecoderProperties2; 105 CMyComPtr<ICompressSetDecoderProperties2> _setDecoderProperties2;
103 106
104public: 107public:
105 CMyComPtr<ICompressFilter> Filter; 108 CMyComPtr<ICompressFilter> Filter;
106 109
107 CFilterCoder(bool encodeMode); 110 CFilterCoder(bool encodeMode);
108 ~CFilterCoder();
109 111
110 class C_InStream_Releaser 112 struct C_InStream_Releaser
111 { 113 {
112 public:
113 CFilterCoder *FilterCoder; 114 CFilterCoder *FilterCoder;
114 C_InStream_Releaser(): FilterCoder(NULL) {} 115 C_InStream_Releaser(): FilterCoder(NULL) {}
115 ~C_InStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseInStream(); } 116 ~C_InStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseInStream(); }
116 }; 117 };
117 118
118 class C_OutStream_Releaser 119 struct C_OutStream_Releaser
119 { 120 {
120 public:
121 CFilterCoder *FilterCoder; 121 CFilterCoder *FilterCoder;
122 C_OutStream_Releaser(): FilterCoder(NULL) {} 122 C_OutStream_Releaser(): FilterCoder(NULL) {}
123 ~C_OutStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseOutStream(); } 123 ~C_OutStream_Releaser() { if (FilterCoder) FilterCoder->ReleaseOutStream(); }
124 }; 124 };
125 125
126 class C_Filter_Releaser 126 struct C_Filter_Releaser
127 { 127 {
128 public:
129 CFilterCoder *FilterCoder; 128 CFilterCoder *FilterCoder;
130 C_Filter_Releaser(): FilterCoder(NULL) {} 129 C_Filter_Releaser(): FilterCoder(NULL) {}
131 ~C_Filter_Releaser() { if (FilterCoder) FilterCoder->Filter.Release(); } 130 ~C_Filter_Releaser() { if (FilterCoder) FilterCoder->Filter.Release(); }
132 }; 131 };
133 132
133private:
134 Z7_COM_QI_BEGIN2(ICompressCoder)
134 135
135 MY_QUERYINTERFACE_BEGIN2(ICompressCoder) 136 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
136 137 Z7_COM_QI_ENTRY(ICompressInitEncoder)
137 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
138 MY_QUERYINTERFACE_ENTRY(ICompressInitEncoder)
139 138
140 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) 139 Z7_COM_QI_ENTRY(ICompressSetInStream)
141 MY_QUERYINTERFACE_ENTRY(ISequentialInStream) 140 Z7_COM_QI_ENTRY(ISequentialInStream)
142 141
143 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStream) 142 Z7_COM_QI_ENTRY(ICompressSetOutStream)
144 MY_QUERYINTERFACE_ENTRY(ISequentialOutStream) 143 Z7_COM_QI_ENTRY(ISequentialOutStream)
145 MY_QUERYINTERFACE_ENTRY(IOutStreamFinish) 144 Z7_COM_QI_ENTRY(IOutStreamFinish)
146 145
147 MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize) 146 Z7_COM_QI_ENTRY(ICompressSetBufSize)
148 147
149 #ifndef _NO_CRYPTO 148 #ifndef Z7_NO_CRYPTO
150 MY_QUERYINTERFACE_ENTRY_AG(ICryptoSetPassword, Filter, _SetPassword) 149 Z7_COM_QI_ENTRY_AG(ICryptoSetPassword, Filter, _setPassword)
151 MY_QUERYINTERFACE_ENTRY_AG(ICryptoProperties, Filter, _CryptoProperties) 150 Z7_COM_QI_ENTRY_AG(ICryptoProperties, Filter, _cryptoProperties)
152 #endif 151 #endif
153 152
154 #ifndef EXTRACT_ONLY 153 #ifndef Z7_EXTRACT_ONLY
155 MY_QUERYINTERFACE_ENTRY_AG(ICompressSetCoderProperties, Filter, _SetCoderProperties) 154 Z7_COM_QI_ENTRY_AG(ICompressSetCoderProperties, Filter, _setCoderProperties)
156 MY_QUERYINTERFACE_ENTRY_AG(ICompressWriteCoderProperties, Filter, _WriteCoderProperties) 155 Z7_COM_QI_ENTRY_AG(ICompressWriteCoderProperties, Filter, _writeCoderProperties)
157 // MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetSalt, Filter, _CryptoResetSalt) 156 Z7_COM_QI_ENTRY_AG(ICompressSetCoderPropertiesOpt, Filter, _setCoderPropertiesOpt)
158 MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetInitVector, Filter, _CryptoResetInitVector) 157 // Z7_COM_QI_ENTRY_AG(ICryptoResetSalt, Filter, _cryptoResetSalt)
158 Z7_COM_QI_ENTRY_AG(ICryptoResetInitVector, Filter, _cryptoResetInitVector)
159 #endif 159 #endif
160 160
161 MY_QUERYINTERFACE_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _SetDecoderProperties2) 161 Z7_COM_QI_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _setDecoderProperties2)
162 MY_QUERYINTERFACE_END 162 Z7_COM_QI_END
163 MY_ADDREF_RELEASE 163 Z7_COM_ADDREF_RELEASE
164
165 164
166 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, 165public:
167 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 166 Z7_IFACE_COM7_IMP(ICompressCoder)
168 167 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
169 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); 168 Z7_IFACE_COM7_IMP(ICompressInitEncoder)
170 STDMETHOD(InitEncoder)(); 169 Z7_IFACE_COM7_IMP(ICompressSetInStream)
171 170private:
172 STDMETHOD(SetInStream)(ISequentialInStream *inStream); 171 Z7_IFACE_COM7_IMP(ISequentialInStream)
173 STDMETHOD(ReleaseInStream)(); 172public:
174 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 173 Z7_IFACE_COM7_IMP(ICompressSetOutStream)
175 174private:
176 STDMETHOD(SetOutStream)(ISequentialOutStream *outStream); 175 Z7_IFACE_COM7_IMP(ISequentialOutStream)
177 STDMETHOD(ReleaseOutStream)(); 176public:
178 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); 177 Z7_IFACE_COM7_IMP(IOutStreamFinish)
179 STDMETHOD(OutStreamFinish)(); 178private:
180 179
181 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size); 180 Z7_IFACE_COM7_IMP(ICompressSetBufSize)
182 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size);
183 181
184 #ifndef _NO_CRYPTO 182 #ifndef Z7_NO_CRYPTO
185 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); 183 Z7_IFACE_COM7_IMP(ICryptoSetPassword)
186 184 Z7_IFACE_COM7_IMP(ICryptoProperties)
187 STDMETHOD(SetKey)(const Byte *data, UInt32 size);
188 STDMETHOD(SetInitVector)(const Byte *data, UInt32 size);
189 #endif 185 #endif
190 186
191 #ifndef EXTRACT_ONLY 187 #ifndef Z7_EXTRACT_ONLY
192 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, 188 Z7_IFACE_COM7_IMP(ICompressSetCoderProperties)
193 const PROPVARIANT *properties, UInt32 numProperties); 189 Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties)
194 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); 190 Z7_IFACE_COM7_IMP(ICompressSetCoderPropertiesOpt)
195 // STDMETHOD(ResetSalt)(); 191 // Z7_IFACE_COM7_IMP(ICryptoResetSalt)
196 STDMETHOD(ResetInitVector)(); 192 Z7_IFACE_COM7_IMP(ICryptoResetInitVector)
197 #endif 193 #endif
198 194
199 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); 195public:
200 196 Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
201 197
202 HRESULT Init_NoSubFilterInit(); 198 HRESULT Init_NoSubFilterInit();
203}; 199};
diff --git a/CPP/7zip/Common/InBuffer.cpp b/CPP/7zip/Common/InBuffer.cpp
index fe6d149..b0f222c 100644
--- a/CPP/7zip/Common/InBuffer.cpp
+++ b/CPP/7zip/Common/InBuffer.cpp
@@ -7,10 +7,10 @@
7#include "InBuffer.h" 7#include "InBuffer.h"
8 8
9CInBufferBase::CInBufferBase() throw(): 9CInBufferBase::CInBufferBase() throw():
10 _buf(0), 10 _buf(NULL),
11 _bufLim(0), 11 _bufLim(NULL),
12 _bufBase(0), 12 _bufBase(NULL),
13 _stream(0), 13 _stream(NULL),
14 _processedSize(0), 14 _processedSize(0),
15 _bufSize(0), 15 _bufSize(0),
16 _wasFinished(false), 16 _wasFinished(false),
@@ -22,18 +22,18 @@ bool CInBuffer::Create(size_t bufSize) throw()
22 const unsigned kMinBlockSize = 1; 22 const unsigned kMinBlockSize = 1;
23 if (bufSize < kMinBlockSize) 23 if (bufSize < kMinBlockSize)
24 bufSize = kMinBlockSize; 24 bufSize = kMinBlockSize;
25 if (_bufBase != 0 && _bufSize == bufSize) 25 if (_bufBase != NULL && _bufSize == bufSize)
26 return true; 26 return true;
27 Free(); 27 Free();
28 _bufSize = bufSize; 28 _bufSize = bufSize;
29 _bufBase = (Byte *)::MidAlloc(bufSize); 29 _bufBase = (Byte *)::MidAlloc(bufSize);
30 return (_bufBase != 0); 30 return (_bufBase != NULL);
31} 31}
32 32
33void CInBuffer::Free() throw() 33void CInBuffer::Free() throw()
34{ 34{
35 ::MidFree(_bufBase); 35 ::MidFree(_bufBase);
36 _bufBase = 0; 36 _bufBase = NULL;
37} 37}
38 38
39void CInBufferBase::Init() throw() 39void CInBufferBase::Init() throw()
@@ -42,7 +42,7 @@ void CInBufferBase::Init() throw()
42 _buf = _bufBase; 42 _buf = _bufBase;
43 _bufLim = _buf; 43 _bufLim = _buf;
44 _wasFinished = false; 44 _wasFinished = false;
45 #ifdef _NO_EXCEPTIONS 45 #ifdef Z7_NO_EXCEPTIONS
46 ErrorCode = S_OK; 46 ErrorCode = S_OK;
47 #endif 47 #endif
48 NumExtraBytes = 0; 48 NumExtraBytes = 0;
@@ -50,7 +50,7 @@ void CInBufferBase::Init() throw()
50 50
51bool CInBufferBase::ReadBlock() 51bool CInBufferBase::ReadBlock()
52{ 52{
53 #ifdef _NO_EXCEPTIONS 53 #ifdef Z7_NO_EXCEPTIONS
54 if (ErrorCode != S_OK) 54 if (ErrorCode != S_OK)
55 return false; 55 return false;
56 #endif 56 #endif
@@ -61,8 +61,8 @@ bool CInBufferBase::ReadBlock()
61 _bufLim = _bufBase; 61 _bufLim = _bufBase;
62 UInt32 processed; 62 UInt32 processed;
63 // FIX_ME: we can improve it to support (_bufSize >= (1 << 32)) 63 // FIX_ME: we can improve it to support (_bufSize >= (1 << 32))
64 HRESULT result = _stream->Read(_bufBase, (UInt32)_bufSize, &processed); 64 const HRESULT result = _stream->Read(_bufBase, (UInt32)_bufSize, &processed);
65 #ifdef _NO_EXCEPTIONS 65 #ifdef Z7_NO_EXCEPTIONS
66 ErrorCode = result; 66 ErrorCode = result;
67 #else 67 #else
68 if (result != S_OK) 68 if (result != S_OK)
diff --git a/CPP/7zip/Common/InBuffer.h b/CPP/7zip/Common/InBuffer.h
index fa06394..3aaf797 100644
--- a/CPP/7zip/Common/InBuffer.h
+++ b/CPP/7zip/Common/InBuffer.h
@@ -1,12 +1,12 @@
1// InBuffer.h 1// InBuffer.h
2 2
3#ifndef __IN_BUFFER_H 3#ifndef ZIP7_INC_IN_BUFFER_H
4#define __IN_BUFFER_H 4#define ZIP7_INC_IN_BUFFER_H
5 5
6#include "../../Common/MyException.h" 6#include "../../Common/MyException.h"
7#include "../IStream.h" 7#include "../IStream.h"
8 8
9#ifndef _NO_EXCEPTIONS 9#ifndef Z7_NO_EXCEPTIONS
10struct CInBufferException: public CSystemException 10struct CInBufferException: public CSystemException
11{ 11{
12 CInBufferException(HRESULT errorCode): CSystemException(errorCode) {} 12 CInBufferException(HRESULT errorCode): CSystemException(errorCode) {}
@@ -31,7 +31,7 @@ protected:
31 Byte ReadByte_FromNewBlock(); 31 Byte ReadByte_FromNewBlock();
32 32
33public: 33public:
34 #ifdef _NO_EXCEPTIONS 34 #ifdef Z7_NO_EXCEPTIONS
35 HRESULT ErrorCode; 35 HRESULT ErrorCode;
36 #endif 36 #endif
37 UInt32 NumExtraBytes; 37 UInt32 NumExtraBytes;
@@ -60,7 +60,7 @@ public:
60 _buf = buf + pos; 60 _buf = buf + pos;
61 _bufLim = buf + end; 61 _bufLim = buf + end;
62 _wasFinished = false; 62 _wasFinished = false;
63 #ifdef _NO_EXCEPTIONS 63 #ifdef Z7_NO_EXCEPTIONS
64 ErrorCode = S_OK; 64 ErrorCode = S_OK;
65 #endif 65 #endif
66 NumExtraBytes = 0; 66 NumExtraBytes = 0;
@@ -68,7 +68,7 @@ public:
68 68
69 void Init() throw(); 69 void Init() throw();
70 70
71 MY_FORCE_INLINE 71 Z7_FORCE_INLINE
72 bool ReadByte(Byte &b) 72 bool ReadByte(Byte &b)
73 { 73 {
74 if (_buf >= _bufLim) 74 if (_buf >= _bufLim)
@@ -77,7 +77,7 @@ public:
77 return true; 77 return true;
78 } 78 }
79 79
80 MY_FORCE_INLINE 80 Z7_FORCE_INLINE
81 bool ReadByte_FromBuf(Byte &b) 81 bool ReadByte_FromBuf(Byte &b)
82 { 82 {
83 if (_buf >= _bufLim) 83 if (_buf >= _bufLim)
@@ -86,7 +86,7 @@ public:
86 return true; 86 return true;
87 } 87 }
88 88
89 MY_FORCE_INLINE 89 Z7_FORCE_INLINE
90 Byte ReadByte() 90 Byte ReadByte()
91 { 91 {
92 if (_buf >= _bufLim) 92 if (_buf >= _bufLim)
diff --git a/CPP/7zip/Common/InOutTempBuffer.cpp b/CPP/7zip/Common/InOutTempBuffer.cpp
index cae6b80..3f7272e 100644
--- a/CPP/7zip/Common/InOutTempBuffer.cpp
+++ b/CPP/7zip/Common/InOutTempBuffer.cpp
@@ -2,170 +2,236 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/Alloc.h"
6
5#include "InOutTempBuffer.h" 7#include "InOutTempBuffer.h"
8
6#include "StreamUtils.h" 9#include "StreamUtils.h"
7 10
8#ifdef USE_InOutTempBuffer_FILE 11#ifdef USE_InOutTempBuffer_FILE
9 12
10#include "../../../C/7zCrc.h" 13#include "../../../C/7zCrc.h"
11 14
12using namespace NWindows;
13using namespace NFile;
14using namespace NDir;
15
16static const size_t kTempBufSize = (1 << 20);
17
18#define kTempFilePrefixString FTEXT("7zt") 15#define kTempFilePrefixString FTEXT("7zt")
19CInOutTempBuffer::~CInOutTempBuffer() 16/*
20{ 17 Total buffer size limit, if we use temp file scheme:
21 delete []_buf; 18 32-bit: 16 MiB = 1 MiB * 16 buffers
22} 19 64-bit: 4 GiB = 1 MiB * 4096 buffers
20*/
21static const size_t kNumBufsMax = (size_t)1 << (sizeof(size_t) * 2 - 4);
22
23#endif 23#endif
24 24
25CInOutTempBuffer::CInOutTempBuffer() 25static const size_t kBufSize = (size_t)1 << 20;
26 #ifdef USE_InOutTempBuffer_FILE
27 : _buf(NULL)
28 #endif
29{ }
30 26
31void CInOutTempBuffer::Create()
32{
33 #ifdef USE_InOutTempBuffer_FILE
34 if (!_buf)
35 _buf = new Byte[kTempBufSize];
36 #endif
37}
38 27
39void CInOutTempBuffer::InitWriting() 28CInOutTempBuffer::CInOutTempBuffer():
29 _size(0),
30 _bufs(NULL),
31 _numBufs(0),
32 _numFilled(0)
40{ 33{
41 #ifdef USE_InOutTempBuffer_FILE 34 #ifdef USE_InOutTempBuffer_FILE
42 _bufPos = 0; 35 _tempFile_Created = false;
36 _useMemOnly = false;
43 _crc = CRC_INIT_VAL; 37 _crc = CRC_INIT_VAL;
44 _tempFileCreated = false; 38 #endif
45 #endif
46 _size = 0;
47} 39}
48 40
41CInOutTempBuffer::~CInOutTempBuffer()
42{
43 for (size_t i = 0; i < _numBufs; i++)
44 MyFree(_bufs[i]);
45 MyFree(_bufs);
46}
49 47
50#ifdef USE_InOutTempBuffer_FILE
51 48
52static inline HRESULT Get_HRESULT_LastError() 49void *CInOutTempBuffer::GetBuf(size_t index)
53{ 50{
54 #ifdef _WIN32 51 if (index >= _numBufs)
55 DWORD lastError = ::GetLastError(); 52 {
56 if (lastError != 0) 53 const size_t num = (_numBufs == 0 ? 16 : _numBufs * 2);
57 return HRESULT_FROM_WIN32(lastError); 54 void **p = (void **)MyRealloc(_bufs, num * sizeof(void *));
58 #endif 55 if (!p)
59 return E_FAIL; 56 return NULL;
57 _bufs = p;
58 memset(p + _numBufs, 0, (num - _numBufs) * sizeof(void *));
59 _numBufs = num;
60 }
61
62 void *buf = _bufs[index];
63 if (!buf)
64 {
65 buf = MyAlloc(kBufSize);
66 if (buf)
67 _bufs[index] = buf;
68 }
69 return buf;
60} 70}
61 71
62#endif
63
64 72
65HRESULT CInOutTempBuffer::Write_HRESULT(const void *data, UInt32 size) 73HRESULT CInOutTempBuffer::Write_HRESULT(const void *data, UInt32 size)
66{ 74{
67 #ifdef USE_InOutTempBuffer_FILE
68
69 if (size == 0) 75 if (size == 0)
70 return S_OK; 76 return S_OK;
71 size_t cur = kTempBufSize - _bufPos; 77
72 if (cur != 0) 78 #ifdef USE_InOutTempBuffer_FILE
79 if (!_tempFile_Created)
80 #endif
81 for (;;) // loop for additional attemp to allocate memory after file creation error
73 { 82 {
74 if (cur > size) 83 #ifdef USE_InOutTempBuffer_FILE
75 cur = size; 84 bool allocError = false;
76 memcpy(_buf + _bufPos, data, cur); 85 #endif
77 _crc = CrcUpdate(_crc, data, cur); 86
78 _bufPos += cur; 87 for (;;) // loop for writing to buffers
79 _size += cur; 88 {
80 size -= (UInt32)cur; 89 const size_t index = (size_t)(_size / kBufSize);
81 data = ((const Byte *)data) + cur; 90
82 } 91 #ifdef USE_InOutTempBuffer_FILE
83 92 if (index >= kNumBufsMax && !_useMemOnly)
84 if (size == 0) 93 break;
85 return S_OK; 94 #endif
95
96 void *buf = GetBuf(index);
97 if (!buf)
98 {
99 #ifdef USE_InOutTempBuffer_FILE
100 if (!_useMemOnly)
101 {
102 allocError = true;
103 break;
104 }
105 #endif
106 return E_OUTOFMEMORY;
107 }
108
109 const size_t offset = (size_t)(_size) & (kBufSize - 1);
110 size_t cur = kBufSize - offset;
111 if (cur > size)
112 cur = size;
113 memcpy((Byte *)buf + offset, data, cur);
114 _size += cur;
115 if (index >= _numFilled)
116 _numFilled = index + 1;
117 data = (const void *)((const Byte *)data + cur);
118 size -= (UInt32)cur;
119 if (size == 0)
120 return S_OK;
121 }
86 122
87 if (!_tempFileCreated) 123 #ifdef USE_InOutTempBuffer_FILE
88 { 124 #ifndef _WIN32
89 if (!_tempFile.CreateRandomInTempFolder(kTempFilePrefixString, &_outFile)) 125 _outFile.mode_for_Create = 0600; // only owner will have the rights to access this file
90 return Get_HRESULT_LastError(); 126 #endif
91 _tempFileCreated = true; 127 if (_tempFile.CreateRandomInTempFolder(kTempFilePrefixString, &_outFile))
128 {
129 _tempFile_Created = true;
130 break;
131 }
132 _useMemOnly = true;
133 if (allocError)
134 return GetLastError_noZero_HRESULT();
135 #endif
92 } 136 }
93 UInt32 processed;
94 if (!_outFile.Write(data, size, processed))
95 return Get_HRESULT_LastError();
96 _crc = CrcUpdate(_crc, data, processed);
97 _size += processed;
98 return (processed == size) ? S_OK : E_FAIL;
99
100 #else
101
102 const size_t newSize = _size + size;
103 if (newSize < _size)
104 return E_OUTOFMEMORY;
105 if (!_dynBuffer.EnsureCapacity(newSize))
106 return E_OUTOFMEMORY;
107 memcpy(((Byte *)_dynBuffer) + _size, data, size);
108 _size = newSize;
109 return S_OK;
110 137
111 #endif 138 #ifdef USE_InOutTempBuffer_FILE
139 if (!_outFile.WriteFull(data, size))
140 return GetLastError_noZero_HRESULT();
141 _crc = CrcUpdate(_crc, data, size);
142 _size += size;
143 return S_OK;
144 #endif
112} 145}
113 146
114 147
115HRESULT CInOutTempBuffer::WriteToStream(ISequentialOutStream *stream) 148HRESULT CInOutTempBuffer::WriteToStream(ISequentialOutStream *stream)
116{ 149{
117 #ifdef USE_InOutTempBuffer_FILE 150 UInt64 rem = _size;
118 151 // if (rem == 0) return S_OK;
119 if (!_outFile.Close())
120 return E_FAIL;
121 152
122 UInt64 size = 0; 153 const size_t numFilled = _numFilled;
123 UInt32 crc = CRC_INIT_VAL; 154 _numFilled = 0;
124 155
125 if (_bufPos != 0) 156 for (size_t i = 0; i < numFilled; i++)
126 {
127 RINOK(WriteStream(stream, _buf, _bufPos));
128 crc = CrcUpdate(crc, _buf, _bufPos);
129 size += _bufPos;
130 }
131
132 if (_tempFileCreated)
133 { 157 {
134 NIO::CInFile inFile; 158 if (rem == 0)
135 if (!inFile.Open(_tempFile.GetPath()))
136 return E_FAIL; 159 return E_FAIL;
137 while (size < _size) 160 size_t cur = kBufSize;
161 if (cur > rem)
162 cur = (size_t)rem;
163 RINOK(WriteStream(stream, _bufs[i], cur))
164 rem -= cur;
165 #ifdef USE_InOutTempBuffer_FILE
166 // we will use _bufs[0] later for writing from temp file
167 if (i != 0 || !_tempFile_Created)
168 #endif
138 { 169 {
139 UInt32 processed; 170 MyFree(_bufs[i]);
140 if (!inFile.ReadPart(_buf, kTempBufSize, processed)) 171 _bufs[i] = NULL;
141 return E_FAIL;
142 if (processed == 0)
143 break;
144 RINOK(WriteStream(stream, _buf, processed));
145 crc = CrcUpdate(crc, _buf, processed);
146 size += processed;
147 } 172 }
148 } 173 }
149 return (_crc == crc && size == _size) ? S_OK : E_FAIL;
150 174
151 #else
152 175
153 return WriteStream(stream, (const Byte *)_dynBuffer, _size); 176 #ifdef USE_InOutTempBuffer_FILE
154 177
155 #endif 178 if (rem == 0)
156} 179 return _tempFile_Created ? E_FAIL : S_OK;
157 180
158/* 181 if (!_tempFile_Created)
159STDMETHODIMP CSequentialOutTempBufferImp::Write(const void *data, UInt32 size, UInt32 *processed)
160{
161 if (!_buf->Write(data, size))
162 {
163 if (processed)
164 *processed = 0;
165 return E_FAIL; 182 return E_FAIL;
183
184 if (!_outFile.Close())
185 return GetLastError_noZero_HRESULT();
186
187 HRESULT hres;
188 void *buf = GetBuf(0); // index
189 if (!buf)
190 hres = E_OUTOFMEMORY;
191 else
192 {
193 NWindows::NFile::NIO::CInFile inFile;
194 if (!inFile.Open(_tempFile.GetPath()))
195 hres = GetLastError_noZero_HRESULT();
196 else
197 {
198 UInt32 crc = CRC_INIT_VAL;
199 for (;;)
200 {
201 size_t processed;
202 if (!inFile.ReadFull(buf, kBufSize, processed))
203 {
204 hres = GetLastError_noZero_HRESULT();
205 break;
206 }
207 if (processed == 0)
208 {
209 // we compare crc without CRC_GET_DIGEST
210 hres = (_crc == crc ? S_OK : E_FAIL);
211 break;
212 }
213 size_t n = processed;
214 if (n > rem)
215 n = (size_t)rem;
216 hres = WriteStream(stream, buf, n);
217 if (hres != S_OK)
218 break;
219 crc = CrcUpdate(crc, buf, n);
220 rem -= n;
221 if (n != processed)
222 {
223 hres = E_FAIL;
224 break;
225 }
226 }
227 }
166 } 228 }
167 if (processed) 229
168 *processed = size; 230 // _tempFile.DisableDeleting(); // for debug
169 return S_OK; 231 _tempFile.Remove();
232 RINOK(hres)
233
234 #endif
235
236 return rem == 0 ? S_OK : E_FAIL;
170} 237}
171*/
diff --git a/CPP/7zip/Common/InOutTempBuffer.h b/CPP/7zip/Common/InOutTempBuffer.h
index 755935e..345c386 100644
--- a/CPP/7zip/Common/InOutTempBuffer.h
+++ b/CPP/7zip/Common/InOutTempBuffer.h
@@ -1,66 +1,45 @@
1// InOutTempBuffer.h 1// InOutTempBuffer.h
2 2
3#ifndef __IN_OUT_TEMP_BUFFER_H 3#ifndef ZIP7_INC_IN_OUT_TEMP_BUFFER_H
4#define __IN_OUT_TEMP_BUFFER_H 4#define ZIP7_INC_IN_OUT_TEMP_BUFFER_H
5 5
6#ifdef _WIN32 6// #ifdef _WIN32
7// #define USE_InOutTempBuffer_FILE 7#define USE_InOutTempBuffer_FILE
8#endif 8// #endif
9 9
10#ifdef USE_InOutTempBuffer_FILE 10#ifdef USE_InOutTempBuffer_FILE
11#include "../../Windows/FileDir.h" 11#include "../../Windows/FileDir.h"
12#else
13#include "StreamObjects.h"
14#endif 12#endif
15 13
16#include "../IStream.h" 14#include "../IStream.h"
17 15
18class CInOutTempBuffer 16class CInOutTempBuffer
19{ 17{
20 #ifdef USE_InOutTempBuffer_FILE 18 UInt64 _size;
19 void **_bufs;
20 size_t _numBufs;
21 size_t _numFilled;
22
23 #ifdef USE_InOutTempBuffer_FILE
21 24
25 bool _tempFile_Created;
26 bool _useMemOnly;
27 UInt32 _crc;
28 // COutFile object must be declared after CTempFile object for correct destructor order
22 NWindows::NFile::NDir::CTempFile _tempFile; 29 NWindows::NFile::NDir::CTempFile _tempFile;
23 NWindows::NFile::NIO::COutFile _outFile; 30 NWindows::NFile::NIO::COutFile _outFile;
24 bool _tempFileCreated;
25 Byte *_buf;
26 size_t _bufPos;
27 UInt64 _size;
28 UInt32 _crc;
29 31
30 #else 32 #endif
31
32 CByteDynBuffer _dynBuffer;
33 size_t _size;
34
35 #endif
36 33
37 CLASS_NO_COPY(CInOutTempBuffer); 34 void *GetBuf(size_t index);
35
36 Z7_CLASS_NO_COPY(CInOutTempBuffer)
38public: 37public:
39 CInOutTempBuffer(); 38 CInOutTempBuffer();
40 void Create();
41
42 #ifdef USE_InOutTempBuffer_FILE
43 ~CInOutTempBuffer(); 39 ~CInOutTempBuffer();
44 #endif
45
46 void InitWriting();
47 HRESULT Write_HRESULT(const void *data, UInt32 size); 40 HRESULT Write_HRESULT(const void *data, UInt32 size);
48 HRESULT WriteToStream(ISequentialOutStream *stream); 41 HRESULT WriteToStream(ISequentialOutStream *stream);
49 UInt64 GetDataSize() const { return _size; } 42 UInt64 GetDataSize() const { return _size; }
50}; 43};
51 44
52/*
53class CSequentialOutTempBufferImp:
54 public ISequentialOutStream,
55 public CMyUnknownImp
56{
57 CInOutTempBuffer *_buf;
58public:
59 void Init(CInOutTempBuffer *buffer) { _buf = buffer; }
60 MY_UNKNOWN_IMP
61
62 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
63};
64*/
65
66#endif 45#endif
diff --git a/CPP/7zip/Common/LimitedStreams.cpp b/CPP/7zip/Common/LimitedStreams.cpp
index 980c795..664cd0c 100644
--- a/CPP/7zip/Common/LimitedStreams.cpp
+++ b/CPP/7zip/Common/LimitedStreams.cpp
@@ -6,7 +6,7 @@
6 6
7#include "LimitedStreams.h" 7#include "LimitedStreams.h"
8 8
9STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 9Z7_COM7F_IMF(CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
10{ 10{
11 UInt32 realProcessedSize = 0; 11 UInt32 realProcessedSize = 0;
12 { 12 {
@@ -27,7 +27,7 @@ STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *p
27 return result; 27 return result;
28} 28}
29 29
30STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 30Z7_COM7F_IMF(CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
31{ 31{
32 if (processedSize) 32 if (processedSize)
33 *processedSize = 0; 33 *processedSize = 0;
@@ -46,7 +46,7 @@ STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSi
46 if (newPos != _physPos) 46 if (newPos != _physPos)
47 { 47 {
48 _physPos = newPos; 48 _physPos = newPos;
49 RINOK(SeekToPhys()); 49 RINOK(SeekToPhys())
50 } 50 }
51 HRESULT res = _stream->Read(data, size, &size); 51 HRESULT res = _stream->Read(data, size, &size);
52 if (processedSize) 52 if (processedSize)
@@ -56,7 +56,7 @@ STDMETHODIMP CLimitedInStream::Read(void *data, UInt32 size, UInt32 *processedSi
56 return res; 56 return res;
57} 57}
58 58
59STDMETHODIMP CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 59Z7_COM7F_IMF(CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
60{ 60{
61 switch (seekOrigin) 61 switch (seekOrigin)
62 { 62 {
@@ -75,17 +75,17 @@ STDMETHODIMP CLimitedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new
75 75
76HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream) 76HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream)
77{ 77{
78 *resStream = 0; 78 *resStream = NULL;
79 CLimitedInStream *streamSpec = new CLimitedInStream; 79 CLimitedInStream *streamSpec = new CLimitedInStream;
80 CMyComPtr<ISequentialInStream> streamTemp = streamSpec; 80 CMyComPtr<ISequentialInStream> streamTemp = streamSpec;
81 streamSpec->SetStream(inStream); 81 streamSpec->SetStream(inStream);
82 RINOK(streamSpec->InitAndSeek(pos, size)); 82 RINOK(streamSpec->InitAndSeek(pos, size))
83 streamSpec->SeekToStart(); 83 streamSpec->SeekToStart();
84 *resStream = streamTemp.Detach(); 84 *resStream = streamTemp.Detach();
85 return S_OK; 85 return S_OK;
86} 86}
87 87
88STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 88Z7_COM7F_IMF(CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
89{ 89{
90 if (processedSize) 90 if (processedSize)
91 *processedSize = 0; 91 *processedSize = 0;
@@ -110,7 +110,7 @@ STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSi
110 if (newPos != _physPos) 110 if (newPos != _physPos)
111 { 111 {
112 _physPos = newPos; 112 _physPos = newPos;
113 RINOK(SeekToPhys()); 113 RINOK(SeekToPhys())
114 } 114 }
115 115
116 _curRem = blockSize - offsetInBlock; 116 _curRem = blockSize - offsetInBlock;
@@ -130,7 +130,7 @@ STDMETHODIMP CClusterInStream::Read(void *data, UInt32 size, UInt32 *processedSi
130 return res; 130 return res;
131} 131}
132 132
133STDMETHODIMP CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 133Z7_COM7F_IMF(CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
134{ 134{
135 switch (seekOrigin) 135 switch (seekOrigin)
136 { 136 {
@@ -150,7 +150,7 @@ STDMETHODIMP CClusterInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new
150} 150}
151 151
152 152
153STDMETHODIMP CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize) 153Z7_COM7F_IMF(CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize))
154{ 154{
155 if (processedSize) 155 if (processedSize)
156 *processedSize = 0; 156 *processedSize = 0;
@@ -201,7 +201,7 @@ STDMETHODIMP CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize
201 if (_phyPos != phy) 201 if (_phyPos != phy)
202 { 202 {
203 _phyPos = (UInt64)0 - 1; // we don't trust seek_pos in case of error 203 _phyPos = (UInt64)0 - 1; // we don't trust seek_pos in case of error
204 RINOK(Stream->Seek((Int64)phy, STREAM_SEEK_SET, NULL)); 204 RINOK(InStream_SeekSet(Stream, phy))
205 _phyPos = phy; 205 _phyPos = phy;
206 } 206 }
207 } 207 }
@@ -218,7 +218,7 @@ STDMETHODIMP CExtentsStream::Read(void *data, UInt32 size, UInt32 *processedSize
218} 218}
219 219
220 220
221STDMETHODIMP CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 221Z7_COM7F_IMF(CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
222{ 222{
223 switch (seekOrigin) 223 switch (seekOrigin)
224 { 224 {
@@ -236,7 +236,7 @@ STDMETHODIMP CExtentsStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo
236} 236}
237 237
238 238
239STDMETHODIMP CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 239Z7_COM7F_IMF(CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
240{ 240{
241 HRESULT result = S_OK; 241 HRESULT result = S_OK;
242 if (processedSize) 242 if (processedSize)
@@ -263,7 +263,7 @@ STDMETHODIMP CLimitedSequentialOutStream::Write(const void *data, UInt32 size, U
263} 263}
264 264
265 265
266STDMETHODIMP CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 266Z7_COM7F_IMF(CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
267{ 267{
268 UInt32 cur; 268 UInt32 cur;
269 HRESULT res = Stream->Read(data, size, &cur); 269 HRESULT res = Stream->Read(data, size, &cur);
@@ -273,7 +273,7 @@ STDMETHODIMP CTailInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
273 return res; 273 return res;
274} 274}
275 275
276STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 276Z7_COM7F_IMF(CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
277{ 277{
278 switch (seekOrigin) 278 switch (seekOrigin)
279 { 279 {
@@ -282,7 +282,7 @@ STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
282 case STREAM_SEEK_END: 282 case STREAM_SEEK_END:
283 { 283 {
284 UInt64 pos = 0; 284 UInt64 pos = 0;
285 RINOK(Stream->Seek(offset, STREAM_SEEK_END, &pos)); 285 RINOK(Stream->Seek(offset, STREAM_SEEK_END, &pos))
286 if (pos < Offset) 286 if (pos < Offset)
287 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK; 287 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
288 _virtPos = pos - Offset; 288 _virtPos = pos - Offset;
@@ -297,10 +297,10 @@ STDMETHODIMP CTailInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
297 _virtPos = (UInt64)offset; 297 _virtPos = (UInt64)offset;
298 if (newPosition) 298 if (newPosition)
299 *newPosition = _virtPos; 299 *newPosition = _virtPos;
300 return Stream->Seek((Int64)(Offset + _virtPos), STREAM_SEEK_SET, NULL); 300 return InStream_SeekSet(Stream, Offset + _virtPos);
301} 301}
302 302
303STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 303Z7_COM7F_IMF(CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
304{ 304{
305 if (processedSize) 305 if (processedSize)
306 *processedSize = 0; 306 *processedSize = 0;
@@ -329,7 +329,7 @@ STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *proce
329 if (newPos != _physPos) 329 if (newPos != _physPos)
330 { 330 {
331 _physPos = newPos; 331 _physPos = newPos;
332 RINOK(SeekToPhys()); 332 RINOK(SeekToPhys())
333 } 333 }
334 res = _stream->Read(data, size, &size); 334 res = _stream->Read(data, size, &size);
335 _physPos += size; 335 _physPos += size;
@@ -340,7 +340,7 @@ STDMETHODIMP CLimitedCachedInStream::Read(void *data, UInt32 size, UInt32 *proce
340 return res; 340 return res;
341} 341}
342 342
343STDMETHODIMP CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 343Z7_COM7F_IMF(CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
344{ 344{
345 switch (seekOrigin) 345 switch (seekOrigin)
346 { 346 {
@@ -357,7 +357,7 @@ STDMETHODIMP CLimitedCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt6
357 return S_OK; 357 return S_OK;
358} 358}
359 359
360STDMETHODIMP CTailOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 360Z7_COM7F_IMF(CTailOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
361{ 361{
362 UInt32 cur; 362 UInt32 cur;
363 HRESULT res = Stream->Write(data, size, &cur); 363 HRESULT res = Stream->Write(data, size, &cur);
@@ -369,7 +369,7 @@ STDMETHODIMP CTailOutStream::Write(const void *data, UInt32 size, UInt32 *proces
369 return res; 369 return res;
370} 370}
371 371
372STDMETHODIMP CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 372Z7_COM7F_IMF(CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
373{ 373{
374 switch (seekOrigin) 374 switch (seekOrigin)
375 { 375 {
@@ -386,7 +386,7 @@ STDMETHODIMP CTailOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPo
386 return Stream->Seek((Int64)(Offset + _virtPos), STREAM_SEEK_SET, NULL); 386 return Stream->Seek((Int64)(Offset + _virtPos), STREAM_SEEK_SET, NULL);
387} 387}
388 388
389STDMETHODIMP CTailOutStream::SetSize(UInt64 newSize) 389Z7_COM7F_IMF(CTailOutStream::SetSize(UInt64 newSize))
390{ 390{
391 _virtSize = newSize; 391 _virtSize = newSize;
392 return Stream->SetSize(Offset + newSize); 392 return Stream->SetSize(Offset + newSize);
diff --git a/CPP/7zip/Common/LimitedStreams.h b/CPP/7zip/Common/LimitedStreams.h
index 50c7cd8..69fcdcd 100644
--- a/CPP/7zip/Common/LimitedStreams.h
+++ b/CPP/7zip/Common/LimitedStreams.h
@@ -1,17 +1,19 @@
1// LimitedStreams.h 1// LimitedStreams.h
2 2
3#ifndef __LIMITED_STREAMS_H 3#ifndef ZIP7_INC_LIMITED_STREAMS_H
4#define __LIMITED_STREAMS_H 4#define ZIP7_INC_LIMITED_STREAMS_H
5 5
6#include "../../Common/MyBuffer.h" 6#include "../../Common/MyBuffer.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
8#include "../../Common/MyVector.h" 8#include "../../Common/MyVector.h"
9#include "../IStream.h" 9#include "../IStream.h"
10 10
11class CLimitedSequentialInStream: 11#include "StreamUtils.h"
12 public ISequentialInStream, 12
13 public CMyUnknownImp 13Z7_CLASS_IMP_COM_1(
14{ 14 CLimitedSequentialInStream
15 , ISequentialInStream
16)
15 CMyComPtr<ISequentialInStream> _stream; 17 CMyComPtr<ISequentialInStream> _stream;
16 UInt64 _size; 18 UInt64 _size;
17 UInt64 _pos; 19 UInt64 _pos;
@@ -25,26 +27,22 @@ public:
25 _pos = 0; 27 _pos = 0;
26 _wasFinished = false; 28 _wasFinished = false;
27 } 29 }
28
29 MY_UNKNOWN_IMP1(ISequentialInStream)
30
31 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
32 UInt64 GetSize() const { return _pos; } 30 UInt64 GetSize() const { return _pos; }
33 UInt64 GetRem() const { return _size - _pos; } 31 UInt64 GetRem() const { return _size - _pos; }
34 bool WasFinished() const { return _wasFinished; } 32 bool WasFinished() const { return _wasFinished; }
35}; 33};
36 34
37class CLimitedInStream: 35
38 public IInStream, 36Z7_CLASS_IMP_IInStream(
39 public CMyUnknownImp 37 CLimitedInStream
40{ 38)
41 CMyComPtr<IInStream> _stream; 39 CMyComPtr<IInStream> _stream;
42 UInt64 _virtPos; 40 UInt64 _virtPos;
43 UInt64 _physPos; 41 UInt64 _physPos;
44 UInt64 _size; 42 UInt64 _size;
45 UInt64 _startOffset; 43 UInt64 _startOffset;
46 44
47 HRESULT SeekToPhys() { return _stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); } 45 HRESULT SeekToPhys() { return InStream_SeekSet(_stream, _physPos); }
48public: 46public:
49 void SetStream(IInStream *stream) { _stream = stream; } 47 void SetStream(IInStream *stream) { _stream = stream; }
50 HRESULT InitAndSeek(UInt64 startOffset, UInt64 size) 48 HRESULT InitAndSeek(UInt64 startOffset, UInt64 size)
@@ -55,21 +53,15 @@ public:
55 _size = size; 53 _size = size;
56 return SeekToPhys(); 54 return SeekToPhys();
57 } 55 }
58
59 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
60
61 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
62 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
63
64 HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); } 56 HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); }
65}; 57};
66 58
67HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream); 59HRESULT CreateLimitedInStream(IInStream *inStream, UInt64 pos, UInt64 size, ISequentialInStream **resStream);
68 60
69class CClusterInStream: 61
70 public IInStream, 62Z7_CLASS_IMP_IInStream(
71 public CMyUnknownImp 63 CClusterInStream
72{ 64)
73 UInt64 _virtPos; 65 UInt64 _virtPos;
74 UInt64 _physPos; 66 UInt64 _physPos;
75 UInt32 _curRem; 67 UInt32 _curRem;
@@ -80,7 +72,7 @@ public:
80 CRecordVector<UInt32> Vector; 72 CRecordVector<UInt32> Vector;
81 UInt64 StartOffset; 73 UInt64 StartOffset;
82 74
83 HRESULT SeekToPhys() { return Stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); } 75 HRESULT SeekToPhys() { return InStream_SeekSet(Stream, _physPos); }
84 76
85 HRESULT InitAndSeek() 77 HRESULT InitAndSeek()
86 { 78 {
@@ -94,11 +86,6 @@ public:
94 } 86 }
95 return S_OK; 87 return S_OK;
96 } 88 }
97
98 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
99
100 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
101 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
102}; 89};
103 90
104 91
@@ -114,23 +101,18 @@ struct CSeekExtent
114 bool Is_ZeroFill() const { return Phy == k_SeekExtent_Phy_Type_ZeroFill; } 101 bool Is_ZeroFill() const { return Phy == k_SeekExtent_Phy_Type_ZeroFill; }
115}; 102};
116 103
117class CExtentsStream: 104
118 public IInStream, 105Z7_CLASS_IMP_IInStream(
119 public CMyUnknownImp 106 CExtentsStream
120{ 107)
121 UInt64 _virtPos; 108 UInt64 _virtPos;
122 UInt64 _phyPos; 109 UInt64 _phyPos;
123 unsigned _prevExtentIndex; 110 unsigned _prevExtentIndex;
124
125public: 111public:
126 CMyComPtr<IInStream> Stream; 112 CMyComPtr<IInStream> Stream;
127 CRecordVector<CSeekExtent> Extents; 113 CRecordVector<CSeekExtent> Extents;
128 114
129 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
130 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
131 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
132 void ReleaseStream() { Stream.Release(); } 115 void ReleaseStream() { Stream.Release(); }
133
134 void Init() 116 void Init()
135 { 117 {
136 _virtPos = 0; 118 _virtPos = 0;
@@ -141,17 +123,15 @@ public:
141 123
142 124
143 125
144class CLimitedSequentialOutStream: 126Z7_CLASS_IMP_COM_1(
145 public ISequentialOutStream, 127 CLimitedSequentialOutStream
146 public CMyUnknownImp 128 , ISequentialOutStream
147{ 129)
148 CMyComPtr<ISequentialOutStream> _stream; 130 CMyComPtr<ISequentialOutStream> _stream;
149 UInt64 _size; 131 UInt64 _size;
150 bool _overflow; 132 bool _overflow;
151 bool _overflowIsAllowed; 133 bool _overflowIsAllowed;
152public: 134public:
153 MY_UNKNOWN_IMP1(ISequentialOutStream)
154 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
155 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 135 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
156 void ReleaseStream() { _stream.Release(); } 136 void ReleaseStream() { _stream.Release(); }
157 void Init(UInt64 size, bool overflowIsAllowed = false) 137 void Init(UInt64 size, bool overflowIsAllowed = false)
@@ -165,10 +145,9 @@ public:
165}; 145};
166 146
167 147
168class CTailInStream: 148Z7_CLASS_IMP_IInStream(
169 public IInStream, 149 CTailInStream
170 public CMyUnknownImp 150)
171{
172 UInt64 _virtPos; 151 UInt64 _virtPos;
173public: 152public:
174 CMyComPtr<IInStream> Stream; 153 CMyComPtr<IInStream> Stream;
@@ -178,19 +157,13 @@ public:
178 { 157 {
179 _virtPos = 0; 158 _virtPos = 0;
180 } 159 }
181 160 HRESULT SeekToStart() { return InStream_SeekSet(Stream, Offset); }
182 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
183
184 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
185 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
186
187 HRESULT SeekToStart() { return Stream->Seek((Int64)Offset, STREAM_SEEK_SET, NULL); }
188}; 161};
189 162
190class CLimitedCachedInStream: 163
191 public IInStream, 164Z7_CLASS_IMP_IInStream(
192 public CMyUnknownImp 165 CLimitedCachedInStream
193{ 166)
194 CMyComPtr<IInStream> _stream; 167 CMyComPtr<IInStream> _stream;
195 UInt64 _virtPos; 168 UInt64 _virtPos;
196 UInt64 _physPos; 169 UInt64 _physPos;
@@ -201,8 +174,7 @@ class CLimitedCachedInStream:
201 size_t _cacheSize; 174 size_t _cacheSize;
202 size_t _cachePhyPos; 175 size_t _cachePhyPos;
203 176
204 177 HRESULT SeekToPhys() { return InStream_SeekSet(_stream, _physPos); }
205 HRESULT SeekToPhys() { return _stream->Seek((Int64)_physPos, STREAM_SEEK_SET, NULL); }
206public: 178public:
207 CByteBuffer Buffer; 179 CByteBuffer Buffer;
208 180
@@ -223,37 +195,27 @@ public:
223 return SeekToPhys(); 195 return SeekToPhys();
224 } 196 }
225 197
226 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
227
228 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
229 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
230
231 HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); } 198 HRESULT SeekToStart() { return Seek(0, STREAM_SEEK_SET, NULL); }
232}; 199};
233 200
234class CTailOutStream: 201
202class CTailOutStream Z7_final :
235 public IOutStream, 203 public IOutStream,
236 public CMyUnknownImp 204 public CMyUnknownImp
237{ 205{
206 Z7_IFACES_IMP_UNK_2(ISequentialOutStream, IOutStream)
207
238 UInt64 _virtPos; 208 UInt64 _virtPos;
239 UInt64 _virtSize; 209 UInt64 _virtSize;
240public: 210public:
241 CMyComPtr<IOutStream> Stream; 211 CMyComPtr<IOutStream> Stream;
242 UInt64 Offset; 212 UInt64 Offset;
243 213
244 virtual ~CTailOutStream() {}
245
246 MY_UNKNOWN_IMP2(ISequentialOutStream, IOutStream)
247
248 void Init() 214 void Init()
249 { 215 {
250 _virtPos = 0; 216 _virtPos = 0;
251 _virtSize = 0; 217 _virtSize = 0;
252 } 218 }
253
254 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
255 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
256 STDMETHOD(SetSize)(UInt64 newSize);
257}; 219};
258 220
259#endif 221#endif
diff --git a/CPP/7zip/Common/LockedStream.h b/CPP/7zip/Common/LockedStream.h
index efebf19..99ee805 100644
--- a/CPP/7zip/Common/LockedStream.h
+++ b/CPP/7zip/Common/LockedStream.h
@@ -1,6 +1,6 @@
1// LockedStream.h 1// LockedStream.h
2 2
3#ifndef __LOCKED_STREAM_H 3#ifndef ZIP7_INC_LOCKED_STREAM_H
4#define __LOCKED_STREAM_H 4#define ZIP7_INC_LOCKED_STREAM_H
5 5
6#endif 6#endif
diff --git a/CPP/7zip/Common/MemBlocks.cpp b/CPP/7zip/Common/MemBlocks.cpp
index 9b0652c..aa68244 100644
--- a/CPP/7zip/Common/MemBlocks.cpp
+++ b/CPP/7zip/Common/MemBlocks.cpp
@@ -34,8 +34,8 @@ bool CMemBlockManager::AllocateSpace_bool(size_t numBlocks)
34void CMemBlockManager::FreeSpace() 34void CMemBlockManager::FreeSpace()
35{ 35{
36 ::MidFree(_data); 36 ::MidFree(_data);
37 _data = 0; 37 _data = NULL;
38 _headFree= 0; 38 _headFree= NULL;
39} 39}
40 40
41void *CMemBlockManager::AllocateBlock() 41void *CMemBlockManager::AllocateBlock()
@@ -157,7 +157,7 @@ HRESULT CMemBlocks::WriteToStream(size_t blockSize, ISequentialOutStream *outStr
157 curSize = (size_t)totalSize; 157 curSize = (size_t)totalSize;
158 if (blockIndex >= Blocks.Size()) 158 if (blockIndex >= Blocks.Size())
159 return E_FAIL; 159 return E_FAIL;
160 RINOK(WriteStream(outStream, Blocks[blockIndex], curSize)); 160 RINOK(WriteStream(outStream, Blocks[blockIndex], curSize))
161 totalSize -= curSize; 161 totalSize -= curSize;
162 } 162 }
163 return S_OK; 163 return S_OK;
@@ -207,7 +207,7 @@ void CMemLockBlocks::Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManag
207 blocks.Blocks.Add(Blocks[i]); 207 blocks.Blocks.Add(Blocks[i]);
208 else 208 else
209 FreeBlock(i, memManager); 209 FreeBlock(i, memManager);
210 Blocks[i] = 0; 210 Blocks[i] = NULL;
211 totalSize += blockSize; 211 totalSize += blockSize;
212 } 212 }
213 blocks.TotalSize = TotalSize; 213 blocks.TotalSize = TotalSize;
diff --git a/CPP/7zip/Common/MemBlocks.h b/CPP/7zip/Common/MemBlocks.h
index 3c9cefd..7c34f21 100644
--- a/CPP/7zip/Common/MemBlocks.h
+++ b/CPP/7zip/Common/MemBlocks.h
@@ -1,7 +1,7 @@
1// MemBlocks.h 1// MemBlocks.h
2 2
3#ifndef __MEM_BLOCKS_H 3#ifndef ZIP7_INC_MEM_BLOCKS_H
4#define __MEM_BLOCKS_H 4#define ZIP7_INC_MEM_BLOCKS_H
5 5
6#include "../../Common/MyVector.h" 6#include "../../Common/MyVector.h"
7 7
@@ -30,7 +30,7 @@ class CMemBlockManagerMt: public CMemBlockManager
30{ 30{
31 NWindows::NSynchronization::CCriticalSection _criticalSection; 31 NWindows::NSynchronization::CCriticalSection _criticalSection;
32public: 32public:
33 SYNC_OBJ_DECL(Synchro); 33 SYNC_OBJ_DECL(Synchro)
34 NWindows::NSynchronization::CSemaphore_WFMO Semaphore; 34 NWindows::NSynchronization::CSemaphore_WFMO Semaphore;
35 35
36 CMemBlockManagerMt(size_t blockSize = (1 << 20)): CMemBlockManager(blockSize) {} 36 CMemBlockManagerMt(size_t blockSize = (1 << 20)): CMemBlockManager(blockSize) {}
@@ -62,7 +62,7 @@ struct CMemLockBlocks: public CMemBlocks
62{ 62{
63 bool LockMode; 63 bool LockMode;
64 64
65 CMemLockBlocks(): LockMode(true) {}; 65 CMemLockBlocks(): LockMode(true) {}
66 void Free(CMemBlockManagerMt *memManager); 66 void Free(CMemBlockManagerMt *memManager);
67 void FreeBlock(unsigned index, CMemBlockManagerMt *memManager); 67 void FreeBlock(unsigned index, CMemBlockManagerMt *memManager);
68 // HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager); 68 // HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager);
diff --git a/CPP/7zip/Common/MethodId.h b/CPP/7zip/Common/MethodId.h
index 28b615f..19b1f10 100644
--- a/CPP/7zip/Common/MethodId.h
+++ b/CPP/7zip/Common/MethodId.h
@@ -1,7 +1,7 @@
1// MethodId.h 1// MethodId.h
2 2
3#ifndef __7Z_METHOD_ID_H 3#ifndef ZIP7_INC_7Z_METHOD_ID_H
4#define __7Z_METHOD_ID_H 4#define ZIP7_INC_7Z_METHOD_ID_H
5 5
6#include "../../Common/MyTypes.h" 6#include "../../Common/MyTypes.h"
7 7
diff --git a/CPP/7zip/Common/MethodProps.cpp b/CPP/7zip/Common/MethodProps.cpp
index 0e8ff1c..fe60f61 100644
--- a/CPP/7zip/Common/MethodProps.cpp
+++ b/CPP/7zip/Common/MethodProps.cpp
@@ -379,14 +379,14 @@ struct CNameToPropID
379 379
380 380
381// the following are related to NCoderPropID::EEnum values 381// the following are related to NCoderPropID::EEnum values
382 382// NCoderPropID::k_NUM_DEFINED
383static const CNameToPropID g_NameToPropID[] = 383static const CNameToPropID g_NameToPropID[] =
384{ 384{
385 { VT_UI4, "" }, 385 { VT_UI4, "" },
386 { VT_UI4, "d" }, 386 { VT_UI4, "d" },
387 { VT_UI4, "mem" }, 387 { VT_UI4, "mem" },
388 { VT_UI4, "o" }, 388 { VT_UI4, "o" },
389 { VT_UI4, "c" }, 389 { VT_UI8, "c" },
390 { VT_UI4, "pb" }, 390 { VT_UI4, "pb" },
391 { VT_UI4, "lc" }, 391 { VT_UI4, "lc" },
392 { VT_UI4, "lp" }, 392 { VT_UI4, "lp" },
@@ -400,15 +400,57 @@ static const CNameToPropID g_NameToPropID[] =
400 { VT_UI4, "x" }, 400 { VT_UI4, "x" },
401 { VT_UI8, "reduce" }, 401 { VT_UI8, "reduce" },
402 { VT_UI8, "expect" }, 402 { VT_UI8, "expect" },
403 { VT_UI4, "b" }, 403 { VT_UI8, "cc" }, // "cc" in v23, "b" in v22.01
404 { VT_UI4, "check" }, 404 { VT_UI4, "check" },
405 { VT_BSTR, "filter" }, 405 { VT_BSTR, "filter" },
406 { VT_UI8, "memuse" } 406 { VT_UI8, "memuse" },
407 { VT_UI8, "aff" },
408 { VT_UI4, "offset" },
409 { VT_UI4, "zhb" }
410 /*
411 ,
412 // { VT_UI4, "zhc" },
413 // { VT_UI4, "zhd" },
414 // { VT_UI4, "zcb" },
415 { VT_UI4, "dc" },
416 { VT_UI4, "zx" },
417 { VT_UI4, "zf" },
418 { VT_UI4, "zmml" },
419 { VT_UI4, "zov" },
420 { VT_BOOL, "zmfr" },
421 { VT_BOOL, "zle" }, // long enable
422 // { VT_UI4, "zldb" },
423 { VT_UI4, "zld" },
424 { VT_UI4, "zlhb" },
425 { VT_UI4, "zlmml" },
426 { VT_UI4, "zlbb" },
427 { VT_UI4, "zlhrb" },
428 { VT_BOOL, "zwus" },
429 { VT_BOOL, "zshp" },
430 { VT_BOOL, "zshs" },
431 { VT_BOOL, "zshe" },
432 { VT_BOOL, "zshg" },
433 { VT_UI4, "zpsm" }
434 */
435 // { VT_UI4, "mcb" }, // mc log version
436 // { VT_UI4, "ztlen" }, // fb ?
407}; 437};
408 438
439/*
440#if defined(static_assert) || (defined(__cplusplus) && __cplusplus >= 200410L) || (defined(_MSC_VER) && _MSC_VER >= 1600)
441
442#if (defined(__cplusplus) && __cplusplus < 201103L) \
443 && defined(__clang__) && __clang_major__ >= 4
444#pragma GCC diagnostic ignored "-Wc11-extensions"
445#endif
446 static_assert(Z7_ARRAY_SIZE(g_NameToPropID) == NCoderPropID::k_NUM_DEFINED,
447 "g_NameToPropID doesn't match NCoderPropID enum");
448#endif
449*/
450
409static int FindPropIdExact(const UString &name) 451static int FindPropIdExact(const UString &name)
410{ 452{
411 for (unsigned i = 0; i < ARRAY_SIZE(g_NameToPropID); i++) 453 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NameToPropID); i++)
412 if (StringsAreEqualNoCase_Ascii(name, g_NameToPropID[i].Name)) 454 if (StringsAreEqualNoCase_Ascii(name, g_NameToPropID[i].Name))
413 return (int)i; 455 return (int)i;
414 return -1; 456 return -1;
@@ -493,6 +535,10 @@ static bool IsLogSizeProp(PROPID propid)
493 case NCoderPropID::kUsedMemorySize: 535 case NCoderPropID::kUsedMemorySize:
494 case NCoderPropID::kBlockSize: 536 case NCoderPropID::kBlockSize:
495 case NCoderPropID::kBlockSize2: 537 case NCoderPropID::kBlockSize2:
538 /*
539 case NCoderPropID::kChainSize:
540 case NCoderPropID::kLdmWindowSize:
541 */
496 // case NCoderPropID::kReduceSize: 542 // case NCoderPropID::kReduceSize:
497 return true; 543 return true;
498 } 544 }
@@ -503,14 +549,19 @@ HRESULT CMethodProps::SetParam(const UString &name, const UString &value)
503{ 549{
504 int index = FindPropIdExact(name); 550 int index = FindPropIdExact(name);
505 if (index < 0) 551 if (index < 0)
506 return E_INVALIDARG; 552 {
553 // 'b' was used as NCoderPropID::kBlockSize2 before v23
554 if (!name.IsEqualTo_Ascii_NoCase("b") || value.Find(L':') >= 0)
555 return E_INVALIDARG;
556 index = NCoderPropID::kBlockSize2;
557 }
507 const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index]; 558 const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index];
508 CProp prop; 559 CProp prop;
509 prop.Id = (unsigned)index; 560 prop.Id = (unsigned)index;
510 561
511 if (IsLogSizeProp(prop.Id)) 562 if (IsLogSizeProp(prop.Id))
512 { 563 {
513 RINOK(StringToDictSize(value, prop.Value)); 564 RINOK(StringToDictSize(value, prop.Value))
514 } 565 }
515 else 566 else
516 { 567 {
@@ -561,7 +612,7 @@ HRESULT CMethodProps::ParseParamsFromString(const UString &srcString)
561 const UString &param = params[i]; 612 const UString &param = params[i];
562 UString name, value; 613 UString name, value;
563 SplitParam(param, name, value); 614 SplitParam(param, name, value);
564 RINOK(SetParam(name, value)); 615 RINOK(SetParam(name, value))
565 } 616 }
566 return S_OK; 617 return S_OK;
567} 618}
@@ -582,7 +633,7 @@ HRESULT CMethodProps::ParseParamsFromPROPVARIANT(const UString &realName, const
582 } 633 }
583 634
584 // {realName}=value 635 // {realName}=value
585 int index = FindPropIdExact(realName); 636 const int index = FindPropIdExact(realName);
586 if (index < 0) 637 if (index < 0)
587 return E_INVALIDARG; 638 return E_INVALIDARG;
588 const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index]; 639 const CNameToPropID &nameToPropID = g_NameToPropID[(unsigned)index];
@@ -591,7 +642,7 @@ HRESULT CMethodProps::ParseParamsFromPROPVARIANT(const UString &realName, const
591 642
592 if (IsLogSizeProp(prop.Id)) 643 if (IsLogSizeProp(prop.Id))
593 { 644 {
594 RINOK(PROPVARIANT_to_DictSize(value, prop.Value)); 645 RINOK(PROPVARIANT_to_DictSize(value, prop.Value))
595 } 646 }
596 else 647 else
597 { 648 {
diff --git a/CPP/7zip/Common/MethodProps.h b/CPP/7zip/Common/MethodProps.h
index 5b5c96a..3c332d6 100644
--- a/CPP/7zip/Common/MethodProps.h
+++ b/CPP/7zip/Common/MethodProps.h
@@ -1,7 +1,7 @@
1// MethodProps.h 1// MethodProps.h
2 2
3#ifndef __7Z_METHOD_PROPS_H 3#ifndef ZIP7_INC_7Z_METHOD_PROPS_H
4#define __7Z_METHOD_PROPS_H 4#define ZIP7_INC_7Z_METHOD_PROPS_H
5 5
6#include "../../Common/MyString.h" 6#include "../../Common/MyString.h"
7#include "../../Common/Defs.h" 7#include "../../Common/Defs.h"
diff --git a/CPP/7zip/Common/MultiOutStream.cpp b/CPP/7zip/Common/MultiOutStream.cpp
new file mode 100644
index 0000000..8efb977
--- /dev/null
+++ b/CPP/7zip/Common/MultiOutStream.cpp
@@ -0,0 +1,849 @@
1// MultiOutStream.cpp
2
3#include "StdAfx.h"
4
5// #define DEBUG_VOLUMES
6
7#ifdef DEBUG_VOLUMES
8#include <stdio.h>
9 #define PRF(x) x;
10#else
11 #define PRF(x)
12#endif
13
14#include "../../Common/ComTry.h"
15
16#include "../../Windows/FileDir.h"
17#include "../../Windows/FileFind.h"
18#include "../../Windows/System.h"
19
20#include "MultiOutStream.h"
21
22using namespace NWindows;
23using namespace NFile;
24using namespace NDir;
25
26static const unsigned k_NumVols_MAX = k_VectorSizeMax - 1;
27 // 2; // for debug
28
29/*
30#define UPDATE_HRES(hres, x) \
31 { const HRESULT res2 = (x); if (hres == SZ_OK) hres = res2; }
32*/
33
34HRESULT CMultiOutStream::Destruct()
35{
36 COM_TRY_BEGIN
37 HRESULT hres = S_OK;
38 HRESULT hres3 = S_OK;
39
40 while (!Streams.IsEmpty())
41 {
42 try
43 {
44 HRESULT hres2;
45 if (NeedDelete)
46 {
47 /* we could call OptReOpen_and_SetSize() to test that we try to delete correct file,
48 but we cannot guarantee that (RealSize) will be correct after Write() or another failures.
49 And we still want to delete files even for such cases.
50 So we don't check for OptReOpen_and_SetSize() here: */
51 // if (OptReOpen_and_SetSize(Streams.Size() - 1, 0) == S_OK)
52 hres2 = CloseStream_and_DeleteFile(Streams.Size() - 1);
53 }
54 else
55 {
56 hres2 = CloseStream(Streams.Size() - 1);
57 }
58 if (hres == S_OK)
59 hres = hres2;
60 }
61 catch(...)
62 {
63 hres3 = E_OUTOFMEMORY;
64 }
65
66 {
67 /* Stream was released in CloseStream_*() above already, and it was removed from linked list
68 it's some unexpected case, if Stream is still attached here.
69 So the following code is optional: */
70 CVolStream &s = Streams.Back();
71 if (s.Stream)
72 {
73 if (hres3 == S_OK)
74 hres3 = E_FAIL;
75 s.Stream.Detach();
76 /* it will be not failure, even if we call RemoveFromLinkedList()
77 twice for same CVolStream in this Destruct() function */
78 RemoveFromLinkedList(Streams.Size() - 1);
79 }
80 }
81 Streams.DeleteBack();
82 // Delete_LastStream_Records();
83 }
84
85 if (hres == S_OK)
86 hres = hres3;
87 if (hres == S_OK && NumListItems != 0)
88 hres = E_FAIL;
89 return hres;
90 COM_TRY_END
91}
92
93
94CMultiOutStream::~CMultiOutStream()
95{
96 // we try to avoid exception in destructors
97 Destruct();
98}
99
100
101void CMultiOutStream::Init(const CRecordVector<UInt64> &sizes)
102{
103 Streams.Clear();
104 InitLinkedList();
105 Sizes = sizes;
106 NeedDelete = true;
107 MTime_Defined = false;
108 FinalVol_WasReopen = false;
109 NumOpenFiles_AllowedMax = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks();
110
111 _streamIndex = 0;
112 _offsetPos = 0;
113 _absPos = 0;
114 _length = 0;
115 _absLimit = (UInt64)(Int64)-1;
116
117 _restrict_Begin = 0;
118 _restrict_End = (UInt64)(Int64)-1;
119 _restrict_Global = 0;
120
121 UInt64 sum = 0;
122 unsigned i = 0;
123 for (i = 0; i < Sizes.Size(); i++)
124 {
125 if (i >= k_NumVols_MAX)
126 {
127 _absLimit = sum;
128 break;
129 }
130 const UInt64 size = Sizes[i];
131 const UInt64 next = sum + size;
132 if (next < sum)
133 break;
134 sum = next;
135 }
136
137 // if (Sizes.IsEmpty()) throw "no volume sizes";
138 const UInt64 size = Sizes.Back();
139 if (size == 0)
140 throw "zero size last volume";
141
142 if (i == Sizes.Size())
143 if ((_absLimit - sum) / size >= (k_NumVols_MAX - i))
144 _absLimit = sum + (k_NumVols_MAX - i) * size;
145}
146
147
148/* IsRestricted():
149 we must call only if volume is full (s.RealSize==VolSize) or finished.
150 the function doesn't use VolSize and it uses s.RealSize instead.
151 it returns true : if stream is restricted, and we can't close that stream
152 it returns false : if there is no restriction, and we can close that stream
153 Note: (RealSize == 0) (empty volume) on restriction bounds are supposed as non-restricted
154*/
155bool CMultiOutStream::IsRestricted(const CVolStream &s) const
156{
157 if (s.Start < _restrict_Global)
158 return true;
159 if (_restrict_Begin == _restrict_End)
160 return false;
161 if (_restrict_Begin <= s.Start)
162 return _restrict_End > s.Start;
163 return _restrict_Begin < s.Start + s.RealSize;
164}
165
166/*
167// this function check also _length and volSize
168bool CMultiOutStream::IsRestricted_for_Close(unsigned index) const
169{
170 const CVolStream &s = Streams[index];
171 if (_length <= s.Start) // we don't close streams after the end, because we still can write them later
172 return true;
173 // (_length > s.Start)
174 const UInt64 volSize = GetVolSize_for_Stream(index);
175 if (volSize == 0)
176 return IsRestricted_Empty(s);
177 if (_length - s.Start < volSize)
178 return true;
179 return IsRestricted(s);
180}
181*/
182
183FString CMultiOutStream::GetFilePath(unsigned index)
184{
185 FString name;
186 name.Add_UInt32(index + 1);
187 while (name.Len() < 3)
188 name.InsertAtFront(FTEXT('0'));
189 name.Insert(0, Prefix);
190 return name;
191}
192
193
194// we close stream, but we still keep item in Streams[] vector
195HRESULT CMultiOutStream::CloseStream(unsigned index)
196{
197 CVolStream &s = Streams[index];
198 if (s.Stream)
199 {
200 RINOK(s.StreamSpec->Close())
201 // the following two commands must be called together:
202 s.Stream.Release();
203 RemoveFromLinkedList(index);
204 }
205 return S_OK;
206}
207
208
209// we close stream and delete file, but we still keep item in Streams[] vector
210HRESULT CMultiOutStream::CloseStream_and_DeleteFile(unsigned index)
211{
212 PRF(printf("\n====== %u, CloseStream_AndDelete \n", index));
213 RINOK(CloseStream(index))
214 FString path = GetFilePath(index);
215 path += Streams[index].Postfix;
216 // we can checki that file exist
217 // if (NFind::DoesFileExist_Raw(path))
218 if (!DeleteFileAlways(path))
219 return GetLastError_noZero_HRESULT();
220 return S_OK;
221}
222
223
224HRESULT CMultiOutStream::CloseStream_and_FinalRename(unsigned index)
225{
226 PRF(printf("\n====== %u, CloseStream_and_FinalRename \n", index));
227 CVolStream &s = Streams[index];
228 // HRESULT res = S_OK;
229 bool mtime_WasSet = false;
230 if (MTime_Defined && s.Stream)
231 {
232 if (s.StreamSpec->SetMTime(&MTime))
233 mtime_WasSet = true;
234 // else res = GetLastError_noZero_HRESULT();
235 }
236
237 RINOK(CloseStream(index))
238 if (s.Postfix.IsEmpty()) // if Postfix is empty, the path is already final
239 return S_OK;
240 const FString path = GetFilePath(index);
241 FString tempPath = path;
242 tempPath += s.Postfix;
243
244 if (MTime_Defined && !mtime_WasSet)
245 {
246 if (!SetDirTime(tempPath, NULL, NULL, &MTime))
247 {
248 // res = GetLastError_noZero_HRESULT();
249 }
250 }
251 if (!MyMoveFile(tempPath, path))
252 return GetLastError_noZero_HRESULT();
253 /* we clear CVolStream::Postfix. So we will not use Temp path
254 anymore for this stream, and we will work only with final path */
255 s.Postfix.Empty();
256 // we can ignore set_mtime error or we can return it
257 return S_OK;
258 // return res;
259}
260
261
262HRESULT CMultiOutStream::PrepareToOpenNew()
263{
264 if (NumListItems < NumOpenFiles_AllowedMax)
265 return S_OK;
266 /* when we create zip archive: in most cases we need only starting
267 data of restricted region for rewriting zip's local header.
268 So here we close latest created volume (from Head), and we try to
269 keep oldest volumes that will be used for header rewriting later. */
270 const int index = Head;
271 if (index == -1)
272 return E_FAIL;
273 PRF(printf("\n== %u, PrepareToOpenNew::CloseStream, NumListItems =%u \n", index, NumListItems));
274 /* we don't expect non-restricted stream here in normal cases (if _restrict_Global was not changed).
275 if there was non-restricted stream, it should be closed before */
276 // if (!IsRestricted_for_Close(index)) return CloseStream_and_FinalRename(index);
277 return CloseStream((unsigned)index);
278}
279
280
281HRESULT CMultiOutStream::CreateNewStream(UInt64 newSize)
282{
283 PRF(printf("\n== %u, CreateNewStream, size =%u \n", Streams.Size(), (unsigned)newSize));
284
285 if (Streams.Size() >= k_NumVols_MAX)
286 return E_INVALIDARG; // E_OUTOFMEMORY
287
288 RINOK(PrepareToOpenNew())
289 CVolStream s;
290 s.StreamSpec = new COutFileStream;
291 s.Stream = s.StreamSpec;
292 const FString path = GetFilePath(Streams.Size());
293
294 if (NFind::DoesFileExist_Raw(path))
295 return HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS);
296 if (!CreateTempFile2(path, false, s.Postfix, &s.StreamSpec->File))
297 return GetLastError_noZero_HRESULT();
298
299 s.Start = GetGlobalOffset_for_NewStream();
300 s.Pos = 0;
301 s.RealSize = 0;
302
303 const unsigned index = Streams.Add(s);
304 InsertToLinkedList(index);
305
306 if (newSize != 0)
307 return s.SetSize2(newSize);
308 return S_OK;
309}
310
311
312HRESULT CMultiOutStream::CreateStreams_If_Required(unsigned streamIndex)
313{
314 // UInt64 lastStreamSize = 0;
315 for (;;)
316 {
317 const unsigned numStreamsBefore = Streams.Size();
318 if (streamIndex < numStreamsBefore)
319 return S_OK;
320 UInt64 newSize;
321 if (streamIndex == numStreamsBefore)
322 {
323 // it's final volume that will be used for real writing.
324 /* SetSize(_offsetPos) is not required,
325 because the file Size will be set later by calling Seek() with Write() */
326 newSize = 0; // lastStreamSize;
327 }
328 else
329 {
330 // it's intermediate volume. So we need full volume size
331 newSize = GetVolSize_for_Stream(numStreamsBefore);
332 }
333
334 RINOK(CreateNewStream(newSize))
335
336 // optional check
337 if (numStreamsBefore + 1 != Streams.Size()) return E_FAIL;
338
339 if (streamIndex != numStreamsBefore)
340 {
341 // it's intermediate volume. So we can close it, if it's non-restricted
342 bool isRestricted;
343 {
344 const CVolStream &s = Streams[numStreamsBefore];
345 if (newSize == 0)
346 isRestricted = IsRestricted_Empty(s);
347 else
348 isRestricted = IsRestricted(s);
349 }
350 if (!isRestricted)
351 {
352 RINOK(CloseStream_and_FinalRename(numStreamsBefore))
353 }
354 }
355 }
356}
357
358
359HRESULT CMultiOutStream::ReOpenStream(unsigned streamIndex)
360{
361 PRF(printf("\n====== %u, ReOpenStream \n", streamIndex));
362 RINOK(PrepareToOpenNew())
363 CVolStream &s = Streams[streamIndex];
364
365 FString path = GetFilePath(streamIndex);
366 path += s.Postfix;
367
368 s.StreamSpec = new COutFileStream;
369 s.Stream = s.StreamSpec;
370 s.Pos = 0;
371
372 HRESULT hres;
373 if (s.StreamSpec->Open(path, OPEN_EXISTING))
374 {
375 if (s.Postfix.IsEmpty())
376 {
377 /* it's unexpected case that we open finished volume.
378 It can mean that the code for restriction is incorrect */
379 FinalVol_WasReopen = true;
380 }
381 UInt64 realSize = 0;
382 hres = s.StreamSpec->GetSize(&realSize);
383 if (hres == S_OK)
384 {
385 if (realSize == s.RealSize)
386 {
387 InsertToLinkedList(streamIndex);
388 return S_OK;
389 }
390 // file size was changed between Close() and ReOpen()
391 // we must release Stream to be consistent with linked list
392 hres = E_FAIL;
393 }
394 }
395 else
396 hres = GetLastError_noZero_HRESULT();
397 s.Stream.Release();
398 s.StreamSpec = NULL;
399 return hres;
400}
401
402
403/* Sets size of stream, if new size is not equal to old size (RealSize).
404 If stream was closed and size change is required, it reopens the stream. */
405
406HRESULT CMultiOutStream::OptReOpen_and_SetSize(unsigned index, UInt64 size)
407{
408 CVolStream &s = Streams[index];
409 if (size == s.RealSize)
410 return S_OK;
411 if (!s.Stream)
412 {
413 RINOK(ReOpenStream(index))
414 }
415 PRF(printf("\n== %u, OptReOpen_and_SetSize, size =%u RealSize = %u\n", index, (unsigned)size, (unsigned)s.RealSize));
416 // comment it to debug tail after data
417 return s.SetSize2(size);
418}
419
420
421/*
422call Normalize_finalMode(false), if _length was changed.
423 for all streams starting after _length:
424 - it sets zero size
425 - it still keeps file open
426 Note: after _length reducing with CMultiOutStream::SetSize() we can
427 have very big number of empty streams at the end of Streams[] list.
428 And Normalize_finalMode() will runs all these empty streams of Streams[] vector.
429 So it can be ineffective, if we call Normalize_finalMode() many
430 times after big reducing of (_length).
431
432call Normalize_finalMode(true) to set final presentations of all streams
433 for all streams starting after _length:
434 - it sets zero size
435 - it removes file
436 - it removes CVolStream object from Streams[] vector
437
438Note: we don't remove zero sized first volume, if (_length == 0)
439*/
440
441HRESULT CMultiOutStream::Normalize_finalMode(bool finalMode)
442{
443 PRF(printf("\n== Normalize_finalMode: _length =%d \n", (unsigned)_length));
444
445 unsigned i = Streams.Size();
446
447 UInt64 offset = 0;
448
449 /* At first we normalize (reduce or increase) the sizes of all existing
450 streams in Streams[] that can be affected by changed _length.
451 And we remove tailing zero-size streams, if (finalMode == true) */
452 while (i != 0)
453 {
454 offset = Streams[--i].Start; // it's last item in Streams[]
455 // we don't want to remove first volume
456 if (offset < _length || i == 0)
457 {
458 const UInt64 volSize = GetVolSize_for_Stream(i);
459 UInt64 size = _length - offset; // (size != 0) here
460 if (size > volSize)
461 size = volSize;
462 RINOK(OptReOpen_and_SetSize(i, size))
463 if (_length - offset <= volSize)
464 return S_OK;
465 // _length - offset > volSize
466 offset += volSize;
467 // _length > offset
468 break;
469 // UPDATE_HRES(res, OptReOpen_and_SetSize(i, size));
470 }
471
472 /* we Set Size of stream to zero even for (finalMode==true), although
473 that stream will be deleted in next commands */
474 // UPDATE_HRES(res, OptReOpen_and_SetSize(i, 0));
475 RINOK(OptReOpen_and_SetSize(i, 0))
476 if (finalMode)
477 {
478 RINOK(CloseStream_and_DeleteFile(i))
479 /* CVolStream::Stream was released above already, and it was
480 removed from linked list. So we don't need to update linked list
481 structure, when we delete last item in Streams[] */
482 Streams.DeleteBack();
483 // Delete_LastStream_Records();
484 }
485 }
486
487 /* now we create new zero-filled streams to cover all data up to _length */
488
489 if (_length == 0)
490 return S_OK;
491
492 // (offset) is start offset of next stream after existing Streams[]
493
494 for (;;)
495 {
496 // _length > offset
497 const UInt64 volSize = GetVolSize_for_Stream(Streams.Size());
498 UInt64 size = _length - offset; // (size != 0) here
499 if (size > volSize)
500 size = volSize;
501 RINOK(CreateNewStream(size))
502 if (_length - offset <= volSize)
503 return S_OK;
504 // _length - offset > volSize)
505 offset += volSize;
506 // _length > offset
507 }
508}
509
510
511HRESULT CMultiOutStream::FinalFlush_and_CloseFiles(unsigned &numTotalVolumesRes)
512{
513 // at first we remove unused zero-sized streams after _length
514 HRESULT res = Normalize_finalMode(true);
515 numTotalVolumesRes = Streams.Size();
516 FOR_VECTOR (i, Streams)
517 {
518 const HRESULT res2 = CloseStream_and_FinalRename(i);
519 if (res == S_OK)
520 res = res2;
521 }
522 if (NumListItems != 0 && res == S_OK)
523 res = E_FAIL;
524 return res;
525}
526
527
528bool CMultiOutStream::SetMTime_Final(const CFiTime &mTime)
529{
530 // we will set mtime only if new value differs from previous
531 if (!FinalVol_WasReopen && MTime_Defined && Compare_FiTime(&MTime, &mTime) == 0)
532 return true;
533 bool res = true;
534 FOR_VECTOR (i, Streams)
535 {
536 CVolStream &s = Streams[i];
537 if (s.Stream)
538 {
539 if (!s.StreamSpec->SetMTime(&mTime))
540 res = false;
541 }
542 else
543 {
544 if (!SetDirTime(GetFilePath(i), NULL, NULL, &mTime))
545 res = false;
546 }
547 }
548 return res;
549}
550
551
552Z7_COM7F_IMF(CMultiOutStream::SetSize(UInt64 newSize))
553{
554 COM_TRY_BEGIN
555 if ((Int64)newSize < 0)
556 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
557 if (newSize > _absLimit)
558 {
559 /* big seek value was sent to SetSize() or to Seek()+Write().
560 It can mean one of two situations:
561 1) some incorrect code called it with big seek value.
562 2) volume size was small, and we have too big number of volumes
563 */
564 /* in Windows SetEndOfFile() can return:
565 ERROR_NEGATIVE_SEEK: for >= (1 << 63)
566 ERROR_INVALID_PARAMETER: for > (16 TiB - 64 KiB)
567 ERROR_DISK_FULL: for <= (16 TiB - 64 KiB)
568 */
569 // return E_FAIL;
570 // return E_OUTOFMEMORY;
571 return E_INVALIDARG;
572 }
573
574 if (newSize > _length)
575 {
576 // we don't expect such case. So we just define global restriction */
577 _restrict_Global = newSize;
578 }
579 else if (newSize < _restrict_Global)
580 _restrict_Global = newSize;
581
582 PRF(printf("\n== SetSize, size =%u \n", (unsigned)newSize));
583
584 _length = newSize;
585 return Normalize_finalMode(false);
586
587 COM_TRY_END
588}
589
590
591Z7_COM7F_IMF(CMultiOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
592{
593 COM_TRY_BEGIN
594 if (processedSize)
595 *processedSize = 0;
596 if (size == 0)
597 return S_OK;
598
599 if (_absPos > _length)
600 {
601 // it create data only up to _absPos.
602 // but we still can need additional new streams, if _absPos at range of volume
603 RINOK(SetSize(_absPos))
604 }
605
606 while (size != 0)
607 {
608 UInt64 volSize;
609 {
610 if (_streamIndex < Sizes.Size() - 1)
611 {
612 volSize = Sizes[_streamIndex];
613 if (_offsetPos >= volSize)
614 {
615 _offsetPos -= volSize;
616 _streamIndex++;
617 continue;
618 }
619 }
620 else
621 {
622 volSize = Sizes[Sizes.Size() - 1];
623 if (_offsetPos >= volSize)
624 {
625 const UInt64 v = _offsetPos / volSize;
626 if (v >= ((UInt32)(Int32)-1) - _streamIndex)
627 return E_INVALIDARG;
628 // throw 202208;
629 _streamIndex += (unsigned)v;
630 _offsetPos -= (unsigned)v * volSize;
631 }
632 if (_streamIndex >= k_NumVols_MAX)
633 return E_INVALIDARG;
634 }
635 }
636
637 // (_offsetPos < volSize) here
638
639 /* we can need to create one or more streams here,
640 vol_size for some streams is allowed to be 0.
641 Also we close some new created streams, if they are non-restricted */
642 // file Size will be set later by calling Seek() with Write()
643
644 /* the case (_absPos > _length) was processed above with SetSize(_absPos),
645 so here it's expected. that we can create optional zero-size streams and then _streamIndex */
646 RINOK(CreateStreams_If_Required(_streamIndex))
647
648 CVolStream &s = Streams[_streamIndex];
649
650 PRF(printf("\n%d, == Write : Pos = %u, RealSize = %u size =%u \n",
651 _streamIndex, (unsigned)s.Pos, (unsigned)s.RealSize, size));
652
653 if (!s.Stream)
654 {
655 RINOK(ReOpenStream(_streamIndex))
656 }
657 if (_offsetPos != s.Pos)
658 {
659 RINOK(s.Stream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL))
660 s.Pos = _offsetPos;
661 }
662
663 UInt32 curSize = size;
664 {
665 const UInt64 rem = volSize - _offsetPos;
666 if (curSize > rem)
667 curSize = (UInt32)rem;
668 }
669 // curSize != 0
670 UInt32 realProcessed = 0;
671
672 HRESULT hres = s.Stream->Write(data, curSize, &realProcessed);
673
674 data = (const void *)((const Byte *)data + realProcessed);
675 size -= realProcessed;
676 s.Pos += realProcessed;
677 _offsetPos += realProcessed;
678 _absPos += realProcessed;
679 if (_length < _absPos)
680 _length = _absPos;
681 if (s.RealSize < _offsetPos)
682 s.RealSize = _offsetPos;
683 if (processedSize)
684 *processedSize += realProcessed;
685
686 if (s.Pos == volSize)
687 {
688 bool isRestricted;
689 if (volSize == 0)
690 isRestricted = IsRestricted_Empty(s);
691 else
692 isRestricted = IsRestricted(s);
693 if (!isRestricted)
694 {
695 const HRESULT res2 = CloseStream_and_FinalRename(_streamIndex);
696 if (hres == S_OK)
697 hres = res2;
698 }
699 _streamIndex++;
700 _offsetPos = 0;
701 }
702
703 RINOK(hres)
704 if (realProcessed == 0 && curSize != 0)
705 return E_FAIL;
706 // break;
707 }
708 return S_OK;
709 COM_TRY_END
710}
711
712
713Z7_COM7F_IMF(CMultiOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
714{
715 PRF(printf("\n-- Seek seekOrigin=%u Seek =%u\n", seekOrigin, (unsigned)offset));
716
717 switch (seekOrigin)
718 {
719 case STREAM_SEEK_SET: break;
720 case STREAM_SEEK_CUR: offset += _absPos; break;
721 case STREAM_SEEK_END: offset += _length; break;
722 default: return STG_E_INVALIDFUNCTION;
723 }
724 if (offset < 0)
725 return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
726 if ((UInt64)offset != _absPos)
727 {
728 _absPos = (UInt64)offset;
729 _offsetPos = (UInt64)offset;
730 _streamIndex = 0;
731 }
732 if (newPosition)
733 *newPosition = (UInt64)offset;
734 return S_OK;
735}
736
737
738// result value will be saturated to (UInt32)(Int32)-1
739
740unsigned CMultiOutStream::GetStreamIndex_for_Offset(UInt64 offset, UInt64 &relOffset) const
741{
742 const unsigned last = Sizes.Size() - 1;
743 for (unsigned i = 0; i < last; i++)
744 {
745 const UInt64 size = Sizes[i];
746 if (offset < size)
747 {
748 relOffset = offset;
749 return i;
750 }
751 offset -= size;
752 }
753 const UInt64 size = Sizes[last];
754 const UInt64 v = offset / size;
755 if (v >= ((UInt32)(Int32)-1) - last)
756 return (UInt32)(Int32)-1; // saturation
757 relOffset = offset - (unsigned)v * size;
758 return last + (unsigned)(v);
759}
760
761
762Z7_COM7F_IMF(CMultiOutStream::SetRestriction(UInt64 begin, UInt64 end))
763{
764 COM_TRY_BEGIN
765
766 // begin = end = 0; // for debug
767
768 PRF(printf("\n==================== CMultiOutStream::SetRestriction %u, %u\n", (unsigned)begin, (unsigned)end));
769 if (begin > end)
770 {
771 // these value are FAILED values.
772 return E_FAIL;
773 // return E_INVALIDARG;
774 /*
775 // or we can ignore error with 3 ways: no change, non-restricted, saturation:
776 end = begin; // non-restricted
777 end = (UInt64)(Int64)-1; // saturation:
778 return S_OK;
779 */
780 }
781 UInt64 b = _restrict_Begin;
782 UInt64 e = _restrict_End;
783 _restrict_Begin = begin;
784 _restrict_End = end;
785
786 if (b == e) // if there were no restriction before
787 return S_OK; // no work to derestrict now.
788
789 /* [b, e) is previous restricted region. So all volumes that
790 intersect that [b, e) region are candidats for derestriction */
791
792 if (begin != end) // if there is new non-empty restricted region
793 {
794 /* Now we will try to reduce or change (b) and (e) bounds
795 to reduce main loop that checks volumes for derestriction.
796 We still use one big derestriction region in main loop, although
797 in some cases we could have two smaller derestriction regions.
798 Also usually restriction region cannot move back from previous start position,
799 so (b <= begin) is expected here for normal cases */
800 if (b == begin) // if same low bounds
801 b = end; // we need to derestrict only after the end of new restricted region
802 if (e == end) // if same high bounds
803 e = begin; // we need to derestrict only before the begin of new restricted region
804 }
805
806 if (b > e) // || b == (UInt64)(Int64)-1
807 return S_OK;
808
809 /* Here we close finished volumes that are not restricted anymore.
810 We close (low number) volumes at first. */
811
812 UInt64 offset;
813 unsigned index = GetStreamIndex_for_Offset(b, offset);
814
815 for (; index < Streams.Size(); index++)
816 {
817 {
818 const CVolStream &s = Streams[index];
819 if (_length <= s.Start)
820 break; // we don't close streams after _length
821 // (_length > s.Start)
822 const UInt64 volSize = GetVolSize_for_Stream(index);
823 if (volSize == 0)
824 {
825 if (e < s.Start)
826 break;
827 // we don't close empty stream, if next byte [s.Start, s.Start] is restricted
828 if (IsRestricted_Empty(s))
829 continue;
830 }
831 else
832 {
833 if (e <= s.Start)
834 break;
835 // we don't close non full streams
836 if (_length - s.Start < volSize)
837 break;
838 // (volSize == s.RealSize) is expected here. So no need to check it
839 // if (volSize != s.RealSize) break;
840 if (IsRestricted(s))
841 continue;
842 }
843 }
844 RINOK(CloseStream_and_FinalRename(index))
845 }
846
847 return S_OK;
848 COM_TRY_END
849}
diff --git a/CPP/7zip/Common/MultiOutStream.h b/CPP/7zip/Common/MultiOutStream.h
new file mode 100644
index 0000000..2fb7811
--- /dev/null
+++ b/CPP/7zip/Common/MultiOutStream.h
@@ -0,0 +1,160 @@
1// MultiOutStream.h
2
3#ifndef ZIP7_INC_MULTI_OUT_STREAM_H
4#define ZIP7_INC_MULTI_OUT_STREAM_H
5
6#include "FileStreams.h"
7
8Z7_CLASS_IMP_COM_2(
9 CMultiOutStream
10 , IOutStream
11 , IStreamSetRestriction
12)
13 Z7_IFACE_COM7_IMP(ISequentialOutStream)
14
15 Z7_CLASS_NO_COPY(CMultiOutStream)
16
17 struct CVolStream
18 {
19 COutFileStream *StreamSpec;
20 CMyComPtr<IOutStream> Stream;
21 UInt64 Start; // start pos of current Stream in global stream
22 UInt64 Pos; // pos in current Stream
23 UInt64 RealSize;
24 int Next; // next older
25 int Prev; // prev newer
26 AString Postfix;
27
28 HRESULT SetSize2(UInt64 size)
29 {
30 const HRESULT res = Stream->SetSize(size);
31 if (res == SZ_OK)
32 RealSize = size;
33 return res;
34 }
35 };
36
37 unsigned _streamIndex; // (_streamIndex >= Stream.Size()) is allowed in some internal code
38 UInt64 _offsetPos; // offset relative to Streams[_streamIndex] volume. (_offsetPos >= volSize is allowed)
39 UInt64 _absPos;
40 UInt64 _length; // virtual Length
41 UInt64 _absLimit;
42
43 CObjectVector<CVolStream> Streams;
44 CRecordVector<UInt64> Sizes;
45
46 UInt64 _restrict_Begin;
47 UInt64 _restrict_End;
48 UInt64 _restrict_Global;
49
50 unsigned NumOpenFiles_AllowedMax;
51
52 // ----- Double Linked List -----
53
54 unsigned NumListItems;
55 int Head; // newest
56 int Tail; // oldest
57
58 void InitLinkedList()
59 {
60 Head = -1;
61 Tail = -1;
62 NumListItems = 0;
63 }
64
65 void InsertToLinkedList(unsigned index)
66 {
67 {
68 CVolStream &node = Streams[index];
69 node.Next = Head;
70 node.Prev = -1;
71 }
72 if (Head != -1)
73 Streams[(unsigned)Head].Prev = (int)index;
74 else
75 {
76 // if (Tail != -1) throw 1;
77 Tail = (int)index;
78 }
79 Head = (int)index;
80 NumListItems++;
81 }
82
83 void RemoveFromLinkedList(unsigned index)
84 {
85 CVolStream &s = Streams[index];
86 if (s.Next != -1) Streams[(unsigned)s.Next].Prev = s.Prev; else Tail = s.Prev;
87 if (s.Prev != -1) Streams[(unsigned)s.Prev].Next = s.Next; else Head = s.Next;
88 s.Next = -1; // optional
89 s.Prev = -1; // optional
90 NumListItems--;
91 }
92
93 /*
94 void Delete_LastStream_Records()
95 {
96 if (Streams.Back().Stream)
97 RemoveFromLinkedList(Streams.Size() - 1);
98 Streams.DeleteBack();
99 }
100 */
101
102 UInt64 GetVolSize_for_Stream(unsigned i) const
103 {
104 const unsigned last = Sizes.Size() - 1;
105 return Sizes[i < last ? i : last];
106 }
107 UInt64 GetGlobalOffset_for_NewStream() const
108 {
109 return Streams.Size() == 0 ? 0:
110 Streams.Back().Start +
111 GetVolSize_for_Stream(Streams.Size() - 1);
112 }
113 unsigned GetStreamIndex_for_Offset(UInt64 offset, UInt64 &relOffset) const;
114 bool IsRestricted(const CVolStream &s) const;
115 bool IsRestricted_Empty(const CVolStream &s) const
116 {
117 // (s) must be stream that has (VolSize == 0).
118 // we treat empty stream as restricted, if next byte is restricted.
119 if (s.Start < _restrict_Global)
120 return true;
121 return
122 (_restrict_Begin != _restrict_End)
123 && (_restrict_Begin <= s.Start)
124 && (_restrict_Begin == s.Start || _restrict_End > s.Start);
125 }
126 // bool IsRestricted_for_Close(unsigned index) const;
127 FString GetFilePath(unsigned index);
128
129 HRESULT CloseStream(unsigned index);
130 HRESULT CloseStream_and_DeleteFile(unsigned index);
131 HRESULT CloseStream_and_FinalRename(unsigned index);
132
133 HRESULT PrepareToOpenNew();
134 HRESULT CreateNewStream(UInt64 newSize);
135 HRESULT CreateStreams_If_Required(unsigned streamIndex);
136 HRESULT ReOpenStream(unsigned streamIndex);
137 HRESULT OptReOpen_and_SetSize(unsigned index, UInt64 size);
138
139 HRESULT Normalize_finalMode(bool finalMode);
140public:
141 FString Prefix;
142 CFiTime MTime;
143 bool MTime_Defined;
144 bool FinalVol_WasReopen;
145 bool NeedDelete;
146
147 CMultiOutStream() {}
148 ~CMultiOutStream();
149 void Init(const CRecordVector<UInt64> &sizes);
150 bool SetMTime_Final(const CFiTime &mTime);
151 UInt64 GetSize() const { return _length; }
152 /* it makes final flushing, closes open files and renames to final name if required
153 but it still keeps Streams array of all closed files.
154 So we still can delete all files later, if required */
155 HRESULT FinalFlush_and_CloseFiles(unsigned &numTotalVolumesRes);
156 // Destruct object without exceptions
157 HRESULT Destruct();
158};
159
160#endif
diff --git a/CPP/7zip/Common/OffsetStream.cpp b/CPP/7zip/Common/OffsetStream.cpp
index b16124c..a6b005e 100644
--- a/CPP/7zip/Common/OffsetStream.cpp
+++ b/CPP/7zip/Common/OffsetStream.cpp
@@ -2,8 +2,6 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../Common/Defs.h"
6
7#include "OffsetStream.h" 5#include "OffsetStream.h"
8 6
9HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset) 7HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset)
@@ -13,12 +11,12 @@ HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset)
13 return _stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL); 11 return _stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL);
14} 12}
15 13
16STDMETHODIMP COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 14Z7_COM7F_IMF(COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
17{ 15{
18 return _stream->Write(data, size, processedSize); 16 return _stream->Write(data, size, processedSize);
19} 17}
20 18
21STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 19Z7_COM7F_IMF(COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
22{ 20{
23 if (seekOrigin == STREAM_SEEK_SET) 21 if (seekOrigin == STREAM_SEEK_SET)
24 { 22 {
@@ -27,13 +25,13 @@ STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *new
27 offset += _offset; 25 offset += _offset;
28 } 26 }
29 UInt64 absoluteNewPosition = 0; // =0 for gcc-10 27 UInt64 absoluteNewPosition = 0; // =0 for gcc-10
30 HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition); 28 const HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition);
31 if (newPosition) 29 if (newPosition)
32 *newPosition = absoluteNewPosition - _offset; 30 *newPosition = absoluteNewPosition - _offset;
33 return result; 31 return result;
34} 32}
35 33
36STDMETHODIMP COffsetOutStream::SetSize(UInt64 newSize) 34Z7_COM7F_IMF(COffsetOutStream::SetSize(UInt64 newSize))
37{ 35{
38 return _stream->SetSize(_offset + newSize); 36 return _stream->SetSize(_offset + newSize);
39} 37}
diff --git a/CPP/7zip/Common/OffsetStream.h b/CPP/7zip/Common/OffsetStream.h
index 9074a24..9bd554c 100644
--- a/CPP/7zip/Common/OffsetStream.h
+++ b/CPP/7zip/Common/OffsetStream.h
@@ -1,26 +1,22 @@
1// OffsetStream.h 1// OffsetStream.h
2 2
3#ifndef __OFFSET_STREAM_H 3#ifndef ZIP7_INC_OFFSET_STREAM_H
4#define __OFFSET_STREAM_H 4#define ZIP7_INC_OFFSET_STREAM_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
8#include "../IStream.h" 8#include "../IStream.h"
9 9
10class COffsetOutStream: 10Z7_CLASS_IMP_NOQIB_1(
11 public IOutStream, 11 COffsetOutStream
12 public CMyUnknownImp 12 , IOutStream
13{ 13)
14 UInt64 _offset; 14 Z7_IFACE_COM7_IMP(ISequentialOutStream)
15
15 CMyComPtr<IOutStream> _stream; 16 CMyComPtr<IOutStream> _stream;
17 UInt64 _offset;
16public: 18public:
17 HRESULT Init(IOutStream *stream, UInt64 offset); 19 HRESULT Init(IOutStream *stream, UInt64 offset);
18
19 MY_UNKNOWN_IMP
20
21 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
22 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
23 STDMETHOD(SetSize)(UInt64 newSize);
24}; 20};
25 21
26#endif 22#endif
diff --git a/CPP/7zip/Common/OutBuffer.cpp b/CPP/7zip/Common/OutBuffer.cpp
index 4ba34a0..197b376 100644
--- a/CPP/7zip/Common/OutBuffer.cpp
+++ b/CPP/7zip/Common/OutBuffer.cpp
@@ -11,18 +11,18 @@ bool COutBuffer::Create(UInt32 bufSize) throw()
11 const UInt32 kMinBlockSize = 1; 11 const UInt32 kMinBlockSize = 1;
12 if (bufSize < kMinBlockSize) 12 if (bufSize < kMinBlockSize)
13 bufSize = kMinBlockSize; 13 bufSize = kMinBlockSize;
14 if (_buf != 0 && _bufSize == bufSize) 14 if (_buf && _bufSize == bufSize)
15 return true; 15 return true;
16 Free(); 16 Free();
17 _bufSize = bufSize; 17 _bufSize = bufSize;
18 _buf = (Byte *)::MidAlloc(bufSize); 18 _buf = (Byte *)::MidAlloc(bufSize);
19 return (_buf != 0); 19 return (_buf != NULL);
20} 20}
21 21
22void COutBuffer::Free() throw() 22void COutBuffer::Free() throw()
23{ 23{
24 ::MidFree(_buf); 24 ::MidFree(_buf);
25 _buf = 0; 25 _buf = NULL;
26} 26}
27 27
28void COutBuffer::Init() throw() 28void COutBuffer::Init() throw()
@@ -32,7 +32,7 @@ void COutBuffer::Init() throw()
32 _pos = 0; 32 _pos = 0;
33 _processedSize = 0; 33 _processedSize = 0;
34 _overDict = false; 34 _overDict = false;
35 #ifdef _NO_EXCEPTIONS 35 #ifdef Z7_NO_EXCEPTIONS
36 ErrorCode = S_OK; 36 ErrorCode = S_OK;
37 #endif 37 #endif
38} 38}
@@ -51,17 +51,17 @@ HRESULT COutBuffer::FlushPart() throw()
51 // _streamPos < _bufSize 51 // _streamPos < _bufSize
52 UInt32 size = (_streamPos >= _pos) ? (_bufSize - _streamPos) : (_pos - _streamPos); 52 UInt32 size = (_streamPos >= _pos) ? (_bufSize - _streamPos) : (_pos - _streamPos);
53 HRESULT result = S_OK; 53 HRESULT result = S_OK;
54 #ifdef _NO_EXCEPTIONS 54 #ifdef Z7_NO_EXCEPTIONS
55 result = ErrorCode; 55 result = ErrorCode;
56 #endif 56 #endif
57 if (_buf2 != 0) 57 if (_buf2)
58 { 58 {
59 memcpy(_buf2, _buf + _streamPos, size); 59 memcpy(_buf2, _buf + _streamPos, size);
60 _buf2 += size; 60 _buf2 += size;
61 } 61 }
62 62
63 if (_stream != 0 63 if (_stream
64 #ifdef _NO_EXCEPTIONS 64 #ifdef Z7_NO_EXCEPTIONS
65 && (ErrorCode == S_OK) 65 && (ErrorCode == S_OK)
66 #endif 66 #endif
67 ) 67 )
@@ -85,14 +85,14 @@ HRESULT COutBuffer::FlushPart() throw()
85 85
86HRESULT COutBuffer::Flush() throw() 86HRESULT COutBuffer::Flush() throw()
87{ 87{
88 #ifdef _NO_EXCEPTIONS 88 #ifdef Z7_NO_EXCEPTIONS
89 if (ErrorCode != S_OK) 89 if (ErrorCode != S_OK)
90 return ErrorCode; 90 return ErrorCode;
91 #endif 91 #endif
92 92
93 while (_streamPos != _pos) 93 while (_streamPos != _pos)
94 { 94 {
95 HRESULT result = FlushPart(); 95 const HRESULT result = FlushPart();
96 if (result != S_OK) 96 if (result != S_OK)
97 return result; 97 return result;
98 } 98 }
@@ -101,8 +101,8 @@ HRESULT COutBuffer::Flush() throw()
101 101
102void COutBuffer::FlushWithCheck() 102void COutBuffer::FlushWithCheck()
103{ 103{
104 HRESULT result = Flush(); 104 const HRESULT result = Flush();
105 #ifdef _NO_EXCEPTIONS 105 #ifdef Z7_NO_EXCEPTIONS
106 ErrorCode = result; 106 ErrorCode = result;
107 #else 107 #else
108 if (result != S_OK) 108 if (result != S_OK)
diff --git a/CPP/7zip/Common/OutBuffer.h b/CPP/7zip/Common/OutBuffer.h
index d7ca9f6..cef7d50 100644
--- a/CPP/7zip/Common/OutBuffer.h
+++ b/CPP/7zip/Common/OutBuffer.h
@@ -1,13 +1,13 @@
1// OutBuffer.h 1// OutBuffer.h
2 2
3#ifndef __OUT_BUFFER_H 3#ifndef ZIP7_INC_OUT_BUFFER_H
4#define __OUT_BUFFER_H 4#define ZIP7_INC_OUT_BUFFER_H
5 5
6#include "../IStream.h" 6#include "../IStream.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
8#include "../../Common/MyException.h" 8#include "../../Common/MyException.h"
9 9
10#ifndef _NO_EXCEPTIONS 10#ifndef Z7_NO_EXCEPTIONS
11struct COutBufferException: public CSystemException 11struct COutBufferException: public CSystemException
12{ 12{
13 COutBufferException(HRESULT errorCode): CSystemException(errorCode) {} 13 COutBufferException(HRESULT errorCode): CSystemException(errorCode) {}
@@ -29,11 +29,11 @@ protected:
29 29
30 HRESULT FlushPart() throw(); 30 HRESULT FlushPart() throw();
31public: 31public:
32 #ifdef _NO_EXCEPTIONS 32 #ifdef Z7_NO_EXCEPTIONS
33 HRESULT ErrorCode; 33 HRESULT ErrorCode;
34 #endif 34 #endif
35 35
36 COutBuffer(): _buf(0), _pos(0), _stream(0), _buf2(0) {} 36 COutBuffer(): _buf(NULL), _pos(0), _stream(NULL), _buf2(NULL) {}
37 ~COutBuffer() { Free(); } 37 ~COutBuffer() { Free(); }
38 38
39 bool Create(UInt32 bufSize) throw(); 39 bool Create(UInt32 bufSize) throw();
diff --git a/CPP/7zip/Common/OutMemStream.cpp b/CPP/7zip/Common/OutMemStream.cpp
index 241589d..29a2394 100644
--- a/CPP/7zip/Common/OutMemStream.cpp
+++ b/CPP/7zip/Common/OutMemStream.cpp
@@ -31,13 +31,13 @@ void COutMemStream::DetachData(CMemLockBlocks &blocks)
31 31
32HRESULT COutMemStream::WriteToRealStream() 32HRESULT COutMemStream::WriteToRealStream()
33{ 33{
34 RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream)); 34 RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream))
35 Blocks.Free(_memManager); 35 Blocks.Free(_memManager);
36 return S_OK; 36 return S_OK;
37} 37}
38 38
39 39
40STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 40Z7_COM7F_IMF(COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
41{ 41{
42 if (_realStreamMode) 42 if (_realStreamMode)
43 return OutSeqStream->Write(data, size, processedSize); 43 return OutSeqStream->Write(data, size, processedSize);
@@ -58,7 +58,7 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process
58 size -= (UInt32)curSize; 58 size -= (UInt32)curSize;
59 _curBlockPos += curSize; 59 _curBlockPos += curSize;
60 60
61 UInt64 pos64 = GetPos(); 61 const UInt64 pos64 = GetPos();
62 if (pos64 > Blocks.TotalSize) 62 if (pos64 > Blocks.TotalSize)
63 Blocks.TotalSize = pos64; 63 Blocks.TotalSize = pos64;
64 if (_curBlockPos == _memManager->GetBlockSize()) 64 if (_curBlockPos == _memManager->GetBlockSize())
@@ -83,9 +83,9 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process
83 case (WAIT_OBJECT_0 + 1): 83 case (WAIT_OBJECT_0 + 1):
84 { 84 {
85 _realStreamMode = true; 85 _realStreamMode = true;
86 RINOK(WriteToRealStream()); 86 RINOK(WriteToRealStream())
87 UInt32 processedSize2; 87 UInt32 processedSize2;
88 HRESULT res = OutSeqStream->Write(data, size, &processedSize2); 88 const HRESULT res = OutSeqStream->Write(data, size, &processedSize2);
89 if (processedSize) 89 if (processedSize)
90 *processedSize += processedSize2; 90 *processedSize += processedSize2;
91 return res; 91 return res;
@@ -103,7 +103,7 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process
103 { 103 {
104 if (waitResult == WAIT_FAILED) 104 if (waitResult == WAIT_FAILED)
105 { 105 {
106 DWORD res = ::GetLastError(); 106 const DWORD res = ::GetLastError();
107 if (res != 0) 107 if (res != 0)
108 return HRESULT_FROM_WIN32(res); 108 return HRESULT_FROM_WIN32(res);
109 } 109 }
@@ -118,7 +118,7 @@ STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *process
118 return S_OK; 118 return S_OK;
119} 119}
120 120
121STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 121Z7_COM7F_IMF(COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
122{ 122{
123 if (_realStreamMode) 123 if (_realStreamMode)
124 { 124 {
@@ -145,7 +145,7 @@ STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPos
145 return S_OK; 145 return S_OK;
146} 146}
147 147
148STDMETHODIMP COutMemStream::SetSize(UInt64 newSize) 148Z7_COM7F_IMF(COutMemStream::SetSize(UInt64 newSize))
149{ 149{
150 if (_realStreamMode) 150 if (_realStreamMode)
151 { 151 {
diff --git a/CPP/7zip/Common/OutMemStream.h b/CPP/7zip/Common/OutMemStream.h
index 873742e..7fc2dbd 100644
--- a/CPP/7zip/Common/OutMemStream.h
+++ b/CPP/7zip/Common/OutMemStream.h
@@ -1,19 +1,21 @@
1// OutMemStream.h 1// OutMemStream.h
2 2
3#ifndef __OUT_MEM_STREAM_H 3#ifndef ZIP7_INC_OUT_MEM_STREAM_H
4#define __OUT_MEM_STREAM_H 4#define ZIP7_INC_OUT_MEM_STREAM_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
8#include "MemBlocks.h" 8#include "MemBlocks.h"
9 9
10class COutMemStream: 10Z7_CLASS_IMP_NOQIB_1(
11 public IOutStream, 11 COutMemStream
12 public CMyUnknownImp 12 , IOutStream
13{ 13)
14 Z7_IFACE_COM7_IMP(ISequentialOutStream)
15
14 CMemBlockManagerMt *_memManager; 16 CMemBlockManagerMt *_memManager;
15 unsigned _curBlockIndex;
16 size_t _curBlockPos; 17 size_t _curBlockPos;
18 unsigned _curBlockIndex;
17 bool _realStreamMode; 19 bool _realStreamMode;
18 20
19 bool _unlockEventWasSent; 21 bool _unlockEventWasSent;
@@ -24,14 +26,13 @@ class COutMemStream:
24 HRESULT StopWriteResult; 26 HRESULT StopWriteResult;
25 CMemLockBlocks Blocks; 27 CMemLockBlocks Blocks;
26 28
27 UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; }
28
29 CMyComPtr<ISequentialOutStream> OutSeqStream; 29 CMyComPtr<ISequentialOutStream> OutSeqStream;
30 CMyComPtr<IOutStream> OutStream; 30 CMyComPtr<IOutStream> OutStream;
31 31
32 UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; }
33
32public: 34public:
33 35
34
35 HRes CreateEvents(SYNC_PARAM_DECL(synchro)) 36 HRes CreateEvents(SYNC_PARAM_DECL(synchro))
36 { 37 {
37 WRes wres = StopWritingEvent.CreateIfNotCreated_Reset(SYNC_WFMO(synchro)); 38 WRes wres = StopWritingEvent.CreateIfNotCreated_Reset(SYNC_WFMO(synchro));
@@ -98,12 +99,6 @@ public:
98 StopWriteResult = res; 99 StopWriteResult = res;
99 StopWritingEvent.Set(); 100 StopWritingEvent.Set();
100 } 101 }
101
102 MY_UNKNOWN_IMP
103
104 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
105 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
106 STDMETHOD(SetSize)(UInt64 newSize);
107}; 102};
108 103
109#endif 104#endif
diff --git a/CPP/7zip/Common/ProgressMt.cpp b/CPP/7zip/Common/ProgressMt.cpp
index c2714a2..ee21ab3 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
31 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); 31 NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
32 if (inSize) 32 if (inSize)
33 { 33 {
34 UInt64 diff = *inSize - InSizes[index]; 34 const UInt64 diff = *inSize - InSizes[index];
35 InSizes[index] = *inSize; 35 InSizes[index] = *inSize;
36 TotalInSize += diff; 36 TotalInSize += diff;
37 } 37 }
38 if (outSize) 38 if (outSize)
39 { 39 {
40 UInt64 diff = *outSize - OutSizes[index]; 40 const UInt64 diff = *outSize - OutSizes[index];
41 OutSizes[index] = *outSize; 41 OutSizes[index] = *outSize;
42 TotalOutSize += diff; 42 TotalOutSize += diff;
43 } 43 }
@@ -47,7 +47,7 @@ HRESULT CMtCompressProgressMixer::SetRatioInfo(unsigned index, const UInt64 *inS
47} 47}
48 48
49 49
50STDMETHODIMP CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 50Z7_COM7F_IMF(CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
51{ 51{
52 return _progress->SetRatioInfo(_index, inSize, outSize); 52 return _progress->SetRatioInfo(_index, inSize, outSize);
53} 53}
diff --git a/CPP/7zip/Common/ProgressMt.h b/CPP/7zip/Common/ProgressMt.h
index 32da976..78c806c 100644
--- a/CPP/7zip/Common/ProgressMt.h
+++ b/CPP/7zip/Common/ProgressMt.h
@@ -1,7 +1,7 @@
1// ProgressMt.h 1// ProgressMt.h
2 2
3#ifndef __PROGRESSMT_H 3#ifndef ZIP7_INC_PROGRESSMT_H
4#define __PROGRESSMT_H 4#define ZIP7_INC_PROGRESSMT_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7#include "../../Common/MyVector.h" 7#include "../../Common/MyVector.h"
@@ -24,12 +24,13 @@ public:
24 HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize); 24 HRESULT SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize);
25}; 25};
26 26
27class CMtCompressProgress: 27
28 public ICompressProgressInfo, 28Z7_CLASS_IMP_NOQIB_1(
29 public CMyUnknownImp 29 CMtCompressProgress
30{ 30 , ICompressProgressInfo
31 CMtCompressProgressMixer *_progress; 31)
32 unsigned _index; 32 unsigned _index;
33 CMtCompressProgressMixer *_progress;
33public: 34public:
34 void Init(CMtCompressProgressMixer *progress, unsigned index) 35 void Init(CMtCompressProgressMixer *progress, unsigned index)
35 { 36 {
@@ -37,10 +38,6 @@ public:
37 _index = index; 38 _index = index;
38 } 39 }
39 void Reinit() { _progress->Reinit(_index); } 40 void Reinit() { _progress->Reinit(_index); }
40
41 MY_UNKNOWN_IMP
42
43 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
44}; 41};
45 42
46#endif 43#endif
diff --git a/CPP/7zip/Common/ProgressUtils.cpp b/CPP/7zip/Common/ProgressUtils.cpp
index 41385cc..fb81f29 100644
--- a/CPP/7zip/Common/ProgressUtils.cpp
+++ b/CPP/7zip/Common/ProgressUtils.cpp
@@ -5,11 +5,11 @@
5#include "ProgressUtils.h" 5#include "ProgressUtils.h"
6 6
7CLocalProgress::CLocalProgress(): 7CLocalProgress::CLocalProgress():
8 SendRatio(true),
9 SendProgress(true),
8 ProgressOffset(0), 10 ProgressOffset(0),
9 InSize(0), 11 InSize(0),
10 OutSize(0), 12 OutSize(0)
11 SendRatio(true),
12 SendProgress(true)
13 {} 13 {}
14 14
15void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain) 15void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain)
@@ -20,7 +20,7 @@ void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain)
20 _inSizeIsMain = inSizeIsMain; 20 _inSizeIsMain = inSizeIsMain;
21} 21}
22 22
23STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 23Z7_COM7F_IMF(CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
24{ 24{
25 UInt64 inSize2 = InSize; 25 UInt64 inSize2 = InSize;
26 UInt64 outSize2 = OutSize; 26 UInt64 outSize2 = OutSize;
@@ -32,7 +32,7 @@ STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *ou
32 32
33 if (SendRatio && _ratioProgress) 33 if (SendRatio && _ratioProgress)
34 { 34 {
35 RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2)); 35 RINOK(_ratioProgress->SetRatioInfo(&inSize2, &outSize2))
36 } 36 }
37 37
38 if (SendProgress) 38 if (SendProgress)
diff --git a/CPP/7zip/Common/ProgressUtils.h b/CPP/7zip/Common/ProgressUtils.h
index e94265b..dad5fcc 100644
--- a/CPP/7zip/Common/ProgressUtils.h
+++ b/CPP/7zip/Common/ProgressUtils.h
@@ -1,35 +1,33 @@
1// ProgressUtils.h 1// ProgressUtils.h
2 2
3#ifndef __PROGRESS_UTILS_H 3#ifndef ZIP7_INC_PROGRESS_UTILS_H
4#define __PROGRESS_UTILS_H 4#define ZIP7_INC_PROGRESS_UTILS_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
8#include "../ICoder.h" 8#include "../ICoder.h"
9#include "../IProgress.h" 9#include "../IProgress.h"
10 10
11class CLocalProgress: 11Z7_CLASS_IMP_COM_1(
12 public ICompressProgressInfo, 12 CLocalProgress
13 public CMyUnknownImp 13 , ICompressProgressInfo
14{ 14)
15public:
16 bool SendRatio;
17 bool SendProgress;
18private:
19 bool _inSizeIsMain;
15 CMyComPtr<IProgress> _progress; 20 CMyComPtr<IProgress> _progress;
16 CMyComPtr<ICompressProgressInfo> _ratioProgress; 21 CMyComPtr<ICompressProgressInfo> _ratioProgress;
17 bool _inSizeIsMain;
18public: 22public:
19 UInt64 ProgressOffset; 23 UInt64 ProgressOffset;
20 UInt64 InSize; 24 UInt64 InSize;
21 UInt64 OutSize; 25 UInt64 OutSize;
22 bool SendRatio;
23 bool SendProgress;
24 26
25 CLocalProgress(); 27 CLocalProgress();
26 28
27 void Init(IProgress *progress, bool inSizeIsMain); 29 void Init(IProgress *progress, bool inSizeIsMain);
28 HRESULT SetCur(); 30 HRESULT SetCur();
29
30 MY_UNKNOWN_IMP1(ICompressProgressInfo)
31
32 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
33}; 31};
34 32
35#endif 33#endif
diff --git a/CPP/7zip/Common/PropId.cpp b/CPP/7zip/Common/PropId.cpp
index 0e643e8..6117b0e 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] =
111 VT_UI4, 111 VT_UI4,
112 VT_UI4, 112 VT_UI4,
113 VT_UI4, 113 VT_UI4,
114 VT_UI4 // kpidDeviceMinor 114 VT_UI4,
115 VT_UI4,
116 VT_UI4 // kpidDevMinor
115}; 117};
diff --git a/CPP/7zip/Common/RegisterArc.h b/CPP/7zip/Common/RegisterArc.h
index a0384fa..55c1483 100644
--- a/CPP/7zip/Common/RegisterArc.h
+++ b/CPP/7zip/Common/RegisterArc.h
@@ -1,7 +1,7 @@
1// RegisterArc.h 1// RegisterArc.h
2 2
3#ifndef __REGISTER_ARC_H 3#ifndef ZIP7_INC_REGISTER_ARC_H
4#define __REGISTER_ARC_H 4#define ZIP7_INC_REGISTER_ARC_H
5 5
6#include "../Archive/IArchive.h" 6#include "../Archive/IArchive.h"
7 7
@@ -34,7 +34,7 @@ void RegisterArc(const CArcInfo *arcInfo) throw();
34 34
35#define IMP_CreateArcIn IMP_CreateArcIn_2(CHandler()) 35#define IMP_CreateArcIn IMP_CreateArcIn_2(CHandler())
36 36
37#ifdef EXTRACT_ONLY 37#ifdef Z7_EXTRACT_ONLY
38 #define IMP_CreateArcOut 38 #define IMP_CreateArcOut
39 #define CreateArcOut NULL 39 #define CreateArcOut NULL
40#else 40#else
@@ -52,7 +52,7 @@ void RegisterArc(const CArcInfo *arcInfo) throw();
52 52
53#define REGISTER_ARC_I_CLS(cls, n, e, ae, id, sig, offs, flags, isArc) \ 53#define REGISTER_ARC_I_CLS(cls, n, e, ae, id, sig, offs, flags, isArc) \
54 IMP_CreateArcIn_2(cls) \ 54 IMP_CreateArcIn_2(cls) \
55 REGISTER_ARC_R(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, 0, CreateArc, NULL, isArc) 55 REGISTER_ARC_R(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, 0, CreateArc, NULL, isArc)
56 56
57#define REGISTER_ARC_I_CLS_NO_SIG(cls, n, e, ae, id, offs, flags, isArc) \ 57#define REGISTER_ARC_I_CLS_NO_SIG(cls, n, e, ae, id, offs, flags, isArc) \
58 IMP_CreateArcIn_2(cls) \ 58 IMP_CreateArcIn_2(cls) \
@@ -68,12 +68,12 @@ void RegisterArc(const CArcInfo *arcInfo) throw();
68#define REGISTER_ARC_IO(n, e, ae, id, sig, offs, flags, tf, isArc) \ 68#define REGISTER_ARC_IO(n, e, ae, id, sig, offs, flags, tf, isArc) \
69 IMP_CreateArcIn \ 69 IMP_CreateArcIn \
70 IMP_CreateArcOut \ 70 IMP_CreateArcOut \
71 REGISTER_ARC_R(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) 71 REGISTER_ARC_R(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc)
72 72
73#define REGISTER_ARC_IO_DECREMENT_SIG(n, e, ae, id, sig, offs, flags, tf, isArc) \ 73#define REGISTER_ARC_IO_DECREMENT_SIG(n, e, ae, id, sig, offs, flags, tf, isArc) \
74 IMP_CreateArcIn \ 74 IMP_CreateArcIn \
75 IMP_CreateArcOut \ 75 IMP_CreateArcOut \
76 REGISTER_ARC_V(n, e, ae, id, ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) \ 76 REGISTER_ARC_V(n, e, ae, id, Z7_ARRAY_SIZE(sig), sig, offs, flags, tf, CreateArc, CreateArcOut, isArc) \
77 struct CRegisterArcDecSig { CRegisterArcDecSig() { sig[0]--; RegisterArc(&g_ArcInfo); }}; \ 77 struct CRegisterArcDecSig { CRegisterArcDecSig() { sig[0]--; RegisterArc(&g_ArcInfo); }}; \
78 static CRegisterArcDecSig g_RegisterArc; 78 static CRegisterArcDecSig g_RegisterArc;
79 79
diff --git a/CPP/7zip/Common/RegisterCodec.h b/CPP/7zip/Common/RegisterCodec.h
index a942da7..cf94998 100644
--- a/CPP/7zip/Common/RegisterCodec.h
+++ b/CPP/7zip/Common/RegisterCodec.h
@@ -1,7 +1,7 @@
1// RegisterCodec.h 1// RegisterCodec.h
2 2
3#ifndef __REGISTER_CODEC_H 3#ifndef ZIP7_INC_REGISTER_CODEC_H
4#define __REGISTER_CODEC_H 4#define ZIP7_INC_REGISTER_CODEC_H
5 5
6#include "../Common/MethodId.h" 6#include "../Common/MethodId.h"
7 7
@@ -37,7 +37,7 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw();
37#define REGISTER_CODECS_VAR static const CCodecInfo g_CodecsInfo[] = 37#define REGISTER_CODECS_VAR static const CCodecInfo g_CodecsInfo[] =
38 38
39#define REGISTER_CODECS(x) struct REGISTER_CODECS_NAME(x) { \ 39#define REGISTER_CODECS(x) struct REGISTER_CODECS_NAME(x) { \
40 REGISTER_CODECS_NAME(x)() { for (unsigned i = 0; i < ARRAY_SIZE(g_CodecsInfo); i++) \ 40 REGISTER_CODECS_NAME(x)() { for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_CodecsInfo); i++) \
41 RegisterCodec(&g_CodecsInfo[i]); }}; \ 41 RegisterCodec(&g_CodecsInfo[i]); }}; \
42 static REGISTER_CODECS_NAME(x) g_RegisterCodecs; 42 static REGISTER_CODECS_NAME(x) g_RegisterCodecs;
43 43
@@ -48,7 +48,7 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw();
48 REGISTER_CODEC(x) 48 REGISTER_CODEC(x)
49 49
50 50
51#ifdef EXTRACT_ONLY 51#ifdef Z7_EXTRACT_ONLY
52 #define REGISTER_CODEC_E(x, clsDec, clsEnc, id, name) \ 52 #define REGISTER_CODEC_E(x, clsDec, clsEnc, id, name) \
53 REGISTER_CODEC_CREATE(CreateDec, clsDec) \ 53 REGISTER_CODEC_CREATE(CreateDec, clsDec) \
54 REGISTER_CODEC_2(x, CreateDec, NULL, id, name) 54 REGISTER_CODEC_2(x, CreateDec, NULL, id, name)
@@ -71,7 +71,7 @@ void RegisterCodec(const CCodecInfo *codecInfo) throw();
71 REGISTER_FILTER_ITEM(crDec, crEnc, id, name); \ 71 REGISTER_FILTER_ITEM(crDec, crEnc, id, name); \
72 REGISTER_CODEC(x) 72 REGISTER_CODEC(x)
73 73
74#ifdef EXTRACT_ONLY 74#ifdef Z7_EXTRACT_ONLY
75 #define REGISTER_FILTER_E(x, clsDec, clsEnc, id, name) \ 75 #define REGISTER_FILTER_E(x, clsDec, clsEnc, id, name) \
76 REGISTER_FILTER_CREATE(x ## _CreateDec, clsDec) \ 76 REGISTER_FILTER_CREATE(x ## _CreateDec, clsDec) \
77 REGISTER_FILTER(x, x ## _CreateDec, NULL, id, name) 77 REGISTER_FILTER(x, x ## _CreateDec, NULL, id, name)
@@ -97,7 +97,7 @@ void RegisterHasher(const CHasherInfo *hasher) throw();
97#define REGISTER_HASHER_NAME(x) CRegHasher_ ## x 97#define REGISTER_HASHER_NAME(x) CRegHasher_ ## x
98 98
99#define REGISTER_HASHER(cls, id, name, size) \ 99#define REGISTER_HASHER(cls, id, name, size) \
100 STDMETHODIMP_(UInt32) cls::GetDigestSize() throw() { return size; } \ 100 Z7_COM7F_IMF2(UInt32, cls::GetDigestSize()) { return size; } \
101 static IHasher *CreateHasherSpec() { return new cls(); } \ 101 static IHasher *CreateHasherSpec() { return new cls(); } \
102 static const CHasherInfo g_HasherInfo = { CreateHasherSpec, id, name, size }; \ 102 static const CHasherInfo g_HasherInfo = { CreateHasherSpec, id, name, size }; \
103 struct REGISTER_HASHER_NAME(cls) { REGISTER_HASHER_NAME(cls)() { RegisterHasher(&g_HasherInfo); }}; \ 103 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 1cbd7fe..8086655 100644
--- a/CPP/7zip/Common/StdAfx.h
+++ b/CPP/7zip/Common/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../Common/Common.h" 9#include "../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Common/StreamBinder.cpp b/CPP/7zip/Common/StreamBinder.cpp
index 6b6e0e5..38334af 100644
--- a/CPP/7zip/Common/StreamBinder.cpp
+++ b/CPP/7zip/Common/StreamBinder.cpp
@@ -6,51 +6,44 @@
6 6
7#include "StreamBinder.h" 7#include "StreamBinder.h"
8 8
9class CBinderInStream: 9Z7_CLASS_IMP_COM_1(
10 public ISequentialInStream, 10 CBinderInStream
11 public CMyUnknownImp 11 , ISequentialInStream
12{ 12)
13 CStreamBinder *_binder; 13 CStreamBinder *_binder;
14public: 14public:
15 MY_UNKNOWN_IMP1(ISequentialInStream)
16 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
17 ~CBinderInStream() { _binder->CloseRead_CallOnce(); } 15 ~CBinderInStream() { _binder->CloseRead_CallOnce(); }
18 CBinderInStream(CStreamBinder *binder): _binder(binder) {} 16 CBinderInStream(CStreamBinder *binder): _binder(binder) {}
19}; 17};
20 18
21STDMETHODIMP CBinderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 19Z7_COM7F_IMF(CBinderInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
22 { return _binder->Read(data, size, processedSize); } 20 { return _binder->Read(data, size, processedSize); }
23 21
24class CBinderOutStream: 22
25 public ISequentialOutStream, 23Z7_CLASS_IMP_COM_1(
26 public CMyUnknownImp 24 CBinderOutStream
27{ 25 , ISequentialOutStream
26)
28 CStreamBinder *_binder; 27 CStreamBinder *_binder;
29public: 28public:
30 MY_UNKNOWN_IMP1(ISequentialOutStream)
31 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
32 ~CBinderOutStream() { _binder->CloseWrite(); } 29 ~CBinderOutStream() { _binder->CloseWrite(); }
33 CBinderOutStream(CStreamBinder *binder): _binder(binder) {} 30 CBinderOutStream(CStreamBinder *binder): _binder(binder) {}
34}; 31};
35 32
36STDMETHODIMP CBinderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 33Z7_COM7F_IMF(CBinderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
37 { return _binder->Write(data, size, processedSize); } 34 { return _binder->Write(data, size, processedSize); }
38 35
39 36
40static HRESULT Event__Create_or_Reset(NWindows::NSynchronization::CAutoResetEvent &event) 37static HRESULT Event_Create_or_Reset(NWindows::NSynchronization::CAutoResetEvent &event)
41{ 38{
42 WRes wres; 39 const WRes wres = event.CreateIfNotCreated_Reset();
43 if (event.IsCreated())
44 wres = event.Reset();
45 else
46 wres = event.Create();
47 return HRESULT_FROM_WIN32(wres); 40 return HRESULT_FROM_WIN32(wres);
48} 41}
49 42
50HRESULT CStreamBinder::Create_ReInit() 43HRESULT CStreamBinder::Create_ReInit()
51{ 44{
52 RINOK(Event__Create_or_Reset(_canRead_Event)); 45 RINOK(Event_Create_or_Reset(_canRead_Event))
53 // RINOK(Event__Create_or_Reset(_canWrite_Event)); 46 // RINOK(Event_Create_or_Reset(_canWrite_Event))
54 47
55 // _canWrite_Semaphore.Close(); 48 // _canWrite_Semaphore.Close();
56 // we need at least 3 items of maxCount: 1 for normal unlock in Read(), 2 items for unlock in CloseRead_CallOnce() 49 // 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 16c872f..c0a7079 100644
--- a/CPP/7zip/Common/StreamBinder.h
+++ b/CPP/7zip/Common/StreamBinder.h
@@ -1,7 +1,7 @@
1// StreamBinder.h 1// StreamBinder.h
2 2
3#ifndef __STREAM_BINDER_H 3#ifndef ZIP7_INC_STREAM_BINDER_H
4#define __STREAM_BINDER_H 4#define ZIP7_INC_STREAM_BINDER_H
5 5
6#include "../../Windows/Synchronization.h" 6#include "../../Windows/Synchronization.h"
7 7
diff --git a/CPP/7zip/Common/StreamObjects.cpp b/CPP/7zip/Common/StreamObjects.cpp
index 2d941df..b54f423 100644
--- a/CPP/7zip/Common/StreamObjects.cpp
+++ b/CPP/7zip/Common/StreamObjects.cpp
@@ -2,13 +2,11 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include <stdlib.h>
6
7#include "../../../C/Alloc.h" 5#include "../../../C/Alloc.h"
8 6
9#include "StreamObjects.h" 7#include "StreamObjects.h"
10 8
11STDMETHODIMP CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 9Z7_COM7F_IMF(CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
12{ 10{
13 if (processedSize) 11 if (processedSize)
14 *processedSize = 0; 12 *processedSize = 0;
@@ -26,7 +24,7 @@ STDMETHODIMP CBufferInStream::Read(void *data, UInt32 size, UInt32 *processedSiz
26 return S_OK; 24 return S_OK;
27} 25}
28 26
29STDMETHODIMP CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 27Z7_COM7F_IMF(CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
30{ 28{
31 switch (seekOrigin) 29 switch (seekOrigin)
32 { 30 {
@@ -43,7 +41,7 @@ STDMETHODIMP CBufferInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newP
43 return S_OK; 41 return S_OK;
44} 42}
45 43
46STDMETHODIMP CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 44Z7_COM7F_IMF(CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
47{ 45{
48 if (processedSize) 46 if (processedSize)
49 *processedSize = 0; 47 *processedSize = 0;
@@ -61,7 +59,7 @@ STDMETHODIMP CBufInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
61 return S_OK; 59 return S_OK;
62} 60}
63 61
64STDMETHODIMP CBufInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 62Z7_COM7F_IMF(CBufInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
65{ 63{
66 switch (seekOrigin) 64 switch (seekOrigin)
67 { 65 {
@@ -99,8 +97,8 @@ void Create_BufInStream_WithNewBuffer(const void *data, size_t size, ISequential
99 97
100void CByteDynBuffer::Free() throw() 98void CByteDynBuffer::Free() throw()
101{ 99{
102 free(_buf); 100 MyFree(_buf);
103 _buf = 0; 101 _buf = NULL;
104 _capacity = 0; 102 _capacity = 0;
105} 103}
106 104
@@ -108,11 +106,10 @@ bool CByteDynBuffer::EnsureCapacity(size_t cap) throw()
108{ 106{
109 if (cap <= _capacity) 107 if (cap <= _capacity)
110 return true; 108 return true;
111 size_t delta = _capacity / 4; 109 const size_t cap2 = _capacity + _capacity / 4;
112 size_t cap2 = _capacity + delta;
113 if (cap < cap2) 110 if (cap < cap2)
114 cap = cap2; 111 cap = cap2;
115 Byte *buf = (Byte *)realloc(_buf, cap); 112 Byte *buf = (Byte *)MyRealloc(_buf, cap);
116 if (!buf) 113 if (!buf)
117 return false; 114 return false;
118 _buf = buf; 115 _buf = buf;
@@ -135,7 +132,7 @@ void CDynBufSeqOutStream::CopyToBuffer(CByteBuffer &dest) const
135 dest.CopyFrom((const Byte *)_buffer, _size); 132 dest.CopyFrom((const Byte *)_buffer, _size);
136} 133}
137 134
138STDMETHODIMP CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 135Z7_COM7F_IMF(CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
139{ 136{
140 if (processedSize) 137 if (processedSize)
141 *processedSize = 0; 138 *processedSize = 0;
@@ -151,7 +148,7 @@ STDMETHODIMP CDynBufSeqOutStream::Write(const void *data, UInt32 size, UInt32 *p
151 return S_OK; 148 return S_OK;
152} 149}
153 150
154STDMETHODIMP CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 151Z7_COM7F_IMF(CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
155{ 152{
156 size_t rem = _size - _pos; 153 size_t rem = _size - _pos;
157 if (rem > size) 154 if (rem > size)
@@ -166,7 +163,7 @@ STDMETHODIMP CBufPtrSeqOutStream::Write(const void *data, UInt32 size, UInt32 *p
166 return (rem != 0 || size == 0) ? S_OK : E_FAIL; 163 return (rem != 0 || size == 0) ? S_OK : E_FAIL;
167} 164}
168 165
169STDMETHODIMP CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize) 166Z7_COM7F_IMF(CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize))
170{ 167{
171 UInt32 realProcessedSize; 168 UInt32 realProcessedSize;
172 HRESULT result = _stream->Write(data, size, &realProcessedSize); 169 HRESULT result = _stream->Write(data, size, &realProcessedSize);
@@ -216,12 +213,12 @@ void CCachedInStream::Init(UInt64 size) throw()
216{ 213{
217 _size = size; 214 _size = size;
218 _pos = 0; 215 _pos = 0;
219 size_t numBlocks = (size_t)1 << _numBlocksLog; 216 const size_t numBlocks = (size_t)1 << _numBlocksLog;
220 for (size_t i = 0; i < numBlocks; i++) 217 for (size_t i = 0; i < numBlocks; i++)
221 _tags[i] = kEmptyTag; 218 _tags[i] = kEmptyTag;
222} 219}
223 220
224STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 221Z7_COM7F_IMF(CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
225{ 222{
226 if (processedSize) 223 if (processedSize)
227 *processedSize = 0; 224 *processedSize = 0;
@@ -231,7 +228,7 @@ STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSiz
231 return S_OK; 228 return S_OK;
232 229
233 { 230 {
234 UInt64 rem = _size - _pos; 231 const UInt64 rem = _size - _pos;
235 if (size > rem) 232 if (size > rem)
236 size = (UInt32)rem; 233 size = (UInt32)rem;
237 } 234 }
@@ -245,12 +242,12 @@ STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSiz
245 if (_tags[cacheIndex] != cacheTag) 242 if (_tags[cacheIndex] != cacheTag)
246 { 243 {
247 _tags[cacheIndex] = kEmptyTag; 244 _tags[cacheIndex] = kEmptyTag;
248 UInt64 remInBlock = _size - (cacheTag << _blockSizeLog); 245 const UInt64 remInBlock = _size - (cacheTag << _blockSizeLog);
249 size_t blockSize = (size_t)1 << _blockSizeLog; 246 size_t blockSize = (size_t)1 << _blockSizeLog;
250 if (blockSize > remInBlock) 247 if (blockSize > remInBlock)
251 blockSize = (size_t)remInBlock; 248 blockSize = (size_t)remInBlock;
252 249
253 RINOK(ReadBlock(cacheTag, p, blockSize)); 250 RINOK(ReadBlock(cacheTag, p, blockSize))
254 251
255 _tags[cacheIndex] = cacheTag; 252 _tags[cacheIndex] = cacheTag;
256 } 253 }
@@ -275,7 +272,7 @@ STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSiz
275} 272}
276 273
277 274
278STDMETHODIMP CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) 275Z7_COM7F_IMF(CCachedInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
279{ 276{
280 switch (seekOrigin) 277 switch (seekOrigin)
281 { 278 {
diff --git a/CPP/7zip/Common/StreamObjects.h b/CPP/7zip/Common/StreamObjects.h
index a8fb229..2c0ebea 100644
--- a/CPP/7zip/Common/StreamObjects.h
+++ b/CPP/7zip/Common/StreamObjects.h
@@ -1,7 +1,7 @@
1// StreamObjects.h 1// StreamObjects.h
2 2
3#ifndef __STREAM_OBJECTS_H 3#ifndef ZIP7_INC_STREAM_OBJECTS_H
4#define __STREAM_OBJECTS_H 4#define ZIP7_INC_STREAM_OBJECTS_H
5 5
6#include "../../Common/MyBuffer.h" 6#include "../../Common/MyBuffer.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
@@ -9,35 +9,27 @@
9 9
10#include "../IStream.h" 10#include "../IStream.h"
11 11
12class CBufferInStream: 12Z7_CLASS_IMP_IInStream(
13 public IInStream, 13 CBufferInStream
14 public CMyUnknownImp 14)
15{
16 UInt64 _pos; 15 UInt64 _pos;
17public: 16public:
18 CByteBuffer Buf; 17 CByteBuffer Buf;
19 void Init() { _pos = 0; } 18 void Init() { _pos = 0; }
20
21 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
22
23 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
24 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
25}; 19};
26 20
27 21
28struct CReferenceBuf: 22Z7_CLASS_IMP_COM_0(
29 public IUnknown, 23 CReferenceBuf
30 public CMyUnknownImp 24)
31{ 25public:
32 CByteBuffer Buf; 26 CByteBuffer Buf;
33 MY_UNKNOWN_IMP
34}; 27};
35 28
36 29
37class CBufInStream: 30Z7_CLASS_IMP_IInStream(
38 public IInStream, 31 CBufInStream
39 public CMyUnknownImp 32)
40{
41 const Byte *_data; 33 const Byte *_data;
42 UInt64 _pos; 34 UInt64 _pos;
43 size_t _size; 35 size_t _size;
@@ -52,9 +44,8 @@ public:
52 } 44 }
53 void Init(CReferenceBuf *ref) { Init(ref->Buf, ref->Buf.Size(), ref); } 45 void Init(CReferenceBuf *ref) { Init(ref->Buf, ref->Buf.Size(), ref); }
54 46
55 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream) 47 // Seek() is allowed here. So reading order could be changed
56 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); 48 bool WasFinished() const { return _pos == _size; }
57 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
58}; 49};
59 50
60 51
@@ -64,13 +55,13 @@ inline void Create_BufInStream_WithNewBuffer(const CByteBuffer &buf, ISequential
64 { Create_BufInStream_WithNewBuffer(buf, buf.Size(), stream); } 55 { Create_BufInStream_WithNewBuffer(buf, buf.Size(), stream); }
65 56
66 57
67class CByteDynBuffer 58class CByteDynBuffer Z7_final
68{ 59{
69 size_t _capacity; 60 size_t _capacity;
70 Byte *_buf; 61 Byte *_buf;
71 CLASS_NO_COPY(CByteDynBuffer); 62 Z7_CLASS_NO_COPY(CByteDynBuffer)
72public: 63public:
73 CByteDynBuffer(): _capacity(0), _buf(NULL) {}; 64 CByteDynBuffer(): _capacity(0), _buf(NULL) {}
74 // there is no copy constructor. So don't copy this object. 65 // there is no copy constructor. So don't copy this object.
75 ~CByteDynBuffer() { Free(); } 66 ~CByteDynBuffer() { Free(); }
76 void Free() throw(); 67 void Free() throw();
@@ -81,10 +72,10 @@ public:
81}; 72};
82 73
83 74
84class CDynBufSeqOutStream: 75Z7_CLASS_IMP_COM_1(
85 public ISequentialOutStream, 76 CDynBufSeqOutStream
86 public CMyUnknownImp 77 , ISequentialOutStream
87{ 78)
88 CByteDynBuffer _buffer; 79 CByteDynBuffer _buffer;
89 size_t _size; 80 size_t _size;
90public: 81public:
@@ -95,16 +86,13 @@ public:
95 void CopyToBuffer(CByteBuffer &dest) const; 86 void CopyToBuffer(CByteBuffer &dest) const;
96 Byte *GetBufPtrForWriting(size_t addSize); 87 Byte *GetBufPtrForWriting(size_t addSize);
97 void UpdateSize(size_t addSize) { _size += addSize; } 88 void UpdateSize(size_t addSize) { _size += addSize; }
98
99 MY_UNKNOWN_IMP1(ISequentialOutStream)
100 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
101}; 89};
102 90
103 91
104class CBufPtrSeqOutStream: 92Z7_CLASS_IMP_COM_1(
105 public ISequentialOutStream, 93 CBufPtrSeqOutStream
106 public CMyUnknownImp 94 , ISequentialOutStream
107{ 95)
108 Byte *_buffer; 96 Byte *_buffer;
109 size_t _size; 97 size_t _size;
110 size_t _pos; 98 size_t _pos;
@@ -116,25 +104,19 @@ public:
116 _size = size; 104 _size = size;
117 } 105 }
118 size_t GetPos() const { return _pos; } 106 size_t GetPos() const { return _pos; }
119
120 MY_UNKNOWN_IMP1(ISequentialOutStream)
121 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
122}; 107};
123 108
124 109
125class CSequentialOutStreamSizeCount: 110Z7_CLASS_IMP_COM_1(
126 public ISequentialOutStream, 111 CSequentialOutStreamSizeCount
127 public CMyUnknownImp 112 , ISequentialOutStream
128{ 113)
129 CMyComPtr<ISequentialOutStream> _stream; 114 CMyComPtr<ISequentialOutStream> _stream;
130 UInt64 _size; 115 UInt64 _size;
131public: 116public:
132 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 117 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
133 void Init() { _size = 0; } 118 void Init() { _size = 0; }
134 UInt64 GetSize() const { return _size; } 119 UInt64 GetSize() const { return _size; }
135
136 MY_UNKNOWN_IMP1(ISequentialOutStream)
137 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
138}; 120};
139 121
140 122
@@ -142,6 +124,8 @@ class CCachedInStream:
142 public IInStream, 124 public IInStream,
143 public CMyUnknownImp 125 public CMyUnknownImp
144{ 126{
127 Z7_IFACES_IMP_UNK_2(ISequentialInStream, IInStream)
128
145 UInt64 *_tags; 129 UInt64 *_tags;
146 Byte *_data; 130 Byte *_data;
147 size_t _dataSize; 131 size_t _dataSize;
@@ -153,14 +137,10 @@ protected:
153 virtual HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) = 0; 137 virtual HRESULT ReadBlock(UInt64 blockIndex, Byte *dest, size_t blockSize) = 0;
154public: 138public:
155 CCachedInStream(): _tags(NULL), _data(NULL) {} 139 CCachedInStream(): _tags(NULL), _data(NULL) {}
156 virtual ~CCachedInStream() { Free(); } // the destructor must be virtual (release calls it) !!! 140 virtual ~CCachedInStream() { Free(); } // the destructor must be virtual (Release() calls it) !!!
157 void Free() throw(); 141 void Free() throw();
158 bool Alloc(unsigned blockSizeLog, unsigned numBlocksLog) throw(); 142 bool Alloc(unsigned blockSizeLog, unsigned numBlocksLog) throw();
159 void Init(UInt64 size) throw(); 143 void Init(UInt64 size) throw();
160
161 MY_UNKNOWN_IMP2(ISequentialInStream, IInStream)
162 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
163 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
164}; 144};
165 145
166#endif 146#endif
diff --git a/CPP/7zip/Common/StreamUtils.cpp b/CPP/7zip/Common/StreamUtils.cpp
index 1402f42..24eed36 100644
--- a/CPP/7zip/Common/StreamUtils.cpp
+++ b/CPP/7zip/Common/StreamUtils.cpp
@@ -2,10 +2,55 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../Common/MyCom.h"
6
5#include "StreamUtils.h" 7#include "StreamUtils.h"
6 8
7static const UInt32 kBlockSize = ((UInt32)1 << 31); 9static const UInt32 kBlockSize = ((UInt32)1 << 31);
8 10
11
12HRESULT InStream_SeekToBegin(IInStream *stream) throw()
13{
14 return InStream_SeekSet(stream, 0);
15}
16
17
18HRESULT InStream_AtBegin_GetSize(IInStream *stream, UInt64 &sizeRes) throw()
19{
20#ifdef _WIN32
21 {
22 Z7_DECL_CMyComPtr_QI_FROM(
23 IStreamGetSize,
24 streamGetSize, stream)
25 if (streamGetSize && streamGetSize->GetSize(&sizeRes) == S_OK)
26 return S_OK;
27 }
28#endif
29 const HRESULT hres = InStream_GetSize_SeekToEnd(stream, sizeRes);
30 const HRESULT hres2 = InStream_SeekToBegin(stream);
31 return hres != S_OK ? hres : hres2;
32}
33
34
35HRESULT InStream_GetPos_GetSize(IInStream *stream, UInt64 &curPosRes, UInt64 &sizeRes) throw()
36{
37 RINOK(InStream_GetPos(stream, curPosRes))
38#ifdef _WIN32
39 {
40 Z7_DECL_CMyComPtr_QI_FROM(
41 IStreamGetSize,
42 streamGetSize, stream)
43 if (streamGetSize && streamGetSize->GetSize(&sizeRes) == S_OK)
44 return S_OK;
45 }
46#endif
47 const HRESULT hres = InStream_GetSize_SeekToEnd(stream, sizeRes);
48 const HRESULT hres2 = InStream_SeekSet(stream, curPosRes);
49 return hres != S_OK ? hres : hres2;
50}
51
52
53
9HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize) throw() 54HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize) throw()
10{ 55{
11 size_t size = *processedSize; 56 size_t size = *processedSize;
@@ -18,7 +63,7 @@ HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSiz
18 *processedSize += processedSizeLoc; 63 *processedSize += processedSizeLoc;
19 data = (void *)((Byte *)data + processedSizeLoc); 64 data = (void *)((Byte *)data + processedSizeLoc);
20 size -= processedSizeLoc; 65 size -= processedSizeLoc;
21 RINOK(res); 66 RINOK(res)
22 if (processedSizeLoc == 0) 67 if (processedSizeLoc == 0)
23 return S_OK; 68 return S_OK;
24 } 69 }
@@ -28,14 +73,14 @@ HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSiz
28HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw() 73HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw()
29{ 74{
30 size_t processedSize = size; 75 size_t processedSize = size;
31 RINOK(ReadStream(stream, data, &processedSize)); 76 RINOK(ReadStream(stream, data, &processedSize))
32 return (size == processedSize) ? S_OK : S_FALSE; 77 return (size == processedSize) ? S_OK : S_FALSE;
33} 78}
34 79
35HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) throw() 80HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) throw()
36{ 81{
37 size_t processedSize = size; 82 size_t processedSize = size;
38 RINOK(ReadStream(stream, data, &processedSize)); 83 RINOK(ReadStream(stream, data, &processedSize))
39 return (size == processedSize) ? S_OK : E_FAIL; 84 return (size == processedSize) ? S_OK : E_FAIL;
40} 85}
41 86
@@ -48,7 +93,7 @@ HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size)
48 HRESULT res = stream->Write(data, curSize, &processedSizeLoc); 93 HRESULT res = stream->Write(data, curSize, &processedSizeLoc);
49 data = (const void *)((const Byte *)data + processedSizeLoc); 94 data = (const void *)((const Byte *)data + processedSizeLoc);
50 size -= processedSizeLoc; 95 size -= processedSizeLoc;
51 RINOK(res); 96 RINOK(res)
52 if (processedSizeLoc == 0) 97 if (processedSizeLoc == 0)
53 return E_FAIL; 98 return E_FAIL;
54 } 99 }
diff --git a/CPP/7zip/Common/StreamUtils.h b/CPP/7zip/Common/StreamUtils.h
index ae914c0..35a62ed 100644
--- a/CPP/7zip/Common/StreamUtils.h
+++ b/CPP/7zip/Common/StreamUtils.h
@@ -1,10 +1,28 @@
1// StreamUtils.h 1// StreamUtils.h
2 2
3#ifndef __STREAM_UTILS_H 3#ifndef ZIP7_INC_STREAM_UTILS_H
4#define __STREAM_UTILS_H 4#define ZIP7_INC_STREAM_UTILS_H
5 5
6#include "../IStream.h" 6#include "../IStream.h"
7 7
8inline HRESULT InStream_SeekSet(IInStream *stream, UInt64 offset) throw()
9 { return stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL); }
10inline HRESULT InStream_GetPos(IInStream *stream, UInt64 &curPosRes) throw()
11 { return stream->Seek(0, STREAM_SEEK_CUR, &curPosRes); }
12inline HRESULT InStream_GetSize_SeekToEnd(IInStream *stream, UInt64 &sizeRes) throw()
13 { return stream->Seek(0, STREAM_SEEK_END, &sizeRes); }
14
15HRESULT InStream_SeekToBegin(IInStream *stream) throw();
16HRESULT InStream_AtBegin_GetSize(IInStream *stream, UInt64 &size) throw();
17HRESULT InStream_GetPos_GetSize(IInStream *stream, UInt64 &curPosRes, UInt64 &sizeRes) throw();
18
19inline HRESULT InStream_GetSize_SeekToBegin(IInStream *stream, UInt64 &sizeRes) throw()
20{
21 RINOK(InStream_SeekToBegin(stream))
22 return InStream_AtBegin_GetSize(stream, sizeRes);
23}
24
25
8HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *size) throw(); 26HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *size) throw();
9HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw(); 27HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) throw();
10HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) throw(); 28HRESULT 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 8479d68..66c7fa2 100644
--- a/CPP/7zip/Common/UniqBlocks.h
+++ b/CPP/7zip/Common/UniqBlocks.h
@@ -1,7 +1,7 @@
1// UniqBlocks.h 1// UniqBlocks.h
2 2
3#ifndef __UNIQ_BLOCKS_H 3#ifndef ZIP7_INC_UNIQ_BLOCKS_H
4#define __UNIQ_BLOCKS_H 4#define ZIP7_INC_UNIQ_BLOCKS_H
5 5
6#include "../../Common/MyBuffer.h" 6#include "../../Common/MyBuffer.h"
7#include "../../Common/MyString.h" 7#include "../../Common/MyString.h"
diff --git a/CPP/7zip/Common/VirtThread.cpp b/CPP/7zip/Common/VirtThread.cpp
index bf24bb1..3cf7296 100644
--- a/CPP/7zip/Common/VirtThread.cpp
+++ b/CPP/7zip/Common/VirtThread.cpp
@@ -11,7 +11,7 @@ static THREAD_FUNC_DECL CoderThread(void *p)
11 CVirtThread *t = (CVirtThread *)p; 11 CVirtThread *t = (CVirtThread *)p;
12 t->StartEvent.Lock(); 12 t->StartEvent.Lock();
13 if (t->Exit) 13 if (t->Exit)
14 return 0; 14 return THREAD_FUNC_RET_ZERO;
15 t->Execute(); 15 t->Execute();
16 t->FinishedEvent.Set(); 16 t->FinishedEvent.Set();
17 } 17 }
@@ -19,8 +19,8 @@ static THREAD_FUNC_DECL CoderThread(void *p)
19 19
20WRes CVirtThread::Create() 20WRes CVirtThread::Create()
21{ 21{
22 RINOK_WRes(StartEvent.CreateIfNotCreated_Reset()); 22 RINOK_WRes(StartEvent.CreateIfNotCreated_Reset())
23 RINOK_WRes(FinishedEvent.CreateIfNotCreated_Reset()); 23 RINOK_WRes(FinishedEvent.CreateIfNotCreated_Reset())
24 // StartEvent.Reset(); 24 // StartEvent.Reset();
25 // FinishedEvent.Reset(); 25 // FinishedEvent.Reset();
26 Exit = false; 26 Exit = false;
diff --git a/CPP/7zip/Common/VirtThread.h b/CPP/7zip/Common/VirtThread.h
index b4d8a5a..809b356 100644
--- a/CPP/7zip/Common/VirtThread.h
+++ b/CPP/7zip/Common/VirtThread.h
@@ -1,7 +1,7 @@
1// VirtThread.h 1// VirtThread.h
2 2
3#ifndef __VIRT_THREAD_H 3#ifndef ZIP7_INC_VIRT_THREAD_H
4#define __VIRT_THREAD_H 4#define ZIP7_INC_VIRT_THREAD_H
5 5
6#include "../../Windows/Synchronization.h" 6#include "../../Windows/Synchronization.h"
7#include "../../Windows/Thread.h" 7#include "../../Windows/Thread.h"
@@ -13,7 +13,7 @@ struct CVirtThread
13 NWindows::CThread Thread; 13 NWindows::CThread Thread;
14 bool Exit; 14 bool Exit;
15 15
16 ~CVirtThread() { WaitThreadFinish(); } 16 virtual ~CVirtThread() { WaitThreadFinish(); }
17 void WaitThreadFinish(); // call it in destructor of child class ! 17 void WaitThreadFinish(); // call it in destructor of child class !
18 WRes Create(); 18 WRes Create();
19 WRes Start(); 19 WRes Start();
diff --git a/CPP/7zip/Compress/BZip2Const.h b/CPP/7zip/Compress/BZip2Const.h
index 7927d01..0dfcfe5 100644
--- a/CPP/7zip/Compress/BZip2Const.h
+++ b/CPP/7zip/Compress/BZip2Const.h
@@ -1,7 +1,7 @@
1// Compress/BZip2Const.h 1// Compress/BZip2Const.h
2 2
3#ifndef __COMPRESS_BZIP2_CONST_H 3#ifndef ZIP7_INC_COMPRESS_BZIP2_CONST_H
4#define __COMPRESS_BZIP2_CONST_H 4#define ZIP7_INC_COMPRESS_BZIP2_CONST_H
5 5
6namespace NCompress { 6namespace NCompress {
7namespace NBZip2 { 7namespace NBZip2 {
diff --git a/CPP/7zip/Compress/BZip2Crc.h b/CPP/7zip/Compress/BZip2Crc.h
index 3b16c60..10e147b 100644
--- a/CPP/7zip/Compress/BZip2Crc.h
+++ b/CPP/7zip/Compress/BZip2Crc.h
@@ -1,7 +1,7 @@
1// BZip2Crc.h 1// BZip2Crc.h
2 2
3#ifndef __BZIP2_CRC_H 3#ifndef ZIP7_INC_BZIP2_CRC_H
4#define __BZIP2_CRC_H 4#define ZIP7_INC_BZIP2_CRC_H
5 5
6#include "../../Common/MyTypes.h" 6#include "../../Common/MyTypes.h"
7 7
@@ -11,10 +11,10 @@ class CBZip2Crc
11 static UInt32 Table[256]; 11 static UInt32 Table[256];
12public: 12public:
13 static void InitTable(); 13 static void InitTable();
14 CBZip2Crc(UInt32 initVal = 0xFFFFFFFF): _value(initVal) {}; 14 CBZip2Crc(UInt32 initVal = 0xFFFFFFFF): _value(initVal) {}
15 void Init(UInt32 initVal = 0xFFFFFFFF) { _value = initVal; } 15 void Init(UInt32 initVal = 0xFFFFFFFF) { _value = initVal; }
16 void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } 16 void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); }
17 void UpdateByte(unsigned int b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } 17 void UpdateByte(unsigned b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); }
18 UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; } 18 UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; }
19}; 19};
20 20
@@ -22,7 +22,7 @@ class CBZip2CombinedCrc
22{ 22{
23 UInt32 _value; 23 UInt32 _value;
24public: 24public:
25 CBZip2CombinedCrc(): _value(0){}; 25 CBZip2CombinedCrc(): _value(0) {}
26 void Init() { _value = 0; } 26 void Init() { _value = 0; }
27 void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; } 27 void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; }
28 UInt32 GetDigest() const { return _value ; } 28 UInt32 GetDigest() const { return _value ; }
diff --git a/CPP/7zip/Compress/BZip2Decoder.cpp b/CPP/7zip/Compress/BZip2Decoder.cpp
index c09c160..b28da5f 100644
--- a/CPP/7zip/Compress/BZip2Decoder.cpp
+++ b/CPP/7zip/Compress/BZip2Decoder.cpp
@@ -32,7 +32,7 @@ namespace NCompress {
32namespace NBZip2 { 32namespace NBZip2 {
33 33
34// #undef NO_INLINE 34// #undef NO_INLINE
35#define NO_INLINE MY_NO_INLINE 35#define NO_INLINE Z7_NO_INLINE
36 36
37#define BZIP2_BYTE_MODE 37#define BZIP2_BYTE_MODE
38 38
@@ -169,7 +169,7 @@ enum EState
169SRes CBitDecoder::ReadByte(int &b) 169SRes CBitDecoder::ReadByte(int &b)
170{ 170{
171 b = -1; 171 b = -1;
172 READ_BITS_8(b, 8); 172 READ_BITS_8(b, 8)
173 return SZ_OK; 173 return SZ_OK;
174} 174}
175 175
@@ -180,7 +180,7 @@ SRes CBase::ReadStreamSignature2()
180 for (;;) 180 for (;;)
181 { 181 {
182 unsigned b; 182 unsigned b;
183 READ_BITS_8(b, 8); 183 READ_BITS_8(b, 8)
184 184
185 if ( (state2 == 0 && b != kArSig0) 185 if ( (state2 == 0 && b != kArSig0)
186 || (state2 == 1 && b != kArSig1) 186 || (state2 == 1 && b != kArSig1)
@@ -230,7 +230,7 @@ SRes CBase::ReadBlockSignature2()
230 while (state2 < 10) 230 while (state2 < 10)
231 { 231 {
232 unsigned b; 232 unsigned b;
233 READ_BITS_8(b, 8); 233 READ_BITS_8(b, 8)
234 temp[state2] = (Byte)b; 234 temp[state2] = (Byte)b;
235 state2++; 235 state2++;
236 } 236 }
@@ -285,7 +285,7 @@ SRes CBase::ReadBlock2()
285 { 285 {
286 if (Props.randMode) 286 if (Props.randMode)
287 { 287 {
288 READ_BIT(Props.randMode); 288 READ_BIT(Props.randMode)
289 } 289 }
290 state = STATE_ORIG_BITS; 290 state = STATE_ORIG_BITS;
291 // g_Tick = GetCpuTicks(); 291 // g_Tick = GetCpuTicks();
@@ -293,7 +293,7 @@ SRes CBase::ReadBlock2()
293 293
294 if (state == STATE_ORIG_BITS) 294 if (state == STATE_ORIG_BITS)
295 { 295 {
296 READ_BITS(Props.origPtr, kNumOrigBits); 296 READ_BITS(Props.origPtr, kNumOrigBits)
297 if (Props.origPtr >= blockSizeMax) 297 if (Props.origPtr >= blockSizeMax)
298 return SZ_ERROR_DATA; 298 return SZ_ERROR_DATA;
299 state = STATE_IN_USE; 299 state = STATE_IN_USE;
@@ -303,7 +303,7 @@ SRes CBase::ReadBlock2()
303 303
304 if (state == STATE_IN_USE) 304 if (state == STATE_IN_USE)
305 { 305 {
306 READ_BITS(state2, 16); 306 READ_BITS(state2, 16)
307 state = STATE_IN_USE2; 307 state = STATE_IN_USE2;
308 state3 = 0; 308 state3 = 0;
309 numInUse = 0; 309 numInUse = 0;
@@ -316,7 +316,7 @@ SRes CBase::ReadBlock2()
316 if (state2 & ((UInt32)0x8000 >> (state3 >> 4))) 316 if (state2 & ((UInt32)0x8000 >> (state3 >> 4)))
317 { 317 {
318 unsigned b; 318 unsigned b;
319 READ_BIT(b); 319 READ_BIT(b)
320 if (b) 320 if (b)
321 mtf.Add(numInUse++, (Byte)state3); 321 mtf.Add(numInUse++, (Byte)state3);
322 } 322 }
@@ -328,7 +328,7 @@ SRes CBase::ReadBlock2()
328 328
329 if (state == STATE_NUM_TABLES) 329 if (state == STATE_NUM_TABLES)
330 { 330 {
331 READ_BITS_8(numTables, kNumTablesBits); 331 READ_BITS_8(numTables, kNumTablesBits)
332 state = STATE_NUM_SELECTORS; 332 state = STATE_NUM_SELECTORS;
333 if (numTables < kNumTablesMin || numTables > kNumTablesMax) 333 if (numTables < kNumTablesMin || numTables > kNumTablesMax)
334 return SZ_ERROR_DATA; 334 return SZ_ERROR_DATA;
@@ -336,7 +336,7 @@ SRes CBase::ReadBlock2()
336 336
337 if (state == STATE_NUM_SELECTORS) 337 if (state == STATE_NUM_SELECTORS)
338 { 338 {
339 READ_BITS(numSelectors, kNumSelectorsBits); 339 READ_BITS(numSelectors, kNumSelectorsBits)
340 state = STATE_SELECTORS; 340 state = STATE_SELECTORS;
341 state2 = 0x543210; 341 state2 = 0x543210;
342 state3 = 0; 342 state3 = 0;
@@ -358,7 +358,7 @@ SRes CBase::ReadBlock2()
358 for (;;) 358 for (;;)
359 { 359 {
360 unsigned b; 360 unsigned b;
361 READ_BIT(b); 361 READ_BIT(b)
362 if (!b) 362 if (!b)
363 break; 363 break;
364 if (++state4 >= numTables) 364 if (++state4 >= numTables)
@@ -392,7 +392,7 @@ SRes CBase::ReadBlock2()
392 { 392 {
393 if (state3 == 0) 393 if (state3 == 0)
394 { 394 {
395 READ_BITS_8(state3, kNumLevelsBits); 395 READ_BITS_8(state3, kNumLevelsBits)
396 state4 = 0; 396 state4 = 0;
397 state5 = 0; 397 state5 = 0;
398 } 398 }
@@ -407,14 +407,14 @@ SRes CBase::ReadBlock2()
407 if (state5 == 0) 407 if (state5 == 0)
408 { 408 {
409 unsigned b; 409 unsigned b;
410 READ_BIT(b); 410 READ_BIT(b)
411 if (!b) 411 if (!b)
412 break; 412 break;
413 } 413 }
414 414
415 state5 = 1; 415 state5 = 1;
416 unsigned b; 416 unsigned b;
417 READ_BIT(b); 417 READ_BIT(b)
418 418
419 state5 = 0; 419 state5 = 0;
420 state3++; 420 state3++;
@@ -573,8 +573,8 @@ SRes CBase::ReadBlock2()
573 573
574 // UInt32 b = (UInt32)mtf.GetAndMove((unsigned)sym); 574 // UInt32 b = (UInt32)mtf.GetAndMove((unsigned)sym);
575 575
576 const unsigned lim = sym >> MTF_MOVS; 576 const unsigned lim = sym >> Z7_MTF_MOVS;
577 const unsigned pos = (sym & MTF_MASK) << 3; 577 const unsigned pos = (sym & Z7_MTF_MASK) << 3;
578 CMtfVar next = mtf.Buf[lim]; 578 CMtfVar next = mtf.Buf[lim];
579 CMtfVar prev = (next >> pos) & 0xFF; 579 CMtfVar prev = (next >> pos) & 0xFF;
580 580
@@ -593,7 +593,7 @@ SRes CBase::ReadBlock2()
593 { 593 {
594 CMtfVar n0 = *m; 594 CMtfVar n0 = *m;
595 *m = (n0 << 8) | prev; 595 *m = (n0 << 8) | prev;
596 prev = (n0 >> (MTF_MASK << 3)); 596 prev = (n0 >> (Z7_MTF_MASK << 3));
597 } 597 }
598 while (++m != mLim); 598 while (++m != mLim);
599 } 599 }
@@ -879,7 +879,7 @@ HRESULT CDecoder::DecodeBlock(const CBlockProps &props)
879 879
880 if (processed >= size) 880 if (processed >= size)
881 { 881 {
882 RINOK(Flush()); 882 RINOK(Flush())
883 } 883 }
884 884
885 if (block.Finished()) 885 if (block.Finished())
@@ -900,7 +900,7 @@ CDecoder::CDecoder():
900 _inBuf(NULL), 900 _inBuf(NULL),
901 _inProcessed(0) 901 _inProcessed(0)
902{ 902{
903 #ifndef _7ZIP_ST 903 #ifndef Z7_ST
904 MtMode = false; 904 MtMode = false;
905 NeedWaitScout = false; 905 NeedWaitScout = false;
906 // ScoutRes = S_OK; 906 // ScoutRes = S_OK;
@@ -912,7 +912,7 @@ CDecoder::~CDecoder()
912{ 912{
913 PRIN("\n~CDecoder()"); 913 PRIN("\n~CDecoder()");
914 914
915 #ifndef _7ZIP_ST 915 #ifndef Z7_ST
916 916
917 if (Thread.IsCreated()) 917 if (Thread.IsCreated())
918 { 918 {
@@ -966,7 +966,7 @@ HRESULT CDecoder::ReadStreamSignature()
966{ 966{
967 for (;;) 967 for (;;)
968 { 968 {
969 RINOK(ReadInput()); 969 RINOK(ReadInput())
970 SRes res = Base.ReadStreamSignature2(); 970 SRes res = Base.ReadStreamSignature2();
971 if (res != SZ_OK) 971 if (res != SZ_OK)
972 return S_FALSE; 972 return S_FALSE;
@@ -992,7 +992,7 @@ HRESULT CDecoder::ReadBlockSignature()
992{ 992{
993 for (;;) 993 for (;;)
994 { 994 {
995 RINOK(ReadInput()); 995 RINOK(ReadInput())
996 996
997 SRes res = Base.ReadBlockSignature2(); 997 SRes res = Base.ReadBlockSignature2();
998 998
@@ -1015,7 +1015,7 @@ HRESULT CDecoder::ReadBlock()
1015{ 1015{
1016 for (;;) 1016 for (;;)
1017 { 1017 {
1018 RINOK(ReadInput()); 1018 RINOK(ReadInput())
1019 1019
1020 SRes res = Base.ReadBlock2(); 1020 SRes res = Base.ReadBlock2();
1021 1021
@@ -1036,18 +1036,18 @@ HRESULT CDecoder::ReadBlock()
1036HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress) 1036HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1037{ 1037{
1038 { 1038 {
1039 #ifndef _7ZIP_ST 1039 #ifndef Z7_ST
1040 _block.StopScout = false; 1040 _block.StopScout = false;
1041 #endif 1041 #endif
1042 } 1042 }
1043 1043
1044 RINOK(StartRead()); 1044 RINOK(StartRead())
1045 1045
1046 UInt64 inPrev = 0; 1046 UInt64 inPrev = 0;
1047 UInt64 outPrev = 0; 1047 UInt64 outPrev = 0;
1048 1048
1049 { 1049 {
1050 #ifndef _7ZIP_ST 1050 #ifndef Z7_ST
1051 CWaitScout_Releaser waitScout_Releaser(this); 1051 CWaitScout_Releaser waitScout_Releaser(this);
1052 1052
1053 bool useMt = false; 1053 bool useMt = false;
@@ -1072,7 +1072,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1072 const UInt64 outCur = GetOutProcessedSize(); 1072 const UInt64 outCur = GetOutProcessedSize();
1073 if (packPos - inPrev >= kProgressStep || outCur - outPrev >= kProgressStep) 1073 if (packPos - inPrev >= kProgressStep || outCur - outPrev >= kProgressStep)
1074 { 1074 {
1075 RINOK(progress->SetRatioInfo(&packPos, &outCur)); 1075 RINOK(progress->SetRatioInfo(&packPos, &outCur))
1076 inPrev = packPos; 1076 inPrev = packPos;
1077 outPrev = outCur; 1077 outPrev = outCur;
1078 } 1078 }
@@ -1083,7 +1083,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1083 return nextRes; 1083 return nextRes;
1084 1084
1085 if ( 1085 if (
1086 #ifndef _7ZIP_ST 1086 #ifndef Z7_ST
1087 !useMt && 1087 !useMt &&
1088 #endif 1088 #endif
1089 !wasFinished && Base.state == STATE_BLOCK_SIGNATURE) 1089 !wasFinished && Base.state == STATE_BLOCK_SIGNATURE)
@@ -1125,7 +1125,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1125 1125
1126 wasFinished = false; 1126 wasFinished = false;
1127 1127
1128 #ifndef _7ZIP_ST 1128 #ifndef Z7_ST
1129 if (MtMode) 1129 if (MtMode)
1130 if (props.blockSize != 0) 1130 if (props.blockSize != 0)
1131 { 1131 {
@@ -1136,7 +1136,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1136 if (!Thread.IsCreated()) 1136 if (!Thread.IsCreated())
1137 { 1137 {
1138 PRIN("=== MT_MODE"); 1138 PRIN("=== MT_MODE");
1139 RINOK(CreateThread()); 1139 RINOK(CreateThread())
1140 } 1140 }
1141 useMt = true; 1141 useMt = true;
1142 } 1142 }
@@ -1148,7 +1148,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1148 { 1148 {
1149 crc = nextCrc; 1149 crc = nextCrc;
1150 1150
1151 #ifndef _7ZIP_ST 1151 #ifndef Z7_ST
1152 if (useMt) 1152 if (useMt)
1153 { 1153 {
1154 PRIN("DecoderEvent.Lock()"); 1154 PRIN("DecoderEvent.Lock()");
@@ -1165,7 +1165,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1165 crc = _block.Crc; 1165 crc = _block.Crc;
1166 packPos = _block.PackPos; 1166 packPos = _block.PackPos;
1167 wasFinished = _block.WasFinished; 1167 wasFinished = _block.WasFinished;
1168 RINOK(_block.Res); 1168 RINOK(_block.Res)
1169 } 1169 }
1170 else 1170 else
1171 #endif 1171 #endif
@@ -1175,7 +1175,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1175 1175
1176 TICKS_START 1176 TICKS_START
1177 Base.Props.randMode = 1; 1177 Base.Props.randMode = 1;
1178 RINOK(ReadBlock()); 1178 RINOK(ReadBlock())
1179 TICKS_UPDATE(0) 1179 TICKS_UPDATE(0)
1180 1180
1181 props = Base.Props; 1181 props = Base.Props;
@@ -1190,7 +1190,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1190 TICKS_UPDATE(1) 1190 TICKS_UPDATE(1)
1191 } 1191 }
1192 1192
1193 #ifndef _7ZIP_ST 1193 #ifndef Z7_ST
1194 if (useMt && !wasFinished) 1194 if (useMt && !wasFinished)
1195 { 1195 {
1196 /* 1196 /*
@@ -1216,7 +1216,7 @@ HRESULT CDecoder::DecodeStreams(ICompressProgressInfo *progress)
1216 if (props.blockSize == 0) 1216 if (props.blockSize == 0)
1217 continue; 1217 continue;
1218 1218
1219 RINOK(DecodeBlock(props)); 1219 RINOK(DecodeBlock(props))
1220 1220
1221 if (!_blockFinished) 1221 if (!_blockFinished)
1222 return nextRes; 1222 return nextRes;
@@ -1278,8 +1278,8 @@ void CDecoder::InitOutSize(const UInt64 *outSize)
1278} 1278}
1279 1279
1280 1280
1281STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 1281Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
1282 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 1282 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
1283{ 1283{
1284 /* 1284 /*
1285 { 1285 {
@@ -1344,21 +1344,21 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
1344} 1344}
1345 1345
1346 1346
1347STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 1347Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
1348{ 1348{
1349 FinishMode = (finishMode != 0); 1349 FinishMode = (finishMode != 0);
1350 return S_OK; 1350 return S_OK;
1351} 1351}
1352 1352
1353 1353
1354STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 1354Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
1355{ 1355{
1356 *value = GetInStreamSize(); 1356 *value = GetInStreamSize();
1357 return S_OK; 1357 return S_OK;
1358} 1358}
1359 1359
1360 1360
1361STDMETHODIMP CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize) 1361Z7_COM7F_IMF(CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize))
1362{ 1362{
1363 Base.AlignToByte(); 1363 Base.AlignToByte();
1364 UInt32 i; 1364 UInt32 i;
@@ -1376,7 +1376,7 @@ STDMETHODIMP CDecoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *proc
1376} 1376}
1377 1377
1378 1378
1379#ifndef _7ZIP_ST 1379#ifndef Z7_ST
1380 1380
1381#define PRIN_MT(s) PRIN(" " s) 1381#define PRIN_MT(s) PRIN(" " s)
1382 1382
@@ -1397,9 +1397,9 @@ void CDecoder::RunScout()
1397 for (;;) 1397 for (;;)
1398 { 1398 {
1399 { 1399 {
1400 PRIN_MT("ScoutEvent.Lock()"); 1400 PRIN_MT("ScoutEvent.Lock()")
1401 WRes wres = ScoutEvent.Lock(); 1401 WRes wres = ScoutEvent.Lock();
1402 PRIN_MT("-- ScoutEvent.Lock()"); 1402 PRIN_MT("-- ScoutEvent.Lock()")
1403 if (wres != 0) 1403 if (wres != 0)
1404 { 1404 {
1405 // ScoutRes = wres; 1405 // ScoutRes = wres;
@@ -1461,7 +1461,7 @@ void CDecoder::RunScout()
1461 1461
1462 res = ReadBlock(); 1462 res = ReadBlock();
1463 1463
1464 PRIN_MT("-- Base.ReadBlock"); 1464 PRIN_MT("-- Base.ReadBlock")
1465 if (res != S_OK) 1465 if (res != S_OK)
1466 break; 1466 break;
1467 block.Props = Base.Props; 1467 block.Props = Base.Props;
@@ -1505,13 +1505,13 @@ void CDecoder::RunScout()
1505 1505
1506 if (res != S_OK) 1506 if (res != S_OK)
1507 { 1507 {
1508 PRIN_MT("error"); 1508 PRIN_MT("error")
1509 block.Res = res; 1509 block.Res = res;
1510 block.WasFinished = true; 1510 block.WasFinished = true;
1511 } 1511 }
1512 1512
1513 block.PackPos = GetInputProcessedSize(); 1513 block.PackPos = GetInputProcessedSize();
1514 PRIN_MT("DecoderEvent.Set()"); 1514 PRIN_MT("DecoderEvent.Set()")
1515 WRes wres = DecoderEvent.Set(); 1515 WRes wres = DecoderEvent.Set();
1516 if (wres != 0) 1516 if (wres != 0)
1517 { 1517 {
@@ -1522,7 +1522,7 @@ void CDecoder::RunScout()
1522} 1522}
1523 1523
1524 1524
1525STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) 1525Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads))
1526{ 1526{
1527 MtMode = (numThreads > 1); 1527 MtMode = (numThreads > 1);
1528 1528
@@ -1538,10 +1538,10 @@ STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads)
1538 1538
1539 1539
1540 1540
1541#ifndef NO_READ_FROM_CODER 1541#ifndef Z7_NO_READ_FROM_CODER
1542 1542
1543 1543
1544STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) 1544Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream))
1545{ 1545{
1546 Base.InStreamRef = inStream; 1546 Base.InStreamRef = inStream;
1547 Base.InStream = inStream; 1547 Base.InStream = inStream;
@@ -1549,7 +1549,7 @@ STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream)
1549} 1549}
1550 1550
1551 1551
1552STDMETHODIMP CDecoder::ReleaseInStream() 1552Z7_COM7F_IMF(CDecoder::ReleaseInStream())
1553{ 1553{
1554 Base.InStreamRef.Release(); 1554 Base.InStreamRef.Release();
1555 Base.InStream = NULL; 1555 Base.InStream = NULL;
@@ -1558,7 +1558,7 @@ STDMETHODIMP CDecoder::ReleaseInStream()
1558 1558
1559 1559
1560 1560
1561STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 1561Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize))
1562{ 1562{
1563 InitOutSize(outSize); 1563 InitOutSize(outSize);
1564 1564
@@ -1583,7 +1583,7 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
1583 1583
1584 1584
1585 1585
1586STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 1586Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
1587{ 1587{
1588 *processedSize = 0; 1588 *processedSize = 0;
1589 1589
@@ -1689,7 +1689,7 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
1689 1689
1690// ---------- NSIS ---------- 1690// ---------- NSIS ----------
1691 1691
1692STDMETHODIMP CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 1692Z7_COM7F_IMF(CNsisDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
1693{ 1693{
1694 *processedSize = 0; 1694 *processedSize = 0;
1695 1695
diff --git a/CPP/7zip/Compress/BZip2Decoder.h b/CPP/7zip/Compress/BZip2Decoder.h
index 8fe4ef1..a8ef700 100644
--- a/CPP/7zip/Compress/BZip2Decoder.h
+++ b/CPP/7zip/Compress/BZip2Decoder.h
@@ -1,14 +1,14 @@
1// Compress/BZip2Decoder.h 1// Compress/BZip2Decoder.h
2 2
3#ifndef __COMPRESS_BZIP2_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_BZIP2_DECODER_H
4#define __COMPRESS_BZIP2_DECODER_H 4#define ZIP7_INC_COMPRESS_BZIP2_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
8// #define NO_READ_FROM_CODER 8// #define Z7_NO_READ_FROM_CODER
9// #define _7ZIP_ST 9// #define Z7_ST
10 10
11#ifndef _7ZIP_ST 11#ifndef Z7_ST
12#include "../../Windows/Synchronization.h" 12#include "../../Windows/Synchronization.h"
13#include "../../Windows/Thread.h" 13#include "../../Windows/Thread.h"
14#endif 14#endif
@@ -134,7 +134,7 @@ public:
134 134
135 ISequentialInStream *InStream; 135 ISequentialInStream *InStream;
136 136
137 #ifndef NO_READ_FROM_CODER 137 #ifndef Z7_NO_READ_FROM_CODER
138 CMyComPtr<ISequentialInStream> InStreamRef; 138 CMyComPtr<ISequentialInStream> InStreamRef;
139 #endif 139 #endif
140 140
@@ -194,24 +194,51 @@ public:
194 194
195 195
196 196
197class CDecoder : 197class CDecoder:
198 public ICompressCoder, 198 public ICompressCoder,
199 public ICompressSetFinishMode, 199 public ICompressSetFinishMode,
200 public ICompressGetInStreamProcessedSize, 200 public ICompressGetInStreamProcessedSize,
201 public ICompressReadUnusedFromInBuf, 201 public ICompressReadUnusedFromInBuf,
202 202#ifndef Z7_NO_READ_FROM_CODER
203 #ifndef NO_READ_FROM_CODER
204 public ICompressSetInStream, 203 public ICompressSetInStream,
205 public ICompressSetOutStreamSize, 204 public ICompressSetOutStreamSize,
206 public ISequentialInStream, 205 public ISequentialInStream,
207 #endif 206#endif
208 207#ifndef Z7_ST
209 #ifndef _7ZIP_ST
210 public ICompressSetCoderMt, 208 public ICompressSetCoderMt,
211 #endif 209#endif
212
213 public CMyUnknownImp 210 public CMyUnknownImp
214{ 211{
212 Z7_COM_QI_BEGIN2(ICompressCoder)
213 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
214 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
215 Z7_COM_QI_ENTRY(ICompressReadUnusedFromInBuf)
216#ifndef Z7_NO_READ_FROM_CODER
217 Z7_COM_QI_ENTRY(ICompressSetInStream)
218 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
219 Z7_COM_QI_ENTRY(ISequentialInStream)
220#endif
221#ifndef Z7_ST
222 Z7_COM_QI_ENTRY(ICompressSetCoderMt)
223#endif
224 Z7_COM_QI_END
225 Z7_COM_ADDREF_RELEASE
226
227 Z7_IFACE_COM7_IMP(ICompressCoder)
228 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
229 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
230 Z7_IFACE_COM7_IMP(ICompressReadUnusedFromInBuf)
231#ifndef Z7_NO_READ_FROM_CODER
232 Z7_IFACE_COM7_IMP(ICompressSetInStream)
233 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
234 Z7_IFACE_COM7_IMP_NONFINAL(ISequentialInStream)
235#endif
236public:
237#ifndef Z7_ST
238 Z7_IFACE_COM7_IMP(ICompressSetCoderMt)
239#endif
240
241private:
215 Byte *_outBuf; 242 Byte *_outBuf;
216 size_t _outPos; 243 size_t _outPos;
217 UInt64 _outWritten; 244 UInt64 _outWritten;
@@ -235,7 +262,7 @@ public:
235 CSpecState _spec; 262 CSpecState _spec;
236 UInt32 *_counters; 263 UInt32 *_counters;
237 264
238 #ifndef _7ZIP_ST 265 #ifndef Z7_ST
239 266
240 struct CBlock 267 struct CBlock
241 { 268 {
@@ -339,60 +366,20 @@ public:
339 HRESULT DecodeBlock(const CBlockProps &props); 366 HRESULT DecodeBlock(const CBlockProps &props);
340 HRESULT DecodeStreams(ICompressProgressInfo *progress); 367 HRESULT DecodeStreams(ICompressProgressInfo *progress);
341 368
342 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
343 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
344 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
345 MY_QUERYINTERFACE_ENTRY(ICompressReadUnusedFromInBuf)
346
347 #ifndef NO_READ_FROM_CODER
348 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream)
349 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
350 MY_QUERYINTERFACE_ENTRY(ISequentialInStream)
351 #endif
352
353 #ifndef _7ZIP_ST
354 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt)
355 #endif
356
357 MY_QUERYINTERFACE_END
358 MY_ADDREF_RELEASE
359
360
361 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
362 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
363
364 STDMETHOD(SetFinishMode)(UInt32 finishMode);
365 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
366 STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize);
367
368 UInt64 GetNumStreams() const { return Base.NumStreams; } 369 UInt64 GetNumStreams() const { return Base.NumStreams; }
369 UInt64 GetNumBlocks() const { return Base.NumBlocks; } 370 UInt64 GetNumBlocks() const { return Base.NumBlocks; }
370 371
371 #ifndef NO_READ_FROM_CODER
372
373 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
374 STDMETHOD(ReleaseInStream)();
375 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
376 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
377
378 #endif
379
380 #ifndef _7ZIP_ST
381 STDMETHOD(SetNumberOfThreads)(UInt32 numThreads);
382 #endif
383
384 CDecoder(); 372 CDecoder();
385 ~CDecoder(); 373 virtual ~CDecoder();
386}; 374};
387 375
388 376
389 377
390#ifndef NO_READ_FROM_CODER 378#ifndef Z7_NO_READ_FROM_CODER
391 379
392class CNsisDecoder : public CDecoder 380class CNsisDecoder Z7_final: public CDecoder
393{ 381{
394public: 382 Z7_IFACE_COM7_IMP(ISequentialInStream)
395 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
396}; 383};
397 384
398#endif 385#endif
diff --git a/CPP/7zip/Compress/BZip2Encoder.cpp b/CPP/7zip/Compress/BZip2Encoder.cpp
index 62c15d6..ef2555a 100644
--- a/CPP/7zip/Compress/BZip2Encoder.cpp
+++ b/CPP/7zip/Compress/BZip2Encoder.cpp
@@ -46,7 +46,7 @@ void CThreadInfo::Free()
46 m_Block = NULL; 46 m_Block = NULL;
47} 47}
48 48
49#ifndef _7ZIP_ST 49#ifndef Z7_ST
50 50
51static THREAD_FUNC_DECL MFThread(void *threadCoderInfo) 51static THREAD_FUNC_DECL MFThread(void *threadCoderInfo)
52{ 52{
@@ -146,14 +146,14 @@ CEncoder::CEncoder()
146{ 146{
147 _props.Normalize(-1); 147 _props.Normalize(-1);
148 148
149 #ifndef _7ZIP_ST 149 #ifndef Z7_ST
150 ThreadsInfo = NULL; 150 ThreadsInfo = NULL;
151 m_NumThreadsPrev = 0; 151 m_NumThreadsPrev = 0;
152 NumThreads = 1; 152 NumThreads = 1;
153 #endif 153 #endif
154} 154}
155 155
156#ifndef _7ZIP_ST 156#ifndef Z7_ST
157CEncoder::~CEncoder() 157CEncoder::~CEncoder()
158{ 158{
159 Free(); 159 Free();
@@ -558,8 +558,8 @@ void CThreadInfo::EncodeBlock(const Byte *block, UInt32 blockSize)
558 { 558 {
559 UInt32 groupSize = 0; 559 UInt32 groupSize = 0;
560 UInt32 groupIndex = 0; 560 UInt32 groupIndex = 0;
561 const Byte *lens = 0; 561 const Byte *lens = NULL;
562 const UInt32 *codes = 0; 562 const UInt32 *codes = NULL;
563 UInt32 mtfPos = 0; 563 UInt32 mtfPos = 0;
564 do 564 do
565 { 565 {
@@ -706,7 +706,7 @@ HRESULT CThreadInfo::EncodeBlock3(UInt32 blockSize)
706 706
707 EncodeBlock2(m_Block, blockSize, Encoder->_props.NumPasses); 707 EncodeBlock2(m_Block, blockSize, Encoder->_props.NumPasses);
708 708
709 #ifndef _7ZIP_ST 709 #ifndef Z7_ST
710 if (Encoder->MtMode) 710 if (Encoder->MtMode)
711 Encoder->ThreadsInfo[m_BlockIndex].CanWriteEvent.Lock(); 711 Encoder->ThreadsInfo[m_BlockIndex].CanWriteEvent.Lock();
712 #endif 712 #endif
@@ -714,7 +714,7 @@ HRESULT CThreadInfo::EncodeBlock3(UInt32 blockSize)
714 Encoder->CombinedCrc.Update(m_CRCs[i]); 714 Encoder->CombinedCrc.Update(m_CRCs[i]);
715 Encoder->WriteBytes(m_TempArray, outStreamTemp.GetPos(), outStreamTemp.GetCurByte()); 715 Encoder->WriteBytes(m_TempArray, outStreamTemp.GetPos(), outStreamTemp.GetCurByte());
716 HRESULT res = S_OK; 716 HRESULT res = S_OK;
717 #ifndef _7ZIP_ST 717 #ifndef Z7_ST
718 if (Encoder->MtMode) 718 if (Encoder->MtMode)
719 { 719 {
720 UInt32 blockIndex = m_BlockIndex + 1; 720 UInt32 blockIndex = m_BlockIndex + 1;
@@ -746,13 +746,13 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
746 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 746 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)
747{ 747{
748 NumBlocks = 0; 748 NumBlocks = 0;
749 #ifndef _7ZIP_ST 749 #ifndef Z7_ST
750 Progress = progress; 750 Progress = progress;
751 RINOK(Create()); 751 RINOK(Create())
752 for (UInt32 t = 0; t < NumThreads; t++) 752 for (UInt32 t = 0; t < NumThreads; t++)
753 #endif 753 #endif
754 { 754 {
755 #ifndef _7ZIP_ST 755 #ifndef Z7_ST
756 CThreadInfo &ti = ThreadsInfo[t]; 756 CThreadInfo &ti = ThreadsInfo[t];
757 if (MtMode) 757 if (MtMode)
758 { 758 {
@@ -787,7 +787,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
787 m_OutStream.Init(); 787 m_OutStream.Init();
788 788
789 CombinedCrc.Init(); 789 CombinedCrc.Init();
790 #ifndef _7ZIP_ST 790 #ifndef Z7_ST
791 NextBlockIndex = 0; 791 NextBlockIndex = 0;
792 StreamWasFinished = false; 792 StreamWasFinished = false;
793 CloseThreads = false; 793 CloseThreads = false;
@@ -799,7 +799,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
799 WriteByte(kArSig2); 799 WriteByte(kArSig2);
800 WriteByte((Byte)(kArSig3 + _props.BlockSizeMult)); 800 WriteByte((Byte)(kArSig3 + _props.BlockSizeMult));
801 801
802 #ifndef _7ZIP_ST 802 #ifndef Z7_ST
803 803
804 if (MtMode) 804 if (MtMode)
805 { 805 {
@@ -814,7 +814,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
814 for (t = 0; t < NumThreads; t++) 814 for (t = 0; t < NumThreads; t++)
815 ThreadsInfo[t].WaitingWasStartedEvent.Lock(); 815 ThreadsInfo[t].WaitingWasStartedEvent.Lock();
816 CanStartWaitingEvent.Reset(); 816 CanStartWaitingEvent.Reset();
817 RINOK(Result); 817 RINOK(Result)
818 } 818 }
819 else 819 else
820 #endif 820 #endif
@@ -822,7 +822,7 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
822 for (;;) 822 for (;;)
823 { 823 {
824 CThreadInfo &ti = 824 CThreadInfo &ti =
825 #ifndef _7ZIP_ST 825 #ifndef Z7_ST
826 ThreadsInfo[0]; 826 ThreadsInfo[0];
827 #else 827 #else
828 ThreadsInfo; 828 ThreadsInfo;
@@ -830,12 +830,12 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
830 UInt32 blockSize = ReadRleBlock(ti.m_Block); 830 UInt32 blockSize = ReadRleBlock(ti.m_Block);
831 if (blockSize == 0) 831 if (blockSize == 0)
832 break; 832 break;
833 RINOK(ti.EncodeBlock3(blockSize)); 833 RINOK(ti.EncodeBlock3(blockSize))
834 if (progress) 834 if (progress)
835 { 835 {
836 const UInt64 unpackSize = m_InStream.GetProcessedSize(); 836 const UInt64 unpackSize = m_InStream.GetProcessedSize();
837 const UInt64 packSize = m_OutStream.GetProcessedSize(); 837 const UInt64 packSize = m_OutStream.GetProcessedSize();
838 RINOK(progress->SetRatioInfo(&unpackSize, &packSize)); 838 RINOK(progress->SetRatioInfo(&unpackSize, &packSize))
839 } 839 }
840 } 840 }
841 } 841 }
@@ -847,14 +847,14 @@ HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
847 WriteByte(kFinSig5); 847 WriteByte(kFinSig5);
848 848
849 WriteCrc(CombinedCrc.GetDigest()); 849 WriteCrc(CombinedCrc.GetDigest());
850 RINOK(Flush()); 850 RINOK(Flush())
851 if (!m_InStream.WasFinished()) 851 if (!m_InStream.WasFinished())
852 return E_FAIL; 852 return E_FAIL;
853 return S_OK; 853 return S_OK;
854} 854}
855 855
856STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 856Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
857 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 857 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
858{ 858{
859 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 859 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
860 catch(const CInBufferException &e) { return e.ErrorCode; } 860 catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -862,7 +862,7 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream
862 catch(...) { return S_FALSE; } 862 catch(...) { return S_FALSE; }
863} 863}
864 864
865HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 865Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
866{ 866{
867 int level = -1; 867 int level = -1;
868 CEncProps props; 868 CEncProps props;
@@ -892,7 +892,7 @@ HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *c
892 case NCoderPropID::kLevel: level = (int)v; break; 892 case NCoderPropID::kLevel: level = (int)v; break;
893 case NCoderPropID::kNumThreads: 893 case NCoderPropID::kNumThreads:
894 { 894 {
895 #ifndef _7ZIP_ST 895 #ifndef Z7_ST
896 SetNumberOfThreads(v); 896 SetNumberOfThreads(v);
897 #endif 897 #endif
898 break; 898 break;
@@ -905,8 +905,8 @@ HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *c
905 return S_OK; 905 return S_OK;
906} 906}
907 907
908#ifndef _7ZIP_ST 908#ifndef Z7_ST
909STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads) 909Z7_COM7F_IMF(CEncoder::SetNumberOfThreads(UInt32 numThreads))
910{ 910{
911 const UInt32 kNumThreadsMax = 64; 911 const UInt32 kNumThreadsMax = 64;
912 if (numThreads < 1) numThreads = 1; 912 if (numThreads < 1) numThreads = 1;
diff --git a/CPP/7zip/Compress/BZip2Encoder.h b/CPP/7zip/Compress/BZip2Encoder.h
index e2828a9..4a04fbd 100644
--- a/CPP/7zip/Compress/BZip2Encoder.h
+++ b/CPP/7zip/Compress/BZip2Encoder.h
@@ -1,12 +1,12 @@
1// BZip2Encoder.h 1// BZip2Encoder.h
2 2
3#ifndef __COMPRESS_BZIP2_ENCODER_H 3#ifndef ZIP7_INC_COMPRESS_BZIP2_ENCODER_H
4#define __COMPRESS_BZIP2_ENCODER_H 4#define ZIP7_INC_COMPRESS_BZIP2_ENCODER_H
5 5
6#include "../../Common/Defs.h" 6#include "../../Common/Defs.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
8 8
9#ifndef _7ZIP_ST 9#ifndef Z7_ST
10#include "../../Windows/Synchronization.h" 10#include "../../Windows/Synchronization.h"
11#include "../../Windows/Thread.h" 11#include "../../Windows/Thread.h"
12#endif 12#endif
@@ -107,8 +107,6 @@ private:
107 UInt32 m_CRCs[1 << kNumPassesMax]; 107 UInt32 m_CRCs[1 << kNumPassesMax];
108 UInt32 m_NumCrcs; 108 UInt32 m_NumCrcs;
109 109
110 UInt32 m_BlockIndex;
111
112 void WriteBits2(UInt32 value, unsigned numBits); 110 void WriteBits2(UInt32 value, unsigned numBits);
113 void WriteByte2(Byte b); 111 void WriteByte2(Byte b);
114 void WriteBit2(Byte v); 112 void WriteBit2(Byte v);
@@ -120,7 +118,7 @@ private:
120public: 118public:
121 bool m_OptimizeNumTables; 119 bool m_OptimizeNumTables;
122 CEncoder *Encoder; 120 CEncoder *Encoder;
123 #ifndef _7ZIP_ST 121 #ifndef Z7_ST
124 NWindows::CThread Thread; 122 NWindows::CThread Thread;
125 123
126 NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent; 124 NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent;
@@ -129,13 +127,15 @@ public:
129 // it's not member of this thread. We just need one event per thread 127 // it's not member of this thread. We just need one event per thread
130 NWindows::NSynchronization::CAutoResetEvent CanWriteEvent; 128 NWindows::NSynchronization::CAutoResetEvent CanWriteEvent;
131 129
130private:
131 UInt32 m_BlockIndex;
132 UInt64 m_UnpackSize; 132 UInt64 m_UnpackSize;
133 133public:
134 Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. 134 Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size.
135 HRESULT Create(); 135 HRESULT Create();
136 void FinishStream(bool needLeave); 136 void FinishStream(bool needLeave);
137 THREAD_FUNC_RET_TYPE ThreadFunc(); 137 THREAD_FUNC_RET_TYPE ThreadFunc();
138 #endif 138 #endif
139 139
140 CThreadInfo(): m_Block(NULL), m_BlockSorterIndex(NULL) {} 140 CThreadInfo(): m_Block(NULL), m_BlockSorterIndex(NULL) {}
141 ~CThreadInfo() { Free(); } 141 ~CThreadInfo() { Free(); }
@@ -161,23 +161,41 @@ struct CEncProps
161 bool DoOptimizeNumTables() const { return NumPasses > 1; } 161 bool DoOptimizeNumTables() const { return NumPasses > 1; }
162}; 162};
163 163
164class CEncoder : 164class CEncoder Z7_final:
165 public ICompressCoder, 165 public ICompressCoder,
166 public ICompressSetCoderProperties, 166 public ICompressSetCoderProperties,
167 #ifndef _7ZIP_ST 167 #ifndef Z7_ST
168 public ICompressSetCoderMt, 168 public ICompressSetCoderMt,
169 #endif 169 #endif
170 public CMyUnknownImp 170 public CMyUnknownImp
171{ 171{
172 Z7_COM_QI_BEGIN2(ICompressCoder)
173 Z7_COM_QI_ENTRY(ICompressSetCoderProperties)
174 #ifndef Z7_ST
175 Z7_COM_QI_ENTRY(ICompressSetCoderMt)
176 #endif
177 Z7_COM_QI_END
178 Z7_COM_ADDREF_RELEASE
179
180 Z7_IFACE_COM7_IMP(ICompressCoder)
181 Z7_IFACE_COM7_IMP(ICompressSetCoderProperties)
182 #ifndef Z7_ST
183 Z7_IFACE_COM7_IMP(ICompressSetCoderMt)
184 #endif
185
186 #ifndef Z7_ST
172 UInt32 m_NumThreadsPrev; 187 UInt32 m_NumThreadsPrev;
188 #endif
173public: 189public:
174 CInBuffer m_InStream; 190 CInBuffer m_InStream;
191 #ifndef Z7_ST
175 Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. 192 Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size.
193 #endif
176 CBitmEncoder<COutBuffer> m_OutStream; 194 CBitmEncoder<COutBuffer> m_OutStream;
177 CEncProps _props; 195 CEncProps _props;
178 CBZip2CombinedCrc CombinedCrc; 196 CBZip2CombinedCrc CombinedCrc;
179 197
180 #ifndef _7ZIP_ST 198 #ifndef Z7_ST
181 CThreadInfo *ThreadsInfo; 199 CThreadInfo *ThreadsInfo;
182 NWindows::NSynchronization::CManualResetEvent CanProcessEvent; 200 NWindows::NSynchronization::CManualResetEvent CanProcessEvent;
183 NWindows::NSynchronization::CCriticalSection CS; 201 NWindows::NSynchronization::CCriticalSection CS;
@@ -191,9 +209,9 @@ public:
191 209
192 HRESULT Result; 210 HRESULT Result;
193 ICompressProgressInfo *Progress; 211 ICompressProgressInfo *Progress;
194 #else 212 #else
195 CThreadInfo ThreadsInfo; 213 CThreadInfo ThreadsInfo;
196 #endif 214 #endif
197 215
198 UInt64 NumBlocks; 216 UInt64 NumBlocks;
199 217
@@ -207,37 +225,21 @@ public:
207 // void WriteBit(Byte v); 225 // void WriteBit(Byte v);
208 void WriteCrc(UInt32 v); 226 void WriteCrc(UInt32 v);
209 227
210 #ifndef _7ZIP_ST 228 #ifndef Z7_ST
211 HRESULT Create(); 229 HRESULT Create();
212 void Free(); 230 void Free();
213 #endif 231 #endif
214 232
215public: 233public:
216 CEncoder(); 234 CEncoder();
217 #ifndef _7ZIP_ST 235 #ifndef Z7_ST
218 ~CEncoder(); 236 ~CEncoder();
219 #endif 237 #endif
220 238
221 HRESULT Flush() { return m_OutStream.Flush(); } 239 HRESULT Flush() { return m_OutStream.Flush(); }
222 240
223 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
224 #ifndef _7ZIP_ST
225 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt)
226 #endif
227 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties)
228 MY_QUERYINTERFACE_END
229 MY_ADDREF_RELEASE
230
231 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, 241 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
232 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 242 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
233
234 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
235 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
236 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
237
238 #ifndef _7ZIP_ST
239 STDMETHOD(SetNumberOfThreads)(UInt32 numThreads);
240 #endif
241}; 243};
242 244
243}} 245}}
diff --git a/CPP/7zip/Compress/BZip2Register.cpp b/CPP/7zip/Compress/BZip2Register.cpp
index 6e96036..83b911d 100644
--- a/CPP/7zip/Compress/BZip2Register.cpp
+++ b/CPP/7zip/Compress/BZip2Register.cpp
@@ -5,7 +5,7 @@
5#include "../Common/RegisterCodec.h" 5#include "../Common/RegisterCodec.h"
6 6
7#include "BZip2Decoder.h" 7#include "BZip2Decoder.h"
8#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) 8#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_BZIP2_EXTRACT_ONLY)
9#include "BZip2Encoder.h" 9#include "BZip2Encoder.h"
10#endif 10#endif
11 11
@@ -14,7 +14,7 @@ namespace NBZip2 {
14 14
15REGISTER_CODEC_CREATE(CreateDec, CDecoder) 15REGISTER_CODEC_CREATE(CreateDec, CDecoder)
16 16
17#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) 17#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_BZIP2_EXTRACT_ONLY)
18REGISTER_CODEC_CREATE(CreateEnc, CEncoder) 18REGISTER_CODEC_CREATE(CreateEnc, CEncoder)
19#else 19#else
20#define CreateEnc NULL 20#define CreateEnc NULL
diff --git a/CPP/7zip/Compress/Bcj2Coder.cpp b/CPP/7zip/Compress/Bcj2Coder.cpp
index 561fd08..27e78b0 100644
--- a/CPP/7zip/Compress/Bcj2Coder.cpp
+++ b/CPP/7zip/Compress/Bcj2Coder.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5// #include <stdio.h>
6
5#include "../../../C/Alloc.h" 7#include "../../../C/Alloc.h"
6 8
7#include "../Common/StreamUtils.h" 9#include "../Common/StreamUtils.h"
@@ -13,42 +15,47 @@ namespace NBcj2 {
13 15
14CBaseCoder::CBaseCoder() 16CBaseCoder::CBaseCoder()
15{ 17{
16 for (int i = 0; i < BCJ2_NUM_STREAMS + 1; i++) 18 for (unsigned i = 0; i < BCJ2_NUM_STREAMS + 1; i++)
17 { 19 {
18 _bufs[i] = NULL; 20 _bufs[i] = NULL;
19 _bufsCurSizes[i] = 0; 21 _bufsSizes[i] = 0;
20 _bufsNewSizes[i] = (1 << 18); 22 _bufsSizes_New[i] = (1 << 18);
21 } 23 }
22} 24}
23 25
24CBaseCoder::~CBaseCoder() 26CBaseCoder::~CBaseCoder()
25{ 27{
26 for (int i = 0; i < BCJ2_NUM_STREAMS + 1; i++) 28 for (unsigned i = 0; i < BCJ2_NUM_STREAMS + 1; i++)
27 ::MidFree(_bufs[i]); 29 ::MidFree(_bufs[i]);
28} 30}
29 31
30HRESULT CBaseCoder::Alloc(bool allocForOrig) 32HRESULT CBaseCoder::Alloc(bool allocForOrig)
31{ 33{
32 unsigned num = allocForOrig ? BCJ2_NUM_STREAMS + 1 : BCJ2_NUM_STREAMS; 34 const unsigned num = allocForOrig ? BCJ2_NUM_STREAMS + 1 : BCJ2_NUM_STREAMS;
33 for (unsigned i = 0; i < num; i++) 35 for (unsigned i = 0; i < num; i++)
34 { 36 {
35 UInt32 newSize = _bufsNewSizes[i]; 37 UInt32 size = _bufsSizes_New[i];
36 const UInt32 kMinBufSize = 1; 38 /* buffer sizes for BCJ2_STREAM_CALL and BCJ2_STREAM_JUMP streams
37 if (newSize < kMinBufSize) 39 must be aligned for 4 */
38 newSize = kMinBufSize; 40 size &= ~(UInt32)3;
39 if (!_bufs[i] || newSize != _bufsCurSizes[i]) 41 const UInt32 kMinBufSize = 4;
42 if (size < kMinBufSize)
43 size = kMinBufSize;
44 // size = 4 * 100; // for debug
45 // if (BCJ2_IS_32BIT_STREAM(i) == 1) size = 4 * 1; // for debug
46 if (!_bufs[i] || size != _bufsSizes[i])
40 { 47 {
41 if (_bufs[i]) 48 if (_bufs[i])
42 { 49 {
43 ::MidFree(_bufs[i]); 50 ::MidFree(_bufs[i]);
44 _bufs[i] = 0; 51 _bufs[i] = NULL;
45 } 52 }
46 _bufsCurSizes[i] = 0; 53 _bufsSizes[i] = 0;
47 Byte *buf = (Byte *)::MidAlloc(newSize); 54 Byte *buf = (Byte *)::MidAlloc(size);
48 _bufs[i] = buf;
49 if (!buf) 55 if (!buf)
50 return E_OUTOFMEMORY; 56 return E_OUTOFMEMORY;
51 _bufsCurSizes[i] = newSize; 57 _bufs[i] = buf;
58 _bufsSizes[i] = size;
52 } 59 }
53 } 60 }
54 return S_OK; 61 return S_OK;
@@ -56,23 +63,30 @@ HRESULT CBaseCoder::Alloc(bool allocForOrig)
56 63
57 64
58 65
59#ifndef EXTRACT_ONLY 66#ifndef Z7_EXTRACT_ONLY
60 67
61CEncoder::CEncoder(): _relatLim(BCJ2_RELAT_LIMIT) {} 68CEncoder::CEncoder():
69 _relatLim(BCJ2_ENC_RELAT_LIMIT_DEFAULT)
70 // , _excludeRangeBits(BCJ2_RELAT_EXCLUDE_NUM_BITS)
71 {}
62CEncoder::~CEncoder() {} 72CEncoder::~CEncoder() {}
63 73
64STDMETHODIMP CEncoder::SetInBufSize(UInt32, UInt32 size) { _bufsNewSizes[BCJ2_NUM_STREAMS] = size; return S_OK; } 74Z7_COM7F_IMF(CEncoder::SetInBufSize(UInt32, UInt32 size))
65STDMETHODIMP CEncoder::SetOutBufSize(UInt32 streamIndex, UInt32 size) { _bufsNewSizes[streamIndex] = size; return S_OK; } 75 { _bufsSizes_New[BCJ2_NUM_STREAMS] = size; return S_OK; }
76Z7_COM7F_IMF(CEncoder::SetOutBufSize(UInt32 streamIndex, UInt32 size))
77 { _bufsSizes_New[streamIndex] = size; return S_OK; }
66 78
67STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 79Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
68{ 80{
69 UInt32 relatLim = BCJ2_RELAT_LIMIT; 81 UInt32 relatLim = BCJ2_ENC_RELAT_LIMIT_DEFAULT;
70 82 // UInt32 excludeRangeBits = BCJ2_RELAT_EXCLUDE_NUM_BITS;
71 for (UInt32 i = 0; i < numProps; i++) 83 for (UInt32 i = 0; i < numProps; i++)
72 { 84 {
73 const PROPVARIANT &prop = props[i]; 85 const PROPVARIANT &prop = props[i];
74 PROPID propID = propIDs[i]; 86 const PROPID propID = propIDs[i];
75 if (propID >= NCoderPropID::kReduceSize) 87 if (propID >= NCoderPropID::kReduceSize
88 // && propID != NCoderPropID::kHashBits
89 )
76 continue; 90 continue;
77 switch (propID) 91 switch (propID)
78 { 92 {
@@ -87,225 +101,310 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA
87 relatLim = (UInt32)1 << v; 101 relatLim = (UInt32)1 << v;
88 break; 102 break;
89 } 103 }
104 case NCoderPropID::kHashBits:
105 {
106 if (prop.vt != VT_UI4)
107 return E_INVALIDARG;
108 UInt32 v = prop.ulVal;
109 if (v > 31)
110 return E_INVALIDARG;
111 excludeRangeBits = v;
112 break;
113 }
90 */ 114 */
91 case NCoderPropID::kDictionarySize: 115 case NCoderPropID::kDictionarySize:
92 { 116 {
93 if (prop.vt != VT_UI4) 117 if (prop.vt != VT_UI4)
94 return E_INVALIDARG; 118 return E_INVALIDARG;
95 relatLim = prop.ulVal; 119 relatLim = prop.ulVal;
96 if (relatLim > ((UInt32)1 << 31)) 120 if (relatLim > BCJ2_ENC_RELAT_LIMIT_MAX)
97 return E_INVALIDARG; 121 return E_INVALIDARG;
98 break; 122 break;
99 } 123 }
100
101 case NCoderPropID::kNumThreads: 124 case NCoderPropID::kNumThreads:
102 continue;
103 case NCoderPropID::kLevel: 125 case NCoderPropID::kLevel:
104 continue; 126 continue;
105
106 default: return E_INVALIDARG; 127 default: return E_INVALIDARG;
107 } 128 }
108 } 129 }
109
110 _relatLim = relatLim; 130 _relatLim = relatLim;
111 131 // _excludeRangeBits = excludeRangeBits;
112 return S_OK; 132 return S_OK;
113} 133}
114 134
115 135
116HRESULT CEncoder::CodeReal(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, 136HRESULT CEncoder::CodeReal(
137 ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
117 ISequentialOutStream * const *outStreams, const UInt64 * const * /* outSizes */, UInt32 numOutStreams, 138 ISequentialOutStream * const *outStreams, const UInt64 * const * /* outSizes */, UInt32 numOutStreams,
118 ICompressProgressInfo *progress) 139 ICompressProgressInfo *progress)
119{ 140{
120 if (numInStreams != 1 || numOutStreams != BCJ2_NUM_STREAMS) 141 if (numInStreams != 1 || numOutStreams != BCJ2_NUM_STREAMS)
121 return E_INVALIDARG; 142 return E_INVALIDARG;
122 143
123 RINOK(Alloc()); 144 RINOK(Alloc())
124 145
125 UInt32 fileSize_for_Conv = 0; 146 CBcj2Enc_ip_unsigned fileSize_minus1 = BCJ2_ENC_FileSizeField_UNLIMITED;
126 if (inSizes && inSizes[0]) 147 if (inSizes && inSizes[0])
127 { 148 {
128 UInt64 inSize = *inSizes[0]; 149 const UInt64 inSize = *inSizes[0];
129 if (inSize <= BCJ2_FileSize_MAX) 150 #ifdef BCJ2_ENC_FileSize_MAX
130 fileSize_for_Conv = (UInt32)inSize; 151 if (inSize <= BCJ2_ENC_FileSize_MAX)
152 #endif
153 fileSize_minus1 = BCJ2_ENC_GET_FileSizeField_VAL_FROM_FileSize(inSize);
131 } 154 }
132 155
133 CMyComPtr<ICompressGetSubStreamSize> getSubStreamSize; 156 Z7_DECL_CMyComPtr_QI_FROM(ICompressGetSubStreamSize, getSubStreamSize, inStreams[0])
134 inStreams[0]->QueryInterface(IID_ICompressGetSubStreamSize, (void **)&getSubStreamSize);
135 157
136 CBcj2Enc enc; 158 CBcj2Enc enc;
137
138 enc.src = _bufs[BCJ2_NUM_STREAMS]; 159 enc.src = _bufs[BCJ2_NUM_STREAMS];
139 enc.srcLim = enc.src; 160 enc.srcLim = enc.src;
140
141 { 161 {
142 for (int i = 0; i < BCJ2_NUM_STREAMS; i++) 162 for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++)
143 { 163 {
144 enc.bufs[i] = _bufs[i]; 164 enc.bufs[i] = _bufs[i];
145 enc.lims[i] = _bufs[i] + _bufsCurSizes[i]; 165 enc.lims[i] = _bufs[i] + _bufsSizes[i];
146 } 166 }
147 } 167 }
148
149 size_t numBytes_in_ReadBuf = 0;
150 UInt64 prevProgress = 0;
151 UInt64 totalStreamRead = 0; // size read from InputStream
152 UInt64 currentInPos = 0; // data that was processed, it doesn't include data in input buffer and data in enc.temp
153 UInt64 outSizeRc = 0;
154
155 Bcj2Enc_Init(&enc); 168 Bcj2Enc_Init(&enc);
156 169 enc.fileIp64 = 0;
157 enc.fileIp = 0; 170 enc.fileSize64_minus1 = fileSize_minus1;
158 enc.fileSize = fileSize_for_Conv;
159
160 enc.relatLimit = _relatLim; 171 enc.relatLimit = _relatLim;
161 172 // enc.relatExcludeBits = _excludeRangeBits;
162 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE; 173 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
163 174
164 bool needSubSize = false; 175 // Varibales that correspond processed data in input stream:
165 UInt64 subStreamIndex = 0; 176 UInt64 inPos_without_Temp = 0; // it doesn't include data in enc.temp[]
166 UInt64 subStreamStartPos = 0; 177 UInt64 inPos_with_Temp = 0; // it includes data in enc.temp[]
178
179 UInt64 prevProgress = 0;
180 UInt64 totalRead = 0; // size read from input stream
181 UInt64 outSizeRc = 0;
182 UInt64 subStream_Index = 0;
183 UInt64 subStream_StartPos = 0; // global start offset of subStreams[subStream_Index]
184 UInt64 subStream_Size = 0;
185 const Byte *srcLim_Read = _bufs[BCJ2_NUM_STREAMS];
167 bool readWasFinished = false; 186 bool readWasFinished = false;
187 bool isAccurate = false;
188 bool wasUnknownSize = false;
168 189
169 for (;;) 190 for (;;)
170 { 191 {
171 if (needSubSize && getSubStreamSize) 192 if (readWasFinished && enc.srcLim == srcLim_Read)
172 {
173 enc.fileIp = 0;
174 enc.fileSize = fileSize_for_Conv;
175 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
176
177 for (;;)
178 {
179 UInt64 subStreamSize = 0;
180 HRESULT result = getSubStreamSize->GetSubStreamSize(subStreamIndex, &subStreamSize);
181 needSubSize = false;
182
183 if (result == S_OK)
184 {
185 UInt64 newEndPos = subStreamStartPos + subStreamSize;
186
187 bool isAccurateEnd = (newEndPos < totalStreamRead ||
188 (newEndPos <= totalStreamRead && readWasFinished));
189
190 if (newEndPos <= currentInPos && isAccurateEnd)
191 {
192 subStreamStartPos = newEndPos;
193 subStreamIndex++;
194 continue;
195 }
196
197 enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf;
198
199 if (isAccurateEnd)
200 {
201 // data in enc.temp is possible here
202 size_t rem = (size_t)(totalStreamRead - newEndPos);
203
204 /* Pos_of(enc.src) <= old newEndPos <= newEndPos
205 in another case, it's fail in some code */
206 if ((size_t)(enc.srcLim - enc.src) < rem)
207 return E_FAIL;
208
209 enc.srcLim -= rem;
210 enc.finishMode = BCJ2_ENC_FINISH_MODE_END_BLOCK;
211 }
212
213 if (subStreamSize <= BCJ2_FileSize_MAX)
214 {
215 enc.fileIp = enc.ip + (UInt32)(subStreamStartPos - currentInPos);
216 enc.fileSize = (UInt32)subStreamSize;
217 }
218 break;
219 }
220
221 if (result == S_FALSE)
222 break;
223 if (result == E_NOTIMPL)
224 {
225 getSubStreamSize.Release();
226 break;
227 }
228 return result;
229 }
230 }
231
232 if (readWasFinished && totalStreamRead - currentInPos == Bcj2Enc_Get_InputData_Size(&enc))
233 enc.finishMode = BCJ2_ENC_FINISH_MODE_END_STREAM; 193 enc.finishMode = BCJ2_ENC_FINISH_MODE_END_STREAM;
234 194
195 // for debug:
196 // for (int y=0;y<100;y++) { CBcj2Enc enc2 = enc; Bcj2Enc_Encode(&enc2); }
197
235 Bcj2Enc_Encode(&enc); 198 Bcj2Enc_Encode(&enc);
236 199
237 currentInPos = totalStreamRead - numBytes_in_ReadBuf + (size_t)(enc.src - _bufs[BCJ2_NUM_STREAMS]) - enc.tempPos; 200 inPos_with_Temp = totalRead - (size_t)(srcLim_Read - enc.src);
201 inPos_without_Temp = inPos_with_Temp - Bcj2Enc_Get_AvailInputSize_in_Temp(&enc);
238 202
203 // if (inPos_without_Temp != enc.ip64) return E_FAIL;
204
239 if (Bcj2Enc_IsFinished(&enc)) 205 if (Bcj2Enc_IsFinished(&enc))
240 break; 206 break;
241 207
242 if (enc.state < BCJ2_NUM_STREAMS) 208 if (enc.state < BCJ2_NUM_STREAMS)
243 { 209 {
210 if (enc.bufs[enc.state] != enc.lims[enc.state])
211 return E_FAIL;
244 const size_t curSize = (size_t)(enc.bufs[enc.state] - _bufs[enc.state]); 212 const size_t curSize = (size_t)(enc.bufs[enc.state] - _bufs[enc.state]);
245 // printf("Write stream = %2d %6d\n", enc.state, curSize); 213 // printf("Write stream = %2d %6d\n", enc.state, curSize);
246 RINOK(WriteStream(outStreams[enc.state], _bufs[enc.state], curSize)); 214 RINOK(WriteStream(outStreams[enc.state], _bufs[enc.state], curSize))
247 if (enc.state == BCJ2_STREAM_RC) 215 if (enc.state == BCJ2_STREAM_RC)
248 outSizeRc += curSize; 216 outSizeRc += curSize;
249
250 enc.bufs[enc.state] = _bufs[enc.state]; 217 enc.bufs[enc.state] = _bufs[enc.state];
251 enc.lims[enc.state] = _bufs[enc.state] + _bufsCurSizes[enc.state]; 218 enc.lims[enc.state] = _bufs[enc.state] + _bufsSizes[enc.state];
252 } 219 }
253 else if (enc.state != BCJ2_ENC_STATE_ORIG)
254 return E_FAIL;
255 else 220 else
256 { 221 {
257 needSubSize = true; 222 if (enc.state != BCJ2_ENC_STATE_ORIG)
258 223 return E_FAIL;
259 if (numBytes_in_ReadBuf != (size_t)(enc.src - _bufs[BCJ2_NUM_STREAMS])) 224 // (enc.state == BCJ2_ENC_STATE_ORIG)
225 if (enc.src != enc.srcLim)
226 return E_FAIL;
227 if (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE
228 && Bcj2Enc_Get_AvailInputSize_in_Temp(&enc) != 0)
229 return E_FAIL;
230
231 if (enc.src == srcLim_Read)
260 { 232 {
261 enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; 233 if (readWasFinished)
262 continue; 234 return E_FAIL;
235 UInt32 curSize = _bufsSizes[BCJ2_NUM_STREAMS];
236 RINOK(inStreams[0]->Read(_bufs[BCJ2_NUM_STREAMS], curSize, &curSize))
237 // printf("Read %6u bytes\n", curSize);
238 if (curSize == 0)
239 readWasFinished = true;
240 totalRead += curSize;
241 enc.src = _bufs[BCJ2_NUM_STREAMS];
242 srcLim_Read = _bufs[BCJ2_NUM_STREAMS] + curSize;
263 } 243 }
244 enc.srcLim = srcLim_Read;
264 245
265 if (readWasFinished) 246 if (getSubStreamSize)
266 continue;
267
268 numBytes_in_ReadBuf = 0;
269 enc.src = _bufs[BCJ2_NUM_STREAMS];
270 enc.srcLim = _bufs[BCJ2_NUM_STREAMS];
271
272 UInt32 curSize = _bufsCurSizes[BCJ2_NUM_STREAMS];
273 RINOK(inStreams[0]->Read(_bufs[BCJ2_NUM_STREAMS], curSize, &curSize));
274
275 // printf("Read %6d bytes\n", curSize);
276 if (curSize == 0)
277 { 247 {
278 readWasFinished = true; 248 /* we set base default conversions options that will be used,
279 continue; 249 if subStream related options will be not OK */
280 } 250 enc.fileIp64 = 0;
251 enc.fileSize64_minus1 = fileSize_minus1;
252 for (;;)
253 {
254 UInt64 nextPos;
255 if (isAccurate)
256 nextPos = subStream_StartPos + subStream_Size;
257 else
258 {
259 const HRESULT hres = getSubStreamSize->GetSubStreamSize(subStream_Index, &subStream_Size);
260 if (hres != S_OK)
261 {
262 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
263 /* if sub-stream size is unknown, we use default settings.
264 We still can recover to normal mode for next sub-stream,
265 if GetSubStreamSize() will return S_OK, when current
266 sub-stream will be finished.
267 */
268 if (hres == S_FALSE)
269 {
270 wasUnknownSize = true;
271 break;
272 }
273 if (hres == E_NOTIMPL)
274 {
275 getSubStreamSize.Release();
276 break;
277 }
278 return hres;
279 }
280 // printf("GetSubStreamSize %6u : %6u \n", (unsigned)subStream_Index, (unsigned)subStream_Size);
281 nextPos = subStream_StartPos + subStream_Size;
282 if ((Int64)subStream_Size == -1)
283 {
284 /* it's not expected, but (-1) can mean unknown size. */
285 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
286 wasUnknownSize = true;
287 break;
288 }
289 if (nextPos < subStream_StartPos)
290 return E_FAIL;
291 isAccurate =
292 (nextPos < totalRead
293 || (nextPos <= totalRead && readWasFinished));
294 }
295
296 /* (nextPos) is estimated end position of current sub_stream.
297 But only (totalRead) and (readWasFinished) values
298 can confirm that this estimated end position is accurate.
299 That end position is accurate, if it can't be changed in
300 further calls of GetSubStreamSize() */
301
302 /* (nextPos < inPos_with_Temp) is unexpected case here, that we
303 can get if from some incorrect ICompressGetSubStreamSize object,
304 where new GetSubStreamSize() call returns smaller size than
305 confirmed by Read() size from previous GetSubStreamSize() call.
306 */
307 if (nextPos < inPos_with_Temp)
308 {
309 if (wasUnknownSize)
310 {
311 /* that case can be complicated for recovering.
312 so we disable sub-streams requesting. */
313 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
314 getSubStreamSize.Release();
315 break;
316 }
317 return E_FAIL; // to stop after failure
318 }
319
320 if (nextPos <= inPos_with_Temp)
321 {
322 // (nextPos == inPos_with_Temp)
323 /* CBcj2Enc encoder requires to finish each [non-empty] block (sub-stream)
324 with BCJ2_ENC_FINISH_MODE_END_BLOCK
325 or with BCJ2_ENC_FINISH_MODE_END_STREAM for last block:
326 And we send data of new block to CBcj2Enc, only if previous block was finished.
327 So we switch to next sub-stream if after Bcj2Enc_Encode() call we have
328 && (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE)
329 && (nextPos == inPos_with_Temp)
330 && (enc.state == BCJ2_ENC_STATE_ORIG)
331 */
332 if (enc.finishMode != BCJ2_ENC_FINISH_MODE_CONTINUE)
333 {
334 /* subStream_StartPos is increased only here.
335 (subStream_StartPos == inPos_with_Temp) : at start
336 (subStream_StartPos <= inPos_with_Temp) : will be later
337 */
338 subStream_StartPos = nextPos;
339 subStream_Size = 0;
340 wasUnknownSize = false;
341 subStream_Index++;
342 isAccurate = false;
343 // we don't change finishMode here
344 continue;
345 }
346 }
347
348 enc.finishMode = BCJ2_ENC_FINISH_MODE_CONTINUE;
349 /* for (!isAccurate) case:
350 (totalRead <= real_end_of_subStream)
351 so we can use BCJ2_ENC_FINISH_MODE_CONTINUE up to (totalRead)
352 // we don't change settings at the end of substream, if settings were unknown,
353 */
354
355 /* if (wasUnknownSize) then we can't trust size of that sub-stream.
356 so we use default settings instead */
357 if (!wasUnknownSize)
358 #ifdef BCJ2_ENC_FileSize_MAX
359 if (subStream_Size <= BCJ2_ENC_FileSize_MAX)
360 #endif
361 {
362 enc.fileIp64 =
363 (CBcj2Enc_ip_unsigned)(
364 (CBcj2Enc_ip_signed)enc.ip64 +
365 (CBcj2Enc_ip_signed)(subStream_StartPos - inPos_without_Temp));
366 Bcj2Enc_SET_FileSize(&enc, subStream_Size)
367 }
368
369 if (isAccurate)
370 {
371 /* (real_end_of_subStream == nextPos <= totalRead)
372 So we can use BCJ2_ENC_FINISH_MODE_END_BLOCK up to (nextPos). */
373 const size_t rem = (size_t)(totalRead - nextPos);
374 if ((size_t)(enc.srcLim - enc.src) < rem)
375 return E_FAIL;
376 enc.srcLim -= rem;
377 enc.finishMode = BCJ2_ENC_FINISH_MODE_END_BLOCK;
378 }
281 379
282 numBytes_in_ReadBuf = curSize; 380 break;
283 totalStreamRead += numBytes_in_ReadBuf; 381 } // for() loop
284 enc.srcLim = _bufs[BCJ2_NUM_STREAMS] + numBytes_in_ReadBuf; 382 } // getSubStreamSize
285 } 383 }
286 384
287 if (progress && currentInPos - prevProgress >= (1 << 20)) 385 if (progress && inPos_without_Temp - prevProgress >= (1 << 22))
288 { 386 {
289 const UInt64 outSize2 = currentInPos + outSizeRc + (size_t)(enc.bufs[BCJ2_STREAM_RC] - enc.bufs[BCJ2_STREAM_RC]); 387 prevProgress = inPos_without_Temp;
290 prevProgress = currentInPos; 388 const UInt64 outSize2 = inPos_without_Temp + outSizeRc +
291 // printf("progress %8d, %8d\n", (int)inSize2, (int)outSize2); 389 (size_t)(enc.bufs[BCJ2_STREAM_RC] - _bufs[BCJ2_STREAM_RC]);
292 RINOK(progress->SetRatioInfo(&currentInPos, &outSize2)); 390 // printf("progress %8u, %8u\n", (unsigned)inSize2, (unsigned)outSize2);
391 RINOK(progress->SetRatioInfo(&inPos_without_Temp, &outSize2))
293 } 392 }
294 } 393 }
295 394
296 for (int i = 0; i < BCJ2_NUM_STREAMS; i++) 395 for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++)
297 { 396 {
298 RINOK(WriteStream(outStreams[i], _bufs[i], (size_t)(enc.bufs[i] - _bufs[i]))); 397 RINOK(WriteStream(outStreams[i], _bufs[i], (size_t)(enc.bufs[i] - _bufs[i])))
299 } 398 }
300 399 // if (inPos_without_Temp != subStream_StartPos + subStream_Size) return E_FAIL;
301 // if (currentInPos != subStreamStartPos + subStreamSize) return E_FAIL;
302
303 return S_OK; 400 return S_OK;
304} 401}
305 402
306STDMETHODIMP CEncoder::Code(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, 403
404Z7_COM7F_IMF(CEncoder::Code(
405 ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
307 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, 406 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams,
308 ICompressProgressInfo *progress) 407 ICompressProgressInfo *progress))
309{ 408{
310 try 409 try
311 { 410 {
@@ -321,141 +420,170 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream * const *inStreams, const UInt64
321 420
322 421
323 422
324STDMETHODIMP CDecoder::SetInBufSize(UInt32 streamIndex, UInt32 size) { _bufsNewSizes[streamIndex] = size; return S_OK; } 423CDecoder::CDecoder():
325STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _bufsNewSizes[BCJ2_NUM_STREAMS] = size; return S_OK; } 424 _finishMode(false)
326 425#ifndef Z7_NO_READ_FROM_CODER
327CDecoder::CDecoder(): _finishMode(false), _outSizeDefined(false), _outSize(0) 426 , _outSizeDefined(false)
427 , _outSize(0)
428 , _outSize_Processed(0)
429#endif
328{} 430{}
329 431
330STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 432Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 streamIndex, UInt32 size))
433 { _bufsSizes_New[streamIndex] = size; return S_OK; }
434Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32, UInt32 size))
435 { _bufsSizes_New[BCJ2_NUM_STREAMS] = size; return S_OK; }
436
437Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
331{ 438{
332 _finishMode = (finishMode != 0); 439 _finishMode = (finishMode != 0);
333 return S_OK; 440 return S_OK;
334} 441}
335 442
336void CDecoder::InitCommon() 443void CBaseDecoder::InitCommon()
337{ 444{
445 for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++)
338 { 446 {
339 for (int i = 0; i < BCJ2_NUM_STREAMS; i++) 447 dec.lims[i] = dec.bufs[i] = _bufs[i];
340 dec.lims[i] = dec.bufs[i] = _bufs[i]; 448 _readRes[i] = S_OK;
449 _extraSizes[i] = 0;
450 _readSizes[i] = 0;
341 } 451 }
452 Bcj2Dec_Init(&dec);
453}
342 454
455
456/* call ReadInStream() only after Bcj2Dec_Decode().
457 input requirement:
458 (dec.state < BCJ2_NUM_STREAMS)
459*/
460void CBaseDecoder::ReadInStream(ISequentialInStream *inStream)
461{
462 const unsigned state = dec.state;
463 UInt32 total;
343 { 464 {
344 for (int i = 0; i < BCJ2_NUM_STREAMS; i++) 465 Byte *buf = _bufs[state];
466 const Byte *cur = dec.bufs[state];
467 // if (cur != dec.lims[state]) throw 1; // unexpected case
468 dec.lims[state] =
469 dec.bufs[state] = buf;
470 total = (UInt32)_extraSizes[state];
471 for (UInt32 i = 0; i < total; i++)
472 buf[i] = cur[i];
473 }
474
475 if (_readRes[state] != S_OK)
476 return;
477
478 do
479 {
480 UInt32 curSize = _bufsSizes[state] - total;
481 // if (state == 0) curSize = 0; // for debug
482 // curSize = 7; // for debug
483 /* even if we have reached provided inSizes[state] limit,
484 we call Read() with (curSize != 0), because
485 we want the called handler of stream->Read() could
486 execute required Init/Flushing code even for empty stream.
487 In another way we could call Read() with (curSize == 0) for
488 finished streams, but some Read() handlers can ignore Read(size=0) calls.
489 */
490 const HRESULT hres = inStream->Read(_bufs[state] + total, curSize, &curSize);
491 _readRes[state] = hres;
492 if (curSize == 0)
493 break;
494 _readSizes[state] += curSize;
495 total += curSize;
496 if (hres != S_OK)
497 break;
498 }
499 while (total < 4 && BCJ2_IS_32BIT_STREAM(state));
500
501 /* we exit from decoding loop here, if we can't
502 provide new data for input stream.
503 Usually it's normal exit after full stream decoding. */
504 if (total == 0)
505 return;
506
507 if (BCJ2_IS_32BIT_STREAM(state))
508 {
509 const unsigned extra = ((unsigned)total & 3);
510 _extraSizes[state] = extra;
511 if (total < 4)
345 { 512 {
346 _extraReadSizes[i] = 0; 513 if (_readRes[state] == S_OK)
347 _inStreamsProcessed[i] = 0; 514 _readRes[state] = S_FALSE; // actually it's stream error. So maybe we need another error code.
348 _readRes[i] = S_OK; 515 return;
349 } 516 }
517 total -= extra;
350 } 518 }
351 519
352 Bcj2Dec_Init(&dec); 520 dec.lims[state] += total; // = _bufs[state] + total;
353} 521}
354 522
355HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, 523
524Z7_COM7F_IMF(CDecoder::Code(
525 ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
356 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, 526 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams,
357 ICompressProgressInfo *progress) 527 ICompressProgressInfo *progress))
358{ 528{
359 if (numInStreams != BCJ2_NUM_STREAMS || numOutStreams != 1) 529 if (numInStreams != BCJ2_NUM_STREAMS || numOutStreams != 1)
360 return E_INVALIDARG; 530 return E_INVALIDARG;
361 531
362 RINOK(Alloc()); 532 RINOK(Alloc())
363
364 InitCommon(); 533 InitCommon();
365 534
366 dec.destLim = dec.dest = _bufs[BCJ2_NUM_STREAMS]; 535 dec.destLim = dec.dest = _bufs[BCJ2_NUM_STREAMS];
367 536
368 UInt64 outSizeProcessed = 0; 537 UInt64 outSizeWritten = 0;
369 UInt64 prevProgress = 0; 538 UInt64 prevProgress = 0;
370 539
371 HRESULT res = S_OK; 540 HRESULT hres_Crit = S_OK; // critical hres status (mostly from input stream reading)
541 HRESULT hres_Weak = S_OK; // first non-critical error code from input stream reading
372 542
373 for (;;) 543 for (;;)
374 { 544 {
375 if (Bcj2Dec_Decode(&dec) != SZ_OK) 545 if (Bcj2Dec_Decode(&dec) != SZ_OK)
376 return S_FALSE; 546 {
377 547 /* it's possible only at start (first 5 bytes in RC stream) */
548 hres_Crit = S_FALSE;
549 break;
550 }
378 if (dec.state < BCJ2_NUM_STREAMS) 551 if (dec.state < BCJ2_NUM_STREAMS)
379 { 552 {
380 size_t totalRead = _extraReadSizes[dec.state]; 553 ReadInStream(inStreams[dec.state]);
554 const unsigned state = dec.state;
555 const HRESULT hres = _readRes[state];
556 if (dec.lims[state] == _bufs[state])
381 { 557 {
382 Byte *buf = _bufs[dec.state]; 558 // we break decoding, if there are no new data in input stream
383 for (size_t i = 0; i < totalRead; i++) 559 hres_Crit = hres;
384 buf[i] = dec.bufs[dec.state][i];
385 dec.lims[dec.state] =
386 dec.bufs[dec.state] = buf;
387 }
388
389 if (_readRes[dec.state] != S_OK)
390 {
391 res = _readRes[dec.state];
392 break; 560 break;
393 } 561 }
394 562 if (hres != S_OK && hres_Weak == S_OK)
395 do 563 hres_Weak = hres;
396 {
397 UInt32 curSize = _bufsCurSizes[dec.state] - (UInt32)totalRead;
398 /*
399 we want to call Read even even if size is 0
400 if (inSizes && inSizes[dec.state])
401 {
402 UInt64 rem = *inSizes[dec.state] - _inStreamsProcessed[dec.state];
403 if (curSize > rem)
404 curSize = (UInt32)rem;
405 }
406 */
407
408 HRESULT res2 = inStreams[dec.state]->Read(_bufs[dec.state] + totalRead, curSize, &curSize);
409 _readRes[dec.state] = res2;
410 if (curSize == 0)
411 break;
412 _inStreamsProcessed[dec.state] += curSize;
413 totalRead += curSize;
414 if (res2 != S_OK)
415 break;
416 }
417 while (totalRead < 4 && BCJ2_IS_32BIT_STREAM(dec.state));
418
419 if (_readRes[dec.state] != S_OK)
420 res = _readRes[dec.state];
421
422 if (totalRead == 0)
423 break;
424
425 // res == S_OK;
426
427 if (BCJ2_IS_32BIT_STREAM(dec.state))
428 {
429 unsigned extraSize = ((unsigned)totalRead & 3);
430 _extraReadSizes[dec.state] = extraSize;
431 if (totalRead < 4)
432 {
433 res = (_readRes[dec.state] != S_OK) ? _readRes[dec.state] : S_FALSE;
434 break;
435 }
436 totalRead -= extraSize;
437 }
438
439 dec.lims[dec.state] = _bufs[dec.state] + totalRead;
440 } 564 }
441 else // if (dec.state <= BCJ2_STATE_ORIG) 565 else // (BCJ2_DEC_STATE_ORIG_0 <= state <= BCJ2_STATE_ORIG)
442 { 566 {
443 const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]);
444 if (curSize != 0)
445 { 567 {
446 outSizeProcessed += curSize; 568 const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]);
447 RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)); 569 if (curSize != 0)
570 {
571 outSizeWritten += curSize;
572 RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize))
573 }
448 } 574 }
449 dec.dest = _bufs[BCJ2_NUM_STREAMS];
450 { 575 {
451 size_t rem = _bufsCurSizes[BCJ2_NUM_STREAMS]; 576 UInt32 rem = _bufsSizes[BCJ2_NUM_STREAMS];
452 if (outSizes && outSizes[0]) 577 if (outSizes && outSizes[0])
453 { 578 {
454 UInt64 outSize = *outSizes[0] - outSizeProcessed; 579 const UInt64 outSize = *outSizes[0] - outSizeWritten;
455 if (rem > outSize) 580 if (rem > outSize)
456 rem = (size_t)outSize; 581 rem = (UInt32)outSize;
457 } 582 }
583 dec.dest = _bufs[BCJ2_NUM_STREAMS];
458 dec.destLim = dec.dest + rem; 584 dec.destLim = dec.dest + rem;
585 /* we exit from decoding loop here,
586 if (outSizes[0]) limit for output stream was reached */
459 if (rem == 0) 587 if (rem == 0)
460 break; 588 break;
461 } 589 }
@@ -463,47 +591,67 @@ HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * co
463 591
464 if (progress) 592 if (progress)
465 { 593 {
466 const UInt64 outSize2 = outSizeProcessed + (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]); 594 // here we don't count additional data in dec.temp (up to 4 bytes for output stream)
467 if (outSize2 - prevProgress >= (1 << 22)) 595 const UInt64 processed = outSizeWritten + (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]);
596 if (processed - prevProgress >= (1 << 24))
468 { 597 {
469 const UInt64 inSize2 = outSize2 + _inStreamsProcessed[BCJ2_STREAM_RC] - (size_t)(dec.lims[BCJ2_STREAM_RC] - dec.bufs[BCJ2_STREAM_RC]); 598 prevProgress = processed;
470 RINOK(progress->SetRatioInfo(&inSize2, &outSize2)); 599 const UInt64 inSize = processed +
471 prevProgress = outSize2; 600 _readSizes[BCJ2_STREAM_RC] - (size_t)(
601 dec.lims[BCJ2_STREAM_RC] -
602 dec.bufs[BCJ2_STREAM_RC]);
603 RINOK(progress->SetRatioInfo(&inSize, &prevProgress))
472 } 604 }
473 } 605 }
474 } 606 }
475 607
476 const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]);
477 if (curSize != 0)
478 { 608 {
479 outSizeProcessed += curSize; 609 const size_t curSize = (size_t)(dec.dest - _bufs[BCJ2_NUM_STREAMS]);
480 RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize)); 610 if (curSize != 0)
611 {
612 outSizeWritten += curSize;
613 RINOK(WriteStream(outStreams[0], _bufs[BCJ2_NUM_STREAMS], curSize))
614 }
481 } 615 }
482 616
483 if (res != S_OK) 617 if (hres_Crit == S_OK) hres_Crit = hres_Weak;
484 return res; 618 if (hres_Crit != S_OK) return hres_Crit;
485 619
486 if (_finishMode) 620 if (_finishMode)
487 { 621 {
488 if (!Bcj2Dec_IsFinished(&dec)) 622 if (!Bcj2Dec_IsMaybeFinished_code(&dec))
489 return S_FALSE; 623 return S_FALSE;
490 624
491 // we still allow the cases when input streams are larger than required for decoding. 625 /* here we support two correct ways to finish full stream decoding
492 // so the case (dec.state == BCJ2_STATE_ORIG) is also allowed, if MAIN stream is larger than required. 626 with one of the following conditions:
493 if (dec.state != BCJ2_STREAM_MAIN && 627 - the end of input stream MAIN was reached
494 dec.state != BCJ2_DEC_STATE_ORIG) 628 - the end of output stream ORIG was reached
629 Currently 7-Zip/7z code ends with (state == BCJ2_STREAM_MAIN),
630 because the sizes of MAIN and ORIG streams are known and these
631 sizes are stored in 7z archive headers.
632 And Bcj2Dec_Decode() exits with (state == BCJ2_STREAM_MAIN),
633 if both MAIN and ORIG streams have reached buffers limits.
634 But if the size of MAIN stream is not known or if the
635 size of MAIN stream includes some padding after payload data,
636 then we still can correctly finish decoding with
637 (state == BCJ2_DEC_STATE_ORIG), if we know the exact size
638 of output ORIG stream.
639 */
640 if (dec.state != BCJ2_STREAM_MAIN)
641 if (dec.state != BCJ2_DEC_STATE_ORIG)
642 return S_FALSE;
643
644 /* the caller also will know written size.
645 So the following check is optional: */
646 if (outSizes && outSizes[0] && *outSizes[0] != outSizeWritten)
495 return S_FALSE; 647 return S_FALSE;
496 648
497 if (inSizes) 649 if (inSizes)
498 { 650 {
499 for (int i = 0; i < BCJ2_NUM_STREAMS; i++) 651 for (unsigned i = 0; i < BCJ2_NUM_STREAMS; i++)
500 { 652 {
501 const size_t rem = (size_t)(dec.lims[i] - dec.bufs[i]) + _extraReadSizes[i]; 653 /* if (inSizes[i]) is defined, we do full check for processed stream size. */
502 /* 654 if (inSizes[i] && *inSizes[i] != GetProcessedSize_ForInStream(i))
503 if (rem != 0)
504 return S_FALSE;
505 */
506 if (inSizes[i] && *inSizes[i] != _inStreamsProcessed[i] - rem)
507 return S_FALSE; 655 return S_FALSE;
508 } 656 }
509 } 657 }
@@ -512,49 +660,65 @@ HRESULT CDecoder::Code(ISequentialInStream * const *inStreams, const UInt64 * co
512 return S_OK; 660 return S_OK;
513} 661}
514 662
515STDMETHODIMP CDecoder::SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream) 663
664Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value))
665{
666 *value = GetProcessedSize_ForInStream(streamIndex);
667 return S_OK;
668}
669
670
671#ifndef Z7_NO_READ_FROM_CODER
672
673Z7_COM7F_IMF(CDecoder::SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream))
516{ 674{
517 _inStreams[streamIndex] = inStream; 675 _inStreams[streamIndex] = inStream;
518 return S_OK; 676 return S_OK;
519} 677}
520 678
521STDMETHODIMP CDecoder::ReleaseInStream2(UInt32 streamIndex) 679Z7_COM7F_IMF(CDecoder::ReleaseInStream2(UInt32 streamIndex))
522{ 680{
523 _inStreams[streamIndex].Release(); 681 _inStreams[streamIndex].Release();
524 return S_OK; 682 return S_OK;
525} 683}
526 684
527STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 685Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize))
528{ 686{
529 _outSizeDefined = (outSize != NULL); 687 _outSizeDefined = (outSize != NULL);
530 _outSize = 0; 688 _outSize = 0;
531 if (_outSizeDefined) 689 if (_outSizeDefined)
532 _outSize = *outSize; 690 _outSize = *outSize;
533
534 _outSize_Processed = 0; 691 _outSize_Processed = 0;
535 692
536 HRESULT res = Alloc(false); 693 const HRESULT res = Alloc(false); // allocForOrig
537
538 InitCommon(); 694 InitCommon();
539 dec.destLim = dec.dest = NULL; 695 dec.destLim = dec.dest = NULL;
540
541 return res; 696 return res;
542} 697}
543 698
544 699
545STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 700Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
546{ 701{
547 if (processedSize) 702 if (processedSize)
548 *processedSize = 0; 703 *processedSize = 0;
549 704
550 if (size == 0) 705 /* Note the case:
551 return S_OK; 706 The output (ORIG) stream can be empty.
707 But BCJ2_STREAM_RC stream always is not empty.
708 And we want to support full data processing for all streams.
709 We disable check (size == 0) here.
710 So if the caller calls this CDecoder::Read() with (size == 0),
711 we execute required Init/Flushing code in this CDecoder object.
712 Also this CDecoder::Read() function will call Read() for input streams.
713 So the handlers of input streams objects also can do Init/Flushing.
714 */
715 // if (size == 0) return S_OK; // disabled to allow (size == 0) processing
552 716
553 UInt32 totalProcessed = 0; 717 UInt32 totalProcessed = 0;
554 718
555 if (_outSizeDefined) 719 if (_outSizeDefined)
556 { 720 {
557 UInt64 rem = _outSize - _outSize_Processed; 721 const UInt64 rem = _outSize - _outSize_Processed;
558 if (size > rem) 722 if (size > rem)
559 size = (UInt32)rem; 723 size = (UInt32)rem;
560 } 724 }
@@ -565,102 +729,125 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
565 729
566 for (;;) 730 for (;;)
567 { 731 {
568 SRes sres = Bcj2Dec_Decode(&dec); 732 if (Bcj2Dec_Decode(&dec) != SZ_OK)
569 if (sres != SZ_OK) 733 return S_FALSE; // this error can be only at start of stream
570 return S_FALSE;
571
572 { 734 {
573 UInt32 curSize = (UInt32)(dec.dest - (Byte *)data); 735 const UInt32 curSize = (UInt32)(size_t)(dec.dest - (Byte *)data);
574 if (curSize != 0) 736 if (curSize != 0)
575 { 737 {
576 totalProcessed += curSize;
577 if (processedSize)
578 *processedSize = totalProcessed;
579 data = (void *)((Byte *)data + curSize); 738 data = (void *)((Byte *)data + curSize);
580 size -= curSize; 739 size -= curSize;
581 _outSize_Processed += curSize; 740 _outSize_Processed += curSize;
741 totalProcessed += curSize;
742 if (processedSize)
743 *processedSize = totalProcessed;
582 } 744 }
583 } 745 }
584
585 if (dec.state >= BCJ2_NUM_STREAMS) 746 if (dec.state >= BCJ2_NUM_STREAMS)
586 break; 747 break;
587 748 ReadInStream(_inStreams[dec.state]);
749 if (dec.lims[dec.state] == _bufs[dec.state])
588 { 750 {
589 size_t totalRead = _extraReadSizes[dec.state]; 751 /* we break decoding, if there are no new data in input stream.
590 { 752 and we ignore error code, if some data were written to output buffer. */
591 Byte *buf = _bufs[dec.state]; 753 if (totalProcessed == 0)
592 for (size_t i = 0; i < totalRead; i++) 754 res = _readRes[dec.state];
593 buf[i] = dec.bufs[dec.state][i]; 755 break;
594 dec.lims[dec.state] =
595 dec.bufs[dec.state] = buf;
596 }
597
598 if (_readRes[dec.state] != S_OK)
599 return _readRes[dec.state];
600
601 do
602 {
603 UInt32 curSize = _bufsCurSizes[dec.state] - (UInt32)totalRead;
604 HRESULT res2 = _inStreams[dec.state]->Read(_bufs[dec.state] + totalRead, curSize, &curSize);
605 _readRes[dec.state] = res2;
606 if (curSize == 0)
607 break;
608 _inStreamsProcessed[dec.state] += curSize;
609 totalRead += curSize;
610 if (res2 != S_OK)
611 break;
612 }
613 while (totalRead < 4 && BCJ2_IS_32BIT_STREAM(dec.state));
614
615 if (totalRead == 0)
616 {
617 if (totalProcessed == 0)
618 res = _readRes[dec.state];
619 break;
620 }
621
622 if (BCJ2_IS_32BIT_STREAM(dec.state))
623 {
624 unsigned extraSize = ((unsigned)totalRead & 3);
625 _extraReadSizes[dec.state] = extraSize;
626 if (totalRead < 4)
627 {
628 if (totalProcessed != 0)
629 return S_OK;
630 return (_readRes[dec.state] != S_OK) ? _readRes[dec.state] : S_FALSE;
631 }
632 totalRead -= extraSize;
633 }
634
635 dec.lims[dec.state] = _bufs[dec.state] + totalRead;
636 } 756 }
637 } 757 }
638 758
759 if (res == S_OK)
639 if (_finishMode && _outSizeDefined && _outSize == _outSize_Processed) 760 if (_finishMode && _outSizeDefined && _outSize == _outSize_Processed)
640 { 761 {
641 if (!Bcj2Dec_IsFinished(&dec)) 762 if (!Bcj2Dec_IsMaybeFinished_code(&dec))
642 return S_FALSE; 763 return S_FALSE;
643 764 if (dec.state != BCJ2_STREAM_MAIN)
644 if (dec.state != BCJ2_STREAM_MAIN && 765 if (dec.state != BCJ2_DEC_STATE_ORIG)
645 dec.state != BCJ2_DEC_STATE_ORIG)
646 return S_FALSE; 766 return S_FALSE;
647
648 /*
649 for (int i = 0; i < BCJ2_NUM_STREAMS; i++)
650 if (dec.bufs[i] != dec.lims[i] || _extraReadSizes[i] != 0)
651 return S_FALSE;
652 */
653 } 767 }
654 768
655 return res; 769 return res;
656} 770}
657 771
772#endif
658 773
659STDMETHODIMP CDecoder::GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value) 774}}
775
776
777/*
778extern "C"
660{ 779{
661 const size_t rem = (size_t)(dec.lims[streamIndex] - dec.bufs[streamIndex]) + _extraReadSizes[streamIndex]; 780extern UInt32 bcj2_stats[256 + 2][2];
662 *value = _inStreamsProcessed[streamIndex] - rem;
663 return S_OK;
664} 781}
665 782
666}} 783static class CBcj2Stat
784{
785public:
786 ~CBcj2Stat()
787 {
788 printf("\nBCJ2 stat:");
789 unsigned sums[2] = { 0, 0 };
790 int i;
791 for (i = 2; i < 256 + 2; i++)
792 {
793 sums[0] += bcj2_stats[i][0];
794 sums[1] += bcj2_stats[i][1];
795 }
796 const unsigned sums2 = sums[0] + sums[1];
797 for (int vi = 0; vi < 256 + 3; vi++)
798 {
799 printf("\n");
800 UInt32 n0, n1;
801 if (vi < 4)
802 printf("\n");
803
804 if (vi < 2)
805 i = vi;
806 else if (vi == 2)
807 i = -1;
808 else
809 i = vi - 1;
810
811 if (i < 0)
812 {
813 n0 = sums[0];
814 n1 = sums[1];
815 printf("calls :");
816 }
817 else
818 {
819 if (i == 0)
820 printf("jcc :");
821 else if (i == 1)
822 printf("jump :");
823 else
824 printf("call %02x :", i - 2);
825 n0 = bcj2_stats[i][0];
826 n1 = bcj2_stats[i][1];
827 }
828
829 const UInt32 sum = n0 + n1;
830 printf(" %10u", sum);
831
832 #define PRINT_PERC(val, sum) \
833 { UInt32 _sum = sum; if (_sum == 0) _sum = 1; \
834 printf(" %7.3f %%", (double)((double)val * (double)100 / (double)_sum )); }
835
836 if (i >= 2 || i < 0)
837 {
838 PRINT_PERC(sum, sums2);
839 }
840 else
841 printf("%10s", "");
842
843 printf(" :%10u", n0);
844 PRINT_PERC(n0, sum);
845
846 printf(" :%10u", n1);
847 PRINT_PERC(n1, sum);
848 }
849 printf("\n\n");
850 fflush(stdout);
851 }
852} g_CBcjStat;
853*/
diff --git a/CPP/7zip/Compress/Bcj2Coder.h b/CPP/7zip/Compress/Bcj2Coder.h
index ca6a1e4..2ab91bc 100644
--- a/CPP/7zip/Compress/Bcj2Coder.h
+++ b/CPP/7zip/Compress/Bcj2Coder.h
@@ -1,7 +1,7 @@
1// Bcj2Coder.h 1// Bcj2Coder.h
2 2
3#ifndef __COMPRESS_BCJ2_CODER_H 3#ifndef ZIP7_INC_COMPRESS_BCJ2_CODER_H
4#define __COMPRESS_BCJ2_CODER_H 4#define ZIP7_INC_COMPRESS_BCJ2_CODER_H
5 5
6#include "../../../C/Bcj2.h" 6#include "../../../C/Bcj2.h"
7 7
@@ -16,8 +16,8 @@ class CBaseCoder
16{ 16{
17protected: 17protected:
18 Byte *_bufs[BCJ2_NUM_STREAMS + 1]; 18 Byte *_bufs[BCJ2_NUM_STREAMS + 1];
19 UInt32 _bufsCurSizes[BCJ2_NUM_STREAMS + 1]; 19 UInt32 _bufsSizes[BCJ2_NUM_STREAMS + 1];
20 UInt32 _bufsNewSizes[BCJ2_NUM_STREAMS + 1]; 20 UInt32 _bufsSizes_New[BCJ2_NUM_STREAMS + 1];
21 21
22 HRESULT Alloc(bool allocForOrig = true); 22 HRESULT Alloc(bool allocForOrig = true);
23public: 23public:
@@ -26,92 +26,99 @@ public:
26}; 26};
27 27
28 28
29#ifndef EXTRACT_ONLY 29#ifndef Z7_EXTRACT_ONLY
30 30
31class CEncoder: 31class CEncoder Z7_final:
32 public ICompressCoder2, 32 public ICompressCoder2,
33 public ICompressSetCoderProperties, 33 public ICompressSetCoderProperties,
34 public ICompressSetBufSize, 34 public ICompressSetBufSize,
35 public CMyUnknownImp, 35 public CMyUnknownImp,
36 public CBaseCoder 36 public CBaseCoder
37{ 37{
38 Z7_IFACES_IMP_UNK_3(
39 ICompressCoder2,
40 ICompressSetCoderProperties,
41 ICompressSetBufSize)
42
38 UInt32 _relatLim; 43 UInt32 _relatLim;
44 // UInt32 _excludeRangeBits;
39 45
40 HRESULT CodeReal(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, 46 HRESULT CodeReal(
47 ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
41 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, 48 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams,
42 ICompressProgressInfo *progress); 49 ICompressProgressInfo *progress);
43
44public: 50public:
45 MY_UNKNOWN_IMP3(ICompressCoder2, ICompressSetCoderProperties, ICompressSetBufSize)
46
47 STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
48 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams,
49 ICompressProgressInfo *progress);
50
51 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
52
53 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size);
54 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size);
55
56 CEncoder(); 51 CEncoder();
57 ~CEncoder(); 52 ~CEncoder();
58}; 53};
59 54
60#endif 55#endif
61 56
62class CDecoder: 57
58
59class CBaseDecoder: public CBaseCoder
60{
61protected:
62 HRESULT _readRes[BCJ2_NUM_STREAMS];
63 unsigned _extraSizes[BCJ2_NUM_STREAMS];
64 UInt64 _readSizes[BCJ2_NUM_STREAMS];
65
66 CBcj2Dec dec;
67
68 UInt64 GetProcessedSize_ForInStream(unsigned i) const
69 {
70 return _readSizes[i] - ((size_t)(dec.lims[i] - dec.bufs[i]) + _extraSizes[i]);
71 }
72 void InitCommon();
73 void ReadInStream(ISequentialInStream *inStream);
74};
75
76
77class CDecoder Z7_final:
63 public ICompressCoder2, 78 public ICompressCoder2,
64 public ICompressSetFinishMode, 79 public ICompressSetFinishMode,
65 public ICompressGetInStreamProcessedSize2, 80 public ICompressGetInStreamProcessedSize2,
81 public ICompressSetBufSize,
82#ifndef Z7_NO_READ_FROM_CODER
66 public ICompressSetInStream2, 83 public ICompressSetInStream2,
67 public ISequentialInStream,
68 public ICompressSetOutStreamSize, 84 public ICompressSetOutStreamSize,
69 public ICompressSetBufSize, 85 public ISequentialInStream,
86#endif
70 public CMyUnknownImp, 87 public CMyUnknownImp,
71 public CBaseCoder 88 public CBaseDecoder
72{ 89{
73 unsigned _extraReadSizes[BCJ2_NUM_STREAMS]; 90 Z7_COM_QI_BEGIN2(ICompressCoder2)
74 UInt64 _inStreamsProcessed[BCJ2_NUM_STREAMS]; 91 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
75 HRESULT _readRes[BCJ2_NUM_STREAMS]; 92 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize2)
76 CMyComPtr<ISequentialInStream> _inStreams[BCJ2_NUM_STREAMS]; 93 Z7_COM_QI_ENTRY(ICompressSetBufSize)
94 #ifndef Z7_NO_READ_FROM_CODER
95 Z7_COM_QI_ENTRY(ICompressSetInStream2)
96 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
97 Z7_COM_QI_ENTRY(ISequentialInStream)
98 #endif
99 Z7_COM_QI_END
100 Z7_COM_ADDREF_RELEASE
101
102 Z7_IFACE_COM7_IMP(ICompressCoder2)
103 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
104 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize2)
105 Z7_IFACE_COM7_IMP(ICompressSetBufSize)
106#ifndef Z7_NO_READ_FROM_CODER
107 Z7_IFACE_COM7_IMP(ICompressSetInStream2)
108 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
109 Z7_IFACE_COM7_IMP(ISequentialInStream)
110#endif
77 111
78 bool _finishMode; 112 bool _finishMode;
113
114#ifndef Z7_NO_READ_FROM_CODER
79 bool _outSizeDefined; 115 bool _outSizeDefined;
80 UInt64 _outSize; 116 UInt64 _outSize;
81 UInt64 _outSize_Processed; 117 UInt64 _outSize_Processed;
82 CBcj2Dec dec; 118 CMyComPtr<ISequentialInStream> _inStreams[BCJ2_NUM_STREAMS];
83 119#endif
84 void InitCommon(); 120
85 // HRESULT ReadSpec();
86
87public: 121public:
88 MY_UNKNOWN_IMP7(
89 ICompressCoder2,
90 ICompressSetFinishMode,
91 ICompressGetInStreamProcessedSize2,
92 ICompressSetInStream2,
93 ISequentialInStream,
94 ICompressSetOutStreamSize,
95 ICompressSetBufSize
96 );
97
98 STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams,
99 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams,
100 ICompressProgressInfo *progress);
101
102 STDMETHOD(SetFinishMode)(UInt32 finishMode);
103 STDMETHOD(GetInStreamProcessedSize2)(UInt32 streamIndex, UInt64 *value);
104
105 STDMETHOD(SetInStream2)(UInt32 streamIndex, ISequentialInStream *inStream);
106 STDMETHOD(ReleaseInStream2)(UInt32 streamIndex);
107
108 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
109
110 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
111
112 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size);
113 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size);
114
115 CDecoder(); 122 CDecoder();
116}; 123};
117 124
diff --git a/CPP/7zip/Compress/Bcj2Register.cpp b/CPP/7zip/Compress/Bcj2Register.cpp
index 2868f1c..1ce4dec 100644
--- a/CPP/7zip/Compress/Bcj2Register.cpp
+++ b/CPP/7zip/Compress/Bcj2Register.cpp
@@ -10,7 +10,7 @@ namespace NCompress {
10namespace NBcj2 { 10namespace NBcj2 {
11 11
12REGISTER_CODEC_CREATE_2(CreateCodec, CDecoder(), ICompressCoder2) 12REGISTER_CODEC_CREATE_2(CreateCodec, CDecoder(), ICompressCoder2)
13#ifndef EXTRACT_ONLY 13#ifndef Z7_EXTRACT_ONLY
14REGISTER_CODEC_CREATE_2(CreateCodecOut, CEncoder(), ICompressCoder2) 14REGISTER_CODEC_CREATE_2(CreateCodecOut, CEncoder(), ICompressCoder2)
15#else 15#else
16#define CreateCodecOut NULL 16#define CreateCodecOut NULL
diff --git a/CPP/7zip/Compress/BcjCoder.cpp b/CPP/7zip/Compress/BcjCoder.cpp
index 32aa176..0047874 100644
--- a/CPP/7zip/Compress/BcjCoder.cpp
+++ b/CPP/7zip/Compress/BcjCoder.cpp
@@ -7,17 +7,17 @@
7namespace NCompress { 7namespace NCompress {
8namespace NBcj { 8namespace NBcj {
9 9
10STDMETHODIMP CCoder::Init() 10Z7_COM7F_IMF(CCoder2::Init())
11{ 11{
12 _bufferPos = 0; 12 _pc = 0;
13 x86_Convert_Init(_prevMask); 13 _state = Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL;
14 return S_OK; 14 return S_OK;
15} 15}
16 16
17STDMETHODIMP_(UInt32) CCoder::Filter(Byte *data, UInt32 size) 17Z7_COM7F_IMF2(UInt32, CCoder2::Filter(Byte *data, UInt32 size))
18{ 18{
19 UInt32 processed = (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, _encode); 19 const UInt32 processed = (UInt32)(size_t)(_convFunc(data, size, _pc, &_state) - data);
20 _bufferPos += processed; 20 _pc += processed;
21 return processed; 21 return processed;
22} 22}
23 23
diff --git a/CPP/7zip/Compress/BcjCoder.h b/CPP/7zip/Compress/BcjCoder.h
index 7883906..734a278 100644
--- a/CPP/7zip/Compress/BcjCoder.h
+++ b/CPP/7zip/Compress/BcjCoder.h
@@ -1,7 +1,7 @@
1// BcjCoder.h 1// BcjCoder.h
2 2
3#ifndef __COMPRESS_BCJ_CODER_H 3#ifndef ZIP7_INC_COMPRESS_BCJ_CODER_H
4#define __COMPRESS_BCJ_CODER_H 4#define ZIP7_INC_COMPRESS_BCJ_CODER_H
5 5
6#include "../../../C/Bra.h" 6#include "../../../C/Bra.h"
7 7
@@ -12,18 +12,24 @@
12namespace NCompress { 12namespace NCompress {
13namespace NBcj { 13namespace NBcj {
14 14
15class CCoder: 15/* CCoder in old versions used another constructor parameter CCoder(int encode).
16 public ICompressFilter, 16 And some code called it as CCoder(0).
17 public CMyUnknownImp 17 We have changed constructor parameter type.
18{ 18 So we have changed the name of class also to CCoder2. */
19 UInt32 _bufferPos; 19
20 UInt32 _prevMask; 20Z7_CLASS_IMP_COM_1(
21 int _encode; 21 CCoder2
22 , ICompressFilter
23)
24 UInt32 _pc;
25 UInt32 _state;
26 z7_Func_BranchConvSt _convFunc;
22public: 27public:
23 MY_UNKNOWN_IMP1(ICompressFilter); 28 CCoder2(z7_Func_BranchConvSt convFunc):
24 INTERFACE_ICompressFilter(;) 29 _pc(0),
25 30 _state(Z7_BRANCH_CONV_ST_X86_STATE_INIT_VAL),
26 CCoder(int encode): _bufferPos(0), _encode(encode) { x86_Convert_Init(_prevMask); } 31 _convFunc(convFunc)
32 {}
27}; 33};
28 34
29}} 35}}
diff --git a/CPP/7zip/Compress/BcjRegister.cpp b/CPP/7zip/Compress/BcjRegister.cpp
index f06dcfe..0348f64 100644
--- a/CPP/7zip/Compress/BcjRegister.cpp
+++ b/CPP/7zip/Compress/BcjRegister.cpp
@@ -10,8 +10,8 @@ namespace NCompress {
10namespace NBcj { 10namespace NBcj {
11 11
12REGISTER_FILTER_E(BCJ, 12REGISTER_FILTER_E(BCJ,
13 CCoder(false), 13 CCoder2(z7_BranchConvSt_X86_Dec),
14 CCoder(true), 14 CCoder2(z7_BranchConvSt_X86_Enc),
15 0x3030103, "BCJ") 15 0x3030103, "BCJ")
16 16
17}} 17}}
diff --git a/CPP/7zip/Compress/BitlDecoder.h b/CPP/7zip/Compress/BitlDecoder.h
index 825864d..789ad1f 100644
--- a/CPP/7zip/Compress/BitlDecoder.h
+++ b/CPP/7zip/Compress/BitlDecoder.h
@@ -1,7 +1,7 @@
1// BitlDecoder.h -- the Least Significant Bit of byte is First 1// BitlDecoder.h -- the Least Significant Bit of byte is First
2 2
3#ifndef __BITL_DECODER_H 3#ifndef ZIP7_INC_BITL_DECODER_H
4#define __BITL_DECODER_H 4#define ZIP7_INC_BITL_DECODER_H
5 5
6#include "../IStream.h" 6#include "../IStream.h"
7 7
@@ -54,14 +54,14 @@ public:
54 54
55 bool ThereAreDataInBitsBuffer() const { return this->_bitPos != kNumBigValueBits; } 55 bool ThereAreDataInBitsBuffer() const { return this->_bitPos != kNumBigValueBits; }
56 56
57 MY_FORCE_INLINE 57 Z7_FORCE_INLINE
58 void Normalize() 58 void Normalize()
59 { 59 {
60 for (; _bitPos >= 8; _bitPos -= 8) 60 for (; _bitPos >= 8; _bitPos -= 8)
61 _value = ((UInt32)_stream.ReadByte() << (kNumBigValueBits - _bitPos)) | _value; 61 _value = ((UInt32)_stream.ReadByte() << (kNumBigValueBits - _bitPos)) | _value;
62 } 62 }
63 63
64 MY_FORCE_INLINE 64 Z7_FORCE_INLINE
65 UInt32 ReadBits(unsigned numBits) 65 UInt32 ReadBits(unsigned numBits)
66 { 66 {
67 Normalize(); 67 Normalize();
@@ -102,7 +102,7 @@ public:
102 _normalValue = 0; 102 _normalValue = 0;
103 } 103 }
104 104
105 MY_FORCE_INLINE 105 Z7_FORCE_INLINE
106 void Normalize() 106 void Normalize()
107 { 107 {
108 for (; this->_bitPos >= 8; this->_bitPos -= 8) 108 for (; this->_bitPos >= 8; this->_bitPos -= 8)
@@ -113,21 +113,21 @@ public:
113 } 113 }
114 } 114 }
115 115
116 MY_FORCE_INLINE 116 Z7_FORCE_INLINE
117 UInt32 GetValue(unsigned numBits) 117 UInt32 GetValue(unsigned numBits)
118 { 118 {
119 Normalize(); 119 Normalize();
120 return ((this->_value >> (8 - this->_bitPos)) & kMask) >> (kNumValueBits - numBits); 120 return ((this->_value >> (8 - this->_bitPos)) & kMask) >> (kNumValueBits - numBits);
121 } 121 }
122 122
123 MY_FORCE_INLINE 123 Z7_FORCE_INLINE
124 void MovePos(unsigned numBits) 124 void MovePos(unsigned numBits)
125 { 125 {
126 this->_bitPos += numBits; 126 this->_bitPos += numBits;
127 _normalValue >>= numBits; 127 _normalValue >>= numBits;
128 } 128 }
129 129
130 MY_FORCE_INLINE 130 Z7_FORCE_INLINE
131 UInt32 ReadBits(unsigned numBits) 131 UInt32 ReadBits(unsigned numBits)
132 { 132 {
133 Normalize(); 133 Normalize();
@@ -138,10 +138,10 @@ public:
138 138
139 void AlignToByte() { MovePos((32 - this->_bitPos) & 7); } 139 void AlignToByte() { MovePos((32 - this->_bitPos) & 7); }
140 140
141 MY_FORCE_INLINE 141 Z7_FORCE_INLINE
142 Byte ReadDirectByte() { return this->_stream.ReadByte(); } 142 Byte ReadDirectByte() { return this->_stream.ReadByte(); }
143 143
144 MY_FORCE_INLINE 144 Z7_FORCE_INLINE
145 Byte ReadAlignedByte() 145 Byte ReadAlignedByte()
146 { 146 {
147 if (this->_bitPos == kNumBigValueBits) 147 if (this->_bitPos == kNumBigValueBits)
@@ -152,7 +152,7 @@ public:
152 } 152 }
153 153
154 // call it only if the object is aligned for byte. 154 // call it only if the object is aligned for byte.
155 MY_FORCE_INLINE 155 Z7_FORCE_INLINE
156 bool ReadAlignedByte_FromBuf(Byte &b) 156 bool ReadAlignedByte_FromBuf(Byte &b)
157 { 157 {
158 if (this->_stream.NumExtraBytes != 0) 158 if (this->_stream.NumExtraBytes != 0)
diff --git a/CPP/7zip/Compress/BitlEncoder.h b/CPP/7zip/Compress/BitlEncoder.h
index 9a4612f..67b1428 100644
--- a/CPP/7zip/Compress/BitlEncoder.h
+++ b/CPP/7zip/Compress/BitlEncoder.h
@@ -1,7 +1,7 @@
1// BitlEncoder.h -- the Least Significant Bit of byte is First 1// BitlEncoder.h -- the Least Significant Bit of byte is First
2 2
3#ifndef __BITL_ENCODER_H 3#ifndef ZIP7_INC_BITL_ENCODER_H
4#define __BITL_ENCODER_H 4#define ZIP7_INC_BITL_ENCODER_H
5 5
6#include "../Common/OutBuffer.h" 6#include "../Common/OutBuffer.h"
7 7
diff --git a/CPP/7zip/Compress/BitmDecoder.h b/CPP/7zip/Compress/BitmDecoder.h
index 9ce41bd..199a228 100644
--- a/CPP/7zip/Compress/BitmDecoder.h
+++ b/CPP/7zip/Compress/BitmDecoder.h
@@ -1,7 +1,7 @@
1// BitmDecoder.h -- the Most Significant Bit of byte is First 1// BitmDecoder.h -- the Most Significant Bit of byte is First
2 2
3#ifndef __BITM_DECODER_H 3#ifndef ZIP7_INC_BITM_DECODER_H
4#define __BITM_DECODER_H 4#define ZIP7_INC_BITM_DECODER_H
5 5
6#include "../IStream.h" 6#include "../IStream.h"
7 7
@@ -47,28 +47,28 @@ public:
47 return (_stream.NumExtraBytes > 4); 47 return (_stream.NumExtraBytes > 4);
48 } 48 }
49 49
50 MY_FORCE_INLINE 50 Z7_FORCE_INLINE
51 void Normalize() 51 void Normalize()
52 { 52 {
53 for (; _bitPos >= 8; _bitPos -= 8) 53 for (; _bitPos >= 8; _bitPos -= 8)
54 _value = (_value << 8) | _stream.ReadByte(); 54 _value = (_value << 8) | _stream.ReadByte();
55 } 55 }
56 56
57 MY_FORCE_INLINE 57 Z7_FORCE_INLINE
58 UInt32 GetValue(unsigned numBits) const 58 UInt32 GetValue(unsigned numBits) const
59 { 59 {
60 // return (_value << _bitPos) >> (kNumBigValueBits - numBits); 60 // return (_value << _bitPos) >> (kNumBigValueBits - numBits);
61 return ((_value >> (8 - _bitPos)) & kMask) >> (kNumValueBits - numBits); 61 return ((_value >> (8 - _bitPos)) & kMask) >> (kNumValueBits - numBits);
62 } 62 }
63 63
64 MY_FORCE_INLINE 64 Z7_FORCE_INLINE
65 void MovePos(unsigned numBits) 65 void MovePos(unsigned numBits)
66 { 66 {
67 _bitPos += numBits; 67 _bitPos += numBits;
68 Normalize(); 68 Normalize();
69 } 69 }
70 70
71 MY_FORCE_INLINE 71 Z7_FORCE_INLINE
72 UInt32 ReadBits(unsigned numBits) 72 UInt32 ReadBits(unsigned numBits)
73 { 73 {
74 UInt32 res = GetValue(numBits); 74 UInt32 res = GetValue(numBits);
@@ -91,7 +91,7 @@ public:
91 91
92 void AlignToByte() { MovePos((kNumBigValueBits - _bitPos) & 7); } 92 void AlignToByte() { MovePos((kNumBigValueBits - _bitPos) & 7); }
93 93
94 MY_FORCE_INLINE 94 Z7_FORCE_INLINE
95 UInt32 ReadAlignBits() { return ReadBits((kNumBigValueBits - _bitPos) & 7); } 95 UInt32 ReadAlignBits() { return ReadBits((kNumBigValueBits - _bitPos) & 7); }
96}; 96};
97 97
diff --git a/CPP/7zip/Compress/BitmEncoder.h b/CPP/7zip/Compress/BitmEncoder.h
index 4499c79..978ee1c 100644
--- a/CPP/7zip/Compress/BitmEncoder.h
+++ b/CPP/7zip/Compress/BitmEncoder.h
@@ -1,7 +1,7 @@
1// BitmEncoder.h -- the Most Significant Bit of byte is First 1// BitmEncoder.h -- the Most Significant Bit of byte is First
2 2
3#ifndef __BITM_ENCODER_H 3#ifndef ZIP7_INC_BITM_ENCODER_H
4#define __BITM_ENCODER_H 4#define ZIP7_INC_BITM_ENCODER_H
5 5
6#include "../IStream.h" 6#include "../IStream.h"
7 7
diff --git a/CPP/7zip/Compress/BranchMisc.cpp b/CPP/7zip/Compress/BranchMisc.cpp
index d0e75e8..d9fec8c 100644
--- a/CPP/7zip/Compress/BranchMisc.cpp
+++ b/CPP/7zip/Compress/BranchMisc.cpp
@@ -2,22 +2,109 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/CpuArch.h"
6
7#include "../Common/StreamUtils.h"
8
5#include "BranchMisc.h" 9#include "BranchMisc.h"
6 10
7namespace NCompress { 11namespace NCompress {
8namespace NBranch { 12namespace NBranch {
9 13
10STDMETHODIMP CCoder::Init() 14Z7_COM7F_IMF(CCoder::Init())
15{
16 _pc = 0;
17 return S_OK;
18}
19
20
21Z7_COM7F_IMF2(UInt32, CCoder::Filter(Byte *data, UInt32 size))
22{
23 const UInt32 processed = (UInt32)(size_t)(BraFunc(data, size, _pc) - data);
24 _pc += processed;
25 return processed;
26}
27
28
29namespace NArm64 {
30
31#ifndef Z7_EXTRACT_ONLY
32
33Z7_COM7F_IMF(CEncoder::Init())
34{
35 _pc = _pc_Init;
36 return S_OK;
37}
38
39Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size))
40{
41 const UInt32 processed = (UInt32)(size_t)(Z7_BRANCH_CONV_ENC(ARM64)(data, size, _pc) - data);
42 _pc += processed;
43 return processed;
44}
45
46Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
11{ 47{
12 _bufferPos = 0; 48 UInt32 pc = 0;
49 for (UInt32 i = 0; i < numProps; i++)
50 {
51 const PROPID propID = propIDs[i];
52 if (propID == NCoderPropID::kDefaultProp ||
53 propID == NCoderPropID::kBranchOffset)
54 {
55 const PROPVARIANT &prop = props[i];
56 if (prop.vt != VT_UI4)
57 return E_INVALIDARG;
58 pc = prop.ulVal;
59 if ((pc & 3) != 0)
60 return E_INVALIDARG;
61 }
62 }
63 _pc_Init = pc;
13 return S_OK; 64 return S_OK;
14} 65}
15 66
16STDMETHODIMP_(UInt32) CCoder::Filter(Byte *data, UInt32 size) 67
68Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
69{
70 if (_pc_Init == 0)
71 return S_OK;
72 Byte buf[4];
73 SetUi32(buf, _pc_Init)
74 return WriteStream(outStream, buf, 4);
75}
76
77#endif
78
79
80Z7_COM7F_IMF(CDecoder::Init())
17{ 81{
18 UInt32 processed = (UInt32)BraFunc(data, size, _bufferPos, _encode); 82 _pc = _pc_Init;
19 _bufferPos += processed; 83 return S_OK;
84}
85
86Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
87{
88 const UInt32 processed = (UInt32)(size_t)(Z7_BRANCH_CONV_DEC(ARM64)(data, size, _pc) - data);
89 _pc += processed;
20 return processed; 90 return processed;
21} 91}
22 92
93Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size))
94{
95 UInt32 val = 0;
96 if (size != 0)
97 {
98 if (size != 4)
99 return E_NOTIMPL;
100 val = GetUi32(props);
101 if ((val & 3) != 0)
102 return E_NOTIMPL;
103 }
104 _pc_Init = val;
105 return S_OK;
106}
107
108}
109
23}} 110}}
diff --git a/CPP/7zip/Compress/BranchMisc.h b/CPP/7zip/Compress/BranchMisc.h
index 66fc23d..a5793f7 100644
--- a/CPP/7zip/Compress/BranchMisc.h
+++ b/CPP/7zip/Compress/BranchMisc.h
@@ -1,35 +1,57 @@
1// BranchMisc.h 1// BranchMisc.h
2 2
3#ifndef __COMPRESS_BRANCH_MISC_H 3#ifndef ZIP7_INC_COMPRESS_BRANCH_MISC_H
4#define __COMPRESS_BRANCH_MISC_H 4#define ZIP7_INC_COMPRESS_BRANCH_MISC_H
5#include "../../../C/Bra.h"
5 6
6#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
7 8
8#include "../ICoder.h" 9#include "../ICoder.h"
9 10
10EXTERN_C_BEGIN 11namespace NCompress {
12namespace NBranch {
11 13
12typedef SizeT (*Func_Bra)(Byte *data, SizeT size, UInt32 ip, int encoding); 14Z7_CLASS_IMP_COM_1(
15 CCoder
16 , ICompressFilter
17)
18 UInt32 _pc;
19 z7_Func_BranchConv BraFunc;
20public:
21 CCoder(z7_Func_BranchConv bra): _pc(0), BraFunc(bra) {}
22};
13 23
14EXTERN_C_END 24namespace NArm64 {
15 25
16namespace NCompress { 26#ifndef Z7_EXTRACT_ONLY
17namespace NBranch {
18 27
19class CCoder: 28Z7_CLASS_IMP_COM_3(
20 public ICompressFilter, 29 CEncoder
21 public CMyUnknownImp 30 , ICompressFilter
22{ 31 , ICompressSetCoderProperties
23 UInt32 _bufferPos; 32 , ICompressWriteCoderProperties
24 int _encode; 33)
25 Func_Bra BraFunc; 34 UInt32 _pc;
35 UInt32 _pc_Init;
26public: 36public:
27 MY_UNKNOWN_IMP1(ICompressFilter); 37 CEncoder(): _pc(0), _pc_Init(0) {}
28 INTERFACE_ICompressFilter(;) 38};
39
40#endif
29 41
30 CCoder(Func_Bra bra, int encode): _bufferPos(0), _encode(encode), BraFunc(bra) {} 42Z7_CLASS_IMP_COM_2(
43 CDecoder
44 , ICompressFilter
45 , ICompressSetDecoderProperties2
46)
47 UInt32 _pc;
48 UInt32 _pc_Init;
49public:
50 CDecoder(): _pc(0), _pc_Init(0) {}
31}; 51};
32 52
53}
54
33}} 55}}
34 56
35#endif 57#endif
diff --git a/CPP/7zip/Compress/BranchRegister.cpp b/CPP/7zip/Compress/BranchRegister.cpp
index 6331c1b..80fbf60 100644
--- a/CPP/7zip/Compress/BranchRegister.cpp
+++ b/CPP/7zip/Compress/BranchRegister.cpp
@@ -2,8 +2,6 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/Bra.h"
6
7#include "../Common/RegisterCodec.h" 5#include "../Common/RegisterCodec.h"
8 6
9#include "BranchMisc.h" 7#include "BranchMisc.h"
@@ -11,9 +9,18 @@
11namespace NCompress { 9namespace NCompress {
12namespace NBranch { 10namespace NBranch {
13 11
12#ifdef Z7_EXTRACT_ONLY
13#define GET_CREATE_FUNC(x) NULL
14#define CREATE_BRA_E(n)
15#else
16#define GET_CREATE_FUNC(x) x
17#define CREATE_BRA_E(n) \
18 REGISTER_FILTER_CREATE(CreateBra_Encoder_ ## n, CCoder(Z7_BRANCH_CONV_ENC(n)))
19#endif
20
14#define CREATE_BRA(n) \ 21#define CREATE_BRA(n) \
15 REGISTER_FILTER_CREATE(CreateBra_Decoder_ ## n, CCoder(n ## _Convert, false)) \ 22 REGISTER_FILTER_CREATE(CreateBra_Decoder_ ## n, CCoder(Z7_BRANCH_CONV_DEC(n))) \
16 REGISTER_FILTER_CREATE(CreateBra_Encoder_ ## n, CCoder(n ## _Convert, true)) \ 23 CREATE_BRA_E(n)
17 24
18CREATE_BRA(PPC) 25CREATE_BRA(PPC)
19CREATE_BRA(IA64) 26CREATE_BRA(IA64)
@@ -23,8 +30,8 @@ CREATE_BRA(SPARC)
23 30
24#define METHOD_ITEM(n, id, name) \ 31#define METHOD_ITEM(n, id, name) \
25 REGISTER_FILTER_ITEM( \ 32 REGISTER_FILTER_ITEM( \
26 CreateBra_Decoder_ ## n, \ 33 CreateBra_Decoder_ ## n, GET_CREATE_FUNC( \
27 CreateBra_Encoder_ ## n, \ 34 CreateBra_Encoder_ ## n), \
28 0x3030000 + id, name) 35 0x3030000 + id, name)
29 36
30REGISTER_CODECS_VAR 37REGISTER_CODECS_VAR
@@ -38,4 +45,11 @@ REGISTER_CODECS_VAR
38 45
39REGISTER_CODECS(Branch) 46REGISTER_CODECS(Branch)
40 47
48namespace NArm64 {
49REGISTER_FILTER_E(ARM64,
50 CDecoder(),
51 CEncoder(),
52 0xa, "ARM64")
53}
54
41}} 55}}
diff --git a/CPP/7zip/Compress/ByteSwap.cpp b/CPP/7zip/Compress/ByteSwap.cpp
index 4c11806..cc28d8b 100644
--- a/CPP/7zip/Compress/ByteSwap.cpp
+++ b/CPP/7zip/Compress/ByteSwap.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/SwapBytes.h"
6
5#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
6 8
7#include "../ICoder.h" 9#include "../ICoder.h"
@@ -11,80 +13,77 @@
11namespace NCompress { 13namespace NCompress {
12namespace NByteSwap { 14namespace NByteSwap {
13 15
14class CByteSwap2: 16Z7_CLASS_IMP_COM_1(CByteSwap2, ICompressFilter) };
15 public ICompressFilter, 17Z7_CLASS_IMP_COM_1(CByteSwap4, ICompressFilter) };
16 public CMyUnknownImp
17{
18public:
19 MY_UNKNOWN_IMP1(ICompressFilter);
20 INTERFACE_ICompressFilter(;)
21};
22
23class CByteSwap4:
24 public ICompressFilter,
25 public CMyUnknownImp
26{
27public:
28 MY_UNKNOWN_IMP1(ICompressFilter);
29 INTERFACE_ICompressFilter(;)
30};
31 18
32STDMETHODIMP CByteSwap2::Init() { return S_OK; } 19Z7_COM7F_IMF(CByteSwap2::Init()) { return S_OK; }
33 20
34STDMETHODIMP_(UInt32) CByteSwap2::Filter(Byte *data, UInt32 size) 21Z7_COM7F_IMF2(UInt32, CByteSwap2::Filter(Byte *data, UInt32 size))
35{ 22{
36 const UInt32 kStep = 2; 23 const UInt32 kMask = 2 - 1;
37 if (size < kStep) 24 size &= ~kMask;
38 return 0; 25 /*
39 size &= ~(kStep - 1); 26 if ((unsigned)(ptrdiff_t)data & kMask)
40
41 const Byte *end = data + (size_t)size;
42
43 do
44 { 27 {
45 Byte b0 = data[0]; 28 if (size == 0)
46 data[0] = data[1]; 29 return 0;
47 data[1] = b0; 30 const Byte *end = data + (size_t)size;
48 data += kStep; 31 do
32 {
33 const Byte b0 = data[0];
34 data[0] = data[1];
35 data[1] = b0;
36 data += kStep;
37 }
38 while (data != end);
49 } 39 }
50 while (data != end); 40 else
51 41 */
42 z7_SwapBytes2((UInt16 *)(void *)data, size >> 1);
52 return size; 43 return size;
53} 44}
54 45
55STDMETHODIMP CByteSwap4::Init() { return S_OK; }
56 46
57STDMETHODIMP_(UInt32) CByteSwap4::Filter(Byte *data, UInt32 size) 47Z7_COM7F_IMF(CByteSwap4::Init()) { return S_OK; }
48
49Z7_COM7F_IMF2(UInt32, CByteSwap4::Filter(Byte *data, UInt32 size))
58{ 50{
59 const UInt32 kStep = 4; 51 const UInt32 kMask = 4 - 1;
60 if (size < kStep) 52 size &= ~kMask;
61 return 0; 53 /*
62 size &= ~(kStep - 1); 54 if ((unsigned)(ptrdiff_t)data & kMask)
63
64 const Byte *end = data + (size_t)size;
65
66 do
67 { 55 {
68 Byte b0 = data[0]; 56 if (size == 0)
69 Byte b1 = data[1]; 57 return 0;
70 data[0] = data[3]; 58 const Byte *end = data + (size_t)size;
71 data[1] = data[2]; 59 do
72 data[2] = b1; 60 {
73 data[3] = b0; 61 const Byte b0 = data[0];
74 data += kStep; 62 const Byte b1 = data[1];
63 data[0] = data[3];
64 data[1] = data[2];
65 data[2] = b1;
66 data[3] = b0;
67 data += kStep;
68 }
69 while (data != end);
75 } 70 }
76 while (data != end); 71 else
77 72 */
73 z7_SwapBytes4((UInt32 *)(void *)data, size >> 2);
78 return size; 74 return size;
79} 75}
80 76
77static struct C_SwapBytesPrepare { C_SwapBytesPrepare() { z7_SwapBytesPrepare(); } } g_SwapBytesPrepare;
78
79
81REGISTER_FILTER_CREATE(CreateFilter2, CByteSwap2()) 80REGISTER_FILTER_CREATE(CreateFilter2, CByteSwap2())
82REGISTER_FILTER_CREATE(CreateFilter4, CByteSwap4()) 81REGISTER_FILTER_CREATE(CreateFilter4, CByteSwap4())
83 82
84REGISTER_CODECS_VAR 83REGISTER_CODECS_VAR
85{ 84{
86 REGISTER_FILTER_ITEM(CreateFilter2, CreateFilter2, 0x20302, "Swap2"), 85 REGISTER_FILTER_ITEM(CreateFilter2, CreateFilter2, 0x20302, "Swap2"),
87 REGISTER_FILTER_ITEM(CreateFilter4, CreateFilter4, 0x20304, "Swap4") 86 REGISTER_FILTER_ITEM(CreateFilter4, CreateFilter4, 0x20304, "Swap4"),
88}; 87};
89 88
90REGISTER_CODECS(ByteSwap) 89REGISTER_CODECS(ByteSwap)
diff --git a/CPP/7zip/Compress/Codec.def b/CPP/7zip/Compress/Codec.def
index f55b2d5..e2bc0df 100644
--- a/CPP/7zip/Compress/Codec.def
+++ b/CPP/7zip/Compress/Codec.def
@@ -4,3 +4,4 @@ EXPORTS
4 GetMethodProperty PRIVATE 4 GetMethodProperty PRIVATE
5 CreateDecoder PRIVATE 5 CreateDecoder PRIVATE
6 CreateEncoder PRIVATE 6 CreateEncoder PRIVATE
7 GetModuleProp PRIVATE
diff --git a/CPP/7zip/Compress/CodecExports.cpp b/CPP/7zip/Compress/CodecExports.cpp
index 5bb6ff8..e37ae14 100644
--- a/CPP/7zip/Compress/CodecExports.cpp
+++ b/CPP/7zip/Compress/CodecExports.cpp
@@ -3,11 +3,13 @@
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/CpuArch.h" 5#include "../../../C/CpuArch.h"
6#include "../../../C/7zVersion.h"
6 7
7#include "../../Common/ComTry.h" 8#include "../../Common/ComTry.h"
8#include "../../Common/MyCom.h" 9#include "../../Common/MyCom.h"
9 10
10#include "../../Windows/Defs.h" 11#include "../../Windows/Defs.h"
12#include "../../Windows/PropVariant.h"
11 13
12#include "../ICoder.h" 14#include "../ICoder.h"
13 15
@@ -21,7 +23,7 @@ extern const CHasherInfo *g_Hashers[];
21 23
22static void SetPropFromAscii(const char *s, PROPVARIANT *prop) throw() 24static void SetPropFromAscii(const char *s, PROPVARIANT *prop) throw()
23{ 25{
24 UINT len = (UINT)strlen(s); 26 const UINT len = (UINT)strlen(s);
25 BSTR dest = ::SysAllocStringLen(NULL, len); 27 BSTR dest = ::SysAllocStringLen(NULL, len);
26 if (dest) 28 if (dest)
27 { 29 {
@@ -45,7 +47,7 @@ static HRESULT MethodToClassID(UInt16 typeId, CMethodId id, PROPVARIANT *value)
45 clsId.Data1 = k_7zip_GUID_Data1; 47 clsId.Data1 = k_7zip_GUID_Data1;
46 clsId.Data2 = k_7zip_GUID_Data2; 48 clsId.Data2 = k_7zip_GUID_Data2;
47 clsId.Data3 = typeId; 49 clsId.Data3 = typeId;
48 SetUi64(clsId.Data4, id); 50 SetUi64(clsId.Data4, id)
49 return SetPropGUID(clsId, value); 51 return SetPropGUID(clsId, value);
50} 52}
51 53
@@ -61,7 +63,7 @@ static HRESULT FindCodecClassId(const GUID *clsid, bool isCoder2, bool isFilter,
61 if (clsid->Data3 == k_7zip_GUID_Data3_Decoder) encode = false; 63 if (clsid->Data3 == k_7zip_GUID_Data3_Decoder) encode = false;
62 else if (clsid->Data3 != k_7zip_GUID_Data3_Encoder) return S_OK; 64 else if (clsid->Data3 != k_7zip_GUID_Data3_Encoder) return S_OK;
63 65
64 UInt64 id = GetUi64(clsid->Data4); 66 const UInt64 id = GetUi64(clsid->Data4);
65 67
66 for (unsigned i = 0; i < g_NumCodecs; i++) 68 for (unsigned i = 0; i < g_NumCodecs; i++)
67 { 69 {
@@ -75,7 +77,7 @@ static HRESULT FindCodecClassId(const GUID *clsid, bool isCoder2, bool isFilter,
75 if (codec.NumStreams == 1 ? isCoder2 : !isCoder2) 77 if (codec.NumStreams == 1 ? isCoder2 : !isCoder2)
76 return E_NOINTERFACE; 78 return E_NOINTERFACE;
77 79
78 index = i; 80 index = (int)i;
79 return S_OK; 81 return S_OK;
80 } 82 }
81 83
@@ -169,7 +171,7 @@ STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject)
169 171
170 bool isFilter = false; 172 bool isFilter = false;
171 bool isCoder2 = false; 173 bool isCoder2 = false;
172 bool isCoder = (*iid == IID_ICompressCoder) != 0; 174 const bool isCoder = (*iid == IID_ICompressCoder) != 0;
173 if (!isCoder) 175 if (!isCoder)
174 { 176 {
175 isFilter = (*iid == IID_ICompressFilter) != 0; 177 isFilter = (*iid == IID_ICompressFilter) != 0;
@@ -183,13 +185,13 @@ STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject)
183 185
184 bool encode; 186 bool encode;
185 int codecIndex; 187 int codecIndex;
186 HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex); 188 const HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex);
187 if (res != S_OK) 189 if (res != S_OK)
188 return res; 190 return res;
189 if (codecIndex < 0) 191 if (codecIndex < 0)
190 return CLASS_E_CLASSNOTAVAILABLE; 192 return CLASS_E_CLASSNOTAVAILABLE;
191 193
192 return CreateCoderMain(codecIndex, encode, outObject); 194 return CreateCoderMain((unsigned)codecIndex, encode, outObject);
193} 195}
194 196
195 197
@@ -255,8 +257,8 @@ STDAPI GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value)
255} 257}
256 258
257 259
258STDAPI GetNumberOfMethods(UINT32 *numCodecs); 260STDAPI GetNumberOfMethods(UInt32 *numCodecs);
259STDAPI GetNumberOfMethods(UINT32 *numCodecs) 261STDAPI GetNumberOfMethods(UInt32 *numCodecs)
260{ 262{
261 *numCodecs = g_NumCodecs; 263 *numCodecs = g_NumCodecs;
262 return S_OK; 264 return S_OK;
@@ -271,10 +273,10 @@ static int FindHasherClassId(const GUID *clsid) throw()
271 clsid->Data2 != k_7zip_GUID_Data2 || 273 clsid->Data2 != k_7zip_GUID_Data2 ||
272 clsid->Data3 != k_7zip_GUID_Data3_Hasher) 274 clsid->Data3 != k_7zip_GUID_Data3_Hasher)
273 return -1; 275 return -1;
274 UInt64 id = GetUi64(clsid->Data4); 276 const UInt64 id = GetUi64(clsid->Data4);
275 for (unsigned i = 0; i < g_NumCodecs; i++) 277 for (unsigned i = 0; i < g_NumCodecs; i++)
276 if (id == g_Hashers[i]->Id) 278 if (id == g_Hashers[i]->Id)
277 return i; 279 return (int)i;
278 return -1; 280 return -1;
279} 281}
280 282
@@ -292,11 +294,11 @@ STDAPI CreateHasher(const GUID *clsid, IHasher **outObject);
292STDAPI CreateHasher(const GUID *clsid, IHasher **outObject) 294STDAPI CreateHasher(const GUID *clsid, IHasher **outObject)
293{ 295{
294 COM_TRY_BEGIN 296 COM_TRY_BEGIN
295 *outObject = 0; 297 *outObject = NULL;
296 int index = FindHasherClassId(clsid); 298 const int index = FindHasherClassId(clsid);
297 if (index < 0) 299 if (index < 0)
298 return CLASS_E_CLASSNOTAVAILABLE; 300 return CLASS_E_CLASSNOTAVAILABLE;
299 return CreateHasher2(index, outObject); 301 return CreateHasher2((UInt32)(unsigned)index, outObject);
300 COM_TRY_END 302 COM_TRY_END
301} 303}
302 304
@@ -326,17 +328,7 @@ STDAPI GetHasherProp(UInt32 codecIndex, PROPID propID, PROPVARIANT *value)
326 return S_OK; 328 return S_OK;
327} 329}
328 330
329class CHashers: 331Z7_CLASS_IMP_COM_1(CHashers, IHashers) };
330 public IHashers,
331 public CMyUnknownImp
332{
333public:
334 MY_UNKNOWN_IMP1(IHashers)
335
336 STDMETHOD_(UInt32, GetNumHashers)();
337 STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value);
338 STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher);
339};
340 332
341STDAPI GetHashers(IHashers **hashers); 333STDAPI GetHashers(IHashers **hashers);
342STDAPI GetHashers(IHashers **hashers) 334STDAPI GetHashers(IHashers **hashers)
@@ -349,17 +341,38 @@ STDAPI GetHashers(IHashers **hashers)
349 COM_TRY_END 341 COM_TRY_END
350} 342}
351 343
352STDMETHODIMP_(UInt32) CHashers::GetNumHashers() 344Z7_COM7F_IMF2(UInt32, CHashers::GetNumHashers())
353{ 345{
354 return g_NumHashers; 346 return g_NumHashers;
355} 347}
356 348
357STDMETHODIMP CHashers::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value) 349Z7_COM7F_IMF(CHashers::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value))
358{ 350{
359 return ::GetHasherProp(index, propID, value); 351 return ::GetHasherProp(index, propID, value);
360} 352}
361 353
362STDMETHODIMP CHashers::CreateHasher(UInt32 index, IHasher **hasher) 354Z7_COM7F_IMF(CHashers::CreateHasher(UInt32 index, IHasher **hasher))
363{ 355{
364 return ::CreateHasher2(index, hasher); 356 return ::CreateHasher2(index, hasher);
365} 357}
358
359
360STDAPI GetModuleProp(PROPID propID, PROPVARIANT *value);
361STDAPI GetModuleProp(PROPID propID, PROPVARIANT *value)
362{
363 ::VariantClear((VARIANTARG *)value);
364 switch (propID)
365 {
366 case NModulePropID::kInterfaceType:
367 {
368 NWindows::NCOM::PropVarEm_Set_UInt32(value, NModuleInterfaceType::k_IUnknown_VirtDestructor_ThisModule);
369 break;
370 }
371 case NModulePropID::kVersion:
372 {
373 NWindows::NCOM::PropVarEm_Set_UInt32(value, (MY_VER_MAJOR << 16) | MY_VER_MINOR);
374 break;
375 }
376 }
377 return S_OK;
378}
diff --git a/CPP/7zip/Compress/CopyCoder.cpp b/CPP/7zip/Compress/CopyCoder.cpp
index a49bba8..b779e08 100644
--- a/CPP/7zip/Compress/CopyCoder.cpp
+++ b/CPP/7zip/Compress/CopyCoder.cpp
@@ -15,15 +15,15 @@ CCopyCoder::~CCopyCoder()
15 ::MidFree(_buf); 15 ::MidFree(_buf);
16} 16}
17 17
18STDMETHODIMP CCopyCoder::SetFinishMode(UInt32 /* finishMode */) 18Z7_COM7F_IMF(CCopyCoder::SetFinishMode(UInt32 /* finishMode */))
19{ 19{
20 return S_OK; 20 return S_OK;
21} 21}
22 22
23STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, 23Z7_COM7F_IMF(CCopyCoder::Code(ISequentialInStream *inStream,
24 ISequentialOutStream *outStream, 24 ISequentialOutStream *outStream,
25 const UInt64 * /* inSize */, const UInt64 *outSize, 25 const UInt64 * /* inSize */, const UInt64 *outSize,
26 ICompressProgressInfo *progress) 26 ICompressProgressInfo *progress))
27{ 27{
28 if (!_buf) 28 if (!_buf)
29 { 29 {
@@ -44,7 +44,12 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream,
44 { 44 {
45 size = (UInt32)rem; 45 size = (UInt32)rem;
46 if (size == 0) 46 if (size == 0)
47 {
48 /* if we enable the following check,
49 we will make one call of Read(_buf, 0) for empty stream */
50 // if (TotalSize != 0)
47 return S_OK; 51 return S_OK;
52 }
48 } 53 }
49 } 54 }
50 55
@@ -81,7 +86,7 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream,
81 return E_FAIL; // internal code failure 86 return E_FAIL; // internal code failure
82 pos += processed; 87 pos += processed;
83 TotalSize += processed; 88 TotalSize += processed;
84 RINOK(res); 89 RINOK(res)
85 if (processed == 0) 90 if (processed == 0)
86 return E_FAIL; 91 return E_FAIL;
87 } 92 }
@@ -90,32 +95,32 @@ STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream,
90 else 95 else
91 TotalSize += size; 96 TotalSize += size;
92 97
93 RINOK(readRes); 98 RINOK(readRes)
94 99
95 if (size != kBufSize) 100 if (size != kBufSize)
96 return S_OK; 101 return S_OK;
97 102
98 if (progress && (TotalSize & (((UInt32)1 << 22) - 1)) == 0) 103 if (progress && (TotalSize & (((UInt32)1 << 22) - 1)) == 0)
99 { 104 {
100 RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize)); 105 RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize))
101 } 106 }
102 } 107 }
103} 108}
104 109
105STDMETHODIMP CCopyCoder::SetInStream(ISequentialInStream *inStream) 110Z7_COM7F_IMF(CCopyCoder::SetInStream(ISequentialInStream *inStream))
106{ 111{
107 _inStream = inStream; 112 _inStream = inStream;
108 TotalSize = 0; 113 TotalSize = 0;
109 return S_OK; 114 return S_OK;
110} 115}
111 116
112STDMETHODIMP CCopyCoder::ReleaseInStream() 117Z7_COM7F_IMF(CCopyCoder::ReleaseInStream())
113{ 118{
114 _inStream.Release(); 119 _inStream.Release();
115 return S_OK; 120 return S_OK;
116} 121}
117 122
118STDMETHODIMP CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize) 123Z7_COM7F_IMF(CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize))
119{ 124{
120 UInt32 realProcessedSize = 0; 125 UInt32 realProcessedSize = 0;
121 HRESULT res = _inStream->Read(data, size, &realProcessedSize); 126 HRESULT res = _inStream->Read(data, size, &realProcessedSize);
@@ -125,7 +130,7 @@ STDMETHODIMP CCopyCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
125 return res; 130 return res;
126} 131}
127 132
128STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value) 133Z7_COM7F_IMF(CCopyCoder::GetInStreamProcessedSize(UInt64 *value))
129{ 134{
130 *value = TotalSize; 135 *value = TotalSize;
131 return S_OK; 136 return S_OK;
@@ -141,7 +146,7 @@ HRESULT CopyStream_ExactSize(ISequentialInStream *inStream, ISequentialOutStream
141{ 146{
142 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; 147 NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
143 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; 148 CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
144 RINOK(copyCoder->Code(inStream, outStream, NULL, &size, progress)); 149 RINOK(copyCoder->Code(inStream, outStream, NULL, &size, progress))
145 return copyCoderSpec->TotalSize == size ? S_OK : E_FAIL; 150 return copyCoderSpec->TotalSize == size ? S_OK : E_FAIL;
146} 151}
147 152
diff --git a/CPP/7zip/Compress/CopyCoder.h b/CPP/7zip/Compress/CopyCoder.h
index a9d0b6d..cb93e4e 100644
--- a/CPP/7zip/Compress/CopyCoder.h
+++ b/CPP/7zip/Compress/CopyCoder.h
@@ -1,7 +1,7 @@
1// Compress/CopyCoder.h 1// Compress/CopyCoder.h
2 2
3#ifndef __COMPRESS_COPY_CODER_H 3#ifndef ZIP7_INC_COMPRESS_COPY_CODER_H
4#define __COMPRESS_COPY_CODER_H 4#define ZIP7_INC_COMPRESS_COPY_CODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -9,36 +9,21 @@
9 9
10namespace NCompress { 10namespace NCompress {
11 11
12class CCopyCoder: 12Z7_CLASS_IMP_COM_5(
13 public ICompressCoder, 13 CCopyCoder
14 public ICompressSetInStream, 14 , ICompressCoder
15 public ISequentialInStream, 15 , ICompressSetInStream
16 public ICompressSetFinishMode, 16 , ISequentialInStream
17 public ICompressGetInStreamProcessedSize, 17 , ICompressSetFinishMode
18 public CMyUnknownImp 18 , ICompressGetInStreamProcessedSize
19{ 19)
20 Byte *_buf; 20 Byte *_buf;
21 CMyComPtr<ISequentialInStream> _inStream; 21 CMyComPtr<ISequentialInStream> _inStream;
22public: 22public:
23 UInt64 TotalSize; 23 UInt64 TotalSize;
24 24
25 CCopyCoder(): _buf(0), TotalSize(0) {}; 25 CCopyCoder(): _buf(NULL), TotalSize(0) {}
26 ~CCopyCoder(); 26 ~CCopyCoder();
27
28 MY_UNKNOWN_IMP5(
29 ICompressCoder,
30 ICompressSetInStream,
31 ISequentialInStream,
32 ICompressSetFinishMode,
33 ICompressGetInStreamProcessedSize)
34
35 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
36 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
37 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
38 STDMETHOD(ReleaseInStream)();
39 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
40 STDMETHOD(SetFinishMode)(UInt32 finishMode);
41 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
42}; 27};
43 28
44HRESULT CopyStream(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); 29HRESULT CopyStream(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress);
diff --git a/CPP/7zip/Compress/Deflate64Register.cpp b/CPP/7zip/Compress/Deflate64Register.cpp
index 14d20bb..7f6bae0 100644
--- a/CPP/7zip/Compress/Deflate64Register.cpp
+++ b/CPP/7zip/Compress/Deflate64Register.cpp
@@ -5,8 +5,7 @@
5#include "../Common/RegisterCodec.h" 5#include "../Common/RegisterCodec.h"
6 6
7#include "DeflateDecoder.h" 7#include "DeflateDecoder.h"
8 8#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY)
9#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY)
10#include "DeflateEncoder.h" 9#include "DeflateEncoder.h"
11#endif 10#endif
12 11
@@ -15,7 +14,7 @@ namespace NDeflate {
15 14
16REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder64()) 15REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder64())
17 16
18#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) 17#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY)
19REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder64()) 18REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder64())
20#else 19#else
21#define CreateEnc NULL 20#define CreateEnc NULL
diff --git a/CPP/7zip/Compress/DeflateConst.h b/CPP/7zip/Compress/DeflateConst.h
index cfbbf88..a73d8ff 100644
--- a/CPP/7zip/Compress/DeflateConst.h
+++ b/CPP/7zip/Compress/DeflateConst.h
@@ -1,7 +1,7 @@
1// DeflateConst.h 1// DeflateConst.h
2 2
3#ifndef __DEFLATE_CONST_H 3#ifndef ZIP7_INC_DEFLATE_CONST_H
4#define __DEFLATE_CONST_H 4#define ZIP7_INC_DEFLATE_CONST_H
5 5
6namespace NCompress { 6namespace NCompress {
7namespace NDeflate { 7namespace NDeflate {
diff --git a/CPP/7zip/Compress/DeflateDecoder.cpp b/CPP/7zip/Compress/DeflateDecoder.cpp
index e4f66b7..017b694 100644
--- a/CPP/7zip/Compress/DeflateDecoder.cpp
+++ b/CPP/7zip/Compress/DeflateDecoder.cpp
@@ -83,7 +83,7 @@ bool CCoder::ReadTables(void)
83 m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock); 83 m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock);
84 if (m_InBitStream.ExtraBitsWereRead()) 84 if (m_InBitStream.ExtraBitsWereRead())
85 return false; 85 return false;
86 UInt32 blockType = ReadBits(kBlockTypeFieldSize); 86 const UInt32 blockType = ReadBits(kBlockTypeFieldSize);
87 if (blockType > NBlockType::kDynamicHuffman) 87 if (blockType > NBlockType::kDynamicHuffman)
88 return false; 88 return false;
89 if (m_InBitStream.ExtraBitsWereRead()) 89 if (m_InBitStream.ExtraBitsWereRead())
@@ -109,9 +109,9 @@ bool CCoder::ReadTables(void)
109 } 109 }
110 else 110 else
111 { 111 {
112 unsigned numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; 112 const unsigned numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin;
113 _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin; 113 _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin;
114 unsigned numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; 114 const unsigned numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin;
115 115
116 if (!_deflate64Mode) 116 if (!_deflate64Mode)
117 if (_numDistLevels > kDistTableSize32) 117 if (_numDistLevels > kDistTableSize32)
@@ -120,7 +120,7 @@ bool CCoder::ReadTables(void)
120 Byte levelLevels[kLevelTableSize]; 120 Byte levelLevels[kLevelTableSize];
121 for (unsigned i = 0; i < kLevelTableSize; i++) 121 for (unsigned i = 0; i < kLevelTableSize; i++)
122 { 122 {
123 unsigned position = kCodeLengthAlphabetOrder[i]; 123 const unsigned position = kCodeLengthAlphabetOrder[i];
124 if (i < numLevelCodes) 124 if (i < numLevelCodes)
125 levelLevels[position] = (Byte)ReadBits(kLevelFieldSize); 125 levelLevels[position] = (Byte)ReadBits(kLevelFieldSize);
126 else 126 else
@@ -130,7 +130,7 @@ bool CCoder::ReadTables(void)
130 if (m_InBitStream.ExtraBitsWereRead()) 130 if (m_InBitStream.ExtraBitsWereRead())
131 return false; 131 return false;
132 132
133 RIF(m_LevelDecoder.Build(levelLevels)); 133 RIF(m_LevelDecoder.Build(levelLevels))
134 134
135 Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize]; 135 Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize];
136 if (!DecodeLevels(tmpLevels, numLitLenLevels + _numDistLevels)) 136 if (!DecodeLevels(tmpLevels, numLitLenLevels + _numDistLevels))
@@ -143,7 +143,7 @@ bool CCoder::ReadTables(void)
143 memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels); 143 memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels);
144 memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels); 144 memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels);
145 } 145 }
146 RIF(m_MainDecoder.Build(levels.litLenLevels)); 146 RIF(m_MainDecoder.Build(levels.litLenLevels))
147 return m_DistDecoder.Build(levels.distLevels); 147 return m_DistDecoder.Build(levels.distLevels);
148} 148}
149 149
@@ -174,7 +174,7 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro
174 if (!_keepHistory) 174 if (!_keepHistory)
175 if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32)) 175 if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32))
176 return E_OUTOFMEMORY; 176 return E_OUTOFMEMORY;
177 RINOK(InitInStream(_needInitInStream)); 177 RINOK(InitInStream(_needInitInStream))
178 m_OutWindowStream.Init(_keepHistory); 178 m_OutWindowStream.Init(_keepHistory);
179 179
180 m_FinalBlock = false; 180 m_FinalBlock = false;
@@ -185,7 +185,7 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro
185 while (_remainLen > 0 && curSize > 0) 185 while (_remainLen > 0 && curSize > 0)
186 { 186 {
187 _remainLen--; 187 _remainLen--;
188 Byte b = m_OutWindowStream.GetByte(_rep0); 188 const Byte b = m_OutWindowStream.GetByte(_rep0);
189 m_OutWindowStream.PutByte(b); 189 m_OutWindowStream.PutByte(b);
190 curSize--; 190 curSize--;
191 } 191 }
@@ -314,7 +314,7 @@ HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputPro
314} 314}
315 315
316 316
317#ifdef _NO_EXCEPTIONS 317#ifdef Z7_NO_EXCEPTIONS
318 318
319#define DEFLATE_TRY_BEGIN 319#define DEFLATE_TRY_BEGIN
320#define DEFLATE_TRY_END(res) 320#define DEFLATE_TRY_END(res)
@@ -361,7 +361,7 @@ HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo
361 if (!finishInputStream && curSize == 0) 361 if (!finishInputStream && curSize == 0)
362 break; 362 break;
363 363
364 RINOK(CodeSpec(curSize, finishInputStream, progress ? kInputProgressLimit : 0)); 364 RINOK(CodeSpec(curSize, finishInputStream, progress ? kInputProgressLimit : 0))
365 365
366 if (_remainLen == kLenIdFinished) 366 if (_remainLen == kLenIdFinished)
367 break; 367 break;
@@ -370,7 +370,7 @@ HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo
370 { 370 {
371 const UInt64 inSize = m_InBitStream.GetProcessedSize() - inStart; 371 const UInt64 inSize = m_InBitStream.GetProcessedSize() - inStart;
372 const UInt64 nowPos64 = GetOutProcessedCur(); 372 const UInt64 nowPos64 = GetOutProcessedCur();
373 RINOK(progress->SetRatioInfo(&inSize, &nowPos64)); 373 RINOK(progress->SetRatioInfo(&inSize, &nowPos64))
374 } 374 }
375 } 375 }
376 376
@@ -392,12 +392,12 @@ HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo
392} 392}
393 393
394 394
395HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 395Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
396 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 396 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
397{ 397{
398 SetInStream(inStream); 398 SetInStream(inStream);
399 SetOutStreamSize(outSize); 399 SetOutStreamSize(outSize);
400 HRESULT res = CodeReal(outStream, progress); 400 const HRESULT res = CodeReal(outStream, progress);
401 ReleaseInStream(); 401 ReleaseInStream();
402 /* 402 /*
403 if (res == S_OK) 403 if (res == S_OK)
@@ -408,21 +408,21 @@ HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStr
408} 408}
409 409
410 410
411STDMETHODIMP CCoder::SetFinishMode(UInt32 finishMode) 411Z7_COM7F_IMF(CCoder::SetFinishMode(UInt32 finishMode))
412{ 412{
413 Set_NeedFinishInput(finishMode != 0); 413 Set_NeedFinishInput(finishMode != 0);
414 return S_OK; 414 return S_OK;
415} 415}
416 416
417 417
418STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) 418Z7_COM7F_IMF(CCoder::GetInStreamProcessedSize(UInt64 *value))
419{ 419{
420 *value = m_InBitStream.GetStreamSize(); 420 *value = m_InBitStream.GetStreamSize();
421 return S_OK; 421 return S_OK;
422} 422}
423 423
424 424
425STDMETHODIMP CCoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize) 425Z7_COM7F_IMF(CCoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize))
426{ 426{
427 AlignToByte(); 427 AlignToByte();
428 UInt32 i = 0; 428 UInt32 i = 0;
@@ -439,7 +439,7 @@ STDMETHODIMP CCoder::ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *proces
439} 439}
440 440
441 441
442STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream) 442Z7_COM7F_IMF(CCoder::SetInStream(ISequentialInStream *inStream))
443{ 443{
444 m_InStreamRef = inStream; 444 m_InStreamRef = inStream;
445 m_InBitStream.SetStream(inStream); 445 m_InBitStream.SetStream(inStream);
@@ -447,7 +447,7 @@ STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream)
447} 447}
448 448
449 449
450STDMETHODIMP CCoder::ReleaseInStream() 450Z7_COM7F_IMF(CCoder::ReleaseInStream())
451{ 451{
452 m_InStreamRef.Release(); 452 m_InStreamRef.Release();
453 return S_OK; 453 return S_OK;
@@ -468,7 +468,7 @@ void CCoder::SetOutStreamSizeResume(const UInt64 *outSize)
468} 468}
469 469
470 470
471STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize) 471Z7_COM7F_IMF(CCoder::SetOutStreamSize(const UInt64 *outSize))
472{ 472{
473 /* 473 /*
474 18.06: 474 18.06:
@@ -484,9 +484,9 @@ STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize)
484} 484}
485 485
486 486
487#ifndef NO_READ_FROM_CODER 487#ifndef Z7_NO_READ_FROM_CODER
488 488
489STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) 489Z7_COM7F_IMF(CCoder::Read(void *data, UInt32 size, UInt32 *processedSize))
490{ 490{
491 HRESULT res; 491 HRESULT res;
492 492
@@ -517,7 +517,7 @@ STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
517 DEFLATE_TRY_END(res) 517 DEFLATE_TRY_END(res)
518 518
519 { 519 {
520 HRESULT res2 = Flush(); 520 const HRESULT res2 = Flush();
521 if (res2 != S_OK) 521 if (res2 != S_OK)
522 res = res2; 522 res = res2;
523 } 523 }
diff --git a/CPP/7zip/Compress/DeflateDecoder.h b/CPP/7zip/Compress/DeflateDecoder.h
index 141184e..d31f299 100644
--- a/CPP/7zip/Compress/DeflateDecoder.h
+++ b/CPP/7zip/Compress/DeflateDecoder.h
@@ -1,7 +1,7 @@
1// DeflateDecoder.h 1// DeflateDecoder.h
2 2
3#ifndef __DEFLATE_DECODER_H 3#ifndef ZIP7_INC_DEFLATE_DECODER_H
4#define __DEFLATE_DECODER_H 4#define ZIP7_INC_DEFLATE_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -26,13 +26,37 @@ class CCoder:
26 public ICompressSetFinishMode, 26 public ICompressSetFinishMode,
27 public ICompressGetInStreamProcessedSize, 27 public ICompressGetInStreamProcessedSize,
28 public ICompressReadUnusedFromInBuf, 28 public ICompressReadUnusedFromInBuf,
29 #ifndef NO_READ_FROM_CODER
30 public ICompressSetInStream, 29 public ICompressSetInStream,
31 public ICompressSetOutStreamSize, 30 public ICompressSetOutStreamSize,
31 #ifndef Z7_NO_READ_FROM_CODER
32 public ISequentialInStream, 32 public ISequentialInStream,
33 #endif 33 #endif
34 public CMyUnknownImp 34 public CMyUnknownImp
35{ 35{
36 Z7_COM_QI_BEGIN2(ICompressCoder)
37 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
38 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
39 Z7_COM_QI_ENTRY(ICompressReadUnusedFromInBuf)
40 Z7_COM_QI_ENTRY(ICompressSetInStream)
41 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
42 #ifndef Z7_NO_READ_FROM_CODER
43 Z7_COM_QI_ENTRY(ISequentialInStream)
44 #endif
45 Z7_COM_QI_END
46 Z7_COM_ADDREF_RELEASE
47
48 Z7_IFACE_COM7_IMP(ICompressCoder)
49 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
50 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
51 Z7_IFACE_COM7_IMP(ICompressReadUnusedFromInBuf)
52public:
53 Z7_IFACE_COM7_IMP(ICompressSetInStream)
54private:
55 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
56 #ifndef Z7_NO_READ_FROM_CODER
57 Z7_IFACE_COM7_IMP(ISequentialInStream)
58 #endif
59
36 CLzOutWindow m_OutWindowStream; 60 CLzOutWindow m_OutWindowStream;
37 CMyComPtr<ISequentialInStream> m_InStreamRef; 61 CMyComPtr<ISequentialInStream> m_InStreamRef;
38 NBitl::CDecoder<CInBuffer> m_InBitStream; 62 NBitl::CDecoder<CInBuffer> m_InBitStream;
@@ -89,50 +113,20 @@ public:
89 Byte ZlibFooter[4]; 113 Byte ZlibFooter[4];
90 114
91 CCoder(bool deflate64Mode); 115 CCoder(bool deflate64Mode);
92 virtual ~CCoder() {}; 116 virtual ~CCoder() {}
93 117
94 void SetNsisMode(bool nsisMode) { _deflateNSIS = nsisMode; } 118 void SetNsisMode(bool nsisMode) { _deflateNSIS = nsisMode; }
95 119
96 void Set_KeepHistory(bool keepHistory) { _keepHistory = keepHistory; } 120 void Set_KeepHistory(bool keepHistory) { _keepHistory = keepHistory; }
97 void Set_NeedFinishInput(bool needFinishInput) { _needFinishInput = needFinishInput; } 121 void Set_NeedFinishInput(bool needFinishInput) { _needFinishInput = needFinishInput; }
98 122
99 bool IsFinished() const { return _remainLen == kLenIdFinished;; } 123 bool IsFinished() const { return _remainLen == kLenIdFinished; }
100 bool IsFinalBlock() const { return m_FinalBlock; } 124 bool IsFinalBlock() const { return m_FinalBlock; }
101 125
102 HRESULT CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo *progress); 126 HRESULT CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo *progress);
103 127
104 MY_QUERYINTERFACE_BEGIN2(ICompressCoder) 128public:
105 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
106 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
107 MY_QUERYINTERFACE_ENTRY(ICompressReadUnusedFromInBuf)
108
109 #ifndef NO_READ_FROM_CODER
110 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream)
111 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
112 MY_QUERYINTERFACE_ENTRY(ISequentialInStream)
113 #endif
114
115 MY_QUERYINTERFACE_END
116 MY_ADDREF_RELEASE
117
118
119 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
120 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
121
122 STDMETHOD(SetFinishMode)(UInt32 finishMode);
123 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
124 STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize);
125
126 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
127 STDMETHOD(ReleaseInStream)();
128 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
129
130 #ifndef NO_READ_FROM_CODER
131 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
132 #endif
133
134 HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); 129 HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress);
135
136 HRESULT InitInStream(bool needInit); 130 HRESULT InitInStream(bool needInit);
137 131
138 void AlignToByte() { m_InBitStream.AlignToByte(); } 132 void AlignToByte() { m_InBitStream.AlignToByte(); }
diff --git a/CPP/7zip/Compress/DeflateEncoder.cpp b/CPP/7zip/Compress/DeflateEncoder.cpp
index 8168ec7..e277ad6 100644
--- a/CPP/7zip/Compress/DeflateEncoder.cpp
+++ b/CPP/7zip/Compress/DeflateEncoder.cpp
@@ -14,7 +14,7 @@
14#undef NO_INLINE 14#undef NO_INLINE
15 15
16#ifdef _MSC_VER 16#ifdef _MSC_VER
17#define NO_INLINE MY_NO_INLINE 17#define NO_INLINE Z7_NO_INLINE
18#else 18#else
19#define NO_INLINE 19#define NO_INLINE
20#endif 20#endif
@@ -158,34 +158,34 @@ CCoder::CCoder(bool deflate64Mode):
158HRESULT CCoder::Create() 158HRESULT CCoder::Create()
159{ 159{
160 // COM_TRY_BEGIN 160 // COM_TRY_BEGIN
161 if (m_Values == 0) 161 if (!m_Values)
162 { 162 {
163 m_Values = (CCodeValue *)MyAlloc((kMaxUncompressedBlockSize) * sizeof(CCodeValue)); 163 m_Values = (CCodeValue *)MyAlloc((kMaxUncompressedBlockSize) * sizeof(CCodeValue));
164 if (m_Values == 0) 164 if (!m_Values)
165 return E_OUTOFMEMORY; 165 return E_OUTOFMEMORY;
166 } 166 }
167 if (m_Tables == 0) 167 if (!m_Tables)
168 { 168 {
169 m_Tables = (CTables *)MyAlloc((kNumTables) * sizeof(CTables)); 169 m_Tables = (CTables *)MyAlloc((kNumTables) * sizeof(CTables));
170 if (m_Tables == 0) 170 if (!m_Tables)
171 return E_OUTOFMEMORY; 171 return E_OUTOFMEMORY;
172 } 172 }
173 173
174 if (m_IsMultiPass) 174 if (m_IsMultiPass)
175 { 175 {
176 if (m_OnePosMatchesMemory == 0) 176 if (!m_OnePosMatchesMemory)
177 { 177 {
178 m_OnePosMatchesMemory = (UInt16 *)::MidAlloc(kMatchArraySize * sizeof(UInt16)); 178 m_OnePosMatchesMemory = (UInt16 *)::MidAlloc(kMatchArraySize * sizeof(UInt16));
179 if (m_OnePosMatchesMemory == 0) 179 if (!m_OnePosMatchesMemory)
180 return E_OUTOFMEMORY; 180 return E_OUTOFMEMORY;
181 } 181 }
182 } 182 }
183 else 183 else
184 { 184 {
185 if (m_DistanceMemory == 0) 185 if (!m_DistanceMemory)
186 { 186 {
187 m_DistanceMemory = (UInt16 *)MyAlloc((kMatchMaxLen + 2) * 2 * sizeof(UInt16)); 187 m_DistanceMemory = (UInt16 *)MyAlloc((kMatchMaxLen + 2) * 2 * sizeof(UInt16));
188 if (m_DistanceMemory == 0) 188 if (!m_DistanceMemory)
189 return E_OUTOFMEMORY; 189 return E_OUTOFMEMORY;
190 m_MatchDistances = m_DistanceMemory; 190 m_MatchDistances = m_DistanceMemory;
191 } 191 }
@@ -195,10 +195,11 @@ HRESULT CCoder::Create()
195 { 195 {
196 _lzInWindow.btMode = (Byte)(_btMode ? 1 : 0); 196 _lzInWindow.btMode = (Byte)(_btMode ? 1 : 0);
197 _lzInWindow.numHashBytes = 3; 197 _lzInWindow.numHashBytes = 3;
198 _lzInWindow.numHashBytes_Min = 3;
198 if (!MatchFinder_Create(&_lzInWindow, 199 if (!MatchFinder_Create(&_lzInWindow,
199 m_Deflate64Mode ? kHistorySize64 : kHistorySize32, 200 m_Deflate64Mode ? kHistorySize64 : kHistorySize32,
200 kNumOpts + kMaxUncompressedBlockSize, 201 kNumOpts + kMaxUncompressedBlockSize,
201 m_NumFastBytes, m_MatchMaxLen - m_NumFastBytes, &g_Alloc)) 202 m_NumFastBytes, m_MatchMaxLen - m_NumFastBytes, &g_AlignedAlloc))
202 return E_OUTOFMEMORY; 203 return E_OUTOFMEMORY;
203 if (!m_OutStream.Create(1 << 20)) 204 if (!m_OutStream.Create(1 << 20))
204 return E_OUTOFMEMORY; 205 return E_OUTOFMEMORY;
@@ -239,16 +240,16 @@ HRESULT CCoder::BaseSetEncoderProperties2(const PROPID *propIDs, const PROPVARIA
239 240
240void CCoder::Free() 241void CCoder::Free()
241{ 242{
242 ::MidFree(m_OnePosMatchesMemory); m_OnePosMatchesMemory = 0; 243 ::MidFree(m_OnePosMatchesMemory); m_OnePosMatchesMemory = NULL;
243 ::MyFree(m_DistanceMemory); m_DistanceMemory = 0; 244 ::MyFree(m_DistanceMemory); m_DistanceMemory = NULL;
244 ::MyFree(m_Values); m_Values = 0; 245 ::MyFree(m_Values); m_Values = NULL;
245 ::MyFree(m_Tables); m_Tables = 0; 246 ::MyFree(m_Tables); m_Tables = NULL;
246} 247}
247 248
248CCoder::~CCoder() 249CCoder::~CCoder()
249{ 250{
250 Free(); 251 Free();
251 MatchFinder_Free(&_lzInWindow, &g_Alloc); 252 MatchFinder_Free(&_lzInWindow, &g_AlignedAlloc);
252} 253}
253 254
254NO_INLINE void CCoder::GetMatches() 255NO_INLINE void CCoder::GetMatches()
@@ -945,17 +946,19 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
945 m_CheckStatic = (m_NumPasses != 1 || m_NumDivPasses != 1); 946 m_CheckStatic = (m_NumPasses != 1 || m_NumDivPasses != 1);
946 m_IsMultiPass = (m_CheckStatic || (m_NumPasses != 1 || m_NumDivPasses != 1)); 947 m_IsMultiPass = (m_CheckStatic || (m_NumPasses != 1 || m_NumDivPasses != 1));
947 948
948 RINOK(Create()); 949 /* we can set stream mode before MatchFinder_Create
949 950 if default MatchFinder mode was not STREAM_MODE) */
950 m_ValueBlockSize = (7 << 10) + (1 << 12) * m_NumDivPasses; 951 // MatchFinder_SET_STREAM_MODE(&_lzInWindow);
951
952 UInt64 nowPos = 0;
953 952
954 CSeqInStreamWrap _seqInStream; 953 CSeqInStreamWrap _seqInStream;
955
956 _seqInStream.Init(inStream); 954 _seqInStream.Init(inStream);
955 MatchFinder_SET_STREAM(&_lzInWindow, &_seqInStream.vt)
957 956
958 _lzInWindow.stream = &_seqInStream.vt; 957 RINOK(Create())
958
959 m_ValueBlockSize = (7 << 10) + (1 << 12) * m_NumDivPasses;
960
961 UInt64 nowPos = 0;
959 962
960 MatchFinder_Init(&_lzInWindow); 963 MatchFinder_Init(&_lzInWindow);
961 m_OutStream.SetStream(outStream); 964 m_OutStream.SetStream(outStream);
@@ -978,7 +981,7 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
978 if (progress != NULL) 981 if (progress != NULL)
979 { 982 {
980 UInt64 packSize = m_OutStream.GetProcessedSize(); 983 UInt64 packSize = m_OutStream.GetProcessedSize();
981 RINOK(progress->SetRatioInfo(&nowPos, &packSize)); 984 RINOK(progress->SetRatioInfo(&nowPos, &packSize))
982 } 985 }
983 } 986 }
984 while (Inline_MatchFinder_GetNumAvailableBytes(&_lzInWindow) != 0); 987 while (Inline_MatchFinder_GetNumAvailableBytes(&_lzInWindow) != 0);
@@ -999,18 +1002,18 @@ HRESULT CCoder::BaseCode(ISequentialInStream *inStream, ISequentialOutStream *ou
999 catch(...) { return E_FAIL; } 1002 catch(...) { return E_FAIL; }
1000} 1003}
1001 1004
1002STDMETHODIMP CCOMCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 1005Z7_COM7F_IMF(CCOMCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
1003 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 1006 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
1004 { return BaseCode(inStream, outStream, inSize, outSize, progress); } 1007 { return BaseCode(inStream, outStream, inSize, outSize, progress); }
1005 1008
1006STDMETHODIMP CCOMCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 1009Z7_COM7F_IMF(CCOMCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
1007 { return BaseSetEncoderProperties2(propIDs, props, numProps); } 1010 { return BaseSetEncoderProperties2(propIDs, props, numProps); }
1008 1011
1009STDMETHODIMP CCOMCoder64::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 1012Z7_COM7F_IMF(CCOMCoder64::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
1010 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 1013 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
1011 { return BaseCode(inStream, outStream, inSize, outSize, progress); } 1014 { return BaseCode(inStream, outStream, inSize, outSize, progress); }
1012 1015
1013STDMETHODIMP CCOMCoder64::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 1016Z7_COM7F_IMF(CCOMCoder64::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
1014 { return BaseSetEncoderProperties2(propIDs, props, numProps); } 1017 { return BaseSetEncoderProperties2(propIDs, props, numProps); }
1015 1018
1016}}} 1019}}}
diff --git a/CPP/7zip/Compress/DeflateEncoder.h b/CPP/7zip/Compress/DeflateEncoder.h
index 94d250e..be181e1 100644
--- a/CPP/7zip/Compress/DeflateEncoder.h
+++ b/CPP/7zip/Compress/DeflateEncoder.h
@@ -1,7 +1,7 @@
1// DeflateEncoder.h 1// DeflateEncoder.h
2 2
3#ifndef __DEFLATE_ENCODER_H 3#ifndef ZIP7_INC_DEFLATE_ENCODER_H
4#define __DEFLATE_ENCODER_H 4#define ZIP7_INC_DEFLATE_ENCODER_H
5 5
6#include "../../../C/LzFind.h" 6#include "../../../C/LzFind.h"
7 7
@@ -176,32 +176,26 @@ public:
176}; 176};
177 177
178 178
179class CCOMCoder : 179class CCOMCoder Z7_final:
180 public ICompressCoder, 180 public ICompressCoder,
181 public ICompressSetCoderProperties, 181 public ICompressSetCoderProperties,
182 public CMyUnknownImp, 182 public CMyUnknownImp,
183 public CCoder 183 public CCoder
184{ 184{
185 Z7_IFACES_IMP_UNK_2(ICompressCoder, ICompressSetCoderProperties)
185public: 186public:
186 MY_UNKNOWN_IMP2(ICompressCoder, ICompressSetCoderProperties) 187 CCOMCoder(): CCoder(false) {}
187 CCOMCoder(): CCoder(false) {};
188 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
189 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
190 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
191}; 188};
192 189
193class CCOMCoder64 : 190class CCOMCoder64 Z7_final:
194 public ICompressCoder, 191 public ICompressCoder,
195 public ICompressSetCoderProperties, 192 public ICompressSetCoderProperties,
196 public CMyUnknownImp, 193 public CMyUnknownImp,
197 public CCoder 194 public CCoder
198{ 195{
196 Z7_IFACES_IMP_UNK_2(ICompressCoder, ICompressSetCoderProperties)
199public: 197public:
200 MY_UNKNOWN_IMP2(ICompressCoder, ICompressSetCoderProperties) 198 CCOMCoder64(): CCoder(true) {}
201 CCOMCoder64(): CCoder(true) {};
202 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
203 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
204 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
205}; 199};
206 200
207}}} 201}}}
diff --git a/CPP/7zip/Compress/DeflateRegister.cpp b/CPP/7zip/Compress/DeflateRegister.cpp
index 387be6e..eaedb84 100644
--- a/CPP/7zip/Compress/DeflateRegister.cpp
+++ b/CPP/7zip/Compress/DeflateRegister.cpp
@@ -5,7 +5,7 @@
5#include "../Common/RegisterCodec.h" 5#include "../Common/RegisterCodec.h"
6 6
7#include "DeflateDecoder.h" 7#include "DeflateDecoder.h"
8#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) 8#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY)
9#include "DeflateEncoder.h" 9#include "DeflateEncoder.h"
10#endif 10#endif
11 11
@@ -14,7 +14,7 @@ namespace NDeflate {
14 14
15REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder) 15REGISTER_CODEC_CREATE(CreateDec, NDecoder::CCOMCoder)
16 16
17#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) 17#if !defined(Z7_EXTRACT_ONLY) && !defined(Z7_DEFLATE_EXTRACT_ONLY)
18REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder) 18REGISTER_CODEC_CREATE(CreateEnc, NEncoder::CCOMCoder)
19#else 19#else
20#define CreateEnc NULL 20#define CreateEnc NULL
diff --git a/CPP/7zip/Compress/DeltaFilter.cpp b/CPP/7zip/Compress/DeltaFilter.cpp
index 3986ae4..35b77ba 100644
--- a/CPP/7zip/Compress/DeltaFilter.cpp
+++ b/CPP/7zip/Compress/DeltaFilter.cpp
@@ -23,41 +23,40 @@ struct CDelta
23}; 23};
24 24
25 25
26#ifndef EXTRACT_ONLY 26#ifndef Z7_EXTRACT_ONLY
27 27
28class CEncoder: 28class CEncoder Z7_final:
29 public ICompressFilter, 29 public ICompressFilter,
30 public ICompressSetCoderProperties, 30 public ICompressSetCoderProperties,
31 public ICompressWriteCoderProperties, 31 public ICompressWriteCoderProperties,
32 CDelta, 32 public CMyUnknownImp,
33 public CMyUnknownImp 33 CDelta
34{ 34{
35public: 35 Z7_IFACES_IMP_UNK_3(
36 MY_UNKNOWN_IMP3(ICompressFilter, ICompressSetCoderProperties, ICompressWriteCoderProperties) 36 ICompressFilter,
37 INTERFACE_ICompressFilter(;) 37 ICompressSetCoderProperties,
38 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); 38 ICompressWriteCoderProperties)
39 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream);
40}; 39};
41 40
42STDMETHODIMP CEncoder::Init() 41Z7_COM7F_IMF(CEncoder::Init())
43{ 42{
44 DeltaInit(); 43 DeltaInit();
45 return S_OK; 44 return S_OK;
46} 45}
47 46
48STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) 47Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size))
49{ 48{
50 Delta_Encode(_state, _delta, data, size); 49 Delta_Encode(_state, _delta, data, size);
51 return size; 50 return size;
52} 51}
53 52
54STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) 53Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
55{ 54{
56 UInt32 delta = _delta; 55 UInt32 delta = _delta;
57 for (UInt32 i = 0; i < numProps; i++) 56 for (UInt32 i = 0; i < numProps; i++)
58 { 57 {
59 const PROPVARIANT &prop = props[i]; 58 const PROPVARIANT &prop = props[i];
60 PROPID propID = propIDs[i]; 59 const PROPID propID = propIDs[i];
61 if (propID >= NCoderPropID::kReduceSize) 60 if (propID >= NCoderPropID::kReduceSize)
62 continue; 61 continue;
63 if (prop.vt != VT_UI4) 62 if (prop.vt != VT_UI4)
@@ -78,40 +77,39 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA
78 return S_OK; 77 return S_OK;
79} 78}
80 79
81STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) 80Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
82{ 81{
83 Byte prop = (Byte)(_delta - 1); 82 const Byte prop = (Byte)(_delta - 1);
84 return outStream->Write(&prop, 1, NULL); 83 return outStream->Write(&prop, 1, NULL);
85} 84}
86 85
87#endif 86#endif
88 87
89 88
90class CDecoder: 89class CDecoder Z7_final:
91 public ICompressFilter, 90 public ICompressFilter,
92 public ICompressSetDecoderProperties2, 91 public ICompressSetDecoderProperties2,
93 CDelta, 92 public CMyUnknownImp,
94 public CMyUnknownImp 93 CDelta
95{ 94{
96public: 95 Z7_IFACES_IMP_UNK_2(
97 MY_UNKNOWN_IMP2(ICompressFilter, ICompressSetDecoderProperties2) 96 ICompressFilter,
98 INTERFACE_ICompressFilter(;) 97 ICompressSetDecoderProperties2)
99 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
100}; 98};
101 99
102STDMETHODIMP CDecoder::Init() 100Z7_COM7F_IMF(CDecoder::Init())
103{ 101{
104 DeltaInit(); 102 DeltaInit();
105 return S_OK; 103 return S_OK;
106} 104}
107 105
108STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) 106Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
109{ 107{
110 Delta_Decode(_state, _delta, data, size); 108 Delta_Decode(_state, _delta, data, size);
111 return size; 109 return size;
112} 110}
113 111
114STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size) 112Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size))
115{ 113{
116 if (size != 1) 114 if (size != 1)
117 return E_INVALIDARG; 115 return E_INVALIDARG;
diff --git a/CPP/7zip/Compress/HuffmanDecoder.h b/CPP/7zip/Compress/HuffmanDecoder.h
index f052987..4b8169f 100644
--- a/CPP/7zip/Compress/HuffmanDecoder.h
+++ b/CPP/7zip/Compress/HuffmanDecoder.h
@@ -1,7 +1,7 @@
1// Compress/HuffmanDecoder.h 1// Compress/HuffmanDecoder.h
2 2
3#ifndef __COMPRESS_HUFFMAN_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_HUFFMAN_DECODER_H
4#define __COMPRESS_HUFFMAN_DECODER_H 4#define ZIP7_INC_COMPRESS_HUFFMAN_DECODER_H
5 5
6#include "../../Common/MyTypes.h" 6#include "../../Common/MyTypes.h"
7 7
@@ -141,7 +141,7 @@ public:
141 141
142 142
143 template <class TBitDecoder> 143 template <class TBitDecoder>
144 MY_FORCE_INLINE 144 Z7_FORCE_INLINE
145 UInt32 Decode(TBitDecoder *bitStream) const 145 UInt32 Decode(TBitDecoder *bitStream) const
146 { 146 {
147 UInt32 val = bitStream->GetValue(kNumBitsMax); 147 UInt32 val = bitStream->GetValue(kNumBitsMax);
@@ -166,7 +166,7 @@ public:
166 166
167 167
168 template <class TBitDecoder> 168 template <class TBitDecoder>
169 MY_FORCE_INLINE 169 Z7_FORCE_INLINE
170 UInt32 DecodeFull(TBitDecoder *bitStream) const 170 UInt32 DecodeFull(TBitDecoder *bitStream) const
171 { 171 {
172 UInt32 val = bitStream->GetValue(kNumBitsMax); 172 UInt32 val = bitStream->GetValue(kNumBitsMax);
diff --git a/CPP/7zip/Compress/ImplodeDecoder.cpp b/CPP/7zip/Compress/ImplodeDecoder.cpp
index 97a3cdf..12f2dce 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()
49 49
50 for (sym = 0; sym < numSymbols; sym++) 50 for (sym = 0; sym < numSymbols; sym++)
51 { 51 {
52 unsigned len = lens[sym]; 52 const unsigned len = lens[sym];
53 if (len != 0) 53 if (len != 0)
54 _symbols[--counts[len]] = (Byte)sym; 54 _symbols[--counts[len]] = (Byte)sym;
55 } 55 }
@@ -60,10 +60,10 @@ bool CHuffmanDecoder::Build(const Byte *lens, unsigned numSymbols) throw()
60 60
61UInt32 CHuffmanDecoder::Decode(CInBit *inStream) const throw() 61UInt32 CHuffmanDecoder::Decode(CInBit *inStream) const throw()
62{ 62{
63 UInt32 val = inStream->GetValue(kNumHuffmanBits); 63 const UInt32 val = inStream->GetValue(kNumHuffmanBits);
64 unsigned numBits; 64 unsigned numBits;
65 for (numBits = 1; val < _limits[numBits]; numBits++); 65 for (numBits = 1; val < _limits[numBits]; numBits++);
66 UInt32 sym = _symbols[_poses[numBits] + ((val - _limits[numBits]) >> (kNumHuffmanBits - numBits))]; 66 const UInt32 sym = _symbols[_poses[numBits] + ((val - _limits[numBits]) >> (kNumHuffmanBits - numBits))];
67 inStream->MovePos(numBits); 67 inStream->MovePos(numBits);
68 return sym; 68 return sym;
69} 69}
@@ -95,9 +95,9 @@ bool CCoder::BuildHuff(CHuffmanDecoder &decoder, unsigned numSymbols)
95 unsigned index = 0; 95 unsigned index = 0;
96 do 96 do
97 { 97 {
98 unsigned b = (unsigned)_inBitStream.ReadAlignedByte(); 98 const unsigned b = (unsigned)_inBitStream.ReadAlignedByte();
99 Byte level = (Byte)((b & 0xF) + 1); 99 const Byte level = (Byte)((b & 0xF) + 1);
100 unsigned rep = ((unsigned)b >> 4) + 1; 100 const unsigned rep = ((unsigned)b >> 4) + 1;
101 if (index + rep > numSymbols) 101 if (index + rep > numSymbols)
102 return false; 102 return false;
103 for (unsigned j = 0; j < rep; j++) 103 for (unsigned j = 0; j < rep; j++)
@@ -149,7 +149,7 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
149 if (progress && (pos - prevProgress) >= (1 << 18)) 149 if (progress && (pos - prevProgress) >= (1 << 18))
150 { 150 {
151 const UInt64 packSize = _inBitStream.GetProcessedSize(); 151 const UInt64 packSize = _inBitStream.GetProcessedSize();
152 RINOK(progress->SetRatioInfo(&packSize, &pos)); 152 RINOK(progress->SetRatioInfo(&packSize, &pos))
153 prevProgress = pos; 153 prevProgress = pos;
154 } 154 }
155 155
@@ -158,7 +158,7 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
158 Byte b; 158 Byte b;
159 if (literalsOn) 159 if (literalsOn)
160 { 160 {
161 UInt32 sym = _litDecoder.Decode(&_inBitStream); 161 const UInt32 sym = _litDecoder.Decode(&_inBitStream);
162 // if (sym >= kLitTableSize) break; 162 // if (sym >= kLitTableSize) break;
163 b = (Byte)sym; 163 b = (Byte)sym;
164 } 164 }
@@ -169,7 +169,7 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
169 } 169 }
170 else 170 else
171 { 171 {
172 UInt32 lowDistBits = _inBitStream.ReadBits(numDistDirectBits); 172 const UInt32 lowDistBits = _inBitStream.ReadBits(numDistDirectBits);
173 UInt32 dist = _distDecoder.Decode(&_inBitStream); 173 UInt32 dist = _distDecoder.Decode(&_inBitStream);
174 // if (dist >= kDistTableSize) break; 174 // if (dist >= kDistTableSize) break;
175 dist = (dist << numDistDirectBits) + lowDistBits; 175 dist = (dist << numDistDirectBits) + lowDistBits;
@@ -222,8 +222,8 @@ HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *ou
222} 222}
223 223
224 224
225STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 225Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
226 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 226 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
227{ 227{
228 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 228 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
229 // catch(const CInBufferException &e) { return e.ErrorCode; } 229 // catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -233,7 +233,7 @@ STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *o
233} 233}
234 234
235 235
236STDMETHODIMP CCoder::SetDecoderProperties2(const Byte *data, UInt32 size) 236Z7_COM7F_IMF(CCoder::SetDecoderProperties2(const Byte *data, UInt32 size))
237{ 237{
238 if (size == 0) 238 if (size == 0)
239 return E_NOTIMPL; 239 return E_NOTIMPL;
@@ -242,14 +242,14 @@ STDMETHODIMP CCoder::SetDecoderProperties2(const Byte *data, UInt32 size)
242} 242}
243 243
244 244
245STDMETHODIMP CCoder::SetFinishMode(UInt32 finishMode) 245Z7_COM7F_IMF(CCoder::SetFinishMode(UInt32 finishMode))
246{ 246{
247 _fullStreamMode = (finishMode != 0); 247 _fullStreamMode = (finishMode != 0);
248 return S_OK; 248 return S_OK;
249} 249}
250 250
251 251
252STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) 252Z7_COM7F_IMF(CCoder::GetInStreamProcessedSize(UInt64 *value))
253{ 253{
254 *value = _inBitStream.GetProcessedSize(); 254 *value = _inBitStream.GetProcessedSize();
255 return S_OK; 255 return S_OK;
diff --git a/CPP/7zip/Compress/ImplodeDecoder.h b/CPP/7zip/Compress/ImplodeDecoder.h
index a73c143..ec70045 100644
--- a/CPP/7zip/Compress/ImplodeDecoder.h
+++ b/CPP/7zip/Compress/ImplodeDecoder.h
@@ -1,7 +1,7 @@
1// ImplodeDecoder.h 1// ImplodeDecoder.h
2 2
3#ifndef __COMPRESS_IMPLODE_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_IMPLODE_DECODER_H
4#define __COMPRESS_IMPLODE_DECODER_H 4#define ZIP7_INC_COMPRESS_IMPLODE_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -32,13 +32,13 @@ public:
32}; 32};
33 33
34 34
35class CCoder: 35Z7_CLASS_IMP_NOQIB_4(
36 public ICompressCoder, 36 CCoder
37 public ICompressSetDecoderProperties2, 37 , ICompressCoder
38 public ICompressSetFinishMode, 38 , ICompressSetDecoderProperties2
39 public ICompressGetInStreamProcessedSize, 39 , ICompressSetFinishMode
40 public CMyUnknownImp 40 , ICompressGetInStreamProcessedSize
41{ 41)
42 CLzOutWindow _outWindowStream; 42 CLzOutWindow _outWindowStream;
43 CInBit _inBitStream; 43 CInBit _inBitStream;
44 44
@@ -52,19 +52,7 @@ class CCoder:
52 bool BuildHuff(CHuffmanDecoder &table, unsigned numSymbols); 52 bool BuildHuff(CHuffmanDecoder &table, unsigned numSymbols);
53 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, 53 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
54 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 54 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
55
56public: 55public:
57 MY_UNKNOWN_IMP3(
58 ICompressSetDecoderProperties2,
59 ICompressSetFinishMode,
60 ICompressGetInStreamProcessedSize)
61
62 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
63 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
64 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
65 STDMETHOD(SetFinishMode)(UInt32 finishMode);
66 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
67
68 CCoder(); 56 CCoder();
69}; 57};
70 58
diff --git a/CPP/7zip/Compress/ImplodeHuffmanDecoder.h b/CPP/7zip/Compress/ImplodeHuffmanDecoder.h
index ea25211..dcf8ac6 100644
--- a/CPP/7zip/Compress/ImplodeHuffmanDecoder.h
+++ b/CPP/7zip/Compress/ImplodeHuffmanDecoder.h
@@ -1,6 +1,6 @@
1// ImplodeHuffmanDecoder.h 1// ImplodeHuffmanDecoder.h
2 2
3#ifndef __IMPLODE_HUFFMAN_DECODER_H 3#ifndef ZIP7_INC_IMPLODE_HUFFMAN_DECODER_H
4#define __IMPLODE_HUFFMAN_DECODER_H 4#define ZIP7_INC_IMPLODE_HUFFMAN_DECODER_H
5 5
6#endif 6#endif
diff --git a/CPP/7zip/Compress/LzOutWindow.cpp b/CPP/7zip/Compress/LzOutWindow.cpp
index eb34640..aae02eb 100644
--- a/CPP/7zip/Compress/LzOutWindow.cpp
+++ b/CPP/7zip/Compress/LzOutWindow.cpp
@@ -8,7 +8,7 @@ void CLzOutWindow::Init(bool solid) throw()
8{ 8{
9 if (!solid) 9 if (!solid)
10 COutBuffer::Init(); 10 COutBuffer::Init();
11 #ifdef _NO_EXCEPTIONS 11 #ifdef Z7_NO_EXCEPTIONS
12 ErrorCode = S_OK; 12 ErrorCode = S_OK;
13 #endif 13 #endif
14} 14}
diff --git a/CPP/7zip/Compress/LzOutWindow.h b/CPP/7zip/Compress/LzOutWindow.h
index 30ac334..599b124 100644
--- a/CPP/7zip/Compress/LzOutWindow.h
+++ b/CPP/7zip/Compress/LzOutWindow.h
@@ -1,11 +1,11 @@
1// LzOutWindow.h 1// LzOutWindow.h
2 2
3#ifndef __LZ_OUT_WINDOW_H 3#ifndef ZIP7_INC_LZ_OUT_WINDOW_H
4#define __LZ_OUT_WINDOW_H 4#define ZIP7_INC_LZ_OUT_WINDOW_H
5 5
6#include "../Common/OutBuffer.h" 6#include "../Common/OutBuffer.h"
7 7
8#ifndef _NO_EXCEPTIONS 8#ifndef Z7_NO_EXCEPTIONS
9typedef COutBufferException CLzOutWindowException; 9typedef COutBufferException CLzOutWindowException;
10#endif 10#endif
11 11
diff --git a/CPP/7zip/Compress/LzfseDecoder.cpp b/CPP/7zip/Compress/LzfseDecoder.cpp
index 0eb10af..236d5bd 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)
293} 293}
294 294
295 295
296static MY_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask) 296static Z7_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask)
297{ 297{
298 for (unsigned i = 0;;) 298 for (unsigned i = 0;;)
299 { 299 {
@@ -305,7 +305,7 @@ static MY_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask)
305} 305}
306 306
307 307
308static MY_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table) 308static Z7_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table)
309{ 309{
310 for (unsigned i = 0; i < NUM_LIT_SYMBOLS; i++) 310 for (unsigned i = 0; i < NUM_LIT_SYMBOLS; i++)
311 { 311 {
@@ -440,7 +440,7 @@ typedef struct
440} CBitStream; 440} CBitStream;
441 441
442 442
443static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s, 443static Z7_FORCE_INLINE int FseInStream_Init(CBitStream *s,
444 int n, // [-7, 0], (-n == number_of_unused_bits) in last byte 444 int n, // [-7, 0], (-n == number_of_unused_bits) in last byte
445 const Byte **pbuf) 445 const Byte **pbuf)
446{ 446{
@@ -448,7 +448,7 @@ static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s,
448 s->accum = GetUi32(*pbuf); 448 s->accum = GetUi32(*pbuf);
449 if (n) 449 if (n)
450 { 450 {
451 s->numBits = n + 32; 451 s->numBits = (unsigned)(n + 32);
452 if ((s->accum >> s->numBits) != 0) 452 if ((s->accum >> s->numBits) != 0)
453 return -1; // ERROR, encoder should have zeroed the upper bits 453 return -1; // ERROR, encoder should have zeroed the upper bits
454 } 454 }
@@ -466,7 +466,7 @@ static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s,
466#define mask31(x, numBits) ((x) & (((UInt32)1 << (numBits)) - 1)) 466#define mask31(x, numBits) ((x) & (((UInt32)1 << (numBits)) - 1))
467 467
468#define FseInStream_FLUSH \ 468#define FseInStream_FLUSH \
469 { unsigned nbits = (31 - in.numBits) & -8; \ 469 { const unsigned nbits = (31 - in.numBits) & (unsigned)-8; \
470 if (nbits) { \ 470 if (nbits) { \
471 buf -= (nbits >> 3); \ 471 buf -= (nbits >> 3); \
472 if (buf < buf_check) return S_FALSE; \ 472 if (buf < buf_check) return S_FALSE; \
@@ -476,7 +476,7 @@ static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s,
476 476
477 477
478 478
479static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits) 479static Z7_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits)
480{ 480{
481 s->numBits -= numBits; 481 s->numBits -= numBits;
482 UInt32 v = s->accum >> s->numBits; 482 UInt32 v = s->accum >> s->numBits;
@@ -491,7 +491,7 @@ static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits)
491 dest = (Byte)(e >> 8); } 491 dest = (Byte)(e >> 8); }
492 492
493 493
494static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate, 494static Z7_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate,
495 const CExtraEntry *table, 495 const CExtraEntry *table,
496 CBitStream *s) 496 CBitStream *s)
497{ 497{
@@ -509,6 +509,7 @@ static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate,
509#define freqs_LIT (freqs_D + NUM_D_SYMBOLS) 509#define freqs_LIT (freqs_D + NUM_D_SYMBOLS)
510 510
511#define GET_BITS_64(v, offset, num, dest) dest = (UInt32) ((v >> (offset)) & ((1 << (num)) - 1)); 511#define GET_BITS_64(v, offset, num, dest) dest = (UInt32) ((v >> (offset)) & ((1 << (num)) - 1));
512#define GET_BITS_64_Int32(v, offset, num, dest) dest = (Int32)((v >> (offset)) & ((1 << (num)) - 1));
512#define GET_BITS_32(v, offset, num, dest) dest = (CFseState)((v >> (offset)) & ((1 << (num)) - 1)); 513#define GET_BITS_32(v, offset, num, dest) dest = (CFseState)((v >> (offset)) & ((1 << (num)) - 1));
513 514
514 515
@@ -592,22 +593,22 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
592 UInt64 v; 593 UInt64 v;
593 594
594 v = GetUi64(temp); 595 v = GetUi64(temp);
595 GET_BITS_64(v, 0, 20, numLiterals); 596 GET_BITS_64(v, 0, 20, numLiterals)
596 GET_BITS_64(v, 20, 20, litPayloadSize); 597 GET_BITS_64(v, 20, 20, litPayloadSize)
597 GET_BITS_64(v, 40, 20, numMatches); 598 GET_BITS_64(v, 40, 20, numMatches)
598 GET_BITS_64(v, 60, 3 + 1, literal_bits); // (NumberOfUsedBits - 1) 599 GET_BITS_64_Int32(v, 60, 3 + 1, literal_bits) // (NumberOfUsedBits - 1)
599 literal_bits -= 7; // (-NumberOfUnusedBits) 600 literal_bits -= 7; // (-NumberOfUnusedBits)
600 if (literal_bits > 0) 601 if (literal_bits > 0)
601 return S_FALSE; 602 return S_FALSE;
602 // GET_BITS_64(v, 63, 1, unused); 603 // GET_BITS_64(v, 63, 1, unused);
603 604
604 v = GetUi64(temp + 8); 605 v = GetUi64(temp + 8);
605 GET_BITS_64(v, 0, 10, lit_state_0); 606 GET_BITS_64(v, 0, 10, lit_state_0)
606 GET_BITS_64(v, 10, 10, lit_state_1); 607 GET_BITS_64(v, 10, 10, lit_state_1)
607 GET_BITS_64(v, 20, 10, lit_state_2); 608 GET_BITS_64(v, 20, 10, lit_state_2)
608 GET_BITS_64(v, 30, 10, lit_state_3); 609 GET_BITS_64(v, 30, 10, lit_state_3)
609 GET_BITS_64(v, 40, 20, lmdPayloadSize); 610 GET_BITS_64(v, 40, 20, lmdPayloadSize)
610 GET_BITS_64(v, 60, 3 + 1, lmd_bits); 611 GET_BITS_64_Int32(v, 60, 3 + 1, lmd_bits)
611 lmd_bits -= 7; 612 lmd_bits -= 7;
612 if (lmd_bits > 0) 613 if (lmd_bits > 0)
613 return S_FALSE; 614 return S_FALSE;
@@ -618,10 +619,10 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
618 // correspond to a field in the uncompressed header version, 619 // correspond to a field in the uncompressed header version,
619 // but is required; we wouldn't know the size of the 620 // but is required; we wouldn't know the size of the
620 // compresssed header otherwise. 621 // compresssed header otherwise.
621 GET_BITS_32(v32, 0, 10, l_state); 622 GET_BITS_32(v32, 0, 10, l_state)
622 GET_BITS_32(v32, 10, 10, m_state); 623 GET_BITS_32(v32, 10, 10, m_state)
623 GET_BITS_32(v32, 20, 10 + 2, d_state); 624 GET_BITS_32(v32, 20, 10 + 2, d_state)
624 // GET_BITS_64(v, 62, 2, unused); 625 // GET_BITS_64(v, 62, 2, unused)
625 626
626 headerSize = GetUi32(temp + 16); 627 headerSize = GetUi32(temp + 16);
627 if (headerSize <= kPreHeaderSize + kHeaderSize) 628 if (headerSize <= kPreHeaderSize + kHeaderSize)
@@ -726,11 +727,11 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
726 for (; lit < lit_limit; lit += 4) 727 for (; lit < lit_limit; lit += 4)
727 { 728 {
728 FseInStream_FLUSH 729 FseInStream_FLUSH
729 DECODE_LIT (lit[0], lit_state_0); 730 DECODE_LIT (lit[0], lit_state_0)
730 DECODE_LIT (lit[1], lit_state_1); 731 DECODE_LIT (lit[1], lit_state_1)
731 FseInStream_FLUSH 732 FseInStream_FLUSH
732 DECODE_LIT (lit[2], lit_state_2); 733 DECODE_LIT (lit[2], lit_state_2)
733 DECODE_LIT (lit[3], lit_state_3); 734 DECODE_LIT (lit[3], lit_state_3)
734 } 735 }
735 736
736 if ((buf_start - buf) * 8 != (int)in.numBits) 737 if ((buf_start - buf) * 8 != (int)in.numBits)
@@ -821,7 +822,7 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
821 822
822 // LZFSE encoder writes 8 additional zero bytes before LMD payload 823 // LZFSE encoder writes 8 additional zero bytes before LMD payload
823 // We test it: 824 // We test it:
824 if ((buf - buf_start) * 8 + in.numBits != 64) 825 if ((size_t)(buf - buf_start) * 8 + in.numBits != 64)
825 return S_FALSE; 826 return S_FALSE;
826 if (GetUi64(buf_start) != 0) 827 if (GetUi64(buf_start) != 0)
827 return S_FALSE; 828 return S_FALSE;
@@ -830,7 +831,7 @@ HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
830} 831}
831 832
832 833
833STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, 834HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
834 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 835 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
835{ 836{
836 PRF(printf("\n\nLzfseDecoder %7u %7u\n", (unsigned)*outSize, (unsigned)*inSize)); 837 PRF(printf("\n\nLzfseDecoder %7u %7u\n", (unsigned)*outSize, (unsigned)*inSize));
@@ -853,12 +854,14 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr
853 854
854 if (LzvnMode) 855 if (LzvnMode)
855 { 856 {
857 if (!outSize || !inSize)
858 return E_NOTIMPL;
856 const UInt64 unpackSize = *outSize; 859 const UInt64 unpackSize = *outSize;
857 const UInt64 packSize = *inSize; 860 const UInt64 packSize = *inSize;
858 if (unpackSize > (UInt32)(Int32)-1 861 if (unpackSize > (UInt32)(Int32)-1
859 || packSize > (UInt32)(Int32)-1) 862 || packSize > (UInt32)(Int32)-1)
860 return S_FALSE; 863 return S_FALSE;
861 RINOK(DecodeLzvn((UInt32)unpackSize, (UInt32)packSize)); 864 RINOK(DecodeLzvn((UInt32)unpackSize, (UInt32)packSize))
862 } 865 }
863 else 866 else
864 for (;;) 867 for (;;)
@@ -868,12 +871,11 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr
868 871
869 if (progress && ((pos - prevOut) >= (1 << 22) || (packPos - prevIn) >= (1 << 22))) 872 if (progress && ((pos - prevOut) >= (1 << 22) || (packPos - prevIn) >= (1 << 22)))
870 { 873 {
871 RINOK(progress->SetRatioInfo(&packPos, &pos)); 874 RINOK(progress->SetRatioInfo(&packPos, &pos))
872 prevIn = packPos; 875 prevIn = packPos;
873 prevOut = pos; 876 prevOut = pos;
874 } 877 }
875 878
876 const UInt64 rem = *outSize - pos;
877 UInt32 v; 879 UInt32 v;
878 RINOK(GetUInt32(v)) 880 RINOK(GetUInt32(v))
879 if ((v & 0xFFFFFF) != 0x787662) // bvx 881 if ((v & 0xFFFFFF) != 0x787662) // bvx
@@ -884,12 +886,15 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr
884 break; 886 break;
885 887
886 UInt32 unpackSize; 888 UInt32 unpackSize;
887 RINOK(GetUInt32(unpackSize)); 889 RINOK(GetUInt32(unpackSize))
888 890
889 UInt32 cur = unpackSize; 891 UInt32 cur = unpackSize;
890 if (cur > rem) 892 if (outSize)
891 cur = (UInt32)rem; 893 {
892 894 const UInt64 rem = *outSize - pos;
895 if (cur > rem)
896 cur = (UInt32)rem;
897 }
893 unpackSize -= cur; 898 unpackSize -= cur;
894 899
895 HRESULT res; 900 HRESULT res;
@@ -917,15 +922,15 @@ STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStr
917 coderReleaser.NeedFlush = false; 922 coderReleaser.NeedFlush = false;
918 HRESULT res = m_OutWindowStream.Flush(); 923 HRESULT res = m_OutWindowStream.Flush();
919 if (res == S_OK) 924 if (res == S_OK)
920 if (*inSize != m_InStream.GetProcessedSize() 925 if ((inSize && *inSize != m_InStream.GetProcessedSize())
921 || *outSize != m_OutWindowStream.GetProcessedSize()) 926 || (outSize && *outSize != m_OutWindowStream.GetProcessedSize()))
922 res = S_FALSE; 927 res = S_FALSE;
923 return res; 928 return res;
924} 929}
925 930
926 931
927STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 932Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
928 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 933 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
929{ 934{
930 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 935 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
931 catch(const CInBufferException &e) { return e.ErrorCode; } 936 catch(const CInBufferException &e) { return e.ErrorCode; }
diff --git a/CPP/7zip/Compress/LzfseDecoder.h b/CPP/7zip/Compress/LzfseDecoder.h
index 401e0ba..b7227dc 100644
--- a/CPP/7zip/Compress/LzfseDecoder.h
+++ b/CPP/7zip/Compress/LzfseDecoder.h
@@ -1,7 +1,7 @@
1// LzfseDecoder.h 1// LzfseDecoder.h
2 2
3#ifndef __LZFSE_DECODER_H 3#ifndef ZIP7_INC_LZFSE_DECODER_H
4#define __LZFSE_DECODER_H 4#define ZIP7_INC_LZFSE_DECODER_H
5 5
6#include "../../Common/MyBuffer.h" 6#include "../../Common/MyBuffer.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
@@ -15,10 +15,10 @@
15namespace NCompress { 15namespace NCompress {
16namespace NLzfse { 16namespace NLzfse {
17 17
18class CDecoder: 18Z7_CLASS_IMP_NOQIB_1(
19 public ICompressCoder, 19 CDecoder
20 public CMyUnknownImp 20 , ICompressCoder
21{ 21)
22 CLzOutWindow m_OutWindowStream; 22 CLzOutWindow m_OutWindowStream;
23 CInBuffer m_InStream; 23 CInBuffer m_InStream;
24 CByteBuffer _literals; 24 CByteBuffer _literals;
@@ -44,11 +44,10 @@ class CDecoder:
44 HRESULT DecodeLzvn(UInt32 unpackSize, UInt32 packSize); 44 HRESULT DecodeLzvn(UInt32 unpackSize, UInt32 packSize);
45 HRESULT DecodeLzfse(UInt32 unpackSize, Byte version); 45 HRESULT DecodeLzfse(UInt32 unpackSize, Byte version);
46 46
47 STDMETHOD(CodeReal)(ISequentialInStream *inStream, ISequentialOutStream *outStream, 47 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
48 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 48 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
49public: 49public:
50 bool LzvnMode; 50 bool LzvnMode;
51 MY_UNKNOWN_IMP
52 51
53 CDecoder(): 52 CDecoder():
54 LzvnMode(false) 53 LzvnMode(false)
@@ -57,9 +56,6 @@ public:
57 // sizes are checked in Code() 56 // sizes are checked in Code()
58 // UInt64 GetInputProcessedSize() const { return m_InStream.GetProcessedSize(); } 57 // UInt64 GetInputProcessedSize() const { return m_InStream.GetProcessedSize(); }
59 // UInt64 GetOutputProcessedSize() const { return m_OutWindowStream.GetProcessedSize(); } 58 // UInt64 GetOutputProcessedSize() const { return m_OutWindowStream.GetProcessedSize(); }
60
61 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize,
62 const UInt64 *outSize, ICompressProgressInfo *progress);
63}; 59};
64 60
65}} 61}}
diff --git a/CPP/7zip/Compress/LzhDecoder.cpp b/CPP/7zip/Compress/LzhDecoder.cpp
index b0aa753..064bc55 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)
15 UInt32 sum = 0; 15 UInt32 sum = 0;
16 for (unsigned i = 0; i < num; i++) 16 for (unsigned i = 0; i < num; i++)
17 { 17 {
18 unsigned len = lens[i]; 18 const unsigned len = lens[i];
19 if (len != 0) 19 if (len != 0)
20 sum += ((UInt32)1 << (NUM_CODE_BITS - len)); 20 sum += ((UInt32)1 << (NUM_CODE_BITS - len));
21 } 21 }
@@ -26,11 +26,12 @@ bool CCoder::ReadTP(unsigned num, unsigned numBits, int spec)
26{ 26{
27 _symbolT = -1; 27 _symbolT = -1;
28 28
29 UInt32 n = _inBitStream.ReadBits(numBits); 29 const UInt32 n = _inBitStream.ReadBits(numBits);
30 if (n == 0) 30 if (n == 0)
31 { 31 {
32 _symbolT = _inBitStream.ReadBits(numBits); 32 const unsigned s = _inBitStream.ReadBits(numBits);
33 return ((unsigned)_symbolT < num); 33 _symbolT = (int)s;
34 return (s < num);
34 } 35 }
35 36
36 if (n > num) 37 if (n > num)
@@ -46,7 +47,7 @@ bool CCoder::ReadTP(unsigned num, unsigned numBits, int spec)
46 47
47 do 48 do
48 { 49 {
49 UInt32 val = _inBitStream.GetValue(16); 50 const UInt32 val = _inBitStream.GetValue(16);
50 unsigned c = val >> 13; 51 unsigned c = val >> 13;
51 52
52 if (c == 7) 53 if (c == 7)
@@ -85,8 +86,9 @@ bool CCoder::ReadC()
85 86
86 if (n == 0) 87 if (n == 0)
87 { 88 {
88 _symbolC = _inBitStream.ReadBits(NUM_C_BITS); 89 const unsigned s = _inBitStream.ReadBits(NUM_C_BITS);
89 return ((unsigned)_symbolC < NC); 90 _symbolC = (int)s;
91 return (s < NC);
90 } 92 }
91 93
92 if (n > NC) 94 if (n > NC)
@@ -135,7 +137,7 @@ bool CCoder::ReadC()
135 137
136HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress) 138HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
137{ 139{
138 unsigned pbit = (DictSize <= (1 << 14) ? 4 : 5); 140 const unsigned pbit = (DictSize <= (1 << 14) ? 4 : 5);
139 141
140 UInt32 blockSize = 0; 142 UInt32 blockSize = 0;
141 143
@@ -148,9 +150,9 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
148 150
149 if (progress) 151 if (progress)
150 { 152 {
151 UInt64 packSize = _inBitStream.GetProcessedSize(); 153 const UInt64 packSize = _inBitStream.GetProcessedSize();
152 UInt64 pos = _outWindow.GetProcessedSize(); 154 const UInt64 pos = _outWindow.GetProcessedSize();
153 RINOK(progress->SetRatioInfo(&packSize, &pos)); 155 RINOK(progress->SetRatioInfo(&packSize, &pos))
154 } 156 }
155 157
156 blockSize = _inBitStream.ReadBits(16); 158 blockSize = _inBitStream.ReadBits(16);
@@ -217,8 +219,8 @@ HRESULT CCoder::CodeReal(UInt64 rem, ICompressProgressInfo *progress)
217} 219}
218 220
219 221
220STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 222Z7_COM7F_IMF(CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
221 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 223 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
222{ 224{
223 try 225 try
224 { 226 {
@@ -237,7 +239,7 @@ STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *o
237 239
238 CCoderReleaser coderReleaser(this); 240 CCoderReleaser coderReleaser(this);
239 241
240 RINOK(CodeReal(*outSize, progress)); 242 RINOK(CodeReal(*outSize, progress))
241 243
242 coderReleaser.Disable(); 244 coderReleaser.Disable();
243 return _outWindow.Flush(); 245 return _outWindow.Flush();
diff --git a/CPP/7zip/Compress/LzhDecoder.h b/CPP/7zip/Compress/LzhDecoder.h
index 5e13d82..491212e 100644
--- a/CPP/7zip/Compress/LzhDecoder.h
+++ b/CPP/7zip/Compress/LzhDecoder.h
@@ -1,7 +1,7 @@
1// LzhDecoder.h 1// LzhDecoder.h
2 2
3#ifndef __COMPRESS_LZH_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_LZH_DECODER_H
4#define __COMPRESS_LZH_DECODER_H 4#define ZIP7_INC_COMPRESS_LZH_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -26,10 +26,10 @@ const unsigned NT = (NUM_CODE_BITS + 3);
26const unsigned NP = (NUM_DIC_BITS_MAX + 1); 26const unsigned NP = (NUM_DIC_BITS_MAX + 1);
27const unsigned NPT = NP; // Max(NT, NP) 27const unsigned NPT = NP; // Max(NT, NP)
28 28
29class CCoder: 29Z7_CLASS_IMP_NOQIB_1(
30 public ICompressCoder, 30 CCoder
31 public CMyUnknownImp 31 , ICompressCoder
32{ 32)
33 CLzOutWindow _outWindow; 33 CLzOutWindow _outWindow;
34 NBitm::CDecoder<CInBuffer> _inBitStream; 34 NBitm::CDecoder<CInBuffer> _inBitStream;
35 35
@@ -54,14 +54,9 @@ class CCoder:
54 54
55 HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress); 55 HRESULT CodeReal(UInt64 outSize, ICompressProgressInfo *progress);
56public: 56public:
57 MY_UNKNOWN_IMP
58
59 UInt32 DictSize; 57 UInt32 DictSize;
60 bool FinishMode; 58 bool FinishMode;
61 59
62 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
63 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
64
65 void SetDictSize(unsigned dictSize) { DictSize = dictSize; } 60 void SetDictSize(unsigned dictSize) { DictSize = dictSize; }
66 61
67 CCoder(): DictSize(1 << 16), FinishMode(false) {} 62 CCoder(): DictSize(1 << 16), FinishMode(false) {}
diff --git a/CPP/7zip/Compress/Lzma2Decoder.cpp b/CPP/7zip/Compress/Lzma2Decoder.cpp
index 653fe2d..eab7800 100644
--- a/CPP/7zip/Compress/Lzma2Decoder.cpp
+++ b/CPP/7zip/Compress/Lzma2Decoder.cpp
@@ -21,7 +21,7 @@ CDecoder::CDecoder():
21 , _finishMode(false) 21 , _finishMode(false)
22 , _inBufSize(1 << 20) 22 , _inBufSize(1 << 20)
23 , _outStep(1 << 20) 23 , _outStep(1 << 20)
24 #ifndef _7ZIP_ST 24 #ifndef Z7_ST
25 , _tryMt(1) 25 , _tryMt(1)
26 , _numThreads(1) 26 , _numThreads(1)
27 , _memUsage((UInt64)(sizeof(size_t)) << 28) 27 , _memUsage((UInt64)(sizeof(size_t)) << 28)
@@ -34,10 +34,10 @@ CDecoder::~CDecoder()
34 Lzma2DecMt_Destroy(_dec); 34 Lzma2DecMt_Destroy(_dec);
35} 35}
36 36
37STDMETHODIMP CDecoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSize = size; return S_OK; } 37Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 , UInt32 size)) { _inBufSize = size; return S_OK; }
38STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _outStep = size; return S_OK; } 38Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32 , UInt32 size)) { _outStep = size; return S_OK; }
39 39
40STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) 40Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size))
41{ 41{
42 if (size != 1) 42 if (size != 1)
43 return E_NOTIMPL; 43 return E_NOTIMPL;
@@ -48,7 +48,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size)
48} 48}
49 49
50 50
51STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 51Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
52{ 52{
53 _finishMode = (finishMode != 0); 53 _finishMode = (finishMode != 0);
54 return S_OK; 54 return S_OK;
@@ -56,7 +56,7 @@ STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode)
56 56
57 57
58 58
59#ifndef _7ZIP_ST 59#ifndef Z7_ST
60 60
61static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize) 61static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize)
62{ 62{
@@ -81,8 +81,8 @@ static UInt64 Get_ExpectedBlockSize_From_Dict(UInt32 dictSize)
81#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ 81#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \
82 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; 82 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes;
83 83
84STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 84Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
85 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 85 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
86{ 86{
87 _inProcessed = 0; 87 _inProcessed = 0;
88 88
@@ -102,24 +102,24 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
102 props.inBufSize_ST = _inBufSize; 102 props.inBufSize_ST = _inBufSize;
103 props.outStep_ST = _outStep; 103 props.outStep_ST = _outStep;
104 104
105 #ifndef _7ZIP_ST 105 #ifndef Z7_ST
106 { 106 {
107 props.numThreads = 1; 107 props.numThreads = 1;
108 UInt32 numThreads = _numThreads; 108 UInt32 numThreads = _numThreads;
109 109
110 if (_tryMt && numThreads >= 1) 110 if (_tryMt && numThreads >= 1)
111 { 111 {
112 UInt64 useLimit = _memUsage; 112 const UInt64 useLimit = _memUsage;
113 UInt32 dictSize = LZMA2_DIC_SIZE_FROM_PROP_FULL(_prop); 113 const UInt32 dictSize = LZMA2_DIC_SIZE_FROM_PROP_FULL(_prop);
114 UInt64 expectedBlockSize64 = Get_ExpectedBlockSize_From_Dict(dictSize); 114 const UInt64 expectedBlockSize64 = Get_ExpectedBlockSize_From_Dict(dictSize);
115 size_t expectedBlockSize = (size_t)expectedBlockSize64; 115 const size_t expectedBlockSize = (size_t)expectedBlockSize64;
116 size_t inBlockMax = expectedBlockSize + expectedBlockSize / 16; 116 const size_t inBlockMax = expectedBlockSize + expectedBlockSize / 16;
117 if (expectedBlockSize == expectedBlockSize64 && inBlockMax >= expectedBlockSize) 117 if (expectedBlockSize == expectedBlockSize64 && inBlockMax >= expectedBlockSize)
118 { 118 {
119 props.outBlockMax = expectedBlockSize; 119 props.outBlockMax = expectedBlockSize;
120 props.inBlockMax = inBlockMax; 120 props.inBlockMax = inBlockMax;
121 const size_t kOverheadSize = props.inBufSize_MT + (1 << 16); 121 const size_t kOverheadSize = props.inBufSize_MT + (1 << 16);
122 UInt64 okThreads = useLimit / (props.outBlockMax + props.inBlockMax + kOverheadSize); 122 const UInt64 okThreads = useLimit / (props.outBlockMax + props.inBlockMax + kOverheadSize);
123 if (numThreads > okThreads) 123 if (numThreads > okThreads)
124 numThreads = (UInt32)okThreads; 124 numThreads = (UInt32)okThreads;
125 if (numThreads == 0) 125 if (numThreads == 0)
@@ -143,7 +143,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
143 UInt64 inProcessed = 0; 143 UInt64 inProcessed = 0;
144 int isMT = False; 144 int isMT = False;
145 145
146 #ifndef _7ZIP_ST 146 #ifndef Z7_ST
147 isMT = _tryMt; 147 isMT = _tryMt;
148 #endif 148 #endif
149 149
@@ -162,7 +162,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
162 */ 162 */
163 163
164 164
165 #ifndef _7ZIP_ST 165 #ifndef Z7_ST
166 /* we reset _tryMt, only if p->props.numThreads was changed */ 166 /* we reset _tryMt, only if p->props.numThreads was changed */
167 if (props.numThreads > 1) 167 if (props.numThreads > 1)
168 _tryMt = isMT; 168 _tryMt = isMT;
@@ -186,22 +186,22 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
186} 186}
187 187
188 188
189STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 189Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
190{ 190{
191 *value = _inProcessed; 191 *value = _inProcessed;
192 return S_OK; 192 return S_OK;
193} 193}
194 194
195 195
196#ifndef _7ZIP_ST 196#ifndef Z7_ST
197 197
198STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) 198Z7_COM7F_IMF(CDecoder::SetNumberOfThreads(UInt32 numThreads))
199{ 199{
200 _numThreads = numThreads; 200 _numThreads = numThreads;
201 return S_OK; 201 return S_OK;
202} 202}
203 203
204STDMETHODIMP CDecoder::SetMemLimit(UInt64 memUsage) 204Z7_COM7F_IMF(CDecoder::SetMemLimit(UInt64 memUsage))
205{ 205{
206 _memUsage = memUsage; 206 _memUsage = memUsage;
207 return S_OK; 207 return S_OK;
@@ -210,9 +210,9 @@ STDMETHODIMP CDecoder::SetMemLimit(UInt64 memUsage)
210#endif 210#endif
211 211
212 212
213#ifndef NO_READ_FROM_CODER 213#ifndef Z7_NO_READ_FROM_CODER
214 214
215STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 215Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize))
216{ 216{
217 CLzma2DecMtProps props; 217 CLzma2DecMtProps props;
218 Lzma2DecMtProps_Init(&props); 218 Lzma2DecMtProps_Init(&props);
@@ -230,7 +230,7 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
230 230
231 _inWrap.Init(_inStream); 231 _inWrap.Init(_inStream);
232 232
233 SRes res = Lzma2DecMt_Init(_dec, _prop, &props, outSize, _finishMode, &_inWrap.vt); 233 const SRes res = Lzma2DecMt_Init(_dec, _prop, &props, outSize, _finishMode, &_inWrap.vt);
234 234
235 if (res != SZ_OK) 235 if (res != SZ_OK)
236 return SResToHRESULT(res); 236 return SResToHRESULT(res);
@@ -238,11 +238,13 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
238} 238}
239 239
240 240
241STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; } 241Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream))
242STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; } 242 { _inStream = inStream; return S_OK; }
243Z7_COM7F_IMF(CDecoder::ReleaseInStream())
244 { _inStream.Release(); return S_OK; }
243 245
244 246
245STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 247Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
246{ 248{
247 if (processedSize) 249 if (processedSize)
248 *processedSize = 0; 250 *processedSize = 0;
@@ -250,7 +252,7 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
250 size_t size2 = size; 252 size_t size2 = size;
251 UInt64 inProcessed = 0; 253 UInt64 inProcessed = 0;
252 254
253 SRes res = Lzma2DecMt_Read(_dec, (Byte *)data, &size2, &inProcessed); 255 const SRes res = Lzma2DecMt_Read(_dec, (Byte *)data, &size2, &inProcessed);
254 256
255 _inProcessed += inProcessed; 257 _inProcessed += inProcessed;
256 if (processedSize) 258 if (processedSize)
diff --git a/CPP/7zip/Compress/Lzma2Decoder.h b/CPP/7zip/Compress/Lzma2Decoder.h
index e141488..7ca717e 100644
--- a/CPP/7zip/Compress/Lzma2Decoder.h
+++ b/CPP/7zip/Compress/Lzma2Decoder.h
@@ -1,7 +1,7 @@
1// Lzma2Decoder.h 1// Lzma2Decoder.h
2 2
3#ifndef __LZMA2_DECODER_H 3#ifndef ZIP7_INC_LZMA2_DECODER_H
4#define __LZMA2_DECODER_H 4#define ZIP7_INC_LZMA2_DECODER_H
5 5
6#include "../../../C/Lzma2DecMt.h" 6#include "../../../C/Lzma2DecMt.h"
7 7
@@ -10,26 +10,55 @@
10namespace NCompress { 10namespace NCompress {
11namespace NLzma2 { 11namespace NLzma2 {
12 12
13class CDecoder: 13class CDecoder Z7_final:
14 public ICompressCoder, 14 public ICompressCoder,
15 public ICompressSetDecoderProperties2, 15 public ICompressSetDecoderProperties2,
16 public ICompressSetFinishMode, 16 public ICompressSetFinishMode,
17 public ICompressGetInStreamProcessedSize, 17 public ICompressGetInStreamProcessedSize,
18 public ICompressSetBufSize, 18 public ICompressSetBufSize,
19 19 #ifndef Z7_NO_READ_FROM_CODER
20 #ifndef NO_READ_FROM_CODER
21 public ICompressSetInStream, 20 public ICompressSetInStream,
22 public ICompressSetOutStreamSize, 21 public ICompressSetOutStreamSize,
23 public ISequentialInStream, 22 public ISequentialInStream,
24 #endif 23 #endif
25 24 #ifndef Z7_ST
26 #ifndef _7ZIP_ST
27 public ICompressSetCoderMt, 25 public ICompressSetCoderMt,
28 public ICompressSetMemLimit, 26 public ICompressSetMemLimit,
29 #endif 27 #endif
30
31 public CMyUnknownImp 28 public CMyUnknownImp
32{ 29{
30 Z7_COM_QI_BEGIN2(ICompressCoder)
31 Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2)
32 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
33 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
34 Z7_COM_QI_ENTRY(ICompressSetBufSize)
35 #ifndef Z7_NO_READ_FROM_CODER
36 Z7_COM_QI_ENTRY(ICompressSetInStream)
37 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
38 Z7_COM_QI_ENTRY(ISequentialInStream)
39 #endif
40 #ifndef Z7_ST
41 Z7_COM_QI_ENTRY(ICompressSetCoderMt)
42 Z7_COM_QI_ENTRY(ICompressSetMemLimit)
43 #endif
44 Z7_COM_QI_END
45 Z7_COM_ADDREF_RELEASE
46
47 Z7_IFACE_COM7_IMP(ICompressCoder)
48 Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
49 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
50 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
51 Z7_IFACE_COM7_IMP(ICompressSetBufSize)
52 #ifndef Z7_NO_READ_FROM_CODER
53 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
54 Z7_IFACE_COM7_IMP(ICompressSetInStream)
55 Z7_IFACE_COM7_IMP(ISequentialInStream)
56 #endif
57 #ifndef Z7_ST
58 Z7_IFACE_COM7_IMP(ICompressSetCoderMt)
59 Z7_IFACE_COM7_IMP(ICompressSetMemLimit)
60 #endif
61
33 CLzma2DecMtHandle _dec; 62 CLzma2DecMtHandle _dec;
34 UInt64 _inProcessed; 63 UInt64 _inProcessed;
35 Byte _prop; 64 Byte _prop;
@@ -37,58 +66,20 @@ class CDecoder:
37 UInt32 _inBufSize; 66 UInt32 _inBufSize;
38 UInt32 _outStep; 67 UInt32 _outStep;
39 68
40public: 69 #ifndef Z7_ST
41 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
42 MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2)
43 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
44 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
45 MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize)
46
47 #ifndef NO_READ_FROM_CODER
48 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream)
49 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
50 MY_QUERYINTERFACE_ENTRY(ISequentialInStream)
51 #endif
52
53 #ifndef _7ZIP_ST
54 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt)
55 MY_QUERYINTERFACE_ENTRY(ICompressSetMemLimit)
56 #endif
57
58 MY_QUERYINTERFACE_END
59 MY_ADDREF_RELEASE
60
61 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
62 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
63 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
64 STDMETHOD(SetFinishMode)(UInt32 finishMode);
65 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
66 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size);
67 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size);
68
69 #ifndef _7ZIP_ST
70private:
71 int _tryMt; 70 int _tryMt;
72 UInt32 _numThreads; 71 UInt32 _numThreads;
73 UInt64 _memUsage; 72 UInt64 _memUsage;
74public: 73 #endif
75 STDMETHOD(SetNumberOfThreads)(UInt32 numThreads);
76 STDMETHOD(SetMemLimit)(UInt64 memUsage);
77 #endif
78 74
79 #ifndef NO_READ_FROM_CODER 75 #ifndef Z7_NO_READ_FROM_CODER
80private:
81 CMyComPtr<ISequentialInStream> _inStream; 76 CMyComPtr<ISequentialInStream> _inStream;
82 CSeqInStreamWrap _inWrap; 77 CSeqInStreamWrap _inWrap;
83public: 78 #endif
84 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
85 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
86 STDMETHOD(ReleaseInStream)();
87 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
88 #endif
89 79
80public:
90 CDecoder(); 81 CDecoder();
91 virtual ~CDecoder(); 82 ~CDecoder();
92}; 83};
93 84
94}} 85}}
diff --git a/CPP/7zip/Compress/Lzma2Encoder.cpp b/CPP/7zip/Compress/Lzma2Encoder.cpp
index 6a5d679..0dc7e23 100644
--- a/CPP/7zip/Compress/Lzma2Encoder.cpp
+++ b/CPP/7zip/Compress/Lzma2Encoder.cpp
@@ -55,33 +55,33 @@ HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzm
55 lzma2Props.numTotalThreads = (int)(prop.ulVal); 55 lzma2Props.numTotalThreads = (int)(prop.ulVal);
56 break; 56 break;
57 default: 57 default:
58 RINOK(NLzma::SetLzmaProp(propID, prop, lzma2Props.lzmaProps)); 58 RINOK(NLzma::SetLzmaProp(propID, prop, lzma2Props.lzmaProps))
59 } 59 }
60 return S_OK; 60 return S_OK;
61} 61}
62 62
63 63
64STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, 64Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs,
65 const PROPVARIANT *coderProps, UInt32 numProps) 65 const PROPVARIANT *coderProps, UInt32 numProps))
66{ 66{
67 CLzma2EncProps lzma2Props; 67 CLzma2EncProps lzma2Props;
68 Lzma2EncProps_Init(&lzma2Props); 68 Lzma2EncProps_Init(&lzma2Props);
69 69
70 for (UInt32 i = 0; i < numProps; i++) 70 for (UInt32 i = 0; i < numProps; i++)
71 { 71 {
72 RINOK(SetLzma2Prop(propIDs[i], coderProps[i], lzma2Props)); 72 RINOK(SetLzma2Prop(propIDs[i], coderProps[i], lzma2Props))
73 } 73 }
74 return SResToHRESULT(Lzma2Enc_SetProps(_encoder, &lzma2Props)); 74 return SResToHRESULT(Lzma2Enc_SetProps(_encoder, &lzma2Props));
75} 75}
76 76
77 77
78STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, 78Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
79 const PROPVARIANT *coderProps, UInt32 numProps) 79 const PROPVARIANT *coderProps, UInt32 numProps))
80{ 80{
81 for (UInt32 i = 0; i < numProps; i++) 81 for (UInt32 i = 0; i < numProps; i++)
82 { 82 {
83 const PROPVARIANT &prop = coderProps[i]; 83 const PROPVARIANT &prop = coderProps[i];
84 PROPID propID = propIDs[i]; 84 const PROPID propID = propIDs[i];
85 if (propID == NCoderPropID::kExpectedDataSize) 85 if (propID == NCoderPropID::kExpectedDataSize)
86 if (prop.vt == VT_UI8) 86 if (prop.vt == VT_UI8)
87 Lzma2Enc_SetDataSize(_encoder, prop.uhVal.QuadPart); 87 Lzma2Enc_SetDataSize(_encoder, prop.uhVal.QuadPart);
@@ -90,9 +90,9 @@ STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
90} 90}
91 91
92 92
93STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) 93Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
94{ 94{
95 Byte prop = Lzma2Enc_WriteProperties(_encoder); 95 const Byte prop = Lzma2Enc_WriteProperties(_encoder);
96 return WriteStream(outStream, &prop, 1); 96 return WriteStream(outStream, &prop, 1);
97} 97}
98 98
@@ -100,8 +100,8 @@ STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)
100#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ 100#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \
101 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; 101 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes;
102 102
103STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 103Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
104 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 104 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
105{ 105{
106 CSeqInStreamWrap inWrap; 106 CSeqInStreamWrap inWrap;
107 CSeqOutStreamWrap outWrap; 107 CSeqOutStreamWrap outWrap;
diff --git a/CPP/7zip/Compress/Lzma2Encoder.h b/CPP/7zip/Compress/Lzma2Encoder.h
index f681ad1..18c29e1 100644
--- a/CPP/7zip/Compress/Lzma2Encoder.h
+++ b/CPP/7zip/Compress/Lzma2Encoder.h
@@ -1,7 +1,7 @@
1// Lzma2Encoder.h 1// Lzma2Encoder.h
2 2
3#ifndef __LZMA2_ENCODER_H 3#ifndef ZIP7_INC_LZMA2_ENCODER_H
4#define __LZMA2_ENCODER_H 4#define ZIP7_INC_LZMA2_ENCODER_H
5 5
6#include "../../../C/Lzma2Enc.h" 6#include "../../../C/Lzma2Enc.h"
7 7
@@ -12,29 +12,17 @@
12namespace NCompress { 12namespace NCompress {
13namespace NLzma2 { 13namespace NLzma2 {
14 14
15class CEncoder: 15Z7_CLASS_IMP_COM_4(
16 public ICompressCoder, 16 CEncoder
17 public ICompressSetCoderProperties, 17 , ICompressCoder
18 public ICompressWriteCoderProperties, 18 , ICompressSetCoderProperties
19 public ICompressSetCoderPropertiesOpt, 19 , ICompressWriteCoderProperties
20 public CMyUnknownImp 20 , ICompressSetCoderPropertiesOpt
21{ 21)
22 CLzma2EncHandle _encoder; 22 CLzma2EncHandle _encoder;
23public: 23public:
24 MY_UNKNOWN_IMP4(
25 ICompressCoder,
26 ICompressSetCoderProperties,
27 ICompressWriteCoderProperties,
28 ICompressSetCoderPropertiesOpt)
29
30 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
31 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
32 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
33 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream);
34 STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
35
36 CEncoder(); 24 CEncoder();
37 virtual ~CEncoder(); 25 ~CEncoder();
38}; 26};
39 27
40}} 28}}
diff --git a/CPP/7zip/Compress/Lzma2Register.cpp b/CPP/7zip/Compress/Lzma2Register.cpp
index 8f279eb..fe53346 100644
--- a/CPP/7zip/Compress/Lzma2Register.cpp
+++ b/CPP/7zip/Compress/Lzma2Register.cpp
@@ -6,7 +6,7 @@
6 6
7#include "Lzma2Decoder.h" 7#include "Lzma2Decoder.h"
8 8
9#ifndef EXTRACT_ONLY 9#ifndef Z7_EXTRACT_ONLY
10#include "Lzma2Encoder.h" 10#include "Lzma2Encoder.h"
11#endif 11#endif
12 12
diff --git a/CPP/7zip/Compress/LzmaDecoder.cpp b/CPP/7zip/Compress/LzmaDecoder.cpp
index a25d36d..4f05b48 100644
--- a/CPP/7zip/Compress/LzmaDecoder.cpp
+++ b/CPP/7zip/Compress/LzmaDecoder.cpp
@@ -25,14 +25,14 @@ namespace NCompress {
25namespace NLzma { 25namespace NLzma {
26 26
27CDecoder::CDecoder(): 27CDecoder::CDecoder():
28 _inBuf(NULL),
29 _lzmaStatus(LZMA_STATUS_NOT_SPECIFIED),
30 FinishStream(false), 28 FinishStream(false),
31 _propsWereSet(false), 29 _propsWereSet(false),
32 _outSizeDefined(false), 30 _outSizeDefined(false),
33 _outStep(1 << 20), 31 _outStep(1 << 20),
34 _inBufSize(0), 32 _inBufSize(0),
35 _inBufSizeNew(1 << 20) 33 _inBufSizeNew(1 << 20),
34 _lzmaStatus(LZMA_STATUS_NOT_SPECIFIED),
35 _inBuf(NULL)
36{ 36{
37 _inProcessed = 0; 37 _inProcessed = 0;
38 _inPos = _inLim = 0; 38 _inPos = _inLim = 0;
@@ -42,7 +42,7 @@ CDecoder::CDecoder():
42 _alloc.numAlignBits = 7; 42 _alloc.numAlignBits = 7;
43 _alloc.offset = 0; 43 _alloc.offset = 0;
44 */ 44 */
45 LzmaDec_Construct(&_state); 45 LzmaDec_CONSTRUCT(&_state)
46} 46}
47 47
48CDecoder::~CDecoder() 48CDecoder::~CDecoder()
@@ -51,8 +51,10 @@ CDecoder::~CDecoder()
51 MyFree(_inBuf); 51 MyFree(_inBuf);
52} 52}
53 53
54STDMETHODIMP CDecoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSizeNew = size; return S_OK; } 54Z7_COM7F_IMF(CDecoder::SetInBufSize(UInt32 , UInt32 size))
55STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _outStep = size; return S_OK; } 55 { _inBufSizeNew = size; return S_OK; }
56Z7_COM7F_IMF(CDecoder::SetOutBufSize(UInt32 , UInt32 size))
57 { _outStep = size; return S_OK; }
56 58
57HRESULT CDecoder::CreateInputBuffer() 59HRESULT CDecoder::CreateInputBuffer()
58{ 60{
@@ -69,7 +71,7 @@ HRESULT CDecoder::CreateInputBuffer()
69} 71}
70 72
71 73
72STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) 74Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size))
73{ 75{
74 RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_AlignedAlloc))) // &_alloc.vt 76 RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_AlignedAlloc))) // &_alloc.vt
75 _propsWereSet = true; 77 _propsWereSet = true;
@@ -90,7 +92,7 @@ void CDecoder::SetOutStreamSizeResume(const UInt64 *outSize)
90} 92}
91 93
92 94
93STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 95Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize))
94{ 96{
95 _inProcessed = 0; 97 _inProcessed = 0;
96 _inPos = _inLim = 0; 98 _inPos = _inLim = 0;
@@ -99,14 +101,14 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
99} 101}
100 102
101 103
102STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 104Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
103{ 105{
104 FinishStream = (finishMode != 0); 106 FinishStream = (finishMode != 0);
105 return S_OK; 107 return S_OK;
106} 108}
107 109
108 110
109STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 111Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
110{ 112{
111 *value = _inProcessed; 113 *value = _inProcessed;
112 return S_OK; 114 return S_OK;
@@ -154,7 +156,7 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *
154 SizeT inProcessed = _inLim - _inPos; 156 SizeT inProcessed = _inLim - _inPos;
155 ELzmaStatus status; 157 ELzmaStatus status;
156 158
157 SRes res = LzmaDec_DecodeToDic(&_state, dicPos + size, _inBuf + _inPos, &inProcessed, finishMode, &status); 159 const SRes res = LzmaDec_DecodeToDic(&_state, dicPos + size, _inBuf + _inPos, &inProcessed, finishMode, &status);
158 160
159 _lzmaStatus = status; 161 _lzmaStatus = status;
160 _inPos += (UInt32)inProcessed; 162 _inPos += (UInt32)inProcessed;
@@ -163,22 +165,22 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *
163 _outProcessed += outProcessed; 165 _outProcessed += outProcessed;
164 166
165 // we check for LZMA_STATUS_NEEDS_MORE_INPUT to allow RangeCoder initialization, if (_outSizeDefined && _outSize == 0) 167 // we check for LZMA_STATUS_NEEDS_MORE_INPUT to allow RangeCoder initialization, if (_outSizeDefined && _outSize == 0)
166 bool outFinished = (_outSizeDefined && _outProcessed >= _outSize); 168 const bool outFinished = (_outSizeDefined && _outProcessed >= _outSize);
167 169
168 bool needStop = (res != 0 170 const bool needStop = (res != 0
169 || (inProcessed == 0 && outProcessed == 0) 171 || (inProcessed == 0 && outProcessed == 0)
170 || status == LZMA_STATUS_FINISHED_WITH_MARK 172 || status == LZMA_STATUS_FINISHED_WITH_MARK
171 || (outFinished && status != LZMA_STATUS_NEEDS_MORE_INPUT)); 173 || (outFinished && status != LZMA_STATUS_NEEDS_MORE_INPUT));
172 174
173 if (needStop || outProcessed >= size) 175 if (needStop || outProcessed >= size)
174 { 176 {
175 HRESULT res2 = WriteStream(outStream, _state.dic + wrPos, _state.dicPos - wrPos); 177 const HRESULT res2 = WriteStream(outStream, _state.dic + wrPos, _state.dicPos - wrPos);
176 178
177 if (_state.dicPos == _state.dicBufSize) 179 if (_state.dicPos == _state.dicBufSize)
178 _state.dicPos = 0; 180 _state.dicPos = 0;
179 wrPos = _state.dicPos; 181 wrPos = _state.dicPos;
180 182
181 RINOK(res2); 183 RINOK(res2)
182 184
183 if (needStop) 185 if (needStop)
184 { 186 {
@@ -207,14 +209,14 @@ HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *
207 if (progress) 209 if (progress)
208 { 210 {
209 const UInt64 inSize = _inProcessed - startInProgress; 211 const UInt64 inSize = _inProcessed - startInProgress;
210 RINOK(progress->SetRatioInfo(&inSize, &_outProcessed)); 212 RINOK(progress->SetRatioInfo(&inSize, &_outProcessed))
211 } 213 }
212 } 214 }
213} 215}
214 216
215 217
216STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 218Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
217 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 219 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
218{ 220{
219 if (!_inBuf) 221 if (!_inBuf)
220 return E_INVALIDARG; 222 return E_INVALIDARG;
@@ -227,13 +229,14 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
227} 229}
228 230
229 231
230#ifndef NO_READ_FROM_CODER 232#ifndef Z7_NO_READ_FROM_CODER
231
232STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; }
233STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; }
234 233
234Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream))
235 { _inStream = inStream; return S_OK; }
236Z7_COM7F_IMF(CDecoder::ReleaseInStream())
237 { _inStream.Release(); return S_OK; }
235 238
236STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 239Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
237{ 240{
238 if (processedSize) 241 if (processedSize)
239 *processedSize = 0; 242 *processedSize = 0;
@@ -264,7 +267,7 @@ STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
264 SizeT outProcessed = size; 267 SizeT outProcessed = size;
265 ELzmaStatus status; 268 ELzmaStatus status;
266 269
267 SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed, 270 const SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed,
268 _inBuf + _inPos, &inProcessed, finishMode, &status); 271 _inBuf + _inPos, &inProcessed, finishMode, &status);
269 272
270 _lzmaStatus = status; 273 _lzmaStatus = status;
@@ -308,7 +311,7 @@ HRESULT CDecoder::CodeResume(ISequentialOutStream *outStream, const UInt64 *outS
308 311
309HRESULT CDecoder::ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize) 312HRESULT CDecoder::ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize)
310{ 313{
311 RINOK(CreateInputBuffer()); 314 RINOK(CreateInputBuffer())
312 315
313 if (processedSize) 316 if (processedSize)
314 *processedSize = 0; 317 *processedSize = 0;
diff --git a/CPP/7zip/Compress/LzmaDecoder.h b/CPP/7zip/Compress/LzmaDecoder.h
index 37dec02..095e76f 100644
--- a/CPP/7zip/Compress/LzmaDecoder.h
+++ b/CPP/7zip/Compress/LzmaDecoder.h
@@ -1,7 +1,7 @@
1// LzmaDecoder.h 1// LzmaDecoder.h
2 2
3#ifndef __LZMA_DECODER_H 3#ifndef ZIP7_INC_LZMA_DECODER_H
4#define __LZMA_DECODER_H 4#define ZIP7_INC_LZMA_DECODER_H
5 5
6// #include "../../../C/Alloc.h" 6// #include "../../../C/Alloc.h"
7#include "../../../C/LzmaDec.h" 7#include "../../../C/LzmaDec.h"
@@ -12,39 +12,71 @@
12namespace NCompress { 12namespace NCompress {
13namespace NLzma { 13namespace NLzma {
14 14
15class CDecoder: 15class CDecoder Z7_final:
16 public ICompressCoder, 16 public ICompressCoder,
17 public ICompressSetDecoderProperties2, 17 public ICompressSetDecoderProperties2,
18 public ICompressSetFinishMode, 18 public ICompressSetFinishMode,
19 public ICompressGetInStreamProcessedSize, 19 public ICompressGetInStreamProcessedSize,
20 public ICompressSetBufSize, 20 public ICompressSetBufSize,
21 #ifndef NO_READ_FROM_CODER 21 #ifndef Z7_NO_READ_FROM_CODER
22 public ICompressSetInStream, 22 public ICompressSetInStream,
23 public ICompressSetOutStreamSize, 23 public ICompressSetOutStreamSize,
24 public ISequentialInStream, 24 public ISequentialInStream,
25 #endif 25 #endif
26 public CMyUnknownImp 26 public CMyUnknownImp
27{ 27{
28 Byte *_inBuf; 28 Z7_COM_QI_BEGIN2(ICompressCoder)
29 UInt32 _inPos; 29 Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2)
30 UInt32 _inLim; 30 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
31 31 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
32 ELzmaStatus _lzmaStatus; 32 Z7_COM_QI_ENTRY(ICompressSetBufSize)
33 #ifndef Z7_NO_READ_FROM_CODER
34 Z7_COM_QI_ENTRY(ICompressSetInStream)
35 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
36 Z7_COM_QI_ENTRY(ISequentialInStream)
37 #endif
38 Z7_COM_QI_END
39 Z7_COM_ADDREF_RELEASE
40
41 Z7_IFACE_COM7_IMP(ICompressCoder)
42public:
43 Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
44private:
45 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
46 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
47 // Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
33 48
49 Z7_IFACE_COM7_IMP(ICompressSetBufSize)
50
51 #ifndef Z7_NO_READ_FROM_CODER
34public: 52public:
35 bool FinishStream; // set it before decoding, if you need to decode full LZMA stream 53 Z7_IFACE_COM7_IMP(ICompressSetInStream)
54private:
55 Z7_IFACE_COM7_IMP(ISequentialInStream)
56 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
57 #else
58 Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize));
59 #endif
36 60
61public:
62 bool FinishStream; // set it before decoding, if you need to decode full LZMA stream
37private: 63private:
38 bool _propsWereSet; 64 bool _propsWereSet;
39 bool _outSizeDefined; 65 bool _outSizeDefined;
40 UInt64 _outSize;
41 UInt64 _inProcessed;
42 UInt64 _outProcessed;
43 66
44 UInt32 _outStep; 67 UInt32 _outStep;
45 UInt32 _inBufSize; 68 UInt32 _inBufSize;
46 UInt32 _inBufSizeNew; 69 UInt32 _inBufSizeNew;
47 70
71 ELzmaStatus _lzmaStatus;
72 UInt32 _inPos;
73 UInt32 _inLim;
74 Byte *_inBuf;
75
76 UInt64 _outSize;
77 UInt64 _inProcessed;
78 UInt64 _outProcessed;
79
48 // CAlignOffsetAlloc _alloc; 80 // CAlignOffsetAlloc _alloc;
49 81
50 CLzmaDec _state; 82 CLzmaDec _state;
@@ -53,53 +85,21 @@ private:
53 HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress); 85 HRESULT CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress);
54 void SetOutStreamSizeResume(const UInt64 *outSize); 86 void SetOutStreamSizeResume(const UInt64 *outSize);
55 87
56public: 88 #ifndef Z7_NO_READ_FROM_CODER
57 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
58 MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2)
59 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
60 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
61 MY_QUERYINTERFACE_ENTRY(ICompressSetBufSize)
62 #ifndef NO_READ_FROM_CODER
63 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream)
64 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
65 MY_QUERYINTERFACE_ENTRY(ISequentialInStream)
66 #endif
67 MY_QUERYINTERFACE_END
68 MY_ADDREF_RELEASE
69
70 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
71 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
72 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
73 STDMETHOD(SetFinishMode)(UInt32 finishMode);
74 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
75 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
76 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size);
77 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size);
78
79 #ifndef NO_READ_FROM_CODER
80
81private: 89private:
82 CMyComPtr<ISequentialInStream> _inStream; 90 CMyComPtr<ISequentialInStream> _inStream;
83public: 91public:
84
85 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
86 STDMETHOD(ReleaseInStream)();
87 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
88
89 HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress); 92 HRESULT CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress);
90 HRESULT ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize); 93 HRESULT ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize);
91 94 #endif
92 #endif
93
94 UInt64 GetInputProcessedSize() const { return _inProcessed; }
95 95
96public:
96 CDecoder(); 97 CDecoder();
97 virtual ~CDecoder(); 98 ~CDecoder();
98 99
100 UInt64 GetInputProcessedSize() const { return _inProcessed; }
99 UInt64 GetOutputProcessedSize() const { return _outProcessed; } 101 UInt64 GetOutputProcessedSize() const { return _outProcessed; }
100
101 bool NeedsMoreInput() const { return _lzmaStatus == LZMA_STATUS_NEEDS_MORE_INPUT; } 102 bool NeedsMoreInput() const { return _lzmaStatus == LZMA_STATUS_NEEDS_MORE_INPUT; }
102
103 bool CheckFinishStatus(bool withEndMark) const 103 bool CheckFinishStatus(bool withEndMark) const
104 { 104 {
105 return _lzmaStatus == (withEndMark ? 105 return _lzmaStatus == (withEndMark ?
diff --git a/CPP/7zip/Compress/LzmaEncoder.cpp b/CPP/7zip/Compress/LzmaEncoder.cpp
index dabd77a..08e3ba5 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)
48 48
49static int ParseMatchFinder(const wchar_t *s, int *btMode, int *numHashBytes) 49static int ParseMatchFinder(const wchar_t *s, int *btMode, int *numHashBytes)
50{ 50{
51 wchar_t c = GetLowCharFast(*s++); 51 const wchar_t c = GetLowCharFast(*s++);
52 if (c == 'h') 52 if (c == 'h')
53 { 53 {
54 if (GetLowCharFast(*s++) != 'c') 54 if (GetLowCharFast(*s++) != 'c')
55 return 0; 55 return 0;
56 int num = (int)(*s++ - L'0'); 56 const int num = (int)(*s++ - L'0');
57 if (num < 4 || num > 5) 57 if (num < 4 || num > 5)
58 return 0; 58 return 0;
59 if (*s != 0) 59 if (*s != 0)
@@ -68,7 +68,7 @@ static int ParseMatchFinder(const wchar_t *s, int *btMode, int *numHashBytes)
68 { 68 {
69 if (GetLowCharFast(*s++) != 't') 69 if (GetLowCharFast(*s++) != 't')
70 return 0; 70 return 0;
71 int num = (int)(*s++ - L'0'); 71 const int num = (int)(*s++ - L'0');
72 if (num < 2 || num > 5) 72 if (num < 2 || num > 5)
73 return 0; 73 return 0;
74 if (*s != 0) 74 if (*s != 0)
@@ -101,6 +101,15 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep)
101 return S_OK; 101 return S_OK;
102 } 102 }
103 103
104 if (propID == NCoderPropID::kHashBits)
105 {
106 if (prop.vt == VT_UI4)
107 ep.numHashOutBits = prop.ulVal;
108 else
109 return E_INVALIDARG;
110 return S_OK;
111 }
112
104 if (propID > NCoderPropID::kReduceSize) 113 if (propID > NCoderPropID::kReduceSize)
105 return S_OK; 114 return S_OK;
106 115
@@ -133,7 +142,7 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep)
133 142
134 if (prop.vt != VT_UI4) 143 if (prop.vt != VT_UI4)
135 return E_INVALIDARG; 144 return E_INVALIDARG;
136 UInt32 v = prop.ulVal; 145 const UInt32 v = prop.ulVal;
137 switch (propID) 146 switch (propID)
138 { 147 {
139 case NCoderPropID::kDefaultProp: 148 case NCoderPropID::kDefaultProp:
@@ -155,8 +164,8 @@ HRESULT SetLzmaProp(PROPID propID, const PROPVARIANT &prop, CLzmaEncProps &ep)
155 return S_OK; 164 return S_OK;
156} 165}
157 166
158STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, 167Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs,
159 const PROPVARIANT *coderProps, UInt32 numProps) 168 const PROPVARIANT *coderProps, UInt32 numProps))
160{ 169{
161 CLzmaEncProps props; 170 CLzmaEncProps props;
162 LzmaEncProps_Init(&props); 171 LzmaEncProps_Init(&props);
@@ -164,7 +173,7 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs,
164 for (UInt32 i = 0; i < numProps; i++) 173 for (UInt32 i = 0; i < numProps; i++)
165 { 174 {
166 const PROPVARIANT &prop = coderProps[i]; 175 const PROPVARIANT &prop = coderProps[i];
167 PROPID propID = propIDs[i]; 176 const PROPID propID = propIDs[i];
168 switch (propID) 177 switch (propID)
169 { 178 {
170 case NCoderPropID::kEndMarker: 179 case NCoderPropID::kEndMarker:
@@ -173,20 +182,20 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs,
173 props.writeEndMark = (prop.boolVal != VARIANT_FALSE); 182 props.writeEndMark = (prop.boolVal != VARIANT_FALSE);
174 break; 183 break;
175 default: 184 default:
176 RINOK(SetLzmaProp(propID, prop, props)); 185 RINOK(SetLzmaProp(propID, prop, props))
177 } 186 }
178 } 187 }
179 return SResToHRESULT(LzmaEnc_SetProps(_encoder, &props)); 188 return SResToHRESULT(LzmaEnc_SetProps(_encoder, &props));
180} 189}
181 190
182 191
183STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, 192Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
184 const PROPVARIANT *coderProps, UInt32 numProps) 193 const PROPVARIANT *coderProps, UInt32 numProps))
185{ 194{
186 for (UInt32 i = 0; i < numProps; i++) 195 for (UInt32 i = 0; i < numProps; i++)
187 { 196 {
188 const PROPVARIANT &prop = coderProps[i]; 197 const PROPVARIANT &prop = coderProps[i];
189 PROPID propID = propIDs[i]; 198 const PROPID propID = propIDs[i];
190 if (propID == NCoderPropID::kExpectedDataSize) 199 if (propID == NCoderPropID::kExpectedDataSize)
191 if (prop.vt == VT_UI8) 200 if (prop.vt == VT_UI8)
192 LzmaEnc_SetDataSize(_encoder, prop.uhVal.QuadPart); 201 LzmaEnc_SetDataSize(_encoder, prop.uhVal.QuadPart);
@@ -195,11 +204,11 @@ STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
195} 204}
196 205
197 206
198STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) 207Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
199{ 208{
200 Byte props[LZMA_PROPS_SIZE]; 209 Byte props[LZMA_PROPS_SIZE];
201 size_t size = LZMA_PROPS_SIZE; 210 SizeT size = LZMA_PROPS_SIZE;
202 RINOK(LzmaEnc_WriteProperties(_encoder, props, &size)); 211 RINOK(LzmaEnc_WriteProperties(_encoder, props, &size))
203 return WriteStream(outStream, props, size); 212 return WriteStream(outStream, props, size);
204} 213}
205 214
@@ -293,8 +302,8 @@ static void PrintStat(HANDLE thread, UInt64 totalTime, const CBaseStat *prevStat
293 302
294 303
295 304
296STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 305Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
297 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 306 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
298{ 307{
299 CSeqInStreamWrap inWrap; 308 CSeqInStreamWrap inWrap;
300 CSeqOutStreamWrap outWrap; 309 CSeqOutStreamWrap outWrap;
diff --git a/CPP/7zip/Compress/LzmaEncoder.h b/CPP/7zip/Compress/LzmaEncoder.h
index 7d706ad..2836d7d 100644
--- a/CPP/7zip/Compress/LzmaEncoder.h
+++ b/CPP/7zip/Compress/LzmaEncoder.h
@@ -1,7 +1,7 @@
1// LzmaEncoder.h 1// LzmaEncoder.h
2 2
3#ifndef __LZMA_ENCODER_H 3#ifndef ZIP7_INC_LZMA_ENCODER_H
4#define __LZMA_ENCODER_H 4#define ZIP7_INC_LZMA_ENCODER_H
5 5
6#include "../../../C/LzmaEnc.h" 6#include "../../../C/LzmaEnc.h"
7 7
@@ -12,30 +12,29 @@
12namespace NCompress { 12namespace NCompress {
13namespace NLzma { 13namespace NLzma {
14 14
15class CEncoder: 15class CEncoder Z7_final:
16 public ICompressCoder, 16 public ICompressCoder,
17 public ICompressSetCoderProperties, 17 public ICompressSetCoderProperties,
18 public ICompressWriteCoderProperties, 18 public ICompressWriteCoderProperties,
19 public ICompressSetCoderPropertiesOpt, 19 public ICompressSetCoderPropertiesOpt,
20 public CMyUnknownImp 20 public CMyUnknownImp
21{ 21{
22 CLzmaEncHandle _encoder; 22 Z7_COM_UNKNOWN_IMP_4(
23 UInt64 _inputProcessed;
24public:
25 MY_UNKNOWN_IMP4(
26 ICompressCoder, 23 ICompressCoder,
27 ICompressSetCoderProperties, 24 ICompressSetCoderProperties,
28 ICompressWriteCoderProperties, 25 ICompressWriteCoderProperties,
29 ICompressSetCoderPropertiesOpt) 26 ICompressSetCoderPropertiesOpt)
30 27 Z7_IFACE_COM7_IMP(ICompressCoder)
31 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, 28public:
32 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 29 Z7_IFACE_COM7_IMP(ICompressSetCoderProperties)
33 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); 30 Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties)
34 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); 31 Z7_IFACE_COM7_IMP(ICompressSetCoderPropertiesOpt)
35 STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps); 32
33 CLzmaEncHandle _encoder;
34 UInt64 _inputProcessed;
36 35
37 CEncoder(); 36 CEncoder();
38 virtual ~CEncoder(); 37 ~CEncoder();
39 38
40 UInt64 GetInputProcessedSize() const { return _inputProcessed; } 39 UInt64 GetInputProcessedSize() const { return _inputProcessed; }
41 bool IsWriteEndMark() const { return LzmaEnc_IsWriteEndMark(_encoder) != 0; } 40 bool IsWriteEndMark() const { return LzmaEnc_IsWriteEndMark(_encoder) != 0; }
diff --git a/CPP/7zip/Compress/LzmaRegister.cpp b/CPP/7zip/Compress/LzmaRegister.cpp
index c802a99..887f7a2 100644
--- a/CPP/7zip/Compress/LzmaRegister.cpp
+++ b/CPP/7zip/Compress/LzmaRegister.cpp
@@ -6,7 +6,7 @@
6 6
7#include "LzmaDecoder.h" 7#include "LzmaDecoder.h"
8 8
9#ifndef EXTRACT_ONLY 9#ifndef Z7_EXTRACT_ONLY
10#include "LzmaEncoder.h" 10#include "LzmaEncoder.h"
11#endif 11#endif
12 12
diff --git a/CPP/7zip/Compress/LzmsDecoder.cpp b/CPP/7zip/Compress/LzmsDecoder.cpp
index e27afa3..38c0408 100644
--- a/CPP/7zip/Compress/LzmsDecoder.cpp
+++ b/CPP/7zip/Compress/LzmsDecoder.cpp
@@ -77,7 +77,7 @@ static unsigned GetNumPosSlots(size_t size)
77 unsigned right = k_NumPosSyms; 77 unsigned right = k_NumPosSyms;
78 for (;;) 78 for (;;)
79 { 79 {
80 unsigned m = (left + right) / 2; 80 const unsigned m = (left + right) / 2;
81 if (left == m) 81 if (left == m)
82 return m + 1; 82 return m + 1;
83 if (size >= g_PosBases[m]) 83 if (size >= g_PosBases[m])
@@ -139,7 +139,7 @@ static void x86_Filter(Byte *data, UInt32 size, Int32 *history)
139 139
140 Int32 maxTransOffset = k_x86_TransOffset; 140 Int32 maxTransOffset = k_x86_TransOffset;
141 141
142 Byte b = p[0]; 142 const Byte b = p[0];
143 143
144 if (b == 0x48) 144 if (b == 0x48)
145 { 145 {
@@ -202,8 +202,8 @@ static void x86_Filter(Byte *data, UInt32 size, Int32 *history)
202 UInt32 n = GetUi32(p2); 202 UInt32 n = GetUi32(p2);
203 if (i - last_x86_pos <= maxTransOffset) 203 if (i - last_x86_pos <= maxTransOffset)
204 { 204 {
205 n -= i; 205 n = (UInt32)((Int32)n - i);
206 SetUi32(p2, n); 206 SetUi32(p2, n)
207 } 207 }
208 target = history + (((UInt32)i + n) & 0xFFFF); 208 target = history + (((UInt32)i + n) & 0xFFFF);
209 } 209 }
@@ -319,7 +319,7 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out
319 if (_rc.Decode(&mainState, k_NumMainProbs, mainProbs) == 0) 319 if (_rc.Decode(&mainState, k_NumMainProbs, mainProbs) == 0)
320 { 320 {
321 UInt32 number; 321 UInt32 number;
322 HUFF_DEC(number, m_LitDecoder); 322 HUFF_DEC(number, m_LitDecoder)
323 LIMIT_CHECK 323 LIMIT_CHECK
324 _win[_pos++] = (Byte)number; 324 _win[_pos++] = (Byte)number;
325 prevType = 0; 325 prevType = 0;
@@ -331,12 +331,12 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out
331 if (_rc.Decode(&lzRepStates[0], k_NumRepProbs, lzRepProbs[0]) == 0) 331 if (_rc.Decode(&lzRepStates[0], k_NumRepProbs, lzRepProbs[0]) == 0)
332 { 332 {
333 UInt32 number; 333 UInt32 number;
334 HUFF_DEC(number, m_PosDecoder); 334 HUFF_DEC(number, m_PosDecoder)
335 LIMIT_CHECK 335 LIMIT_CHECK
336 336
337 unsigned numDirectBits = g_PosDirectBits[number]; 337 const unsigned numDirectBits = g_PosDirectBits[number];
338 distance = g_PosBases[number]; 338 distance = g_PosBases[number];
339 READ_BITS_CHECK(numDirectBits); 339 READ_BITS_CHECK(numDirectBits)
340 distance += _bs.ReadBits32(numDirectBits); 340 distance += _bs.ReadBits32(numDirectBits);
341 // LIMIT_CHECK 341 // LIMIT_CHECK
342 _reps[3] = _reps[2]; 342 _reps[3] = _reps[2];
@@ -394,13 +394,13 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out
394 } 394 }
395 395
396 UInt32 lenSlot; 396 UInt32 lenSlot;
397 HUFF_DEC(lenSlot, m_LenDecoder); 397 HUFF_DEC(lenSlot, m_LenDecoder)
398 LIMIT_CHECK 398 LIMIT_CHECK
399 399
400 UInt32 len = g_LenBases[lenSlot]; 400 UInt32 len = g_LenBases[lenSlot];
401 { 401 {
402 unsigned numDirectBits = k_LenDirectBits[lenSlot]; 402 const unsigned numDirectBits = k_LenDirectBits[lenSlot];
403 READ_BITS_CHECK(numDirectBits); 403 READ_BITS_CHECK(numDirectBits)
404 len += _bs.ReadBits32(numDirectBits); 404 len += _bs.ReadBits32(numDirectBits);
405 } 405 }
406 // LIMIT_CHECK 406 // LIMIT_CHECK
@@ -429,16 +429,16 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out
429 429
430 if (_rc.Decode(&deltaRepStates[0], k_NumRepProbs, deltaRepProbs[0]) == 0) 430 if (_rc.Decode(&deltaRepStates[0], k_NumRepProbs, deltaRepProbs[0]) == 0)
431 { 431 {
432 HUFF_DEC(power, m_PowerDecoder); 432 HUFF_DEC(power, m_PowerDecoder)
433 LIMIT_CHECK 433 LIMIT_CHECK
434 434
435 UInt32 number; 435 UInt32 number;
436 HUFF_DEC(number, m_DeltaDecoder); 436 HUFF_DEC(number, m_DeltaDecoder)
437 LIMIT_CHECK 437 LIMIT_CHECK
438 438
439 unsigned numDirectBits = g_PosDirectBits[number]; 439 const unsigned numDirectBits = g_PosDirectBits[number];
440 distance32 = g_PosBases[number]; 440 distance32 = g_PosBases[number];
441 READ_BITS_CHECK(numDirectBits); 441 READ_BITS_CHECK(numDirectBits)
442 distance32 += _bs.ReadBits32(numDirectBits); 442 distance32 += _bs.ReadBits32(numDirectBits);
443 // LIMIT_CHECK 443 // LIMIT_CHECK
444 444
@@ -500,16 +500,16 @@ HRESULT CDecoder::CodeReal(const Byte *in, size_t inSize, Byte *_win, size_t out
500 power = (UInt32)(_deltaReps[0] >> 32); 500 power = (UInt32)(_deltaReps[0] >> 32);
501 } 501 }
502 502
503 UInt32 dist = (distance32 << power); 503 const UInt32 dist = (distance32 << power);
504 504
505 UInt32 lenSlot; 505 UInt32 lenSlot;
506 HUFF_DEC(lenSlot, m_LenDecoder); 506 HUFF_DEC(lenSlot, m_LenDecoder)
507 LIMIT_CHECK 507 LIMIT_CHECK
508 508
509 UInt32 len = g_LenBases[lenSlot]; 509 UInt32 len = g_LenBases[lenSlot];
510 { 510 {
511 unsigned numDirectBits = k_LenDirectBits[lenSlot]; 511 unsigned numDirectBits = k_LenDirectBits[lenSlot];
512 READ_BITS_CHECK(numDirectBits); 512 READ_BITS_CHECK(numDirectBits)
513 len += _bs.ReadBits32(numDirectBits); 513 len += _bs.ReadBits32(numDirectBits);
514 } 514 }
515 // LIMIT_CHECK 515 // LIMIT_CHECK
diff --git a/CPP/7zip/Compress/LzmsDecoder.h b/CPP/7zip/Compress/LzmsDecoder.h
index f0909a1..e173c97 100644
--- a/CPP/7zip/Compress/LzmsDecoder.h
+++ b/CPP/7zip/Compress/LzmsDecoder.h
@@ -1,8 +1,8 @@
1// LzmsDecoder.h 1// LzmsDecoder.h
2// The code is based on LZMS description from wimlib code 2// The code is based on LZMS description from wimlib code
3 3
4#ifndef __LZMS_DECODER_H 4#ifndef ZIP7_INC_LZMS_DECODER_H
5#define __LZMS_DECODER_H 5#define ZIP7_INC_LZMS_DECODER_H
6 6
7// #define SHOW_DEBUG_INFO 7// #define SHOW_DEBUG_INFO
8 8
@@ -158,7 +158,7 @@ struct CProbEntry
158 158
159 void Update(unsigned bit) throw() 159 void Update(unsigned bit) throw()
160 { 160 {
161 Prob += (Int32)(Hist >> (k_ProbLimit - 1)) - (Int32)bit; 161 Prob += (UInt32)((Int32)(Hist >> (k_ProbLimit - 1)) - (Int32)bit);
162 Hist = (Hist << 1) | bit; 162 Hist = (Hist << 1) | bit;
163 } 163 }
164}; 164};
diff --git a/CPP/7zip/Compress/Lzx.h b/CPP/7zip/Compress/Lzx.h
index 29ca4ca..2532088 100644
--- a/CPP/7zip/Compress/Lzx.h
+++ b/CPP/7zip/Compress/Lzx.h
@@ -1,7 +1,9 @@
1// Lzx.h 1// Lzx.h
2 2
3#ifndef __COMPRESS_LZX_H 3#ifndef ZIP7_INC_COMPRESS_LZX_H
4#define __COMPRESS_LZX_H 4#define ZIP7_INC_COMPRESS_LZX_H
5
6#include "../../Common/MyTypes.h"
5 7
6namespace NCompress { 8namespace NCompress {
7namespace NLzx { 9namespace NLzx {
diff --git a/CPP/7zip/Compress/LzxDecoder.cpp b/CPP/7zip/Compress/LzxDecoder.cpp
index e59cd40..b50d863 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
27 return; 27 return;
28 size -= kResidue; 28 size -= kResidue;
29 29
30 Byte save = data[(size_t)size + 4]; 30 const Byte save = data[(size_t)size + 4];
31 data[(size_t)size + 4] = 0xE8; 31 data[(size_t)size + 4] = 0xE8;
32 32
33 for (UInt32 i = 0;;) 33 for (UInt32 i = 0;;)
@@ -52,7 +52,7 @@ static void x86_Filter(Byte *data, UInt32 size, UInt32 processedSize, UInt32 tra
52 if (v >= pos && v < (Int32)translationSize) 52 if (v >= pos && v < (Int32)translationSize)
53 { 53 {
54 v += (v >= 0 ? pos : (Int32)translationSize); 54 v += (v >= 0 ? pos : (Int32)translationSize);
55 SetUi32(p, (UInt32)v); 55 SetUi32(p, (UInt32)v)
56 } 56 }
57 } 57 }
58 } 58 }
@@ -88,7 +88,7 @@ HRESULT CDecoder::Flush()
88 if (_x86_translationSize != 0) 88 if (_x86_translationSize != 0)
89 { 89 {
90 Byte *destData = _win + _writePos; 90 Byte *destData = _win + _writePos;
91 UInt32 curSize = _pos - _writePos; 91 const UInt32 curSize = _pos - _writePos;
92 if (KeepHistoryForNext) 92 if (KeepHistoryForNext)
93 { 93 {
94 if (!_x86_buf) 94 if (!_x86_buf)
@@ -125,7 +125,7 @@ bool CDecoder::ReadTable(Byte *levels, unsigned numSymbols)
125 Byte levels2[kLevelTableSize]; 125 Byte levels2[kLevelTableSize];
126 for (unsigned i = 0; i < kLevelTableSize; i++) 126 for (unsigned i = 0; i < kLevelTableSize; i++)
127 levels2[i] = (Byte)ReadBits(kNumLevelBits); 127 levels2[i] = (Byte)ReadBits(kNumLevelBits);
128 RIF(_levelDecoder.Build(levels2)); 128 RIF(_levelDecoder.Build(levels2))
129 } 129 }
130 130
131 unsigned i = 0; 131 unsigned i = 0;
@@ -163,7 +163,7 @@ bool CDecoder::ReadTable(Byte *levels, unsigned numSymbols)
163 else 163 else
164 return false; 164 return false;
165 165
166 unsigned limit = i + num; 166 const unsigned limit = i + num;
167 if (limit > numSymbols) 167 if (limit > numSymbols)
168 return false; 168 return false;
169 169
@@ -188,7 +188,7 @@ bool CDecoder::ReadTables(void)
188 188
189 _bitStream.NormalizeBig(); 189 _bitStream.NormalizeBig();
190 190
191 unsigned blockType = (unsigned)ReadBits(kBlockType_NumBits); 191 const unsigned blockType = (unsigned)ReadBits(kBlockType_NumBits);
192 if (blockType > kBlockType_Uncompressed) 192 if (blockType > kBlockType_Uncompressed)
193 return false; 193 return false;
194 194
@@ -227,7 +227,7 @@ bool CDecoder::ReadTables(void)
227 227
228 for (unsigned i = 0; i < kNumReps; i++) 228 for (unsigned i = 0; i < kNumReps; i++)
229 { 229 {
230 UInt32 rep = _bitStream.ReadUInt32(); 230 const UInt32 rep = _bitStream.ReadUInt32();
231 if (rep > _winSize) 231 if (rep > _winSize)
232 return false; 232 return false;
233 _reps[i] = rep; 233 _reps[i] = rep;
@@ -244,16 +244,16 @@ bool CDecoder::ReadTables(void)
244 _numAlignBits = kNumAlignBits; 244 _numAlignBits = kNumAlignBits;
245 for (unsigned i = 0; i < kAlignTableSize; i++) 245 for (unsigned i = 0; i < kAlignTableSize; i++)
246 levels[i] = (Byte)ReadBits(kNumAlignLevelBits); 246 levels[i] = (Byte)ReadBits(kNumAlignLevelBits);
247 RIF(_alignDecoder.Build(levels)); 247 RIF(_alignDecoder.Build(levels))
248 } 248 }
249 } 249 }
250 250
251 RIF(ReadTable(_mainLevels, 256)); 251 RIF(ReadTable(_mainLevels, 256))
252 RIF(ReadTable(_mainLevels + 256, _numPosLenSlots)); 252 RIF(ReadTable(_mainLevels + 256, _numPosLenSlots))
253 unsigned end = 256 + _numPosLenSlots; 253 unsigned end = 256 + _numPosLenSlots;
254 memset(_mainLevels + end, 0, kMainTableSize - end); 254 memset(_mainLevels + end, 0, kMainTableSize - end);
255 RIF(_mainDecoder.Build(_mainLevels)); 255 RIF(_mainDecoder.Build(_mainLevels))
256 RIF(ReadTable(_lenLevels, kNumLenSymbols)); 256 RIF(ReadTable(_lenLevels, kNumLenSymbols))
257 return _lenDecoder.Build(_lenLevels); 257 return _lenDecoder.Build(_lenLevels);
258} 258}
259 259
@@ -310,7 +310,7 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize)
310 310
311 if (_isUncompressedBlock) 311 if (_isUncompressedBlock)
312 { 312 {
313 size_t rem = _bitStream.GetRem(); 313 const size_t rem = _bitStream.GetRem();
314 if (rem == 0) 314 if (rem == 0)
315 return S_FALSE; 315 return S_FALSE;
316 if (next > rem) 316 if (next > rem)
@@ -359,8 +359,8 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize)
359 sym -= 256; 359 sym -= 256;
360 if (sym >= _numPosLenSlots) 360 if (sym >= _numPosLenSlots)
361 return S_FALSE; 361 return S_FALSE;
362 UInt32 posSlot = sym / kNumLenSlots; 362 const UInt32 posSlot = sym / kNumLenSlots;
363 UInt32 lenSlot = sym % kNumLenSlots; 363 const UInt32 lenSlot = sym % kNumLenSlots;
364 UInt32 len = kMatchMinLen + lenSlot; 364 UInt32 len = kMatchMinLen + lenSlot;
365 365
366 if (lenSlot == kNumLenSlots - 1) 366 if (lenSlot == kNumLenSlots - 1)
@@ -397,7 +397,7 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize)
397 if (numDirectBits >= _numAlignBits) 397 if (numDirectBits >= _numAlignBits)
398 { 398 {
399 dist += (_bitStream.ReadBitsSmall(numDirectBits - kNumAlignBits) << kNumAlignBits); 399 dist += (_bitStream.ReadBitsSmall(numDirectBits - kNumAlignBits) << kNumAlignBits);
400 UInt32 alignTemp = _alignDecoder.Decode(&_bitStream); 400 const UInt32 alignTemp = _alignDecoder.Decode(&_bitStream);
401 if (alignTemp >= kAlignTableSize) 401 if (alignTemp >= kAlignTableSize)
402 return S_FALSE; 402 return S_FALSE;
403 dist += alignTemp; 403 dist += alignTemp;
@@ -435,7 +435,7 @@ HRESULT CDecoder::CodeSpec(UInt32 curSize)
435 } 435 }
436 else 436 else
437 { 437 {
438 ptrdiff_t src = (ptrdiff_t)srcPos - (ptrdiff_t)_pos; 438 const ptrdiff_t src = (ptrdiff_t)srcPos - (ptrdiff_t)_pos;
439 _pos += len; 439 _pos += len;
440 const Byte *lim = dest + len; 440 const Byte *lim = dest + len;
441 *(dest) = *(dest + src); 441 *(dest) = *(dest + src);
@@ -485,8 +485,8 @@ HRESULT CDecoder::Code(const Byte *inData, size_t inSize, UInt32 outSize)
485 485
486 _bitStream.Init(inData, inSize); 486 _bitStream.Init(inData, inSize);
487 487
488 HRESULT res = CodeSpec(outSize); 488 const HRESULT res = CodeSpec(outSize);
489 HRESULT res2 = Flush(); 489 const HRESULT res2 = Flush();
490 return (res == S_OK ? res2 : res); 490 return (res == S_OK ? res2 : res);
491} 491}
492 492
@@ -496,7 +496,7 @@ HRESULT CDecoder::SetParams2(unsigned numDictBits)
496 _numDictBits = numDictBits; 496 _numDictBits = numDictBits;
497 if (numDictBits < kNumDictBits_Min || numDictBits > kNumDictBits_Max) 497 if (numDictBits < kNumDictBits_Min || numDictBits > kNumDictBits_Max)
498 return E_INVALIDARG; 498 return E_INVALIDARG;
499 unsigned numPosSlots = (numDictBits < 20) ? 499 const unsigned numPosSlots = (numDictBits < 20) ?
500 numDictBits * 2 : 500 numDictBits * 2 :
501 34 + ((unsigned)1 << (numDictBits - 17)); 501 34 + ((unsigned)1 << (numDictBits - 17));
502 _numPosLenSlots = numPosSlots * kNumLenSlots; 502 _numPosLenSlots = numPosSlots * kNumLenSlots;
@@ -506,9 +506,9 @@ HRESULT CDecoder::SetParams2(unsigned numDictBits)
506 506
507HRESULT CDecoder::SetParams_and_Alloc(unsigned numDictBits) 507HRESULT CDecoder::SetParams_and_Alloc(unsigned numDictBits)
508{ 508{
509 RINOK(SetParams2(numDictBits)); 509 RINOK(SetParams2(numDictBits))
510 510
511 UInt32 newWinSize = (UInt32)1 << numDictBits; 511 const UInt32 newWinSize = (UInt32)1 << numDictBits;
512 512
513 if (NeedAlloc) 513 if (NeedAlloc)
514 { 514 {
diff --git a/CPP/7zip/Compress/LzxDecoder.h b/CPP/7zip/Compress/LzxDecoder.h
index 4d70b27..ab114e5 100644
--- a/CPP/7zip/Compress/LzxDecoder.h
+++ b/CPP/7zip/Compress/LzxDecoder.h
@@ -1,7 +1,7 @@
1// LzxDecoder.h 1// LzxDecoder.h
2 2
3#ifndef __LZX_DECODER_H 3#ifndef ZIP7_INC_LZX_DECODER_H
4#define __LZX_DECODER_H 4#define ZIP7_INC_LZX_DECODER_H
5 5
6#include "../../../C/CpuArch.h" 6#include "../../../C/CpuArch.h"
7 7
@@ -167,10 +167,9 @@ public:
167}; 167};
168 168
169 169
170class CDecoder: 170Z7_CLASS_IMP_COM_0(
171 public IUnknown, 171 CDecoder
172 public CMyUnknownImp 172)
173{
174 CBitDecoder _bitStream; 173 CBitDecoder _bitStream;
175 Byte *_win; 174 Byte *_win;
176 UInt32 _pos; 175 UInt32 _pos;
@@ -220,8 +219,6 @@ public:
220 CDecoder(bool wimMode = false); 219 CDecoder(bool wimMode = false);
221 ~CDecoder(); 220 ~CDecoder();
222 221
223 MY_UNKNOWN_IMP
224
225 HRESULT SetExternalWindow(Byte *win, unsigned numDictBits) 222 HRESULT SetExternalWindow(Byte *win, unsigned numDictBits)
226 { 223 {
227 NeedAlloc = false; 224 NeedAlloc = false;
diff --git a/CPP/7zip/Compress/Mtf8.h b/CPP/7zip/Compress/Mtf8.h
index 50a84ce..1b44d00 100644
--- a/CPP/7zip/Compress/Mtf8.h
+++ b/CPP/7zip/Compress/Mtf8.h
@@ -1,7 +1,7 @@
1// Mtf8.h 1// Mtf8.h
2 2
3#ifndef __COMPRESS_MTF8_H 3#ifndef ZIP7_INC_COMPRESS_MTF8_H
4#define __COMPRESS_MTF8_H 4#define ZIP7_INC_COMPRESS_MTF8_H
5 5
6#include "../../../C/CpuArch.h" 6#include "../../../C/CpuArch.h"
7 7
@@ -15,7 +15,7 @@ struct CMtf8Encoder
15 { 15 {
16 size_t pos; 16 size_t pos;
17 for (pos = 0; Buf[pos] != v; pos++); 17 for (pos = 0; Buf[pos] != v; pos++);
18 unsigned resPos = (unsigned)pos; 18 const unsigned resPos = (unsigned)pos;
19 for (; pos >= 8; pos -= 8) 19 for (; pos >= 8; pos -= 8)
20 { 20 {
21 Buf[pos] = Buf[pos - 1]; 21 Buf[pos] = Buf[pos - 1];
@@ -66,28 +66,28 @@ struct CMtf8Decoder
66 66
67#ifdef MY_CPU_64BIT 67#ifdef MY_CPU_64BIT
68 typedef UInt64 CMtfVar; 68 typedef UInt64 CMtfVar;
69 #define MTF_MOVS 3 69 #define Z7_MTF_MOVS 3
70#else 70#else
71 typedef UInt32 CMtfVar; 71 typedef UInt32 CMtfVar;
72 #define MTF_MOVS 2 72 #define Z7_MTF_MOVS 2
73#endif 73#endif
74 74
75#define MTF_MASK ((1 << MTF_MOVS) - 1) 75#define Z7_MTF_MASK ((1 << Z7_MTF_MOVS) - 1)
76 76
77 77
78struct CMtf8Decoder 78struct CMtf8Decoder
79{ 79{
80 CMtfVar Buf[256 >> MTF_MOVS]; 80 CMtfVar Buf[256 >> Z7_MTF_MOVS];
81 81
82 void StartInit() { memset(Buf, 0, sizeof(Buf)); } 82 void StartInit() { memset(Buf, 0, sizeof(Buf)); }
83 void Add(unsigned pos, Byte val) { Buf[pos >> MTF_MOVS] |= ((CMtfVar)val << ((pos & MTF_MASK) << 3)); } 83 void Add(unsigned pos, Byte val) { Buf[pos >> Z7_MTF_MOVS] |= ((CMtfVar)val << ((pos & Z7_MTF_MASK) << 3)); }
84 Byte GetHead() const { return (Byte)Buf[0]; } 84 Byte GetHead() const { return (Byte)Buf[0]; }
85 85
86 MY_FORCE_INLINE 86 Z7_FORCE_INLINE
87 Byte GetAndMove(unsigned pos) throw() 87 Byte GetAndMove(unsigned pos) throw()
88 { 88 {
89 UInt32 lim = ((UInt32)pos >> MTF_MOVS); 89 const UInt32 lim = ((UInt32)pos >> Z7_MTF_MOVS);
90 pos = (pos & MTF_MASK) << 3; 90 pos = (pos & Z7_MTF_MASK) << 3;
91 CMtfVar prev = (Buf[lim] >> pos) & 0xFF; 91 CMtfVar prev = (Buf[lim] >> pos) & 0xFF;
92 92
93 UInt32 i = 0; 93 UInt32 i = 0;
@@ -98,7 +98,7 @@ struct CMtf8Decoder
98 { 98 {
99 CMtfVar next = Buf[0]; 99 CMtfVar next = Buf[0];
100 Buf[0] = (next << 8) | prev; 100 Buf[0] = (next << 8) | prev;
101 prev = (next >> (MTF_MASK << 3)); 101 prev = (next >> (Z7_MTF_MASK << 3));
102 i = 1; 102 i = 1;
103 lim -= 1; 103 lim -= 1;
104 } 104 }
@@ -107,21 +107,21 @@ struct CMtf8Decoder
107 CMtfVar n0 = Buf[i]; 107 CMtfVar n0 = Buf[i];
108 CMtfVar n1 = Buf[i + 1]; 108 CMtfVar n1 = Buf[i + 1];
109 Buf[i ] = (n0 << 8) | prev; 109 Buf[i ] = (n0 << 8) | prev;
110 Buf[i + 1] = (n1 << 8) | (n0 >> (MTF_MASK << 3)); 110 Buf[i + 1] = (n1 << 8) | (n0 >> (Z7_MTF_MASK << 3));
111 prev = (n1 >> (MTF_MASK << 3)); 111 prev = (n1 >> (Z7_MTF_MASK << 3));
112 } 112 }
113 */ 113 */
114 114
115 for (; i < lim; i++) 115 for (; i < lim; i++)
116 { 116 {
117 CMtfVar n0 = Buf[i]; 117 const CMtfVar n0 = Buf[i];
118 Buf[i ] = (n0 << 8) | prev; 118 Buf[i ] = (n0 << 8) | prev;
119 prev = (n0 >> (MTF_MASK << 3)); 119 prev = (n0 >> (Z7_MTF_MASK << 3));
120 } 120 }
121 121
122 122
123 CMtfVar next = Buf[i]; 123 const CMtfVar next = Buf[i];
124 CMtfVar mask = (((CMtfVar)0x100 << pos) - 1); 124 const CMtfVar mask = (((CMtfVar)0x100 << pos) - 1);
125 Buf[i] = (next & ~mask) | (((next << 8) | prev) & mask); 125 Buf[i] = (next & ~mask) | (((next << 8) | prev) & mask);
126 return (Byte)Buf[0]; 126 return (Byte)Buf[0];
127 } 127 }
diff --git a/CPP/7zip/Compress/PpmdDecoder.cpp b/CPP/7zip/Compress/PpmdDecoder.cpp
index 7f54ec3..1238df6 100644
--- a/CPP/7zip/Compress/PpmdDecoder.cpp
+++ b/CPP/7zip/Compress/PpmdDecoder.cpp
@@ -1,5 +1,4 @@
1// PpmdDecoder.cpp 1// PpmdDecoder.cpp
2// 2020-07-03 : Igor Pavlov : Public domain
3 2
4#include "StdAfx.h" 3#include "StdAfx.h"
5 4
@@ -29,14 +28,13 @@ CDecoder::~CDecoder()
29 Ppmd7_Free(&_ppmd, &g_BigAlloc); 28 Ppmd7_Free(&_ppmd, &g_BigAlloc);
30} 29}
31 30
32STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size) 31Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size))
33{ 32{
34 if (size < 5) 33 if (size < 5)
35 return E_INVALIDARG; 34 return E_INVALIDARG;
36 _order = props[0]; 35 _order = props[0];
37 UInt32 memSize = GetUi32(props + 1); 36 const UInt32 memSize = GetUi32(props + 1);
38 if ( 37 if (_order < PPMD7_MIN_ORDER ||
39 // _order < PPMD7_MIN_ORDER ||
40 _order > PPMD7_MAX_ORDER || 38 _order > PPMD7_MAX_ORDER ||
41 memSize < PPMD7_MIN_MEM_SIZE || 39 memSize < PPMD7_MIN_MEM_SIZE ||
42 memSize > PPMD7_MAX_MEM_SIZE) 40 memSize > PPMD7_MAX_MEM_SIZE)
@@ -48,7 +46,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *props, UInt32 size)
48 return S_OK; 46 return S_OK;
49} 47}
50 48
51#define _rangeDec _ppmd.rc.dec 49#define MY_rangeDec _ppmd.rc.dec
52 50
53#define CHECK_EXTRA_ERROR \ 51#define CHECK_EXTRA_ERROR \
54 if (_inStream.Extra) { \ 52 if (_inStream.Extra) { \
@@ -67,7 +65,7 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size)
67 case kStatus_Error: return S_FALSE; 65 case kStatus_Error: return S_FALSE;
68 case kStatus_NeedInit: 66 case kStatus_NeedInit:
69 _inStream.Init(); 67 _inStream.Init();
70 if (!Ppmd7z_RangeDec_Init(&_rangeDec)) 68 if (!Ppmd7z_RangeDec_Init(&MY_rangeDec))
71 { 69 {
72 _status = kStatus_Error; 70 _status = kStatus_Error;
73 return (_res = S_FALSE); 71 return (_res = S_FALSE);
@@ -110,7 +108,7 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size)
110 if (!FinishStream 108 if (!FinishStream
111 || !_outSizeDefined 109 || !_outSizeDefined
112 || _outSize != _processedSize 110 || _outSize != _processedSize
113 || _rangeDec.Code == 0) 111 || MY_rangeDec.Code == 0)
114 return S_OK; 112 return S_OK;
115 /* 113 /*
116 // We can decode additional End Marker here: 114 // We can decode additional End Marker here:
@@ -119,7 +117,7 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size)
119 */ 117 */
120 } 118 }
121 119
122 if (sym != PPMD7_SYM_END || _rangeDec.Code != 0) 120 if (sym != PPMD7_SYM_END || MY_rangeDec.Code != 0)
123 { 121 {
124 _status = kStatus_Error; 122 _status = kStatus_Error;
125 return (_res = S_FALSE); 123 return (_res = S_FALSE);
@@ -131,8 +129,8 @@ HRESULT CDecoder::CodeSpec(Byte *memStream, UInt32 size)
131 129
132 130
133 131
134STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 132Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
135 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 133 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
136{ 134{
137 if (!_outBuf) 135 if (!_outBuf)
138 { 136 {
@@ -147,16 +145,16 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
147 do 145 do
148 { 146 {
149 const UInt64 startPos = _processedSize; 147 const UInt64 startPos = _processedSize;
150 HRESULT res = CodeSpec(_outBuf, kBufSize); 148 const HRESULT res = CodeSpec(_outBuf, kBufSize);
151 size_t processed = (size_t)(_processedSize - startPos); 149 const size_t processed = (size_t)(_processedSize - startPos);
152 RINOK(WriteStream(outStream, _outBuf, processed)); 150 RINOK(WriteStream(outStream, _outBuf, processed))
153 RINOK(res); 151 RINOK(res)
154 if (_status == kStatus_Finished_With_Mark) 152 if (_status == kStatus_Finished_With_Mark)
155 break; 153 break;
156 if (progress) 154 if (progress)
157 { 155 {
158 const UInt64 inProcessed = _inStream.GetProcessed(); 156 const UInt64 inProcessed = _inStream.GetProcessed();
159 RINOK(progress->SetRatioInfo(&inProcessed, &_processedSize)); 157 RINOK(progress->SetRatioInfo(&inProcessed, &_processedSize))
160 } 158 }
161 } 159 }
162 while (!_outSizeDefined || _processedSize < _outSize); 160 while (!_outSizeDefined || _processedSize < _outSize);
@@ -168,7 +166,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
168} 166}
169 167
170 168
171STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) 169Z7_COM7F_IMF(CDecoder::SetOutStreamSize(const UInt64 *outSize))
172{ 170{
173 _outSizeDefined = (outSize != NULL); 171 _outSizeDefined = (outSize != NULL);
174 if (_outSizeDefined) 172 if (_outSizeDefined)
@@ -179,37 +177,37 @@ STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
179 return S_OK; 177 return S_OK;
180} 178}
181 179
182STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 180Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
183{ 181{
184 FinishStream = (finishMode != 0); 182 FinishStream = (finishMode != 0);
185 return S_OK; 183 return S_OK;
186} 184}
187 185
188STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 186Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
189{ 187{
190 *value = _inStream.GetProcessed(); 188 *value = _inStream.GetProcessed();
191 return S_OK; 189 return S_OK;
192} 190}
193 191
194#ifndef NO_READ_FROM_CODER 192#ifndef Z7_NO_READ_FROM_CODER
195 193
196STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) 194Z7_COM7F_IMF(CDecoder::SetInStream(ISequentialInStream *inStream))
197{ 195{
198 InSeqStream = inStream; 196 InSeqStream = inStream;
199 _inStream.Stream = inStream; 197 _inStream.Stream = inStream;
200 return S_OK; 198 return S_OK;
201} 199}
202 200
203STDMETHODIMP CDecoder::ReleaseInStream() 201Z7_COM7F_IMF(CDecoder::ReleaseInStream())
204{ 202{
205 InSeqStream.Release(); 203 InSeqStream.Release();
206 return S_OK; 204 return S_OK;
207} 205}
208 206
209STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) 207Z7_COM7F_IMF(CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize))
210{ 208{
211 const UInt64 startPos = _processedSize; 209 const UInt64 startPos = _processedSize;
212 HRESULT res = CodeSpec((Byte *)data, size); 210 const HRESULT res = CodeSpec((Byte *)data, size);
213 if (processedSize) 211 if (processedSize)
214 *processedSize = (UInt32)(_processedSize - startPos); 212 *processedSize = (UInt32)(_processedSize - startPos);
215 return res; 213 return res;
diff --git a/CPP/7zip/Compress/PpmdDecoder.h b/CPP/7zip/Compress/PpmdDecoder.h
index f1a8ee2..22e5bd4 100644
--- a/CPP/7zip/Compress/PpmdDecoder.h
+++ b/CPP/7zip/Compress/PpmdDecoder.h
@@ -1,8 +1,7 @@
1// PpmdDecoder.h 1// PpmdDecoder.h
2// 2020-07-03 : Igor Pavlov : Public domain
3 2
4#ifndef __COMPRESS_PPMD_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_PPMD_DECODER_H
5#define __COMPRESS_PPMD_DECODER_H 4#define ZIP7_INC_COMPRESS_PPMD_DECODER_H
6 5
7#include "../../../C/Ppmd7.h" 6#include "../../../C/Ppmd7.h"
8 7
@@ -15,18 +14,42 @@
15namespace NCompress { 14namespace NCompress {
16namespace NPpmd { 15namespace NPpmd {
17 16
18class CDecoder : 17class CDecoder Z7_final:
19 public ICompressCoder, 18 public ICompressCoder,
20 public ICompressSetDecoderProperties2, 19 public ICompressSetDecoderProperties2,
21 public ICompressSetFinishMode, 20 public ICompressSetFinishMode,
22 public ICompressGetInStreamProcessedSize, 21 public ICompressGetInStreamProcessedSize,
23 #ifndef NO_READ_FROM_CODER 22 #ifndef Z7_NO_READ_FROM_CODER
24 public ICompressSetInStream, 23 public ICompressSetInStream,
25 public ICompressSetOutStreamSize, 24 public ICompressSetOutStreamSize,
26 public ISequentialInStream, 25 public ISequentialInStream,
27 #endif 26 #endif
28 public CMyUnknownImp 27 public CMyUnknownImp
29{ 28{
29 Z7_COM_QI_BEGIN2(ICompressCoder)
30 Z7_COM_QI_ENTRY(ICompressSetDecoderProperties2)
31 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
32 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
33 #ifndef Z7_NO_READ_FROM_CODER
34 Z7_COM_QI_ENTRY(ICompressSetInStream)
35 Z7_COM_QI_ENTRY(ICompressSetOutStreamSize)
36 Z7_COM_QI_ENTRY(ISequentialInStream)
37 #endif
38 Z7_COM_QI_END
39 Z7_COM_ADDREF_RELEASE
40
41 Z7_IFACE_COM7_IMP(ICompressCoder)
42 Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
43 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
44 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
45 #ifndef Z7_NO_READ_FROM_CODER
46 Z7_IFACE_COM7_IMP(ICompressSetOutStreamSize)
47 Z7_IFACE_COM7_IMP(ICompressSetInStream)
48 Z7_IFACE_COM7_IMP(ISequentialInStream)
49 #else
50 Z7_COM7F_IMF(SetOutStreamSize(const UInt64 *outSize));
51 #endif
52
30 Byte *_outBuf; 53 Byte *_outBuf;
31 CByteInBufWrap _inStream; 54 CByteInBufWrap _inStream;
32 CPpmd7 _ppmd; 55 CPpmd7 _ppmd;
@@ -43,36 +66,9 @@ class CDecoder :
43 66
44public: 67public:
45 68
46 #ifndef NO_READ_FROM_CODER 69 #ifndef Z7_NO_READ_FROM_CODER
47 CMyComPtr<ISequentialInStream> InSeqStream; 70 CMyComPtr<ISequentialInStream> InSeqStream;
48 #endif 71 #endif
49
50 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
51 MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2)
52 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
53 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
54 #ifndef NO_READ_FROM_CODER
55 MY_QUERYINTERFACE_ENTRY(ICompressSetInStream)
56 MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize)
57 MY_QUERYINTERFACE_ENTRY(ISequentialInStream)
58 #endif
59 MY_QUERYINTERFACE_END
60 MY_ADDREF_RELEASE
61
62
63 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
64 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
65 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
66 STDMETHOD(SetFinishMode)(UInt32 finishMode);
67 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
68
69 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
70
71 #ifndef NO_READ_FROM_CODER
72 STDMETHOD(SetInStream)(ISequentialInStream *inStream);
73 STDMETHOD(ReleaseInStream)();
74 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
75 #endif
76 72
77 CDecoder(): 73 CDecoder():
78 _outBuf(NULL), 74 _outBuf(NULL),
diff --git a/CPP/7zip/Compress/PpmdEncoder.cpp b/CPP/7zip/Compress/PpmdEncoder.cpp
index d41d2ac..2dfca6d 100644
--- a/CPP/7zip/Compress/PpmdEncoder.cpp
+++ b/CPP/7zip/Compress/PpmdEncoder.cpp
@@ -24,7 +24,7 @@ void CEncProps::Normalize(int level)
24 const unsigned kMult = 16; 24 const unsigned kMult = 16;
25 if (MemSize / kMult > ReduceSize) 25 if (MemSize / kMult > ReduceSize)
26 { 26 {
27 for (unsigned i = 16; i <= 31; i++) 27 for (unsigned i = 16; i < 32; i++)
28 { 28 {
29 UInt32 m = (UInt32)1 << i; 29 UInt32 m = (UInt32)1 << i;
30 if (ReduceSize <= m / kMult) 30 if (ReduceSize <= m / kMult)
@@ -52,7 +52,7 @@ CEncoder::~CEncoder()
52 Ppmd7_Free(&_ppmd, &g_BigAlloc); 52 Ppmd7_Free(&_ppmd, &g_BigAlloc);
53} 53}
54 54
55STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 55Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
56{ 56{
57 int level = -1; 57 int level = -1;
58 CEncProps props; 58 CEncProps props;
@@ -109,7 +109,7 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA
109 109
110 if (prop.vt != VT_UI4) 110 if (prop.vt != VT_UI4)
111 return E_INVALIDARG; 111 return E_INVALIDARG;
112 UInt32 v = (UInt32)prop.ulVal; 112 const UInt32 v = (UInt32)prop.ulVal;
113 switch (propID) 113 switch (propID)
114 { 114 {
115 case NCoderPropID::kOrder: 115 case NCoderPropID::kOrder:
@@ -127,17 +127,17 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA
127 return S_OK; 127 return S_OK;
128} 128}
129 129
130STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) 130Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
131{ 131{
132 const UInt32 kPropSize = 5; 132 const UInt32 kPropSize = 5;
133 Byte props[kPropSize]; 133 Byte props[kPropSize];
134 props[0] = (Byte)_props.Order; 134 props[0] = (Byte)_props.Order;
135 SetUi32(props + 1, _props.MemSize); 135 SetUi32(props + 1, _props.MemSize)
136 return WriteStream(outStream, props, kPropSize); 136 return WriteStream(outStream, props, kPropSize);
137} 137}
138 138
139HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 139Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
140 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 140 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
141{ 141{
142 if (!_inBuf) 142 if (!_inBuf)
143 { 143 {
@@ -160,7 +160,7 @@ HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outS
160 for (;;) 160 for (;;)
161 { 161 {
162 UInt32 size; 162 UInt32 size;
163 RINOK(inStream->Read(_inBuf, kBufSize, &size)); 163 RINOK(inStream->Read(_inBuf, kBufSize, &size))
164 if (size == 0) 164 if (size == 0)
165 { 165 {
166 // We don't write EndMark in PPMD-7z. 166 // We don't write EndMark in PPMD-7z.
@@ -179,13 +179,13 @@ HRESULT CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outS
179 */ 179 */
180 180
181 Ppmd7z_EncodeSymbols(&_ppmd, buf, lim); 181 Ppmd7z_EncodeSymbols(&_ppmd, buf, lim);
182 RINOK(_outStream.Res); 182 RINOK(_outStream.Res)
183 183
184 processed += size; 184 processed += size;
185 if (progress) 185 if (progress)
186 { 186 {
187 const UInt64 outSize = _outStream.GetProcessed(); 187 const UInt64 outSize = _outStream.GetProcessed();
188 RINOK(progress->SetRatioInfo(&processed, &outSize)); 188 RINOK(progress->SetRatioInfo(&processed, &outSize))
189 } 189 }
190 } 190 }
191} 191}
diff --git a/CPP/7zip/Compress/PpmdEncoder.h b/CPP/7zip/Compress/PpmdEncoder.h
index 0104663..057cccb 100644
--- a/CPP/7zip/Compress/PpmdEncoder.h
+++ b/CPP/7zip/Compress/PpmdEncoder.h
@@ -1,7 +1,7 @@
1// PpmdEncoder.h 1// PpmdEncoder.h
2 2
3#ifndef __COMPRESS_PPMD_ENCODER_H 3#ifndef ZIP7_INC_COMPRESS_PPMD_ENCODER_H
4#define __COMPRESS_PPMD_ENCODER_H 4#define ZIP7_INC_COMPRESS_PPMD_ENCODER_H
5 5
6#include "../../../C/Ppmd7.h" 6#include "../../../C/Ppmd7.h"
7 7
@@ -29,25 +29,17 @@ struct CEncProps
29 void Normalize(int level); 29 void Normalize(int level);
30}; 30};
31 31
32class CEncoder : 32Z7_CLASS_IMP_COM_3(
33 public ICompressCoder, 33 CEncoder
34 public ICompressSetCoderProperties, 34 , ICompressCoder
35 public ICompressWriteCoderProperties, 35 , ICompressSetCoderProperties
36 public CMyUnknownImp 36 , ICompressWriteCoderProperties
37{ 37)
38 Byte *_inBuf; 38 Byte *_inBuf;
39 CByteOutBufWrap _outStream; 39 CByteOutBufWrap _outStream;
40 CPpmd7 _ppmd; 40 CPpmd7 _ppmd;
41 CEncProps _props; 41 CEncProps _props;
42public: 42public:
43 MY_UNKNOWN_IMP3(
44 ICompressCoder,
45 ICompressSetCoderProperties,
46 ICompressWriteCoderProperties)
47 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
48 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
49 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
50 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream);
51 CEncoder(); 43 CEncoder();
52 ~CEncoder(); 44 ~CEncoder();
53}; 45};
diff --git a/CPP/7zip/Compress/PpmdRegister.cpp b/CPP/7zip/Compress/PpmdRegister.cpp
index a3ebb5f..fb5619c 100644
--- a/CPP/7zip/Compress/PpmdRegister.cpp
+++ b/CPP/7zip/Compress/PpmdRegister.cpp
@@ -6,7 +6,7 @@
6 6
7#include "PpmdDecoder.h" 7#include "PpmdDecoder.h"
8 8
9#ifndef EXTRACT_ONLY 9#ifndef Z7_EXTRACT_ONLY
10#include "PpmdEncoder.h" 10#include "PpmdEncoder.h"
11#endif 11#endif
12 12
diff --git a/CPP/7zip/Compress/PpmdZip.cpp b/CPP/7zip/Compress/PpmdZip.cpp
index 434e143..5039131 100644
--- a/CPP/7zip/Compress/PpmdZip.cpp
+++ b/CPP/7zip/Compress/PpmdZip.cpp
@@ -24,8 +24,8 @@ CDecoder::~CDecoder()
24 Ppmd8_Free(&_ppmd, &g_BigAlloc); 24 Ppmd8_Free(&_ppmd, &g_BigAlloc);
25} 25}
26 26
27STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 27Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
28 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 28 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
29{ 29{
30 // try { 30 // try {
31 31
@@ -44,10 +44,10 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
44 if (_inStream.Extra) 44 if (_inStream.Extra)
45 return S_FALSE; 45 return S_FALSE;
46 46
47 UInt32 val = GetUi16(buf); 47 const UInt32 val = GetUi16(buf);
48 unsigned order = (val & 0xF) + 1; 48 const unsigned order = (val & 0xF) + 1;
49 UInt32 mem = ((val >> 4) & 0xFF) + 1; 49 const UInt32 mem = ((val >> 4) & 0xFF) + 1;
50 unsigned restor = (val >> 12); 50 const unsigned restor = (val >> 12);
51 if (order < 2 || restor > 2) 51 if (order < 2 || restor > 2)
52 return S_FALSE; 52 return S_FALSE;
53 53
@@ -94,12 +94,12 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
94 } 94 }
95 while (buf != lim); 95 while (buf != lim);
96 96
97 size_t cur = (size_t)(buf - _outStream.Buf); 97 const size_t cur = (size_t)(buf - _outStream.Buf);
98 processedSize += cur; 98 processedSize += cur;
99 99
100 RINOK(WriteStream(outStream, _outStream.Buf, cur)); 100 RINOK(WriteStream(outStream, _outStream.Buf, cur))
101 101
102 RINOK(_inStream.Res); 102 RINOK(_inStream.Res)
103 if (_inStream.Extra) 103 if (_inStream.Extra)
104 return S_FALSE; 104 return S_FALSE;
105 105
@@ -114,18 +114,18 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
114 if (progress) 114 if (progress)
115 { 115 {
116 const UInt64 inProccessed = _inStream.GetProcessed(); 116 const UInt64 inProccessed = _inStream.GetProcessed();
117 RINOK(progress->SetRatioInfo(&inProccessed, &processedSize)); 117 RINOK(progress->SetRatioInfo(&inProccessed, &processedSize))
118 } 118 }
119 } 119 }
120 120
121 RINOK(_inStream.Res); 121 RINOK(_inStream.Res)
122 122
123 if (_fullFileMode) 123 if (_fullFileMode)
124 { 124 {
125 if (!wasFinished) 125 if (!wasFinished)
126 { 126 {
127 int res = Ppmd8_DecodeSymbol(&_ppmd); 127 const int res = Ppmd8_DecodeSymbol(&_ppmd);
128 RINOK(_inStream.Res); 128 RINOK(_inStream.Res)
129 if (_inStream.Extra || res != -1) 129 if (_inStream.Extra || res != -1)
130 return S_FALSE; 130 return S_FALSE;
131 } 131 }
@@ -142,13 +142,13 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
142} 142}
143 143
144 144
145STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 145Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
146{ 146{
147 _fullFileMode = (finishMode != 0); 147 _fullFileMode = (finishMode != 0);
148 return S_OK; 148 return S_OK;
149} 149}
150 150
151STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 151Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
152{ 152{
153 *value = _inStream.GetProcessed(); 153 *value = _inStream.GetProcessed();
154 return S_OK; 154 return S_OK;
@@ -184,14 +184,14 @@ CEncoder::~CEncoder()
184 Ppmd8_Free(&_ppmd, &g_BigAlloc); 184 Ppmd8_Free(&_ppmd, &g_BigAlloc);
185} 185}
186 186
187STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 187Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
188{ 188{
189 int level = -1; 189 int level = -1;
190 CEncProps props; 190 CEncProps props;
191 for (UInt32 i = 0; i < numProps; i++) 191 for (UInt32 i = 0; i < numProps; i++)
192 { 192 {
193 const PROPVARIANT &prop = coderProps[i]; 193 const PROPVARIANT &prop = coderProps[i];
194 PROPID propID = propIDs[i]; 194 const PROPID propID = propIDs[i];
195 if (propID > NCoderPropID::kReduceSize) 195 if (propID > NCoderPropID::kReduceSize)
196 continue; 196 continue;
197 if (propID == NCoderPropID::kReduceSize) 197 if (propID == NCoderPropID::kReduceSize)
@@ -203,7 +203,7 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIA
203 } 203 }
204 if (prop.vt != VT_UI4) 204 if (prop.vt != VT_UI4)
205 return E_INVALIDARG; 205 return E_INVALIDARG;
206 UInt32 v = (UInt32)prop.ulVal; 206 const UInt32 v = (UInt32)prop.ulVal;
207 switch (propID) 207 switch (propID)
208 { 208 {
209 case NCoderPropID::kUsedMemorySize: 209 case NCoderPropID::kUsedMemorySize:
@@ -238,8 +238,8 @@ CEncoder::CEncoder()
238 Ppmd8_Construct(&_ppmd); 238 Ppmd8_Construct(&_ppmd);
239} 239}
240 240
241STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 241Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
242 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 242 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
243{ 243{
244 if (!_inStream.Alloc()) 244 if (!_inStream.Alloc())
245 return E_OUTOFMEMORY; 245 return E_OUTOFMEMORY;
@@ -251,21 +251,21 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream
251 _outStream.Stream = outStream; 251 _outStream.Stream = outStream;
252 _outStream.Init(); 252 _outStream.Init();
253 253
254 Ppmd8_Init_RangeEnc(&_ppmd); 254 Ppmd8_Init_RangeEnc(&_ppmd)
255 Ppmd8_Init(&_ppmd, (unsigned)_props.Order, (unsigned)_props.Restor); 255 Ppmd8_Init(&_ppmd, (unsigned)_props.Order, (unsigned)_props.Restor);
256 256
257 { 257 {
258 UInt32 val = (UInt32)(((unsigned)_props.Order - 1) + ((_props.MemSizeMB - 1) << 4) + ((unsigned)_props.Restor << 12)); 258 const UInt32 val = (UInt32)(((unsigned)_props.Order - 1) + ((_props.MemSizeMB - 1) << 4) + ((unsigned)_props.Restor << 12));
259 _outStream.WriteByte((Byte)(val & 0xFF)); 259 _outStream.WriteByte((Byte)(val & 0xFF));
260 _outStream.WriteByte((Byte)(val >> 8)); 260 _outStream.WriteByte((Byte)(val >> 8));
261 } 261 }
262 RINOK(_outStream.Res); 262 RINOK(_outStream.Res)
263 263
264 UInt64 processed = 0; 264 UInt64 processed = 0;
265 for (;;) 265 for (;;)
266 { 266 {
267 UInt32 size; 267 UInt32 size;
268 RINOK(inStream->Read(_inStream.Buf, kBufSize, &size)); 268 RINOK(inStream->Read(_inStream.Buf, kBufSize, &size))
269 if (size == 0) 269 if (size == 0)
270 { 270 {
271 Ppmd8_EncodeSymbol(&_ppmd, -1); 271 Ppmd8_EncodeSymbol(&_ppmd, -1);
@@ -284,12 +284,12 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream
284 } 284 }
285 while (++buf != lim); 285 while (++buf != lim);
286 286
287 RINOK(_outStream.Res); 287 RINOK(_outStream.Res)
288 288
289 if (progress) 289 if (progress)
290 { 290 {
291 const UInt64 outProccessed = _outStream.GetProcessed(); 291 const UInt64 outProccessed = _outStream.GetProcessed();
292 RINOK(progress->SetRatioInfo(&processed, &outProccessed)); 292 RINOK(progress->SetRatioInfo(&processed, &outProccessed))
293 } 293 }
294 } 294 }
295} 295}
diff --git a/CPP/7zip/Compress/PpmdZip.h b/CPP/7zip/Compress/PpmdZip.h
index 9d1fc4b..a23d008 100644
--- a/CPP/7zip/Compress/PpmdZip.h
+++ b/CPP/7zip/Compress/PpmdZip.h
@@ -1,7 +1,7 @@
1// PpmdZip.h 1// PpmdZip.h
2 2
3#ifndef __COMPRESS_PPMD_ZIP_H 3#ifndef ZIP7_INC_COMPRESS_PPMD_ZIP_H
4#define __COMPRESS_PPMD_ZIP_H 4#define ZIP7_INC_COMPRESS_PPMD_ZIP_H
5 5
6#include "../../../C/Alloc.h" 6#include "../../../C/Alloc.h"
7#include "../../../C/Ppmd8.h" 7#include "../../../C/Ppmd8.h"
@@ -27,31 +27,22 @@ struct CBuf
27 { 27 {
28 if (!Buf) 28 if (!Buf)
29 Buf = (Byte *)::MidAlloc(kBufSize); 29 Buf = (Byte *)::MidAlloc(kBufSize);
30 return (Buf != 0); 30 return (Buf != NULL);
31 } 31 }
32}; 32};
33 33
34 34
35class CDecoder : 35Z7_CLASS_IMP_NOQIB_3(
36 public ICompressCoder, 36 CDecoder
37 public ICompressSetFinishMode, 37 , ICompressCoder
38 public ICompressGetInStreamProcessedSize, 38 , ICompressSetFinishMode
39 public CMyUnknownImp 39 , ICompressGetInStreamProcessedSize
40{ 40)
41 CByteInBufWrap _inStream; 41 CByteInBufWrap _inStream;
42 CBuf _outStream; 42 CBuf _outStream;
43 CPpmd8 _ppmd; 43 CPpmd8 _ppmd;
44 bool _fullFileMode; 44 bool _fullFileMode;
45public: 45public:
46 MY_UNKNOWN_IMP2(
47 ICompressSetFinishMode,
48 ICompressGetInStreamProcessedSize)
49
50 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
51 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
52 STDMETHOD(SetFinishMode)(UInt32 finishMode);
53 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
54
55 CDecoder(bool fullFileMode = true); 46 CDecoder(bool fullFileMode = true);
56 ~CDecoder(); 47 ~CDecoder();
57}; 48};
@@ -74,20 +65,17 @@ struct CEncProps
74 void Normalize(int level); 65 void Normalize(int level);
75}; 66};
76 67
77class CEncoder : 68
78 public ICompressCoder, 69Z7_CLASS_IMP_NOQIB_2(
79 public ICompressSetCoderProperties, 70 CEncoder
80 public CMyUnknownImp 71 , ICompressCoder
81{ 72 , ICompressSetCoderProperties
73)
82 CByteOutBufWrap _outStream; 74 CByteOutBufWrap _outStream;
83 CBuf _inStream; 75 CBuf _inStream;
84 CPpmd8 _ppmd; 76 CPpmd8 _ppmd;
85 CEncProps _props; 77 CEncProps _props;
86public: 78public:
87 MY_UNKNOWN_IMP1(ICompressSetCoderProperties)
88 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
89 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
90 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
91 CEncoder(); 79 CEncoder();
92 ~CEncoder(); 80 ~CEncoder();
93}; 81};
diff --git a/CPP/7zip/Compress/QuantumDecoder.cpp b/CPP/7zip/Compress/QuantumDecoder.cpp
index 8c65058..16ef0fc 100644
--- a/CPP/7zip/Compress/QuantumDecoder.cpp
+++ b/CPP/7zip/Compress/QuantumDecoder.cpp
@@ -33,12 +33,12 @@ void CModelDecoder::Init(unsigned numItems)
33 33
34unsigned CModelDecoder::Decode(CRangeDecoder *rc) 34unsigned CModelDecoder::Decode(CRangeDecoder *rc)
35{ 35{
36 UInt32 threshold = rc->GetThreshold(Freqs[0]); 36 const UInt32 threshold = rc->GetThreshold(Freqs[0]);
37 unsigned i; 37 unsigned i;
38 for (i = 1; Freqs[i] > threshold; i++); 38 for (i = 1; Freqs[i] > threshold; i++);
39 39
40 rc->Decode(Freqs[i], Freqs[(size_t)i - 1], Freqs[0]); 40 rc->Decode(Freqs[i], Freqs[(size_t)i - 1], Freqs[0]);
41 unsigned res = Vals[--i]; 41 const unsigned res = Vals[--i];
42 42
43 do 43 do
44 Freqs[i] = (UInt16)(Freqs[i] + kUpdateStep); 44 Freqs[i] = (UInt16)(Freqs[i] + kUpdateStep);
@@ -55,8 +55,8 @@ unsigned CModelDecoder::Decode(CRangeDecoder *rc)
55 for (unsigned j = i + 1; j < NumItems; j++) 55 for (unsigned j = i + 1; j < NumItems; j++)
56 if (Freqs[i] < Freqs[j]) 56 if (Freqs[i] < Freqs[j])
57 { 57 {
58 UInt16 tmpFreq = Freqs[i]; 58 const UInt16 tmpFreq = Freqs[i];
59 Byte tmpVal = Vals[i]; 59 const Byte tmpVal = Vals[i];
60 Freqs[i] = Freqs[j]; 60 Freqs[i] = Freqs[j];
61 Vals[i] = Vals[j]; 61 Vals[i] = Vals[j];
62 Freqs[j] = tmpFreq; 62 Freqs[j] = tmpFreq;
@@ -90,7 +90,7 @@ void CDecoder::Init()
90 unsigned i; 90 unsigned i;
91 for (i = 0; i < kNumLitSelectors; i++) 91 for (i = 0; i < kNumLitSelectors; i++)
92 m_Literals[i].Init(kNumLitSymbols); 92 m_Literals[i].Init(kNumLitSymbols);
93 unsigned numItems = (_numDictBits == 0 ? 1 : (_numDictBits << 1)); 93 const unsigned numItems = (_numDictBits == 0 ? 1 : (_numDictBits << 1));
94 const unsigned kNumPosSymbolsMax[kNumMatchSelectors] = { 24, 36, 42 }; 94 const unsigned kNumPosSymbolsMax[kNumMatchSelectors] = { 24, 36, 42 };
95 for (i = 0; i < kNumMatchSelectors; i++) 95 for (i = 0; i < kNumMatchSelectors; i++)
96 m_PosSlot[i].Init(MyMin(numItems, kNumPosSymbolsMax[i])); 96 m_PosSlot[i].Init(MyMin(numItems, kNumPosSymbolsMax[i]));
@@ -116,7 +116,7 @@ HRESULT CDecoder::CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize)
116 116
117 if (selector < kNumLitSelectors) 117 if (selector < kNumLitSelectors)
118 { 118 {
119 Byte b = (Byte)((selector << (8 - kNumLitSelectorBits)) + m_Literals[selector].Decode(&rc)); 119 const Byte b = (Byte)((selector << (8 - kNumLitSelectorBits)) + m_Literals[selector].Decode(&rc));
120 _outWindow.PutByte(b); 120 _outWindow.PutByte(b);
121 outSize--; 121 outSize--;
122 } 122 }
@@ -131,7 +131,7 @@ HRESULT CDecoder::CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize)
131 if (lenSlot >= kNumSimpleLenSlots) 131 if (lenSlot >= kNumSimpleLenSlots)
132 { 132 {
133 lenSlot -= 2; 133 lenSlot -= 2;
134 unsigned numDirectBits = (unsigned)(lenSlot >> 2); 134 const unsigned numDirectBits = (unsigned)(lenSlot >> 2);
135 len += ((4 | (lenSlot & 3)) << numDirectBits) - 2; 135 len += ((4 | (lenSlot & 3)) << numDirectBits) - 2;
136 if (numDirectBits < 6) 136 if (numDirectBits < 6)
137 len += rc.Stream.ReadBits(numDirectBits); 137 len += rc.Stream.ReadBits(numDirectBits);
@@ -174,8 +174,8 @@ HRESULT CDecoder::Code(const Byte *inData, size_t inSize,
174 if (!keepHistory) 174 if (!keepHistory)
175 Init(); 175 Init();
176 176
177 HRESULT res = CodeSpec(inData, inSize, outSize); 177 const HRESULT res = CodeSpec(inData, inSize, outSize);
178 HRESULT res2 = _outWindow.Flush(); 178 const HRESULT res2 = _outWindow.Flush();
179 return res != S_OK ? res : res2; 179 return res != S_OK ? res : res2;
180 } 180 }
181 catch(const CLzOutWindowException &e) { return e.ErrorCode; } 181 catch(const CLzOutWindowException &e) { return e.ErrorCode; }
diff --git a/CPP/7zip/Compress/QuantumDecoder.h b/CPP/7zip/Compress/QuantumDecoder.h
index afeba70..925989a 100644
--- a/CPP/7zip/Compress/QuantumDecoder.h
+++ b/CPP/7zip/Compress/QuantumDecoder.h
@@ -1,7 +1,7 @@
1// QuantumDecoder.h 1// QuantumDecoder.h
2 2
3#ifndef __COMPRESS_QUANTUM_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_QUANTUM_DECODER_H
4#define __COMPRESS_QUANTUM_DECODER_H 4#define ZIP7_INC_COMPRESS_QUANTUM_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -142,10 +142,9 @@ public:
142}; 142};
143 143
144 144
145class CDecoder: 145Z7_CLASS_IMP_COM_0(
146 public IUnknown, 146 CDecoder
147 public CMyUnknownImp 147)
148{
149 CLzOutWindow _outWindow; 148 CLzOutWindow _outWindow;
150 unsigned _numDictBits; 149 unsigned _numDictBits;
151 150
@@ -157,17 +156,12 @@ class CDecoder:
157 void Init(); 156 void Init();
158 HRESULT CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize); 157 HRESULT CodeSpec(const Byte *inData, size_t inSize, UInt32 outSize);
159public: 158public:
160
161 MY_UNKNOWN_IMP
162
163 HRESULT Code(const Byte *inData, size_t inSize, 159 HRESULT Code(const Byte *inData, size_t inSize,
164 ISequentialOutStream *outStream, UInt32 outSize, 160 ISequentialOutStream *outStream, UInt32 outSize,
165 bool keepHistory); 161 bool keepHistory);
166
167 HRESULT SetParams(unsigned numDictBits); 162 HRESULT SetParams(unsigned numDictBits);
168 163
169 CDecoder(): _numDictBits(0) {} 164 CDecoder(): _numDictBits(0) {}
170 virtual ~CDecoder() {}
171}; 165};
172 166
173}} 167}}
diff --git a/CPP/7zip/Compress/Rar1Decoder.cpp b/CPP/7zip/Compress/Rar1Decoder.cpp
index 510bbd1..050cde2 100644
--- a/CPP/7zip/Compress/Rar1Decoder.cpp
+++ b/CPP/7zip/Compress/Rar1Decoder.cpp
@@ -39,7 +39,7 @@ static const UInt32 kHistorySize = (1 << 16);
39CDecoder::CDecoder(): 39CDecoder::CDecoder():
40 _isSolid(false), 40 _isSolid(false),
41 _solidAllowed(false) 41 _solidAllowed(false)
42 { } 42 {}
43 43
44UInt32 CDecoder::ReadBits(unsigned numBits) { return m_InBitStream.ReadBits(numBits); } 44UInt32 CDecoder::ReadBits(unsigned numBits) { return m_InBitStream.ReadBits(numBits); }
45 45
@@ -73,8 +73,8 @@ UInt32 CDecoder::DecodeNum(const Byte *numTab)
73 73
74 for (;;) 74 for (;;)
75 { 75 {
76 UInt32 num = numTab[i]; 76 const UInt32 num = numTab[i];
77 UInt32 cur = num << (kNumBits - i); 77 const UInt32 cur = num << (kNumBits - i);
78 if (val < cur) 78 if (val < cur)
79 break; 79 break;
80 i++; 80 i++;
@@ -126,7 +126,7 @@ HRESULT CDecoder::ShortLZ()
126 return CopyBlock(dist, len); 126 return CopyBlock(dist, len);
127 } 127 }
128 128
129 UInt32 saveLen = len; 129 const UInt32 saveLen = len;
130 dist = m_RepDists[(m_RepDistPtr - (len - 9)) & 3]; 130 dist = m_RepDists[(m_RepDistPtr - (len - 9)) & 3];
131 131
132 len = DecodeNum(PosL1); 132 len = DecodeNum(PosL1);
@@ -342,9 +342,9 @@ HRESULT CDecoder::HuffDecode()
342void CDecoder::GetFlagsBuf() 342void CDecoder::GetFlagsBuf()
343{ 343{
344 UInt32 flags, newFlagsPlace; 344 UInt32 flags, newFlagsPlace;
345 UInt32 flagsPlace = DecodeNum(PosHf2); // [0, 256] 345 const UInt32 flagsPlace = DecodeNum(PosHf2); // [0, 256]
346 346
347 if (flagsPlace >= ARRAY_SIZE(ChSetC)) 347 if (flagsPlace >= Z7_ARRAY_SIZE(ChSetC))
348 return; 348 return;
349 349
350 for (;;) 350 for (;;)
@@ -362,15 +362,15 @@ void CDecoder::GetFlagsBuf()
362} 362}
363 363
364 364
365void CDecoder::CorrHuff(UInt32 *CharSet,UInt32 *NumToPlace) 365void CDecoder::CorrHuff(UInt32 *CharSet, UInt32 *NumToPlace)
366{ 366{
367 int i; 367 int i;
368 for (i = 7; i >= 0; i--) 368 for (i = 7; i >= 0; i--)
369 for (int j = 0; j < 32; j++, CharSet++) 369 for (unsigned j = 0; j < 32; j++, CharSet++)
370 *CharSet = (*CharSet & ~0xff) | i; 370 *CharSet = (*CharSet & ~(UInt32)0xff) | (unsigned)i;
371 memset(NumToPlace, 0, sizeof(NToPl)); 371 memset(NumToPlace, 0, sizeof(NToPl));
372 for (i = 6; i >= 0; i--) 372 for (i = 6; i >= 0; i--)
373 NumToPlace[i] = (7 - i) * 32; 373 NumToPlace[i] = (7 - (unsigned)i) * 32;
374} 374}
375 375
376 376
@@ -459,7 +459,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
459 FlagBuf <<= 1; 459 FlagBuf <<= 1;
460 if (Nlzb > Nhfb) 460 if (Nlzb > Nhfb)
461 { 461 {
462 RINOK(LongLZ()); 462 RINOK(LongLZ())
463 continue; 463 continue;
464 } 464 }
465 } 465 }
@@ -476,7 +476,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
476 if ((FlagBuf & 0x80) == 0) 476 if ((FlagBuf & 0x80) == 0)
477 { 477 {
478 FlagBuf <<= 1; 478 FlagBuf <<= 1;
479 RINOK(ShortLZ()); 479 RINOK(ShortLZ())
480 continue; 480 continue;
481 } 481 }
482 482
@@ -484,13 +484,13 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
484 484
485 if (Nlzb <= Nhfb) 485 if (Nlzb <= Nhfb)
486 { 486 {
487 RINOK(LongLZ()); 487 RINOK(LongLZ())
488 continue; 488 continue;
489 } 489 }
490 } 490 }
491 } 491 }
492 492
493 RINOK(HuffDecode()); 493 RINOK(HuffDecode())
494 } 494 }
495 495
496 _solidAllowed = true; 496 _solidAllowed = true;
@@ -498,8 +498,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
498} 498}
499 499
500 500
501STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 501Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
502 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 502 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
503{ 503{
504 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 504 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
505 catch(const CInBufferException &e) { return e.ErrorCode; } 505 catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -507,7 +507,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
507 catch(...) { return S_FALSE; } 507 catch(...) { return S_FALSE; }
508} 508}
509 509
510STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 510Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
511{ 511{
512 if (size < 1) 512 if (size < 1)
513 return E_INVALIDARG; 513 return E_INVALIDARG;
diff --git a/CPP/7zip/Compress/Rar1Decoder.h b/CPP/7zip/Compress/Rar1Decoder.h
index 52907e5..6d0e31d 100644
--- a/CPP/7zip/Compress/Rar1Decoder.h
+++ b/CPP/7zip/Compress/Rar1Decoder.h
@@ -2,8 +2,8 @@
2// According to unRAR license, this code may not be used to develop 2// According to unRAR license, this code may not be used to develop
3// a program that creates RAR archives 3// a program that creates RAR archives
4 4
5#ifndef __COMPRESS_RAR1_DECODER_H 5#ifndef ZIP7_INC_COMPRESS_RAR1_DECODER_H
6#define __COMPRESS_RAR1_DECODER_H 6#define ZIP7_INC_COMPRESS_RAR1_DECODER_H
7 7
8#include "../../Common/MyCom.h" 8#include "../../Common/MyCom.h"
9 9
@@ -20,11 +20,11 @@ namespace NRar1 {
20 20
21const UInt32 kNumRepDists = 4; 21const UInt32 kNumRepDists = 4;
22 22
23class CDecoder : 23Z7_CLASS_IMP_COM_2(
24 public ICompressCoder, 24 CDecoder
25 public ICompressSetDecoderProperties2, 25 , ICompressCoder
26 public CMyUnknownImp 26 , ICompressSetDecoderProperties2
27{ 27)
28 CLzOutWindow m_OutWindowStream; 28 CLzOutWindow m_OutWindowStream;
29 NBitm::CDecoder<CInBuffer> m_InBitStream; 29 NBitm::CDecoder<CInBuffer> m_InBitStream;
30 30
@@ -64,14 +64,6 @@ class CDecoder :
64 64
65public: 65public:
66 CDecoder(); 66 CDecoder();
67
68 MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2)
69
70 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
71 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
72
73 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
74
75}; 67};
76 68
77}} 69}}
diff --git a/CPP/7zip/Compress/Rar2Decoder.cpp b/CPP/7zip/Compress/Rar2Decoder.cpp
index b1c8c2d..92404b6 100644
--- a/CPP/7zip/Compress/Rar2Decoder.cpp
+++ b/CPP/7zip/Compress/Rar2Decoder.cpp
@@ -13,30 +13,32 @@ namespace NRar2 {
13 13
14namespace NMultimedia { 14namespace NMultimedia {
15 15
16#define my_abs(x) (unsigned)abs(x)
17
16Byte CFilter::Decode(int &channelDelta, Byte deltaByte) 18Byte CFilter::Decode(int &channelDelta, Byte deltaByte)
17{ 19{
18 D4 = D3; 20 D4 = D3;
19 D3 = D2; 21 D3 = D2;
20 D2 = LastDelta - D1; 22 D2 = LastDelta - D1;
21 D1 = LastDelta; 23 D1 = LastDelta;
22 int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3); 24 const int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3);
23 25
24 Byte realValue = (Byte)(predictedValue - deltaByte); 26 const Byte realValue = (Byte)(predictedValue - deltaByte);
25 27
26 { 28 {
27 int i = ((int)(signed char)deltaByte) << 3; 29 const int i = ((int)(signed char)deltaByte) << 3;
28 30
29 Dif[0] += abs(i); 31 Dif[0] += my_abs(i);
30 Dif[1] += abs(i - D1); 32 Dif[1] += my_abs(i - D1);
31 Dif[2] += abs(i + D1); 33 Dif[2] += my_abs(i + D1);
32 Dif[3] += abs(i - D2); 34 Dif[3] += my_abs(i - D2);
33 Dif[4] += abs(i + D2); 35 Dif[4] += my_abs(i + D2);
34 Dif[5] += abs(i - D3); 36 Dif[5] += my_abs(i - D3);
35 Dif[6] += abs(i + D3); 37 Dif[6] += my_abs(i + D3);
36 Dif[7] += abs(i - D4); 38 Dif[7] += my_abs(i - D4);
37 Dif[8] += abs(i + D4); 39 Dif[8] += my_abs(i + D4);
38 Dif[9] += abs(i - channelDelta); 40 Dif[9] += my_abs(i - channelDelta);
39 Dif[10] += abs(i + channelDelta); 41 Dif[10] += my_abs(i + channelDelta);
40 } 42 }
41 43
42 channelDelta = LastDelta = (signed char)(realValue - LastChar); 44 channelDelta = LastDelta = (signed char)(realValue - LastChar);
@@ -48,7 +50,7 @@ Byte CFilter::Decode(int &channelDelta, Byte deltaByte)
48 UInt32 numMinDif = 0; 50 UInt32 numMinDif = 0;
49 Dif[0] = 0; 51 Dif[0] = 0;
50 52
51 for (unsigned i = 1; i < ARRAY_SIZE(Dif); i++) 53 for (unsigned i = 1; i < Z7_ARRAY_SIZE(Dif); i++)
52 { 54 {
53 if (Dif[i] < minDif) 55 if (Dif[i] < minDif)
54 { 56 {
@@ -129,13 +131,13 @@ bool CDecoder::ReadTables(void)
129 unsigned i; 131 unsigned i;
130 for (i = 0; i < kLevelTableSize; i++) 132 for (i = 0; i < kLevelTableSize; i++)
131 levelLevels[i] = (Byte)ReadBits(4); 133 levelLevels[i] = (Byte)ReadBits(4);
132 RIF(m_LevelDecoder.Build(levelLevels)); 134 RIF(m_LevelDecoder.Build(levelLevels))
133 135
134 i = 0; 136 i = 0;
135 137
136 do 138 do
137 { 139 {
138 UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream); 140 const UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream);
139 if (sym < kTableDirectLevels) 141 if (sym < kTableDirectLevels)
140 { 142 {
141 lens[i] = (Byte)((sym + m_LastLevels[i]) & kLevelMask); 143 lens[i] = (Byte)((sym + m_LastLevels[i]) & kLevelMask);
@@ -154,7 +156,7 @@ bool CDecoder::ReadTables(void)
154 // return false; 156 // return false;
155 num = numLevels; // original unRAR 157 num = numLevels; // original unRAR
156 } 158 }
157 Byte v = lens[(size_t)i - 1]; 159 const Byte v = lens[(size_t)i - 1];
158 do 160 do
159 lens[i++] = v; 161 lens[i++] = v;
160 while (i < num); 162 while (i < num);
@@ -188,13 +190,13 @@ bool CDecoder::ReadTables(void)
188 if (m_AudioMode) 190 if (m_AudioMode)
189 for (i = 0; i < m_NumChannels; i++) 191 for (i = 0; i < m_NumChannels; i++)
190 { 192 {
191 RIF(m_MMDecoders[i].Build(&lens[i * kMMTableSize])); 193 RIF(m_MMDecoders[i].Build(&lens[i * kMMTableSize]))
192 } 194 }
193 else 195 else
194 { 196 {
195 RIF(m_MainDecoder.Build(&lens[0])); 197 RIF(m_MainDecoder.Build(&lens[0]))
196 RIF(m_DistDecoder.Build(&lens[kMainTableSize])); 198 RIF(m_DistDecoder.Build(&lens[kMainTableSize]))
197 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize])); 199 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize]))
198 } 200 }
199 201
200 memcpy(m_LastLevels, lens, kMaxTableSize); 202 memcpy(m_LastLevels, lens, kMaxTableSize);
@@ -214,7 +216,7 @@ bool CDecoder::ReadLastTables()
214 { 216 {
215 if (m_AudioMode) 217 if (m_AudioMode)
216 { 218 {
217 UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); 219 const UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream);
218 if (symbol == 256) 220 if (symbol == 256)
219 return ReadTables(); 221 return ReadTables();
220 if (symbol >= kMMTableSize) 222 if (symbol >= kMMTableSize)
@@ -222,7 +224,7 @@ bool CDecoder::ReadLastTables()
222 } 224 }
223 else 225 else
224 { 226 {
225 UInt32 sym = m_MainDecoder.Decode(&m_InBitStream); 227 const UInt32 sym = m_MainDecoder.Decode(&m_InBitStream);
226 if (sym == kReadTableNumber) 228 if (sym == kReadTableNumber)
227 return ReadTables(); 229 return ReadTables();
228 if (sym >= kMainTableSize) 230 if (sym >= kMainTableSize)
@@ -237,7 +239,7 @@ bool CDecoder::DecodeMm(UInt32 pos)
237{ 239{
238 while (pos-- != 0) 240 while (pos-- != 0)
239 { 241 {
240 UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream); 242 const UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].Decode(&m_InBitStream);
241 if (m_InBitStream.ExtraBitsWereRead()) 243 if (m_InBitStream.ExtraBitsWereRead())
242 return false; 244 return false;
243 if (symbol >= 256) 245 if (symbol >= 256)
@@ -247,7 +249,7 @@ bool CDecoder::DecodeMm(UInt32 pos)
247 Byte byReal = (Byte)(byPredict - (Byte)symbol); 249 Byte byReal = (Byte)(byPredict - (Byte)symbol);
248 m_Predictor.Update(byReal, byPredict); 250 m_Predictor.Update(byReal, byPredict);
249 */ 251 */
250 Byte byReal = m_MmFilter.Decode((Byte)symbol); 252 const Byte byReal = m_MmFilter.Decode((Byte)symbol);
251 m_OutWindowStream.PutByte(byReal); 253 m_OutWindowStream.PutByte(byReal);
252 if (++m_MmFilter.CurrentChannel == m_NumChannels) 254 if (++m_MmFilter.CurrentChannel == m_NumChannels)
253 m_MmFilter.CurrentChannel = 0; 255 m_MmFilter.CurrentChannel = 0;
@@ -375,7 +377,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
375 if (!m_TablesOK) 377 if (!m_TablesOK)
376 return S_FALSE; 378 return S_FALSE;
377 379
378 UInt64 startPos = m_OutWindowStream.GetProcessedSize(); 380 const UInt64 startPos = m_OutWindowStream.GetProcessedSize();
379 while (pos < unPackSize) 381 while (pos < unPackSize)
380 { 382 {
381 UInt32 blockSize = 1 << 20; 383 UInt32 blockSize = 1 << 20;
@@ -396,7 +398,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
396 if (m_InBitStream.ExtraBitsWereRead()) 398 if (m_InBitStream.ExtraBitsWereRead())
397 return S_FALSE; 399 return S_FALSE;
398 400
399 UInt64 globalPos = m_OutWindowStream.GetProcessedSize(); 401 const UInt64 globalPos = m_OutWindowStream.GetProcessedSize();
400 pos = globalPos - blockStartPos; 402 pos = globalPos - blockStartPos;
401 if (pos < blockSize) 403 if (pos < blockSize)
402 if (!ReadTables()) 404 if (!ReadTables())
@@ -405,7 +407,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
405 if (progress) 407 if (progress)
406 { 408 {
407 const UInt64 packSize = m_InBitStream.GetProcessedSize(); 409 const UInt64 packSize = m_InBitStream.GetProcessedSize();
408 RINOK(progress->SetRatioInfo(&packSize, &pos)); 410 RINOK(progress->SetRatioInfo(&packSize, &pos))
409 } 411 }
410 } 412 }
411 if (pos > unPackSize) 413 if (pos > unPackSize)
@@ -419,8 +421,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
419 return m_OutWindowStream.Flush(); 421 return m_OutWindowStream.Flush();
420} 422}
421 423
422STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 424Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
423 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 425 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
424{ 426{
425 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 427 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
426 catch(const CInBufferException &e) { return e.ErrorCode; } 428 catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -428,7 +430,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
428 catch(...) { return S_FALSE; } 430 catch(...) { return S_FALSE; }
429} 431}
430 432
431STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 433Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
432{ 434{
433 if (size < 1) 435 if (size < 1)
434 return E_INVALIDARG; 436 return E_INVALIDARG;
diff --git a/CPP/7zip/Compress/Rar2Decoder.h b/CPP/7zip/Compress/Rar2Decoder.h
index f42f228..d77bfc1 100644
--- a/CPP/7zip/Compress/Rar2Decoder.h
+++ b/CPP/7zip/Compress/Rar2Decoder.h
@@ -2,8 +2,8 @@
2// According to unRAR license, this code may not be used to develop 2// According to unRAR license, this code may not be used to develop
3// a program that creates RAR archives 3// a program that creates RAR archives
4 4
5#ifndef __COMPRESS_RAR2_DECODER_H 5#ifndef ZIP7_INC_COMPRESS_RAR2_DECODER_H
6#define __COMPRESS_RAR2_DECODER_H 6#define ZIP7_INC_COMPRESS_RAR2_DECODER_H
7 7
8#include "../../Common/MyCom.h" 8#include "../../Common/MyCom.h"
9 9
@@ -112,11 +112,11 @@ typedef NBitm::CDecoder<CInBuffer> CBitDecoder;
112 112
113const unsigned kNumHuffmanBits = 15; 113const unsigned kNumHuffmanBits = 15;
114 114
115class CDecoder : 115Z7_CLASS_IMP_NOQIB_2(
116 public ICompressCoder, 116 CDecoder
117 public ICompressSetDecoderProperties2, 117 , ICompressCoder
118 public CMyUnknownImp 118 , ICompressSetDecoderProperties2
119{ 119)
120 CLzOutWindow m_OutWindowStream; 120 CLzOutWindow m_OutWindowStream;
121 CBitDecoder m_InBitStream; 121 CBitDecoder m_InBitStream;
122 122
@@ -157,14 +157,6 @@ class CDecoder :
157 157
158public: 158public:
159 CDecoder(); 159 CDecoder();
160
161 MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2)
162
163 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
164 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
165
166 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
167
168}; 160};
169 161
170}} 162}}
diff --git a/CPP/7zip/Compress/Rar3Decoder.cpp b/CPP/7zip/Compress/Rar3Decoder.cpp
index 2271dcc..a4943ad 100644
--- a/CPP/7zip/Compress/Rar3Decoder.cpp
+++ b/CPP/7zip/Compress/Rar3Decoder.cpp
@@ -38,15 +38,15 @@ static const UInt32 kVmCodeSizeMax = 1 << 16;
38 38
39extern "C" { 39extern "C" {
40 40
41static Byte Wrap_ReadByte(const IByteIn *pp) throw() 41static Byte Wrap_ReadByte(IByteInPtr pp) throw()
42{ 42{
43 CByteIn *p = CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); 43 CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj);
44 return p->BitDecoder.Stream.ReadByte(); 44 return p->BitDecoder.Stream.ReadByte();
45} 45}
46 46
47static Byte Wrap_ReadBits8(const IByteIn *pp) throw() 47static Byte Wrap_ReadBits8(IByteInPtr pp) throw()
48{ 48{
49 CByteIn *p = CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj); 49 CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj);
50 return (Byte)p->BitDecoder.ReadByteFromAligned(); 50 return (Byte)p->BitDecoder.ReadByteFromAligned();
51} 51}
52 52
@@ -54,13 +54,13 @@ static Byte Wrap_ReadBits8(const IByteIn *pp) throw()
54 54
55 55
56CDecoder::CDecoder(): 56CDecoder::CDecoder():
57 _window(0), 57 _window(NULL),
58 _winPos(0), 58 _winPos(0),
59 _wrPtr(0), 59 _wrPtr(0),
60 _lzSize(0), 60 _lzSize(0),
61 _writtenFileSize(0), 61 _writtenFileSize(0),
62 _vmData(0), 62 _vmData(NULL),
63 _vmCode(0), 63 _vmCode(NULL),
64 _isSolid(false), 64 _isSolid(false),
65 _solidAllowed(false) 65 _solidAllowed(false)
66{ 66{
@@ -106,7 +106,7 @@ HRESULT CDecoder::WriteArea(UInt32 startPtr, UInt32 endPtr)
106{ 106{
107 if (startPtr <= endPtr) 107 if (startPtr <= endPtr)
108 return WriteData(_window + startPtr, endPtr - startPtr); 108 return WriteData(_window + startPtr, endPtr - startPtr);
109 RINOK(WriteData(_window + startPtr, kWindowSize - startPtr)); 109 RINOK(WriteData(_window + startPtr, kWindowSize - startPtr))
110 return WriteData(_window, endPtr); 110 return WriteData(_window, endPtr);
111} 111}
112 112
@@ -146,7 +146,7 @@ HRESULT CDecoder::WriteBuf()
146 { 146 {
147 if (writtenBorder != blockStart) 147 if (writtenBorder != blockStart)
148 { 148 {
149 RINOK(WriteArea(writtenBorder, blockStart)); 149 RINOK(WriteArea(writtenBorder, blockStart))
150 writtenBorder = blockStart; 150 writtenBorder = blockStart;
151 writeSize = (_winPos - writtenBorder) & kWindowMask; 151 writeSize = (_winPos - writtenBorder) & kWindowMask;
152 } 152 }
@@ -353,26 +353,26 @@ bool CDecoder::ReadVmCodeLZ()
353 353
354bool CDecoder::ReadVmCodePPM() 354bool CDecoder::ReadVmCodePPM()
355{ 355{
356 int firstByte = DecodePpmSymbol(); 356 const int firstByte = DecodePpmSymbol();
357 if (firstByte < 0) 357 if (firstByte < 0)
358 return false; 358 return false;
359 UInt32 len = (firstByte & 7) + 1; 359 UInt32 len = (firstByte & 7) + 1;
360 if (len == 7) 360 if (len == 7)
361 { 361 {
362 int b1 = DecodePpmSymbol(); 362 const int b1 = DecodePpmSymbol();
363 if (b1 < 0) 363 if (b1 < 0)
364 return false; 364 return false;
365 len = b1 + 7; 365 len = (unsigned)b1 + 7;
366 } 366 }
367 else if (len == 8) 367 else if (len == 8)
368 { 368 {
369 int b1 = DecodePpmSymbol(); 369 const int b1 = DecodePpmSymbol();
370 if (b1 < 0) 370 if (b1 < 0)
371 return false; 371 return false;
372 int b2 = DecodePpmSymbol(); 372 const int b2 = DecodePpmSymbol();
373 if (b2 < 0) 373 if (b2 < 0)
374 return false; 374 return false;
375 len = b1 * 256 + b2; 375 len = (unsigned)b1 * 256 + (unsigned)b2;
376 } 376 }
377 if (len > kVmDataSizeMax) 377 if (len > kVmDataSizeMax)
378 return false; 378 return false;
@@ -380,12 +380,12 @@ bool CDecoder::ReadVmCodePPM()
380 return false; 380 return false;
381 for (UInt32 i = 0; i < len; i++) 381 for (UInt32 i = 0; i < len; i++)
382 { 382 {
383 int b = DecodePpmSymbol(); 383 const int b = DecodePpmSymbol();
384 if (b < 0) 384 if (b < 0)
385 return false; 385 return false;
386 _vmData[i] = (Byte)b; 386 _vmData[i] = (Byte)b;
387 } 387 }
388 return AddVmCode(firstByte, len); 388 return AddVmCode((unsigned)firstByte, len);
389} 389}
390 390
391#define RIF(x) { if (!(x)) return S_FALSE; } 391#define RIF(x) { if (!(x)) return S_FALSE; }
@@ -398,7 +398,7 @@ HRESULT CDecoder::InitPPM()
398{ 398{
399 unsigned maxOrder = (unsigned)ReadBits(7); 399 unsigned maxOrder = (unsigned)ReadBits(7);
400 400
401 bool reset = ((maxOrder & 0x20) != 0); 401 const bool reset = ((maxOrder & 0x20) != 0);
402 UInt32 maxMB = 0; 402 UInt32 maxMB = 0;
403 if (reset) 403 if (reset)
404 maxMB = (Byte)Wrap_ReadBits8(&m_InBitStream.IByteIn_obj); 404 maxMB = (Byte)Wrap_ReadBits8(&m_InBitStream.IByteIn_obj);
@@ -446,7 +446,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing)
446 { 446 {
447 if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) 447 if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos)
448 { 448 {
449 RINOK(WriteBuf()); 449 RINOK(WriteBuf())
450 if (_writtenFileSize > _unpackSize) 450 if (_writtenFileSize > _unpackSize)
451 { 451 {
452 keepDecompressing = false; 452 keepDecompressing = false;
@@ -455,7 +455,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing)
455 } 455 }
456 if (InputEofError_Fast()) 456 if (InputEofError_Fast())
457 return false; 457 return false;
458 int c = DecodePpmSymbol(); 458 const int c = DecodePpmSymbol();
459 if (c < 0) 459 if (c < 0)
460 { 460 {
461 PpmError = true; 461 PpmError = true;
@@ -463,7 +463,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing)
463 } 463 }
464 if (c == PpmEscChar) 464 if (c == PpmEscChar)
465 { 465 {
466 int nextCh = DecodePpmSymbol(); 466 const int nextCh = DecodePpmSymbol();
467 if (nextCh < 0) 467 if (nextCh < 0)
468 { 468 {
469 PpmError = true; 469 PpmError = true;
@@ -490,7 +490,7 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing)
490 { 490 {
491 for (int i = 0; i < 3; i++) 491 for (int i = 0; i < 3; i++)
492 { 492 {
493 int c2 = DecodePpmSymbol(); 493 const int c2 = DecodePpmSymbol();
494 if (c2 < 0) 494 if (c2 < 0)
495 { 495 {
496 PpmError = true; 496 PpmError = true;
@@ -501,13 +501,13 @@ HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing)
501 dist++; 501 dist++;
502 len += 28; 502 len += 28;
503 } 503 }
504 int c2 = DecodePpmSymbol(); 504 const int c2 = DecodePpmSymbol();
505 if (c2 < 0) 505 if (c2 < 0)
506 { 506 {
507 PpmError = true; 507 PpmError = true;
508 return S_FALSE; 508 return S_FALSE;
509 } 509 }
510 len += c2; 510 len += (unsigned)c2;
511 if (dist >= _lzSize) 511 if (dist >= _lzSize)
512 return S_FALSE; 512 return S_FALSE;
513 CopyBlock(dist, len); 513 CopyBlock(dist, len);
@@ -552,7 +552,7 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing)
552 552
553 for (i = 0; i < kLevelTableSize; i++) 553 for (i = 0; i < kLevelTableSize; i++)
554 { 554 {
555 UInt32 len = ReadBits(4); 555 const UInt32 len = ReadBits(4);
556 if (len == 15) 556 if (len == 15)
557 { 557 {
558 UInt32 zeroCount = ReadBits(4); 558 UInt32 zeroCount = ReadBits(4);
@@ -568,13 +568,13 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing)
568 levelLevels[i] = (Byte)len; 568 levelLevels[i] = (Byte)len;
569 } 569 }
570 570
571 RIF(m_LevelDecoder.Build(levelLevels)); 571 RIF(m_LevelDecoder.Build(levelLevels))
572 572
573 i = 0; 573 i = 0;
574 574
575 do 575 do
576 { 576 {
577 UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream.BitDecoder); 577 const UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream.BitDecoder);
578 if (sym < 16) 578 if (sym < 16)
579 { 579 {
580 lens[i] = Byte((sym + m_LastLevels[i]) & 15); 580 lens[i] = Byte((sym + m_LastLevels[i]) & 15);
@@ -617,10 +617,10 @@ HRESULT CDecoder::ReadTables(bool &keepDecompressing)
617 } 617 }
618 */ 618 */
619 619
620 RIF(m_MainDecoder.Build(&lens[0])); 620 RIF(m_MainDecoder.Build(&lens[0]))
621 RIF(m_DistDecoder.Build(&lens[kMainTableSize])); 621 RIF(m_DistDecoder.Build(&lens[kMainTableSize]))
622 RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])); 622 RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize]))
623 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])); 623 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize]))
624 624
625 memcpy(m_LastLevels, lens, kTablesSizesSum); 625 memcpy(m_LastLevels, lens, kTablesSizesSum);
626 626
@@ -667,7 +667,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing)
667 { 667 {
668 if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) 668 if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos)
669 { 669 {
670 RINOK(WriteBuf()); 670 RINOK(WriteBuf())
671 if (_writtenFileSize > _unpackSize) 671 if (_writtenFileSize > _unpackSize)
672 { 672 {
673 keepDecompressing = false; 673 keepDecompressing = false;
@@ -686,7 +686,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing)
686 } 686 }
687 else if (sym == kSymbolReadTable) 687 else if (sym == kSymbolReadTable)
688 { 688 {
689 RINOK(ReadEndOfBlock(keepDecompressing)); 689 RINOK(ReadEndOfBlock(keepDecompressing))
690 break; 690 break;
691 } 691 }
692 else if (sym == 257) 692 else if (sym == 257)
@@ -749,7 +749,7 @@ HRESULT CDecoder::DecodeLZ(bool &keepDecompressing)
749 len = kNormalMatchMinLen + sym; 749 len = kNormalMatchMinLen + sym;
750 if (sym >= 8) 750 if (sym >= 8)
751 { 751 {
752 unsigned num = (sym >> 2) - 1; 752 const unsigned num = (sym >> 2) - 1;
753 len = kNormalMatchMinLen + ((4 + (sym & 3)) << num) + m_InBitStream.BitDecoder.ReadBits_upto8(num); 753 len = kNormalMatchMinLen + ((4 + (sym & 3)) << num) + m_InBitStream.BitDecoder.ReadBits_upto8(num);
754 } 754 }
755 const UInt32 sym2 = m_DistDecoder.Decode(&m_InBitStream.BitDecoder); 755 const UInt32 sym2 = m_DistDecoder.Decode(&m_InBitStream.BitDecoder);
@@ -833,7 +833,7 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress)
833 if (!_isSolid || !TablesRead) 833 if (!_isSolid || !TablesRead)
834 { 834 {
835 bool keepDecompressing; 835 bool keepDecompressing;
836 RINOK(ReadTables(keepDecompressing)); 836 RINOK(ReadTables(keepDecompressing))
837 if (!keepDecompressing) 837 if (!keepDecompressing)
838 { 838 {
839 _solidAllowed = true; 839 _solidAllowed = true;
@@ -858,17 +858,17 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress)
858 if (InputEofError()) 858 if (InputEofError())
859 return S_FALSE; 859 return S_FALSE;
860 860
861 UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); 861 const UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize();
862 RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); 862 RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize))
863 if (!keepDecompressing) 863 if (!keepDecompressing)
864 break; 864 break;
865 } 865 }
866 866
867 _solidAllowed = true; 867 _solidAllowed = true;
868 868
869 RINOK(WriteBuf()); 869 RINOK(WriteBuf())
870 UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize(); 870 const UInt64 packSize = m_InBitStream.BitDecoder.GetProcessedSize();
871 RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); 871 RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize))
872 if (_writtenFileSize < _unpackSize) 872 if (_writtenFileSize < _unpackSize)
873 return S_FALSE; 873 return S_FALSE;
874 874
@@ -878,8 +878,8 @@ HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress)
878 return S_OK; 878 return S_OK;
879} 879}
880 880
881STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 881Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
882 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 882 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
883{ 883{
884 try 884 try
885 { 885 {
@@ -924,7 +924,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
924 // by error in data stream. 924 // by error in data stream.
925} 925}
926 926
927STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 927Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
928{ 928{
929 if (size < 1) 929 if (size < 1)
930 return E_INVALIDARG; 930 return E_INVALIDARG;
diff --git a/CPP/7zip/Compress/Rar3Decoder.h b/CPP/7zip/Compress/Rar3Decoder.h
index fdecc55..4711052 100644
--- a/CPP/7zip/Compress/Rar3Decoder.h
+++ b/CPP/7zip/Compress/Rar3Decoder.h
@@ -4,8 +4,8 @@
4 4
5/* This code uses Carryless rangecoder (1999): Dmitry Subbotin : Public domain */ 5/* This code uses Carryless rangecoder (1999): Dmitry Subbotin : Public domain */
6 6
7#ifndef __COMPRESS_RAR3_DECODER_H 7#ifndef ZIP7_INC_COMPRESS_RAR3_DECODER_H
8#define __COMPRESS_RAR3_DECODER_H 8#define ZIP7_INC_COMPRESS_RAR3_DECODER_H
9 9
10#include "../../../C/Ppmd7.h" 10#include "../../../C/Ppmd7.h"
11 11
@@ -156,11 +156,11 @@ struct CTempFilter: public NVm::CProgramInitState
156 156
157const unsigned kNumHuffmanBits = 15; 157const unsigned kNumHuffmanBits = 15;
158 158
159class CDecoder: 159Z7_CLASS_IMP_NOQIB_2(
160 public ICompressCoder, 160 CDecoder
161 public ICompressSetDecoderProperties2, 161 , ICompressCoder
162 public CMyUnknownImp 162 , ICompressSetDecoderProperties2
163{ 163)
164 CByteIn m_InBitStream; 164 CByteIn m_InBitStream;
165 Byte *_window; 165 Byte *_window;
166 UInt32 _winPos; 166 UInt32 _winPos;
@@ -231,17 +231,6 @@ class CDecoder:
231 bool InputEofError() const { return m_InBitStream.BitDecoder.ExtraBitsWereRead(); } 231 bool InputEofError() const { return m_InBitStream.BitDecoder.ExtraBitsWereRead(); }
232 bool InputEofError_Fast() const { return (m_InBitStream.BitDecoder.Stream.NumExtraBytes > 2); } 232 bool InputEofError_Fast() const { return (m_InBitStream.BitDecoder.Stream.NumExtraBytes > 2); }
233 233
234public:
235 CDecoder();
236 ~CDecoder();
237
238 MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2)
239
240 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
241 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
242
243 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
244
245 void CopyBlock(UInt32 dist, UInt32 len) 234 void CopyBlock(UInt32 dist, UInt32 len)
246 { 235 {
247 _lzSize += len; 236 _lzSize += len;
@@ -270,11 +259,15 @@ public:
270 259
271 void PutByte(Byte b) 260 void PutByte(Byte b)
272 { 261 {
273 UInt32 wp = _winPos; 262 const UInt32 wp = _winPos;
274 _window[wp] = b; 263 _window[wp] = b;
275 _winPos = (wp + 1) & kWindowMask; 264 _winPos = (wp + 1) & kWindowMask;
276 _lzSize++; 265 _lzSize++;
277 } 266 }
267
268public:
269 CDecoder();
270 ~CDecoder();
278}; 271};
279 272
280}} 273}}
diff --git a/CPP/7zip/Compress/Rar3Vm.cpp b/CPP/7zip/Compress/Rar3Vm.cpp
index 6accd08..9b728ef 100644
--- a/CPP/7zip/Compress/Rar3Vm.cpp
+++ b/CPP/7zip/Compress/Rar3Vm.cpp
@@ -29,8 +29,8 @@ UInt32 CMemBitDecoder::ReadBits(unsigned numBits)
29 UInt32 res = 0; 29 UInt32 res = 0;
30 for (;;) 30 for (;;)
31 { 31 {
32 unsigned b = _bitPos < _bitSize ? (unsigned)_data[_bitPos >> 3] : 0; 32 const unsigned b = _bitPos < _bitSize ? (unsigned)_data[_bitPos >> 3] : 0;
33 unsigned avail = (unsigned)(8 - (_bitPos & 7)); 33 const unsigned avail = (unsigned)(8 - (_bitPos & 7));
34 if (numBits <= avail) 34 if (numBits <= avail)
35 { 35 {
36 _bitPos += numBits; 36 _bitPos += numBits;
@@ -46,8 +46,8 @@ UInt32 CMemBitDecoder::ReadBit() { return ReadBits(1); }
46 46
47UInt32 CMemBitDecoder::ReadEncodedUInt32() 47UInt32 CMemBitDecoder::ReadEncodedUInt32()
48{ 48{
49 unsigned v = (unsigned)ReadBits(2); 49 const unsigned v = (unsigned)ReadBits(2);
50 UInt32 res = ReadBits(4 << v); 50 UInt32 res = ReadBits(4u << v);
51 if (v == 1 && res < 16) 51 if (v == 1 && res < 16)
52 res = 0xFFFFFF00 | (res << 4) | ReadBits(4); 52 res = 0xFFFFFF00 | (res << 4) | ReadBits(4);
53 return res; 53 return res;
@@ -57,7 +57,13 @@ namespace NVm {
57 57
58static const UInt32 kStackRegIndex = kNumRegs - 1; 58static const UInt32 kStackRegIndex = kNumRegs - 1;
59 59
60#ifdef RARVM_VM_ENABLE 60#ifdef Z7_RARVM_VM_ENABLE
61
62#if defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40400) \
63 || defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 30000)
64// enumeration values not explicitly handled in switch
65#pragma GCC diagnostic ignored "-Wswitch-enum"
66#endif
61 67
62static const UInt32 FLAG_C = 1; 68static const UInt32 FLAG_C = 1;
63static const UInt32 FLAG_Z = 2; 69static const UInt32 FLAG_Z = 2;
@@ -144,7 +150,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState,
144 R[kNumRegs] = 0; 150 R[kNumRegs] = 0;
145 Flags = 0; 151 Flags = 0;
146 152
147 UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize); 153 const UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize);
148 if (globalSize != 0) 154 if (globalSize != 0)
149 memcpy(Mem + kGlobalOffset, &initState->GlobalData[0], globalSize); 155 memcpy(Mem + kGlobalOffset, &initState->GlobalData[0], globalSize);
150 UInt32 staticSize = MyMin((UInt32)prg->StaticData.Size(), kGlobalSize - globalSize); 156 UInt32 staticSize = MyMin((UInt32)prg->StaticData.Size(), kGlobalSize - globalSize);
@@ -153,13 +159,13 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState,
153 159
154 bool res = true; 160 bool res = true;
155 161
156 #ifdef RARVM_STANDARD_FILTERS 162 #ifdef Z7_RARVM_STANDARD_FILTERS
157 if (prg->StandardFilterIndex >= 0) 163 if (prg->StandardFilterIndex >= 0)
158 res = ExecuteStandardFilter(prg->StandardFilterIndex); 164 res = ExecuteStandardFilter((unsigned)prg->StandardFilterIndex);
159 else 165 else
160 #endif 166 #endif
161 { 167 {
162 #ifdef RARVM_VM_ENABLE 168 #ifdef Z7_RARVM_VM_ENABLE
163 res = ExecuteCode(prg); 169 res = ExecuteCode(prg);
164 if (!res) 170 if (!res)
165 { 171 {
@@ -192,7 +198,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState,
192 return res; 198 return res;
193} 199}
194 200
195#ifdef RARVM_VM_ENABLE 201#ifdef Z7_RARVM_VM_ENABLE
196 202
197#define SET_IP(IP) \ 203#define SET_IP(IP) \
198 if ((IP) >= numCommands) return true; \ 204 if ((IP) >= numCommands) return true; \
@@ -200,7 +206,7 @@ bool CVm::Execute(CProgram *prg, const CProgramInitState *initState,
200 cmd = commands + (IP); 206 cmd = commands + (IP);
201 207
202#define GET_FLAG_S_B(res) (((res) & 0x80) ? FLAG_S : 0) 208#define GET_FLAG_S_B(res) (((res) & 0x80) ? FLAG_S : 0)
203#define SET_IP_OP1 { UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val); } 209#define SET_IP_OP1 { const UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val) }
204#define FLAGS_UPDATE_SZ Flags = res == 0 ? FLAG_Z : res & FLAG_S 210#define FLAGS_UPDATE_SZ Flags = res == 0 ? FLAG_Z : res & FLAG_S
205#define FLAGS_UPDATE_SZ_B Flags = (res & 0xFF) == 0 ? FLAG_Z : GET_FLAG_S_B(res) 211#define FLAGS_UPDATE_SZ_B Flags = (res & 0xFF) == 0 ? FLAG_Z : GET_FLAG_S_B(res)
206 212
@@ -220,6 +226,7 @@ void CVm::SetOperand32(const COperand *op, UInt32 val)
220 { 226 {
221 case OP_TYPE_REG: R[op->Data] = val; return; 227 case OP_TYPE_REG: R[op->Data] = val; return;
222 case OP_TYPE_REGMEM: SetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask], val); return; 228 case OP_TYPE_REGMEM: SetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask], val); return;
229 default: break;
223 } 230 }
224} 231}
225 232
@@ -228,7 +235,7 @@ Byte CVm::GetOperand8(const COperand *op) const
228 switch (op->Type) 235 switch (op->Type)
229 { 236 {
230 case OP_TYPE_REG: return (Byte)R[op->Data]; 237 case OP_TYPE_REG: return (Byte)R[op->Data];
231 case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask];; 238 case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask];
232 default: return (Byte)op->Data; 239 default: return (Byte)op->Data;
233 } 240 }
234} 241}
@@ -239,6 +246,7 @@ void CVm::SetOperand8(const COperand *op, Byte val)
239 { 246 {
240 case OP_TYPE_REG: R[op->Data] = (R[op->Data] & 0xFFFFFF00) | val; return; 247 case OP_TYPE_REG: R[op->Data] = (R[op->Data] & 0xFFFFFF00) | val; return;
241 case OP_TYPE_REGMEM: Mem[(op->Base + R[op->Data]) & kSpaceMask] = val; return; 248 case OP_TYPE_REGMEM: Mem[(op->Base + R[op->Data]) & kSpaceMask] = val; return;
249 default: break;
242 } 250 }
243} 251}
244 252
@@ -262,7 +270,7 @@ bool CVm::ExecuteCode(const CProgram *prg)
262 Int32 maxOpCount = 25000000; 270 Int32 maxOpCount = 25000000;
263 const CCommand *commands = &prg->Commands[0]; 271 const CCommand *commands = &prg->Commands[0];
264 const CCommand *cmd = commands; 272 const CCommand *cmd = commands;
265 UInt32 numCommands = prg->Commands.Size(); 273 const UInt32 numCommands = prg->Commands.Size();
266 if (numCommands == 0) 274 if (numCommands == 0)
267 return false; 275 return false;
268 276
@@ -278,152 +286,152 @@ bool CVm::ExecuteCode(const CProgram *prg)
278 break; 286 break;
279 case CMD_CMP: 287 case CMD_CMP:
280 { 288 {
281 UInt32 v1 = GetOperand32(&cmd->Op1); 289 const UInt32 v1 = GetOperand32(&cmd->Op1);
282 UInt32 res = v1 - GetOperand32(&cmd->Op2); 290 const UInt32 res = v1 - GetOperand32(&cmd->Op2);
283 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); 291 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S);
284 } 292 }
285 break; 293 break;
286 case CMD_CMPB: 294 case CMD_CMPB:
287 { 295 {
288 Byte v1 = GetOperand8(&cmd->Op1); 296 const Byte v1 = GetOperand8(&cmd->Op1);
289 Byte res = (Byte)((v1 - GetOperand8(&cmd->Op2)) & 0xFF); 297 const Byte res = (Byte)((v1 - GetOperand8(&cmd->Op2)) & 0xFF);
290 Flags = res == 0 ? FLAG_Z : (res > v1) | GET_FLAG_S_B(res); 298 Flags = res == 0 ? FLAG_Z : (res > v1) | GET_FLAG_S_B(res);
291 } 299 }
292 break; 300 break;
293 case CMD_ADD: 301 case CMD_ADD:
294 { 302 {
295 UInt32 v1 = GetOperand32(&cmd->Op1); 303 const UInt32 v1 = GetOperand32(&cmd->Op1);
296 UInt32 res = v1 + GetOperand32(&cmd->Op2); 304 const UInt32 res = v1 + GetOperand32(&cmd->Op2);
297 SetOperand32(&cmd->Op1, res); 305 SetOperand32(&cmd->Op1, res);
298 Flags = (res < v1) | (res == 0 ? FLAG_Z : (res & FLAG_S)); 306 Flags = (res < v1) | (res == 0 ? FLAG_Z : (res & FLAG_S));
299 } 307 }
300 break; 308 break;
301 case CMD_ADDB: 309 case CMD_ADDB:
302 { 310 {
303 Byte v1 = GetOperand8(&cmd->Op1); 311 const Byte v1 = GetOperand8(&cmd->Op1);
304 Byte res = (Byte)((v1 + GetOperand8(&cmd->Op2)) & 0xFF); 312 const Byte res = (Byte)((v1 + GetOperand8(&cmd->Op2)) & 0xFF);
305 SetOperand8(&cmd->Op1, (Byte)res); 313 SetOperand8(&cmd->Op1, (Byte)res);
306 Flags = (res < v1) | (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)); 314 Flags = (res < v1) | (res == 0 ? FLAG_Z : GET_FLAG_S_B(res));
307 } 315 }
308 break; 316 break;
309 case CMD_ADC: 317 case CMD_ADC:
310 { 318 {
311 UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); 319 const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1);
312 UInt32 FC = (Flags & FLAG_C); 320 const UInt32 FC = (Flags & FLAG_C);
313 UInt32 res = v1 + GetOperand(cmd->ByteMode, &cmd->Op2) + FC; 321 UInt32 res = v1 + GetOperand(cmd->ByteMode, &cmd->Op2) + FC;
314 if (cmd->ByteMode) 322 if (cmd->ByteMode)
315 res &= 0xFF; 323 res &= 0xFF;
316 SetOperand(cmd->ByteMode, &cmd->Op1, res); 324 SetOperand(cmd->ByteMode, &cmd->Op1, res);
317 Flags = (res < v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); 325 Flags = (res < v1 || (res == v1 && FC)) | (res == 0 ? FLAG_Z : (res & FLAG_S));
318 } 326 }
319 break; 327 break;
320 case CMD_SUB: 328 case CMD_SUB:
321 { 329 {
322 UInt32 v1 = GetOperand32(&cmd->Op1); 330 const UInt32 v1 = GetOperand32(&cmd->Op1);
323 UInt32 res = v1 - GetOperand32(&cmd->Op2); 331 const UInt32 res = v1 - GetOperand32(&cmd->Op2);
324 SetOperand32(&cmd->Op1, res); 332 SetOperand32(&cmd->Op1, res);
325 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); 333 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S);
326 } 334 }
327 break; 335 break;
328 case CMD_SUBB: 336 case CMD_SUBB:
329 { 337 {
330 UInt32 v1 = GetOperand8(&cmd->Op1); 338 const UInt32 v1 = GetOperand8(&cmd->Op1);
331 UInt32 res = v1 - GetOperand8(&cmd->Op2); 339 const UInt32 res = v1 - GetOperand8(&cmd->Op2);
332 SetOperand8(&cmd->Op1, (Byte)res); 340 SetOperand8(&cmd->Op1, (Byte)res);
333 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); 341 Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S);
334 } 342 }
335 break; 343 break;
336 case CMD_SBB: 344 case CMD_SBB:
337 { 345 {
338 UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); 346 const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1);
339 UInt32 FC = (Flags & FLAG_C); 347 const UInt32 FC = (Flags & FLAG_C);
340 UInt32 res = v1 - GetOperand(cmd->ByteMode, &cmd->Op2) - FC; 348 UInt32 res = v1 - GetOperand(cmd->ByteMode, &cmd->Op2) - FC;
341 // Flags = res == 0 ? FLAG_Z : (res > v1 || res == v1 && FC) | (res & FLAG_S); 349 // Flags = res == 0 ? FLAG_Z : (res > v1 || res == v1 && FC) | (res & FLAG_S);
342 if (cmd->ByteMode) 350 if (cmd->ByteMode)
343 res &= 0xFF; 351 res &= 0xFF;
344 SetOperand(cmd->ByteMode, &cmd->Op1, res); 352 SetOperand(cmd->ByteMode, &cmd->Op1, res);
345 Flags = (res > v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); 353 Flags = (res > v1 || (res == v1 && FC)) | (res == 0 ? FLAG_Z : (res & FLAG_S));
346 } 354 }
347 break; 355 break;
348 case CMD_INC: 356 case CMD_INC:
349 { 357 {
350 UInt32 res = GetOperand32(&cmd->Op1) + 1; 358 const UInt32 res = GetOperand32(&cmd->Op1) + 1;
351 SetOperand32(&cmd->Op1, res); 359 SetOperand32(&cmd->Op1, res);
352 FLAGS_UPDATE_SZ; 360 FLAGS_UPDATE_SZ;
353 } 361 }
354 break; 362 break;
355 case CMD_INCB: 363 case CMD_INCB:
356 { 364 {
357 Byte res = (Byte)(GetOperand8(&cmd->Op1) + 1); 365 const Byte res = (Byte)(GetOperand8(&cmd->Op1) + 1);
358 SetOperand8(&cmd->Op1, res);; 366 SetOperand8(&cmd->Op1, res);
359 FLAGS_UPDATE_SZ_B; 367 FLAGS_UPDATE_SZ_B;
360 } 368 }
361 break; 369 break;
362 case CMD_DEC: 370 case CMD_DEC:
363 { 371 {
364 UInt32 res = GetOperand32(&cmd->Op1) - 1; 372 const UInt32 res = GetOperand32(&cmd->Op1) - 1;
365 SetOperand32(&cmd->Op1, res); 373 SetOperand32(&cmd->Op1, res);
366 FLAGS_UPDATE_SZ; 374 FLAGS_UPDATE_SZ;
367 } 375 }
368 break; 376 break;
369 case CMD_DECB: 377 case CMD_DECB:
370 { 378 {
371 Byte res = (Byte)(GetOperand8(&cmd->Op1) - 1); 379 const Byte res = (Byte)(GetOperand8(&cmd->Op1) - 1);
372 SetOperand8(&cmd->Op1, res);; 380 SetOperand8(&cmd->Op1, res);
373 FLAGS_UPDATE_SZ_B; 381 FLAGS_UPDATE_SZ_B;
374 } 382 }
375 break; 383 break;
376 case CMD_XOR: 384 case CMD_XOR:
377 { 385 {
378 UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2); 386 const UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2);
379 SetOperand32(&cmd->Op1, res); 387 SetOperand32(&cmd->Op1, res);
380 FLAGS_UPDATE_SZ; 388 FLAGS_UPDATE_SZ;
381 } 389 }
382 break; 390 break;
383 case CMD_XORB: 391 case CMD_XORB:
384 { 392 {
385 Byte res = (Byte)(GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2)); 393 const Byte res = (Byte)(GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2));
386 SetOperand8(&cmd->Op1, res); 394 SetOperand8(&cmd->Op1, res);
387 FLAGS_UPDATE_SZ_B; 395 FLAGS_UPDATE_SZ_B;
388 } 396 }
389 break; 397 break;
390 case CMD_AND: 398 case CMD_AND:
391 { 399 {
392 UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); 400 const UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2);
393 SetOperand32(&cmd->Op1, res); 401 SetOperand32(&cmd->Op1, res);
394 FLAGS_UPDATE_SZ; 402 FLAGS_UPDATE_SZ;
395 } 403 }
396 break; 404 break;
397 case CMD_ANDB: 405 case CMD_ANDB:
398 { 406 {
399 Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); 407 const Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2));
400 SetOperand8(&cmd->Op1, res); 408 SetOperand8(&cmd->Op1, res);
401 FLAGS_UPDATE_SZ_B; 409 FLAGS_UPDATE_SZ_B;
402 } 410 }
403 break; 411 break;
404 case CMD_OR: 412 case CMD_OR:
405 { 413 {
406 UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2); 414 const UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2);
407 SetOperand32(&cmd->Op1, res); 415 SetOperand32(&cmd->Op1, res);
408 FLAGS_UPDATE_SZ; 416 FLAGS_UPDATE_SZ;
409 } 417 }
410 break; 418 break;
411 case CMD_ORB: 419 case CMD_ORB:
412 { 420 {
413 Byte res = (Byte)(GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2)); 421 const Byte res = (Byte)(GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2));
414 SetOperand8(&cmd->Op1, res); 422 SetOperand8(&cmd->Op1, res);
415 FLAGS_UPDATE_SZ_B; 423 FLAGS_UPDATE_SZ_B;
416 } 424 }
417 break; 425 break;
418 case CMD_TEST: 426 case CMD_TEST:
419 { 427 {
420 UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); 428 const UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2);
421 FLAGS_UPDATE_SZ; 429 FLAGS_UPDATE_SZ;
422 } 430 }
423 break; 431 break;
424 case CMD_TESTB: 432 case CMD_TESTB:
425 { 433 {
426 Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2)); 434 const Byte res = (Byte)(GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2));
427 FLAGS_UPDATE_SZ_B; 435 FLAGS_UPDATE_SZ_B;
428 } 436 }
429 break; 437 break;
@@ -432,14 +440,14 @@ bool CVm::ExecuteCode(const CProgram *prg)
432 break; 440 break;
433 case CMD_NEG: 441 case CMD_NEG:
434 { 442 {
435 UInt32 res = 0 - GetOperand32(&cmd->Op1); 443 const UInt32 res = 0 - GetOperand32(&cmd->Op1);
436 SetOperand32(&cmd->Op1, res); 444 SetOperand32(&cmd->Op1, res);
437 Flags = res == 0 ? FLAG_Z : FLAG_C | (res & FLAG_S); 445 Flags = res == 0 ? FLAG_Z : FLAG_C | (res & FLAG_S);
438 } 446 }
439 break; 447 break;
440 case CMD_NEGB: 448 case CMD_NEGB:
441 { 449 {
442 Byte res = (Byte)(0 - GetOperand8(&cmd->Op1)); 450 const Byte res = (Byte)(0 - GetOperand8(&cmd->Op1));
443 SetOperand8(&cmd->Op1, res); 451 SetOperand8(&cmd->Op1, res);
444 Flags = res == 0 ? FLAG_Z : FLAG_C | GET_FLAG_S_B(res); 452 Flags = res == 0 ? FLAG_Z : FLAG_C | GET_FLAG_S_B(res);
445 } 453 }
@@ -447,115 +455,115 @@ bool CVm::ExecuteCode(const CProgram *prg)
447 455
448 case CMD_SHL: 456 case CMD_SHL:
449 { 457 {
450 UInt32 v1 = GetOperand32(&cmd->Op1); 458 const UInt32 v1 = GetOperand32(&cmd->Op1);
451 int v2 = (int)GetOperand32(&cmd->Op2); 459 const int v2 = (int)GetOperand32(&cmd->Op2);
452 UInt32 res = v1 << v2; 460 const UInt32 res = v1 << v2;
453 SetOperand32(&cmd->Op1, res); 461 SetOperand32(&cmd->Op1, res);
454 Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 << (v2 - 1)) & 0x80000000 ? FLAG_C : 0); 462 Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 << (v2 - 1)) & 0x80000000 ? FLAG_C : 0);
455 } 463 }
456 break; 464 break;
457 case CMD_SHLB: 465 case CMD_SHLB:
458 { 466 {
459 Byte v1 = GetOperand8(&cmd->Op1); 467 const Byte v1 = GetOperand8(&cmd->Op1);
460 int v2 = (int)GetOperand8(&cmd->Op2); 468 const int v2 = (int)GetOperand8(&cmd->Op2);
461 Byte res = (Byte)(v1 << v2); 469 const Byte res = (Byte)(v1 << v2);
462 SetOperand8(&cmd->Op1, res); 470 SetOperand8(&cmd->Op1, res);
463 Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 << (v2 - 1)) & 0x80 ? FLAG_C : 0); 471 Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 << (v2 - 1)) & 0x80 ? FLAG_C : 0);
464 } 472 }
465 break; 473 break;
466 case CMD_SHR: 474 case CMD_SHR:
467 { 475 {
468 UInt32 v1 = GetOperand32(&cmd->Op1); 476 const UInt32 v1 = GetOperand32(&cmd->Op1);
469 int v2 = (int)GetOperand32(&cmd->Op2); 477 const int v2 = (int)GetOperand32(&cmd->Op2);
470 UInt32 res = v1 >> v2; 478 const UInt32 res = v1 >> v2;
471 SetOperand32(&cmd->Op1, res); 479 SetOperand32(&cmd->Op1, res);
472 Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); 480 Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C);
473 } 481 }
474 break; 482 break;
475 case CMD_SHRB: 483 case CMD_SHRB:
476 { 484 {
477 Byte v1 = GetOperand8(&cmd->Op1); 485 const Byte v1 = GetOperand8(&cmd->Op1);
478 int v2 = (int)GetOperand8(&cmd->Op2); 486 const int v2 = (int)GetOperand8(&cmd->Op2);
479 Byte res = (Byte)(v1 >> v2); 487 const Byte res = (Byte)(v1 >> v2);
480 SetOperand8(&cmd->Op1, res); 488 SetOperand8(&cmd->Op1, res);
481 Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); 489 Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C);
482 } 490 }
483 break; 491 break;
484 case CMD_SAR: 492 case CMD_SAR:
485 { 493 {
486 UInt32 v1 = GetOperand32(&cmd->Op1); 494 const UInt32 v1 = GetOperand32(&cmd->Op1);
487 int v2 = (int)GetOperand32(&cmd->Op2); 495 const int v2 = (int)GetOperand32(&cmd->Op2);
488 UInt32 res = UInt32(((Int32)v1) >> v2); 496 const UInt32 res = UInt32(((Int32)v1) >> v2);
489 SetOperand32(&cmd->Op1, res); 497 SetOperand32(&cmd->Op1, res);
490 Flags= (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); 498 Flags= (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C);
491 } 499 }
492 break; 500 break;
493 case CMD_SARB: 501 case CMD_SARB:
494 { 502 {
495 Byte v1 = GetOperand8(&cmd->Op1); 503 const Byte v1 = GetOperand8(&cmd->Op1);
496 int v2 = (int)GetOperand8(&cmd->Op2); 504 const int v2 = (int)GetOperand8(&cmd->Op2);
497 Byte res = (Byte)(((signed char)v1) >> v2); 505 const Byte res = (Byte)(((signed char)v1) >> v2);
498 SetOperand8(&cmd->Op1, res); 506 SetOperand8(&cmd->Op1, res);
499 Flags= (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); 507 Flags= (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C);
500 } 508 }
501 break; 509 break;
502 510
503 case CMD_JMP: 511 case CMD_JMP:
504 SET_IP_OP1; 512 SET_IP_OP1
505 continue; 513 continue;
506 case CMD_JZ: 514 case CMD_JZ:
507 if ((Flags & FLAG_Z) != 0) 515 if ((Flags & FLAG_Z) != 0)
508 { 516 {
509 SET_IP_OP1; 517 SET_IP_OP1
510 continue; 518 continue;
511 } 519 }
512 break; 520 break;
513 case CMD_JNZ: 521 case CMD_JNZ:
514 if ((Flags & FLAG_Z) == 0) 522 if ((Flags & FLAG_Z) == 0)
515 { 523 {
516 SET_IP_OP1; 524 SET_IP_OP1
517 continue; 525 continue;
518 } 526 }
519 break; 527 break;
520 case CMD_JS: 528 case CMD_JS:
521 if ((Flags & FLAG_S) != 0) 529 if ((Flags & FLAG_S) != 0)
522 { 530 {
523 SET_IP_OP1; 531 SET_IP_OP1
524 continue; 532 continue;
525 } 533 }
526 break; 534 break;
527 case CMD_JNS: 535 case CMD_JNS:
528 if ((Flags & FLAG_S) == 0) 536 if ((Flags & FLAG_S) == 0)
529 { 537 {
530 SET_IP_OP1; 538 SET_IP_OP1
531 continue; 539 continue;
532 } 540 }
533 break; 541 break;
534 case CMD_JB: 542 case CMD_JB:
535 if ((Flags & FLAG_C) != 0) 543 if ((Flags & FLAG_C) != 0)
536 { 544 {
537 SET_IP_OP1; 545 SET_IP_OP1
538 continue; 546 continue;
539 } 547 }
540 break; 548 break;
541 case CMD_JBE: 549 case CMD_JBE:
542 if ((Flags & (FLAG_C | FLAG_Z)) != 0) 550 if ((Flags & (FLAG_C | FLAG_Z)) != 0)
543 { 551 {
544 SET_IP_OP1; 552 SET_IP_OP1
545 continue; 553 continue;
546 } 554 }
547 break; 555 break;
548 case CMD_JA: 556 case CMD_JA:
549 if ((Flags & (FLAG_C | FLAG_Z)) == 0) 557 if ((Flags & (FLAG_C | FLAG_Z)) == 0)
550 { 558 {
551 SET_IP_OP1; 559 SET_IP_OP1
552 continue; 560 continue;
553 } 561 }
554 break; 562 break;
555 case CMD_JAE: 563 case CMD_JAE:
556 if ((Flags & FLAG_C) == 0) 564 if ((Flags & FLAG_C) == 0)
557 { 565 {
558 SET_IP_OP1; 566 SET_IP_OP1
559 continue; 567 continue;
560 } 568 }
561 break; 569 break;
@@ -571,7 +579,7 @@ bool CVm::ExecuteCode(const CProgram *prg)
571 case CMD_CALL: 579 case CMD_CALL:
572 R[kStackRegIndex] -= 4; 580 R[kStackRegIndex] -= 4;
573 SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], (UInt32)(cmd - commands + 1)); 581 SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], (UInt32)(cmd - commands + 1));
574 SET_IP_OP1; 582 SET_IP_OP1
575 continue; 583 continue;
576 584
577 case CMD_PUSHA: 585 case CMD_PUSHA:
@@ -604,29 +612,29 @@ bool CVm::ExecuteCode(const CProgram *prg)
604 break; 612 break;
605 case CMD_XCHG: 613 case CMD_XCHG:
606 { 614 {
607 UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); 615 const UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1);
608 SetOperand(cmd->ByteMode, &cmd->Op1, GetOperand(cmd->ByteMode, &cmd->Op2)); 616 SetOperand(cmd->ByteMode, &cmd->Op1, GetOperand(cmd->ByteMode, &cmd->Op2));
609 SetOperand(cmd->ByteMode, &cmd->Op2, v1); 617 SetOperand(cmd->ByteMode, &cmd->Op2, v1);
610 } 618 }
611 break; 619 break;
612 case CMD_MUL: 620 case CMD_MUL:
613 { 621 {
614 UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2); 622 const UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2);
615 SetOperand32(&cmd->Op1, res); 623 SetOperand32(&cmd->Op1, res);
616 } 624 }
617 break; 625 break;
618 case CMD_MULB: 626 case CMD_MULB:
619 { 627 {
620 Byte res = (Byte)(GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2)); 628 const Byte res = (Byte)(GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2));
621 SetOperand8(&cmd->Op1, res); 629 SetOperand8(&cmd->Op1, res);
622 } 630 }
623 break; 631 break;
624 case CMD_DIV: 632 case CMD_DIV:
625 { 633 {
626 UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2); 634 const UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2);
627 if (divider != 0) 635 if (divider != 0)
628 { 636 {
629 UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider; 637 const UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider;
630 SetOperand(cmd->ByteMode, &cmd->Op1, res); 638 SetOperand(cmd->ByteMode, &cmd->Op1, res);
631 } 639 }
632 } 640 }
@@ -636,8 +644,8 @@ bool CVm::ExecuteCode(const CProgram *prg)
636 { 644 {
637 if (R[kStackRegIndex] >= kSpaceSize) 645 if (R[kStackRegIndex] >= kSpaceSize)
638 return true; 646 return true;
639 UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); 647 const UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]);
640 SET_IP(ip); 648 SET_IP(ip)
641 R[kStackRegIndex] += 4; 649 R[kStackRegIndex] += 4;
642 continue; 650 continue;
643 } 651 }
@@ -695,7 +703,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize)
695 703
696 if (inp.ReadBit()) 704 if (inp.ReadBit())
697 { 705 {
698 UInt32 dataSize = inp.ReadEncodedUInt32() + 1; 706 const UInt32 dataSize = inp.ReadEncodedUInt32() + 1;
699 for (UInt32 i = 0; inp.Avail() && i < dataSize; i++) 707 for (UInt32 i = 0; inp.Avail() && i < dataSize; i++)
700 StaticData.Add((Byte)inp.ReadBits(8)); 708 StaticData.Add((Byte)inp.ReadBits(8));
701 } 709 }
@@ -705,28 +713,30 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize)
705 Commands.Add(CCommand()); 713 Commands.Add(CCommand());
706 CCommand *cmd = &Commands.Back(); 714 CCommand *cmd = &Commands.Back();
707 715
716 unsigned opCode;
708 if (inp.ReadBit() == 0) 717 if (inp.ReadBit() == 0)
709 cmd->OpCode = (ECommand)inp.ReadBits(3); 718 opCode = inp.ReadBits(3);
710 else 719 else
711 cmd->OpCode = (ECommand)(8 + inp.ReadBits(5)); 720 opCode = 8 + inp.ReadBits(5);
712 721 cmd->OpCode = (ECommand)opCode;
713 if (kCmdFlags[(unsigned)cmd->OpCode] & CF_BYTEMODE) 722 const unsigned cmdFlags = kCmdFlags[opCode];
723 if (cmdFlags & CF_BYTEMODE)
714 cmd->ByteMode = (inp.ReadBit()) ? true : false; 724 cmd->ByteMode = (inp.ReadBit()) ? true : false;
715 else 725 else
716 cmd->ByteMode = 0; 726 cmd->ByteMode = 0;
717 727
718 int opNum = (kCmdFlags[(unsigned)cmd->OpCode] & CF_OPMASK); 728 const unsigned opNum = (cmdFlags & CF_OPMASK);
719 729
720 if (opNum > 0) 730 if (opNum)
721 { 731 {
722 DecodeArg(inp, cmd->Op1, cmd->ByteMode); 732 DecodeArg(inp, cmd->Op1, cmd->ByteMode);
723 if (opNum == 2) 733 if (opNum == 2)
724 DecodeArg(inp, cmd->Op2, cmd->ByteMode); 734 DecodeArg(inp, cmd->Op2, cmd->ByteMode);
725 else 735 else
726 { 736 {
727 if (cmd->Op1.Type == OP_TYPE_INT && (kCmdFlags[(unsigned)cmd->OpCode] & (CF_JUMP | CF_PROC))) 737 if (cmd->Op1.Type == OP_TYPE_INT && (cmdFlags & (CF_JUMP | CF_PROC)))
728 { 738 {
729 int dist = cmd->Op1.Data; 739 Int32 dist = (Int32)cmd->Op1.Data;
730 if (dist >= 256) 740 if (dist >= 256)
731 dist -= 256; 741 dist -= 256;
732 else 742 else
@@ -739,7 +749,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize)
739 dist -= 16; 749 dist -= 16;
740 dist += Commands.Size() - 1; 750 dist += Commands.Size() - 1;
741 } 751 }
742 cmd->Op1.Data = dist; 752 cmd->Op1.Data = (UInt32)dist;
743 } 753 }
744 } 754 }
745 } 755 }
@@ -763,6 +773,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize)
763 case CMD_SHR: cmd->OpCode = CMD_SHRB; break; 773 case CMD_SHR: cmd->OpCode = CMD_SHRB; break;
764 case CMD_SAR: cmd->OpCode = CMD_SARB; break; 774 case CMD_SAR: cmd->OpCode = CMD_SARB; break;
765 case CMD_MUL: cmd->OpCode = CMD_MULB; break; 775 case CMD_MUL: cmd->OpCode = CMD_MULB; break;
776 default: break;
766 } 777 }
767 } 778 }
768 } 779 }
@@ -771,7 +782,7 @@ void CProgram::ReadProgram(const Byte *code, UInt32 codeSize)
771#endif 782#endif
772 783
773 784
774#ifdef RARVM_STANDARD_FILTERS 785#ifdef Z7_RARVM_STANDARD_FILTERS
775 786
776enum EStandardFilter 787enum EStandardFilter
777{ 788{
@@ -803,12 +814,13 @@ kStdFilters[]=
803 814
804static int FindStandardFilter(const Byte *code, UInt32 codeSize) 815static int FindStandardFilter(const Byte *code, UInt32 codeSize)
805{ 816{
806 UInt32 crc = CrcCalc(code, codeSize); 817 // return -1; // for debug VM execution
807 for (unsigned i = 0; i < ARRAY_SIZE(kStdFilters); i++) 818 const UInt32 crc = CrcCalc(code, codeSize);
819 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kStdFilters); i++)
808 { 820 {
809 const CStandardFilterSignature &sfs = kStdFilters[i]; 821 const CStandardFilterSignature &sfs = kStdFilters[i];
810 if (sfs.CRC == crc && sfs.Length == codeSize) 822 if (sfs.CRC == crc && sfs.Length == codeSize)
811 return i; 823 return (int)i;
812 } 824 }
813 return -1; 825 return -1;
814} 826}
@@ -820,11 +832,11 @@ bool CProgram::PrepareProgram(const Byte *code, UInt32 codeSize)
820{ 832{
821 IsSupported = false; 833 IsSupported = false;
822 834
823 #ifdef RARVM_VM_ENABLE 835 #ifdef Z7_RARVM_VM_ENABLE
824 Commands.Clear(); 836 Commands.Clear();
825 #endif 837 #endif
826 838
827 #ifdef RARVM_STANDARD_FILTERS 839 #ifdef Z7_RARVM_STANDARD_FILTERS
828 StandardFilterIndex = -1; 840 StandardFilterIndex = -1;
829 #endif 841 #endif
830 842
@@ -838,20 +850,20 @@ bool CProgram::PrepareProgram(const Byte *code, UInt32 codeSize)
838 { 850 {
839 IsSupported = true; 851 IsSupported = true;
840 isOK = true; 852 isOK = true;
841 #ifdef RARVM_STANDARD_FILTERS 853 #ifdef Z7_RARVM_STANDARD_FILTERS
842 StandardFilterIndex = FindStandardFilter(code, codeSize); 854 StandardFilterIndex = FindStandardFilter(code, codeSize);
843 if (StandardFilterIndex >= 0) 855 if (StandardFilterIndex >= 0)
844 return true; 856 return true;
845 #endif 857 #endif
846 858
847 #ifdef RARVM_VM_ENABLE 859 #ifdef Z7_RARVM_VM_ENABLE
848 ReadProgram(code + 1, codeSize - 1); 860 ReadProgram(code + 1, codeSize - 1);
849 #else 861 #else
850 IsSupported = false; 862 IsSupported = false;
851 #endif 863 #endif
852 } 864 }
853 865
854 #ifdef RARVM_VM_ENABLE 866 #ifdef Z7_RARVM_VM_ENABLE
855 Commands.Add(CCommand()); 867 Commands.Add(CCommand());
856 Commands.Back().OpCode = CMD_RET; 868 Commands.Back().OpCode = CMD_RET;
857 #endif 869 #endif
@@ -865,7 +877,7 @@ void CVm::SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize)
865 memmove(Mem + pos, data, MyMin(dataSize, kSpaceSize - pos)); 877 memmove(Mem + pos, data, MyMin(dataSize, kSpaceSize - pos));
866} 878}
867 879
868#ifdef RARVM_STANDARD_FILTERS 880#ifdef Z7_RARVM_STANDARD_FILTERS
869 881
870static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9) 882static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9)
871{ 883{
@@ -873,7 +885,7 @@ static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9)
873 return; 885 return;
874 dataSize -= 4; 886 dataSize -= 4;
875 const UInt32 kFileSize = 0x1000000; 887 const UInt32 kFileSize = 0x1000000;
876 Byte cmpMask = (Byte)(e9 ? 0xFE : 0xFF); 888 const Byte cmpMask = (Byte)(e9 ? 0xFE : 0xFF);
877 for (UInt32 curPos = 0; curPos < dataSize;) 889 for (UInt32 curPos = 0; curPos < dataSize;)
878 { 890 {
879 curPos++; 891 curPos++;
@@ -921,7 +933,7 @@ static void ItaniumDecode(Byte *data, UInt32 dataSize, UInt32 fileOffset)
921 raw &= ~(kMask << m); 933 raw &= ~(kMask << m);
922 raw |= (v << m); 934 raw |= (v << m);
923 // p[0] = (Byte)raw; p[1] = (Byte)(raw >> 8); p[2] = (Byte)(raw >> 16); 935 // p[0] = (Byte)raw; p[1] = (Byte)(raw >> 8); p[2] = (Byte)(raw >> 16);
924 SetUi32(p, raw); 936 SetUi32(p, raw)
925 } 937 }
926 } 938 }
927 while (++m <= 4); 939 while (++m <= 4);
@@ -960,12 +972,12 @@ static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR)
960 predicted = prevByte; 972 predicted = prevByte;
961 else 973 else
962 { 974 {
963 unsigned int upperLeftByte = destData[i - width]; 975 const unsigned int upperLeftByte = destData[i - width];
964 unsigned int upperByte = destData[i - width + 3]; 976 const unsigned int upperByte = destData[i - width + 3];
965 predicted = prevByte + upperByte - upperLeftByte; 977 predicted = prevByte + upperByte - upperLeftByte;
966 int pa = abs((int)(predicted - prevByte)); 978 const int pa = abs((int)(predicted - prevByte));
967 int pb = abs((int)(predicted - upperByte)); 979 const int pb = abs((int)(predicted - upperByte));
968 int pc = abs((int)(predicted - upperLeftByte)); 980 const int pc = abs((int)(predicted - upperLeftByte));
969 if (pa <= pb && pa <= pc) 981 if (pa <= pb && pa <= pc)
970 predicted = prevByte; 982 predicted = prevByte;
971 else 983 else
@@ -982,12 +994,14 @@ static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR)
982 const UInt32 border = dataSize - 2; 994 const UInt32 border = dataSize - 2;
983 for (UInt32 i = posR; i < border; i += 3) 995 for (UInt32 i = posR; i < border; i += 3)
984 { 996 {
985 Byte g = destData[i + 1]; 997 const Byte g = destData[i + 1];
986 destData[i ] = (Byte)(destData[i ] + g); 998 destData[i ] = (Byte)(destData[i ] + g);
987 destData[i + 2] = (Byte)(destData[i + 2] + g); 999 destData[i + 2] = (Byte)(destData[i + 2] + g);
988 } 1000 }
989} 1001}
990 1002
1003#define my_abs(x) (unsigned)abs(x)
1004
991static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels) 1005static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels)
992{ 1006{
993 Byte *destData = srcData + dataSize; 1007 Byte *destData = srcData + dataSize;
@@ -1001,34 +1015,34 @@ static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels)
1001 for (UInt32 i = curChannel, byteCount = 0; i < dataSize; i += numChannels, byteCount++) 1015 for (UInt32 i = curChannel, byteCount = 0; i < dataSize; i += numChannels, byteCount++)
1002 { 1016 {
1003 D3 = D2; 1017 D3 = D2;
1004 D2 = prevDelta - D1; 1018 D2 = (Int32)prevDelta - D1;
1005 D1 = prevDelta; 1019 D1 = (Int32)prevDelta;
1006 1020
1007 UInt32 predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; 1021 UInt32 predicted = (UInt32)((Int32)(8 * prevByte) + K1 * D1 + K2 * D2 + K3 * D3);
1008 predicted = (predicted >> 3) & 0xFF; 1022 predicted = (predicted >> 3) & 0xFF;
1009 1023
1010 UInt32 curByte = *(srcData++); 1024 const UInt32 curByte = *(srcData++);
1011 1025
1012 predicted -= curByte; 1026 predicted -= curByte;
1013 destData[i] = (Byte)predicted; 1027 destData[i] = (Byte)predicted;
1014 prevDelta = (UInt32)(Int32)(signed char)(predicted - prevByte); 1028 prevDelta = (UInt32)(Int32)(signed char)(predicted - prevByte);
1015 prevByte = predicted; 1029 prevByte = predicted;
1016 1030
1017 Int32 D = ((Int32)(signed char)curByte) << 3; 1031 const Int32 D = ((Int32)(signed char)curByte) << 3;
1018 1032
1019 dif[0] += abs(D); 1033 dif[0] += my_abs(D);
1020 dif[1] += abs(D - D1); 1034 dif[1] += my_abs(D - D1);
1021 dif[2] += abs(D + D1); 1035 dif[2] += my_abs(D + D1);
1022 dif[3] += abs(D - D2); 1036 dif[3] += my_abs(D - D2);
1023 dif[4] += abs(D + D2); 1037 dif[4] += my_abs(D + D2);
1024 dif[5] += abs(D - D3); 1038 dif[5] += my_abs(D - D3);
1025 dif[6] += abs(D + D3); 1039 dif[6] += my_abs(D + D3);
1026 1040
1027 if ((byteCount & 0x1F) == 0) 1041 if ((byteCount & 0x1F) == 0)
1028 { 1042 {
1029 UInt32 minDif = dif[0], numMinDif = 0; 1043 UInt32 minDif = dif[0], numMinDif = 0;
1030 dif[0] = 0; 1044 dif[0] = 0;
1031 for (unsigned j = 1; j < ARRAY_SIZE(dif); j++) 1045 for (unsigned j = 1; j < Z7_ARRAY_SIZE(dif); j++)
1032 { 1046 {
1033 if (dif[j] < minDif) 1047 if (dif[j] < minDif)
1034 { 1048 {
@@ -1068,7 +1082,7 @@ static UInt32 UpCaseDecode(Byte *data, UInt32 dataSize)
1068 1082
1069bool CVm::ExecuteStandardFilter(unsigned filterIndex) 1083bool CVm::ExecuteStandardFilter(unsigned filterIndex)
1070{ 1084{
1071 UInt32 dataSize = R[4]; 1085 const UInt32 dataSize = R[4];
1072 if (dataSize >= kGlobalOffset) 1086 if (dataSize >= kGlobalOffset)
1073 return false; 1087 return false;
1074 EStandardFilter filterType = kStdFilters[filterIndex].Type; 1088 EStandardFilter filterType = kStdFilters[filterIndex].Type;
@@ -1088,7 +1102,7 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex)
1088 { 1102 {
1089 if (dataSize >= kGlobalOffset / 2) 1103 if (dataSize >= kGlobalOffset / 2)
1090 return false; 1104 return false;
1091 UInt32 numChannels = R[0]; 1105 const UInt32 numChannels = R[0];
1092 if (numChannels == 0 || numChannels > 1024) // unrar 5.5.5 1106 if (numChannels == 0 || numChannels > 1024) // unrar 5.5.5
1093 return false; 1107 return false;
1094 SetBlockPos(dataSize); 1108 SetBlockPos(dataSize);
@@ -1100,8 +1114,8 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex)
1100 { 1114 {
1101 if (dataSize >= kGlobalOffset / 2 || dataSize < 3) // unrar 5.5.5 1115 if (dataSize >= kGlobalOffset / 2 || dataSize < 3) // unrar 5.5.5
1102 return false; 1116 return false;
1103 UInt32 width = R[0]; 1117 const UInt32 width = R[0];
1104 UInt32 posR = R[1]; 1118 const UInt32 posR = R[1];
1105 if (width < 3 || width - 3 > dataSize || posR > 2) // unrar 5.5.5 1119 if (width < 3 || width - 3 > dataSize || posR > 2) // unrar 5.5.5
1106 return false; 1120 return false;
1107 SetBlockPos(dataSize); 1121 SetBlockPos(dataSize);
@@ -1113,7 +1127,7 @@ bool CVm::ExecuteStandardFilter(unsigned filterIndex)
1113 { 1127 {
1114 if (dataSize >= kGlobalOffset / 2) 1128 if (dataSize >= kGlobalOffset / 2)
1115 return false; 1129 return false;
1116 UInt32 numChannels = R[0]; 1130 const UInt32 numChannels = R[0];
1117 if (numChannels == 0 || numChannels > 128) // unrar 5.5.5 1131 if (numChannels == 0 || numChannels > 128) // unrar 5.5.5
1118 return false; 1132 return false;
1119 SetBlockPos(dataSize); 1133 SetBlockPos(dataSize);
diff --git a/CPP/7zip/Compress/Rar3Vm.h b/CPP/7zip/Compress/Rar3Vm.h
index 3fc5151..fde7e95 100644
--- a/CPP/7zip/Compress/Rar3Vm.h
+++ b/CPP/7zip/Compress/Rar3Vm.h
@@ -2,15 +2,15 @@
2// According to unRAR license, this code may not be used to develop 2// According to unRAR license, this code may not be used to develop
3// a program that creates RAR archives 3// a program that creates RAR archives
4 4
5#ifndef __COMPRESS_RAR3_VM_H 5#ifndef ZIP7_INC_COMPRESS_RAR3_VM_H
6#define __COMPRESS_RAR3_VM_H 6#define ZIP7_INC_COMPRESS_RAR3_VM_H
7 7
8#include "../../../C/CpuArch.h" 8#include "../../../C/CpuArch.h"
9 9
10#include "../../Common/MyVector.h" 10#include "../../Common/MyVector.h"
11 11
12#define RARVM_STANDARD_FILTERS 12#define Z7_RARVM_STANDARD_FILTERS
13// #define RARVM_VM_ENABLE 13// #define Z7_RARVM_VM_ENABLE
14 14
15namespace NCompress { 15namespace NCompress {
16namespace NRar3 { 16namespace NRar3 {
@@ -37,7 +37,7 @@ public:
37namespace NVm { 37namespace NVm {
38 38
39inline UInt32 GetValue32(const void *addr) { return GetUi32(addr); } 39inline UInt32 GetValue32(const void *addr) { return GetUi32(addr); }
40inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value); } 40inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value) }
41 41
42const unsigned kNumRegBits = 3; 42const unsigned kNumRegBits = 3;
43const UInt32 kNumRegs = 1 << kNumRegBits; 43const UInt32 kNumRegs = 1 << kNumRegBits;
@@ -58,7 +58,7 @@ namespace NGlobalOffset
58} 58}
59 59
60 60
61#ifdef RARVM_VM_ENABLE 61#ifdef Z7_RARVM_VM_ENABLE
62 62
63enum ECommand 63enum ECommand
64{ 64{
@@ -104,14 +104,14 @@ struct CBlockRef
104 104
105class CProgram 105class CProgram
106{ 106{
107 #ifdef RARVM_VM_ENABLE 107 #ifdef Z7_RARVM_VM_ENABLE
108 void ReadProgram(const Byte *code, UInt32 codeSize); 108 void ReadProgram(const Byte *code, UInt32 codeSize);
109public: 109public:
110 CRecordVector<CCommand> Commands; 110 CRecordVector<CCommand> Commands;
111 #endif 111 #endif
112 112
113public: 113public:
114 #ifdef RARVM_STANDARD_FILTERS 114 #ifdef Z7_RARVM_STANDARD_FILTERS
115 int StandardFilterIndex; 115 int StandardFilterIndex;
116 #endif 116 #endif
117 117
@@ -150,7 +150,7 @@ class CVm
150 if (byteMode) 150 if (byteMode)
151 *(Byte *)addr = (Byte)value; 151 *(Byte *)addr = (Byte)value;
152 else 152 else
153 SetUi32(addr, value); 153 SetUi32(addr, value)
154 } 154 }
155 155
156 UInt32 GetFixedGlobalValue32(UInt32 globalOffset) { return GetValue(false, &Mem[kGlobalOffset + globalOffset]); } 156 UInt32 GetFixedGlobalValue32(UInt32 globalOffset) { return GetValue(false, &Mem[kGlobalOffset + globalOffset]); }
@@ -162,7 +162,7 @@ public:
162 162
163private: 163private:
164 164
165 #ifdef RARVM_VM_ENABLE 165 #ifdef Z7_RARVM_VM_ENABLE
166 UInt32 GetOperand32(const COperand *op) const; 166 UInt32 GetOperand32(const COperand *op) const;
167 void SetOperand32(const COperand *op, UInt32 val); 167 void SetOperand32(const COperand *op, UInt32 val);
168 Byte GetOperand8(const COperand *op) const; 168 Byte GetOperand8(const COperand *op) const;
@@ -172,7 +172,7 @@ private:
172 bool ExecuteCode(const CProgram *prg); 172 bool ExecuteCode(const CProgram *prg);
173 #endif 173 #endif
174 174
175 #ifdef RARVM_STANDARD_FILTERS 175 #ifdef Z7_RARVM_STANDARD_FILTERS
176 bool ExecuteStandardFilter(unsigned filterIndex); 176 bool ExecuteStandardFilter(unsigned filterIndex);
177 #endif 177 #endif
178 178
diff --git a/CPP/7zip/Compress/Rar5Decoder.cpp b/CPP/7zip/Compress/Rar5Decoder.cpp
index caabb31..e55d7de 100644
--- a/CPP/7zip/Compress/Rar5Decoder.cpp
+++ b/CPP/7zip/Compress/Rar5Decoder.cpp
@@ -21,12 +21,12 @@ void CBitDecoder::Prepare2() throw()
21 if (_buf > _bufLim) 21 if (_buf > _bufLim)
22 return; 22 return;
23 23
24 size_t rem = _bufLim - _buf; 24 size_t rem = (size_t)(_bufLim - _buf);
25 if (rem != 0) 25 if (rem != 0)
26 memmove(_bufBase, _buf, rem); 26 memmove(_bufBase, _buf, rem);
27 27
28 _bufLim = _bufBase + rem; 28 _bufLim = _bufBase + rem;
29 _processedSize += (_buf - _bufBase); 29 _processedSize += (size_t)(_buf - _bufBase);
30 _buf = _bufBase; 30 _buf = _bufBase;
31 31
32 if (!_wasFinished) 32 if (!_wasFinished)
@@ -42,7 +42,7 @@ void CBitDecoder::Prepare2() throw()
42 } 42 }
43 } 43 }
44 44
45 rem = _bufLim - _buf; 45 rem = (size_t)(_bufLim - _buf);
46 _bufCheck = _buf; 46 _bufCheck = _buf;
47 if (rem < kSize) 47 if (rem < kSize)
48 memset(_bufLim, 0xFF, kSize - rem); 48 memset(_bufLim, 0xFF, kSize - rem);
@@ -92,7 +92,7 @@ HRESULT CDecoder::WriteData(const Byte *data, size_t size)
92 size_t cur = size; 92 size_t cur = size;
93 if (_unpackSize_Defined) 93 if (_unpackSize_Defined)
94 { 94 {
95 UInt64 rem = _unpackSize - _writtenFileSize; 95 const UInt64 rem = _unpackSize - _writtenFileSize;
96 if (cur > rem) 96 if (cur > rem)
97 cur = (size_t)rem; 97 cur = (size_t)rem;
98 } 98 }
@@ -122,26 +122,26 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f)
122 if (dataSize > 4) 122 if (dataSize > 4)
123 { 123 {
124 dataSize -= 4; 124 dataSize -= 4;
125 UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); 125 const UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart);
126 126
127 const UInt32 kFileSize = (UInt32)1 << 24; 127 const UInt32 kFileSize = (UInt32)1 << 24;
128 Byte cmpMask = (Byte)(f.Type == FILTER_E8 ? 0xFF : 0xFE); 128 const Byte cmpMask = (Byte)(f.Type == FILTER_E8 ? 0xFF : 0xFE);
129 129
130 for (UInt32 curPos = 0; curPos < dataSize;) 130 for (UInt32 curPos = 0; curPos < dataSize;)
131 { 131 {
132 curPos++; 132 curPos++;
133 if (((*data++) & cmpMask) == 0xE8) 133 if (((*data++) & cmpMask) == 0xE8)
134 { 134 {
135 UInt32 offset = (curPos + fileOffset) & (kFileSize - 1); 135 const UInt32 offset = (curPos + fileOffset) & (kFileSize - 1);
136 UInt32 addr = GetUi32(data); 136 const UInt32 addr = GetUi32(data);
137 137
138 if (addr < kFileSize) 138 if (addr < kFileSize)
139 { 139 {
140 SetUi32(data, addr - offset); 140 SetUi32(data, addr - offset)
141 } 141 }
142 else if (addr > ((UInt32)0xFFFFFFFF - offset)) // (addr > ~(offset)) 142 else if (addr > ((UInt32)0xFFFFFFFF - offset)) // (addr > ~(offset))
143 { 143 {
144 SetUi32(data, addr + kFileSize); 144 SetUi32(data, addr + kFileSize)
145 } 145 }
146 146
147 data += 4; 147 data += 4;
@@ -157,7 +157,7 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f)
157 if (dataSize >= 4) 157 if (dataSize >= 4)
158 { 158 {
159 dataSize -= 4; 159 dataSize -= 4;
160 UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart); 160 const UInt32 fileOffset = (UInt32)(f.Start - _lzFileStart);
161 161
162 for (UInt32 curPos = 0; curPos <= dataSize; curPos += 4) 162 for (UInt32 curPos = 0; curPos <= dataSize; curPos += 4)
163 { 163 {
@@ -183,7 +183,7 @@ HRESULT CDecoder::ExecuteFilter(const CFilter &f)
183 return E_OUTOFMEMORY; 183 return E_OUTOFMEMORY;
184 184
185 Byte *dest = _filterDst; 185 Byte *dest = _filterDst;
186 UInt32 numChannels = f.Channels; 186 const UInt32 numChannels = f.Channels;
187 187
188 for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) 188 for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++)
189 { 189 {
@@ -216,27 +216,27 @@ HRESULT CDecoder::WriteBuf()
216 { 216 {
217 const CFilter &f = _filters[i]; 217 const CFilter &f = _filters[i];
218 218
219 UInt64 blockStart = f.Start; 219 const UInt64 blockStart = f.Start;
220 220
221 size_t lzAvail = (size_t)(_lzSize - _lzWritten); 221 const size_t lzAvail = (size_t)(_lzSize - _lzWritten);
222 if (lzAvail == 0) 222 if (lzAvail == 0)
223 break; 223 break;
224 224
225 if (blockStart > _lzWritten) 225 if (blockStart > _lzWritten)
226 { 226 {
227 UInt64 rem = blockStart - _lzWritten; 227 const UInt64 rem = blockStart - _lzWritten;
228 size_t size = lzAvail; 228 size_t size = lzAvail;
229 if (size > rem) 229 if (size > rem)
230 size = (size_t)rem; 230 size = (size_t)rem;
231 if (size != 0) 231 if (size != 0)
232 { 232 {
233 RINOK(WriteData(_window + _winPos - lzAvail, size)); 233 RINOK(WriteData(_window + _winPos - lzAvail, size))
234 _lzWritten += size; 234 _lzWritten += size;
235 } 235 }
236 continue; 236 continue;
237 } 237 }
238 238
239 UInt32 blockSize = f.Size; 239 const UInt32 blockSize = f.Size;
240 size_t offset = (size_t)(_lzWritten - blockStart); 240 size_t offset = (size_t)(_lzWritten - blockStart);
241 if (offset == 0) 241 if (offset == 0)
242 { 242 {
@@ -245,7 +245,7 @@ HRESULT CDecoder::WriteBuf()
245 return E_OUTOFMEMORY; 245 return E_OUTOFMEMORY;
246 } 246 }
247 247
248 size_t blockRem = (size_t)blockSize - offset; 248 const size_t blockRem = (size_t)blockSize - offset;
249 size_t size = lzAvail; 249 size_t size = lzAvail;
250 if (size > blockRem) 250 if (size > blockRem)
251 size = blockRem; 251 size = blockRem;
@@ -256,7 +256,7 @@ HRESULT CDecoder::WriteBuf()
256 return S_OK; 256 return S_OK;
257 257
258 _numUnusedFilters = ++i; 258 _numUnusedFilters = ++i;
259 RINOK(ExecuteFilter(f)); 259 RINOK(ExecuteFilter(f))
260 } 260 }
261 261
262 DeleteUnusedFilters(); 262 DeleteUnusedFilters();
@@ -264,8 +264,8 @@ HRESULT CDecoder::WriteBuf()
264 if (!_filters.IsEmpty()) 264 if (!_filters.IsEmpty())
265 return S_OK; 265 return S_OK;
266 266
267 size_t lzAvail = (size_t)(_lzSize - _lzWritten); 267 const size_t lzAvail = (size_t)(_lzSize - _lzWritten);
268 RINOK(WriteData(_window + _winPos - lzAvail, lzAvail)); 268 RINOK(WriteData(_window + _winPos - lzAvail, lzAvail))
269 _lzWritten += lzAvail; 269 _lzWritten += lzAvail;
270 return S_OK; 270 return S_OK;
271} 271}
@@ -273,7 +273,7 @@ HRESULT CDecoder::WriteBuf()
273 273
274static UInt32 ReadUInt32(CBitDecoder &bi) 274static UInt32 ReadUInt32(CBitDecoder &bi)
275{ 275{
276 unsigned numBytes = bi.ReadBits9fix(2) + 1; 276 const unsigned numBytes = bi.ReadBits9fix(2) + 1;
277 UInt32 v = 0; 277 UInt32 v = 0;
278 for (unsigned i = 0; i < numBytes; i++) 278 for (unsigned i = 0; i < numBytes; i++)
279 v += ((UInt32)bi.ReadBits9fix(8) << (i * 8)); 279 v += ((UInt32)bi.ReadBits9fix(8) << (i * 8));
@@ -289,7 +289,7 @@ HRESULT CDecoder::AddFilter(CBitDecoder &_bitStream)
289 289
290 if (_filters.Size() >= MAX_UNPACK_FILTERS) 290 if (_filters.Size() >= MAX_UNPACK_FILTERS)
291 { 291 {
292 RINOK(WriteBuf()); 292 RINOK(WriteBuf())
293 DeleteUnusedFilters(); 293 DeleteUnusedFilters();
294 if (_filters.Size() >= MAX_UNPACK_FILTERS) 294 if (_filters.Size() >= MAX_UNPACK_FILTERS)
295 { 295 {
@@ -301,7 +301,7 @@ HRESULT CDecoder::AddFilter(CBitDecoder &_bitStream)
301 _bitStream.Prepare(); 301 _bitStream.Prepare();
302 302
303 CFilter f; 303 CFilter f;
304 UInt32 blockStart = ReadUInt32(_bitStream); 304 const UInt32 blockStart = ReadUInt32(_bitStream);
305 f.Size = ReadUInt32(_bitStream); 305 f.Size = ReadUInt32(_bitStream);
306 306
307 if (f.Size > ((UInt32)1 << 22)) 307 if (f.Size > ((UInt32)1 << 22))
@@ -336,17 +336,17 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream)
336 if (_progress) 336 if (_progress)
337 { 337 {
338 const UInt64 packSize = _bitStream.GetProcessedSize(); 338 const UInt64 packSize = _bitStream.GetProcessedSize();
339 RINOK(_progress->SetRatioInfo(&packSize, &_writtenFileSize)); 339 RINOK(_progress->SetRatioInfo(&packSize, &_writtenFileSize))
340 } 340 }
341 341
342 _bitStream.AlignToByte(); 342 _bitStream.AlignToByte();
343 _bitStream.Prepare(); 343 _bitStream.Prepare();
344 344
345 { 345 {
346 unsigned flags = _bitStream.ReadByteInAligned(); 346 const unsigned flags = _bitStream.ReadByteInAligned();
347 unsigned checkSum = _bitStream.ReadByteInAligned(); 347 unsigned checkSum = _bitStream.ReadByteInAligned();
348 checkSum ^= flags; 348 checkSum ^= flags;
349 unsigned num = (flags >> 3) & 3; 349 const unsigned num = (flags >> 3) & 3;
350 if (num == 3) 350 if (num == 3)
351 return S_FALSE; 351 return S_FALSE;
352 UInt32 blockSize = _bitStream.ReadByteInAligned(); 352 UInt32 blockSize = _bitStream.ReadByteInAligned();
@@ -399,7 +399,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream)
399 for (unsigned i = 0; i < kLevelTableSize;) 399 for (unsigned i = 0; i < kLevelTableSize;)
400 { 400 {
401 _bitStream.Prepare(); 401 _bitStream.Prepare();
402 unsigned len = (unsigned)_bitStream.ReadBits9fix(4); 402 const unsigned len = (unsigned)_bitStream.ReadBits9fix(4);
403 if (len == 15) 403 if (len == 15)
404 { 404 {
405 unsigned num = (unsigned)_bitStream.ReadBits9fix(4); 405 unsigned num = (unsigned)_bitStream.ReadBits9fix(4);
@@ -421,7 +421,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream)
421 if (_bitStream.IsBlockOverRead()) 421 if (_bitStream.IsBlockOverRead())
422 return S_FALSE; 422 return S_FALSE;
423 423
424 RIF(m_LevelDecoder.Build(lens2)); 424 RIF(m_LevelDecoder.Build(lens2))
425 } 425 }
426 426
427 Byte lens[kTablesSizesSum]; 427 Byte lens[kTablesSizesSum];
@@ -437,7 +437,7 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream)
437 return S_FALSE; 437 return S_FALSE;
438 } 438 }
439 439
440 UInt32 sym = m_LevelDecoder.Decode(&_bitStream); 440 const UInt32 sym = m_LevelDecoder.Decode(&_bitStream);
441 441
442 if (sym < 16) 442 if (sym < 16)
443 lens[i++] = (Byte)sym; 443 lens[i++] = (Byte)sym;
@@ -469,10 +469,10 @@ HRESULT CDecoder::ReadTables(CBitDecoder &_bitStream)
469 if (_bitStream.InputEofError()) 469 if (_bitStream.InputEofError())
470 return S_FALSE; 470 return S_FALSE;
471 471
472 RIF(m_MainDecoder.Build(&lens[0])); 472 RIF(m_MainDecoder.Build(&lens[0]))
473 RIF(m_DistDecoder.Build(&lens[kMainTableSize])); 473 RIF(m_DistDecoder.Build(&lens[kMainTableSize]))
474 RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize])); 474 RIF(m_AlignDecoder.Build(&lens[kMainTableSize + kDistTableSize]))
475 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize])); 475 RIF(m_LenDecoder.Build(&lens[kMainTableSize + kDistTableSize + kAlignTableSize]))
476 476
477 _useAlignBits = false; 477 _useAlignBits = false;
478 // _useAlignBits = true; 478 // _useAlignBits = true;
@@ -492,7 +492,7 @@ static inline unsigned SlotToLen(CBitDecoder &_bitStream, unsigned slot)
492{ 492{
493 if (slot < 8) 493 if (slot < 8)
494 return slot + 2; 494 return slot + 2;
495 unsigned numBits = (slot >> 2) - 1; 495 const unsigned numBits = (slot >> 2) - 1;
496 return 2 + ((4 | (slot & 3)) << numBits) + _bitStream.ReadBits9(numBits); 496 return 2 + ((4 | (slot & 3)) << numBits) + _bitStream.ReadBits9(numBits);
497} 497}
498 498
@@ -523,7 +523,7 @@ HRESULT CDecoder::DecodeLZ()
523 { 523 {
524 if (_winPos >= limit) 524 if (_winPos >= limit)
525 { 525 {
526 RINOK(WriteBuf()); 526 RINOK(WriteBuf())
527 if (_unpackSize_Defined && _writtenFileSize > _unpackSize) 527 if (_unpackSize_Defined && _writtenFileSize > _unpackSize)
528 break; // return S_FALSE; 528 break; // return S_FALSE;
529 529
@@ -543,7 +543,7 @@ HRESULT CDecoder::DecodeLZ()
543 if (remLen != 0) 543 if (remLen != 0)
544 { 544 {
545 size_t winPos = _winPos; 545 size_t winPos = _winPos;
546 size_t winMask = _winMask; 546 const size_t winMask = _winMask;
547 size_t pos = (winPos - (size_t)rep0 - 1) & winMask; 547 size_t pos = (winPos - (size_t)rep0 - 1) & winMask;
548 548
549 Byte *win = _window; 549 Byte *win = _window;
@@ -570,13 +570,13 @@ HRESULT CDecoder::DecodeLZ()
570 if (_bitStream._buf >= _bitStream._bufCheck) 570 if (_bitStream._buf >= _bitStream._bufCheck)
571 _bitStream.Prepare2(); 571 _bitStream.Prepare2();
572 572
573 UInt64 processed = _bitStream.GetProcessedSize_Round(); 573 const UInt64 processed = _bitStream.GetProcessedSize_Round();
574 if (processed >= _bitStream._blockEnd) 574 if (processed >= _bitStream._blockEnd)
575 { 575 {
576 if (processed > _bitStream._blockEnd) 576 if (processed > _bitStream._blockEnd)
577 break; // return S_FALSE; 577 break; // return S_FALSE;
578 { 578 {
579 unsigned bits7 = _bitStream.GetProcessedBits7(); 579 const unsigned bits7 = _bitStream.GetProcessedBits7();
580 if (bits7 > _bitStream._blockEndBits7) 580 if (bits7 > _bitStream._blockEndBits7)
581 break; // return S_FALSE; 581 break; // return S_FALSE;
582 if (bits7 == _bitStream._blockEndBits7) 582 if (bits7 == _bitStream._blockEndBits7)
@@ -597,7 +597,7 @@ HRESULT CDecoder::DecodeLZ()
597 return _bitStream._hres; 597 return _bitStream._hres;
598 // break; 598 // break;
599 } 599 }
600 RINOK(ReadTables(_bitStream)); 600 RINOK(ReadTables(_bitStream))
601 continue; 601 continue;
602 } 602 }
603 } 603 }
@@ -608,7 +608,7 @@ HRESULT CDecoder::DecodeLZ()
608 break; // return S_FALSE; 608 break; // return S_FALSE;
609 } 609 }
610 610
611 UInt32 sym = m_MainDecoder.Decode(&_bitStream); 611 const UInt32 sym = m_MainDecoder.Decode(&_bitStream);
612 612
613 if (sym < 256) 613 if (sym < 256)
614 { 614 {
@@ -654,7 +654,7 @@ HRESULT CDecoder::DecodeLZ()
654 { 654 {
655 if (sym == 256) 655 if (sym == 256)
656 { 656 {
657 RINOK(AddFilter(_bitStream)); 657 RINOK(AddFilter(_bitStream))
658 continue; 658 continue;
659 } 659 }
660 else // if (sym == 257) 660 else // if (sym == 257)
@@ -682,7 +682,7 @@ HRESULT CDecoder::DecodeLZ()
682 { 682 {
683 if (rep0 >= _numCorrectDistSymbols) 683 if (rep0 >= _numCorrectDistSymbols)
684 break; // return S_FALSE; 684 break; // return S_FALSE;
685 unsigned numBits = (rep0 >> 1) - 1; 685 const unsigned numBits = (rep0 >> 1) - 1;
686 rep0 = (2 | (rep0 & 1)) << numBits; 686 rep0 = (2 | (rep0 & 1)) << numBits;
687 687
688 if (numBits < kNumAlignBits) 688 if (numBits < kNumAlignBits)
@@ -697,7 +697,7 @@ HRESULT CDecoder::DecodeLZ()
697 { 697 {
698 // if (numBits > kNumAlignBits) 698 // if (numBits > kNumAlignBits)
699 rep0 += (_bitStream.ReadBits32(numBits - kNumAlignBits) << kNumAlignBits); 699 rep0 += (_bitStream.ReadBits32(numBits - kNumAlignBits) << kNumAlignBits);
700 UInt32 a = m_AlignDecoder.Decode(&_bitStream); 700 const UInt32 a = m_AlignDecoder.Decode(&_bitStream);
701 if (a >= kAlignTableSize) 701 if (a >= kAlignTableSize)
702 break; // return S_FALSE; 702 break; // return S_FALSE;
703 rep0 += a; 703 rep0 += a;
@@ -718,7 +718,7 @@ HRESULT CDecoder::DecodeLZ()
718 size_t winPos = _winPos; 718 size_t winPos = _winPos;
719 size_t pos = (winPos - (size_t)rep0 - 1) & _winMask; 719 size_t pos = (winPos - (size_t)rep0 - 1) & _winMask;
720 { 720 {
721 size_t rem = limit - winPos; 721 const size_t rem = limit - winPos;
722 // size_t rem = _winSize - winPos; 722 // size_t rem = _winSize - winPos;
723 723
724 if (lenCur > rem) 724 if (lenCur > rem)
@@ -825,8 +825,8 @@ HRESULT CDecoder::CodeReal()
825 825
826static const unsigned kWinSize_Log_Min = 17; 826static const unsigned kWinSize_Log_Min = 17;
827 827
828STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 828Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
829 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 829 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
830{ 830{
831 try 831 try
832 { 832 {
@@ -850,7 +850,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
850 memset(_window, 0, _winSize); 850 memset(_window, 0, _winSize);
851 else 851 else
852 { 852 {
853 size_t pos = (size_t)_lzSize & _winSize; 853 const size_t pos = (size_t)_lzSize & _winSize;
854 size_t rem2 = _winSize - pos; 854 size_t rem2 = _winSize - pos;
855 if (rem2 > rem) 855 if (rem2 > rem)
856 rem2 = (size_t)rem; 856 rem2 = (size_t)rem;
@@ -905,10 +905,10 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
905 // but the original unRAR decoder still supports such grow case. 905 // but the original unRAR decoder still supports such grow case.
906 906
907 Byte *winOld = _window; 907 Byte *winOld = _window;
908 size_t oldSize = _winSize; 908 const size_t oldSize = _winSize;
909 size_t newMask = newSize - 1; 909 const size_t newMask = newSize - 1;
910 size_t oldMask = _winSize - 1; 910 const size_t oldMask = _winSize - 1;
911 size_t winPos = _winPos; 911 const size_t winPos = _winPos;
912 for (size_t i = 1; i <= oldSize; i++) 912 for (size_t i = 1; i <= oldSize; i++)
913 win[(winPos - i) & newMask] = winOld[(winPos - i) & oldMask]; 913 win[(winPos - i) & newMask] = winOld[(winPos - i) & oldMask];
914 ::MidFree(_window); 914 ::MidFree(_window);
@@ -951,7 +951,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
951 951
952 _progress = progress; 952 _progress = progress;
953 953
954 HRESULT res = CodeReal(); 954 const HRESULT res = CodeReal();
955 955
956 if (res != S_OK) 956 if (res != S_OK)
957 return res; 957 return res;
@@ -968,7 +968,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
968 // by error in data stream. 968 // by error in data stream.
969} 969}
970 970
971STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 971Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
972{ 972{
973 if (size != 2) 973 if (size != 2)
974 return E_NOTIMPL; 974 return E_NOTIMPL;
diff --git a/CPP/7zip/Compress/Rar5Decoder.h b/CPP/7zip/Compress/Rar5Decoder.h
index 8174c4a..daf05dd 100644
--- a/CPP/7zip/Compress/Rar5Decoder.h
+++ b/CPP/7zip/Compress/Rar5Decoder.h
@@ -2,8 +2,8 @@
2// According to unRAR license, this code may not be used to develop 2// According to unRAR license, this code may not be used to develop
3// a program that creates RAR archives 3// a program that creates RAR archives
4 4
5#ifndef __COMPRESS_RAR5_DECODER_H 5#ifndef ZIP7_INC_COMPRESS_RAR5_DECODER_H
6#define __COMPRESS_RAR5_DECODER_H 6#define ZIP7_INC_COMPRESS_RAR5_DECODER_H
7 7
8#include "../../../C/CpuArch.h" 8#include "../../../C/CpuArch.h"
9 9
@@ -19,7 +19,6 @@
19namespace NCompress { 19namespace NCompress {
20namespace NRar5 { 20namespace NRar5 {
21 21
22
23/* 22/*
24struct CInBufferException: public CSystemException 23struct CInBufferException: public CSystemException
25{ 24{
@@ -55,7 +54,7 @@ public:
55 _bufCheck2 = _buf; 54 _bufCheck2 = _buf;
56 else 55 else
57 { 56 {
58 UInt64 delta = _blockEnd - processed; 57 const UInt64 delta = _blockEnd - processed;
59 if ((size_t)(_bufCheck - _buf) > delta) 58 if ((size_t)(_bufCheck - _buf) > delta)
60 _bufCheck2 = _buf + (size_t)delta; 59 _bufCheck2 = _buf + (size_t)delta;
61 } 60 }
@@ -64,7 +63,7 @@ public:
64 63
65 bool IsBlockOverRead() const 64 bool IsBlockOverRead() const
66 { 65 {
67 UInt64 v = GetProcessedSize_Round(); 66 const UInt64 v = GetProcessedSize_Round();
68 if (v < _blockEnd) 67 if (v < _blockEnd)
69 return false; 68 return false;
70 if (v > _blockEnd) 69 if (v > _blockEnd)
@@ -113,8 +112,8 @@ public:
113 bool InputEofError() const { return ExtraBitsWereRead(); } 112 bool InputEofError() const { return ExtraBitsWereRead(); }
114 113
115 unsigned GetProcessedBits7() const { return _bitPos; } 114 unsigned GetProcessedBits7() const { return _bitPos; }
116 UInt64 GetProcessedSize_Round() const { return _processedSize + (_buf - _bufBase); } 115 UInt64 GetProcessedSize_Round() const { return _processedSize + (size_t)(_buf - _bufBase); }
117 UInt64 GetProcessedSize() const { return _processedSize + (_buf - _bufBase) + ((_bitPos + 7) >> 3); } 116 UInt64 GetProcessedSize() const { return _processedSize + (size_t)(_buf - _bufBase) + ((_bitPos + 7) >> 3); }
118 117
119 void AlignToByte() 118 void AlignToByte()
120 { 119 {
@@ -157,7 +156,7 @@ public:
157 { 156 {
158 const Byte *buf = _buf; 157 const Byte *buf = _buf;
159 UInt32 v = ((UInt32)buf[0] << 8) | (UInt32)buf[1]; 158 UInt32 v = ((UInt32)buf[0] << 8) | (UInt32)buf[1];
160 UInt32 mask = ((1 << numBits) - 1); 159 const UInt32 mask = ((1 << numBits) - 1);
161 numBits += _bitPos; 160 numBits += _bitPos;
162 v >>= (16 - numBits); 161 v >>= (16 - numBits);
163 _buf = buf + (numBits >> 3); 162 _buf = buf + (numBits >> 3);
@@ -167,7 +166,7 @@ public:
167 166
168 UInt32 ReadBits32(unsigned numBits) 167 UInt32 ReadBits32(unsigned numBits)
169 { 168 {
170 UInt32 mask = ((1 << numBits) - 1); 169 const UInt32 mask = ((1 << numBits) - 1);
171 numBits += _bitPos; 170 numBits += _bitPos;
172 const Byte *buf = _buf; 171 const Byte *buf = _buf;
173 UInt32 v = GetBe32(buf); 172 UInt32 v = GetBe32(buf);
@@ -205,11 +204,11 @@ const unsigned kTablesSizesSum = kMainTableSize + kDistTableSize + kAlignTableSi
205 204
206const unsigned kNumHuffmanBits = 15; 205const unsigned kNumHuffmanBits = 15;
207 206
208class CDecoder: 207Z7_CLASS_IMP_NOQIB_2(
209 public ICompressCoder, 208 CDecoder
210 public ICompressSetDecoderProperties2, 209 , ICompressCoder
211 public CMyUnknownImp 210 , ICompressSetDecoderProperties2
212{ 211)
213 bool _useAlignBits; 212 bool _useAlignBits;
214 bool _isLastBlock; 213 bool _isLastBlock;
215 bool _unpackSize_Defined; 214 bool _unpackSize_Defined;
@@ -293,13 +292,6 @@ class CDecoder:
293public: 292public:
294 CDecoder(); 293 CDecoder();
295 ~CDecoder(); 294 ~CDecoder();
296
297 MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2)
298
299 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
300 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
301
302 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
303}; 295};
304 296
305}} 297}}
diff --git a/CPP/7zip/Compress/ShrinkDecoder.cpp b/CPP/7zip/Compress/ShrinkDecoder.cpp
index 22f3844..c8e2083 100644
--- a/CPP/7zip/Compress/ShrinkDecoder.cpp
+++ b/CPP/7zip/Compress/ShrinkDecoder.cpp
@@ -198,7 +198,7 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
198 while (i); 198 while (i);
199 } 199 }
200 200
201 RINOK(outBuffer.Flush()); 201 RINOK(outBuffer.Flush())
202 202
203 if (res == S_OK) 203 if (res == S_OK)
204 if (_fullStreamMode) 204 if (_fullStreamMode)
@@ -216,8 +216,8 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
216} 216}
217 217
218 218
219STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 219Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
220 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 220 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
221{ 221{
222 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 222 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
223 // catch(const CInBufferException &e) { return e.ErrorCode; } 223 // catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -227,14 +227,14 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
227} 227}
228 228
229 229
230STDMETHODIMP CDecoder::SetFinishMode(UInt32 finishMode) 230Z7_COM7F_IMF(CDecoder::SetFinishMode(UInt32 finishMode))
231{ 231{
232 _fullStreamMode = (finishMode != 0); 232 _fullStreamMode = (finishMode != 0);
233 return S_OK; 233 return S_OK;
234} 234}
235 235
236 236
237STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) 237Z7_COM7F_IMF(CDecoder::GetInStreamProcessedSize(UInt64 *value))
238{ 238{
239 *value = _inProcessed; 239 *value = _inProcessed;
240 return S_OK; 240 return S_OK;
diff --git a/CPP/7zip/Compress/ShrinkDecoder.h b/CPP/7zip/Compress/ShrinkDecoder.h
index b095b5f..5e7f78f 100644
--- a/CPP/7zip/Compress/ShrinkDecoder.h
+++ b/CPP/7zip/Compress/ShrinkDecoder.h
@@ -1,7 +1,7 @@
1// ShrinkDecoder.h 1// ShrinkDecoder.h
2 2
3#ifndef __COMPRESS_SHRINK_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_SHRINK_DECODER_H
4#define __COMPRESS_SHRINK_DECODER_H 4#define ZIP7_INC_COMPRESS_SHRINK_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -13,12 +13,12 @@ namespace NShrink {
13const unsigned kNumMaxBits = 13; 13const unsigned kNumMaxBits = 13;
14const unsigned kNumItems = 1 << kNumMaxBits; 14const unsigned kNumItems = 1 << kNumMaxBits;
15 15
16class CDecoder : 16Z7_CLASS_IMP_NOQIB_3(
17 public ICompressCoder, 17 CDecoder
18 public ICompressSetFinishMode, 18 , ICompressCoder
19 public ICompressGetInStreamProcessedSize, 19 , ICompressSetFinishMode
20 public CMyUnknownImp 20 , ICompressGetInStreamProcessedSize
21{ 21)
22 bool _fullStreamMode; 22 bool _fullStreamMode;
23 UInt64 _inProcessed; 23 UInt64 _inProcessed;
24 24
@@ -28,16 +28,6 @@ class CDecoder :
28 28
29 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, 29 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
30 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 30 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
31
32public:
33 MY_UNKNOWN_IMP2(
34 ICompressSetFinishMode,
35 ICompressGetInStreamProcessedSize)
36
37 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
38 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
39 STDMETHOD(SetFinishMode)(UInt32 finishMode);
40 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
41}; 31};
42 32
43}} 33}}
diff --git a/CPP/7zip/Compress/StdAfx.h b/CPP/7zip/Compress/StdAfx.h
index 1cbd7fe..8086655 100644
--- a/CPP/7zip/Compress/StdAfx.h
+++ b/CPP/7zip/Compress/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../Common/Common.h" 9#include "../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Compress/XpressDecoder.cpp b/CPP/7zip/Compress/XpressDecoder.cpp
index a8bbd00..8816a12 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)
50 Byte levels[kNumSyms]; 50 Byte levels[kNumSyms];
51 for (unsigned i = 0; i < kNumSyms / 2; i++) 51 for (unsigned i = 0; i < kNumSyms / 2; i++)
52 { 52 {
53 Byte b = in[i]; 53 const Byte b = in[i];
54 levels[(size_t)i * 2] = (Byte)(b & 0xF); 54 levels[(size_t)i * 2] = (Byte)(b & 0xF);
55 levels[(size_t)i * 2 + 1] = (Byte)(b >> 4); 55 levels[(size_t)i * 2 + 1] = (Byte)(b >> 4);
56 } 56 }
@@ -64,7 +64,7 @@ HRESULT Decode(const Byte *in, size_t inSize, Byte *out, size_t outSize)
64 const Byte *lim = in + inSize - 1; 64 const Byte *lim = in + inSize - 1;
65 65
66 in += kNumSyms / 2; 66 in += kNumSyms / 2;
67 bs.Value = (GetUi16(in) << 16) | GetUi16(in + 2); 67 bs.Value = ((UInt32)GetUi16(in) << 16) | GetUi16(in + 2);
68 in += 4; 68 in += 4;
69 bs.BitPos = 32; 69 bs.BitPos = 32;
70 70
diff --git a/CPP/7zip/Compress/XpressDecoder.h b/CPP/7zip/Compress/XpressDecoder.h
index cada85b..aaa5b25 100644
--- a/CPP/7zip/Compress/XpressDecoder.h
+++ b/CPP/7zip/Compress/XpressDecoder.h
@@ -1,7 +1,9 @@
1// XpressDecoder.h 1// XpressDecoder.h
2 2
3#ifndef __XPRESS_DECODER_H 3#ifndef ZIP7_INC_XPRESS_DECODER_H
4#define __XPRESS_DECODER_H 4#define ZIP7_INC_XPRESS_DECODER_H
5
6#include "../../Common/MyWindows.h"
5 7
6namespace NCompress { 8namespace NCompress {
7namespace NXpress { 9namespace NXpress {
diff --git a/CPP/7zip/Compress/XzDecoder.cpp b/CPP/7zip/Compress/XzDecoder.cpp
index 0371173..420bd71 100644
--- a/CPP/7zip/Compress/XzDecoder.cpp
+++ b/CPP/7zip/Compress/XzDecoder.cpp
@@ -50,10 +50,10 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream
50 50
51 int isMT = False; 51 int isMT = False;
52 52
53 #ifndef _7ZIP_ST 53 #ifndef Z7_ST
54 { 54 {
55 props.numThreads = 1; 55 props.numThreads = 1;
56 UInt32 numThreads = _numThreads; 56 const UInt32 numThreads = _numThreads;
57 57
58 if (_tryMt && numThreads > 1) 58 if (_tryMt && numThreads > 1)
59 { 59 {
@@ -87,7 +87,7 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream
87 87
88 MainDecodeSRes = res; 88 MainDecodeSRes = res;
89 89
90 #ifndef _7ZIP_ST 90 #ifndef Z7_ST
91 // _tryMt = isMT; 91 // _tryMt = isMT;
92 #endif 92 #endif
93 93
@@ -113,33 +113,33 @@ HRESULT CDecoder::Decode(ISequentialInStream *seqInStream, ISequentialOutStream
113} 113}
114 114
115 115
116HRESULT CComDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 116Z7_COM7F_IMF(CComDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
117 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) 117 const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress))
118{ 118{
119 return Decode(inStream, outStream, outSize, _finishStream, progress); 119 return Decode(inStream, outStream, outSize, _finishStream, progress);
120} 120}
121 121
122STDMETHODIMP CComDecoder::SetFinishMode(UInt32 finishMode) 122Z7_COM7F_IMF(CComDecoder::SetFinishMode(UInt32 finishMode))
123{ 123{
124 _finishStream = (finishMode != 0); 124 _finishStream = (finishMode != 0);
125 return S_OK; 125 return S_OK;
126} 126}
127 127
128STDMETHODIMP CComDecoder::GetInStreamProcessedSize(UInt64 *value) 128Z7_COM7F_IMF(CComDecoder::GetInStreamProcessedSize(UInt64 *value))
129{ 129{
130 *value = Stat.InSize; 130 *value = Stat.InSize;
131 return S_OK; 131 return S_OK;
132} 132}
133 133
134#ifndef _7ZIP_ST 134#ifndef Z7_ST
135 135
136STDMETHODIMP CComDecoder::SetNumberOfThreads(UInt32 numThreads) 136Z7_COM7F_IMF(CComDecoder::SetNumberOfThreads(UInt32 numThreads))
137{ 137{
138 _numThreads = numThreads; 138 _numThreads = numThreads;
139 return S_OK; 139 return S_OK;
140} 140}
141 141
142STDMETHODIMP CComDecoder::SetMemLimit(UInt64 memUsage) 142Z7_COM7F_IMF(CComDecoder::SetMemLimit(UInt64 memUsage))
143{ 143{
144 _memUsage = memUsage; 144 _memUsage = memUsage;
145 return S_OK; 145 return S_OK;
diff --git a/CPP/7zip/Compress/XzDecoder.h b/CPP/7zip/Compress/XzDecoder.h
index 7ad81f4..40ed4f5 100644
--- a/CPP/7zip/Compress/XzDecoder.h
+++ b/CPP/7zip/Compress/XzDecoder.h
@@ -1,7 +1,7 @@
1// XzDecoder.h 1// XzDecoder.h
2 2
3#ifndef __XZ_DECODER_H 3#ifndef ZIP7_INC_XZ_DECODER_H
4#define __XZ_DECODER_H 4#define ZIP7_INC_XZ_DECODER_H
5 5
6#include "../../../C/Xz.h" 6#include "../../../C/Xz.h"
7 7
@@ -46,45 +46,38 @@ struct CDecoder
46}; 46};
47 47
48 48
49class CComDecoder: 49class CComDecoder Z7_final:
50 public ICompressCoder, 50 public ICompressCoder,
51 public ICompressSetFinishMode, 51 public ICompressSetFinishMode,
52 public ICompressGetInStreamProcessedSize, 52 public ICompressGetInStreamProcessedSize,
53 53 #ifndef Z7_ST
54 #ifndef _7ZIP_ST
55 public ICompressSetCoderMt, 54 public ICompressSetCoderMt,
56 public ICompressSetMemLimit, 55 public ICompressSetMemLimit,
57 #endif 56 #endif
58
59 public CMyUnknownImp, 57 public CMyUnknownImp,
60 public CDecoder 58 public CDecoder
61{ 59{
60 Z7_COM_QI_BEGIN2(ICompressCoder)
61 Z7_COM_QI_ENTRY(ICompressSetFinishMode)
62 Z7_COM_QI_ENTRY(ICompressGetInStreamProcessedSize)
63 #ifndef Z7_ST
64 Z7_COM_QI_ENTRY(ICompressSetCoderMt)
65 Z7_COM_QI_ENTRY(ICompressSetMemLimit)
66 #endif
67 Z7_COM_QI_END
68 Z7_COM_ADDREF_RELEASE
69
70 Z7_IFACE_COM7_IMP(ICompressCoder)
71 Z7_IFACE_COM7_IMP(ICompressSetFinishMode)
72 Z7_IFACE_COM7_IMP(ICompressGetInStreamProcessedSize)
73 #ifndef Z7_ST
74 Z7_IFACE_COM7_IMP(ICompressSetCoderMt)
75 Z7_IFACE_COM7_IMP(ICompressSetMemLimit)
76 #endif
77
62 bool _finishStream; 78 bool _finishStream;
63 79
64public: 80public:
65 MY_QUERYINTERFACE_BEGIN2(ICompressCoder)
66
67 MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode)
68 MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize)
69
70 #ifndef _7ZIP_ST
71 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderMt)
72 MY_QUERYINTERFACE_ENTRY(ICompressSetMemLimit)
73 #endif
74
75 MY_QUERYINTERFACE_END
76 MY_ADDREF_RELEASE
77
78 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
79 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
80 STDMETHOD(SetFinishMode)(UInt32 finishMode);
81 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value);
82
83 #ifndef _7ZIP_ST
84 STDMETHOD(SetNumberOfThreads)(UInt32 numThreads);
85 STDMETHOD(SetMemLimit)(UInt64 memUsage);
86 #endif
87
88 CComDecoder(): _finishStream(false) {} 81 CComDecoder(): _finishStream(false) {}
89}; 82};
90 83
diff --git a/CPP/7zip/Compress/XzEncoder.cpp b/CPP/7zip/Compress/XzEncoder.cpp
index d6f42ca..33f0bde 100644
--- a/CPP/7zip/Compress/XzEncoder.cpp
+++ b/CPP/7zip/Compress/XzEncoder.cpp
@@ -15,9 +15,7 @@
15namespace NCompress { 15namespace NCompress {
16 16
17namespace NLzma2 { 17namespace NLzma2 {
18
19HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzma2Props); 18HRESULT SetLzma2Prop(PROPID propID, const PROPVARIANT &prop, CLzma2EncProps &lzma2Props);
20
21} 19}
22 20
23namespace NXz { 21namespace NXz {
@@ -63,7 +61,7 @@ static const CMethodNamePair g_NamePairs[] =
63 61
64static int FilterIdFromName(const wchar_t *name) 62static int FilterIdFromName(const wchar_t *name)
65{ 63{
66 for (unsigned i = 0; i < ARRAY_SIZE(g_NamePairs); i++) 64 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_NamePairs); i++)
67 { 65 {
68 const CMethodNamePair &pair = g_NamePairs[i]; 66 const CMethodNamePair &pair = g_NamePairs[i];
69 if (StringsAreEqualNoCase_Ascii(name, pair.Name)) 67 if (StringsAreEqualNoCase_Ascii(name, pair.Name))
@@ -130,7 +128,7 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop)
130 { 128 {
131 if (prop.vt == VT_UI4) 129 if (prop.vt == VT_UI4)
132 { 130 {
133 UInt32 id32 = prop.ulVal; 131 const UInt32 id32 = prop.ulVal;
134 if (id32 == XZ_ID_Delta) 132 if (id32 == XZ_ID_Delta)
135 return E_INVALIDARG; 133 return E_INVALIDARG;
136 xzProps.filterProps.id = prop.ulVal; 134 xzProps.filterProps.id = prop.ulVal;
@@ -156,7 +154,7 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop)
156 } 154 }
157 else 155 else
158 { 156 {
159 int filterId = FilterIdFromName(prop.bstrVal); 157 const int filterId = FilterIdFromName(prop.bstrVal);
160 if (filterId < 0 /* || filterId == XZ_ID_LZMA2 */) 158 if (filterId < 0 /* || filterId == XZ_ID_LZMA2 */)
161 return E_INVALIDARG; 159 return E_INVALIDARG;
162 id32 = (unsigned)filterId; 160 id32 = (unsigned)filterId;
@@ -165,11 +163,11 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop)
165 163
166 if (id32 == XZ_ID_Delta) 164 if (id32 == XZ_ID_Delta)
167 { 165 {
168 wchar_t c = *name; 166 const wchar_t c = *name;
169 if (c != '-' && c != ':') 167 if (c != '-' && c != ':')
170 return E_INVALIDARG; 168 return E_INVALIDARG;
171 name++; 169 name++;
172 UInt32 delta = ConvertStringToUInt32(name, &end); 170 const UInt32 delta = ConvertStringToUInt32(name, &end);
173 if (end == name || *end != 0 || delta == 0 || delta > 256) 171 if (end == name || *end != 0 || delta == 0 || delta > 256)
174 return E_INVALIDARG; 172 return E_INVALIDARG;
175 xzProps.filterProps.delta = delta; 173 xzProps.filterProps.delta = delta;
@@ -185,14 +183,14 @@ HRESULT CEncoder::SetCoderProp(PROPID propID, const PROPVARIANT &prop)
185} 183}
186 184
187 185
188STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, 186Z7_COM7F_IMF(CEncoder::SetCoderProperties(const PROPID *propIDs,
189 const PROPVARIANT *coderProps, UInt32 numProps) 187 const PROPVARIANT *coderProps, UInt32 numProps))
190{ 188{
191 XzProps_Init(&xzProps); 189 XzProps_Init(&xzProps);
192 190
193 for (UInt32 i = 0; i < numProps; i++) 191 for (UInt32 i = 0; i < numProps; i++)
194 { 192 {
195 RINOK(SetCoderProp(propIDs[i], coderProps[i])); 193 RINOK(SetCoderProp(propIDs[i], coderProps[i]))
196 } 194 }
197 195
198 return S_OK; 196 return S_OK;
@@ -200,13 +198,13 @@ STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs,
200} 198}
201 199
202 200
203STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs, 201Z7_COM7F_IMF(CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
204 const PROPVARIANT *coderProps, UInt32 numProps) 202 const PROPVARIANT *coderProps, UInt32 numProps))
205{ 203{
206 for (UInt32 i = 0; i < numProps; i++) 204 for (UInt32 i = 0; i < numProps; i++)
207 { 205 {
208 const PROPVARIANT &prop = coderProps[i]; 206 const PROPVARIANT &prop = coderProps[i];
209 PROPID propID = propIDs[i]; 207 const PROPID propID = propIDs[i];
210 if (propID == NCoderPropID::kExpectedDataSize) 208 if (propID == NCoderPropID::kExpectedDataSize)
211 if (prop.vt == VT_UI8) 209 if (prop.vt == VT_UI8)
212 XzEnc_SetDataSize(_encoder, prop.uhVal.QuadPart); 210 XzEnc_SetDataSize(_encoder, prop.uhVal.QuadPart);
@@ -218,8 +216,8 @@ STDMETHODIMP CEncoder::SetCoderPropertiesOpt(const PROPID *propIDs,
218#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \ 216#define RET_IF_WRAP_ERROR(wrapRes, sRes, sResErrorCode) \
219 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes; 217 if (wrapRes != S_OK /* && (sRes == SZ_OK || sRes == sResErrorCode) */) return wrapRes;
220 218
221STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 219Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
222 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 220 const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
223{ 221{
224 CSeqInStreamWrap inWrap; 222 CSeqInStreamWrap inWrap;
225 CSeqOutStreamWrap outWrap; 223 CSeqOutStreamWrap outWrap;
diff --git a/CPP/7zip/Compress/XzEncoder.h b/CPP/7zip/Compress/XzEncoder.h
index ea5190e..434f582 100644
--- a/CPP/7zip/Compress/XzEncoder.h
+++ b/CPP/7zip/Compress/XzEncoder.h
@@ -1,7 +1,7 @@
1// XzEncoder.h 1// XzEncoder.h
2 2
3#ifndef __XZ_ENCODER_H 3#ifndef ZIP7_INC_XZ_ENCODER_H
4#define __XZ_ENCODER_H 4#define ZIP7_INC_XZ_ENCODER_H
5 5
6#include "../../../C/XzEnc.h" 6#include "../../../C/XzEnc.h"
7 7
@@ -12,33 +12,22 @@
12namespace NCompress { 12namespace NCompress {
13namespace NXz { 13namespace NXz {
14 14
15 15Z7_CLASS_IMP_COM_3(
16class CEncoder: 16 CEncoder
17 public ICompressCoder, 17 , ICompressCoder
18 public ICompressSetCoderProperties, 18 , ICompressSetCoderProperties
19 public ICompressSetCoderPropertiesOpt, 19 , ICompressSetCoderPropertiesOpt
20 public CMyUnknownImp 20)
21{
22 CXzEncHandle _encoder; 21 CXzEncHandle _encoder;
23public: 22public:
24 CXzProps xzProps; 23 CXzProps xzProps;
25 24
26 MY_UNKNOWN_IMP3(
27 ICompressCoder,
28 ICompressSetCoderProperties,
29 ICompressSetCoderPropertiesOpt)
30
31 void InitCoderProps(); 25 void InitCoderProps();
32 HRESULT SetCheckSize(UInt32 checkSizeInBytes); 26 HRESULT SetCheckSize(UInt32 checkSizeInBytes);
33 HRESULT SetCoderProp(PROPID propID, const PROPVARIANT &prop); 27 HRESULT SetCoderProp(PROPID propID, const PROPVARIANT &prop);
34
35 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
36 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
37 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
38 STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
39 28
40 CEncoder(); 29 CEncoder();
41 virtual ~CEncoder(); 30 ~CEncoder();
42}; 31};
43 32
44}} 33}}
diff --git a/CPP/7zip/Compress/ZDecoder.cpp b/CPP/7zip/Compress/ZDecoder.cpp
index 06eab00..07c5fe5 100644
--- a/CPP/7zip/Compress/ZDecoder.cpp
+++ b/CPP/7zip/Compress/ZDecoder.cpp
@@ -22,9 +22,9 @@ static const unsigned kNumMaxBits = 16;
22 22
23void CDecoder::Free() 23void CDecoder::Free()
24{ 24{
25 MyFree(_parents); _parents = 0; 25 MyFree(_parents); _parents = NULL;
26 MyFree(_suffixes); _suffixes = 0; 26 MyFree(_suffixes); _suffixes = NULL;
27 MyFree(_stack); _stack = 0; 27 MyFree(_stack); _stack = NULL;
28} 28}
29 29
30CDecoder::~CDecoder() { Free(); } 30CDecoder::~CDecoder() { Free(); }
@@ -52,29 +52,29 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
52 if (inBuffer.ReadBytes(buf, 3) < 3) 52 if (inBuffer.ReadBytes(buf, 3) < 3)
53 return S_FALSE; 53 return S_FALSE;
54 if (buf[0] != 0x1F || buf[1] != 0x9D) 54 if (buf[0] != 0x1F || buf[1] != 0x9D)
55 return S_FALSE;; 55 return S_FALSE;
56 } 56 }
57 Byte prop = buf[2]; 57 Byte prop = buf[2];
58 58
59 if ((prop & 0x60) != 0) 59 if ((prop & 0x60) != 0)
60 return S_FALSE; 60 return S_FALSE;
61 unsigned maxbits = prop & kNumBitsMask; 61 const unsigned maxbits = prop & kNumBitsMask;
62 if (maxbits < kNumMinBits || maxbits > kNumMaxBits) 62 if (maxbits < kNumMinBits || maxbits > kNumMaxBits)
63 return S_FALSE; 63 return S_FALSE;
64 UInt32 numItems = 1 << maxbits; 64 const UInt32 numItems = 1 << maxbits;
65 // Speed optimization: blockSymbol can contain unused velue. 65 // Speed optimization: blockSymbol can contain unused velue.
66 66
67 if (maxbits != _numMaxBits || _parents == 0 || _suffixes == 0 || _stack == 0) 67 if (maxbits != _numMaxBits || !_parents || !_suffixes || !_stack)
68 { 68 {
69 Free(); 69 Free();
70 _parents = (UInt16 *)MyAlloc(numItems * sizeof(UInt16)); if (_parents == 0) return E_OUTOFMEMORY; 70 _parents = (UInt16 *)MyAlloc(numItems * sizeof(UInt16)); if (!_parents) return E_OUTOFMEMORY;
71 _suffixes = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (_suffixes == 0) return E_OUTOFMEMORY; 71 _suffixes = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (!_suffixes) return E_OUTOFMEMORY;
72 _stack = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (_stack == 0) return E_OUTOFMEMORY; 72 _stack = (Byte *)MyAlloc(numItems * sizeof(Byte)); if (!_stack) return E_OUTOFMEMORY;
73 _numMaxBits = maxbits; 73 _numMaxBits = maxbits;
74 } 74 }
75 75
76 UInt64 prevPos = 0; 76 UInt64 prevPos = 0;
77 UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); 77 const UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits);
78 unsigned numBits = kNumMinBits; 78 unsigned numBits = kNumMinBits;
79 UInt32 head = (blockSymbol == 256) ? 257 : 256; 79 UInt32 head = (blockSymbol == 256) ? 257 : 256;
80 bool needPrev = false; 80 bool needPrev = false;
@@ -91,15 +91,15 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
91 { 91 {
92 numBufBits = (unsigned)inBuffer.ReadBytes(buf, numBits) * 8; 92 numBufBits = (unsigned)inBuffer.ReadBytes(buf, numBits) * 8;
93 bitPos = 0; 93 bitPos = 0;
94 UInt64 nowPos = outBuffer.GetProcessedSize(); 94 const UInt64 nowPos = outBuffer.GetProcessedSize();
95 if (progress && nowPos - prevPos >= (1 << 13)) 95 if (progress && nowPos - prevPos >= (1 << 13))
96 { 96 {
97 prevPos = nowPos; 97 prevPos = nowPos;
98 UInt64 packSize = inBuffer.GetProcessedSize(); 98 const UInt64 packSize = inBuffer.GetProcessedSize();
99 RINOK(progress->SetRatioInfo(&packSize, &nowPos)); 99 RINOK(progress->SetRatioInfo(&packSize, &nowPos))
100 } 100 }
101 } 101 }
102 unsigned bytePos = bitPos >> 3; 102 const unsigned bytePos = bitPos >> 3;
103 UInt32 symbol = buf[bytePos] | ((UInt32)buf[(size_t)bytePos + 1] << 8) | ((UInt32)buf[(size_t)bytePos + 2] << 16); 103 UInt32 symbol = buf[bytePos] | ((UInt32)buf[(size_t)bytePos + 1] << 8) | ((UInt32)buf[(size_t)bytePos + 2] << 16);
104 symbol >>= (bitPos & 7); 104 symbol >>= (bitPos & 7);
105 symbol &= (1 << numBits) - 1; 105 symbol &= (1 << numBits) - 1;
@@ -153,12 +153,12 @@ HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *
153 needPrev = false; 153 needPrev = false;
154 } 154 }
155 PackSize = inBuffer.GetProcessedSize(); 155 PackSize = inBuffer.GetProcessedSize();
156 HRESULT res2 = outBuffer.Flush(); 156 const HRESULT res2 = outBuffer.Flush();
157 return (res == S_OK) ? res2 : res; 157 return (res == S_OK) ? res2 : res;
158} 158}
159 159
160STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 160Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
161 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 161 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
162{ 162{
163 try { return CodeReal(inStream, outStream, inSize, outSize, progress); } 163 try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
164 catch(const CInBufferException &e) { return e.ErrorCode; } 164 catch(const CInBufferException &e) { return e.ErrorCode; }
@@ -172,14 +172,14 @@ bool CheckStream(const Byte *data, size_t size)
172 return false; 172 return false;
173 if (data[0] != 0x1F || data[1] != 0x9D) 173 if (data[0] != 0x1F || data[1] != 0x9D)
174 return false; 174 return false;
175 Byte prop = data[2]; 175 const Byte prop = data[2];
176 if ((prop & 0x60) != 0) 176 if ((prop & 0x60) != 0)
177 return false; 177 return false;
178 unsigned maxbits = prop & kNumBitsMask; 178 const unsigned maxbits = prop & kNumBitsMask;
179 if (maxbits < kNumMinBits || maxbits > kNumMaxBits) 179 if (maxbits < kNumMinBits || maxbits > kNumMaxBits)
180 return false; 180 return false;
181 UInt32 numItems = 1 << maxbits; 181 const UInt32 numItems = 1 << maxbits;
182 UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits); 182 const UInt32 blockSymbol = ((prop & kBlockModeMask) != 0) ? 256 : ((UInt32)1 << kNumMaxBits);
183 unsigned numBits = kNumMinBits; 183 unsigned numBits = kNumMinBits;
184 UInt32 head = (blockSymbol == 256) ? 257 : 256; 184 UInt32 head = (blockSymbol == 256) ? 257 : 256;
185 unsigned bitPos = 0; 185 unsigned bitPos = 0;
@@ -192,14 +192,14 @@ bool CheckStream(const Byte *data, size_t size)
192 { 192 {
193 if (numBufBits == bitPos) 193 if (numBufBits == bitPos)
194 { 194 {
195 unsigned num = (numBits < size) ? numBits : (unsigned)size; 195 const unsigned num = (numBits < size) ? numBits : (unsigned)size;
196 memcpy(buf, data, num); 196 memcpy(buf, data, num);
197 data += num; 197 data += num;
198 size -= num; 198 size -= num;
199 numBufBits = num * 8; 199 numBufBits = num * 8;
200 bitPos = 0; 200 bitPos = 0;
201 } 201 }
202 unsigned bytePos = bitPos >> 3; 202 const unsigned bytePos = bitPos >> 3;
203 UInt32 symbol = buf[bytePos] | ((UInt32)buf[bytePos + 1] << 8) | ((UInt32)buf[bytePos + 2] << 16); 203 UInt32 symbol = buf[bytePos] | ((UInt32)buf[bytePos + 1] << 8) | ((UInt32)buf[bytePos + 2] << 16);
204 symbol >>= (bitPos & 7); 204 symbol >>= (bitPos & 7);
205 symbol &= (1 << numBits) - 1; 205 symbol &= (1 << numBits) - 1;
diff --git a/CPP/7zip/Compress/ZDecoder.h b/CPP/7zip/Compress/ZDecoder.h
index 19acd49..390b013 100644
--- a/CPP/7zip/Compress/ZDecoder.h
+++ b/CPP/7zip/Compress/ZDecoder.h
@@ -1,7 +1,7 @@
1// ZDecoder.h 1// ZDecoder.h
2 2
3#ifndef __COMPRESS_Z_DECODER_H 3#ifndef ZIP7_INC_COMPRESS_Z_DECODER_H
4#define __COMPRESS_Z_DECODER_H 4#define ZIP7_INC_COMPRESS_Z_DECODER_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -12,28 +12,23 @@ namespace NZ {
12 12
13// Z decoder decodes Z data stream, including 3 bytes of header. 13// Z decoder decodes Z data stream, including 3 bytes of header.
14 14
15class CDecoder: 15Z7_CLASS_IMP_COM_1(
16 public ICompressCoder, 16 CDecoder
17 public CMyUnknownImp 17 , ICompressCoder
18{ 18)
19 UInt16 *_parents; 19 UInt16 *_parents;
20 Byte *_suffixes; 20 Byte *_suffixes;
21 Byte *_stack; 21 Byte *_stack;
22 unsigned _numMaxBits; 22 unsigned _numMaxBits;
23 23
24public: 24public:
25 CDecoder(): _parents(0), _suffixes(0), _stack(0), /* _prop(0), */ _numMaxBits(0) {}; 25 CDecoder(): _parents(NULL), _suffixes(NULL), _stack(NULL), /* _prop(0), */ _numMaxBits(0) {}
26 ~CDecoder(); 26 ~CDecoder();
27 void Free(); 27 void Free();
28 UInt64 PackSize; 28 UInt64 PackSize;
29 29
30 MY_UNKNOWN_IMP1(ICompressCoder)
31
32 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, 30 HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
33 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); 31 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
34
35 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
36 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
37}; 32};
38 33
39/* 34/*
diff --git a/CPP/7zip/Compress/ZlibDecoder.cpp b/CPP/7zip/Compress/ZlibDecoder.cpp
index 2356c7c..a066932 100644
--- a/CPP/7zip/Compress/ZlibDecoder.cpp
+++ b/CPP/7zip/Compress/ZlibDecoder.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../C/CpuArch.h"
6
5#include "../Common/StreamUtils.h" 7#include "../Common/StreamUtils.h"
6 8
7#include "ZlibDecoder.h" 9#include "ZlibDecoder.h"
@@ -22,7 +24,7 @@ UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size)
22 UInt32 b = (adler >> 16) & 0xFFFF; 24 UInt32 b = (adler >> 16) & 0xFFFF;
23 while (size > 0) 25 while (size > 0)
24 { 26 {
25 unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size; 27 const unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size;
26 unsigned i; 28 unsigned i;
27 for (i = 0; i < curSize; i++) 29 for (i = 0; i < curSize; i++)
28 { 30 {
@@ -37,7 +39,7 @@ UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size)
37 return (b << 16) + a; 39 return (b << 16) + a;
38} 40}
39 41
40STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize) 42Z7_COM7F_IMF(COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize))
41{ 43{
42 HRESULT result = S_OK; 44 HRESULT result = S_OK;
43 if (_stream) 45 if (_stream)
@@ -49,8 +51,8 @@ STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *p
49 return result; 51 return result;
50} 52}
51 53
52STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 54Z7_COM7F_IMF(CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
53 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) 55 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress))
54{ 56{
55 DEFLATE_TRY_BEGIN 57 DEFLATE_TRY_BEGIN
56 if (!AdlerStream) 58 if (!AdlerStream)
@@ -65,7 +67,7 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
65 if (inSize && *inSize < 2) 67 if (inSize && *inSize < 2)
66 return S_FALSE; 68 return S_FALSE;
67 Byte buf[2]; 69 Byte buf[2];
68 RINOK(ReadStream_FALSE(inStream, buf, 2)); 70 RINOK(ReadStream_FALSE(inStream, buf, 2))
69 if (!IsZlib(buf)) 71 if (!IsZlib(buf))
70 return S_FALSE; 72 return S_FALSE;
71 73
@@ -76,13 +78,13 @@ STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream
76 if (inSize) 78 if (inSize)
77 inSize2 = *inSize - 2; 79 inSize2 = *inSize - 2;
78 80
79 HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize ? &inSize2 : NULL, outSize, progress); 81 const HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize ? &inSize2 : NULL, outSize, progress);
80 AdlerSpec->ReleaseStream(); 82 AdlerSpec->ReleaseStream();
81 83
82 if (res == S_OK) 84 if (res == S_OK)
83 { 85 {
84 const Byte *p = DeflateDecoderSpec->ZlibFooter; 86 const Byte *p = DeflateDecoderSpec->ZlibFooter;
85 UInt32 adler = ((UInt32)p[0] << 24) | ((UInt32)p[1] << 16) | ((UInt32)p[2] << 8) | p[3]; 87 const UInt32 adler = GetBe32(p);
86 if (adler != AdlerSpec->GetAdler()) 88 if (adler != AdlerSpec->GetAdler())
87 return S_FALSE; 89 return S_FALSE;
88 } 90 }
diff --git a/CPP/7zip/Compress/ZlibDecoder.h b/CPP/7zip/Compress/ZlibDecoder.h
index 8c5e73b..1dc5c67 100644
--- a/CPP/7zip/Compress/ZlibDecoder.h
+++ b/CPP/7zip/Compress/ZlibDecoder.h
@@ -1,7 +1,7 @@
1// ZlibDecoder.h 1// ZlibDecoder.h
2 2
3#ifndef __ZLIB_DECODER_H 3#ifndef ZIP7_INC_ZLIB_DECODER_H
4#define __ZLIB_DECODER_H 4#define ZIP7_INC_ZLIB_DECODER_H
5 5
6#include "DeflateDecoder.h" 6#include "DeflateDecoder.h"
7 7
@@ -10,16 +10,14 @@ namespace NZlib {
10 10
11const UInt32 ADLER_INIT_VAL = 1; 11const UInt32 ADLER_INIT_VAL = 1;
12 12
13class COutStreamWithAdler: 13Z7_CLASS_IMP_NOQIB_1(
14 public ISequentialOutStream, 14 COutStreamWithAdler
15 public CMyUnknownImp 15 , ISequentialOutStream
16{ 16)
17 CMyComPtr<ISequentialOutStream> _stream; 17 CMyComPtr<ISequentialOutStream> _stream;
18 UInt32 _adler; 18 UInt32 _adler;
19 UInt64 _size; 19 UInt64 _size;
20public: 20public:
21 MY_UNKNOWN_IMP
22 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
23 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 21 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
24 void ReleaseStream() { _stream.Release(); } 22 void ReleaseStream() { _stream.Release(); }
25 void Init() { _adler = ADLER_INIT_VAL; _size = 0; } 23 void Init() { _adler = ADLER_INIT_VAL; _size = 0; }
@@ -27,23 +25,17 @@ public:
27 UInt64 GetSize() const { return _size; } 25 UInt64 GetSize() const { return _size; }
28}; 26};
29 27
30class CDecoder: 28Z7_CLASS_IMP_NOQIB_1(
31 public ICompressCoder, 29 CDecoder
32 public CMyUnknownImp 30 , ICompressCoder
33{ 31)
34 COutStreamWithAdler *AdlerSpec; 32 COutStreamWithAdler *AdlerSpec;
35 CMyComPtr<ISequentialOutStream> AdlerStream; 33 CMyComPtr<ISequentialOutStream> AdlerStream;
36
37 NCompress::NDeflate::NDecoder::CCOMCoder *DeflateDecoderSpec; 34 NCompress::NDeflate::NDecoder::CCOMCoder *DeflateDecoderSpec;
38 CMyComPtr<ICompressCoder> DeflateDecoder; 35 CMyComPtr<ICompressCoder> DeflateDecoder;
39public: 36public:
40 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
41 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
42
43 UInt64 GetInputProcessedSize() const { return DeflateDecoderSpec->GetInputProcessedSize() + 2; } 37 UInt64 GetInputProcessedSize() const { return DeflateDecoderSpec->GetInputProcessedSize() + 2; }
44 UInt64 GetOutputProcessedSize() const { return AdlerSpec->GetSize(); } 38 UInt64 GetOutputProcessedSize() const { return AdlerSpec->GetSize(); }
45
46 MY_UNKNOWN_IMP
47}; 39};
48 40
49static bool inline IsZlib(const Byte *p) 41static bool inline IsZlib(const Byte *p)
@@ -65,8 +57,8 @@ static bool inline IsZlib_3bytes(const Byte *p)
65{ 57{
66 if (!IsZlib(p)) 58 if (!IsZlib(p))
67 return false; 59 return false;
68 unsigned val = p[2]; 60 const unsigned val = p[2];
69 unsigned blockType = (val >> 1) & 0x3; 61 const unsigned blockType = (val >> 1) & 0x3;
70 if (blockType == 3) // unsupported block type for deflate 62 if (blockType == 3) // unsupported block type for deflate
71 return false; 63 return false;
72 if (blockType == NCompress::NDeflate::NBlockType::kStored && (val >> 3) != 0) 64 if (blockType == NCompress::NDeflate::NBlockType::kStored && (val >> 3) != 0)
diff --git a/CPP/7zip/Compress/ZlibEncoder.cpp b/CPP/7zip/Compress/ZlibEncoder.cpp
index 09235c3..3670d30 100644
--- a/CPP/7zip/Compress/ZlibEncoder.cpp
+++ b/CPP/7zip/Compress/ZlibEncoder.cpp
@@ -14,12 +14,12 @@ namespace NZlib {
14 14
15UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size); 15UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size);
16 16
17STDMETHODIMP CInStreamWithAdler::Read(void *data, UInt32 size, UInt32 *processedSize) 17Z7_COM7F_IMF(CInStreamWithAdler::Read(void *data, UInt32 size, UInt32 *processedSize))
18{ 18{
19 HRESULT result = _stream->Read(data, size, &size); 19 const HRESULT result = _stream->Read(data, size, &size);
20 _adler = Adler32_Update(_adler, (const Byte *)data, size); 20 _adler = Adler32_Update(_adler, (const Byte *)data, size);
21 _size += size; 21 _size += size;
22 if (processedSize != NULL) 22 if (processedSize)
23 *processedSize = size; 23 *processedSize = size;
24 return result; 24 return result;
25} 25}
@@ -30,8 +30,8 @@ void CEncoder::Create()
30 DeflateEncoder = DeflateEncoderSpec = new NDeflate::NEncoder::CCOMCoder; 30 DeflateEncoder = DeflateEncoderSpec = new NDeflate::NEncoder::CCOMCoder;
31} 31}
32 32
33STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, 33Z7_COM7F_IMF(CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
34 const UInt64 *inSize, const UInt64 * /* outSize */, ICompressProgressInfo *progress) 34 const UInt64 *inSize, const UInt64 * /* outSize */, ICompressProgressInfo *progress))
35{ 35{
36 DEFLATE_TRY_BEGIN 36 DEFLATE_TRY_BEGIN
37 if (!AdlerStream) 37 if (!AdlerStream)
@@ -40,19 +40,19 @@ STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream
40 40
41 { 41 {
42 Byte buf[2] = { 0x78, 0xDA }; 42 Byte buf[2] = { 0x78, 0xDA };
43 RINOK(WriteStream(outStream, buf, 2)); 43 RINOK(WriteStream(outStream, buf, 2))
44 } 44 }
45 45
46 AdlerSpec->SetStream(inStream); 46 AdlerSpec->SetStream(inStream);
47 AdlerSpec->Init(); 47 AdlerSpec->Init();
48 HRESULT res = DeflateEncoder->Code(AdlerStream, outStream, inSize, NULL, progress); 48 const HRESULT res = DeflateEncoder->Code(AdlerStream, outStream, inSize, NULL, progress);
49 AdlerSpec->ReleaseStream(); 49 AdlerSpec->ReleaseStream();
50 50
51 RINOK(res); 51 RINOK(res)
52 52
53 { 53 {
54 UInt32 a = AdlerSpec->GetAdler(); 54 const UInt32 a = AdlerSpec->GetAdler();
55 Byte buf[4] = { (Byte)(a >> 24), (Byte)(a >> 16), (Byte)(a >> 8), (Byte)(a) }; 55 const Byte buf[4] = { (Byte)(a >> 24), (Byte)(a >> 16), (Byte)(a >> 8), (Byte)(a) };
56 return WriteStream(outStream, buf, 4); 56 return WriteStream(outStream, buf, 4);
57 } 57 }
58 DEFLATE_TRY_END 58 DEFLATE_TRY_END
diff --git a/CPP/7zip/Compress/ZlibEncoder.h b/CPP/7zip/Compress/ZlibEncoder.h
index 621cc1d..484a307 100644
--- a/CPP/7zip/Compress/ZlibEncoder.h
+++ b/CPP/7zip/Compress/ZlibEncoder.h
@@ -1,23 +1,21 @@
1// ZlibEncoder.h 1// ZlibEncoder.h
2 2
3#ifndef __ZLIB_ENCODER_H 3#ifndef ZIP7_INC_ZLIB_ENCODER_H
4#define __ZLIB_ENCODER_H 4#define ZIP7_INC_ZLIB_ENCODER_H
5 5
6#include "DeflateEncoder.h" 6#include "DeflateEncoder.h"
7 7
8namespace NCompress { 8namespace NCompress {
9namespace NZlib { 9namespace NZlib {
10 10
11class CInStreamWithAdler: 11Z7_CLASS_IMP_NOQIB_1(
12 public ISequentialInStream, 12 CInStreamWithAdler
13 public CMyUnknownImp 13 , ISequentialInStream
14{ 14)
15 CMyComPtr<ISequentialInStream> _stream; 15 CMyComPtr<ISequentialInStream> _stream;
16 UInt32 _adler; 16 UInt32 _adler;
17 UInt64 _size; 17 UInt64 _size;
18public: 18public:
19 MY_UNKNOWN_IMP
20 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
21 void SetStream(ISequentialInStream *stream) { _stream = stream; } 19 void SetStream(ISequentialInStream *stream) { _stream = stream; }
22 void ReleaseStream() { _stream.Release(); } 20 void ReleaseStream() { _stream.Release(); }
23 void Init() { _adler = 1; _size = 0; } // ADLER_INIT_VAL 21 void Init() { _adler = 1; _size = 0; } // ADLER_INIT_VAL
@@ -25,10 +23,10 @@ public:
25 UInt64 GetSize() const { return _size; } 23 UInt64 GetSize() const { return _size; }
26}; 24};
27 25
28class CEncoder: 26Z7_CLASS_IMP_NOQIB_1(
29 public ICompressCoder, 27 CEncoder
30 public CMyUnknownImp 28 , ICompressCoder
31{ 29)
32 CInStreamWithAdler *AdlerSpec; 30 CInStreamWithAdler *AdlerSpec;
33 CMyComPtr<ISequentialInStream> AdlerStream; 31 CMyComPtr<ISequentialInStream> AdlerStream;
34 CMyComPtr<ICompressCoder> DeflateEncoder; 32 CMyComPtr<ICompressCoder> DeflateEncoder;
@@ -36,11 +34,7 @@ public:
36 NCompress::NDeflate::NEncoder::CCOMCoder *DeflateEncoderSpec; 34 NCompress::NDeflate::NEncoder::CCOMCoder *DeflateEncoderSpec;
37 35
38 void Create(); 36 void Create();
39 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
40 const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
41 UInt64 GetInputProcessedSize() const { return AdlerSpec->GetSize(); } 37 UInt64 GetInputProcessedSize() const { return AdlerSpec->GetSize(); }
42
43 MY_UNKNOWN_IMP
44}; 38};
45 39
46}} 40}}
diff --git a/CPP/7zip/Crypto/7zAes.cpp b/CPP/7zip/Crypto/7zAes.cpp
index 7f34e91..6b1c648 100644
--- a/CPP/7zip/Crypto/7zAes.cpp
+++ b/CPP/7zip/Crypto/7zAes.cpp
@@ -8,7 +8,7 @@
8#include "../../Common/ComTry.h" 8#include "../../Common/ComTry.h"
9#include "../../Common/MyBuffer2.h" 9#include "../../Common/MyBuffer2.h"
10 10
11#ifndef _7ZIP_ST 11#ifndef Z7_ST
12#include "../../Windows/Synchronization.h" 12#include "../../Windows/Synchronization.h"
13#endif 13#endif
14 14
@@ -17,7 +17,7 @@
17#include "7zAes.h" 17#include "7zAes.h"
18#include "MyAes.h" 18#include "MyAes.h"
19 19
20#ifndef EXTRACT_ONLY 20#ifndef Z7_EXTRACT_ONLY
21#include "RandGen.h" 21#include "RandGen.h"
22#endif 22#endif
23 23
@@ -86,8 +86,8 @@ void CKeyInfo::CalcKey()
86 r += numUnroll; 86 r += numUnroll;
87 do 87 do
88 { 88 {
89 SetUi32(dest, i); i++; dest += bufSize; 89 SetUi32(dest, i) i++; dest += bufSize;
90 // SetUi32(dest, i); i++; dest += bufSize; 90 // SetUi32(dest, i) i++; dest += bufSize;
91 } 91 }
92 while (i < r); 92 while (i < r);
93 Sha256_Update((CSha256 *)(void *)(Byte *)sha, buf, unrollSize); 93 Sha256_Update((CSha256 *)(void *)(Byte *)sha, buf, unrollSize);
@@ -153,7 +153,7 @@ void CKeyInfoCache::Add(const CKeyInfo &key)
153 153
154static CKeyInfoCache g_GlobalKeyCache(32); 154static CKeyInfoCache g_GlobalKeyCache(32);
155 155
156#ifndef _7ZIP_ST 156#ifndef Z7_ST
157 static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; 157 static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection;
158 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); 158 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection);
159#else 159#else
@@ -185,10 +185,10 @@ void CBase::PrepareKey()
185 g_GlobalKeyCache.FindAndAdd(_key); 185 g_GlobalKeyCache.FindAndAdd(_key);
186} 186}
187 187
188#ifndef EXTRACT_ONLY 188#ifndef Z7_EXTRACT_ONLY
189 189
190/* 190/*
191STDMETHODIMP CEncoder::ResetSalt() 191Z7_COM7F_IMF(CEncoder::ResetSalt())
192{ 192{
193 _key.SaltSize = 4; 193 _key.SaltSize = 4;
194 g_RandomGenerator.Generate(_key.Salt, _key.SaltSize); 194 g_RandomGenerator.Generate(_key.Salt, _key.SaltSize);
@@ -196,7 +196,7 @@ STDMETHODIMP CEncoder::ResetSalt()
196} 196}
197*/ 197*/
198 198
199STDMETHODIMP CEncoder::ResetInitVector() 199Z7_COM7F_IMF(CEncoder::ResetInitVector())
200{ 200{
201 for (unsigned i = 0; i < sizeof(_iv); i++) 201 for (unsigned i = 0; i < sizeof(_iv); i++)
202 _iv[i] = 0; 202 _iv[i] = 0;
@@ -205,7 +205,7 @@ STDMETHODIMP CEncoder::ResetInitVector()
205 return S_OK; 205 return S_OK;
206} 206}
207 207
208STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) 208Z7_COM7F_IMF(CEncoder::WriteCoderProperties(ISequentialOutStream *outStream))
209{ 209{
210 Byte props[2 + sizeof(_key.Salt) + sizeof(_iv)]; 210 Byte props[2 + sizeof(_key.Salt) + sizeof(_iv)];
211 unsigned propsSize = 1; 211 unsigned propsSize = 1;
@@ -243,7 +243,7 @@ CDecoder::CDecoder()
243 _aesFilter = new CAesCbcDecoder(kKeySize); 243 _aesFilter = new CAesCbcDecoder(kKeySize);
244} 244}
245 245
246STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 246Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
247{ 247{
248 _key.ClearProps(); 248 _key.ClearProps();
249 249
@@ -282,7 +282,7 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)
282} 282}
283 283
284 284
285STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) 285Z7_COM7F_IMF(CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size))
286{ 286{
287 COM_TRY_BEGIN 287 COM_TRY_BEGIN
288 288
@@ -293,23 +293,23 @@ STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size)
293 COM_TRY_END 293 COM_TRY_END
294} 294}
295 295
296STDMETHODIMP CBaseCoder::Init() 296Z7_COM7F_IMF(CBaseCoder::Init())
297{ 297{
298 COM_TRY_BEGIN 298 COM_TRY_BEGIN
299 299
300 PrepareKey(); 300 PrepareKey();
301 CMyComPtr<ICryptoProperties> cp; 301 CMyComPtr<ICryptoProperties> cp;
302 RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); 302 RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp))
303 if (!cp) 303 if (!cp)
304 return E_FAIL; 304 return E_FAIL;
305 RINOK(cp->SetKey(_key.Key, kKeySize)); 305 RINOK(cp->SetKey(_key.Key, kKeySize))
306 RINOK(cp->SetInitVector(_iv, sizeof(_iv))); 306 RINOK(cp->SetInitVector(_iv, sizeof(_iv)))
307 return _aesFilter->Init(); 307 return _aesFilter->Init();
308 308
309 COM_TRY_END 309 COM_TRY_END
310} 310}
311 311
312STDMETHODIMP_(UInt32) CBaseCoder::Filter(Byte *data, UInt32 size) 312Z7_COM7F_IMF2(UInt32, CBaseCoder::Filter(Byte *data, UInt32 size))
313{ 313{
314 return _aesFilter->Filter(data, size); 314 return _aesFilter->Filter(data, size);
315} 315}
diff --git a/CPP/7zip/Crypto/7zAes.h b/CPP/7zip/Crypto/7zAes.h
index a67ac0b..8f7bf03 100644
--- a/CPP/7zip/Crypto/7zAes.h
+++ b/CPP/7zip/Crypto/7zAes.h
@@ -1,7 +1,7 @@
1// 7zAes.h 1// 7zAes.h
2 2
3#ifndef __CRYPTO_7Z_AES_H 3#ifndef ZIP7_INC_CRYPTO_7Z_AES_H
4#define __CRYPTO_7Z_AES_H 4#define ZIP7_INC_CRYPTO_7Z_AES_H
5 5
6#include "../../Common/MyBuffer.h" 6#include "../../Common/MyBuffer.h"
7#include "../../Common/MyCom.h" 7#include "../../Common/MyCom.h"
@@ -43,10 +43,13 @@ public:
43 Password.Wipe(); 43 Password.Wipe();
44 NumCyclesPower = 0; 44 NumCyclesPower = 0;
45 SaltSize = 0; 45 SaltSize = 0;
46 MY_memset_0_ARRAY(Salt); 46 Z7_memset_0_ARRAY(Salt);
47 MY_memset_0_ARRAY(Key); 47 Z7_memset_0_ARRAY(Key);
48 } 48 }
49 49
50#ifdef Z7_CPP_IS_SUPPORTED_default
51 CKeyInfo(const CKeyInfo &) = default;
52#endif
50 ~CKeyInfo() { Wipe(); } 53 ~CKeyInfo() { Wipe(); }
51}; 54};
52 55
@@ -79,48 +82,46 @@ class CBaseCoder:
79 public CMyUnknownImp, 82 public CMyUnknownImp,
80 public CBase 83 public CBase
81{ 84{
85 Z7_IFACE_COM7_IMP(ICompressFilter)
86 Z7_IFACE_COM7_IMP(ICryptoSetPassword)
82protected: 87protected:
88 virtual ~CBaseCoder() {}
83 CMyComPtr<ICompressFilter> _aesFilter; 89 CMyComPtr<ICompressFilter> _aesFilter;
84
85public:
86 INTERFACE_ICompressFilter(;)
87
88 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size);
89}; 90};
90 91
91#ifndef EXTRACT_ONLY 92#ifndef Z7_EXTRACT_ONLY
92 93
93class CEncoder: 94class CEncoder Z7_final:
94 public CBaseCoder, 95 public CBaseCoder,
95 public ICompressWriteCoderProperties, 96 public ICompressWriteCoderProperties,
96 // public ICryptoResetSalt, 97 // public ICryptoResetSalt,
97 public ICryptoResetInitVector 98 public ICryptoResetInitVector
98{ 99{
99public: 100 Z7_COM_UNKNOWN_IMP_4(
100 MY_UNKNOWN_IMP4(
101 ICompressFilter, 101 ICompressFilter,
102 ICryptoSetPassword, 102 ICryptoSetPassword,
103 ICompressWriteCoderProperties, 103 ICompressWriteCoderProperties,
104 // ICryptoResetSalt, 104 // ICryptoResetSalt,
105 ICryptoResetInitVector) 105 ICryptoResetInitVector)
106 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); 106 Z7_IFACE_COM7_IMP(ICompressWriteCoderProperties)
107 // STDMETHOD(ResetSalt)(); 107 // Z7_IFACE_COM7_IMP(ICryptoResetSalt)
108 STDMETHOD(ResetInitVector)(); 108 Z7_IFACE_COM7_IMP(ICryptoResetInitVector)
109public:
109 CEncoder(); 110 CEncoder();
110}; 111};
111 112
112#endif 113#endif
113 114
114class CDecoder: 115class CDecoder Z7_final:
115 public CBaseCoder, 116 public CBaseCoder,
116 public ICompressSetDecoderProperties2 117 public ICompressSetDecoderProperties2
117{ 118{
118public: 119 Z7_COM_UNKNOWN_IMP_3(
119 MY_UNKNOWN_IMP3(
120 ICompressFilter, 120 ICompressFilter,
121 ICryptoSetPassword, 121 ICryptoSetPassword,
122 ICompressSetDecoderProperties2) 122 ICompressSetDecoderProperties2)
123 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); 123 Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
124public:
124 CDecoder(); 125 CDecoder();
125}; 126};
126 127
diff --git a/CPP/7zip/Crypto/7zAesRegister.cpp b/CPP/7zip/Crypto/7zAesRegister.cpp
index 35605f4..69d0890 100644
--- a/CPP/7zip/Crypto/7zAesRegister.cpp
+++ b/CPP/7zip/Crypto/7zAesRegister.cpp
@@ -9,7 +9,7 @@
9namespace NCrypto { 9namespace NCrypto {
10namespace N7z { 10namespace N7z {
11 11
12REGISTER_FILTER_E(_7zAES, 12REGISTER_FILTER_E(SzAES,
13 CDecoder, 13 CDecoder,
14 CEncoder, 14 CEncoder,
15 0x6F10701, "7zAES") 15 0x6F10701, "7zAES")
diff --git a/CPP/7zip/Crypto/HmacSha1.cpp b/CPP/7zip/Crypto/HmacSha1.cpp
index d085bb0..30b1a8f 100644
--- a/CPP/7zip/Crypto/HmacSha1.cpp
+++ b/CPP/7zip/Crypto/HmacSha1.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include <string.h>
6
5#include "../../../C/CpuArch.h" 7#include "../../../C/CpuArch.h"
6 8
7#include "HmacSha1.h" 9#include "HmacSha1.h"
diff --git a/CPP/7zip/Crypto/HmacSha1.h b/CPP/7zip/Crypto/HmacSha1.h
index d4b21b3..a36c78e 100644
--- a/CPP/7zip/Crypto/HmacSha1.h
+++ b/CPP/7zip/Crypto/HmacSha1.h
@@ -1,8 +1,8 @@
1// HmacSha1.h 1// HmacSha1.h
2// Implements HMAC-SHA-1 (RFC2104, FIPS-198) 2// Implements HMAC-SHA-1 (RFC2104, FIPS-198)
3 3
4#ifndef __CRYPTO_HMAC_SHA1_H 4#ifndef ZIP7_INC_CRYPTO_HMAC_SHA1_H
5#define __CRYPTO_HMAC_SHA1_H 5#define ZIP7_INC_CRYPTO_HMAC_SHA1_H
6 6
7#include "Sha1Cls.h" 7#include "Sha1Cls.h"
8 8
diff --git a/CPP/7zip/Crypto/HmacSha256.cpp b/CPP/7zip/Crypto/HmacSha256.cpp
index cec5e75..56f8ede 100644
--- a/CPP/7zip/Crypto/HmacSha256.cpp
+++ b/CPP/7zip/Crypto/HmacSha256.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include <string.h>
6
5#include "../../../C/CpuArch.h" 7#include "../../../C/CpuArch.h"
6 8
7#include "HmacSha256.h" 9#include "HmacSha256.h"
diff --git a/CPP/7zip/Crypto/HmacSha256.h b/CPP/7zip/Crypto/HmacSha256.h
index d709f43..4039c0c 100644
--- a/CPP/7zip/Crypto/HmacSha256.h
+++ b/CPP/7zip/Crypto/HmacSha256.h
@@ -1,8 +1,8 @@
1// HmacSha256.h 1// HmacSha256.h
2// Implements HMAC-SHA-256 (RFC2104, FIPS-198) 2// Implements HMAC-SHA-256 (RFC2104, FIPS-198)
3 3
4#ifndef __CRYPTO_HMAC_SHA256_H 4#ifndef ZIP7_INC_CRYPTO_HMAC_SHA256_H
5#define __CRYPTO_HMAC_SHA256_H 5#define ZIP7_INC_CRYPTO_HMAC_SHA256_H
6 6
7#include "../../../C/Sha256.h" 7#include "../../../C/Sha256.h"
8 8
diff --git a/CPP/7zip/Crypto/MyAes.cpp b/CPP/7zip/Crypto/MyAes.cpp
index 5cb7f46..6abc388 100644
--- a/CPP/7zip/Crypto/MyAes.cpp
+++ b/CPP/7zip/Crypto/MyAes.cpp
@@ -10,11 +10,16 @@ namespace NCrypto {
10 10
11static struct CAesTabInit { CAesTabInit() { AesGenTables();} } g_AesTabInit; 11static struct CAesTabInit { CAesTabInit() { AesGenTables();} } g_AesTabInit;
12 12
13CAesCoder::CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode): 13CAesCoder::CAesCoder(
14 _keySize(keySize), 14 // bool encodeMode,
15 unsigned keySize
16 // , bool ctrMode
17 ):
15 _keyIsSet(false), 18 _keyIsSet(false),
16 _encodeMode(encodeMode), 19 // _encodeMode(encodeMode),
17 _ctrMode(ctrMode), 20 // _ctrMode(ctrMode),
21 _keySize(keySize),
22 // _ctrPos(0), // _ctrPos =0 will be set in Init()
18 _aes(AES_NUM_IVMRK_WORDS * 4 + AES_BLOCK_SIZE * 2) 23 _aes(AES_NUM_IVMRK_WORDS * 4 + AES_BLOCK_SIZE * 2)
19{ 24{
20 // _offset = ((0 - (unsigned)(ptrdiff_t)_aes) & 0xF) / sizeof(UInt32); 25 // _offset = ((0 - (unsigned)(ptrdiff_t)_aes) & 0xF) / sizeof(UInt32);
@@ -24,64 +29,128 @@ CAesCoder::CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode):
24 for (unsigned i = 0; i < 16; i++) _iv[i] = (Byte)(i + 1); 29 for (unsigned i = 0; i < 16; i++) _iv[i] = (Byte)(i + 1);
25 _iv[0] = 0xFE; _iv[1] = _iv[2] = _iv[3] = 0xFF; 30 _iv[0] = 0xFE; _iv[1] = _iv[2] = _iv[3] = 0xFF;
26 */ 31 */
27 SetFunctions(0);
28} 32}
29 33
30STDMETHODIMP CAesCoder::Init() 34Z7_COM7F_IMF(CAesCoder::Init())
31{ 35{
36 _ctrPos = 0;
32 AesCbc_Init(Aes(), _iv); 37 AesCbc_Init(Aes(), _iv);
33 return _keyIsSet ? S_OK : E_NOTIMPL; // E_FAIL 38 return _keyIsSet ? S_OK : E_NOTIMPL; // E_FAIL
34} 39}
35 40
36STDMETHODIMP_(UInt32) CAesCoder::Filter(Byte *data, UInt32 size) 41Z7_COM7F_IMF2(UInt32, CAesCoder::Filter(Byte *data, UInt32 size))
37{ 42{
38 if (!_keyIsSet) 43 if (!_keyIsSet)
39 return 0; 44 return 0;
40 if (size == 0)
41 return 0;
42 if (size < AES_BLOCK_SIZE) 45 if (size < AES_BLOCK_SIZE)
43 { 46 {
44 #ifndef _SFX 47 if (size == 0)
45 if (_ctrMode) 48 return 0;
46 {
47 // use that code only for last block !!!
48 Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS);
49 memset(ctr, 0, AES_BLOCK_SIZE);
50 memcpy(ctr, data, size);
51 _codeFunc(Aes(), ctr, 1);
52 memcpy(data, ctr, size);
53 return size;
54 }
55 #endif
56 return AES_BLOCK_SIZE; 49 return AES_BLOCK_SIZE;
57 } 50 }
58 size >>= 4; 51 size >>= 4;
52 // (data) must be aligned for 16-bytes here
59 _codeFunc(Aes(), data, size); 53 _codeFunc(Aes(), data, size);
60 return size << 4; 54 return size << 4;
61} 55}
62 56
63STDMETHODIMP CAesCoder::SetKey(const Byte *data, UInt32 size) 57
58Z7_COM7F_IMF(CAesCoder::SetKey(const Byte *data, UInt32 size))
64{ 59{
65 if ((size & 0x7) != 0 || size < 16 || size > 32) 60 if ((size & 0x7) != 0 || size < 16 || size > 32)
66 return E_INVALIDARG; 61 return E_INVALIDARG;
67 if (_keySize != 0 && size != _keySize) 62 if (_keySize != 0 && size != _keySize)
68 return E_INVALIDARG; 63 return E_INVALIDARG;
69 AES_SET_KEY_FUNC setKeyFunc = (_ctrMode | _encodeMode) ? Aes_SetKey_Enc : Aes_SetKey_Dec; 64 _setKeyFunc(Aes() + 4, data, size);
70 setKeyFunc(Aes() + 4, data, size);
71 _keyIsSet = true; 65 _keyIsSet = true;
72 return S_OK; 66 return S_OK;
73} 67}
74 68
75STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size) 69Z7_COM7F_IMF(CAesCoder::SetInitVector(const Byte *data, UInt32 size))
76{ 70{
77 if (size != AES_BLOCK_SIZE) 71 if (size != AES_BLOCK_SIZE)
78 return E_INVALIDARG; 72 return E_INVALIDARG;
79 memcpy(_iv, data, size); 73 memcpy(_iv, data, size);
74 /* we allow SetInitVector() call before SetKey() call.
75 so we ignore possible error in Init() here */
80 CAesCoder::Init(); // don't call virtual function here !!! 76 CAesCoder::Init(); // don't call virtual function here !!!
81 return S_OK; 77 return S_OK;
82} 78}
83 79
84#ifndef _SFX 80
81#ifndef Z7_SFX
82
83/*
84Z7_COM7F_IMF(CAesCtrCoder::Init())
85{
86 _ctrPos = 0;
87 return CAesCoder::Init();
88}
89*/
90
91Z7_COM7F_IMF2(UInt32, CAesCtrCoder::Filter(Byte *data, UInt32 size))
92{
93 if (!_keyIsSet)
94 return 0;
95 if (size == 0)
96 return 0;
97
98 if (_ctrPos != 0)
99 {
100 /* Optimized caller will not call here */
101 const Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS);
102 unsigned num = 0;
103 for (unsigned i = _ctrPos; i != AES_BLOCK_SIZE; i++)
104 {
105 if (num == size)
106 {
107 _ctrPos = i;
108 return num;
109 }
110 data[num++] ^= ctr[i];
111 }
112 _ctrPos = 0;
113 /* if (num < size) {
114 we can filter more data with _codeFunc().
115 But it's supposed that the caller can work correctly,
116 even if we do only partial filtering here.
117 So we filter data only for current 16-byte block. }
118 */
119 /*
120 size -= num;
121 size >>= 4;
122 // (data) must be aligned for 16-bytes here
123 _codeFunc(Aes(), data + num, size);
124 return num + (size << 4);
125 */
126 return num;
127 }
128
129 if (size < AES_BLOCK_SIZE)
130 {
131 /* The good optimized caller can call here only in last Filter() call.
132 But we support also non-optimized callers,
133 where another Filter() calls are allowed after this call.
134 */
135 Byte *ctr = (Byte *)(Aes() + AES_NUM_IVMRK_WORDS);
136 memset(ctr, 0, AES_BLOCK_SIZE);
137 memcpy(ctr, data, size);
138 _codeFunc(Aes(), ctr, 1);
139 memcpy(data, ctr, size);
140 _ctrPos = size;
141 return size;
142 }
143
144 size >>= 4;
145 // (data) must be aligned for 16-bytes here
146 _codeFunc(Aes(), data, size);
147 return size << 4;
148}
149
150#endif // Z7_SFX
151
152
153#ifndef Z7_EXTRACT_ONLY
85 154
86#ifdef MY_CPU_X86_OR_AMD64 155#ifdef MY_CPU_X86_OR_AMD64
87 #define USE_HW_AES 156 #define USE_HW_AES
@@ -101,93 +170,65 @@ STDMETHODIMP CAesCoder::SetInitVector(const Byte *data, UInt32 size)
101 #endif 170 #endif
102#endif 171#endif
103 172
173#ifdef USE_HW_AES
174 #define SET_AES_FUNC_2(f2) \
175 if (algo == 2) if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW) \
176 { f = f2; }
177 #ifdef MY_CPU_X86_OR_AMD64
178 #define SET_AES_FUNC_23(f2, f3) \
179 SET_AES_FUNC_2(f2) \
180 if (algo == 3) if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW_256) \
181 { f = f3; }
182 #else // MY_CPU_X86_OR_AMD64
183 #define SET_AES_FUNC_23(f2, f3) \
184 SET_AES_FUNC_2(f2)
185 #endif // MY_CPU_X86_OR_AMD64
186#else // USE_HW_AES
187 #define SET_AES_FUNC_23(f2, f3)
188#endif // USE_HW_AES
189
190#define SET_AES_FUNCS(c, f0, f1, f2, f3) \
191 bool c::SetFunctions(UInt32 algo) { \
192 _codeFunc = f0; if (algo < 1) return true; \
193 AES_CODE_FUNC f = NULL; \
194 if (algo == 1) { f = f1; } \
195 SET_AES_FUNC_23(f2, f3) \
196 if (f) { _codeFunc = f; return true; } \
197 return false; }
198
199
200
201#ifndef Z7_SFX
202SET_AES_FUNCS(
203 CAesCtrCoder,
204 g_AesCtr_Code,
205 AesCtr_Code,
206 AesCtr_Code_HW,
207 AesCtr_Code_HW_256)
104#endif 208#endif
105 209
106 210SET_AES_FUNCS(
107bool CAesCoder::SetFunctions(UInt32 211 CAesCbcEncoder,
108 #ifndef _SFX 212 g_AesCbc_Encode,
109 algo 213 AesCbc_Encode,
110 #endif 214 AesCbc_Encode_HW,
111 ) 215 AesCbc_Encode_HW)
112{ 216
113 _codeFunc = g_AesCbc_Decode; 217SET_AES_FUNCS(
114 218 CAesCbcDecoder,
115 #ifdef _SFX 219 g_AesCbc_Decode,
116 220 AesCbc_Decode,
117 return true; 221 AesCbc_Decode_HW,
118 222 AesCbc_Decode_HW_256)
119 #else 223
120 224Z7_COM7F_IMF(CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
121 if (_ctrMode)
122 _codeFunc = g_AesCtr_Code;
123 else if (_encodeMode)
124 _codeFunc = g_AesCbc_Encode;
125
126 if (algo < 1)
127 return true;
128
129 if (algo == 1)
130 {
131 _codeFunc = AesCbc_Decode;
132
133 #ifndef _SFX
134 if (_ctrMode)
135 _codeFunc = AesCtr_Code;
136 else if (_encodeMode)
137 _codeFunc = AesCbc_Encode;
138 #endif
139 return true;
140 }
141
142 #ifdef USE_HW_AES
143 // if (CPU_IsSupported_AES())
144 {
145 if (algo == 2)
146 if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW)
147 {
148 _codeFunc = AesCbc_Decode_HW;
149 #ifndef _SFX
150 if (_ctrMode)
151 _codeFunc = AesCtr_Code_HW;
152 else if (_encodeMode)
153 _codeFunc = AesCbc_Encode_HW;
154 #endif
155 return true;
156 }
157
158 #if defined(MY_CPU_X86_OR_AMD64)
159 if (algo == 3)
160 if (g_Aes_SupportedFunctions_Flags & k_Aes_SupportedFunctions_HW_256)
161 {
162 _codeFunc = AesCbc_Decode_HW_256;
163 #ifndef _SFX
164 if (_ctrMode)
165 _codeFunc = AesCtr_Code_HW_256;
166 else if (_encodeMode)
167 _codeFunc = AesCbc_Encode_HW;
168 #endif
169 return true;
170 }
171 #endif
172 }
173 #endif
174
175 return false;
176
177 #endif
178}
179
180
181#ifndef _SFX
182
183STDMETHODIMP CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)
184{ 225{
185 UInt32 algo = 0; 226 UInt32 algo = 0;
186 for (UInt32 i = 0; i < numProps; i++) 227 for (UInt32 i = 0; i < numProps; i++)
187 { 228 {
188 const PROPVARIANT &prop = coderProps[i];
189 if (propIDs[i] == NCoderPropID::kDefaultProp) 229 if (propIDs[i] == NCoderPropID::kDefaultProp)
190 { 230 {
231 const PROPVARIANT &prop = coderProps[i];
191 if (prop.vt != VT_UI4) 232 if (prop.vt != VT_UI4)
192 return E_INVALIDARG; 233 return E_INVALIDARG;
193 if (prop.ulVal > 3) 234 if (prop.ulVal > 3)
@@ -200,6 +241,6 @@ STDMETHODIMP CAesCoder::SetCoderProperties(const PROPID *propIDs, const PROPVARI
200 return S_OK; 241 return S_OK;
201} 242}
202 243
203#endif 244#endif // Z7_EXTRACT_ONLY
204 245
205} 246}
diff --git a/CPP/7zip/Crypto/MyAes.h b/CPP/7zip/Crypto/MyAes.h
index a60042b..a3c1c27 100644
--- a/CPP/7zip/Crypto/MyAes.h
+++ b/CPP/7zip/Crypto/MyAes.h
@@ -1,7 +1,7 @@
1// Crypto/MyAes.h 1// Crypto/MyAes.h
2 2
3#ifndef __CRYPTO_MY_AES_H 3#ifndef ZIP7_INC_CRYPTO_MY_AES_H
4#define __CRYPTO_MY_AES_H 4#define ZIP7_INC_CRYPTO_MY_AES_H
5 5
6#include "../../../C/Aes.h" 6#include "../../../C/Aes.h"
7 7
@@ -12,68 +12,111 @@
12 12
13namespace NCrypto { 13namespace NCrypto {
14 14
15#ifdef Z7_EXTRACT_ONLY
16#define Z7_IFACEN_IAesCoderSetFunctions(x)
17#else
18#define Z7_IFACEN_IAesCoderSetFunctions(x) \
19 virtual bool SetFunctions(UInt32 algo) x
20#endif
21
22
15class CAesCoder: 23class CAesCoder:
16 public ICompressFilter, 24 public ICompressFilter,
17 public ICryptoProperties, 25 public ICryptoProperties,
18 #ifndef _SFX 26 #ifndef Z7_EXTRACT_ONLY
19 public ICompressSetCoderProperties, 27 public ICompressSetCoderProperties,
20 #endif 28 #endif
21 public CMyUnknownImp 29 public CMyUnknownImp
22{ 30{
23 AES_CODE_FUNC _codeFunc; 31 Z7_COM_QI_BEGIN2(ICompressFilter)
32 Z7_COM_QI_ENTRY(ICryptoProperties)
33 #ifndef Z7_EXTRACT_ONLY
34 Z7_COM_QI_ENTRY(ICompressSetCoderProperties)
35 #endif
36 Z7_COM_QI_END
37 Z7_COM_ADDREF_RELEASE
38
39public:
40 Z7_IFACE_COM7_IMP_NONFINAL(ICompressFilter)
41 Z7_IFACE_COM7_IMP(ICryptoProperties)
42private:
43 #ifndef Z7_EXTRACT_ONLY
44 Z7_IFACE_COM7_IMP(ICompressSetCoderProperties)
45 #endif
46
47protected:
48 bool _keyIsSet;
49 // bool _encodeMode;
50 // bool _ctrMode;
24 // unsigned _offset; 51 // unsigned _offset;
25 unsigned _keySize; 52 unsigned _keySize;
26 bool _keyIsSet; 53 unsigned _ctrPos; // we need _ctrPos here for Init() / SetInitVector()
27 bool _encodeMode; 54 AES_CODE_FUNC _codeFunc;
28 bool _ctrMode; 55 AES_SET_KEY_FUNC _setKeyFunc;
29 56private:
30 // UInt32 _aes[AES_NUM_IVMRK_WORDS + 3]; 57 // UInt32 _aes[AES_NUM_IVMRK_WORDS + 3];
31 CAlignedBuffer _aes; 58 CAlignedBuffer1 _aes;
32 59
33 Byte _iv[AES_BLOCK_SIZE]; 60 Byte _iv[AES_BLOCK_SIZE];
34 61
35 // UInt32 *Aes() { return _aes + _offset; } 62 // UInt32 *Aes() { return _aes + _offset; }
63protected:
36 UInt32 *Aes() { return (UInt32 *)(void *)(Byte *)_aes; } 64 UInt32 *Aes() { return (UInt32 *)(void *)(Byte *)_aes; }
37 65
38 bool SetFunctions(UInt32 algo); 66 Z7_IFACE_PURE(IAesCoderSetFunctions)
39 67
40public: 68public:
41 CAesCoder(bool encodeMode, unsigned keySize, bool ctrMode); 69 CAesCoder(
42 70 // bool encodeMode,
43 virtual ~CAesCoder() {}; // we need virtual destructor for derived classes 71 unsigned keySize
44 72 // , bool ctrMode
45 MY_QUERYINTERFACE_BEGIN2(ICompressFilter) 73 );
46 MY_QUERYINTERFACE_ENTRY(ICryptoProperties) 74 virtual ~CAesCoder() {} // we need virtual destructor for derived classes
47 #ifndef _SFX
48 MY_QUERYINTERFACE_ENTRY(ICompressSetCoderProperties)
49 #endif
50 MY_QUERYINTERFACE_END
51 MY_ADDREF_RELEASE
52
53 INTERFACE_ICompressFilter(;)
54
55 void SetKeySize(unsigned size) { _keySize = size; } 75 void SetKeySize(unsigned size) { _keySize = size; }
56
57 STDMETHOD(SetKey)(const Byte *data, UInt32 size);
58 STDMETHOD(SetInitVector)(const Byte *data, UInt32 size);
59
60 #ifndef _SFX
61 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
62 #endif
63}; 76};
64 77
65#ifndef _SFX 78
79#ifndef Z7_EXTRACT_ONLY
66struct CAesCbcEncoder: public CAesCoder 80struct CAesCbcEncoder: public CAesCoder
67{ 81{
68 CAesCbcEncoder(unsigned keySize = 0): CAesCoder(true, keySize, false) {} 82 CAesCbcEncoder(unsigned keySize = 0): CAesCoder(keySize)
83 {
84 _setKeyFunc = Aes_SetKey_Enc;
85 _codeFunc = g_AesCbc_Encode;
86 }
87 Z7_IFACE_IMP(IAesCoderSetFunctions)
69}; 88};
70#endif 89#endif
71 90
72struct CAesCbcDecoder: public CAesCoder 91struct CAesCbcDecoder: public CAesCoder
73{ 92{
74 CAesCbcDecoder(unsigned keySize = 0): CAesCoder(false, keySize, false) {} 93 CAesCbcDecoder(unsigned keySize = 0): CAesCoder(keySize)
94 {
95 _setKeyFunc = Aes_SetKey_Dec;
96 _codeFunc = g_AesCbc_Decode;
97 }
98 Z7_IFACE_IMP(IAesCoderSetFunctions)
75}; 99};
76 100
101#ifndef Z7_SFX
102struct CAesCtrCoder: public CAesCoder
103{
104private:
105 // unsigned _ctrPos;
106 // Z7_IFACE_COM7_IMP(ICompressFilter)
107 // Z7_COM7F_IMP(Init())
108 Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size))
109public:
110 CAesCtrCoder(unsigned keySize = 0): CAesCoder(keySize)
111 {
112 _ctrPos = 0;
113 _setKeyFunc = Aes_SetKey_Enc;
114 _codeFunc = g_AesCtr_Code;
115 }
116 Z7_IFACE_IMP(IAesCoderSetFunctions)
117};
118#endif
119
77} 120}
78 121
79#endif 122#endif
diff --git a/CPP/7zip/Crypto/MyAesReg.cpp b/CPP/7zip/Crypto/MyAesReg.cpp
index 86bd254..e2b4f72 100644
--- a/CPP/7zip/Crypto/MyAesReg.cpp
+++ b/CPP/7zip/Crypto/MyAesReg.cpp
@@ -8,22 +8,21 @@
8 8
9namespace NCrypto { 9namespace NCrypto {
10 10
11#ifndef _SFX 11#ifndef Z7_SFX
12 12
13#define REGISTER_AES_2(name, nameString, keySize, isCtr) \ 13#define REGISTER_AES_2(name, nameString, keySize) \
14 REGISTER_FILTER_E(name, \ 14 REGISTER_FILTER_E(name, \
15 CAesCoder(false, keySize, isCtr), \ 15 CAesCbcDecoder(keySize), \
16 CAesCoder(true , keySize, isCtr), \ 16 CAesCbcEncoder(keySize), \
17 0x6F00100 | ((keySize - 16) * 8) | (isCtr ? 4 : 1), \ 17 0x6F00100 | ((keySize - 16) * 8) | (/* isCtr */ 0 ? 4 : 1), \
18 nameString) \ 18 nameString) \
19 19
20#define REGISTER_AES(name, nameString, isCtr) \ 20#define REGISTER_AES(name, nameString) \
21 /* REGISTER_AES_2(AES128 ## name, "AES128" nameString, 16, isCtr) */ \ 21 /* REGISTER_AES_2(AES128 ## name, "AES128" nameString, 16) */ \
22 /* REGISTER_AES_2(AES192 ## name, "AES192" nameString, 24, isCtr) */ \ 22 /* REGISTER_AES_2(AES192 ## name, "AES192" nameString, 24) */ \
23 REGISTER_AES_2(AES256 ## name, "AES256" nameString, 32, isCtr) \ 23 REGISTER_AES_2(AES256 ## name, "AES256" nameString, 32) \
24 24
25REGISTER_AES(CBC, "CBC", false) 25REGISTER_AES(CBC, "CBC")
26// REGISTER_AES(CTR, "CTR", true)
27 26
28#endif 27#endif
29 28
diff --git a/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp b/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp
index 6b504ee..3d9e4c1 100644
--- a/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp
+++ b/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include <string.h>
6
5#include "../../../C/CpuArch.h" 7#include "../../../C/CpuArch.h"
6 8
7#include "HmacSha1.h" 9#include "HmacSha1.h"
@@ -28,7 +30,7 @@ void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize,
28 30
29 MY_ALIGN (16) 31 MY_ALIGN (16)
30 UInt32 u[kNumDigestWords]; 32 UInt32 u[kNumDigestWords];
31 SetBe32(u, i); 33 SetBe32(u, i)
32 34
33 ctx.Update((const Byte *)u, 4); 35 ctx.Update((const Byte *)u, 4);
34 ctx.Final((Byte *)u); 36 ctx.Final((Byte *)u);
@@ -36,7 +38,7 @@ void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize,
36 ctx = baseCtx; 38 ctx = baseCtx;
37 ctx.GetLoopXorDigest1((void *)u, numIterations - 1); 39 ctx.GetLoopXorDigest1((void *)u, numIterations - 1);
38 40
39 const unsigned curSize = (keySize < kDigestSize) ? (unsigned)keySize : kDigestSize;; 41 const unsigned curSize = (keySize < kDigestSize) ? (unsigned)keySize : kDigestSize;
40 memcpy(key, (const Byte *)u, curSize); 42 memcpy(key, (const Byte *)u, curSize);
41 key += curSize; 43 key += curSize;
42 keySize -= curSize; 44 keySize -= curSize;
diff --git a/CPP/7zip/Crypto/Pbkdf2HmacSha1.h b/CPP/7zip/Crypto/Pbkdf2HmacSha1.h
index e9462e4..89cbe41 100644
--- a/CPP/7zip/Crypto/Pbkdf2HmacSha1.h
+++ b/CPP/7zip/Crypto/Pbkdf2HmacSha1.h
@@ -1,8 +1,8 @@
1// Pbkdf2HmacSha1.h 1// Pbkdf2HmacSha1.h
2// Password-Based Key Derivation Function (RFC 2898, PKCS #5) based on HMAC-SHA-1 2// Password-Based Key Derivation Function (RFC 2898, PKCS #5) based on HMAC-SHA-1
3 3
4#ifndef __CRYPTO_PBKDF2_HMAC_SHA1_H 4#ifndef ZIP7_INC_CRYPTO_PBKDF2_HMAC_SHA1_H
5#define __CRYPTO_PBKDF2_HMAC_SHA1_H 5#define ZIP7_INC_CRYPTO_PBKDF2_HMAC_SHA1_H
6 6
7#include <stddef.h> 7#include <stddef.h>
8 8
diff --git a/CPP/7zip/Crypto/RandGen.cpp b/CPP/7zip/Crypto/RandGen.cpp
index 65633fd..05a6c06 100644
--- a/CPP/7zip/Crypto/RandGen.cpp
+++ b/CPP/7zip/Crypto/RandGen.cpp
@@ -6,7 +6,7 @@
6 6
7#ifndef USE_STATIC_SYSTEM_RAND 7#ifndef USE_STATIC_SYSTEM_RAND
8 8
9#ifndef _7ZIP_ST 9#ifndef Z7_ST
10#include "../../Windows/Synchronization.h" 10#include "../../Windows/Synchronization.h"
11#endif 11#endif
12 12
@@ -76,9 +76,9 @@ void CRandomGenerator::Init()
76 #ifdef _WIN32 76 #ifdef _WIN32
77 77
78 DWORD w = ::GetCurrentProcessId(); 78 DWORD w = ::GetCurrentProcessId();
79 HASH_UPD(w); 79 HASH_UPD(w)
80 w = ::GetCurrentThreadId(); 80 w = ::GetCurrentThreadId();
81 HASH_UPD(w); 81 HASH_UPD(w)
82 82
83 #ifdef UNDER_CE 83 #ifdef UNDER_CE
84 /* 84 /*
@@ -96,11 +96,14 @@ void CRandomGenerator::Init()
96 } 96 }
97 #else 97 #else
98 { 98 {
99 HMODULE hModule = ::LoadLibrary(TEXT("Advapi32.dll")); 99 const HMODULE hModule = ::LoadLibrary(TEXT("advapi32.dll"));
100 if (hModule) 100 if (hModule)
101 { 101 {
102 // SystemFunction036() is real name of RtlGenRandom() function 102 // SystemFunction036() is real name of RtlGenRandom() function
103 Func_RtlGenRandom my_RtlGenRandom = (Func_RtlGenRandom)(void *)GetProcAddress(hModule, "SystemFunction036"); 103 const
104 Func_RtlGenRandom
105 my_RtlGenRandom = Z7_GET_PROC_ADDRESS(
106 Func_RtlGenRandom, hModule, "SystemFunction036");
104 if (my_RtlGenRandom) 107 if (my_RtlGenRandom)
105 { 108 {
106 if (my_RtlGenRandom(buf, kBufSize)) 109 if (my_RtlGenRandom(buf, kBufSize))
@@ -117,9 +120,9 @@ void CRandomGenerator::Init()
117 #else 120 #else
118 121
119 pid_t pid = getpid(); 122 pid_t pid = getpid();
120 HASH_UPD(pid); 123 HASH_UPD(pid)
121 pid = getppid(); 124 pid = getppid();
122 HASH_UPD(pid); 125 HASH_UPD(pid)
123 126
124 { 127 {
125 int f = open("/dev/urandom", O_RDONLY); 128 int f = open("/dev/urandom", O_RDONLY);
@@ -164,25 +167,25 @@ void CRandomGenerator::Init()
164 #ifdef _WIN32 167 #ifdef _WIN32
165 LARGE_INTEGER v; 168 LARGE_INTEGER v;
166 if (::QueryPerformanceCounter(&v)) 169 if (::QueryPerformanceCounter(&v))
167 HASH_UPD(v.QuadPart); 170 HASH_UPD(v.QuadPart)
168 #endif 171 #endif
169 172
170 #ifdef USE_POSIX_TIME 173 #ifdef USE_POSIX_TIME
171 #ifdef USE_POSIX_TIME2 174 #ifdef USE_POSIX_TIME2
172 timeval v; 175 timeval v;
173 if (gettimeofday(&v, 0) == 0) 176 if (gettimeofday(&v, NULL) == 0)
174 { 177 {
175 HASH_UPD(v.tv_sec); 178 HASH_UPD(v.tv_sec)
176 HASH_UPD(v.tv_usec); 179 HASH_UPD(v.tv_usec)
177 } 180 }
178 #endif 181 #endif
179 time_t v2 = time(NULL); 182 const time_t v2 = time(NULL);
180 HASH_UPD(v2); 183 HASH_UPD(v2)
181 #endif 184 #endif
182 185
183 #ifdef _WIN32 186 #ifdef _WIN32
184 DWORD tickCount = ::GetTickCount(); 187 const DWORD tickCount = ::GetTickCount();
185 HASH_UPD(tickCount); 188 HASH_UPD(tickCount)
186 #endif 189 #endif
187 190
188 for (unsigned j = 0; j < 100; j++) 191 for (unsigned j = 0; j < 100; j++)
@@ -198,7 +201,7 @@ void CRandomGenerator::Init()
198 _needInit = false; 201 _needInit = false;
199} 202}
200 203
201#ifndef _7ZIP_ST 204#ifndef Z7_ST
202 static NWindows::NSynchronization::CCriticalSection g_CriticalSection; 205 static NWindows::NSynchronization::CCriticalSection g_CriticalSection;
203 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 206 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
204#else 207#else
@@ -222,7 +225,7 @@ void CRandomGenerator::Generate(Byte *data, unsigned size)
222 225
223 Sha256_Init(&hash); 226 Sha256_Init(&hash);
224 UInt32 salt = 0xF672ABD1; 227 UInt32 salt = 0xF672ABD1;
225 HASH_UPD(salt); 228 HASH_UPD(salt)
226 Sha256_Update(&hash, _buff, SHA256_DIGEST_SIZE); 229 Sha256_Update(&hash, _buff, SHA256_DIGEST_SIZE);
227 MY_ALIGN (16) 230 MY_ALIGN (16)
228 Byte buff[SHA256_DIGEST_SIZE]; 231 Byte buff[SHA256_DIGEST_SIZE];
@@ -232,6 +235,7 @@ void CRandomGenerator::Generate(Byte *data, unsigned size)
232 } 235 }
233} 236}
234 237
238MY_ALIGN (16)
235CRandomGenerator g_RandomGenerator; 239CRandomGenerator g_RandomGenerator;
236 240
237#endif 241#endif
diff --git a/CPP/7zip/Crypto/RandGen.h b/CPP/7zip/Crypto/RandGen.h
index 5122ec4..3bd69ec 100644
--- a/CPP/7zip/Crypto/RandGen.h
+++ b/CPP/7zip/Crypto/RandGen.h
@@ -1,7 +1,7 @@
1// RandGen.h 1// RandGen.h
2 2
3#ifndef __CRYPTO_RAND_GEN_H 3#ifndef ZIP7_INC_CRYPTO_RAND_GEN_H
4#define __CRYPTO_RAND_GEN_H 4#define ZIP7_INC_CRYPTO_RAND_GEN_H
5 5
6#include "../../../C/Sha256.h" 6#include "../../../C/Sha256.h"
7 7
@@ -27,10 +27,11 @@ class CRandomGenerator
27 27
28 void Init(); 28 void Init();
29public: 29public:
30 CRandomGenerator(): _needInit(true) {}; 30 CRandomGenerator(): _needInit(true) {}
31 void Generate(Byte *data, unsigned size); 31 void Generate(Byte *data, unsigned size);
32}; 32};
33 33
34MY_ALIGN (16)
34extern CRandomGenerator g_RandomGenerator; 35extern CRandomGenerator g_RandomGenerator;
35 36
36#define MY_RAND_GEN(data, size) g_RandomGenerator.Generate(data, size) 37#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 2bbaa93..8e55763 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)
54 Keys[3] = 0xA4E7F123L; 54 Keys[3] = 0xA4E7F123L;
55 55
56 Byte psw[128]; 56 Byte psw[128];
57 MY_memset_0_ARRAY(psw); 57 Z7_memset_0_ARRAY(psw);
58 if (size != 0) 58 if (size != 0)
59 { 59 {
60 if (size >= sizeof(psw)) 60 if (size >= sizeof(psw))
@@ -99,22 +99,22 @@ void CData::CryptBlock(Byte *buf, bool encrypt)
99 B = D; D = TB; 99 B = D; D = TB;
100 } 100 }
101 101
102 SetUi32(buf + 0, C ^ Keys[0]); 102 SetUi32(buf + 0, C ^ Keys[0])
103 SetUi32(buf + 4, D ^ Keys[1]); 103 SetUi32(buf + 4, D ^ Keys[1])
104 SetUi32(buf + 8, A ^ Keys[2]); 104 SetUi32(buf + 8, A ^ Keys[2])
105 SetUi32(buf + 12, B ^ Keys[3]); 105 SetUi32(buf + 12, B ^ Keys[3])
106 106
107 UpdateKeys(encrypt ? buf : inBuf); 107 UpdateKeys(encrypt ? buf : inBuf);
108} 108}
109 109
110STDMETHODIMP CDecoder::Init() 110Z7_COM7F_IMF(CDecoder::Init())
111{ 111{
112 return S_OK; 112 return S_OK;
113} 113}
114 114
115static const UInt32 kBlockSize = 16; 115static const UInt32 kBlockSize = 16;
116 116
117STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) 117Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
118{ 118{
119 if (size == 0) 119 if (size == 0)
120 return 0; 120 return 0;
diff --git a/CPP/7zip/Crypto/Rar20Crypto.h b/CPP/7zip/Crypto/Rar20Crypto.h
index 596619c..8550718 100644
--- a/CPP/7zip/Crypto/Rar20Crypto.h
+++ b/CPP/7zip/Crypto/Rar20Crypto.h
@@ -1,7 +1,7 @@
1// Crypto/Rar20Crypto.h 1// Crypto/Rar20Crypto.h
2 2
3#ifndef __CRYPTO_RAR20_CRYPTO_H 3#ifndef ZIP7_INC_CRYPTO_RAR20_CRYPTO_H
4#define __CRYPTO_RAR20_CRYPTO_H 4#define ZIP7_INC_CRYPTO_RAR20_CRYPTO_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -31,8 +31,8 @@ public:
31 ~CData() { Wipe(); } 31 ~CData() { Wipe(); }
32 void Wipe() 32 void Wipe()
33 { 33 {
34 MY_memset_0_ARRAY(SubstTable); 34 Z7_memset_0_ARRAY(SubstTable);
35 MY_memset_0_ARRAY(Keys); 35 Z7_memset_0_ARRAY(Keys);
36 } 36 }
37 37
38 void EncryptBlock(Byte *buf) { CryptBlock(buf, true); } 38 void EncryptBlock(Byte *buf) { CryptBlock(buf, true); }
@@ -40,14 +40,13 @@ public:
40 void SetPassword(const Byte *password, unsigned passwordLen); 40 void SetPassword(const Byte *password, unsigned passwordLen);
41}; 41};
42 42
43class CDecoder: 43class CDecoder Z7_final:
44 public ICompressFilter, 44 public ICompressFilter,
45 public CMyUnknownImp, 45 public CMyUnknownImp,
46 public CData 46 public CData
47{ 47{
48public: 48 Z7_COM_UNKNOWN_IMP_0
49 MY_UNKNOWN_IMP 49 Z7_IFACE_COM7_IMP(ICompressFilter)
50 INTERFACE_ICompressFilter(;)
51}; 50};
52 51
53}} 52}}
diff --git a/CPP/7zip/Crypto/Rar5Aes.cpp b/CPP/7zip/Crypto/Rar5Aes.cpp
index 5834bbb..26c6100 100644
--- a/CPP/7zip/Crypto/Rar5Aes.cpp
+++ b/CPP/7zip/Crypto/Rar5Aes.cpp
@@ -4,7 +4,7 @@
4 4
5#include "../../../C/CpuArch.h" 5#include "../../../C/CpuArch.h"
6 6
7#ifndef _7ZIP_ST 7#ifndef Z7_ST
8#include "../../Windows/Synchronization.h" 8#include "../../Windows/Synchronization.h"
9#endif 9#endif
10 10
@@ -129,11 +129,11 @@ void CDecoder::SetPassword(const Byte *data, size_t size)
129} 129}
130 130
131 131
132STDMETHODIMP CDecoder::Init() 132Z7_COM7F_IMF(CDecoder::Init())
133{ 133{
134 CalcKey_and_CheckPassword(); 134 CalcKey_and_CheckPassword();
135 RINOK(SetKey(_key, kAesKeySize)); 135 RINOK(SetKey(_key, kAesKeySize))
136 RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)); 136 RINOK(SetInitVector(_iv, AES_BLOCK_SIZE))
137 return CAesCoder::Init(); 137 return CAesCoder::Init();
138} 138}
139 139
@@ -144,7 +144,7 @@ UInt32 CDecoder::Hmac_Convert_Crc32(UInt32 crc) const
144 NSha256::CHmac ctx; 144 NSha256::CHmac ctx;
145 ctx.SetKey(_hashKey, NSha256::kDigestSize); 145 ctx.SetKey(_hashKey, NSha256::kDigestSize);
146 UInt32 v; 146 UInt32 v;
147 SetUi32(&v, crc); 147 SetUi32(&v, crc)
148 ctx.Update((const Byte *)&v, 4); 148 ctx.Update((const Byte *)&v, 4);
149 MY_ALIGN (16) 149 MY_ALIGN (16)
150 UInt32 h[SHA256_NUM_DIGEST_WORDS]; 150 UInt32 h[SHA256_NUM_DIGEST_WORDS];
@@ -153,7 +153,7 @@ UInt32 CDecoder::Hmac_Convert_Crc32(UInt32 crc) const
153 for (unsigned i = 0; i < SHA256_NUM_DIGEST_WORDS; i++) 153 for (unsigned i = 0; i < SHA256_NUM_DIGEST_WORDS; i++)
154 crc ^= (UInt32)GetUi32(h + i); 154 crc ^= (UInt32)GetUi32(h + i);
155 return crc; 155 return crc;
156}; 156}
157 157
158 158
159void CDecoder::Hmac_Convert_32Bytes(Byte *data) const 159void CDecoder::Hmac_Convert_32Bytes(Byte *data) const
@@ -163,12 +163,12 @@ void CDecoder::Hmac_Convert_32Bytes(Byte *data) const
163 ctx.SetKey(_hashKey, NSha256::kDigestSize); 163 ctx.SetKey(_hashKey, NSha256::kDigestSize);
164 ctx.Update(data, NSha256::kDigestSize); 164 ctx.Update(data, NSha256::kDigestSize);
165 ctx.Final(data); 165 ctx.Final(data);
166}; 166}
167 167
168 168
169static CKey g_Key; 169static CKey g_Key;
170 170
171#ifndef _7ZIP_ST 171#ifndef Z7_ST
172 static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; 172 static NWindows::NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection;
173 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); 173 #define MT_LOCK NWindows::NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection);
174#else 174#else
diff --git a/CPP/7zip/Crypto/Rar5Aes.h b/CPP/7zip/Crypto/Rar5Aes.h
index e779c17..3cd7992 100644
--- a/CPP/7zip/Crypto/Rar5Aes.h
+++ b/CPP/7zip/Crypto/Rar5Aes.h
@@ -1,7 +1,7 @@
1// Crypto/Rar5Aes.h 1// Crypto/Rar5Aes.h
2 2
3#ifndef __CRYPTO_RAR5_AES_H 3#ifndef ZIP7_INC_CRYPTO_RAR5_AES_H
4#define __CRYPTO_RAR5_AES_H 4#define ZIP7_INC_CRYPTO_RAR5_AES_H
5 5
6#include "../../../C/Sha256.h" 6#include "../../../C/Sha256.h"
7 7
@@ -53,17 +53,21 @@ struct CKey
53 void Wipe() 53 void Wipe()
54 { 54 {
55 _password.Wipe(); 55 _password.Wipe();
56 MY_memset_0_ARRAY(_salt); 56 Z7_memset_0_ARRAY(_salt);
57 MY_memset_0_ARRAY(_key); 57 Z7_memset_0_ARRAY(_key);
58 MY_memset_0_ARRAY(_check_Calced); 58 Z7_memset_0_ARRAY(_check_Calced);
59 MY_memset_0_ARRAY(_hashKey); 59 Z7_memset_0_ARRAY(_hashKey);
60 } 60 }
61 61
62#ifdef Z7_CPP_IS_SUPPORTED_default
63 // CKey(const CKey &) = default;
64 CKey& operator =(const CKey &) = default;
65#endif
62 ~CKey() { Wipe(); } 66 ~CKey() { Wipe(); }
63}; 67};
64 68
65 69
66class CDecoder: 70class CDecoder Z7_final:
67 public CAesCbcDecoder, 71 public CAesCbcDecoder,
68 public CKey 72 public CKey
69{ 73{
@@ -77,7 +81,7 @@ public:
77 81
78 CDecoder(); 82 CDecoder();
79 83
80 STDMETHOD(Init)(); 84 Z7_COM7F_IMP(Init())
81 85
82 void SetPassword(const Byte *data, size_t size); 86 void SetPassword(const Byte *data, size_t size);
83 HRESULT SetDecoderProps(const Byte *data, unsigned size, bool includeIV, bool isService); 87 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 aa9444c..878ea3a 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)
78 _password.CopyFrom(data, (size_t)size); 78 _password.CopyFrom(data, (size_t)size);
79} 79}
80 80
81STDMETHODIMP CDecoder::Init() 81Z7_COM7F_IMF(CDecoder::Init())
82{ 82{
83 CalcKey(); 83 CalcKey();
84 RINOK(SetKey(_key, kAesKeySize)); 84 RINOK(SetKey(_key, kAesKeySize))
85 RINOK(SetInitVector(_iv, AES_BLOCK_SIZE)); 85 RINOK(SetInitVector(_iv, AES_BLOCK_SIZE))
86 return CAesCoder::Init(); 86 return CAesCoder::Init();
87} 87}
88 88
@@ -116,7 +116,7 @@ static void UpdatePswDataSha1(Byte *data)
116 116
117 for (i = 0; i < SHA1_NUM_BLOCK_WORDS; i++) 117 for (i = 0; i < SHA1_NUM_BLOCK_WORDS; i++)
118 { 118 {
119 SetUi32(data + i * 4, W[kNumW - SHA1_NUM_BLOCK_WORDS + i]); 119 SetUi32(data + i * 4, W[kNumW - SHA1_NUM_BLOCK_WORDS + i])
120 } 120 }
121} 121}
122 122
diff --git a/CPP/7zip/Crypto/RarAes.h b/CPP/7zip/Crypto/RarAes.h
index 2bb6866..d3c104c 100644
--- a/CPP/7zip/Crypto/RarAes.h
+++ b/CPP/7zip/Crypto/RarAes.h
@@ -1,7 +1,7 @@
1// Crypto/RarAes.h 1// Crypto/RarAes.h
2 2
3#ifndef __CRYPTO_RAR_AES_H 3#ifndef ZIP7_INC_CRYPTO_RAR_AES_H
4#define __CRYPTO_RAR_AES_H 4#define ZIP7_INC_CRYPTO_RAR_AES_H
5 5
6#include "../../../C/Aes.h" 6#include "../../../C/Aes.h"
7 7
@@ -16,10 +16,8 @@ namespace NRar3 {
16 16
17const unsigned kAesKeySize = 16; 17const unsigned kAesKeySize = 16;
18 18
19class CDecoder: 19class CDecoder Z7_final:
20 public CAesCbcDecoder 20 public CAesCbcDecoder
21 // public ICompressSetDecoderProperties2,
22 // public ICryptoSetPassword
23{ 21{
24 Byte _salt[8]; 22 Byte _salt[8];
25 bool _thereIsSalt; 23 bool _thereIsSalt;
@@ -33,25 +31,20 @@ class CDecoder:
33 31
34 void CalcKey(); 32 void CalcKey();
35public: 33public:
36 /* 34 Z7_COM7F_IMP(Init())
37 MY_UNKNOWN_IMP1(
38 ICryptoSetPassword
39 // ICompressSetDecoderProperties2
40 */
41 STDMETHOD(Init)();
42 35
43 void SetPassword(const Byte *data, unsigned size); 36 void SetPassword(const Byte *data, unsigned size);
44 HRESULT SetDecoderProperties2(const Byte *data, UInt32 size); 37 HRESULT SetDecoderProperties2(const Byte *data, UInt32 size);
45 38
46 CDecoder(); 39 CDecoder();
47 40
48 ~CDecoder() { Wipe(); } 41 ~CDecoder() Z7_DESTRUCTOR_override { Wipe(); }
49 void Wipe() 42 void Wipe()
50 { 43 {
51 _password.Wipe(); 44 _password.Wipe();
52 MY_memset_0_ARRAY(_salt); 45 Z7_memset_0_ARRAY(_salt);
53 MY_memset_0_ARRAY(_key); 46 Z7_memset_0_ARRAY(_key);
54 MY_memset_0_ARRAY(_iv); 47 Z7_memset_0_ARRAY(_iv);
55 } 48 }
56 // void SetRar350Mode(bool rar350Mode) { _rar350Mode = rar350Mode; } 49 // void SetRar350Mode(bool rar350Mode) { _rar350Mode = rar350Mode; }
57}; 50};
diff --git a/CPP/7zip/Crypto/Sha1Cls.h b/CPP/7zip/Crypto/Sha1Cls.h
index 3461678..56ae040 100644
--- a/CPP/7zip/Crypto/Sha1Cls.h
+++ b/CPP/7zip/Crypto/Sha1Cls.h
@@ -1,7 +1,7 @@
1// Crypto/Sha1Cls.h 1// Crypto/Sha1Cls.h
2 2
3#ifndef __CRYPTO_SHA1_CLS_H 3#ifndef ZIP7_INC_CRYPTO_SHA1_CLS_H
4#define __CRYPTO_SHA1_CLS_H 4#define ZIP7_INC_CRYPTO_SHA1_CLS_H
5 5
6#include "../../../C/Sha1.h" 6#include "../../../C/Sha1.h"
7 7
diff --git a/CPP/7zip/Crypto/StdAfx.h b/CPP/7zip/Crypto/StdAfx.h
index 1cbd7fe..8086655 100644
--- a/CPP/7zip/Crypto/StdAfx.h
+++ b/CPP/7zip/Crypto/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../Common/Common.h" 9#include "../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/Crypto/WzAes.cpp b/CPP/7zip/Crypto/WzAes.cpp
index b422b50..3f2adab 100644
--- a/CPP/7zip/Crypto/WzAes.cpp
+++ b/CPP/7zip/Crypto/WzAes.cpp
@@ -23,7 +23,7 @@ const unsigned kAesKeySizeMax = 32;
23 23
24static const UInt32 kNumKeyGenIterations = 1000; 24static const UInt32 kNumKeyGenIterations = 1000;
25 25
26STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) 26Z7_COM7F_IMF(CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size))
27{ 27{
28 if (size > kPasswordSizeMax) 28 if (size > kPasswordSizeMax)
29 return E_INVALIDARG; 29 return E_INVALIDARG;
@@ -34,6 +34,7 @@ STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size)
34 34
35void CBaseCoder::Init2() 35void CBaseCoder::Init2()
36{ 36{
37 _hmacOverCalc = 0;
37 const unsigned dkSizeMax32 = (2 * kAesKeySizeMax + kPwdVerifSize + 3) / 4; 38 const unsigned dkSizeMax32 = (2 * kAesKeySizeMax + kPwdVerifSize + 3) / 4;
38 Byte dk[dkSizeMax32 * 4]; 39 Byte dk[dkSizeMax32 * 4];
39 40
@@ -59,7 +60,7 @@ void CBaseCoder::Init2()
59 if (_aesCoderSpec->Init() != S_OK) throw 3; 60 if (_aesCoderSpec->Init() != S_OK) throw 3;
60} 61}
61 62
62STDMETHODIMP CBaseCoder::Init() 63Z7_COM7F_IMF(CBaseCoder::Init())
63{ 64{
64 return S_OK; 65 return S_OK;
65} 66}
@@ -69,7 +70,7 @@ HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream)
69 unsigned saltSize = _key.GetSaltSize(); 70 unsigned saltSize = _key.GetSaltSize();
70 MY_RAND_GEN(_key.Salt, saltSize); 71 MY_RAND_GEN(_key.Salt, saltSize);
71 Init2(); 72 Init2();
72 RINOK(WriteStream(outStream, _key.Salt, saltSize)); 73 RINOK(WriteStream(outStream, _key.Salt, saltSize))
73 return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifSize); 74 return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifSize);
74} 75}
75 76
@@ -82,7 +83,7 @@ HRESULT CEncoder::WriteFooter(ISequentialOutStream *outStream)
82} 83}
83 84
84/* 85/*
85STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) 86Z7_COM7F_IMF(CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size))
86{ 87{
87 if (size != 1) 88 if (size != 1)
88 return E_INVALIDARG; 89 return E_INVALIDARG;
@@ -93,10 +94,10 @@ STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)
93 94
94HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) 95HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream)
95{ 96{
96 unsigned saltSize = _key.GetSaltSize(); 97 const unsigned saltSize = _key.GetSaltSize();
97 unsigned extraSize = saltSize + kPwdVerifSize; 98 const unsigned extraSize = saltSize + kPwdVerifSize;
98 Byte temp[kSaltSizeMax + kPwdVerifSize]; 99 Byte temp[kSaltSizeMax + kPwdVerifSize];
99 RINOK(ReadStream_FAIL(inStream, temp, extraSize)); 100 RINOK(ReadStream_FAIL(inStream, temp, extraSize))
100 unsigned i; 101 unsigned i;
101 for (i = 0; i < saltSize; i++) 102 for (i = 0; i < saltSize; i++)
102 _key.Salt[i] = temp[i]; 103 _key.Salt[i] = temp[i];
@@ -124,11 +125,13 @@ HRESULT CDecoder::CheckMac(ISequentialInStream *inStream, bool &isOK)
124 isOK = false; 125 isOK = false;
125 MY_ALIGN (16) 126 MY_ALIGN (16)
126 Byte mac1[kMacSize]; 127 Byte mac1[kMacSize];
127 RINOK(ReadStream_FAIL(inStream, mac1, kMacSize)); 128 RINOK(ReadStream_FAIL(inStream, mac1, kMacSize))
128 MY_ALIGN (16) 129 MY_ALIGN (16)
129 UInt32 mac2[NSha1::kNumDigestWords]; 130 UInt32 mac2[NSha1::kNumDigestWords];
130 Hmac()->Final((Byte *)mac2); 131 Hmac()->Final((Byte *)mac2);
131 isOK = CompareArrays(mac1, (const Byte *)mac2, kMacSize); 132 isOK = CompareArrays(mac1, (const Byte *)mac2, kMacSize);
133 if (_hmacOverCalc)
134 isOK = false;
132 return S_OK; 135 return S_OK;
133} 136}
134 137
@@ -202,7 +205,7 @@ void AesCtr2_Code(CAesCtr2 *p, Byte *data, SizeT size)
202 205
203/* (size != 16 * N) is allowed only for last Filter() call */ 206/* (size != 16 * N) is allowed only for last Filter() call */
204 207
205STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) 208Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size))
206{ 209{
207 // AesCtr2_Code(&_aes, data, size); 210 // AesCtr2_Code(&_aes, data, size);
208 size = _aesCoder->Filter(data, size); 211 size = _aesCoder->Filter(data, size);
@@ -210,14 +213,18 @@ STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size)
210 return size; 213 return size;
211} 214}
212 215
213STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) 216Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
214{ 217{
215 if (size >= 16) 218 if (size >= 16)
216 size &= ~(UInt32)15; 219 size &= ~(UInt32)15;
217 220 if (_hmacOverCalc < size)
218 Hmac()->Update(data, size); 221 {
222 Hmac()->Update(data + _hmacOverCalc, size - _hmacOverCalc);
223 _hmacOverCalc = size;
224 }
219 // AesCtr2_Code(&_aes, data, size); 225 // AesCtr2_Code(&_aes, data, size);
220 size = _aesCoder->Filter(data, size); 226 size = _aesCoder->Filter(data, size);
227 _hmacOverCalc -= size;
221 return size; 228 return size;
222} 229}
223 230
diff --git a/CPP/7zip/Crypto/WzAes.h b/CPP/7zip/Crypto/WzAes.h
index fa6221c..113ec81 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":
9 - 2 bytes contain Password Verifier's Code 9 - 2 bytes contain Password Verifier's Code
10*/ 10*/
11 11
12#ifndef __CRYPTO_WZ_AES_H 12#ifndef ZIP7_INC_CRYPTO_WZ_AES_H
13#define __CRYPTO_WZ_AES_H 13#define ZIP7_INC_CRYPTO_WZ_AES_H
14 14
15#include "../../Common/MyBuffer.h" 15#include "../../Common/MyBuffer.h"
16 16
@@ -65,8 +65,8 @@ struct CKeyInfo
65 void Wipe() 65 void Wipe()
66 { 66 {
67 Password.Wipe(); 67 Password.Wipe();
68 MY_memset_0_ARRAY(Salt); 68 Z7_memset_0_ARRAY(Salt);
69 MY_memset_0_ARRAY(PwdVerifComputed); 69 Z7_memset_0_ARRAY(PwdVerifComputed);
70 } 70 }
71 71
72 ~CKeyInfo() { Wipe(); } 72 ~CKeyInfo() { Wipe(); }
@@ -94,12 +94,18 @@ class CBaseCoder:
94 public ICryptoSetPassword, 94 public ICryptoSetPassword,
95 public CMyUnknownImp 95 public CMyUnknownImp
96{ 96{
97 Z7_COM_UNKNOWN_IMP_1(ICryptoSetPassword)
98 Z7_COM7F_IMP(Init())
99public:
100 Z7_IFACE_COM7_IMP(ICryptoSetPassword)
97protected: 101protected:
98 CKeyInfo _key; 102 CKeyInfo _key;
99 103
100 // NSha1::CHmac _hmac; 104 // NSha1::CHmac _hmac;
101 // NSha1::CHmac *Hmac() { return &_hmac; } 105 // NSha1::CHmac *Hmac() { return &_hmac; }
102 CAlignedBuffer _hmacBuf; 106 CAlignedBuffer1 _hmacBuf;
107 UInt32 _hmacOverCalc;
108
103 NSha1::CHmac *Hmac() { return (NSha1::CHmac *)(void *)(Byte *)_hmacBuf; } 109 NSha1::CHmac *Hmac() { return (NSha1::CHmac *)(void *)(Byte *)_hmacBuf; }
104 110
105 // CAesCtr2 _aes; 111 // CAesCtr2 _aes;
@@ -108,18 +114,12 @@ protected:
108 CBaseCoder(): 114 CBaseCoder():
109 _hmacBuf(sizeof(NSha1::CHmac)) 115 _hmacBuf(sizeof(NSha1::CHmac))
110 { 116 {
111 _aesCoderSpec = new CAesCoder(true, 32, true); 117 _aesCoderSpec = new CAesCtrCoder(32);
112 _aesCoder = _aesCoderSpec; 118 _aesCoder = _aesCoderSpec;
113 } 119 }
114 120
115 void Init2(); 121 void Init2();
116public: 122public:
117 MY_UNKNOWN_IMP1(ICryptoSetPassword)
118
119 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size);
120
121 STDMETHOD(Init)();
122
123 unsigned GetHeaderSize() const { return _key.GetSaltSize() + kPwdVerifSize; } 123 unsigned GetHeaderSize() const { return _key.GetSaltSize() + kPwdVerifSize; }
124 unsigned GetAddPackSize() const { return GetHeaderSize() + kMacSize; } 124 unsigned GetAddPackSize() const { return GetHeaderSize() + kMacSize; }
125 125
@@ -134,24 +134,23 @@ public:
134 virtual ~CBaseCoder() {} 134 virtual ~CBaseCoder() {}
135}; 135};
136 136
137class CEncoder: 137class CEncoder Z7_final:
138 public CBaseCoder 138 public CBaseCoder
139{ 139{
140 Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size))
140public: 141public:
141 STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size);
142 HRESULT WriteHeader(ISequentialOutStream *outStream); 142 HRESULT WriteHeader(ISequentialOutStream *outStream);
143 HRESULT WriteFooter(ISequentialOutStream *outStream); 143 HRESULT WriteFooter(ISequentialOutStream *outStream);
144}; 144};
145 145
146class CDecoder: 146class CDecoder Z7_final:
147 public CBaseCoder 147 public CBaseCoder
148 // public ICompressSetDecoderProperties2 148 // public ICompressSetDecoderProperties2
149{ 149{
150 Byte _pwdVerifFromArchive[kPwdVerifSize]; 150 Byte _pwdVerifFromArchive[kPwdVerifSize];
151 Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size))
151public: 152public:
152 // ICompressSetDecoderProperties2 153 // Z7_IFACE_COM7_IMP(ICompressSetDecoderProperties2)
153 // STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
154 STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size);
155 HRESULT ReadHeader(ISequentialInStream *inStream); 154 HRESULT ReadHeader(ISequentialInStream *inStream);
156 bool Init_and_CheckPassword(); 155 bool Init_and_CheckPassword();
157 HRESULT CheckMac(ISequentialInStream *inStream, bool &isOK); 156 HRESULT CheckMac(ISequentialInStream *inStream, bool &isOK);
diff --git a/CPP/7zip/Crypto/ZipCrypto.cpp b/CPP/7zip/Crypto/ZipCrypto.cpp
index 8610297..047e2bd 100644
--- a/CPP/7zip/Crypto/ZipCrypto.cpp
+++ b/CPP/7zip/Crypto/ZipCrypto.cpp
@@ -20,14 +20,14 @@ namespace NZip {
20#define DECRYPT_BYTE_1 UInt32 temp = key2 | 2; 20#define DECRYPT_BYTE_1 UInt32 temp = key2 | 2;
21#define DECRYPT_BYTE_2 ((Byte)((temp * (temp ^ 1)) >> 8)) 21#define DECRYPT_BYTE_2 ((Byte)((temp * (temp ^ 1)) >> 8))
22 22
23STDMETHODIMP CCipher::CryptoSetPassword(const Byte *data, UInt32 size) 23Z7_COM7F_IMF(CCipher::CryptoSetPassword(const Byte *data, UInt32 size))
24{ 24{
25 UInt32 key0 = 0x12345678; 25 UInt32 key0 = 0x12345678;
26 UInt32 key1 = 0x23456789; 26 UInt32 key1 = 0x23456789;
27 UInt32 key2 = 0x34567890; 27 UInt32 key2 = 0x34567890;
28 28
29 for (UInt32 i = 0; i < size; i++) 29 for (UInt32 i = 0; i < size; i++)
30 UPDATE_KEYS(data[i]); 30 UPDATE_KEYS(data[i])
31 31
32 KeyMem0 = key0; 32 KeyMem0 = key0;
33 KeyMem1 = key1; 33 KeyMem1 = key1;
@@ -36,7 +36,7 @@ STDMETHODIMP CCipher::CryptoSetPassword(const Byte *data, UInt32 size)
36 return S_OK; 36 return S_OK;
37} 37}
38 38
39STDMETHODIMP CCipher::Init() 39Z7_COM7F_IMF(CCipher::Init())
40{ 40{
41 return S_OK; 41 return S_OK;
42} 42}
@@ -58,7 +58,7 @@ HRESULT CEncoder::WriteHeader_Check16(ISequentialOutStream *outStream, UInt16 cr
58 return WriteStream(outStream, h, kHeaderSize); 58 return WriteStream(outStream, h, kHeaderSize);
59} 59}
60 60
61STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) 61Z7_COM7F_IMF2(UInt32, CEncoder::Filter(Byte *data, UInt32 size))
62{ 62{
63 UInt32 key0 = this->Key0; 63 UInt32 key0 = this->Key0;
64 UInt32 key1 = this->Key1; 64 UInt32 key1 = this->Key1;
@@ -69,7 +69,7 @@ STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size)
69 Byte b = data[i]; 69 Byte b = data[i];
70 DECRYPT_BYTE_1 70 DECRYPT_BYTE_1
71 data[i] = (Byte)(b ^ DECRYPT_BYTE_2); 71 data[i] = (Byte)(b ^ DECRYPT_BYTE_2);
72 UPDATE_KEYS(b); 72 UPDATE_KEYS(b)
73 } 73 }
74 74
75 this->Key0 = key0; 75 this->Key0 = key0;
@@ -90,7 +90,7 @@ void CDecoder::Init_BeforeDecode()
90 Filter(_header, kHeaderSize); 90 Filter(_header, kHeaderSize);
91} 91}
92 92
93STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) 93Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
94{ 94{
95 UInt32 key0 = this->Key0; 95 UInt32 key0 = this->Key0;
96 UInt32 key1 = this->Key1; 96 UInt32 key1 = this->Key1;
@@ -100,7 +100,7 @@ STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size)
100 { 100 {
101 DECRYPT_BYTE_1 101 DECRYPT_BYTE_1
102 Byte b = (Byte)(data[i] ^ DECRYPT_BYTE_2); 102 Byte b = (Byte)(data[i] ^ DECRYPT_BYTE_2);
103 UPDATE_KEYS(b); 103 UPDATE_KEYS(b)
104 data[i] = b; 104 data[i] = b;
105 } 105 }
106 106
diff --git a/CPP/7zip/Crypto/ZipCrypto.h b/CPP/7zip/Crypto/ZipCrypto.h
index d2fe4c4..485470e 100644
--- a/CPP/7zip/Crypto/ZipCrypto.h
+++ b/CPP/7zip/Crypto/ZipCrypto.h
@@ -1,7 +1,7 @@
1// Crypto/ZipCrypto.h 1// Crypto/ZipCrypto.h
2 2
3#ifndef __CRYPTO_ZIP_CRYPTO_H 3#ifndef ZIP7_INC_CRYPTO_ZIP_CRYPTO_H
4#define __CRYPTO_ZIP_CRYPTO_H 4#define ZIP7_INC_CRYPTO_ZIP_CRYPTO_H
5 5
6#include "../../Common/MyCom.h" 6#include "../../Common/MyCom.h"
7 7
@@ -30,6 +30,10 @@ class CCipher:
30 public ICryptoSetPassword, 30 public ICryptoSetPassword,
31 public CMyUnknownImp 31 public CMyUnknownImp
32{ 32{
33 Z7_COM_UNKNOWN_IMP_1(ICryptoSetPassword)
34 Z7_COM7F_IMP(Init())
35public:
36 Z7_IFACE_COM7_IMP(ICryptoSetPassword)
33protected: 37protected:
34 UInt32 Key0; 38 UInt32 Key0;
35 UInt32 Key1; 39 UInt32 Key1;
@@ -47,10 +51,6 @@ protected:
47 } 51 }
48 52
49public: 53public:
50 MY_UNKNOWN_IMP1(ICryptoSetPassword)
51 STDMETHOD(Init)();
52 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size);
53
54 virtual ~CCipher() 54 virtual ~CCipher()
55 { 55 {
56 Key0 = KeyMem0 = 56 Key0 = KeyMem0 =
@@ -59,18 +59,18 @@ public:
59 } 59 }
60}; 60};
61 61
62class CEncoder: public CCipher 62class CEncoder Z7_final: public CCipher
63{ 63{
64 Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size))
64public: 65public:
65 STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size);
66 HRESULT WriteHeader_Check16(ISequentialOutStream *outStream, UInt16 crc); 66 HRESULT WriteHeader_Check16(ISequentialOutStream *outStream, UInt16 crc);
67}; 67};
68 68
69class CDecoder: public CCipher 69class CDecoder Z7_final: public CCipher
70{ 70{
71 Z7_COM7F_IMP2(UInt32, Filter(Byte *data, UInt32 size))
71public: 72public:
72 Byte _header[kHeaderSize]; 73 Byte _header[kHeaderSize];
73 STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size);
74 HRESULT ReadHeader(ISequentialInStream *inStream); 74 HRESULT ReadHeader(ISequentialInStream *inStream);
75 void Init_BeforeDecode(); 75 void Init_BeforeDecode();
76}; 76};
diff --git a/CPP/7zip/Crypto/ZipStrong.cpp b/CPP/7zip/Crypto/ZipStrong.cpp
index 895ce94..59698d8 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)
59 DeriveKey(sha, MasterKey); 59 DeriveKey(sha, MasterKey);
60} 60}
61 61
62STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) 62
63
64CDecoder::CDecoder()
65{
66 CAesCbcDecoder *d = new CAesCbcDecoder();
67 _cbcDecoder = d;
68 _aesFilter = d;
69}
70
71Z7_COM7F_IMF(CDecoder::CryptoSetPassword(const Byte *data, UInt32 size))
63{ 72{
64 _key.SetPassword(data, size); 73 _key.SetPassword(data, size);
65 return S_OK; 74 return S_OK;
66} 75}
67 76
68STDMETHODIMP CBaseCoder::Init() 77Z7_COM7F_IMF(CDecoder::Init())
69{ 78{
70 return S_OK; 79 return S_OK;
71} 80}
72 81
82Z7_COM7F_IMF2(UInt32, CDecoder::Filter(Byte *data, UInt32 size))
83{
84 return _aesFilter->Filter(data, size);
85}
86
87
73HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize) 88HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize)
74{ 89{
75 Byte temp[4]; 90 Byte temp[4];
76 RINOK(ReadStream_FALSE(inStream, temp, 2)); 91 RINOK(ReadStream_FALSE(inStream, temp, 2))
77 _ivSize = GetUi16(temp); 92 _ivSize = GetUi16(temp);
78 if (_ivSize == 0) 93 if (_ivSize == 0)
79 { 94 {
80 memset(_iv, 0, 16); 95 memset(_iv, 0, 16);
81 SetUi32(_iv + 0, crc); 96 SetUi32(_iv + 0, crc)
82 SetUi64(_iv + 4, unpackSize); 97 SetUi64(_iv + 4, unpackSize)
83 _ivSize = 12; 98 _ivSize = 12;
84 } 99 }
85 else if (_ivSize == 16) 100 else if (_ivSize == 16)
86 { 101 {
87 RINOK(ReadStream_FALSE(inStream, _iv, _ivSize)); 102 RINOK(ReadStream_FALSE(inStream, _iv, _ivSize))
88 } 103 }
89 else 104 else
90 return E_NOTIMPL; 105 return E_NOTIMPL;
91 RINOK(ReadStream_FALSE(inStream, temp, 4)); 106 RINOK(ReadStream_FALSE(inStream, temp, 4))
92 _remSize = GetUi32(temp); 107 _remSize = GetUi32(temp);
93 // const UInt32 kAlign = 16; 108 // const UInt32 kAlign = 16;
94 if (_remSize < 16 || _remSize > (1 << 18)) 109 if (_remSize < 16 || _remSize > (1 << 18))
@@ -208,9 +223,10 @@ HRESULT CDecoder::Init_and_CheckPassword(bool &passwOK)
208 return E_NOTIMPL; 223 return E_NOTIMPL;
209 224
210 { 225 {
211 RINOK(SetKey(_key.MasterKey, _key.KeySize)); 226 RINOK(_cbcDecoder->SetKey(_key.MasterKey, _key.KeySize))
212 RINOK(SetInitVector(_iv, 16)); 227 RINOK(_cbcDecoder->SetInitVector(_iv, 16))
213 RINOK(Init()); 228 // SetInitVector() calls also Init()
229 RINOK(_cbcDecoder->Init()) // it's optional
214 Filter(p, rdSize); 230 Filter(p, rdSize);
215 231
216 rdSize -= kPadSize; 232 rdSize -= kPadSize;
@@ -228,9 +244,10 @@ HRESULT CDecoder::Init_and_CheckPassword(bool &passwOK)
228 sha.Update(p, rdSize); 244 sha.Update(p, rdSize);
229 DeriveKey(sha, fileKey); 245 DeriveKey(sha, fileKey);
230 246
231 RINOK(SetKey(fileKey, _key.KeySize)); 247 RINOK(_cbcDecoder->SetKey(fileKey, _key.KeySize))
232 RINOK(SetInitVector(_iv, 16)); 248 RINOK(_cbcDecoder->SetInitVector(_iv, 16))
233 Init(); 249 // SetInitVector() calls also Init()
250 RINOK(_cbcDecoder->Init()) // it's optional
234 251
235 memmove(p, p + validOffset, validSize); 252 memmove(p, p + validOffset, validSize);
236 Filter(p, validSize); 253 Filter(p, validSize);
diff --git a/CPP/7zip/Crypto/ZipStrong.h b/CPP/7zip/Crypto/ZipStrong.h
index 2b58a5c..a2b5cdd 100644
--- a/CPP/7zip/Crypto/ZipStrong.h
+++ b/CPP/7zip/Crypto/ZipStrong.h
@@ -1,7 +1,7 @@
1// Crypto/ZipStrong.h 1// Crypto/ZipStrong.h
2 2
3#ifndef __CRYPTO_ZIP_STRONG_H 3#ifndef ZIP7_INC_CRYPTO_ZIP_STRONG_H
4#define __CRYPTO_ZIP_STRONG_H 4#define ZIP7_INC_CRYPTO_ZIP_STRONG_H
5 5
6#include "../../Common/MyBuffer2.h" 6#include "../../Common/MyBuffer2.h"
7 7
@@ -28,34 +28,29 @@ struct CKeyInfo
28 28
29 void SetPassword(const Byte *data, UInt32 size); 29 void SetPassword(const Byte *data, UInt32 size);
30 30
31 ~CKeyInfo() { Wipe(); }
32 void Wipe() 31 void Wipe()
33 { 32 {
34 MY_memset_0_ARRAY(MasterKey); 33 Z7_memset_0_ARRAY(MasterKey);
35 } 34 }
36}; 35};
37 36
38class CBaseCoder:
39 public CAesCbcDecoder,
40 public ICryptoSetPassword
41{
42protected:
43 CKeyInfo _key;
44 CAlignedBuffer _bufAligned;
45public:
46 STDMETHOD(Init)();
47 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size);
48};
49 37
50const unsigned kAesPadAllign = AES_BLOCK_SIZE; 38const unsigned kAesPadAllign = AES_BLOCK_SIZE;
51 39
52class CDecoder: public CBaseCoder 40Z7_CLASS_IMP_COM_2(
53{ 41 CDecoder
42 , ICompressFilter
43 , ICryptoSetPassword
44)
45 CAesCbcDecoder *_cbcDecoder;
46 CMyComPtr<ICompressFilter> _aesFilter;
47 CKeyInfo _key;
48 CAlignedBuffer _bufAligned;
49
54 UInt32 _ivSize; 50 UInt32 _ivSize;
55 Byte _iv[16]; 51 Byte _iv[16];
56 UInt32 _remSize; 52 UInt32 _remSize;
57public: 53public:
58 MY_UNKNOWN_IMP1(ICryptoSetPassword)
59 HRESULT ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize); 54 HRESULT ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize);
60 HRESULT Init_and_CheckPassword(bool &passwOK); 55 HRESULT Init_and_CheckPassword(bool &passwOK);
61 UInt32 GetPadSize(UInt32 packSize32) const 56 UInt32 GetPadSize(UInt32 packSize32) const
@@ -64,11 +59,12 @@ public:
64 // Change it, if is not AES 59 // Change it, if is not AES
65 return kAesPadAllign - (packSize32 & (kAesPadAllign - 1)); 60 return kAesPadAllign - (packSize32 & (kAesPadAllign - 1));
66 } 61 }
67 62 CDecoder();
68 ~CDecoder() { Wipe(); } 63 ~CDecoder() { Wipe(); }
69 void Wipe() 64 void Wipe()
70 { 65 {
71 MY_memset_0_ARRAY(_iv); 66 Z7_memset_0_ARRAY(_iv);
67 _key.Wipe();
72 } 68 }
73}; 69};
74 70
diff --git a/CPP/7zip/Guid.txt b/CPP/7zip/Guid.txt
index 8fcdd84..eee28f7 100644
--- a/CPP/7zip/Guid.txt
+++ b/CPP/7zip/Guid.txt
@@ -31,12 +31,15 @@
31 02 ISequentialOutStream 31 02 ISequentialOutStream
32 03 IInStream 32 03 IInStream
33 04 IOutStream 33 04 IOutStream
34
34 06 IStreamGetSize 35 06 IStreamGetSize
35 07 IOutStreamFinish 36 07 IOutStreamFinish
36 08 IStreamGetProps 37 08 IStreamGetProps
37 09 IStreamGetProps2 38 09 IStreamGetProps2
38 0A IStreamGetProp 39 0A IStreamGetProp
39 40
41 10 IStreamSetRestriction
42
40 43
4104 ICoder.h 4404 ICoder.h
42 45
@@ -94,7 +97,8 @@
94 10 IArchiveOpenCallback 97 10 IArchiveOpenCallback
95 98
96 20 IArchiveExtractCallback 99 20 IArchiveExtractCallback
97 21 IArchiveExtractCallbackMessage 100 21 IArchiveExtractCallbackMessage (deprecated in v23)
101 22 IArchiveExtractCallbackMessage2 (new in v23)
98 102
99 30 IArchiveOpenVolumeCallback 103 30 IArchiveOpenVolumeCallback
100 40 IInArchiveGetStream 104 40 IInArchiveGetStream
diff --git a/CPP/7zip/ICoder.h b/CPP/7zip/ICoder.h
index 9177f5e..aec2834 100644
--- a/CPP/7zip/ICoder.h
+++ b/CPP/7zip/ICoder.h
@@ -1,39 +1,40 @@
1// ICoder.h 1// ICoder.h
2 2
3#ifndef __ICODER_H 3#ifndef ZIP7_INC_ICODER_H
4#define __ICODER_H 4#define ZIP7_INC_ICODER_H
5 5
6#include "IStream.h" 6#include "IStream.h"
7 7
8#define CODER_INTERFACE(i, x) DECL_INTERFACE(i, 4, x) 8Z7_PURE_INTERFACES_BEGIN
9 9
10CODER_INTERFACE(ICompressProgressInfo, 0x04) 10#define Z7_IFACE_CONSTR_CODER(i, n) \
11{ 11 Z7_DECL_IFACE_7ZIP(i, 4, n) \
12 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize) PURE; 12 { Z7_IFACE_COM7_PURE(i) };
13
14 /* (inSize) can be NULL, if unknown
15 (outSize) can be NULL, if unknown
16 13
14#define Z7_IFACEM_ICompressProgressInfo(x) \
15 x(SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
16Z7_IFACE_CONSTR_CODER(ICompressProgressInfo, 0x04)
17 /*
18 SetRatioInfo()
19 (inSize) can be NULL, if unknown
20 (outSize) can be NULL, if unknown
17 returns: 21 returns:
18 S_OK 22 S_OK
19 E_ABORT : Break by user 23 E_ABORT : Break by user
20 another error codes 24 another error codes
21 */ 25 */
22};
23 26
24CODER_INTERFACE(ICompressCoder, 0x05) 27#define Z7_IFACEM_ICompressCoder(x) \
25{ 28 x(Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, \
26 STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, 29 const UInt64 *inSize, const UInt64 *outSize, \
27 const UInt64 *inSize, const UInt64 *outSize, 30 ICompressProgressInfo *progress))
28 ICompressProgressInfo *progress) PURE; 31Z7_IFACE_CONSTR_CODER(ICompressCoder, 0x05)
29};
30 32
31CODER_INTERFACE(ICompressCoder2, 0x18) 33#define Z7_IFACEM_ICompressCoder2(x) \
32{ 34 x(Code(ISequentialInStream * const *inStreams, const UInt64 *const *inSizes, UInt32 numInStreams, \
33 STDMETHOD(Code)(ISequentialInStream * const *inStreams, const UInt64 * const *inSizes, UInt32 numInStreams, 35 ISequentialOutStream *const *outStreams, const UInt64 *const *outSizes, UInt32 numOutStreams, \
34 ISequentialOutStream * const *outStreams, const UInt64 * const *outSizes, UInt32 numOutStreams, 36 ICompressProgressInfo *progress))
35 ICompressProgressInfo *progress) PURE; 37Z7_IFACE_CONSTR_CODER(ICompressCoder2, 0x18)
36};
37 38
38/* 39/*
39 ICompressCoder::Code 40 ICompressCoder::Code
@@ -54,7 +55,7 @@ CODER_INTERFACE(ICompressCoder2, 0x18)
54 { 55 {
55 Encoders in 7-Zip ignore (inSize). 56 Encoders in 7-Zip ignore (inSize).
56 Decoder can use (*inSize) to check that stream was decoded correctly. 57 Decoder can use (*inSize) to check that stream was decoded correctly.
57 Some decoder in 7-Zip check it, if (full_decoding mode was set via ICompressSetFinishMode) 58 Some decoders in 7-Zip check it, if (full_decoding mode was set via ICompressSetFinishMode)
58 } 59 }
59 60
60 If it's required to limit the reading from input stream (inStream), it can 61 If it's required to limit the reading from input stream (inStream), it can
@@ -132,71 +133,91 @@ namespace NCoderPropID
132 kCheckSize, // VT_UI4 : size of digest in bytes 133 kCheckSize, // VT_UI4 : size of digest in bytes
133 kFilter, // VT_BSTR 134 kFilter, // VT_BSTR
134 kMemUse, // VT_UI8 135 kMemUse, // VT_UI8
135 kAffinity // VT_UI8 136 kAffinity, // VT_UI8
137 kBranchOffset, // VT_UI4
138 kHashBits, // VT_UI4
139 /*
140 // kHash3Bits, // VT_UI4
141 // kHash2Bits, // VT_UI4
142 // kChainBits, // VT_UI4
143 kChainSize, // VT_UI4
144 kNativeLevel, // VT_UI4
145 kFast, // VT_UI4
146 kMinMatch, // VT_UI4 The minimum slen is 3 and the maximum is 7.
147 kOverlapLog, // VT_UI4 The minimum ovlog is 0 and the maximum is 9. (default: 6)
148 kRowMatchFinder, // VT_BOOL
149 kLdmEnable, // VT_BOOL
150 // kLdmWindowSizeLog, // VT_UI4
151 kLdmWindowSize, // VT_UI4
152 kLdmHashLog, // VT_UI4 The minimum ldmhlog is 6 and the maximum is 26 (default: 20).
153 kLdmMinMatchLength, // VT_UI4 The minimum ldmslen is 4 and the maximum is 4096 (default: 64).
154 kLdmBucketSizeLog, // VT_UI4 The minimum ldmblog is 0 and the maximum is 8 (default: 3).
155 kLdmHashRateLog, // VT_UI4 The default value is wlog - ldmhlog.
156 kWriteUnpackSizeFlag, // VT_BOOL
157 kUsePledged, // VT_BOOL
158 kUseSizeHintPledgedForSmall, // VT_BOOL
159 kUseSizeHintForEach, // VT_BOOL
160 kUseSizeHintGlobal, // VT_BOOL
161 kParamSelectMode, // VT_UI4
162 // kSearchLog, // VT_UI4 The minimum slog is 1 and the maximum is 26
163 // kTargetLen, // VT_UI4 The minimum tlen is 0 and the maximum is 999.
164 */
165 k_NUM_DEFINED
136 }; 166 };
137} 167}
138 168
139CODER_INTERFACE(ICompressSetCoderPropertiesOpt, 0x1F) 169#define Z7_IFACEM_ICompressSetCoderPropertiesOpt(x) \
140{ 170 x(SetCoderPropertiesOpt(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
141 STDMETHOD(SetCoderPropertiesOpt)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) PURE; 171Z7_IFACE_CONSTR_CODER(ICompressSetCoderPropertiesOpt, 0x1F)
142};
143 172
144CODER_INTERFACE(ICompressSetCoderProperties, 0x20) 173
145{ 174#define Z7_IFACEM_ICompressSetCoderProperties(x) \
146 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps) PURE; 175 x(SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps))
147}; 176Z7_IFACE_CONSTR_CODER(ICompressSetCoderProperties, 0x20)
148 177
149/* 178/*
150CODER_INTERFACE(ICompressSetCoderProperties, 0x21) 179#define Z7_IFACEM_ICompressSetDecoderProperties(x) \
151{ 180 x(SetDecoderProperties(ISequentialInStream *inStream))
152 STDMETHOD(SetDecoderProperties)(ISequentialInStream *inStream) PURE; 181Z7_IFACE_CONSTR_CODER(ICompressSetDecoderProperties, 0x21)
153};
154*/ 182*/
155 183
156CODER_INTERFACE(ICompressSetDecoderProperties2, 0x22) 184#define Z7_IFACEM_ICompressSetDecoderProperties2(x) \
157{ 185 x(SetDecoderProperties2(const Byte *data, UInt32 size))
186Z7_IFACE_CONSTR_CODER(ICompressSetDecoderProperties2, 0x22)
158 /* returns: 187 /* returns:
159 S_OK 188 S_OK
160 E_NOTIMP : unsupported properties 189 E_NOTIMP : unsupported properties
161 E_INVALIDARG : incorrect (or unsupported) properties 190 E_INVALIDARG : incorrect (or unsupported) properties
162 E_OUTOFMEMORY : memory allocation error 191 E_OUTOFMEMORY : memory allocation error
163 */ 192 */
164 STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size) PURE;
165};
166 193
167CODER_INTERFACE(ICompressWriteCoderProperties, 0x23)
168{
169 STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream) PURE;
170};
171 194
172CODER_INTERFACE(ICompressGetInStreamProcessedSize, 0x24) 195#define Z7_IFACEM_ICompressWriteCoderProperties(x) \
173{ 196 x(WriteCoderProperties(ISequentialOutStream *outStream))
174 STDMETHOD(GetInStreamProcessedSize)(UInt64 *value) PURE; 197Z7_IFACE_CONSTR_CODER(ICompressWriteCoderProperties, 0x23)
175};
176 198
177CODER_INTERFACE(ICompressSetCoderMt, 0x25) 199#define Z7_IFACEM_ICompressGetInStreamProcessedSize(x) \
178{ 200 x(GetInStreamProcessedSize(UInt64 *value))
179 STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE; 201Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize, 0x24)
180};
181 202
182CODER_INTERFACE(ICompressSetFinishMode, 0x26) 203#define Z7_IFACEM_ICompressSetCoderMt(x) \
183{ 204 x(SetNumberOfThreads(UInt32 numThreads))
184 STDMETHOD(SetFinishMode)(UInt32 finishMode) PURE; 205Z7_IFACE_CONSTR_CODER(ICompressSetCoderMt, 0x25)
185 206
207#define Z7_IFACEM_ICompressSetFinishMode(x) \
208 x(SetFinishMode(UInt32 finishMode))
209Z7_IFACE_CONSTR_CODER(ICompressSetFinishMode, 0x26)
186 /* finishMode: 210 /* finishMode:
187 0 : partial decoding is allowed. It's default mode for ICompressCoder::Code(), if (outSize) is defined. 211 0 : partial decoding is allowed. It's default mode for ICompressCoder::Code(), if (outSize) is defined.
188 1 : full decoding. The stream must be finished at the end of decoding. */ 212 1 : full decoding. The stream must be finished at the end of decoding. */
189};
190 213
191CODER_INTERFACE(ICompressGetInStreamProcessedSize2, 0x27) 214#define Z7_IFACEM_ICompressGetInStreamProcessedSize2(x) \
192{ 215 x(GetInStreamProcessedSize2(UInt32 streamIndex, UInt64 *value))
193 STDMETHOD(GetInStreamProcessedSize2)(UInt32 streamIndex, UInt64 *value) PURE; 216Z7_IFACE_CONSTR_CODER(ICompressGetInStreamProcessedSize2, 0x27)
194};
195 217
196CODER_INTERFACE(ICompressSetMemLimit, 0x28) 218#define Z7_IFACEM_ICompressSetMemLimit(x) \
197{ 219 x(SetMemLimit(UInt64 memUsage))
198 STDMETHOD(SetMemLimit)(UInt64 memUsage) PURE; 220Z7_IFACE_CONSTR_CODER(ICompressSetMemLimit, 0x28)
199};
200 221
201 222
202/* 223/*
@@ -208,23 +229,18 @@ CODER_INTERFACE(ICompressSetMemLimit, 0x28)
208 data from the internal buffer. 229 data from the internal buffer.
209 in ReadUnusedFromInBuf(): the Coder is not allowed to use (ISequentialInStream *inStream) object, that was sent to ICoder::Code(). 230 in ReadUnusedFromInBuf(): the Coder is not allowed to use (ISequentialInStream *inStream) object, that was sent to ICoder::Code().
210*/ 231*/
211 232#define Z7_IFACEM_ICompressReadUnusedFromInBuf(x) \
212CODER_INTERFACE(ICompressReadUnusedFromInBuf, 0x29) 233 x(ReadUnusedFromInBuf(void *data, UInt32 size, UInt32 *processedSize))
213{ 234Z7_IFACE_CONSTR_CODER(ICompressReadUnusedFromInBuf, 0x29)
214 STDMETHOD(ReadUnusedFromInBuf)(void *data, UInt32 size, UInt32 *processedSize) PURE;
215};
216 235
217 236
218 237#define Z7_IFACEM_ICompressGetSubStreamSize(x) \
219CODER_INTERFACE(ICompressGetSubStreamSize, 0x30) 238 x(GetSubStreamSize(UInt64 subStream, UInt64 *value))
220{ 239Z7_IFACE_CONSTR_CODER(ICompressGetSubStreamSize, 0x30)
221 STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value) PURE;
222
223 /* returns: 240 /* returns:
224 S_OK : (*value) contains the size or estimated size (can be incorrect size) 241 S_OK : (*value) contains the size or estimated size (can be incorrect size)
225 S_FALSE : size is undefined 242 S_FALSE : size is undefined
226 E_NOTIMP : the feature is not implemented 243 E_NOTIMP : the feature is not implemented
227
228 Let's (read_size) is size of data that was already read by ISequentialInStream::Read(). 244 Let's (read_size) is size of data that was already read by ISequentialInStream::Read().
229 The caller should call GetSubStreamSize() after each Read() and check sizes: 245 The caller should call GetSubStreamSize() after each Read() and check sizes:
230 if (start_of_subStream + *value < read_size) 246 if (start_of_subStream + *value < read_size)
@@ -234,74 +250,74 @@ CODER_INTERFACE(ICompressGetSubStreamSize, 0x30)
234 subStream++; 250 subStream++;
235 } 251 }
236 */ 252 */
237};
238 253
239CODER_INTERFACE(ICompressSetInStream, 0x31) 254#define Z7_IFACEM_ICompressSetInStream(x) \
240{ 255 x(SetInStream(ISequentialInStream *inStream)) \
241 STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE; 256 x(ReleaseInStream())
242 STDMETHOD(ReleaseInStream)() PURE; 257Z7_IFACE_CONSTR_CODER(ICompressSetInStream, 0x31)
243};
244 258
245CODER_INTERFACE(ICompressSetOutStream, 0x32) 259#define Z7_IFACEM_ICompressSetOutStream(x) \
246{ 260 x(SetOutStream(ISequentialOutStream *outStream)) \
247 STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE; 261 x(ReleaseOutStream())
248 STDMETHOD(ReleaseOutStream)() PURE; 262Z7_IFACE_CONSTR_CODER(ICompressSetOutStream, 0x32)
249};
250 263
251/* 264/*
252CODER_INTERFACE(ICompressSetInStreamSize, 0x33) 265#define Z7_IFACEM_ICompressSetInStreamSize(x) \
253{ 266 x(SetInStreamSize(const UInt64 *inSize)) \
254 STDMETHOD(SetInStreamSize)(const UInt64 *inSize) PURE; 267Z7_IFACE_CONSTR_CODER(ICompressSetInStreamSize, 0x33)
255};
256*/ 268*/
257 269
258CODER_INTERFACE(ICompressSetOutStreamSize, 0x34) 270#define Z7_IFACEM_ICompressSetOutStreamSize(x) \
259{ 271 x(SetOutStreamSize(const UInt64 *outSize))
260 STDMETHOD(SetOutStreamSize)(const UInt64 *outSize) PURE; 272Z7_IFACE_CONSTR_CODER(ICompressSetOutStreamSize, 0x34)
261
262 /* That function initializes decoder structures. 273 /* That function initializes decoder structures.
263 Call this function only for stream version of decoder. 274 Call this function only for stream version of decoder.
264 if (outSize == NULL), then output size is unknown 275 if (outSize == NULL), then output size is unknown
265 if (outSize != NULL), then the decoder must stop decoding after (*outSize) bytes. */ 276 if (outSize != NULL), then the decoder must stop decoding after (*outSize) bytes. */
266};
267
268CODER_INTERFACE(ICompressSetBufSize, 0x35)
269{
270 STDMETHOD(SetInBufSize)(UInt32 streamIndex, UInt32 size) PURE;
271 STDMETHOD(SetOutBufSize)(UInt32 streamIndex, UInt32 size) PURE;
272};
273 277
274CODER_INTERFACE(ICompressInitEncoder, 0x36) 278#define Z7_IFACEM_ICompressSetBufSize(x) \
275{ 279 x(SetInBufSize(UInt32 streamIndex, UInt32 size)) \
276 STDMETHOD(InitEncoder)() PURE; 280 x(SetOutBufSize(UInt32 streamIndex, UInt32 size))
281
282Z7_IFACE_CONSTR_CODER(ICompressSetBufSize, 0x35)
277 283
284#define Z7_IFACEM_ICompressInitEncoder(x) \
285 x(InitEncoder())
286Z7_IFACE_CONSTR_CODER(ICompressInitEncoder, 0x36)
278 /* That function initializes encoder structures. 287 /* That function initializes encoder structures.
279 Call this function only for stream version of encoder. */ 288 Call this function only for stream version of encoder. */
280};
281 289
282CODER_INTERFACE(ICompressSetInStream2, 0x37) 290#define Z7_IFACEM_ICompressSetInStream2(x) \
283{ 291 x(SetInStream2(UInt32 streamIndex, ISequentialInStream *inStream)) \
284 STDMETHOD(SetInStream2)(UInt32 streamIndex, ISequentialInStream *inStream) PURE; 292 x(ReleaseInStream2(UInt32 streamIndex))
285 STDMETHOD(ReleaseInStream2)(UInt32 streamIndex) PURE; 293Z7_IFACE_CONSTR_CODER(ICompressSetInStream2, 0x37)
286};
287 294
288/* 295/*
289CODER_INTERFACE(ICompressSetOutStream2, 0x38) 296#define Z7_IFACEM_ICompressSetOutStream2(x) \
290{ 297 x(SetOutStream2(UInt32 streamIndex, ISequentialOutStream *outStream))
291 STDMETHOD(SetOutStream2)(UInt32 streamIndex, ISequentialOutStream *outStream) PURE; 298 x(ReleaseOutStream2(UInt32 streamIndex))
292 STDMETHOD(ReleaseOutStream2)(UInt32 streamIndex) PURE; 299Z7_IFACE_CONSTR_CODER(ICompressSetOutStream2, 0x38)
293}; 300
294 301#define Z7_IFACEM_ICompressSetInStreamSize2(x) \
295CODER_INTERFACE(ICompressSetInStreamSize2, 0x39) 302 x(SetInStreamSize2(UInt32 streamIndex, const UInt64 *inSize))
296{ 303Z7_IFACE_CONSTR_CODER(ICompressSetInStreamSize2, 0x39)
297 STDMETHOD(SetInStreamSize2)(UInt32 streamIndex, const UInt64 *inSize) PURE;
298};
299*/ 304*/
300 305
306/*
307#define Z7_IFACEM_ICompressInSubStreams(x) \
308 x(GetNextInSubStream(UInt64 *streamIndexRes, ISequentialInStream **stream))
309Z7_IFACE_CONSTR_CODER(ICompressInSubStreams, 0x3A)
310
311#define Z7_IFACEM_ICompressOutSubStreams(x) \
312 x(GetNextOutSubStream(UInt64 *streamIndexRes, ISequentialOutStream **stream))
313Z7_IFACE_CONSTR_CODER(ICompressOutSubStreams, 0x3B)
314*/
301 315
302/* 316/*
303 ICompressFilter 317 ICompressFilter
304 Filter() converts as most as possible bytes required for fast processing. 318 Filter(Byte *data, UInt32 size)
319 (size)
320 converts as most as possible bytes required for fast processing.
305 Some filters have (smallest_fast_block). 321 Some filters have (smallest_fast_block).
306 For example, (smallest_fast_block == 16) for AES CBC/CTR filters. 322 For example, (smallest_fast_block == 16) for AES CBC/CTR filters.
307 If data stream is not finished, caller must call Filter() for larger block: 323 If data stream is not finished, caller must call Filter() for larger block:
@@ -310,13 +326,28 @@ CODER_INTERFACE(ICompressSetInStreamSize2, 0x39)
310 { 326 {
311 The filter can leave some bytes at the end of data without conversion: 327 The filter can leave some bytes at the end of data without conversion:
312 if there are data alignment reasons or speed reasons. 328 if there are data alignment reasons or speed reasons.
313 The caller must read additional data from stream and call Filter() again. 329 The caller can read additional data from stream and call Filter() again.
314 } 330 }
315 If data stream was finished, caller can call Filter() for (size < smallest_fast_block) 331 If data stream was finished, caller can call Filter() for (size < smallest_fast_block)
316 332
317 data : must be aligned for at least 16 bytes for some filters (AES) 333 (data) parameter:
318 334 Some filters require alignment for any Filter() call:
319 returns: (outSize): 335 1) (stream_offset % alignment_size) == (data % alignment_size)
336 2) (alignment_size == 2^N)
337 where (stream_offset) - is the number of bytes that were already filtered before.
338 The callers of Filter() are required to meet these requirements.
339 (alignment_size) can be different:
340 16 : for AES filters
341 4 or 2 : for some branch convert filters
342 1 : for another filters
343 (alignment_size >= 16) is enough for all current filters of 7-Zip.
344 But the caller can use larger (alignment_size).
345 Recommended alignment for (data) of Filter() call is (alignment_size == 64).
346 Also it's recommended to use aligned value for (size):
347 (size % alignment_size == 0),
348 if it's not last call of Filter() for current stream.
349
350 returns: (outSize):
320 if (outSize == 0) : Filter have not converted anything. 351 if (outSize == 0) : Filter have not converted anything.
321 So the caller can stop processing, if data stream was finished. 352 So the caller can stop processing, if data stream was finished.
322 if (outSize <= size) : Filter have converted outSize bytes 353 if (outSize <= size) : Filter have converted outSize bytes
@@ -325,60 +356,47 @@ CODER_INTERFACE(ICompressSetInStreamSize2, 0x39)
325 (it's for crypto block algorithms). 356 (it's for crypto block algorithms).
326*/ 357*/
327 358
328#define INTERFACE_ICompressFilter(x) \ 359#define Z7_IFACEM_ICompressFilter(x) \
329 STDMETHOD(Init)() x; \ 360 x(Init()) \
330 STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) x; \ 361 x##2(UInt32, Filter(Byte *data, UInt32 size))
362Z7_IFACE_CONSTR_CODER(ICompressFilter, 0x40)
331 363
332CODER_INTERFACE(ICompressFilter, 0x40)
333{
334 INTERFACE_ICompressFilter(PURE);
335};
336 364
365#define Z7_IFACEM_ICompressCodecsInfo(x) \
366 x(GetNumMethods(UInt32 *numMethods)) \
367 x(GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)) \
368 x(CreateDecoder(UInt32 index, const GUID *iid, void* *coder)) \
369 x(CreateEncoder(UInt32 index, const GUID *iid, void* *coder))
370Z7_IFACE_CONSTR_CODER(ICompressCodecsInfo, 0x60)
337 371
338CODER_INTERFACE(ICompressCodecsInfo, 0x60) 372#define Z7_IFACEM_ISetCompressCodecsInfo(x) \
339{ 373 x(SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo))
340 STDMETHOD(GetNumMethods)(UInt32 *numMethods) PURE; 374Z7_IFACE_CONSTR_CODER(ISetCompressCodecsInfo, 0x61)
341 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE;
342 STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder) PURE;
343 STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder) PURE;
344};
345 375
346CODER_INTERFACE(ISetCompressCodecsInfo, 0x61) 376#define Z7_IFACEM_ICryptoProperties(x) \
347{ 377 x(SetKey(const Byte *data, UInt32 size)) \
348 STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo) PURE; 378 x(SetInitVector(const Byte *data, UInt32 size))
349}; 379Z7_IFACE_CONSTR_CODER(ICryptoProperties, 0x80)
350
351CODER_INTERFACE(ICryptoProperties, 0x80)
352{
353 STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE;
354 STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE;
355};
356 380
357/* 381/*
358CODER_INTERFACE(ICryptoResetSalt, 0x88) 382 x(ResetSalt())
359{ 383Z7_IFACE_CONSTR_CODER(ICryptoResetSalt, 0x88)
360 STDMETHOD(ResetSalt)() PURE;
361};
362*/ 384*/
363 385
364CODER_INTERFACE(ICryptoResetInitVector, 0x8C) 386#define Z7_IFACEM_ICryptoResetInitVector(x) \
365{ 387 x(ResetInitVector())
366 STDMETHOD(ResetInitVector)() PURE; 388Z7_IFACE_CONSTR_CODER(ICryptoResetInitVector, 0x8C)
367
368 /* Call ResetInitVector() only for encoding. 389 /* Call ResetInitVector() only for encoding.
369 Call ResetInitVector() before encoding and before WriteCoderProperties(). 390 Call ResetInitVector() before encoding and before WriteCoderProperties().
370 Crypto encoder can create random IV in that function. */ 391 Crypto encoder can create random IV in that function. */
371};
372 392
373CODER_INTERFACE(ICryptoSetPassword, 0x90) 393#define Z7_IFACEM_ICryptoSetPassword(x) \
374{ 394 x(CryptoSetPassword(const Byte *data, UInt32 size))
375 STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size) PURE; 395Z7_IFACE_CONSTR_CODER(ICryptoSetPassword, 0x90)
376};
377 396
378CODER_INTERFACE(ICryptoSetCRC, 0xA0) 397#define Z7_IFACEM_ICryptoSetCRC(x) \
379{ 398 x(CryptoSetCRC(UInt32 crc))
380 STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE; 399Z7_IFACE_CONSTR_CODER(ICryptoSetCRC, 0xA0)
381};
382 400
383 401
384namespace NMethodPropID 402namespace NMethodPropID
@@ -399,24 +417,48 @@ namespace NMethodPropID
399 }; 417 };
400} 418}
401 419
402 420namespace NModuleInterfaceType
403#define INTERFACE_IHasher(x) \
404 STDMETHOD_(void, Init)() throw() x; \
405 STDMETHOD_(void, Update)(const void *data, UInt32 size) throw() x; \
406 STDMETHOD_(void, Final)(Byte *digest) throw() x; \
407 STDMETHOD_(UInt32, GetDigestSize)() throw() x; \
408
409CODER_INTERFACE(IHasher, 0xC0)
410{ 421{
411 INTERFACE_IHasher(PURE) 422 /*
412}; 423 virtual destructor in IUnknown:
424 - no : 7-Zip (Windows)
425 - no : 7-Zip (Linux) (v23) in default mode
426 - yes : p7zip
427 - yes : 7-Zip (Linux) before v23
428 - yes : 7-Zip (Linux) (v23), if Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN is defined
429 */
430 const UInt32 k_IUnknown_VirtDestructor_No = 0;
431 const UInt32 k_IUnknown_VirtDestructor_Yes = 1;
432 const UInt32 k_IUnknown_VirtDestructor_ThisModule =
433 #if !defined(_WIN32) && defined(Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN)
434 k_IUnknown_VirtDestructor_Yes;
435 #else
436 k_IUnknown_VirtDestructor_No;
437 #endif
438}
413 439
414CODER_INTERFACE(IHashers, 0xC1) 440namespace NModulePropID
415{ 441{
416 STDMETHOD_(UInt32, GetNumHashers)() PURE; 442 enum EEnum
417 STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE; 443 {
418 STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher) PURE; 444 kInterfaceType, // VT_UI4
419}; 445 kVersion // VT_UI4
446 };
447}
448
449
450#define Z7_IFACEM_IHasher(x) \
451 x##2(void, Init()) \
452 x##2(void, Update(const void *data, UInt32 size)) \
453 x##2(void, Final(Byte *digest)) \
454 x##2(UInt32, GetDigestSize())
455Z7_IFACE_CONSTR_CODER(IHasher, 0xC0)
456
457#define Z7_IFACEM_IHashers(x) \
458 x##2(UInt32, GetNumHashers()) \
459 x(GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value)) \
460 x(CreateHasher(UInt32 index, IHasher **hasher))
461Z7_IFACE_CONSTR_CODER(IHashers, 0xC1)
420 462
421extern "C" 463extern "C"
422{ 464{
@@ -428,6 +470,8 @@ extern "C"
428 typedef HRESULT (WINAPI *Func_GetHashers)(IHashers **hashers); 470 typedef HRESULT (WINAPI *Func_GetHashers)(IHashers **hashers);
429 471
430 typedef HRESULT (WINAPI *Func_SetCodecs)(ICompressCodecsInfo *compressCodecsInfo); 472 typedef HRESULT (WINAPI *Func_SetCodecs)(ICompressCodecsInfo *compressCodecsInfo);
473 typedef HRESULT (WINAPI *Func_GetModuleProp)(PROPID propID, PROPVARIANT *value);
431} 474}
432 475
476Z7_PURE_INTERFACES_END
433#endif 477#endif
diff --git a/CPP/7zip/IDecl.h b/CPP/7zip/IDecl.h
index 077ef0e..c4d4541 100644
--- a/CPP/7zip/IDecl.h
+++ b/CPP/7zip/IDecl.h
@@ -1,8 +1,9 @@
1// IDecl.h 1// IDecl.h
2 2
3#ifndef __IDECL_H 3#ifndef ZIP7_INC_IDECL_H
4#define __IDECL_H 4#define ZIP7_INC_IDECL_H
5 5
6#include "../Common/Common.h"
6#include "../Common/MyUnknown.h" 7#include "../Common/MyUnknown.h"
7 8
8#define k_7zip_GUID_Data1 0x23170F69 9#define k_7zip_GUID_Data1 0x23170F69
@@ -14,15 +15,62 @@
14#define k_7zip_GUID_Data3_Encoder 0x2791 15#define k_7zip_GUID_Data3_Encoder 0x2791
15#define k_7zip_GUID_Data3_Hasher 0x2792 16#define k_7zip_GUID_Data3_Hasher 0x2792
16 17
17 18#define Z7_DECL_IFACE_7ZIP_SUB(i, _base, groupId, subId) \
18#define DECL_INTERFACE_SUB(i, base, groupId, subId) \ 19 Z7_DEFINE_GUID(IID_ ## i, \
19 DEFINE_GUID(IID_ ## i, \
20 k_7zip_GUID_Data1, \ 20 k_7zip_GUID_Data1, \
21 k_7zip_GUID_Data2, \ 21 k_7zip_GUID_Data2, \
22 k_7zip_GUID_Data3_Common, \ 22 k_7zip_GUID_Data3_Common, \
23 0, 0, 0, (groupId), 0, (subId), 0, 0); \ 23 0, 0, 0, (groupId), 0, (subId), 0, 0); \
24 struct i: public base 24 struct Z7_DECLSPEC_NOVTABLE i: public _base
25
26#define Z7_DECL_IFACE_7ZIP(i, groupId, subId) \
27 Z7_DECL_IFACE_7ZIP_SUB(i, IUnknown, groupId, subId)
28
29
30#ifdef COM_DECLSPEC_NOTHROW
31#define Z7_COMWF_B COM_DECLSPEC_NOTHROW STDMETHODIMP
32#define Z7_COMWF_B_(t) COM_DECLSPEC_NOTHROW STDMETHODIMP_(t)
33#else
34#define Z7_COMWF_B STDMETHODIMP
35#define Z7_COMWF_B_(t) STDMETHODIMP_(t)
36#endif
37
38#if defined(_MSC_VER) && !defined(COM_DECLSPEC_NOTHROW)
39#define Z7_COM7F_B __declspec(nothrow) STDMETHODIMP
40#define Z7_COM7F_B_(t) __declspec(nothrow) STDMETHODIMP_(t)
41#else
42#define Z7_COM7F_B Z7_COMWF_B
43#define Z7_COM7F_B_(t) Z7_COMWF_B_(t)
44#endif
45
46// #define Z7_COM7F_E Z7_noexcept
47#define Z7_COM7F_E throw()
48#define Z7_COM7F_EO Z7_COM7F_E Z7_override
49#define Z7_COM7F_EOF Z7_COM7F_EO Z7_final
50#define Z7_COM7F_IMF(f) Z7_COM7F_B f Z7_COM7F_E
51#define Z7_COM7F_IMF2(t, f) Z7_COM7F_B_(t) f Z7_COM7F_E
52
53#define Z7_COM7F_PURE(f) virtual Z7_COM7F_IMF(f) =0;
54#define Z7_COM7F_PURE2(t, f) virtual Z7_COM7F_IMF2(t, f) =0;
55#define Z7_COM7F_IMP(f) Z7_COM7F_IMF(f) Z7_override Z7_final;
56#define Z7_COM7F_IMP2(t, f) Z7_COM7F_IMF2(t, f) Z7_override Z7_final;
57#define Z7_COM7F_IMP_NONFINAL(f) Z7_COM7F_IMF(f) Z7_override;
58#define Z7_COM7F_IMP_NONFINAL2(t, f) Z7_COM7F_IMF2(t, f) Z7_override;
59
60#define Z7_IFACE_PURE(name) Z7_IFACEN_ ## name(=0;)
61#define Z7_IFACE_IMP(name) Z7_IFACEN_ ## name(Z7_override Z7_final;)
62
63#define Z7_IFACE_COM7_PURE(name) Z7_IFACEM_ ## name(Z7_COM7F_PURE)
64#define Z7_IFACE_COM7_IMP(name) Z7_IFACEM_ ## name(Z7_COM7F_IMP)
65#define Z7_IFACE_COM7_IMP_NONFINAL(name) Z7_IFACEM_ ## name(Z7_COM7F_IMP_NONFINAL)
66
67
68#define Z7_IFACE_DECL_PURE(name) \
69 DECLARE_INTERFACE(name) \
70 { Z7_IFACE_PURE(name) };
25 71
26#define DECL_INTERFACE(i, groupId, subId) DECL_INTERFACE_SUB(i, IUnknown, groupId, subId) 72#define Z7_IFACE_DECL_PURE_(name, baseiface) \
73 DECLARE_INTERFACE_(name, baseiface) \
74 { Z7_IFACE_PURE(name) };
27 75
28#endif 76#endif
diff --git a/CPP/7zip/IPassword.h b/CPP/7zip/IPassword.h
index 4ccc9ac..689f08c 100644
--- a/CPP/7zip/IPassword.h
+++ b/CPP/7zip/IPassword.h
@@ -1,14 +1,17 @@
1// IPassword.h 1// IPassword.h
2 2
3#ifndef __IPASSWORD_H 3#ifndef ZIP7_INC_IPASSWORD_H
4#define __IPASSWORD_H 4#define ZIP7_INC_IPASSWORD_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7#include "../Common/MyUnknown.h"
8 7
9#include "IDecl.h" 8#include "IDecl.h"
10 9
11#define PASSWORD_INTERFACE(i, x) DECL_INTERFACE(i, 5, x) 10Z7_PURE_INTERFACES_BEGIN
11
12#define Z7_IFACE_CONSTR_PASSWORD(i, n) \
13 Z7_DECL_IFACE_7ZIP(i, 5, n) \
14 { Z7_IFACE_COM7_PURE(i) };
12 15
13/* 16/*
14How to use output parameter (BSTR *password): 17How to use output parameter (BSTR *password):
@@ -20,10 +23,9 @@ out: The callee rewrites BSTR variable (*password) with new allocated string poi
20 The caller must free BSTR string with function SysFreeString(); 23 The caller must free BSTR string with function SysFreeString();
21*/ 24*/
22 25
23PASSWORD_INTERFACE(ICryptoGetTextPassword, 0x10) 26#define Z7_IFACEM_ICryptoGetTextPassword(x) \
24{ 27 x(CryptoGetTextPassword(BSTR *password))
25 STDMETHOD(CryptoGetTextPassword)(BSTR *password) PURE; 28Z7_IFACE_CONSTR_PASSWORD(ICryptoGetTextPassword, 0x10)
26};
27 29
28 30
29/* 31/*
@@ -44,10 +46,9 @@ out:
44 The caller must free BSTR string with function SysFreeString() 46 The caller must free BSTR string with function SysFreeString()
45*/ 47*/
46 48
49#define Z7_IFACEM_ICryptoGetTextPassword2(x) \
50 x(CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password))
51Z7_IFACE_CONSTR_PASSWORD(ICryptoGetTextPassword2, 0x11)
47 52
48PASSWORD_INTERFACE(ICryptoGetTextPassword2, 0x11) 53Z7_PURE_INTERFACES_END
49{
50 STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password) PURE;
51};
52
53#endif 54#endif
diff --git a/CPP/7zip/IProgress.h b/CPP/7zip/IProgress.h
index fac951e..6714983 100644
--- a/CPP/7zip/IProgress.h
+++ b/CPP/7zip/IProgress.h
@@ -1,19 +1,20 @@
1// IProgress.h 1// IProgress.h
2 2
3#ifndef __IPROGRESS_H 3#ifndef ZIP7_INC_IPROGRESS_H
4#define __IPROGRESS_H 4#define ZIP7_INC_IPROGRESS_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7 7
8#include "IDecl.h" 8#include "IDecl.h"
9 9
10#define INTERFACE_IProgress(x) \ 10Z7_PURE_INTERFACES_BEGIN
11 STDMETHOD(SetTotal)(UInt64 total) x; \
12 STDMETHOD(SetCompleted)(const UInt64 *completeValue) x; \
13 11
14DECL_INTERFACE(IProgress, 0, 5) 12#define Z7_IFACEM_IProgress(x) \
15{ 13 x(SetTotal(UInt64 total)) \
16 INTERFACE_IProgress(PURE) 14 x(SetCompleted(const UInt64 *completeValue)) \
17};
18 15
16Z7_DECL_IFACE_7ZIP(IProgress, 0, 5)
17 { Z7_IFACE_COM7_PURE(IProgress) };
18
19Z7_PURE_INTERFACES_END
19#endif 20#endif
diff --git a/CPP/7zip/IStream.h b/CPP/7zip/IStream.h
index 2793a1e..4a58bc9 100644
--- a/CPP/7zip/IStream.h
+++ b/CPP/7zip/IStream.h
@@ -1,24 +1,28 @@
1// IStream.h 1// IStream.h
2 2
3#ifndef __ISTREAM_H 3#ifndef ZIP7_INC_ISTREAM_H
4#define __ISTREAM_H 4#define ZIP7_INC_ISTREAM_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7#include "../Common/MyWindows.h" 7#include "../Common/MyWindows.h"
8 8
9#include "IDecl.h" 9#include "IDecl.h"
10 10
11#define STREAM_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 3, x) 11Z7_PURE_INTERFACES_BEGIN
12#define STREAM_INTERFACE(i, x) STREAM_INTERFACE_SUB(i, IUnknown, x)
13 12
14STREAM_INTERFACE(ISequentialInStream, 0x01) 13#define Z7_IFACE_CONSTR_STREAM_SUB(i, base, n) \
15{ 14 Z7_DECL_IFACE_7ZIP_SUB(i, base, 3, n) \
16 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) PURE; 15 { Z7_IFACE_COM7_PURE(i) };
17 16
18 /* 17#define Z7_IFACE_CONSTR_STREAM(i, n) \
18 Z7_IFACE_CONSTR_STREAM_SUB(i, IUnknown, n)
19
20
21/*
22ISequentialInStream::Read()
19 The requirement for caller: (processedSize != NULL). 23 The requirement for caller: (processedSize != NULL).
20 The callee can allow (processedSize == NULL) for compatibility reasons. 24 The callee can allow (processedSize == NULL) for compatibility reasons.
21 25
22 if (size == 0), this function returns S_OK and (*processedSize) is set to 0. 26 if (size == 0), this function returns S_OK and (*processedSize) is set to 0.
23 27
24 if (size != 0) 28 if (size != 0)
@@ -31,21 +35,21 @@ STREAM_INTERFACE(ISequentialInStream, 0x01)
31 35
32 If seek pointer before Read() call was changed to position past the end of stream: 36 If seek pointer before Read() call was changed to position past the end of stream:
33 if (seek_pointer >= stream_size), this function returns S_OK and (*processedSize) is set to 0. 37 if (seek_pointer >= stream_size), this function returns S_OK and (*processedSize) is set to 0.
34 38
35 ERROR CASES: 39 ERROR CASES:
36 If the function returns error code, then (*processedSize) is size of 40 If the function returns error code, then (*processedSize) is size of
37 data written to (data) buffer (it can be data before error or data with errors). 41 data written to (data) buffer (it can be data before error or data with errors).
38 The recommended way for callee to work with reading errors: 42 The recommended way for callee to work with reading errors:
39 1) write part of data before error to (data) buffer and return S_OK. 43 1) write part of data before error to (data) buffer and return S_OK.
40 2) return error code for further calls of Read(). 44 2) return error code for further calls of Read().
41 */ 45*/
42}; 46#define Z7_IFACEM_ISequentialInStream(x) \
47 x(Read(void *data, UInt32 size, UInt32 *processedSize))
48Z7_IFACE_CONSTR_STREAM(ISequentialInStream, 0x01)
43 49
44STREAM_INTERFACE(ISequentialOutStream, 0x02) 50
45{ 51/*
46 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize) PURE; 52ISequentialOutStream::Write()
47
48 /*
49 The requirement for caller: (processedSize != NULL). 53 The requirement for caller: (processedSize != NULL).
50 The callee can allow (processedSize == NULL) for compatibility reasons. 54 The callee can allow (processedSize == NULL) for compatibility reasons.
51 55
@@ -59,8 +63,11 @@ STREAM_INTERFACE(ISequentialOutStream, 0x02)
59 ERROR CASES: 63 ERROR CASES:
60 If the function returns error code, then (*processedSize) is size of 64 If the function returns error code, then (*processedSize) is size of
61 data written from (data) buffer. 65 data written from (data) buffer.
62 */ 66*/
63}; 67#define Z7_IFACEM_ISequentialOutStream(x) \
68 x(Write(const void *data, UInt32 size, UInt32 *processedSize))
69Z7_IFACE_CONSTR_STREAM(ISequentialOutStream, 0x02)
70
64 71
65#ifdef _WIN32 72#ifdef _WIN32
66 73
@@ -72,48 +79,42 @@ STREAM_INTERFACE(ISequentialOutStream, 0x02)
72 79
73#else 80#else
74 81
75#define HRESULT_WIN32_ERROR_NEGATIVE_SEEK MY__E_ERROR_NEGATIVE_SEEK 82#define HRESULT_WIN32_ERROR_NEGATIVE_SEEK MY_E_ERROR_NEGATIVE_SEEK
76 83
77#endif 84#endif
78 85
79 86
80/* Seek() Function 87/*
81 If you seek before the beginning of the stream, Seek() function returns error code: 88IInStream::Seek() / IOutStream::Seek()
89 If you seek to position before the beginning of the stream,
90 Seek() function returns error code:
82 Recommended error code is __HRESULT_FROM_WIN32(ERROR_NEGATIVE_SEEK). 91 Recommended error code is __HRESULT_FROM_WIN32(ERROR_NEGATIVE_SEEK).
83 or STG_E_INVALIDFUNCTION 92 or STG_E_INVALIDFUNCTION
84
85 It is allowed to seek past the end of the stream. 93 It is allowed to seek past the end of the stream.
86
87
88 if Seek() returns error, then the value of *newPosition is undefined. 94 if Seek() returns error, then the value of *newPosition is undefined.
89*/ 95*/
90 96
91STREAM_INTERFACE_SUB(IInStream, ISequentialInStream, 0x03) 97#define Z7_IFACEM_IInStream(x) \
92{ 98 x(Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
93 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; 99Z7_IFACE_CONSTR_STREAM_SUB(IInStream, ISequentialInStream, 0x03)
94};
95 100
96STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04) 101#define Z7_IFACEM_IOutStream(x) \
97{ 102 x(Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)) \
98 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; 103 x(SetSize(UInt64 newSize))
99 STDMETHOD(SetSize)(UInt64 newSize) PURE; 104Z7_IFACE_CONSTR_STREAM_SUB(IOutStream, ISequentialOutStream, 0x04)
100};
101 105
102STREAM_INTERFACE(IStreamGetSize, 0x06) 106#define Z7_IFACEM_IStreamGetSize(x) \
103{ 107 x(GetSize(UInt64 *size))
104 STDMETHOD(GetSize)(UInt64 *size) PURE; 108Z7_IFACE_CONSTR_STREAM(IStreamGetSize, 0x06)
105};
106 109
107STREAM_INTERFACE(IOutStreamFinish, 0x07) 110#define Z7_IFACEM_IOutStreamFinish(x) \
108{ 111 x(OutStreamFinish())
109 STDMETHOD(OutStreamFinish)() PURE; 112Z7_IFACE_CONSTR_STREAM(IOutStreamFinish, 0x07)
110};
111 113
114#define Z7_IFACEM_IStreamGetProps(x) \
115 x(GetProps(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib))
116Z7_IFACE_CONSTR_STREAM(IStreamGetProps, 0x08)
112 117
113STREAM_INTERFACE(IStreamGetProps, 0x08)
114{
115 STDMETHOD(GetProps)(UInt64 *size, FILETIME *cTime, FILETIME *aTime, FILETIME *mTime, UInt32 *attrib) PURE;
116};
117 118
118struct CStreamFileProps 119struct CStreamFileProps
119{ 120{
@@ -128,16 +129,79 @@ struct CStreamFileProps
128 FILETIME MTime; 129 FILETIME MTime;
129}; 130};
130 131
131STREAM_INTERFACE(IStreamGetProps2, 0x09)
132{
133 STDMETHOD(GetProps2)(CStreamFileProps *props) PURE;
134};
135 132
133#define Z7_IFACEM_IStreamGetProps2(x) \
134 x(GetProps2(CStreamFileProps *props))
135Z7_IFACE_CONSTR_STREAM(IStreamGetProps2, 0x09)
136 136
137STREAM_INTERFACE(IStreamGetProp, 0x0a) 137#define Z7_IFACEM_IStreamGetProp(x) \
138{ 138 x(GetProperty(PROPID propID, PROPVARIANT *value)) \
139 STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) PURE; 139 x(ReloadProps())
140 STDMETHOD(ReloadProps)() PURE; 140Z7_IFACE_CONSTR_STREAM(IStreamGetProp, 0x0a)
141}; 141
142
143/*
144IStreamSetRestriction::SetRestriction(UInt64 begin, UInt64 end)
145
146 It sets region of data in output stream that is restricted.
147 For restricted region it's expected (or allowed)
148 to change data with different calls of Write()/SetSize().
149 Another regions of output stream will be supposed as non-restricted:
150 - The callee usually doesn't flush the data in restricted region.
151 - The callee usually can flush data from non-restricted region.
152
153inputs:
154
155 (begin > end) is not allowed, and returns E_FAIL;
156
157 if (begin == end)
158 {
159 it means that there is no region restriction for flushing.
160 The callee is allowed to flush already written data and
161 is allowed to flush all data in future calls of
162 ISequentialOutStream::Write(), but before next call of SetRestriction().
163 The pair of values (begin == 0 && end == 0) is recommended to
164 remove all restrictions.
165 }
166
167 if (begin < end)
168 {
169 it means that callee must NOT to flush any data in region [begin, end).
170 The caller is allowed to Seek() to that region and rewrite the
171 data in that restriction region.
172 if (end == (UInt64(Int64)-1)
173 {
174 there is no upper bound for restricted region.
175 So non-restricted region will be [0, begin) in that case
176 }
177
178 Note: it's not expected that some already written region was marked as
179 non-restricted by old call SetRestriction() and later the part of
180 that region was marked as restricted with new call SetRestriction().
181 For example, for different calls with non-empty restricted regions:
182 (begin_new >= begin_old) is expected :
183 {
184 SetRestriction(begin_old, ...)
185 ...
186 SetRestriction(begin_new, ...)
187 }
188 }
189
190 returns:
191 - if (begin > end) it return ERROR code (E_FAIL)
192 - S_OK : if no errors.
193 - Also the call of SetRestriction() can initiate the flushing of already written data.
194 So it can return the result of that flushing.
195
196 Note: IOutStream::SetSize() also can change the data.
197 So it's not expected the call
198 IOutStream::SetSize() to unrestricted already written region.
199*/
200
201#define Z7_IFACEM_IStreamSetRestriction(x) \
202 x(SetRestriction(UInt64 begin, UInt64 end)) \
203
204Z7_IFACE_CONSTR_STREAM(IStreamSetRestriction, 0x10)
142 205
206Z7_PURE_INTERFACES_END
143#endif 207#endif
diff --git a/CPP/7zip/LzmaDec.mak b/CPP/7zip/LzmaDec.mak
index bed4700..3beb505 100644
--- a/CPP/7zip/LzmaDec.mak
+++ b/CPP/7zip/LzmaDec.mak
@@ -1,6 +1,6 @@
1!IF "$(PLATFORM)" == "x64" 1!IF "$(PLATFORM)" == "x64"
2!IFNDEF NO_ASM 2!IFNDEF NO_ASM
3CFLAGS_C_SPEC = -D_LZMA_DEC_OPT 3CFLAGS_C_SPEC = -DZ7_LZMA_DEC_OPT
4ASM_OBJS = $(ASM_OBJS) \ 4ASM_OBJS = $(ASM_OBJS) \
5 $O\LzmaDecOpt.obj 5 $O\LzmaDecOpt.obj
6!ENDIF 6!ENDIF
diff --git a/CPP/7zip/MyVersionInfo.rc b/CPP/7zip/MyVersionInfo.rc
index fab6686..fc63d79 100644
--- a/CPP/7zip/MyVersionInfo.rc
+++ b/CPP/7zip/MyVersionInfo.rc
@@ -1,2 +1,2 @@
1#include "MyVersion.h" 1#include "MyVersion.h"
2#include "..\..\C\7zVersion.rc" 2#include "../../C/7zVersion.rc"
diff --git a/CPP/7zip/PropID.h b/CPP/7zip/PropID.h
index 2da636f..e074794 100644
--- a/CPP/7zip/PropID.h
+++ b/CPP/7zip/PropID.h
@@ -1,7 +1,7 @@
1// PropID.h 1// PropID.h
2 2
3#ifndef __7ZIP_PROP_ID_H 3#ifndef ZIP7_INC_7ZIP_PROP_ID_H
4#define __7ZIP_PROP_ID_H 4#define ZIP7_INC_7ZIP_PROP_ID_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7 7
@@ -110,6 +110,8 @@ enum
110 kpidGroupId, 110 kpidGroupId,
111 kpidDeviceMajor, 111 kpidDeviceMajor,
112 kpidDeviceMinor, 112 kpidDeviceMinor,
113 kpidDevMajor,
114 kpidDevMinor,
113 115
114 kpid_NUM_DEFINED, 116 kpid_NUM_DEFINED,
115 117
diff --git a/CPP/7zip/UI/Agent/Agent.cpp b/CPP/7zip/UI/Agent/Agent.cpp
index cc20c11..6761b28 100644
--- a/CPP/7zip/UI/Agent/Agent.cpp
+++ b/CPP/7zip/UI/Agent/Agent.cpp
@@ -12,7 +12,7 @@
12#include "../../../Windows/FileName.h" 12#include "../../../Windows/FileName.h"
13#include "../../../Windows/PropVariantConv.h" 13#include "../../../Windows/PropVariantConv.h"
14 14
15#ifndef _7ZIP_ST 15#ifndef Z7_ST
16#include "../../../Windows/Synchronization.h" 16#include "../../../Windows/Synchronization.h"
17#endif 17#endif
18 18
@@ -29,8 +29,12 @@ static const bool k_keepEmptyDirPrefixes =
29 false; // 22.00 29 false; // 22.00
30 // true; // 21.07 30 // true; // 21.07
31 31
32#ifdef EXTERNAL_CODECS 32#ifdef Z7_EXTERNAL_CODECS
33 extern
34 CExternalCodecs g_ExternalCodecs;
33 CExternalCodecs g_ExternalCodecs; 35 CExternalCodecs g_ExternalCodecs;
36 extern
37 const CExternalCodecs *g_ExternalCodecs_Ptr;
34 const CExternalCodecs *g_ExternalCodecs_Ptr; 38 const CExternalCodecs *g_ExternalCodecs_Ptr;
35 static CCodecs::CReleaser g_CodecsReleaser; 39 static CCodecs::CReleaser g_CodecsReleaser;
36#else 40#else
@@ -39,7 +43,7 @@ static const bool k_keepEmptyDirPrefixes =
39 CMyComPtr<IUnknown> g_CodecsRef; 43 CMyComPtr<IUnknown> g_CodecsRef;
40#endif 44#endif
41 45
42#ifndef _7ZIP_ST 46#ifndef Z7_ST
43static NSynchronization::CCriticalSection g_CriticalSection; 47static NSynchronization::CCriticalSection g_CriticalSection;
44#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 48#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
45#else 49#else
@@ -50,7 +54,7 @@ void FreeGlobalCodecs()
50{ 54{
51 MT_LOCK 55 MT_LOCK
52 56
53 #ifdef EXTERNAL_CODECS 57 #ifdef Z7_EXTERNAL_CODECS
54 if (g_CodecsObj) 58 if (g_CodecsObj)
55 { 59 {
56 g_CodecsObj->CloseLibs(); 60 g_CodecsObj->CloseLibs();
@@ -73,7 +77,7 @@ HRESULT LoadGlobalCodecs()
73 77
74 g_CodecsObj = new CCodecs; 78 g_CodecsObj = new CCodecs;
75 79
76 #ifdef EXTERNAL_CODECS 80 #ifdef Z7_EXTERNAL_CODECS
77 g_ExternalCodecs.GetCodecs = g_CodecsObj; 81 g_ExternalCodecs.GetCodecs = g_CodecsObj;
78 g_ExternalCodecs.GetHashers = g_CodecsObj; 82 g_ExternalCodecs.GetHashers = g_CodecsObj;
79 g_CodecsReleaser.Set(g_CodecsObj); 83 g_CodecsReleaser.Set(g_CodecsObj);
@@ -82,7 +86,7 @@ HRESULT LoadGlobalCodecs()
82 g_CodecsRef = g_CodecsObj; 86 g_CodecsRef = g_CodecsObj;
83 #endif 87 #endif
84 88
85 RINOK(g_CodecsObj->Load()); 89 RINOK(g_CodecsObj->Load())
86 if (g_CodecsObj->Formats.IsEmpty()) 90 if (g_CodecsObj->Formats.IsEmpty())
87 { 91 {
88 FreeGlobalCodecs(); 92 FreeGlobalCodecs();
@@ -91,15 +95,15 @@ HRESULT LoadGlobalCodecs()
91 95
92 Codecs_AddHashArcHandler(g_CodecsObj); 96 Codecs_AddHashArcHandler(g_CodecsObj);
93 97
94 #ifdef EXTERNAL_CODECS 98 #ifdef Z7_EXTERNAL_CODECS
95 RINOK(g_ExternalCodecs.Load()); 99 RINOK(g_ExternalCodecs.Load())
96 g_ExternalCodecs_Ptr = &g_ExternalCodecs; 100 g_ExternalCodecs_Ptr = &g_ExternalCodecs;
97 #endif 101 #endif
98 102
99 return S_OK; 103 return S_OK;
100} 104}
101 105
102STDMETHODIMP CAgentFolder::GetAgentFolder(CAgentFolder **agentFolder) 106Z7_COM7F_IMF(CAgentFolder::GetAgentFolder(CAgentFolder **agentFolder))
103{ 107{
104 *agentFolder = this; 108 *agentFolder = this;
105 return S_OK; 109 return S_OK;
@@ -119,9 +123,9 @@ void CAgentFolder::LoadFolder(unsigned proxyDirIndex)
119 _items.Add(item); 123 _items.Add(item);
120 const CProxyFile2 &file = _proxy2->Files[dir.Items[i]]; 124 const CProxyFile2 &file = _proxy2->Files[dir.Items[i]];
121 if (file.DirIndex != -1) 125 if (file.DirIndex != -1)
122 LoadFolder(file.DirIndex); 126 LoadFolder((unsigned)file.DirIndex);
123 if (_loadAltStreams && file.AltDirIndex != -1) 127 if (_loadAltStreams && file.AltDirIndex != -1)
124 LoadFolder(file.AltDirIndex); 128 LoadFolder((unsigned)file.AltDirIndex);
125 } 129 }
126 return; 130 return;
127 } 131 }
@@ -143,7 +147,7 @@ void CAgentFolder::LoadFolder(unsigned proxyDirIndex)
143 } 147 }
144} 148}
145 149
146STDMETHODIMP CAgentFolder::LoadItems() 150Z7_COM7F_IMF(CAgentFolder::LoadItems())
147{ 151{
148 if (!_agentSpec->_archiveLink.IsOpen) 152 if (!_agentSpec->_archiveLink.IsOpen)
149 return E_FAIL; 153 return E_FAIL;
@@ -160,7 +164,7 @@ STDMETHODIMP CAgentFolder::LoadItems()
160 return S_OK; 164 return S_OK;
161} 165}
162 166
163STDMETHODIMP CAgentFolder::GetNumberOfItems(UInt32 *numItems) 167Z7_COM7F_IMF(CAgentFolder::GetNumberOfItems(UInt32 *numItems))
164{ 168{
165 if (_flatMode) 169 if (_flatMode)
166 *numItems = _items.Size(); 170 *numItems = _items.Size();
@@ -217,7 +221,7 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const
217 { 221 {
218 const CProxyFile2 &file = _proxy2->Files[(unsigned)_proxy2->Dirs[proxyIndex].ArcIndex]; 222 const CProxyFile2 &file = _proxy2->Files[(unsigned)_proxy2->Dirs[proxyIndex].ArcIndex];
219 len += file.NameLen + 1; 223 len += file.NameLen + 1;
220 proxyIndex = (file.Parent == -1) ? 0 : _proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); 224 proxyIndex = (file.Parent == -1) ? 0 : (unsigned)_proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream);
221 } 225 }
222 226
223 wchar_t *p = prefix.GetBuf_SetEnd(len) + len; 227 wchar_t *p = prefix.GetBuf_SetEnd(len) + len;
@@ -229,7 +233,7 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const
229 *p = WCHAR_PATH_SEPARATOR; 233 *p = WCHAR_PATH_SEPARATOR;
230 p -= file.NameLen; 234 p -= file.NameLen;
231 wmemcpy(p, file.Name, file.NameLen); 235 wmemcpy(p, file.Name, file.NameLen);
232 proxyIndex = (file.Parent == -1) ? 0 : _proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream); 236 proxyIndex = (file.Parent == -1) ? 0 : (unsigned)_proxy2->Files[(unsigned)file.Parent].GetDirIndex(file.IsAltStream);
233 } 237 }
234 } 238 }
235 else 239 else
@@ -239,7 +243,7 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const
239 { 243 {
240 const CProxyDir *dir = &_proxy->Dirs[proxyIndex]; 244 const CProxyDir *dir = &_proxy->Dirs[proxyIndex];
241 len += dir->NameLen + 1; 245 len += dir->NameLen + 1;
242 proxyIndex = dir->ParentDir; 246 proxyIndex = (unsigned)dir->ParentDir;
243 } 247 }
244 248
245 wchar_t *p = prefix.GetBuf_SetEnd(len) + len; 249 wchar_t *p = prefix.GetBuf_SetEnd(len) + len;
@@ -251,14 +255,14 @@ void CAgentFolder::GetPrefix(UInt32 index, UString &prefix) const
251 *p = WCHAR_PATH_SEPARATOR; 255 *p = WCHAR_PATH_SEPARATOR;
252 p -= dir->NameLen; 256 p -= dir->NameLen;
253 wmemcpy(p, dir->Name, dir->NameLen); 257 wmemcpy(p, dir->Name, dir->NameLen);
254 proxyIndex = dir->ParentDir; 258 proxyIndex = (unsigned)dir->ParentDir;
255 } 259 }
256 } 260 }
257} 261}
258 262
259UString CAgentFolder::GetFullPrefix(UInt32 index) const 263UString CAgentFolder::GetFullPrefix(UInt32 index) const
260{ 264{
261 int foldIndex = _proxyDirIndex; 265 unsigned foldIndex = _proxyDirIndex;
262 266
263 if (_flatMode) 267 if (_flatMode)
264 foldIndex = _items[index].DirIndex; 268 foldIndex = _items[index].DirIndex;
@@ -269,7 +273,7 @@ UString CAgentFolder::GetFullPrefix(UInt32 index) const
269 return _proxy->GetDirPath_as_Prefix(foldIndex); 273 return _proxy->GetDirPath_as_Prefix(foldIndex);
270} 274}
271 275
272STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index) 276Z7_COM7F_IMF2(UInt64, CAgentFolder::GetItemSize(UInt32 index))
273{ 277{
274 unsigned arcIndex; 278 unsigned arcIndex;
275 if (_proxy2) 279 if (_proxy2)
@@ -294,7 +298,7 @@ STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index)
294 return item.Size; 298 return item.Size;
295 if (!item.IsLeaf()) 299 if (!item.IsLeaf())
296 return 0; 300 return 0;
297 arcIndex = item.ArcIndex; 301 arcIndex = (unsigned)item.ArcIndex;
298 } 302 }
299 else 303 else
300 { 304 {
@@ -309,7 +313,7 @@ STDMETHODIMP_(UInt64) CAgentFolder::GetItemSize(UInt32 index)
309 return 0; 313 return 0;
310} 314}
311 315
312STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 316Z7_COM7F_IMF(CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
313{ 317{
314 COM_TRY_BEGIN 318 COM_TRY_BEGIN
315 NCOM::CPropVariant prop; 319 NCOM::CPropVariant prop;
@@ -363,7 +367,7 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT
363 // if (itemFolder.IsLeaf) 367 // if (itemFolder.IsLeaf)
364 if (!item.Ignore) 368 if (!item.Ignore)
365 { 369 {
366 RINOK(_agentSpec->GetArchive()->GetProperty(arcIndex, propID, value)); 370 RINOK(_agentSpec->GetArchive()->GetProperty(arcIndex, propID, value))
367 } 371 }
368 if (itemFolder.CrcIsDefined && value->vt == VT_EMPTY) 372 if (itemFolder.CrcIsDefined && value->vt == VT_EMPTY)
369 prop = itemFolder.Crc; 373 prop = itemFolder.Crc;
@@ -397,7 +401,7 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT
397 { 401 {
398 if (item.IsLeaf()) 402 if (item.IsLeaf())
399 { 403 {
400 RINOK(_agentSpec->GetArchive()->GetProperty(item.ArcIndex, propID, value)); 404 RINOK(_agentSpec->GetArchive()->GetProperty((unsigned)item.ArcIndex, propID, value))
401 } 405 }
402 if (item.CrcIsDefined && value->vt == VT_EMPTY) 406 if (item.CrcIsDefined && value->vt == VT_EMPTY)
403 prop = item.Crc; 407 prop = item.Crc;
@@ -405,7 +409,7 @@ STDMETHODIMP CAgentFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT
405 } 409 }
406 default: 410 default:
407 if (item.IsLeaf()) 411 if (item.IsLeaf())
408 return _agentSpec->GetArchive()->GetProperty(item.ArcIndex, propID, value); 412 return _agentSpec->GetArchive()->GetProperty((unsigned)item.ArcIndex, propID, value);
409 } 413 }
410 } 414 }
411 else 415 else
@@ -436,7 +440,7 @@ static UInt64 GetUInt64Prop(IInArchive *archive, UInt32 index, PROPID propID)
436 return 0; 440 return 0;
437} 441}
438 442
439STDMETHODIMP CAgentFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) 443Z7_COM7F_IMF(CAgentFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len))
440{ 444{
441 if (_proxy2) 445 if (_proxy2)
442 { 446 {
@@ -467,9 +471,9 @@ STDMETHODIMP CAgentFolder::GetItemName(UInt32 index, const wchar_t **name, unsig
467 } 471 }
468} 472}
469 473
470STDMETHODIMP CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len) 474Z7_COM7F_IMF(CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len))
471{ 475{
472 *name = 0; 476 *name = NULL;
473 *len = 0; 477 *len = 0;
474 if (!_flatMode) 478 if (!_flatMode)
475 return S_OK; 479 return S_OK;
@@ -493,7 +497,7 @@ STDMETHODIMP CAgentFolder::GetItemPrefix(UInt32 index, const wchar_t **name, uns
493 return S_OK; 497 return S_OK;
494} 498}
495 499
496static int CompareRawProps(IArchiveGetRawProps *rawProps, int arcIndex1, int arcIndex2, PROPID propID) 500static int CompareRawProps(IArchiveGetRawProps *rawProps, unsigned arcIndex1, unsigned arcIndex2, PROPID propID)
497{ 501{
498 // if (propID == kpidSha1) 502 // if (propID == kpidSha1)
499 if (rawProps) 503 if (rawProps)
@@ -501,14 +505,14 @@ static int CompareRawProps(IArchiveGetRawProps *rawProps, int arcIndex1, int arc
501 const void *p1, *p2; 505 const void *p1, *p2;
502 UInt32 size1, size2; 506 UInt32 size1, size2;
503 UInt32 propType1, propType2; 507 UInt32 propType1, propType2;
504 HRESULT res1 = rawProps->GetRawProp(arcIndex1, propID, &p1, &size1, &propType1); 508 const HRESULT res1 = rawProps->GetRawProp(arcIndex1, propID, &p1, &size1, &propType1);
505 HRESULT res2 = rawProps->GetRawProp(arcIndex2, propID, &p2, &size2, &propType2); 509 const HRESULT res2 = rawProps->GetRawProp(arcIndex2, propID, &p2, &size2, &propType2);
506 if (res1 == S_OK && res2 == S_OK) 510 if (res1 == S_OK && res2 == S_OK)
507 { 511 {
508 for (UInt32 i = 0; i < size1 && i < size2; i++) 512 for (UInt32 i = 0; i < size1 && i < size2; i++)
509 { 513 {
510 Byte b1 = ((const Byte *)p1)[i]; 514 const Byte b1 = ((const Byte *)p1)[i];
511 Byte b2 = ((const Byte *)p2)[i]; 515 const Byte b2 = ((const Byte *)p2)[i];
512 if (b1 < b2) return -1; 516 if (b1 < b2) return -1;
513 if (b1 > b2) return 1; 517 if (b1 > b2) return 1;
514 } 518 }
@@ -681,7 +685,7 @@ int CAgentFolder::CompareItems2(UInt32 index1, UInt32 index2, PROPID propID, Int
681} 685}
682 686
683 687
684STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw) 688Z7_COM7F_IMF2(Int32, CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw))
685{ 689{
686 try { 690 try {
687 if (_proxy2) 691 if (_proxy2)
@@ -725,7 +729,7 @@ STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PR
725 if (realIndex1 < dir1->SubDirs.Size()) 729 if (realIndex1 < dir1->SubDirs.Size())
726 { 730 {
727 proxFolder1 = &_proxy->Dirs[dir1->SubDirs[realIndex1]]; 731 proxFolder1 = &_proxy->Dirs[dir1->SubDirs[realIndex1]];
728 arcIndex1 = proxFolder1->ArcIndex; 732 arcIndex1 = (unsigned)proxFolder1->ArcIndex;
729 } 733 }
730 else 734 else
731 arcIndex1 = dir1->SubFiles[realIndex1 - dir1->SubDirs.Size()]; 735 arcIndex1 = dir1->SubFiles[realIndex1 - dir1->SubDirs.Size()];
@@ -733,7 +737,7 @@ STDMETHODIMP_(Int32) CAgentFolder::CompareItems(UInt32 index1, UInt32 index2, PR
733 if (realIndex2 < dir2->SubDirs.Size()) 737 if (realIndex2 < dir2->SubDirs.Size())
734 { 738 {
735 proxFolder2 = &_proxy->Dirs[dir2->SubDirs[realIndex2]]; 739 proxFolder2 = &_proxy->Dirs[dir2->SubDirs[realIndex2]];
736 arcIndex2 = proxFolder2->ArcIndex; 740 arcIndex2 = (unsigned)proxFolder2->ArcIndex;
737 } 741 }
738 else 742 else
739 arcIndex2 = dir2->SubFiles[realIndex2 - dir2->SubDirs.Size()]; 743 arcIndex2 = dir2->SubFiles[realIndex2 - dir2->SubDirs.Size()];
@@ -866,17 +870,17 @@ HRESULT CAgentFolder::BindToFolder_Internal(unsigned proxyDirIndex, IFolderFolde
866 return S_OK; 870 return S_OK;
867} 871}
868 872
869STDMETHODIMP CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 873Z7_COM7F_IMF(CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder))
870{ 874{
871 COM_TRY_BEGIN 875 COM_TRY_BEGIN
872 if (_proxy2) 876 if (_proxy2)
873 { 877 {
874 SET_realIndex_AND_dir_2 878 SET_realIndex_AND_dir_2
875 unsigned arcIndex = dir->Items[realIndex]; 879 const unsigned arcIndex = dir->Items[realIndex];
876 const CProxyFile2 &item = _proxy2->Files[arcIndex]; 880 const CProxyFile2 &item = _proxy2->Files[arcIndex];
877 if (!item.IsDir()) 881 if (!item.IsDir())
878 return E_INVALIDARG; 882 return E_INVALIDARG;
879 return BindToFolder_Internal(item.DirIndex, resultFolder); 883 return BindToFolder_Internal((unsigned)item.DirIndex, resultFolder);
880 } 884 }
881 SET_realIndex_AND_dir 885 SET_realIndex_AND_dir
882 if (realIndex >= (UInt32)dir->SubDirs.Size()) 886 if (realIndex >= (UInt32)dir->SubDirs.Size())
@@ -885,20 +889,20 @@ STDMETHODIMP CAgentFolder::BindToFolder(UInt32 index, IFolderFolder **resultFold
885 COM_TRY_END 889 COM_TRY_END
886} 890}
887 891
888STDMETHODIMP CAgentFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) 892Z7_COM7F_IMF(CAgentFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder))
889{ 893{
890 COM_TRY_BEGIN 894 COM_TRY_BEGIN
891 if (_proxy2) 895 if (_proxy2)
892 { 896 {
893 int index = _proxy2->FindItem(_proxyDirIndex, name, true); 897 const int index = _proxy2->FindItem(_proxyDirIndex, name, true);
894 if (index == -1) 898 if (index == -1)
895 return E_INVALIDARG; 899 return E_INVALIDARG;
896 return BindToFolder_Internal(_proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]].DirIndex, resultFolder); 900 return BindToFolder_Internal((unsigned)_proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]].DirIndex, resultFolder);
897 } 901 }
898 int index = _proxy->FindSubDir(_proxyDirIndex, name); 902 const int index = _proxy->FindSubDir(_proxyDirIndex, name);
899 if (index == -1) 903 if (index == -1)
900 return E_INVALIDARG; 904 return E_INVALIDARG;
901 return BindToFolder_Internal(index, resultFolder); 905 return BindToFolder_Internal((unsigned)index, resultFolder);
902 COM_TRY_END 906 COM_TRY_END
903} 907}
904 908
@@ -933,7 +937,7 @@ HRESULT CAgentFolder::BindToAltStreams_Internal(unsigned proxyDirIndex, IFolderF
933 return S_OK; 937 return S_OK;
934} 938}
935 939
936STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **resultFolder) 940Z7_COM7F_IMF(CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **resultFolder))
937{ 941{
938 COM_TRY_BEGIN 942 COM_TRY_BEGIN
939 943
@@ -958,11 +962,11 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **result
958 } 962 }
959 else 963 else
960 { 964 {
961 unsigned arcIndex = _proxy2->Dirs[_proxyDirIndex].ArcIndex; 965 const unsigned arcIndex = (unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex;
962 const CProxyFile2 &item = _proxy2->Files[arcIndex]; 966 const CProxyFile2 &item = _proxy2->Files[arcIndex];
963 if (item.AltDirIndex == -1) 967 if (item.AltDirIndex == -1)
964 return S_OK; 968 return S_OK;
965 altDirIndex = item.AltDirIndex; 969 altDirIndex = (unsigned)item.AltDirIndex;
966 // parentFolder = _parentFolder; 970 // parentFolder = _parentFolder;
967 } 971 }
968 972
@@ -974,17 +978,17 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(UInt32 index, IFolderFolder **result
974 } 978 }
975 979
976 SET_realIndex_AND_dir_2 980 SET_realIndex_AND_dir_2
977 unsigned arcIndex = dir->Items[realIndex]; 981 const unsigned arcIndex = dir->Items[realIndex];
978 const CProxyFile2 &item = _proxy2->Files[arcIndex]; 982 const CProxyFile2 &item = _proxy2->Files[arcIndex];
979 if (item.AltDirIndex == -1) 983 if (item.AltDirIndex == -1)
980 return S_OK; 984 return S_OK;
981 return BindToAltStreams_Internal(item.AltDirIndex, resultFolder); 985 return BindToAltStreams_Internal((unsigned)item.AltDirIndex, resultFolder);
982 } 986 }
983 987
984 COM_TRY_END 988 COM_TRY_END
985} 989}
986 990
987STDMETHODIMP CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder) 991Z7_COM7F_IMF(CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder))
988{ 992{
989 COM_TRY_BEGIN 993 COM_TRY_BEGIN
990 994
@@ -1006,14 +1010,14 @@ STDMETHODIMP CAgentFolder::BindToAltStreams(const wchar_t *name, IFolderFolder *
1006 const CProxyFile2 &file = _proxy2->Files[dir.Items[i]]; 1010 const CProxyFile2 &file = _proxy2->Files[dir.Items[i]];
1007 if (file.AltDirIndex != -1) 1011 if (file.AltDirIndex != -1)
1008 if (CompareFileNames(file.Name, name) == 0) 1012 if (CompareFileNames(file.Name, name) == 0)
1009 return BindToAltStreams_Internal(file.AltDirIndex, resultFolder); 1013 return BindToAltStreams_Internal((unsigned)file.AltDirIndex, resultFolder);
1010 } 1014 }
1011 return E_INVALIDARG; 1015 return E_INVALIDARG;
1012 } 1016 }
1013 COM_TRY_END 1017 COM_TRY_END
1014} 1018}
1015 1019
1016STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupported) 1020Z7_COM7F_IMF(CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupported))
1017{ 1021{
1018 *isSupported = BoolToInt(false); 1022 *isSupported = BoolToInt(false);
1019 1023
@@ -1032,7 +1036,7 @@ STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupport
1032 *isSupported = BoolToInt(true); 1036 *isSupported = BoolToInt(true);
1033 return S_OK; 1037 return S_OK;
1034 } 1038 }
1035 arcIndex = _proxy2->Dirs[_proxyDirIndex].ArcIndex; 1039 arcIndex = (unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex;
1036 } 1040 }
1037 else 1041 else
1038 { 1042 {
@@ -1046,7 +1050,7 @@ STDMETHODIMP CAgentFolder::AreAltStreamsSupported(UInt32 index, Int32 *isSupport
1046} 1050}
1047 1051
1048 1052
1049STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder) 1053Z7_COM7F_IMF(CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder))
1050{ 1054{
1051 COM_TRY_BEGIN 1055 COM_TRY_BEGIN
1052 /* 1056 /*
@@ -1071,15 +1075,15 @@ STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder)
1071 if (parentIndex == -1) 1075 if (parentIndex == -1)
1072 proxyDirIndex = k_Proxy2_RootDirIndex; 1076 proxyDirIndex = k_Proxy2_RootDirIndex;
1073 else 1077 else
1074 proxyDirIndex = _proxy2->Files[(unsigned)parentIndex].DirIndex; 1078 proxyDirIndex = (unsigned)_proxy2->Files[(unsigned)parentIndex].DirIndex;
1075 } 1079 }
1076 } 1080 }
1077 else 1081 else
1078 { 1082 {
1079 int parent = _proxy->Dirs[_proxyDirIndex].ParentDir; 1083 const int parent = _proxy->Dirs[_proxyDirIndex].ParentDir;
1080 if (parent == -1) 1084 if (parent == -1)
1081 return S_OK; 1085 return S_OK;
1082 proxyDirIndex = parent; 1086 proxyDirIndex = (unsigned)parent;
1083 } 1087 }
1084 1088
1085 CAgentFolder *folderSpec = new CAgentFolder; 1089 CAgentFolder *folderSpec = new CAgentFolder;
@@ -1091,10 +1095,11 @@ STDMETHODIMP CAgentFolder::BindToParentFolder(IFolderFolder **resultFolder)
1091 COM_TRY_END 1095 COM_TRY_END
1092} 1096}
1093 1097
1094STDMETHODIMP CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream) 1098Z7_COM7F_IMF(CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream))
1095{ 1099{
1096 CMyComPtr<IInArchiveGetStream> getStream; 1100 Z7_DECL_CMyComPtr_QI_FROM(
1097 _agentSpec->GetArchive()->QueryInterface(IID_IInArchiveGetStream, (void **)&getStream); 1101 IInArchiveGetStream,
1102 getStream, _agentSpec->GetArchive())
1098 if (!getStream) 1103 if (!getStream)
1099 return S_OK; 1104 return S_OK;
1100 1105
@@ -1113,7 +1118,7 @@ STDMETHODIMP CAgentFolder::GetStream(UInt32 index, ISequentialInStream **stream)
1113 const CProxyDir &item = _proxy->Dirs[dir->SubDirs[realIndex]]; 1118 const CProxyDir &item = _proxy->Dirs[dir->SubDirs[realIndex]];
1114 if (!item.IsLeaf()) 1119 if (!item.IsLeaf())
1115 return S_OK; 1120 return S_OK;
1116 arcIndex = item.ArcIndex; 1121 arcIndex = (unsigned)item.ArcIndex;
1117 } 1122 }
1118 else 1123 else
1119 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; 1124 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()];
@@ -1139,11 +1144,11 @@ struct CArchiveItemPropertyTemp
1139 VARTYPE Type; 1144 VARTYPE Type;
1140}; 1145};
1141 1146
1142STDMETHODIMP CAgentFolder::GetNumberOfProperties(UInt32 *numProps) 1147Z7_COM7F_IMF(CAgentFolder::GetNumberOfProperties(UInt32 *numProps))
1143{ 1148{
1144 COM_TRY_BEGIN 1149 COM_TRY_BEGIN
1145 RINOK(_agentSpec->GetArchive()->GetNumberOfProperties(numProps)); 1150 RINOK(_agentSpec->GetArchive()->GetNumberOfProperties(numProps))
1146 *numProps += ARRAY_SIZE(kProps); 1151 *numProps += Z7_ARRAY_SIZE(kProps);
1147 if (!_flatMode) 1152 if (!_flatMode)
1148 (*numProps)--; 1153 (*numProps)--;
1149 /* 1154 /*
@@ -1164,7 +1169,7 @@ STDMETHODIMP CAgentFolder::GetNumberOfProperties(UInt32 *numProps)
1164 COM_TRY_END 1169 COM_TRY_END
1165} 1170}
1166 1171
1167STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) 1172Z7_COM7F_IMF(CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType))
1168{ 1173{
1169 COM_TRY_BEGIN 1174 COM_TRY_BEGIN
1170 UInt32 numProps; 1175 UInt32 numProps;
@@ -1182,7 +1187,7 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro
1182 { 1187 {
1183 *propID = kpidName; 1188 *propID = kpidName;
1184 *varType = VT_BSTR; 1189 *varType = VT_BSTR;
1185 *name = 0; 1190 *name = NULL;
1186 return S_OK; 1191 return S_OK;
1187 } 1192 }
1188 index--; 1193 index--;
@@ -1190,7 +1195,7 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro
1190 1195
1191 if (index < numProps) 1196 if (index < numProps)
1192 { 1197 {
1193 RINOK(_agentSpec->GetArchive()->GetPropertyInfo(index, name, propID, varType)); 1198 RINOK(_agentSpec->GetArchive()->GetPropertyInfo(index, name, propID, varType))
1194 if (*propID == kpidPath) 1199 if (*propID == kpidPath)
1195 *propID = kpidName; 1200 *propID = kpidName;
1196 } 1201 }
@@ -1206,7 +1211,7 @@ STDMETHODIMP CAgentFolder::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *pro
1206 */ 1211 */
1207 *propID = kProps[index]; 1212 *propID = kProps[index];
1208 *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; 1213 *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID];
1209 *name = 0; 1214 *name = NULL;
1210 } 1215 }
1211 return S_OK; 1216 return S_OK;
1212 COM_TRY_END 1217 COM_TRY_END
@@ -1221,7 +1226,7 @@ static const PROPID kFolderProps[] =
1221 kpidCRC 1226 kpidCRC
1222}; 1227};
1223 1228
1224STDMETHODIMP CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 1229Z7_COM7F_IMF(CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value))
1225{ 1230{
1226 COM_TRY_BEGIN 1231 COM_TRY_BEGIN
1227 1232
@@ -1284,21 +1289,23 @@ STDMETHODIMP CAgentFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)
1284 COM_TRY_END 1289 COM_TRY_END
1285} 1290}
1286 1291
1287STDMETHODIMP CAgentFolder::GetNumberOfFolderProperties(UInt32 *numProps) 1292Z7_COM7F_IMF(CAgentFolder::GetNumberOfFolderProperties(UInt32 *numProps))
1288{ 1293{
1289 *numProps = ARRAY_SIZE(kFolderProps); 1294 *numProps = Z7_ARRAY_SIZE(kFolderProps);
1290 return S_OK; 1295 return S_OK;
1291} 1296}
1292 1297
1293STDMETHODIMP CAgentFolder::GetFolderPropertyInfo IMP_IFolderFolder_GetProp(kFolderProps) 1298IMP_IFolderFolder_GetProp(
1299 CAgentFolder::GetFolderPropertyInfo,
1300 kFolderProps)
1294 1301
1295STDMETHODIMP CAgentFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */) 1302Z7_COM7F_IMF(CAgentFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */))
1296{ 1303{
1297 return E_FAIL; 1304 return E_FAIL;
1298} 1305}
1299 1306
1300 1307
1301STDMETHODIMP CAgentFolder::GetNumRawProps(UInt32 *numProps) 1308Z7_COM7F_IMF(CAgentFolder::GetNumRawProps(UInt32 *numProps))
1302{ 1309{
1303 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); 1310 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps();
1304 if (rawProps) 1311 if (rawProps)
@@ -1307,7 +1314,7 @@ STDMETHODIMP CAgentFolder::GetNumRawProps(UInt32 *numProps)
1307 return S_OK; 1314 return S_OK;
1308} 1315}
1309 1316
1310STDMETHODIMP CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 1317Z7_COM7F_IMF(CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
1311{ 1318{
1312 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); 1319 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps();
1313 if (rawProps) 1320 if (rawProps)
@@ -1315,7 +1322,7 @@ STDMETHODIMP CAgentFolder::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *prop
1315 return E_FAIL; 1322 return E_FAIL;
1316} 1323}
1317 1324
1318STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 1325Z7_COM7F_IMF(CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
1319{ 1326{
1320 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps(); 1327 IArchiveGetRawProps *rawProps = _agentSpec->_archiveLink.GetArchiveGetRawProps();
1321 if (rawProps) 1328 if (rawProps)
@@ -1339,7 +1346,7 @@ STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **
1339 *propType = 0; 1346 *propType = 0;
1340 return S_OK; 1347 return S_OK;
1341 } 1348 }
1342 arcIndex = item.ArcIndex; 1349 arcIndex = (unsigned)item.ArcIndex;
1343 } 1350 }
1344 else 1351 else
1345 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; 1352 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()];
@@ -1352,29 +1359,27 @@ STDMETHODIMP CAgentFolder::GetRawProp(UInt32 index, PROPID propID, const void **
1352 return S_OK; 1359 return S_OK;
1353} 1360}
1354 1361
1355STDMETHODIMP CAgentFolder::GetFolderArcProps(IFolderArcProps **object) 1362Z7_COM7F_IMF(CAgentFolder::GetFolderArcProps(IFolderArcProps **object))
1356{ 1363{
1357 CMyComPtr<IFolderArcProps> temp = _agentSpec; 1364 CMyComPtr<IFolderArcProps> temp = _agentSpec;
1358 *object = temp.Detach(); 1365 *object = temp.Detach();
1359 return S_OK; 1366 return S_OK;
1360} 1367}
1361 1368
1362#ifdef NEW_FOLDER_INTERFACE
1363 1369
1364STDMETHODIMP CAgentFolder::SetFlatMode(Int32 flatMode) 1370Z7_COM7F_IMF(CAgentFolder::SetFlatMode(Int32 flatMode))
1365{ 1371{
1366 _flatMode = IntToBool(flatMode); 1372 _flatMode = IntToBool(flatMode);
1367 return S_OK; 1373 return S_OK;
1368} 1374}
1369 1375
1370#endif
1371 1376
1372int CAgentFolder::GetRealIndex(unsigned index) const 1377int CAgentFolder::GetRealIndex(unsigned index) const
1373{ 1378{
1374 if (!_flatMode) 1379 if (!_flatMode)
1375 { 1380 {
1376 if (_proxy2) 1381 if (_proxy2)
1377 return _proxy2->GetRealIndex(_proxyDirIndex, index); 1382 return (int)_proxy2->GetRealIndex(_proxyDirIndex, index);
1378 else 1383 else
1379 return _proxy->GetRealIndex(_proxyDirIndex, index); 1384 return _proxy->GetRealIndex(_proxyDirIndex, index);
1380 } 1385 }
@@ -1383,12 +1388,12 @@ int CAgentFolder::GetRealIndex(unsigned index) const
1383 if (_proxy2) 1388 if (_proxy2)
1384 { 1389 {
1385 const CProxyDir2 *dir = &_proxy2->Dirs[item.DirIndex]; 1390 const CProxyDir2 *dir = &_proxy2->Dirs[item.DirIndex];
1386 return dir->Items[item.Index]; 1391 return (int)dir->Items[item.Index];
1387 } 1392 }
1388 else 1393 else
1389 { 1394 {
1390 const CProxyDir *dir = &_proxy->Dirs[item.DirIndex]; 1395 const CProxyDir *dir = &_proxy->Dirs[item.DirIndex];
1391 unsigned realIndex = item.Index; 1396 const unsigned realIndex = item.Index;
1392 if (realIndex < dir->SubDirs.Size()) 1397 if (realIndex < dir->SubDirs.Size())
1393 { 1398 {
1394 const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]]; 1399 const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]];
@@ -1396,7 +1401,7 @@ int CAgentFolder::GetRealIndex(unsigned index) const
1396 return -1; 1401 return -1;
1397 return f.ArcIndex; 1402 return f.ArcIndex;
1398 } 1403 }
1399 return dir->SubFiles[realIndex - dir->SubDirs.Size()]; 1404 return (int)dir->SubFiles[realIndex - dir->SubDirs.Size()];
1400 } 1405 }
1401 } 1406 }
1402} 1407}
@@ -1437,7 +1442,7 @@ void CAgentFolder::GetRealIndices(const UInt32 *indices, UInt32 numItems, bool i
1437 const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]]; 1442 const CProxyDir &f = _proxy->Dirs[dir->SubDirs[realIndex]];
1438 if (!f.IsLeaf()) 1443 if (!f.IsLeaf())
1439 continue; 1444 continue;
1440 arcIndex = f.ArcIndex; 1445 arcIndex = (unsigned)f.ArcIndex;
1441 } 1446 }
1442 else 1447 else
1443 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()]; 1448 arcIndex = dir->SubFiles[realIndex - dir->SubDirs.Size()];
@@ -1448,7 +1453,7 @@ void CAgentFolder::GetRealIndices(const UInt32 *indices, UInt32 numItems, bool i
1448 HeapSort(&realIndices.Front(), realIndices.Size()); 1453 HeapSort(&realIndices.Front(), realIndices.Size());
1449} 1454}
1450 1455
1451STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices, 1456Z7_COM7F_IMF(CAgentFolder::Extract(const UInt32 *indices,
1452 UInt32 numItems, 1457 UInt32 numItems,
1453 Int32 includeAltStreams, 1458 Int32 includeAltStreams,
1454 Int32 replaceAltStreamColon, 1459 Int32 replaceAltStreamColon,
@@ -1456,7 +1461,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices,
1456 NExtract::NOverwriteMode::EEnum overwriteMode, 1461 NExtract::NOverwriteMode::EEnum overwriteMode,
1457 const wchar_t *path, 1462 const wchar_t *path,
1458 Int32 testMode, 1463 Int32 testMode,
1459 IFolderArchiveExtractCallback *extractCallback2) 1464 IFolderArchiveExtractCallback *extractCallback2))
1460{ 1465{
1461 COM_TRY_BEGIN 1466 COM_TRY_BEGIN
1462 1467
@@ -1492,6 +1497,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices,
1492 { 1497 {
1493 pathU = us2fs(path); 1498 pathU = us2fs(path);
1494 if (!pathU.IsEmpty()) 1499 if (!pathU.IsEmpty())
1500 if (!NFile::NName::IsAltStreamPrefixWithColon(pathU))
1495 { 1501 {
1496 NFile::NName::NormalizeDirPathPrefix(pathU); 1502 NFile::NName::NormalizeDirPathPrefix(pathU);
1497 NFile::NDir::CreateComplexDir(pathU); 1503 NFile::NDir::CreateComplexDir(pathU);
@@ -1524,7 +1530,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices,
1524 (UInt64)(Int64)-1); 1530 (UInt64)(Int64)-1);
1525 1531
1526 if (_proxy2) 1532 if (_proxy2)
1527 extractCallbackSpec->SetBaseParentFolderIndex(_proxy2->Dirs[_proxyDirIndex].ArcIndex); 1533 extractCallbackSpec->SetBaseParentFolderIndex((unsigned)_proxy2->Dirs[_proxyDirIndex].ArcIndex);
1528 1534
1529 // do we need another base folder for subfolders ? 1535 // do we need another base folder for subfolders ?
1530 extractCallbackSpec->DirPathPrefix_for_HashFiles = _agentSpec->_hashBaseFolderPrefix; 1536 extractCallbackSpec->DirPathPrefix_for_HashFiles = _agentSpec->_hashBaseFolderPrefix;
@@ -1538,7 +1544,7 @@ STDMETHODIMP CAgentFolder::Extract(const UInt32 *indices,
1538 1544
1539 if (!testMode) 1545 if (!testMode)
1540 { 1546 {
1541 RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices)); 1547 RINOK(extractCallbackSpec->PrepareHardLinks(&realIndices))
1542 } 1548 }
1543 1549
1544 #endif 1550 #endif
@@ -1592,12 +1598,12 @@ bool CAgent::CanUpdate() const
1592 return true; 1598 return true;
1593} 1599}
1594 1600
1595STDMETHODIMP CAgent::Open( 1601Z7_COM7F_IMF(CAgent::Open(
1596 IInStream *inStream, 1602 IInStream *inStream,
1597 const wchar_t *filePath, 1603 const wchar_t *filePath,
1598 const wchar_t *arcFormat, 1604 const wchar_t *arcFormat,
1599 BSTR *archiveType, 1605 BSTR *archiveType,
1600 IArchiveOpenCallback *openArchiveCallback) 1606 IArchiveOpenCallback *openArchiveCallback))
1601{ 1607{
1602 COM_TRY_BEGIN 1608 COM_TRY_BEGIN
1603 _archiveFilePath = filePath; 1609 _archiveFilePath = filePath;
@@ -1609,7 +1615,7 @@ STDMETHODIMP CAgent::Open(
1609 if (!inStream) 1615 if (!inStream)
1610 { 1616 {
1611 if (!fi.Find(us2fs(_archiveFilePath))) 1617 if (!fi.Find(us2fs(_archiveFilePath)))
1612 return ::GetLastError(); 1618 return GetLastError_noZero_HRESULT();
1613 if (fi.IsDir()) 1619 if (fi.IsDir())
1614 return E_FAIL; 1620 return E_FAIL;
1615 _attrib = fi.Attrib; 1621 _attrib = fi.Attrib;
@@ -1623,7 +1629,7 @@ STDMETHODIMP CAgent::Open(
1623 } 1629 }
1624 CArcInfoEx archiverInfo0, archiverInfo1; 1630 CArcInfoEx archiverInfo0, archiverInfo1;
1625 1631
1626 RINOK(LoadGlobalCodecs()); 1632 RINOK(LoadGlobalCodecs())
1627 1633
1628 CObjectVector<COpenType> types; 1634 CObjectVector<COpenType> types;
1629 if (!ParseOpenTypes(*g_CodecsObj, arcFormat, types)) 1635 if (!ParseOpenTypes(*g_CodecsObj, arcFormat, types))
@@ -1665,7 +1671,7 @@ STDMETHODIMP CAgent::Open(
1665 ArchiveType = GetTypeOfArc(arc); 1671 ArchiveType = GetTypeOfArc(arc);
1666 if (archiveType) 1672 if (archiveType)
1667 { 1673 {
1668 RINOK(StringToBstr(ArchiveType, archiveType)); 1674 RINOK(StringToBstr(ArchiveType, archiveType))
1669 } 1675 }
1670 1676
1671 if (arc.IsHashHandler(options)) 1677 if (arc.IsHashHandler(options))
@@ -1678,7 +1684,7 @@ STDMETHODIMP CAgent::Open(
1678} 1684}
1679 1685
1680 1686
1681STDMETHODIMP CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback) 1687Z7_COM7F_IMF(CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback))
1682{ 1688{
1683 COM_TRY_BEGIN 1689 COM_TRY_BEGIN
1684 if (_proxy2) 1690 if (_proxy2)
@@ -1704,12 +1710,12 @@ STDMETHODIMP CAgent::ReOpen(IArchiveOpenCallback *openArchiveCallback)
1704 options.filePath = _archiveFilePath; 1710 options.filePath = _archiveFilePath;
1705 options.callback = openArchiveCallback; 1711 options.callback = openArchiveCallback;
1706 1712
1707 RINOK(_archiveLink.ReOpen(options)); 1713 RINOK(_archiveLink.ReOpen(options))
1708 return ReadItems(); 1714 return ReadItems();
1709 COM_TRY_END 1715 COM_TRY_END
1710} 1716}
1711 1717
1712STDMETHODIMP CAgent::Close() 1718Z7_COM7F_IMF(CAgent::Close())
1713{ 1719{
1714 COM_TRY_BEGIN 1720 COM_TRY_BEGIN
1715 return _archiveLink.Close(); 1721 return _archiveLink.Close();
@@ -1717,7 +1723,7 @@ STDMETHODIMP CAgent::Close()
1717} 1723}
1718 1724
1719/* 1725/*
1720STDMETHODIMP CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties) 1726Z7_COM7F_IMF(CAgent::EnumProperties(IEnumSTATPROPSTG **EnumProperties)
1721{ 1727{
1722 return _archive->EnumProperties(EnumProperties); 1728 return _archive->EnumProperties(EnumProperties);
1723} 1729}
@@ -1748,7 +1754,7 @@ HRESULT CAgent::ReadItems()
1748 CMyComBSTR name; 1754 CMyComBSTR name;
1749 PROPID propID; 1755 PROPID propID;
1750 VARTYPE varType; 1756 VARTYPE varType;
1751 RINOK(arc.Archive->GetPropertyInfo(i, &name, &propID, &varType)); 1757 RINOK(arc.Archive->GetPropertyInfo(i, &name, &propID, &varType))
1752 if (propID == kpidPath) 1758 if (propID == kpidPath)
1753 ThereIsPathProp = true; 1759 ThereIsPathProp = true;
1754 /* 1760 /*
@@ -1763,12 +1769,12 @@ HRESULT CAgent::ReadItems()
1763 return _proxy->Load(GetArc(), NULL); 1769 return _proxy->Load(GetArc(), NULL);
1764} 1770}
1765 1771
1766STDMETHODIMP CAgent::BindToRootFolder(IFolderFolder **resultFolder) 1772Z7_COM7F_IMF(CAgent::BindToRootFolder(IFolderFolder **resultFolder))
1767{ 1773{
1768 COM_TRY_BEGIN 1774 COM_TRY_BEGIN
1769 if (!_archiveLink.Arcs.IsEmpty()) 1775 if (!_archiveLink.Arcs.IsEmpty())
1770 { 1776 {
1771 RINOK(ReadItems()); 1777 RINOK(ReadItems())
1772 } 1778 }
1773 CAgentFolder *folderSpec = new CAgentFolder; 1779 CAgentFolder *folderSpec = new CAgentFolder;
1774 CMyComPtr<IFolderFolder> rootFolder = folderSpec; 1780 CMyComPtr<IFolderFolder> rootFolder = folderSpec;
@@ -1778,12 +1784,12 @@ STDMETHODIMP CAgent::BindToRootFolder(IFolderFolder **resultFolder)
1778 COM_TRY_END 1784 COM_TRY_END
1779} 1785}
1780 1786
1781STDMETHODIMP CAgent::Extract( 1787Z7_COM7F_IMF(CAgent::Extract(
1782 NExtract::NPathMode::EEnum pathMode, 1788 NExtract::NPathMode::EEnum pathMode,
1783 NExtract::NOverwriteMode::EEnum overwriteMode, 1789 NExtract::NOverwriteMode::EEnum overwriteMode,
1784 const wchar_t *path, 1790 const wchar_t *path,
1785 Int32 testMode, 1791 Int32 testMode,
1786 IFolderArchiveExtractCallback *extractCallback2) 1792 IFolderArchiveExtractCallback *extractCallback2))
1787{ 1793{
1788 COM_TRY_BEGIN 1794 COM_TRY_BEGIN
1789 1795
@@ -1820,40 +1826,40 @@ STDMETHODIMP CAgent::Extract(
1820 1826
1821 if (!testMode) 1827 if (!testMode)
1822 { 1828 {
1823 RINOK(extractCallbackSpec->PrepareHardLinks(NULL)); // NULL means all items 1829 RINOK(extractCallbackSpec->PrepareHardLinks(NULL)) // NULL means all items
1824 } 1830 }
1825 1831
1826 #endif 1832 #endif
1827 1833
1828 return GetArchive()->Extract(0, (UInt32)(Int32)-1, testMode, extractCallback); 1834 return GetArchive()->Extract(NULL, (UInt32)(Int32)-1, testMode, extractCallback);
1829 COM_TRY_END 1835 COM_TRY_END
1830} 1836}
1831 1837
1832STDMETHODIMP CAgent::GetNumberOfProperties(UInt32 *numProps) 1838Z7_COM7F_IMF(CAgent::GetNumberOfProperties(UInt32 *numProps))
1833{ 1839{
1834 COM_TRY_BEGIN 1840 COM_TRY_BEGIN
1835 return GetArchive()->GetNumberOfProperties(numProps); 1841 return GetArchive()->GetNumberOfProperties(numProps);
1836 COM_TRY_END 1842 COM_TRY_END
1837} 1843}
1838 1844
1839STDMETHODIMP CAgent::GetPropertyInfo(UInt32 index, 1845Z7_COM7F_IMF(CAgent::GetPropertyInfo(UInt32 index,
1840 BSTR *name, PROPID *propID, VARTYPE *varType) 1846 BSTR *name, PROPID *propID, VARTYPE *varType))
1841{ 1847{
1842 COM_TRY_BEGIN 1848 COM_TRY_BEGIN
1843 RINOK(GetArchive()->GetPropertyInfo(index, name, propID, varType)); 1849 RINOK(GetArchive()->GetPropertyInfo(index, name, propID, varType))
1844 if (*propID == kpidPath) 1850 if (*propID == kpidPath)
1845 *propID = kpidName; 1851 *propID = kpidName;
1846 return S_OK; 1852 return S_OK;
1847 COM_TRY_END 1853 COM_TRY_END
1848} 1854}
1849 1855
1850STDMETHODIMP CAgent::GetArcNumLevels(UInt32 *numLevels) 1856Z7_COM7F_IMF(CAgent::GetArcNumLevels(UInt32 *numLevels))
1851{ 1857{
1852 *numLevels = _archiveLink.Arcs.Size(); 1858 *numLevels = _archiveLink.Arcs.Size();
1853 return S_OK; 1859 return S_OK;
1854} 1860}
1855 1861
1856STDMETHODIMP CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value) 1862Z7_COM7F_IMF(CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value))
1857{ 1863{
1858 COM_TRY_BEGIN 1864 COM_TRY_BEGIN
1859 NWindows::NCOM::CPropVariant prop; 1865 NWindows::NCOM::CPropVariant prop;
@@ -1933,28 +1939,28 @@ STDMETHODIMP CAgent::GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value)
1933 COM_TRY_END 1939 COM_TRY_END
1934} 1940}
1935 1941
1936STDMETHODIMP CAgent::GetArcNumProps(UInt32 level, UInt32 *numProps) 1942Z7_COM7F_IMF(CAgent::GetArcNumProps(UInt32 level, UInt32 *numProps))
1937{ 1943{
1938 return _archiveLink.Arcs[level].Archive->GetNumberOfArchiveProperties(numProps); 1944 return _archiveLink.Arcs[level].Archive->GetNumberOfArchiveProperties(numProps);
1939} 1945}
1940 1946
1941STDMETHODIMP CAgent::GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) 1947Z7_COM7F_IMF(CAgent::GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType))
1942{ 1948{
1943 return _archiveLink.Arcs[level].Archive->GetArchivePropertyInfo(index, name, propID, varType); 1949 return _archiveLink.Arcs[level].Archive->GetArchivePropertyInfo(index, name, propID, varType);
1944} 1950}
1945 1951
1946// MainItemProperty 1952// MainItemProperty
1947STDMETHODIMP CAgent::GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value) 1953Z7_COM7F_IMF(CAgent::GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value))
1948{ 1954{
1949 return _archiveLink.Arcs[level - 1].Archive->GetProperty(_archiveLink.Arcs[level].SubfileIndex, propID, value); 1955 return _archiveLink.Arcs[level - 1].Archive->GetProperty(_archiveLink.Arcs[level].SubfileIndex, propID, value);
1950} 1956}
1951 1957
1952STDMETHODIMP CAgent::GetArcNumProps2(UInt32 level, UInt32 *numProps) 1958Z7_COM7F_IMF(CAgent::GetArcNumProps2(UInt32 level, UInt32 *numProps))
1953{ 1959{
1954 return _archiveLink.Arcs[level - 1].Archive->GetNumberOfProperties(numProps); 1960 return _archiveLink.Arcs[level - 1].Archive->GetNumberOfProperties(numProps);
1955} 1961}
1956 1962
1957STDMETHODIMP CAgent::GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) 1963Z7_COM7F_IMF(CAgent::GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType))
1958{ 1964{
1959 return _archiveLink.Arcs[level - 1].Archive->GetPropertyInfo(index, name, propID, varType); 1965 return _archiveLink.Arcs[level - 1].Archive->GetPropertyInfo(index, name, propID, varType);
1960} 1966}
diff --git a/CPP/7zip/UI/Agent/Agent.h b/CPP/7zip/UI/Agent/Agent.h
index 8e8a4c7..ea81aa8 100644
--- a/CPP/7zip/UI/Agent/Agent.h
+++ b/CPP/7zip/UI/Agent/Agent.h
@@ -1,19 +1,17 @@
1// Agent/Agent.h 1// Agent/Agent.h
2 2
3#ifndef __AGENT_AGENT_H 3#ifndef ZIP7_INC_AGENT_AGENT_H
4#define __AGENT_AGENT_H 4#define ZIP7_INC_AGENT_AGENT_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../../../Windows/PropVariant.h" 8#include "../../../Windows/PropVariant.h"
9 9
10#include "../Common/LoadCodecs.h"
10#include "../Common/OpenArchive.h" 11#include "../Common/OpenArchive.h"
11#include "../Common/UpdateAction.h" 12#include "../Common/UpdateAction.h"
12 13
13#ifdef NEW_FOLDER_INTERFACE
14#include "../FileManager/IFolder.h" 14#include "../FileManager/IFolder.h"
15#include "../Common/LoadCodecs.h"
16#endif
17 15
18#include "AgentProxy.h" 16#include "AgentProxy.h"
19#include "IFolderArchive.h" 17#include "IFolderArchive.h"
@@ -24,10 +22,13 @@ void FreeGlobalCodecs();
24 22
25class CAgentFolder; 23class CAgentFolder;
26 24
27DECL_INTERFACE(IArchiveFolderInternal, 0x01, 0xC) 25Z7_PURE_INTERFACES_BEGIN
28{ 26
29 STDMETHOD(GetAgentFolder)(CAgentFolder **agentFolder) PURE; 27#define Z7_IFACEM_IArchiveFolderInternal(x) \
30}; 28 x(GetAgentFolder(CAgentFolder **agentFolder))
29Z7_IFACE_CONSTR_FOLDERARC(IArchiveFolderInternal, 0xC)
30
31Z7_PURE_INTERFACES_END
31 32
32struct CProxyItem 33struct CProxyItem
33{ 34{
@@ -47,7 +48,7 @@ enum AGENT_OP
47 AGENT_OP_Comment 48 AGENT_OP_Comment
48}; 49};
49 50
50class CAgentFolder: 51class CAgentFolder Z7_final:
51 public IFolderFolder, 52 public IFolderFolder,
52 public IFolderAltStreams, 53 public IFolderAltStreams,
53 public IFolderProperties, 54 public IFolderProperties,
@@ -59,65 +60,51 @@ class CAgentFolder:
59 public IArchiveFolderInternal, 60 public IArchiveFolderInternal,
60 public IInArchiveGetStream, 61 public IInArchiveGetStream,
61 public IFolderSetZoneIdMode, 62 public IFolderSetZoneIdMode,
62#ifdef NEW_FOLDER_INTERFACE
63 public IFolderOperations, 63 public IFolderOperations,
64 public IFolderSetFlatMode, 64 public IFolderSetFlatMode,
65#endif
66 public CMyUnknownImp 65 public CMyUnknownImp
67{ 66{
68 void LoadFolder(unsigned proxyDirIndex); 67 Z7_COM_QI_BEGIN2(IFolderFolder)
68 Z7_COM_QI_ENTRY(IFolderAltStreams)
69 Z7_COM_QI_ENTRY(IFolderProperties)
70 Z7_COM_QI_ENTRY(IArchiveGetRawProps)
71 Z7_COM_QI_ENTRY(IGetFolderArcProps)
72 Z7_COM_QI_ENTRY(IFolderCompare)
73 Z7_COM_QI_ENTRY(IFolderGetItemName)
74 Z7_COM_QI_ENTRY(IArchiveFolder)
75 Z7_COM_QI_ENTRY(IArchiveFolderInternal)
76 Z7_COM_QI_ENTRY(IInArchiveGetStream)
77 Z7_COM_QI_ENTRY(IFolderSetZoneIdMode)
78 Z7_COM_QI_ENTRY(IFolderOperations)
79 Z7_COM_QI_ENTRY(IFolderSetFlatMode)
80 Z7_COM_QI_END
81 Z7_COM_ADDREF_RELEASE
82
83 Z7_IFACE_COM7_IMP(IFolderFolder)
84 Z7_IFACE_COM7_IMP(IFolderAltStreams)
85 Z7_IFACE_COM7_IMP(IFolderProperties)
86 Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
87 Z7_IFACE_COM7_IMP(IGetFolderArcProps)
88 Z7_IFACE_COM7_IMP(IFolderCompare)
89 Z7_IFACE_COM7_IMP(IFolderGetItemName)
90 Z7_IFACE_COM7_IMP(IArchiveFolder)
91 Z7_IFACE_COM7_IMP(IArchiveFolderInternal)
92 Z7_IFACE_COM7_IMP(IInArchiveGetStream)
93 Z7_IFACE_COM7_IMP(IFolderSetZoneIdMode)
94 Z7_IFACE_COM7_IMP(IFolderOperations)
95 Z7_IFACE_COM7_IMP(IFolderSetFlatMode)
96
97 void LoadFolder(unsigned proxyDirIndex);
69public: 98public:
70
71 MY_QUERYINTERFACE_BEGIN2(IFolderFolder)
72 MY_QUERYINTERFACE_ENTRY(IFolderAltStreams)
73 MY_QUERYINTERFACE_ENTRY(IFolderProperties)
74 MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps)
75 MY_QUERYINTERFACE_ENTRY(IGetFolderArcProps)
76 MY_QUERYINTERFACE_ENTRY(IFolderCompare)
77 MY_QUERYINTERFACE_ENTRY(IFolderGetItemName)
78 MY_QUERYINTERFACE_ENTRY(IArchiveFolder)
79 MY_QUERYINTERFACE_ENTRY(IArchiveFolderInternal)
80 MY_QUERYINTERFACE_ENTRY(IInArchiveGetStream)
81 MY_QUERYINTERFACE_ENTRY(IFolderSetZoneIdMode)
82 #ifdef NEW_FOLDER_INTERFACE
83 MY_QUERYINTERFACE_ENTRY(IFolderOperations)
84 MY_QUERYINTERFACE_ENTRY(IFolderSetFlatMode)
85 #endif
86 MY_QUERYINTERFACE_END
87 MY_ADDREF_RELEASE
88
89 HRESULT BindToFolder_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder); 99 HRESULT BindToFolder_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder);
90 HRESULT BindToAltStreams_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder); 100 HRESULT BindToAltStreams_Internal(unsigned proxyDirIndex, IFolderFolder **resultFolder);
91 int GetRealIndex(unsigned index) const; 101 int GetRealIndex(unsigned index) const;
92 void GetRealIndices(const UInt32 *indices, UInt32 numItems, 102 void GetRealIndices(const UInt32 *indices, UInt32 numItems,
93 bool includeAltStreams, bool includeFolderSubItemsInFlatMode, CUIntVector &realIndices) const; 103 bool includeAltStreams, bool includeFolderSubItemsInFlatMode, CUIntVector &realIndices) const;
94 104
95 INTERFACE_IFolderSetZoneIdMode(;)
96
97 INTERFACE_FolderFolder(;)
98 INTERFACE_FolderAltStreams(;)
99 INTERFACE_FolderProperties(;)
100 INTERFACE_IArchiveGetRawProps(;)
101 INTERFACE_IFolderGetItemName(;)
102
103 STDMETHOD(GetFolderArcProps)(IFolderArcProps **object);
104 STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw);
105 int CompareItems3(UInt32 index1, UInt32 index2, PROPID propID); 105 int CompareItems3(UInt32 index1, UInt32 index2, PROPID propID);
106 int CompareItems2(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); 106 int CompareItems2(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw);
107 107
108 // IArchiveFolder
109 INTERFACE_IArchiveFolder(;)
110
111 STDMETHOD(GetAgentFolder)(CAgentFolder **agentFolder);
112
113 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
114
115 #ifdef NEW_FOLDER_INTERFACE
116 INTERFACE_FolderOperations(;)
117
118 STDMETHOD(SetFlatMode)(Int32 flatMode);
119 #endif
120
121 CAgentFolder(): 108 CAgentFolder():
122 _proxyDirIndex(0), 109 _proxyDirIndex(0),
123 _isAltStreamFolder(false), 110 _isAltStreamFolder(false),
@@ -173,32 +160,32 @@ public:
173 NExtract::NZoneIdMode::EEnum _zoneMode; 160 NExtract::NZoneIdMode::EEnum _zoneMode;
174}; 161};
175 162
176class CAgent: 163class CAgent Z7_final:
177 public IInFolderArchive, 164 public IInFolderArchive,
178 public IFolderArcProps, 165 public IFolderArcProps,
179 #ifndef EXTRACT_ONLY 166 #ifndef Z7_EXTRACT_ONLY
180 public IOutFolderArchive, 167 public IOutFolderArchive,
181 public ISetProperties, 168 public ISetProperties,
182 #endif 169 #endif
183 public CMyUnknownImp 170 public CMyUnknownImp
184{ 171{
185public: 172 Z7_COM_QI_BEGIN2(IInFolderArchive)
173 Z7_COM_QI_ENTRY(IFolderArcProps)
174 #ifndef Z7_EXTRACT_ONLY
175 Z7_COM_QI_ENTRY(IOutFolderArchive)
176 Z7_COM_QI_ENTRY(ISetProperties)
177 #endif
178 Z7_COM_QI_END
179 Z7_COM_ADDREF_RELEASE
186 180
187 MY_QUERYINTERFACE_BEGIN2(IInFolderArchive) 181 Z7_IFACE_COM7_IMP(IInFolderArchive)
188 MY_QUERYINTERFACE_ENTRY(IFolderArcProps) 182 Z7_IFACE_COM7_IMP(IFolderArcProps)
189 #ifndef EXTRACT_ONLY
190 MY_QUERYINTERFACE_ENTRY(IOutFolderArchive)
191 MY_QUERYINTERFACE_ENTRY(ISetProperties)
192 #endif
193 MY_QUERYINTERFACE_END
194 MY_ADDREF_RELEASE
195 183
196 INTERFACE_IInFolderArchive(;) 184 #ifndef Z7_EXTRACT_ONLY
197 INTERFACE_IFolderArcProps(;) 185 Z7_IFACE_COM7_IMP(ISetProperties)
198
199 #ifndef EXTRACT_ONLY
200 INTERFACE_IOutFolderArchive(;)
201 186
187public:
188 Z7_IFACE_COM7_IMP(IOutFolderArchive)
202 HRESULT CommonUpdate(ISequentialOutStream *outArchiveStream, 189 HRESULT CommonUpdate(ISequentialOutStream *outArchiveStream,
203 unsigned numUpdateItems, IArchiveUpdateCallback *updateCallback); 190 unsigned numUpdateItems, IArchiveUpdateCallback *updateCallback);
204 191
@@ -216,15 +203,11 @@ public:
216 HRESULT UpdateOneFile(ISequentialOutStream *outArchiveStream, 203 HRESULT UpdateOneFile(ISequentialOutStream *outArchiveStream,
217 const UInt32 *indices, UInt32 numItems, const wchar_t *diskFilePath, 204 const UInt32 *indices, UInt32 numItems, const wchar_t *diskFilePath,
218 IFolderArchiveUpdateCallback *updateCallback100); 205 IFolderArchiveUpdateCallback *updateCallback100);
206 #endif
219 207
220 // ISetProperties
221 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
222 #endif
223
224 CAgent();
225 ~CAgent();
226private: 208private:
227 HRESULT ReadItems(); 209 HRESULT ReadItems();
210
228public: 211public:
229 CProxyArc *_proxy; 212 CProxyArc *_proxy;
230 CProxyArc2 *_proxy2; 213 CProxyArc2 *_proxy2;
@@ -248,13 +231,16 @@ public:
248 bool _isHashHandler; 231 bool _isHashHandler;
249 FString _hashBaseFolderPrefix; 232 FString _hashBaseFolderPrefix;
250 233
251 #ifndef EXTRACT_ONLY 234 #ifndef Z7_EXTRACT_ONLY
252 CObjectVector<UString> m_PropNames; 235 CObjectVector<UString> m_PropNames;
253 CObjectVector<NWindows::NCOM::CPropVariant> m_PropValues; 236 CObjectVector<NWindows::NCOM::CPropVariant> m_PropValues;
254 #endif 237 #endif
238
239 CAgent();
240 ~CAgent();
255 241
256 const CArc &GetArc() const { return _archiveLink.Arcs.Back(); } 242 const CArc &GetArc() const { return _archiveLink.Arcs.Back(); }
257 IInArchive *GetArchive() const { if ( _archiveLink.Arcs.IsEmpty()) return 0; return GetArc().Archive; } 243 IInArchive *GetArchive() const { if ( _archiveLink.Arcs.IsEmpty()) return NULL; return GetArc().Archive; }
258 bool CanUpdate() const; 244 bool CanUpdate() const;
259 245
260 bool Is_Attrib_ReadOnly() const 246 bool Is_Attrib_ReadOnly() const
@@ -285,7 +271,7 @@ public:
285 UString GetErrorMessage() const 271 UString GetErrorMessage() const
286 { 272 {
287 UString s; 273 UString s;
288 for (int i = _archiveLink.Arcs.Size() - 1; i >= 0; i--) 274 for (int i = (int)_archiveLink.Arcs.Size() - 1; i >= 0; i--)
289 { 275 {
290 const CArc &arc = _archiveLink.Arcs[i]; 276 const CArc &arc = _archiveLink.Arcs[i];
291 277
@@ -326,23 +312,42 @@ public:
326 } 312 }
327 313
328 void KeepModeForNextOpen() { _archiveLink.KeepModeForNextOpen(); } 314 void KeepModeForNextOpen() { _archiveLink.KeepModeForNextOpen(); }
329
330}; 315};
331 316
332 317
333#ifdef NEW_FOLDER_INTERFACE 318// #ifdef NEW_FOLDER_INTERFACE
334 319
335class CArchiveFolderManager: 320struct CCodecIcons
336 public IFolderManager,
337 public CMyUnknownImp
338{ 321{
322 struct CIconPair
323 {
324 UString Ext;
325 int IconIndex;
326 };
327 CObjectVector<CIconPair> IconPairs;
328
329 // void Clear() { IconPairs.Clear(); }
330 void LoadIcons(HMODULE m);
331 bool FindIconIndex(const UString &ext, int &iconIndex) const;
332};
333
334
335Z7_CLASS_IMP_COM_1(
336 CArchiveFolderManager
337 , IFolderManager
338)
339 CObjectVector<CCodecIcons> CodecIconsVector;
340 CCodecIcons InternalIcons;
341 bool WasLoaded;
342
339 void LoadFormats(); 343 void LoadFormats();
340 int FindFormat(const UString &type); 344 // int FindFormat(const UString &type);
341public: 345public:
342 MY_UNKNOWN_IMP1(IFolderManager) 346 CArchiveFolderManager():
343 INTERFACE_IFolderManager(;) 347 WasLoaded(false)
348 {}
344}; 349};
345 350
346#endif 351// #endif
347 352
348#endif 353#endif
diff --git a/CPP/7zip/UI/Agent/AgentOut.cpp b/CPP/7zip/UI/Agent/AgentOut.cpp
index da8da6c..b5a25a3 100644
--- a/CPP/7zip/UI/Agent/AgentOut.cpp
+++ b/CPP/7zip/UI/Agent/AgentOut.cpp
@@ -20,7 +20,7 @@
20using namespace NWindows; 20using namespace NWindows;
21using namespace NCOM; 21using namespace NCOM;
22 22
23STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder) 23Z7_COM7F_IMF(CAgent::SetFolder(IFolderFolder *folder))
24{ 24{
25 _updatePathPrefix.Empty(); 25 _updatePathPrefix.Empty();
26 _updatePathPrefix_is_AltFolder = false; 26 _updatePathPrefix_is_AltFolder = false;
@@ -30,11 +30,12 @@ STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder)
30 return S_OK; 30 return S_OK;
31 31
32 { 32 {
33 CMyComPtr<IArchiveFolderInternal> afi; 33 Z7_DECL_CMyComPtr_QI_FROM(
34 RINOK(folder->QueryInterface(IID_IArchiveFolderInternal, (void **)&afi)); 34 IArchiveFolderInternal,
35 afi, folder)
35 if (afi) 36 if (afi)
36 { 37 {
37 RINOK(afi->GetAgentFolder(&_agentFolder)); 38 RINOK(afi->GetAgentFolder(&_agentFolder))
38 } 39 }
39 if (!_agentFolder) 40 if (!_agentFolder)
40 return E_FAIL; 41 return E_FAIL;
@@ -47,8 +48,8 @@ STDMETHODIMP CAgent::SetFolder(IFolderFolder *folder)
47 return S_OK; 48 return S_OK;
48} 49}
49 50
50STDMETHODIMP CAgent::SetFiles(const wchar_t *folderPrefix, 51Z7_COM7F_IMF(CAgent::SetFiles(const wchar_t *folderPrefix,
51 const wchar_t * const *names, UInt32 numNames) 52 const wchar_t * const *names, UInt32 numNames))
52{ 53{
53 _folderPrefix = us2fs(folderPrefix); 54 _folderPrefix = us2fs(folderPrefix);
54 _names.ClearAndReserve(numNames); 55 _names.ClearAndReserve(numNames);
@@ -69,8 +70,8 @@ static HRESULT EnumerateArchiveItems(CAgent *agent,
69 unsigned arcIndex = item.SubFiles[i]; 70 unsigned arcIndex = item.SubFiles[i];
70 const CProxyFile &fileItem = agent->_proxy->Files[arcIndex]; 71 const CProxyFile &fileItem = agent->_proxy->Files[arcIndex];
71 CArcItem ai; 72 CArcItem ai;
72 RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)); 73 RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime))
73 RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)); 74 RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined))
74 ai.IsDir = false; 75 ai.IsDir = false;
75 ai.Name = prefix + fileItem.Name; 76 ai.Name = prefix + fileItem.Name;
76 ai.Censored = true; // test it 77 ai.Censored = true; // test it
@@ -85,15 +86,15 @@ static HRESULT EnumerateArchiveItems(CAgent *agent,
85 if (dirItem.IsLeaf()) 86 if (dirItem.IsLeaf())
86 { 87 {
87 CArcItem ai; 88 CArcItem ai;
88 RINOK(agent->GetArc().GetItem_MTime(dirItem.ArcIndex, ai.MTime)); 89 RINOK(agent->GetArc().GetItem_MTime((unsigned)dirItem.ArcIndex, ai.MTime))
89 ai.IsDir = true; 90 ai.IsDir = true;
90 ai.Size_Defined = false; 91 ai.Size_Defined = false;
91 ai.Name = fullName; 92 ai.Name = fullName;
92 ai.Censored = true; // test it 93 ai.Censored = true; // test it
93 ai.IndexInServer = dirItem.ArcIndex; 94 ai.IndexInServer = (unsigned)dirItem.ArcIndex;
94 arcItems.Add(ai); 95 arcItems.Add(ai);
95 } 96 }
96 RINOK(EnumerateArchiveItems(agent, dirItem, fullName + WCHAR_PATH_SEPARATOR, arcItems)); 97 RINOK(EnumerateArchiveItems(agent, dirItem, fullName + WCHAR_PATH_SEPARATOR, arcItems))
97 } 98 }
98 99
99 return S_OK; 100 return S_OK;
@@ -113,38 +114,38 @@ static HRESULT EnumerateArchiveItems2(const CAgent *agent,
113 ai.IndexInServer = arcIndex; 114 ai.IndexInServer = arcIndex;
114 ai.Name = prefix + file.Name; 115 ai.Name = prefix + file.Name;
115 ai.Censored = true; // test it 116 ai.Censored = true; // test it
116 RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime)); 117 RINOK(agent->GetArc().GetItem_MTime(arcIndex, ai.MTime))
117 ai.IsDir = file.IsDir(); 118 ai.IsDir = file.IsDir();
118 ai.Size_Defined = false; 119 ai.Size_Defined = false;
119 ai.IsAltStream = file.IsAltStream; 120 ai.IsAltStream = file.IsAltStream;
120 if (!ai.IsDir) 121 if (!ai.IsDir)
121 { 122 {
122 RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined)); 123 RINOK(agent->GetArc().GetItem_Size(arcIndex, ai.Size, ai.Size_Defined))
123 ai.IsDir = false; 124 ai.IsDir = false;
124 } 125 }
125 arcItems.Add(ai); 126 arcItems.Add(ai);
126 127
127 if (file.AltDirIndex != -1) 128 if (file.AltDirIndex != -1)
128 { 129 {
129 RINOK(EnumerateArchiveItems2(agent, file.AltDirIndex, ai.Name + L':', arcItems)); 130 RINOK(EnumerateArchiveItems2(agent, (unsigned)file.AltDirIndex, ai.Name + L':', arcItems))
130 } 131 }
131 132
132 if (ai.IsDir) 133 if (ai.IsDir)
133 { 134 {
134 RINOK(EnumerateArchiveItems2(agent, file.DirIndex, ai.Name + WCHAR_PATH_SEPARATOR, arcItems)); 135 RINOK(EnumerateArchiveItems2(agent, (unsigned)file.DirIndex, ai.Name + WCHAR_PATH_SEPARATOR, arcItems))
135 } 136 }
136 } 137 }
137 return S_OK; 138 return S_OK;
138} 139}
139 140
140struct CAgUpCallbackImp: public IUpdateProduceCallback 141struct CAgUpCallbackImp Z7_final: public IUpdateProduceCallback
141{ 142{
142 const CObjectVector<CArcItem> *_arcItems; 143 const CObjectVector<CArcItem> *_arcItems;
143 IFolderArchiveUpdateCallback *_callback; 144 IFolderArchiveUpdateCallback *_callback;
144 145
145 CAgUpCallbackImp(const CObjectVector<CArcItem> *a, 146 CAgUpCallbackImp(const CObjectVector<CArcItem> *a,
146 IFolderArchiveUpdateCallback *callback): _arcItems(a), _callback(callback) {} 147 IFolderArchiveUpdateCallback *callback): _arcItems(a), _callback(callback) {}
147 HRESULT ShowDeleteFile(unsigned arcIndex); 148 HRESULT ShowDeleteFile(unsigned arcIndex) Z7_override;
148}; 149};
149 150
150HRESULT CAgUpCallbackImp::ShowDeleteFile(unsigned arcIndex) 151HRESULT CAgUpCallbackImp::ShowDeleteFile(unsigned arcIndex)
@@ -164,7 +165,7 @@ static void SetInArchiveInterfaces(CAgent *agent, CArchiveUpdateCallback *upd)
164 upd->ArcFileName = ExtractFileNameFromPath(arc.Path); 165 upd->ArcFileName = ExtractFileNameFromPath(arc.Path);
165} 166}
166 167
167struct CDirItemsCallback_AgentOut: public IDirItemsCallback 168struct CDirItemsCallback_AgentOut Z7_final: public IDirItemsCallback
168{ 169{
169 CMyComPtr<IFolderScanProgress> FolderScanProgress; 170 CMyComPtr<IFolderScanProgress> FolderScanProgress;
170 IFolderArchiveUpdateCallback *FolderArchiveUpdateCallback; 171 IFolderArchiveUpdateCallback *FolderArchiveUpdateCallback;
@@ -172,30 +173,28 @@ struct CDirItemsCallback_AgentOut: public IDirItemsCallback
172 173
173 CDirItemsCallback_AgentOut(): FolderArchiveUpdateCallback(NULL), ErrorCode(S_OK) {} 174 CDirItemsCallback_AgentOut(): FolderArchiveUpdateCallback(NULL), ErrorCode(S_OK) {}
174 175
175 HRESULT ScanError(const FString &name, DWORD systemError) 176 HRESULT ScanError(const FString &name, DWORD systemError) Z7_override
176 { 177 {
177 HRESULT hres = HRESULT_FROM_WIN32(systemError); 178 const HRESULT hres = HRESULT_FROM_WIN32(systemError);
178 if (FolderArchiveUpdateCallback) 179 if (FolderArchiveUpdateCallback)
179 return FolderScanProgress->ScanError(fs2us(name), hres); 180 return FolderScanProgress->ScanError(fs2us(name), hres);
180 ErrorCode = hres; 181 ErrorCode = hres;
181 return ErrorCode; 182 return ErrorCode;
182 } 183 }
183 184
184 HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) 185 HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) Z7_override
185 { 186 {
186 if (FolderScanProgress) 187 if (FolderScanProgress)
187 return FolderScanProgress->ScanProgress(st.NumDirs, st.NumFiles + st.NumAltStreams, 188 return FolderScanProgress->ScanProgress(st.NumDirs, st.NumFiles + st.NumAltStreams,
188 st.GetTotalBytes(), fs2us(path), BoolToInt(isDir)); 189 st.GetTotalBytes(), fs2us(path), BoolToInt(isDir));
189
190 if (FolderArchiveUpdateCallback) 190 if (FolderArchiveUpdateCallback)
191 return FolderArchiveUpdateCallback->SetNumFiles(st.NumFiles); 191 return FolderArchiveUpdateCallback->SetNumFiles(st.NumFiles);
192
193 return S_OK; 192 return S_OK;
194 } 193 }
195}; 194};
196 195
197 196
198STDMETHODIMP CAgent::DoOperation( 197Z7_COM7F_IMF(CAgent::DoOperation(
199 FStringVector *requestedPaths, 198 FStringVector *requestedPaths,
200 FStringVector *processedPaths, 199 FStringVector *processedPaths,
201 CCodecs *codecs, 200 CCodecs *codecs,
@@ -203,7 +202,7 @@ STDMETHODIMP CAgent::DoOperation(
203 ISequentialOutStream *outArchiveStream, 202 ISequentialOutStream *outArchiveStream,
204 const Byte *stateActions, 203 const Byte *stateActions,
205 const wchar_t *sfxModule, 204 const wchar_t *sfxModule,
206 IFolderArchiveUpdateCallback *updateCallback100) 205 IFolderArchiveUpdateCallback *updateCallback100))
207{ 206{
208 if (!CanUpdate()) 207 if (!CanUpdate())
209 return E_NOTIMPL; 208 return E_NOTIMPL;
@@ -226,9 +225,10 @@ STDMETHODIMP CAgent::DoOperation(
226 225
227 { 226 {
228 FString folderPrefix = _folderPrefix; 227 FString folderPrefix = _folderPrefix;
229 NFile::NName::NormalizeDirPathPrefix(folderPrefix); 228 if (!NFile::NName::IsAltStreamPrefixWithColon(fs2us(folderPrefix)))
229 NFile::NName::NormalizeDirPathPrefix(folderPrefix);
230 230
231 RINOK(dirItems.EnumerateItems2(folderPrefix, _updatePathPrefix, _names, requestedPaths)); 231 RINOK(dirItems.EnumerateItems2(folderPrefix, _updatePathPrefix, _names, requestedPaths))
232 232
233 if (_updatePathPrefix_is_AltFolder) 233 if (_updatePathPrefix_is_AltFolder)
234 { 234 {
@@ -246,21 +246,21 @@ STDMETHODIMP CAgent::DoOperation(
246 246
247 if (GetArchive()) 247 if (GetArchive())
248 { 248 {
249 RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)); 249 RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive))
250 } 250 }
251 else 251 else
252 { 252 {
253 if (formatIndex < 0) 253 if (formatIndex < 0)
254 return E_FAIL; 254 return E_FAIL;
255 RINOK(codecs->CreateOutArchive(formatIndex, outArchive)); 255 RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive))
256 256
257 #ifdef EXTERNAL_CODECS 257 #ifdef Z7_EXTERNAL_CODECS
258 { 258 {
259 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo; 259 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
260 outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); 260 outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
261 if (setCompressCodecsInfo) 261 if (setCompressCodecsInfo)
262 { 262 {
263 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)); 263 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs))
264 } 264 }
265 } 265 }
266 #endif 266 #endif
@@ -268,7 +268,7 @@ STDMETHODIMP CAgent::DoOperation(
268 268
269 NFileTimeType::EEnum fileTimeType = NFileTimeType::kNotDefined; 269 NFileTimeType::EEnum fileTimeType = NFileTimeType::kNotDefined;
270 UInt32 value; 270 UInt32 value;
271 RINOK(outArchive->GetFileTimeType(&value)); 271 RINOK(outArchive->GetFileTimeType(&value))
272 // we support any future fileType here. 272 // we support any future fileType here.
273 // 22.00: 273 // 22.00:
274 fileTimeType = (NFileTimeType::EEnum)value; 274 fileTimeType = (NFileTimeType::EEnum)value;
@@ -291,15 +291,15 @@ STDMETHODIMP CAgent::DoOperation(
291 CObjectVector<CArcItem> arcItems; 291 CObjectVector<CArcItem> arcItems;
292 if (GetArchive()) 292 if (GetArchive())
293 { 293 {
294 RINOK(ReadItems()); 294 RINOK(ReadItems())
295 if (_proxy2) 295 if (_proxy2)
296 { 296 {
297 RINOK(EnumerateArchiveItems2(this, k_Proxy2_RootDirIndex, L"", arcItems)); 297 RINOK(EnumerateArchiveItems2(this, k_Proxy2_RootDirIndex, L"", arcItems))
298 RINOK(EnumerateArchiveItems2(this, k_Proxy2_AltRootDirIndex, L":", arcItems)); 298 RINOK(EnumerateArchiveItems2(this, k_Proxy2_AltRootDirIndex, L":", arcItems))
299 } 299 }
300 else 300 else
301 { 301 {
302 RINOK(EnumerateArchiveItems(this, _proxy->Dirs[0], L"", arcItems)); 302 RINOK(EnumerateArchiveItems(this, _proxy->Dirs[0], L"", arcItems))
303 } 303 }
304 } 304 }
305 305
@@ -321,7 +321,7 @@ STDMETHODIMP CAgent::DoOperation(
321 321
322 if (updateCallback100) 322 if (updateCallback100)
323 { 323 {
324 RINOK(updateCallback100->SetNumFiles(numFiles)); 324 RINOK(updateCallback100->SetNumFiles(numFiles))
325 } 325 }
326 326
327 CUpdateCallbackAgent updateCallbackAgent; 327 CUpdateCallbackAgent updateCallbackAgent;
@@ -347,12 +347,14 @@ STDMETHODIMP CAgent::DoOperation(
347 updateCallbackSpec->ProcessedItemsStatuses = processedItems; 347 updateCallbackSpec->ProcessedItemsStatuses = processedItems;
348 } 348 }
349 349
350 CMyComPtr<ISetProperties> setProperties; 350 Z7_DECL_CMyComPtr_QI_FROM(
351 if (outArchive->QueryInterface(IID_ISetProperties, (void **)&setProperties) == S_OK) 351 ISetProperties,
352 setProperties, outArchive)
353 if (setProperties)
352 { 354 {
353 if (m_PropNames.Size() == 0) 355 if (m_PropNames.Size() == 0)
354 { 356 {
355 RINOK(setProperties->SetProperties(0, 0, 0)); 357 RINOK(setProperties->SetProperties(NULL, NULL, 0))
356 } 358 }
357 else 359 else
358 { 360 {
@@ -365,7 +367,7 @@ STDMETHODIMP CAgent::DoOperation(
365 { 367 {
366 FOR_VECTOR (i, m_PropValues) 368 FOR_VECTOR (i, m_PropValues)
367 propValues[i] = m_PropValues[i]; 369 propValues[i] = m_PropValues[i];
368 RINOK(setProperties->SetProperties(&names.Front(), propValues, names.Size())); 370 RINOK(setProperties->SetProperties(&names.Front(), propValues, names.Size()))
369 } 371 }
370 catch(...) 372 catch(...)
371 { 373 {
@@ -385,7 +387,7 @@ STDMETHODIMP CAgent::DoOperation(
385 if (!sfxStreamSpec->Open(us2fs(sfxModule))) 387 if (!sfxStreamSpec->Open(us2fs(sfxModule)))
386 return E_FAIL; 388 return E_FAIL;
387 // throw "Can't open sfx module"; 389 // throw "Can't open sfx module";
388 RINOK(NCompress::CopyStream(sfxStream, outArchiveStream, NULL)); 390 RINOK(NCompress::CopyStream(sfxStream, outArchiveStream, NULL))
389 } 391 }
390 392
391 HRESULT res = outArchive->UpdateItems(outArchiveStream, updatePairs2.Size(), updateCallback); 393 HRESULT res = outArchive->UpdateItems(outArchiveStream, updatePairs2.Size(), updateCallback);
@@ -413,11 +415,11 @@ STDMETHODIMP CAgent::DoOperation(
413 return res; 415 return res;
414} 416}
415 417
416STDMETHODIMP CAgent::DoOperation2( 418Z7_COM7F_IMF(CAgent::DoOperation2(
417 FStringVector *requestedPaths, 419 FStringVector *requestedPaths,
418 FStringVector *processedPaths, 420 FStringVector *processedPaths,
419 ISequentialOutStream *outArchiveStream, 421 ISequentialOutStream *outArchiveStream,
420 const Byte *stateActions, const wchar_t *sfxModule, IFolderArchiveUpdateCallback *updateCallback100) 422 const Byte *stateActions, const wchar_t *sfxModule, IFolderArchiveUpdateCallback *updateCallback100))
421{ 423{
422 return DoOperation(requestedPaths, processedPaths, g_CodecsObj, -1, outArchiveStream, stateActions, sfxModule, updateCallback100); 424 return DoOperation(requestedPaths, processedPaths, g_CodecsObj, -1, outArchiveStream, stateActions, sfxModule, updateCallback100);
423} 425}
@@ -428,13 +430,13 @@ HRESULT CAgent::CommonUpdate(ISequentialOutStream *outArchiveStream,
428 if (!CanUpdate()) 430 if (!CanUpdate())
429 return E_NOTIMPL; 431 return E_NOTIMPL;
430 CMyComPtr<IOutArchive> outArchive; 432 CMyComPtr<IOutArchive> outArchive;
431 RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive)); 433 RINOK(GetArchive()->QueryInterface(IID_IOutArchive, (void **)&outArchive))
432 return outArchive->UpdateItems(outArchiveStream, numUpdateItems, updateCallback); 434 return outArchive->UpdateItems(outArchiveStream, numUpdateItems, updateCallback);
433} 435}
434 436
435STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream, 437Z7_COM7F_IMF(CAgent::DeleteItems(ISequentialOutStream *outArchiveStream,
436 const UInt32 *indices, UInt32 numItems, 438 const UInt32 *indices, UInt32 numItems,
437 IFolderArchiveUpdateCallback *updateCallback100) 439 IFolderArchiveUpdateCallback *updateCallback100))
438{ 440{
439 if (!CanUpdate()) 441 if (!CanUpdate())
440 return E_NOTIMPL; 442 return E_NOTIMPL;
@@ -451,7 +453,7 @@ STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream,
451 realIndices); 453 realIndices);
452 unsigned curIndex = 0; 454 unsigned curIndex = 0;
453 UInt32 numItemsInArchive; 455 UInt32 numItemsInArchive;
454 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); 456 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive))
455 457
456 UString deletePath; 458 UString deletePath;
457 459
@@ -460,8 +462,8 @@ STDMETHODIMP CAgent::DeleteItems(ISequentialOutStream *outArchiveStream,
460 if (curIndex < realIndices.Size()) 462 if (curIndex < realIndices.Size())
461 if (realIndices[curIndex] == i) 463 if (realIndices[curIndex] == i)
462 { 464 {
463 RINOK(GetArc().GetItem_Path2(i, deletePath)); 465 RINOK(GetArc().GetItem_Path2(i, deletePath))
464 RINOK(updateCallback100->DeleteOperation(deletePath)); 466 RINOK(updateCallback100->DeleteOperation(deletePath))
465 467
466 curIndex++; 468 curIndex++;
467 continue; 469 continue;
@@ -491,7 +493,7 @@ HRESULT CAgent::CreateFolder(ISequentialOutStream *outArchiveStream,
491 CMyComPtr<IArchiveUpdateCallback> updateCallback(updateCallbackSpec); 493 CMyComPtr<IArchiveUpdateCallback> updateCallback(updateCallbackSpec);
492 494
493 UInt32 numItemsInArchive; 495 UInt32 numItemsInArchive;
494 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); 496 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive))
495 for (UInt32 i = 0; i < numItemsInArchive; i++) 497 for (UInt32 i = 0; i < numItemsInArchive; i++)
496 { 498 {
497 CUpdatePair2 up2; 499 CUpdatePair2 up2;
@@ -569,7 +571,7 @@ HRESULT CAgent::RenameItem(ISequentialOutStream *outArchiveStream,
569 571
570 unsigned curIndex = 0; 572 unsigned curIndex = 0;
571 UInt32 numItemsInArchive; 573 UInt32 numItemsInArchive;
572 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); 574 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive))
573 575
574 for (UInt32 i = 0; i < numItemsInArchive; i++) 576 for (UInt32 i = 0; i < numItemsInArchive; i++)
575 { 577 {
@@ -579,15 +581,15 @@ HRESULT CAgent::RenameItem(ISequentialOutStream *outArchiveStream,
579 if (realIndices[curIndex] == i) 581 if (realIndices[curIndex] == i)
580 { 582 {
581 up2.NewProps = true; 583 up2.NewProps = true;
582 RINOK(GetArc().IsItem_Anti(i, up2.IsAnti)); // it must work without that line too. 584 RINOK(GetArc().IsItem_Anti(i, up2.IsAnti)) // it must work without that line too.
583 585
584 UString oldFullPath; 586 UString oldFullPath;
585 RINOK(GetArc().GetItem_Path2(i, oldFullPath)); 587 RINOK(GetArc().GetItem_Path2(i, oldFullPath))
586 588
587 if (!IsPath1PrefixedByPath2(oldFullPath, oldItemPath)) 589 if (!IsPath1PrefixedByPath2(oldFullPath, oldItemPath))
588 return E_INVALIDARG; 590 return E_INVALIDARG;
589 591
590 up2.NewNameIndex = newNames.Add(newItemPath + oldFullPath.Ptr(oldItemPath.Len())); 592 up2.NewNameIndex = (int)newNames.Add(newItemPath + oldFullPath.Ptr(oldItemPath.Len()));
591 up2.IsMainRenameItem = (mainRealIndex == (int)i); 593 up2.IsMainRenameItem = (mainRealIndex == (int)i);
592 curIndex++; 594 curIndex++;
593 } 595 }
@@ -627,7 +629,7 @@ HRESULT CAgent::CommentItem(ISequentialOutStream *outArchiveStream,
627 return E_NOTIMPL; 629 return E_NOTIMPL;
628 630
629 UInt32 numItemsInArchive; 631 UInt32 numItemsInArchive;
630 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); 632 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive))
631 633
632 UString newName = newItemName; 634 UString newName = newItemName;
633 635
@@ -686,7 +688,7 @@ HRESULT CAgent::UpdateOneFile(ISequentialOutStream *outArchiveStream,
686 } 688 }
687 689
688 UInt32 numItemsInArchive; 690 UInt32 numItemsInArchive;
689 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive)); 691 RINOK(GetArchive()->GetNumberOfItems(&numItemsInArchive))
690 for (UInt32 i = 0; i < numItemsInArchive; i++) 692 for (UInt32 i = 0; i < numItemsInArchive; i++)
691 { 693 {
692 CUpdatePair2 up2; 694 CUpdatePair2 up2;
@@ -710,7 +712,7 @@ HRESULT CAgent::UpdateOneFile(ISequentialOutStream *outArchiveStream,
710 return CommonUpdate(outArchiveStream, updatePairs.Size(), updateCallback); 712 return CommonUpdate(outArchiveStream, updatePairs.Size(), updateCallback);
711} 713}
712 714
713STDMETHODIMP CAgent::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 715Z7_COM7F_IMF(CAgent::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
714{ 716{
715 m_PropNames.Clear(); 717 m_PropNames.Clear();
716 m_PropValues.Clear(); 718 m_PropValues.Clear();
diff --git a/CPP/7zip/UI/Agent/AgentProxy.cpp b/CPP/7zip/UI/Agent/AgentProxy.cpp
index 4c9c386..df9f315 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
39 const unsigned dirIndex2 = subDirs[mid]; 39 const unsigned dirIndex2 = subDirs[mid];
40 const int comp = CompareFileNames(name, Dirs[dirIndex2].Name); 40 const int comp = CompareFileNames(name, Dirs[dirIndex2].Name);
41 if (comp == 0) 41 if (comp == 0)
42 return dirIndex2; 42 return (int)dirIndex2;
43 if (comp < 0) 43 if (comp < 0)
44 right = mid; 44 right = mid;
45 else 45 else
@@ -77,18 +77,18 @@ unsigned CProxyArc::AddDir(unsigned dirIndex, int arcIndex, const UString &name)
77 if (item.ArcIndex == -1) 77 if (item.ArcIndex == -1)
78 item.ArcIndex = arcIndex; 78 item.ArcIndex = arcIndex;
79 } 79 }
80 return subDirIndex; 80 return (unsigned)subDirIndex;
81 } 81 }
82 subDirIndex = Dirs.Size(); 82 subDirIndex = (int)Dirs.Size();
83 Dirs[dirIndex].SubDirs.Insert(insertPos, subDirIndex); 83 Dirs[dirIndex].SubDirs.Insert(insertPos, (unsigned)subDirIndex);
84 CProxyDir &item = Dirs.AddNew(); 84 CProxyDir &item = Dirs.AddNew();
85 85
86 item.NameLen = name.Len(); 86 item.NameLen = name.Len();
87 item.Name = AllocStringAndCopy(name); 87 item.Name = AllocStringAndCopy(name);
88 88
89 item.ArcIndex = arcIndex; 89 item.ArcIndex = arcIndex;
90 item.ParentDir = dirIndex; 90 item.ParentDir = (int)dirIndex;
91 return subDirIndex; 91 return (unsigned)subDirIndex;
92} 92}
93 93
94void CProxyDir::Clear() 94void CProxyDir::Clear()
@@ -97,14 +97,15 @@ void CProxyDir::Clear()
97 SubFiles.Clear(); 97 SubFiles.Clear();
98} 98}
99 99
100void CProxyArc::GetDirPathParts(int dirIndex, UStringVector &pathParts) const 100void CProxyArc::GetDirPathParts(unsigned dirIndex, UStringVector &pathParts) const
101{ 101{
102 pathParts.Clear(); 102 pathParts.Clear();
103 while (dirIndex != -1) 103 // while (dirIndex != -1)
104 for (;;)
104 { 105 {
105 const CProxyDir &dir = Dirs[dirIndex]; 106 const CProxyDir &dir = Dirs[dirIndex];
106 dirIndex = dir.ParentDir; 107 dirIndex = (unsigned)dir.ParentDir;
107 if (dirIndex == -1) 108 if (dir.ParentDir == -1)
108 break; 109 break;
109 pathParts.Insert(0, dir.Name); 110 pathParts.Insert(0, dir.Name);
110 // 22.00: we normalize name 111 // 22.00: we normalize name
@@ -112,14 +113,15 @@ void CProxyArc::GetDirPathParts(int dirIndex, UStringVector &pathParts) const
112 } 113 }
113} 114}
114 115
115UString CProxyArc::GetDirPath_as_Prefix(int dirIndex) const 116UString CProxyArc::GetDirPath_as_Prefix(unsigned dirIndex) const
116{ 117{
117 UString s; 118 UString s;
118 while (dirIndex != -1) 119 // while (dirIndex != -1)
120 for (;;)
119 { 121 {
120 const CProxyDir &dir = Dirs[dirIndex]; 122 const CProxyDir &dir = Dirs[dirIndex];
121 dirIndex = dir.ParentDir; 123 dirIndex = (unsigned)dir.ParentDir;
122 if (dirIndex == -1) 124 if (dir.ParentDir == -1)
123 break; 125 break;
124 s.InsertAtFront(WCHAR_PATH_SEPARATOR); 126 s.InsertAtFront(WCHAR_PATH_SEPARATOR);
125 s.Insert(0, dir.Name); 127 s.Insert(0, dir.Name);
@@ -133,7 +135,7 @@ void CProxyArc::AddRealIndices(unsigned dirIndex, CUIntVector &realIndices) cons
133{ 135{
134 const CProxyDir &dir = Dirs[dirIndex]; 136 const CProxyDir &dir = Dirs[dirIndex];
135 if (dir.IsLeaf()) 137 if (dir.IsLeaf())
136 realIndices.Add(dir.ArcIndex); 138 realIndices.Add((unsigned)dir.ArcIndex);
137 unsigned i; 139 unsigned i;
138 for (i = 0; i < dir.SubDirs.Size(); i++) 140 for (i = 0; i < dir.SubDirs.Size(); i++)
139 AddRealIndices(dir.SubDirs[i], realIndices); 141 AddRealIndices(dir.SubDirs[i], realIndices);
@@ -152,7 +154,7 @@ int CProxyArc::GetRealIndex(unsigned dirIndex, unsigned index) const
152 return f.ArcIndex; 154 return f.ArcIndex;
153 return -1; 155 return -1;
154 } 156 }
155 return dir.SubFiles[index - numDirItems]; 157 return (int)dir.SubFiles[index - numDirItems];
156} 158}
157 159
158void CProxyArc::GetRealIndices(unsigned dirIndex, const UInt32 *indices, UInt32 numItems, CUIntVector &realIndices) const 160void CProxyArc::GetRealIndices(unsigned dirIndex, const UInt32 *indices, UInt32 numItems, CUIntVector &realIndices) const
@@ -242,10 +244,10 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
242 IInArchive *archive = arc.Archive; 244 IInArchive *archive = arc.Archive;
243 245
244 UInt32 numItems; 246 UInt32 numItems;
245 RINOK(archive->GetNumberOfItems(&numItems)); 247 RINOK(archive->GetNumberOfItems(&numItems))
246 248
247 if (progress) 249 if (progress)
248 RINOK(progress->SetTotal(numItems)); 250 RINOK(progress->SetTotal(numItems))
249 251
250 Files.Alloc(numItems); 252 Files.Alloc(numItems);
251 253
@@ -258,7 +260,7 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
258 if (progress && (i & 0xFFFF) == 0) 260 if (progress && (i & 0xFFFF) == 0)
259 { 261 {
260 const UInt64 currentItemIndex = i; 262 const UInt64 currentItemIndex = i;
261 RINOK(progress->SetCompleted(&currentItemIndex)); 263 RINOK(progress->SetCompleted(&currentItemIndex))
262 } 264 }
263 265
264 const wchar_t *s = NULL; 266 const wchar_t *s = NULL;
@@ -293,7 +295,7 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
293 #endif 295 #endif
294 { 296 {
295 prop.Clear(); 297 prop.Clear();
296 RINOK(arc.Archive->GetProperty(i, kpidPath, &prop)); 298 RINOK(arc.Archive->GetProperty(i, kpidPath, &prop))
297 if (prop.vt == VT_BSTR) 299 if (prop.vt == VT_BSTR)
298 { 300 {
299 s = prop.bstrVal; 301 s = prop.bstrVal;
@@ -303,7 +305,7 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
303 return E_FAIL; 305 return E_FAIL;
304 if (len == 0) 306 if (len == 0)
305 { 307 {
306 RINOK(arc.GetItem_DefaultPath(i, path)); 308 RINOK(arc.GetItem_DefaultPath(i, path))
307 len = path.Len(); 309 len = path.Len();
308 s = path; 310 s = path;
309 } 311 }
@@ -370,7 +372,7 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
370 */ 372 */
371 373
372 bool isDir; 374 bool isDir;
373 RINOK(Archive_IsItem_Dir(archive, i, isDir)); 375 RINOK(Archive_IsItem_Dir(archive, i, isDir))
374 376
375 CProxyFile &f = Files[i]; 377 CProxyFile &f = Files[i];
376 378
@@ -407,31 +409,32 @@ HRESULT CProxyArc::Load(const CArc &arc, IProgress *progress)
407 409
408// ---------- for Tree-mode archive ---------- 410// ---------- for Tree-mode archive ----------
409 411
410void CProxyArc2::GetDirPathParts(int dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const 412void CProxyArc2::GetDirPathParts(unsigned dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const
411{ 413{
412 pathParts.Clear(); 414 pathParts.Clear();
413 415
414 isAltStreamDir = false; 416 isAltStreamDir = false;
415 417
416 if (dirIndex == (int)k_Proxy2_RootDirIndex) 418 if (dirIndex == k_Proxy2_RootDirIndex)
417 return; 419 return;
418 if (dirIndex == (int)k_Proxy2_AltRootDirIndex) 420 if (dirIndex == k_Proxy2_AltRootDirIndex)
419 { 421 {
420 isAltStreamDir = true; 422 isAltStreamDir = true;
421 return; 423 return;
422 } 424 }
423 425
424 while (dirIndex >= (int)k_Proxy2_NumRootDirs) 426 while (dirIndex >= k_Proxy2_NumRootDirs)
425 { 427 {
426 const CProxyDir2 &dir = Dirs[dirIndex]; 428 const CProxyDir2 &dir = Dirs[dirIndex];
427 const CProxyFile2 &file = Files[(unsigned)dir.ArcIndex]; 429 const CProxyFile2 &file = Files[(unsigned)dir.ArcIndex];
428 if (pathParts.IsEmpty() && dirIndex == file.AltDirIndex) 430 if (pathParts.IsEmpty() && (int)dirIndex == file.AltDirIndex)
429 isAltStreamDir = true; 431 isAltStreamDir = true;
430 pathParts.Insert(0, file.Name); 432 pathParts.Insert(0, file.Name);
431 int par = file.Parent; 433 const int par = file.Parent;
432 if (par == -1) 434 if (par == -1)
433 break; 435 break;
434 dirIndex = Files[(unsigned)par].DirIndex; 436 dirIndex = (unsigned)Files[(unsigned)par].DirIndex;
437 // if ((int)dirIndex == -1) break;
435 } 438 }
436} 439}
437 440
@@ -465,9 +468,9 @@ void CProxyArc2::AddRealIndices_of_ArcItem(unsigned arcIndex, bool includeAltStr
465 realIndices.Add(arcIndex); 468 realIndices.Add(arcIndex);
466 const CProxyFile2 &file = Files[arcIndex]; 469 const CProxyFile2 &file = Files[arcIndex];
467 if (file.DirIndex != -1) 470 if (file.DirIndex != -1)
468 AddRealIndices_of_Dir(file.DirIndex, includeAltStreams, realIndices); 471 AddRealIndices_of_Dir((unsigned)file.DirIndex, includeAltStreams, realIndices);
469 if (includeAltStreams && file.AltDirIndex != -1) 472 if (includeAltStreams && file.AltDirIndex != -1)
470 AddRealIndices_of_Dir(file.AltDirIndex, includeAltStreams, realIndices); 473 AddRealIndices_of_Dir((unsigned)file.AltDirIndex, includeAltStreams, realIndices);
471} 474}
472 475
473void CProxyArc2::AddRealIndices_of_Dir(unsigned dirIndex, bool includeAltStreams, CUIntVector &realIndices) const 476void CProxyArc2::AddRealIndices_of_Dir(unsigned dirIndex, bool includeAltStreams, CUIntVector &realIndices) const
@@ -538,7 +541,7 @@ void CProxyArc2::CalculateSizes(unsigned dirIndex, IInArchive *archive)
538 dir.NumSubDirs++; 541 dir.NumSubDirs++;
539 CProxyDir2 &f = Dirs[subFile.DirIndex]; 542 CProxyDir2 &f = Dirs[subFile.DirIndex];
540 f.PathPrefix = dir.PathPrefix + s + WCHAR_PATH_SEPARATOR; 543 f.PathPrefix = dir.PathPrefix + s + WCHAR_PATH_SEPARATOR;
541 CalculateSizes(subFile.DirIndex, archive); 544 CalculateSizes((unsigned)subFile.DirIndex, archive);
542 dir.Size += f.Size; 545 dir.Size += f.Size;
543 dir.PackSize += f.PackSize; 546 dir.PackSize += f.PackSize;
544 dir.NumSubFiles += f.NumSubFiles; 547 dir.NumSubFiles += f.NumSubFiles;
@@ -557,7 +560,7 @@ void CProxyArc2::CalculateSizes(unsigned dirIndex, IInArchive *archive)
557 // dir.NumSubDirs++; 560 // dir.NumSubDirs++;
558 CProxyDir2 &f = Dirs[subFile.AltDirIndex]; 561 CProxyDir2 &f = Dirs[subFile.AltDirIndex];
559 f.PathPrefix = dir.PathPrefix + subFile.Name + L':'; 562 f.PathPrefix = dir.PathPrefix + subFile.Name + L':';
560 CalculateSizes(subFile.AltDirIndex, archive); 563 CalculateSizes((unsigned)subFile.AltDirIndex, archive);
561 } 564 }
562 } 565 }
563} 566}
@@ -589,9 +592,9 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
589 IInArchive *archive = arc.Archive; 592 IInArchive *archive = arc.Archive;
590 593
591 UInt32 numItems; 594 UInt32 numItems;
592 RINOK(archive->GetNumberOfItems(&numItems)); 595 RINOK(archive->GetNumberOfItems(&numItems))
593 if (progress) 596 if (progress)
594 RINOK(progress->SetTotal(numItems)); 597 RINOK(progress->SetTotal(numItems))
595 UString fileName; 598 UString fileName;
596 599
597 600
@@ -617,7 +620,7 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
617 if (progress && (i & 0xFFFFF) == 0) 620 if (progress && (i & 0xFFFFF) == 0)
618 { 621 {
619 UInt64 currentItemIndex = i; 622 UInt64 currentItemIndex = i;
620 RINOK(progress->SetCompleted(&currentItemIndex)); 623 RINOK(progress->SetCompleted(&currentItemIndex))
621 } 624 }
622 625
623 CProxyFile2 &file = Files[i]; 626 CProxyFile2 &file = Files[i];
@@ -625,7 +628,7 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
625 const void *p; 628 const void *p;
626 UInt32 size; 629 UInt32 size;
627 UInt32 propType; 630 UInt32 propType;
628 RINOK(arc.GetRawProps->GetRawProp(i, kpidName, &p, &size, &propType)); 631 RINOK(arc.GetRawProps->GetRawProp(i, kpidName, &p, &size, &propType))
629 632
630 #ifdef MY_CPU_LE 633 #ifdef MY_CPU_LE
631 if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE) 634 if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE)
@@ -648,7 +651,7 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
648 else 651 else
649 { 652 {
650 NCOM::CPropVariant prop; 653 NCOM::CPropVariant prop;
651 RINOK(arc.Archive->GetProperty(i, kpidName, &prop)); 654 RINOK(arc.Archive->GetProperty(i, kpidName, &prop))
652 const wchar_t *s; 655 const wchar_t *s;
653 if (prop.vt == VT_BSTR) 656 if (prop.vt == VT_BSTR)
654 s = prop.bstrVal; 657 s = prop.bstrVal;
@@ -663,13 +666,13 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
663 666
664 UInt32 parent = (UInt32)(Int32)-1; 667 UInt32 parent = (UInt32)(Int32)-1;
665 UInt32 parentType = 0; 668 UInt32 parentType = 0;
666 RINOK(arc.GetRawProps->GetParent(i, &parent, &parentType)); 669 RINOK(arc.GetRawProps->GetParent(i, &parent, &parentType))
667 file.Parent = (Int32)parent; 670 file.Parent = (Int32)parent;
668 671
669 if (arc.Ask_Deleted) 672 if (arc.Ask_Deleted)
670 { 673 {
671 bool isDeleted = false; 674 bool isDeleted = false;
672 RINOK(Archive_IsItem_Deleted(archive, i, isDeleted)); 675 RINOK(Archive_IsItem_Deleted(archive, i, isDeleted))
673 if (isDeleted) 676 if (isDeleted)
674 { 677 {
675 // continue; 678 // continue;
@@ -678,16 +681,16 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
678 } 681 }
679 682
680 bool isDir; 683 bool isDir;
681 RINOK(Archive_IsItem_Dir(archive, i, isDir)); 684 RINOK(Archive_IsItem_Dir(archive, i, isDir))
682 685
683 if (isDir) 686 if (isDir)
684 { 687 {
685 file.DirIndex = Dirs.Size(); 688 file.DirIndex = (int)Dirs.Size();
686 CProxyDir2 &dir = Dirs.AddNew(); 689 CProxyDir2 &dir = Dirs.AddNew();
687 dir.ArcIndex = i; 690 dir.ArcIndex = (int)i;
688 } 691 }
689 if (arc.Ask_AltStream) 692 if (arc.Ask_AltStream)
690 RINOK(Archive_IsItem_AltStream(archive, i, file.IsAltStream)); 693 RINOK(Archive_IsItem_AltStream(archive, i, file.IsAltStream))
691 } 694 }
692 695
693 for (i = 0; i < numItems; i++) 696 for (i = 0; i < numItems; i++)
@@ -704,7 +707,7 @@ HRESULT CProxyArc2::Load(const CArc &arc, IProgress *progress)
704 int &folderIndex2 = Files[(unsigned)file.Parent].AltDirIndex; 707 int &folderIndex2 = Files[(unsigned)file.Parent].AltDirIndex;
705 if (folderIndex2 == -1) 708 if (folderIndex2 == -1)
706 { 709 {
707 folderIndex2 = Dirs.Size(); 710 folderIndex2 = (int)Dirs.Size();
708 CProxyDir2 &dir = Dirs.AddNew(); 711 CProxyDir2 &dir = Dirs.AddNew();
709 dir.ArcIndex = file.Parent; 712 dir.ArcIndex = file.Parent;
710 } 713 }
@@ -743,7 +746,7 @@ int CProxyArc2::FindItem(unsigned dirIndex, const wchar_t *name, bool foldersOnl
743 if (foldersOnly && file.DirIndex == -1) 746 if (foldersOnly && file.DirIndex == -1)
744 continue; 747 continue;
745 if (CompareFileNames(file.Name, name) == 0) 748 if (CompareFileNames(file.Name, name) == 0)
746 return i; 749 return (int)i;
747 } 750 }
748 return -1; 751 return -1;
749} 752}
diff --git a/CPP/7zip/UI/Agent/AgentProxy.h b/CPP/7zip/UI/Agent/AgentProxy.h
index 233174b..c24dd91 100644
--- a/CPP/7zip/UI/Agent/AgentProxy.h
+++ b/CPP/7zip/UI/Agent/AgentProxy.h
@@ -1,7 +1,7 @@
1// AgentProxy.h 1// AgentProxy.h
2 2
3#ifndef __AGENT_PROXY_H 3#ifndef ZIP7_INC_AGENT_PROXY_H
4#define __AGENT_PROXY_H 4#define ZIP7_INC_AGENT_PROXY_H
5 5
6#include "../Common/OpenArchive.h" 6#include "../Common/OpenArchive.h"
7 7
@@ -34,7 +34,7 @@ struct CProxyDir
34 UInt32 NumSubFiles; 34 UInt32 NumSubFiles;
35 bool CrcIsDefined; 35 bool CrcIsDefined;
36 36
37 CProxyDir(): Name(NULL), NameLen(0), ParentDir(-1) {}; 37 CProxyDir(): Name(NULL), NameLen(0), ParentDir(-1) {}
38 ~CProxyDir() { delete [](wchar_t *)(void *)Name; } 38 ~CProxyDir() { delete [](wchar_t *)(void *)Name; }
39 39
40 void Clear(); 40 void Clear();
@@ -54,9 +54,9 @@ public:
54 // returns index in Dirs[], or -1, 54 // returns index in Dirs[], or -1,
55 int FindSubDir(unsigned dirIndex, const wchar_t *name) const; 55 int FindSubDir(unsigned dirIndex, const wchar_t *name) const;
56 56
57 void GetDirPathParts(int dirIndex, UStringVector &pathParts) const; 57 void GetDirPathParts(unsigned dirIndex, UStringVector &pathParts) const;
58 // returns full path of Dirs[dirIndex], including back slash 58 // returns full path of Dirs[dirIndex], including back slash
59 UString GetDirPath_as_Prefix(int dirIndex) const; 59 UString GetDirPath_as_Prefix(unsigned dirIndex) const;
60 60
61 // AddRealIndices DOES ADD also item represented by dirIndex (if it's Leaf) 61 // AddRealIndices DOES ADD also item represented by dirIndex (if it's Leaf)
62 void AddRealIndices(unsigned dirIndex, CUIntVector &realIndices) const; 62 void AddRealIndices(unsigned dirIndex, CUIntVector &realIndices) const;
@@ -73,7 +73,7 @@ struct CProxyFile2
73{ 73{
74 int DirIndex; // >= 0 for dir. (index in ProxyArchive2->Dirs) 74 int DirIndex; // >= 0 for dir. (index in ProxyArchive2->Dirs)
75 int AltDirIndex; // >= 0 if there are alt streams. (index in ProxyArchive2->Dirs) 75 int AltDirIndex; // >= 0 if there are alt streams. (index in ProxyArchive2->Dirs)
76 int Parent; // >= 0 if there is parent. (index in archive and in ProxyArchive2->Files) 76 int Parent; // >= 0 if there is parent. (index in archive and in ProxyArchive2->Files)
77 const wchar_t *Name; 77 const wchar_t *Name;
78 unsigned NameLen; 78 unsigned NameLen;
79 bool NeedDeleteName; 79 bool NeedDeleteName;
@@ -109,7 +109,7 @@ struct CProxyDir2
109 UInt32 NumSubDirs; 109 UInt32 NumSubDirs;
110 UInt32 NumSubFiles; 110 UInt32 NumSubFiles;
111 111
112 CProxyDir2(): ArcIndex(-1) {}; 112 CProxyDir2(): ArcIndex(-1) {}
113 void AddFileSubItem(UInt32 index, const UString &name); 113 void AddFileSubItem(UInt32 index, const UString &name);
114 void Clear(); 114 void Clear();
115}; 115};
@@ -130,7 +130,7 @@ public:
130 130
131 bool IsThere_SubDir(unsigned dirIndex, const UString &name) const; 131 bool IsThere_SubDir(unsigned dirIndex, const UString &name) const;
132 132
133 void GetDirPathParts(int dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const; 133 void GetDirPathParts(unsigned dirIndex, UStringVector &pathParts, bool &isAltStreamDir) const;
134 UString GetDirPath_as_Prefix(unsigned dirIndex, bool &isAltStreamDir) const; 134 UString GetDirPath_as_Prefix(unsigned dirIndex, bool &isAltStreamDir) const;
135 bool IsAltDir(unsigned dirIndex) const; 135 bool IsAltDir(unsigned dirIndex) const;
136 136
diff --git a/CPP/7zip/UI/Agent/ArchiveFolder.cpp b/CPP/7zip/UI/Agent/ArchiveFolder.cpp
index eca02ba..89b20dc 100644
--- a/CPP/7zip/UI/Agent/ArchiveFolder.cpp
+++ b/CPP/7zip/UI/Agent/ArchiveFolder.cpp
@@ -9,22 +9,23 @@
9#include "Agent.h" 9#include "Agent.h"
10 10
11/* 11/*
12STDMETHODIMP CAgentFolder::SetReplaceAltStreamCharsMode(Int32 replaceAltStreamCharsMode) 12Z7_COM7F_IMF(CAgentFolder::SetReplaceAltStreamCharsMode(Int32 replaceAltStreamCharsMode))
13{ 13{
14 _replaceAltStreamCharsMode = replaceAltStreamCharsMode; 14 _replaceAltStreamCharsMode = replaceAltStreamCharsMode;
15 return S_OK; 15 return S_OK;
16} 16}
17*/ 17*/
18 18
19STDMETHODIMP CAgentFolder::SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode) 19Z7_COM7F_IMF(CAgentFolder::SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode))
20{ 20{
21 _zoneMode = zoneMode; 21 _zoneMode = zoneMode;
22 return S_OK; 22 return S_OK;
23} 23}
24 24
25STDMETHODIMP CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, 25
26Z7_COM7F_IMF(CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems,
26 Int32 includeAltStreams, Int32 replaceAltStreamCharsMode, 27 Int32 includeAltStreams, Int32 replaceAltStreamCharsMode,
27 const wchar_t *path, IFolderOperationsExtractCallback *callback) 28 const wchar_t *path, IFolderOperationsExtractCallback *callback))
28{ 29{
29 if (moveMode) 30 if (moveMode)
30 return E_NOTIMPL; 31 return E_NOTIMPL;
@@ -32,7 +33,7 @@ STDMETHODIMP CAgentFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32
32 CMyComPtr<IFolderArchiveExtractCallback> extractCallback2; 33 CMyComPtr<IFolderArchiveExtractCallback> extractCallback2;
33 { 34 {
34 CMyComPtr<IFolderOperationsExtractCallback> callbackWrap = callback; 35 CMyComPtr<IFolderOperationsExtractCallback> callbackWrap = callback;
35 RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)); 36 RINOK(callbackWrap.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2))
36 } 37 }
37 NExtract::NPathMode::EEnum pathMode; 38 NExtract::NPathMode::EEnum pathMode;
38 if (!_flatMode) 39 if (!_flatMode)
diff --git a/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp b/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp
index 55457f4..3fa027d 100644
--- a/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp
+++ b/CPP/7zip/UI/Agent/ArchiveFolderOpen.cpp
@@ -2,26 +2,96 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5// #ifdef NEW_FOLDER_INTERFACE
6
7#include "../../../Common/StringToInt.h"
5#include "../../../Windows/DLL.h" 8#include "../../../Windows/DLL.h"
9#include "../../../Windows/ResourceString.h"
6 10
7#include "Agent.h" 11#include "Agent.h"
8 12
13extern HINSTANCE g_hInstance;
14static const UINT kIconTypesResId = 100;
15
16void CCodecIcons::LoadIcons(HMODULE m)
17{
18 IconPairs.Clear();
19 UString iconTypes;
20 NWindows::MyLoadString(m, kIconTypesResId, iconTypes);
21 UStringVector pairs;
22 SplitString(iconTypes, pairs);
23 FOR_VECTOR (i, pairs)
24 {
25 const UString &s = pairs[i];
26 int pos = s.Find(L':');
27 CIconPair iconPair;
28 iconPair.IconIndex = -1;
29 if (pos < 0)
30 pos = (int)s.Len();
31 else
32 {
33 const UString num = s.Ptr((unsigned)pos + 1);
34 if (!num.IsEmpty())
35 {
36 const wchar_t *end;
37 iconPair.IconIndex = (int)ConvertStringToUInt32(num, &end);
38 if (*end != 0)
39 continue;
40 }
41 }
42 iconPair.Ext = s.Left((unsigned)pos);
43 IconPairs.Add(iconPair);
44 }
45}
46
47bool CCodecIcons::FindIconIndex(const UString &ext, int &iconIndex) const
48{
49 iconIndex = -1;
50 FOR_VECTOR (i, IconPairs)
51 {
52 const CIconPair &pair = IconPairs[i];
53 if (ext.IsEqualTo_NoCase(pair.Ext))
54 {
55 iconIndex = pair.IconIndex;
56 return true;
57 }
58 }
59 return false;
60}
61
62
9void CArchiveFolderManager::LoadFormats() 63void CArchiveFolderManager::LoadFormats()
10{ 64{
65 if (WasLoaded)
66 return;
67
11 LoadGlobalCodecs(); 68 LoadGlobalCodecs();
69
70 #ifdef Z7_EXTERNAL_CODECS
71 CodecIconsVector.Clear();
72 FOR_VECTOR (i, g_CodecsObj->Libs)
73 {
74 CCodecIcons &ci = CodecIconsVector.AddNew();
75 ci.LoadIcons(g_CodecsObj->Libs[i].Lib.Get_HMODULE());
76 }
77 #endif
78 InternalIcons.LoadIcons(g_hInstance);
79 WasLoaded = true;
12} 80}
13 81
82/*
14int CArchiveFolderManager::FindFormat(const UString &type) 83int CArchiveFolderManager::FindFormat(const UString &type)
15{ 84{
16 FOR_VECTOR (i, g_CodecsObj->Formats) 85 FOR_VECTOR (i, g_CodecsObj->Formats)
17 if (type.IsEqualTo_NoCase(g_CodecsObj->Formats[i].Name)) 86 if (type.IsEqualTo_NoCase(g_CodecsObj->Formats[i].Name))
18 return i; 87 return (int)i;
19 return -1; 88 return -1;
20} 89}
90*/
21 91
22STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream, 92Z7_COM7F_IMF(CArchiveFolderManager::OpenFolderFile(IInStream *inStream,
23 const wchar_t *filePath, const wchar_t *arcFormat, 93 const wchar_t *filePath, const wchar_t *arcFormat,
24 IFolderFolder **resultFolder, IProgress *progress) 94 IFolderFolder **resultFolder, IProgress *progress))
25{ 95{
26 CMyComPtr<IArchiveOpenCallback> openArchiveCallback; 96 CMyComPtr<IArchiveOpenCallback> openArchiveCallback;
27 if (progress) 97 if (progress)
@@ -32,7 +102,7 @@ STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream,
32 CAgent *agent = new CAgent(); 102 CAgent *agent = new CAgent();
33 CMyComPtr<IInFolderArchive> archive = agent; 103 CMyComPtr<IInFolderArchive> archive = agent;
34 104
35 HRESULT res = agent->Open(inStream, filePath, arcFormat, NULL, openArchiveCallback); 105 const HRESULT res = archive->Open(inStream, filePath, arcFormat, NULL, openArchiveCallback);
36 106
37 if (res != S_OK) 107 if (res != S_OK)
38 { 108 {
@@ -44,7 +114,7 @@ STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream,
44 return res; 114 return res;
45 } 115 }
46 116
47 RINOK(agent->BindToRootFolder(resultFolder)); 117 RINOK(archive->BindToRootFolder(resultFolder))
48 return res; 118 return res;
49} 119}
50 120
@@ -58,7 +128,7 @@ HRESULT CAgent::FolderReOpen(
58 128
59 129
60/* 130/*
61STDMETHODIMP CArchiveFolderManager::GetExtensions(const wchar_t *type, BSTR *extensions) 131Z7_COM7F_IMF(CArchiveFolderManager::GetExtensions(const wchar_t *type, BSTR *extensions))
62{ 132{
63 *extensions = 0; 133 *extensions = 0;
64 int formatIndex = FindFormat(type); 134 int formatIndex = FindFormat(type);
@@ -78,47 +148,52 @@ static void AddIconExt(const CCodecIcons &lib, UString &dest)
78 } 148 }
79} 149}
80 150
81STDMETHODIMP CArchiveFolderManager::GetExtensions(BSTR *extensions) 151
152Z7_COM7F_IMF(CArchiveFolderManager::GetExtensions(BSTR *extensions))
82{ 153{
154 *extensions = NULL;
83 LoadFormats(); 155 LoadFormats();
84 *extensions = 0;
85 UString res; 156 UString res;
86 157
87 #ifdef EXTERNAL_CODECS 158 #ifdef Z7_EXTERNAL_CODECS
88 159 /*
89 FOR_VECTOR (i, g_CodecsObj->Libs) 160 FOR_VECTOR (i, g_CodecsObj->Libs)
90 AddIconExt(g_CodecsObj->Libs[i], res); 161 AddIconExt(g_CodecsObj->Libs[i].CodecIcons, res);
91 162 */
163 FOR_VECTOR (i, CodecIconsVector)
164 AddIconExt(CodecIconsVector[i], res);
92 #endif 165 #endif
93 166
94 AddIconExt(g_CodecsObj->InternalIcons, res); 167 AddIconExt(
168 // g_CodecsObj->
169 InternalIcons, res);
170
95 return StringToBstr(res, extensions); 171 return StringToBstr(res, extensions);
96} 172}
97 173
98STDMETHODIMP CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex) 174
175Z7_COM7F_IMF(CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex))
99{ 176{
100 *iconPath = 0; 177 *iconPath = NULL;
101 *iconIndex = 0; 178 *iconIndex = 0;
102
103 LoadFormats(); 179 LoadFormats();
104 180
105 #ifdef EXTERNAL_CODECS 181 #ifdef Z7_EXTERNAL_CODECS
106 182 // FOR_VECTOR (i, g_CodecsObj->Libs)
107 FOR_VECTOR (i, g_CodecsObj->Libs) 183 FOR_VECTOR (i, CodecIconsVector)
108 { 184 {
109 const CCodecLib &lib = g_CodecsObj->Libs[i];
110 int ii; 185 int ii;
111 if (lib.FindIconIndex(ext, ii)) 186 if (CodecIconsVector[i].FindIconIndex(ext, ii))
112 { 187 {
188 const CCodecLib &lib = g_CodecsObj->Libs[i];
113 *iconIndex = ii; 189 *iconIndex = ii;
114 return StringToBstr(fs2us(lib.Path), iconPath); 190 return StringToBstr(fs2us(lib.Path), iconPath);
115 } 191 }
116 } 192 }
117
118 #endif 193 #endif
119 194
120 int ii; 195 int ii;
121 if (g_CodecsObj->InternalIcons.FindIconIndex(ext, ii)) 196 if (InternalIcons.FindIconIndex(ext, ii))
122 { 197 {
123 FString path; 198 FString path;
124 if (NWindows::NDLL::MyGetModuleFileName(path)) 199 if (NWindows::NDLL::MyGetModuleFileName(path))
@@ -131,7 +206,7 @@ STDMETHODIMP CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPa
131} 206}
132 207
133/* 208/*
134STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types) 209Z7_COM7F_IMF(CArchiveFolderManager::GetTypes(BSTR *types))
135{ 210{
136 LoadFormats(); 211 LoadFormats();
137 UString typesStrings; 212 UString typesStrings;
@@ -146,9 +221,11 @@ STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types)
146 } 221 }
147 return StringToBstr(typesStrings, types); 222 return StringToBstr(typesStrings, types);
148} 223}
149STDMETHODIMP CArchiveFolderManager::CreateFolderFile(const wchar_t * type, 224Z7_COM7F_IMF(CArchiveFolderManager::CreateFolderFile(const wchar_t * type,
150 const wchar_t * filePath, IProgress progress) 225 const wchar_t * filePath, IProgress progress))
151{ 226{
152 return E_NOTIMPL; 227 return E_NOTIMPL;
153} 228}
154*/ 229*/
230
231// #endif
diff --git a/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp b/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp
index cd18c99..0189224 100644
--- a/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp
+++ b/CPP/7zip/UI/Agent/ArchiveFolderOut.cpp
@@ -83,7 +83,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
83 try 83 try
84 { 84 {
85 85
86 RINOK(_agentSpec->SetFolder(this)); 86 RINOK(_agentSpec->SetFolder(this))
87 87
88 // ---------- Save FolderItem ---------- 88 // ---------- Save FolderItem ----------
89 89
@@ -95,7 +95,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
95 FStringVector processedPaths; 95 FStringVector processedPaths;
96 96
97 CWorkDirTempFile tempFile; 97 CWorkDirTempFile tempFile;
98 RINOK(tempFile.CreateTempFile(us2fs(_agentSpec->_archiveFilePath))); 98 RINOK(tempFile.CreateTempFile(us2fs(_agentSpec->_archiveFilePath)))
99 { 99 {
100 CMyComPtr<IOutStream> tailStream; 100 CMyComPtr<IOutStream> tailStream;
101 const CArc &arc = *_agentSpec->_archiveLink.GetArc(); 101 const CArc &arc = *_agentSpec->_archiveLink.GetArc();
@@ -106,8 +106,8 @@ HRESULT CAgentFolder::CommonUpdateOperation(
106 { 106 {
107 if (arc.Offset < 0) 107 if (arc.Offset < 0)
108 return E_NOTIMPL; 108 return E_NOTIMPL;
109 RINOK(arc.InStream->Seek(0, STREAM_SEEK_SET, NULL)); 109 RINOK(arc.InStream->Seek(0, STREAM_SEEK_SET, NULL))
110 RINOK(NCompress::CopyStream_ExactSize(arc.InStream, tempFile.OutStream, arc.ArcStreamOffset, NULL)); 110 RINOK(NCompress::CopyStream_ExactSize(arc.InStream, tempFile.OutStream, arc.ArcStreamOffset, NULL))
111 CTailOutStream *tailStreamSpec = new CTailOutStream; 111 CTailOutStream *tailStreamSpec = new CTailOutStream;
112 tailStream = tailStreamSpec; 112 tailStream = tailStreamSpec;
113 tailStreamSpec->Stream = tempFile.OutStream; 113 tailStreamSpec->Stream = tempFile.OutStream;
@@ -117,7 +117,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
117 117
118 HRESULT result; 118 HRESULT result;
119 119
120 switch (operation) 120 switch ((int)operation)
121 { 121 {
122 case AGENT_OP_Delete: 122 case AGENT_OP_Delete:
123 result = _agentSpec->DeleteItems(tailStream, indices, numItems, updateCallback100); 123 result = _agentSpec->DeleteItems(tailStream, indices, numItems, updateCallback100);
@@ -149,18 +149,18 @@ HRESULT CAgentFolder::CommonUpdateOperation(
149 return E_FAIL; 149 return E_FAIL;
150 } 150 }
151 151
152 RINOK(result); 152 RINOK(result)
153 } 153 }
154 154
155 _agentSpec->KeepModeForNextOpen(); 155 _agentSpec->KeepModeForNextOpen();
156 _agentSpec->Close(); 156 _agent->Close();
157 157
158 // before 9.26: if there was error for MoveToOriginal archive was closed. 158 // before 9.26: if there was error for MoveToOriginal archive was closed.
159 // now: we reopen archive after close 159 // now: we reopen archive after close
160 160
161 // m_FolderItem = NULL; 161 // m_FolderItem = NULL;
162 162
163 HRESULT res = tempFile.MoveToOriginal(true); 163 const HRESULT res = tempFile.MoveToOriginal(true);
164 164
165 // RINOK(res); 165 // RINOK(res);
166 if (res == S_OK) 166 if (res == S_OK)
@@ -185,7 +185,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
185 CMyComPtr<IArchiveOpenCallback> openCallback; 185 CMyComPtr<IArchiveOpenCallback> openCallback;
186 if (updateCallback100) 186 if (updateCallback100)
187 updateCallback100->QueryInterface(IID_IArchiveOpenCallback, (void **)&openCallback); 187 updateCallback100->QueryInterface(IID_IArchiveOpenCallback, (void **)&openCallback);
188 RINOK(_agentSpec->ReOpen(openCallback)); 188 RINOK(_agent->ReOpen(openCallback))
189 } 189 }
190 190
191 // CAgent::ReOpen() deletes _proxy and _proxy2 191 // CAgent::ReOpen() deletes _proxy and _proxy2
@@ -199,7 +199,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
199 // ---------- Restore FolderItem ---------- 199 // ---------- Restore FolderItem ----------
200 200
201 CMyComPtr<IFolderFolder> archiveFolder; 201 CMyComPtr<IFolderFolder> archiveFolder;
202 RINOK(_agentSpec->BindToRootFolder(&archiveFolder)); 202 RINOK(_agent->BindToRootFolder(&archiveFolder))
203 203
204 // CAgent::BindToRootFolder() changes _proxy and _proxy2 204 // CAgent::BindToRootFolder() changes _proxy and _proxy2
205 _proxy = _agentSpec->_proxy; 205 _proxy = _agentSpec->_proxy;
@@ -209,10 +209,10 @@ HRESULT CAgentFolder::CommonUpdateOperation(
209 { 209 {
210 FOR_VECTOR (i, pathParts) 210 FOR_VECTOR (i, pathParts)
211 { 211 {
212 int next = _proxy->FindSubDir(_proxyDirIndex, pathParts[i]); 212 const int next = _proxy->FindSubDir(_proxyDirIndex, pathParts[i]);
213 if (next == -1) 213 if (next == -1)
214 break; 214 break;
215 _proxyDirIndex = next; 215 _proxyDirIndex = (unsigned)next;
216 } 216 }
217 } 217 }
218 218
@@ -224,19 +224,19 @@ HRESULT CAgentFolder::CommonUpdateOperation(
224 } 224 }
225 else FOR_VECTOR (i, pathParts) 225 else FOR_VECTOR (i, pathParts)
226 { 226 {
227 bool dirOnly = (i + 1 < pathParts.Size() || !isAltStreamFolder); 227 const bool dirOnly = (i + 1 < pathParts.Size() || !isAltStreamFolder);
228 int index = _proxy2->FindItem(_proxyDirIndex, pathParts[i], dirOnly); 228 const int index = _proxy2->FindItem(_proxyDirIndex, pathParts[i], dirOnly);
229 if (index == -1) 229 if (index == -1)
230 break; 230 break;
231 231
232 const CProxyFile2 &file = _proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]]; 232 const CProxyFile2 &file = _proxy2->Files[_proxy2->Dirs[_proxyDirIndex].Items[index]];
233 233
234 if (dirOnly) 234 if (dirOnly)
235 _proxyDirIndex = file.DirIndex; 235 _proxyDirIndex = (unsigned)file.DirIndex;
236 else 236 else
237 { 237 {
238 if (file.AltDirIndex != -1) 238 if (file.AltDirIndex != -1)
239 _proxyDirIndex = file.AltDirIndex; 239 _proxyDirIndex = (unsigned)file.AltDirIndex;
240 break; 240 break;
241 } 241 }
242 } 242 }
@@ -295,7 +295,7 @@ HRESULT CAgentFolder::CommonUpdateOperation(
295 { 295 {
296 UString s2 ("Error: "); 296 UString s2 ("Error: ");
297 s2 += s; 297 s2 += s;
298 RINOK(updateCallback100->UpdateErrorMessage(s2)); 298 RINOK(updateCallback100->UpdateErrorMessage(s2))
299 return E_FAIL; 299 return E_FAIL;
300 } 300 }
301 throw; 301 throw;
@@ -303,16 +303,15 @@ HRESULT CAgentFolder::CommonUpdateOperation(
303} 303}
304 304
305 305
306 306Z7_COM7F_IMF(CAgentFolder::CopyFrom(Int32 moveMode,
307STDMETHODIMP CAgentFolder::CopyFrom(Int32 moveMode, 307 const wchar_t *fromFolderPath, /* test it */
308 const wchar_t *fromFolderPath, // test it
309 const wchar_t * const *itemsPaths, 308 const wchar_t * const *itemsPaths,
310 UInt32 numItems, 309 UInt32 numItems,
311 IProgress *progress) 310 IProgress *progress))
312{ 311{
313 COM_TRY_BEGIN 312 COM_TRY_BEGIN
314 { 313 {
315 RINOK(_agentSpec->SetFiles(fromFolderPath, itemsPaths, numItems)); 314 RINOK(_agentSpec->SetFiles(fromFolderPath, itemsPaths, numItems))
316 return CommonUpdateOperation(AGENT_OP_Uni, (moveMode != 0), NULL, 315 return CommonUpdateOperation(AGENT_OP_Uni, (moveMode != 0), NULL,
317 &NUpdateArchive::k_ActionSet_Add, 316 &NUpdateArchive::k_ActionSet_Add,
318 NULL, 0, progress); 317 NULL, 0, progress);
@@ -320,7 +319,7 @@ STDMETHODIMP CAgentFolder::CopyFrom(Int32 moveMode,
320 COM_TRY_END 319 COM_TRY_END
321} 320}
322 321
323STDMETHODIMP CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPath, IProgress *progress) 322Z7_COM7F_IMF(CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPath, IProgress *progress))
324{ 323{
325 COM_TRY_BEGIN 324 COM_TRY_BEGIN
326 return CommonUpdateOperation(AGENT_OP_CopyFromFile, false, itemPath, 325 return CommonUpdateOperation(AGENT_OP_CopyFromFile, false, itemPath,
@@ -329,7 +328,7 @@ STDMETHODIMP CAgentFolder::CopyFromFile(UInt32 destIndex, const wchar_t *itemPat
329 COM_TRY_END 328 COM_TRY_END
330} 329}
331 330
332STDMETHODIMP CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress) 331Z7_COM7F_IMF(CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress))
333{ 332{
334 COM_TRY_BEGIN 333 COM_TRY_BEGIN
335 return CommonUpdateOperation(AGENT_OP_Delete, false, NULL, 334 return CommonUpdateOperation(AGENT_OP_Delete, false, NULL,
@@ -337,7 +336,7 @@ STDMETHODIMP CAgentFolder::Delete(const UInt32 *indices, UInt32 numItems, IProgr
337 COM_TRY_END 336 COM_TRY_END
338} 337}
339 338
340STDMETHODIMP CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress) 339Z7_COM7F_IMF(CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress))
341{ 340{
342 COM_TRY_BEGIN 341 COM_TRY_BEGIN
343 342
@@ -359,7 +358,7 @@ STDMETHODIMP CAgentFolder::CreateFolder(const wchar_t *name, IProgress *progress
359 COM_TRY_END 358 COM_TRY_END
360} 359}
361 360
362STDMETHODIMP CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress) 361Z7_COM7F_IMF(CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress))
363{ 362{
364 COM_TRY_BEGIN 363 COM_TRY_BEGIN
365 return CommonUpdateOperation(AGENT_OP_Rename, false, newName, NULL, 364 return CommonUpdateOperation(AGENT_OP_Rename, false, newName, NULL,
@@ -367,13 +366,13 @@ STDMETHODIMP CAgentFolder::Rename(UInt32 index, const wchar_t *newName, IProgres
367 COM_TRY_END 366 COM_TRY_END
368} 367}
369 368
370STDMETHODIMP CAgentFolder::CreateFile(const wchar_t * /* name */, IProgress * /* progress */) 369Z7_COM7F_IMF(CAgentFolder::CreateFile(const wchar_t * /* name */, IProgress * /* progress */))
371{ 370{
372 return E_NOTIMPL; 371 return E_NOTIMPL;
373} 372}
374 373
375STDMETHODIMP CAgentFolder::SetProperty(UInt32 index, PROPID propID, 374Z7_COM7F_IMF(CAgentFolder::SetProperty(UInt32 index, PROPID propID,
376 const PROPVARIANT *value, IProgress *progress) 375 const PROPVARIANT *value, IProgress *progress))
377{ 376{
378 COM_TRY_BEGIN 377 COM_TRY_BEGIN
379 if (propID != kpidComment || value->vt != VT_BSTR) 378 if (propID != kpidComment || value->vt != VT_BSTR)
diff --git a/CPP/7zip/UI/Agent/IFolderArchive.h b/CPP/7zip/UI/Agent/IFolderArchive.h
index 92eb616..55f1423 100644
--- a/CPP/7zip/UI/Agent/IFolderArchive.h
+++ b/CPP/7zip/UI/Agent/IFolderArchive.h
@@ -1,7 +1,7 @@
1// IFolderArchive.h 1// IFolderArchive.h
2 2
3#ifndef __IFOLDER_ARCHIVE_H 3#ifndef ZIP7_INC_IFOLDER_ARCHIVE_H
4#define __IFOLDER_ARCHIVE_H 4#define ZIP7_INC_IFOLDER_ARCHIVE_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
@@ -12,8 +12,7 @@
12#include "../Common/ExtractMode.h" 12#include "../Common/ExtractMode.h"
13#include "../Common/IFileExtractCallback.h" 13#include "../Common/IFileExtractCallback.h"
14 14
15#define FOLDER_ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 0x01, x) 15Z7_PURE_INTERFACES_BEGIN
16#define FOLDER_ARCHIVE_INTERFACE(i, x) FOLDER_ARCHIVE_INTERFACE_SUB(i, IUnknown, x)
17 16
18/* ---------- IArchiveFolder ---------- 17/* ---------- IArchiveFolder ----------
19IArchiveFolder is implemented by CAgentFolder (Agent/Agent.h) 18IArchiveFolder is implemented by CAgentFolder (Agent/Agent.h)
@@ -24,19 +23,16 @@ IArchiveFolder is used by:
24 CPlugin::ExtractFiles 23 CPlugin::ExtractFiles
25*/ 24*/
26 25
27#define INTERFACE_IArchiveFolder(x) \ 26#define Z7_IFACEM_IArchiveFolder(x) \
28 STDMETHOD(Extract)(const UInt32 *indices, UInt32 numItems, \ 27 x(Extract(const UInt32 *indices, UInt32 numItems, \
29 Int32 includeAltStreams, \ 28 Int32 includeAltStreams, \
30 Int32 replaceAltStreamCharsMode, \ 29 Int32 replaceAltStreamCharsMode, \
31 NExtract::NPathMode::EEnum pathMode, \ 30 NExtract::NPathMode::EEnum pathMode, \
32 NExtract::NOverwriteMode::EEnum overwriteMode, \ 31 NExtract::NOverwriteMode::EEnum overwriteMode, \
33 const wchar_t *path, Int32 testMode, \ 32 const wchar_t *path, Int32 testMode, \
34 IFolderArchiveExtractCallback *extractCallback2) x; \ 33 IFolderArchiveExtractCallback *extractCallback2)) \
35 34
36FOLDER_ARCHIVE_INTERFACE(IArchiveFolder, 0x0D) 35Z7_IFACE_CONSTR_FOLDERARC(IArchiveFolder, 0x0D)
37{
38 INTERFACE_IArchiveFolder(PURE)
39};
40 36
41 37
42/* ---------- IInFolderArchive ---------- 38/* ---------- IInFolderArchive ----------
@@ -44,85 +40,68 @@ IInFolderArchive is implemented by CAgent (Agent/Agent.h)
44IInFolderArchive Is used by FAR/Plugin 40IInFolderArchive Is used by FAR/Plugin
45*/ 41*/
46 42
47#define INTERFACE_IInFolderArchive(x) \ 43#define Z7_IFACEM_IInFolderArchive(x) \
48 STDMETHOD(Open)(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveTypeRes, IArchiveOpenCallback *openArchiveCallback) x; \ 44 x(Open(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, BSTR *archiveTypeRes, IArchiveOpenCallback *openArchiveCallback)) \
49 STDMETHOD(ReOpen)(IArchiveOpenCallback *openArchiveCallback) x; \ 45 x(ReOpen(IArchiveOpenCallback *openArchiveCallback)) \
50 STDMETHOD(Close)() x; \ 46 x(Close()) \
51 STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ 47 x(GetNumberOfProperties(UInt32 *numProperties)) \
52 STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ 48 x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
53 STDMETHOD(BindToRootFolder)(IFolderFolder **resultFolder) x; \ 49 x(BindToRootFolder(IFolderFolder **resultFolder)) \
54 STDMETHOD(Extract)(NExtract::NPathMode::EEnum pathMode, \ 50 x(Extract(NExtract::NPathMode::EEnum pathMode, \
55 NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, \ 51 NExtract::NOverwriteMode::EEnum overwriteMode, const wchar_t *path, \
56 Int32 testMode, IFolderArchiveExtractCallback *extractCallback2) x; \ 52 Int32 testMode, IFolderArchiveExtractCallback *extractCallback2)) \
57 53
58FOLDER_ARCHIVE_INTERFACE(IInFolderArchive, 0x0E) 54Z7_IFACE_CONSTR_FOLDERARC(IInFolderArchive, 0x0E)
59{ 55
60 INTERFACE_IInFolderArchive(PURE) 56#define Z7_IFACEM_IFolderArchiveUpdateCallback(x) \
61}; 57 x(CompressOperation(const wchar_t *name)) \
62 58 x(DeleteOperation(const wchar_t *name)) \
63#define INTERFACE_IFolderArchiveUpdateCallback(x) \ 59 x(OperationResult(Int32 opRes)) \
64 STDMETHOD(CompressOperation)(const wchar_t *name) x; \ 60 x(UpdateErrorMessage(const wchar_t *message)) \
65 STDMETHOD(DeleteOperation)(const wchar_t *name) x; \ 61 x(SetNumFiles(UInt64 numFiles)) \
66 STDMETHOD(OperationResult)(Int32 opRes) x; \ 62
67 STDMETHOD(UpdateErrorMessage)(const wchar_t *message) x; \ 63Z7_IFACE_CONSTR_FOLDERARC_SUB(IFolderArchiveUpdateCallback, IProgress, 0x0B)
68 STDMETHOD(SetNumFiles)(UInt64 numFiles) x; \ 64
69 65#define Z7_IFACEM_IOutFolderArchive(x) \
70FOLDER_ARCHIVE_INTERFACE_SUB(IFolderArchiveUpdateCallback, IProgress, 0x0B) 66 x(SetFolder(IFolderFolder *folder)) \
71{ 67 x(SetFiles(const wchar_t *folderPrefix, const wchar_t * const *names, UInt32 numNames)) \
72 INTERFACE_IFolderArchiveUpdateCallback(PURE) 68 x(DeleteItems(ISequentialOutStream *outArchiveStream, \
73}; 69 const UInt32 *indices, UInt32 numItems, IFolderArchiveUpdateCallback *updateCallback)) \
74 70 x(DoOperation( \
75#define INTERFACE_IOutFolderArchive(x) \
76 STDMETHOD(SetFolder)(IFolderFolder *folder) x; \
77 STDMETHOD(SetFiles)(const wchar_t *folderPrefix, const wchar_t * const *names, UInt32 numNames) x; \
78 STDMETHOD(DeleteItems)(ISequentialOutStream *outArchiveStream, \
79 const UInt32 *indices, UInt32 numItems, IFolderArchiveUpdateCallback *updateCallback) x; \
80 STDMETHOD(DoOperation)( \
81 FStringVector *requestedPaths, \ 71 FStringVector *requestedPaths, \
82 FStringVector *processedPaths, \ 72 FStringVector *processedPaths, \
83 CCodecs *codecs, int index, \ 73 CCodecs *codecs, int index, \
84 ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \ 74 ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \
85 IFolderArchiveUpdateCallback *updateCallback) x; \ 75 IFolderArchiveUpdateCallback *updateCallback)) \
86 STDMETHOD(DoOperation2)( \ 76 x(DoOperation2( \
87 FStringVector *requestedPaths, \ 77 FStringVector *requestedPaths, \
88 FStringVector *processedPaths, \ 78 FStringVector *processedPaths, \
89 ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \ 79 ISequentialOutStream *outArchiveStream, const Byte *stateActions, const wchar_t *sfxModule, \
90 IFolderArchiveUpdateCallback *updateCallback) x; \ 80 IFolderArchiveUpdateCallback *updateCallback)) \
91 81
92FOLDER_ARCHIVE_INTERFACE(IOutFolderArchive, 0x0F) 82Z7_IFACE_CONSTR_FOLDERARC(IOutFolderArchive, 0x0F)
93{
94 INTERFACE_IOutFolderArchive(PURE)
95};
96 83
97 84
98#define INTERFACE_IFolderArchiveUpdateCallback2(x) \ 85#define Z7_IFACEM_IFolderArchiveUpdateCallback2(x) \
99 STDMETHOD(OpenFileError)(const wchar_t *path, HRESULT errorCode) x; \ 86 x(OpenFileError(const wchar_t *path, HRESULT errorCode)) \
100 STDMETHOD(ReadingFileError)(const wchar_t *path, HRESULT errorCode) x; \ 87 x(ReadingFileError(const wchar_t *path, HRESULT errorCode)) \
101 STDMETHOD(ReportExtractResult)(Int32 opRes, Int32 isEncrypted, const wchar_t *path) x; \ 88 x(ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *path)) \
102 STDMETHOD(ReportUpdateOperation)(UInt32 notifyOp, const wchar_t *path, Int32 isDir) x; \ 89 x(ReportUpdateOperation(UInt32 notifyOp, const wchar_t *path, Int32 isDir)) \
103 90
104FOLDER_ARCHIVE_INTERFACE(IFolderArchiveUpdateCallback2, 0x10) 91Z7_IFACE_CONSTR_FOLDERARC(IFolderArchiveUpdateCallback2, 0x10)
105{
106 INTERFACE_IFolderArchiveUpdateCallback2(PURE)
107};
108 92
109 93
110#define INTERFACE_IFolderScanProgress(x) \ 94#define Z7_IFACEM_IFolderScanProgress(x) \
111 STDMETHOD(ScanError)(const wchar_t *path, HRESULT errorCode) x; \ 95 x(ScanError(const wchar_t *path, HRESULT errorCode)) \
112 STDMETHOD(ScanProgress)(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 isDir) x; \ 96 x(ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 isDir)) \
113 97
114FOLDER_ARCHIVE_INTERFACE(IFolderScanProgress, 0x11) 98Z7_IFACE_CONSTR_FOLDERARC(IFolderScanProgress, 0x11)
115{
116 INTERFACE_IFolderScanProgress(PURE)
117};
118 99
119 100
120#define INTERFACE_IFolderSetZoneIdMode(x) \ 101#define Z7_IFACEM_IFolderSetZoneIdMode(x) \
121 STDMETHOD(SetZoneIdMode)(NExtract::NZoneIdMode::EEnum zoneMode) x; \ 102 x(SetZoneIdMode(NExtract::NZoneIdMode::EEnum zoneMode)) \
122 103
123FOLDER_ARCHIVE_INTERFACE(IFolderSetZoneIdMode, 0x12) 104Z7_IFACE_CONSTR_FOLDERARC(IFolderSetZoneIdMode, 0x12)
124{
125 INTERFACE_IFolderSetZoneIdMode(PURE)
126};
127 105
106Z7_PURE_INTERFACES_END
128#endif 107#endif
diff --git a/CPP/7zip/UI/Agent/StdAfx.h b/CPP/7zip/UI/Agent/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/UI/Agent/StdAfx.h
+++ b/CPP/7zip/UI/Agent/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp b/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp
index 53a13bb..8299902 100644
--- a/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp
+++ b/CPP/7zip/UI/Agent/UpdateCallbackAgent.cpp
@@ -71,12 +71,12 @@ HRESULT CUpdateCallbackAgent::Finalize()
71 71
72HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemError) 72HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemError)
73{ 73{
74 HRESULT hres = HRESULT_FROM_WIN32(systemError); 74 const HRESULT hres = HRESULT_FROM_WIN32(systemError);
75 // if (systemError == ERROR_SHARING_VIOLATION) 75 // if (systemError == ERROR_SHARING_VIOLATION)
76 { 76 {
77 if (Callback2) 77 if (Callback2)
78 { 78 {
79 RINOK(Callback2->OpenFileError(fs2us(path), hres)); 79 RINOK(Callback2->OpenFileError(fs2us(path), hres))
80 return S_FALSE; 80 return S_FALSE;
81 } 81 }
82 82
@@ -86,7 +86,7 @@ HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemErr
86 s += NError::MyFormatMessage(systemError); 86 s += NError::MyFormatMessage(systemError);
87 s += ": "; 87 s += ": ";
88 s += fs2us(path); 88 s += fs2us(path);
89 RINOK(Callback->UpdateErrorMessage(s)); 89 RINOK(Callback->UpdateErrorMessage(s))
90 return S_FALSE; 90 return S_FALSE;
91 } 91 }
92 } 92 }
@@ -96,13 +96,13 @@ HRESULT CUpdateCallbackAgent::OpenFileError(const FString &path, DWORD systemErr
96 96
97HRESULT CUpdateCallbackAgent::ReadingFileError(const FString &path, DWORD systemError) 97HRESULT CUpdateCallbackAgent::ReadingFileError(const FString &path, DWORD systemError)
98{ 98{
99 HRESULT hres = HRESULT_FROM_WIN32(systemError); 99 const HRESULT hres = HRESULT_FROM_WIN32(systemError);
100 100
101 // if (systemError == ERROR_SHARING_VIOLATION) 101 // if (systemError == ERROR_SHARING_VIOLATION)
102 { 102 {
103 if (Callback2) 103 if (Callback2)
104 { 104 {
105 RINOK(Callback2->ReadingFileError(fs2us(path), hres)); 105 RINOK(Callback2->ReadingFileError(fs2us(path), hres))
106 } 106 }
107 else if (Callback) 107 else if (Callback)
108 { 108 {
@@ -110,7 +110,7 @@ HRESULT CUpdateCallbackAgent::ReadingFileError(const FString &path, DWORD system
110 s += NError::MyFormatMessage(systemError); 110 s += NError::MyFormatMessage(systemError);
111 s += ": "; 111 s += ": ";
112 s += fs2us(path); 112 s += fs2us(path);
113 RINOK(Callback->UpdateErrorMessage(s)); 113 RINOK(Callback->UpdateErrorMessage(s))
114 } 114 }
115 } 115 }
116 // FailedFiles.Add(name); 116 // FailedFiles.Add(name);
@@ -164,12 +164,12 @@ HRESULT CUpdateCallbackAgent::ReportUpdateOperation(UInt32 op, const wchar_t *na
164 164
165/* 165/*
166HRESULT CUpdateCallbackAgent::SetPassword(const UString & 166HRESULT CUpdateCallbackAgent::SetPassword(const UString &
167 #ifndef _NO_CRYPTO 167 #ifndef Z7_NO_CRYPTO
168 password 168 password
169 #endif 169 #endif
170 ) 170 )
171{ 171{
172 #ifndef _NO_CRYPTO 172 #ifndef Z7_NO_CRYPTO
173 PasswordIsDefined = true; 173 PasswordIsDefined = true;
174 Password = password; 174 Password = password;
175 #endif 175 #endif
diff --git a/CPP/7zip/UI/Agent/UpdateCallbackAgent.h b/CPP/7zip/UI/Agent/UpdateCallbackAgent.h
index 4da7693..179ce98 100644
--- a/CPP/7zip/UI/Agent/UpdateCallbackAgent.h
+++ b/CPP/7zip/UI/Agent/UpdateCallbackAgent.h
@@ -1,15 +1,15 @@
1// UpdateCallbackAgent.h 1// UpdateCallbackAgent.h
2 2
3#ifndef __UPDATE_CALLBACK_AGENT_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_AGENT_H
4#define __UPDATE_CALLBACK_AGENT_H 4#define ZIP7_INC_UPDATE_CALLBACK_AGENT_H
5 5
6#include "../Common/UpdateCallback.h" 6#include "../Common/UpdateCallback.h"
7 7
8#include "IFolderArchive.h" 8#include "IFolderArchive.h"
9 9
10class CUpdateCallbackAgent: public IUpdateCallbackUI 10class CUpdateCallbackAgent Z7_final: public IUpdateCallbackUI
11{ 11{
12 INTERFACE_IUpdateCallbackUI(;) 12 Z7_IFACE_IMP(IUpdateCallbackUI)
13 13
14 CMyComPtr<ICryptoGetTextPassword2> _cryptoGetTextPassword; 14 CMyComPtr<ICryptoGetTextPassword2> _cryptoGetTextPassword;
15 CMyComPtr<IFolderArchiveUpdateCallback> Callback; 15 CMyComPtr<IFolderArchiveUpdateCallback> Callback;
diff --git a/CPP/7zip/UI/Client7z/Client7z.cpp b/CPP/7zip/UI/Client7z/Client7z.cpp
index a55fa22..121a2f1 100644
--- a/CPP/7zip/UI/Client7z/Client7z.cpp
+++ b/CPP/7zip/UI/Client7z/Client7z.cpp
@@ -5,10 +5,9 @@
5#include <stdio.h> 5#include <stdio.h>
6 6
7#include "../../../Common/MyWindows.h" 7#include "../../../Common/MyWindows.h"
8
9#include "../../../Common/Defs.h"
10#include "../../../Common/MyInitGuid.h" 8#include "../../../Common/MyInitGuid.h"
11 9
10#include "../../../Common/Defs.h"
12#include "../../../Common/IntToString.h" 11#include "../../../Common/IntToString.h"
13#include "../../../Common/StringConvert.h" 12#include "../../../Common/StringConvert.h"
14 13
@@ -30,13 +29,13 @@
30#ifdef _WIN32 29#ifdef _WIN32
31extern 30extern
32HINSTANCE g_hInstance; 31HINSTANCE g_hInstance;
33HINSTANCE g_hInstance = 0; 32HINSTANCE g_hInstance = NULL;
34#endif 33#endif
35 34
36// You can find full list of all GUIDs supported by 7-Zip in Guid.txt file. 35// You can find full list of all GUIDs supported by 7-Zip in Guid.txt file.
37// 7z format GUID: {23170F69-40C1-278A-1000-000110070000} 36// 7z format GUID: {23170F69-40C1-278A-1000-000110070000}
38 37
39#define DEFINE_GUID_ARC(name, id) DEFINE_GUID(name, \ 38#define DEFINE_GUID_ARC(name, id) Z7_DEFINE_GUID(name, \
40 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, id, 0x00, 0x00); 39 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, id, 0x00, 0x00);
41 40
42enum 41enum
@@ -154,7 +153,7 @@ static void PrintError(const char *message, const FString &name)
154static HRESULT IsArchiveItemProp(IInArchive *archive, UInt32 index, PROPID propID, bool &result) 153static HRESULT IsArchiveItemProp(IInArchive *archive, UInt32 index, PROPID propID, bool &result)
155{ 154{
156 NCOM::CPropVariant prop; 155 NCOM::CPropVariant prop;
157 RINOK(archive->GetProperty(index, propID, &prop)); 156 RINOK(archive->GetProperty(index, propID, &prop))
158 if (prop.vt == VT_BOOL) 157 if (prop.vt == VT_BOOL)
159 result = VARIANT_BOOLToBool(prop.boolVal); 158 result = VARIANT_BOOLToBool(prop.boolVal);
160 else if (prop.vt == VT_EMPTY) 159 else if (prop.vt == VT_EMPTY)
@@ -177,18 +176,13 @@ static const wchar_t * const kEmptyFileAlias = L"[Content]";
177// Archive Open callback class 176// Archive Open callback class
178 177
179 178
180class CArchiveOpenCallback: 179class CArchiveOpenCallback Z7_final:
181 public IArchiveOpenCallback, 180 public IArchiveOpenCallback,
182 public ICryptoGetTextPassword, 181 public ICryptoGetTextPassword,
183 public CMyUnknownImp 182 public CMyUnknownImp
184{ 183{
184 Z7_IFACES_IMP_UNK_2(IArchiveOpenCallback, ICryptoGetTextPassword)
185public: 185public:
186 MY_UNKNOWN_IMP1(ICryptoGetTextPassword)
187
188 STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes);
189 STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes);
190
191 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
192 186
193 bool PasswordIsDefined; 187 bool PasswordIsDefined;
194 UString Password; 188 UString Password;
@@ -196,17 +190,17 @@ public:
196 CArchiveOpenCallback() : PasswordIsDefined(false) {} 190 CArchiveOpenCallback() : PasswordIsDefined(false) {}
197}; 191};
198 192
199STDMETHODIMP CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) 193Z7_COM7F_IMF(CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */))
200{ 194{
201 return S_OK; 195 return S_OK;
202} 196}
203 197
204STDMETHODIMP CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) 198Z7_COM7F_IMF(CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */))
205{ 199{
206 return S_OK; 200 return S_OK;
207} 201}
208 202
209STDMETHODIMP CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password) 203Z7_COM7F_IMF(CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password))
210{ 204{
211 if (!PasswordIsDefined) 205 if (!PasswordIsDefined)
212 { 206 {
@@ -321,27 +315,14 @@ struct CArcTime
321 315
322 316
323 317
324class CArchiveExtractCallback: 318class CArchiveExtractCallback Z7_final:
325 public IArchiveExtractCallback, 319 public IArchiveExtractCallback,
326 public ICryptoGetTextPassword, 320 public ICryptoGetTextPassword,
327 public CMyUnknownImp 321 public CMyUnknownImp
328{ 322{
329public: 323 Z7_IFACES_IMP_UNK_2(IArchiveExtractCallback, ICryptoGetTextPassword)
330 MY_UNKNOWN_IMP1(ICryptoGetTextPassword) 324 Z7_IFACE_COM7_IMP(IProgress)
331
332 // IProgress
333 STDMETHOD(SetTotal)(UInt64 size);
334 STDMETHOD(SetCompleted)(const UInt64 *completeValue);
335
336 // IArchiveExtractCallback
337 STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode);
338 STDMETHOD(PrepareOperation)(Int32 askExtractMode);
339 STDMETHOD(SetOperationResult)(Int32 resultEOperationResult);
340 325
341 // ICryptoGetTextPassword
342 STDMETHOD(CryptoGetTextPassword)(BSTR *aPassword);
343
344private:
345 CMyComPtr<IInArchive> _archiveHandler; 326 CMyComPtr<IInArchive> _archiveHandler;
346 FString _directoryPath; // Output directory 327 FString _directoryPath; // Output directory
347 UString _filePath; // name inside arcvhive 328 UString _filePath; // name inside arcvhive
@@ -376,26 +357,26 @@ void CArchiveExtractCallback::Init(IInArchive *archiveHandler, const FString &di
376 NName::NormalizeDirPathPrefix(_directoryPath); 357 NName::NormalizeDirPathPrefix(_directoryPath);
377} 358}
378 359
379STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 /* size */) 360Z7_COM7F_IMF(CArchiveExtractCallback::SetTotal(UInt64 /* size */))
380{ 361{
381 return S_OK; 362 return S_OK;
382} 363}
383 364
384STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */) 365Z7_COM7F_IMF(CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */))
385{ 366{
386 return S_OK; 367 return S_OK;
387} 368}
388 369
389STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, 370Z7_COM7F_IMF(CArchiveExtractCallback::GetStream(UInt32 index,
390 ISequentialOutStream **outStream, Int32 askExtractMode) 371 ISequentialOutStream **outStream, Int32 askExtractMode))
391{ 372{
392 *outStream = 0; 373 *outStream = NULL;
393 _outFileStream.Release(); 374 _outFileStream.Release();
394 375
395 { 376 {
396 // Get Name 377 // Get Name
397 NCOM::CPropVariant prop; 378 NCOM::CPropVariant prop;
398 RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop)); 379 RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop))
399 380
400 UString fullPath; 381 UString fullPath;
401 if (prop.vt == VT_EMPTY) 382 if (prop.vt == VT_EMPTY)
@@ -415,7 +396,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
415 { 396 {
416 // Get Attrib 397 // Get Attrib
417 NCOM::CPropVariant prop; 398 NCOM::CPropVariant prop;
418 RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop)); 399 RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop))
419 if (prop.vt == VT_EMPTY) 400 if (prop.vt == VT_EMPTY)
420 { 401 {
421 _processedFileInfo.Attrib = 0; 402 _processedFileInfo.Attrib = 0;
@@ -430,13 +411,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
430 } 411 }
431 } 412 }
432 413
433 RINOK(IsArchiveItemFolder(_archiveHandler, index, _processedFileInfo.isDir)); 414 RINOK(IsArchiveItemFolder(_archiveHandler, index, _processedFileInfo.isDir))
434 415
435 { 416 {
436 _processedFileInfo.MTime.Clear(); 417 _processedFileInfo.MTime.Clear();
437 // Get Modified Time 418 // Get Modified Time
438 NCOM::CPropVariant prop; 419 NCOM::CPropVariant prop;
439 RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop)); 420 RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop))
440 switch (prop.vt) 421 switch (prop.vt)
441 { 422 {
442 case VT_EMPTY: 423 case VT_EMPTY:
@@ -453,7 +434,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
453 { 434 {
454 // Get Size 435 // Get Size
455 NCOM::CPropVariant prop; 436 NCOM::CPropVariant prop;
456 RINOK(_archiveHandler->GetProperty(index, kpidSize, &prop)); 437 RINOK(_archiveHandler->GetProperty(index, kpidSize, &prop))
457 UInt64 newFileSize; 438 UInt64 newFileSize;
458 /* bool newFileSizeDefined = */ ConvertPropVariantToUInt64(prop, newFileSize); 439 /* bool newFileSizeDefined = */ ConvertPropVariantToUInt64(prop, newFileSize);
459 } 440 }
@@ -498,13 +479,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
498 return S_OK; 479 return S_OK;
499} 480}
500 481
501STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) 482Z7_COM7F_IMF(CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode))
502{ 483{
503 _extractMode = false; 484 _extractMode = false;
504 switch (askExtractMode) 485 switch (askExtractMode)
505 { 486 {
506 case NArchive::NExtract::NAskMode::kExtract: _extractMode = true; break; 487 case NArchive::NExtract::NAskMode::kExtract: _extractMode = true; break;
507 }; 488 }
508 switch (askExtractMode) 489 switch (askExtractMode)
509 { 490 {
510 case NArchive::NExtract::NAskMode::kExtract: Print(kExtractingString); break; 491 case NArchive::NExtract::NAskMode::kExtract: Print(kExtractingString); break;
@@ -513,12 +494,12 @@ STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode)
513 case NArchive::NExtract::NAskMode::kReadExternal: Print(kReadingString); break; 494 case NArchive::NExtract::NAskMode::kReadExternal: Print(kReadingString); break;
514 default: 495 default:
515 Print("??? "); break; 496 Print("??? "); break;
516 }; 497 }
517 Print(_filePath); 498 Print(_filePath);
518 return S_OK; 499 return S_OK;
519} 500}
520 501
521STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult) 502Z7_COM7F_IMF(CArchiveExtractCallback::SetOperationResult(Int32 operationResult))
522{ 503{
523 switch (operationResult) 504 switch (operationResult)
524 { 505 {
@@ -564,7 +545,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult)
564 else 545 else
565 { 546 {
566 char temp[16]; 547 char temp[16];
567 ConvertUInt32ToString(operationResult, temp); 548 ConvertUInt32ToString((UInt32)operationResult, temp);
568 Print("Error #"); 549 Print("Error #");
569 Print(temp); 550 Print(temp);
570 } 551 }
@@ -579,7 +560,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult)
579 _processedFileInfo.MTime.Write_To_FiTime(ft); 560 _processedFileInfo.MTime.Write_To_FiTime(ft);
580 _outFileStreamSpec->SetMTime(&ft); 561 _outFileStreamSpec->SetMTime(&ft);
581 } 562 }
582 RINOK(_outFileStreamSpec->Close()); 563 RINOK(_outFileStreamSpec->Close())
583 } 564 }
584 _outFileStream.Release(); 565 _outFileStream.Release();
585 if (_extractMode && _processedFileInfo.Attrib_Defined) 566 if (_extractMode && _processedFileInfo.Attrib_Defined)
@@ -589,7 +570,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult)
589} 570}
590 571
591 572
592STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password) 573Z7_COM7F_IMF(CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password))
593{ 574{
594 if (!PasswordIsDefined) 575 if (!PasswordIsDefined)
595 { 576 {
@@ -617,28 +598,14 @@ struct CDirItem: public NWindows::NFile::NFind::CFileInfoBase
617 {} 598 {}
618}; 599};
619 600
620class CArchiveUpdateCallback: 601class CArchiveUpdateCallback Z7_final:
621 public IArchiveUpdateCallback2, 602 public IArchiveUpdateCallback2,
622 public ICryptoGetTextPassword2, 603 public ICryptoGetTextPassword2,
623 public CMyUnknownImp 604 public CMyUnknownImp
624{ 605{
625public: 606 Z7_IFACES_IMP_UNK_2(IArchiveUpdateCallback2, ICryptoGetTextPassword2)
626 MY_UNKNOWN_IMP2(IArchiveUpdateCallback2, ICryptoGetTextPassword2) 607 Z7_IFACE_COM7_IMP(IProgress)
627 608 Z7_IFACE_COM7_IMP(IArchiveUpdateCallback)
628 // IProgress
629 STDMETHOD(SetTotal)(UInt64 size);
630 STDMETHOD(SetCompleted)(const UInt64 *completeValue);
631
632 // IUpdateCallback2
633 STDMETHOD(GetUpdateItemInfo)(UInt32 index,
634 Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive);
635 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value);
636 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream);
637 STDMETHOD(SetOperationResult)(Int32 operationResult);
638 STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size);
639 STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream);
640
641 STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password);
642 609
643public: 610public:
644 CRecordVector<UInt64> VolumesSizes; 611 CRecordVector<UInt64> VolumesSizes;
@@ -675,18 +642,18 @@ public:
675 } 642 }
676}; 643};
677 644
678STDMETHODIMP CArchiveUpdateCallback::SetTotal(UInt64 /* size */) 645Z7_COM7F_IMF(CArchiveUpdateCallback::SetTotal(UInt64 /* size */))
679{ 646{
680 return S_OK; 647 return S_OK;
681} 648}
682 649
683STDMETHODIMP CArchiveUpdateCallback::SetCompleted(const UInt64 * /* completeValue */) 650Z7_COM7F_IMF(CArchiveUpdateCallback::SetCompleted(const UInt64 * /* completeValue */))
684{ 651{
685 return S_OK; 652 return S_OK;
686} 653}
687 654
688STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */, 655Z7_COM7F_IMF(CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */,
689 Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive) 656 Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive))
690{ 657{
691 if (newData) 658 if (newData)
692 *newData = BoolToInt(true); 659 *newData = BoolToInt(true);
@@ -697,7 +664,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */,
697 return S_OK; 664 return S_OK;
698} 665}
699 666
700STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 667Z7_COM7F_IMF(CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
701{ 668{
702 NCOM::CPropVariant prop; 669 NCOM::CPropVariant prop;
703 670
@@ -744,9 +711,9 @@ static void GetStream2(const wchar_t *name)
744 Print(name); 711 Print(name);
745} 712}
746 713
747STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream) 714Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream))
748{ 715{
749 RINOK(Finilize()); 716 RINOK(Finilize())
750 717
751 const CDirItem &dirItem = (*DirItems)[index]; 718 const CDirItem &dirItem = (*DirItems)[index];
752 GetStream2(dirItem.Path_For_Handler); 719 GetStream2(dirItem.Path_For_Handler);
@@ -760,8 +727,8 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream
760 FString path = DirPrefix + dirItem.FullPath; 727 FString path = DirPrefix + dirItem.FullPath;
761 if (!inStreamSpec->Open(path)) 728 if (!inStreamSpec->Open(path))
762 { 729 {
763 DWORD sysError = ::GetLastError(); 730 const DWORD sysError = ::GetLastError();
764 FailedCodes.Add(sysError); 731 FailedCodes.Add(HRESULT_FROM_WIN32(sysError));
765 FailedFiles.Add(path); 732 FailedFiles.Add(path);
766 // if (systemError == ERROR_SHARING_VIOLATION) 733 // if (systemError == ERROR_SHARING_VIOLATION)
767 { 734 {
@@ -777,13 +744,13 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream
777 return S_OK; 744 return S_OK;
778} 745}
779 746
780STDMETHODIMP CArchiveUpdateCallback::SetOperationResult(Int32 /* operationResult */) 747Z7_COM7F_IMF(CArchiveUpdateCallback::SetOperationResult(Int32 /* operationResult */))
781{ 748{
782 m_NeedBeClosed = true; 749 m_NeedBeClosed = true;
783 return S_OK; 750 return S_OK;
784} 751}
785 752
786STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) 753Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size))
787{ 754{
788 if (VolumesSizes.Size() == 0) 755 if (VolumesSizes.Size() == 0)
789 return S_FALSE; 756 return S_FALSE;
@@ -793,7 +760,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size)
793 return S_OK; 760 return S_OK;
794} 761}
795 762
796STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream) 763Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream))
797{ 764{
798 wchar_t temp[16]; 765 wchar_t temp[16];
799 ConvertUInt32ToString(index + 1, temp); 766 ConvertUInt32ToString(index + 1, temp);
@@ -801,18 +768,18 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOu
801 while (res.Len() < 2) 768 while (res.Len() < 2)
802 res.InsertAtFront(L'0'); 769 res.InsertAtFront(L'0');
803 UString fileName = VolName; 770 UString fileName = VolName;
804 fileName += '.'; 771 fileName.Add_Dot();
805 fileName += res; 772 fileName += res;
806 fileName += VolExt; 773 fileName += VolExt;
807 COutFileStream *streamSpec = new COutFileStream; 774 COutFileStream *streamSpec = new COutFileStream;
808 CMyComPtr<ISequentialOutStream> streamLoc(streamSpec); 775 CMyComPtr<ISequentialOutStream> streamLoc(streamSpec);
809 if (!streamSpec->Create(us2fs(fileName), false)) 776 if (!streamSpec->Create(us2fs(fileName), false))
810 return ::GetLastError(); 777 return GetLastError_noZero_HRESULT();
811 *volumeStream = streamLoc.Detach(); 778 *volumeStream = streamLoc.Detach();
812 return S_OK; 779 return S_OK;
813} 780}
814 781
815STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) 782Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password))
816{ 783{
817 if (!PasswordIsDefined) 784 if (!PasswordIsDefined)
818 { 785 {
@@ -836,7 +803,7 @@ STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDef
836#define NT_CHECK_FAIL_ACTION PrintError("Unsupported Windows version"); return 1; 803#define NT_CHECK_FAIL_ACTION PrintError("Unsupported Windows version"); return 1;
837#endif 804#endif
838 805
839int MY_CDECL main(int numArgs, const char *args[]) 806int Z7_CDECL main(int numArgs, const char *args[])
840{ 807{
841 NT_CHECK 808 NT_CHECK
842 809
@@ -872,8 +839,11 @@ int MY_CDECL main(int numArgs, const char *args[])
872 return 1; 839 return 1;
873 } 840 }
874 841
875 Func_CreateObject createObjectFunc = (Func_CreateObject)lib.GetProc("CreateObject"); 842 Func_CreateObject
876 if (!createObjectFunc) 843 f_CreateObject = Z7_GET_PROC_ADDRESS(
844 Func_CreateObject, lib.Get_HMODULE(),
845 "CreateObject");
846 if (!f_CreateObject)
877 { 847 {
878 PrintError("Cannot get CreateObject"); 848 PrintError("Cannot get CreateObject");
879 return 1; 849 return 1;
@@ -966,7 +936,7 @@ int MY_CDECL main(int numArgs, const char *args[])
966 } 936 }
967 937
968 CMyComPtr<IOutArchive> outArchive; 938 CMyComPtr<IOutArchive> outArchive;
969 if (createObjectFunc(&CLSID_Format, &IID_IOutArchive, (void **)&outArchive) != S_OK) 939 if (f_CreateObject(&CLSID_Format, &IID_IOutArchive, (void **)&outArchive) != S_OK)
970 { 940 {
971 PrintError("Cannot get class object"); 941 PrintError("Cannot get class object");
972 return 1; 942 return 1;
@@ -986,7 +956,7 @@ int MY_CDECL main(int numArgs, const char *args[])
986 L"s", 956 L"s",
987 L"x" 957 L"x"
988 }; 958 };
989 const unsigned kNumProps = ARRAY_SIZE(names); 959 const unsigned kNumProps = Z7_ARRAY_SIZE(names);
990 NCOM::CPropVariant values[kNumProps] = 960 NCOM::CPropVariant values[kNumProps] =
991 { 961 {
992 L"lzma", 962 L"lzma",
@@ -1048,7 +1018,7 @@ int MY_CDECL main(int numArgs, const char *args[])
1048 } 1018 }
1049 1019
1050 CMyComPtr<IInArchive> archive; 1020 CMyComPtr<IInArchive> archive;
1051 if (createObjectFunc(&CLSID_Format, &IID_IInArchive, (void **)&archive) != S_OK) 1021 if (f_CreateObject(&CLSID_Format, &IID_IInArchive, (void **)&archive) != S_OK)
1052 { 1022 {
1053 PrintError("Cannot get class object"); 1023 PrintError("Cannot get class object");
1054 return 1; 1024 return 1;
diff --git a/CPP/7zip/UI/Client7z/Client7z.dsp b/CPP/7zip/UI/Client7z/Client7z.dsp
index b412c8e..d46300f 100644
--- a/CPP/7zip/UI/Client7z/Client7z.dsp
+++ b/CPP/7zip/UI/Client7z/Client7z.dsp
@@ -104,6 +104,10 @@ SOURCE=.\StdAfx.h
104# PROP Default_Filter "" 104# PROP Default_Filter ""
105# Begin Source File 105# Begin Source File
106 106
107SOURCE=..\..\..\Windows\Defs.h
108# End Source File
109# Begin Source File
110
107SOURCE=..\..\..\Windows\DLL.cpp 111SOURCE=..\..\..\Windows\DLL.cpp
108# End Source File 112# End Source File
109# Begin Source File 113# Begin Source File
@@ -144,6 +148,10 @@ SOURCE=..\..\..\Windows\FileName.h
144# End Source File 148# End Source File
145# Begin Source File 149# Begin Source File
146 150
151SOURCE=..\..\..\Windows\NtCheck.h
152# End Source File
153# Begin Source File
154
147SOURCE=..\..\..\Windows\PropVariant.cpp 155SOURCE=..\..\..\Windows\PropVariant.cpp
148# End Source File 156# End Source File
149# Begin Source File 157# Begin Source File
@@ -158,12 +166,24 @@ SOURCE=..\..\..\Windows\PropVariantConv.cpp
158 166
159SOURCE=..\..\..\Windows\PropVariantConv.h 167SOURCE=..\..\..\Windows\PropVariantConv.h
160# End Source File 168# End Source File
169# Begin Source File
170
171SOURCE=..\..\..\Windows\TimeUtils.h
172# End Source File
161# End Group 173# End Group
162# Begin Group "Common" 174# Begin Group "Common"
163 175
164# PROP Default_Filter "" 176# PROP Default_Filter ""
165# Begin Source File 177# Begin Source File
166 178
179SOURCE=..\..\..\Common\Common.h
180# End Source File
181# Begin Source File
182
183SOURCE=..\..\..\Common\Defs.h
184# End Source File
185# Begin Source File
186
167SOURCE=..\..\..\Common\IntToString.cpp 187SOURCE=..\..\..\Common\IntToString.cpp
168# End Source File 188# End Source File
169# Begin Source File 189# Begin Source File
@@ -172,6 +192,22 @@ SOURCE=..\..\..\Common\IntToString.h
172# End Source File 192# End Source File
173# Begin Source File 193# Begin Source File
174 194
195SOURCE=..\..\..\Common\MyBuffer.h
196# End Source File
197# Begin Source File
198
199SOURCE=..\..\..\Common\MyCom.h
200# End Source File
201# Begin Source File
202
203SOURCE=..\..\..\Common\MyInitGuid.h
204# End Source File
205# Begin Source File
206
207SOURCE=..\..\..\Common\MyLinux.h
208# End Source File
209# Begin Source File
210
175SOURCE=..\..\..\Common\MyString.cpp 211SOURCE=..\..\..\Common\MyString.cpp
176# End Source File 212# End Source File
177# Begin Source File 213# Begin Source File
@@ -180,6 +216,10 @@ SOURCE=..\..\..\Common\MyString.h
180# End Source File 216# End Source File
181# Begin Source File 217# Begin Source File
182 218
219SOURCE=..\..\..\Common\MyTypes.h
220# End Source File
221# Begin Source File
222
183SOURCE=..\..\..\Common\MyVector.cpp 223SOURCE=..\..\..\Common\MyVector.cpp
184# End Source File 224# End Source File
185# Begin Source File 225# Begin Source File
@@ -188,6 +228,10 @@ SOURCE=..\..\..\Common\MyVector.h
188# End Source File 228# End Source File
189# Begin Source File 229# Begin Source File
190 230
231SOURCE=..\..\..\Common\MyWindows.h
232# End Source File
233# Begin Source File
234
191SOURCE=..\..\..\Common\NewHandler.cpp 235SOURCE=..\..\..\Common\NewHandler.cpp
192# End Source File 236# End Source File
193# Begin Source File 237# Begin Source File
@@ -222,6 +266,54 @@ SOURCE=..\..\Common\FileStreams.cpp
222 266
223SOURCE=..\..\Common\FileStreams.h 267SOURCE=..\..\Common\FileStreams.h
224# End Source File 268# End Source File
269# Begin Source File
270
271SOURCE=..\..\Common\UniqBlocks.h
272# End Source File
273# End Group
274# Begin Group "C"
275
276# PROP Default_Filter ""
277# Begin Source File
278
279SOURCE=..\..\..\..\C\7zTypes.h
280# End Source File
281# Begin Source File
282
283SOURCE=..\..\..\..\C\7zVersion.h
284# End Source File
285# Begin Source File
286
287SOURCE=..\..\..\..\C\7zWindows.h
288# End Source File
289# Begin Source File
290
291SOURCE=..\..\..\..\C\Compiler.h
292# End Source File
293# Begin Source File
294
295SOURCE=..\..\..\..\C\CpuArch.h
296# End Source File
297# End Group
298# Begin Group "7zip"
299
300# PROP Default_Filter ""
301# Begin Source File
302
303SOURCE=..\..\IDecl.h
304# End Source File
305# Begin Source File
306
307SOURCE=..\..\IPassword.h
308# End Source File
309# Begin Source File
310
311SOURCE=..\..\IProgress.h
312# End Source File
313# Begin Source File
314
315SOURCE=..\..\PropID.h
316# End Source File
225# End Group 317# End Group
226# Begin Source File 318# Begin Source File
227 319
@@ -229,7 +321,7 @@ SOURCE=.\Client7z.cpp
229# End Source File 321# End Source File
230# Begin Source File 322# Begin Source File
231 323
232SOURCE=..\..\..\..\C\Sort.h 324SOURCE=..\..\Archive\IArchive.h
233# End Source File 325# End Source File
234# End Target 326# End Target
235# End Project 327# End Project
diff --git a/CPP/7zip/UI/Client7z/StdAfx.h b/CPP/7zip/UI/Client7z/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/UI/Client7z/StdAfx.h
+++ b/CPP/7zip/UI/Client7z/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/UI/Common/ArchiveCommandLine.cpp b/CPP/7zip/UI/Common/ArchiveCommandLine.cpp
index d88c851..2bdbc41 100644
--- a/CPP/7zip/UI/Common/ArchiveCommandLine.cpp
+++ b/CPP/7zip/UI/Common/ArchiveCommandLine.cpp
@@ -15,7 +15,7 @@
15 15
16#include <stdio.h> 16#include <stdio.h>
17 17
18#ifdef _7ZIP_LARGE_PAGES 18#ifdef Z7_LARGE_PAGES
19#include "../../../../C/Alloc.h" 19#include "../../../../C/Alloc.h"
20#endif 20#endif
21 21
@@ -42,7 +42,7 @@
42extern bool g_CaseSensitive; 42extern bool g_CaseSensitive;
43extern bool g_PathTrailReplaceMode; 43extern bool g_PathTrailReplaceMode;
44 44
45#ifdef _7ZIP_LARGE_PAGES 45#ifdef Z7_LARGE_PAGES
46extern 46extern
47bool g_LargePagesMode; 47bool g_LargePagesMode;
48bool g_LargePagesMode = false; 48bool g_LargePagesMode = false;
@@ -174,7 +174,7 @@ enum Enum
174 kDeleteAfterCompressing, 174 kDeleteAfterCompressing,
175 kSetArcMTime 175 kSetArcMTime
176 176
177 #ifndef _NO_CRYPTO 177 #ifndef Z7_NO_CRYPTO
178 , kPassword 178 , kPassword
179 #endif 179 #endif
180}; 180};
@@ -322,7 +322,7 @@ static const CSwitchForm kSwitchForms[] =
322 { "sdel", SWFRM_SIMPLE }, 322 { "sdel", SWFRM_SIMPLE },
323 { "stl", SWFRM_SIMPLE } 323 { "stl", SWFRM_SIMPLE }
324 324
325 #ifndef _NO_CRYPTO 325 #ifndef Z7_NO_CRYPTO
326 , { "p", SWFRM_STRING } 326 , { "p", SWFRM_STRING }
327 #endif 327 #endif
328}; 328};
@@ -340,7 +340,7 @@ static const char * const kEmptyFilePath = "Empty file path";
340 340
341bool CArcCommand::IsFromExtractGroup() const 341bool CArcCommand::IsFromExtractGroup() const
342{ 342{
343 switch (CommandType) 343 switch ((int)CommandType)
344 { 344 {
345 case NCommandType::kTest: 345 case NCommandType::kTest:
346 case NCommandType::kExtract: 346 case NCommandType::kExtract:
@@ -353,7 +353,7 @@ bool CArcCommand::IsFromExtractGroup() const
353 353
354NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const 354NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const
355{ 355{
356 switch (CommandType) 356 switch ((int)CommandType)
357 { 357 {
358 case NCommandType::kTest: 358 case NCommandType::kTest:
359 case NCommandType::kExtractFull: 359 case NCommandType::kExtractFull:
@@ -365,7 +365,7 @@ NExtract::NPathMode::EEnum CArcCommand::GetPathMode() const
365 365
366bool CArcCommand::IsFromUpdateGroup() const 366bool CArcCommand::IsFromUpdateGroup() const
367{ 367{
368 switch (CommandType) 368 switch ((int)CommandType)
369 { 369 {
370 case NCommandType::kAdd: 370 case NCommandType::kAdd:
371 case NCommandType::kUpdate: 371 case NCommandType::kUpdate:
@@ -438,7 +438,7 @@ static void AddNameToCensor(NWildcard::CCensor &censor,
438{ 438{
439 bool recursed = false; 439 bool recursed = false;
440 440
441 switch (nop.RecursedType) 441 switch ((int)nop.RecursedType)
442 { 442 {
443 case NRecursedType::kWildcardOnlyRecursed: 443 case NRecursedType::kWildcardOnlyRecursed:
444 recursed = DoesNameContainWildcard(name); 444 recursed = DoesNameContainWildcard(name);
@@ -905,7 +905,7 @@ static void SetAddCommandOptions(
905 CUpdateOptions &options) 905 CUpdateOptions &options)
906{ 906{
907 NUpdateArchive::CActionSet defaultActionSet; 907 NUpdateArchive::CActionSet defaultActionSet;
908 switch (commandType) 908 switch ((int)commandType)
909 { 909 {
910 case NCommandType::kAdd: 910 case NCommandType::kAdd:
911 defaultActionSet = NUpdateArchive::k_ActionSet_Add; 911 defaultActionSet = NUpdateArchive::k_ActionSet_Add;
@@ -944,8 +944,10 @@ static void SetAddCommandOptions(
944 FOR_VECTOR (i, sv) 944 FOR_VECTOR (i, sv)
945 { 945 {
946 UInt64 size; 946 UInt64 size;
947 if (!ParseComplexSize(sv[i], size) || size == 0) 947 if (!ParseComplexSize(sv[i], size))
948 throw CArcCmdLineException("Incorrect volume size:", sv[i]); 948 throw CArcCmdLineException("Incorrect volume size:", sv[i]);
949 if (i == sv.Size() - 1 && size == 0)
950 throw CArcCmdLineException("zero size last volume is not allowed");
949 options.VolumesSizes.Add(size); 951 options.VolumesSizes.Add(size);
950 } 952 }
951 } 953 }
@@ -992,7 +994,7 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings,
992 CArcCmdLineOptions &options) 994 CArcCmdLineOptions &options)
993{ 995{
994 Parse1Log.Empty(); 996 Parse1Log.Empty();
995 if (!parser.ParseStrings(kSwitchForms, ARRAY_SIZE(kSwitchForms), commandStrings)) 997 if (!parser.ParseStrings(kSwitchForms, Z7_ARRAY_SIZE(kSwitchForms), commandStrings))
996 throw CArcCmdLineException(parser.ErrorMessage, parser.ErrorLine); 998 throw CArcCmdLineException(parser.ErrorMessage, parser.ErrorLine);
997 999
998 options.IsInTerminal = MY_IS_TERMINAL(stdin); 1000 options.IsInTerminal = MY_IS_TERMINAL(stdin);
@@ -1054,7 +1056,7 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings,
1054 1056
1055 if (parser[NKey::kLargePages].ThereIs) 1057 if (parser[NKey::kLargePages].ThereIs)
1056 { 1058 {
1057 unsigned slp = 0; 1059 UInt32 slp = 0;
1058 const UString &s = parser[NKey::kLargePages].PostStrings[0]; 1060 const UString &s = parser[NKey::kLargePages].PostStrings[0];
1059 if (s.IsEmpty()) 1061 if (s.IsEmpty())
1060 slp = 1; 1062 slp = 1;
@@ -1064,7 +1066,7 @@ void CArcCmdLineParser::Parse1(const UStringVector &commandStrings,
1064 throw CArcCmdLineException("Unsupported switch postfix for -slp", s); 1066 throw CArcCmdLineException("Unsupported switch postfix for -slp", s);
1065 } 1067 }
1066 1068
1067 #ifdef _7ZIP_LARGE_PAGES 1069 #ifdef Z7_LARGE_PAGES
1068 if (slp > 1070 if (slp >
1069 #if defined(_WIN32) && !defined(UNDER_CE) 1071 #if defined(_WIN32) && !defined(UNDER_CE)
1070 (unsigned)NSecurity::Get_LargePages_RiskLevel() 1072 (unsigned)NSecurity::Get_LargePages_RiskLevel()
@@ -1181,8 +1183,8 @@ static const CCodePagePair g_CodePagePairs[] =
1181 { "utf-8", CP_UTF8 }, 1183 { "utf-8", CP_UTF8 },
1182 { "win", CP_ACP }, 1184 { "win", CP_ACP },
1183 { "dos", CP_OEMCP }, 1185 { "dos", CP_OEMCP },
1184 { "utf-16le", MY__CP_UTF16 }, 1186 { "utf-16le", Z7_WIN_CP_UTF16 },
1185 { "utf-16be", MY__CP_UTF16BE } 1187 { "utf-16be", Z7_WIN_CP_UTF16BE }
1186}; 1188};
1187 1189
1188static Int32 FindCharset(const NCommandLineParser::CParser &parser, unsigned keyIndex, 1190static Int32 FindCharset(const NCommandLineParser::CParser &parser, unsigned keyIndex,
@@ -1197,7 +1199,7 @@ static Int32 FindCharset(const NCommandLineParser::CParser &parser, unsigned key
1197 if (v < ((UInt32)1 << 16)) 1199 if (v < ((UInt32)1 << 16))
1198 return (Int32)v; 1200 return (Int32)v;
1199 name.MakeLower_Ascii(); 1201 name.MakeLower_Ascii();
1200 unsigned num = byteOnlyCodePages ? kNumByteOnlyCodePages : ARRAY_SIZE(g_CodePagePairs); 1202 const unsigned num = byteOnlyCodePages ? kNumByteOnlyCodePages : Z7_ARRAY_SIZE(g_CodePagePairs);
1201 for (unsigned i = 0;; i++) 1203 for (unsigned i = 0;; i++)
1202 { 1204 {
1203 if (i == num) // to disable warnings from different compilers 1205 if (i == num) // to disable warnings from different compilers
@@ -1355,7 +1357,7 @@ void CArcCmdLineParser::Parse2(CArcCmdLineOptions &options)
1355 options.YesToAll = parser[NKey::kYes].ThereIs; 1357 options.YesToAll = parser[NKey::kYes].ThereIs;
1356 1358
1357 1359
1358 #ifndef _NO_CRYPTO 1360 #ifndef Z7_NO_CRYPTO
1359 options.PasswordEnabled = parser[NKey::kPassword].ThereIs; 1361 options.PasswordEnabled = parser[NKey::kPassword].ThereIs;
1360 if (options.PasswordEnabled) 1362 if (options.PasswordEnabled)
1361 options.Password = parser[NKey::kPassword].PostStrings[0]; 1363 options.Password = parser[NKey::kPassword].PostStrings[0];
diff --git a/CPP/7zip/UI/Common/ArchiveCommandLine.h b/CPP/7zip/UI/Common/ArchiveCommandLine.h
index 745f999..9e375b5 100644
--- a/CPP/7zip/UI/Common/ArchiveCommandLine.h
+++ b/CPP/7zip/UI/Common/ArchiveCommandLine.h
@@ -1,7 +1,7 @@
1// ArchiveCommandLine.h 1// ArchiveCommandLine.h
2 2
3#ifndef __ARCHIVE_COMMAND_LINE_H 3#ifndef ZIP7_INC_ARCHIVE_COMMAND_LINE_H
4#define __ARCHIVE_COMMAND_LINE_H 4#define ZIP7_INC_ARCHIVE_COMMAND_LINE_H
5 5
6#include "../../../Common/CommandLineParser.h" 6#include "../../../Common/CommandLineParser.h"
7#include "../../../Common/Wildcard.h" 7#include "../../../Common/Wildcard.h"
@@ -66,6 +66,14 @@ struct CArcCmdLineOptions
66 bool TechMode; 66 bool TechMode;
67 bool ShowTime; 67 bool ShowTime;
68 68
69 CBoolPair NtSecurity;
70 CBoolPair AltStreams;
71 CBoolPair HardLinks;
72 CBoolPair SymLinks;
73
74 CBoolPair StoreOwnerId;
75 CBoolPair StoreOwnerName;
76
69 AString ListFields; 77 AString ListFields;
70 78
71 int ConsoleCodePage; 79 int ConsoleCodePage;
@@ -75,7 +83,7 @@ struct CArcCmdLineOptions
75 CArcCommand Command; 83 CArcCommand Command;
76 UString ArchiveName; 84 UString ArchiveName;
77 85
78 #ifndef _NO_CRYPTO 86 #ifndef Z7_NO_CRYPTO
79 bool PasswordEnabled; 87 bool PasswordEnabled;
80 UString Password; 88 UString Password;
81 #endif 89 #endif
@@ -83,7 +91,7 @@ struct CArcCmdLineOptions
83 UStringVector HashMethods; 91 UStringVector HashMethods;
84 // UString HashFilePath; 92 // UString HashFilePath;
85 93
86 bool AppendName; 94 // bool AppendName;
87 // UStringVector ArchivePathsSorted; 95 // UStringVector ArchivePathsSorted;
88 // UStringVector ArchivePathsFullSorted; 96 // UStringVector ArchivePathsFullSorted;
89 NWildcard::CCensor arcCensor; 97 NWildcard::CCensor arcCensor;
@@ -93,14 +101,6 @@ struct CArcCmdLineOptions
93 101
94 CExtractOptionsBase ExtractOptions; 102 CExtractOptionsBase ExtractOptions;
95 103
96 CBoolPair NtSecurity;
97 CBoolPair AltStreams;
98 CBoolPair HardLinks;
99 CBoolPair SymLinks;
100
101 CBoolPair StoreOwnerId;
102 CBoolPair StoreOwnerName;
103
104 CUpdateOptions UpdateOptions; 104 CUpdateOptions UpdateOptions;
105 CHashOptions HashOptions; 105 CHashOptions HashOptions;
106 UString ArcType; 106 UString ArcType;
@@ -145,7 +145,7 @@ struct CArcCmdLineOptions
145 145
146 LogLevel(0) 146 LogLevel(0)
147 { 147 {
148 }; 148 }
149}; 149};
150 150
151class CArcCmdLineParser 151class CArcCmdLineParser
diff --git a/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp b/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp
index a574f13..4b0cbed 100644
--- a/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp
+++ b/CPP/7zip/UI/Common/ArchiveExtractCallback.cpp
@@ -25,8 +25,8 @@
25#include "../../../Windows/PropVariant.h" 25#include "../../../Windows/PropVariant.h"
26#include "../../../Windows/PropVariantConv.h" 26#include "../../../Windows/PropVariantConv.h"
27 27
28#if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) 28#if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX)
29#define _USE_SECURITY_CODE 29#define Z7_USE_SECURITY_CODE
30#include "../../../Windows/SecurityUtils.h" 30#include "../../../Windows/SecurityUtils.h"
31#endif 31#endif
32 32
@@ -54,9 +54,9 @@ static const char * const kCantCreateHardLink = "Cannot create hard link";
54static const char * const kCantCreateSymLink = "Cannot create symbolic link"; 54static const char * const kCantCreateSymLink = "Cannot create symbolic link";
55#endif 55#endif
56 56
57#ifndef _SFX 57#ifndef Z7_SFX
58 58
59STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize) 59Z7_COM7F_IMF(COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *processedSize))
60{ 60{
61 HRESULT result = S_OK; 61 HRESULT result = S_OK;
62 if (_stream) 62 if (_stream)
@@ -69,10 +69,10 @@ STDMETHODIMP COutStreamWithHash::Write(const void *data, UInt32 size, UInt32 *pr
69 return result; 69 return result;
70} 70}
71 71
72#endif // _SFX 72#endif // Z7_SFX
73 73
74 74
75#ifdef _USE_SECURITY_CODE 75#ifdef Z7_USE_SECURITY_CODE
76bool InitLocalPrivileges(); 76bool InitLocalPrivileges();
77bool InitLocalPrivileges() 77bool InitLocalPrivileges()
78{ 78{
@@ -92,11 +92,11 @@ bool InitLocalPrivileges()
92 return false; 92 return false;
93 return (GetLastError() == ERROR_SUCCESS); 93 return (GetLastError() == ERROR_SUCCESS);
94} 94}
95#endif // _USE_SECURITY_CODE 95#endif // Z7_USE_SECURITY_CODE
96 96
97 97
98 98
99#if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) 99#if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX)
100 100
101static const char * const kOfficeExtensions = 101static const char * const kOfficeExtensions =
102 " doc dot wbk" 102 " doc dot wbk"
@@ -117,7 +117,7 @@ static bool FindExt2(const char *p, const UString &name)
117 return false; 117 return false;
118 118
119 AString s; 119 AString s;
120 for (unsigned pos = dotPos + 1;; pos++) 120 for (unsigned pos = (unsigned)(dotPos + 1);; pos++)
121 { 121 {
122 const wchar_t c = name[pos]; 122 const wchar_t c = name[pos];
123 if (c <= 0) 123 if (c <= 0)
@@ -142,7 +142,7 @@ static const FChar * const k_ZoneId_StreamName = FTEXT(":Zone.Identifier");
142 142
143void ReadZoneFile_Of_BaseFile(CFSTR fileName2, CByteBuffer &buf) 143void ReadZoneFile_Of_BaseFile(CFSTR fileName2, CByteBuffer &buf)
144{ 144{
145 FString fileName = fileName2; 145 FString fileName (fileName2);
146 fileName += k_ZoneId_StreamName; 146 fileName += k_ZoneId_StreamName;
147 147
148 buf.Free(); 148 buf.Free();
@@ -188,13 +188,13 @@ static HRESULT Archive_Get_HardLinkNode(IInArchive *archive, UInt32 index, CHard
188 defined = false; 188 defined = false;
189 { 189 {
190 NCOM::CPropVariant prop; 190 NCOM::CPropVariant prop;
191 RINOK(archive->GetProperty(index, kpidINode, &prop)); 191 RINOK(archive->GetProperty(index, kpidINode, &prop))
192 if (!ConvertPropVariantToUInt64(prop, h.INode)) 192 if (!ConvertPropVariantToUInt64(prop, h.INode))
193 return S_OK; 193 return S_OK;
194 } 194 }
195 { 195 {
196 NCOM::CPropVariant prop; 196 NCOM::CPropVariant prop;
197 RINOK(archive->GetProperty(index, kpidStreamId, &prop)); 197 RINOK(archive->GetProperty(index, kpidStreamId, &prop))
198 ConvertPropVariantToUInt64(prop, h.StreamId); 198 ConvertPropVariantToUInt64(prop, h.StreamId);
199 } 199 }
200 defined = true; 200 defined = true;
@@ -218,22 +218,27 @@ HRESULT CArchiveExtractCallback::PrepareHardLinks(const CRecordVector<UInt32> *r
218 numItems = realIndices->Size(); 218 numItems = realIndices->Size();
219 else 219 else
220 { 220 {
221 RINOK(archive->GetNumberOfItems(&numItems)); 221 RINOK(archive->GetNumberOfItems(&numItems))
222 } 222 }
223 223
224 for (UInt32 i = 0; i < numItems; i++) 224 for (UInt32 i = 0; i < numItems; i++)
225 { 225 {
226 CHardLinkNode h; 226 CHardLinkNode h;
227 bool defined; 227 bool defined;
228 UInt32 realIndex = realIndices ? (*realIndices)[i] : i; 228 const UInt32 realIndex = realIndices ? (*realIndices)[i] : i;
229 229
230 RINOK(Archive_Get_HardLinkNode(archive, realIndex, h, defined)); 230 RINOK(Archive_Get_HardLinkNode(archive, realIndex, h, defined))
231 if (defined) 231 if (defined)
232 { 232 {
233 bool isAltStream = false; 233 bool isAltStream = false;
234 RINOK(Archive_IsItem_AltStream(archive, realIndex, isAltStream)); 234 RINOK(Archive_IsItem_AltStream(archive, realIndex, isAltStream))
235 if (!isAltStream) 235 if (!isAltStream)
236 hardIDs.Add(h); 236 {
237 bool isDir = false;
238 RINOK(Archive_IsItem_Dir(archive, realIndex, isDir))
239 if (!isDir)
240 hardIDs.Add(h);
241 }
237 } 242 }
238 } 243 }
239 } 244 }
@@ -275,7 +280,7 @@ CArchiveExtractCallback::CArchiveExtractCallback():
275 LocalProgressSpec = new CLocalProgress(); 280 LocalProgressSpec = new CLocalProgress();
276 _localProgress = LocalProgressSpec; 281 _localProgress = LocalProgressSpec;
277 282
278 #ifdef _USE_SECURITY_CODE 283 #ifdef Z7_USE_SECURITY_CODE
279 _saclEnabled = InitLocalPrivileges(); 284 _saclEnabled = InitLocalPrivileges();
280 #endif 285 #endif
281} 286}
@@ -325,16 +330,18 @@ void CArchiveExtractCallback::Init(
325 330
326 _extractCallback2 = extractCallback2; 331 _extractCallback2 = extractCallback2;
327 332
333 /*
328 _compressProgress.Release(); 334 _compressProgress.Release();
329 _extractCallback2.QueryInterface(IID_ICompressProgressInfo, &_compressProgress); 335 _extractCallback2.QueryInterface(IID_ICompressProgressInfo, &_compressProgress);
330 336
331 _callbackMessage.Release(); 337 _callbackMessage.Release();
332 _extractCallback2.QueryInterface(IID_IArchiveExtractCallbackMessage, &_callbackMessage); 338 _extractCallback2.QueryInterface(IID_IArchiveExtractCallbackMessage2, &_callbackMessage);
339 */
333 340
334 _folderArchiveExtractCallback2.Release(); 341 _folderArchiveExtractCallback2.Release();
335 _extractCallback2.QueryInterface(IID_IFolderArchiveExtractCallback2, &_folderArchiveExtractCallback2); 342 _extractCallback2.QueryInterface(IID_IFolderArchiveExtractCallback2, &_folderArchiveExtractCallback2);
336 343
337 #ifndef _SFX 344 #ifndef Z7_SFX
338 345
339 ExtractToStreamCallback.Release(); 346 ExtractToStreamCallback.Release();
340 _extractCallback2.QueryInterface(IID_IFolderExtractToStreamCallback, &ExtractToStreamCallback); 347 _extractCallback2.QueryInterface(IID_IFolderExtractToStreamCallback, &ExtractToStreamCallback);
@@ -355,7 +362,7 @@ void CArchiveExtractCallback::Init(
355 _removePathParts = removePathParts; 362 _removePathParts = removePathParts;
356 _removePartsForAltStreams = removePartsForAltStreams; 363 _removePartsForAltStreams = removePartsForAltStreams;
357 364
358 #ifndef _SFX 365 #ifndef Z7_SFX
359 _baseParentFolder = (UInt32)(Int32)-1; 366 _baseParentFolder = (UInt32)(Int32)-1;
360 _use_baseParentFolder_mode = false; 367 _use_baseParentFolder_mode = false;
361 #endif 368 #endif
@@ -374,7 +381,7 @@ void CArchiveExtractCallback::Init(
374} 381}
375 382
376 383
377STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 size) 384Z7_COM7F_IMF(CArchiveExtractCallback::SetTotal(UInt64 size))
378{ 385{
379 COM_TRY_BEGIN 386 COM_TRY_BEGIN
380 _progressTotal = size; 387 _progressTotal = size;
@@ -407,7 +414,7 @@ static UInt64 MyMultDiv64(UInt64 unpCur, UInt64 unpTotal, UInt64 packTotal)
407} 414}
408 415
409 416
410STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue) 417Z7_COM7F_IMF(CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue))
411{ 418{
412 COM_TRY_BEGIN 419 COM_TRY_BEGIN
413 420
@@ -428,7 +435,7 @@ STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 *completeValue)
428} 435}
429 436
430 437
431STDMETHODIMP CArchiveExtractCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 438Z7_COM7F_IMF(CArchiveExtractCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
432{ 439{
433 COM_TRY_BEGIN 440 COM_TRY_BEGIN
434 return _localProgress->SetRatioInfo(inSize, outSize); 441 return _localProgress->SetRatioInfo(inSize, outSize);
@@ -510,7 +517,7 @@ HRESULT CArchiveExtractCallback::GetTime(UInt32 index, PROPID propID, CArcTime &
510{ 517{
511 ft.Clear(); 518 ft.Clear();
512 NCOM::CPropVariant prop; 519 NCOM::CPropVariant prop;
513 RINOK(_arc->Archive->GetProperty(index, propID, &prop)); 520 RINOK(_arc->Archive->GetProperty(index, propID, &prop))
514 if (prop.vt == VT_FILETIME) 521 if (prop.vt == VT_FILETIME)
515 ft.Set_From_Prop(prop); 522 ft.Set_From_Prop(prop);
516 else if (prop.vt != VT_EMPTY) 523 else if (prop.vt != VT_EMPTY)
@@ -521,7 +528,7 @@ HRESULT CArchiveExtractCallback::GetTime(UInt32 index, PROPID propID, CArcTime &
521 528
522HRESULT CArchiveExtractCallback::GetUnpackSize() 529HRESULT CArchiveExtractCallback::GetUnpackSize()
523{ 530{
524 return _arc->GetItem_Size(_index, _curSize, _curSizeDefined); 531 return _arc->GetItem_Size(_index, _curSize, _curSize_Defined);
525} 532}
526 533
527static void AddPathToMessage(UString &s, const FString &path) 534static void AddPathToMessage(UString &s, const FString &path)
@@ -564,9 +571,9 @@ HRESULT CArchiveExtractCallback::SendMessageError2(HRESULT errorCode, const char
564 return _extractCallback2->MessageError(s); 571 return _extractCallback2->MessageError(s);
565} 572}
566 573
567#ifndef _SFX 574#ifndef Z7_SFX
568 575
569STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value) 576Z7_COM7F_IMF(CGetProp::GetProp(PROPID propID, PROPVARIANT *value))
570{ 577{
571 /* 578 /*
572 if (propID == kpidName) 579 if (propID == kpidName)
@@ -581,7 +588,7 @@ STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value)
581 return Arc->Archive->GetProperty(IndexInArc, propID, value); 588 return Arc->Archive->GetProperty(IndexInArc, propID, value);
582} 589}
583 590
584#endif // _SFX 591#endif // Z7_SFX
585 592
586 593
587#ifdef SUPPORT_LINKS 594#ifdef SUPPORT_LINKS
@@ -749,15 +756,15 @@ HRESULT CArchiveExtractCallback::MyCopyFile(ISequentialOutStream *outStream)
749 NIO::CInFile inFile; 756 NIO::CInFile inFile;
750 NIO::COutFile outFile; 757 NIO::COutFile outFile;
751 758
752 if (!inFile.Open(_CopyFile_Path)) 759 if (!inFile.Open(_copyFile_Path))
753 return SendMessageError_with_LastError("Open error", _CopyFile_Path); 760 return SendMessageError_with_LastError("Open error", _copyFile_Path);
754 761
755 for (;;) 762 for (;;)
756 { 763 {
757 UInt32 num; 764 UInt32 num;
758 765
759 if (!inFile.Read(buf.Buf, kBufSize, num)) 766 if (!inFile.Read(buf.Buf, kBufSize, num))
760 return SendMessageError_with_LastError("Read error", _CopyFile_Path); 767 return SendMessageError_with_LastError("Read error", _copyFile_Path);
761 768
762 if (num == 0) 769 if (num == 0)
763 return S_OK; 770 return S_OK;
@@ -777,7 +784,7 @@ HRESULT CArchiveExtractCallback::ReadLink()
777 784
778 { 785 {
779 NCOM::CPropVariant prop; 786 NCOM::CPropVariant prop;
780 RINOK(archive->GetProperty(index, kpidHardLink, &prop)); 787 RINOK(archive->GetProperty(index, kpidHardLink, &prop))
781 if (prop.vt == VT_BSTR) 788 if (prop.vt == VT_BSTR)
782 { 789 {
783 _link.isHardLink = true; 790 _link.isHardLink = true;
@@ -807,7 +814,7 @@ HRESULT CArchiveExtractCallback::ReadLink()
807 814
808 { 815 {
809 NCOM::CPropVariant prop; 816 NCOM::CPropVariant prop;
810 RINOK(archive->GetProperty(index, kpidSymLink, &prop)); 817 RINOK(archive->GetProperty(index, kpidSymLink, &prop))
811 if (prop.vt == VT_BSTR) 818 if (prop.vt == VT_BSTR)
812 { 819 {
813 _link.isHardLink = false; 820 _link.isHardLink = false;
@@ -937,7 +944,7 @@ static HRESULT GetOwner(IInArchive *archive,
937{ 944{
938 { 945 {
939 NWindows::NCOM::CPropVariant prop; 946 NWindows::NCOM::CPropVariant prop;
940 RINOK(archive->GetProperty(index, pidId, &prop)); 947 RINOK(archive->GetProperty(index, pidId, &prop))
941 if (prop.vt == VT_UI4) 948 if (prop.vt == VT_UI4)
942 { 949 {
943 res.Id_Defined = true; 950 res.Id_Defined = true;
@@ -951,7 +958,7 @@ static HRESULT GetOwner(IInArchive *archive,
951 } 958 }
952 { 959 {
953 NWindows::NCOM::CPropVariant prop; 960 NWindows::NCOM::CPropVariant prop;
954 RINOK(archive->GetProperty(index, pidName, &prop)); 961 RINOK(archive->GetProperty(index, pidName, &prop))
955 if (prop.vt == VT_BSTR) 962 if (prop.vt == VT_BSTR)
956 { 963 {
957 const UString s = prop.bstrVal; 964 const UString s = prop.bstrVal;
@@ -981,11 +988,11 @@ HRESULT CArchiveExtractCallback::Read_fi_Props()
981 #ifndef _WIN32 988 #ifndef _WIN32
982 _fi.Owner.Clear(); 989 _fi.Owner.Clear();
983 _fi.Group.Clear(); 990 _fi.Group.Clear();
984 #endif 991 #endif
985 992
986 { 993 {
987 NCOM::CPropVariant prop; 994 NCOM::CPropVariant prop;
988 RINOK(archive->GetProperty(index, kpidPosixAttrib, &prop)); 995 RINOK(archive->GetProperty(index, kpidPosixAttrib, &prop))
989 if (prop.vt == VT_UI4) 996 if (prop.vt == VT_UI4)
990 { 997 {
991 _fi.SetFromPosixAttrib(prop.ulVal); 998 _fi.SetFromPosixAttrib(prop.ulVal);
@@ -996,7 +1003,7 @@ HRESULT CArchiveExtractCallback::Read_fi_Props()
996 1003
997 { 1004 {
998 NCOM::CPropVariant prop; 1005 NCOM::CPropVariant prop;
999 RINOK(archive->GetProperty(index, kpidAttrib, &prop)); 1006 RINOK(archive->GetProperty(index, kpidAttrib, &prop))
1000 if (prop.vt == VT_UI4) 1007 if (prop.vt == VT_UI4)
1001 { 1008 {
1002 _fi.Attrib = prop.ulVal; 1009 _fi.Attrib = prop.ulVal;
@@ -1006,9 +1013,9 @@ HRESULT CArchiveExtractCallback::Read_fi_Props()
1006 return E_FAIL; 1013 return E_FAIL;
1007 } 1014 }
1008 1015
1009 RINOK(GetTime(index, kpidCTime, _fi.CTime)); 1016 RINOK(GetTime(index, kpidCTime, _fi.CTime))
1010 RINOK(GetTime(index, kpidATime, _fi.ATime)); 1017 RINOK(GetTime(index, kpidATime, _fi.ATime))
1011 RINOK(GetTime(index, kpidMTime, _fi.MTime)); 1018 RINOK(GetTime(index, kpidMTime, _fi.MTime))
1012 1019
1013 #ifndef _WIN32 1020 #ifndef _WIN32
1014 if (_ntOptions.ExtractOwner) 1021 if (_ntOptions.ExtractOwner)
@@ -1104,9 +1111,19 @@ void CArchiveExtractCallback::CreateFolders()
1104 // 21.04 : we don't change original (_item.PathParts) here 1111 // 21.04 : we don't change original (_item.PathParts) here
1105 UStringVector pathParts = _item.PathParts; 1112 UStringVector pathParts = _item.PathParts;
1106 1113
1107 if (!_item.IsDir) 1114 if (!pathParts.IsEmpty())
1108 { 1115 {
1109 if (!pathParts.IsEmpty()) 1116 /* v23: if we extract symlink, and we know that it links to dir:
1117 Linux: we don't create dir item (symlink_from_path) here.
1118 Windows: SetReparseData() will create dir item, if it doesn't exist,
1119 but if we create dir item here, it's not problem. */
1120 if (!_item.IsDir
1121 #ifdef SUPPORT_LINKS
1122 #ifndef WIN32
1123 || !_link.linkPath.IsEmpty()
1124 #endif
1125 #endif
1126 )
1110 pathParts.DeleteBack(); 1127 pathParts.DeleteBack();
1111 } 1128 }
1112 1129
@@ -1167,7 +1184,7 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool
1167 RINOK(_extractCallback2->AskOverwrite( 1184 RINOK(_extractCallback2->AskOverwrite(
1168 fs2us(realFullProcessedPath), &ft1, &fileInfo.Size, _item.Path, 1185 fs2us(realFullProcessedPath), &ft1, &fileInfo.Size, _item.Path,
1169 _fi.MTime.Def ? &_fi.MTime.FT : NULL, 1186 _fi.MTime.Def ? &_fi.MTime.FT : NULL,
1170 _curSizeDefined ? &_curSize : NULL, 1187 _curSize_Defined ? &_curSize : NULL,
1171 &overwriteResult)) 1188 &overwriteResult))
1172 1189
1173 switch (overwriteResult) 1190 switch (overwriteResult)
@@ -1197,7 +1214,7 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool
1197 { 1214 {
1198 if (!AutoRenamePath(fullProcessedPath)) 1215 if (!AutoRenamePath(fullProcessedPath))
1199 { 1216 {
1200 RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)); 1217 RINOK(SendMessageError(kCantAutoRename, fullProcessedPath))
1201 return E_FAIL; 1218 return E_FAIL;
1202 } 1219 }
1203 _isRenamed = true; 1220 _isRenamed = true;
@@ -1207,14 +1224,14 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool
1207 FString existPath (fullProcessedPath); 1224 FString existPath (fullProcessedPath);
1208 if (!AutoRenamePath(existPath)) 1225 if (!AutoRenamePath(existPath))
1209 { 1226 {
1210 RINOK(SendMessageError(kCantAutoRename, fullProcessedPath)); 1227 RINOK(SendMessageError(kCantAutoRename, fullProcessedPath))
1211 return E_FAIL; 1228 return E_FAIL;
1212 } 1229 }
1213 // MyMoveFile can rename folders. So it's OK to use it for folders too 1230 // MyMoveFile can rename folders. So it's OK to use it for folders too
1214 if (!MyMoveFile(fullProcessedPath, existPath)) 1231 if (!MyMoveFile(fullProcessedPath, existPath))
1215 { 1232 {
1216 HRESULT errorCode = GetLastError_noZero_HRESULT(); 1233 HRESULT errorCode = GetLastError_noZero_HRESULT();
1217 RINOK(SendMessageError2(errorCode, kCantRenameFile, existPath, fullProcessedPath)); 1234 RINOK(SendMessageError2(errorCode, kCantRenameFile, existPath, fullProcessedPath))
1218 return E_FAIL; 1235 return E_FAIL;
1219 } 1236 }
1220 } 1237 }
@@ -1225,7 +1242,7 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool
1225 // do we need to delete all files in folder? 1242 // do we need to delete all files in folder?
1226 if (!RemoveDir(fullProcessedPath)) 1243 if (!RemoveDir(fullProcessedPath))
1227 { 1244 {
1228 RINOK(SendMessageError_with_LastError(kCantDeleteOutputDir, fullProcessedPath)); 1245 RINOK(SendMessageError_with_LastError(kCantDeleteOutputDir, fullProcessedPath))
1229 return S_OK; 1246 return S_OK;
1230 } 1247 }
1231 } 1248 }
@@ -1235,7 +1252,7 @@ HRESULT CArchiveExtractCallback::CheckExistFile(FString &fullProcessedPath, bool
1235 if (!DeleteFileAlways(fullProcessedPath)) 1252 if (!DeleteFileAlways(fullProcessedPath))
1236 if (GetLastError() != ERROR_FILE_NOT_FOUND) // check it in linux 1253 if (GetLastError() != ERROR_FILE_NOT_FOUND) // check it in linux
1237 { 1254 {
1238 RINOK(SendMessageError_with_LastError(kCantDeleteOutputFile, fullProcessedPath)); 1255 RINOK(SendMessageError_with_LastError(kCantDeleteOutputFile, fullProcessedPath))
1239 return S_OK; 1256 return S_OK;
1240 // return E_FAIL; 1257 // return E_FAIL;
1241 } 1258 }
@@ -1274,7 +1291,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1274{ 1291{
1275 needExit = true; 1292 needExit = true;
1276 1293
1277 RINOK(Read_fi_Props()); 1294 RINOK(Read_fi_Props())
1278 1295
1279 #ifdef SUPPORT_LINKS 1296 #ifdef SUPPORT_LINKS
1280 IInArchive *archive = _arc->Archive; 1297 IInArchive *archive = _arc->Archive;
@@ -1283,7 +1300,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1283 const UInt32 index = _index; 1300 const UInt32 index = _index;
1284 1301
1285 bool isAnti = false; 1302 bool isAnti = false;
1286 RINOK(_arc->IsItem_Anti(index, isAnti)); 1303 RINOK(_arc->IsItem_Anti(index, isAnti))
1287 1304
1288 CorrectPathParts(); 1305 CorrectPathParts();
1289 UString processedPath (MakePathFromParts(_item.PathParts)); 1306 UString processedPath (MakePathFromParts(_item.PathParts));
@@ -1333,7 +1350,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1333 } 1350 }
1334 else if (!_isSplit) 1351 else if (!_isSplit)
1335 { 1352 {
1336 RINOK(CheckExistFile(fullProcessedPath, needExit)); 1353 RINOK(CheckExistFile(fullProcessedPath, needExit))
1337 if (needExit) 1354 if (needExit)
1338 return S_OK; 1355 return S_OK;
1339 needExit = true; 1356 needExit = true;
@@ -1357,7 +1374,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1357 #ifndef UNDER_CE 1374 #ifndef UNDER_CE
1358 { 1375 {
1359 bool linkWasSet = false; 1376 bool linkWasSet = false;
1360 RINOK(SetFromLinkPath(fullProcessedPath, _link, linkWasSet)); 1377 RINOK(SetFromLinkPath(fullProcessedPath, _link, linkWasSet))
1361 if (linkWasSet) 1378 if (linkWasSet)
1362 { 1379 {
1363 _isSymLinkCreated = _link.IsSymLink(); 1380 _isSymLinkCreated = _link.IsSymLink();
@@ -1367,18 +1384,18 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1367 } 1384 }
1368 #endif // UNDER_CE 1385 #endif // UNDER_CE
1369 1386
1370 // if (_CopyFile_Path.IsEmpty()) 1387 // if (_copyFile_Path.IsEmpty())
1371 { 1388 {
1372 needExit = false; 1389 needExit = false;
1373 return S_OK; 1390 return S_OK;
1374 } 1391 }
1375 } 1392 }
1376 1393
1377 if (!_hardLinks.IDs.IsEmpty() && !_item.IsAltStream) 1394 if (!_hardLinks.IDs.IsEmpty() && !_item.IsAltStream && !_item.IsDir)
1378 { 1395 {
1379 CHardLinkNode h; 1396 CHardLinkNode h;
1380 bool defined; 1397 bool defined;
1381 RINOK(Archive_Get_HardLinkNode(archive, index, h, defined)); 1398 RINOK(Archive_Get_HardLinkNode(archive, index, h, defined))
1382 if (defined) 1399 if (defined)
1383 { 1400 {
1384 const int linkIndex = _hardLinks.IDs.FindInSorted2(h); 1401 const int linkIndex = _hardLinks.IDs.FindInSorted2(h);
@@ -1392,7 +1409,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1392 if (!MyCreateHardLink(fullProcessedPath, hl)) 1409 if (!MyCreateHardLink(fullProcessedPath, hl))
1393 { 1410 {
1394 HRESULT errorCode = GetLastError_noZero_HRESULT(); 1411 HRESULT errorCode = GetLastError_noZero_HRESULT();
1395 RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, hl)); 1412 RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, hl))
1396 return S_OK; 1413 return S_OK;
1397 } 1414 }
1398 1415
@@ -1412,13 +1429,13 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1412 // ---------- CREATE WRITE FILE ----- 1429 // ---------- CREATE WRITE FILE -----
1413 1430
1414 _outFileStreamSpec = new COutFileStream; 1431 _outFileStreamSpec = new COutFileStream;
1415 CMyComPtr<ISequentialOutStream> outFileStream_Loc(_outFileStreamSpec); 1432 CMyComPtr<IOutStream> outFileStream_Loc(_outFileStreamSpec);
1416 1433
1417 if (!_outFileStreamSpec->Open(fullProcessedPath, _isSplit ? OPEN_ALWAYS: CREATE_ALWAYS)) 1434 if (!_outFileStreamSpec->Open(fullProcessedPath, _isSplit ? OPEN_ALWAYS: CREATE_ALWAYS))
1418 { 1435 {
1419 // if (::GetLastError() != ERROR_FILE_EXISTS || !isSplit) 1436 // if (::GetLastError() != ERROR_FILE_EXISTS || !isSplit)
1420 { 1437 {
1421 RINOK(SendMessageError_with_LastError(kCantOpenOutFile, fullProcessedPath)); 1438 RINOK(SendMessageError_with_LastError(kCantOpenOutFile, fullProcessedPath))
1422 return S_OK; 1439 return S_OK;
1423 } 1440 }
1424 } 1441 }
@@ -1427,7 +1444,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1427 1444
1428 bool is_SymLink_in_Data = false; 1445 bool is_SymLink_in_Data = false;
1429 1446
1430 if (_curSizeDefined && _curSize > 0 && _curSize < (1 << 12)) 1447 if (_curSize_Defined && _curSize > 0 && _curSize < (1 << 12))
1431 { 1448 {
1432 if (_fi.IsLinuxSymLink()) 1449 if (_fi.IsLinuxSymLink())
1433 { 1450 {
@@ -1451,18 +1468,18 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1451 } 1468 }
1452 else // not reprase 1469 else // not reprase
1453 { 1470 {
1454 if (_ntOptions.PreAllocateOutFile && !_isSplit && _curSizeDefined && _curSize > (1 << 12)) 1471 if (_ntOptions.PreAllocateOutFile && !_isSplit && _curSize_Defined && _curSize > (1 << 12))
1455 { 1472 {
1456 // UInt64 ticks = GetCpuTicks(); 1473 // UInt64 ticks = GetCpuTicks();
1457 _fileLength_that_WasSet = _curSize; 1474 _fileLength_that_WasSet = _curSize;
1458 bool res = _outFileStreamSpec->File.SetLength(_curSize); 1475 bool res = _outFileStreamSpec->File.SetLength(_curSize);
1459 _fileLengthWasSet = res; 1476 _fileLength_WasSet = res;
1460 1477
1461 // ticks = GetCpuTicks() - ticks; 1478 // ticks = GetCpuTicks() - ticks;
1462 // printf("\nticks = %10d\n", (unsigned)ticks); 1479 // printf("\nticks = %10d\n", (unsigned)ticks);
1463 if (!res) 1480 if (!res)
1464 { 1481 {
1465 RINOK(SendMessageError_with_LastError(kCantSetFileLen, fullProcessedPath)); 1482 RINOK(SendMessageError_with_LastError(kCantSetFileLen, fullProcessedPath))
1466 } 1483 }
1467 1484
1468 /* 1485 /*
@@ -1484,7 +1501,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1484 res = _outFileStreamSpec->SeekToBegin_bool(); 1501 res = _outFileStreamSpec->SeekToBegin_bool();
1485 if (!res) 1502 if (!res)
1486 { 1503 {
1487 RINOK(SendMessageError_with_LastError("Cannot seek to begin of file", fullProcessedPath)); 1504 RINOK(SendMessageError_with_LastError("Cannot seek to begin of file", fullProcessedPath))
1488 } 1505 }
1489 } // PreAllocateOutFile 1506 } // PreAllocateOutFile
1490 1507
@@ -1501,7 +1518,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1501 1518
1502 if (_isSplit) 1519 if (_isSplit)
1503 { 1520 {
1504 RINOK(_outFileStreamSpec->Seek((Int64)_position, STREAM_SEEK_SET, NULL)); 1521 RINOK(outFileStream_Loc->Seek((Int64)_position, STREAM_SEEK_SET, NULL))
1505 } 1522 }
1506 outStreamLoc = outFileStream_Loc; 1523 outStreamLoc = outFileStream_Loc;
1507 } // if not reprase 1524 } // if not reprase
@@ -1516,7 +1533,7 @@ HRESULT CArchiveExtractCallback::GetExtractStream(CMyComPtr<ISequentialOutStream
1516 1533
1517HRESULT CArchiveExtractCallback::GetItem(UInt32 index) 1534HRESULT CArchiveExtractCallback::GetItem(UInt32 index)
1518{ 1535{
1519 #ifndef _SFX 1536 #ifndef Z7_SFX
1520 _item._use_baseParentFolder_mode = _use_baseParentFolder_mode; 1537 _item._use_baseParentFolder_mode = _use_baseParentFolder_mode;
1521 if (_use_baseParentFolder_mode) 1538 if (_use_baseParentFolder_mode)
1522 { 1539 {
@@ -1525,7 +1542,7 @@ HRESULT CArchiveExtractCallback::GetItem(UInt32 index)
1525 _pathMode == NExtract::NPathMode::kAbsPaths) 1542 _pathMode == NExtract::NPathMode::kAbsPaths)
1526 _item._baseParentFolder = -1; 1543 _item._baseParentFolder = -1;
1527 } 1544 }
1528 #endif // _SFX 1545 #endif // Z7_SFX
1529 1546
1530 #ifdef SUPPORT_ALT_STREAMS 1547 #ifdef SUPPORT_ALT_STREAMS
1531 _item.WriteToAltStreamIfColon = _ntOptions.WriteToAltStreamIfColon; 1548 _item.WriteToAltStreamIfColon = _ntOptions.WriteToAltStreamIfColon;
@@ -1535,13 +1552,13 @@ HRESULT CArchiveExtractCallback::GetItem(UInt32 index)
1535} 1552}
1536 1553
1537 1554
1538STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) 1555Z7_COM7F_IMF(CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode))
1539{ 1556{
1540 COM_TRY_BEGIN 1557 COM_TRY_BEGIN
1541 1558
1542 *outStream = NULL; 1559 *outStream = NULL;
1543 1560
1544 #ifndef _SFX 1561 #ifndef Z7_SFX
1545 if (_hashStream) 1562 if (_hashStream)
1546 _hashStreamSpec->ReleaseStream(); 1563 _hashStreamSpec->ReleaseStream();
1547 _hashStreamWasUsed = false; 1564 _hashStreamWasUsed = false;
@@ -1555,8 +1572,8 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1555 _isSplit = false; 1572 _isSplit = false;
1556 1573
1557 _curSize = 0; 1574 _curSize = 0;
1558 _curSizeDefined = false; 1575 _curSize_Defined = false;
1559 _fileLengthWasSet = false; 1576 _fileLength_WasSet = false;
1560 _fileLength_that_WasSet = 0; 1577 _fileLength_that_WasSet = 0;
1561 _index = index; 1578 _index = index;
1562 1579
@@ -1574,7 +1591,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1574 _itemFailure = false; 1591 _itemFailure = false;
1575 1592
1576 #ifdef SUPPORT_LINKS 1593 #ifdef SUPPORT_LINKS
1577 // _CopyFile_Path.Empty(); 1594 // _copyFile_Path.Empty();
1578 _link.Clear(); 1595 _link.Clear();
1579 #endif 1596 #endif
1580 1597
@@ -1590,16 +1607,16 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1590 else 1607 else
1591 _extractMode = true; 1608 _extractMode = true;
1592 break; 1609 break;
1593 }; 1610 }
1594 1611
1595 1612
1596 IInArchive *archive = _arc->Archive; 1613 IInArchive *archive = _arc->Archive;
1597 1614
1598 RINOK(GetItem(index)); 1615 RINOK(GetItem(index))
1599 1616
1600 { 1617 {
1601 NCOM::CPropVariant prop; 1618 NCOM::CPropVariant prop;
1602 RINOK(archive->GetProperty(index, kpidPosition, &prop)); 1619 RINOK(archive->GetProperty(index, kpidPosition, &prop))
1603 if (prop.vt != VT_EMPTY) 1620 if (prop.vt != VT_EMPTY)
1604 { 1621 {
1605 if (prop.vt != VT_UI8) 1622 if (prop.vt != VT_UI8)
@@ -1610,13 +1627,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1610 } 1627 }
1611 1628
1612 #ifdef SUPPORT_LINKS 1629 #ifdef SUPPORT_LINKS
1613 RINOK(ReadLink()); 1630 RINOK(ReadLink())
1614 #endif // SUPPORT_LINKS 1631 #endif // SUPPORT_LINKS
1615 1632
1616 1633
1617 RINOK(Archive_GetItemBoolProp(archive, index, kpidEncrypted, _encrypted)); 1634 RINOK(Archive_GetItemBoolProp(archive, index, kpidEncrypted, _encrypted))
1618 1635
1619 RINOK(GetUnpackSize()); 1636 RINOK(GetUnpackSize())
1620 1637
1621 #ifdef SUPPORT_ALT_STREAMS 1638 #ifdef SUPPORT_ALT_STREAMS
1622 if (!_ntOptions.AltStreams.Val && _item.IsAltStream) 1639 if (!_ntOptions.AltStreams.Val && _item.IsAltStream)
@@ -1632,7 +1649,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1632 return S_OK; 1649 return S_OK;
1633 } 1650 }
1634 1651
1635 #ifndef _SFX 1652 #ifndef Z7_SFX
1636 if (_use_baseParentFolder_mode) 1653 if (_use_baseParentFolder_mode)
1637 { 1654 {
1638 if (!pathParts.IsEmpty()) 1655 if (!pathParts.IsEmpty())
@@ -1651,7 +1668,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1651 } 1668 }
1652 } 1669 }
1653 else 1670 else
1654 #endif // _SFX 1671 #endif // Z7_SFX
1655 { 1672 {
1656 if (pathParts.IsEmpty()) 1673 if (pathParts.IsEmpty())
1657 { 1674 {
@@ -1734,12 +1751,8 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1734 numRemovePathParts = pathParts.Size() - 1; 1751 numRemovePathParts = pathParts.Size() - 1;
1735 break; 1752 break;
1736 } 1753 }
1737 /*
1738 case NExtract::NPathMode::kFullPaths:
1739 case NExtract::NPathMode::kAbsPaths: 1754 case NExtract::NPathMode::kAbsPaths:
1740 break; 1755 // default:
1741 */
1742 default:
1743 break; 1756 break;
1744 } 1757 }
1745 1758
@@ -1747,7 +1760,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1747 } 1760 }
1748 1761
1749 1762
1750 #ifndef _SFX 1763 #ifndef Z7_SFX
1751 1764
1752 if (ExtractToStreamCallback) 1765 if (ExtractToStreamCallback)
1753 { 1766 {
@@ -1772,7 +1785,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1772 return ExtractToStreamCallback->GetStream7(name, BoolToInt(_item.IsDir), outStream, askExtractMode, GetProp); 1785 return ExtractToStreamCallback->GetStream7(name, BoolToInt(_item.IsDir), outStream, askExtractMode, GetProp);
1773 } 1786 }
1774 1787
1775 #endif // _SFX 1788 #endif // Z7_SFX
1776 1789
1777 1790
1778 CMyComPtr<ISequentialOutStream> outStreamLoc; 1791 CMyComPtr<ISequentialOutStream> outStreamLoc;
@@ -1784,13 +1797,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1784 else 1797 else
1785 { 1798 {
1786 bool needExit = true; 1799 bool needExit = true;
1787 RINOK(GetExtractStream(outStreamLoc, needExit)); 1800 RINOK(GetExtractStream(outStreamLoc, needExit))
1788 if (needExit) 1801 if (needExit)
1789 return S_OK; 1802 return S_OK;
1790 } 1803 }
1791 } 1804 }
1792 1805
1793 #ifndef _SFX 1806 #ifndef Z7_SFX
1794 if (_hashStream) 1807 if (_hashStream)
1795 { 1808 {
1796 if (askExtractMode == NArchive::NExtract::NAskMode::kExtract || 1809 if (askExtractMode == NArchive::NExtract::NAskMode::kExtract ||
@@ -1802,13 +1815,13 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1802 _hashStreamWasUsed = true; 1815 _hashStreamWasUsed = true;
1803 } 1816 }
1804 } 1817 }
1805 #endif // _SFX 1818 #endif // Z7_SFX
1806 1819
1807 if (outStreamLoc) 1820 if (outStreamLoc)
1808 { 1821 {
1809 /* 1822 /*
1810 #ifdef SUPPORT_LINKS 1823 #ifdef SUPPORT_LINKS
1811 if (!_CopyFile_Path.IsEmpty()) 1824 if (!_copyFile_Path.IsEmpty())
1812 { 1825 {
1813 RINOK(PrepareOperation(askExtractMode)); 1826 RINOK(PrepareOperation(askExtractMode));
1814 RINOK(MyCopyFile(outStreamLoc)); 1827 RINOK(MyCopyFile(outStreamLoc));
@@ -1836,11 +1849,11 @@ STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStre
1836 1849
1837 1850
1838 1851
1839STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) 1852Z7_COM7F_IMF(CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode))
1840{ 1853{
1841 COM_TRY_BEGIN 1854 COM_TRY_BEGIN
1842 1855
1843 #ifndef _SFX 1856 #ifndef Z7_SFX
1844 if (ExtractToStreamCallback) 1857 if (ExtractToStreamCallback)
1845 return ExtractToStreamCallback->PrepareOperation7(askExtractMode); 1858 return ExtractToStreamCallback->PrepareOperation7(askExtractMode);
1846 #endif 1859 #endif
@@ -1855,10 +1868,10 @@ STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode)
1855 else 1868 else
1856 _extractMode = true; 1869 _extractMode = true;
1857 break; 1870 break;
1858 }; 1871 }
1859 1872
1860 return _extractCallback2->PrepareOperation(_item.Path, BoolToInt(_item.IsDir), 1873 return _extractCallback2->PrepareOperation(_item.Path, BoolToInt(_item.IsDir),
1861 askExtractMode, _isSplit ? &_position: 0); 1874 askExtractMode, _isSplit ? &_position: NULL);
1862 1875
1863 COM_TRY_END 1876 COM_TRY_END
1864} 1877}
@@ -1875,28 +1888,28 @@ HRESULT CArchiveExtractCallback::CloseFile()
1875 HRESULT hres = S_OK; 1888 HRESULT hres = S_OK;
1876 1889
1877 const UInt64 processedSize = _outFileStreamSpec->ProcessedSize; 1890 const UInt64 processedSize = _outFileStreamSpec->ProcessedSize;
1878 if (_fileLengthWasSet && _fileLength_that_WasSet > processedSize) 1891 if (_fileLength_WasSet && _fileLength_that_WasSet > processedSize)
1879 { 1892 {
1880 bool res = _outFileStreamSpec->File.SetLength(processedSize); 1893 const bool res = _outFileStreamSpec->File.SetLength(processedSize);
1881 _fileLengthWasSet = res; 1894 _fileLength_WasSet = res;
1882 if (!res) 1895 if (!res)
1883 { 1896 {
1884 HRESULT hres2 = SendMessageError_with_LastError(kCantSetFileLen, us2fs(_item.Path)); 1897 const HRESULT hres2 = SendMessageError_with_LastError(kCantSetFileLen, us2fs(_item.Path));
1885 if (hres == S_OK) 1898 if (hres == S_OK)
1886 hres = hres2; 1899 hres = hres2;
1887 } 1900 }
1888 } 1901 }
1889 1902
1890 _curSize = processedSize; 1903 _curSize = processedSize;
1891 _curSizeDefined = true; 1904 _curSize_Defined = true;
1892 1905
1893 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) 1906 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX)
1894 if (ZoneBuf.Size() != 0 1907 if (ZoneBuf.Size() != 0
1895 && !_item.IsAltStream) 1908 && !_item.IsAltStream)
1896 { 1909 {
1897 // if (NFind::DoesFileExist_Raw(tempFilePath)) 1910 // if (NFind::DoesFileExist_Raw(tempFilePath))
1898 if (ZoneMode != NExtract::NZoneIdMode::kOffice || 1911 if (ZoneMode != NExtract::NZoneIdMode::kOffice ||
1899 FindExt2(kOfficeExtensions, _diskFilePath)) 1912 FindExt2(kOfficeExtensions, fs2us(_diskFilePath)))
1900 { 1913 {
1901 // we must write zone file before setting of timestamps 1914 // we must write zone file before setting of timestamps
1902 const FString path = _diskFilePath + k_ZoneId_StreamName; 1915 const FString path = _diskFilePath + k_ZoneId_StreamName;
@@ -1920,7 +1933,7 @@ HRESULT CArchiveExtractCallback::CloseFile()
1920 t.MTime_Defined ? &t.MTime : NULL); 1933 t.MTime_Defined ? &t.MTime : NULL);
1921 // #endif 1934 // #endif
1922 1935
1923 RINOK(_outFileStreamSpec->Close()); 1936 RINOK(_outFileStreamSpec->Close())
1924 _outFileStream.Release(); 1937 _outFileStream.Release();
1925 return hres; 1938 return hres;
1926} 1939}
@@ -1964,7 +1977,7 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath(
1964 { 1977 {
1965 if (!NName::GetFullPath(_dirPathPrefix_Full, us2fs(relatPath), existPath)) 1978 if (!NName::GetFullPath(_dirPathPrefix_Full, us2fs(relatPath), existPath))
1966 { 1979 {
1967 RINOK(SendMessageError("Incorrect path", us2fs(relatPath))); 1980 RINOK(SendMessageError("Incorrect path", us2fs(relatPath)))
1968 } 1981 }
1969 } 1982 }
1970 else 1983 else
@@ -1982,8 +1995,8 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath(
1982 { 1995 {
1983 if (!MyCreateHardLink(fullProcessedPath, existPath)) 1996 if (!MyCreateHardLink(fullProcessedPath, existPath))
1984 { 1997 {
1985 HRESULT errorCode = GetLastError_noZero_HRESULT(); 1998 const HRESULT errorCode = GetLastError_noZero_HRESULT();
1986 RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, existPath)); 1999 RINOK(SendMessageError2(errorCode, kCantCreateHardLink, fullProcessedPath, existPath))
1987 } 2000 }
1988 linkWasSet = true; 2001 linkWasSet = true;
1989 return S_OK; 2002 return S_OK;
@@ -1998,8 +2011,8 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath(
1998 } 2011 }
1999 else 2012 else
2000 { 2013 {
2001 if (_curSizeDefined && _curSize == fi.Size) 2014 if (_curSize_Defined && _curSize == fi.Size)
2002 _CopyFile_Path = existPath; 2015 _copyFile_Path = existPath;
2003 else 2016 else
2004 { 2017 {
2005 RINOK(SendMessageError2("File size collision for file copying", existPath, fullProcessedPath)); 2018 RINOK(SendMessageError2("File size collision for file copying", existPath, fullProcessedPath));
@@ -2060,12 +2073,12 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath(
2060 CReparseAttr attr; 2073 CReparseAttr attr;
2061 if (!attr.Parse(data, data.Size())) 2074 if (!attr.Parse(data, data.Size()))
2062 { 2075 {
2063 RINOK(SendMessageError("Internal error for symbolic link file", us2fs(_item.Path))); 2076 RINOK(SendMessageError("Internal error for symbolic link file", us2fs(_item.Path)))
2064 return S_OK; 2077 return S_OK;
2065 } 2078 }
2066 if (!NFile::NIO::SetReparseData(fullProcessedPath, _item.IsDir, data, (DWORD)data.Size())) 2079 if (!NFile::NIO::SetReparseData(fullProcessedPath, _item.IsDir, data, (DWORD)data.Size()))
2067 { 2080 {
2068 RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)); 2081 RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath))
2069 return S_OK; 2082 return S_OK;
2070 } 2083 }
2071 linkWasSet = true; 2084 linkWasSet = true;
@@ -2077,7 +2090,7 @@ HRESULT CArchiveExtractCallback::SetFromLinkPath(
2077 2090
2078 if (!NFile::NIO::SetSymLink(fullProcessedPath, existPath)) 2091 if (!NFile::NIO::SetSymLink(fullProcessedPath, existPath))
2079 { 2092 {
2080 RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath)); 2093 RINOK(SendMessageError_with_LastError(kCantCreateSymLink, fullProcessedPath))
2081 return S_OK; 2094 return S_OK;
2082 } 2095 }
2083 linkWasSet = true; 2096 linkWasSet = true;
@@ -2110,7 +2123,7 @@ bool CLinkInfo::Parse(const Byte *data, size_t dataSize, bool isLinuxData)
2110 // if windows link was created, then we also must use linux separator 2123 // if windows link was created, then we also must use linux separator
2111 if (u.IsEmpty()) 2124 if (u.IsEmpty())
2112 return false; 2125 return false;
2113 wchar_t c = u[0]; 2126 const wchar_t c = u[0];
2114 isRelative = !IS_PATH_SEPAR(c); 2127 isRelative = !IS_PATH_SEPAR(c);
2115 return true; 2128 return true;
2116 } 2129 }
@@ -2157,7 +2170,7 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile()
2157 { 2170 {
2158 repraseMode = true; 2171 repraseMode = true;
2159 reparseSize = _bufPtrSeqOutStream_Spec->GetPos(); 2172 reparseSize = _bufPtrSeqOutStream_Spec->GetPos();
2160 if (_curSizeDefined && reparseSize == _outMemBuf.Size()) 2173 if (_curSize_Defined && reparseSize == _outMemBuf.Size())
2161 { 2174 {
2162 /* 2175 /*
2163 CReparseAttr reparse; 2176 CReparseAttr reparse;
@@ -2181,7 +2194,7 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile()
2181 } 2194 }
2182 if (!needSetReparse && _outFileStream) 2195 if (!needSetReparse && _outFileStream)
2183 { 2196 {
2184 HRESULT res2 = WriteStream(_outFileStream, _outMemBuf, reparseSize); 2197 const HRESULT res2 = WriteStream(_outFileStream, _outMemBuf, reparseSize);
2185 if (res == S_OK) 2198 if (res == S_OK)
2186 res = res2; 2199 res = res2;
2187 } 2200 }
@@ -2191,18 +2204,18 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile()
2191 #endif // SUPPORT_LINKS 2204 #endif // SUPPORT_LINKS
2192 2205
2193 2206
2194 HRESULT res2 = CloseFile(); 2207 const HRESULT res2 = CloseFile();
2195 2208
2196 if (res == S_OK) 2209 if (res == S_OK)
2197 res = res2; 2210 res = res2;
2198 2211
2199 RINOK(res); 2212 RINOK(res)
2200 2213
2201 #ifdef SUPPORT_LINKS 2214 #ifdef SUPPORT_LINKS
2202 if (repraseMode) 2215 if (repraseMode)
2203 { 2216 {
2204 _curSize = reparseSize; 2217 _curSize = reparseSize;
2205 _curSizeDefined = true; 2218 _curSize_Defined = true;
2206 2219
2207 #ifdef SUPPORT_LINKS 2220 #ifdef SUPPORT_LINKS
2208 if (needSetReparse) 2221 if (needSetReparse)
@@ -2211,19 +2224,19 @@ HRESULT CArchiveExtractCallback::CloseReparseAndFile()
2211 // in Windows : we can create symbolic link even without file deleting 2224 // in Windows : we can create symbolic link even without file deleting
2212 if (!DeleteFileAlways(_diskFilePath)) 2225 if (!DeleteFileAlways(_diskFilePath))
2213 { 2226 {
2214 RINOK(SendMessageError_with_LastError("can't delete file", _diskFilePath)); 2227 RINOK(SendMessageError_with_LastError("can't delete file", _diskFilePath))
2215 } 2228 }
2216 { 2229 {
2217 /* 2230 /*
2218 // for DEBUG ONLY: we can extract sym links as WSL links 2231 // for DEBUG ONLY: we can extract sym links as WSL links
2219 // to elimanate (non-admin) errors for sym links. 2232 // to eliminate (non-admin) errors for sym links.
2220 #ifdef _WIN32 2233 #ifdef _WIN32
2221 if (!linkInfo.isHardLink && !linkInfo.isJunction) 2234 if (!linkInfo.isHardLink && !linkInfo.isJunction)
2222 linkInfo.isWSL = true; 2235 linkInfo.isWSL = true;
2223 #endif 2236 #endif
2224 */ 2237 */
2225 bool linkWasSet = false; 2238 bool linkWasSet = false;
2226 RINOK(SetFromLinkPath(_diskFilePath, linkInfo, linkWasSet)); 2239 RINOK(SetFromLinkPath(_diskFilePath, linkInfo, linkWasSet))
2227 if (linkWasSet) 2240 if (linkWasSet)
2228 _isSymLinkCreated = linkInfo.IsSymLink(); 2241 _isSymLinkCreated = linkInfo.IsSymLink();
2229 else 2242 else
@@ -2282,13 +2295,13 @@ void CArchiveExtractCallback::SetAttrib()
2282} 2295}
2283 2296
2284 2297
2285STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes) 2298Z7_COM7F_IMF(CArchiveExtractCallback::SetOperationResult(Int32 opRes))
2286{ 2299{
2287 COM_TRY_BEGIN 2300 COM_TRY_BEGIN
2288 2301
2289 // printf("\nCArchiveExtractCallback::SetOperationResult: %d %s\n", opRes, GetAnsiString(_diskFilePath)); 2302 // printf("\nCArchiveExtractCallback::SetOperationResult: %d %s\n", opRes, GetAnsiString(_diskFilePath));
2290 2303
2291 #ifndef _SFX 2304 #ifndef Z7_SFX
2292 if (ExtractToStreamCallback) 2305 if (ExtractToStreamCallback)
2293 { 2306 {
2294 GetUnpackSize(); 2307 GetUnpackSize();
@@ -2296,7 +2309,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes)
2296 } 2309 }
2297 #endif 2310 #endif
2298 2311
2299 #ifndef _SFX 2312 #ifndef Z7_SFX
2300 2313
2301 if (_hashStreamWasUsed) 2314 if (_hashStreamWasUsed)
2302 { 2315 {
@@ -2308,16 +2321,16 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes)
2308 #endif 2321 #endif
2309 , _item.Path); 2322 , _item.Path);
2310 _curSize = _hashStreamSpec->GetSize(); 2323 _curSize = _hashStreamSpec->GetSize();
2311 _curSizeDefined = true; 2324 _curSize_Defined = true;
2312 _hashStreamSpec->ReleaseStream(); 2325 _hashStreamSpec->ReleaseStream();
2313 _hashStreamWasUsed = false; 2326 _hashStreamWasUsed = false;
2314 } 2327 }
2315 2328
2316 #endif // _SFX 2329 #endif // Z7_SFX
2317 2330
2318 RINOK(CloseReparseAndFile()); 2331 RINOK(CloseReparseAndFile())
2319 2332
2320 #ifdef _USE_SECURITY_CODE 2333 #ifdef Z7_USE_SECURITY_CODE
2321 if (!_stdOutMode && _extractMode && _ntOptions.NtSecurity.Val && _arc->GetRawProps) 2334 if (!_stdOutMode && _extractMode && _ntOptions.NtSecurity.Val && _arc->GetRawProps)
2322 { 2335 {
2323 const void *data; 2336 const void *data;
@@ -2337,12 +2350,12 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes)
2337 } 2350 }
2338 } 2351 }
2339 } 2352 }
2340 #endif // _USE_SECURITY_CODE 2353 #endif // Z7_USE_SECURITY_CODE
2341 2354
2342 if (!_curSizeDefined) 2355 if (!_curSize_Defined)
2343 GetUnpackSize(); 2356 GetUnpackSize();
2344 2357
2345 if (_curSizeDefined) 2358 if (_curSize_Defined)
2346 { 2359 {
2347 #ifdef SUPPORT_ALT_STREAMS 2360 #ifdef SUPPORT_ALT_STREAMS
2348 if (_item.IsAltStream) 2361 if (_item.IsAltStream)
@@ -2364,7 +2377,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes)
2364 if (_needSetAttrib) 2377 if (_needSetAttrib)
2365 SetAttrib(); 2378 SetAttrib();
2366 2379
2367 RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted))); 2380 RINOK(_extractCallback2->SetOperationResult(opRes, BoolToInt(_encrypted)))
2368 2381
2369 return S_OK; 2382 return S_OK;
2370 2383
@@ -2373,7 +2386,7 @@ STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 opRes)
2373 2386
2374 2387
2375 2388
2376STDMETHODIMP CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes) 2389Z7_COM7F_IMF(CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes))
2377{ 2390{
2378 if (_folderArchiveExtractCallback2) 2391 if (_folderArchiveExtractCallback2)
2379 { 2392 {
@@ -2383,9 +2396,9 @@ STDMETHODIMP CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt
2383 if (indexType == NArchive::NEventIndexType::kInArcIndex && index != (UInt32)(Int32)-1) 2396 if (indexType == NArchive::NEventIndexType::kInArcIndex && index != (UInt32)(Int32)-1)
2384 { 2397 {
2385 CReadArcItem item; 2398 CReadArcItem item;
2386 RINOK(_arc->GetItem(index, item)); 2399 RINOK(_arc->GetItem(index, item))
2387 s = item.Path; 2400 s = item.Path;
2388 RINOK(Archive_GetItemBoolProp(_arc->Archive, index, kpidEncrypted, isEncrypted)); 2401 RINOK(Archive_GetItemBoolProp(_arc->Archive, index, kpidEncrypted, isEncrypted))
2389 } 2402 }
2390 else 2403 else
2391 { 2404 {
@@ -2401,13 +2414,13 @@ STDMETHODIMP CArchiveExtractCallback::ReportExtractResult(UInt32 indexType, UInt
2401} 2414}
2402 2415
2403 2416
2404STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password) 2417Z7_COM7F_IMF(CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password))
2405{ 2418{
2406 COM_TRY_BEGIN 2419 COM_TRY_BEGIN
2407 if (!_cryptoGetTextPassword) 2420 if (!_cryptoGetTextPassword)
2408 { 2421 {
2409 RINOK(_extractCallback2.QueryInterface(IID_ICryptoGetTextPassword, 2422 RINOK(_extractCallback2.QueryInterface(IID_ICryptoGetTextPassword,
2410 &_cryptoGetTextPassword)); 2423 &_cryptoGetTextPassword))
2411 } 2424 }
2412 return _cryptoGetTextPassword->CryptoGetTextPassword(password); 2425 return _cryptoGetTextPassword->CryptoGetTextPassword(password);
2413 COM_TRY_END 2426 COM_TRY_END
@@ -2435,13 +2448,13 @@ FString CArchiveExtractCallback::Hash_GetFullFilePath()
2435} 2448}
2436 2449
2437 2450
2438STDMETHODIMP CArchiveExtractCallback::GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 2451Z7_COM7F_IMF(CArchiveExtractCallback::GetDiskProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
2439{ 2452{
2440 COM_TRY_BEGIN 2453 COM_TRY_BEGIN
2441 NCOM::CPropVariant prop; 2454 NCOM::CPropVariant prop;
2442 if (propID == kpidSize) 2455 if (propID == kpidSize)
2443 { 2456 {
2444 RINOK(GetItem(index)); 2457 RINOK(GetItem(index))
2445 const FString fullProcessedPath = Hash_GetFullFilePath(); 2458 const FString fullProcessedPath = Hash_GetFullFilePath();
2446 NFile::NFind::CFileInfo fi; 2459 NFile::NFind::CFileInfo fi;
2447 if (fi.Find_FollowLink(fullProcessedPath)) 2460 if (fi.Find_FollowLink(fullProcessedPath))
@@ -2454,7 +2467,7 @@ STDMETHODIMP CArchiveExtractCallback::GetDiskProperty(UInt32 index, PROPID propI
2454} 2467}
2455 2468
2456 2469
2457STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode) 2470Z7_COM7F_IMF(CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode))
2458{ 2471{
2459 COM_TRY_BEGIN 2472 COM_TRY_BEGIN
2460 *inStream = NULL; 2473 *inStream = NULL;
@@ -2462,7 +2475,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStre
2462 if (mode != NUpdateNotifyOp::kHashRead) 2475 if (mode != NUpdateNotifyOp::kHashRead)
2463 return E_FAIL; 2476 return E_FAIL;
2464 2477
2465 RINOK(GetItem(index)); 2478 RINOK(GetItem(index))
2466 const FString fullProcessedPath = Hash_GetFullFilePath(); 2479 const FString fullProcessedPath = Hash_GetFullFilePath();
2467 2480
2468 CInFileStream *inStreamSpec = new CInFileStream; 2481 CInFileStream *inStreamSpec = new CInFileStream;
@@ -2470,7 +2483,7 @@ STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStre
2470 inStreamSpec->Set_PreserveATime(_ntOptions.PreserveATime); 2483 inStreamSpec->Set_PreserveATime(_ntOptions.PreserveATime);
2471 if (!inStreamSpec->OpenShared(fullProcessedPath, _ntOptions.OpenShareForWrite)) 2484 if (!inStreamSpec->OpenShared(fullProcessedPath, _ntOptions.OpenShareForWrite))
2472 { 2485 {
2473 RINOK(SendMessageError_with_LastError(kCantOpenInFile, fullProcessedPath)); 2486 RINOK(SendMessageError_with_LastError(kCantOpenInFile, fullProcessedPath))
2474 return S_OK; 2487 return S_OK;
2475 } 2488 }
2476 *inStream = inStreamRef.Detach(); 2489 *inStream = inStreamRef.Detach();
@@ -2479,8 +2492,8 @@ STDMETHODIMP CArchiveExtractCallback::GetStream2(UInt32 index, ISequentialInStre
2479} 2492}
2480 2493
2481 2494
2482STDMETHODIMP CArchiveExtractCallback::ReportOperation( 2495Z7_COM7F_IMF(CArchiveExtractCallback::ReportOperation(
2483 UInt32 /* indexType */, UInt32 /* index */, UInt32 /* op */) 2496 UInt32 /* indexType */, UInt32 /* index */, UInt32 /* op */))
2484{ 2497{
2485 // COM_TRY_BEGIN 2498 // COM_TRY_BEGIN
2486 return S_OK; 2499 return S_OK;
@@ -2571,7 +2584,7 @@ HRESULT CArchiveExtractCallback::SetDirsTimes()
2571HRESULT CArchiveExtractCallback::CloseArc() 2584HRESULT CArchiveExtractCallback::CloseArc()
2572{ 2585{
2573 HRESULT res = CloseReparseAndFile(); 2586 HRESULT res = CloseReparseAndFile();
2574 HRESULT res2 = SetDirsTimes(); 2587 const HRESULT res2 = SetDirsTimes();
2575 if (res == S_OK) 2588 if (res == S_OK)
2576 res = res2; 2589 res = res2;
2577 _arc = NULL; 2590 _arc = NULL;
diff --git a/CPP/7zip/UI/Common/ArchiveExtractCallback.h b/CPP/7zip/UI/Common/ArchiveExtractCallback.h
index fe70bc9..5ed20f3 100644
--- a/CPP/7zip/UI/Common/ArchiveExtractCallback.h
+++ b/CPP/7zip/UI/Common/ArchiveExtractCallback.h
@@ -1,7 +1,7 @@
1// ArchiveExtractCallback.h 1// ArchiveExtractCallback.h
2 2
3#ifndef __ARCHIVE_EXTRACT_CALLBACK_H 3#ifndef ZIP7_INC_ARCHIVE_EXTRACT_CALLBACK_H
4#define __ARCHIVE_EXTRACT_CALLBACK_H 4#define ZIP7_INC_ARCHIVE_EXTRACT_CALLBACK_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyLinux.h" 7#include "../../../Common/MyLinux.h"
@@ -21,20 +21,18 @@
21 21
22#include "HashCalc.h" 22#include "HashCalc.h"
23 23
24#ifndef _SFX 24#ifndef Z7_SFX
25 25
26class COutStreamWithHash: 26Z7_CLASS_IMP_NOQIB_1(
27 public ISequentialOutStream, 27 COutStreamWithHash
28 public CMyUnknownImp 28 , ISequentialOutStream
29{ 29)
30 CMyComPtr<ISequentialOutStream> _stream; 30 CMyComPtr<ISequentialOutStream> _stream;
31 UInt64 _size; 31 UInt64 _size;
32 bool _calculate; 32 bool _calculate;
33public: 33public:
34 IHashCalc *_hash; 34 IHashCalc *_hash;
35 35
36 MY_UNKNOWN_IMP
37 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
38 void SetStream(ISequentialOutStream *stream) { _stream = stream; } 36 void SetStream(ISequentialOutStream *stream) { _stream = stream; }
39 void ReleaseStream() { _stream.Release(); } 37 void ReleaseStream() { _stream.Release(); }
40 void Init(bool calculate = true) 38 void Init(bool calculate = true)
@@ -89,24 +87,21 @@ struct CExtractNtOptions
89 } 87 }
90}; 88};
91 89
92#ifndef _SFX 90#ifndef Z7_SFX
93 91
94class CGetProp: 92Z7_CLASS_IMP_COM_1(
95 public IGetProp, 93 CGetProp
96 public CMyUnknownImp 94 , IGetProp
97{ 95)
98public: 96public:
99 const CArc *Arc;
100 UInt32 IndexInArc; 97 UInt32 IndexInArc;
98 const CArc *Arc;
101 // UString Name; // relative path 99 // UString Name; // relative path
102
103 MY_UNKNOWN_IMP1(IGetProp)
104 INTERFACE_IGetProp(;)
105}; 100};
106 101
107#endif 102#endif
108 103
109#ifndef _SFX 104#ifndef Z7_SFX
110#ifndef UNDER_CE 105#ifndef UNDER_CE
111 106
112#define SUPPORT_LINKS 107#define SUPPORT_LINKS
@@ -249,32 +244,75 @@ struct COwnerInfo
249#endif 244#endif
250 245
251 246
252class CArchiveExtractCallback: 247class CArchiveExtractCallback Z7_final:
253 public IArchiveExtractCallback, 248 public IArchiveExtractCallback,
254 public IArchiveExtractCallbackMessage, 249 public IArchiveExtractCallbackMessage2,
255 public ICryptoGetTextPassword, 250 public ICryptoGetTextPassword,
256 public ICompressProgressInfo, 251 public ICompressProgressInfo,
257 public IArchiveUpdateCallbackFile, 252 public IArchiveUpdateCallbackFile,
258 public IArchiveGetDiskProperty, 253 public IArchiveGetDiskProperty,
259 public CMyUnknownImp 254 public CMyUnknownImp
260{ 255{
256 Z7_COM_UNKNOWN_IMP_5(
257 /* IArchiveExtractCallback, */
258 IArchiveExtractCallbackMessage2,
259 ICryptoGetTextPassword,
260 ICompressProgressInfo,
261 IArchiveUpdateCallbackFile,
262 IArchiveGetDiskProperty)
263
264 Z7_IFACE_COM7_IMP(IProgress)
265 Z7_IFACE_COM7_IMP(IArchiveExtractCallback)
266 Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage2)
267 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
268 Z7_IFACE_COM7_IMP(ICompressProgressInfo)
269 Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackFile)
270 Z7_IFACE_COM7_IMP(IArchiveGetDiskProperty)
271
261 const CArc *_arc; 272 const CArc *_arc;
262 CExtractNtOptions _ntOptions; 273 CExtractNtOptions _ntOptions;
263 274
275 bool _isSplit;
276
277 bool _extractMode;
278
279 bool Write_CTime;
280 bool Write_ATime;
281 bool Write_MTime;
282 bool _keepAndReplaceEmptyDirPrefixes; // replace them to "_";
283
284 bool _encrypted;
285
286 // bool _is_SymLink_in_Data;
287 bool _is_SymLink_in_Data_Linux; // false = WIN32, true = LINUX
288
289 bool _needSetAttrib;
290 bool _isSymLinkCreated;
291 bool _itemFailure;
292
293 bool _curSize_Defined;
294 bool _fileLength_WasSet;
295
296 bool _removePartsForAltStreams;
297
298 bool _stdOutMode;
299 bool _testMode;
300 bool _multiArchives;
301
302 NExtract::NPathMode::EEnum _pathMode;
303 NExtract::NOverwriteMode::EEnum _overwriteMode;
304
264 const NWildcard::CCensorNode *_wildcardCensor; // we need wildcard for single pass mode (stdin) 305 const NWildcard::CCensorNode *_wildcardCensor; // we need wildcard for single pass mode (stdin)
265 CMyComPtr<IFolderArchiveExtractCallback> _extractCallback2; 306 CMyComPtr<IFolderArchiveExtractCallback> _extractCallback2;
266 CMyComPtr<ICompressProgressInfo> _compressProgress; 307 // CMyComPtr<ICompressProgressInfo> _compressProgress;
267 CMyComPtr<ICryptoGetTextPassword> _cryptoGetTextPassword; 308 // CMyComPtr<IArchiveExtractCallbackMessage2> _callbackMessage;
268 CMyComPtr<IArchiveExtractCallbackMessage> _callbackMessage;
269 CMyComPtr<IFolderArchiveExtractCallback2> _folderArchiveExtractCallback2; 309 CMyComPtr<IFolderArchiveExtractCallback2> _folderArchiveExtractCallback2;
310 CMyComPtr<ICryptoGetTextPassword> _cryptoGetTextPassword;
270 311
271 FString _dirPathPrefix; 312 FString _dirPathPrefix;
272 FString _dirPathPrefix_Full; 313 FString _dirPathPrefix_Full;
273 NExtract::NPathMode::EEnum _pathMode;
274 NExtract::NOverwriteMode::EEnum _overwriteMode;
275 bool _keepAndReplaceEmptyDirPrefixes; // replace them to "_";
276 314
277 #ifndef _SFX 315 #ifndef Z7_SFX
278 316
279 CMyComPtr<IFolderExtractToStreamCallback> ExtractToStreamCallback; 317 CMyComPtr<IFolderExtractToStreamCallback> ExtractToStreamCallback;
280 CGetProp *GetProp_Spec; 318 CGetProp *GetProp_Spec;
@@ -285,15 +323,6 @@ class CArchiveExtractCallback:
285 CReadArcItem _item; 323 CReadArcItem _item;
286 FString _diskFilePath; 324 FString _diskFilePath;
287 UInt64 _position; 325 UInt64 _position;
288 bool _isSplit;
289
290 bool _extractMode;
291
292 bool Write_CTime;
293 bool Write_ATime;
294 bool Write_MTime;
295
296 bool _encrypted;
297 326
298 struct CProcessedFileInfo 327 struct CProcessedFileInfo
299 { 328 {
@@ -339,17 +368,8 @@ class CArchiveExtractCallback:
339 } 368 }
340 } _fi; 369 } _fi;
341 370
342 // bool _is_SymLink_in_Data;
343 bool _is_SymLink_in_Data_Linux; // false = WIN32, true = LINUX
344
345 bool _needSetAttrib;
346 bool _isSymLinkCreated;
347 bool _itemFailure;
348
349 UInt32 _index; 371 UInt32 _index;
350 UInt64 _curSize; 372 UInt64 _curSize;
351 bool _curSizeDefined;
352 bool _fileLengthWasSet;
353 UInt64 _fileLength_that_WasSet; 373 UInt64 _fileLength_that_WasSet;
354 374
355 COutFileStream *_outFileStreamSpec; 375 COutFileStream *_outFileStreamSpec;
@@ -360,25 +380,17 @@ class CArchiveExtractCallback:
360 CMyComPtr<ISequentialOutStream> _bufPtrSeqOutStream; 380 CMyComPtr<ISequentialOutStream> _bufPtrSeqOutStream;
361 381
362 382
363 #ifndef _SFX 383 #ifndef Z7_SFX
364 384
365 COutStreamWithHash *_hashStreamSpec; 385 COutStreamWithHash *_hashStreamSpec;
366 CMyComPtr<ISequentialOutStream> _hashStream; 386 CMyComPtr<ISequentialOutStream> _hashStream;
367 bool _hashStreamWasUsed; 387 bool _hashStreamWasUsed;
368 388
369 #endif
370
371 bool _removePartsForAltStreams;
372 UStringVector _removePathParts;
373
374 #ifndef _SFX
375 bool _use_baseParentFolder_mode; 389 bool _use_baseParentFolder_mode;
376 UInt32 _baseParentFolder; 390 UInt32 _baseParentFolder;
377 #endif 391 #endif
378 392
379 bool _stdOutMode; 393 UStringVector _removePathParts;
380 bool _testMode;
381 bool _multiArchives;
382 394
383 CMyComPtr<ICompressProgressInfo> _localProgress; 395 CMyComPtr<ICompressProgressInfo> _localProgress;
384 UInt64 _packTotal; 396 UInt64 _packTotal;
@@ -392,7 +404,7 @@ class CArchiveExtractCallback:
392 // CObjectVector<NWindows::NFile::NDir::CDelayedSymLink> _delayedSymLinks; 404 // CObjectVector<NWindows::NFile::NDir::CDelayedSymLink> _delayedSymLinks;
393 #endif 405 #endif
394 406
395 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) 407 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX)
396 bool _saclEnabled; 408 bool _saclEnabled;
397 #endif 409 #endif
398 410
@@ -425,23 +437,6 @@ public:
425 437
426 FString DirPathPrefix_for_HashFiles; 438 FString DirPathPrefix_for_HashFiles;
427 439
428 MY_UNKNOWN_IMP5(
429 IArchiveExtractCallbackMessage,
430 ICryptoGetTextPassword,
431 ICompressProgressInfo,
432 IArchiveUpdateCallbackFile,
433 IArchiveGetDiskProperty
434 )
435
436 INTERFACE_IArchiveExtractCallback(;)
437 INTERFACE_IArchiveExtractCallbackMessage(;)
438 INTERFACE_IArchiveUpdateCallbackFile(;)
439 INTERFACE_IArchiveGetDiskProperty(;)
440
441 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
442
443 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
444
445 CArchiveExtractCallback(); 440 CArchiveExtractCallback();
446 441
447 void InitForMulti(bool multiArchives, 442 void InitForMulti(bool multiArchives,
@@ -462,7 +457,7 @@ public:
462 NumFolders = NumFiles = NumAltStreams = UnpackSize = AltStreams_UnpackSize = 0; 457 NumFolders = NumFiles = NumAltStreams = UnpackSize = AltStreams_UnpackSize = 0;
463 } 458 }
464 459
465 #ifndef _SFX 460 #ifndef Z7_SFX
466 461
467 void SetHashMethods(IHashCalc *hash) 462 void SetHashMethods(IHashCalc *hash)
468 { 463 {
@@ -494,7 +489,7 @@ private:
494 CHardLinks _hardLinks; 489 CHardLinks _hardLinks;
495 CLinkInfo _link; 490 CLinkInfo _link;
496 491
497 // FString _CopyFile_Path; 492 // FString _copyFile_Path;
498 // HRESULT MyCopyFile(ISequentialOutStream *outStream); 493 // HRESULT MyCopyFile(ISequentialOutStream *outStream);
499 HRESULT Link(const FString &fullProcessedPath); 494 HRESULT Link(const FString &fullProcessedPath);
500 HRESULT ReadLink(); 495 HRESULT ReadLink();
@@ -512,7 +507,7 @@ public:
512 507
513 // call it after Init() 508 // call it after Init()
514 509
515 #ifndef _SFX 510 #ifndef Z7_SFX
516 void SetBaseParentFolderIndex(UInt32 indexInArc) 511 void SetBaseParentFolderIndex(UInt32 indexInArc)
517 { 512 {
518 _baseParentFolder = indexInArc; 513 _baseParentFolder = indexInArc;
diff --git a/CPP/7zip/UI/Common/ArchiveName.cpp b/CPP/7zip/UI/Common/ArchiveName.cpp
index 1baf3e1..1c0c3a8 100644
--- a/CPP/7zip/UI/Common/ArchiveName.cpp
+++ b/CPP/7zip/UI/Common/ArchiveName.cpp
@@ -2,154 +2,175 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../../C/Sort.h"
6
5#include "../../../Common/Wildcard.h" 7#include "../../../Common/Wildcard.h"
8#include "../../../Common/StringToInt.h"
6 9
7#include "../../../Windows/FileDir.h" 10#include "../../../Windows/FileDir.h"
8#include "../../../Windows/FileName.h" 11#include "../../../Windows/FileName.h"
9 12
10#include "ExtractingFilePath.h"
11#include "ArchiveName.h" 13#include "ArchiveName.h"
14#include "ExtractingFilePath.h"
12 15
13using namespace NWindows; 16using namespace NWindows;
14using namespace NFile; 17using namespace NFile;
15 18
16static UString CreateArchiveName(const NFind::CFileInfo &fi, bool keepName) 19
20static const char *g_ArcExts =
21 "7z"
22 "\0" "zip"
23 "\0" "tar"
24 "\0" "wim"
25 "\0";
26
27static const char *g_HashExts =
28 "sha256"
29 "\0";
30
31
32UString CreateArchiveName(
33 const UStringVector &paths,
34 bool isHash,
35 const NFind::CFileInfo *fi,
36 UString &baseName)
17{ 37{
18 FString resultName = fi.Name; 38 bool keepName = isHash;
19 if (!fi.IsDir() && !keepName) 39 /*
40 if (paths.Size() == 1)
20 { 41 {
21 int dotPos = resultName.ReverseFind_Dot(); 42 const UString &name = paths[0];
22 if (dotPos > 0) 43 if (name.Len() > 4)
23 { 44 if (CompareFileNames(name.RightPtr(4), L".tar") == 0)
24 FString archiveName2 = resultName.Left((unsigned)dotPos); 45 keepName = true;
25 if (archiveName2.ReverseFind_Dot() < 0)
26 resultName = archiveName2;
27 }
28 } 46 }
29 return Get_Correct_FsFile_Name(fs2us(resultName)); 47 */
30}
31 48
32static FString CreateArchiveName2(const FString &path, bool fromPrev, bool keepName) 49 UString name ("Archive");
33{ 50 NFind::CFileInfo fi3;
34 FString resultName ("Archive"); 51 if (paths.Size() > 1)
35 if (fromPrev) 52 fi = NULL;
53 if (!fi && paths.Size() != 0)
36 { 54 {
37 FString dirPrefix; 55 const UString &path = paths.Front();
38 if (NDir::GetOnlyDirPrefix(path, dirPrefix)) 56 if (paths.Size() == 1)
39 { 57 {
40 if (!dirPrefix.IsEmpty() && IsPathSepar(dirPrefix.Back())) 58 if (fi3.Find(us2fs(path)))
41 { 59 fi = &fi3;
42 #if defined(_WIN32) && !defined(UNDER_CE)
43 if (NName::IsDriveRootPath_SuperAllowed(dirPrefix))
44 resultName = dirPrefix[dirPrefix.Len() - 3]; // only letter
45 else
46 #endif
47 {
48 dirPrefix.DeleteBack();
49 NFind::CFileInfo fi;
50 if (fi.Find(dirPrefix))
51 resultName = fi.Name;
52 }
53 }
54 } 60 }
55 } 61 else
56 else
57 {
58 NFind::CFileInfo fi;
59 if (fi.Find(path))
60 { 62 {
61 resultName = fi.Name; 63 // we try to use name of parent folder
62 if (!fi.IsDir() && !keepName) 64 FString dirPrefix;
65 if (NDir::GetOnlyDirPrefix(us2fs(path), dirPrefix))
63 { 66 {
64 int dotPos = resultName.ReverseFind_Dot(); 67 if (!dirPrefix.IsEmpty() && IsPathSepar(dirPrefix.Back()))
65 if (dotPos > 0)
66 { 68 {
67 FString name2 = resultName.Left((unsigned)dotPos); 69 #if defined(_WIN32) && !defined(UNDER_CE)
68 if (name2.ReverseFind_Dot() < 0) 70 if (NName::IsDriveRootPath_SuperAllowed(dirPrefix))
69 resultName = name2; 71 {
72 if (path != fs2us(dirPrefix))
73 name = dirPrefix[dirPrefix.Len() - 3]; // only letter
74 }
75 else
76 #endif
77 {
78 dirPrefix.DeleteBack();
79 if (!dirPrefix.IsEmpty())
80 {
81 const int slash = dirPrefix.ReverseFind_PathSepar();
82 if (slash >= 0 && slash != (int)dirPrefix.Len() - 1)
83 name = dirPrefix.Ptr(slash + 1);
84 else if (fi3.Find(dirPrefix))
85 name = fs2us(fi3.Name);
86 }
87 }
70 } 88 }
71 } 89 }
72 } 90 }
73 } 91 }
74 return resultName;
75}
76
77 92
78UString CreateArchiveName(const UStringVector &paths, const NFind::CFileInfo *fi)
79{
80 bool keepName = false;
81 /*
82 if (paths.Size() == 1)
83 {
84 const UString &name = paths[0];
85 if (name.Len() > 4)
86 if (CompareFileNames(name.RightPtr(4), L".tar") == 0)
87 keepName = true;
88 }
89 */
90
91 UString name;
92 if (fi) 93 if (fi)
93 name = CreateArchiveName(*fi, keepName);
94 else
95 { 94 {
96 if (paths.IsEmpty()) 95 name = fs2us(fi->Name);
97 return L"archive"; 96 if (!fi->IsDir() && !keepName)
98 bool fromPrev = (paths.Size() > 1); 97 {
99 name = Get_Correct_FsFile_Name(fs2us(CreateArchiveName2(us2fs(paths.Front()), fromPrev, keepName))); 98 const int dotPos = name.Find(L'.');
99 if (dotPos > 0 && name.Find(L'.', (unsigned)dotPos + 1) < 0)
100 name.DeleteFrom((unsigned)dotPos);
101 }
100 } 102 }
103 name = Get_Correct_FsFile_Name(name);
101 104
102 UStringVector names; 105 CRecordVector<UInt32> ids;
103 106 bool simple_IsAllowed = true;
107 // for (int y = 0; y < 10000; y++) // for debug
104 { 108 {
109 // ids.Clear();
110 UString n;
111
105 FOR_VECTOR (i, paths) 112 FOR_VECTOR (i, paths)
106 { 113 {
107 NFind::CFileInfo fi2; 114 const UString &a = paths[i];
108 const NFind::CFileInfo *fp; 115 const int slash = a.ReverseFind_PathSepar();
109 if (fi && paths.Size() == 1) 116 // if (name.Len() >= a.Len() - slash + 1) continue;
110 fp = fi; 117 const wchar_t *s = a.Ptr(slash + 1);
111 else 118 if (!IsPath1PrefixedByPath2(s, name))
119 continue;
120 s += name.Len();
121 const char *exts = isHash ? g_HashExts : g_ArcExts;
122
123 for (;;)
112 { 124 {
113 if (!fi2.Find(us2fs(paths[i]))) 125 const char *ext = exts;
126 const unsigned len = MyStringLen(ext);
127 if (len == 0)
128 break;
129 exts += len + 1;
130 n = s;
131 if (n.Len() <= len)
132 continue;
133 if (!StringsAreEqualNoCase_Ascii(n.RightPtr(len), ext))
134 continue;
135 n.DeleteFrom(n.Len() - len);
136 if (n.Back() != '.')
137 continue;
138 n.DeleteBack();
139 if (n.IsEmpty())
140 {
141 simple_IsAllowed = false;
142 break;
143 }
144 if (n.Len() < 2)
145 continue;
146 if (n[0] != '_')
114 continue; 147 continue;
115 fp = &fi2; 148 const wchar_t *end;
149 const UInt32 v = ConvertStringToUInt32(n.Ptr(1), &end);
150 if (*end != 0)
151 continue;
152 ids.Add(v);
153 break;
116 } 154 }
117 names.Add(fs2us(fp->Name));
118 } 155 }
119 } 156 }
120 157
121 UString postfix; 158 baseName = name;
122 UInt32 index = 1; 159 if (!simple_IsAllowed)
123
124 for (;;)
125 { 160 {
126 // we don't want cases when we include archive to itself. 161 HeapSort(&ids.Front(), ids.Size());
127 // so we find first available name for archive 162 UInt32 v = 2;
128 const UString name2 = name + postfix; 163 const unsigned num = ids.Size();
129 const UString name2_zip = name2 + L".zip"; 164 for (unsigned i = 0; i < num; i++)
130 const UString name2_7z = name2 + L".7z";
131 const UString name2_tar = name2 + L".tar";
132 const UString name2_wim = name2 + L".wim";
133
134 unsigned i = 0;
135
136 for (i = 0; i < names.Size(); i++)
137 { 165 {
138 const UString &fname = names[i]; 166 const UInt32 id = ids[i];
139 if ( 0 == CompareFileNames(fname, name2_zip) 167 if (id > v)
140 || 0 == CompareFileNames(fname, name2_7z)
141 || 0 == CompareFileNames(fname, name2_tar)
142 || 0 == CompareFileNames(fname, name2_wim))
143 break; 168 break;
169 if (id == v)
170 v = id + 1;
144 } 171 }
145 172 name += '_';
146 if (i == names.Size()) 173 name.Add_UInt32(v);
147 break;
148 index++;
149 postfix = "_";
150 postfix.Add_UInt32(index);
151 } 174 }
152
153 name += postfix;
154 return name; 175 return name;
155} 176}
diff --git a/CPP/7zip/UI/Common/ArchiveName.h b/CPP/7zip/UI/Common/ArchiveName.h
index 0d32645..9b6b7fe 100644
--- a/CPP/7zip/UI/Common/ArchiveName.h
+++ b/CPP/7zip/UI/Common/ArchiveName.h
@@ -1,10 +1,16 @@
1// ArchiveName.h 1// ArchiveName.h
2 2
3#ifndef __ARCHIVE_NAME_H 3#ifndef ZIP7_INC_ARCHIVE_NAME_H
4#define __ARCHIVE_NAME_H 4#define ZIP7_INC_ARCHIVE_NAME_H
5 5
6#include "../../../Windows/FileFind.h" 6#include "../../../Windows/FileFind.h"
7 7
8UString CreateArchiveName(const UStringVector &paths, const NWindows::NFile::NFind::CFileInfo *fi = NULL); 8/* (fi != NULL) only if (paths.Size() == 1) */
9
10UString CreateArchiveName(
11 const UStringVector &paths,
12 bool isHash,
13 const NWindows::NFile::NFind::CFileInfo *fi,
14 UString &baseName);
9 15
10#endif 16#endif
diff --git a/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp b/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp
index 64aa987..4e5f1f5 100644
--- a/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp
+++ b/CPP/7zip/UI/Common/ArchiveOpenCallback.cpp
@@ -6,14 +6,54 @@
6 6
7#include "../../../Windows/FileName.h" 7#include "../../../Windows/FileName.h"
8#include "../../../Windows/PropVariant.h" 8#include "../../../Windows/PropVariant.h"
9#include "../../../Windows/System.h"
9 10
10#include "../../Common/FileStreams.h" 11#include "../../Common/StreamUtils.h"
11 12
12#include "ArchiveOpenCallback.h" 13#include "ArchiveOpenCallback.h"
13 14
15// #define DEBUG_VOLUMES
16
17#ifdef DEBUG_VOLUMES
18#include <stdio.h>
19#endif
20
21
22#ifdef DEBUG_VOLUMES
23 #define PRF(x) x
24#else
25 #define PRF(x)
26#endif
27
14using namespace NWindows; 28using namespace NWindows;
15 29
16STDMETHODIMP COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes) 30HRESULT COpenCallbackImp::Init2(const FString &folderPrefix, const FString &fileName)
31{
32 Volumes.Init();
33 FileNames.Clear();
34 FileNames_WasUsed.Clear();
35 FileSizes.Clear();
36 _subArchiveMode = false;
37 // TotalSize = 0;
38 PasswordWasAsked = false;
39 _folderPrefix = folderPrefix;
40 if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName))
41 {
42 // throw 20121118;
43 return GetLastError_noZero_HRESULT();
44 }
45 return S_OK;
46}
47
48Z7_COM7F_IMF(COpenCallbackImp::SetSubArchiveName(const wchar_t *name))
49{
50 _subArchiveMode = true;
51 _subArchiveName = name;
52 // TotalSize = 0;
53 return S_OK;
54}
55
56Z7_COM7F_IMF(COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes))
17{ 57{
18 COM_TRY_BEGIN 58 COM_TRY_BEGIN
19 if (ReOpenCallback) 59 if (ReOpenCallback)
@@ -24,7 +64,7 @@ STDMETHODIMP COpenCallbackImp::SetTotal(const UInt64 *files, const UInt64 *bytes
24 COM_TRY_END 64 COM_TRY_END
25} 65}
26 66
27STDMETHODIMP COpenCallbackImp::SetCompleted(const UInt64 *files, const UInt64 *bytes) 67Z7_COM7F_IMF(COpenCallbackImp::SetCompleted(const UInt64 *files, const UInt64 *bytes))
28{ 68{
29 COM_TRY_BEGIN 69 COM_TRY_BEGIN
30 if (ReOpenCallback) 70 if (ReOpenCallback)
@@ -36,7 +76,7 @@ STDMETHODIMP COpenCallbackImp::SetCompleted(const UInt64 *files, const UInt64 *b
36} 76}
37 77
38 78
39STDMETHODIMP COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value) 79Z7_COM7F_IMF(COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value))
40{ 80{
41 COM_TRY_BEGIN 81 COM_TRY_BEGIN
42 NCOM::CPropVariant prop; 82 NCOM::CPropVariant prop;
@@ -63,24 +103,180 @@ STDMETHODIMP COpenCallbackImp::GetProperty(PROPID propID, PROPVARIANT *value)
63 COM_TRY_END 103 COM_TRY_END
64} 104}
65 105
66struct CInFileStreamVol: public CInFileStream 106
67{ 107// ---------- CInFileStreamVol ----------
68 unsigned FileNameIndex; 108
109Z7_CLASS_IMP_COM_2(
110 CInFileStreamVol
111 , IInStream
112 , IStreamGetSize
113)
114 Z7_IFACE_COM7_IMP(ISequentialInStream)
115public:
116 unsigned FileIndex;
69 COpenCallbackImp *OpenCallbackImp; 117 COpenCallbackImp *OpenCallbackImp;
70 CMyComPtr<IArchiveOpenCallback> OpenCallbackRef; 118 CMyComPtr<IArchiveOpenCallback> OpenCallbackRef;
71 119
120 HRESULT EnsureOpen()
121 {
122 return OpenCallbackImp->Volumes.EnsureOpen(FileIndex);
123 }
124
72 ~CInFileStreamVol() 125 ~CInFileStreamVol()
73 { 126 {
74 if (OpenCallbackRef) 127 if (OpenCallbackRef)
75 OpenCallbackImp->FileNames_WasUsed[FileNameIndex] = false; 128 OpenCallbackImp->AtCloseFile(FileIndex);
76 } 129 }
77}; 130};
78 131
79 132
133void CMultiStreams::InsertToList(unsigned index)
134{
135 {
136 CSubStream &s = Streams[index];
137 s.Next = Head;
138 s.Prev = -1;
139 }
140 if (Head != -1)
141 Streams[(unsigned)Head].Prev = (int)index;
142 else
143 {
144 // if (Tail != -1) throw 1;
145 Tail = (int)index;
146 }
147 Head = (int)index;
148 NumListItems++;
149}
150
151// s must bee in List
152void CMultiStreams::RemoveFromList(CSubStream &s)
153{
154 if (s.Next != -1) Streams[(unsigned)s.Next].Prev = s.Prev; else Tail = s.Prev;
155 if (s.Prev != -1) Streams[(unsigned)s.Prev].Next = s.Next; else Head = s.Next;
156 s.Next = -1; // optional
157 s.Prev = -1; // optional
158 NumListItems--;
159}
160
161void CMultiStreams::CloseFile(unsigned index)
162{
163 CSubStream &s = Streams[index];
164 if (s.Stream)
165 {
166 s.Stream.Release();
167 RemoveFromList(s);
168 // s.InFile->Close();
169 // s.IsOpen = false;
170 #ifdef DEBUG_VOLUMES
171 static int numClosing = 0;
172 numClosing++;
173 printf("\nCloseFile %u, total_closes = %u, num_open_files = %u\n", index, numClosing, NumListItems);
174 #endif
175 }
176}
177
178void CMultiStreams::Init()
179{
180 Head = -1;
181 Tail = -1;
182 NumListItems = 0;
183 Streams.Clear();
184}
185
186CMultiStreams::CMultiStreams():
187 Head(-1),
188 Tail(-1),
189 NumListItems(0)
190{
191 NumOpenFiles_AllowedMax = NSystem::Get_File_OPEN_MAX_Reduced_for_3_tasks();
192 PRF(printf("\nNumOpenFiles_Limit = %u\n", NumOpenFiles_AllowedMax));
193}
194
195
196HRESULT CMultiStreams::PrepareToOpenNew()
197{
198 if (NumListItems < NumOpenFiles_AllowedMax)
199 return S_OK;
200 if (Tail == -1)
201 return E_FAIL;
202 CMultiStreams::CSubStream &tailStream = Streams[(unsigned)Tail];
203 RINOK(InStream_GetPos(tailStream.Stream, tailStream.LocalPos))
204 CloseFile((unsigned)Tail);
205 return S_OK;
206}
207
208
209HRESULT CMultiStreams::EnsureOpen(unsigned index)
210{
211 CMultiStreams::CSubStream &s = Streams[index];
212 if (s.Stream)
213 {
214 if ((int)index != Head)
215 {
216 RemoveFromList(s);
217 InsertToList(index);
218 }
219 }
220 else
221 {
222 RINOK(PrepareToOpenNew())
223 {
224 CInFileStream *inFile = new CInFileStream;
225 CMyComPtr<IInStream> inStreamTemp = inFile;
226 if (!inFile->Open(s.Path))
227 return GetLastError_noZero_HRESULT();
228 s.FileSpec = inFile;
229 s.Stream = s.FileSpec;
230 InsertToList(index);
231 }
232 // s.IsOpen = true;
233 if (s.LocalPos != 0)
234 {
235 RINOK(s.Stream->Seek((Int64)s.LocalPos, STREAM_SEEK_SET, &s.LocalPos))
236 }
237 #ifdef DEBUG_VOLUMES
238 static int numOpens = 0;
239 numOpens++;
240 printf("\n-- %u, ReOpen, total_reopens = %u, num_open_files = %u\n", index, numOpens, NumListItems);
241 #endif
242 }
243 return S_OK;
244}
245
246
247Z7_COM7F_IMF(CInFileStreamVol::Read(void *data, UInt32 size, UInt32 *processedSize))
248{
249 if (processedSize)
250 *processedSize = 0;
251 if (size == 0)
252 return S_OK;
253 RINOK(EnsureOpen())
254 CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex];
255 PRF(printf("\n== %u, Read =%u \n", FileIndex, size));
256 return s.Stream->Read(data, size, processedSize);
257}
258
259Z7_COM7F_IMF(CInFileStreamVol::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition))
260{
261 // if (seekOrigin >= 3) return STG_E_INVALIDFUNCTION;
262 RINOK(EnsureOpen())
263 CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex];
264 PRF(printf("\n-- %u, Seek seekOrigin=%u Seek =%u\n", FileIndex, seekOrigin, (unsigned)offset));
265 return s.Stream->Seek(offset, seekOrigin, newPosition);
266}
267
268Z7_COM7F_IMF(CInFileStreamVol::GetSize(UInt64 *size))
269{
270 RINOK(EnsureOpen())
271 CMultiStreams::CSubStream &s = OpenCallbackImp->Volumes.Streams[FileIndex];
272 return s.FileSpec->GetSize(size);
273}
274
275
80// from ArchiveExtractCallback.cpp 276// from ArchiveExtractCallback.cpp
81bool IsSafePath(const UString &path); 277bool IsSafePath(const UString &path);
82 278
83STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStream) 279Z7_COM7F_IMF(COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStream))
84{ 280{
85 COM_TRY_BEGIN 281 COM_TRY_BEGIN
86 *inStream = NULL; 282 *inStream = NULL;
@@ -89,13 +285,13 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre
89 return S_FALSE; 285 return S_FALSE;
90 if (Callback) 286 if (Callback)
91 { 287 {
92 RINOK(Callback->Open_CheckBreak()); 288 RINOK(Callback->Open_CheckBreak())
93 } 289 }
94 290
95 UString name2 = name; 291 UString name2 = name;
96 292
97 293
98 #ifndef _SFX 294 #ifndef Z7_SFX
99 295
100 #ifdef _WIN32 296 #ifdef _WIN32
101 name2.Replace(L'/', WCHAR_PATH_SEPARATOR); 297 name2.Replace(L'/', WCHAR_PATH_SEPARATOR);
@@ -112,7 +308,7 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre
112 if (name2.Find(L'*') >= 0) 308 if (name2.Find(L'*') >= 0)
113 return S_FALSE; 309 return S_FALSE;
114 { 310 {
115 int startPos = 0; 311 unsigned startPos = 0;
116 if (name2.IsPrefixedBy_Ascii_NoCase("\\\\?\\")) 312 if (name2.IsPrefixedBy_Ascii_NoCase("\\\\?\\"))
117 startPos = 3; 313 startPos = 3;
118 if (name2.Find(L'?', startPos) >= 0) 314 if (name2.Find(L'?', startPos) >= 0)
@@ -130,16 +326,32 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre
130 return S_FALSE; 326 return S_FALSE;
131 if (_fileInfo.IsDir()) 327 if (_fileInfo.IsDir())
132 return S_FALSE; 328 return S_FALSE;
133 CInFileStreamVol *inFile = new CInFileStreamVol; 329
134 CMyComPtr<IInStream> inStreamTemp = inFile; 330 CMultiStreams::CSubStream s;
135 if (!inFile->Open(fullPath)) 331
136 { 332 {
137 return GetLastError_noZero_HRESULT(); 333 CInFileStream *inFile = new CInFileStream;
334 CMyComPtr<IInStream> inStreamTemp = inFile;
335 if (!inFile->Open(fullPath))
336 return GetLastError_noZero_HRESULT();
337 RINOK(Volumes.PrepareToOpenNew())
338 s.FileSpec = inFile;
339 s.Stream = s.FileSpec;
340 s.Path = fullPath;
341 // s.Size = _fileInfo.Size;
342 // s.IsOpen = true;
138 } 343 }
139 344
345 const unsigned fileIndex = Volumes.Streams.Add(s);
346 Volumes.InsertToList(fileIndex);
347
140 FileSizes.Add(_fileInfo.Size); 348 FileSizes.Add(_fileInfo.Size);
141 FileNames.Add(name2); 349 FileNames.Add(name2);
142 inFile->FileNameIndex = FileNames_WasUsed.Add(true); 350 FileNames_WasUsed.Add(true);
351
352 CInFileStreamVol *inFile = new CInFileStreamVol;
353 CMyComPtr<IInStream> inStreamTemp = inFile;
354 inFile->FileIndex = fileIndex;
143 inFile->OpenCallbackImp = this; 355 inFile->OpenCallbackImp = this;
144 inFile->OpenCallbackRef = this; 356 inFile->OpenCallbackRef = this;
145 // TotalSize += _fileInfo.Size; 357 // TotalSize += _fileInfo.Size;
@@ -148,14 +360,16 @@ STDMETHODIMP COpenCallbackImp::GetStream(const wchar_t *name, IInStream **inStre
148 COM_TRY_END 360 COM_TRY_END
149} 361}
150 362
151#ifndef _NO_CRYPTO 363
152STDMETHODIMP COpenCallbackImp::CryptoGetTextPassword(BSTR *password) 364#ifndef Z7_NO_CRYPTO
365Z7_COM7F_IMF(COpenCallbackImp::CryptoGetTextPassword(BSTR *password))
153{ 366{
154 COM_TRY_BEGIN 367 COM_TRY_BEGIN
155 if (ReOpenCallback) 368 if (ReOpenCallback)
156 { 369 {
157 CMyComPtr<ICryptoGetTextPassword> getTextPassword; 370 Z7_DECL_CMyComPtr_QI_FROM(
158 ReOpenCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); 371 ICryptoGetTextPassword,
372 getTextPassword, ReOpenCallback)
159 if (getTextPassword) 373 if (getTextPassword)
160 return getTextPassword->CryptoGetTextPassword(password); 374 return getTextPassword->CryptoGetTextPassword(password);
161 } 375 }
@@ -166,3 +380,14 @@ STDMETHODIMP COpenCallbackImp::CryptoGetTextPassword(BSTR *password)
166 COM_TRY_END 380 COM_TRY_END
167} 381}
168#endif 382#endif
383
384// IProgress
385Z7_COM7F_IMF(COpenCallbackImp::SetTotal(const UInt64 /* total */))
386{
387 return S_OK;
388}
389
390Z7_COM7F_IMF(COpenCallbackImp::SetCompleted(const UInt64 * /* completed */))
391{
392 return S_OK;
393}
diff --git a/CPP/7zip/UI/Common/ArchiveOpenCallback.h b/CPP/7zip/UI/Common/ArchiveOpenCallback.h
index 46b2676..4e44c9d 100644
--- a/CPP/7zip/UI/Common/ArchiveOpenCallback.h
+++ b/CPP/7zip/UI/Common/ArchiveOpenCallback.h
@@ -1,112 +1,176 @@
1// ArchiveOpenCallback.h 1// ArchiveOpenCallback.h
2 2
3#ifndef __ARCHIVE_OPEN_CALLBACK_H 3#ifndef ZIP7_INC_ARCHIVE_OPEN_CALLBACK_H
4#define __ARCHIVE_OPEN_CALLBACK_H 4#define ZIP7_INC_ARCHIVE_OPEN_CALLBACK_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#include "../../../Windows/FileFind.h" 8#include "../../../Windows/FileFind.h"
9#include "../../../Windows/FileIO.h"
10 9
11#ifndef _NO_CRYPTO 10#include "../../Common/FileStreams.h"
11
12#ifndef Z7_NO_CRYPTO
12#include "../../IPassword.h" 13#include "../../IPassword.h"
13#endif 14#endif
14#include "../../Archive/IArchive.h" 15#include "../../Archive/IArchive.h"
15 16
16#ifdef _NO_CRYPTO 17Z7_PURE_INTERFACES_BEGIN
18
19#ifdef Z7_NO_CRYPTO
17 20
18#define INTERFACE_IOpenCallbackUI_Crypto(x) 21#define Z7_IFACEM_IOpenCallbackUI_Crypto(x)
19 22
20#else 23#else
21 24
22#define INTERFACE_IOpenCallbackUI_Crypto(x) \ 25#define Z7_IFACEM_IOpenCallbackUI_Crypto(x) \
23 virtual HRESULT Open_CryptoGetTextPassword(BSTR *password) x; \ 26 virtual HRESULT Open_CryptoGetTextPassword(BSTR *password) x \
24 /* virtual HRESULT Open_GetPasswordIfAny(bool &passwordIsDefined, UString &password) x; */ \ 27 /* virtual HRESULT Open_GetPasswordIfAny(bool &passwordIsDefined, UString &password) x */ \
25 /* virtual bool Open_WasPasswordAsked() x; */ \ 28 /* virtual bool Open_WasPasswordAsked() x */ \
26 /* virtual void Open_Clear_PasswordWasAsked_Flag() x; */ \ 29 /* virtual void Open_Clear_PasswordWasAsked_Flag() x */ \
27 30
28#endif 31#endif
29 32
30#define INTERFACE_IOpenCallbackUI(x) \ 33#define Z7_IFACEN_IOpenCallbackUI(x) \
31 virtual HRESULT Open_CheckBreak() x; \ 34 virtual HRESULT Open_CheckBreak() x \
32 virtual HRESULT Open_SetTotal(const UInt64 *files, const UInt64 *bytes) x; \ 35 virtual HRESULT Open_SetTotal(const UInt64 *files, const UInt64 *bytes) x \
33 virtual HRESULT Open_SetCompleted(const UInt64 *files, const UInt64 *bytes) x; \ 36 virtual HRESULT Open_SetCompleted(const UInt64 *files, const UInt64 *bytes) x \
34 virtual HRESULT Open_Finished() x; \ 37 virtual HRESULT Open_Finished() x \
35 INTERFACE_IOpenCallbackUI_Crypto(x) 38 Z7_IFACEM_IOpenCallbackUI_Crypto(x)
39
40Z7_IFACE_DECL_PURE(IOpenCallbackUI)
41
42Z7_PURE_INTERFACES_END
43
36 44
37struct IOpenCallbackUI 45class CMultiStreams Z7_final
38{ 46{
39 INTERFACE_IOpenCallbackUI(=0) 47public:
48 struct CSubStream
49 {
50 CMyComPtr<IInStream> Stream;
51 CInFileStream *FileSpec;
52 FString Path;
53 // UInt64 Size;
54 UInt64 LocalPos;
55 int Next; // next older
56 int Prev; // prev newer
57 // bool IsOpen;
58
59 CSubStream():
60 FileSpec(NULL),
61 // Size(0),
62 LocalPos(0),
63 Next(-1),
64 Prev(-1)
65 // IsOpen(false)
66 {}
67 };
68
69 CObjectVector<CSubStream> Streams;
70private:
71 // we must use critical section here, if we want to access from different volumnes simultaneously
72 int Head; // newest
73 int Tail; // oldest
74 unsigned NumListItems;
75 unsigned NumOpenFiles_AllowedMax;
76public:
77
78 CMultiStreams();
79 void Init();
80 HRESULT PrepareToOpenNew();
81 void InsertToList(unsigned index);
82 void RemoveFromList(CSubStream &s);
83 void CloseFile(unsigned index);
84 HRESULT EnsureOpen(unsigned index);
40}; 85};
41 86
42class COpenCallbackImp: 87
88/*
89 We need COpenCallbackImp class for multivolume processing.
90 Also we use it as proxy from COM interfaces (IArchiveOpenCallback) to internal (IOpenCallbackUI) interfaces.
91 If archive is multivolume:
92 COpenCallbackImp object will exist after Open stage.
93 COpenCallbackImp object will be deleted when last reference
94 from each volume object (CInFileStreamVol) will be closed (when archive will be closed).
95*/
96
97class COpenCallbackImp Z7_final:
43 public IArchiveOpenCallback, 98 public IArchiveOpenCallback,
44 public IArchiveOpenVolumeCallback, 99 public IArchiveOpenVolumeCallback,
45 public IArchiveOpenSetSubArchiveName, 100 public IArchiveOpenSetSubArchiveName,
46 #ifndef _NO_CRYPTO 101 #ifndef Z7_NO_CRYPTO
47 public ICryptoGetTextPassword, 102 public ICryptoGetTextPassword,
48 #endif 103 #endif
104 public IProgress, // IProgress is used for 7zFM
49 public CMyUnknownImp 105 public CMyUnknownImp
50{ 106{
107 Z7_COM_QI_BEGIN2(IArchiveOpenCallback)
108 Z7_COM_QI_ENTRY(IArchiveOpenVolumeCallback)
109 Z7_COM_QI_ENTRY(IArchiveOpenSetSubArchiveName)
110 #ifndef Z7_NO_CRYPTO
111 Z7_COM_QI_ENTRY(ICryptoGetTextPassword)
112 #endif
113 // Z7_COM_QI_ENTRY(IProgress) // the code doesn't require it
114 Z7_COM_QI_END
115 Z7_COM_ADDREF_RELEASE
116
117 Z7_IFACE_COM7_IMP(IArchiveOpenCallback)
118 Z7_IFACE_COM7_IMP(IArchiveOpenVolumeCallback)
119 Z7_IFACE_COM7_IMP(IProgress)
51public: 120public:
52 MY_QUERYINTERFACE_BEGIN2(IArchiveOpenVolumeCallback) 121 Z7_IFACE_COM7_IMP(IArchiveOpenSetSubArchiveName)
53 MY_QUERYINTERFACE_ENTRY(IArchiveOpenSetSubArchiveName)
54 #ifndef _NO_CRYPTO
55 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword)
56 #endif
57 MY_QUERYINTERFACE_END
58 MY_ADDREF_RELEASE
59
60 INTERFACE_IArchiveOpenCallback(;)
61 INTERFACE_IArchiveOpenVolumeCallback(;)
62
63 #ifndef _NO_CRYPTO
64 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
65 #endif
66
67 STDMETHOD(SetSubArchiveName(const wchar_t *name))
68 {
69 _subArchiveMode = true;
70 _subArchiveName = name;
71 // TotalSize = 0;
72 return S_OK;
73 }
74
75private: 122private:
76 FString _folderPrefix; 123 #ifndef Z7_NO_CRYPTO
77 NWindows::NFile::NFind::CFileInfo _fileInfo; 124 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
125 #endif
126
78 bool _subArchiveMode; 127 bool _subArchiveMode;
79 UString _subArchiveName;
80 128
81public: 129public:
130 bool PasswordWasAsked;
82 UStringVector FileNames; 131 UStringVector FileNames;
83 CBoolVector FileNames_WasUsed; 132 CBoolVector FileNames_WasUsed;
84 CRecordVector<UInt64> FileSizes; 133 CRecordVector<UInt64> FileSizes;
85
86 bool PasswordWasAsked;
87 134
135 void AtCloseFile(unsigned fileIndex)
136 {
137 FileNames_WasUsed[fileIndex] = false;
138 Volumes.CloseFile(fileIndex);
139 }
140
141 /* we have two ways to Callback from this object
142 1) IArchiveOpenCallback * ReOpenCallback - for ReOpen function, when IOpenCallbackUI is not available
143 2) IOpenCallbackUI *Callback - for usual callback
144 we can't transfer IOpenCallbackUI pointer via internal interface,
145 so we use ReOpenCallback to callback without IOpenCallbackUI.
146 */
147
148 /* we use Callback/ReOpenCallback only at Open stage.
149 So the CMyComPtr reference counter is not required,
150 and we don't want additional reference to unused object,
151 if COpenCallbackImp is not closed
152 */
153 IArchiveOpenCallback *ReOpenCallback;
154 // CMyComPtr<IArchiveOpenCallback> ReOpenCallback;
88 IOpenCallbackUI *Callback; 155 IOpenCallbackUI *Callback;
89 CMyComPtr<IArchiveOpenCallback> ReOpenCallback; 156 // CMyComPtr<IUnknown> Callback_Ref;
157
158private:
159 FString _folderPrefix;
160 UString _subArchiveName;
161 NWindows::NFile::NFind::CFileInfo _fileInfo;
162
163public:
164 CMultiStreams Volumes;
165
90 // UInt64 TotalSize; 166 // UInt64 TotalSize;
91 167
92 COpenCallbackImp(): _subArchiveMode(false), Callback(NULL) {} 168 COpenCallbackImp():
169 _subArchiveMode(false),
170 ReOpenCallback(NULL),
171 Callback(NULL) {}
93 172
94 HRESULT Init2(const FString &folderPrefix, const FString &fileName) 173 HRESULT Init2(const FString &folderPrefix, const FString &fileName);
95 {
96 FileNames.Clear();
97 FileNames_WasUsed.Clear();
98 FileSizes.Clear();
99 _subArchiveMode = false;
100 // TotalSize = 0;
101 PasswordWasAsked = false;
102 _folderPrefix = folderPrefix;
103 if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName))
104 {
105 // throw 20121118;
106 return GetLastError_noZero_HRESULT();
107 }
108 return S_OK;
109 }
110 174
111 bool SetSecondFileInfo(CFSTR newName) 175 bool SetSecondFileInfo(CFSTR newName)
112 { 176 {
diff --git a/CPP/7zip/UI/Common/Bench.cpp b/CPP/7zip/UI/Common/Bench.cpp
index cc0cfd0..5da9783 100644
--- a/CPP/7zip/UI/Common/Bench.cpp
+++ b/CPP/7zip/UI/Common/Bench.cpp
@@ -36,19 +36,20 @@
36#include "../../../../C/7zCrc.h" 36#include "../../../../C/7zCrc.h"
37#include "../../../../C/RotateDefs.h" 37#include "../../../../C/RotateDefs.h"
38 38
39#ifndef _7ZIP_ST 39#ifndef Z7_ST
40#include "../../../Windows/Synchronization.h" 40#include "../../../Windows/Synchronization.h"
41#include "../../../Windows/Thread.h" 41#include "../../../Windows/Thread.h"
42#endif 42#endif
43 43
44#include "../../../Windows/FileIO.h"
45#include "../../../Windows/FileFind.h" 44#include "../../../Windows/FileFind.h"
45#include "../../../Windows/FileIO.h"
46#include "../../../Windows/SystemInfo.h" 46#include "../../../Windows/SystemInfo.h"
47 47
48#include "../../../Common/IntToString.h"
49#include "../../../Common/MyBuffer2.h" 48#include "../../../Common/MyBuffer2.h"
49#include "../../../Common/IntToString.h"
50#include "../../../Common/StringConvert.h" 50#include "../../../Common/StringConvert.h"
51#include "../../../Common/StringToInt.h" 51#include "../../../Common/StringToInt.h"
52#include "../../../Common/Wildcard.h"
52 53
53#include "../../Common/MethodProps.h" 54#include "../../Common/MethodProps.h"
54#include "../../Common/StreamObjects.h" 55#include "../../Common/StreamObjects.h"
@@ -58,7 +59,7 @@
58 59
59using namespace NWindows; 60using namespace NWindows;
60 61
61#ifndef _7ZIP_ST 62#ifndef Z7_ST
62static const UInt32 k_LZMA = 0x030101; 63static const UInt32 k_LZMA = 0x030101;
63#endif 64#endif
64 65
@@ -122,7 +123,7 @@ class CBaseRandomGenerator
122public: 123public:
123 CBaseRandomGenerator(UInt32 salt = 0): Salt(salt) { Init(); } 124 CBaseRandomGenerator(UInt32 salt = 0): Salt(salt) { Init(); }
124 void Init() { A1 = 362436069; A2 = 521288629;} 125 void Init() { A1 = 362436069; A2 = 521288629;}
125 MY_FORCE_INLINE 126 Z7_FORCE_INLINE
126 UInt32 GetRnd() 127 UInt32 GetRnd()
127 { 128 {
128 return Salt ^ 129 return Salt ^
@@ -134,7 +135,7 @@ public:
134}; 135};
135 136
136 137
137MY_NO_INLINE 138Z7_NO_INLINE
138static void RandGen(Byte *buf, size_t size) 139static void RandGen(Byte *buf, size_t size)
139{ 140{
140 CBaseRandomGenerator RG; 141 CBaseRandomGenerator RG;
@@ -143,7 +144,7 @@ static void RandGen(Byte *buf, size_t size)
143 for (i = 0; i < size4; i += 4) 144 for (i = 0; i < size4; i += 4)
144 { 145 {
145 const UInt32 v = RG.GetRnd(); 146 const UInt32 v = RG.GetRnd();
146 SetUi32(buf + i, v); 147 SetUi32(buf + i, v)
147 } 148 }
148 UInt32 v = RG.GetRnd(); 149 UInt32 v = RG.GetRnd();
149 for (; i < size; i++) 150 for (; i < size; i++)
@@ -255,16 +256,14 @@ public:
255}; 256};
256 257
257 258
258class CBenchmarkInStream: 259Z7_CLASS_IMP_NOQIB_1(
259 public ISequentialInStream, 260 CBenchmarkInStream
260 public CMyUnknownImp 261 , ISequentialInStream
261{ 262)
262 const Byte *Data; 263 const Byte *Data;
263 size_t Pos; 264 size_t Pos;
264 size_t Size; 265 size_t Size;
265
266public: 266public:
267 MY_UNKNOWN_IMP
268 void Init(const Byte *data, size_t size) 267 void Init(const Byte *data, size_t size)
269 { 268 {
270 Data = data; 269 Data = data;
@@ -272,10 +271,9 @@ public:
272 Pos = 0; 271 Pos = 0;
273 } 272 }
274 bool WasFinished() const { return Pos == Size; } 273 bool WasFinished() const { return Pos == Size; }
275 STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
276}; 274};
277 275
278STDMETHODIMP CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processedSize) 276Z7_COM7F_IMF(CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processedSize))
279{ 277{
280 const UInt32 kMaxBlockSize = (1 << 20); 278 const UInt32 kMaxBlockSize = (1 << 20);
281 if (size > kMaxBlockSize) 279 if (size > kMaxBlockSize)
@@ -293,11 +291,14 @@ STDMETHODIMP CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processed
293 return S_OK; 291 return S_OK;
294} 292}
295 293
296class CBenchmarkOutStream: 294
295class CBenchmarkOutStream Z7_final:
297 public ISequentialOutStream, 296 public ISequentialOutStream,
298 public CMidAlignedBuffer, 297 public CMyUnknownImp,
299 public CMyUnknownImp 298 public CMidAlignedBuffer
300{ 299{
300 Z7_COM_UNKNOWN_IMP_0
301 Z7_IFACE_COM7_IMP(ISequentialOutStream)
301 // bool _overflow; 302 // bool _overflow;
302public: 303public:
303 size_t Pos; 304 size_t Pos;
@@ -328,12 +329,9 @@ public:
328 size_t GetPos() const { return Pos; } 329 size_t GetPos() const { return Pos; }
329 330
330 // void Print() { printf("\n%8d %8d\n", (unsigned)BufferSize, (unsigned)Pos); } 331 // void Print() { printf("\n%8d %8d\n", (unsigned)BufferSize, (unsigned)Pos); }
331
332 MY_UNKNOWN_IMP
333 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
334}; 332};
335 333
336STDMETHODIMP CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 334Z7_COM7F_IMF(CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
337{ 335{
338 size_t curSize = Size() - Pos; 336 size_t curSize = Size() - Pos;
339 if (curSize > size) 337 if (curSize > size)
@@ -357,27 +355,24 @@ STDMETHODIMP CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *p
357} 355}
358 356
359 357
360class CCrcOutStream: 358Z7_CLASS_IMP_NOQIB_1(
361 public ISequentialOutStream, 359 CCrcOutStream
362 public CMyUnknownImp 360 , ISequentialOutStream
363{ 361)
364public: 362public:
365 bool CalcCrc; 363 bool CalcCrc;
366 UInt32 Crc; 364 UInt32 Crc;
367 UInt64 Pos; 365 UInt64 Pos;
368 366
369 MY_UNKNOWN_IMP 367 CCrcOutStream(): CalcCrc(true) {}
370
371 CCrcOutStream(): CalcCrc(true) {};
372 void Init() { Crc = CRC_INIT_VAL; Pos = 0; } 368 void Init() { Crc = CRC_INIT_VAL; Pos = 0; }
373 void Calc(const void *data, size_t size) 369 void Calc(const void *data, size_t size)
374 { 370 {
375 Crc = CrcUpdate(Crc, data, size); 371 Crc = CrcUpdate(Crc, data, size);
376 } 372 }
377 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
378}; 373};
379 374
380STDMETHODIMP CCrcOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) 375Z7_COM7F_IMF(CCrcOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize))
381{ 376{
382 if (CalcCrc) 377 if (CalcCrc)
383 Calc(data, size); 378 Calc(data, size);
@@ -394,7 +389,7 @@ static UInt64 GetTimeCount()
394 #ifdef USE_POSIX_TIME 389 #ifdef USE_POSIX_TIME
395 #ifdef USE_POSIX_TIME2 390 #ifdef USE_POSIX_TIME2
396 timeval v; 391 timeval v;
397 if (gettimeofday(&v, 0) == 0) 392 if (gettimeofday(&v, NULL) == 0)
398 return (UInt64)(v.tv_sec) * 1000000 + (UInt64)v.tv_usec; 393 return (UInt64)(v.tv_sec) * 1000000 + (UInt64)v.tv_usec;
399 return (UInt64)time(NULL) * 1000000; 394 return (UInt64)time(NULL) * 1000000;
400 #else 395 #else
@@ -531,9 +526,9 @@ static UInt64 GetUserFreq()
531 #endif 526 #endif
532} 527}
533 528
534class CBenchProgressStatus 529class CBenchProgressStatus Z7_final
535{ 530{
536 #ifndef _7ZIP_ST 531 #ifndef Z7_ST
537 NSynchronization::CCriticalSection CS; 532 NSynchronization::CCriticalSection CS;
538 #endif 533 #endif
539public: 534public:
@@ -541,14 +536,14 @@ public:
541 bool EncodeMode; 536 bool EncodeMode;
542 void SetResult(HRESULT res) 537 void SetResult(HRESULT res)
543 { 538 {
544 #ifndef _7ZIP_ST 539 #ifndef Z7_ST
545 NSynchronization::CCriticalSectionLock lock(CS); 540 NSynchronization::CCriticalSectionLock lock(CS);
546 #endif 541 #endif
547 Res = res; 542 Res = res;
548 } 543 }
549 HRESULT GetResult() 544 HRESULT GetResult()
550 { 545 {
551 #ifndef _7ZIP_ST 546 #ifndef Z7_ST
552 NSynchronization::CCriticalSectionLock lock(CS); 547 NSynchronization::CCriticalSectionLock lock(CS);
553 #endif 548 #endif
554 return Res; 549 return Res;
@@ -580,22 +575,22 @@ void CBenchInfoCalc::SetFinishTime(CBenchInfo &dest)
580 dest.UserTime = UserTime.GetUserTime(); 575 dest.UserTime = UserTime.GetUserTime();
581} 576}
582 577
583class CBenchProgressInfo: 578class CBenchProgressInfo Z7_final:
584 public ICompressProgressInfo, 579 public ICompressProgressInfo,
585 public CMyUnknownImp, 580 public CMyUnknownImp,
586 public CBenchInfoCalc 581 public CBenchInfoCalc
587{ 582{
583 Z7_COM_UNKNOWN_IMP_0
584 Z7_IFACE_COM7_IMP(ICompressProgressInfo)
588public: 585public:
589 CBenchProgressStatus *Status; 586 CBenchProgressStatus *Status;
590 IBenchCallback *Callback; 587 IBenchCallback *Callback;
591 588
592 CBenchProgressInfo(): Callback(NULL) {} 589 CBenchProgressInfo(): Callback(NULL) {}
593 MY_UNKNOWN_IMP
594 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
595}; 590};
596 591
597 592
598STDMETHODIMP CBenchProgressInfo::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 593Z7_COM7F_IMF(CBenchProgressInfo::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
599{ 594{
600 HRESULT res = Status->GetResult(); 595 HRESULT res = Status->GetResult();
601 if (res != S_OK) 596 if (res != S_OK)
@@ -760,13 +755,20 @@ UInt64 CBenchInfo::GetSpeed(UInt64 numUnits) const
760 return MyMultDiv64(numUnits, GlobalFreq, GlobalTime); 755 return MyMultDiv64(numUnits, GlobalFreq, GlobalTime);
761} 756}
762 757
758static UInt64 GetNumCommands_from_Size_and_Complexity(UInt64 size, Int32 complexity)
759{
760 return complexity >= 0 ?
761 size * (UInt32)complexity :
762 size / (UInt32)(-complexity);
763}
764
763struct CBenchProps 765struct CBenchProps
764{ 766{
765 bool LzmaRatingMode; 767 bool LzmaRatingMode;
766 768
767 UInt32 EncComplex; 769 Int32 EncComplex;
768 UInt32 DecComplexCompr; 770 Int32 DecComplexCompr;
769 UInt32 DecComplexUnc; 771 Int32 DecComplexUnc;
770 772
771 unsigned KeySize; 773 unsigned KeySize;
772 774
@@ -777,21 +779,23 @@ struct CBenchProps
777 779
778 void SetLzmaCompexity(); 780 void SetLzmaCompexity();
779 781
780 UInt64 GeComprCommands(UInt64 unpackSize) 782 UInt64 GetNumCommands_Enc(UInt64 unpackSize) const
781 { 783 {
782 const UInt32 kMinSize = 100; 784 const UInt32 kMinSize = 100;
783 if (unpackSize < kMinSize) 785 if (unpackSize < kMinSize)
784 unpackSize = kMinSize; 786 unpackSize = kMinSize;
785 return unpackSize * EncComplex; 787 return GetNumCommands_from_Size_and_Complexity(unpackSize, EncComplex);
786 } 788 }
787 789
788 UInt64 GeDecomprCommands(UInt64 packSize, UInt64 unpackSize) 790 UInt64 GetNumCommands_Dec(UInt64 packSize, UInt64 unpackSize) const
789 { 791 {
790 return (packSize * DecComplexCompr + unpackSize * DecComplexUnc); 792 return
793 GetNumCommands_from_Size_and_Complexity(packSize, DecComplexCompr) +
794 GetNumCommands_from_Size_and_Complexity(unpackSize, DecComplexUnc);
791 } 795 }
792 796
793 UInt64 GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size); 797 UInt64 GetRating_Enc(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) const;
794 UInt64 GetDecompressRating(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations); 798 UInt64 GetRating_Dec(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) const;
795}; 799};
796 800
797void CBenchProps::SetLzmaCompexity() 801void CBenchProps::SetLzmaCompexity()
@@ -802,11 +806,11 @@ void CBenchProps::SetLzmaCompexity()
802 LzmaRatingMode = true; 806 LzmaRatingMode = true;
803} 807}
804 808
805UInt64 CBenchProps::GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) 809UInt64 CBenchProps::GetRating_Enc(UInt64 dictSize, UInt64 elapsedTime, UInt64 freq, UInt64 size) const
806{ 810{
807 if (dictSize < (1 << kBenchMinDicLogSize)) 811 if (dictSize < (1 << kBenchMinDicLogSize))
808 dictSize = (1 << kBenchMinDicLogSize); 812 dictSize = (1 << kBenchMinDicLogSize);
809 UInt64 encComplex = EncComplex; 813 Int32 encComplex = EncComplex;
810 if (LzmaRatingMode) 814 if (LzmaRatingMode)
811 { 815 {
812 /* 816 /*
@@ -822,13 +826,13 @@ UInt64 CBenchProps::GetCompressRating(UInt64 dictSize, UInt64 elapsedTime, UInt6
822 const UInt32 t = GetLogSize_Sub(dictSize) - (kBenchMinDicLogSize << kSubBits); 826 const UInt32 t = GetLogSize_Sub(dictSize) - (kBenchMinDicLogSize << kSubBits);
823 encComplex = 870 + ((t * t * 5) >> (2 * kSubBits)); 827 encComplex = 870 + ((t * t * 5) >> (2 * kSubBits));
824 } 828 }
825 const UInt64 numCommands = (UInt64)size * encComplex; 829 const UInt64 numCommands = GetNumCommands_from_Size_and_Complexity(size, encComplex);
826 return MyMultDiv64(numCommands, freq, elapsedTime); 830 return MyMultDiv64(numCommands, freq, elapsedTime);
827} 831}
828 832
829UInt64 CBenchProps::GetDecompressRating(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) 833UInt64 CBenchProps::GetRating_Dec(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt64 numIterations) const
830{ 834{
831 const UInt64 numCommands = (inSize * DecComplexCompr + outSize * DecComplexUnc) * numIterations; 835 const UInt64 numCommands = GetNumCommands_Dec(inSize, outSize) * numIterations;
832 return MyMultDiv64(numCommands, freq, elapsedTime); 836 return MyMultDiv64(numCommands, freq, elapsedTime);
833} 837}
834 838
@@ -838,18 +842,18 @@ UInt64 CBenchInfo::GetRating_LzmaEnc(UInt64 dictSize) const
838{ 842{
839 CBenchProps props; 843 CBenchProps props;
840 props.SetLzmaCompexity(); 844 props.SetLzmaCompexity();
841 return props.GetCompressRating(dictSize, GlobalTime, GlobalFreq, UnpackSize * NumIterations); 845 return props.GetRating_Enc(dictSize, GlobalTime, GlobalFreq, UnpackSize * NumIterations);
842} 846}
843 847
844UInt64 CBenchInfo::GetRating_LzmaDec() const 848UInt64 CBenchInfo::GetRating_LzmaDec() const
845{ 849{
846 CBenchProps props; 850 CBenchProps props;
847 props.SetLzmaCompexity(); 851 props.SetLzmaCompexity();
848 return props.GetDecompressRating(GlobalTime, GlobalFreq, UnpackSize, PackSize, NumIterations); 852 return props.GetRating_Dec(GlobalTime, GlobalFreq, UnpackSize, PackSize, NumIterations);
849} 853}
850 854
851 855
852#ifndef _7ZIP_ST 856#ifndef Z7_ST
853 857
854#define NUM_CPU_LEVELS_MAX 3 858#define NUM_CPU_LEVELS_MAX 3
855 859
@@ -988,15 +992,22 @@ struct CBenchSyncCommon
988 992
989 993
990 994
995enum E_CheckCrcMode
996{
997 k_CheckCrcMode_Never = 0,
998 k_CheckCrcMode_Always = 1,
999 k_CheckCrcMode_FirstPass = 2
1000};
1001
991class CEncoderInfo; 1002class CEncoderInfo;
992 1003
993class CEncoderInfo 1004class CEncoderInfo Z7_final
994{ 1005{
995 CLASS_NO_COPY(CEncoderInfo) 1006 Z7_CLASS_NO_COPY(CEncoderInfo)
996 1007
997public: 1008public:
998 1009
999 #ifndef _7ZIP_ST 1010 #ifndef Z7_ST
1000 NWindows::CThread thread[2]; 1011 NWindows::CThread thread[2];
1001 NSynchronization::CManualResetEvent ReadyEvent; 1012 NSynchronization::CManualResetEvent ReadyEvent;
1002 UInt32 NumDecoderSubThreads; 1013 UInt32 NumDecoderSubThreads;
@@ -1004,6 +1015,7 @@ public:
1004 UInt32 EncoderIndex; 1015 UInt32 EncoderIndex;
1005 UInt32 NumEncoderInternalThreads; 1016 UInt32 NumEncoderInternalThreads;
1006 CAffinityMode AffinityMode; 1017 CAffinityMode AffinityMode;
1018 bool IsGlobalMtMode; // if more than one benchmark encoder threads
1007 #endif 1019 #endif
1008 1020
1009 CMyComPtr<ICompressCoder> _encoder; 1021 CMyComPtr<ICompressCoder> _encoder;
@@ -1024,14 +1036,17 @@ public:
1024 1036
1025 HRESULT Set_Key_and_IV(ICryptoProperties *cp) 1037 HRESULT Set_Key_and_IV(ICryptoProperties *cp)
1026 { 1038 {
1027 RINOK(cp->SetKey(_key, KeySize)); 1039 RINOK(cp->SetKey(_key, KeySize))
1028 return cp->SetInitVector(_iv, sizeof(_iv)); 1040 return cp->SetInitVector(_iv, sizeof(_iv));
1029 } 1041 }
1030 1042
1031 Byte _psw[16]; 1043 Byte _psw[16];
1032 1044
1033 bool CheckCrc_Enc; 1045 bool CheckCrc_Enc; /* = 1, if we want to check packed data crcs after each pass
1034 bool CheckCrc_Dec; 1046 used for filter and usual coders */
1047 bool UseRealData_Enc; /* = 1, if we want to use only original data for each pass
1048 used only for filter */
1049 E_CheckCrcMode CheckCrcMode_Dec;
1035 1050
1036 struct CDecoderInfo 1051 struct CDecoderInfo
1037 { 1052 {
@@ -1079,13 +1094,15 @@ public:
1079 HRESULT Decode(UInt32 decoderIndex); 1094 HRESULT Decode(UInt32 decoderIndex);
1080 1095
1081 CEncoderInfo(): 1096 CEncoderInfo():
1082 #ifndef _7ZIP_ST 1097 #ifndef Z7_ST
1083 Common(NULL), 1098 Common(NULL),
1099 IsGlobalMtMode(true),
1084 #endif 1100 #endif
1085 Salt(0), 1101 Salt(0),
1086 KeySize(0), 1102 KeySize(0),
1087 CheckCrc_Enc(true), 1103 CheckCrc_Enc(true),
1088 CheckCrc_Dec(true), 1104 UseRealData_Enc(true),
1105 CheckCrcMode_Dec(k_CheckCrcMode_Always),
1089 outStreamSpec(NULL), 1106 outStreamSpec(NULL),
1090 callback(NULL), 1107 callback(NULL),
1091 printCallback(NULL), 1108 printCallback(NULL),
@@ -1093,7 +1110,7 @@ public:
1093 propStreamSpec(NULL) 1110 propStreamSpec(NULL)
1094 {} 1111 {}
1095 1112
1096 #ifndef _7ZIP_ST 1113 #ifndef Z7_ST
1097 1114
1098 static THREAD_FUNC_DECL EncodeThreadFunction(void *param) 1115 static THREAD_FUNC_DECL EncodeThreadFunction(void *param)
1099 { 1116 {
@@ -1115,7 +1132,7 @@ public:
1115 if (res != S_OK) 1132 if (res != S_OK)
1116 encoder->progressInfoSpec[0]->Status->SetResult(res); 1133 encoder->progressInfoSpec[0]->Status->SetResult(res);
1117 encoder->ReadyEvent.Set(); 1134 encoder->ReadyEvent.Set();
1118 return 0; 1135 return THREAD_FUNC_RET_ZERO;
1119 } 1136 }
1120 1137
1121 static THREAD_FUNC_DECL DecodeThreadFunction(void *param) 1138 static THREAD_FUNC_DECL DecodeThreadFunction(void *param)
@@ -1128,7 +1145,7 @@ public:
1128 1145
1129 CEncoderInfo *encoder = decoder->Encoder; 1146 CEncoderInfo *encoder = decoder->Encoder;
1130 encoder->Results[decoder->DecoderIndex] = encoder->Decode(decoder->DecoderIndex); 1147 encoder->Results[decoder->DecoderIndex] = encoder->Decode(decoder->DecoderIndex);
1131 return 0; 1148 return THREAD_FUNC_RET_ZERO;
1132 } 1149 }
1133 1150
1134 HRESULT CreateEncoderThread() 1151 HRESULT CreateEncoderThread()
@@ -1184,17 +1201,30 @@ HRESULT CEncoderInfo::Generate()
1184 const COneMethodInfo &method = _method; 1201 const COneMethodInfo &method = _method;
1185 1202
1186 // we need extra space, if input data is already compressed 1203 // we need extra space, if input data is already compressed
1187 const size_t kCompressedBufferSize = GetBenchCompressedSize(kBufferSize); 1204 const size_t kCompressedBufferSize = _encoderFilter ?
1205 kBufferSize :
1206 GetBenchCompressedSize(kBufferSize);
1188 1207
1189 if (kCompressedBufferSize < kBufferSize) 1208 if (kCompressedBufferSize < kBufferSize)
1190 return E_FAIL; 1209 return E_FAIL;
1191 1210
1192 uncompressedDataPtr = fileData; 1211 uncompressedDataPtr = fileData;
1193 1212 if (fileData)
1194 if (!fileData)
1195 { 1213 {
1196 ALLOC_WITH_HRESULT(&rg, kBufferSize); 1214 #if !defined(Z7_ST)
1197 1215 if (IsGlobalMtMode)
1216 {
1217 /* we copy the data to local buffer of thread to eliminate
1218 using of shared buffer by different threads */
1219 ALLOC_WITH_HRESULT(&rg, kBufferSize)
1220 memcpy((Byte *)rg, fileData, kBufferSize);
1221 uncompressedDataPtr = (const Byte *)rg;
1222 }
1223 #endif
1224 }
1225 else
1226 {
1227 ALLOC_WITH_HRESULT(&rg, kBufferSize)
1198 // DWORD ttt = GetTickCount(); 1228 // DWORD ttt = GetTickCount();
1199 if (generateDictBits == 0) 1229 if (generateDictBits == 0)
1200 rg.GenerateSimpleRandom(Salt); 1230 rg.GenerateSimpleRandom(Salt);
@@ -1211,12 +1241,6 @@ HRESULT CEncoderInfo::Generate()
1211 crc = CrcCalc((const Byte *)rg, rg.Size()); 1241 crc = CrcCalc((const Byte *)rg, rg.Size());
1212 uncompressedDataPtr = (const Byte *)rg; 1242 uncompressedDataPtr = (const Byte *)rg;
1213 } 1243 }
1214
1215 if (_encoderFilter)
1216 {
1217 ALLOC_WITH_HRESULT(&rgCopy, kBufferSize);
1218 }
1219
1220 1244
1221 if (!outStream) 1245 if (!outStream)
1222 { 1246 {
@@ -1226,6 +1250,15 @@ HRESULT CEncoderInfo::Generate()
1226 1250
1227 ALLOC_WITH_HRESULT(outStreamSpec, kCompressedBufferSize) 1251 ALLOC_WITH_HRESULT(outStreamSpec, kCompressedBufferSize)
1228 1252
1253 if (_encoderFilter)
1254 {
1255 /* we try to reduce the number of memcpy() in main encoding loop.
1256 so we copy data to temp buffers here */
1257 ALLOC_WITH_HRESULT(&rgCopy, kBufferSize)
1258 memcpy((Byte *)*outStreamSpec, uncompressedDataPtr, kBufferSize);
1259 memcpy((Byte *)rgCopy, uncompressedDataPtr, kBufferSize);
1260 }
1261
1229 if (!propStream) 1262 if (!propStream)
1230 { 1263 {
1231 propStreamSpec = new CBufPtrSeqOutStream; // CBenchmarkOutStream; 1264 propStreamSpec = new CBufPtrSeqOutStream; // CBenchmarkOutStream;
@@ -1251,7 +1284,7 @@ HRESULT CEncoderInfo::Generate()
1251 /* in posix new thread uses same affinity as parent thread, 1284 /* in posix new thread uses same affinity as parent thread,
1252 so we don't need to send affinity to coder in posix */ 1285 so we don't need to send affinity to coder in posix */
1253 UInt64 affMask; 1286 UInt64 affMask;
1254 #if !defined(_7ZIP_ST) && defined(_WIN32) 1287 #if !defined(Z7_ST) && defined(_WIN32)
1255 { 1288 {
1256 CCpuSet cpuSet; 1289 CCpuSet cpuSet;
1257 affMask = AffinityMode.GetAffinityMask(EncoderIndex, &cpuSet); 1290 affMask = AffinityMode.GetAffinityMask(EncoderIndex, &cpuSet);
@@ -1262,7 +1295,7 @@ HRESULT CEncoderInfo::Generate()
1262 // affMask <<= 3; // debug line: to test no affinity in coder; 1295 // affMask <<= 3; // debug line: to test no affinity in coder;
1263 // affMask = 0; 1296 // affMask = 0;
1264 1297
1265 RINOK(method.SetCoderProps_DSReduce_Aff(scp, &reduceSize, (affMask != 0 ? &affMask : NULL))); 1298 RINOK(method.SetCoderProps_DSReduce_Aff(scp, &reduceSize, (affMask != 0 ? &affMask : NULL)))
1266 } 1299 }
1267 else 1300 else
1268 { 1301 {
@@ -1274,7 +1307,7 @@ HRESULT CEncoderInfo::Generate()
1274 coder.QueryInterface(IID_ICompressWriteCoderProperties, &writeCoderProps); 1307 coder.QueryInterface(IID_ICompressWriteCoderProperties, &writeCoderProps);
1275 if (writeCoderProps) 1308 if (writeCoderProps)
1276 { 1309 {
1277 RINOK(writeCoderProps->WriteCoderProperties(propStream)); 1310 RINOK(writeCoderProps->WriteCoderProperties(propStream))
1278 } 1311 }
1279 1312
1280 { 1313 {
@@ -1282,7 +1315,7 @@ HRESULT CEncoderInfo::Generate()
1282 coder.QueryInterface(IID_ICryptoSetPassword, &sp); 1315 coder.QueryInterface(IID_ICryptoSetPassword, &sp);
1283 if (sp) 1316 if (sp)
1284 { 1317 {
1285 RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))); 1318 RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw)))
1286 1319
1287 // we must call encoding one time to calculate password key for key cache. 1320 // we must call encoding one time to calculate password key for key cache.
1288 // it must be after WriteCoderProperties! 1321 // it must be after WriteCoderProperties!
@@ -1304,7 +1337,7 @@ HRESULT CEncoderInfo::Generate()
1304 CMyComPtr<ISequentialOutStream> crcStream = crcStreamSpec; 1337 CMyComPtr<ISequentialOutStream> crcStream = crcStreamSpec;
1305 crcStreamSpec->Init(); 1338 crcStreamSpec->Init();
1306 1339
1307 RINOK(_encoder->Code(inStream, crcStream, 0, 0, NULL)); 1340 RINOK(_encoder->Code(inStream, crcStream, NULL, NULL, NULL))
1308 } 1341 }
1309 } 1342 }
1310 } 1343 }
@@ -1314,19 +1347,22 @@ HRESULT CEncoderInfo::Generate()
1314} 1347}
1315 1348
1316 1349
1317static void My_FilterBench(ICompressFilter *filter, Byte *data, size_t size) 1350static void My_FilterBench(ICompressFilter *filter, Byte *data, size_t size, UInt32 *crc)
1318{ 1351{
1319 while (size != 0) 1352 while (size != 0)
1320 { 1353 {
1321 UInt32 cur = (UInt32)1 << 31; 1354 UInt32 cur = crc ? 1 << 17 : 1 << 24;
1322 if (cur > size) 1355 if (cur > size)
1323 cur = (UInt32)size; 1356 cur = (UInt32)size;
1324 UInt32 processed = filter->Filter(data, cur); 1357 UInt32 processed = filter->Filter(data, cur);
1325 data += processed; 1358 /* if (processed > size) (in AES filter), we must fill last block with zeros.
1326 // if (processed > size) (in AES filter), we must fill last block with zeros. 1359 but it is not important for benchmark. So we just copy that data without filtering.
1327 // but it is not important for benchmark. So we just copy that data without filtering. 1360 if (processed == 0) then filter can't process more */
1328 if (processed > size || processed == 0) 1361 if (processed > size || processed == 0)
1329 break; 1362 processed = (UInt32)size;
1363 if (crc)
1364 *crc = CrcUpdate(*crc, data, processed);
1365 data += processed;
1330 size -= processed; 1366 size -= processed;
1331 } 1367 }
1332} 1368}
@@ -1336,11 +1372,11 @@ HRESULT CEncoderInfo::Encode()
1336{ 1372{
1337 // printf("\nCEncoderInfo::Generate\n"); 1373 // printf("\nCEncoderInfo::Generate\n");
1338 1374
1339 RINOK(Generate()); 1375 RINOK(Generate())
1340 1376
1341 // printf("\n2222\n"); 1377 // printf("\n2222\n");
1342 1378
1343 #ifndef _7ZIP_ST 1379 #ifndef Z7_ST
1344 if (Common) 1380 if (Common)
1345 { 1381 {
1346 Results[0] = S_OK; 1382 Results[0] = S_OK;
@@ -1375,7 +1411,7 @@ HRESULT CEncoderInfo::Encode()
1375 1411
1376 if (cp) 1412 if (cp)
1377 { 1413 {
1378 RINOK(Set_Key_and_IV(cp)); 1414 RINOK(Set_Key_and_IV(cp))
1379 } 1415 }
1380 1416
1381 compressedSize = 0; 1417 compressedSize = 0;
@@ -1384,20 +1420,32 @@ HRESULT CEncoderInfo::Encode()
1384 1420
1385 // CBenchmarkOutStream *outStreamSpec = this->outStreamSpec; 1421 // CBenchmarkOutStream *outStreamSpec = this->outStreamSpec;
1386 UInt64 prev = 0; 1422 UInt64 prev = 0;
1387 const UInt32 mask = (CheckCrc_Enc ? 0 : 0xFFF); 1423
1388 bool useCrc = (mask < NumIterations); 1424 const UInt32 mask = (CheckCrc_Enc ? 0 : 0xFFFF);
1425 const bool useCrc = (mask < NumIterations);
1389 bool crcPrev_defined = false; 1426 bool crcPrev_defined = false;
1390 UInt32 crcPrev = 0; 1427 UInt32 crcPrev = 0;
1391 UInt64 i = NumIterations; 1428
1429 bool useRealData_Enc = UseRealData_Enc;
1430 bool data_Was_Changed = false;
1431 if (useRealData_Enc)
1432 {
1433 /* we want memcpy() for each iteration including first iteration.
1434 So results will be equal for different number of iterations */
1435 data_Was_Changed = true;
1436 }
1437
1438 const UInt64 numIterations = NumIterations;
1439 UInt64 i = numIterations;
1392 // printCallback->NewLine(); 1440 // printCallback->NewLine();
1393 1441
1394 while (i != 0) 1442 while (i != 0)
1395 { 1443 {
1396 i--; 1444 i--;
1397 if (printCallback && bi.UnpackSize - prev >= (1 << 24)) 1445 if (printCallback && bi.UnpackSize - prev >= (1 << 26))
1398 { 1446 {
1399 RINOK(printCallback->CheckBreak());
1400 prev = bi.UnpackSize; 1447 prev = bi.UnpackSize;
1448 RINOK(printCallback->CheckBreak())
1401 } 1449 }
1402 1450
1403 /* 1451 /*
@@ -1411,21 +1459,25 @@ HRESULT CEncoderInfo::Encode()
1411 1459
1412 if (_encoderFilter) 1460 if (_encoderFilter)
1413 { 1461 {
1414 // if (needRealData) 1462 Byte *filterData = rgCopy;
1415 memcpy((Byte *)*outStreamSpec, uncompressedDataPtr, kBufferSize); 1463 if (i == numIterations - 1 || calcCrc || useRealData_Enc)
1464 {
1465 filterData = (Byte *)*outStreamSpec;
1466 if (data_Was_Changed)
1467 memcpy(filterData, uncompressedDataPtr, kBufferSize);
1468 data_Was_Changed = true;
1469 }
1416 _encoderFilter->Init(); 1470 _encoderFilter->Init();
1417 My_FilterBench(_encoderFilter, (Byte *)*outStreamSpec, kBufferSize);
1418 if (calcCrc) 1471 if (calcCrc)
1419 {
1420 outStreamSpec->InitCrc(); 1472 outStreamSpec->InitCrc();
1421 outStreamSpec->Calc((Byte *)*outStreamSpec, kBufferSize); 1473 My_FilterBench(_encoderFilter, filterData, kBufferSize,
1422 } 1474 calcCrc ? &outStreamSpec->Crc : NULL);
1423 } 1475 }
1424 else 1476 else
1425 { 1477 {
1426 outStreamSpec->Init(true, calcCrc); // write real data for speed consistency at any number of iterations 1478 outStreamSpec->Init(true, calcCrc); // write real data for speed consistency at any number of iterations
1427 inStreamSpec->Init(uncompressedDataPtr, kBufferSize); 1479 inStreamSpec->Init(uncompressedDataPtr, kBufferSize);
1428 RINOK(_encoder->Code(inStream, outStream, NULL, NULL, progressInfo[0])); 1480 RINOK(_encoder->Code(inStream, outStream, NULL, NULL, progressInfo[0]))
1429 if (!inStreamSpec->WasFinished()) 1481 if (!inStreamSpec->WasFinished())
1430 return E_FAIL; 1482 return E_FAIL;
1431 if (compressedSize != outStreamSpec->Pos) 1483 if (compressedSize != outStreamSpec->Pos)
@@ -1461,7 +1513,7 @@ HRESULT CEncoderInfo::Encode()
1461 info.PackSize = compressedSize; 1513 info.PackSize = compressedSize;
1462 // printf("\n%7d\n", encoder.compressedSize); 1514 // printf("\n%7d\n", encoder.compressedSize);
1463 1515
1464 RINOK(callback->SetEncodeResult(info, true)); 1516 RINOK(callback->SetEncodeResult(info, true))
1465 printCallback->NewLine(); 1517 printCallback->NewLine();
1466 } 1518 }
1467 */ 1519 */
@@ -1501,13 +1553,13 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1501 pi->BenchInfo.UnpackSize = 0; 1553 pi->BenchInfo.UnpackSize = 0;
1502 pi->BenchInfo.PackSize = 0; 1554 pi->BenchInfo.PackSize = 0;
1503 1555
1504 #ifndef _7ZIP_ST 1556 #ifndef Z7_ST
1505 { 1557 {
1506 CMyComPtr<ICompressSetCoderMt> setCoderMt; 1558 CMyComPtr<ICompressSetCoderMt> setCoderMt;
1507 coder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); 1559 coder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt);
1508 if (setCoderMt) 1560 if (setCoderMt)
1509 { 1561 {
1510 RINOK(setCoderMt->SetNumberOfThreads(NumDecoderSubThreads)); 1562 RINOK(setCoderMt->SetNumberOfThreads(NumDecoderSubThreads))
1511 } 1563 }
1512 } 1564 }
1513 #endif 1565 #endif
@@ -1517,7 +1569,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1517 if (scp) 1569 if (scp)
1518 { 1570 {
1519 const UInt64 reduceSize = _uncompressedDataSize; 1571 const UInt64 reduceSize = _uncompressedDataSize;
1520 RINOK(_method.SetCoderProps(scp, &reduceSize)); 1572 RINOK(_method.SetCoderProps(scp, &reduceSize))
1521 } 1573 }
1522 1574
1523 CMyComPtr<ICryptoProperties> cp; 1575 CMyComPtr<ICryptoProperties> cp;
@@ -1528,7 +1580,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1528 RINOK(setDecProps->SetDecoderProperties2( 1580 RINOK(setDecProps->SetDecoderProperties2(
1529 /* (const Byte *)*propStreamSpec, */ 1581 /* (const Byte *)*propStreamSpec, */
1530 propsData, 1582 propsData,
1531 (UInt32)propStreamSpec->GetPos())); 1583 (UInt32)propStreamSpec->GetPos()))
1532 } 1584 }
1533 1585
1534 { 1586 {
@@ -1536,7 +1588,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1536 coder.QueryInterface(IID_ICryptoSetPassword, &sp); 1588 coder.QueryInterface(IID_ICryptoSetPassword, &sp);
1537 if (sp) 1589 if (sp)
1538 { 1590 {
1539 RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw))); 1591 RINOK(sp->CryptoSetPassword(_psw, sizeof(_psw)))
1540 } 1592 }
1541 } 1593 }
1542 1594
@@ -1544,7 +1596,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1544 1596
1545 if (cp) 1597 if (cp)
1546 { 1598 {
1547 RINOK(Set_Key_and_IV(cp)); 1599 RINOK(Set_Key_and_IV(cp))
1548 } 1600 }
1549 1601
1550 CMyComPtr<ICompressSetFinishMode> setFinishMode; 1602 CMyComPtr<ICompressSetFinishMode> setFinishMode;
@@ -1559,32 +1611,38 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1559 decoder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode); 1611 decoder->QueryInterface(IID_ICompressSetFinishMode, (void **)&setFinishMode);
1560 } 1612 }
1561 1613
1562 const UInt64 numIterations = this->NumIterations; 1614 const UInt64 numIterations = NumIterations;
1563 const UInt32 mask = (CheckCrc_Dec ? 0 : 0xFFF); 1615 const E_CheckCrcMode checkCrcMode = CheckCrcMode_Dec;
1564 1616
1565 for (UInt64 i = 0; i < numIterations; i++) 1617 for (UInt64 i = 0; i < numIterations; i++)
1566 { 1618 {
1567 if (printCallback && pi->BenchInfo.UnpackSize - prev >= (1 << 24)) 1619 if (printCallback && pi->BenchInfo.UnpackSize - prev >= (1 << 26))
1568 { 1620 {
1569 RINOK(printCallback->CheckBreak()); 1621 RINOK(printCallback->CheckBreak())
1570 prev = pi->BenchInfo.UnpackSize; 1622 prev = pi->BenchInfo.UnpackSize;
1571 } 1623 }
1572 1624
1573 const UInt64 outSize = kBufferSize; 1625 const UInt64 outSize = kBufferSize;
1574 bool calcCrc = false; 1626 bool calcCrc = (checkCrcMode != k_CheckCrcMode_Never);
1575 if (((UInt32)i & mask) == 0) 1627
1576 calcCrc = true;
1577 crcOutStreamSpec->Init(); 1628 crcOutStreamSpec->Init();
1578 1629
1579 if (_decoderFilter) 1630 if (_decoderFilter)
1580 { 1631 {
1581 if (calcCrc) // for pure filter speed test without multi-iteration consistency 1632 Byte *filterData = (Byte *)*outStreamSpec;
1582 // if (needRealData)
1583 memcpy((Byte *)rgCopy, (const Byte *)*outStreamSpec, compressedSize);
1584 _decoderFilter->Init();
1585 My_FilterBench(_decoderFilter, (Byte *)rgCopy, compressedSize);
1586 if (calcCrc) 1633 if (calcCrc)
1587 crcOutStreamSpec->Calc((const Byte *)rgCopy, compressedSize); 1634 {
1635 calcCrc = (i == 0);
1636 if (checkCrcMode == k_CheckCrcMode_Always)
1637 {
1638 calcCrc = true;
1639 memcpy((Byte *)rgCopy, (const Byte *)*outStreamSpec, compressedSize);
1640 filterData = rgCopy;
1641 }
1642 }
1643 _decoderFilter->Init();
1644 My_FilterBench(_decoderFilter, filterData, compressedSize,
1645 calcCrc ? &crcOutStreamSpec->Crc : NULL);
1588 } 1646 }
1589 else 1647 else
1590 { 1648 {
@@ -1593,10 +1651,10 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1593 1651
1594 if (setFinishMode) 1652 if (setFinishMode)
1595 { 1653 {
1596 RINOK(setFinishMode->SetFinishMode(BoolToUInt(true))); 1654 RINOK(setFinishMode->SetFinishMode(BoolToUInt(true)))
1597 } 1655 }
1598 1656
1599 RINOK(decoder->Code(inStream, crcOutStream, 0, &outSize, progressInfo[decoderIndex])); 1657 RINOK(decoder->Code(inStream, crcOutStream, NULL, &outSize, progressInfo[decoderIndex]))
1600 1658
1601 if (setFinishMode) 1659 if (setFinishMode)
1602 { 1660 {
@@ -1609,7 +1667,7 @@ HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
1609 if (getInStreamProcessedSize) 1667 if (getInStreamProcessedSize)
1610 { 1668 {
1611 UInt64 processed; 1669 UInt64 processed;
1612 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed)); 1670 RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&processed))
1613 if (processed != compressedSize) 1671 if (processed != compressedSize)
1614 return S_FALSE; 1672 return S_FALSE;
1615 } 1673 }
@@ -1652,7 +1710,7 @@ static UInt64 GetNumIterations(UInt64 numCommands, UInt64 complexInCommands)
1652 1710
1653 1711
1654 1712
1655#ifndef _7ZIP_ST 1713#ifndef Z7_ST
1656 1714
1657// ---------- CBenchThreadsFlusher ---------- 1715// ---------- CBenchThreadsFlusher ----------
1658 1716
@@ -1696,7 +1754,7 @@ WRes CBenchThreadsFlusher::StartAndWait(bool exitMode)
1696 return res; 1754 return res;
1697} 1755}
1698 1756
1699#endif // _7ZIP_ST 1757#endif // Z7_ST
1700 1758
1701 1759
1702 1760
@@ -1714,7 +1772,7 @@ static void SetPseudoRand(Byte *data, size_t size, UInt32 startValue)
1714static HRESULT MethodBench( 1772static HRESULT MethodBench(
1715 DECL_EXTERNAL_CODECS_LOC_VARS 1773 DECL_EXTERNAL_CODECS_LOC_VARS
1716 UInt64 complexInCommands, 1774 UInt64 complexInCommands,
1717 #ifndef _7ZIP_ST 1775 #ifndef Z7_ST
1718 bool oldLzmaBenchMode, 1776 bool oldLzmaBenchMode,
1719 UInt32 numThreads, 1777 UInt32 numThreads,
1720 const CAffinityMode *affinityMode, 1778 const CAffinityMode *affinityMode,
@@ -1731,10 +1789,11 @@ static HRESULT MethodBench(
1731 COneMethodInfo method = method2; 1789 COneMethodInfo method = method2;
1732 UInt64 methodId; 1790 UInt64 methodId;
1733 UInt32 numStreams; 1791 UInt32 numStreams;
1792 bool isFilter;
1734 const int codecIndex = FindMethod_Index( 1793 const int codecIndex = FindMethod_Index(
1735 EXTERNAL_CODECS_LOC_VARS 1794 EXTERNAL_CODECS_LOC_VARS
1736 method.MethodName, true, 1795 method.MethodName, true,
1737 methodId, numStreams); 1796 methodId, numStreams, isFilter);
1738 if (codecIndex < 0) 1797 if (codecIndex < 0)
1739 return E_NOTIMPL; 1798 return E_NOTIMPL;
1740 if (numStreams != 1) 1799 if (numStreams != 1)
@@ -1743,7 +1802,7 @@ static HRESULT MethodBench(
1743 UInt32 numEncoderThreads = 1; 1802 UInt32 numEncoderThreads = 1;
1744 UInt32 numSubDecoderThreads = 1; 1803 UInt32 numSubDecoderThreads = 1;
1745 1804
1746 #ifndef _7ZIP_ST 1805 #ifndef Z7_ST
1747 numEncoderThreads = numThreads; 1806 numEncoderThreads = numThreads;
1748 1807
1749 if (oldLzmaBenchMode) 1808 if (oldLzmaBenchMode)
@@ -1759,7 +1818,7 @@ static HRESULT MethodBench(
1759 } 1818 }
1760 } 1819 }
1761 1820
1762 bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity(); 1821 const bool mtEncMode = (numEncoderThreads > 1) || affinityMode->NeedAffinity();
1763 1822
1764 #endif 1823 #endif
1765 1824
@@ -1771,10 +1830,10 @@ static HRESULT MethodBench(
1771 for (i = 0; i < numEncoderThreads; i++) 1830 for (i = 0; i < numEncoderThreads; i++)
1772 { 1831 {
1773 CEncoderInfo &encoder = encoders[i]; 1832 CEncoderInfo &encoder = encoders[i];
1774 encoder.callback = (i == 0) ? callback : 0; 1833 encoder.callback = (i == 0) ? callback : NULL;
1775 encoder.printCallback = printCallback; 1834 encoder.printCallback = printCallback;
1776 1835
1777 #ifndef _7ZIP_ST 1836 #ifndef Z7_ST
1778 encoder.EncoderIndex = i; 1837 encoder.EncoderIndex = i;
1779 encoder.NumEncoderInternalThreads = numSubDecoderThreads; 1838 encoder.NumEncoderInternalThreads = numSubDecoderThreads;
1780 encoder.AffinityMode = *affinityMode; 1839 encoder.AffinityMode = *affinityMode;
@@ -1794,15 +1853,12 @@ static HRESULT MethodBench(
1794 1853
1795 { 1854 {
1796 CCreatedCoder cod; 1855 CCreatedCoder cod;
1797 RINOK(CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)codecIndex, true, encoder._encoderFilter, cod)); 1856 RINOK(CreateCoder_Index(EXTERNAL_CODECS_LOC_VARS (unsigned)codecIndex, true, encoder._encoderFilter, cod))
1798 encoder._encoder = cod.Coder; 1857 encoder._encoder = cod.Coder;
1799 if (!encoder._encoder && !encoder._encoderFilter) 1858 if (!encoder._encoder && !encoder._encoderFilter)
1800 return E_NOTIMPL; 1859 return E_NOTIMPL;
1801 } 1860 }
1802 1861
1803 encoder.CheckCrc_Enc = (benchProps->EncComplex) > 30;
1804 encoder.CheckCrc_Dec = (benchProps->DecComplexCompr + benchProps->DecComplexUnc) > 30;
1805
1806 SetPseudoRand(encoder._iv, sizeof(encoder._iv), 17); 1862 SetPseudoRand(encoder._iv, sizeof(encoder._iv), 17);
1807 SetPseudoRand(encoder._key, sizeof(encoder._key), 51); 1863 SetPseudoRand(encoder._key, sizeof(encoder._key), 51);
1808 SetPseudoRand(encoder._psw, sizeof(encoder._psw), 123); 1864 SetPseudoRand(encoder._psw, sizeof(encoder._psw), 123);
@@ -1811,11 +1867,27 @@ static HRESULT MethodBench(
1811 { 1867 {
1812 CCreatedCoder cod; 1868 CCreatedCoder cod;
1813 CMyComPtr<ICompressCoder> &decoder = encoder._decoders[j]; 1869 CMyComPtr<ICompressCoder> &decoder = encoder._decoders[j];
1814 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodId, false, encoder._decoderFilter, cod)); 1870 RINOK(CreateCoder_Id(EXTERNAL_CODECS_LOC_VARS methodId, false, encoder._decoderFilter, cod))
1815 decoder = cod.Coder; 1871 decoder = cod.Coder;
1816 if (!encoder._decoderFilter && !decoder) 1872 if (!encoder._decoderFilter && !decoder)
1817 return E_NOTIMPL; 1873 return E_NOTIMPL;
1818 } 1874 }
1875
1876 encoder.UseRealData_Enc =
1877 encoder.CheckCrc_Enc = (benchProps->EncComplex) > 30;
1878
1879 encoder.CheckCrcMode_Dec = k_CheckCrcMode_Always;
1880 if (benchProps->DecComplexCompr +
1881 benchProps->DecComplexUnc <= 30)
1882 encoder.CheckCrcMode_Dec =
1883 k_CheckCrcMode_FirstPass; // for filters
1884 // k_CheckCrcMode_Never; // for debug
1885 // k_CheckCrcMode_Always; // for debug
1886 if (fileData)
1887 {
1888 encoder.UseRealData_Enc = true;
1889 encoder.CheckCrcMode_Dec = k_CheckCrcMode_Always;
1890 }
1819 } 1891 }
1820 1892
1821 UInt32 crc = 0; 1893 UInt32 crc = 0;
@@ -1837,7 +1909,7 @@ static HRESULT MethodBench(
1837 status.Res = S_OK; 1909 status.Res = S_OK;
1838 status.EncodeMode = true; 1910 status.EncodeMode = true;
1839 1911
1840 #ifndef _7ZIP_ST 1912 #ifndef Z7_ST
1841 CBenchThreadsFlusher encoderFlusher; 1913 CBenchThreadsFlusher encoderFlusher;
1842 if (mtEncMode) 1914 if (mtEncMode)
1843 { 1915 {
@@ -1853,7 +1925,7 @@ static HRESULT MethodBench(
1853 for (i = 0; i < numEncoderThreads; i++) 1925 for (i = 0; i < numEncoderThreads; i++)
1854 { 1926 {
1855 CEncoderInfo &encoder = encoders[i]; 1927 CEncoderInfo &encoder = encoders[i];
1856 encoder.NumIterations = GetNumIterations(benchProps->GeComprCommands(uncompressedDataSize), complexInCommands); 1928 encoder.NumIterations = GetNumIterations(benchProps->GetNumCommands_Enc(uncompressedDataSize), complexInCommands);
1857 // encoder.NumIterations = 3; 1929 // encoder.NumIterations = 3;
1858 encoder.Salt = g_CrcTable[i & 0xFF]; 1930 encoder.Salt = g_CrcTable[i & 0xFF];
1859 encoder.Salt ^= (g_CrcTable[(i >> 8) & 0xFF] << 3); 1931 encoder.Salt ^= (g_CrcTable[(i >> 8) & 0xFF] << 3);
@@ -1877,7 +1949,7 @@ static HRESULT MethodBench(
1877 bpi->BenchInfo.NumIterations = numEncoderThreads; 1949 bpi->BenchInfo.NumIterations = numEncoderThreads;
1878 } 1950 }
1879 1951
1880 #ifndef _7ZIP_ST 1952 #ifndef Z7_ST
1881 if (mtEncMode) 1953 if (mtEncMode)
1882 { 1954 {
1883 #ifdef USE_ALLOCA 1955 #ifdef USE_ALLOCA
@@ -1885,6 +1957,7 @@ static HRESULT MethodBench(
1885 #endif 1957 #endif
1886 1958
1887 encoder.Common = &encoderFlusher.Common; 1959 encoder.Common = &encoderFlusher.Common;
1960 encoder.IsGlobalMtMode = numEncoderThreads > 1;
1888 RINOK(encoder.CreateEncoderThread()) 1961 RINOK(encoder.CreateEncoderThread())
1889 } 1962 }
1890 #endif 1963 #endif
@@ -1892,35 +1965,35 @@ static HRESULT MethodBench(
1892 1965
1893 if (printCallback) 1966 if (printCallback)
1894 { 1967 {
1895 RINOK(printCallback->CheckBreak()); 1968 RINOK(printCallback->CheckBreak())
1896 } 1969 }
1897 1970
1898 #ifndef _7ZIP_ST 1971 #ifndef Z7_ST
1899 if (mtEncMode) 1972 if (mtEncMode)
1900 { 1973 {
1901 for (i = 0; i < numEncoderThreads; i++) 1974 for (i = 0; i < numEncoderThreads; i++)
1902 { 1975 {
1903 CEncoderInfo &encoder = encoders[i]; 1976 CEncoderInfo &encoder = encoders[i];
1904 WRes wres = encoder.ReadyEvent.Lock(); 1977 const WRes wres = encoder.ReadyEvent.Lock();
1905 if (wres != 0) 1978 if (wres != 0)
1906 return HRESULT_FROM_WIN32(wres); 1979 return HRESULT_FROM_WIN32(wres);
1907 RINOK(encoder.Results[0]); 1980 RINOK(encoder.Results[0])
1908 } 1981 }
1909 1982
1910 CBenchProgressInfo *bpi = encoders[0].progressInfoSpec[0]; 1983 CBenchProgressInfo *bpi = encoders[0].progressInfoSpec[0];
1911 bpi->SetStartTime(); 1984 bpi->SetStartTime();
1912 1985
1913 WRes wres = encoderFlusher.StartAndWait(); 1986 const WRes wres = encoderFlusher.StartAndWait();
1914 if (status.Res == 0 && wres != 0) 1987 if (status.Res == 0 && wres != 0)
1915 return HRESULT_FROM_WIN32(wres); 1988 return HRESULT_FROM_WIN32(wres);
1916 } 1989 }
1917 else 1990 else
1918 #endif 1991 #endif
1919 { 1992 {
1920 RINOK(encoders[0].Encode()); 1993 RINOK(encoders[0].Encode())
1921 } 1994 }
1922 1995
1923 RINOK(status.Res); 1996 RINOK(status.Res)
1924 1997
1925 CBenchInfo info; 1998 CBenchInfo info;
1926 1999
@@ -1931,13 +2004,13 @@ static HRESULT MethodBench(
1931 2004
1932 for (i = 0; i < numEncoderThreads; i++) 2005 for (i = 0; i < numEncoderThreads; i++)
1933 { 2006 {
1934 CEncoderInfo &encoder = encoders[i]; 2007 const CEncoderInfo &encoder = encoders[i];
1935 info.UnpackSize += encoder.kBufferSize; 2008 info.UnpackSize += encoder.kBufferSize;
1936 info.PackSize += encoder.compressedSize; 2009 info.PackSize += encoder.compressedSize;
1937 // printf("\n%7d\n", encoder.compressedSize); 2010 // printf("\n%7d\n", encoder.compressedSize);
1938 } 2011 }
1939 2012
1940 RINOK(callback->SetEncodeResult(info, true)); 2013 RINOK(callback->SetEncodeResult(info, true))
1941 2014
1942 2015
1943 2016
@@ -1948,7 +2021,7 @@ static HRESULT MethodBench(
1948 status.EncodeMode = false; 2021 status.EncodeMode = false;
1949 2022
1950 const UInt32 numDecoderThreads = numEncoderThreads * numSubDecoderThreads; 2023 const UInt32 numDecoderThreads = numEncoderThreads * numSubDecoderThreads;
1951 #ifndef _7ZIP_ST 2024 #ifndef Z7_ST
1952 const bool mtDecoderMode = (numDecoderThreads > 1) || affinityMode->NeedAffinity(); 2025 const bool mtDecoderMode = (numDecoderThreads > 1) || affinityMode->NeedAffinity();
1953 #endif 2026 #endif
1954 2027
@@ -1957,7 +2030,7 @@ static HRESULT MethodBench(
1957 CEncoderInfo &encoder = encoders[i]; 2030 CEncoderInfo &encoder = encoders[i];
1958 2031
1959 /* 2032 /*
1960 #ifndef _7ZIP_ST 2033 #ifndef Z7_ST
1961 // encoder.affinityMode = *affinityMode; 2034 // encoder.affinityMode = *affinityMode;
1962 if (encoder.NumEncoderInternalThreads != 1) 2035 if (encoder.NumEncoderInternalThreads != 1)
1963 encoder.AffinityMode.DivideNum = encoder.NumEncoderInternalThreads; 2036 encoder.AffinityMode.DivideNum = encoder.NumEncoderInternalThreads;
@@ -1967,7 +2040,11 @@ static HRESULT MethodBench(
1967 2040
1968 if (i == 0) 2041 if (i == 0)
1969 { 2042 {
1970 encoder.NumIterations = GetNumIterations(benchProps->GeDecomprCommands(encoder.compressedSize, encoder.kBufferSize), complexInCommands); 2043 encoder.NumIterations = GetNumIterations(
2044 benchProps->GetNumCommands_Dec(
2045 encoder.compressedSize,
2046 encoder.kBufferSize),
2047 complexInCommands);
1971 CBenchProgressInfo *bpi = encoder.progressInfoSpec[0]; 2048 CBenchProgressInfo *bpi = encoder.progressInfoSpec[0];
1972 bpi->Callback = callback; 2049 bpi->Callback = callback;
1973 bpi->BenchInfo.NumIterations = numDecoderThreads; 2050 bpi->BenchInfo.NumIterations = numDecoderThreads;
@@ -1976,7 +2053,7 @@ static HRESULT MethodBench(
1976 else 2053 else
1977 encoder.NumIterations = encoders[0].NumIterations; 2054 encoder.NumIterations = encoders[0].NumIterations;
1978 2055
1979 #ifndef _7ZIP_ST 2056 #ifndef Z7_ST
1980 { 2057 {
1981 int numSubThreads = method.Get_NumThreads(); 2058 int numSubThreads = method.Get_NumThreads();
1982 encoder.NumDecoderSubThreads = (numSubThreads <= 0) ? 1 : (unsigned)numSubThreads; 2059 encoder.NumDecoderSubThreads = (numSubThreads <= 0) ? 1 : (unsigned)numSubThreads;
@@ -1985,22 +2062,22 @@ static HRESULT MethodBench(
1985 { 2062 {
1986 for (UInt32 j = 0; j < numSubDecoderThreads; j++) 2063 for (UInt32 j = 0; j < numSubDecoderThreads; j++)
1987 { 2064 {
1988 HRESULT res = encoder.CreateDecoderThread(j, (i == 0 && j == 0) 2065 const HRESULT res = encoder.CreateDecoderThread(j, (i == 0 && j == 0)
1989 #ifdef USE_ALLOCA 2066 #ifdef USE_ALLOCA
1990 , ((i * numSubDecoderThreads + j) * 16 * 21) & 0x7FF 2067 , ((i * numSubDecoderThreads + j) * 16 * 21) & 0x7FF
1991 #endif 2068 #endif
1992 ); 2069 );
1993 RINOK(res); 2070 RINOK(res)
1994 } 2071 }
1995 } 2072 }
1996 else 2073 else
1997 #endif 2074 #endif
1998 { 2075 {
1999 RINOK(encoder.Decode(0)); 2076 RINOK(encoder.Decode(0))
2000 } 2077 }
2001 } 2078 }
2002 2079
2003 #ifndef _7ZIP_ST 2080 #ifndef Z7_ST
2004 if (mtDecoderMode) 2081 if (mtDecoderMode)
2005 { 2082 {
2006 WRes wres = 0; 2083 WRes wres = 0;
@@ -2009,26 +2086,26 @@ static HRESULT MethodBench(
2009 for (UInt32 j = 0; j < numSubDecoderThreads; j++) 2086 for (UInt32 j = 0; j < numSubDecoderThreads; j++)
2010 { 2087 {
2011 CEncoderInfo &encoder = encoders[i]; 2088 CEncoderInfo &encoder = encoders[i];
2012 WRes wres2 = encoder.thread[j]. 2089 const WRes wres2 = encoder.thread[j].
2013 // Wait(); // later we can get thread times from thread in UNDER_CE 2090 // Wait(); // later we can get thread times from thread in UNDER_CE
2014 Wait_Close(); 2091 Wait_Close();
2015 if (wres == 0 && wres2 != 0) 2092 if (wres == 0 && wres2 != 0)
2016 wres = wres2; 2093 wres = wres2;
2017 HRESULT res2 = encoder.Results[j]; 2094 const HRESULT res2 = encoder.Results[j];
2018 if (res == 0 && res2 != 0) 2095 if (res == 0 && res2 != 0)
2019 res = res2; 2096 res = res2;
2020 } 2097 }
2021 if (wres != 0) 2098 if (wres != 0)
2022 return HRESULT_FROM_WIN32(wres); 2099 return HRESULT_FROM_WIN32(wres);
2023 RINOK(res); 2100 RINOK(res)
2024 } 2101 }
2025 #endif // _7ZIP_ST 2102 #endif // Z7_ST
2026 2103
2027 RINOK(status.Res); 2104 RINOK(status.Res)
2028 encoders[0].progressInfoSpec[0]->SetFinishTime(info); 2105 encoders[0].progressInfoSpec[0]->SetFinishTime(info);
2029 2106
2030 /* 2107 /*
2031 #ifndef _7ZIP_ST 2108 #ifndef Z7_ST
2032 #ifdef UNDER_CE 2109 #ifdef UNDER_CE
2033 if (mtDecoderMode) 2110 if (mtDecoderMode)
2034 for (i = 0; i < numEncoderThreads; i++) 2111 for (i = 0; i < numEncoderThreads; i++)
@@ -2048,13 +2125,13 @@ static HRESULT MethodBench(
2048 2125
2049 for (i = 0; i < numEncoderThreads; i++) 2126 for (i = 0; i < numEncoderThreads; i++)
2050 { 2127 {
2051 CEncoderInfo &encoder = encoders[i]; 2128 const CEncoderInfo &encoder = encoders[i];
2052 info.UnpackSize += encoder.kBufferSize; 2129 info.UnpackSize += encoder.kBufferSize;
2053 info.PackSize += encoder.compressedSize; 2130 info.PackSize += encoder.compressedSize;
2054 } 2131 }
2055 2132
2056 // RINOK(callback->SetDecodeResult(info, false)); // why we called before 21.03 ?? 2133 // RINOK(callback->SetDecodeResult(info, false)) // why we called before 21.03 ??
2057 RINOK(callback->SetDecodeResult(info, true)); 2134 RINOK(callback->SetDecodeResult(info, true))
2058 2135
2059 return S_OK; 2136 return S_OK;
2060} 2137}
@@ -2234,7 +2311,7 @@ HRESULT CCrcInfo_Base::CrcProcess(UInt64 numIterations,
2234 if (cur - prev >= ((UInt32)1 << 30)) 2311 if (cur - prev >= ((UInt32)1 << 30))
2235 { 2312 {
2236 prev = cur; 2313 prev = cur;
2237 RINOK(callback->CheckBreak()); 2314 RINOK(callback->CheckBreak())
2238 } 2315 }
2239 } 2316 }
2240 } 2317 }
@@ -2266,7 +2343,7 @@ static UInt32 CountCpuFreq(UInt32 sum, UInt32 num, UInt32 val)
2266EXTERN_C_END 2343EXTERN_C_END
2267 2344
2268 2345
2269#ifndef _7ZIP_ST 2346#ifndef Z7_ST
2270 2347
2271struct CBaseThreadInfo 2348struct CBaseThreadInfo
2272{ 2349{
@@ -2300,12 +2377,12 @@ static THREAD_FUNC_DECL FreqThreadFunction(void *param)
2300 { 2377 {
2301 p->CallbackRes = p->Callback->CheckBreak(); 2378 p->CallbackRes = p->Callback->CheckBreak();
2302 if (p->CallbackRes != S_OK) 2379 if (p->CallbackRes != S_OK)
2303 return 0; 2380 break;
2304 } 2381 }
2305 sum = CountCpuFreq(sum, p->Size, g_BenchCpuFreqTemp); 2382 sum = CountCpuFreq(sum, p->Size, g_BenchCpuFreqTemp);
2306 } 2383 }
2307 p->ValRes = sum; 2384 p->ValRes = sum;
2308 return 0; 2385 return THREAD_FUNC_RET_ZERO;
2309} 2386}
2310 2387
2311struct CFreqThreads 2388struct CFreqThreads
@@ -2349,7 +2426,7 @@ struct CCrcInfo: public CBaseThreadInfo
2349 HRESULT Res; 2426 HRESULT Res;
2350 UInt32 CheckSum_Res; 2427 UInt32 CheckSum_Res;
2351 2428
2352 #ifndef _7ZIP_ST 2429 #ifndef Z7_ST
2353 NSynchronization::CManualResetEvent ReadyEvent; 2430 NSynchronization::CManualResetEvent ReadyEvent;
2354 UInt32 ThreadIndex; 2431 UInt32 ThreadIndex;
2355 CBenchSyncCommon *Common; 2432 CBenchSyncCommon *Common;
@@ -2433,7 +2510,7 @@ static THREAD_FUNC_DECL CrcThreadFunction(void *param)
2433 alloca(p->AllocaSize); 2510 alloca(p->AllocaSize);
2434 #endif 2511 #endif
2435 p->Process(); 2512 p->Process();
2436 return 0; 2513 return THREAD_FUNC_RET_ZERO;
2437} 2514}
2438 2515
2439 2516
@@ -2480,7 +2557,7 @@ WRes CCrcThreads::StartAndWait(bool exitMode)
2480 2557
2481static UInt32 CrcCalc1(const Byte *buf, size_t size) 2558static UInt32 CrcCalc1(const Byte *buf, size_t size)
2482{ 2559{
2483 UInt32 crc = CRC_INIT_VAL;; 2560 UInt32 crc = CRC_INIT_VAL;
2484 for (size_t i = 0; i < size; i++) 2561 for (size_t i = 0; i < size; i++)
2485 crc = CRC_UPDATE_BYTE(crc, buf[i]); 2562 crc = CRC_UPDATE_BYTE(crc, buf[i]);
2486 return CRC_GET_DIGEST(crc); 2563 return CRC_GET_DIGEST(crc);
@@ -2522,9 +2599,9 @@ struct CBenchMethod
2522{ 2599{
2523 unsigned Weight; 2600 unsigned Weight;
2524 unsigned DictBits; 2601 unsigned DictBits;
2525 UInt32 EncComplex; 2602 Int32 EncComplex;
2526 UInt32 DecComplexCompr; 2603 Int32 DecComplexCompr;
2527 UInt32 DecComplexUnc; 2604 Int32 DecComplexUnc;
2528 const char *Name; 2605 const char *Name;
2529 // unsigned KeySize; 2606 // unsigned KeySize;
2530}; 2607};
@@ -2563,6 +2640,9 @@ static const CBenchMethod g_Bench[] =
2563 // { 10, 22, 1655, 0, 1830, "PPMDZip:x5" }, 2640 // { 10, 22, 1655, 0, 1830, "PPMDZip:x5" },
2564 { 10, 22, 1655, 0, 1830, "PPMD:x5" }, 2641 { 10, 22, 1655, 0, 1830, "PPMD:x5" },
2565 2642
2643 // { 2, 0, -16, 0, -16, "Swap2" },
2644 { 2, 0, -16, 0, -16, "Swap4" },
2645
2566 // { 2, 0, 3, 0, 4, "Delta:1" }, 2646 // { 2, 0, 3, 0, 4, "Delta:1" },
2567 // { 2, 0, 3, 0, 4, "Delta:2" }, 2647 // { 2, 0, 3, 0, 4, "Delta:2" },
2568 // { 2, 0, 3, 0, 4, "Delta:3" }, 2648 // { 2, 0, 3, 0, 4, "Delta:3" },
@@ -2570,8 +2650,9 @@ static const CBenchMethod g_Bench[] =
2570 // { 2, 0, 3, 0, 4, "Delta:8" }, 2650 // { 2, 0, 3, 0, 4, "Delta:8" },
2571 // { 2, 0, 3, 0, 4, "Delta:32" }, 2651 // { 2, 0, 3, 0, 4, "Delta:32" },
2572 2652
2573 { 2, 0, 4, 0, 4, "BCJ" }, 2653 { 2, 0, 2, 0, 2, "BCJ" },
2574 2654 { 2, 0, 1, 0, 1, "ARM64" },
2655
2575 // { 10, 0, 18, 0, 18, "AES128CBC:1" }, 2656 // { 10, 0, 18, 0, 18, "AES128CBC:1" },
2576 // { 10, 0, 21, 0, 21, "AES192CBC:1" }, 2657 // { 10, 0, 21, 0, 21, "AES192CBC:1" },
2577 { 10, 0, 24, 0, 24, "AES256CBC:1" }, 2658 { 10, 0, 24, 0, 24, "AES256CBC:1" },
@@ -2607,11 +2688,13 @@ struct CBenchHash
2607// #define ARM_CRC_MUL 100 2688// #define ARM_CRC_MUL 100
2608#define ARM_CRC_MUL 1 2689#define ARM_CRC_MUL 1
2609 2690
2691#define k_Hash_Complex_Mult 256
2692
2610static const CBenchHash g_Hash[] = 2693static const CBenchHash g_Hash[] =
2611{ 2694{
2612 { 1, 1820, 0x21e207bb, "CRC32:1" }, 2695 // { 1, 1820, 0x21e207bb, "CRC32:1" },
2613 { 10, 558, 0x21e207bb, "CRC32:4" }, 2696 // { 10, 558, 0x21e207bb, "CRC32:4" },
2614 { 10, 339, 0x21e207bb, "CRC32:8" } , 2697 { 20, 339, 0x21e207bb, "CRC32:8" } ,
2615 { 2, 128 *ARM_CRC_MUL, 0x21e207bb, "CRC32:32" }, 2698 { 2, 128 *ARM_CRC_MUL, 0x21e207bb, "CRC32:32" },
2616 { 2, 64 *ARM_CRC_MUL, 0x21e207bb, "CRC32:64" }, 2699 { 2, 64 *ARM_CRC_MUL, 0x21e207bb, "CRC32:64" },
2617 { 10, 512, 0x41b901d1, "CRC64" }, 2700 { 10, 512, 0x41b901d1, "CRC64" },
@@ -2656,6 +2739,8 @@ static const unsigned kFieldSize_RU = 6;
2656static const unsigned kFieldSize_Rating = 6; 2739static const unsigned kFieldSize_Rating = 6;
2657static const unsigned kFieldSize_EU = 5; 2740static const unsigned kFieldSize_EU = 5;
2658static const unsigned kFieldSize_Effec = 5; 2741static const unsigned kFieldSize_Effec = 5;
2742static const unsigned kFieldSize_CrcSpeed = 8;
2743
2659 2744
2660static const unsigned kFieldSize_TotalSize = 4 + kFieldSize_Speed + kFieldSize_Usage + kFieldSize_RU + kFieldSize_Rating; 2745static const unsigned kFieldSize_TotalSize = 4 + kFieldSize_Speed + kFieldSize_Usage + kFieldSize_RU + kFieldSize_Rating;
2661static const unsigned kFieldSize_EUAndEffec = 2 + kFieldSize_EU + kFieldSize_Effec; 2746static const unsigned kFieldSize_EUAndEffec = 2 + kFieldSize_EU + kFieldSize_Effec;
@@ -2830,7 +2915,7 @@ AString GetProcessThreadsInfo(const NSystem::CProcessAffinity &ti)
2830} 2915}
2831 2916
2832 2917
2833#ifdef _7ZIP_LARGE_PAGES 2918#ifdef Z7_LARGE_PAGES
2834 2919
2835#ifdef _WIN32 2920#ifdef _WIN32
2836extern bool g_LargePagesMode; 2921extern bool g_LargePagesMode;
@@ -2875,7 +2960,7 @@ static void PrintRequirements(IBenchPrintCallback &f, const char *sizeString,
2875 f.Print(" ?"); 2960 f.Print(" ?");
2876 f.Print(" MB"); 2961 f.Print(" MB");
2877 2962
2878 #ifdef _7ZIP_LARGE_PAGES 2963 #ifdef Z7_LARGE_PAGES
2879 { 2964 {
2880 AString s; 2965 AString s;
2881 Add_LargePages_String(s); 2966 Add_LargePages_String(s);
@@ -2890,30 +2975,34 @@ static void PrintRequirements(IBenchPrintCallback &f, const char *sizeString,
2890 2975
2891 2976
2892 2977
2893struct CBenchCallbackToPrint: public IBenchCallback 2978struct CBenchCallbackToPrint Z7_final: public IBenchCallback
2894{ 2979{
2895 CBenchProps BenchProps; 2980 bool NeedPrint;
2896 CTotalBenchRes EncodeRes;
2897 CTotalBenchRes DecodeRes;
2898 IBenchPrintCallback *_file;
2899 UInt64 DictSize;
2900
2901 bool Use2Columns; 2981 bool Use2Columns;
2902 unsigned NameFieldSize;
2903
2904 bool ShowFreq; 2982 bool ShowFreq;
2905 UInt64 CpuFreq; 2983 unsigned NameFieldSize;
2906 2984
2907 unsigned EncodeWeight; 2985 unsigned EncodeWeight;
2908 unsigned DecodeWeight; 2986 unsigned DecodeWeight;
2909 2987
2988 UInt64 CpuFreq;
2989 UInt64 DictSize;
2990
2991 IBenchPrintCallback *_file;
2992 CBenchProps BenchProps;
2993 CTotalBenchRes EncodeRes;
2994 CTotalBenchRes DecodeRes;
2995
2996 CBenchInfo BenchInfo_Results[2];
2997
2910 CBenchCallbackToPrint(): 2998 CBenchCallbackToPrint():
2999 NeedPrint(true),
2911 Use2Columns(false), 3000 Use2Columns(false),
2912 NameFieldSize(0),
2913 ShowFreq(false), 3001 ShowFreq(false),
2914 CpuFreq(0), 3002 NameFieldSize(0),
2915 EncodeWeight(1), 3003 EncodeWeight(1),
2916 DecodeWeight(1) 3004 DecodeWeight(1),
3005 CpuFreq(0)
2917 {} 3006 {}
2918 3007
2919 void Init() { EncodeRes.Init(); DecodeRes.Init(); } 3008 void Init() { EncodeRes.Init(); DecodeRes.Init(); }
@@ -2921,8 +3010,8 @@ struct CBenchCallbackToPrint: public IBenchCallback
2921 void NewLine(); 3010 void NewLine();
2922 3011
2923 HRESULT SetFreq(bool showFreq, UInt64 cpuFreq); 3012 HRESULT SetFreq(bool showFreq, UInt64 cpuFreq);
2924 HRESULT SetEncodeResult(const CBenchInfo &info, bool final); 3013 HRESULT SetEncodeResult(const CBenchInfo &info, bool final) Z7_override;
2925 HRESULT SetDecodeResult(const CBenchInfo &info, bool final); 3014 HRESULT SetDecodeResult(const CBenchInfo &info, bool final) Z7_override;
2926}; 3015};
2927 3016
2928HRESULT CBenchCallbackToPrint::SetFreq(bool showFreq, UInt64 cpuFreq) 3017HRESULT CBenchCallbackToPrint::SetFreq(bool showFreq, UInt64 cpuFreq)
@@ -2934,10 +3023,13 @@ HRESULT CBenchCallbackToPrint::SetFreq(bool showFreq, UInt64 cpuFreq)
2934 3023
2935HRESULT CBenchCallbackToPrint::SetEncodeResult(const CBenchInfo &info, bool final) 3024HRESULT CBenchCallbackToPrint::SetEncodeResult(const CBenchInfo &info, bool final)
2936{ 3025{
2937 RINOK(_file->CheckBreak()); 3026 RINOK(_file->CheckBreak())
2938 if (final) 3027 if (final)
3028 BenchInfo_Results[0] = info;
3029 if (final)
3030 if (NeedPrint)
2939 { 3031 {
2940 UInt64 rating = BenchProps.GetCompressRating(DictSize, info.GlobalTime, info.GlobalFreq, info.UnpackSize * info.NumIterations); 3032 const UInt64 rating = BenchProps.GetRating_Enc(DictSize, info.GlobalTime, info.GlobalFreq, info.UnpackSize * info.NumIterations);
2941 PrintResults(_file, info, 3033 PrintResults(_file, info,
2942 EncodeWeight, rating, 3034 EncodeWeight, rating,
2943 ShowFreq, CpuFreq, &EncodeRes); 3035 ShowFreq, CpuFreq, &EncodeRes);
@@ -2951,10 +3043,13 @@ static const char * const kSep = " | ";
2951 3043
2952HRESULT CBenchCallbackToPrint::SetDecodeResult(const CBenchInfo &info, bool final) 3044HRESULT CBenchCallbackToPrint::SetDecodeResult(const CBenchInfo &info, bool final)
2953{ 3045{
2954 RINOK(_file->CheckBreak()); 3046 RINOK(_file->CheckBreak())
3047 if (final)
3048 BenchInfo_Results[1] = info;
2955 if (final) 3049 if (final)
3050 if (NeedPrint)
2956 { 3051 {
2957 UInt64 rating = BenchProps.GetDecompressRating(info.GlobalTime, info.GlobalFreq, info.UnpackSize, info.PackSize, info.NumIterations); 3052 const UInt64 rating = BenchProps.GetRating_Dec(info.GlobalTime, info.GlobalFreq, info.UnpackSize, info.PackSize, info.NumIterations);
2958 if (Use2Columns) 3053 if (Use2Columns)
2959 _file->Print(kSep); 3054 _file->Print(kSep);
2960 else 3055 else
@@ -2996,10 +3091,22 @@ static void PrintRight(IBenchPrintCallback &f, const char *s, unsigned size)
2996 f.Print(s); 3091 f.Print(s);
2997} 3092}
2998 3093
3094
3095static bool DoesWildcardMatchName_NoCase(const AString &mask, const char *name)
3096{
3097 UString wildc = GetUnicodeString(mask);
3098 UString bname = GetUnicodeString(name);
3099 wildc.MakeLower_Ascii();
3100 bname.MakeLower_Ascii();
3101 return DoesWildcardMatchName(wildc, bname);
3102}
3103
3104
2999static HRESULT TotalBench( 3105static HRESULT TotalBench(
3000 DECL_EXTERNAL_CODECS_LOC_VARS 3106 DECL_EXTERNAL_CODECS_LOC_VARS
3107 const COneMethodInfo &methodMask,
3001 UInt64 complexInCommands, 3108 UInt64 complexInCommands,
3002 #ifndef _7ZIP_ST 3109 #ifndef Z7_ST
3003 UInt32 numThreads, 3110 UInt32 numThreads,
3004 const CAffinityMode *affinityMode, 3111 const CAffinityMode *affinityMode,
3005 #endif 3112 #endif
@@ -3008,9 +3115,11 @@ static HRESULT TotalBench(
3008 const Byte *fileData, 3115 const Byte *fileData,
3009 IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback) 3116 IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback)
3010{ 3117{
3011 for (unsigned i = 0; i < ARRAY_SIZE(g_Bench); i++) 3118 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++)
3012 { 3119 {
3013 const CBenchMethod &bench = g_Bench[i]; 3120 const CBenchMethod &bench = g_Bench[i];
3121 if (!DoesWildcardMatchName_NoCase(methodMask.MethodName, bench.Name))
3122 continue;
3014 PrintLeft(*callback->_file, bench.Name, kFieldSize_Name); 3123 PrintLeft(*callback->_file, bench.Name, kFieldSize_Name);
3015 { 3124 {
3016 unsigned keySize = 32; 3125 unsigned keySize = 32;
@@ -3025,7 +3134,7 @@ static HRESULT TotalBench(
3025 COneMethodInfo method; 3134 COneMethodInfo method;
3026 NCOM::CPropVariant propVariant; 3135 NCOM::CPropVariant propVariant;
3027 propVariant = bench.Name; 3136 propVariant = bench.Name;
3028 RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)); 3137 RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant))
3029 3138
3030 size_t unpackSize2 = unpackSize; 3139 size_t unpackSize2 = unpackSize;
3031 if (!forceUnpackSize && bench.DictBits == 0) 3140 if (!forceUnpackSize && bench.DictBits == 0)
@@ -3034,10 +3143,10 @@ static HRESULT TotalBench(
3034 callback->EncodeWeight = bench.Weight; 3143 callback->EncodeWeight = bench.Weight;
3035 callback->DecodeWeight = bench.Weight; 3144 callback->DecodeWeight = bench.Weight;
3036 3145
3037 HRESULT res = MethodBench( 3146 const HRESULT res = MethodBench(
3038 EXTERNAL_CODECS_LOC_VARS 3147 EXTERNAL_CODECS_LOC_VARS
3039 complexInCommands, 3148 complexInCommands,
3040 #ifndef _7ZIP_ST 3149 #ifndef Z7_ST
3041 false, numThreads, affinityMode, 3150 false, numThreads, affinityMode,
3042 #endif 3151 #endif
3043 method, 3152 method,
@@ -3054,7 +3163,7 @@ static HRESULT TotalBench(
3054 } 3163 }
3055 else 3164 else
3056 { 3165 {
3057 RINOK(res); 3166 RINOK(res)
3058 } 3167 }
3059 3168
3060 callback->NewLine(); 3169 callback->NewLine();
@@ -3080,7 +3189,7 @@ struct CFreqBench
3080 {} 3189 {}
3081 3190
3082 HRESULT FreqBench(IBenchPrintCallback *_file 3191 HRESULT FreqBench(IBenchPrintCallback *_file
3083 #ifndef _7ZIP_ST 3192 #ifndef Z7_ST
3084 , const CAffinityMode *affinityMode 3193 , const CAffinityMode *affinityMode
3085 #endif 3194 #endif
3086 ); 3195 );
@@ -3088,7 +3197,7 @@ struct CFreqBench
3088 3197
3089 3198
3090HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file 3199HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3091 #ifndef _7ZIP_ST 3200 #ifndef Z7_ST
3092 , const CAffinityMode *affinityMode 3201 , const CAffinityMode *affinityMode
3093 #endif 3202 #endif
3094 ) 3203 )
@@ -3100,7 +3209,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3100 if (numThreads == 0) 3209 if (numThreads == 0)
3101 numThreads = 1; 3210 numThreads = 1;
3102 3211
3103 #ifdef _7ZIP_ST 3212 #ifdef Z7_ST
3104 numThreads = 1; 3213 numThreads = 1;
3105 #endif 3214 #endif
3106 3215
@@ -3117,7 +3226,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3117 3226
3118 CBenchInfoCalc progressInfoSpec; 3227 CBenchInfoCalc progressInfoSpec;
3119 3228
3120 #ifndef _7ZIP_ST 3229 #ifndef Z7_ST
3121 3230
3122 bool mtMode = (numThreads > 1) || affinityMode->NeedAffinity(); 3231 bool mtMode = (numThreads > 1) || affinityMode->NeedAffinity();
3123 3232
@@ -3150,7 +3259,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3150 return HRESULT_FROM_WIN32(wres); 3259 return HRESULT_FROM_WIN32(wres);
3151 for (i = 0; i < numThreads; i++) 3260 for (i = 0; i < numThreads; i++)
3152 { 3261 {
3153 RINOK(threads.Items[i].CallbackRes); 3262 RINOK(threads.Items[i].CallbackRes)
3154 } 3263 }
3155 } 3264 }
3156 else 3265 else
@@ -3163,7 +3272,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3163 sum = CountCpuFreq(sum, numIterations2, g_BenchCpuFreqTemp); 3272 sum = CountCpuFreq(sum, numIterations2, g_BenchCpuFreqTemp);
3164 if (_file) 3273 if (_file)
3165 { 3274 {
3166 RINOK(_file->CheckBreak()); 3275 RINOK(_file->CheckBreak())
3167 } 3276 }
3168 } 3277 }
3169 res += sum; 3278 res += sum;
@@ -3172,7 +3281,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3172 if (res == 0x12345678) 3281 if (res == 0x12345678)
3173 if (_file) 3282 if (_file)
3174 { 3283 {
3175 RINOK(_file->CheckBreak()); 3284 RINOK(_file->CheckBreak())
3176 } 3285 }
3177 3286
3178 CBenchInfo info; 3287 CBenchInfo info;
@@ -3193,7 +3302,7 @@ HRESULT CFreqBench::FreqBench(IBenchPrintCallback *_file
3193 0, // weight 3302 0, // weight
3194 rating, 3303 rating,
3195 showFreq, showFreq ? (specifiedFreq != 0 ? specifiedFreq : CpuFreqRes) : 0, NULL); 3304 showFreq, showFreq ? (specifiedFreq != 0 ? specifiedFreq : CpuFreqRes) : 0, NULL);
3196 RINOK(_file->CheckBreak()); 3305 RINOK(_file->CheckBreak())
3197 } 3306 }
3198 3307
3199 return S_OK; 3308 return S_OK;
@@ -3215,7 +3324,7 @@ static HRESULT CrcBench(
3215 const UInt32 *checkSum, 3324 const UInt32 *checkSum,
3216 const COneMethodInfo &method, 3325 const COneMethodInfo &method,
3217 IBenchPrintCallback *_file, 3326 IBenchPrintCallback *_file,
3218 #ifndef _7ZIP_ST 3327 #ifndef Z7_ST
3219 const CAffinityMode *affinityMode, 3328 const CAffinityMode *affinityMode,
3220 #endif 3329 #endif
3221 bool showRating, 3330 bool showRating,
@@ -3225,7 +3334,7 @@ static HRESULT CrcBench(
3225 if (numThreads == 0) 3334 if (numThreads == 0)
3226 numThreads = 1; 3335 numThreads = 1;
3227 3336
3228 #ifdef _7ZIP_ST 3337 #ifdef Z7_ST
3229 numThreads = 1; 3338 numThreads = 1;
3230 #endif 3339 #endif
3231 3340
@@ -3249,14 +3358,14 @@ static HRESULT CrcBench(
3249 */ 3358 */
3250 3359
3251 const size_t bsize = (bufferSize == 0 ? 1 : bufferSize); 3360 const size_t bsize = (bufferSize == 0 ? 1 : bufferSize);
3252 UInt64 numIterations = complexInCommands * 256 / complexity / bsize; 3361 UInt64 numIterations = complexInCommands * k_Hash_Complex_Mult / complexity / bsize;
3253 if (numIterations == 0) 3362 if (numIterations == 0)
3254 numIterations = 1; 3363 numIterations = 1;
3255 3364
3256 CBenchInfoCalc progressInfoSpec; 3365 CBenchInfoCalc progressInfoSpec;
3257 CBenchInfo info; 3366 CBenchInfo info;
3258 3367
3259 #ifndef _7ZIP_ST 3368 #ifndef Z7_ST
3260 bool mtEncMode = (numThreads > 1) || affinityMode->NeedAffinity(); 3369 bool mtEncMode = (numThreads > 1) || affinityMode->NeedAffinity();
3261 3370
3262 if (mtEncMode) 3371 if (mtEncMode)
@@ -3275,14 +3384,14 @@ static HRESULT CrcBench(
3275 { 3384 {
3276 CCrcInfo &ci = threads.Items[i]; 3385 CCrcInfo &ci = threads.Items[i];
3277 AString name; 3386 AString name;
3278 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, ci.Hasher)); 3387 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, ci.Hasher))
3279 if (!ci.Hasher) 3388 if (!ci.Hasher)
3280 return E_NOTIMPL; 3389 return E_NOTIMPL;
3281 CMyComPtr<ICompressSetCoderProperties> scp; 3390 CMyComPtr<ICompressSetCoderProperties> scp;
3282 ci.Hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); 3391 ci.Hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp);
3283 if (scp) 3392 if (scp)
3284 { 3393 {
3285 RINOK(method.SetCoderProps(scp)); 3394 RINOK(method.SetCoderProps(scp))
3286 } 3395 }
3287 3396
3288 ci.Callback = _file; 3397 ci.Callback = _file;
@@ -3320,7 +3429,7 @@ static HRESULT CrcBench(
3320 WRes wres = ci.ReadyEvent.Lock(); 3429 WRes wres = ci.ReadyEvent.Lock();
3321 if (wres != 0) 3430 if (wres != 0)
3322 return HRESULT_FROM_WIN32(wres); 3431 return HRESULT_FROM_WIN32(wres);
3323 RINOK(ci.Res); 3432 RINOK(ci.Res)
3324 } 3433 }
3325 3434
3326 progressInfoSpec.SetStartTime(); 3435 progressInfoSpec.SetStartTime();
@@ -3333,7 +3442,7 @@ static HRESULT CrcBench(
3333 3442
3334 for (i = 0; i < numThreads; i++) 3443 for (i = 0; i < numThreads; i++)
3335 { 3444 {
3336 RINOK(threads.Items[i].Res); 3445 RINOK(threads.Items[i].Res)
3337 if (i != 0) 3446 if (i != 0)
3338 if (threads.Items[i].CheckSum_Res != 3447 if (threads.Items[i].CheckSum_Res !=
3339 threads.Items[i - 1].CheckSum_Res) 3448 threads.Items[i - 1].CheckSum_Res)
@@ -3345,20 +3454,20 @@ static HRESULT CrcBench(
3345 { 3454 {
3346 CMyComPtr<IHasher> hasher; 3455 CMyComPtr<IHasher> hasher;
3347 AString name; 3456 AString name;
3348 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, hasher)); 3457 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS hashID, name, hasher))
3349 if (!hasher) 3458 if (!hasher)
3350 return E_NOTIMPL; 3459 return E_NOTIMPL;
3351 CMyComPtr<ICompressSetCoderProperties> scp; 3460 CMyComPtr<ICompressSetCoderProperties> scp;
3352 hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); 3461 hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp);
3353 if (scp) 3462 if (scp)
3354 { 3463 {
3355 RINOK(method.SetCoderProps(scp)); 3464 RINOK(method.SetCoderProps(scp))
3356 } 3465 }
3357 CCrcInfo_Base crcib; 3466 CCrcInfo_Base crcib;
3358 crcib.CreateLocalBuf = false; 3467 crcib.CreateLocalBuf = false;
3359 RINOK(crcib.Generate(fileData, bufferSize)); 3468 RINOK(crcib.Generate(fileData, bufferSize))
3360 progressInfoSpec.SetStartTime(); 3469 progressInfoSpec.SetStartTime();
3361 RINOK(crcib.CrcProcess(numIterations, checkSum, hasher, _file)); 3470 RINOK(crcib.CrcProcess(numIterations, checkSum, hasher, _file))
3362 progressInfoSpec.SetFinishTime(info); 3471 progressInfoSpec.SetFinishTime(info);
3363 } 3472 }
3364 3473
@@ -3382,7 +3491,7 @@ static HRESULT CrcBench(
3382 benchWeight, rating, 3491 benchWeight, rating,
3383 showFreq, cpuFreq, encodeRes); 3492 showFreq, cpuFreq, encodeRes);
3384 } 3493 }
3385 RINOK(_file->CheckBreak()); 3494 RINOK(_file->CheckBreak())
3386 } 3495 }
3387 3496
3388 speed = info.GetSpeed(unpSizeThreads); 3497 speed = info.GetSpeed(unpSizeThreads);
@@ -3395,20 +3504,23 @@ static HRESULT CrcBench(
3395 3504
3396static HRESULT TotalBench_Hash( 3505static HRESULT TotalBench_Hash(
3397 DECL_EXTERNAL_CODECS_LOC_VARS 3506 DECL_EXTERNAL_CODECS_LOC_VARS
3507 const COneMethodInfo &methodMask,
3398 UInt64 complexInCommands, 3508 UInt64 complexInCommands,
3399 UInt32 numThreads, 3509 UInt32 numThreads,
3400 size_t bufSize, 3510 size_t bufSize,
3401 const Byte *fileData, 3511 const Byte *fileData,
3402 IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback, 3512 IBenchPrintCallback *printCallback, CBenchCallbackToPrint *callback,
3403 #ifndef _7ZIP_ST 3513 #ifndef Z7_ST
3404 const CAffinityMode *affinityMode, 3514 const CAffinityMode *affinityMode,
3405 #endif 3515 #endif
3406 CTotalBenchRes *encodeRes, 3516 CTotalBenchRes *encodeRes,
3407 bool showFreq, UInt64 cpuFreq) 3517 bool showFreq, UInt64 cpuFreq)
3408{ 3518{
3409 for (unsigned i = 0; i < ARRAY_SIZE(g_Hash); i++) 3519 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Hash); i++)
3410 { 3520 {
3411 const CBenchHash &bench = g_Hash[i]; 3521 const CBenchHash &bench = g_Hash[i];
3522 if (!DoesWildcardMatchName_NoCase(methodMask.MethodName, bench.Name))
3523 continue;
3412 PrintLeft(*callback->_file, bench.Name, kFieldSize_Name); 3524 PrintLeft(*callback->_file, bench.Name, kFieldSize_Name);
3413 // callback->BenchProps.DecComplexUnc = bench.DecComplexUnc; 3525 // callback->BenchProps.DecComplexUnc = bench.DecComplexUnc;
3414 // callback->BenchProps.DecComplexCompr = bench.DecComplexCompr; 3526 // callback->BenchProps.DecComplexCompr = bench.DecComplexCompr;
@@ -3417,11 +3529,11 @@ static HRESULT TotalBench_Hash(
3417 COneMethodInfo method; 3529 COneMethodInfo method;
3418 NCOM::CPropVariant propVariant; 3530 NCOM::CPropVariant propVariant;
3419 propVariant = bench.Name; 3531 propVariant = bench.Name;
3420 RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant)); 3532 RINOK(method.ParseMethodFromPROPVARIANT(UString(), propVariant))
3421 3533
3422 UInt64 speed, usage; 3534 UInt64 speed, usage;
3423 3535
3424 HRESULT res = CrcBench( 3536 const HRESULT res = CrcBench(
3425 EXTERNAL_CODECS_LOC_VARS 3537 EXTERNAL_CODECS_LOC_VARS
3426 complexInCommands, 3538 complexInCommands,
3427 numThreads, bufSize, fileData, 3539 numThreads, bufSize, fileData,
@@ -3430,7 +3542,7 @@ static HRESULT TotalBench_Hash(
3430 (!fileData && bufSize == (1 << kNumHashDictBits)) ? &bench.CheckSum : NULL, 3542 (!fileData && bufSize == (1 << kNumHashDictBits)) ? &bench.CheckSum : NULL,
3431 method, 3543 method,
3432 printCallback, 3544 printCallback,
3433 #ifndef _7ZIP_ST 3545 #ifndef Z7_ST
3434 affinityMode, 3546 affinityMode,
3435 #endif 3547 #endif
3436 true, // showRating 3548 true, // showRating
@@ -3441,7 +3553,7 @@ static HRESULT TotalBench_Hash(
3441 } 3553 }
3442 else 3554 else
3443 { 3555 {
3444 RINOK(res); 3556 RINOK(res)
3445 } 3557 }
3446 callback->NewLine(); 3558 callback->NewLine();
3447 } 3559 }
@@ -3451,7 +3563,8 @@ static HRESULT TotalBench_Hash(
3451struct CTempValues 3563struct CTempValues
3452{ 3564{
3453 UInt64 *Values; 3565 UInt64 *Values;
3454 CTempValues(UInt32 num) { Values = new UInt64[num]; } 3566 CTempValues(): Values(NULL) {}
3567 void Alloc(UInt32 num) { Values = new UInt64[num]; }
3455 ~CTempValues() { delete []Values; } 3568 ~CTempValues() { delete []Values; }
3456}; 3569};
3457 3570
@@ -3482,6 +3595,29 @@ static void Print_Usage_and_Threads(IBenchPrintCallback &f, UInt64 usage, UInt32
3482} 3595}
3483 3596
3484 3597
3598static void Print_Delimiter(IBenchPrintCallback &f)
3599{
3600 f.Print(" |");
3601}
3602
3603static void Print_Pow(IBenchPrintCallback &f, unsigned pow)
3604{
3605 char s[16];
3606 ConvertUInt32ToString(pow, s);
3607 unsigned pos = MyStringLen(s);
3608 s[pos++] = ':';
3609 s[pos] = 0;
3610 PrintLeft(f, s, kFieldSize_SmallName); // 4
3611}
3612
3613static void Bench_BW_Print_Usage_Speed(IBenchPrintCallback &f,
3614 UInt64 usage, UInt64 speed)
3615{
3616 PrintUsage(f, usage, kFieldSize_Usage);
3617 PrintNumber(f, speed / 1000000, kFieldSize_CrcSpeed);
3618}
3619
3620
3485HRESULT Bench( 3621HRESULT Bench(
3486 DECL_EXTERNAL_CODECS_LOC_VARS 3622 DECL_EXTERNAL_CODECS_LOC_VARS
3487 IBenchPrintCallback *printCallback, 3623 IBenchPrintCallback *printCallback,
@@ -3500,7 +3636,7 @@ HRESULT Bench(
3500 NSystem::CProcessAffinity threadsInfo; 3636 NSystem::CProcessAffinity threadsInfo;
3501 threadsInfo.InitST(); 3637 threadsInfo.InitST();
3502 3638
3503 #ifndef _7ZIP_ST 3639 #ifndef Z7_ST
3504 3640
3505 if (threadsInfo.Get() && threadsInfo.GetNumProcessThreads() != 0) 3641 if (threadsInfo.Get() && threadsInfo.GetNumProcessThreads() != 0)
3506 numCPUs = threadsInfo.GetNumProcessThreads(); 3642 numCPUs = threadsInfo.GetNumProcessThreads();
@@ -3533,7 +3669,7 @@ HRESULT Bench(
3533 UInt64 complexInCommands = kComplexInCommands; 3669 UInt64 complexInCommands = kComplexInCommands;
3534 UInt32 numThreads_Start = 1; 3670 UInt32 numThreads_Start = 1;
3535 3671
3536 #ifndef _7ZIP_ST 3672 #ifndef Z7_ST
3537 CAffinityMode affinityMode; 3673 CAffinityMode affinityMode;
3538 #endif 3674 #endif
3539 3675
@@ -3597,7 +3733,7 @@ HRESULT Bench(
3597 3733
3598 // (len == 0) is allowed. Also it's allowed if Alloc(0) returns NULL here 3734 // (len == 0) is allowed. Also it's allowed if Alloc(0) returns NULL here
3599 3735
3600 ALLOC_WITH_HRESULT(&fileDataBuffer, len); 3736 ALLOC_WITH_HRESULT(&fileDataBuffer, len)
3601 use_fileData = true; 3737 use_fileData = true;
3602 3738
3603 { 3739 {
@@ -3616,7 +3752,7 @@ HRESULT Bench(
3616 3752
3617 if (name.IsEqualTo("time")) 3753 if (name.IsEqualTo("time"))
3618 { 3754 {
3619 RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); 3755 RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs))
3620 needSetComplexity = true; 3756 needSetComplexity = true;
3621 testTimeMs *= 1000; 3757 testTimeMs *= 1000;
3622 continue; 3758 continue;
@@ -3624,7 +3760,7 @@ HRESULT Bench(
3624 3760
3625 if (name.IsEqualTo("timems")) 3761 if (name.IsEqualTo("timems"))
3626 { 3762 {
3627 RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs)); 3763 RINOK(ParsePropToUInt32(UString(), propVariant, testTimeMs))
3628 needSetComplexity = true; 3764 needSetComplexity = true;
3629 continue; 3765 continue;
3630 } 3766 }
@@ -3632,7 +3768,7 @@ HRESULT Bench(
3632 if (name.IsEqualTo("tic")) 3768 if (name.IsEqualTo("tic"))
3633 { 3769 {
3634 UInt32 v; 3770 UInt32 v;
3635 RINOK(ParsePropToUInt32(UString(), propVariant, v)); 3771 RINOK(ParsePropToUInt32(UString(), propVariant, v))
3636 if (v >= 64) 3772 if (v >= 64)
3637 return E_INVALIDARG; 3773 return E_INVALIDARG;
3638 complexInCommands = (UInt64)1 << v; 3774 complexInCommands = (UInt64)1 << v;
@@ -3644,7 +3780,7 @@ HRESULT Bench(
3644 isFixedDict = true; 3780 isFixedDict = true;
3645 if (isCurrent_fixedDict || name.IsEqualTo("ds")) 3781 if (isCurrent_fixedDict || name.IsEqualTo("ds"))
3646 { 3782 {
3647 RINOK(ParsePropToUInt32(UString(), propVariant, startDicLog)); 3783 RINOK(ParsePropToUInt32(UString(), propVariant, startDicLog))
3648 if (startDicLog > 32) 3784 if (startDicLog > 32)
3649 return E_INVALIDARG; 3785 return E_INVALIDARG;
3650 startDicLog_Defined = true; 3786 startDicLog_Defined = true;
@@ -3653,17 +3789,17 @@ HRESULT Bench(
3653 3789
3654 if (name.IsEqualTo("mts")) 3790 if (name.IsEqualTo("mts"))
3655 { 3791 {
3656 RINOK(ParsePropToUInt32(UString(), propVariant, numThreads_Start)); 3792 RINOK(ParsePropToUInt32(UString(), propVariant, numThreads_Start))
3657 continue; 3793 continue;
3658 } 3794 }
3659 3795
3660 if (name.IsEqualTo("af")) 3796 if (name.IsEqualTo("af"))
3661 { 3797 {
3662 UInt32 bundle; 3798 UInt32 bundle;
3663 RINOK(ParsePropToUInt32(UString(), propVariant, bundle)); 3799 RINOK(ParsePropToUInt32(UString(), propVariant, bundle))
3664 if (bundle > 0 && bundle < numCPUs) 3800 if (bundle > 0 && bundle < numCPUs)
3665 { 3801 {
3666 #ifndef _7ZIP_ST 3802 #ifndef Z7_ST
3667 affinityMode.SetLevels(numCPUs, 2); 3803 affinityMode.SetLevels(numCPUs, 2);
3668 affinityMode.NumBundleThreads = bundle; 3804 affinityMode.NumBundleThreads = bundle;
3669 #endif 3805 #endif
@@ -3674,7 +3810,7 @@ HRESULT Bench(
3674 if (name.IsEqualTo("freq")) 3810 if (name.IsEqualTo("freq"))
3675 { 3811 {
3676 UInt32 freq32 = 0; 3812 UInt32 freq32 = 0;
3677 RINOK(ParsePropToUInt32(UString(), propVariant, freq32)); 3813 RINOK(ParsePropToUInt32(UString(), propVariant, freq32))
3678 if (freq32 == 0) 3814 if (freq32 == 0)
3679 return E_INVALIDARG; 3815 return E_INVALIDARG;
3680 specifiedFreq = (UInt64)freq32 * 1000000; 3816 specifiedFreq = (UInt64)freq32 * 1000000;
@@ -3691,7 +3827,7 @@ HRESULT Bench(
3691 3827
3692 if (name.IsPrefixedBy_Ascii_NoCase("mt")) 3828 if (name.IsPrefixedBy_Ascii_NoCase("mt"))
3693 { 3829 {
3694 UString s = name.Ptr(2); 3830 const UString s = name.Ptr(2);
3695 if (s.IsEqualTo("*") 3831 if (s.IsEqualTo("*")
3696 || (s.IsEmpty() 3832 || (s.IsEmpty()
3697 && propVariant.vt == VT_BSTR 3833 && propVariant.vt == VT_BSTR
@@ -3700,13 +3836,13 @@ HRESULT Bench(
3700 multiThreadTests = true; 3836 multiThreadTests = true;
3701 continue; 3837 continue;
3702 } 3838 }
3703 #ifndef _7ZIP_ST 3839 #ifndef Z7_ST
3704 RINOK(ParseMtProp(s, propVariant, numCPUs, numThreadsSpecified)); 3840 RINOK(ParseMtProp(s, propVariant, numCPUs, numThreadsSpecified))
3705 #endif 3841 #endif
3706 continue; 3842 continue;
3707 } 3843 }
3708 3844
3709 RINOK(method.ParseMethodFromPROPVARIANT(name, propVariant)); 3845 RINOK(method.ParseMethodFromPROPVARIANT(name, propVariant))
3710 } 3846 }
3711 } 3847 }
3712 3848
@@ -3714,13 +3850,13 @@ HRESULT Bench(
3714 { 3850 {
3715 AString s; 3851 AString s;
3716 3852
3717 #ifndef _WIN32 3853 #ifndef _WIN32
3718 s += "Compiler: "; 3854 s += "Compiler: ";
3719 GetCompiler(s); 3855 GetCompiler(s);
3720 printCallback->Print(s); 3856 printCallback->Print(s);
3721 printCallback->NewLine(); 3857 printCallback->NewLine();
3722 s.Empty(); 3858 s.Empty();
3723 #endif 3859 #endif
3724 3860
3725 GetSystemInfoText(s); 3861 GetSystemInfoText(s);
3726 printCallback->Print(s); 3862 printCallback->Print(s);
@@ -3744,7 +3880,7 @@ HRESULT Bench(
3744 for (int jj = 0;; jj++) 3880 for (int jj = 0;; jj++)
3745 { 3881 {
3746 if (printCallback) 3882 if (printCallback)
3747 RINOK(printCallback->CheckBreak()); 3883 RINOK(printCallback->CheckBreak())
3748 3884
3749 UInt64 start = ::GetTimeCount(); 3885 UInt64 start = ::GetTimeCount();
3750 UInt32 sum = (UInt32)start; 3886 UInt32 sum = (UInt32)start;
@@ -3776,7 +3912,7 @@ HRESULT Bench(
3776 } 3912 }
3777 if (freqCallback) 3913 if (freqCallback)
3778 { 3914 {
3779 RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult)); 3915 RINOK(freqCallback->AddCpuFreq(1, hz, kBenchmarkUsageMult))
3780 } 3916 }
3781 3917
3782 if (jj >= 1) 3918 if (jj >= 1)
@@ -3806,7 +3942,7 @@ HRESULT Bench(
3806 } 3942 }
3807 if (freqCallback) 3943 if (freqCallback)
3808 { 3944 {
3809 RINOK(freqCallback->FreqsFinished(1)); 3945 RINOK(freqCallback->FreqsFinished(1))
3810 } 3946 }
3811 } 3947 }
3812 3948
@@ -3830,17 +3966,24 @@ HRESULT Bench(
3830 printCallback->Print(s); 3966 printCallback->Print(s);
3831 printCallback->Print("T CPU Freq (MHz):"); 3967 printCallback->Print("T CPU Freq (MHz):");
3832 } 3968 }
3833 UInt64 numMilCommands = 1 << 10; 3969 UInt64 numMilCommands = 1 <<
3970 #ifdef _DEBUG
3971 7;
3972 #else
3973 10;
3974 #endif
3975
3834 if (specifiedFreq != 0) 3976 if (specifiedFreq != 0)
3835 { 3977 {
3836 while (numMilCommands > 1 && specifiedFreq < (numMilCommands * 1000000)) 3978 while (numMilCommands > 1 && specifiedFreq < (numMilCommands * 1000000))
3837 numMilCommands >>= 1; 3979 numMilCommands >>= 1;
3838 } 3980 }
3839 3981
3840 for (int jj = 0;; jj++) 3982 // for (int jj = 0;; jj++)
3983 for (;;)
3841 { 3984 {
3842 if (printCallback) 3985 if (printCallback)
3843 RINOK(printCallback->CheckBreak()); 3986 RINOK(printCallback->CheckBreak())
3844 3987
3845 { 3988 {
3846 // PrintLeft(f, "CPU", kFieldSize_Name); 3989 // PrintLeft(f, "CPU", kFieldSize_Name);
@@ -3855,16 +3998,16 @@ HRESULT Bench(
3855 fb.showFreq = true; 3998 fb.showFreq = true;
3856 fb.specifiedFreq = 1; 3999 fb.specifiedFreq = 1;
3857 4000
3858 HRESULT res = fb.FreqBench(NULL /* printCallback */ 4001 const HRESULT res = fb.FreqBench(NULL /* printCallback */
3859 #ifndef _7ZIP_ST 4002 #ifndef Z7_ST
3860 , &affinityMode 4003 , &affinityMode
3861 #endif 4004 #endif
3862 ); 4005 );
3863 RINOK(res); 4006 RINOK(res)
3864 4007
3865 if (freqCallback) 4008 if (freqCallback)
3866 { 4009 {
3867 RINOK(freqCallback->AddCpuFreq(numThreads, fb.CpuFreqRes, fb.UsageRes)); 4010 RINOK(freqCallback->AddCpuFreq(numThreads, fb.CpuFreqRes, fb.UsageRes))
3868 } 4011 }
3869 4012
3870 if (printCallback) 4013 if (printCallback)
@@ -3889,7 +4032,7 @@ HRESULT Bench(
3889 } 4032 }
3890 // if (jj >= 1) 4033 // if (jj >= 1)
3891 { 4034 {
3892 bool needStop = (numMilCommands >= (1 << 4035 const bool needStop = (numMilCommands >= (1 <<
3893 #ifdef _DEBUG 4036 #ifdef _DEBUG
3894 7 4037 7
3895 #else 4038 #else
@@ -3903,7 +4046,7 @@ HRESULT Bench(
3903 } 4046 }
3904 if (freqCallback) 4047 if (freqCallback)
3905 { 4048 {
3906 RINOK(freqCallback->FreqsFinished(numThreads)); 4049 RINOK(freqCallback->FreqsFinished(numThreads))
3907 } 4050 }
3908 } 4051 }
3909 4052
@@ -3923,10 +4066,12 @@ HRESULT Bench(
3923 UInt64 dict = (UInt64)1 << startDicLog; 4066 UInt64 dict = (UInt64)1 << startDicLog;
3924 const bool dictIsDefined = (isFixedDict || method.Get_DicSize(dict)); 4067 const bool dictIsDefined = (isFixedDict || method.Get_DicSize(dict));
3925 4068
3926 const int level = method.GetLevel(); 4069 const unsigned level = method.GetLevel();
3927 4070
3928 if (method.MethodName.IsEmpty()) 4071 AString &methodName = method.MethodName;
3929 method.MethodName = "LZMA"; 4072 const AString original_MethodName = methodName;
4073 if (methodName.IsEmpty())
4074 methodName = "LZMA";
3930 4075
3931 if (benchCallback) 4076 if (benchCallback)
3932 { 4077 {
@@ -3949,7 +4094,7 @@ HRESULT Bench(
3949 return MethodBench( 4094 return MethodBench(
3950 EXTERNAL_CODECS_LOC_VARS 4095 EXTERNAL_CODECS_LOC_VARS
3951 complexInCommands, 4096 complexInCommands,
3952 #ifndef _7ZIP_ST 4097 #ifndef Z7_ST
3953 true, numThreadsSpecified, 4098 true, numThreadsSpecified,
3954 &affinityMode, 4099 &affinityMode,
3955 #endif 4100 #endif
@@ -3958,13 +4103,28 @@ HRESULT Bench(
3958 kOldLzmaDictBits, printCallback, benchCallback, &benchProps); 4103 kOldLzmaDictBits, printCallback, benchCallback, &benchProps);
3959 } 4104 }
3960 4105
3961 AString methodName (method.MethodName);
3962 if (methodName.IsEqualTo_Ascii_NoCase("CRC")) 4106 if (methodName.IsEqualTo_Ascii_NoCase("CRC"))
3963 methodName = "crc32"; 4107 methodName = "crc32";
3964 method.MethodName = methodName; 4108
3965 CMethodId hashID; 4109 CMethodId hashID;
3966 4110 const bool isHashMethod = FindHashMethod(EXTERNAL_CODECS_LOC_VARS methodName, hashID);
3967 if (FindHashMethod(EXTERNAL_CODECS_LOC_VARS methodName, hashID)) 4111 int codecIndex = -1;
4112 bool isFilter = false;
4113 if (!isHashMethod)
4114 {
4115 UInt32 numStreams;
4116 codecIndex = FindMethod_Index(EXTERNAL_CODECS_LOC_VARS original_MethodName,
4117 true, // encode
4118 hashID, numStreams, isFilter);
4119 // we can allow non filter for BW tests
4120 if (!isFilter) codecIndex = -1;
4121 }
4122
4123 CBenchCallbackToPrint callback;
4124 callback.Init();
4125 callback._file = printCallback;
4126
4127 if (isHashMethod || codecIndex != -1)
3968 { 4128 {
3969 if (!printCallback) 4129 if (!printCallback)
3970 return S_FALSE; 4130 return S_FALSE;
@@ -3981,17 +4141,27 @@ HRESULT Bench(
3981 dict64 = fileDataBuffer.Size(); 4141 dict64 = fileDataBuffer.Size();
3982 } 4142 }
3983 4143
3984 // methhodName.RemoveChar(L'-'); 4144 for (;;)
3985 UInt32 complexity = 10000; 4145 {
4146 const int index = method.FindProp(NCoderPropID::kDictionarySize);
4147 if (index < 0)
4148 break;
4149 method.Props.Delete((unsigned)index);
4150 }
4151
4152 // methodName.RemoveChar(L'-');
4153 Int32 complexity = 16 * k_Hash_Complex_Mult; // for unknown hash method
3986 const UInt32 *checkSum = NULL; 4154 const UInt32 *checkSum = NULL;
4155 int benchIndex = -1;
4156
4157 if (isHashMethod)
3987 { 4158 {
3988 unsigned i; 4159 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Hash); i++)
3989 for (i = 0; i < ARRAY_SIZE(g_Hash); i++)
3990 { 4160 {
3991 const CBenchHash &h = g_Hash[i]; 4161 const CBenchHash &h = g_Hash[i];
3992 AString benchMethod (h.Name); 4162 AString benchMethod (h.Name);
3993 AString benchProps; 4163 AString benchProps;
3994 int propPos = benchMethod.Find(':'); 4164 const int propPos = benchMethod.Find(':');
3995 if (propPos >= 0) 4165 if (propPos >= 0)
3996 { 4166 {
3997 benchProps = benchMethod.Ptr((unsigned)(propPos + 1)); 4167 benchProps = benchMethod.Ptr((unsigned)(propPos + 1));
@@ -4000,45 +4170,80 @@ HRESULT Bench(
4000 4170
4001 if (AreSameMethodNames(benchMethod, methodName)) 4171 if (AreSameMethodNames(benchMethod, methodName))
4002 { 4172 {
4003 bool isMainMathed = method.PropsString.IsEmpty();
4004 if (isMainMathed)
4005 isMainMathed = !checkSum
4006 || (benchMethod.IsEqualTo_Ascii_NoCase("crc32") && benchProps.IsEqualTo_Ascii_NoCase("8"));
4007 const bool sameProps = method.PropsString.IsEqualTo_Ascii_NoCase(benchProps); 4173 const bool sameProps = method.PropsString.IsEqualTo_Ascii_NoCase(benchProps);
4008 if (sameProps || isMainMathed) 4174 /*
4175 bool isMainMethod = method.PropsString.IsEmpty();
4176 if (isMainMethod)
4177 isMainMethod = !checkSum
4178 || (benchMethod.IsEqualTo_Ascii_NoCase("crc32") && benchProps.IsEqualTo_Ascii_NoCase("8"));
4179 if (sameProps || isMainMethod)
4180 */
4009 { 4181 {
4010 complexity = h.Complex; 4182 complexity = (Int32)h.Complex;
4011 checkSum = &h.CheckSum; 4183 checkSum = &h.CheckSum;
4012 if (sameProps) 4184 if (sameProps)
4013 break; 4185 break;
4186 /*
4187 if property. is not specified, we use the complexity
4188 for latest fastest method (crc32:64)
4189 */
4014 } 4190 }
4015 } 4191 }
4016 } 4192 }
4017 if (!checkSum) 4193 // if (!checkSum) return E_NOTIMPL;
4018 return E_NOTIMPL; 4194 }
4195 else
4196 {
4197 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++)
4198 {
4199 const CBenchMethod &bench = g_Bench[i];
4200 AString benchMethod (bench.Name);
4201 AString benchProps;
4202 const int propPos = benchMethod.Find(':');
4203 if (propPos >= 0)
4204 {
4205 benchProps = benchMethod.Ptr((unsigned)(propPos + 1));
4206 benchMethod.DeleteFrom((unsigned)propPos);
4207 }
4208
4209 if (AreSameMethodNames(benchMethod, methodName))
4210 {
4211 const bool sameProps = method.PropsString.IsEqualTo_Ascii_NoCase(benchProps);
4212 // bool isMainMethod = method.PropsString.IsEmpty();
4213 // if (sameProps || isMainMethod)
4214 {
4215 benchIndex = (int)i;
4216 if (sameProps)
4217 break;
4218 }
4219 }
4220 }
4221 // if (benchIndex < 0) return E_NOTIMPL;
4019 } 4222 }
4020 4223
4021 { 4224 {
4022 UInt64 usage = 1 << 20; 4225 /* we count usage only for crc and filter. non-filters are not supported */
4226 UInt64 usage = (1 << 20);
4023 UInt64 bufSize = dict64; 4227 UInt64 bufSize = dict64;
4228 UInt32 numBlocks = isHashMethod ? 1 : 3;
4024 if (use_fileData) 4229 if (use_fileData)
4025 { 4230 {
4026 usage += fileDataBuffer.Size(); 4231 usage += fileDataBuffer.Size();
4027 if (bufSize > fileDataBuffer.Size()) 4232 if (bufSize > fileDataBuffer.Size())
4028 bufSize = fileDataBuffer.Size(); 4233 bufSize = fileDataBuffer.Size();
4029 #ifndef _7ZIP_ST 4234 if (isHashMethod)
4030 if (numThreadsSpecified != 1) 4235 {
4031 usage += bufSize * numThreadsSpecified * (k_Crc_CreateLocalBuf_For_File ? 1 : 0); 4236 numBlocks = 0;
4032 #endif 4237 #ifndef Z7_ST
4238 if (numThreadsSpecified != 1)
4239 numBlocks = (k_Crc_CreateLocalBuf_For_File ? 1 : 0);
4240 #endif
4241 }
4033 } 4242 }
4034 else 4243 usage += numThreadsSpecified * bufSize * numBlocks;
4035 usage += numThreadsSpecified * bufSize;
4036 Print_Usage_and_Threads(f, usage, numThreadsSpecified); 4244 Print_Usage_and_Threads(f, usage, numThreadsSpecified);
4037 } 4245 }
4038 4246
4039 f.NewLine();
4040
4041 const unsigned kFieldSize_CrcSpeed = 7;
4042 CUIntVector numThreadsVector; 4247 CUIntVector numThreadsVector;
4043 { 4248 {
4044 unsigned nt = numThreads_Start; 4249 unsigned nt = numThreads_Start;
@@ -4047,136 +4252,225 @@ HRESULT Bench(
4047 if (nt > numThreadsSpecified) 4252 if (nt > numThreadsSpecified)
4048 break; 4253 break;
4049 numThreadsVector.Add(nt); 4254 numThreadsVector.Add(nt);
4050 unsigned next = nt * 2; 4255 const unsigned next = nt * 2;
4051 UInt32 ntHalf= numThreadsSpecified / 2; 4256 const UInt32 ntHalf= numThreadsSpecified / 2;
4052 if (ntHalf > nt && ntHalf < next) 4257 if (ntHalf > nt && ntHalf < next)
4053 numThreadsVector.Add(ntHalf); 4258 numThreadsVector.Add(ntHalf);
4054 if (numThreadsSpecified > nt && numThreadsSpecified < next) 4259 if (numThreadsSpecified > nt && numThreadsSpecified < next)
4055 numThreadsVector.Add(numThreadsSpecified); 4260 numThreadsVector.Add(numThreadsSpecified);
4056 nt = next; 4261 nt = next;
4057 } 4262 }
4263 }
4264
4265 unsigned numColumns = isHashMethod ? 1 : 2;
4266 CTempValues speedTotals;
4267 CTempValues usageTotals;
4268 {
4269 const unsigned numItems = numThreadsVector.Size() * numColumns;
4270 speedTotals.Alloc(numItems);
4271 usageTotals.Alloc(numItems);
4272 for (unsigned i = 0; i < numItems; i++)
4058 { 4273 {
4059 f.NewLine(); 4274 speedTotals.Values[i] = 0;
4060 f.Print("THRD"); 4275 usageTotals.Values[i] = 0;
4061 FOR_VECTOR (ti, numThreadsVector)
4062 {
4063 PrintNumber(f, numThreadsVector[ti], 1 + kFieldSize_Usage + kFieldSize_CrcSpeed);
4064 }
4065 } 4276 }
4277 }
4278
4279 f.NewLine();
4280 for (unsigned line = 0; line < 3; line++)
4281 {
4282 f.NewLine();
4283 f.Print(line == 0 ? "THRD" : line == 1 ? " " : "Size");
4284 FOR_VECTOR (ti, numThreadsVector)
4066 { 4285 {
4067 f.NewLine(); 4286 if (ti != 0)
4068 f.Print(" "); 4287 Print_Delimiter(f);
4069 FOR_VECTOR (ti, numThreadsVector) 4288 if (line == 0)
4070 { 4289 {
4071 PrintRight(f, "Usage", kFieldSize_Usage + 1); 4290 PrintSpaces(f, (kFieldSize_CrcSpeed + kFieldSize_Usage + 2) * (numColumns - 1));
4072 PrintRight(f, "BW", kFieldSize_CrcSpeed + 1); 4291 PrintNumber(f, numThreadsVector[ti], 1 + kFieldSize_Usage + kFieldSize_CrcSpeed);
4073 } 4292 }
4074 } 4293 else
4075 {
4076 f.NewLine();
4077 f.Print("Size");
4078 FOR_VECTOR (ti, numThreadsVector)
4079 { 4294 {
4080 PrintRight(f, "%", kFieldSize_Usage + 1); 4295 for (unsigned c = 0; c < numColumns; c++)
4081 PrintRight(f, "MB/s", kFieldSize_CrcSpeed + 1); 4296 {
4297 PrintRight(f, line == 1 ? "Usage" : "%", kFieldSize_Usage + 1);
4298 PrintRight(f, line == 1 ? "BW" : "MB/s", kFieldSize_CrcSpeed + 1);
4299 }
4082 } 4300 }
4083 } 4301 }
4084 } 4302 }
4085
4086 f.NewLine();
4087 f.NewLine(); 4303 f.NewLine();
4088 4304
4089 CTempValues speedTotals(numThreadsVector.Size());
4090 CTempValues usageTotals(numThreadsVector.Size());
4091 {
4092 FOR_VECTOR (ti, numThreadsVector)
4093 {
4094 speedTotals.Values[ti] = 0;
4095 usageTotals.Values[ti] = 0;
4096 }
4097 }
4098
4099 UInt64 numSteps = 0; 4305 UInt64 numSteps = 0;
4100 4306
4101 for (UInt32 i = 0; i < numIterations; i++) 4307 // for (UInt32 iter = 0; iter < numIterations; iter++)
4308 // {
4309 unsigned pow = 10; // kNumHashDictBits
4310 if (startDicLog_Defined)
4311 pow = startDicLog;
4312
4313 // #define NUM_SUB_BITS 2
4314 // pow <<= NUM_SUB_BITS;
4315 for (;; pow++)
4102 { 4316 {
4103 unsigned pow = 10; // kNumHashDictBits 4317 const UInt64 bufSize = (UInt64)1 << pow;
4104 if (startDicLog_Defined) 4318 // UInt64 bufSize = (UInt64)1 << (pow >> NUM_SUB_BITS);
4105 pow = startDicLog; 4319 // bufSize += ((UInt64)pow & ((1 << NUM_SUB_BITS) - 1)) << ((pow >> NUM_SUB_BITS) - NUM_SUB_BITS);
4106 for (;; pow++)
4107 {
4108 const UInt64 bufSize = (UInt64)1 << pow;
4109 char s[16];
4110 ConvertUInt32ToString(pow, s);
4111 unsigned pos = MyStringLen(s);
4112 s[pos++] = ':';
4113 s[pos++] = ' ';
4114 s[pos] = 0;
4115 PrintRight(f, s, 4);
4116
4117 size_t dataSize = fileDataBuffer.Size();
4118 if (dataSize > bufSize || !use_fileData)
4119 dataSize = (size_t)bufSize;
4120 4320
4321 size_t dataSize = fileDataBuffer.Size();
4322 if (dataSize > bufSize || !use_fileData)
4323 dataSize = (size_t)bufSize;
4324
4325 for (UInt32 iter = 0; iter < numIterations; iter++)
4326 {
4327 Print_Pow(f, pow);
4328 // PrintNumber(f, bufSize >> 10, 4);
4329
4121 FOR_VECTOR (ti, numThreadsVector) 4330 FOR_VECTOR (ti, numThreadsVector)
4122 { 4331 {
4123 RINOK(f.CheckBreak()); 4332 RINOK(f.CheckBreak())
4124 const UInt32 t = numThreadsVector[ti]; 4333 const UInt32 numThreads = numThreadsVector[ti];
4125 UInt64 speed = 0; 4334 if (isHashMethod)
4126 UInt64 usage = 0; 4335 {
4127 4336 UInt64 speed = 0;
4128 HRESULT res = CrcBench(EXTERNAL_CODECS_LOC_VARS complexInCommands, 4337 UInt64 usage = 0;
4129 t, 4338 const HRESULT res = CrcBench(EXTERNAL_CODECS_LOC_VARS complexInCommands,
4339 numThreads,
4130 dataSize, (const Byte *)fileDataBuffer, 4340 dataSize, (const Byte *)fileDataBuffer,
4131 speed, usage, 4341 speed, usage,
4132 complexity, 4342 (UInt32)complexity,
4133 1, // benchWeight, 4343 1, // benchWeight,
4134 (pow == kNumHashDictBits && !use_fileData) ? checkSum : NULL, 4344 (pow == kNumHashDictBits && !use_fileData) ? checkSum : NULL,
4135 method, 4345 method,
4136 &f, 4346 &f,
4137 #ifndef _7ZIP_ST 4347 #ifndef Z7_ST
4138 &affinityMode, 4348 &affinityMode,
4139 #endif 4349 #endif
4140 false, // showRating 4350 false, // showRating
4141 NULL, false, 0); 4351 NULL, false, 0);
4142 4352 RINOK(res)
4143 RINOK(res); 4353
4144 4354 if (ti != 0)
4145 PrintUsage(f, usage, kFieldSize_Usage); 4355 Print_Delimiter(f);
4146 PrintNumber(f, speed / 1000000, kFieldSize_CrcSpeed); 4356
4147 speedTotals.Values[ti] += speed; 4357 Bench_BW_Print_Usage_Speed(f, usage, speed);
4148 usageTotals.Values[ti] += usage; 4358 speedTotals.Values[ti] += speed;
4359 usageTotals.Values[ti] += usage;
4360 }
4361 else
4362 {
4363 {
4364 unsigned keySize = 32;
4365 if (IsString1PrefixedByString2(methodName, "AES128")) keySize = 16;
4366 else if (IsString1PrefixedByString2(methodName, "AES192")) keySize = 24;
4367 callback.BenchProps.KeySize = keySize;
4368 }
4369
4370 COneMethodInfo method2 = method;
4371 unsigned bench_DictBits;
4372
4373 if (benchIndex >= 0)
4374 {
4375 const CBenchMethod &bench = g_Bench[benchIndex];
4376 callback.BenchProps.EncComplex = bench.EncComplex;
4377 callback.BenchProps.DecComplexUnc = bench.DecComplexUnc;
4378 callback.BenchProps.DecComplexCompr = bench.DecComplexCompr;
4379 bench_DictBits = bench.DictBits;
4380 // bench_DictBits = kOldLzmaDictBits; = 32 default : for debug
4381 }
4382 else
4383 {
4384 bench_DictBits = kOldLzmaDictBits; // = 32 default
4385 if (isFilter)
4386 {
4387 const unsigned k_UnknownCoderComplexity = 4;
4388 callback.BenchProps.EncComplex = k_UnknownCoderComplexity;
4389 callback.BenchProps.DecComplexUnc = k_UnknownCoderComplexity;
4390 }
4391 else
4392 {
4393 callback.BenchProps.EncComplex = 1 << 10;
4394 callback.BenchProps.DecComplexUnc = 1 << 6;
4395 }
4396 callback.BenchProps.DecComplexCompr = 0;
4397 }
4398 callback.NeedPrint = false;
4399
4400 if (StringsAreEqualNoCase_Ascii(method2.MethodName, "LZMA"))
4401 {
4402 const NCOM::CPropVariant propVariant = (UInt32)pow;
4403 RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant))
4404 }
4405
4406 const HRESULT res = MethodBench(
4407 EXTERNAL_CODECS_LOC_VARS
4408 complexInCommands,
4409 #ifndef Z7_ST
4410 false, // oldLzmaBenchMode
4411 numThreadsVector[ti],
4412 &affinityMode,
4413 #endif
4414 method2,
4415 dataSize, (const Byte *)fileDataBuffer,
4416 bench_DictBits,
4417 printCallback,
4418 &callback,
4419 &callback.BenchProps);
4420 RINOK(res)
4421
4422 if (ti != 0)
4423 Print_Delimiter(f);
4424
4425 for (unsigned i = 0; i < 2; i++)
4426 {
4427 const CBenchInfo &bi = callback.BenchInfo_Results[i];
4428 const UInt64 usage = bi.GetUsage();
4429 const UInt64 speed = bi.GetUnpackSizeSpeed();
4430 usageTotals.Values[ti * 2 + i] += usage;
4431 speedTotals.Values[ti * 2 + i] += speed;
4432 Bench_BW_Print_Usage_Speed(f, usage, speed);
4433 }
4434 }
4149 } 4435 }
4150 4436
4151 f.NewLine(); 4437 f.NewLine();
4152 numSteps++; 4438 numSteps++;
4153 if (dataSize >= dict64)
4154 break;
4155 } 4439 }
4440 if (dataSize >= dict64)
4441 break;
4156 } 4442 }
4443
4157 if (numSteps != 0) 4444 if (numSteps != 0)
4158 { 4445 {
4159 f.NewLine();
4160 f.Print("Avg:"); 4446 f.Print("Avg:");
4161 for (unsigned ti = 0; ti < numThreadsVector.Size(); ti++) 4447 for (unsigned ti = 0; ti < numThreadsVector.Size(); ti++)
4162 { 4448 {
4163 PrintUsage(f, usageTotals.Values[ti] / numSteps, kFieldSize_Usage); 4449 if (ti != 0)
4164 PrintNumber(f, speedTotals.Values[ti] / numSteps / 1000000, kFieldSize_CrcSpeed); 4450 Print_Delimiter(f);
4451 for (unsigned i = 0; i < numColumns; i++)
4452 Bench_BW_Print_Usage_Speed(f,
4453 usageTotals.Values[ti * numColumns + i] / numSteps,
4454 speedTotals.Values[ti * numColumns + i] / numSteps);
4165 } 4455 }
4166 f.NewLine(); 4456 f.NewLine();
4167 } 4457 }
4458
4168 return S_OK; 4459 return S_OK;
4169 } 4460 }
4170 4461
4171 bool use2Columns = false; 4462 bool use2Columns = false;
4172 4463
4173 bool totalBenchMode = (method.MethodName.IsEqualTo_Ascii_NoCase("*")); 4464 bool totalBenchMode = false;
4174 bool onlyHashBench = false; 4465 bool onlyHashBench = false;
4175 if (method.MethodName.IsEqualTo_Ascii_NoCase("hash")) 4466 if (methodName.IsEqualTo_Ascii_NoCase("hash"))
4176 { 4467 {
4177 onlyHashBench = true; 4468 onlyHashBench = true;
4469 methodName = "*";
4178 totalBenchMode = true; 4470 totalBenchMode = true;
4179 } 4471 }
4472 else if (methodName.Find('*') >= 0)
4473 totalBenchMode = true;
4180 4474
4181 // ---------- Threads loop ---------- 4475 // ---------- Threads loop ----------
4182 for (unsigned threadsPassIndex = 0; threadsPassIndex < 3; threadsPassIndex++) 4476 for (unsigned threadsPassIndex = 0; threadsPassIndex < 3; threadsPassIndex++)
@@ -4207,10 +4501,6 @@ HRESULT Bench(
4207 } 4501 }
4208 } 4502 }
4209 4503
4210 CBenchCallbackToPrint callback;
4211 callback.Init();
4212 callback._file = printCallback;
4213
4214 IBenchPrintCallback &f = *printCallback; 4504 IBenchPrintCallback &f = *printCallback;
4215 4505
4216 if (threadsPassIndex > 0) 4506 if (threadsPassIndex > 0)
@@ -4230,7 +4520,7 @@ HRESULT Bench(
4230 4520
4231 if (ramSize_Defined) 4521 if (ramSize_Defined)
4232 for (; dicSizeLog > kBenchMinDicLogSize; dicSizeLog--) 4522 for (; dicSizeLog > kBenchMinDicLogSize; dicSizeLog--)
4233 if (GetBenchMemoryUsage(numThreads, level, ((UInt64)1 << dicSizeLog), totalBenchMode) + (8 << 20) <= ramSize) 4523 if (GetBenchMemoryUsage(numThreads, (int)level, ((UInt64)1 << dicSizeLog), totalBenchMode) + (8 << 20) <= ramSize)
4234 break; 4524 break;
4235 4525
4236 dict = (UInt64)1 << dicSizeLog; 4526 dict = (UInt64)1 << dicSizeLog;
@@ -4246,7 +4536,7 @@ HRESULT Bench(
4246 Print_Usage_and_Threads(f, 4536 Print_Usage_and_Threads(f,
4247 onlyHashBench ? 4537 onlyHashBench ?
4248 GetBenchMemoryUsage_Hash(numThreads, dict) : 4538 GetBenchMemoryUsage_Hash(numThreads, dict) :
4249 GetBenchMemoryUsage(numThreads, level, dict, totalBenchMode), 4539 GetBenchMemoryUsage(numThreads, (int)level, dict, totalBenchMode),
4250 numThreads); 4540 numThreads);
4251 4541
4252 f.NewLine(); 4542 f.NewLine();
@@ -4355,12 +4645,12 @@ HRESULT Bench(
4355 fb.showFreq = (freqTest == kNumCpuTests - 1 || specifiedFreq != 0); 4645 fb.showFreq = (freqTest == kNumCpuTests - 1 || specifiedFreq != 0);
4356 fb.specifiedFreq = specifiedFreq; 4646 fb.specifiedFreq = specifiedFreq;
4357 4647
4358 HRESULT res = fb.FreqBench(printCallback 4648 const HRESULT res = fb.FreqBench(printCallback
4359 #ifndef _7ZIP_ST 4649 #ifndef Z7_ST
4360 , &affinityMode 4650 , &affinityMode
4361 #endif 4651 #endif
4362 ); 4652 );
4363 RINOK(res); 4653 RINOK(res)
4364 4654
4365 cpuFreq = fb.CpuFreqRes; 4655 cpuFreq = fb.CpuFreqRes;
4366 callback.NewLine(); 4656 callback.NewLine();
@@ -4390,9 +4680,9 @@ HRESULT Bench(
4390 dataSize = (size_t)dict; 4680 dataSize = (size_t)dict;
4391 } 4681 }
4392 4682
4393 HRESULT res = TotalBench(EXTERNAL_CODECS_LOC_VARS 4683 const HRESULT res = TotalBench(EXTERNAL_CODECS_LOC_VARS
4394 complexInCommands, 4684 method, complexInCommands,
4395 #ifndef _7ZIP_ST 4685 #ifndef Z7_ST
4396 numThreads, 4686 numThreads,
4397 &affinityMode, 4687 &affinityMode,
4398 #endif 4688 #endif
@@ -4400,7 +4690,7 @@ HRESULT Bench(
4400 dataSize, 4690 dataSize,
4401 (const Byte *)fileDataBuffer, 4691 (const Byte *)fileDataBuffer,
4402 printCallback, &callback); 4692 printCallback, &callback);
4403 RINOK(res); 4693 RINOK(res)
4404 } 4694 }
4405 4695
4406 { 4696 {
@@ -4418,14 +4708,16 @@ HRESULT Bench(
4418 dataSize = (size_t)dict; 4708 dataSize = (size_t)dict;
4419 } 4709 }
4420 4710
4421 HRESULT res = TotalBench_Hash(EXTERNAL_CODECS_LOC_VARS complexInCommands, numThreads, 4711 const HRESULT res = TotalBench_Hash(EXTERNAL_CODECS_LOC_VARS
4712 method, complexInCommands,
4713 numThreads,
4422 dataSize, (const Byte *)fileDataBuffer, 4714 dataSize, (const Byte *)fileDataBuffer,
4423 printCallback, &callback, 4715 printCallback, &callback,
4424 #ifndef _7ZIP_ST 4716 #ifndef Z7_ST
4425 &affinityMode, 4717 &affinityMode,
4426 #endif 4718 #endif
4427 &callback.EncodeRes, true, cpuFreq); 4719 &callback.EncodeRes, true, cpuFreq);
4428 RINOK(res); 4720 RINOK(res)
4429 } 4721 }
4430 4722
4431 callback.NewLine(); 4723 callback.NewLine();
@@ -4439,12 +4731,12 @@ HRESULT Bench(
4439 fb.showFreq = (specifiedFreq != 0); 4731 fb.showFreq = (specifiedFreq != 0);
4440 fb.specifiedFreq = specifiedFreq; 4732 fb.specifiedFreq = specifiedFreq;
4441 4733
4442 HRESULT res = fb.FreqBench(printCallback 4734 const HRESULT res = fb.FreqBench(printCallback
4443 #ifndef _7ZIP_ST 4735 #ifndef Z7_ST
4444 , &affinityMode 4736 , &affinityMode
4445 #endif 4737 #endif
4446 ); 4738 );
4447 RINOK(res); 4739 RINOK(res)
4448 callback.NewLine(); 4740 callback.NewLine();
4449 } 4741 }
4450 } 4742 }
@@ -4455,12 +4747,12 @@ HRESULT Bench(
4455 if (!methodName.IsEqualTo_Ascii_NoCase("LZMA")) 4747 if (!methodName.IsEqualTo_Ascii_NoCase("LZMA"))
4456 { 4748 {
4457 unsigned i; 4749 unsigned i;
4458 for (i = 0; i < ARRAY_SIZE(g_Bench); i++) 4750 for (i = 0; i < Z7_ARRAY_SIZE(g_Bench); i++)
4459 { 4751 {
4460 const CBenchMethod &h = g_Bench[i]; 4752 const CBenchMethod &h = g_Bench[i];
4461 AString benchMethod (h.Name); 4753 AString benchMethod (h.Name);
4462 AString benchProps; 4754 AString benchProps;
4463 int propPos = benchMethod.Find(':'); 4755 const int propPos = benchMethod.Find(':');
4464 if (propPos >= 0) 4756 if (propPos >= 0)
4465 { 4757 {
4466 benchProps = benchMethod.Ptr((unsigned)(propPos + 1)); 4758 benchProps = benchMethod.Ptr((unsigned)(propPos + 1));
@@ -4475,14 +4767,16 @@ HRESULT Bench(
4475 { 4767 {
4476 callback.BenchProps.EncComplex = h.EncComplex; 4768 callback.BenchProps.EncComplex = h.EncComplex;
4477 callback.BenchProps.DecComplexCompr = h.DecComplexCompr; 4769 callback.BenchProps.DecComplexCompr = h.DecComplexCompr;
4478 callback.BenchProps.DecComplexUnc = h.DecComplexUnc;; 4770 callback.BenchProps.DecComplexUnc = h.DecComplexUnc;
4479 needSetComplexity = false; 4771 needSetComplexity = false;
4480 break; 4772 break;
4481 } 4773 }
4482 } 4774 }
4483 } 4775 }
4484 if (i == ARRAY_SIZE(g_Bench)) 4776 /*
4777 if (i == Z7_ARRAY_SIZE(g_Bench))
4485 return E_NOTIMPL; 4778 return E_NOTIMPL;
4779 */
4486 } 4780 }
4487 if (needSetComplexity) 4781 if (needSetComplexity)
4488 callback.BenchProps.SetLzmaCompexity(); 4782 callback.BenchProps.SetLzmaCompexity();
@@ -4499,12 +4793,7 @@ HRESULT Bench(
4499 pow--; 4793 pow--;
4500 for (; GetDictSizeFromLog(pow) <= dict; pow++) 4794 for (; GetDictSizeFromLog(pow) <= dict; pow++)
4501 { 4795 {
4502 char s[16]; 4796 Print_Pow(f, pow);
4503 ConvertUInt32ToString(pow, s);
4504 unsigned pos = MyStringLen(s);
4505 s[pos++] = ':';
4506 s[pos] = 0;
4507 PrintLeft(f, s, kFieldSize_SmallName);
4508 callback.DictSize = (UInt64)1 << pow; 4797 callback.DictSize = (UInt64)1 << pow;
4509 4798
4510 COneMethodInfo method2 = method; 4799 COneMethodInfo method2 = method;
@@ -4515,7 +4804,7 @@ HRESULT Bench(
4515 // method2 can have two different dictionary size properties. 4804 // method2 can have two different dictionary size properties.
4516 // And last property is main. 4805 // And last property is main.
4517 NCOM::CPropVariant propVariant = (UInt32)pow; 4806 NCOM::CPropVariant propVariant = (UInt32)pow;
4518 RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant)); 4807 RINOK(method2.ParseMethodFromPROPVARIANT((UString)"d", propVariant))
4519 } 4808 }
4520 4809
4521 size_t uncompressedDataSize; 4810 size_t uncompressedDataSize;
@@ -4532,10 +4821,10 @@ HRESULT Bench(
4532 uncompressedDataSize += kAdditionalSize; 4821 uncompressedDataSize += kAdditionalSize;
4533 } 4822 }
4534 4823
4535 HRESULT res = MethodBench( 4824 const HRESULT res = MethodBench(
4536 EXTERNAL_CODECS_LOC_VARS 4825 EXTERNAL_CODECS_LOC_VARS
4537 complexInCommands, 4826 complexInCommands,
4538 #ifndef _7ZIP_ST 4827 #ifndef Z7_ST
4539 true, numThreads, 4828 true, numThreads,
4540 &affinityMode, 4829 &affinityMode,
4541 #endif 4830 #endif
@@ -4543,7 +4832,7 @@ HRESULT Bench(
4543 uncompressedDataSize, (const Byte *)fileDataBuffer, 4832 uncompressedDataSize, (const Byte *)fileDataBuffer,
4544 kOldLzmaDictBits, printCallback, &callback, &callback.BenchProps); 4833 kOldLzmaDictBits, printCallback, &callback, &callback.BenchProps);
4545 f.NewLine(); 4834 f.NewLine();
4546 RINOK(res); 4835 RINOK(res)
4547 if (!multiDict) 4836 if (!multiDict)
4548 break; 4837 break;
4549 } 4838 }
diff --git a/CPP/7zip/UI/Common/Bench.h b/CPP/7zip/UI/Common/Bench.h
index ab0c304..313676d 100644
--- a/CPP/7zip/UI/Common/Bench.h
+++ b/CPP/7zip/UI/Common/Bench.h
@@ -1,7 +1,7 @@
1// Bench.h 1// Bench.h
2 2
3#ifndef __7ZIP_BENCH_H 3#ifndef ZIP7_INC_7ZIP_BENCH_H
4#define __7ZIP_BENCH_H 4#define ZIP7_INC_7ZIP_BENCH_H
5 5
6#include "../../../Windows/System.h" 6#include "../../../Windows/System.h"
7 7
@@ -71,32 +71,31 @@ struct CTotalBenchRes
71}; 71};
72 72
73 73
74const unsigned kBenchMinDicLogSize = 18;
75
76UInt64 GetBenchMemoryUsage(UInt32 numThreads, int level, UInt64 dictionary, bool totalBench);
74 77
75struct IBenchCallback 78Z7_PURE_INTERFACES_BEGIN
79DECLARE_INTERFACE(IBenchCallback)
76{ 80{
77 // virtual HRESULT SetFreq(bool showFreq, UInt64 cpuFreq) = 0; 81 // virtual HRESULT SetFreq(bool showFreq, UInt64 cpuFreq) = 0;
78 virtual HRESULT SetEncodeResult(const CBenchInfo &info, bool final) = 0; 82 virtual HRESULT SetEncodeResult(const CBenchInfo &info, bool final) = 0;
79 virtual HRESULT SetDecodeResult(const CBenchInfo &info, bool final) = 0; 83 virtual HRESULT SetDecodeResult(const CBenchInfo &info, bool final) = 0;
80}; 84};
81 85
82 86DECLARE_INTERFACE(IBenchPrintCallback)
83
84const unsigned kBenchMinDicLogSize = 18;
85
86UInt64 GetBenchMemoryUsage(UInt32 numThreads, int level, UInt64 dictionary, bool totalBench);
87
88struct IBenchPrintCallback
89{ 87{
90 virtual void Print(const char *s) = 0; 88 virtual void Print(const char *s) = 0;
91 virtual void NewLine() = 0; 89 virtual void NewLine() = 0;
92 virtual HRESULT CheckBreak() = 0; 90 virtual HRESULT CheckBreak() = 0;
93}; 91};
94 92
95struct IBenchFreqCallback 93DECLARE_INTERFACE(IBenchFreqCallback)
96{ 94{
97 virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) = 0; 95 virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) = 0;
98 virtual HRESULT FreqsFinished(unsigned numThreads) = 0; 96 virtual HRESULT FreqsFinished(unsigned numThreads) = 0;
99}; 97};
98Z7_PURE_INTERFACES_END
100 99
101HRESULT Bench( 100HRESULT Bench(
102 DECL_EXTERNAL_CODECS_LOC_VARS 101 DECL_EXTERNAL_CODECS_LOC_VARS
@@ -113,7 +112,7 @@ void GetSysInfo(AString &s1, AString &s2);
113void GetCpuName(AString &s); 112void GetCpuName(AString &s);
114void AddCpuFeatures(AString &s); 113void AddCpuFeatures(AString &s);
115 114
116#ifdef _7ZIP_LARGE_PAGES 115#ifdef Z7_LARGE_PAGES
117void Add_LargePages_String(AString &s); 116void Add_LargePages_String(AString &s);
118#else 117#else
119// #define Add_LargePages_String 118// #define Add_LargePages_String
diff --git a/CPP/7zip/UI/Common/CompressCall.cpp b/CPP/7zip/UI/Common/CompressCall.cpp
index 3ef047f..42bae2a 100644
--- a/CPP/7zip/UI/Common/CompressCall.cpp
+++ b/CPP/7zip/UI/Common/CompressCall.cpp
@@ -83,7 +83,7 @@ static HRESULT Call7zGui(const UString &params,
83 const WRes wres = process.Create(imageName, params, NULL); // curDir); 83 const WRes wres = process.Create(imageName, params, NULL); // curDir);
84 if (wres != 0) 84 if (wres != 0)
85 { 85 {
86 HRESULT hres = HRESULT_FROM_WIN32(wres); 86 const HRESULT hres = HRESULT_FROM_WIN32(wres);
87 ErrorMessageHRESULT(hres, imageName); 87 ErrorMessageHRESULT(hres, imageName);
88 return hres; 88 return hres;
89 } 89 }
@@ -92,7 +92,7 @@ static HRESULT Call7zGui(const UString &params,
92 else if (event != NULL) 92 else if (event != NULL)
93 { 93 {
94 HANDLE handles[] = { process, *event }; 94 HANDLE handles[] = { process, *event };
95 ::WaitForMultipleObjects(ARRAY_SIZE(handles), handles, FALSE, INFINITE); 95 ::WaitForMultipleObjects(Z7_ARRAY_SIZE(handles), handles, FALSE, INFINITE);
96 } 96 }
97 return S_OK; 97 return S_OK;
98} 98}
@@ -175,7 +175,7 @@ static HRESULT CreateMap(const UStringVector &names,
175 FOR_VECTOR (i, names) 175 FOR_VECTOR (i, names)
176 { 176 {
177 const UString &s = names[i]; 177 const UString &s = names[i];
178 unsigned len = s.Len() + 1; 178 const unsigned len = s.Len() + 1;
179 wmemcpy(cur, (const wchar_t *)s, len); 179 wmemcpy(cur, (const wchar_t *)s, len);
180 cur += len; 180 cur += len;
181 } 181 }
@@ -197,7 +197,7 @@ HRESULT CompressFiles(
197 CFileMapping fileMapping; 197 CFileMapping fileMapping;
198 NSynchronization::CManualResetEvent event; 198 NSynchronization::CManualResetEvent event;
199 params += kIncludeSwitch; 199 params += kIncludeSwitch;
200 RINOK(CreateMap(names, fileMapping, event, params)); 200 RINOK(CreateMap(names, fileMapping, event, params))
201 201
202 if (!arcType.IsEmpty()) 202 if (!arcType.IsEmpty())
203 { 203 {
@@ -336,7 +336,7 @@ void Benchmark(bool totalMode)
336 if (totalMode) 336 if (totalMode)
337 params += " -mm=*"; 337 params += " -mm=*";
338 AddLagePagesSwitch(params); 338 AddLagePagesSwitch(params);
339 HRESULT result = Call7zGui(params, false, NULL); 339 const HRESULT result = Call7zGui(params, false, NULL);
340 if (result != S_OK) 340 if (result != S_OK)
341 ErrorMessageHRESULT(result); 341 ErrorMessageHRESULT(result);
342 MY_TRY_FINISH_VOID 342 MY_TRY_FINISH_VOID
diff --git a/CPP/7zip/UI/Common/CompressCall.h b/CPP/7zip/UI/Common/CompressCall.h
index 2697fda..f2da163 100644
--- a/CPP/7zip/UI/Common/CompressCall.h
+++ b/CPP/7zip/UI/Common/CompressCall.h
@@ -1,7 +1,7 @@
1// CompressCall.h 1// CompressCall.h
2 2
3#ifndef __COMPRESS_CALL_H 3#ifndef ZIP7_INC_COMPRESS_CALL_H
4#define __COMPRESS_CALL_H 4#define ZIP7_INC_COMPRESS_CALL_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/CompressCall2.cpp b/CPP/7zip/UI/Common/CompressCall2.cpp
index 5d617e1..21eb472 100644
--- a/CPP/7zip/UI/Common/CompressCall2.cpp
+++ b/CPP/7zip/UI/Common/CompressCall2.cpp
@@ -2,6 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifndef Z7_EXTERNAL_CODECS
6
5#include "../../../Common/MyException.h" 7#include "../../../Common/MyException.h"
6 8
7#include "../../UI/Common/EnumDirItems.h" 9#include "../../UI/Common/EnumDirItems.h"
@@ -33,7 +35,7 @@ static void ThrowException_if_Error(HRESULT res)
33 throw CSystemException(res); 35 throw CSystemException(res);
34} 36}
35 37
36#ifdef EXTERNAL_CODECS 38#ifdef Z7_EXTERNAL_CODECS
37 39
38#define CREATE_CODECS \ 40#define CREATE_CODECS \
39 CCodecs *codecs = new CCodecs; \ 41 CCodecs *codecs = new CCodecs; \
@@ -42,10 +44,10 @@ static void ThrowException_if_Error(HRESULT res)
42 Codecs_AddHashArcHandler(codecs); 44 Codecs_AddHashArcHandler(codecs);
43 45
44#define LOAD_EXTERNAL_CODECS \ 46#define LOAD_EXTERNAL_CODECS \
45 CExternalCodecs __externalCodecs; \ 47 CExternalCodecs _externalCodecs; \
46 __externalCodecs.GetCodecs = codecs; \ 48 _externalCodecs.GetCodecs = codecs; \
47 __externalCodecs.GetHashers = codecs; \ 49 _externalCodecs.GetHashers = codecs; \
48 ThrowException_if_Error(__externalCodecs.Load()); 50 ThrowException_if_Error(_externalCodecs.Load());
49 51
50#else 52#else
51 53
@@ -321,3 +323,5 @@ void Benchmark(bool totalMode)
321 323
322 MY_TRY_FINISH 324 MY_TRY_FINISH
323} 325}
326
327#endif
diff --git a/CPP/7zip/UI/Common/DefaultName.h b/CPP/7zip/UI/Common/DefaultName.h
index df16456..46f6e9e 100644
--- a/CPP/7zip/UI/Common/DefaultName.h
+++ b/CPP/7zip/UI/Common/DefaultName.h
@@ -1,7 +1,7 @@
1// DefaultName.h 1// DefaultName.h
2 2
3#ifndef __DEFAULT_NAME_H 3#ifndef ZIP7_INC_DEFAULT_NAME_H
4#define __DEFAULT_NAME_H 4#define ZIP7_INC_DEFAULT_NAME_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/DirItem.h b/CPP/7zip/UI/Common/DirItem.h
index 86e385f..ae84937 100644
--- a/CPP/7zip/UI/Common/DirItem.h
+++ b/CPP/7zip/UI/Common/DirItem.h
@@ -1,7 +1,7 @@
1// DirItem.h 1// DirItem.h
2 2
3#ifndef __DIR_ITEM_H 3#ifndef ZIP7_INC_DIR_ITEM_H
4#define __DIR_ITEM_H 4#define ZIP7_INC_DIR_ITEM_H
5 5
6#ifdef _WIN32 6#ifdef _WIN32
7#include "../../../Common/MyLinux.h" 7#include "../../../Common/MyLinux.h"
@@ -72,15 +72,15 @@ struct CDirItemsStat2: public CDirItemsStat
72}; 72};
73 73
74 74
75Z7_PURE_INTERFACES_BEGIN
75 76
76#define INTERFACE_IDirItemsCallback(x) \ 77#define Z7_IFACEN_IDirItemsCallback(x) \
77 virtual HRESULT ScanError(const FString &path, DWORD systemError) x; \ 78 virtual HRESULT ScanError(const FString &path, DWORD systemError) x \
78 virtual HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) x; \ 79 virtual HRESULT ScanProgress(const CDirItemsStat &st, const FString &path, bool isDir) x \
79 80
80struct IDirItemsCallback 81Z7_IFACE_DECL_PURE(IDirItemsCallback)
81{ 82
82 INTERFACE_IDirItemsCallback(=0) 83Z7_PURE_INTERFACES_END
83};
84 84
85 85
86struct CArcTime 86struct CArcTime
diff --git a/CPP/7zip/UI/Common/EnumDirItems.cpp b/CPP/7zip/UI/Common/EnumDirItems.cpp
index dab3725..d536c47 100644
--- a/CPP/7zip/UI/Common/EnumDirItems.cpp
+++ b/CPP/7zip/UI/Common/EnumDirItems.cpp
@@ -18,7 +18,7 @@
18#include "../../../Windows/FileName.h" 18#include "../../../Windows/FileName.h"
19 19
20#if defined(_WIN32) && !defined(UNDER_CE) 20#if defined(_WIN32) && !defined(UNDER_CE)
21#define _USE_SECURITY_CODE 21#define Z7_USE_SECURITY_CODE
22#include "../../../Windows/SecurityUtils.h" 22#include "../../../Windows/SecurityUtils.h"
23#endif 23#endif
24 24
@@ -183,7 +183,7 @@ CDirItems::CDirItems():
183 , ExcludeDirItems(false) 183 , ExcludeDirItems(false)
184 , ExcludeFileItems(false) 184 , ExcludeFileItems(false)
185 , ShareForWrite(false) 185 , ShareForWrite(false)
186 #ifdef _USE_SECURITY_CODE 186 #ifdef Z7_USE_SECURITY_CODE
187 , ReadSecure(false) 187 , ReadSecure(false)
188 #endif 188 #endif
189 #ifndef _WIN32 189 #ifndef _WIN32
@@ -191,13 +191,13 @@ CDirItems::CDirItems():
191 #endif 191 #endif
192 , Callback(NULL) 192 , Callback(NULL)
193{ 193{
194 #ifdef _USE_SECURITY_CODE 194 #ifdef Z7_USE_SECURITY_CODE
195 _saclEnabled = InitLocalPrivileges(); 195 _saclEnabled = InitLocalPrivileges();
196 #endif 196 #endif
197} 197}
198 198
199 199
200#ifdef _USE_SECURITY_CODE 200#ifdef Z7_USE_SECURITY_CODE
201 201
202HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex) 202HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex)
203{ 203{
@@ -236,7 +236,7 @@ HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex)
236 if (res) 236 if (res)
237 { 237 {
238 if (secureSize != TempSecureBuf.Size()) 238 if (secureSize != TempSecureBuf.Size())
239 errorCode = ERROR_INVALID_FUNCTION;; 239 errorCode = ERROR_INVALID_FUNCTION;
240 } 240 }
241 else 241 else
242 errorCode = GetLastError(); 242 errorCode = GetLastError();
@@ -253,7 +253,7 @@ HRESULT CDirItems::AddSecurityItem(const FString &path, int &secureIndex)
253 return AddError(path, errorCode); 253 return AddError(path, errorCode);
254} 254}
255 255
256#endif // _USE_SECURITY_CODE 256#endif // Z7_USE_SECURITY_CODE
257 257
258 258
259HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind::CFileInfo> &files) 259HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind::CFileInfo> &files)
@@ -277,7 +277,7 @@ HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind
277 files.Add(fi); 277 files.Add(fi);
278 if (Callback && (ttt & kScanProgressStepMask) == kScanProgressStepMask) 278 if (Callback && (ttt & kScanProgressStepMask) == kScanProgressStepMask)
279 { 279 {
280 RINOK(ScanProgress(phyPrefix)); 280 RINOK(ScanProgress(phyPrefix))
281 } 281 }
282 } 282 }
283 283
@@ -309,7 +309,7 @@ HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind
309 { 309 {
310 const FString path = phyPrefix + de.Name; 310 const FString path = phyPrefix + de.Name;
311 { 311 {
312 RINOK(AddError(path)); 312 RINOK(AddError(path))
313 continue; 313 continue;
314 } 314 }
315 } 315 }
@@ -318,7 +318,7 @@ HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind
318 318
319 if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) 319 if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask)
320 { 320 {
321 RINOK(ScanProgress(phyPrefix)); 321 RINOK(ScanProgress(phyPrefix))
322 } 322 }
323 } 323 }
324 324
@@ -332,10 +332,10 @@ HRESULT CDirItems::EnumerateOneDir(const FString &phyPrefix, CObjectVector<NFind
332 332
333HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phyPrefix) 333HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phyPrefix)
334{ 334{
335 RINOK(ScanProgress(phyPrefix)); 335 RINOK(ScanProgress(phyPrefix))
336 336
337 CObjectVector<NFind::CFileInfo> files; 337 CObjectVector<NFind::CFileInfo> files;
338 RINOK(EnumerateOneDir(phyPrefix, files)); 338 RINOK(EnumerateOneDir(phyPrefix, files))
339 339
340 FOR_VECTOR (i, files) 340 FOR_VECTOR (i, files)
341 { 341 {
@@ -361,10 +361,10 @@ HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phy
361 if (CanIncludeItem(fi.IsDir())) 361 if (CanIncludeItem(fi.IsDir()))
362 { 362 {
363 int secureIndex = -1; 363 int secureIndex = -1;
364 #ifdef _USE_SECURITY_CODE 364 #ifdef Z7_USE_SECURITY_CODE
365 if (ReadSecure) 365 if (ReadSecure)
366 { 366 {
367 RINOK(AddSecurityItem(phyPrefix + fi.Name, secureIndex)); 367 RINOK(AddSecurityItem(phyPrefix + fi.Name, secureIndex))
368 } 368 }
369 #endif 369 #endif
370 AddDirFileInfo(phyParent, logParent, secureIndex, fi); 370 AddDirFileInfo(phyParent, logParent, secureIndex, fi);
@@ -372,14 +372,14 @@ HRESULT CDirItems::EnumerateDir(int phyParent, int logParent, const FString &phy
372 372
373 if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) 373 if (Callback && (i & kScanProgressStepMask) == kScanProgressStepMask)
374 { 374 {
375 RINOK(ScanProgress(phyPrefix)); 375 RINOK(ScanProgress(phyPrefix))
376 } 376 }
377 377
378 if (fi.IsDir()) 378 if (fi.IsDir())
379 { 379 {
380 const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR; 380 const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR;
381 unsigned parent = AddPrefix(phyParent, logParent, fs2us(name2)); 381 unsigned parent = AddPrefix(phyParent, logParent, fs2us(name2));
382 RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + name2)); 382 RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + name2))
383 } 383 }
384 } 384 }
385 return S_OK; 385 return S_OK;
@@ -412,6 +412,11 @@ HRESULT CDirItems::EnumerateItems2(
412 const int phyParent = phyPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, fs2us(phyPrefix)); 412 const int phyParent = phyPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, fs2us(phyPrefix));
413 const int logParent = logPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, logPrefix); 413 const int logParent = logPrefix.IsEmpty() ? -1 : (int)AddPrefix(-1, -1, logPrefix);
414 414
415 #ifdef _WIN32
416 const bool phyPrefix_isAltStreamPrefix =
417 NFile::NName::IsAltStreamPrefixWithColon(fs2us(phyPrefix));
418 #endif
419
415 FOR_VECTOR (i, filePaths) 420 FOR_VECTOR (i, filePaths)
416 { 421 {
417 const FString &filePath = filePaths[i]; 422 const FString &filePath = filePaths[i];
@@ -419,7 +424,7 @@ HRESULT CDirItems::EnumerateItems2(
419 const FString phyPath = phyPrefix + filePath; 424 const FString phyPath = phyPrefix + filePath;
420 if (!FindFile_KeepDots(fi, phyPath FOLLOW_LINK_PARAM)) 425 if (!FindFile_KeepDots(fi, phyPath FOLLOW_LINK_PARAM))
421 { 426 {
422 RINOK(AddError(phyPath)); 427 RINOK(AddError(phyPath))
423 continue; 428 continue;
424 } 429 }
425 if (requestedPaths) 430 if (requestedPaths)
@@ -437,20 +442,28 @@ HRESULT CDirItems::EnumerateItems2(
437 if (CanIncludeItem(fi.IsDir())) 442 if (CanIncludeItem(fi.IsDir()))
438 { 443 {
439 int secureIndex = -1; 444 int secureIndex = -1;
440 #ifdef _USE_SECURITY_CODE 445 #ifdef Z7_USE_SECURITY_CODE
441 if (ReadSecure) 446 if (ReadSecure)
442 { 447 {
443 RINOK(AddSecurityItem(phyPath, secureIndex)); 448 RINOK(AddSecurityItem(phyPath, secureIndex))
444 } 449 }
445 #endif 450 #endif
451 #ifdef _WIN32
452 if (phyPrefix_isAltStreamPrefix && fi.IsAltStream)
453 {
454 const int pos = fi.Name.Find(FChar(':'));
455 if (pos >= 0)
456 fi.Name.DeleteFrontal((unsigned)pos + 1);
457 }
458 #endif
446 AddDirFileInfo(phyParentCur, logParent, secureIndex, fi); 459 AddDirFileInfo(phyParentCur, logParent, secureIndex, fi);
447 } 460 }
448 461
449 if (fi.IsDir()) 462 if (fi.IsDir())
450 { 463 {
451 const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR; 464 const FString name2 = fi.Name + FCHAR_PATH_SEPARATOR;
452 unsigned parent = AddPrefix(phyParentCur, logParent, fs2us(name2)); 465 const unsigned parent = AddPrefix(phyParentCur, logParent, fs2us(name2));
453 RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + phyPrefixCur + name2)); 466 RINOK(EnumerateDir((int)parent, (int)parent, phyPrefix + phyPrefixCur + name2))
454 } 467 }
455 } 468 }
456 469
@@ -625,10 +638,10 @@ static HRESULT EnumerateForItem(
625 if (dirItems.CanIncludeItem(fi.IsDir())) 638 if (dirItems.CanIncludeItem(fi.IsDir()))
626 { 639 {
627 int secureIndex = -1; 640 int secureIndex = -1;
628 #ifdef _USE_SECURITY_CODE 641 #ifdef Z7_USE_SECURITY_CODE
629 if (dirItems.ReadSecure) 642 if (dirItems.ReadSecure)
630 { 643 {
631 RINOK(dirItems.AddSecurityItem(phyPrefix + fi.Name, secureIndex)); 644 RINOK(dirItems.AddSecurityItem(phyPrefix + fi.Name, secureIndex))
632 } 645 }
633 #endif 646 #endif
634 #if !defined(UNDER_CE) 647 #if !defined(UNDER_CE)
@@ -654,7 +667,7 @@ static HRESULT EnumerateForItem(
654 if (dirItemIndex >= 0) 667 if (dirItemIndex >= 0)
655 { 668 {
656 CDirItem &dirItem = dirItems.Items[(unsigned)dirItemIndex]; 669 CDirItem &dirItem = dirItems.Items[(unsigned)dirItemIndex];
657 RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)); 670 RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix))
658 if (dirItem.ReparseData.Size() != 0) 671 if (dirItem.ReparseData.Size() != 0)
659 return S_OK; 672 return S_OK;
660 } 673 }
@@ -666,7 +679,7 @@ static HRESULT EnumerateForItem(
666 phyPrefix + fi.Name, // with (fi.Name) 679 phyPrefix + fi.Name, // with (fi.Name)
667 newParts, // with (fi.Name) 680 newParts, // with (fi.Name)
668 addAllSubStreams, 681 addAllSubStreams,
669 dirItems)); 682 dirItems))
670 } 683 }
671 #endif 684 #endif
672 685
@@ -787,7 +800,7 @@ static HRESULT EnumerateDirItems(
787 enterToSubFolders = true; 800 enterToSubFolders = true;
788 } 801 }
789 802
790 RINOK(dirItems.ScanProgress(phyPrefix)); 803 RINOK(dirItems.ScanProgress(phyPrefix))
791 804
792 // try direct_names case at first 805 // try direct_names case at first
793 if (addParts.IsEmpty() && !enterToSubFolders) 806 if (addParts.IsEmpty() && !enterToSubFolders)
@@ -818,7 +831,7 @@ static HRESULT EnumerateDirItems(
818 bool needAltStreams = true; 831 bool needAltStreams = true;
819 #endif 832 #endif
820 833
821 #ifdef _USE_SECURITY_CODE 834 #ifdef Z7_USE_SECURITY_CODE
822 bool needSecurity = true; 835 bool needSecurity = true;
823 #endif 836 #endif
824 837
@@ -838,7 +851,7 @@ static HRESULT EnumerateDirItems(
838 851
839 /* 852 /*
840 // do we need to ignore security info for "\\" folder ? 853 // do we need to ignore security info for "\\" folder ?
841 #ifdef _USE_SECURITY_CODE 854 #ifdef Z7_USE_SECURITY_CODE
842 needSecurity = false; 855 needSecurity = false;
843 #endif 856 #endif
844 */ 857 */
@@ -866,7 +879,7 @@ static HRESULT EnumerateDirItems(
866 #endif 879 #endif
867 if (!FindFile_KeepDots(fi, fullPath FOLLOW_LINK_PARAM2)) 880 if (!FindFile_KeepDots(fi, fullPath FOLLOW_LINK_PARAM2))
868 { 881 {
869 RINOK(dirItems.AddError(fullPath)); 882 RINOK(dirItems.AddError(fullPath))
870 continue; 883 continue;
871 } 884 }
872 885
@@ -884,7 +897,7 @@ static HRESULT EnumerateDirItems(
884 if (isDir ? !item.ForDir : !item.ForFile) 897 if (isDir ? !item.ForDir : !item.ForFile)
885 { 898 {
886 // RINOK(dirItems.AddError(fullPath, isDir ? MY_ERROR_IS_DIR: MY_ERROR_NOT_DIR)); 899 // RINOK(dirItems.AddError(fullPath, isDir ? MY_ERROR_IS_DIR: MY_ERROR_NOT_DIR));
887 RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)); 900 RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR))
888 continue; 901 continue;
889 } 902 }
890 { 903 {
@@ -898,10 +911,10 @@ static HRESULT EnumerateDirItems(
898 if (dirItems.CanIncludeItem(fi.IsDir())) 911 if (dirItems.CanIncludeItem(fi.IsDir()))
899 { 912 {
900 int secureIndex = -1; 913 int secureIndex = -1;
901 #ifdef _USE_SECURITY_CODE 914 #ifdef Z7_USE_SECURITY_CODE
902 if (needSecurity && dirItems.ReadSecure) 915 if (needSecurity && dirItems.ReadSecure)
903 { 916 {
904 RINOK(dirItems.AddSecurityItem(fullPath, secureIndex)); 917 RINOK(dirItems.AddSecurityItem(fullPath, secureIndex))
905 } 918 }
906 #endif 919 #endif
907 920
@@ -912,7 +925,7 @@ static HRESULT EnumerateDirItems(
912 #if !defined(UNDER_CE) 925 #if !defined(UNDER_CE)
913 { 926 {
914 CDirItem &dirItem = dirItems.Items.Back(); 927 CDirItem &dirItem = dirItems.Items.Back();
915 RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix)); 928 RINOK(dirItems.SetLinkInfo(dirItem, fi, phyPrefix))
916 if (dirItem.ReparseData.Size() != 0) 929 if (dirItem.ReparseData.Size() != 0)
917 continue; 930 continue;
918 } 931 }
@@ -926,7 +939,7 @@ static HRESULT EnumerateDirItems(
926 fullPath, // including (name) 939 fullPath, // including (name)
927 pathParts, // including (fi.Name) 940 pathParts, // including (fi.Name)
928 true, /* addAllSubStreams */ 941 true, /* addAllSubStreams */
929 dirItems)); 942 dirItems))
930 } 943 }
931 #endif // defined(_WIN32) 944 #endif // defined(_WIN32)
932 945
@@ -975,9 +988,9 @@ static HRESULT EnumerateDirItems(
975 } 988 }
976 989
977 RINOK(EnumerateDirItems_Spec(*nextNode, phyParent, logParent, fi.Name, phyPrefix, 990 RINOK(EnumerateDirItems_Spec(*nextNode, phyParent, logParent, fi.Name, phyPrefix,
978 newParts, dirItems, true)); 991 newParts, dirItems, true))
979 } 992 }
980 993
981 for (i = 0; i < curNode.SubNodes.Size(); i++) 994 for (i = 0; i < curNode.SubNodes.Size(); i++)
982 { 995 {
983 if (i < needEnterVector.Size()) 996 if (i < needEnterVector.Size())
@@ -987,17 +1000,20 @@ static HRESULT EnumerateDirItems(
987 FString fullPath = phyPrefix + us2fs(nextNode.Name); 1000 FString fullPath = phyPrefix + us2fs(nextNode.Name);
988 NFind::CFileInfo fi; 1001 NFind::CFileInfo fi;
989 1002
990 if (phyPrefix.IsEmpty()) 1003 if (nextNode.Name.IsEmpty())
991 { 1004 {
992 { 1005 if (phyPrefix.IsEmpty())
993 if (nextNode.Name.IsEmpty()) 1006 fullPath = CHAR_PATH_SEPARATOR;
994 fullPath = CHAR_PATH_SEPARATOR; 1007 }
995 #ifdef _WIN32 1008 #ifdef _WIN32
996 else if (NWildcard::IsDriveColonName(nextNode.Name)) 1009 else if(phyPrefix.IsEmpty()
997 fullPath.Add_PathSepar(); 1010 || (phyPrefix.Len() == NName::kSuperPathPrefixSize
998 #endif 1011 && IsSuperPath(phyPrefix)))
999 } 1012 {
1013 if (NWildcard::IsDriveColonName(nextNode.Name))
1014 fullPath.Add_PathSepar();
1000 } 1015 }
1016 #endif
1001 1017
1002 // we don't want to call fi.Find() for root folder or virtual folder 1018 // we don't want to call fi.Find() for root folder or virtual folder
1003 if ((phyPrefix.IsEmpty() && nextNode.Name.IsEmpty()) 1019 if ((phyPrefix.IsEmpty() && nextNode.Name.IsEmpty())
@@ -1015,19 +1031,19 @@ static HRESULT EnumerateDirItems(
1015 { 1031 {
1016 if (!nextNode.AreThereIncludeItems()) 1032 if (!nextNode.AreThereIncludeItems())
1017 continue; 1033 continue;
1018 RINOK(dirItems.AddError(fullPath)); 1034 RINOK(dirItems.AddError(fullPath))
1019 continue; 1035 continue;
1020 } 1036 }
1021 1037
1022 if (!fi.IsDir()) 1038 if (!fi.IsDir())
1023 { 1039 {
1024 RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR)); 1040 RINOK(dirItems.AddError(fullPath, DI_DEFAULT_ERROR))
1025 continue; 1041 continue;
1026 } 1042 }
1027 } 1043 }
1028 1044
1029 RINOK(EnumerateDirItems_Spec(nextNode, phyParent, logParent, fi.Name, phyPrefix, 1045 RINOK(EnumerateDirItems_Spec(nextNode, phyParent, logParent, fi.Name, phyPrefix,
1030 UStringVector(), dirItems, false)); 1046 UStringVector(), dirItems, false))
1031 } 1047 }
1032 1048
1033 return S_OK; 1049 return S_OK;
@@ -1073,7 +1089,7 @@ static HRESULT EnumerateDirItems(
1073 fi.Name = driveName; 1089 fi.Name = driveName;
1074 1090
1075 RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix, 1091 RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix,
1076 addParts, dirItems, enterToSubFolders)); 1092 addParts, dirItems, enterToSubFolders))
1077 } 1093 }
1078 return S_OK; 1094 return S_OK;
1079 } 1095 }
@@ -1088,7 +1104,7 @@ static HRESULT EnumerateDirItems(
1088 // for (int y = 0; y < 1; y++) 1104 // for (int y = 0; y < 1; y++)
1089 { 1105 {
1090 // files.Clear(); 1106 // files.Clear();
1091 RINOK(dirItems.EnumerateOneDir(phyPrefix, files)); 1107 RINOK(dirItems.EnumerateOneDir(phyPrefix, files))
1092 /* 1108 /*
1093 FOR_VECTOR (i, files) 1109 FOR_VECTOR (i, files)
1094 { 1110 {
@@ -1134,10 +1150,10 @@ static HRESULT EnumerateDirItems(
1134 #endif 1150 #endif
1135 1151
1136 RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix, 1152 RINOK(EnumerateForItem(fi, curNode, phyParent, logParent, phyPrefix,
1137 addParts, dirItems, enterToSubFolders)); 1153 addParts, dirItems, enterToSubFolders))
1138 if (dirItems.Callback && (i & kScanProgressStepMask) == kScanProgressStepMask) 1154 if (dirItems.Callback && (i & kScanProgressStepMask) == kScanProgressStepMask)
1139 { 1155 {
1140 RINOK(dirItems.ScanProgress(phyPrefix)); 1156 RINOK(dirItems.ScanProgress(phyPrefix))
1141 } 1157 }
1142 } 1158 }
1143 1159
@@ -1170,16 +1186,16 @@ HRESULT EnumerateItems(
1170 RINOK(EnumerateDirItems(pair.Head, phyParent, logParent, us2fs(pair.Prefix), UStringVector(), 1186 RINOK(EnumerateDirItems(pair.Head, phyParent, logParent, us2fs(pair.Prefix), UStringVector(),
1171 dirItems, 1187 dirItems,
1172 false // enterToSubFolders 1188 false // enterToSubFolders
1173 )); 1189 ))
1174 } 1190 }
1175 dirItems.ReserveDown(); 1191 dirItems.ReserveDown();
1176 1192
1177 #if defined(_WIN32) && !defined(UNDER_CE) 1193 #if defined(_WIN32) && !defined(UNDER_CE)
1178 RINOK(dirItems.FillFixedReparse()); 1194 RINOK(dirItems.FillFixedReparse())
1179 #endif 1195 #endif
1180 1196
1181 #ifndef _WIN32 1197 #ifndef _WIN32
1182 RINOK(dirItems.FillDeviceSizes()); 1198 RINOK(dirItems.FillDeviceSizes())
1183 #endif 1199 #endif
1184 1200
1185 return S_OK; 1201 return S_OK;
@@ -1237,7 +1253,7 @@ HRESULT CDirItems::FillFixedReparse()
1237 } 1253 }
1238 */ 1254 */
1239 1255
1240 RINOK(AddError(phyPath)); 1256 RINOK(AddError(phyPath))
1241 continue; 1257 continue;
1242 } 1258 }
1243 1259
@@ -1485,7 +1501,7 @@ HRESULT EnumerateDirItemsAndSort(
1485 { 1501 {
1486 HRESULT res = EnumerateItems(censor, censorPathMode, addPathPrefix, dirItems); 1502 HRESULT res = EnumerateItems(censor, censorPathMode, addPathPrefix, dirItems);
1487 st = dirItems.Stat; 1503 st = dirItems.Stat;
1488 RINOK(res); 1504 RINOK(res)
1489 } 1505 }
1490 1506
1491 FOR_VECTOR (i, dirItems.Items) 1507 FOR_VECTOR (i, dirItems.Items)
diff --git a/CPP/7zip/UI/Common/EnumDirItems.h b/CPP/7zip/UI/Common/EnumDirItems.h
index 9b17c60..24f1c8b 100644
--- a/CPP/7zip/UI/Common/EnumDirItems.h
+++ b/CPP/7zip/UI/Common/EnumDirItems.h
@@ -1,7 +1,7 @@
1// EnumDirItems.h 1// EnumDirItems.h
2 2
3#ifndef __ENUM_DIR_ITEMS_H 3#ifndef ZIP7_INC_ENUM_DIR_ITEMS_H
4#define __ENUM_DIR_ITEMS_H 4#define ZIP7_INC_ENUM_DIR_ITEMS_H
5 5
6#include "../../../Common/Wildcard.h" 6#include "../../../Common/Wildcard.h"
7 7
diff --git a/CPP/7zip/UI/Common/ExitCode.h b/CPP/7zip/UI/Common/ExitCode.h
index b6d7d4d..2d7b029 100644
--- a/CPP/7zip/UI/Common/ExitCode.h
+++ b/CPP/7zip/UI/Common/ExitCode.h
@@ -1,7 +1,7 @@
1// ExitCode.h 1// ExitCode.h
2 2
3#ifndef __EXIT_CODE_H 3#ifndef ZIP7_INC_EXIT_CODE_H
4#define __EXIT_CODE_H 4#define ZIP7_INC_EXIT_CODE_H
5 5
6namespace NExitCode { 6namespace NExitCode {
7 7
diff --git a/CPP/7zip/UI/Common/Extract.cpp b/CPP/7zip/UI/Common/Extract.cpp
index 58f5218..34b4871 100644
--- a/CPP/7zip/UI/Common/Extract.cpp
+++ b/CPP/7zip/UI/Common/Extract.cpp
@@ -43,6 +43,7 @@ static HRESULT DecompressArchive(
43 const CExtractOptions &options, 43 const CExtractOptions &options,
44 bool calcCrc, 44 bool calcCrc,
45 IExtractCallbackUI *callback, 45 IExtractCallbackUI *callback,
46 IFolderArchiveExtractCallback *callbackFAE,
46 CArchiveExtractCallback *ecs, 47 CArchiveExtractCallback *ecs,
47 UString &errorMessage, 48 UString &errorMessage,
48 UInt64 &stdInProcessed) 49 UInt64 &stdInProcessed)
@@ -94,7 +95,7 @@ static HRESULT DecompressArchive(
94 if (!options.StdInMode) 95 if (!options.StdInMode)
95 { 96 {
96 UInt32 numItems; 97 UInt32 numItems;
97 RINOK(archive->GetNumberOfItems(&numItems)); 98 RINOK(archive->GetNumberOfItems(&numItems))
98 99
99 CReadArcItem item; 100 CReadArcItem item;
100 101
@@ -105,7 +106,7 @@ static HRESULT DecompressArchive(
105 || options.ExcludeDirItems 106 || options.ExcludeDirItems
106 || options.ExcludeFileItems) 107 || options.ExcludeFileItems)
107 { 108 {
108 RINOK(arc.GetItem(i, item)); 109 RINOK(arc.GetItem(i, item))
109 if (item.IsDir ? options.ExcludeDirItems : options.ExcludeFileItems) 110 if (item.IsDir ? options.ExcludeDirItems : options.ExcludeFileItems)
110 continue; 111 continue;
111 } 112 }
@@ -115,7 +116,7 @@ static HRESULT DecompressArchive(
115 item.IsAltStream = false; 116 item.IsAltStream = false;
116 if (!options.NtOptions.AltStreams.Val && arc.Ask_AltStream) 117 if (!options.NtOptions.AltStreams.Val && arc.Ask_AltStream)
117 { 118 {
118 RINOK(Archive_IsItem_AltStream(arc.Archive, i, item.IsAltStream)); 119 RINOK(Archive_IsItem_AltStream(arc.Archive, i, item.IsAltStream))
119 } 120 }
120 #endif 121 #endif
121 } 122 }
@@ -194,7 +195,7 @@ static HRESULT DecompressArchive(
194 options.NtOptions, 195 options.NtOptions,
195 options.StdInMode ? &wildcardCensor : NULL, 196 options.StdInMode ? &wildcardCensor : NULL,
196 &arc, 197 &arc,
197 callback, 198 callbackFAE,
198 options.StdOutMode, options.TestMode, 199 options.StdOutMode, options.TestMode,
199 outDir, 200 outDir,
200 removePathParts, false, 201 removePathParts, false,
@@ -207,14 +208,14 @@ static HRESULT DecompressArchive(
207 !options.TestMode && 208 !options.TestMode &&
208 options.NtOptions.HardLinks.Val) 209 options.NtOptions.HardLinks.Val)
209 { 210 {
210 RINOK(ecs->PrepareHardLinks(&realIndices)); 211 RINOK(ecs->PrepareHardLinks(&realIndices))
211 } 212 }
212 213
213 #endif 214 #endif
214 215
215 216
216 HRESULT result; 217 HRESULT result;
217 Int32 testMode = (options.TestMode && !calcCrc) ? 1: 0; 218 const Int32 testMode = (options.TestMode && !calcCrc) ? 1: 0;
218 219
219 CArchiveExtractCallback_Closer ecsCloser(ecs); 220 CArchiveExtractCallback_Closer ecsCloser(ecs);
220 221
@@ -228,7 +229,7 @@ static HRESULT DecompressArchive(
228 else 229 else
229 result = archive->Extract(&realIndices.Front(), realIndices.Size(), testMode, ecs); 230 result = archive->Extract(&realIndices.Front(), realIndices.Size(), testMode, ecs);
230 231
231 HRESULT res2 = ecsCloser.Close(); 232 const HRESULT res2 = ecsCloser.Close();
232 if (result == S_OK) 233 if (result == S_OK)
233 result = res2; 234 result = res2;
234 235
@@ -270,7 +271,8 @@ HRESULT Extract(
270 const CExtractOptions &options, 271 const CExtractOptions &options,
271 IOpenCallbackUI *openCallback, 272 IOpenCallbackUI *openCallback,
272 IExtractCallbackUI *extractCallback, 273 IExtractCallbackUI *extractCallback,
273 #ifndef _SFX 274 IFolderArchiveExtractCallback *faeCallback,
275 #ifndef Z7_SFX
274 IHashCalc *hash, 276 IHashCalc *hash,
275 #endif 277 #endif
276 UString &errorMessage, 278 UString &errorMessage,
@@ -323,13 +325,13 @@ HRESULT Extract(
323 options.ZoneMode, 325 options.ZoneMode,
324 false // keepEmptyDirParts 326 false // keepEmptyDirParts
325 ); 327 );
326 #ifndef _SFX 328 #ifndef Z7_SFX
327 ecs->SetHashMethods(hash); 329 ecs->SetHashMethods(hash);
328 #endif 330 #endif
329 331
330 if (multi) 332 if (multi)
331 { 333 {
332 RINOK(extractCallback->SetTotal(totalPackSize)); 334 RINOK(faeCallback->SetTotal(totalPackSize))
333 } 335 }
334 336
335 UInt64 totalPackProcessed = 0; 337 UInt64 totalPackProcessed = 0;
@@ -364,17 +366,17 @@ HRESULT Extract(
364 } 366 }
365 367
366 /* 368 /*
367 #ifndef _NO_CRYPTO 369 #ifndef Z7_NO_CRYPTO
368 openCallback->Open_Clear_PasswordWasAsked_Flag(); 370 openCallback->Open_Clear_PasswordWasAsked_Flag();
369 #endif 371 #endif
370 */ 372 */
371 373
372 RINOK(extractCallback->BeforeOpen(arcPath, options.TestMode)); 374 RINOK(extractCallback->BeforeOpen(arcPath, options.TestMode))
373 CArchiveLink arcLink; 375 CArchiveLink arcLink;
374 376
375 CObjectVector<COpenType> types2 = types; 377 CObjectVector<COpenType> types2 = types;
376 /* 378 /*
377 #ifndef _SFX 379 #ifndef Z7_SFX
378 if (types.IsEmpty()) 380 if (types.IsEmpty())
379 { 381 {
380 int pos = arcPath.ReverseFind(L'.'); 382 int pos = arcPath.ReverseFind(L'.');
@@ -402,7 +404,7 @@ HRESULT Extract(
402 */ 404 */
403 405
404 COpenOptions op; 406 COpenOptions op;
405 #ifndef _SFX 407 #ifndef Z7_SFX
406 op.props = &options.Properties; 408 op.props = &options.Properties;
407 #endif 409 #endif
408 op.codecs = codecs; 410 op.codecs = codecs;
@@ -418,7 +420,7 @@ HRESULT Extract(
418 return result; 420 return result;
419 421
420 // arcLink.Set_ErrorsText(); 422 // arcLink.Set_ErrorsText();
421 RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, result)); 423 RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, result))
422 424
423 if (result != S_OK) 425 if (result != S_OK)
424 { 426 {
@@ -428,7 +430,7 @@ HRESULT Extract(
428 continue; 430 continue;
429 } 431 }
430 432
431 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(_SFX) 433 #if defined(_WIN32) && !defined(UNDER_CE) && !defined(Z7_SFX)
432 if (options.ZoneMode != NExtract::NZoneIdMode::kNone 434 if (options.ZoneMode != NExtract::NZoneIdMode::kNone
433 && !options.StdInMode) 435 && !options.StdInMode)
434 { 436 {
@@ -446,7 +448,13 @@ HRESULT Extract(
446 /* real Extracting to files is possible. 448 /* real Extracting to files is possible.
447 But user can think that hash archive contains real files. 449 But user can think that hash archive contains real files.
448 So we block extracting here. */ 450 So we block extracting here. */
449 return E_NOTIMPL; 451 // v23.00 : we don't break process.
452 RINOK(extractCallback->OpenResult(codecs, arcLink, arcPath, E_NOTIMPL))
453 thereAreNotOpenArcs = true;
454 if (!options.StdInMode)
455 totalPackProcessed += fi.Size;
456 continue;
457 // return E_NOTIMPL; // before v23
450 } 458 }
451 FString dirPrefix = us2fs(options.HashDir); 459 FString dirPrefix = us2fs(options.HashDir);
452 if (dirPrefix.IsEmpty()) 460 if (dirPrefix.IsEmpty())
@@ -490,7 +498,7 @@ HRESULT Extract(
490 if (newPackSize < 0) 498 if (newPackSize < 0)
491 newPackSize = 0; 499 newPackSize = 0;
492 totalPackSize = (UInt64)newPackSize; 500 totalPackSize = (UInt64)newPackSize;
493 RINOK(extractCallback->SetTotal(totalPackSize)); 501 RINOK(faeCallback->SetTotal(totalPackSize))
494 } 502 }
495 } 503 }
496 } 504 }
@@ -498,13 +506,13 @@ HRESULT Extract(
498 /* 506 /*
499 // Now openCallback and extractCallback use same object. So we don't need to send password. 507 // Now openCallback and extractCallback use same object. So we don't need to send password.
500 508
501 #ifndef _NO_CRYPTO 509 #ifndef Z7_NO_CRYPTO
502 bool passwordIsDefined; 510 bool passwordIsDefined;
503 UString password; 511 UString password;
504 RINOK(openCallback->Open_GetPasswordIfAny(passwordIsDefined, password)); 512 RINOK(openCallback->Open_GetPasswordIfAny(passwordIsDefined, password))
505 if (passwordIsDefined) 513 if (passwordIsDefined)
506 { 514 {
507 RINOK(extractCallback->SetPassword(password)); 515 RINOK(extractCallback->SetPassword(password))
508 } 516 }
509 #endif 517 #endif
510 */ 518 */
@@ -520,7 +528,7 @@ HRESULT Extract(
520 528
521 UInt64 packProcessed; 529 UInt64 packProcessed;
522 const bool calcCrc = 530 const bool calcCrc =
523 #ifndef _SFX 531 #ifndef Z7_SFX
524 (hash != NULL); 532 (hash != NULL);
525 #else 533 #else
526 false; 534 false;
@@ -533,7 +541,8 @@ HRESULT Extract(
533 wildcardCensor, 541 wildcardCensor,
534 options, 542 options,
535 calcCrc, 543 calcCrc,
536 extractCallback, ecs, errorMessage, packProcessed)); 544 extractCallback, faeCallback, ecs,
545 errorMessage, packProcessed))
537 546
538 if (!options.StdInMode) 547 if (!options.StdInMode)
539 packProcessed = fi.Size + arcLink.VolumesSize; 548 packProcessed = fi.Size + arcLink.VolumesSize;
@@ -546,8 +555,8 @@ HRESULT Extract(
546 555
547 if (multi || thereAreNotOpenArcs) 556 if (multi || thereAreNotOpenArcs)
548 { 557 {
549 RINOK(extractCallback->SetTotal(totalPackSize)); 558 RINOK(faeCallback->SetTotal(totalPackSize))
550 RINOK(extractCallback->SetCompleted(&totalPackProcessed)); 559 RINOK(faeCallback->SetCompleted(&totalPackProcessed))
551 } 560 }
552 561
553 st.NumFolders = ecs->NumFolders; 562 st.NumFolders = ecs->NumFolders;
diff --git a/CPP/7zip/UI/Common/Extract.h b/CPP/7zip/UI/Common/Extract.h
index f3d1126..b20f607 100644
--- a/CPP/7zip/UI/Common/Extract.h
+++ b/CPP/7zip/UI/Common/Extract.h
@@ -1,7 +1,7 @@
1// Extract.h 1// Extract.h
2 2
3#ifndef __EXTRACT_H 3#ifndef ZIP7_INC_EXTRACT_H
4#define __EXTRACT_H 4#define ZIP7_INC_EXTRACT_H
5 5
6#include "../../../Windows/FileFind.h" 6#include "../../../Windows/FileFind.h"
7 7
@@ -52,12 +52,12 @@ struct CExtractOptions: public CExtractOptionsBase
52 // bool ShowDialog; 52 // bool ShowDialog;
53 // bool PasswordEnabled; 53 // bool PasswordEnabled;
54 // UString Password; 54 // UString Password;
55 #ifndef _SFX 55 #ifndef Z7_SFX
56 CObjectVector<CProperty> Properties; 56 CObjectVector<CProperty> Properties;
57 #endif 57 #endif
58 58
59 /* 59 /*
60 #ifdef EXTERNAL_CODECS 60 #ifdef Z7_EXTERNAL_CODECS
61 CCodecs *Codecs; 61 CCodecs *Codecs;
62 #endif 62 #endif
63 */ 63 */
@@ -96,7 +96,8 @@ HRESULT Extract(
96 const CExtractOptions &options, 96 const CExtractOptions &options,
97 IOpenCallbackUI *openCallback, 97 IOpenCallbackUI *openCallback,
98 IExtractCallbackUI *extractCallback, 98 IExtractCallbackUI *extractCallback,
99 #ifndef _SFX 99 IFolderArchiveExtractCallback *faeCallback,
100 #ifndef Z7_SFX
100 IHashCalc *hash, 101 IHashCalc *hash,
101 #endif 102 #endif
102 UString &errorMessage, 103 UString &errorMessage,
diff --git a/CPP/7zip/UI/Common/ExtractMode.h b/CPP/7zip/UI/Common/ExtractMode.h
index 9ad831e..6e38f26 100644
--- a/CPP/7zip/UI/Common/ExtractMode.h
+++ b/CPP/7zip/UI/Common/ExtractMode.h
@@ -1,7 +1,7 @@
1// ExtractMode.h 1// ExtractMode.h
2 2
3#ifndef __EXTRACT_MODE_H 3#ifndef ZIP7_INC_EXTRACT_MODE_H
4#define __EXTRACT_MODE_H 4#define ZIP7_INC_EXTRACT_MODE_H
5 5
6namespace NExtract { 6namespace NExtract {
7 7
diff --git a/CPP/7zip/UI/Common/ExtractingFilePath.cpp b/CPP/7zip/UI/Common/ExtractingFilePath.cpp
index a1282b7..88da4ad 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[] =
124 124
125static bool IsSupportedName(const UString &name) 125static bool IsSupportedName(const UString &name)
126{ 126{
127 for (unsigned i = 0; i < ARRAY_SIZE(g_ReservedNames); i++) 127 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_ReservedNames); i++)
128 { 128 {
129 const char *reservedName = g_ReservedNames[i]; 129 const char *reservedName = g_ReservedNames[i];
130 unsigned len = MyStringLen(reservedName); 130 unsigned len = MyStringLen(reservedName);
diff --git a/CPP/7zip/UI/Common/ExtractingFilePath.h b/CPP/7zip/UI/Common/ExtractingFilePath.h
index 8f8f9f1..bb1732f 100644
--- a/CPP/7zip/UI/Common/ExtractingFilePath.h
+++ b/CPP/7zip/UI/Common/ExtractingFilePath.h
@@ -1,7 +1,7 @@
1// ExtractingFilePath.h 1// ExtractingFilePath.h
2 2
3#ifndef __EXTRACTING_FILE_PATH_H 3#ifndef ZIP7_INC_EXTRACTING_FILE_PATH_H
4#define __EXTRACTING_FILE_PATH_H 4#define ZIP7_INC_EXTRACTING_FILE_PATH_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/HashCalc.cpp b/CPP/7zip/UI/Common/HashCalc.cpp
index f0aa4bd..94c8a06 100644
--- a/CPP/7zip/UI/Common/HashCalc.cpp
+++ b/CPP/7zip/UI/Common/HashCalc.cpp
@@ -22,7 +22,7 @@
22 22
23using namespace NWindows; 23using namespace NWindows;
24 24
25#ifdef EXTERNAL_CODECS 25#ifdef Z7_EXTERNAL_CODECS
26extern const CExternalCodecs *g_ExternalCodecs_Ptr; 26extern const CExternalCodecs *g_ExternalCodecs_Ptr;
27#endif 27#endif
28 28
@@ -57,7 +57,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto
57 for (i = 0; i < names.Size(); i++) 57 for (i = 0; i < names.Size(); i++)
58 { 58 {
59 COneMethodInfo m; 59 COneMethodInfo m;
60 RINOK(m.ParseMethodFromString(names[i])); 60 RINOK(m.ParseMethodFromString(names[i]))
61 61
62 if (m.MethodName.IsEmpty()) 62 if (m.MethodName.IsEmpty())
63 m.MethodName = k_DefaultHashMethod; 63 m.MethodName = k_DefaultHashMethod;
@@ -92,7 +92,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto
92 { 92 {
93 CMyComPtr<IHasher> hasher; 93 CMyComPtr<IHasher> hasher;
94 AString name; 94 AString name;
95 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS ids[i], name, hasher)); 95 RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS ids[i], name, hasher))
96 if (!hasher) 96 if (!hasher)
97 throw "Can't create hasher"; 97 throw "Can't create hasher";
98 const COneMethodInfo &m = methods[i]; 98 const COneMethodInfo &m = methods[i];
@@ -100,7 +100,7 @@ HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVecto
100 CMyComPtr<ICompressSetCoderProperties> scp; 100 CMyComPtr<ICompressSetCoderProperties> scp;
101 hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp); 101 hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp);
102 if (scp) 102 if (scp)
103 RINOK(m.SetCoderProps(scp, NULL)); 103 RINOK(m.SetCoderProps(scp, NULL))
104 } 104 }
105 const UInt32 digestSize = hasher->GetDigestSize(); 105 const UInt32 digestSize = hasher->GetDigestSize();
106 if (digestSize > k_HashCalc_DigestSize_Max) 106 if (digestSize > k_HashCalc_DigestSize_Max)
@@ -330,14 +330,14 @@ static void AddHashResultLine(
330 if (numSpaces > 0) 330 if (numSpaces > 0)
331 SetSpacesAndNul(s + pos, (unsigned)numSpaces); 331 SetSpacesAndNul(s + pos, (unsigned)numSpaces);
332 if (i != 0) 332 if (i != 0)
333 _s += ' '; 333 _s.Add_Space();
334 _s += s; 334 _s += s;
335 } 335 }
336 336
337 /* 337 /*
338 if (showSize) 338 if (showSize)
339 { 339 {
340 _s += ' '; 340 _s.Add_Space();
341 static const unsigned kSizeField_Len = 13; // same as in HashCon.cpp 341 static const unsigned kSizeField_Len = 13; // same as in HashCon.cpp
342 char s[kSizeField_Len + 32]; 342 char s[kSizeField_Len + 32];
343 char *p = s; 343 char *p = s;
@@ -467,7 +467,7 @@ HRESULT HashCalc(
467 } 467 }
468 else 468 else
469 { 469 {
470 RINOK(callback->StartScanning()); 470 RINOK(callback->StartScanning())
471 471
472 dirItems.SymLinks = options.SymLinks.Val; 472 dirItems.SymLinks = options.SymLinks.Val;
473 dirItems.ScanAltStreams = options.AltStreamsMode; 473 dirItems.ScanAltStreams = options.AltStreamsMode;
@@ -487,12 +487,12 @@ HRESULT HashCalc(
487 errorInfo = "Scanning error"; 487 errorInfo = "Scanning error";
488 return res; 488 return res;
489 } 489 }
490 RINOK(callback->FinishScanning(dirItems.Stat)); 490 RINOK(callback->FinishScanning(dirItems.Stat))
491 } 491 }
492 492
493 unsigned i; 493 unsigned i;
494 CHashBundle hb; 494 CHashBundle hb;
495 RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS options.Methods)); 495 RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS options.Methods))
496 // hb.Init(); 496 // hb.Init();
497 497
498 hb.NumErrors = dirItems.Stat.NumErrors; 498 hb.NumErrors = dirItems.Stat.NumErrors;
@@ -500,12 +500,12 @@ HRESULT HashCalc(
500 UInt64 totalSize = 0; 500 UInt64 totalSize = 0;
501 if (options.StdInMode) 501 if (options.StdInMode)
502 { 502 {
503 RINOK(callback->SetNumFiles(1)); 503 RINOK(callback->SetNumFiles(1))
504 } 504 }
505 else 505 else
506 { 506 {
507 totalSize = dirItems.Stat.GetTotalBytes(); 507 totalSize = dirItems.Stat.GetTotalBytes();
508 RINOK(callback->SetTotal(totalSize)); 508 RINOK(callback->SetTotal(totalSize))
509 } 509 }
510 510
511 const UInt32 kBufSize = 1 << 15; 511 const UInt32 kBufSize = 1 << 15;
@@ -515,7 +515,7 @@ HRESULT HashCalc(
515 515
516 UInt64 completeValue = 0; 516 UInt64 completeValue = 0;
517 517
518 RINOK(callback->BeforeFirstFile(hb)); 518 RINOK(callback->BeforeFirstFile(hb))
519 519
520 /* 520 /*
521 CDynLimBuf hashFileString((size_t)1 << 31); 521 CDynLimBuf hashFileString((size_t)1 << 31);
@@ -575,7 +575,7 @@ HRESULT HashCalc(
575 if (curSize > di.Size) 575 if (curSize > di.Size)
576 { 576 {
577 totalSize += curSize - di.Size; 577 totalSize += curSize - di.Size;
578 RINOK(callback->SetTotal(totalSize)); 578 RINOK(callback->SetTotal(totalSize))
579 // printf("\ntotal = %d MiB\n", (unsigned)(totalSize >> 20)); 579 // printf("\ntotal = %d MiB\n", (unsigned)(totalSize >> 20));
580 } 580 }
581 } 581 }
@@ -585,7 +585,7 @@ HRESULT HashCalc(
585 } 585 }
586 } 586 }
587 587
588 RINOK(callback->GetStream(path, isDir)); 588 RINOK(callback->GetStream(path, isDir))
589 UInt64 fileSize = 0; 589 UInt64 fileSize = 0;
590 590
591 hb.InitForNewFile(); 591 hb.InitForNewFile();
@@ -597,10 +597,10 @@ HRESULT HashCalc(
597 if ((step & 0xFF) == 0) 597 if ((step & 0xFF) == 0)
598 { 598 {
599 // printf("\ncompl = %d\n", (unsigned)(completeValue >> 20)); 599 // printf("\ncompl = %d\n", (unsigned)(completeValue >> 20));
600 RINOK(callback->SetCompleted(&completeValue)); 600 RINOK(callback->SetCompleted(&completeValue))
601 } 601 }
602 UInt32 size; 602 UInt32 size;
603 RINOK(inStream->Read(buf, kBufSize, &size)); 603 RINOK(inStream->Read(buf, kBufSize, &size))
604 if (size == 0) 604 if (size == 0)
605 break; 605 break;
606 hb.Update(buf, size); 606 hb.Update(buf, size);
@@ -626,8 +626,8 @@ HRESULT HashCalc(
626 } 626 }
627 */ 627 */
628 628
629 RINOK(callback->SetOperationResult(fileSize, hb, !isDir)); 629 RINOK(callback->SetOperationResult(fileSize, hb, !isDir))
630 RINOK(callback->SetCompleted(&completeValue)); 630 RINOK(callback->SetCompleted(&completeValue))
631 } 631 }
632 632
633 /* 633 /*
@@ -776,7 +776,7 @@ bool CHashPair::ParseCksum(const char *s)
776 Name = end; 776 Name = end;
777 777
778 Hash.Alloc(4); 778 Hash.Alloc(4);
779 SetBe32(Hash, crc); 779 SetBe32(Hash, crc)
780 780
781 Size_from_Arc = size; 781 Size_from_Arc = size;
782 Size_from_Arc_Defined = true; 782 Size_from_Arc_Defined = true;
@@ -823,7 +823,7 @@ static UString GetMethod_from_FileName(const UString &name)
823 } 823 }
824 const char *m = ""; 824 const char *m = "";
825 unsigned i; 825 unsigned i;
826 for (i = 0; i < ARRAY_SIZE(k_CsumMethodNames); i++) 826 for (i = 0; i < Z7_ARRAY_SIZE(k_CsumMethodNames); i++)
827 { 827 {
828 m = k_CsumMethodNames[i]; 828 m = k_CsumMethodNames[i];
829 if (isExtension) 829 if (isExtension)
@@ -836,7 +836,7 @@ static UString GetMethod_from_FileName(const UString &name)
836 break; 836 break;
837 } 837 }
838 UString res; 838 UString res;
839 if (i != ARRAY_SIZE(k_CsumMethodNames)) 839 if (i != Z7_ARRAY_SIZE(k_CsumMethodNames))
840 res = m; 840 res = m;
841 return res; 841 return res;
842} 842}
@@ -1033,27 +1033,27 @@ static const Byte kRawProps[] =
1033}; 1033};
1034 1034
1035 1035
1036STDMETHODIMP CHandler::GetParent(UInt32 /* index */ , UInt32 *parent, UInt32 *parentType) 1036Z7_COM7F_IMF(CHandler::GetParent(UInt32 /* index */ , UInt32 *parent, UInt32 *parentType))
1037{ 1037{
1038 *parentType = NParentType::kDir; 1038 *parentType = NParentType::kDir;
1039 *parent = (UInt32)(Int32)-1; 1039 *parent = (UInt32)(Int32)-1;
1040 return S_OK; 1040 return S_OK;
1041} 1041}
1042 1042
1043STDMETHODIMP CHandler::GetNumRawProps(UInt32 *numProps) 1043Z7_COM7F_IMF(CHandler::GetNumRawProps(UInt32 *numProps))
1044{ 1044{
1045 *numProps = ARRAY_SIZE(kRawProps); 1045 *numProps = Z7_ARRAY_SIZE(kRawProps);
1046 return S_OK; 1046 return S_OK;
1047} 1047}
1048 1048
1049STDMETHODIMP CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID) 1049Z7_COM7F_IMF(CHandler::GetRawPropInfo(UInt32 index, BSTR *name, PROPID *propID))
1050{ 1050{
1051 *propID = kRawProps[index]; 1051 *propID = kRawProps[index];
1052 *name = 0; 1052 *name = NULL;
1053 return S_OK; 1053 return S_OK;
1054} 1054}
1055 1055
1056STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 1056Z7_COM7F_IMF(CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
1057{ 1057{
1058 *data = NULL; 1058 *data = NULL;
1059 *dataSize = 0; 1059 *dataSize = 0;
@@ -1077,7 +1077,7 @@ STDMETHODIMP CHandler::GetRawProp(UInt32 index, PROPID propID, const void **data
1077IMP_IInArchive_Props 1077IMP_IInArchive_Props
1078IMP_IInArchive_ArcProps 1078IMP_IInArchive_ArcProps
1079 1079
1080STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 1080Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
1081{ 1081{
1082 *numItems = HashPairs.Size(); 1082 *numItems = HashPairs.Size();
1083 return S_OK; 1083 return S_OK;
@@ -1089,7 +1089,7 @@ static void Add_OptSpace_String(UString &dest, const char *src)
1089 dest += src; 1089 dest += src;
1090} 1090}
1091 1091
1092STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) 1092Z7_COM7F_IMF(CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value))
1093{ 1093{
1094 NWindows::NCOM::CPropVariant prop; 1094 NWindows::NCOM::CPropVariant prop;
1095 switch (propID) 1095 switch (propID)
@@ -1152,7 +1152,7 @@ STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
1152} 1152}
1153 1153
1154 1154
1155STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 1155Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
1156{ 1156{
1157 // COM_TRY_BEGIN 1157 // COM_TRY_BEGIN
1158 NWindows::NCOM::CPropVariant prop; 1158 NWindows::NCOM::CPropVariant prop;
@@ -1206,10 +1206,9 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp
1206{ 1206{
1207 buf.Free(); 1207 buf.Free();
1208 UInt64 len; 1208 UInt64 len;
1209 RINOK(stream->Seek(0, STREAM_SEEK_END, &len)); 1209 RINOK(InStream_AtBegin_GetSize(stream, len))
1210 if (len == 0 || len >= ((UInt64)1 << 31)) 1210 if (len == 0 || len >= ((UInt64)1 << 31))
1211 return S_FALSE; 1211 return S_FALSE;
1212 RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
1213 buf.Alloc((size_t)len); 1212 buf.Alloc((size_t)len);
1214 UInt64 pos = 0; 1213 UInt64 pos = 0;
1215 // return ReadStream_FALSE(stream, buf, (size_t)len); 1214 // return ReadStream_FALSE(stream, buf, (size_t)len);
@@ -1218,7 +1217,7 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp
1218 const UInt32 kBlockSize = ((UInt32)1 << 24); 1217 const UInt32 kBlockSize = ((UInt32)1 << 24);
1219 const UInt32 curSize = (len < kBlockSize) ? (UInt32)len : kBlockSize; 1218 const UInt32 curSize = (len < kBlockSize) ? (UInt32)len : kBlockSize;
1220 UInt32 processedSizeLoc; 1219 UInt32 processedSizeLoc;
1221 RINOK(stream->Read((Byte *)buf + pos, curSize, &processedSizeLoc)); 1220 RINOK(stream->Read((Byte *)buf + pos, curSize, &processedSizeLoc))
1222 if (processedSizeLoc == 0) 1221 if (processedSizeLoc == 0)
1223 return E_FAIL; 1222 return E_FAIL;
1224 len -= processedSizeLoc; 1223 len -= processedSizeLoc;
@@ -1228,13 +1227,13 @@ static HRESULT ReadStream_to_Buf(IInStream *stream, CByteBuffer &buf, IArchiveOp
1228 if (openCallback) 1227 if (openCallback)
1229 { 1228 {
1230 const UInt64 files = 0; 1229 const UInt64 files = 0;
1231 RINOK(openCallback->SetCompleted(&files, &pos)); 1230 RINOK(openCallback->SetCompleted(&files, &pos))
1232 } 1231 }
1233 } 1232 }
1234} 1233}
1235 1234
1236 1235
1237STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback) 1236Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openCallback))
1238{ 1237{
1239 COM_TRY_BEGIN 1238 COM_TRY_BEGIN
1240 { 1239 {
@@ -1261,12 +1260,13 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
1261 1260
1262 if (openCallback) 1261 if (openCallback)
1263 { 1262 {
1264 CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback; 1263 Z7_DECL_CMyComPtr_QI_FROM(
1265 openCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); 1264 IArchiveOpenVolumeCallback,
1266 NCOM::CPropVariant prop; 1265 openVolumeCallback, openCallback)
1267 if (openVolumeCallback) 1266 if (openVolumeCallback)
1268 { 1267 {
1269 RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); 1268 NCOM::CPropVariant prop;
1269 RINOK(openVolumeCallback->GetProperty(kpidName, &prop))
1270 if (prop.vt == VT_BSTR) 1270 if (prop.vt == VT_BSTR)
1271 _nameExtenstion = GetMethod_from_FileName(prop.bstrVal); 1271 _nameExtenstion = GetMethod_from_FileName(prop.bstrVal);
1272 } 1272 }
@@ -1376,7 +1376,7 @@ void CHandler::ClearVars()
1376} 1376}
1377 1377
1378 1378
1379STDMETHODIMP CHandler::Close() 1379Z7_COM7F_IMF(CHandler::Close())
1380{ 1380{
1381 ClearVars(); 1381 ClearVars();
1382 _nameExtenstion.Empty(); 1382 _nameExtenstion.Empty();
@@ -1416,8 +1416,8 @@ static void AddDefaultMethod(UStringVector &methods, unsigned size)
1416 else if (size == 4) m = "crc32"; 1416 else if (size == 4) m = "crc32";
1417 else 1417 else
1418 return; 1418 return;
1419 #ifdef EXTERNAL_CODECS 1419 #ifdef Z7_EXTERNAL_CODECS
1420 const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; 1420 const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr;
1421 #endif 1421 #endif
1422 CMethodId id; 1422 CMethodId id;
1423 if (FindHashMethod(EXTERNAL_CODECS_LOC_VARS 1423 if (FindHashMethod(EXTERNAL_CODECS_LOC_VARS
@@ -1426,8 +1426,8 @@ static void AddDefaultMethod(UStringVector &methods, unsigned size)
1426} 1426}
1427 1427
1428 1428
1429STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems, 1429Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1430 Int32 testMode, IArchiveExtractCallback *extractCallback) 1430 Int32 testMode, IArchiveExtractCallback *extractCallback))
1431{ 1431{
1432 COM_TRY_BEGIN 1432 COM_TRY_BEGIN
1433 1433
@@ -1442,8 +1442,8 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1442 if (numItems == 0) 1442 if (numItems == 0)
1443 return S_OK; 1443 return S_OK;
1444 1444
1445 #ifdef EXTERNAL_CODECS 1445 #ifdef Z7_EXTERNAL_CODECS
1446 const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; 1446 const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr;
1447 #endif 1447 #endif
1448 1448
1449 CHashBundle hb_Glob; 1449 CHashBundle hb_Glob;
@@ -1471,15 +1471,17 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1471 1471
1472 RINOK(hb_Glob.SetMethods( 1472 RINOK(hb_Glob.SetMethods(
1473 EXTERNAL_CODECS_LOC_VARS 1473 EXTERNAL_CODECS_LOC_VARS
1474 methods)); 1474 methods))
1475 1475
1476 CMyComPtr<IArchiveUpdateCallbackFile> updateCallbackFile; 1476 Z7_DECL_CMyComPtr_QI_FROM(
1477 extractCallback->QueryInterface(IID_IArchiveUpdateCallbackFile, (void **)&updateCallbackFile); 1477 IArchiveUpdateCallbackFile,
1478 updateCallbackFile, extractCallback)
1478 if (!updateCallbackFile) 1479 if (!updateCallbackFile)
1479 return E_NOTIMPL; 1480 return E_NOTIMPL;
1480 { 1481 {
1481 CMyComPtr<IArchiveGetDiskProperty> GetDiskProperty; 1482 Z7_DECL_CMyComPtr_QI_FROM(
1482 extractCallback->QueryInterface(IID_IArchiveGetDiskProperty, (void **)&GetDiskProperty); 1483 IArchiveGetDiskProperty,
1484 GetDiskProperty, extractCallback)
1483 if (GetDiskProperty) 1485 if (GetDiskProperty)
1484 { 1486 {
1485 UInt64 totalSize = 0; 1487 UInt64 totalSize = 0;
@@ -1492,13 +1494,13 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1492 continue; 1494 continue;
1493 { 1495 {
1494 NCOM::CPropVariant prop; 1496 NCOM::CPropVariant prop;
1495 RINOK(GetDiskProperty->GetDiskProperty(index, kpidSize, &prop)); 1497 RINOK(GetDiskProperty->GetDiskProperty(index, kpidSize, &prop))
1496 if (prop.vt != VT_UI8) 1498 if (prop.vt != VT_UI8)
1497 continue; 1499 continue;
1498 totalSize += prop.uhVal.QuadPart; 1500 totalSize += prop.uhVal.QuadPart;
1499 } 1501 }
1500 } 1502 }
1501 RINOK(extractCallback->SetTotal(totalSize)); 1503 RINOK(extractCallback->SetTotal(totalSize))
1502 // RINOK(Hash_SetTotalUnpacked->Hash_SetTotalUnpacked(indices, numItems)); 1504 // RINOK(Hash_SetTotalUnpacked->Hash_SetTotalUnpacked(indices, numItems));
1503 } 1505 }
1504 } 1506 }
@@ -1516,7 +1518,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1516 UInt32 i; 1518 UInt32 i;
1517 for (i = 0; i < numItems; i++) 1519 for (i = 0; i < numItems; i++)
1518 { 1520 {
1519 RINOK(lps->SetCur()); 1521 RINOK(lps->SetCur())
1520 const UInt32 index = allFilesMode ? i : indices[i]; 1522 const UInt32 index = allFilesMode ? i : indices[i];
1521 1523
1522 CHashPair &hp = HashPairs[index]; 1524 CHashPair &hp = HashPairs[index];
@@ -1528,7 +1530,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1528 const bool isDir = hp.IsDir(); 1530 const bool isDir = hp.IsDir();
1529 if (!isDir) 1531 if (!isDir)
1530 { 1532 {
1531 RINOK(updateCallbackFile->GetStream2(index, &inStream, NUpdateNotifyOp::kHashRead)); 1533 RINOK(updateCallbackFile->GetStream2(index, &inStream, NUpdateNotifyOp::kHashRead))
1532 if (!inStream) 1534 if (!inStream)
1533 { 1535 {
1534 continue; // we have shown error in GetStream2() 1536 continue; // we have shown error in GetStream2()
@@ -1541,7 +1543,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1541 NArchive::NExtract::NAskMode::kExtract; 1543 NArchive::NExtract::NAskMode::kExtract;
1542 1544
1543 CMyComPtr<ISequentialOutStream> realOutStream; 1545 CMyComPtr<ISequentialOutStream> realOutStream;
1544 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 1546 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
1545 1547
1546 /* PrepareOperation() can expect kExtract to set 1548 /* PrepareOperation() can expect kExtract to set
1547 Attrib and security of output file */ 1549 Attrib and security of output file */
@@ -1570,7 +1572,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1570 methods_loc.Add(UString(hp.Method)); 1572 methods_loc.Add(UString(hp.Method));
1571 RINOK(hb_Loc.SetMethods( 1573 RINOK(hb_Loc.SetMethods(
1572 EXTERNAL_CODECS_LOC_VARS 1574 EXTERNAL_CODECS_LOC_VARS
1573 methods_loc)); 1575 methods_loc))
1574 } 1576 }
1575 else 1577 else
1576 res_SetMethods = E_NOTIMPL; 1578 res_SetMethods = E_NOTIMPL;
@@ -1583,7 +1585,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1583 hb_Use = &hb_Loc; 1585 hb_Use = &hb_Loc;
1584 RINOK(hb_Loc.SetMethods( 1586 RINOK(hb_Loc.SetMethods(
1585 EXTERNAL_CODECS_LOC_VARS 1587 EXTERNAL_CODECS_LOC_VARS
1586 methods_loc)); 1588 methods_loc))
1587 } 1589 }
1588 } 1590 }
1589 1591
@@ -1596,16 +1598,16 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1596 { 1598 {
1597 if ((step & 0xFF) == 0) 1599 if ((step & 0xFF) == 0)
1598 { 1600 {
1599 RINOK(lps->SetRatioInfo(NULL, &fileSize)); 1601 RINOK(progress->SetRatioInfo(NULL, &fileSize))
1600 } 1602 }
1601 UInt32 size; 1603 UInt32 size;
1602 RINOK(inStream->Read(buf, kBufSize, &size)); 1604 RINOK(inStream->Read(buf, kBufSize, &size))
1603 if (size == 0) 1605 if (size == 0)
1604 break; 1606 break;
1605 hb_Use->Update(buf, size); 1607 hb_Use->Update(buf, size);
1606 if (realOutStream) 1608 if (realOutStream)
1607 { 1609 {
1608 RINOK(WriteStream(realOutStream, buf, size)); 1610 RINOK(WriteStream(realOutStream, buf, size))
1609 } 1611 }
1610 fileSize += size; 1612 fileSize += size;
1611 } 1613 }
@@ -1638,7 +1640,7 @@ STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
1638 } 1640 }
1639 } 1641 }
1640 1642
1641 RINOK(extractCallback->SetOperationResult(opRes)); 1643 RINOK(extractCallback->SetOperationResult(opRes))
1642 } 1644 }
1643 1645
1644 return lps->SetCur(); 1646 return lps->SetCur();
@@ -1668,7 +1670,7 @@ static HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PRO
1668 bool convertSlash) 1670 bool convertSlash)
1669{ 1671{
1670 NCOM::CPropVariant prop; 1672 NCOM::CPropVariant prop;
1671 RINOK(callback->GetProperty(index, propId, &prop)); 1673 RINOK(callback->GetProperty(index, propId, &prop))
1672 if (prop.vt == VT_BSTR) 1674 if (prop.vt == VT_BSTR)
1673 { 1675 {
1674 res = prop.bstrVal; 1676 res = prop.bstrVal;
@@ -1681,15 +1683,15 @@ static HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PRO
1681} 1683}
1682 1684
1683 1685
1684STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type) 1686Z7_COM7F_IMF(CHandler::GetFileTimeType(UInt32 *type))
1685{ 1687{
1686 *type = NFileTimeType::kUnix; 1688 *type = NFileTimeType::kUnix;
1687 return S_OK; 1689 return S_OK;
1688} 1690}
1689 1691
1690 1692
1691STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems, 1693Z7_COM7F_IMF(CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
1692 IArchiveUpdateCallback *callback) 1694 IArchiveUpdateCallback *callback))
1693{ 1695{
1694 COM_TRY_BEGIN 1696 COM_TRY_BEGIN
1695 1697
@@ -1697,8 +1699,8 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1697 return E_NOTIMPL; 1699 return E_NOTIMPL;
1698 1700
1699 /* 1701 /*
1700 CMyComPtr<IArchiveUpdateCallbackArcProp> reportArcProp; 1702 Z7_DECL_CMyComPtr_QI_FROM(IArchiveUpdateCallbackArcProp,
1701 callback->QueryInterface(IID_IArchiveUpdateCallbackArcProp, (void **)&reportArcProp); 1703 reportArcProp, callback)
1702 */ 1704 */
1703 1705
1704 CObjectVector<CUpdateItem> updateItems; 1706 CObjectVector<CUpdateItem> updateItems;
@@ -1716,7 +1718,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1716 if (!callback) 1718 if (!callback)
1717 return E_FAIL; 1719 return E_FAIL;
1718 1720
1719 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc)); 1721 RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArc))
1720 1722
1721 ui.NewProps = IntToBool(newProps); 1723 ui.NewProps = IntToBool(newProps);
1722 ui.NewData = IntToBool(newData); 1724 ui.NewData = IntToBool(newData);
@@ -1726,7 +1728,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1726 { 1728 {
1727 { 1729 {
1728 NCOM::CPropVariant prop; 1730 NCOM::CPropVariant prop;
1729 RINOK(callback->GetProperty(i, kpidIsDir, &prop)); 1731 RINOK(callback->GetProperty(i, kpidIsDir, &prop))
1730 if (prop.vt == VT_EMPTY) 1732 if (prop.vt == VT_EMPTY)
1731 ui.IsDir = false; 1733 ui.IsDir = false;
1732 else if (prop.vt != VT_BOOL) 1734 else if (prop.vt != VT_BOOL)
@@ -1736,7 +1738,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1736 } 1738 }
1737 1739
1738 RINOK(GetPropString(callback, i, kpidPath, ui.Path, 1740 RINOK(GetPropString(callback, i, kpidPath, ui.Path,
1739 true)); // convertSlash 1741 true)) // convertSlash
1740 /* 1742 /*
1741 if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/') 1743 if (ui.IsDir && !ui.Name.IsEmpty() && ui.Name.Back() != '/')
1742 ui.Name += '/'; 1744 ui.Name += '/';
@@ -1746,7 +1748,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1746 if (IntToBool(newData)) 1748 if (IntToBool(newData))
1747 { 1749 {
1748 NCOM::CPropVariant prop; 1750 NCOM::CPropVariant prop;
1749 RINOK(callback->GetProperty(i, kpidSize, &prop)); 1751 RINOK(callback->GetProperty(i, kpidSize, &prop))
1750 if (prop.vt == VT_UI8) 1752 if (prop.vt == VT_UI8)
1751 { 1753 {
1752 ui.Size = prop.uhVal.QuadPart; 1754 ui.Size = prop.uhVal.QuadPart;
@@ -1763,11 +1765,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1763 1765
1764 if (complexity != 0) 1766 if (complexity != 0)
1765 { 1767 {
1766 RINOK(callback->SetTotal(complexity)); 1768 RINOK(callback->SetTotal(complexity))
1767 } 1769 }
1768 1770
1769 #ifdef EXTERNAL_CODECS 1771 #ifdef Z7_EXTERNAL_CODECS
1770 const CExternalCodecs *__externalCodecs = g_ExternalCodecs_Ptr; 1772 const CExternalCodecs *_externalCodecs = g_ExternalCodecs_Ptr;
1771 #endif 1773 #endif
1772 1774
1773 CHashBundle hb; 1775 CHashBundle hb;
@@ -1785,13 +1787,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1785 } 1787 }
1786 else 1788 else
1787 { 1789 {
1788 CMyComPtr<IArchiveGetRootProps> getRootProps; 1790 Z7_DECL_CMyComPtr_QI_FROM(
1789 callback->QueryInterface(IID_IArchiveGetRootProps, (void **)&getRootProps); 1791 IArchiveGetRootProps,
1790 1792 getRootProps, callback)
1791 NCOM::CPropVariant prop;
1792 if (getRootProps) 1793 if (getRootProps)
1793 { 1794 {
1794 RINOK(getRootProps->GetRootProp(kpidArcFileName, &prop)); 1795 NCOM::CPropVariant prop;
1796 RINOK(getRootProps->GetRootProp(kpidArcFileName, &prop))
1795 if (prop.vt == VT_BSTR) 1797 if (prop.vt == VT_BSTR)
1796 { 1798 {
1797 const UString method = GetMethod_from_FileName(prop.bstrVal); 1799 const UString method = GetMethod_from_FileName(prop.bstrVal);
@@ -1801,7 +1803,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1801 } 1803 }
1802 } 1804 }
1803 1805
1804 RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods)); 1806 RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS methods))
1805 1807
1806 CLocalProgress *lps = new CLocalProgress; 1808 CLocalProgress *lps = new CLocalProgress;
1807 CMyComPtr<ICompressProgressInfo> progress = lps; 1809 CMyComPtr<ICompressProgressInfo> progress = lps;
@@ -1834,7 +1836,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1834 for (i = 0; i < updateItems.Size(); i++) 1836 for (i = 0; i < updateItems.Size(); i++)
1835 { 1837 {
1836 lps->InSize = complexity; 1838 lps->InSize = complexity;
1837 RINOK(lps->SetCur()); 1839 RINOK(lps->SetCur())
1838 1840
1839 const CUpdateItem &ui = updateItems[i]; 1841 const CUpdateItem &ui = updateItems[i];
1840 1842
@@ -1858,12 +1860,13 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1858 needWrite = false; 1860 needWrite = false;
1859 else 1861 else
1860 { 1862 {
1861 RINOK(res); 1863 RINOK(res)
1862 1864
1863 if (fileInStream) 1865 if (fileInStream)
1864 { 1866 {
1865 CMyComPtr<IStreamGetSize> streamGetSize; 1867 Z7_DECL_CMyComPtr_QI_FROM(
1866 fileInStream->QueryInterface(IID_IStreamGetSize, (void **)&streamGetSize); 1868 IStreamGetSize,
1869 streamGetSize, fileInStream)
1867 if (streamGetSize) 1870 if (streamGetSize)
1868 { 1871 {
1869 UInt64 size; 1872 UInt64 size;
@@ -1871,8 +1874,9 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1871 currentComplexity = size; 1874 currentComplexity = size;
1872 } 1875 }
1873 /* 1876 /*
1874 CMyComPtr<IStreamGetProps> getProps; 1877 Z7_DECL_CMyComPtr_QI_FROM(
1875 fileInStream->QueryInterface(IID_IStreamGetProps, (void **)&getProps); 1878 IStreamGetProps,
1879 getProps, fileInStream)
1876 if (getProps) 1880 if (getProps)
1877 { 1881 {
1878 FILETIME mTime; 1882 FILETIME mTime;
@@ -1901,11 +1905,11 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1901 { 1905 {
1902 if ((step & 0xFF) == 0) 1906 if ((step & 0xFF) == 0)
1903 { 1907 {
1904 RINOK(lps->SetRatioInfo(&fileSize, NULL)); 1908 RINOK(progress->SetRatioInfo(&fileSize, NULL))
1905 // RINOK(callback->SetCompleted(&completeValue)); 1909 // RINOK(callback->SetCompleted(&completeValue));
1906 } 1910 }
1907 UInt32 size; 1911 UInt32 size;
1908 RINOK(fileInStream->Read(buf, kBufSize, &size)); 1912 RINOK(fileInStream->Read(buf, kBufSize, &size))
1909 if (size == 0) 1913 if (size == 0)
1910 break; 1914 break;
1911 hb.Update(buf, size); 1915 hb.Update(buf, size);
@@ -1962,7 +1966,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1962 } 1966 }
1963 } 1967 }
1964 */ 1968 */
1965 RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); 1969 RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK))
1966 } 1970 }
1967 else 1971 else
1968 { 1972 {
@@ -1987,7 +1991,7 @@ STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numIt
1987 return E_OUTOFMEMORY; 1991 return E_OUTOFMEMORY;
1988 } 1992 }
1989 1993
1990 RINOK(WriteStream(outStream, hashFileString, hashFileString.Len())); 1994 RINOK(WriteStream(outStream, hashFileString, hashFileString.Len()))
1991 1995
1992 return S_OK; 1996 return S_OK;
1993 COM_TRY_END 1997 COM_TRY_END
@@ -2040,7 +2044,7 @@ HRESULT CHandler::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value)
2040} 2044}
2041 2045
2042 2046
2043STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps) 2047Z7_COM7F_IMF(CHandler::SetProperties(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps))
2044{ 2048{
2045 COM_TRY_BEGIN 2049 COM_TRY_BEGIN
2046 2050
@@ -2048,7 +2052,7 @@ STDMETHODIMP CHandler::SetProperties(const wchar_t * const *names, const PROPVAR
2048 2052
2049 for (UInt32 i = 0; i < numProps; i++) 2053 for (UInt32 i = 0; i < numProps; i++)
2050 { 2054 {
2051 RINOK(SetProperty(names[i], values[i])); 2055 RINOK(SetProperty(names[i], values[i]))
2052 } 2056 }
2053 return S_OK; 2057 return S_OK;
2054 COM_TRY_END 2058 COM_TRY_END
diff --git a/CPP/7zip/UI/Common/HashCalc.h b/CPP/7zip/UI/Common/HashCalc.h
index c566caa..0b527c1 100644
--- a/CPP/7zip/UI/Common/HashCalc.h
+++ b/CPP/7zip/UI/Common/HashCalc.h
@@ -1,7 +1,7 @@
1// HashCalc.h 1// HashCalc.h
2 2
3#ifndef __HASH_CALC_H 3#ifndef ZIP7_INC_HASH_CALC_H
4#define __HASH_CALC_H 4#define ZIP7_INC_HASH_CALC_H
5 5
6#include "../../../Common/UTFConvert.h" 6#include "../../../Common/UTFConvert.h"
7#include "../../../Common/Wildcard.h" 7#include "../../../Common/Wildcard.h"
@@ -65,8 +65,10 @@ struct CHasherState
65}; 65};
66 66
67 67
68Z7_PURE_INTERFACES_BEGIN
68 69
69struct IHashCalc 70
71DECLARE_INTERFACE(IHashCalc)
70{ 72{
71 virtual void InitForNewFile() = 0; 73 virtual void InitForNewFile() = 0;
72 virtual void Update(const void *data, UInt32 size) = 0; 74 virtual void Update(const void *data, UInt32 size) = 0;
@@ -74,7 +76,9 @@ struct IHashCalc
74 virtual void Final(bool isDir, bool isAltStream, const UString &path) = 0; 76 virtual void Final(bool isDir, bool isAltStream, const UString &path) = 0;
75}; 77};
76 78
77struct CHashBundle: public IHashCalc 79Z7_PURE_INTERFACES_END
80
81struct CHashBundle Z7_final: public IHashCalc
78{ 82{
79 CObjectVector<CHasherState> Hashers; 83 CObjectVector<CHasherState> Hashers;
80 84
@@ -98,32 +102,32 @@ struct CHashBundle: public IHashCalc
98 NumDirs = NumFiles = NumAltStreams = FilesSize = AltStreamsSize = NumErrors = 0; 102 NumDirs = NumFiles = NumAltStreams = FilesSize = AltStreamsSize = NumErrors = 0;
99 } 103 }
100 104
101 virtual ~CHashBundle() {}; 105 void InitForNewFile() Z7_override;
102 106 void Update(const void *data, UInt32 size) Z7_override;
103 void InitForNewFile(); 107 void SetSize(UInt64 size) Z7_override;
104 void Update(const void *data, UInt32 size); 108 void Final(bool isDir, bool isAltStream, const UString &path) Z7_override;
105 void SetSize(UInt64 size);
106 void Final(bool isDir, bool isAltStream, const UString &path);
107}; 109};
108 110
109#define INTERFACE_IHashCallbackUI(x) \ 111Z7_PURE_INTERFACES_BEGIN
110 INTERFACE_IDirItemsCallback(x) \ 112
111 virtual HRESULT StartScanning() x; \ 113// INTERFACE_IDirItemsCallback(x)
112 virtual HRESULT FinishScanning(const CDirItemsStat &st) x; \ 114
113 virtual HRESULT SetNumFiles(UInt64 numFiles) x; \ 115#define Z7_IFACEN_IHashCallbackUI(x) \
114 virtual HRESULT SetTotal(UInt64 size) x; \ 116 virtual HRESULT StartScanning() x \
115 virtual HRESULT SetCompleted(const UInt64 *completeValue) x; \ 117 virtual HRESULT FinishScanning(const CDirItemsStat &st) x \
116 virtual HRESULT CheckBreak() x; \ 118 virtual HRESULT SetNumFiles(UInt64 numFiles) x \
117 virtual HRESULT BeforeFirstFile(const CHashBundle &hb) x; \ 119 virtual HRESULT SetTotal(UInt64 size) x \
118 virtual HRESULT GetStream(const wchar_t *name, bool isFolder) x; \ 120 virtual HRESULT SetCompleted(const UInt64 *completeValue) x \
119 virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x; \ 121 virtual HRESULT CheckBreak() x \
120 virtual HRESULT SetOperationResult(UInt64 fileSize, const CHashBundle &hb, bool showHash) x; \ 122 virtual HRESULT BeforeFirstFile(const CHashBundle &hb) x \
121 virtual HRESULT AfterLastFile(CHashBundle &hb) x; \ 123 virtual HRESULT GetStream(const wchar_t *name, bool isFolder) x \
122 124 virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x \
123struct IHashCallbackUI: public IDirItemsCallback 125 virtual HRESULT SetOperationResult(UInt64 fileSize, const CHashBundle &hb, bool showHash) x \
124{ 126 virtual HRESULT AfterLastFile(CHashBundle &hb) x \
125 INTERFACE_IHashCallbackUI(=0) 127
126}; 128Z7_IFACE_DECL_PURE_(IHashCallbackUI, IDirItemsCallback)
129
130Z7_PURE_INTERFACES_END
127 131
128 132
129struct CHashOptionsLocal 133struct CHashOptionsLocal
@@ -200,7 +204,7 @@ struct CHashOptions
200 OpenShareForWrite(false), 204 OpenShareForWrite(false),
201 StdInMode(false), 205 StdInMode(false),
202 AltStreamsMode(false), 206 AltStreamsMode(false),
203 PathMode(NWildcard::k_RelatPath) {}; 207 PathMode(NWildcard::k_RelatPath) {}
204}; 208};
205 209
206 210
@@ -213,7 +217,7 @@ HRESULT HashCalc(
213 217
214 218
215 219
216#ifndef _SFX 220#ifndef Z7_SFX
217 221
218namespace NHash { 222namespace NHash {
219 223
@@ -264,14 +268,12 @@ struct CHashPair
264}; 268};
265 269
266 270
267class CHandler: 271Z7_CLASS_IMP_CHandler_IInArchive_3(
268 public IInArchive, 272 IArchiveGetRawProps,
269 public IArchiveGetRawProps, 273 /* public IGetArchiveHashHandler, */
270 // public IGetArchiveHashHandler, 274 IOutArchive,
271 public IOutArchive, 275 ISetProperties
272 public ISetProperties, 276)
273 public CMyUnknownImp
274{
275 bool _isArc; 277 bool _isArc;
276 UInt64 _phySize; 278 UInt64 _phySize;
277 CObjectVector<CHashPair> HashPairs; 279 CObjectVector<CHashPair> HashPairs;
@@ -313,21 +315,7 @@ class CHandler:
313 HRESULT SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value); 315 HRESULT SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value);
314 316
315public: 317public:
316
317 CHandler(); 318 CHandler();
318
319 MY_UNKNOWN_IMP4(
320 IInArchive,
321 IArchiveGetRawProps,
322 IOutArchive,
323 ISetProperties
324 /*, IGetArchiveHashHandler */
325 )
326 INTERFACE_IInArchive(;)
327 INTERFACE_IOutArchive(;)
328 INTERFACE_IArchiveGetRawProps(;)
329 // STDMETHOD(GetArchiveHashHandler)(CHandler **handler);
330 STDMETHOD(SetProperties)(const wchar_t * const *names, const PROPVARIANT *values, UInt32 numProps);
331}; 319};
332 320
333} 321}
diff --git a/CPP/7zip/UI/Common/IFileExtractCallback.h b/CPP/7zip/UI/Common/IFileExtractCallback.h
index e6a85c6..dd5c0d7 100644
--- a/CPP/7zip/UI/Common/IFileExtractCallback.h
+++ b/CPP/7zip/UI/Common/IFileExtractCallback.h
@@ -1,7 +1,7 @@
1// IFileExtractCallback.h 1// IFileExtractCallback.h
2 2
3#ifndef __I_FILE_EXTRACT_CALLBACK_H 3#ifndef ZIP7_INC_I_FILE_EXTRACT_CALLBACK_H
4#define __I_FILE_EXTRACT_CALLBACK_H 4#define ZIP7_INC_I_FILE_EXTRACT_CALLBACK_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
@@ -10,6 +10,15 @@
10#include "LoadCodecs.h" 10#include "LoadCodecs.h"
11#include "OpenArchive.h" 11#include "OpenArchive.h"
12 12
13Z7_PURE_INTERFACES_BEGIN
14
15#define Z7_IFACE_CONSTR_FOLDERARC_SUB(i, base, n) \
16 Z7_DECL_IFACE_7ZIP_SUB(i, base, 1, n) \
17 { Z7_IFACE_COM7_PURE(i) };
18
19#define Z7_IFACE_CONSTR_FOLDERARC(i, n) \
20 Z7_IFACE_CONSTR_FOLDERARC_SUB(i, IUnknown, n)
21
13namespace NOverwriteAnswer 22namespace NOverwriteAnswer
14{ 23{
15 enum EEnum 24 enum EEnum
@@ -42,27 +51,21 @@ IID_IFolderArchiveExtractCallback is requested by:
42 IFolderArchiveExtractCallback is used by Common/ArchiveExtractCallback.cpp 51 IFolderArchiveExtractCallback is used by Common/ArchiveExtractCallback.cpp
43*/ 52*/
44 53
45#define INTERFACE_IFolderArchiveExtractCallback(x) \ 54#define Z7_IFACEM_IFolderArchiveExtractCallback(x) \
46 STDMETHOD(AskOverwrite)( \ 55 x(AskOverwrite( \
47 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, \ 56 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, \
48 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, \ 57 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, \
49 Int32 *answer) x; \ 58 Int32 *answer)) \
50 STDMETHOD(PrepareOperation)(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position) x; \ 59 x(PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position)) \
51 STDMETHOD(MessageError)(const wchar_t *message) x; \ 60 x(MessageError(const wchar_t *message)) \
52 STDMETHOD(SetOperationResult)(Int32 opRes, Int32 encrypted) x; \ 61 x(SetOperationResult(Int32 opRes, Int32 encrypted)) \
53 62
54DECL_INTERFACE_SUB(IFolderArchiveExtractCallback, IProgress, 0x01, 0x07) 63Z7_IFACE_CONSTR_FOLDERARC_SUB(IFolderArchiveExtractCallback, IProgress, 0x07)
55{
56 INTERFACE_IFolderArchiveExtractCallback(PURE)
57};
58 64
59#define INTERFACE_IFolderArchiveExtractCallback2(x) \ 65#define Z7_IFACEM_IFolderArchiveExtractCallback2(x) \
60 STDMETHOD(ReportExtractResult)(Int32 opRes, Int32 encrypted, const wchar_t *name) x; \ 66 x(ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name)) \
61 67
62DECL_INTERFACE_SUB(IFolderArchiveExtractCallback2, IUnknown, 0x01, 0x08) 68Z7_IFACE_CONSTR_FOLDERARC(IFolderArchiveExtractCallback2, 0x08)
63{
64 INTERFACE_IFolderArchiveExtractCallback2(PURE)
65};
66 69
67/* ---------- IExtractCallbackUI ---------- 70/* ---------- IExtractCallbackUI ----------
68is implemented by 71is implemented by
@@ -70,45 +73,40 @@ is implemented by
70 FileManager/ExtractCallback.h CExtractCallbackImp 73 FileManager/ExtractCallback.h CExtractCallbackImp
71*/ 74*/
72 75
73#ifdef _NO_CRYPTO 76#ifdef Z7_NO_CRYPTO
74 #define INTERFACE_IExtractCallbackUI_Crypto(x) 77 #define Z7_IFACEM_IExtractCallbackUI_Crypto(px)
75#else 78#else
76 #define INTERFACE_IExtractCallbackUI_Crypto(x) \ 79 #define Z7_IFACEM_IExtractCallbackUI_Crypto(px) \
77 virtual HRESULT SetPassword(const UString &password) x; 80 virtual HRESULT SetPassword(const UString &password) px
78#endif 81#endif
79 82
80#define INTERFACE_IExtractCallbackUI(x) \ 83#define Z7_IFACEN_IExtractCallbackUI(px) \
81 virtual HRESULT BeforeOpen(const wchar_t *name, bool testMode) x; \ 84 virtual HRESULT BeforeOpen(const wchar_t *name, bool testMode) px \
82 virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x; \ 85 virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) px \
83 virtual HRESULT ThereAreNoFiles() x; \ 86 virtual HRESULT ThereAreNoFiles() px \
84 virtual HRESULT ExtractResult(HRESULT result) x; \ 87 virtual HRESULT ExtractResult(HRESULT result) px \
85 INTERFACE_IExtractCallbackUI_Crypto(x) 88 Z7_IFACEM_IExtractCallbackUI_Crypto(px)
86 89
87struct IExtractCallbackUI: IFolderArchiveExtractCallback 90// IExtractCallbackUI - is non-COM interface
88{ 91// IFolderArchiveExtractCallback - is COM interface
89 INTERFACE_IExtractCallbackUI(PURE) 92// Z7_IFACE_DECL_PURE_(IExtractCallbackUI, IFolderArchiveExtractCallback)
90}; 93Z7_IFACE_DECL_PURE(IExtractCallbackUI)
91 94
92 95
93 96
94#define INTERFACE_IGetProp(x) \ 97#define Z7_IFACEM_IGetProp(x) \
95 STDMETHOD(GetProp)(PROPID propID, PROPVARIANT *value) x; \ 98 x(GetProp(PROPID propID, PROPVARIANT *value)) \
96 99
97DECL_INTERFACE_SUB(IGetProp, IUnknown, 0x01, 0x20) 100Z7_IFACE_CONSTR_FOLDERARC(IGetProp, 0x20)
98{
99 INTERFACE_IGetProp(PURE)
100};
101 101
102#define INTERFACE_IFolderExtractToStreamCallback(x) \ 102#define Z7_IFACEM_IFolderExtractToStreamCallback(x) \
103 STDMETHOD(UseExtractToStream)(Int32 *res) x; \ 103 x(UseExtractToStream(Int32 *res)) \
104 STDMETHOD(GetStream7)(const wchar_t *name, Int32 isDir, ISequentialOutStream **outStream, Int32 askExtractMode, IGetProp *getProp) x; \ 104 x(GetStream7(const wchar_t *name, Int32 isDir, ISequentialOutStream **outStream, Int32 askExtractMode, IGetProp *getProp)) \
105 STDMETHOD(PrepareOperation7)(Int32 askExtractMode) x; \ 105 x(PrepareOperation7(Int32 askExtractMode)) \
106 STDMETHOD(SetOperationResult8)(Int32 resultEOperationResult, Int32 encrypted, UInt64 size) x; \ 106 x(SetOperationResult8(Int32 resultEOperationResult, Int32 encrypted, UInt64 size)) \
107 107
108DECL_INTERFACE_SUB(IFolderExtractToStreamCallback, IUnknown, 0x01, 0x31) 108Z7_IFACE_CONSTR_FOLDERARC(IFolderExtractToStreamCallback, 0x31)
109{
110 INTERFACE_IFolderExtractToStreamCallback(PURE)
111};
112 109
110Z7_PURE_INTERFACES_END
113 111
114#endif 112#endif
diff --git a/CPP/7zip/UI/Common/LoadCodecs.cpp b/CPP/7zip/UI/Common/LoadCodecs.cpp
index b6a2073..5a65bdc 100644
--- a/CPP/7zip/UI/Common/LoadCodecs.cpp
+++ b/CPP/7zip/UI/Common/LoadCodecs.cpp
@@ -1,7 +1,7 @@
1// LoadCodecs.cpp 1// LoadCodecs.cpp
2 2
3/* 3/*
4EXTERNAL_CODECS 4Z7_EXTERNAL_CODECS
5--------------- 5---------------
6 CCodecs::Load() tries to detect the directory with plugins. 6 CCodecs::Load() tries to detect the directory with plugins.
7 It stops the checking, if it can find any of the following items: 7 It stops the checking, if it can find any of the following items:
@@ -22,7 +22,7 @@ EXTERNAL_CODECS
22 22
23EXPORT_CODECS 23EXPORT_CODECS
24------------- 24-------------
25 if (EXTERNAL_CODECS) is defined, then the code exports internal 25 if (Z7_EXTERNAL_CODECS) is defined, then the code exports internal
26 codecs of client from CCodecs object to external plugins. 26 codecs of client from CCodecs object to external plugins.
27 7-Zip doesn't use that feature. 7-Zip uses the scheme: 27 7-Zip doesn't use that feature. 7-Zip uses the scheme:
28 - client application without internal plugins. 28 - client application without internal plugins.
@@ -43,29 +43,15 @@ EXPORT_CODECS
43 43
44#include "LoadCodecs.h" 44#include "LoadCodecs.h"
45 45
46using namespace NWindows;
47
48#ifdef NEW_FOLDER_INTERFACE
49#include "../../../Common/StringToInt.h"
50#endif
51
52#include "../../ICoder.h" 46#include "../../ICoder.h"
53#include "../../Common/RegisterArc.h" 47#include "../../Common/RegisterArc.h"
54#include "../../Common/RegisterCodec.h" 48#include "../../Common/RegisterCodec.h"
55 49
56#ifdef EXTERNAL_CODECS 50#ifdef Z7_EXTERNAL_CODECS
57
58// #define EXPORT_CODECS 51// #define EXPORT_CODECS
59
60#endif
61
62#ifdef NEW_FOLDER_INTERFACE
63extern HINSTANCE g_hInstance;
64#include "../../../Windows/ResourceString.h"
65static const UINT kIconTypesResId = 100;
66#endif 52#endif
67 53
68#ifdef EXTERNAL_CODECS 54#ifdef Z7_EXTERNAL_CODECS
69 55
70#include "../../../Windows/FileFind.h" 56#include "../../../Windows/FileFind.h"
71#include "../../../Windows/DLL.h" 57#include "../../../Windows/DLL.h"
@@ -75,6 +61,7 @@ static const UINT kIconTypesResId = 100;
75#include "../../../Windows/Registry.h" 61#include "../../../Windows/Registry.h"
76#endif 62#endif
77 63
64using namespace NWindows;
78using namespace NFile; 65using namespace NFile;
79 66
80 67
@@ -119,10 +106,10 @@ static bool ReadPathFromRegistry(HKEY baseKey, LPCWSTR value, FString &path)
119 106
120#endif // _WIN32 107#endif // _WIN32
121 108
122#endif // EXTERNAL_CODECS 109#endif // Z7_EXTERNAL_CODECS
123 110
124 111
125static const unsigned kNumArcsMax = 64; 112static const unsigned kNumArcsMax = 72;
126static unsigned g_NumArcs = 0; 113static unsigned g_NumArcs = 0;
127static const CArcInfo *g_Arcs[kNumArcsMax]; 114static const CArcInfo *g_Arcs[kNumArcsMax];
128 115
@@ -133,8 +120,10 @@ void RegisterArc(const CArcInfo *arcInfo) throw()
133 g_Arcs[g_NumArcs] = arcInfo; 120 g_Arcs[g_NumArcs] = arcInfo;
134 g_NumArcs++; 121 g_NumArcs++;
135 } 122 }
123 // else throw 1;
136} 124}
137 125
126/*
138static void SplitString(const UString &srcString, UStringVector &destStrings) 127static void SplitString(const UString &srcString, UStringVector &destStrings)
139{ 128{
140 destStrings.Clear(); 129 destStrings.Clear();
@@ -159,6 +148,7 @@ static void SplitString(const UString &srcString, UStringVector &destStrings)
159 if (!s.IsEmpty()) 148 if (!s.IsEmpty())
160 destStrings.Add(s); 149 destStrings.Add(s);
161} 150}
151*/
162 152
163int CArcInfoEx::FindExtension(const UString &ext) const 153int CArcInfoEx::FindExtension(const UString &ext) const
164{ 154{
@@ -187,7 +177,7 @@ void CArcInfoEx::AddExts(const UString &ext, const UString &addExt)
187 } 177 }
188} 178}
189 179
190#ifndef _SFX 180#ifndef Z7_SFX
191 181
192static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector<CByteBuffer> &signatures) 182static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector<CByteBuffer> &signatures)
193{ 183{
@@ -205,11 +195,11 @@ static bool ParseSignatures(const Byte *data, unsigned size, CObjectVector<CByte
205 return true; 195 return true;
206} 196}
207 197
208#endif // _SFX 198#endif // Z7_SFX
209 199
210// #include <stdio.h> 200// #include <stdio.h>
211 201
212#ifdef EXTERNAL_CODECS 202#ifdef Z7_EXTERNAL_CODECS
213 203
214static FString GetBaseFolderPrefixFromRegistry() 204static FString GetBaseFolderPrefixFromRegistry()
215{ 205{
@@ -238,7 +228,7 @@ static HRESULT GetCoderClass(Func_GetMethodProperty getMethodProperty, UInt32 in
238{ 228{
239 NCOM::CPropVariant prop; 229 NCOM::CPropVariant prop;
240 isAssigned = false; 230 isAssigned = false;
241 RINOK(getMethodProperty(index, propId, &prop)); 231 RINOK(getMethodProperty(index, propId, &prop))
242 if (prop.vt == VT_BSTR) 232 if (prop.vt == VT_BSTR)
243 { 233 {
244 if (::SysStringByteLen(prop.bstrVal) != sizeof(GUID)) 234 if (::SysStringByteLen(prop.bstrVal) != sizeof(GUID))
@@ -258,7 +248,7 @@ static HRESULT GetMethodBoolProp(Func_GetMethodProperty getMethodProperty, UInt3
258 NCOM::CPropVariant prop; 248 NCOM::CPropVariant prop;
259 resVal = false; 249 resVal = false;
260 isAssigned = false; 250 isAssigned = false;
261 RINOK(getMethodProperty(index, propId, &prop)); 251 RINOK(getMethodProperty(index, propId, &prop))
262 if (prop.vt == VT_BOOL) 252 if (prop.vt == VT_BOOL)
263 { 253 {
264 isAssigned = true; 254 isAssigned = true;
@@ -269,45 +259,49 @@ static HRESULT GetMethodBoolProp(Func_GetMethodProperty getMethodProperty, UInt3
269 return S_OK; 259 return S_OK;
270} 260}
271 261
262#if defined(__clang__)
263#pragma GCC diagnostic ignored "-Wc++98-compat-pedantic"
264#endif
272 265
273#define MY_GET_FUNC(dest, type, func) *(void **)(&dest) = (func); 266#define MY_GET_FUNC(dest, type, lib, func) \
267 dest = Z7_GET_PROC_ADDRESS(type, lib.Get_HMODULE(), func);
274// #define MY_GET_FUNC(dest, type, func) dest = (type)(func); 268// #define MY_GET_FUNC(dest, type, func) dest = (type)(func);
275 269
276#define MY_GET_FUNC_LOC(dest, type, func) \ 270#define MY_GET_FUNC_LOC(dest, type, lib, func) \
277 type dest; MY_GET_FUNC(dest, type, func) 271 type dest; MY_GET_FUNC(dest, type, lib, func)
278 272
279HRESULT CCodecs::LoadCodecs() 273HRESULT CCodecs::LoadCodecs()
280{ 274{
281 CCodecLib &lib = Libs.Back(); 275 CCodecLib &lib = Libs.Back();
282 276
283 MY_GET_FUNC (lib.CreateDecoder, Func_CreateDecoder, lib.Lib.GetProc("CreateDecoder")); 277 MY_GET_FUNC (lib.CreateDecoder, Func_CreateDecoder, lib.Lib, "CreateDecoder")
284 MY_GET_FUNC (lib.CreateEncoder, Func_CreateEncoder, lib.Lib.GetProc("CreateEncoder")); 278 MY_GET_FUNC (lib.CreateEncoder, Func_CreateEncoder, lib.Lib, "CreateEncoder")
285 MY_GET_FUNC (lib.GetMethodProperty, Func_GetMethodProperty, lib.Lib.GetProc("GetMethodProperty")); 279 MY_GET_FUNC (lib.GetMethodProperty, Func_GetMethodProperty, lib.Lib, "GetMethodProperty")
286 280
287 if (lib.GetMethodProperty) 281 if (lib.GetMethodProperty)
288 { 282 {
289 UInt32 numMethods = 1; 283 UInt32 numMethods = 1;
290 MY_GET_FUNC_LOC (getNumberOfMethods, Func_GetNumberOfMethods, lib.Lib.GetProc("GetNumberOfMethods")); 284 MY_GET_FUNC_LOC (getNumberOfMethods, Func_GetNumberOfMethods, lib.Lib, "GetNumberOfMethods")
291 if (getNumberOfMethods) 285 if (getNumberOfMethods)
292 { 286 {
293 RINOK(getNumberOfMethods(&numMethods)); 287 RINOK(getNumberOfMethods(&numMethods))
294 } 288 }
295 for (UInt32 i = 0; i < numMethods; i++) 289 for (UInt32 i = 0; i < numMethods; i++)
296 { 290 {
297 CDllCodecInfo info; 291 CDllCodecInfo info;
298 info.LibIndex = Libs.Size() - 1; 292 info.LibIndex = Libs.Size() - 1;
299 info.CodecIndex = i; 293 info.CodecIndex = i;
300 RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned)); 294 RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned))
301 RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned)); 295 RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned))
302 RINOK(GetMethodBoolProp(lib.GetMethodProperty, i, NMethodPropID::kIsFilter, info.IsFilter, info.IsFilter_Assigned)); 296 RINOK(GetMethodBoolProp(lib.GetMethodProperty, i, NMethodPropID::kIsFilter, info.IsFilter, info.IsFilter_Assigned))
303 Codecs.Add(info); 297 Codecs.Add(info);
304 } 298 }
305 } 299 }
306 300
307 MY_GET_FUNC_LOC (getHashers, Func_GetHashers, lib.Lib.GetProc("GetHashers")); 301 MY_GET_FUNC_LOC (getHashers, Func_GetHashers, lib.Lib, "GetHashers")
308 if (getHashers) 302 if (getHashers)
309 { 303 {
310 RINOK(getHashers(&lib.ComHashers)); 304 RINOK(getHashers(&lib.ComHashers))
311 if (lib.ComHashers) 305 if (lib.ComHashers)
312 { 306 {
313 UInt32 numMethods = lib.ComHashers->GetNumHashers(); 307 UInt32 numMethods = lib.ComHashers->GetNumHashers();
@@ -330,7 +324,7 @@ static HRESULT GetProp(
330 UInt32 index, PROPID propID, NCOM::CPropVariant &prop) 324 UInt32 index, PROPID propID, NCOM::CPropVariant &prop)
331{ 325{
332 if (getProp2) 326 if (getProp2)
333 return getProp2(index, propID, &prop);; 327 return getProp2(index, propID, &prop);
334 return getProp(propID, &prop); 328 return getProp(propID, &prop);
335} 329}
336 330
@@ -341,7 +335,7 @@ static HRESULT GetProp_Bool(
341{ 335{
342 res = false; 336 res = false;
343 NCOM::CPropVariant prop; 337 NCOM::CPropVariant prop;
344 RINOK(GetProp(getProp, getProp2, index, propID, prop)); 338 RINOK(GetProp(getProp, getProp2, index, propID, prop))
345 if (prop.vt == VT_BOOL) 339 if (prop.vt == VT_BOOL)
346 res = VARIANT_BOOLToBool(prop.boolVal); 340 res = VARIANT_BOOLToBool(prop.boolVal);
347 else if (prop.vt != VT_EMPTY) 341 else if (prop.vt != VT_EMPTY)
@@ -357,7 +351,7 @@ static HRESULT GetProp_UInt32(
357 res = 0; 351 res = 0;
358 defined = false; 352 defined = false;
359 NCOM::CPropVariant prop; 353 NCOM::CPropVariant prop;
360 RINOK(GetProp(getProp, getProp2, index, propID, prop)); 354 RINOK(GetProp(getProp, getProp2, index, propID, prop))
361 if (prop.vt == VT_UI4) 355 if (prop.vt == VT_UI4)
362 { 356 {
363 res = prop.ulVal; 357 res = prop.ulVal;
@@ -375,7 +369,7 @@ static HRESULT GetProp_String(
375{ 369{
376 res.Empty(); 370 res.Empty();
377 NCOM::CPropVariant prop; 371 NCOM::CPropVariant prop;
378 RINOK(GetProp(getProp, getProp2, index, propID, prop)); 372 RINOK(GetProp(getProp, getProp2, index, propID, prop))
379 if (prop.vt == VT_BSTR) 373 if (prop.vt == VT_BSTR)
380 res.SetFromBstr(prop.bstrVal); 374 res.SetFromBstr(prop.bstrVal);
381 else if (prop.vt != VT_EMPTY) 375 else if (prop.vt != VT_EMPTY)
@@ -390,7 +384,7 @@ static HRESULT GetProp_RawData(
390{ 384{
391 bb.Free(); 385 bb.Free();
392 NCOM::CPropVariant prop; 386 NCOM::CPropVariant prop;
393 RINOK(GetProp(getProp, getProp2, index, propID, prop)); 387 RINOK(GetProp(getProp, getProp2, index, propID, prop))
394 if (prop.vt == VT_BSTR) 388 if (prop.vt == VT_BSTR)
395 { 389 {
396 UINT len = ::SysStringByteLen(prop.bstrVal); 390 UINT len = ::SysStringByteLen(prop.bstrVal);
@@ -413,22 +407,22 @@ HRESULT CCodecs::LoadFormats()
413 const NDLL::CLibrary &lib = Libs.Back().Lib; 407 const NDLL::CLibrary &lib = Libs.Back().Lib;
414 408
415 Func_GetHandlerProperty getProp = NULL; 409 Func_GetHandlerProperty getProp = NULL;
416 MY_GET_FUNC_LOC (getProp2, Func_GetHandlerProperty2, lib.GetProc("GetHandlerProperty2")); 410 MY_GET_FUNC_LOC (getProp2, Func_GetHandlerProperty2, lib, "GetHandlerProperty2")
417 MY_GET_FUNC_LOC (getIsArc, Func_GetIsArc, lib.GetProc("GetIsArc")); 411 MY_GET_FUNC_LOC (getIsArc, Func_GetIsArc, lib, "GetIsArc")
418 412
419 UInt32 numFormats = 1; 413 UInt32 numFormats = 1;
420 414
421 if (getProp2) 415 if (getProp2)
422 { 416 {
423 MY_GET_FUNC_LOC (getNumberOfFormats, Func_GetNumberOfFormats, lib.GetProc("GetNumberOfFormats")); 417 MY_GET_FUNC_LOC (getNumberOfFormats, Func_GetNumberOfFormats, lib, "GetNumberOfFormats")
424 if (getNumberOfFormats) 418 if (getNumberOfFormats)
425 { 419 {
426 RINOK(getNumberOfFormats(&numFormats)); 420 RINOK(getNumberOfFormats(&numFormats))
427 } 421 }
428 } 422 }
429 else 423 else
430 { 424 {
431 MY_GET_FUNC (getProp, Func_GetHandlerProperty, lib.GetProc("GetHandlerProperty")); 425 MY_GET_FUNC (getProp, Func_GetHandlerProperty, lib, "GetHandlerProperty")
432 if (!getProp) 426 if (!getProp)
433 return S_OK; 427 return S_OK;
434 } 428 }
@@ -439,7 +433,7 @@ HRESULT CCodecs::LoadFormats()
439 item.LibIndex = (int)(Libs.Size() - 1); 433 item.LibIndex = (int)(Libs.Size() - 1);
440 item.FormatIndex = i; 434 item.FormatIndex = i;
441 435
442 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kName, item.Name)); 436 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kName, item.Name))
443 437
444 { 438 {
445 NCOM::CPropVariant prop; 439 NCOM::CPropVariant prop;
@@ -454,18 +448,18 @@ HRESULT CCodecs::LoadFormats()
454 } 448 }
455 449
456 UString ext, addExt; 450 UString ext, addExt;
457 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kExtension, ext)); 451 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kExtension, ext))
458 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kAddExtension, addExt)); 452 RINOK(GetProp_String(getProp, getProp2, i, NArchive::NHandlerPropID::kAddExtension, addExt))
459 item.AddExts(ext, addExt); 453 item.AddExts(ext, addExt);
460 454
461 GetProp_Bool(getProp, getProp2, i, NArchive::NHandlerPropID::kUpdate, item.UpdateEnabled); 455 GetProp_Bool(getProp, getProp2, i, NArchive::NHandlerPropID::kUpdate, item.UpdateEnabled);
462 bool flags_Defined = false; 456 bool flags_Defined = false;
463 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kFlags, item.Flags, flags_Defined)); 457 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kFlags, item.Flags, flags_Defined))
464 item.NewInterface = flags_Defined; 458 item.NewInterface = flags_Defined;
465 if (!flags_Defined) // && item.UpdateEnabled 459 if (!flags_Defined) // && item.UpdateEnabled
466 { 460 {
467 // support for DLL version before 9.31: 461 // support for DLL version before 9.31:
468 for (unsigned j = 0; j < ARRAY_SIZE(kArcFlagsPars); j += 2) 462 for (unsigned j = 0; j < Z7_ARRAY_SIZE(kArcFlagsPars); j += 2)
469 { 463 {
470 bool val = false; 464 bool val = false;
471 GetProp_Bool(getProp, getProp2, i, kArcFlagsPars[j], val); 465 GetProp_Bool(getProp, getProp2, i, kArcFlagsPars[j], val);
@@ -476,21 +470,21 @@ HRESULT CCodecs::LoadFormats()
476 470
477 { 471 {
478 bool defined = false; 472 bool defined = false;
479 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kTimeFlags, item.TimeFlags, defined)); 473 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kTimeFlags, item.TimeFlags, defined))
480 } 474 }
481 475
482 CByteBuffer sig; 476 CByteBuffer sig;
483 RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kSignature, sig)); 477 RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kSignature, sig))
484 if (sig.Size() != 0) 478 if (sig.Size() != 0)
485 item.Signatures.Add(sig); 479 item.Signatures.Add(sig);
486 else 480 else
487 { 481 {
488 RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kMultiSignature, sig)); 482 RINOK(GetProp_RawData(getProp, getProp2, i, NArchive::NHandlerPropID::kMultiSignature, sig))
489 ParseSignatures(sig, (unsigned)sig.Size(), item.Signatures); 483 ParseSignatures(sig, (unsigned)sig.Size(), item.Signatures);
490 } 484 }
491 485
492 bool signatureOffset_Defined; 486 bool signatureOffset_Defined;
493 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kSignatureOffset, item.SignatureOffset, signatureOffset_Defined)); 487 RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kSignatureOffset, item.SignatureOffset, signatureOffset_Defined))
494 488
495 // bool version_Defined; 489 // bool version_Defined;
496 // RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kVersion, item.Version, version_Defined)); 490 // RINOK(GetProp_UInt32(getProp, getProp2, i, NArchive::NHandlerPropID::kVersion, item.Version, version_Defined));
@@ -503,7 +497,7 @@ HRESULT CCodecs::LoadFormats()
503 return S_OK; 497 return S_OK;
504} 498}
505 499
506#ifdef _7ZIP_LARGE_PAGES 500#ifdef Z7_LARGE_PAGES
507extern "C" 501extern "C"
508{ 502{
509 extern SIZE_T g_LargePageSize; 503 extern SIZE_T g_LargePageSize;
@@ -513,12 +507,57 @@ extern "C"
513 507
514void CCodecs::AddLastError(const FString &path) 508void CCodecs::AddLastError(const FString &path)
515{ 509{
516 HRESULT res = GetLastError_noZero_HRESULT(); 510 const HRESULT res = GetLastError_noZero_HRESULT();
517 CCodecError &error = Errors.AddNew(); 511 CCodecError &error = Errors.AddNew();
518 error.Path = path; 512 error.Path = path;
519 error.ErrorCode = res; 513 error.ErrorCode = res;
520} 514}
521 515
516
517static bool IsSupportedDll(CCodecLib &lib)
518{
519 MY_GET_FUNC_LOC (
520 f_GetModuleProp,
521 Func_GetModuleProp, lib.Lib,
522 "GetModuleProp")
523 /* p7zip and 7-Zip before v23 used virtual destructor in IUnknown,
524 if _WIN32 is not defined */
525 UInt32 flags =
526 #ifdef _WIN32
527 NModuleInterfaceType::k_IUnknown_VirtDestructor_No;
528 #else
529 NModuleInterfaceType::k_IUnknown_VirtDestructor_Yes;
530 #endif
531 if (f_GetModuleProp)
532 {
533 {
534 NCOM::CPropVariant prop;
535 if (f_GetModuleProp(NModulePropID::kInterfaceType, &prop) == S_OK)
536 {
537 if (prop.vt == VT_UI4)
538 flags = prop.ulVal;
539 else if (prop.vt != VT_EMPTY)
540 return false;
541 }
542 }
543 {
544 NCOM::CPropVariant prop;
545 if (f_GetModuleProp(NModulePropID::kVersion, &prop) == S_OK)
546 {
547 if (prop.vt == VT_UI4)
548 lib.Version = prop.ulVal;
549 }
550 }
551 }
552 if (
553 flags
554 // (flags & NModuleFlags::kMask)
555 != NModuleInterfaceType::k_IUnknown_VirtDestructor_ThisModule)
556 return false;
557 return true;
558}
559
560
522HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loadedOK) 561HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loadedOK)
523{ 562{
524 if (loadedOK) 563 if (loadedOK)
@@ -537,7 +576,7 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
537 // #define ERROR_BAD_EXE_FORMAT 193L 576 // #define ERROR_BAD_EXE_FORMAT 193L
538 */ 577 */
539 // return GetLastError_noZero_HRESULT(); 578 // return GetLastError_noZero_HRESULT();
540 DWORD lastError = GetLastError(); 579 const DWORD lastError = GetLastError();
541 if (lastError != ERROR_BAD_EXE_FORMAT) 580 if (lastError != ERROR_BAD_EXE_FORMAT)
542 { 581 {
543 CCodecError &error = Errors.AddNew(); 582 CCodecError &error = Errors.AddNew();
@@ -558,20 +597,30 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
558 bool used = false; 597 bool used = false;
559 // HRESULT res = S_OK; 598 // HRESULT res = S_OK;
560 599
561 if (lib.Lib.Load(dllPath)) 600 if (lib.Lib.Load(dllPath))
601 {
602 if (!IsSupportedDll(lib))
603 {
604 CCodecError &error = Errors.AddNew();
605 error.Path = dllPath;
606 error.Message = "the module is not compatible with program";
607 }
608 else
562 { 609 {
563 if (loadedOK) 610 if (loadedOK)
564 *loadedOK = true; 611 *loadedOK = true;
612 /*
565 #ifdef NEW_FOLDER_INTERFACE 613 #ifdef NEW_FOLDER_INTERFACE
566 lib.LoadIcons(); 614 lib.LoadIcons();
567 #endif 615 #endif
616 */
568 617
569 /* 618 /*
570 { 619 {
571 MY_GET_FUNC_LOC (_LibStartup, Func_LibStartup, lib.Lib.GetProc("LibStartup")); 620 MY_GET_FUNC_LOC (_libStartup, Func_libStartup, lib.Lib, "LibStartup")
572 if (_LibStartup) 621 if (_libStartup)
573 { 622 {
574 HRESULT res = _LibStartup(); 623 HRESULT res = _libStartup();
575 if (res != 0) 624 if (res != 0)
576 { 625 {
577 CCodecError &error = Errors.AddNew(); 626 CCodecError &error = Errors.AddNew();
@@ -582,10 +631,10 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
582 } 631 }
583 */ 632 */
584 633
585 #ifdef _7ZIP_LARGE_PAGES 634 #ifdef Z7_LARGE_PAGES
586 if (g_LargePageSize != 0) 635 if (g_LargePageSize != 0)
587 { 636 {
588 MY_GET_FUNC_LOC (setLargePageMode, Func_SetLargePageMode, lib.Lib.GetProc("SetLargePageMode")); 637 MY_GET_FUNC_LOC (setLargePageMode, Func_SetLargePageMode, lib.Lib, "SetLargePageMode")
589 if (setLargePageMode) 638 if (setLargePageMode)
590 setLargePageMode(); 639 setLargePageMode();
591 } 640 }
@@ -593,14 +642,14 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
593 642
594 if (CaseSensitive_Change) 643 if (CaseSensitive_Change)
595 { 644 {
596 MY_GET_FUNC_LOC (setCaseSensitive, Func_SetCaseSensitive, lib.Lib.GetProc("SetCaseSensitive")); 645 MY_GET_FUNC_LOC (setCaseSensitive, Func_SetCaseSensitive, lib.Lib, "SetCaseSensitive")
597 if (setCaseSensitive) 646 if (setCaseSensitive)
598 setCaseSensitive(CaseSensitive ? 1 : 0); 647 setCaseSensitive(CaseSensitive ? 1 : 0);
599 } 648 }
600 649
601 /* 650 /*
602 { 651 {
603 MY_GET_FUNC_LOC (setClientVersion, Func_SetClientVersion, lib.Lib.GetProc("SetClientVersion")); 652 MY_GET_FUNC_LOC (setClientVersion, Func_SetClientVersion, lib.Lib, "SetClientVersion")
604 if (setClientVersion) 653 if (setClientVersion)
605 { 654 {
606 // const UInt32 kVersion = (MY_VER_MAJOR << 16) | MY_VER_MINOR; 655 // const UInt32 kVersion = (MY_VER_MAJOR << 16) | MY_VER_MINOR;
@@ -610,7 +659,7 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
610 */ 659 */
611 660
612 661
613 MY_GET_FUNC (lib.CreateObject, Func_CreateObject, lib.Lib.GetProc("CreateObject")); 662 MY_GET_FUNC (lib.CreateObject, Func_CreateObject, lib.Lib, "CreateObject")
614 { 663 {
615 unsigned startSize = Codecs.Size() + Hashers.Size(); 664 unsigned startSize = Codecs.Size() + Hashers.Size();
616 HRESULT res = LoadCodecs(); 665 HRESULT res = LoadCodecs();
@@ -640,7 +689,8 @@ HRESULT CCodecs::LoadDll(const FString &dllPath, bool needCheckDll, bool *loaded
640 } 689 }
641 */ 690 */
642 } 691 }
643 else 692 }
693 else
644 { 694 {
645 AddLastError(dllPath); 695 AddLastError(dllPath);
646 } 696 }
@@ -686,7 +736,7 @@ HRESULT CCodecs::LoadDllsFromFolder(const FString &folderPath)
686 continue; 736 continue;
687 #endif 737 #endif
688 738
689 RINOK(LoadDll(folderPrefix + fi.Name, true)); 739 RINOK(LoadDll(folderPrefix + fi.Name, true))
690 } 740 }
691 return S_OK; 741 return S_OK;
692} 742}
@@ -714,18 +764,20 @@ void CCodecs::CloseLibs()
714 // OutputDebugStringA("~CloseLibs end"); 764 // OutputDebugStringA("~CloseLibs end");
715} 765}
716 766
717#endif // EXTERNAL_CODECS 767#endif // Z7_EXTERNAL_CODECS
718 768
719 769
720HRESULT CCodecs::Load() 770HRESULT CCodecs::Load()
721{ 771{
772 /*
722 #ifdef NEW_FOLDER_INTERFACE 773 #ifdef NEW_FOLDER_INTERFACE
723 InternalIcons.LoadIcons(g_hInstance); 774 InternalIcons.LoadIcons(g_hInstance);
724 #endif 775 #endif
776 */
725 777
726 Formats.Clear(); 778 Formats.Clear();
727 779
728 #ifdef EXTERNAL_CODECS 780 #ifdef Z7_EXTERNAL_CODECS
729 Errors.Clear(); 781 Errors.Clear();
730 MainDll_ErrorPath.Empty(); 782 MainDll_ErrorPath.Empty();
731 Codecs.Clear(); 783 Codecs.Clear();
@@ -751,7 +803,7 @@ HRESULT CCodecs::Load()
751 item.AddExts(e, ae); 803 item.AddExts(e, ae);
752 } 804 }
753 805
754 #ifndef _SFX 806 #ifndef Z7_SFX
755 807
756 item.CreateOutArchive = arc.CreateOutArchive; 808 item.CreateOutArchive = arc.CreateOutArchive;
757 item.UpdateEnabled = (arc.CreateOutArchive != NULL); 809 item.UpdateEnabled = (arc.CreateOutArchive != NULL);
@@ -774,16 +826,16 @@ HRESULT CCodecs::Load()
774 826
775 // printf("\nLoad codecs \n"); 827 // printf("\nLoad codecs \n");
776 828
777 #ifdef EXTERNAL_CODECS 829 #ifdef Z7_EXTERNAL_CODECS
778 const FString baseFolder = GetBaseFolderPrefixFromRegistry(); 830 const FString baseFolder = GetBaseFolderPrefixFromRegistry();
779 { 831 {
780 bool loadedOK; 832 bool loadedOK;
781 RINOK(LoadDll(baseFolder + kMainDll, false, &loadedOK)); 833 RINOK(LoadDll(baseFolder + kMainDll, false, &loadedOK))
782 if (!loadedOK) 834 if (!loadedOK)
783 MainDll_ErrorPath = kMainDll; 835 MainDll_ErrorPath = kMainDll;
784 } 836 }
785 RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName)); 837 RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName))
786 RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName)); 838 RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName))
787 839
788 NeedSetLibCodecs = true; 840 NeedSetLibCodecs = true;
789 841
@@ -806,10 +858,10 @@ HRESULT CCodecs::Load()
806 FOR_VECTOR(i, Libs) 858 FOR_VECTOR(i, Libs)
807 { 859 {
808 CCodecLib &lib = Libs[i]; 860 CCodecLib &lib = Libs[i];
809 MY_GET_FUNC (lib.SetCodecs, Func_SetCodecs, lib.Lib.GetProc("SetCodecs")); 861 MY_GET_FUNC (lib.SetCodecs, Func_SetCodecs, lib.Lib, "SetCodecs")
810 if (lib.SetCodecs) 862 if (lib.SetCodecs)
811 { 863 {
812 RINOK(lib.SetCodecs(this)); 864 RINOK(lib.SetCodecs(this))
813 } 865 }
814 } 866 }
815 } 867 }
@@ -821,7 +873,7 @@ HRESULT CCodecs::Load()
821 return S_OK; 873 return S_OK;
822} 874}
823 875
824#ifndef _SFX 876#ifndef Z7_SFX
825 877
826int CCodecs::FindFormatForArchiveName(const UString &arcPath) const 878int CCodecs::FindFormatForArchiveName(const UString &arcPath) const
827{ 879{
@@ -887,60 +939,10 @@ bool CCodecs::FindFormatForArchiveType(const UString &arcType, CIntVector &forma
887 return true; 939 return true;
888} 940}
889 941
890#endif // _SFX 942#endif // Z7_SFX
891
892
893#ifdef NEW_FOLDER_INTERFACE
894
895void CCodecIcons::LoadIcons(HMODULE m)
896{
897 UString iconTypes;
898 MyLoadString(m, kIconTypesResId, iconTypes);
899 UStringVector pairs;
900 SplitString(iconTypes, pairs);
901 FOR_VECTOR (i, pairs)
902 {
903 const UString &s = pairs[i];
904 int pos = s.Find(L':');
905 CIconPair iconPair;
906 iconPair.IconIndex = -1;
907 if (pos < 0)
908 pos = (int)s.Len();
909 else
910 {
911 const UString num = s.Ptr((unsigned)pos + 1);
912 if (!num.IsEmpty())
913 {
914 const wchar_t *end;
915 iconPair.IconIndex = (int)ConvertStringToUInt32(num, &end);
916 if (*end != 0)
917 continue;
918 }
919 }
920 iconPair.Ext = s.Left((unsigned)pos);
921 IconPairs.Add(iconPair);
922 }
923}
924
925bool CCodecIcons::FindIconIndex(const UString &ext, int &iconIndex) const
926{
927 iconIndex = -1;
928 FOR_VECTOR (i, IconPairs)
929 {
930 const CIconPair &pair = IconPairs[i];
931 if (ext.IsEqualTo_NoCase(pair.Ext))
932 {
933 iconIndex = pair.IconIndex;
934 return true;
935 }
936 }
937 return false;
938}
939
940#endif // NEW_FOLDER_INTERFACE
941 943
942 944
943#ifdef EXTERNAL_CODECS 945#ifdef Z7_EXTERNAL_CODECS
944 946
945// #define EXPORT_CODECS 947// #define EXPORT_CODECS
946 948
@@ -964,24 +966,24 @@ STDAPI GetHasherProp(UInt32 codecIndex, PROPID propID, PROPVARIANT *value);
964 966
965#endif // EXPORT_CODECS 967#endif // EXPORT_CODECS
966 968
967STDMETHODIMP CCodecs::GetNumMethods(UInt32 *numMethods) 969Z7_COM7F_IMF(CCodecs::GetNumMethods(UInt32 *numMethods))
968{ 970{
969 *numMethods = NUM_EXPORT_CODECS 971 *numMethods = NUM_EXPORT_CODECS
970 #ifdef EXTERNAL_CODECS 972 #ifdef Z7_EXTERNAL_CODECS
971 + Codecs.Size() 973 + Codecs.Size()
972 #endif 974 #endif
973 ; 975 ;
974 return S_OK; 976 return S_OK;
975} 977}
976 978
977STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 979Z7_COM7F_IMF(CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
978{ 980{
979 #ifdef EXPORT_CODECS 981 #ifdef EXPORT_CODECS
980 if (index < g_NumCodecs) 982 if (index < g_NumCodecs)
981 return GetMethodProperty(index, propID, value); 983 return GetMethodProperty(index, propID, value);
982 #endif 984 #endif
983 985
984 #ifdef EXTERNAL_CODECS 986 #ifdef Z7_EXTERNAL_CODECS
985 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; 987 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS];
986 988
987 if (propID == NMethodPropID::kDecoderIsAssigned || 989 if (propID == NMethodPropID::kDecoderIsAssigned ||
@@ -1010,14 +1012,14 @@ STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *valu
1010 #endif 1012 #endif
1011} 1013}
1012 1014
1013STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder) 1015Z7_COM7F_IMF(CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder))
1014{ 1016{
1015 #ifdef EXPORT_CODECS 1017 #ifdef EXPORT_CODECS
1016 if (index < g_NumCodecs) 1018 if (index < g_NumCodecs)
1017 return CreateDecoder(index, iid, coder); 1019 return CreateDecoder(index, iid, coder);
1018 #endif 1020 #endif
1019 1021
1020 #ifdef EXTERNAL_CODECS 1022 #ifdef Z7_EXTERNAL_CODECS
1021 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; 1023 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS];
1022 if (ci.DecoderIsAssigned) 1024 if (ci.DecoderIsAssigned)
1023 { 1025 {
@@ -1033,14 +1035,14 @@ STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder)
1033 #endif 1035 #endif
1034} 1036}
1035 1037
1036STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder) 1038Z7_COM7F_IMF(CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder))
1037{ 1039{
1038 #ifdef EXPORT_CODECS 1040 #ifdef EXPORT_CODECS
1039 if (index < g_NumCodecs) 1041 if (index < g_NumCodecs)
1040 return CreateEncoder(index, iid, coder); 1042 return CreateEncoder(index, iid, coder);
1041 #endif 1043 #endif
1042 1044
1043 #ifdef EXTERNAL_CODECS 1045 #ifdef Z7_EXTERNAL_CODECS
1044 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; 1046 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS];
1045 if (ci.EncoderIsAssigned) 1047 if (ci.EncoderIsAssigned)
1046 { 1048 {
@@ -1057,23 +1059,23 @@ STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder)
1057} 1059}
1058 1060
1059 1061
1060STDMETHODIMP_(UInt32) CCodecs::GetNumHashers() 1062Z7_COM7F_IMF2(UInt32, CCodecs::GetNumHashers())
1061{ 1063{
1062 return NUM_EXPORT_HASHERS 1064 return NUM_EXPORT_HASHERS
1063 #ifdef EXTERNAL_CODECS 1065 #ifdef Z7_EXTERNAL_CODECS
1064 + Hashers.Size() 1066 + Hashers.Size()
1065 #endif 1067 #endif
1066 ; 1068 ;
1067} 1069}
1068 1070
1069STDMETHODIMP CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value) 1071Z7_COM7F_IMF(CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *value))
1070{ 1072{
1071 #ifdef EXPORT_CODECS 1073 #ifdef EXPORT_CODECS
1072 if (index < g_NumHashers) 1074 if (index < g_NumHashers)
1073 return ::GetHasherProp(index, propID, value); 1075 return ::GetHasherProp(index, propID, value);
1074 #endif 1076 #endif
1075 1077
1076 #ifdef EXTERNAL_CODECS 1078 #ifdef Z7_EXTERNAL_CODECS
1077 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; 1079 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS];
1078 return Libs[ci.LibIndex].ComHashers->GetHasherProp(ci.HasherIndex, propID, value); 1080 return Libs[ci.LibIndex].ComHashers->GetHasherProp(ci.HasherIndex, propID, value);
1079 #else 1081 #else
@@ -1081,13 +1083,13 @@ STDMETHODIMP CCodecs::GetHasherProp(UInt32 index, PROPID propID, PROPVARIANT *va
1081 #endif 1083 #endif
1082} 1084}
1083 1085
1084STDMETHODIMP CCodecs::CreateHasher(UInt32 index, IHasher **hasher) 1086Z7_COM7F_IMF(CCodecs::CreateHasher(UInt32 index, IHasher **hasher))
1085{ 1087{
1086 #ifdef EXPORT_CODECS 1088 #ifdef EXPORT_CODECS
1087 if (index < g_NumHashers) 1089 if (index < g_NumHashers)
1088 return CreateHasher(index, hasher); 1090 return CreateHasher(index, hasher);
1089 #endif 1091 #endif
1090 #ifdef EXTERNAL_CODECS 1092 #ifdef Z7_EXTERNAL_CODECS
1091 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; 1093 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS];
1092 return Libs[ci.LibIndex].ComHashers->CreateHasher(ci.HasherIndex, hasher); 1094 return Libs[ci.LibIndex].ComHashers->CreateHasher(ci.HasherIndex, hasher);
1093 #else 1095 #else
@@ -1102,7 +1104,7 @@ int CCodecs::GetCodec_LibIndex(UInt32 index) const
1102 return -1; 1104 return -1;
1103 #endif 1105 #endif
1104 1106
1105 #ifdef EXTERNAL_CODECS 1107 #ifdef Z7_EXTERNAL_CODECS
1106 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS]; 1108 const CDllCodecInfo &ci = Codecs[index - NUM_EXPORT_CODECS];
1107 return (int)ci.LibIndex; 1109 return (int)ci.LibIndex;
1108 #else 1110 #else
@@ -1117,7 +1119,7 @@ int CCodecs::GetHasherLibIndex(UInt32 index)
1117 return -1; 1119 return -1;
1118 #endif 1120 #endif
1119 1121
1120 #ifdef EXTERNAL_CODECS 1122 #ifdef Z7_EXTERNAL_CODECS
1121 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS]; 1123 const CDllHasherInfo &ci = Hashers[index - NUM_EXPORT_HASHERS];
1122 return (int)ci.LibIndex; 1124 return (int)ci.LibIndex;
1123 #else 1125 #else
@@ -1140,7 +1142,7 @@ bool CCodecs::GetCodec_DecoderIsAssigned(UInt32 index) const
1140 } 1142 }
1141 #endif 1143 #endif
1142 1144
1143 #ifdef EXTERNAL_CODECS 1145 #ifdef Z7_EXTERNAL_CODECS
1144 return Codecs[index - NUM_EXPORT_CODECS].DecoderIsAssigned; 1146 return Codecs[index - NUM_EXPORT_CODECS].DecoderIsAssigned;
1145 #else 1147 #else
1146 return false; 1148 return false;
@@ -1163,7 +1165,7 @@ bool CCodecs::GetCodec_EncoderIsAssigned(UInt32 index) const
1163 } 1165 }
1164 #endif 1166 #endif
1165 1167
1166 #ifdef EXTERNAL_CODECS 1168 #ifdef Z7_EXTERNAL_CODECS
1167 return Codecs[index - NUM_EXPORT_CODECS].EncoderIsAssigned; 1169 return Codecs[index - NUM_EXPORT_CODECS].EncoderIsAssigned;
1168 #else 1170 #else
1169 return false; 1171 return false;
@@ -1190,7 +1192,7 @@ bool CCodecs::GetCodec_IsFilter(UInt32 index, bool &isAssigned) const
1190 } 1192 }
1191 #endif 1193 #endif
1192 1194
1193 #ifdef EXTERNAL_CODECS 1195 #ifdef Z7_EXTERNAL_CODECS
1194 { 1196 {
1195 const CDllCodecInfo &c = Codecs[index - NUM_EXPORT_CODECS]; 1197 const CDllCodecInfo &c = Codecs[index - NUM_EXPORT_CODECS];
1196 isAssigned = c.IsFilter_Assigned; 1198 isAssigned = c.IsFilter_Assigned;
@@ -1217,7 +1219,7 @@ UInt32 CCodecs::GetCodec_NumStreams(UInt32 index)
1217HRESULT CCodecs::GetCodec_Id(UInt32 index, UInt64 &id) 1219HRESULT CCodecs::GetCodec_Id(UInt32 index, UInt64 &id)
1218{ 1220{
1219 NCOM::CPropVariant prop; 1221 NCOM::CPropVariant prop;
1220 RINOK(GetProperty(index, NMethodPropID::kID, &prop)); 1222 RINOK(GetProperty(index, NMethodPropID::kID, &prop))
1221 if (prop.vt != VT_UI8) 1223 if (prop.vt != VT_UI8)
1222 return E_INVALIDARG; 1224 return E_INVALIDARG;
1223 id = prop.uhVal.QuadPart; 1225 id = prop.uhVal.QuadPart;
@@ -1286,9 +1288,9 @@ void CCodecs::GetCodecsErrorMessage(UString &s)
1286 } 1288 }
1287} 1289}
1288 1290
1289#endif // EXTERNAL_CODECS 1291#endif // Z7_EXTERNAL_CODECS
1290 1292
1291#ifndef _SFX 1293#ifndef Z7_SFX
1292 1294
1293extern unsigned g_NumCodecs; 1295extern unsigned g_NumCodecs;
1294extern const CCodecInfo *g_Codecs[]; 1296extern const CCodecInfo *g_Codecs[];
@@ -1311,7 +1313,7 @@ void CCodecs::Get_CodecsInfoUser_Vector(CObjectVector<CCodecInfoUser> &v)
1311 } 1313 }
1312 1314
1313 1315
1314 #ifdef EXTERNAL_CODECS 1316 #ifdef Z7_EXTERNAL_CODECS
1315 { 1317 {
1316 UInt32 numMethods; 1318 UInt32 numMethods;
1317 if (GetNumMethods(&numMethods) == S_OK) 1319 if (GetNumMethods(&numMethods) == S_OK)
diff --git a/CPP/7zip/UI/Common/LoadCodecs.h b/CPP/7zip/UI/Common/LoadCodecs.h
index 50fb9f8..a81bb5c 100644
--- a/CPP/7zip/UI/Common/LoadCodecs.h
+++ b/CPP/7zip/UI/Common/LoadCodecs.h
@@ -1,7 +1,7 @@
1// LoadCodecs.h 1// LoadCodecs.h
2 2
3#ifndef __LOAD_CODECS_H 3#ifndef ZIP7_INC_LOAD_CODECS_H
4#define __LOAD_CODECS_H 4#define ZIP7_INC_LOAD_CODECS_H
5 5
6/* 6/*
7Client application uses LoadCodecs.* to load plugins to 7Client application uses LoadCodecs.* to load plugins to
@@ -10,26 +10,26 @@ CCodecs object, that contains 3 lists of plugins:
10 2) Codecs - external codecs 10 2) Codecs - external codecs
11 3) Hashers - external hashers 11 3) Hashers - external hashers
12 12
13EXTERNAL_CODECS 13Z7_EXTERNAL_CODECS
14--------------- 14---------------
15 15
16 if EXTERNAL_CODECS is defined, then the code tries to load external 16 if Z7_EXTERNAL_CODECS is defined, then the code tries to load external
17 plugins from DLL files (shared libraries). 17 plugins from DLL files (shared libraries).
18 18
19 There are two types of executables in 7-Zip: 19 There are two types of executables in 7-Zip:
20 20
21 1) Executable that uses external plugins must be compiled 21 1) Executable that uses external plugins must be compiled
22 with EXTERNAL_CODECS defined: 22 with Z7_EXTERNAL_CODECS defined:
23 - 7z.exe, 7zG.exe, 7zFM.exe 23 - 7z.exe, 7zG.exe, 7zFM.exe
24 24
25 Note: EXTERNAL_CODECS is used also in CPP/7zip/Common/CreateCoder.h 25 Note: Z7_EXTERNAL_CODECS is used also in CPP/7zip/Common/CreateCoder.h
26 that code is used in plugin module (7z.dll). 26 that code is used in plugin module (7z.dll).
27 27
28 2) Standalone modules are compiled without EXTERNAL_CODECS: 28 2) Standalone modules are compiled without Z7_EXTERNAL_CODECS:
29 - SFX modules: 7z.sfx, 7zCon.sfx 29 - SFX modules: 7z.sfx, 7zCon.sfx
30 - standalone versions of console 7-Zip: 7za.exe, 7zr.exe 30 - standalone versions of console 7-Zip: 7za.exe, 7zr.exe
31 31
32 if EXTERNAL_CODECS is defined, CCodecs class implements interfaces: 32 if Z7_EXTERNAL_CODECS is defined, CCodecs class implements interfaces:
33 - ICompressCodecsInfo : for Codecs 33 - ICompressCodecsInfo : for Codecs
34 - IHashers : for Hashers 34 - IHashers : for Hashers
35 35
@@ -51,7 +51,7 @@ EXTERNAL_CODECS
51#include "../../../Common/MyString.h" 51#include "../../../Common/MyString.h"
52#include "../../../Common/ComTry.h" 52#include "../../../Common/ComTry.h"
53 53
54#ifdef EXTERNAL_CODECS 54#ifdef Z7_EXTERNAL_CODECS
55#include "../../../Windows/DLL.h" 55#include "../../../Windows/DLL.h"
56#endif 56#endif
57 57
@@ -60,7 +60,7 @@ EXTERNAL_CODECS
60#include "../../Archive/IArchive.h" 60#include "../../Archive/IArchive.h"
61 61
62 62
63#ifdef EXTERNAL_CODECS 63#ifdef Z7_EXTERNAL_CODECS
64 64
65struct CDllCodecInfo 65struct CDllCodecInfo
66{ 66{
@@ -104,19 +104,21 @@ struct CArcInfoEx
104 UString Name; 104 UString Name;
105 CObjectVector<CArcExtInfo> Exts; 105 CObjectVector<CArcExtInfo> Exts;
106 106
107 #ifndef _SFX 107 #ifndef Z7_SFX
108 Func_CreateOutArchive CreateOutArchive; 108 Func_CreateOutArchive CreateOutArchive;
109 bool UpdateEnabled; 109 bool UpdateEnabled;
110 bool NewInterface; 110 bool NewInterface;
111 // UInt32 Version; 111 // UInt32 Version;
112 UInt32 SignatureOffset; 112 UInt32 SignatureOffset;
113 CObjectVector<CByteBuffer> Signatures; 113 CObjectVector<CByteBuffer> Signatures;
114 /*
114 #ifdef NEW_FOLDER_INTERFACE 115 #ifdef NEW_FOLDER_INTERFACE
115 UStringVector AssociateExts; 116 UStringVector AssociateExts;
116 #endif 117 #endif
118 */
117 #endif 119 #endif
118 120
119 #ifdef EXTERNAL_CODECS 121 #ifdef Z7_EXTERNAL_CODECS
120 int LibIndex; 122 int LibIndex;
121 UInt32 FormatIndex; 123 UInt32 FormatIndex;
122 CLSID ClassID; 124 CLSID ClassID;
@@ -124,10 +126,10 @@ struct CArcInfoEx
124 126
125 int Compare(const CArcInfoEx &a) const 127 int Compare(const CArcInfoEx &a) const
126 { 128 {
127 int res = Name.Compare(a.Name); 129 const int res = Name.Compare(a.Name);
128 if (res != 0) 130 if (res != 0)
129 return res; 131 return res;
130 #ifdef EXTERNAL_CODECS 132 #ifdef Z7_EXTERNAL_CODECS
131 return MyCompare(LibIndex, a.LibIndex); 133 return MyCompare(LibIndex, a.LibIndex);
132 #else 134 #else
133 return 0; 135 return 0;
@@ -192,6 +194,7 @@ struct CArcInfoEx
192 bool Is_Tar() const { return Name.IsEqualTo_Ascii_NoCase("tar"); } 194 bool Is_Tar() const { return Name.IsEqualTo_Ascii_NoCase("tar"); }
193 bool Is_Zip() const { return Name.IsEqualTo_Ascii_NoCase("zip"); } 195 bool Is_Zip() const { return Name.IsEqualTo_Ascii_NoCase("zip"); }
194 bool Is_Rar() const { return Name.IsEqualTo_Ascii_NoCase("rar"); } 196 bool Is_Rar() const { return Name.IsEqualTo_Ascii_NoCase("rar"); }
197 bool Is_Zstd() const { return Name.IsEqualTo_Ascii_NoCase("zstd"); }
195 198
196 /* 199 /*
197 UString GetAllExtensions() const 200 UString GetAllExtensions() const
@@ -200,7 +203,7 @@ struct CArcInfoEx
200 for (int i = 0; i < Exts.Size(); i++) 203 for (int i = 0; i < Exts.Size(); i++)
201 { 204 {
202 if (i > 0) 205 if (i > 0)
203 s += ' '; 206 s.Add_Space();
204 s += Exts[i].Ext; 207 s += Exts[i].Ext;
205 } 208 }
206 return s; 209 return s;
@@ -215,42 +218,23 @@ struct CArcInfoEx
215 TimeFlags(0), 218 TimeFlags(0),
216 CreateInArchive(NULL), 219 CreateInArchive(NULL),
217 IsArcFunc(NULL) 220 IsArcFunc(NULL)
218 #ifndef _SFX 221 #ifndef Z7_SFX
219 , CreateOutArchive(NULL) 222 , CreateOutArchive(NULL)
220 , UpdateEnabled(false) 223 , UpdateEnabled(false)
221 , NewInterface(false) 224 , NewInterface(false)
222 // , Version(0) 225 // , Version(0)
223 , SignatureOffset(0) 226 , SignatureOffset(0)
224 #endif 227 #endif
225 #ifdef EXTERNAL_CODECS 228 #ifdef Z7_EXTERNAL_CODECS
226 , LibIndex(-1) 229 , LibIndex(-1)
227 #endif 230 #endif
228 {} 231 {}
229}; 232};
230 233
231#ifdef NEW_FOLDER_INTERFACE
232
233struct CCodecIcons
234{
235 struct CIconPair
236 {
237 UString Ext;
238 int IconIndex;
239 };
240 CObjectVector<CIconPair> IconPairs;
241
242 void LoadIcons(HMODULE m);
243 bool FindIconIndex(const UString &ext, int &iconIndex) const;
244};
245
246#endif
247 234
248#ifdef EXTERNAL_CODECS 235#ifdef Z7_EXTERNAL_CODECS
249 236
250struct CCodecLib 237struct CCodecLib
251 #ifdef NEW_FOLDER_INTERFACE
252 : public CCodecIcons
253 #endif
254{ 238{
255 NWindows::NDLL::CLibrary Lib; 239 NWindows::NDLL::CLibrary Lib;
256 FString Path; 240 FString Path;
@@ -262,17 +246,23 @@ struct CCodecLib
262 Func_SetCodecs SetCodecs; 246 Func_SetCodecs SetCodecs;
263 247
264 CMyComPtr<IHashers> ComHashers; 248 CMyComPtr<IHashers> ComHashers;
249
250 UInt32 Version;
265 251
252 /*
266 #ifdef NEW_FOLDER_INTERFACE 253 #ifdef NEW_FOLDER_INTERFACE
267 void LoadIcons() { CCodecIcons::LoadIcons((HMODULE)Lib); } 254 CCodecIcons CodecIcons;
255 void LoadIcons() { CodecIcons.LoadIcons((HMODULE)Lib); }
268 #endif 256 #endif
257 */
269 258
270 CCodecLib(): 259 CCodecLib():
271 CreateObject(NULL), 260 CreateObject(NULL),
272 GetMethodProperty(NULL), 261 GetMethodProperty(NULL),
273 CreateDecoder(NULL), 262 CreateDecoder(NULL),
274 CreateEncoder(NULL), 263 CreateEncoder(NULL),
275 SetCodecs(NULL) 264 SetCodecs(NULL),
265 Version(0)
276 {} 266 {}
277}; 267};
278 268
@@ -301,8 +291,8 @@ struct CCodecInfoUser
301}; 291};
302 292
303 293
304class CCodecs: 294class CCodecs Z7_final:
305 #ifdef EXTERNAL_CODECS 295 #ifdef Z7_EXTERNAL_CODECS
306 public ICompressCodecsInfo, 296 public ICompressCodecsInfo,
307 public IHashers, 297 public IHashers,
308 #else 298 #else
@@ -310,9 +300,15 @@ class CCodecs:
310 #endif 300 #endif
311 public CMyUnknownImp 301 public CMyUnknownImp
312{ 302{
313 CLASS_NO_COPY(CCodecs); 303#ifdef Z7_EXTERNAL_CODECS
304 Z7_IFACES_IMP_UNK_2(ICompressCodecsInfo, IHashers)
305#else
306 Z7_COM_UNKNOWN_IMP_0
307#endif // Z7_EXTERNAL_CODECS
308
309 Z7_CLASS_NO_COPY(CCodecs)
314public: 310public:
315 #ifdef EXTERNAL_CODECS 311 #ifdef Z7_EXTERNAL_CODECS
316 312
317 CObjectVector<CCodecLib> Libs; 313 CObjectVector<CCodecLib> Libs;
318 FString MainDll_ErrorPath; 314 FString MainDll_ErrorPath;
@@ -323,7 +319,7 @@ public:
323 319
324 class CReleaser 320 class CReleaser
325 { 321 {
326 CLASS_NO_COPY(CReleaser); 322 Z7_CLASS_NO_COPY(CReleaser)
327 323
328 /* CCodecsReleaser object releases CCodecs links. 324 /* CCodecsReleaser object releases CCodecs links.
329 1) CCodecs is COM object that is deleted when all links to that object will be released/ 325 1) CCodecs is COM object that is deleted when all links to that object will be released/
@@ -352,13 +348,15 @@ public:
352 348
353 #endif 349 #endif
354 350
351 /*
355 #ifdef NEW_FOLDER_INTERFACE 352 #ifdef NEW_FOLDER_INTERFACE
356 CCodecIcons InternalIcons; 353 CCodecIcons InternalIcons;
357 #endif 354 #endif
355 */
358 356
359 CObjectVector<CArcInfoEx> Formats; 357 CObjectVector<CArcInfoEx> Formats;
360 358
361 #ifdef EXTERNAL_CODECS 359 #ifdef Z7_EXTERNAL_CODECS
362 CRecordVector<CDllCodecInfo> Codecs; 360 CRecordVector<CDllCodecInfo> Codecs;
363 CRecordVector<CDllHasherInfo> Hashers; 361 CRecordVector<CDllHasherInfo> Hashers;
364 #endif 362 #endif
@@ -367,7 +365,7 @@ public:
367 bool CaseSensitive; 365 bool CaseSensitive;
368 366
369 CCodecs(): 367 CCodecs():
370 #ifdef EXTERNAL_CODECS 368 #ifdef Z7_EXTERNAL_CODECS
371 NeedSetLibCodecs(true), 369 NeedSetLibCodecs(true),
372 #endif 370 #endif
373 CaseSensitive_Change(false), 371 CaseSensitive_Change(false),
@@ -386,34 +384,14 @@ public:
386 384
387 HRESULT Load(); 385 HRESULT Load();
388 386
389 #ifndef _SFX 387 #ifndef Z7_SFX
390 int FindFormatForArchiveName(const UString &arcPath) const; 388 int FindFormatForArchiveName(const UString &arcPath) const;
391 int FindFormatForExtension(const UString &ext) const; 389 int FindFormatForExtension(const UString &ext) const;
392 int FindFormatForArchiveType(const UString &arcType) const; 390 int FindFormatForArchiveType(const UString &arcType) const;
393 bool FindFormatForArchiveType(const UString &arcType, CIntVector &formatIndices) const; 391 bool FindFormatForArchiveType(const UString &arcType, CIntVector &formatIndices) const;
394 #endif 392 #endif
395 393
396 #ifdef EXTERNAL_CODECS 394 #ifdef Z7_EXTERNAL_CODECS
397
398 MY_UNKNOWN_IMP2(ICompressCodecsInfo, IHashers)
399
400 STDMETHOD(GetNumMethods)(UInt32 *numMethods);
401 STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value);
402 STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder);
403 STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder);
404
405 STDMETHOD_(UInt32, GetNumHashers)();
406 STDMETHOD(GetHasherProp)(UInt32 index, PROPID propID, PROPVARIANT *value);
407 STDMETHOD(CreateHasher)(UInt32 index, IHasher **hasher);
408
409 #else
410
411 MY_UNKNOWN_IMP
412
413 #endif // EXTERNAL_CODECS
414
415
416 #ifdef EXTERNAL_CODECS
417 395
418 int GetCodec_LibIndex(UInt32 index) const; 396 int GetCodec_LibIndex(UInt32 index) const;
419 bool GetCodec_DecoderIsAssigned(UInt32 index) const; 397 bool GetCodec_DecoderIsAssigned(UInt32 index) const;
@@ -435,7 +413,7 @@ public:
435 HRESULT CreateInArchive(unsigned formatIndex, CMyComPtr<IInArchive> &archive) const 413 HRESULT CreateInArchive(unsigned formatIndex, CMyComPtr<IInArchive> &archive) const
436 { 414 {
437 const CArcInfoEx &ai = Formats[formatIndex]; 415 const CArcInfoEx &ai = Formats[formatIndex];
438 #ifdef EXTERNAL_CODECS 416 #ifdef Z7_EXTERNAL_CODECS
439 if (ai.LibIndex < 0) 417 if (ai.LibIndex < 0)
440 #endif 418 #endif
441 { 419 {
@@ -444,17 +422,17 @@ public:
444 return S_OK; 422 return S_OK;
445 COM_TRY_END 423 COM_TRY_END
446 } 424 }
447 #ifdef EXTERNAL_CODECS 425 #ifdef Z7_EXTERNAL_CODECS
448 return CreateArchiveHandler(ai, false, (void **)&archive); 426 return CreateArchiveHandler(ai, false, (void **)&archive);
449 #endif 427 #endif
450 } 428 }
451 429
452 #ifndef _SFX 430 #ifndef Z7_SFX
453 431
454 HRESULT CreateOutArchive(unsigned formatIndex, CMyComPtr<IOutArchive> &archive) const 432 HRESULT CreateOutArchive(unsigned formatIndex, CMyComPtr<IOutArchive> &archive) const
455 { 433 {
456 const CArcInfoEx &ai = Formats[formatIndex]; 434 const CArcInfoEx &ai = Formats[formatIndex];
457 #ifdef EXTERNAL_CODECS 435 #ifdef Z7_EXTERNAL_CODECS
458 if (ai.LibIndex < 0) 436 if (ai.LibIndex < 0)
459 #endif 437 #endif
460 { 438 {
@@ -464,7 +442,7 @@ public:
464 COM_TRY_END 442 COM_TRY_END
465 } 443 }
466 444
467 #ifdef EXTERNAL_CODECS 445 #ifdef Z7_EXTERNAL_CODECS
468 return CreateArchiveHandler(ai, true, (void **)&archive); 446 return CreateArchiveHandler(ai, true, (void **)&archive);
469 #endif 447 #endif
470 } 448 }
@@ -484,21 +462,21 @@ public:
484 462
485 void Get_CodecsInfoUser_Vector(CObjectVector<CCodecInfoUser> &v); 463 void Get_CodecsInfoUser_Vector(CObjectVector<CCodecInfoUser> &v);
486 464
487 #endif // _SFX 465 #endif // Z7_SFX
488}; 466};
489 467
490#ifdef EXTERNAL_CODECS 468#ifdef Z7_EXTERNAL_CODECS
491 #define CREATE_CODECS_OBJECT \ 469 #define CREATE_CODECS_OBJECT \
492 CCodecs *codecs = new CCodecs; \ 470 CCodecs *codecs = new CCodecs; \
493 CExternalCodecs __externalCodecs; \ 471 CExternalCodecs _externalCodecs; \
494 __externalCodecs.GetCodecs = codecs; \ 472 _externalCodecs.GetCodecs = codecs; \
495 __externalCodecs.GetHashers = codecs; \ 473 _externalCodecs.GetHashers = codecs; \
496 CCodecs::CReleaser codecsReleaser; \ 474 CCodecs::CReleaser codecsReleaser; \
497 codecsReleaser.Set(codecs); 475 codecsReleaser.Set(codecs);
498#else 476#else
499 #define CREATE_CODECS_OBJECT \ 477 #define CREATE_CODECS_OBJECT \
500 CCodecs *codecs = new CCodecs; \ 478 CCodecs *codecs = new CCodecs; \
501 CMyComPtr<IUnknown> __codecsRef = codecs; 479 CMyComPtr<IUnknown> _codecsRef = codecs;
502#endif 480#endif
503 481
504#endif 482#endif
diff --git a/CPP/7zip/UI/Common/OpenArchive.cpp b/CPP/7zip/UI/Common/OpenArchive.cpp
index 4a91a26..a501b86 100644
--- a/CPP/7zip/UI/Common/OpenArchive.cpp
+++ b/CPP/7zip/UI/Common/OpenArchive.cpp
@@ -29,11 +29,11 @@
29#include "DefaultName.h" 29#include "DefaultName.h"
30#include "OpenArchive.h" 30#include "OpenArchive.h"
31 31
32#ifndef _SFX 32#ifndef Z7_SFX
33#include "SetProperties.h" 33#include "SetProperties.h"
34#endif 34#endif
35 35
36#ifndef _SFX 36#ifndef Z7_SFX
37#ifdef SHOW_DEBUG_INFO 37#ifdef SHOW_DEBUG_INFO
38#define PRF(x) x 38#define PRF(x) x
39#else 39#else
@@ -95,7 +95,7 @@ Open:
95using namespace NWindows; 95using namespace NWindows;
96 96
97/* 97/*
98#ifdef _SFX 98#ifdef Z7_SFX
99#define OPEN_PROPS_PARAM 99#define OPEN_PROPS_PARAM
100#else 100#else
101#define OPEN_PROPS_PARAM , props 101#define OPEN_PROPS_PARAM , props
@@ -111,7 +111,7 @@ CArc::~CArc()
111} 111}
112*/ 112*/
113 113
114#ifndef _SFX 114#ifndef Z7_SFX
115 115
116namespace NArchive { 116namespace NArchive {
117namespace NParser { 117namespace NParser {
@@ -172,23 +172,14 @@ struct CParseItem
172 } 172 }
173}; 173};
174 174
175class CHandler: 175Z7_CLASS_IMP_CHandler_IInArchive_1(
176 public IInArchive, 176 IInArchiveGetStream
177 public IInArchiveGetStream, 177)
178 public CMyUnknownImp
179{
180public: 178public:
181 CObjectVector<CParseItem> _items; 179 CObjectVector<CParseItem> _items;
182 UInt64 _maxEndOffset; 180 UInt64 _maxEndOffset;
183 CMyComPtr<IInStream> _stream; 181 CMyComPtr<IInStream> _stream;
184 182
185 MY_UNKNOWN_IMP2(
186 IInArchive,
187 IInArchiveGetStream)
188
189 INTERFACE_IInArchive(;)
190 STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
191
192 UInt64 GetLastEnd() const 183 UInt64 GetLastEnd() const
193 { 184 {
194 if (_items.IsEmpty()) 185 if (_items.IsEmpty())
@@ -300,7 +291,7 @@ static const Byte kProps[] =
300IMP_IInArchive_Props 291IMP_IInArchive_Props
301IMP_IInArchive_ArcProps_NO 292IMP_IInArchive_ArcProps_NO
302 293
303STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */) 294Z7_COM7F_IMF(CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */))
304{ 295{
305 COM_TRY_BEGIN 296 COM_TRY_BEGIN
306 { 297 {
@@ -311,20 +302,20 @@ STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallb
311 COM_TRY_END 302 COM_TRY_END
312} 303}
313 304
314STDMETHODIMP CHandler::Close() 305Z7_COM7F_IMF(CHandler::Close())
315{ 306{
316 _items.Clear(); 307 _items.Clear();
317 _stream.Release(); 308 _stream.Release();
318 return S_OK; 309 return S_OK;
319} 310}
320 311
321STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) 312Z7_COM7F_IMF(CHandler::GetNumberOfItems(UInt32 *numItems))
322{ 313{
323 *numItems = _items.Size(); 314 *numItems = _items.Size();
324 return S_OK; 315 return S_OK;
325} 316}
326 317
327STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 318Z7_COM7F_IMF(CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
328{ 319{
329 COM_TRY_BEGIN 320 COM_TRY_BEGIN
330 NCOM::CPropVariant prop; 321 NCOM::CPropVariant prop;
@@ -340,12 +331,12 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
340 UString s(sz); 331 UString s(sz);
341 if (!item.Name.IsEmpty()) 332 if (!item.Name.IsEmpty())
342 { 333 {
343 s += '.'; 334 s.Add_Dot();
344 s += item.Name; 335 s += item.Name;
345 } 336 }
346 if (!item.Extension.IsEmpty()) 337 if (!item.Extension.IsEmpty())
347 { 338 {
348 s += '.'; 339 s.Add_Dot();
349 s += item.Extension; 340 s += item.Extension;
350 } 341 }
351 prop = s; break; 342 prop = s; break;
@@ -365,12 +356,12 @@ STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *val
365 COM_TRY_END 356 COM_TRY_END
366} 357}
367 358
368HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, 359Z7_COM7F_IMF(CHandler::Extract(const UInt32 *indices, UInt32 numItems,
369 Int32 testMode, IArchiveExtractCallback *extractCallback) 360 Int32 testMode, IArchiveExtractCallback *extractCallback))
370{ 361{
371 COM_TRY_BEGIN 362 COM_TRY_BEGIN
372 363
373 bool allFilesMode = (numItems == (UInt32)(Int32)-1); 364 const bool allFilesMode = (numItems == (UInt32)(Int32)-1);
374 if (allFilesMode) 365 if (allFilesMode)
375 numItems = _items.Size(); 366 numItems = _items.Size();
376 if (_stream && numItems == 0) 367 if (_stream && numItems == 0)
@@ -401,35 +392,35 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
401 { 392 {
402 lps->InSize = totalSize; 393 lps->InSize = totalSize;
403 lps->OutSize = totalSize; 394 lps->OutSize = totalSize;
404 RINOK(lps->SetCur()); 395 RINOK(lps->SetCur())
405 CMyComPtr<ISequentialOutStream> realOutStream; 396 CMyComPtr<ISequentialOutStream> realOutStream;
406 Int32 askMode = testMode ? 397 const Int32 askMode = testMode ?
407 NExtract::NAskMode::kTest : 398 NExtract::NAskMode::kTest :
408 NExtract::NAskMode::kExtract; 399 NExtract::NAskMode::kExtract;
409 UInt32 index = allFilesMode ? i : indices[i]; 400 const UInt32 index = allFilesMode ? i : indices[i];
410 const CParseItem &item = _items[index]; 401 const CParseItem &item = _items[index];
411 402
412 RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); 403 RINOK(extractCallback->GetStream(index, &realOutStream, askMode))
413 UInt64 unpackSize = item.Size; 404 UInt64 unpackSize = item.Size;
414 totalSize += unpackSize; 405 totalSize += unpackSize;
415 bool skipMode = false; 406 bool skipMode = false;
416 if (!testMode && !realOutStream) 407 if (!testMode && !realOutStream)
417 continue; 408 continue;
418 RINOK(extractCallback->PrepareOperation(askMode)); 409 RINOK(extractCallback->PrepareOperation(askMode))
419 410
420 outStreamSpec->SetStream(realOutStream); 411 outStreamSpec->SetStream(realOutStream);
421 realOutStream.Release(); 412 realOutStream.Release();
422 outStreamSpec->Init(skipMode ? 0 : unpackSize, true); 413 outStreamSpec->Init(skipMode ? 0 : unpackSize, true);
423 414
424 Int32 opRes = NExtract::NOperationResult::kOK; 415 Int32 opRes = NExtract::NOperationResult::kOK;
425 RINOK(_stream->Seek((Int64)item.Offset, STREAM_SEEK_SET, NULL)); 416 RINOK(InStream_SeekSet(_stream, item.Offset))
426 streamSpec->Init(unpackSize); 417 streamSpec->Init(unpackSize);
427 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); 418 RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress))
428 419
429 if (outStreamSpec->GetRem() != 0) 420 if (outStreamSpec->GetRem() != 0)
430 opRes = NExtract::NOperationResult::kDataError; 421 opRes = NExtract::NOperationResult::kDataError;
431 outStreamSpec->ReleaseStream(); 422 outStreamSpec->ReleaseStream();
432 RINOK(extractCallback->SetOperationResult(opRes)); 423 RINOK(extractCallback->SetOperationResult(opRes))
433 } 424 }
434 425
435 return S_OK; 426 return S_OK;
@@ -438,7 +429,7 @@ HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
438} 429}
439 430
440 431
441STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) 432Z7_COM7F_IMF(CHandler::GetStream(UInt32 index, ISequentialInStream **stream))
442{ 433{
443 COM_TRY_BEGIN 434 COM_TRY_BEGIN
444 const CParseItem &item = _items[index]; 435 const CParseItem &item = _items[index];
@@ -454,7 +445,7 @@ HRESULT Archive_GetItemBoolProp(IInArchive *arc, UInt32 index, PROPID propID, bo
454{ 445{
455 NCOM::CPropVariant prop; 446 NCOM::CPropVariant prop;
456 result = false; 447 result = false;
457 RINOK(arc->GetProperty(index, propID, &prop)); 448 RINOK(arc->GetProperty(index, propID, &prop))
458 if (prop.vt == VT_BOOL) 449 if (prop.vt == VT_BOOL)
459 result = VARIANT_BOOLToBool(prop.boolVal); 450 result = VARIANT_BOOLToBool(prop.boolVal);
460 else if (prop.vt != VT_EMPTY) 451 else if (prop.vt != VT_EMPTY)
@@ -486,7 +477,7 @@ static HRESULT Archive_GetArcProp_Bool(IInArchive *arc, PROPID propid, bool &res
486{ 477{
487 NCOM::CPropVariant prop; 478 NCOM::CPropVariant prop;
488 result = false; 479 result = false;
489 RINOK(arc->GetArchiveProperty(propid, &prop)); 480 RINOK(arc->GetArchiveProperty(propid, &prop))
490 if (prop.vt == VT_BOOL) 481 if (prop.vt == VT_BOOL)
491 result = VARIANT_BOOLToBool(prop.boolVal); 482 result = VARIANT_BOOLToBool(prop.boolVal);
492 else if (prop.vt != VT_EMPTY) 483 else if (prop.vt != VT_EMPTY)
@@ -498,7 +489,7 @@ static HRESULT Archive_GetArcProp_UInt(IInArchive *arc, PROPID propid, UInt64 &r
498{ 489{
499 defined = false; 490 defined = false;
500 NCOM::CPropVariant prop; 491 NCOM::CPropVariant prop;
501 RINOK(arc->GetArchiveProperty(propid, &prop)); 492 RINOK(arc->GetArchiveProperty(propid, &prop))
502 switch (prop.vt) 493 switch (prop.vt)
503 { 494 {
504 case VT_UI4: result = prop.ulVal; break; 495 case VT_UI4: result = prop.ulVal; break;
@@ -516,7 +507,7 @@ static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &res
516{ 507{
517 defined = false; 508 defined = false;
518 NCOM::CPropVariant prop; 509 NCOM::CPropVariant prop;
519 RINOK(arc->GetArchiveProperty(propid, &prop)); 510 RINOK(arc->GetArchiveProperty(propid, &prop))
520 switch (prop.vt) 511 switch (prop.vt)
521 { 512 {
522 case VT_UI4: result = prop.ulVal; break; 513 case VT_UI4: result = prop.ulVal; break;
@@ -530,7 +521,7 @@ static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &res
530 return S_OK; 521 return S_OK;
531} 522}
532 523
533#ifndef _SFX 524#ifndef Z7_SFX
534 525
535HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const 526HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const
536{ 527{
@@ -550,14 +541,14 @@ HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &p
550 const void *p; 541 const void *p;
551 UInt32 size; 542 UInt32 size;
552 UInt32 propType; 543 UInt32 propType;
553 RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType)); 544 RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType))
554 if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE) 545 if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE)
555 s = (const wchar_t *)p; 546 s = (const wchar_t *)p;
556 else 547 else
557 #endif 548 #endif
558 { 549 {
559 NCOM::CPropVariant prop; 550 NCOM::CPropVariant prop;
560 RINOK(Archive->GetProperty(curIndex, kpidName, &prop)); 551 RINOK(Archive->GetProperty(curIndex, kpidName, &prop))
561 if (prop.vt == VT_BSTR && prop.bstrVal) 552 if (prop.vt == VT_BSTR && prop.bstrVal)
562 s.SetFromBstr(prop.bstrVal); 553 s.SetFromBstr(prop.bstrVal);
563 else if (prop.vt == VT_EMPTY) 554 else if (prop.vt == VT_EMPTY)
@@ -568,7 +559,7 @@ HRESULT CArc::GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &p
568 559
569 UInt32 curParent = (UInt32)(Int32)-1; 560 UInt32 curParent = (UInt32)(Int32)-1;
570 UInt32 parentType = 0; 561 UInt32 parentType = 0;
571 RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType)); 562 RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType))
572 563
573 // 18.06: fixed : we don't want to split name to parts 564 // 18.06: fixed : we don't want to split name to parts
574 /* 565 /*
@@ -742,7 +733,7 @@ HRESULT CArc::GetItem_Path(UInt32 index, UString &result) const
742 733
743 { 734 {
744 NCOM::CPropVariant prop; 735 NCOM::CPropVariant prop;
745 RINOK(Archive->GetProperty(index, kpidPath, &prop)); 736 RINOK(Archive->GetProperty(index, kpidPath, &prop))
746 if (prop.vt == VT_BSTR && prop.bstrVal) 737 if (prop.vt == VT_BSTR && prop.bstrVal)
747 result.SetFromBstr(prop.bstrVal); 738 result.SetFromBstr(prop.bstrVal);
748 else if (prop.vt == VT_EMPTY) 739 else if (prop.vt == VT_EMPTY)
@@ -762,15 +753,15 @@ HRESULT CArc::GetItem_DefaultPath(UInt32 index, UString &result) const
762{ 753{
763 result.Empty(); 754 result.Empty();
764 bool isDir; 755 bool isDir;
765 RINOK(Archive_IsItem_Dir(Archive, index, isDir)); 756 RINOK(Archive_IsItem_Dir(Archive, index, isDir))
766 if (!isDir) 757 if (!isDir)
767 { 758 {
768 result = DefaultName; 759 result = DefaultName;
769 NCOM::CPropVariant prop; 760 NCOM::CPropVariant prop;
770 RINOK(Archive->GetProperty(index, kpidExtension, &prop)); 761 RINOK(Archive->GetProperty(index, kpidExtension, &prop))
771 if (prop.vt == VT_BSTR) 762 if (prop.vt == VT_BSTR)
772 { 763 {
773 result += '.'; 764 result.Add_Dot();
774 result += prop.bstrVal; 765 result += prop.bstrVal;
775 } 766 }
776 else if (prop.vt != VT_EMPTY) 767 else if (prop.vt != VT_EMPTY)
@@ -781,11 +772,11 @@ HRESULT CArc::GetItem_DefaultPath(UInt32 index, UString &result) const
781 772
782HRESULT CArc::GetItem_Path2(UInt32 index, UString &result) const 773HRESULT CArc::GetItem_Path2(UInt32 index, UString &result) const
783{ 774{
784 RINOK(GetItem_Path(index, result)); 775 RINOK(GetItem_Path(index, result))
785 if (Ask_Deleted) 776 if (Ask_Deleted)
786 { 777 {
787 bool isDeleted = false; 778 bool isDeleted = false;
788 RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted)); 779 RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted))
789 if (isDeleted) 780 if (isDeleted)
790 result.Insert(0, L"[DELETED]" WSTRING_PATH_SEPARATOR); 781 result.Insert(0, L"[DELETED]" WSTRING_PATH_SEPARATOR);
791 } 782 }
@@ -830,12 +821,12 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
830 821
831 item.PathParts.Clear(); 822 item.PathParts.Clear();
832 823
833 RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir)); 824 RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir))
834 item.MainIsDir = item.IsDir; 825 item.MainIsDir = item.IsDir;
835 826
836 RINOK(GetItem_Path2(index, item.Path)); 827 RINOK(GetItem_Path2(index, item.Path))
837 828
838 #ifndef _SFX 829 #ifndef Z7_SFX
839 UInt32 mainIndex = index; 830 UInt32 mainIndex = index;
840 #endif 831 #endif
841 832
@@ -844,7 +835,7 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
844 item.MainPath = item.Path; 835 item.MainPath = item.Path;
845 if (Ask_AltStream) 836 if (Ask_AltStream)
846 { 837 {
847 RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream)); 838 RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream))
848 } 839 }
849 840
850 bool needFindAltStream = false; 841 bool needFindAltStream = false;
@@ -856,11 +847,11 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
856 { 847 {
857 UInt32 parentType = 0; 848 UInt32 parentType = 0;
858 UInt32 parentIndex; 849 UInt32 parentIndex;
859 RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType)); 850 RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType))
860 if (parentType == NParentType::kAltStream) 851 if (parentType == NParentType::kAltStream)
861 { 852 {
862 NCOM::CPropVariant prop; 853 NCOM::CPropVariant prop;
863 RINOK(Archive->GetProperty(index, kpidName, &prop)); 854 RINOK(Archive->GetProperty(index, kpidName, &prop))
864 if (prop.vt == VT_BSTR && prop.bstrVal) 855 if (prop.vt == VT_BSTR && prop.bstrVal)
865 item.AltStreamName.SetFromBstr(prop.bstrVal); 856 item.AltStreamName.SetFromBstr(prop.bstrVal);
866 else if (prop.vt != VT_EMPTY) 857 else if (prop.vt != VT_EMPTY)
@@ -885,8 +876,8 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
885 } 876 }
886 else 877 else
887 { 878 {
888 RINOK(GetItem_Path2(parentIndex, item.MainPath)); 879 RINOK(GetItem_Path2(parentIndex, item.MainPath))
889 RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir)); 880 RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir))
890 } 881 }
891 } 882 }
892 } 883 }
@@ -908,10 +899,10 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
908 899
909 #endif 900 #endif
910 901
911 #ifndef _SFX 902 #ifndef Z7_SFX
912 if (item._use_baseParentFolder_mode) 903 if (item._use_baseParentFolder_mode)
913 { 904 {
914 RINOK(GetItem_PathToParent(mainIndex, (unsigned)item._baseParentFolder, item.PathParts)); 905 RINOK(GetItem_PathToParent(mainIndex, (unsigned)item._baseParentFolder, item.PathParts))
915 906
916 #ifdef SUPPORT_ALT_STREAMS 907 #ifdef SUPPORT_ALT_STREAMS
917 if ((item.WriteToAltStreamIfColon || needFindAltStream) && !item.PathParts.IsEmpty()) 908 if ((item.WriteToAltStreamIfColon || needFindAltStream) && !item.PathParts.IsEmpty())
@@ -947,14 +938,14 @@ HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const
947 return S_OK; 938 return S_OK;
948} 939}
949 940
950#ifndef _SFX 941#ifndef Z7_SFX
951 942
952static HRESULT Archive_GetItem_Size(IInArchive *archive, UInt32 index, UInt64 &size, bool &defined) 943static HRESULT Archive_GetItem_Size(IInArchive *archive, UInt32 index, UInt64 &size, bool &defined)
953{ 944{
954 NCOM::CPropVariant prop; 945 NCOM::CPropVariant prop;
955 defined = false; 946 defined = false;
956 size = 0; 947 size = 0;
957 RINOK(archive->GetProperty(index, kpidSize, &prop)); 948 RINOK(archive->GetProperty(index, kpidSize, &prop))
958 switch (prop.vt) 949 switch (prop.vt)
959 { 950 {
960 case VT_UI1: size = prop.bVal; break; 951 case VT_UI1: size = prop.bVal; break;
@@ -975,7 +966,7 @@ HRESULT CArc::GetItem_Size(UInt32 index, UInt64 &size, bool &defined) const
975 NCOM::CPropVariant prop; 966 NCOM::CPropVariant prop;
976 defined = false; 967 defined = false;
977 size = 0; 968 size = 0;
978 RINOK(Archive->GetProperty(index, kpidSize, &prop)); 969 RINOK(Archive->GetProperty(index, kpidSize, &prop))
979 switch (prop.vt) 970 switch (prop.vt)
980 { 971 {
981 case VT_UI1: size = prop.bVal; break; 972 case VT_UI1: size = prop.bVal; break;
@@ -993,7 +984,7 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const
993{ 984{
994 at.Clear(); 985 at.Clear();
995 NCOM::CPropVariant prop; 986 NCOM::CPropVariant prop;
996 RINOK(Archive->GetProperty(index, kpidMTime, &prop)); 987 RINOK(Archive->GetProperty(index, kpidMTime, &prop))
997 988
998 if (prop.vt == VT_FILETIME) 989 if (prop.vt == VT_FILETIME)
999 { 990 {
@@ -1011,7 +1002,7 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const
1011 // (at.Prec == 0) before version 22. 1002 // (at.Prec == 0) before version 22.
1012 // so kpidTimeType is required for that code 1003 // so kpidTimeType is required for that code
1013 prop.Clear(); 1004 prop.Clear();
1014 RINOK(Archive->GetProperty(index, kpidTimeType, &prop)); 1005 RINOK(Archive->GetProperty(index, kpidTimeType, &prop))
1015 if (prop.vt == VT_UI4) 1006 if (prop.vt == VT_UI4)
1016 { 1007 {
1017 UInt32 val = prop.ulVal; 1008 UInt32 val = prop.ulVal;
@@ -1038,7 +1029,7 @@ HRESULT CArc::GetItem_MTime(UInt32 index, CArcTime &at) const
1038 return S_OK; 1029 return S_OK;
1039} 1030}
1040 1031
1041#ifndef _SFX 1032#ifndef Z7_SFX
1042 1033
1043static inline bool TestSignature(const Byte *p1, const Byte *p2, size_t size) 1034static inline bool TestSignature(const Byte *p1, const Byte *p2, size_t size)
1044{ 1035{
@@ -1121,7 +1112,7 @@ static bool IsPreArcFormat(const CArcInfoEx &ai)
1121{ 1112{
1122 if (ai.Flags_PreArc()) 1113 if (ai.Flags_PreArc())
1123 return true; 1114 return true;
1124 return IsNameFromList(ai.Name, k_PreArcFormats, ARRAY_SIZE(k_PreArcFormats)); 1115 return IsNameFromList(ai.Name, k_PreArcFormats, Z7_ARRAY_SIZE(k_PreArcFormats));
1125} 1116}
1126 1117
1127static const char * const k_Formats_with_simple_signuature[] = 1118static const char * const k_Formats_with_simple_signuature[] =
@@ -1143,44 +1134,46 @@ static bool IsNewStyleSignature(const CArcInfoEx &ai)
1143 // if (ai.Version >= 0x91F) 1134 // if (ai.Version >= 0x91F)
1144 if (ai.NewInterface) 1135 if (ai.NewInterface)
1145 return true; 1136 return true;
1146 return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, ARRAY_SIZE(k_Formats_with_simple_signuature)); 1137 return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, Z7_ARRAY_SIZE(k_Formats_with_simple_signuature));
1147} 1138}
1148 1139
1149class CArchiveOpenCallback_Offset: 1140
1141
1142class CArchiveOpenCallback_Offset Z7_final:
1150 public IArchiveOpenCallback, 1143 public IArchiveOpenCallback,
1151 public IArchiveOpenVolumeCallback, 1144 public IArchiveOpenVolumeCallback,
1152 #ifndef _NO_CRYPTO 1145 #ifndef Z7_NO_CRYPTO
1153 public ICryptoGetTextPassword, 1146 public ICryptoGetTextPassword,
1154 #endif 1147 #endif
1155 public CMyUnknownImp 1148 public CMyUnknownImp
1156{ 1149{
1150 Z7_COM_QI_BEGIN2(IArchiveOpenCallback)
1151 Z7_COM_QI_ENTRY(IArchiveOpenVolumeCallback)
1152 #ifndef Z7_NO_CRYPTO
1153 Z7_COM_QI_ENTRY(ICryptoGetTextPassword)
1154 #endif
1155 Z7_COM_QI_END
1156 Z7_COM_ADDREF_RELEASE
1157
1158 Z7_IFACE_COM7_IMP(IArchiveOpenCallback)
1159 Z7_IFACE_COM7_IMP(IArchiveOpenVolumeCallback)
1160 #ifndef Z7_NO_CRYPTO
1161 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
1162 #endif
1163
1157public: 1164public:
1158 CMyComPtr<IArchiveOpenCallback> Callback; 1165 CMyComPtr<IArchiveOpenCallback> Callback;
1159 CMyComPtr<IArchiveOpenVolumeCallback> OpenVolumeCallback; 1166 CMyComPtr<IArchiveOpenVolumeCallback> OpenVolumeCallback;
1160 UInt64 Files; 1167 UInt64 Files;
1161 UInt64 Offset; 1168 UInt64 Offset;
1162 1169
1163 #ifndef _NO_CRYPTO 1170 #ifndef Z7_NO_CRYPTO
1164 CMyComPtr<ICryptoGetTextPassword> GetTextPassword; 1171 CMyComPtr<ICryptoGetTextPassword> GetTextPassword;
1165 #endif 1172 #endif
1166
1167 MY_QUERYINTERFACE_BEGIN2(IArchiveOpenCallback)
1168 MY_QUERYINTERFACE_ENTRY(IArchiveOpenVolumeCallback)
1169 #ifndef _NO_CRYPTO
1170 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword)
1171 #endif
1172 MY_QUERYINTERFACE_END
1173 MY_ADDREF_RELEASE
1174
1175 INTERFACE_IArchiveOpenCallback(;)
1176 INTERFACE_IArchiveOpenVolumeCallback(;)
1177 #ifndef _NO_CRYPTO
1178 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
1179 #endif
1180}; 1173};
1181 1174
1182#ifndef _NO_CRYPTO 1175#ifndef Z7_NO_CRYPTO
1183STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password) 1176Z7_COM7F_IMF(CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password))
1184{ 1177{
1185 COM_TRY_BEGIN 1178 COM_TRY_BEGIN
1186 if (GetTextPassword) 1179 if (GetTextPassword)
@@ -1190,12 +1183,12 @@ STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password)
1190} 1183}
1191#endif 1184#endif
1192 1185
1193STDMETHODIMP CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *) 1186Z7_COM7F_IMF(CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *))
1194{ 1187{
1195 return S_OK; 1188 return S_OK;
1196} 1189}
1197 1190
1198STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes) 1191Z7_COM7F_IMF(CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes))
1199{ 1192{
1200 if (!Callback) 1193 if (!Callback)
1201 return S_OK; 1194 return S_OK;
@@ -1205,7 +1198,7 @@ STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UIn
1205 return Callback->SetCompleted(&Files, &value); 1198 return Callback->SetCompleted(&Files, &value);
1206} 1199}
1207 1200
1208STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value) 1201Z7_COM7F_IMF(CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value))
1209{ 1202{
1210 if (OpenVolumeCallback) 1203 if (OpenVolumeCallback)
1211 return OpenVolumeCallback->GetProperty(propID, value); 1204 return OpenVolumeCallback->GetProperty(propID, value);
@@ -1214,7 +1207,7 @@ STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT
1214 // return E_NOTIMPL; 1207 // return E_NOTIMPL;
1215} 1208}
1216 1209
1217STDMETHODIMP CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream) 1210Z7_COM7F_IMF(CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream))
1218{ 1211{
1219 if (OpenVolumeCallback) 1212 if (OpenVolumeCallback)
1220 return OpenVolumeCallback->GetStream(name, inStream); 1213 return OpenVolumeCallback->GetStream(name, inStream);
@@ -1266,32 +1259,32 @@ HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openR
1266 ErrorInfo.ClearErrors(); 1259 ErrorInfo.ClearErrors();
1267 { 1260 {
1268 NCOM::CPropVariant prop; 1261 NCOM::CPropVariant prop;
1269 RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop)); 1262 RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop))
1270 ErrorInfo.ErrorFlags = GetOpenArcErrorFlags(prop, &ErrorInfo.ErrorFlags_Defined); 1263 ErrorInfo.ErrorFlags = GetOpenArcErrorFlags(prop, &ErrorInfo.ErrorFlags_Defined);
1271 } 1264 }
1272 { 1265 {
1273 NCOM::CPropVariant prop; 1266 NCOM::CPropVariant prop;
1274 RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop)); 1267 RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop))
1275 ErrorInfo.WarningFlags = GetOpenArcErrorFlags(prop); 1268 ErrorInfo.WarningFlags = GetOpenArcErrorFlags(prop);
1276 } 1269 }
1277 1270
1278 { 1271 {
1279 NCOM::CPropVariant prop; 1272 NCOM::CPropVariant prop;
1280 RINOK(archive->GetArchiveProperty(kpidError, &prop)); 1273 RINOK(archive->GetArchiveProperty(kpidError, &prop))
1281 if (prop.vt != VT_EMPTY) 1274 if (prop.vt != VT_EMPTY)
1282 ErrorInfo.ErrorMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown error"); 1275 ErrorInfo.ErrorMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown error");
1283 } 1276 }
1284 1277
1285 { 1278 {
1286 NCOM::CPropVariant prop; 1279 NCOM::CPropVariant prop;
1287 RINOK(archive->GetArchiveProperty(kpidWarning, &prop)); 1280 RINOK(archive->GetArchiveProperty(kpidWarning, &prop))
1288 if (prop.vt != VT_EMPTY) 1281 if (prop.vt != VT_EMPTY)
1289 ErrorInfo.WarningMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown warning"); 1282 ErrorInfo.WarningMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown warning");
1290 } 1283 }
1291 1284
1292 if (openRes == S_OK || ErrorInfo.IsArc_After_NonOpen()) 1285 if (openRes == S_OK || ErrorInfo.IsArc_After_NonOpen())
1293 { 1286 {
1294 RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySize_Defined)); 1287 RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySize_Defined))
1295 /* 1288 /*
1296 RINOK(Archive_GetArcProp_UInt(archive, kpidOkPhySize, OkPhySize, OkPhySize_Defined)); 1289 RINOK(Archive_GetArcProp_UInt(archive, kpidOkPhySize, OkPhySize, OkPhySize_Defined));
1297 if (!OkPhySize_Defined) 1290 if (!OkPhySize_Defined)
@@ -1302,7 +1295,7 @@ HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openR
1302 */ 1295 */
1303 1296
1304 bool offsetDefined; 1297 bool offsetDefined;
1305 RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined)); 1298 RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined))
1306 1299
1307 Int64 globalOffset = (Int64)startPos + Offset; 1300 Int64 globalOffset = (Int64)startPos + Offset;
1308 AvailPhySize = (UInt64)((Int64)FileSize - globalOffset); 1301 AvailPhySize = (UInt64)((Int64)FileSize - globalOffset);
@@ -1338,12 +1331,12 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom
1338 // OutputDebugStringA("a1"); 1331 // OutputDebugStringA("a1");
1339 // PrintNumber("formatIndex", formatIndex); 1332 // PrintNumber("formatIndex", formatIndex);
1340 1333
1341 RINOK(op.codecs->CreateInArchive(formatIndex, archive)); 1334 RINOK(op.codecs->CreateInArchive(formatIndex, archive))
1342 // OutputDebugStringA("a2"); 1335 // OutputDebugStringA("a2");
1343 if (!archive) 1336 if (!archive)
1344 return S_OK; 1337 return S_OK;
1345 1338
1346 #ifdef EXTERNAL_CODECS 1339 #ifdef Z7_EXTERNAL_CODECS
1347 if (op.codecs->NeedSetLibCodecs) 1340 if (op.codecs->NeedSetLibCodecs)
1348 { 1341 {
1349 const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; 1342 const CArcInfoEx &ai = op.codecs->Formats[formatIndex];
@@ -1355,14 +1348,14 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom
1355 archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); 1348 archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
1356 if (setCompressCodecsInfo) 1349 if (setCompressCodecsInfo)
1357 { 1350 {
1358 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs)); 1351 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs))
1359 } 1352 }
1360 } 1353 }
1361 } 1354 }
1362 #endif 1355 #endif
1363 1356
1364 1357
1365 #ifndef _SFX 1358 #ifndef Z7_SFX
1366 1359
1367 const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; 1360 const CArcInfoEx &ai = op.codecs->Formats[formatIndex];
1368 1361
@@ -1392,14 +1385,14 @@ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyCom
1392 } 1385 }
1393 } 1386 }
1394 */ 1387 */
1395 RINOK(SetProperties(archive, *op.props)); 1388 RINOK(SetProperties(archive, *op.props))
1396 } 1389 }
1397 1390
1398 #endif 1391 #endif
1399 return S_OK; 1392 return S_OK;
1400} 1393}
1401 1394
1402#ifndef _SFX 1395#ifndef Z7_SFX
1403 1396
1404static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NArchive::NParser::CParseItem &pi) 1397static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NArchive::NParser::CParseItem &pi)
1405{ 1398{
@@ -1407,14 +1400,14 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr
1407 pi.FileTime_Defined = false; 1400 pi.FileTime_Defined = false;
1408 pi.ArcType = ai.Name; 1401 pi.ArcType = ai.Name;
1409 1402
1410 RINOK(Archive_GetArcProp_Bool(archive, kpidIsNotArcType, pi.IsNotArcType)); 1403 RINOK(Archive_GetArcProp_Bool(archive, kpidIsNotArcType, pi.IsNotArcType))
1411 1404
1412 // RINOK(Archive_GetArcProp_Bool(archive, kpidIsSelfExe, pi.IsSelfExe)); 1405 // RINOK(Archive_GetArcProp_Bool(archive, kpidIsSelfExe, pi.IsSelfExe));
1413 pi.IsSelfExe = ai.Flags_PreArc(); 1406 pi.IsSelfExe = ai.Flags_PreArc();
1414 1407
1415 { 1408 {
1416 NCOM::CPropVariant prop; 1409 NCOM::CPropVariant prop;
1417 RINOK(archive->GetArchiveProperty(kpidMTime, &prop)); 1410 RINOK(archive->GetArchiveProperty(kpidMTime, &prop))
1418 if (prop.vt == VT_FILETIME) 1411 if (prop.vt == VT_FILETIME)
1419 { 1412 {
1420 pi.FileTime_Defined = true; 1413 pi.FileTime_Defined = true;
@@ -1425,7 +1418,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr
1425 if (!pi.FileTime_Defined) 1418 if (!pi.FileTime_Defined)
1426 { 1419 {
1427 NCOM::CPropVariant prop; 1420 NCOM::CPropVariant prop;
1428 RINOK(archive->GetArchiveProperty(kpidCTime, &prop)); 1421 RINOK(archive->GetArchiveProperty(kpidCTime, &prop))
1429 if (prop.vt == VT_FILETIME) 1422 if (prop.vt == VT_FILETIME)
1430 { 1423 {
1431 pi.FileTime_Defined = true; 1424 pi.FileTime_Defined = true;
@@ -1435,7 +1428,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr
1435 1428
1436 { 1429 {
1437 NCOM::CPropVariant prop; 1430 NCOM::CPropVariant prop;
1438 RINOK(archive->GetArchiveProperty(kpidName, &prop)); 1431 RINOK(archive->GetArchiveProperty(kpidName, &prop))
1439 if (prop.vt == VT_BSTR) 1432 if (prop.vt == VT_BSTR)
1440 { 1433 {
1441 pi.Name.SetFromBstr(prop.bstrVal); 1434 pi.Name.SetFromBstr(prop.bstrVal);
@@ -1443,7 +1436,7 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr
1443 } 1436 }
1444 else 1437 else
1445 { 1438 {
1446 RINOK(archive->GetArchiveProperty(kpidExtension, &prop)); 1439 RINOK(archive->GetArchiveProperty(kpidExtension, &prop))
1447 if (prop.vt == VT_BSTR) 1440 if (prop.vt == VT_BSTR)
1448 pi.Extension.SetFromBstr(prop.bstrVal); 1441 pi.Extension.SetFromBstr(prop.bstrVal);
1449 } 1442 }
@@ -1451,14 +1444,14 @@ static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NAr
1451 1444
1452 { 1445 {
1453 NCOM::CPropVariant prop; 1446 NCOM::CPropVariant prop;
1454 RINOK(archive->GetArchiveProperty(kpidShortComment, &prop)); 1447 RINOK(archive->GetArchiveProperty(kpidShortComment, &prop))
1455 if (prop.vt == VT_BSTR) 1448 if (prop.vt == VT_BSTR)
1456 pi.Comment.SetFromBstr(prop.bstrVal); 1449 pi.Comment.SetFromBstr(prop.bstrVal);
1457 } 1450 }
1458 1451
1459 1452
1460 UInt32 numItems; 1453 UInt32 numItems;
1461 RINOK(archive->GetNumberOfItems(&numItems)); 1454 RINOK(archive->GetNumberOfItems(&numItems))
1462 1455
1463 // pi.NumSubFiles = numItems; 1456 // pi.NumSubFiles = numItems;
1464 // RINOK(Archive_GetArcProp_UInt(archive, kpidUnpackSize, pi.UnpackSize, pi.UnpackSize_Defined)); 1457 // RINOK(Archive_GetArcProp_UInt(archive, kpidUnpackSize, pi.UnpackSize, pi.UnpackSize_Defined));
@@ -1499,14 +1492,14 @@ HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset)
1499{ 1492{
1500 if (!op.stream) 1493 if (!op.stream)
1501 return S_OK; 1494 return S_OK;
1502 RINOK(op.stream->Seek((Int64)offset, STREAM_SEEK_SET, NULL)); 1495 RINOK(InStream_SeekSet(op.stream, offset))
1503 const UInt32 kBufSize = 1 << 11; 1496 const UInt32 kBufSize = 1 << 11;
1504 Byte buf[kBufSize]; 1497 Byte buf[kBufSize];
1505 1498
1506 for (;;) 1499 for (;;)
1507 { 1500 {
1508 UInt32 processed = 0; 1501 UInt32 processed = 0;
1509 RINOK(op.stream->Read(buf, kBufSize, &processed)); 1502 RINOK(op.stream->Read(buf, kBufSize, &processed))
1510 if (processed == 0) 1503 if (processed == 0)
1511 { 1504 {
1512 // ErrorInfo.NonZerosTail = false; 1505 // ErrorInfo.NonZerosTail = false;
@@ -1527,21 +1520,19 @@ HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset)
1527 1520
1528 1521
1529 1522
1530#ifndef _SFX 1523#ifndef Z7_SFX
1531 1524
1532class CExtractCallback_To_OpenCallback: 1525Z7_CLASS_IMP_COM_2(
1533 public IArchiveExtractCallback, 1526 CExtractCallback_To_OpenCallback
1534 public ICompressProgressInfo, 1527 , IArchiveExtractCallback
1535 public CMyUnknownImp 1528 , ICompressProgressInfo
1536{ 1529)
1530 Z7_IFACE_COM7_IMP(IProgress)
1537public: 1531public:
1538 CMyComPtr<IArchiveOpenCallback> Callback; 1532 CMyComPtr<IArchiveOpenCallback> Callback;
1539 UInt64 Files; 1533 UInt64 Files;
1540 UInt64 Offset; 1534 UInt64 Offset;
1541 1535
1542 MY_UNKNOWN_IMP2(IArchiveExtractCallback, ICompressProgressInfo)
1543 INTERFACE_IArchiveExtractCallback(;)
1544 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
1545 void Init(IArchiveOpenCallback *callback) 1536 void Init(IArchiveOpenCallback *callback)
1546 { 1537 {
1547 Callback = callback; 1538 Callback = callback;
@@ -1550,17 +1541,17 @@ public:
1550 } 1541 }
1551}; 1542};
1552 1543
1553STDMETHODIMP CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */) 1544Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */))
1554{ 1545{
1555 return S_OK; 1546 return S_OK;
1556} 1547}
1557 1548
1558STDMETHODIMP CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */) 1549Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */))
1559{ 1550{
1560 return S_OK; 1551 return S_OK;
1561} 1552}
1562 1553
1563STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) 1554Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */))
1564{ 1555{
1565 if (Callback) 1556 if (Callback)
1566 { 1557 {
@@ -1572,18 +1563,18 @@ STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize
1572 return S_OK; 1563 return S_OK;
1573} 1564}
1574 1565
1575STDMETHODIMP CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */) 1566Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */))
1576{ 1567{
1577 *outStream = NULL; 1568 *outStream = NULL;
1578 return S_OK; 1569 return S_OK;
1579} 1570}
1580 1571
1581STDMETHODIMP CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */) 1572Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */))
1582{ 1573{
1583 return S_OK; 1574 return S_OK;
1584} 1575}
1585 1576
1586STDMETHODIMP CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */) 1577Z7_COM7F_IMF(CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */))
1587{ 1578{
1588 return S_OK; 1579 return S_OK;
1589} 1580}
@@ -1597,30 +1588,31 @@ static HRESULT OpenArchiveSpec(IInArchive *archive, bool needPhySize,
1597 /* 1588 /*
1598 if (needPhySize) 1589 if (needPhySize)
1599 { 1590 {
1600 CMyComPtr<IArchiveOpen2> open2; 1591 Z7_DECL_CMyComPtr_QI_FROM(
1601 archive->QueryInterface(IID_IArchiveOpen2, (void **)&open2); 1592 IArchiveOpen2,
1593 open2, archive)
1602 if (open2) 1594 if (open2)
1603 return open2->ArcOpen2(stream, kOpenFlags_RealPhySize, openCallback); 1595 return open2->ArcOpen2(stream, kOpenFlags_RealPhySize, openCallback);
1604 } 1596 }
1605 */ 1597 */
1606 RINOK(archive->Open(stream, maxCheckStartPosition, openCallback)); 1598 RINOK(archive->Open(stream, maxCheckStartPosition, openCallback))
1607 if (needPhySize) 1599 if (needPhySize)
1608 { 1600 {
1609 bool phySize_Defined = false; 1601 bool phySize_Defined = false;
1610 UInt64 phySize = 0; 1602 UInt64 phySize = 0;
1611 RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined)); 1603 RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined))
1612 if (phySize_Defined) 1604 if (phySize_Defined)
1613 return S_OK; 1605 return S_OK;
1614 1606
1615 bool phySizeCantBeDetected = false; 1607 bool phySizeCantBeDetected = false;
1616 RINOK(Archive_GetArcProp_Bool(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected)); 1608 RINOK(Archive_GetArcProp_Bool(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected))
1617 1609
1618 if (!phySizeCantBeDetected) 1610 if (!phySizeCantBeDetected)
1619 { 1611 {
1620 PRF(printf("\n-- !phySize_Defined after Open, call archive->Extract()")); 1612 PRF(printf("\n-- !phySize_Defined after Open, call archive->Extract()"));
1621 // It's for bzip2/gz and some xz archives, where Open operation doesn't know phySize. 1613 // It's for bzip2/gz and some xz archives, where Open operation doesn't know phySize.
1622 // But the Handler will know phySize after full archive testing. 1614 // But the Handler will know phySize after full archive testing.
1623 RINOK(archive->Extract(NULL, (UInt32)(Int32)-1, BoolToInt(true), extractCallback)); 1615 RINOK(archive->Extract(NULL, (UInt32)(Int32)-1, BoolToInt(true), extractCallback))
1624 PRF(printf("\n-- OK")); 1616 PRF(printf("\n-- OK"));
1625 } 1617 }
1626 } 1618 }
@@ -1663,7 +1655,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1663 const UString fileName = ExtractFileNameFromPath(Path); 1655 const UString fileName = ExtractFileNameFromPath(Path);
1664 UString extension; 1656 UString extension;
1665 { 1657 {
1666 int dotPos = fileName.ReverseFind_Dot(); 1658 const int dotPos = fileName.ReverseFind_Dot();
1667 if (dotPos >= 0) 1659 if (dotPos >= 0)
1668 extension = fileName.Ptr((unsigned)(dotPos + 1)); 1660 extension = fileName.Ptr((unsigned)(dotPos + 1));
1669 } 1661 }
@@ -1671,7 +1663,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1671 CIntVector orderIndices; 1663 CIntVector orderIndices;
1672 1664
1673 bool searchMarkerInHandler = false; 1665 bool searchMarkerInHandler = false;
1674 #ifdef _SFX 1666 #ifdef Z7_SFX
1675 searchMarkerInHandler = true; 1667 searchMarkerInHandler = true;
1676 #endif 1668 #endif
1677 1669
@@ -1681,25 +1673,25 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1681 isMainFormatArr[i] = false; 1673 isMainFormatArr[i] = false;
1682 } 1674 }
1683 1675
1684 UInt64 maxStartOffset = 1676 const UInt64 maxStartOffset =
1685 op.openType.MaxStartOffset_Defined ? 1677 op.openType.MaxStartOffset_Defined ?
1686 op.openType.MaxStartOffset : 1678 op.openType.MaxStartOffset :
1687 kMaxCheckStartPosition; 1679 kMaxCheckStartPosition;
1688 1680
1689 #ifndef _SFX 1681 #ifndef Z7_SFX
1690 bool isUnknownExt = false; 1682 bool isUnknownExt = false;
1691 #endif 1683 #endif
1692 1684
1693 #ifndef _SFX 1685 #ifndef Z7_SFX
1694 bool isForced = false; 1686 bool isForced = false;
1695 #endif 1687 #endif
1696 1688
1697 unsigned numMainTypes = 0; 1689 unsigned numMainTypes = 0;
1698 int formatIndex = op.openType.FormatIndex; 1690 const int formatIndex = op.openType.FormatIndex;
1699 1691
1700 if (formatIndex >= 0) 1692 if (formatIndex >= 0)
1701 { 1693 {
1702 #ifndef _SFX 1694 #ifndef Z7_SFX
1703 isForced = true; 1695 isForced = true;
1704 #endif 1696 #endif
1705 orderIndices.Add(formatIndex); 1697 orderIndices.Add(formatIndex);
@@ -1711,12 +1703,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1711 else 1703 else
1712 { 1704 {
1713 unsigned numFinded = 0; 1705 unsigned numFinded = 0;
1714 #ifndef _SFX 1706 #ifndef Z7_SFX
1715 bool isPrearcExt = false; 1707 bool isPrearcExt = false;
1716 #endif 1708 #endif
1717 1709
1718 { 1710 {
1719 #ifndef _SFX 1711 #ifndef Z7_SFX
1720 1712
1721 bool isZip = false; 1713 bool isZip = false;
1722 bool isRar = false; 1714 bool isRar = false;
@@ -1758,13 +1750,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1758 if (op.excludedFormats->FindInSorted((int)i) >= 0) 1750 if (op.excludedFormats->FindInSorted((int)i) >= 0)
1759 continue; 1751 continue;
1760 1752
1761 #ifndef _SFX 1753 #ifndef Z7_SFX
1762 if (IsPreArcFormat(ai)) 1754 if (IsPreArcFormat(ai))
1763 isPrearcExt = true; 1755 isPrearcExt = true;
1764 #endif 1756 #endif
1765 1757
1766 if (ai.FindExtension(extension) >= 0 1758 if (ai.FindExtension(extension) >= 0
1767 #ifndef _SFX 1759 #ifndef Z7_SFX
1768 || (isZip && ai.Is_Zip()) 1760 || (isZip && ai.Is_Zip())
1769 || (isRar && ai.Is_Rar()) 1761 || (isRar && ai.Is_Rar())
1770 #endif 1762 #endif
@@ -1795,11 +1787,11 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1795 } 1787 }
1796 */ 1788 */
1797 1789
1798 #ifndef _SFX 1790 #ifndef Z7_SFX
1799 1791
1800 if (op.stream && orderIndices.Size() >= 2) 1792 if (op.stream && orderIndices.Size() >= 2)
1801 { 1793 {
1802 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 1794 RINOK(InStream_SeekToBegin(op.stream))
1803 CByteBuffer byteBuffer; 1795 CByteBuffer byteBuffer;
1804 CIntVector orderIndices2; 1796 CIntVector orderIndices2;
1805 if (numFinded == 0 || IsExeExt(extension)) 1797 if (numFinded == 0 || IsExeExt(extension))
@@ -1808,13 +1800,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1808 } 1800 }
1809 else if (extension.IsEqualTo("000") || extension.IsEqualTo("001")) 1801 else if (extension.IsEqualTo("000") || extension.IsEqualTo("001"))
1810 { 1802 {
1811 int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar"); 1803 const int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar");
1812 if (i >= 0) 1804 if (i >= 0)
1813 { 1805 {
1814 const size_t kBufSize = (1 << 10); 1806 const size_t kBufSize = (1 << 10);
1815 byteBuffer.Alloc(kBufSize); 1807 byteBuffer.Alloc(kBufSize);
1816 size_t processedSize = kBufSize; 1808 size_t processedSize = kBufSize;
1817 RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); 1809 RINOK(ReadStream(op.stream, byteBuffer, &processedSize))
1818 if (processedSize >= 16) 1810 if (processedSize >= 16)
1819 { 1811 {
1820 const Byte *buf = byteBuffer; 1812 const Byte *buf = byteBuffer;
@@ -1834,7 +1826,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1834 const size_t kBufSize = (1 << 10); 1826 const size_t kBufSize = (1 << 10);
1835 byteBuffer.Alloc(kBufSize); 1827 byteBuffer.Alloc(kBufSize);
1836 size_t processedSize = kBufSize; 1828 size_t processedSize = kBufSize;
1837 RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); 1829 RINOK(ReadStream(op.stream, byteBuffer, &processedSize))
1838 if (processedSize == 0) 1830 if (processedSize == 0)
1839 return S_FALSE; 1831 return S_FALSE;
1840 1832
@@ -1870,7 +1862,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1870 1862
1871 FOR_VECTOR (i, orderIndices) 1863 FOR_VECTOR (i, orderIndices)
1872 { 1864 {
1873 int val = orderIndices[i]; 1865 const int val = orderIndices[i];
1874 if (val != -1) 1866 if (val != -1)
1875 orderIndices2.Add(val); 1867 orderIndices2.Add(val);
1876 } 1868 }
@@ -1879,12 +1871,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1879 1871
1880 if (orderIndices.Size() >= 2) 1872 if (orderIndices.Size() >= 2)
1881 { 1873 {
1882 int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso"); 1874 const int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso");
1883 int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf"); 1875 const int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf");
1884 if (iUdf > iIso && iIso >= 0) 1876 if (iUdf > iIso && iIso >= 0)
1885 { 1877 {
1886 int isoIndex = orderIndices[(unsigned)iIso]; 1878 const int isoIndex = orderIndices[(unsigned)iIso];
1887 int udfIndex = orderIndices[(unsigned)iUdf]; 1879 const int udfIndex = orderIndices[(unsigned)iUdf];
1888 orderIndices[(unsigned)iUdf] = isoIndex; 1880 orderIndices[(unsigned)iUdf] = isoIndex;
1889 orderIndices[(unsigned)iIso] = udfIndex; 1881 orderIndices[(unsigned)iIso] = udfIndex;
1890 } 1882 }
@@ -1893,7 +1885,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1893 numMainTypes = numFinded; 1885 numMainTypes = numFinded;
1894 isUnknownExt = (numMainTypes == 0) || isPrearcExt; 1886 isUnknownExt = (numMainTypes == 0) || isPrearcExt;
1895 1887
1896 #else // _SFX 1888 #else // Z7_SFX
1897 1889
1898 numMainTypes = orderIndices.Size(); 1890 numMainTypes = orderIndices.Size();
1899 1891
@@ -1907,13 +1899,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1907 UInt64 fileSize = 0; 1899 UInt64 fileSize = 0;
1908 if (op.stream) 1900 if (op.stream)
1909 { 1901 {
1910 RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); 1902 RINOK(InStream_GetSize_SeekToBegin(op.stream, fileSize))
1911 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL));
1912 } 1903 }
1913 FileSize = fileSize; 1904 FileSize = fileSize;
1914 1905
1915 1906
1916 #ifndef _SFX 1907 #ifndef Z7_SFX
1917 1908
1918 CBoolArr skipFrontalFormat(op.codecs->Formats.Size()); 1909 CBoolArr skipFrontalFormat(op.codecs->Formats.Size());
1919 { 1910 {
@@ -1945,7 +1936,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1945 1936
1946 bool exactOnly = false; 1937 bool exactOnly = false;
1947 1938
1948 #ifndef _SFX 1939 #ifndef Z7_SFX
1949 1940
1950 const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex]; 1941 const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex];
1951 // OutputDebugStringW(ai.Name); 1942 // OutputDebugStringW(ai.Name);
@@ -1963,16 +1954,16 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1963 1954
1964 // Some handlers do not set total bytes. So we set it here 1955 // Some handlers do not set total bytes. So we set it here
1965 if (op.callback) 1956 if (op.callback)
1966 RINOK(op.callback->SetTotal(NULL, &fileSize)); 1957 RINOK(op.callback->SetTotal(NULL, &fileSize))
1967 1958
1968 if (op.stream) 1959 if (op.stream)
1969 { 1960 {
1970 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 1961 RINOK(InStream_SeekToBegin(op.stream))
1971 } 1962 }
1972 1963
1973 CMyComPtr<IInArchive> archive; 1964 CMyComPtr<IInArchive> archive;
1974 1965
1975 RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)); 1966 RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive))
1976 if (!archive) 1967 if (!archive)
1977 continue; 1968 continue;
1978 1969
@@ -1991,13 +1982,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
1991 result = openSeq->OpenSeq(op.seqStream); 1982 result = openSeq->OpenSeq(op.seqStream);
1992 } 1983 }
1993 1984
1994 RINOK(ReadBasicProps(archive, 0, result)); 1985 RINOK(ReadBasicProps(archive, 0, result))
1995 1986
1996 if (result == S_FALSE) 1987 if (result == S_FALSE)
1997 { 1988 {
1998 bool isArc = ErrorInfo.IsArc_After_NonOpen(); 1989 bool isArc = ErrorInfo.IsArc_After_NonOpen();
1999 1990
2000 #ifndef _SFX 1991 #ifndef Z7_SFX
2001 // if it's archive, we allow another open attempt for parser 1992 // if it's archive, we allow another open attempt for parser
2002 if (!mode.CanReturnParser || !isArc) 1993 if (!mode.CanReturnParser || !isArc)
2003 skipFrontalFormat[(unsigned)FormatIndex] = true; 1994 skipFrontalFormat[(unsigned)FormatIndex] = true;
@@ -2017,7 +2008,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2017 // if (formatIndex < 0 && !searchMarkerInHandler) 2008 // if (formatIndex < 0 && !searchMarkerInHandler)
2018 { 2009 {
2019 // if bad archive was detected, we don't need additional open attempts 2010 // if bad archive was detected, we don't need additional open attempts
2020 #ifndef _SFX 2011 #ifndef Z7_SFX
2021 if (!IsPreArcFormat(ai) /* || !mode.SkipSfxStub */) 2012 if (!IsPreArcFormat(ai) /* || !mode.SkipSfxStub */)
2022 #endif 2013 #endif
2023 return S_FALSE; 2014 return S_FALSE;
@@ -2026,7 +2017,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2026 } 2017 }
2027 2018
2028 /* 2019 /*
2029 #ifndef _SFX 2020 #ifndef Z7_SFX
2030 if (IsExeExt(extension) || ai.Flags_PreArc()) 2021 if (IsExeExt(extension) || ai.Flags_PreArc())
2031 { 2022 {
2032 // openOnlyFullArc = false; 2023 // openOnlyFullArc = false;
@@ -2039,9 +2030,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2039 continue; 2030 continue;
2040 } 2031 }
2041 2032
2042 RINOK(result); 2033 RINOK(result)
2043 2034
2044 #ifndef _SFX 2035 #ifndef Z7_SFX
2045 2036
2046 bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; 2037 bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex];
2047 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); 2038 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
@@ -2049,7 +2040,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2049 bool thereIsTail = ErrorInfo.ThereIsTail; 2040 bool thereIsTail = ErrorInfo.ThereIsTail;
2050 if (thereIsTail && mode.ZerosTailIsAllowed) 2041 if (thereIsTail && mode.ZerosTailIsAllowed)
2051 { 2042 {
2052 RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))); 2043 RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize)))
2053 if (ErrorInfo.IgnoreTail) 2044 if (ErrorInfo.IgnoreTail)
2054 thereIsTail = false; 2045 thereIsTail = false;
2055 } 2046 }
@@ -2103,7 +2094,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2103 2094
2104 2095
2105 2096
2106 #ifndef _SFX 2097 #ifndef Z7_SFX
2107 2098
2108 if (!op.stream) 2099 if (!op.stream)
2109 return S_FALSE; 2100 return S_FALSE;
@@ -2148,9 +2139,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2148 endOfFile = true; 2139 endOfFile = true;
2149 } 2140 }
2150 byteBuffer.Alloc(bufSize); 2141 byteBuffer.Alloc(bufSize);
2151 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 2142 RINOK(InStream_SeekToBegin(op.stream))
2152 processedSize = bufSize; 2143 processedSize = bufSize;
2153 RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); 2144 RINOK(ReadStream(op.stream, byteBuffer, &processedSize))
2154 if (processedSize == 0) 2145 if (processedSize == 0)
2155 return S_FALSE; 2146 return S_FALSE;
2156 if (processedSize < bufSize) 2147 if (processedSize < bufSize)
@@ -2232,12 +2223,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2232 const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex]; 2223 const CArcInfoEx &ai = op.codecs->Formats[(unsigned)FormatIndex];
2233 2224
2234 if (op.callback) 2225 if (op.callback)
2235 RINOK(op.callback->SetTotal(NULL, &fileSize)); 2226 RINOK(op.callback->SetTotal(NULL, &fileSize))
2236 2227
2237 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 2228 RINOK(InStream_SeekToBegin(op.stream))
2238 2229
2239 CMyComPtr<IInArchive> archive; 2230 CMyComPtr<IInArchive> archive;
2240 RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive)); 2231 RINOK(PrepareToOpen(op, (unsigned)FormatIndex, archive))
2241 if (!archive) 2232 if (!archive)
2242 continue; 2233 continue;
2243 2234
@@ -2263,9 +2254,9 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2263 // printf(" OpenForSize Error"); 2254 // printf(" OpenForSize Error");
2264 continue; 2255 continue;
2265 } 2256 }
2266 RINOK(result); 2257 RINOK(result)
2267 2258
2268 RINOK(ReadBasicProps(archive, 0, result)); 2259 RINOK(ReadBasicProps(archive, 0, result))
2269 2260
2270 if (Offset > 0) 2261 if (Offset > 0)
2271 { 2262 {
@@ -2302,7 +2293,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2302 2293
2303 if (mode.CanReturnArc) 2294 if (mode.CanReturnArc)
2304 { 2295 {
2305 bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; 2296 const bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex];
2306 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); 2297 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
2307 bool openCur = false; 2298 bool openCur = false;
2308 2299
@@ -2312,7 +2303,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2312 { 2303 {
2313 if (mode.ZerosTailIsAllowed) 2304 if (mode.ZerosTailIsAllowed)
2314 { 2305 {
2315 RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize))); 2306 RINOK(CheckZerosTail(op, (UInt64)(Offset + (Int64)PhySize)))
2316 if (ErrorInfo.IgnoreTail) 2307 if (ErrorInfo.IgnoreTail)
2317 openCur = true; 2308 openCur = true;
2318 } 2309 }
@@ -2352,7 +2343,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2352 continue; 2343 continue;
2353 2344
2354 // printf("\nAdd offset = %d", (int)pi.Offset); 2345 // printf("\nAdd offset = %d", (int)pi.Offset);
2355 RINOK(ReadParseItemProps(archive, ai, pi)); 2346 RINOK(ReadParseItemProps(archive, ai, pi))
2356 handlerSpec->AddItem(pi); 2347 handlerSpec->AddItem(pi);
2357 } 2348 }
2358 } 2349 }
@@ -2451,7 +2442,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2451 // canReturnTailArc = true; 2442 // canReturnTailArc = true;
2452 } 2443 }
2453 2444
2454 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 2445 RINOK(InStream_SeekToBegin(op.stream))
2455 2446
2456 CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream; 2447 CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream;
2457 CMyComPtr<IInStream> limitedStream = limitedStreamSpec; 2448 CMyComPtr<IInStream> limitedStream = limitedStreamSpec;
@@ -2465,13 +2456,13 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2465 openCallback_Offset = openCallback_Offset_Spec; 2456 openCallback_Offset = openCallback_Offset_Spec;
2466 openCallback_Offset_Spec->Callback = op.callback; 2457 openCallback_Offset_Spec->Callback = op.callback;
2467 openCallback_Offset_Spec->Callback.QueryInterface(IID_IArchiveOpenVolumeCallback, &openCallback_Offset_Spec->OpenVolumeCallback); 2458 openCallback_Offset_Spec->Callback.QueryInterface(IID_IArchiveOpenVolumeCallback, &openCallback_Offset_Spec->OpenVolumeCallback);
2468 #ifndef _NO_CRYPTO 2459 #ifndef Z7_NO_CRYPTO
2469 openCallback_Offset_Spec->Callback.QueryInterface(IID_ICryptoGetTextPassword, &openCallback_Offset_Spec->GetTextPassword); 2460 openCallback_Offset_Spec->Callback.QueryInterface(IID_ICryptoGetTextPassword, &openCallback_Offset_Spec->GetTextPassword);
2470 #endif 2461 #endif
2471 } 2462 }
2472 2463
2473 if (op.callback) 2464 if (op.callback)
2474 RINOK(op.callback->SetTotal(NULL, &fileSize)); 2465 RINOK(op.callback->SetTotal(NULL, &fileSize))
2475 2466
2476 CByteBuffer &byteBuffer = limitedStreamSpec->Buffer; 2467 CByteBuffer &byteBuffer = limitedStreamSpec->Buffer;
2477 byteBuffer.Alloc(kBufSize); 2468 byteBuffer.Alloc(kBufSize);
@@ -2509,8 +2500,8 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2509 size_t processedSize = kBufSize - bytesInBuf; 2500 size_t processedSize = kBufSize - bytesInBuf;
2510 // printf("\nRead ask = %d", (unsigned)processedSize); 2501 // printf("\nRead ask = %d", (unsigned)processedSize);
2511 UInt64 seekPos = bufPhyPos + bytesInBuf; 2502 UInt64 seekPos = bufPhyPos + bytesInBuf;
2512 RINOK(op.stream->Seek((Int64)(bufPhyPos + bytesInBuf), STREAM_SEEK_SET, NULL)); 2503 RINOK(InStream_SeekSet(op.stream, bufPhyPos + bytesInBuf))
2513 RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize)); 2504 RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize))
2514 // printf(" processed = %d", (unsigned)processedSize); 2505 // printf(" processed = %d", (unsigned)processedSize);
2515 if (processedSize == 0) 2506 if (processedSize == 0)
2516 { 2507 {
@@ -2568,7 +2559,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2568 2559
2569 if (pos >= callbackPrev + (1 << 23)) 2560 if (pos >= callbackPrev + (1 << 23))
2570 { 2561 {
2571 RINOK(openCallback_Offset_Spec->SetCompleted(NULL, NULL)); 2562 RINOK(openCallback_Offset->SetCompleted(NULL, NULL))
2572 callbackPrev = pos; 2563 callbackPrev = pos;
2573 } 2564 }
2574 } 2565 }
@@ -2691,10 +2682,10 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2691 2682
2692 if (ai.IsArcFunc && startArcPos >= bufPhyPos) 2683 if (ai.IsArcFunc && startArcPos >= bufPhyPos)
2693 { 2684 {
2694 size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos); 2685 const size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos);
2695 if (offsetInBuf < bytesInBuf) 2686 if (offsetInBuf < bytesInBuf)
2696 { 2687 {
2697 UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf); 2688 const UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf);
2698 if (isArcRes == k_IsArc_Res_NO) 2689 if (isArcRes == k_IsArc_Res_NO)
2699 continue; 2690 continue;
2700 if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile) 2691 if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile)
@@ -2716,7 +2707,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2716 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); 2707 const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt);
2717 2708
2718 CMyComPtr<IInArchive> archive; 2709 CMyComPtr<IInArchive> archive;
2719 RINOK(PrepareToOpen(op, index, archive)); 2710 RINOK(PrepareToOpen(op, index, archive))
2720 if (!archive) 2711 if (!archive)
2721 return E_FAIL; 2712 return E_FAIL;
2722 2713
@@ -2728,12 +2719,12 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2728 2719
2729 if (ai.Flags_UseGlobalOffset()) 2720 if (ai.Flags_UseGlobalOffset())
2730 { 2721 {
2731 limitedStreamSpec->InitAndSeek(0, fileSize); 2722 RINOK(limitedStreamSpec->InitAndSeek(0, fileSize))
2732 limitedStream->Seek((Int64)startArcPos, STREAM_SEEK_SET, NULL); 2723 RINOK(InStream_SeekSet(limitedStream, startArcPos))
2733 } 2724 }
2734 else 2725 else
2735 { 2726 {
2736 limitedStreamSpec->InitAndSeek(startArcPos, rem); 2727 RINOK(limitedStreamSpec->InitAndSeek(startArcPos, rem))
2737 arcStreamOffset = startArcPos; 2728 arcStreamOffset = startArcPos;
2738 } 2729 }
2739 2730
@@ -2755,7 +2746,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2755 useOffsetCallback ? (IArchiveOpenCallback *)openCallback_Offset : (IArchiveOpenCallback *)op.callback, 2746 useOffsetCallback ? (IArchiveOpenCallback *)openCallback_Offset : (IArchiveOpenCallback *)op.callback,
2756 extractCallback_To_OpenCallback); 2747 extractCallback_To_OpenCallback);
2757 2748
2758 RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result)); 2749 RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result))
2759 2750
2760 bool isOpen = false; 2751 bool isOpen = false;
2761 2752
@@ -2784,7 +2775,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2784 continue; 2775 continue;
2785 } 2776 }
2786 isOpen = true; 2777 isOpen = true;
2787 RINOK(result); 2778 RINOK(result)
2788 PRF(printf(" OK ")); 2779 PRF(printf(" OK "));
2789 } 2780 }
2790 2781
@@ -2874,7 +2865,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2874 pos = pi.Offset + pi.Size; 2865 pos = pi.Offset + pi.Size;
2875 2866
2876 2867
2877 RINOK(ReadParseItemProps(archive, ai, pi)); 2868 RINOK(ReadParseItemProps(archive, ai, pi))
2878 2869
2879 if (pi.Offset < startArcPos && !mode.EachPos /* && phySize_Defined */) 2870 if (pi.Offset < startArcPos && !mode.EachPos /* && phySize_Defined */)
2880 { 2871 {
@@ -2903,7 +2894,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
2903 bool thereIsTail = ErrorInfo.ThereIsTail; 2894 bool thereIsTail = ErrorInfo.ThereIsTail;
2904 if (thereIsTail && mode.ZerosTailIsAllowed) 2895 if (thereIsTail && mode.ZerosTailIsAllowed)
2905 { 2896 {
2906 RINOK(CheckZerosTail(op, (UInt64)((Int64)arcStreamOffset + Offset + (Int64)PhySize))); 2897 RINOK(CheckZerosTail(op, (UInt64)((Int64)arcStreamOffset + Offset + (Int64)PhySize)))
2907 if (ErrorInfo.IgnoreTail) 2898 if (ErrorInfo.IgnoreTail)
2908 thereIsTail = false; 2899 thereIsTail = false;
2909 } 2900 }
@@ -3029,7 +3020,7 @@ HRESULT CArc::OpenStream2(const COpenOptions &op)
3029 3020
3030HRESULT CArc::OpenStream(const COpenOptions &op) 3021HRESULT CArc::OpenStream(const COpenOptions &op)
3031{ 3022{
3032 RINOK(OpenStream2(op)); 3023 RINOK(OpenStream2(op))
3033 // PrintNumber("op.formatIndex 3", op.formatIndex); 3024 // PrintNumber("op.formatIndex 3", op.formatIndex);
3034 3025
3035 if (Archive) 3026 if (Archive)
@@ -3039,12 +3030,12 @@ HRESULT CArc::OpenStream(const COpenOptions &op)
3039 Archive->QueryInterface(IID_IArchiveGetRawProps, (void **)&GetRawProps); 3030 Archive->QueryInterface(IID_IArchiveGetRawProps, (void **)&GetRawProps);
3040 Archive->QueryInterface(IID_IArchiveGetRootProps, (void **)&GetRootProps); 3031 Archive->QueryInterface(IID_IArchiveGetRootProps, (void **)&GetRootProps);
3041 3032
3042 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsTree, IsTree)); 3033 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsTree, IsTree))
3043 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsDeleted, Ask_Deleted)); 3034 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsDeleted, Ask_Deleted))
3044 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAltStream, Ask_AltStream)); 3035 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAltStream, Ask_AltStream))
3045 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAux, Ask_Aux)); 3036 RINOK(Archive_GetArcProp_Bool(Archive, kpidIsAux, Ask_Aux))
3046 RINOK(Archive_GetArcProp_Bool(Archive, kpidINode, Ask_INode)); 3037 RINOK(Archive_GetArcProp_Bool(Archive, kpidINode, Ask_INode))
3047 RINOK(Archive_GetArcProp_Bool(Archive, kpidReadOnly, IsReadOnly)); 3038 RINOK(Archive_GetArcProp_Bool(Archive, kpidReadOnly, IsReadOnly))
3048 3039
3049 const UString fileName = ExtractFileNameFromPath(Path); 3040 const UString fileName = ExtractFileNameFromPath(Path);
3050 UString extension; 3041 UString extension;
@@ -3074,7 +3065,7 @@ HRESULT CArc::OpenStream(const COpenOptions &op)
3074 return S_OK; 3065 return S_OK;
3075} 3066}
3076 3067
3077#ifdef _SFX 3068#ifdef Z7_SFX
3078 3069
3079#ifdef _WIN32 3070#ifdef _WIN32
3080 #define k_ExeExt ".exe" 3071 #define k_ExeExt ".exe"
@@ -3105,7 +3096,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op)
3105 if (!fileStreamSpec->Open(us2fs(Path))) 3096 if (!fileStreamSpec->Open(us2fs(Path)))
3106 return GetLastError_noZero_HRESULT(); 3097 return GetLastError_noZero_HRESULT();
3107 op.stream = fileStream; 3098 op.stream = fileStream;
3108 #ifdef _SFX 3099 #ifdef Z7_SFX
3109 IgnoreSplit = true; 3100 IgnoreSplit = true;
3110 #endif 3101 #endif
3111 } 3102 }
@@ -3114,7 +3105,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op)
3114 if (callback) 3105 if (callback)
3115 { 3106 {
3116 UInt64 fileSize; 3107 UInt64 fileSize;
3117 RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); 3108 RINOK(InStream_GetSize_SeekToEnd(op.stream, fileSize));
3118 RINOK(op.callback->SetTotal(NULL, &fileSize)) 3109 RINOK(op.callback->SetTotal(NULL, &fileSize))
3119 } 3110 }
3120 */ 3111 */
@@ -3122,7 +3113,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op)
3122 HRESULT res = OpenStream(op); 3113 HRESULT res = OpenStream(op);
3123 IgnoreSplit = false; 3114 IgnoreSplit = false;
3124 3115
3125 #ifdef _SFX 3116 #ifdef Z7_SFX
3126 3117
3127 if (res != S_FALSE 3118 if (res != S_FALSE
3128 || !fileStreamSpec 3119 || !fileStreamSpec
@@ -3141,7 +3132,7 @@ HRESULT CArc::OpenStreamOrFile(COpenOptions &op)
3141 if (ai.Is_Split()) 3132 if (ai.Is_Split())
3142 continue; 3133 continue;
3143 UString path3 = path2; 3134 UString path3 = path2;
3144 path3 += '.'; 3135 path3.Add_Dot();
3145 path3 += ai.GetMainExt(); // "7z" for SFX. 3136 path3 += ai.GetMainExt(); // "7z" for SFX.
3146 Path = path3; 3137 Path = path3;
3147 Path += ".001"; 3138 Path += ".001";
@@ -3187,7 +3178,7 @@ HRESULT CArchiveLink::Close()
3187 for (unsigned i = Arcs.Size(); i != 0;) 3178 for (unsigned i = Arcs.Size(); i != 0;)
3188 { 3179 {
3189 i--; 3180 i--;
3190 RINOK(Arcs[i].Close()); 3181 RINOK(Arcs[i].Close())
3191 } 3182 }
3192 IsOpen = false; 3183 IsOpen = false;
3193 // ErrorsText.Empty(); 3184 // ErrorsText.Empty();
@@ -3320,13 +3311,13 @@ HRESULT CArchiveLink::Open(COpenOptions &op)
3320 UInt32 mainSubfile; 3311 UInt32 mainSubfile;
3321 { 3312 {
3322 NCOM::CPropVariant prop; 3313 NCOM::CPropVariant prop;
3323 RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop)); 3314 RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop))
3324 if (prop.vt == VT_UI4) 3315 if (prop.vt == VT_UI4)
3325 mainSubfile = prop.ulVal; 3316 mainSubfile = prop.ulVal;
3326 else 3317 else
3327 break; 3318 break;
3328 UInt32 numItems; 3319 UInt32 numItems;
3329 RINOK(arc.Archive->GetNumberOfItems(&numItems)); 3320 RINOK(arc.Archive->GetNumberOfItems(&numItems))
3330 if (mainSubfile >= numItems) 3321 if (mainSubfile >= numItems)
3331 break; 3322 break;
3332 } 3323 }
@@ -3345,16 +3336,17 @@ HRESULT CArchiveLink::Open(COpenOptions &op)
3345 break; 3336 break;
3346 3337
3347 CArc arc2; 3338 CArc arc2;
3348 RINOK(arc.GetItem_Path(mainSubfile, arc2.Path)); 3339 RINOK(arc.GetItem_Path(mainSubfile, arc2.Path))
3349 3340
3350 bool zerosTailIsAllowed; 3341 bool zerosTailIsAllowed;
3351 RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed)); 3342 RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed))
3352 3343
3353 3344
3354 if (op.callback) 3345 if (op.callback)
3355 { 3346 {
3356 CMyComPtr<IArchiveOpenSetSubArchiveName> setSubArchiveName; 3347 Z7_DECL_CMyComPtr_QI_FROM(
3357 op.callback->QueryInterface(IID_IArchiveOpenSetSubArchiveName, (void **)&setSubArchiveName); 3348 IArchiveOpenSetSubArchiveName,
3349 setSubArchiveName, op.callback)
3358 if (setSubArchiveName) 3350 if (setSubArchiveName)
3359 setSubArchiveName->SetSubArchiveName(arc2.Path); 3351 setSubArchiveName->SetSubArchiveName(arc2.Path);
3360 } 3352 }
@@ -3365,7 +3357,7 @@ HRESULT CArchiveLink::Open(COpenOptions &op)
3365 CIntVector excl; 3357 CIntVector excl;
3366 3358
3367 COpenOptions op2; 3359 COpenOptions op2;
3368 #ifndef _SFX 3360 #ifndef Z7_SFX
3369 op2.props = op.props; 3361 op2.props = op.props;
3370 #endif 3362 #endif
3371 op2.codecs = op.codecs; 3363 op2.codecs = op.codecs;
@@ -3388,8 +3380,8 @@ HRESULT CArchiveLink::Open(COpenOptions &op)
3388 NonOpen_ArcPath = arc2.Path; 3380 NonOpen_ArcPath = arc2.Path;
3389 break; 3381 break;
3390 } 3382 }
3391 RINOK(result); 3383 RINOK(result)
3392 RINOK(arc.GetItem_MTime(mainSubfile, arc2.MTime)); 3384 RINOK(arc.GetItem_MTime(mainSubfile, arc2.MTime))
3393 Arcs.Add(arc2); 3385 Arcs.Add(arc2);
3394 } 3386 }
3395 IsOpen = !Arcs.IsEmpty(); 3387 IsOpen = !Arcs.IsEmpty();
@@ -3408,7 +3400,7 @@ HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI)
3408 if (!op.stream && !op.stdInMode) 3400 if (!op.stream && !op.stdInMode)
3409 { 3401 {
3410 NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name); 3402 NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name);
3411 RINOK(openCallbackSpec->Init2(prefix, name)); 3403 RINOK(openCallbackSpec->Init2(prefix, name))
3412 } 3404 }
3413 else 3405 else
3414 { 3406 {
@@ -3423,7 +3415,7 @@ HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI)
3423 PasswordWasAsked = openCallbackSpec->PasswordWasAsked; 3415 PasswordWasAsked = openCallbackSpec->PasswordWasAsked;
3424 // Password = openCallbackSpec->Password; 3416 // Password = openCallbackSpec->Password;
3425 3417
3426 RINOK(res); 3418 RINOK(res)
3427 // VolumePaths.Add(fs2us(prefix + name)); 3419 // VolumePaths.Add(fs2us(prefix + name));
3428 3420
3429 FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed) 3421 FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed)
@@ -3446,8 +3438,9 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_
3446 UInt64 fileSize = 0; 3438 UInt64 fileSize = 0;
3447 if (op.stream) 3439 if (op.stream)
3448 { 3440 {
3449 RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); 3441 RINOK(InStream_SeekToBegin(op.stream))
3450 RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); 3442 RINOK(InStream_AtBegin_GetSize(op.stream, fileSize))
3443 // RINOK(InStream_GetSize_SeekToBegin(op.stream, fileSize))
3451 } 3444 }
3452 FileSize = fileSize; 3445 FileSize = fileSize;
3453 3446
@@ -3462,7 +3455,7 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_
3462 tailStreamSpec->Stream = op.stream; 3455 tailStreamSpec->Stream = op.stream;
3463 tailStreamSpec->Offset = (UInt64)globalOffset; 3456 tailStreamSpec->Offset = (UInt64)globalOffset;
3464 tailStreamSpec->Init(); 3457 tailStreamSpec->Init();
3465 RINOK(tailStreamSpec->SeekToStart()); 3458 RINOK(tailStreamSpec->SeekToStart())
3466 } 3459 }
3467 3460
3468 // There are archives with embedded STUBs (like ZIP), so we must support signature scanning 3461 // There are archives with embedded STUBs (like ZIP), so we must support signature scanning
@@ -3475,7 +3468,7 @@ HRESULT CArc::ReOpen(const COpenOptions &op, IArchiveOpenCallback *openCallback_
3475 3468
3476 if (res == S_OK) 3469 if (res == S_OK)
3477 { 3470 {
3478 RINOK(ReadBasicProps(Archive, (UInt64)globalOffset, res)); 3471 RINOK(ReadBasicProps(Archive, (UInt64)globalOffset, res))
3479 ArcStreamOffset = (UInt64)globalOffset; 3472 ArcStreamOffset = (UInt64)globalOffset;
3480 if (ArcStreamOffset != 0) 3473 if (ArcStreamOffset != 0)
3481 InStream = op.stream; 3474 InStream = op.stream;
@@ -3488,7 +3481,7 @@ HRESULT CArchiveLink::Open3(COpenOptions &op, IOpenCallbackUI *callbackUI)
3488 HRESULT res = Open2(op, callbackUI); 3481 HRESULT res = Open2(op, callbackUI);
3489 if (callbackUI) 3482 if (callbackUI)
3490 { 3483 {
3491 RINOK(callbackUI->Open_Finished()); 3484 RINOK(callbackUI->Open_Finished())
3492 } 3485 }
3493 return res; 3486 return res;
3494} 3487}
@@ -3508,6 +3501,8 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op)
3508 if (Arcs.Size() == 0) // ??? 3501 if (Arcs.Size() == 0) // ???
3509 return Open2(op, NULL); 3502 return Open2(op, NULL);
3510 3503
3504 /* if archive is multivolume (unsupported here still)
3505 COpenCallbackImp object will exist after Open stage. */
3511 COpenCallbackImp *openCallbackSpec = new COpenCallbackImp; 3506 COpenCallbackImp *openCallbackSpec = new COpenCallbackImp;
3512 CMyComPtr<IArchiveOpenCallback> openCallbackNew = openCallbackSpec; 3507 CMyComPtr<IArchiveOpenCallback> openCallbackNew = openCallbackSpec;
3513 3508
@@ -3516,7 +3511,7 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op)
3516 { 3511 {
3517 FString dirPrefix, fileName; 3512 FString dirPrefix, fileName;
3518 NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName); 3513 NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName);
3519 RINOK(openCallbackSpec->Init2(dirPrefix, fileName)); 3514 RINOK(openCallbackSpec->Init2(dirPrefix, fileName))
3520 } 3515 }
3521 3516
3522 3517
@@ -3527,7 +3522,9 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op)
3527 op.stream = stream; 3522 op.stream = stream;
3528 3523
3529 CArc &arc = Arcs[0]; 3524 CArc &arc = Arcs[0];
3530 HRESULT res = arc.ReOpen(op, openCallbackNew); 3525 const HRESULT res = arc.ReOpen(op, openCallbackNew);
3526
3527 openCallbackSpec->ReOpenCallback = NULL;
3531 3528
3532 PasswordWasAsked = openCallbackSpec->PasswordWasAsked; 3529 PasswordWasAsked = openCallbackSpec->PasswordWasAsked;
3533 // Password = openCallbackSpec->Password; 3530 // Password = openCallbackSpec->Password;
@@ -3536,7 +3533,7 @@ HRESULT CArchiveLink::ReOpen(COpenOptions &op)
3536 return res; 3533 return res;
3537} 3534}
3538 3535
3539#ifndef _SFX 3536#ifndef Z7_SFX
3540 3537
3541bool ParseComplexSize(const wchar_t *s, UInt64 &result); 3538bool ParseComplexSize(const wchar_t *s, UInt64 &result);
3542bool ParseComplexSize(const wchar_t *s, UInt64 &result) 3539bool ParseComplexSize(const wchar_t *s, UInt64 &result)
diff --git a/CPP/7zip/UI/Common/OpenArchive.h b/CPP/7zip/UI/Common/OpenArchive.h
index e3220b9..5c3bfe5 100644
--- a/CPP/7zip/UI/Common/OpenArchive.h
+++ b/CPP/7zip/UI/Common/OpenArchive.h
@@ -1,7 +1,7 @@
1// OpenArchive.h 1// OpenArchive.h
2 2
3#ifndef __OPEN_ARCHIVE_H 3#ifndef ZIP7_INC_OPEN_ARCHIVE_H
4#define __OPEN_ARCHIVE_H 4#define ZIP7_INC_OPEN_ARCHIVE_H
5 5
6#include "../../../Windows/PropVariant.h" 6#include "../../../Windows/PropVariant.h"
7 7
@@ -10,7 +10,7 @@
10#include "Property.h" 10#include "Property.h"
11#include "DirItem.h" 11#include "DirItem.h"
12 12
13#ifndef _SFX 13#ifndef Z7_SFX
14 14
15#define SUPPORT_ALT_STREAMS 15#define SUPPORT_ALT_STREAMS
16 16
@@ -34,7 +34,7 @@ struct COptionalOpenProperties
34}; 34};
35*/ 35*/
36 36
37#ifdef _SFX 37#ifdef Z7_SFX
38#define OPEN_PROPS_DECL 38#define OPEN_PROPS_DECL
39#else 39#else
40#define OPEN_PROPS_DECL const CObjectVector<CProperty> *props; 40#define OPEN_PROPS_DECL const CObjectVector<CProperty> *props;
@@ -243,7 +243,7 @@ struct CReadArcItem
243 bool MainIsDir; 243 bool MainIsDir;
244 UInt32 ParentIndex; // use it, if IsAltStream 244 UInt32 ParentIndex; // use it, if IsAltStream
245 245
246 #ifndef _SFX 246 #ifndef Z7_SFX
247 bool _use_baseParentFolder_mode; 247 bool _use_baseParentFolder_mode;
248 int _baseParentFolder; 248 int _baseParentFolder;
249 #endif 249 #endif
@@ -254,7 +254,7 @@ struct CReadArcItem
254 WriteToAltStreamIfColon = false; 254 WriteToAltStreamIfColon = false;
255 #endif 255 #endif
256 256
257 #ifndef _SFX 257 #ifndef Z7_SFX
258 _use_baseParentFolder_mode = false; 258 _use_baseParentFolder_mode = false;
259 _baseParentFolder = -1; 259 _baseParentFolder = -1;
260 #endif 260 #endif
@@ -270,7 +270,7 @@ class CArc
270 HRESULT CheckZerosTail(const COpenOptions &op, UInt64 offset); 270 HRESULT CheckZerosTail(const COpenOptions &op, UInt64 offset);
271 HRESULT OpenStream2(const COpenOptions &options); 271 HRESULT OpenStream2(const COpenOptions &options);
272 272
273 #ifndef _SFX 273 #ifndef Z7_SFX
274 // parts.Back() can contain alt stream name "nams:AltName" 274 // parts.Back() can contain alt stream name "nams:AltName"
275 HRESULT GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const; 275 HRESULT GetItem_PathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const;
276 #endif 276 #endif
@@ -285,8 +285,17 @@ public:
285 CMyComPtr<IArchiveGetRawProps> GetRawProps; 285 CMyComPtr<IArchiveGetRawProps> GetRawProps;
286 CMyComPtr<IArchiveGetRootProps> GetRootProps; 286 CMyComPtr<IArchiveGetRootProps> GetRootProps;
287 287
288 CArcErrorInfo ErrorInfo; // for OK archives 288 bool IsParseArc;
289 CArcErrorInfo NonOpen_ErrorInfo; // ErrorInfo for mainArchive (false OPEN) 289
290 bool IsTree;
291 bool IsReadOnly;
292
293 bool Ask_Deleted;
294 bool Ask_AltStream;
295 bool Ask_Aux;
296 bool Ask_INode;
297
298 bool IgnoreSplit; // don't try split handler
290 299
291 UString Path; 300 UString Path;
292 UString filePath; 301 UString filePath;
@@ -305,7 +314,9 @@ public:
305 // bool OkPhySize_Defined; 314 // bool OkPhySize_Defined;
306 UInt64 FileSize; 315 UInt64 FileSize;
307 UInt64 AvailPhySize; // PhySize, but it's reduced if exceed end of file 316 UInt64 AvailPhySize; // PhySize, but it's reduced if exceed end of file
308 // bool offsetDefined; 317
318 CArcErrorInfo ErrorInfo; // for OK archives
319 CArcErrorInfo NonOpen_ErrorInfo; // ErrorInfo for mainArchive (false OPEN)
309 320
310 UInt64 GetEstmatedPhySize() const { return PhySize_Defined ? PhySize : FileSize; } 321 UInt64 GetEstmatedPhySize() const { return PhySize_Defined ? PhySize : FileSize; }
311 322
@@ -314,18 +325,6 @@ public:
314 325
315 // AString ErrorFlagsText; 326 // AString ErrorFlagsText;
316 327
317 bool IsParseArc;
318
319 bool IsTree;
320 bool IsReadOnly;
321
322 bool Ask_Deleted;
323 bool Ask_AltStream;
324 bool Ask_Aux;
325 bool Ask_INode;
326
327 bool IgnoreSplit; // don't try split handler
328
329 // void Set_ErrorFlagsText(); 328 // void Set_ErrorFlagsText();
330 329
331 CArc(): 330 CArc():
@@ -341,8 +340,6 @@ public:
341 340
342 HRESULT ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes); 341 HRESULT ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes);
343 342
344 // ~CArc();
345
346 HRESULT Close() 343 HRESULT Close()
347 { 344 {
348 InStream.Release(); 345 InStream.Release();
diff --git a/CPP/7zip/UI/Common/PropIDUtils.cpp b/CPP/7zip/UI/Common/PropIDUtils.cpp
index 72384b3..ee9ff32 100644
--- a/CPP/7zip/UI/Common/PropIDUtils.cpp
+++ b/CPP/7zip/UI/Common/PropIDUtils.cpp
@@ -14,7 +14,7 @@
14 14
15#include "PropIDUtils.h" 15#include "PropIDUtils.h"
16 16
17#ifndef _SFX 17#ifndef Z7_SFX
18#define Get16(x) GetUi16(x) 18#define Get16(x) GetUi16(x)
19#define Get32(x) GetUi32(x) 19#define Get32(x) GetUi32(x)
20#endif 20#endif
@@ -54,7 +54,7 @@ FILE_ATTRIBUTE_
54 54
55 55
56static const char kPosixTypes[16] = { '0', 'p', 'c', '3', 'd', '5', 'b', '7', '-', '9', 'l', 'B', 's', 'D', 'E', 'F' }; 56static const char kPosixTypes[16] = { '0', 'p', 'c', '3', 'd', '5', 'b', '7', '-', '9', 'l', 'B', 's', 'D', 'E', 'F' };
57#define MY_ATTR_CHAR(a, n, c) ((a) & (1 << (n))) ? c : '-'; 57#define MY_ATTR_CHAR(a, n, c) (((a) & (1 << (n))) ? c : '-')
58 58
59static void ConvertPosixAttribToString(char *s, UInt32 a) throw() 59static void ConvertPosixAttribToString(char *s, UInt32 a) throw()
60{ 60{
@@ -88,7 +88,7 @@ void ConvertWinAttribToString(char *s, UInt32 wa) throw()
88 info-zip - no additional marker. 88 info-zip - no additional marker.
89 */ 89 */
90 90
91 bool isPosix = ((wa & 0xF0000000) != 0); 91 const bool isPosix = ((wa & 0xF0000000) != 0);
92 92
93 UInt32 posix = 0; 93 UInt32 posix = 0;
94 if (isPosix) 94 if (isPosix)
@@ -183,7 +183,7 @@ void ConvertPropertyToShortString2(char *dest, const PROPVARIANT &prop, PROPID p
183 { 183 {
184 if (prop.vt != VT_UI4) 184 if (prop.vt != VT_UI4)
185 break; 185 break;
186 UInt32 a = prop.ulVal; 186 const UInt32 a = prop.ulVal;
187 187
188 /* 188 /*
189 if ((a & 0x8000) && (a & 0x7FFF) == 0) 189 if ((a & 0x8000) && (a & 0x7FFF) == 0)
@@ -207,7 +207,7 @@ void ConvertPropertyToShortString2(char *dest, const PROPVARIANT &prop, PROPID p
207 ConvertUInt32ToString((UInt32)(prop.uhVal.QuadPart >> 48), dest); 207 ConvertUInt32ToString((UInt32)(prop.uhVal.QuadPart >> 48), dest);
208 dest += strlen(dest); 208 dest += strlen(dest);
209 *dest++ = '-'; 209 *dest++ = '-';
210 UInt64 low = prop.uhVal.QuadPart & (((UInt64)1 << 48) - 1); 210 const UInt64 low = prop.uhVal.QuadPart & (((UInt64)1 << 48) - 1);
211 ConvertUInt64ToString(low, dest); 211 ConvertUInt64ToString(low, dest);
212 return; 212 return;
213 } 213 }
@@ -260,7 +260,7 @@ void ConvertPropertyToString2(UString &dest, const PROPVARIANT &prop, PROPID pro
260 dest = temp; 260 dest = temp;
261} 261}
262 262
263#ifndef _SFX 263#ifndef Z7_SFX
264 264
265static inline unsigned GetHex(unsigned v) 265static inline unsigned GetHex(unsigned v)
266{ 266{
@@ -387,33 +387,33 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize)
387 s += "ERROR"; 387 s += "ERROR";
388 return; 388 return;
389 } 389 }
390 UInt32 rev = p[0]; 390 const UInt32 rev = p[0];
391 if (rev != 1) 391 if (rev != 1)
392 { 392 {
393 s += "UNSUPPORTED"; 393 s += "UNSUPPORTED";
394 return; 394 return;
395 } 395 }
396 UInt32 num = p[1]; 396 const UInt32 num = p[1];
397 if (8 + num * 4 > lim) 397 if (8 + num * 4 > lim)
398 { 398 {
399 s += "ERROR"; 399 s += "ERROR";
400 return; 400 return;
401 } 401 }
402 sidSize = 8 + num * 4; 402 sidSize = 8 + num * 4;
403 UInt32 authority = GetBe32(p + 4); 403 const UInt32 authority = GetBe32(p + 4);
404 404
405 if (p[2] == 0 && p[3] == 0 && authority == 5 && num >= 1) 405 if (p[2] == 0 && p[3] == 0 && authority == 5 && num >= 1)
406 { 406 {
407 UInt32 v0 = Get32(p + 8); 407 const UInt32 v0 = Get32(p + 8);
408 if (v0 < ARRAY_SIZE(sidNames)) 408 if (v0 < Z7_ARRAY_SIZE(sidNames))
409 { 409 {
410 s += sidNames[v0]; 410 s += sidNames[v0];
411 return; 411 return;
412 } 412 }
413 if (v0 == 32 && num == 2) 413 if (v0 == 32 && num == 2)
414 { 414 {
415 UInt32 v1 = Get32(p + 12); 415 const UInt32 v1 = Get32(p + 12);
416 int index = FindPairIndex(sid_32_Names, ARRAY_SIZE(sid_32_Names), v1); 416 const int index = FindPairIndex(sid_32_Names, Z7_ARRAY_SIZE(sid_32_Names), v1);
417 if (index >= 0) 417 if (index >= 0)
418 { 418 {
419 s += sid_32_Names[(unsigned)index].sz; 419 s += sid_32_Names[(unsigned)index].sz;
@@ -423,7 +423,7 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize)
423 if (v0 == 21 && num == 5) 423 if (v0 == 21 && num == 5)
424 { 424 {
425 UInt32 v4 = Get32(p + 8 + 4 * 4); 425 UInt32 v4 = Get32(p + 8 + 4 * 4);
426 int index = FindPairIndex(sid_21_Names, ARRAY_SIZE(sid_21_Names), v4); 426 const int index = FindPairIndex(sid_21_Names, Z7_ARRAY_SIZE(sid_21_Names), v4);
427 if (index >= 0) 427 if (index >= 0)
428 { 428 {
429 s += sid_21_Names[(unsigned)index].sz; 429 s += sid_21_Names[(unsigned)index].sz;
@@ -432,7 +432,7 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize)
432 } 432 }
433 if (v0 == 80 && num == 6) 433 if (v0 == 80 && num == 6)
434 { 434 {
435 for (unsigned i = 0; i < ARRAY_SIZE(services_to_name); i++) 435 for (unsigned i = 0; i < Z7_ARRAY_SIZE(services_to_name); i++)
436 { 436 {
437 const CServicesToName &sn = services_to_name[i]; 437 const CServicesToName &sn = services_to_name[i];
438 int j; 438 int j;
@@ -457,7 +457,7 @@ static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize)
457 } 457 }
458 for (UInt32 i = 0; i < num; i++) 458 for (UInt32 i = 0; i < num; i++)
459 { 459 {
460 s += '-'; 460 s.Add_Minus();
461 s.Add_UInt32(Get32(p + 8 + i * 4)); 461 s.Add_UInt32(Get32(p + 8 + i * 4));
462 } 462 }
463} 463}
@@ -475,10 +475,10 @@ static void ParseOwner(AString &s, const Byte *p, UInt32 size, UInt32 pos)
475 475
476static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName, UInt32 flags, UInt32 offset) 476static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName, UInt32 flags, UInt32 offset)
477{ 477{
478 UInt32 control = Get16(p + 2); 478 const UInt32 control = Get16(p + 2);
479 if ((flags & control) == 0) 479 if ((flags & control) == 0)
480 return; 480 return;
481 UInt32 pos = Get32(p + offset); 481 const UInt32 pos = Get32(p + offset);
482 s.Add_Space(); 482 s.Add_Space();
483 s += strName; 483 s += strName;
484 if (pos >= size) 484 if (pos >= size)
@@ -489,7 +489,7 @@ static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName
489 return; 489 return;
490 if (Get16(p) != 2) // revision 490 if (Get16(p) != 2) // revision
491 return; 491 return;
492 UInt32 num = Get32(p + 4); 492 const UInt32 num = Get32(p + 4);
493 s.Add_UInt32(num); 493 s.Add_UInt32(num);
494 494
495 /* 495 /*
@@ -580,26 +580,26 @@ static bool CheckSid(const Byte *data, UInt32 size, UInt32 pos) throw()
580 size -= pos; 580 size -= pos;
581 if (size < 8) 581 if (size < 8)
582 return false; 582 return false;
583 UInt32 rev = data[pos]; 583 const UInt32 rev = data[pos];
584 if (rev != 1) 584 if (rev != 1)
585 return false; 585 return false;
586 UInt32 num = data[pos + 1]; 586 const UInt32 num = data[pos + 1];
587 return (8 + num * 4 <= size); 587 return (8 + num * 4 <= size);
588} 588}
589 589
590static bool CheckAcl(const Byte *p, UInt32 size, UInt32 flags, UInt32 offset) throw() 590static bool CheckAcl(const Byte *p, UInt32 size, UInt32 flags, UInt32 offset) throw()
591{ 591{
592 UInt32 control = Get16(p + 2); 592 const UInt32 control = Get16(p + 2);
593 if ((flags & control) == 0) 593 if ((flags & control) == 0)
594 return true; 594 return true;
595 UInt32 pos = Get32(p + offset); 595 const UInt32 pos = Get32(p + offset);
596 if (pos >= size) 596 if (pos >= size)
597 return false; 597 return false;
598 p += pos; 598 p += pos;
599 size -= pos; 599 size -= pos;
600 if (size < 8) 600 if (size < 8)
601 return false; 601 return false;
602 UInt32 aclSize = Get16(p + 2); 602 const UInt32 aclSize = Get16(p + 2);
603 return (aclSize <= size); 603 return (aclSize <= size);
604} 604}
605 605
@@ -686,22 +686,22 @@ bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s)
686 686
687 if (size < 8) 687 if (size < 8)
688 return false; 688 return false;
689 UInt32 tag = Get32(data); 689 const UInt32 tag = Get32(data);
690 UInt32 len = Get16(data + 4); 690 const UInt32 len = Get16(data + 4);
691 if (len + 8 > size) 691 if (len + 8 > size)
692 return false; 692 return false;
693 if (Get16(data + 6) != 0) // padding 693 if (Get16(data + 6) != 0) // padding
694 return false; 694 return false;
695 695
696 /* 696 /*
697 #define _my_IO_REPARSE_TAG_DEDUP (0x80000013L) 697 #define my_IO_REPARSE_TAG_DEDUP (0x80000013L)
698 if (tag == _my_IO_REPARSE_TAG_DEDUP) 698 if (tag == my_IO_REPARSE_TAG_DEDUP)
699 { 699 {
700 } 700 }
701 */ 701 */
702 702
703 { 703 {
704 int index = FindPairIndex(k_ReparseTags, ARRAY_SIZE(k_ReparseTags), tag); 704 const int index = FindPairIndex(k_ReparseTags, Z7_ARRAY_SIZE(k_ReparseTags), tag);
705 if (index >= 0) 705 if (index >= 0)
706 s += k_ReparseTags[(unsigned)index].sz; 706 s += k_ReparseTags[(unsigned)index].sz;
707 else 707 else
@@ -729,7 +729,7 @@ bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s)
729 s += "..."; 729 s += "...";
730 break; 730 break;
731 } 731 }
732 unsigned b = data[i]; 732 const unsigned b = data[i];
733 s += (char)GetHex((b >> 4) & 0xF); 733 s += (char)GetHex((b >> 4) & 0xF);
734 s += (char)GetHex(b & 0xF); 734 s += (char)GetHex(b & 0xF);
735 } 735 }
diff --git a/CPP/7zip/UI/Common/PropIDUtils.h b/CPP/7zip/UI/Common/PropIDUtils.h
index 915bfc2..6df1e94 100644
--- a/CPP/7zip/UI/Common/PropIDUtils.h
+++ b/CPP/7zip/UI/Common/PropIDUtils.h
@@ -1,7 +1,7 @@
1// PropIDUtils.h 1// PropIDUtils.h
2 2
3#ifndef __PROPID_UTILS_H 3#ifndef ZIP7_INC_PROPID_UTILS_H
4#define __PROPID_UTILS_H 4#define ZIP7_INC_PROPID_UTILS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
@@ -11,7 +11,7 @@ void ConvertPropertyToString2(UString &dest, const PROPVARIANT &propVariant, PRO
11 11
12bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s); 12bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s);
13void ConvertNtSecureToString(const Byte *data, UInt32 size, AString &s); 13void ConvertNtSecureToString(const Byte *data, UInt32 size, AString &s);
14bool CheckNtSecure(const Byte *data, UInt32 size) throw();; 14bool CheckNtSecure(const Byte *data, UInt32 size) throw();
15 15
16void ConvertWinAttribToString(char *s, UInt32 wa) throw(); 16void ConvertWinAttribToString(char *s, UInt32 wa) throw();
17 17
diff --git a/CPP/7zip/UI/Common/Property.h b/CPP/7zip/UI/Common/Property.h
index 8b57a2a..0462809 100644
--- a/CPP/7zip/UI/Common/Property.h
+++ b/CPP/7zip/UI/Common/Property.h
@@ -1,7 +1,7 @@
1// Property.h 1// Property.h
2 2
3#ifndef __7Z_PROPERTY_H 3#ifndef ZIP7_INC_7Z_PROPERTY_H
4#define __7Z_PROPERTY_H 4#define ZIP7_INC_7Z_PROPERTY_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/SetProperties.cpp b/CPP/7zip/UI/Common/SetProperties.cpp
index 4b3037a..5e15d9c 100644
--- a/CPP/7zip/UI/Common/SetProperties.cpp
+++ b/CPP/7zip/UI/Common/SetProperties.cpp
@@ -18,7 +18,7 @@ using namespace NCOM;
18static void ParseNumberString(const UString &s, NCOM::CPropVariant &prop) 18static void ParseNumberString(const UString &s, NCOM::CPropVariant &prop)
19{ 19{
20 const wchar_t *end; 20 const wchar_t *end;
21 UInt64 result = ConvertStringToUInt64(s, &end); 21 const UInt64 result = ConvertStringToUInt64(s, &end);
22 if (*end != 0 || s.IsEmpty()) 22 if (*end != 0 || s.IsEmpty())
23 prop = s; 23 prop = s;
24 else if (result <= (UInt32)0xFFFFFFFF) 24 else if (result <= (UInt32)0xFFFFFFFF)
@@ -46,8 +46,9 @@ HRESULT SetProperties(IUnknown *unknown, const CObjectVector<CProperty> &propert
46{ 46{
47 if (properties.IsEmpty()) 47 if (properties.IsEmpty())
48 return S_OK; 48 return S_OK;
49 CMyComPtr<ISetProperties> setProperties; 49 Z7_DECL_CMyComPtr_QI_FROM(
50 unknown->QueryInterface(IID_ISetProperties, (void **)&setProperties); 50 ISetProperties,
51 setProperties, unknown)
51 if (!setProperties) 52 if (!setProperties)
52 return S_OK; 53 return S_OK;
53 54
@@ -64,7 +65,7 @@ HRESULT SetProperties(IUnknown *unknown, const CObjectVector<CProperty> &propert
64 { 65 {
65 if (!name.IsEmpty()) 66 if (!name.IsEmpty())
66 { 67 {
67 wchar_t c = name.Back(); 68 const wchar_t c = name.Back();
68 if (c == L'-') 69 if (c == L'-')
69 propVariant = false; 70 propVariant = false;
70 else if (c == L'+') 71 else if (c == L'+')
diff --git a/CPP/7zip/UI/Common/SetProperties.h b/CPP/7zip/UI/Common/SetProperties.h
index 892f1a2..0676c45 100644
--- a/CPP/7zip/UI/Common/SetProperties.h
+++ b/CPP/7zip/UI/Common/SetProperties.h
@@ -1,7 +1,7 @@
1// SetProperties.h 1// SetProperties.h
2 2
3#ifndef __SETPROPERTIES_H 3#ifndef ZIP7_INC_SETPROPERTIES_H
4#define __SETPROPERTIES_H 4#define ZIP7_INC_SETPROPERTIES_H
5 5
6#include "Property.h" 6#include "Property.h"
7 7
diff --git a/CPP/7zip/UI/Common/SortUtils.h b/CPP/7zip/UI/Common/SortUtils.h
index 8e42e06..07aa24d 100644
--- a/CPP/7zip/UI/Common/SortUtils.h
+++ b/CPP/7zip/UI/Common/SortUtils.h
@@ -1,7 +1,7 @@
1// SortUtils.h 1// SortUtils.h
2 2
3#ifndef __SORT_UTLS_H 3#ifndef ZIP7_INC_SORT_UTLS_H
4#define __SORT_UTLS_H 4#define ZIP7_INC_SORT_UTLS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/StdAfx.h b/CPP/7zip/UI/Common/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/UI/Common/StdAfx.h
+++ b/CPP/7zip/UI/Common/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/UI/Common/TempFiles.h b/CPP/7zip/UI/Common/TempFiles.h
index 4099e65..dd4ac20 100644
--- a/CPP/7zip/UI/Common/TempFiles.h
+++ b/CPP/7zip/UI/Common/TempFiles.h
@@ -1,7 +1,7 @@
1// TempFiles.h 1// TempFiles.h
2 2
3#ifndef __TEMP_FILES_H 3#ifndef ZIP7_INC_TEMP_FILES_H
4#define __TEMP_FILES_H 4#define ZIP7_INC_TEMP_FILES_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/Common/Update.cpp b/CPP/7zip/UI/Common/Update.cpp
index 042991d..27625ae 100644
--- a/CPP/7zip/UI/Common/Update.cpp
+++ b/CPP/7zip/UI/Common/Update.cpp
@@ -18,6 +18,8 @@
18 18
19#include "../../Common/FileStreams.h" 19#include "../../Common/FileStreams.h"
20#include "../../Common/LimitedStreams.h" 20#include "../../Common/LimitedStreams.h"
21#include "../../Common/MultiOutStream.h"
22#include "../../Common/StreamUtils.h"
21 23
22#include "../../Compress/CopyCoder.h" 24#include "../../Compress/CopyCoder.h"
23 25
@@ -71,203 +73,44 @@ HRESULT CUpdateErrorInfo::SetFromError_DWORD(const char *message, const FString
71 73
72using namespace NUpdateArchive; 74using namespace NUpdateArchive;
73 75
74class COutMultiVolStream: 76struct CMultiOutStream_Rec
75 public IOutStream,
76 public CMyUnknownImp
77{ 77{
78 unsigned _streamIndex; // required stream 78 CMultiOutStream *Spec;
79 UInt64 _offsetPos; // offset from start of _streamIndex index 79 CMyComPtr<IOutStream> Ref;
80 UInt64 _absPos;
81 UInt64 _length;
82
83 struct CAltStreamInfo
84 {
85 COutFileStream *StreamSpec;
86 CMyComPtr<IOutStream> Stream;
87 FString Name;
88 UInt64 Pos;
89 UInt64 RealSize;
90 };
91 CObjectVector<CAltStreamInfo> Streams;
92public:
93 // CMyComPtr<IArchiveUpdateCallback2> VolumeCallback;
94 CRecordVector<UInt64> Sizes;
95 FString Prefix;
96 CTempFiles *TempFiles;
97
98 void Init()
99 {
100 _streamIndex = 0;
101 _offsetPos = 0;
102 _absPos = 0;
103 _length = 0;
104 }
105
106 bool SetMTime(const CFiTime *mTime);
107 HRESULT Close();
108
109 UInt64 GetSize() const { return _length; }
110
111 MY_UNKNOWN_IMP1(IOutStream)
112
113 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
114 STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
115 STDMETHOD(SetSize)(UInt64 newSize);
116}; 80};
117 81
118// static NSynchronization::CCriticalSection g_TempPathsCS; 82struct CMultiOutStream_Bunch
119
120HRESULT COutMultiVolStream::Close()
121{
122 HRESULT res = S_OK;
123 FOR_VECTOR (i, Streams)
124 {
125 COutFileStream *s = Streams[i].StreamSpec;
126 if (s)
127 {
128 HRESULT res2 = s->Close();
129 if (res2 != S_OK)
130 res = res2;
131 }
132 }
133 return res;
134}
135
136bool COutMultiVolStream::SetMTime(const CFiTime *mTime)
137{
138 bool res = true;
139 FOR_VECTOR (i, Streams)
140 {
141 COutFileStream *s = Streams[i].StreamSpec;
142 if (s)
143 if (!s->SetMTime(mTime))
144 res = false;
145 }
146 return res;
147}
148
149STDMETHODIMP COutMultiVolStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
150{ 83{
151 if (processedSize) 84 CObjectVector<CMultiOutStream_Rec> Items;
152 *processedSize = 0; 85
153 while (size > 0) 86 HRESULT Destruct()
154 { 87 {
155 if (_streamIndex >= Streams.Size()) 88 HRESULT hres = S_OK;
89 FOR_VECTOR (i, Items)
156 { 90 {
157 CAltStreamInfo altStream; 91 CMultiOutStream_Rec &rec = Items[i];
158 92 if (rec.Ref)
159 FString name;
160 name.Add_UInt32(_streamIndex + 1);
161 while (name.Len() < 3)
162 name.InsertAtFront(FTEXT('0'));
163 name.Insert(0, Prefix);
164 altStream.StreamSpec = new COutFileStream;
165 altStream.Stream = altStream.StreamSpec;
166 if (!altStream.StreamSpec->Create(name, false))
167 return GetLastError_noZero_HRESULT();
168 { 93 {
169 // NSynchronization::CCriticalSectionLock lock(g_TempPathsCS); 94 const HRESULT hres2 = rec.Spec->Destruct();
170 TempFiles->Paths.Add(name); 95 if (hres == S_OK)
96 hres = hres2;
171 } 97 }
172
173 altStream.Pos = 0;
174 altStream.RealSize = 0;
175 altStream.Name = name;
176 Streams.Add(altStream);
177 continue;
178 }
179 CAltStreamInfo &altStream = Streams[_streamIndex];
180
181 unsigned index = _streamIndex;
182 if (index >= Sizes.Size())
183 index = Sizes.Size() - 1;
184 UInt64 volSize = Sizes[index];
185
186 if (_offsetPos >= volSize)
187 {
188 _offsetPos -= volSize;
189 _streamIndex++;
190 continue;
191 }
192 if (_offsetPos != altStream.Pos)
193 {
194 // CMyComPtr<IOutStream> outStream;
195 // RINOK(altStream.Stream.QueryInterface(IID_IOutStream, &outStream));
196 RINOK(altStream.Stream->Seek((Int64)_offsetPos, STREAM_SEEK_SET, NULL));
197 altStream.Pos = _offsetPos;
198 } 98 }
199 99 Items.Clear();
200 UInt32 curSize = (UInt32)MyMin((UInt64)size, volSize - altStream.Pos); 100 return hres;
201 UInt32 realProcessed;
202 RINOK(altStream.Stream->Write(data, curSize, &realProcessed));
203 data = (const void *)((const Byte *)data + realProcessed);
204 size -= realProcessed;
205 altStream.Pos += realProcessed;
206 _offsetPos += realProcessed;
207 _absPos += realProcessed;
208 if (_absPos > _length)
209 _length = _absPos;
210 if (_offsetPos > altStream.RealSize)
211 altStream.RealSize = _offsetPos;
212 if (processedSize)
213 *processedSize += realProcessed;
214 if (altStream.Pos == volSize)
215 {
216 _streamIndex++;
217 _offsetPos = 0;
218 }
219 if (realProcessed == 0 && curSize != 0)
220 return E_FAIL;
221 break;
222 }
223 return S_OK;
224}
225
226STDMETHODIMP COutMultiVolStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
227{
228 if (seekOrigin >= 3)
229 return STG_E_INVALIDFUNCTION;
230 switch (seekOrigin)
231 {
232 case STREAM_SEEK_SET: _absPos = (UInt64)offset; break;
233 case STREAM_SEEK_CUR: _absPos = (UInt64)((Int64)_absPos + offset); break;
234 case STREAM_SEEK_END: _absPos = (UInt64)((Int64)_length + offset); break;
235 } 101 }
236 _offsetPos = _absPos;
237 if (newPosition)
238 *newPosition = _absPos;
239 _streamIndex = 0;
240 return S_OK;
241}
242 102
243STDMETHODIMP COutMultiVolStream::SetSize(UInt64 newSize) 103 void DisableDeletion()
244{
245 unsigned i = 0;
246 while (i < Streams.Size())
247 { 104 {
248 CAltStreamInfo &altStream = Streams[i++]; 105 FOR_VECTOR (i, Items)
249 if ((UInt64)newSize < altStream.RealSize)
250 { 106 {
251 RINOK(altStream.Stream->SetSize(newSize)); 107 CMultiOutStream_Rec &rec = Items[i];
252 altStream.RealSize = newSize; 108 if (rec.Ref)
253 break; 109 rec.Spec->NeedDelete = false;
254 } 110 }
255 newSize -= altStream.RealSize;
256 } 111 }
257 while (i < Streams.Size()) 112};
258 { 113
259 {
260 CAltStreamInfo &altStream = Streams.Back();
261 altStream.Stream.Release();
262 DeleteFileAlways(altStream.Name);
263 }
264 Streams.DeleteBack();
265 }
266 _offsetPos = _absPos;
267 _streamIndex = 0;
268 _length = newSize;
269 return S_OK;
270}
271 114
272void CArchivePath::ParseFromPath(const UString &path, EArcNameMode mode) 115void CArchivePath::ParseFromPath(const UString &path, EArcNameMode mode)
273{ 116{
@@ -305,7 +148,7 @@ UString CArchivePath::GetFinalPath() const
305 UString path = GetPathWithoutExt(); 148 UString path = GetPathWithoutExt();
306 if (!BaseExtension.IsEmpty()) 149 if (!BaseExtension.IsEmpty())
307 { 150 {
308 path += '.'; 151 path.Add_Dot();
309 path += BaseExtension; 152 path += BaseExtension;
310 } 153 }
311 return path; 154 return path;
@@ -317,7 +160,7 @@ UString CArchivePath::GetFinalVolPath() const
317 // if BaseExtension is empty, we must ignore VolExtension also. 160 // if BaseExtension is empty, we must ignore VolExtension also.
318 if (!BaseExtension.IsEmpty()) 161 if (!BaseExtension.IsEmpty())
319 { 162 {
320 path += '.'; 163 path.Add_Dot();
321 path += VolExtension; 164 path += VolExtension;
322 } 165 }
323 return path; 166 return path;
@@ -329,7 +172,7 @@ FString CArchivePath::GetTempPath() const
329 path += us2fs(Name); 172 path += us2fs(Name);
330 if (!BaseExtension.IsEmpty()) 173 if (!BaseExtension.IsEmpty())
331 { 174 {
332 path += '.'; 175 path.Add_Dot();
333 path += us2fs(BaseExtension); 176 path += us2fs(BaseExtension);
334 } 177 }
335 path += ".tmp"; 178 path += ".tmp";
@@ -403,7 +246,7 @@ bool CUpdateOptions::SetArcPath(const CCodecs *codecs, const UString &arcPath)
403} 246}
404 247
405 248
406struct CUpdateProduceCallbackImp: public IUpdateProduceCallback 249struct CUpdateProduceCallbackImp Z7_final: public IUpdateProduceCallback
407{ 250{
408 const CObjectVector<CArcItem> *_arcItems; 251 const CObjectVector<CArcItem> *_arcItems;
409 CDirItemsStat *_stat; 252 CDirItemsStat *_stat;
@@ -417,7 +260,7 @@ struct CUpdateProduceCallbackImp: public IUpdateProduceCallback
417 _stat(stat), 260 _stat(stat),
418 _callback(callback) {} 261 _callback(callback) {}
419 262
420 virtual HRESULT ShowDeleteFile(unsigned arcIndex); 263 virtual HRESULT ShowDeleteFile(unsigned arcIndex) Z7_override;
421}; 264};
422 265
423 266
@@ -499,6 +342,8 @@ bool CRenamePair::GetNewPath(bool isFolder, const UString &src, UString &dest) c
499int FindAltStreamColon_in_Path(const wchar_t *path); 342int FindAltStreamColon_in_Path(const wchar_t *path);
500#endif 343#endif
501 344
345
346
502static HRESULT Compress( 347static HRESULT Compress(
503 const CUpdateOptions &options, 348 const CUpdateOptions &options,
504 bool isUpdatingItself, 349 bool isUpdatingItself,
@@ -511,6 +356,7 @@ static HRESULT Compress(
511 const CDirItems &dirItems, 356 const CDirItems &dirItems,
512 const CDirItem *parentDirItem, 357 const CDirItem *parentDirItem,
513 CTempFiles &tempFiles, 358 CTempFiles &tempFiles,
359 CMultiOutStream_Bunch &multiStreams,
514 CUpdateErrorInfo &errorInfo, 360 CUpdateErrorInfo &errorInfo,
515 IUpdateCallbackUI *callback, 361 IUpdateCallbackUI *callback,
516 CFinishArchiveStat &st) 362 CFinishArchiveStat &st)
@@ -530,15 +376,15 @@ static HRESULT Compress(
530 } 376 }
531 else 377 else
532 { 378 {
533 RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive)); 379 RINOK(codecs->CreateOutArchive((unsigned)formatIndex, outArchive))
534 380
535 #ifdef EXTERNAL_CODECS 381 #ifdef Z7_EXTERNAL_CODECS
536 { 382 {
537 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo; 383 CMyComPtr<ISetCompressCodecsInfo> setCompressCodecsInfo;
538 outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); 384 outArchive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo);
539 if (setCompressCodecsInfo) 385 if (setCompressCodecsInfo)
540 { 386 {
541 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs)); 387 RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecs))
542 } 388 }
543 } 389 }
544 #endif 390 #endif
@@ -548,7 +394,7 @@ static HRESULT Compress(
548 throw kUpdateIsNotSupoorted; 394 throw kUpdateIsNotSupoorted;
549 395
550 // we need to set properties to get fileTimeType. 396 // we need to set properties to get fileTimeType.
551 RINOK(SetProperties(outArchive, options.MethodMode.Properties)); 397 RINOK(SetProperties(outArchive, options.MethodMode.Properties))
552 398
553 NFileTimeType::EEnum fileTimeType; 399 NFileTimeType::EEnum fileTimeType;
554 { 400 {
@@ -580,7 +426,7 @@ static HRESULT Compress(
580 */ 426 */
581 427
582 UInt32 value; 428 UInt32 value;
583 RINOK(outArchive->GetFileTimeType(&value)); 429 RINOK(outArchive->GetFileTimeType(&value))
584 430
585 // we support any future fileType here. 431 // we support any future fileType here.
586 fileTimeType = (NFileTimeType::EEnum)value; 432 fileTimeType = (NFileTimeType::EEnum)value;
@@ -676,7 +522,7 @@ static HRESULT Compress(
676 if (needRename) 522 if (needRename)
677 { 523 {
678 up2.NewProps = true; 524 up2.NewProps = true;
679 RINOK(arc->IsItem_Anti(i, up2.IsAnti)); 525 RINOK(arc->IsItem_Anti(i, up2.IsAnti))
680 up2.NewNameIndex = (int)newNames.Add(dest); 526 up2.NewNameIndex = (int)newNames.Add(dest);
681 } 527 }
682 updatePairs2.Add(up2); 528 updatePairs2.Add(up2);
@@ -768,7 +614,7 @@ static HRESULT Compress(
768 } 614 }
769 } 615 }
770 } 616 }
771 RINOK(callback->SetNumItems(stat2)); 617 RINOK(callback->SetNumItems(stat2))
772 } 618 }
773 619
774 CArchiveUpdateCallback *updateCallbackSpec = new CArchiveUpdateCallback; 620 CArchiveUpdateCallback *updateCallbackSpec = new CArchiveUpdateCallback;
@@ -828,7 +674,7 @@ static HRESULT Compress(
828 674
829 COutFileStream *outStreamSpec = NULL; 675 COutFileStream *outStreamSpec = NULL;
830 CStdOutFileStream *stdOutFileStreamSpec = NULL; 676 CStdOutFileStream *stdOutFileStreamSpec = NULL;
831 COutMultiVolStream *volStreamSpec = NULL; 677 CMultiOutStream *volStreamSpec = NULL;
832 678
833 if (options.VolumesSizes.Size() == 0) 679 if (options.VolumesSizes.Size() == 0)
834 { 680 {
@@ -881,14 +727,17 @@ static HRESULT Compress(
881 if (arc && arc->GetGlobalOffset() > 0) 727 if (arc && arc->GetGlobalOffset() > 0)
882 return E_NOTIMPL; 728 return E_NOTIMPL;
883 729
884 volStreamSpec = new COutMultiVolStream; 730 volStreamSpec = new CMultiOutStream();
885 outSeekStream = volStreamSpec; 731 outSeekStream = volStreamSpec;
886 outStream = outSeekStream; 732 outStream = outSeekStream;
887 volStreamSpec->Sizes = options.VolumesSizes;
888 volStreamSpec->Prefix = us2fs(archivePath.GetFinalVolPath()); 733 volStreamSpec->Prefix = us2fs(archivePath.GetFinalVolPath());
889 volStreamSpec->Prefix += '.'; 734 volStreamSpec->Prefix.Add_Dot();
890 volStreamSpec->TempFiles = &tempFiles; 735 volStreamSpec->Init(options.VolumesSizes);
891 volStreamSpec->Init(); 736 {
737 CMultiOutStream_Rec &rec = multiStreams.Items.AddNew();
738 rec.Spec = volStreamSpec;
739 rec.Ref = rec.Spec;
740 }
892 741
893 /* 742 /*
894 updateCallbackSpec->VolumesSizes = volumesSizes; 743 updateCallbackSpec->VolumesSizes = volumesSizes;
@@ -913,22 +762,22 @@ static HRESULT Compress(
913 { 762 {
914 outStreamSpec2 = new COutFileStream; 763 outStreamSpec2 = new COutFileStream;
915 sfxOutStream = outStreamSpec2; 764 sfxOutStream = outStreamSpec2;
916 FString realPath = us2fs(archivePath.GetFinalPath()); 765 const FString realPath = us2fs(archivePath.GetFinalPath());
917 if (!outStreamSpec2->Create(realPath, false)) 766 if (!outStreamSpec2->Create(realPath, false))
918 return errorInfo.SetFromLastError("cannot open file", realPath); 767 return errorInfo.SetFromLastError("cannot open file", realPath);
919 } 768 }
920 769
921 { 770 {
922 UInt64 sfxSize; 771 UInt64 sfxSize;
923 RINOK(sfxStreamSpec->GetSize(&sfxSize)); 772 RINOK(sfxStreamSpec->GetSize(&sfxSize))
924 RINOK(callback->WriteSfx(fs2us(options.SfxModule), sfxSize)); 773 RINOK(callback->WriteSfx(fs2us(options.SfxModule), sfxSize))
925 } 774 }
926 775
927 RINOK(NCompress::CopyStream(sfxStream, sfxOutStream, NULL)); 776 RINOK(NCompress::CopyStream(sfxStream, sfxOutStream, NULL))
928 777
929 if (outStreamSpec2) 778 if (outStreamSpec2)
930 { 779 {
931 RINOK(outStreamSpec2->Close()); 780 RINOK(outStreamSpec2->Close())
932 } 781 }
933 } 782 }
934 783
@@ -939,8 +788,8 @@ static HRESULT Compress(
939 else 788 else
940 { 789 {
941 // Int64 globalOffset = arc->GetGlobalOffset(); 790 // Int64 globalOffset = arc->GetGlobalOffset();
942 RINOK(arc->InStream->Seek(0, STREAM_SEEK_SET, NULL)); 791 RINOK(InStream_SeekToBegin(arc->InStream))
943 RINOK(NCompress::CopyStream_ExactSize(arc->InStream, outStream, arc->ArcStreamOffset, NULL)); 792 RINOK(NCompress::CopyStream_ExactSize(arc->InStream, outStream, arc->ArcStreamOffset, NULL))
944 if (options.StdOutMode) 793 if (options.StdOutMode)
945 tailStream = outStream; 794 tailStream = outStream;
946 else 795 else
@@ -953,10 +802,57 @@ static HRESULT Compress(
953 } 802 }
954 } 803 }
955 804
805 CFiTime ft;
806 FiTime_Clear(ft);
807 bool ft_Defined = false;
808 {
809 FOR_VECTOR (i, updatePairs2)
810 {
811 const CUpdatePair2 &pair2 = updatePairs2[i];
812 CFiTime ft2;
813 FiTime_Clear(ft2);
814 bool ft2_Defined = false;
815 /* we use full precision of dirItem, if dirItem is defined
816 and (dirItem will be used or dirItem is sameTime in dir and arc */
817 if (pair2.DirIndex >= 0 &&
818 (pair2.NewProps || pair2.IsSameTime))
819 {
820 ft2 = dirItems.Items[(unsigned)pair2.DirIndex].MTime;
821 ft2_Defined = true;
822 }
823 else if (pair2.UseArcProps && pair2.ArcIndex >= 0)
824 {
825 const CArcItem &arcItem = arcItems[(unsigned)pair2.ArcIndex];
826 if (arcItem.MTime.Def)
827 {
828 arcItem.MTime.Write_To_FiTime(ft2);
829 ft2_Defined = true;
830 }
831 }
832 if (ft2_Defined)
833 {
834 if (!ft_Defined || Compare_FiTime(&ft, &ft2) < 0)
835 {
836 ft = ft2;
837 ft_Defined = true;
838 }
839 }
840 }
841 /*
842 if (fileTimeType != NFileTimeType::kNotDefined)
843 FiTime_Normalize_With_Prec(ft, fileTimeType);
844 */
845 }
846
847 if (volStreamSpec && options.SetArcMTime && ft_Defined)
848 {
849 volStreamSpec->MTime = ft;
850 volStreamSpec->MTime_Defined = true;
851 }
956 852
957 HRESULT result = outArchive->UpdateItems(tailStream, updatePairs2.Size(), updateCallback); 853 HRESULT result = outArchive->UpdateItems(tailStream, updatePairs2.Size(), updateCallback);
958 // callback->Finalize(); 854 // callback->Finalize();
959 RINOK(result); 855 RINOK(result)
960 856
961 if (!updateCallbackSpec->AreAllFilesClosed()) 857 if (!updateCallbackSpec->AreAllFilesClosed())
962 { 858 {
@@ -967,10 +863,6 @@ static HRESULT Compress(
967 863
968 if (options.SetArcMTime) 864 if (options.SetArcMTime)
969 { 865 {
970 CFiTime ft;
971 FiTime_Clear(ft);
972 bool isDefined = false;
973
974 // bool needNormalizeAfterStream; 866 // bool needNormalizeAfterStream;
975 // needParse; 867 // needParse;
976 /* 868 /*
@@ -990,40 +882,9 @@ static HRESULT Compress(
990 // CArcTime at = StreamCallback_ArcMTime; 882 // CArcTime at = StreamCallback_ArcMTime;
991 // updateCallbackSpec->StreamCallback_ArcMTime.Write_To_FiTime(ft); 883 // updateCallbackSpec->StreamCallback_ArcMTime.Write_To_FiTime(ft);
992 // we must normalize with precision from archive; 884 // we must normalize with precision from archive;
993 ft = updateCallbackSpec->LatestMTime; 885 if (!ft_Defined || Compare_FiTime(&ft, &updateCallbackSpec->LatestMTime) < 0)
994 isDefined = true; 886 ft = updateCallbackSpec->LatestMTime;
995 } 887 ft_Defined = true;
996
997 FOR_VECTOR (i, updatePairs2)
998 {
999 const CUpdatePair2 &pair2 = updatePairs2[i];
1000 CFiTime ft2;
1001 bool ft2_Defined = false;
1002 /* we use full precision of dirItem, if dirItem is defined
1003 and (dirItem will be used or dirItem is sameTime in dir and arc */
1004 if (pair2.DirIndex >= 0 &&
1005 (pair2.NewProps || pair2.IsSameTime))
1006 {
1007 ft2 = dirItems.Items[(unsigned)pair2.DirIndex].MTime;
1008 ft2_Defined = true;
1009 }
1010 else if (pair2.UseArcProps && pair2.ArcIndex >= 0)
1011 {
1012 const CArcItem &arcItem = arcItems[(unsigned)pair2.ArcIndex];
1013 if (arcItem.MTime.Def)
1014 {
1015 arcItem.MTime.Write_To_FiTime(ft2);
1016 ft2_Defined = true;
1017 }
1018 }
1019 if (ft2_Defined)
1020 {
1021 if (Compare_FiTime(&ft, &ft2) < 0)
1022 {
1023 ft = ft2;
1024 isDefined = true;
1025 }
1026 }
1027 } 888 }
1028 /* 889 /*
1029 if (fileTimeType != NFileTimeType::kNotDefined) 890 if (fileTimeType != NFileTimeType::kNotDefined)
@@ -1031,12 +892,14 @@ static HRESULT Compress(
1031 */ 892 */
1032 } 893 }
1033 // if (ft.dwLowDateTime != 0 || ft.dwHighDateTime != 0) 894 // if (ft.dwLowDateTime != 0 || ft.dwHighDateTime != 0)
1034 if (isDefined) 895 if (ft_Defined)
1035 { 896 {
897 // we ignore set time errors here.
898 // note that user could move some finished volumes to another folder.
1036 if (outStreamSpec) 899 if (outStreamSpec)
1037 outStreamSpec->SetMTime(&ft); 900 outStreamSpec->SetMTime(&ft);
1038 else if (volStreamSpec) 901 else if (volStreamSpec)
1039 volStreamSpec->SetMTime(&ft); 902 volStreamSpec->SetMTime_Final(ft);
1040 } 903 }
1041 } 904 }
1042 905
@@ -1056,7 +919,10 @@ static HRESULT Compress(
1056 if (outStreamSpec) 919 if (outStreamSpec)
1057 result = outStreamSpec->Close(); 920 result = outStreamSpec->Close();
1058 else if (volStreamSpec) 921 else if (volStreamSpec)
1059 result = volStreamSpec->Close(); 922 {
923 result = volStreamSpec->FinalFlush_and_CloseFiles(st.NumVolumes);
924 st.IsMultiVolMode = true;
925 }
1060 926
1061 RINOK(result) 927 RINOK(result)
1062 928
@@ -1121,7 +987,7 @@ static HRESULT EnumerateInArchiveItems(
1121 arcItems.Clear(); 987 arcItems.Clear();
1122 UInt32 numItems; 988 UInt32 numItems;
1123 IInArchive *archive = arc.Archive; 989 IInArchive *archive = arc.Archive;
1124 RINOK(archive->GetNumberOfItems(&numItems)); 990 RINOK(archive->GetNumberOfItems(&numItems))
1125 arcItems.ClearAndReserve(numItems); 991 arcItems.ClearAndReserve(numItems);
1126 992
1127 CReadArcItem item; 993 CReadArcItem item;
@@ -1132,7 +998,7 @@ static HRESULT EnumerateInArchiveItems(
1132 { 998 {
1133 CArcItem ai; 999 CArcItem ai;
1134 1000
1135 RINOK(arc.GetItem(i, item)); 1001 RINOK(arc.GetItem(i, item))
1136 ai.Name = item.Path; 1002 ai.Name = item.Path;
1137 ai.IsDir = item.IsDir; 1003 ai.IsDir = item.IsDir;
1138 ai.IsAltStream = 1004 ai.IsAltStream =
@@ -1152,8 +1018,8 @@ static HRESULT EnumerateInArchiveItems(
1152 ai.Censored = Censor_CheckPath(censor, item); 1018 ai.Censored = Censor_CheckPath(censor, item);
1153 1019
1154 // ai.MTime will be set to archive MTime, if not present in archive item 1020 // ai.MTime will be set to archive MTime, if not present in archive item
1155 RINOK(arc.GetItem_MTime(i, ai.MTime)); 1021 RINOK(arc.GetItem_MTime(i, ai.MTime))
1156 RINOK(arc.GetItem_Size(i, ai.Size, ai.Size_Defined)); 1022 RINOK(arc.GetItem_Size(i, ai.Size, ai.Size_Defined))
1157 1023
1158 ai.IndexInServer = i; 1024 ai.IndexInServer = i;
1159 arcItems.AddInReserved(ai); 1025 arcItems.AddInReserved(ai);
@@ -1163,10 +1029,73 @@ static HRESULT EnumerateInArchiveItems(
1163 1029
1164#if defined(_WIN32) && !defined(UNDER_CE) 1030#if defined(_WIN32) && !defined(UNDER_CE)
1165 1031
1032#if defined(__MINGW32__) || defined(__MINGW64__)
1033#include <mapi.h>
1034#else
1166#include <MAPI.h> 1035#include <MAPI.h>
1167
1168#endif 1036#endif
1169 1037
1038extern "C" {
1039
1040#ifdef MAPI_FORCE_UNICODE
1041
1042#define Z7_WIN_LPMAPISENDMAILW LPMAPISENDMAILW
1043#define Z7_WIN_MapiFileDescW MapiFileDescW
1044#define Z7_WIN_MapiMessageW MapiMessageW
1045#define Z7_WIN_MapiRecipDescW MapiRecipDescW
1046
1047#else
1048
1049typedef struct
1050{
1051 ULONG ulReserved;
1052 ULONG ulRecipClass;
1053 PWSTR lpszName;
1054 PWSTR lpszAddress;
1055 ULONG ulEIDSize;
1056 PVOID lpEntryID;
1057} Z7_WIN_MapiRecipDescW, *Z7_WIN_lpMapiRecipDescW;
1058
1059typedef struct
1060{
1061 ULONG ulReserved;
1062 ULONG flFlags;
1063 ULONG nPosition;
1064 PWSTR lpszPathName;
1065 PWSTR lpszFileName;
1066 PVOID lpFileType;
1067} Z7_WIN_MapiFileDescW, *Z7_WIN_lpMapiFileDescW;
1068
1069typedef struct
1070{
1071 ULONG ulReserved;
1072 PWSTR lpszSubject;
1073 PWSTR lpszNoteText;
1074 PWSTR lpszMessageType;
1075 PWSTR lpszDateReceived;
1076 PWSTR lpszConversationID;
1077 FLAGS flFlags;
1078 Z7_WIN_lpMapiRecipDescW lpOriginator;
1079 ULONG nRecipCount;
1080 Z7_WIN_lpMapiRecipDescW lpRecips;
1081 ULONG nFileCount;
1082 Z7_WIN_lpMapiFileDescW lpFiles;
1083} Z7_WIN_MapiMessageW, *Z7_WIN_lpMapiMessageW;
1084
1085typedef ULONG (FAR PASCAL Z7_WIN_MAPISENDMAILW)(
1086 LHANDLE lhSession,
1087 ULONG_PTR ulUIParam,
1088 Z7_WIN_lpMapiMessageW lpMessage,
1089 FLAGS flFlags,
1090 ULONG ulReserved
1091);
1092typedef Z7_WIN_MAPISENDMAILW FAR *Z7_WIN_LPMAPISENDMAILW;
1093
1094#endif // MAPI_FORCE_UNICODE
1095}
1096#endif // _WIN32
1097
1098
1170HRESULT UpdateArchive( 1099HRESULT UpdateArchive(
1171 CCodecs *codecs, 1100 CCodecs *codecs,
1172 const CObjectVector<COpenType> &types, 1101 const CObjectVector<COpenType> &types,
@@ -1253,8 +1182,7 @@ HRESULT UpdateArchive(
1253 if (!options.VolumesSizes.IsEmpty()) 1182 if (!options.VolumesSizes.IsEmpty())
1254 { 1183 {
1255 arcPath = options.ArchivePath.GetFinalVolPath(); 1184 arcPath = options.ArchivePath.GetFinalVolPath();
1256 arcPath += '.'; 1185 arcPath += ".001";
1257 arcPath += "001";
1258 } 1186 }
1259 1187
1260 if (cmdArcPath2.IsEmpty()) 1188 if (cmdArcPath2.IsEmpty())
@@ -1268,7 +1196,7 @@ HRESULT UpdateArchive(
1268 if (!fi.Find_FollowLink(us2fs(arcPath))) 1196 if (!fi.Find_FollowLink(us2fs(arcPath)))
1269 { 1197 {
1270 if (renameMode) 1198 if (renameMode)
1271 throw "can't find archive";; 1199 throw "can't find archive";
1272 if (options.MethodMode.Type.FormatIndex < 0) 1200 if (options.MethodMode.Type.FormatIndex < 0)
1273 { 1201 {
1274 if (!options.SetArcPath(codecs, cmdArcPath2)) 1202 if (!options.SetArcPath(codecs, cmdArcPath2))
@@ -1319,7 +1247,7 @@ HRESULT UpdateArchive(
1319 1247
1320 CIntVector excl; 1248 CIntVector excl;
1321 COpenOptions op; 1249 COpenOptions op;
1322 #ifndef _SFX 1250 #ifndef Z7_SFX
1323 op.props = &options.MethodMode.Properties; 1251 op.props = &options.MethodMode.Properties;
1324 #endif 1252 #endif
1325 op.codecs = codecs; 1253 op.codecs = codecs;
@@ -1329,7 +1257,7 @@ HRESULT UpdateArchive(
1329 op.stream = NULL; 1257 op.stream = NULL;
1330 op.filePath = arcPath; 1258 op.filePath = arcPath;
1331 1259
1332 RINOK(callback->StartOpenArchive(arcPath)); 1260 RINOK(callback->StartOpenArchive(arcPath))
1333 1261
1334 HRESULT result = arcLink.Open_Strict(op, openCallback); 1262 HRESULT result = arcLink.Open_Strict(op, openCallback);
1335 1263
@@ -1341,8 +1269,8 @@ HRESULT UpdateArchive(
1341 if (result == S_FALSE) 1269 if (result == S_FALSE)
1342 return E_FAIL; 1270 return E_FAIL;
1343 */ 1271 */
1344 RINOK(res2); 1272 RINOK(res2)
1345 RINOK(result); 1273 RINOK(result)
1346 1274
1347 if (arcLink.VolumePaths.Size() > 1) 1275 if (arcLink.VolumePaths.Size() > 1)
1348 { 1276 {
@@ -1422,7 +1350,7 @@ HRESULT UpdateArchive(
1422 1350
1423 if (needScanning) 1351 if (needScanning)
1424 { 1352 {
1425 RINOK(callback->StartScanning()); 1353 RINOK(callback->StartScanning())
1426 1354
1427 dirItems.SymLinks = options.SymLinks.Val; 1355 dirItems.SymLinks = options.SymLinks.Val;
1428 1356
@@ -1452,7 +1380,7 @@ HRESULT UpdateArchive(
1452 return res; 1380 return res;
1453 } 1381 }
1454 1382
1455 RINOK(callback->FinishScanning(dirItems.Stat)); 1383 RINOK(callback->FinishScanning(dirItems.Stat))
1456 1384
1457 // 22.00: we don't need parent folder, if absolute path mode 1385 // 22.00: we don't need parent folder, if absolute path mode
1458 if (options.PathMode != NWildcard::k_AbsPath) 1386 if (options.PathMode != NWildcard::k_AbsPath)
@@ -1460,7 +1388,7 @@ HRESULT UpdateArchive(
1460 { 1388 {
1461 NFind::CFileInfo fi; 1389 NFind::CFileInfo fi;
1462 FString prefix = us2fs(censor.Pairs[0].Prefix); 1390 FString prefix = us2fs(censor.Pairs[0].Prefix);
1463 prefix += '.'; 1391 prefix.Add_Dot();
1464 // UString prefix = censor.Pairs[0].Prefix; 1392 // UString prefix = censor.Pairs[0].Prefix;
1465 /* 1393 /*
1466 if (prefix.Back() == WCHAR_PATH_SEPARATOR) 1394 if (prefix.Back() == WCHAR_PATH_SEPARATOR)
@@ -1576,7 +1504,7 @@ HRESULT UpdateArchive(
1576 { 1504 {
1577 RINOK(EnumerateInArchiveItems( 1505 RINOK(EnumerateInArchiveItems(
1578 // options.StoreAltStreams, 1506 // options.StoreAltStreams,
1579 censor, arcLink.Arcs.Back(), arcItems)); 1507 censor, arcLink.Arcs.Back(), arcItems))
1580 } 1508 }
1581 1509
1582 /* 1510 /*
@@ -1595,8 +1523,10 @@ HRESULT UpdateArchive(
1595 processedItems[i] = 0; 1523 processedItems[i] = 0;
1596 } 1524 }
1597 1525
1526 CMultiOutStream_Bunch multiStreams;
1527
1598 /* 1528 /*
1599 #ifndef _NO_CRYPTO 1529 #ifndef Z7_NO_CRYPTO
1600 if (arcLink.PasswordWasAsked) 1530 if (arcLink.PasswordWasAsked)
1601 { 1531 {
1602 // We set password, if open have requested password 1532 // We set password, if open have requested password
@@ -1640,18 +1570,22 @@ HRESULT UpdateArchive(
1640 parentDirItem_Ptr, 1570 parentDirItem_Ptr,
1641 1571
1642 tempFiles, 1572 tempFiles,
1643 errorInfo, callback, st)); 1573 multiStreams,
1574 errorInfo, callback, st))
1644 1575
1645 RINOK(callback->FinishArchive(st)); 1576 RINOK(callback->FinishArchive(st))
1646 } 1577 }
1647 1578
1648 1579
1649 if (thereIsInArchive) 1580 if (thereIsInArchive)
1650 { 1581 {
1651 RINOK(arcLink.Close()); 1582 RINOK(arcLink.Close())
1652 arcLink.Release(); 1583 arcLink.Release();
1653 } 1584 }
1654 1585
1586 multiStreams.DisableDeletion();
1587 RINOK(multiStreams.Destruct())
1588
1655 tempFiles.Paths.Clear(); 1589 tempFiles.Paths.Clear();
1656 if (createTempFile) 1590 if (createTempFile)
1657 { 1591 {
@@ -1702,6 +1636,19 @@ HRESULT UpdateArchive(
1702 return errorInfo.Get_HRESULT_Error(); 1636 return errorInfo.Get_HRESULT_Error();
1703 } 1637 }
1704 1638
1639 FStringVector fullPaths;
1640 unsigned i;
1641
1642 for (i = 0; i < options.Commands.Size(); i++)
1643 {
1644 CArchivePath &ap = options.Commands[i].ArchivePath;
1645 const FString finalPath = us2fs(ap.GetFinalPath());
1646 FString arcPath2;
1647 if (!MyGetFullPathName(finalPath, arcPath2))
1648 return errorInfo.SetFromLastError("GetFullPathName error", finalPath);
1649 fullPaths.Add(arcPath2);
1650 }
1651
1705 /* 1652 /*
1706 LPMAPISENDDOCUMENTS fnSend = (LPMAPISENDDOCUMENTS)mapiLib.GetProc("MAPISendDocuments"); 1653 LPMAPISENDDOCUMENTS fnSend = (LPMAPISENDDOCUMENTS)mapiLib.GetProc("MAPISendDocuments");
1707 if (fnSend == 0) 1654 if (fnSend == 0)
@@ -1710,25 +1657,70 @@ HRESULT UpdateArchive(
1710 return errorInfo.Get_HRESULT_Error(); 1657 return errorInfo.Get_HRESULT_Error();
1711 } 1658 }
1712 */ 1659 */
1660 const
1661 Z7_WIN_LPMAPISENDMAILW sendMailW = Z7_GET_PROC_ADDRESS(
1662 Z7_WIN_LPMAPISENDMAILW, mapiLib.Get_HMODULE(),
1663 "MAPISendMailW");
1664 if (sendMailW)
1665 {
1666
1667 CCurrentDirRestorer curDirRestorer;
1668
1669 UStringVector paths;
1670 UStringVector names;
1713 1671
1714 LPMAPISENDMAIL sendMail = (LPMAPISENDMAIL)(void *)mapiLib.GetProc("MAPISendMail"); 1672 for (i = 0; i < fullPaths.Size(); i++)
1715 if (sendMail == 0)
1716 { 1673 {
1717 errorInfo.SetFromLastError("7-Zip cannot find MAPISendMail function"); 1674 const UString arcPath2 = fs2us(fullPaths[i]);
1718 return errorInfo.Get_HRESULT_Error();; 1675 const UString fileName = ExtractFileNameFromPath(arcPath2);
1676 paths.Add(arcPath2);
1677 names.Add(fileName);
1678 // Warning!!! MAPISendDocuments function changes Current directory
1679 // fnSend(0, ";", (LPSTR)(LPCSTR)path, (LPSTR)(LPCSTR)name, 0);
1719 } 1680 }
1720 1681
1721 FStringVector fullPaths; 1682 CRecordVector<Z7_WIN_MapiFileDescW> files;
1722 unsigned i; 1683 files.ClearAndSetSize(paths.Size());
1723 1684
1724 for (i = 0; i < options.Commands.Size(); i++) 1685 for (i = 0; i < paths.Size(); i++)
1725 { 1686 {
1726 CArchivePath &ap = options.Commands[i].ArchivePath; 1687 Z7_WIN_MapiFileDescW &f = files[i];
1727 FString finalPath = us2fs(ap.GetFinalPath()); 1688 memset(&f, 0, sizeof(f));
1728 FString arcPath2; 1689 f.nPosition = 0xFFFFFFFF;
1729 if (!MyGetFullPathName(finalPath, arcPath2)) 1690 f.lpszPathName = paths[i].Ptr_non_const();
1730 return errorInfo.SetFromLastError("GetFullPathName error", finalPath); 1691 f.lpszFileName = names[i].Ptr_non_const();
1731 fullPaths.Add(arcPath2); 1692 }
1693
1694 {
1695 Z7_WIN_MapiMessageW m;
1696 memset(&m, 0, sizeof(m));
1697 m.nFileCount = files.Size();
1698 m.lpFiles = &files.Front();
1699
1700 const UString addr (options.EMailAddress);
1701 Z7_WIN_MapiRecipDescW rec;
1702 if (!addr.IsEmpty())
1703 {
1704 memset(&rec, 0, sizeof(rec));
1705 rec.ulRecipClass = MAPI_TO;
1706 rec.lpszAddress = addr.Ptr_non_const();
1707 m.nRecipCount = 1;
1708 m.lpRecips = &rec;
1709 }
1710
1711 sendMailW((LHANDLE)0, 0, &m, MAPI_DIALOG, 0);
1712 }
1713 }
1714 else
1715 {
1716 const
1717 LPMAPISENDMAIL sendMail = Z7_GET_PROC_ADDRESS(
1718 LPMAPISENDMAIL, mapiLib.Get_HMODULE(),
1719 "MAPISendMail");
1720 if (!sendMail)
1721 {
1722 errorInfo.SetFromLastError("7-Zip cannot find MAPISendMail function");
1723 return errorInfo.Get_HRESULT_Error();
1732 } 1724 }
1733 1725
1734 CCurrentDirRestorer curDirRestorer; 1726 CCurrentDirRestorer curDirRestorer;
@@ -1779,6 +1771,7 @@ HRESULT UpdateArchive(
1779 1771
1780 sendMail((LHANDLE)0, 0, &m, MAPI_DIALOG, 0); 1772 sendMail((LHANDLE)0, 0, &m, MAPI_DIALOG, 0);
1781 } 1773 }
1774 }
1782 } 1775 }
1783 1776
1784 #endif 1777 #endif
@@ -1827,7 +1820,7 @@ HRESULT UpdateArchive(
1827 && Compare_FiTime(&fileInfo.MTime, &dirItem.MTime) == 0 1820 && Compare_FiTime(&fileInfo.MTime, &dirItem.MTime) == 0
1828 && Compare_FiTime(&fileInfo.CTime, &dirItem.CTime) == 0) 1821 && Compare_FiTime(&fileInfo.CTime, &dirItem.CTime) == 0)
1829 { 1822 {
1830 RINOK(callback->DeletingAfterArchiving(phyPath, false)); 1823 RINOK(callback->DeletingAfterArchiving(phyPath, false))
1831 DeleteFileAlways(phyPath); 1824 DeleteFileAlways(phyPath);
1832 } 1825 }
1833 } 1826 }
@@ -1852,12 +1845,12 @@ HRESULT UpdateArchive(
1852 const FString phyPath = dirItems.GetPhyPath(pairs[i].Index); 1845 const FString phyPath = dirItems.GetPhyPath(pairs[i].Index);
1853 if (NFind::DoesDirExist(phyPath)) 1846 if (NFind::DoesDirExist(phyPath))
1854 { 1847 {
1855 RINOK(callback->DeletingAfterArchiving(phyPath, true)); 1848 RINOK(callback->DeletingAfterArchiving(phyPath, true))
1856 RemoveDir(phyPath); 1849 RemoveDir(phyPath);
1857 } 1850 }
1858 } 1851 }
1859 1852
1860 RINOK(callback->FinishDeletingAfterArchiving()); 1853 RINOK(callback->FinishDeletingAfterArchiving())
1861 } 1854 }
1862 1855
1863 return S_OK; 1856 return S_OK;
diff --git a/CPP/7zip/UI/Common/Update.h b/CPP/7zip/UI/Common/Update.h
index 01fc43e..a9459ff 100644
--- a/CPP/7zip/UI/Common/Update.h
+++ b/CPP/7zip/UI/Common/Update.h
@@ -1,7 +1,7 @@
1// Update.h 1// Update.h
2 2
3#ifndef __COMMON_UPDATE_H 3#ifndef ZIP7_INC_COMMON_UPDATE_H
4#define __COMMON_UPDATE_H 4#define ZIP7_INC_COMMON_UPDATE_H
5 5
6#include "../../../Common/Wildcard.h" 6#include "../../../Common/Wildcard.h"
7 7
@@ -34,7 +34,7 @@ struct CArchivePath
34 FString TempPrefix; // path(folder) for temp location 34 FString TempPrefix; // path(folder) for temp location
35 FString TempPostfix; 35 FString TempPostfix;
36 36
37 CArchivePath(): Temp(false) {}; 37 CArchivePath(): Temp(false) {}
38 38
39 void ParseFromPath(const UString &path, EArcNameMode mode); 39 void ParseFromPath(const UString &path, EArcNameMode mode);
40 UString GetPathWithoutExt() const { return Prefix + Name; } 40 UString GetPathWithoutExt() const { return Prefix + Name; }
@@ -81,31 +81,21 @@ struct CRenamePair
81 81
82struct CUpdateOptions 82struct CUpdateOptions
83{ 83{
84 CCompressionMethodMode MethodMode;
85
86 CObjectVector<CUpdateArchiveCommand> Commands;
87 bool UpdateArchiveItself; 84 bool UpdateArchiveItself;
88 CArchivePath ArchivePath;
89 EArcNameMode ArcNameMode;
90
91 bool SfxMode; 85 bool SfxMode;
92 FString SfxModule; 86
93
94 bool PreserveATime; 87 bool PreserveATime;
95 bool OpenShareForWrite; 88 bool OpenShareForWrite;
96 bool StopAfterOpenError; 89 bool StopAfterOpenError;
97 90
98 bool StdInMode; 91 bool StdInMode;
99 UString StdInFileName;
100 bool StdOutMode; 92 bool StdOutMode;
101 93
102 bool EMailMode; 94 bool EMailMode;
103 bool EMailRemoveAfter; 95 bool EMailRemoveAfter;
104 UString EMailAddress;
105 96
106 FString WorkingDir; 97 bool DeleteAfterCompressing;
107 NWildcard::ECensorPathMode PathMode; 98 bool SetArcMTime;
108 // UString AddPathPrefix;
109 99
110 CBoolPair NtSecurity; 100 CBoolPair NtSecurity;
111 CBoolPair AltStreams; 101 CBoolPair AltStreams;
@@ -115,19 +105,28 @@ struct CUpdateOptions
115 CBoolPair StoreOwnerId; 105 CBoolPair StoreOwnerId;
116 CBoolPair StoreOwnerName; 106 CBoolPair StoreOwnerName;
117 107
118 bool DeleteAfterCompressing; 108 EArcNameMode ArcNameMode;
109 NWildcard::ECensorPathMode PathMode;
119 110
120 bool SetArcMTime; 111 CCompressionMethodMode MethodMode;
112
113 CObjectVector<CUpdateArchiveCommand> Commands;
114 CArchivePath ArchivePath;
115
116 FString SfxModule;
117 UString StdInFileName;
118 UString EMailAddress;
119 FString WorkingDir;
120 // UString AddPathPrefix;
121 121
122 CObjectVector<CRenamePair> RenamePairs; 122 CObjectVector<CRenamePair> RenamePairs;
123 CRecordVector<UInt64> VolumesSizes;
123 124
124 bool InitFormatIndex(const CCodecs *codecs, const CObjectVector<COpenType> &types, const UString &arcPath); 125 bool InitFormatIndex(const CCodecs *codecs, const CObjectVector<COpenType> &types, const UString &arcPath);
125 bool SetArcPath(const CCodecs *codecs, const UString &arcPath); 126 bool SetArcPath(const CCodecs *codecs, const UString &arcPath);
126 127
127 CUpdateOptions(): 128 CUpdateOptions():
128 UpdateArchiveItself(true), 129 UpdateArchiveItself(true),
129 ArcNameMode(k_ArcNameMode_Smart),
130
131 SfxMode(false), 130 SfxMode(false),
132 131
133 PreserveATime(false), 132 PreserveATime(false),
@@ -140,12 +139,13 @@ struct CUpdateOptions
140 EMailMode(false), 139 EMailMode(false),
141 EMailRemoveAfter(false), 140 EMailRemoveAfter(false),
142 141
143 PathMode(NWildcard::k_RelatPath),
144
145 DeleteAfterCompressing(false), 142 DeleteAfterCompressing(false),
146 SetArcMTime(false) 143 SetArcMTime(false),
147 144
148 {}; 145 ArcNameMode(k_ArcNameMode_Smart),
146 PathMode(NWildcard::k_RelatPath)
147
148 {}
149 149
150 void SetActionCommand_Add() 150 void SetActionCommand_Add()
151 { 151 {
@@ -154,10 +154,9 @@ struct CUpdateOptions
154 c.ActionSet = NUpdateArchive::k_ActionSet_Add; 154 c.ActionSet = NUpdateArchive::k_ActionSet_Add;
155 Commands.Add(c); 155 Commands.Add(c);
156 } 156 }
157
158 CRecordVector<UInt64> VolumesSizes;
159}; 157};
160 158
159
161struct CUpdateErrorInfo 160struct CUpdateErrorInfo
162{ 161{
163 DWORD SystemError; // it's DWORD (WRes) only; 162 DWORD SystemError; // it's DWORD (WRes) only;
@@ -170,32 +169,40 @@ struct CUpdateErrorInfo
170 HRESULT SetFromLastError(const char *message, const FString &fileName); 169 HRESULT SetFromLastError(const char *message, const FString &fileName);
171 HRESULT SetFromError_DWORD(const char *message, const FString &fileName, DWORD error); 170 HRESULT SetFromError_DWORD(const char *message, const FString &fileName, DWORD error);
172 171
173 CUpdateErrorInfo(): SystemError(0) {}; 172 CUpdateErrorInfo(): SystemError(0) {}
174}; 173};
175 174
176struct CFinishArchiveStat 175struct CFinishArchiveStat
177{ 176{
178 UInt64 OutArcFileSize; 177 UInt64 OutArcFileSize;
178 unsigned NumVolumes;
179 bool IsMultiVolMode;
179 180
180 CFinishArchiveStat(): OutArcFileSize(0) {} 181 CFinishArchiveStat(): OutArcFileSize(0), NumVolumes(0), IsMultiVolMode(false) {}
181}; 182};
182 183
183#define INTERFACE_IUpdateCallbackUI2(x) \ 184Z7_PURE_INTERFACES_BEGIN
184 INTERFACE_IUpdateCallbackUI(x) \ 185
185 INTERFACE_IDirItemsCallback(x) \ 186// INTERFACE_IUpdateCallbackUI(x)
186 virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x; \ 187// INTERFACE_IDirItemsCallback(x)
187 virtual HRESULT StartScanning() x; \ 188
188 virtual HRESULT FinishScanning(const CDirItemsStat &st) x; \ 189#define Z7_IFACEN_IUpdateCallbackUI2(x) \
189 virtual HRESULT StartOpenArchive(const wchar_t *name) x; \ 190 virtual HRESULT OpenResult(const CCodecs *codecs, const CArchiveLink &arcLink, const wchar_t *name, HRESULT result) x \
190 virtual HRESULT StartArchive(const wchar_t *name, bool updating) x; \ 191 virtual HRESULT StartScanning() x \
191 virtual HRESULT FinishArchive(const CFinishArchiveStat &st) x; \ 192 virtual HRESULT FinishScanning(const CDirItemsStat &st) x \
192 virtual HRESULT DeletingAfterArchiving(const FString &path, bool isDir) x; \ 193 virtual HRESULT StartOpenArchive(const wchar_t *name) x \
193 virtual HRESULT FinishDeletingAfterArchiving() x; \ 194 virtual HRESULT StartArchive(const wchar_t *name, bool updating) x \
194 195 virtual HRESULT FinishArchive(const CFinishArchiveStat &st) x \
195struct IUpdateCallbackUI2: public IUpdateCallbackUI, public IDirItemsCallback 196 virtual HRESULT DeletingAfterArchiving(const FString &path, bool isDir) x \
197 virtual HRESULT FinishDeletingAfterArchiving() x \
198
199DECLARE_INTERFACE(IUpdateCallbackUI2):
200 public IUpdateCallbackUI,
201 public IDirItemsCallback
196{ 202{
197 INTERFACE_IUpdateCallbackUI2(=0) 203 Z7_IFACE_PURE(IUpdateCallbackUI2)
198}; 204};
205Z7_PURE_INTERFACES_END
199 206
200HRESULT UpdateArchive( 207HRESULT UpdateArchive(
201 CCodecs *codecs, 208 CCodecs *codecs,
diff --git a/CPP/7zip/UI/Common/UpdateAction.h b/CPP/7zip/UI/Common/UpdateAction.h
index bc53fcd..6a3565e 100644
--- a/CPP/7zip/UI/Common/UpdateAction.h
+++ b/CPP/7zip/UI/Common/UpdateAction.h
@@ -1,7 +1,7 @@
1// UpdateAction.h 1// UpdateAction.h
2 2
3#ifndef __UPDATE_ACTION_H 3#ifndef ZIP7_INC_UPDATE_ACTION_H
4#define __UPDATE_ACTION_H 4#define ZIP7_INC_UPDATE_ACTION_H
5 5
6namespace NUpdateArchive { 6namespace NUpdateArchive {
7 7
diff --git a/CPP/7zip/UI/Common/UpdateCallback.cpp b/CPP/7zip/UI/Common/UpdateCallback.cpp
index c93bfc7..5e2860d 100644
--- a/CPP/7zip/UI/Common/UpdateCallback.cpp
+++ b/CPP/7zip/UI/Common/UpdateCallback.cpp
@@ -7,17 +7,23 @@
7#ifndef _WIN32 7#ifndef _WIN32
8// #include <grp.h> 8// #include <grp.h>
9// #include <pwd.h> 9// #include <pwd.h>
10 10/*
11inclusion of <sys/sysmacros.h> by <sys/types.h> is deprecated since glibc 2.25.
12Since glibc 2.3.3, macros have been aliases for three GNU-specific
13functions: gnu_dev_makedev(), gnu_dev_major(), and gnu_dev_minor()
14*/
11// for major()/minor(): 15// for major()/minor():
12#if defined(__FreeBSD__) || defined(BSD)
13#include <sys/types.h> 16#include <sys/types.h>
17#if defined(__FreeBSD__) || defined(BSD) || defined(__APPLE__)
14#else 18#else
19#ifndef major
15#include <sys/sysmacros.h> 20#include <sys/sysmacros.h>
16#endif 21#endif
17
18#endif 22#endif
19 23
20#ifndef _7ZIP_ST 24#endif // _WIN32
25
26#ifndef Z7_ST
21#include "../../../Windows/Synchronization.h" 27#include "../../../Windows/Synchronization.h"
22#endif 28#endif
23 29
@@ -36,14 +42,14 @@
36#include "UpdateCallback.h" 42#include "UpdateCallback.h"
37 43
38#if defined(_WIN32) && !defined(UNDER_CE) 44#if defined(_WIN32) && !defined(UNDER_CE)
39#define _USE_SECURITY_CODE 45#define Z7_USE_SECURITY_CODE
40#include "../../../Windows/SecurityUtils.h" 46#include "../../../Windows/SecurityUtils.h"
41#endif 47#endif
42 48
43using namespace NWindows; 49using namespace NWindows;
44using namespace NFile; 50using namespace NFile;
45 51
46#ifndef _7ZIP_ST 52#ifndef Z7_ST
47static NSynchronization::CCriticalSection g_CriticalSection; 53static NSynchronization::CCriticalSection g_CriticalSection;
48#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 54#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
49#else 55#else
@@ -51,25 +57,11 @@ static NSynchronization::CCriticalSection g_CriticalSection;
51#endif 57#endif
52 58
53 59
54#ifdef _USE_SECURITY_CODE 60#ifdef Z7_USE_SECURITY_CODE
55bool InitLocalPrivileges(); 61bool InitLocalPrivileges();
56#endif 62#endif
57 63
58CArchiveUpdateCallback::CArchiveUpdateCallback(): 64CArchiveUpdateCallback::CArchiveUpdateCallback():
59 _hardIndex_From((UInt32)(Int32)-1),
60
61 Callback(NULL),
62
63 DirItems(NULL),
64 ParentDirItem(NULL),
65
66 Arc(NULL),
67 ArcItems(NULL),
68 UpdatePairs(NULL),
69 NewNames(NULL),
70 CommentIndex(-1),
71 Comment(NULL),
72
73 PreserveATime(false), 65 PreserveATime(false),
74 ShareForWrite(false), 66 ShareForWrite(false),
75 StopAfterOpenError(false), 67 StopAfterOpenError(false),
@@ -92,29 +84,42 @@ CArchiveUpdateCallback::CArchiveUpdateCallback():
92 Need_LatestMTime(false), 84 Need_LatestMTime(false),
93 LatestMTime_Defined(false), 85 LatestMTime_Defined(false),
94 86
95 ProcessedItemsStatuses(NULL) 87 Callback(NULL),
88
89 DirItems(NULL),
90 ParentDirItem(NULL),
91
92 Arc(NULL),
93 ArcItems(NULL),
94 UpdatePairs(NULL),
95 NewNames(NULL),
96 Comment(NULL),
97 CommentIndex(-1),
98
99 ProcessedItemsStatuses(NULL),
100 _hardIndex_From((UInt32)(Int32)-1)
96{ 101{
97 #ifdef _USE_SECURITY_CODE 102 #ifdef Z7_USE_SECURITY_CODE
98 _saclEnabled = InitLocalPrivileges(); 103 _saclEnabled = InitLocalPrivileges();
99 #endif 104 #endif
100} 105}
101 106
102 107
103STDMETHODIMP CArchiveUpdateCallback::SetTotal(UInt64 size) 108Z7_COM7F_IMF(CArchiveUpdateCallback::SetTotal(UInt64 size))
104{ 109{
105 COM_TRY_BEGIN 110 COM_TRY_BEGIN
106 return Callback->SetTotal(size); 111 return Callback->SetTotal(size);
107 COM_TRY_END 112 COM_TRY_END
108} 113}
109 114
110STDMETHODIMP CArchiveUpdateCallback::SetCompleted(const UInt64 *completeValue) 115Z7_COM7F_IMF(CArchiveUpdateCallback::SetCompleted(const UInt64 *completeValue))
111{ 116{
112 COM_TRY_BEGIN 117 COM_TRY_BEGIN
113 return Callback->SetCompleted(completeValue); 118 return Callback->SetCompleted(completeValue);
114 COM_TRY_END 119 COM_TRY_END
115} 120}
116 121
117STDMETHODIMP CArchiveUpdateCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 122Z7_COM7F_IMF(CArchiveUpdateCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
118{ 123{
119 COM_TRY_BEGIN 124 COM_TRY_BEGIN
120 return Callback->SetRatioInfo(inSize, outSize); 125 return Callback->SetRatioInfo(inSize, outSize);
@@ -135,17 +140,17 @@ static const CStatProp kProps[] =
135 { NULL, kpidIsAnti, VT_BOOL} 140 { NULL, kpidIsAnti, VT_BOOL}
136}; 141};
137 142
138STDMETHODIMP CArchiveUpdateCallback::EnumProperties(IEnumSTATPROPSTG **) 143Z7_COM7F_IMF(CArchiveUpdateCallback::EnumProperties(IEnumSTATPROPSTG **)
139{ 144{
140 return CStatPropEnumerator::CreateEnumerator(kProps, ARRAY_SIZE(kProps), enumerator); 145 return CStatPropEnumerator::CreateEnumerator(kProps, Z7_ARRAY_SIZE(kProps), enumerator);
141} 146}
142*/ 147*/
143 148
144STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index, 149Z7_COM7F_IMF(CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index,
145 Int32 *newData, Int32 *newProps, UInt32 *indexInArchive) 150 Int32 *newData, Int32 *newProps, UInt32 *indexInArchive))
146{ 151{
147 COM_TRY_BEGIN 152 COM_TRY_BEGIN
148 RINOK(Callback->CheckBreak()); 153 RINOK(Callback->CheckBreak())
149 const CUpdatePair2 &up = (*UpdatePairs)[index]; 154 const CUpdatePair2 &up = (*UpdatePairs)[index];
150 if (newData) *newData = BoolToInt(up.NewData); 155 if (newData) *newData = BoolToInt(up.NewData);
151 if (newProps) *newProps = BoolToInt(up.NewProps); 156 if (newProps) *newProps = BoolToInt(up.NewProps);
@@ -160,7 +165,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 index,
160} 165}
161 166
162 167
163STDMETHODIMP CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value) 168Z7_COM7F_IMF(CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *value))
164{ 169{
165 NCOM::CPropVariant prop; 170 NCOM::CPropVariant prop;
166 switch (propID) 171 switch (propID)
@@ -176,14 +181,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetRootProp(PROPID propID, PROPVARIANT *val
176 return S_OK; 181 return S_OK;
177} 182}
178 183
179STDMETHODIMP CArchiveUpdateCallback::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType) 184Z7_COM7F_IMF(CArchiveUpdateCallback::GetParent(UInt32 /* index */, UInt32 *parent, UInt32 *parentType))
180{ 185{
181 *parentType = NParentType::kDir; 186 *parentType = NParentType::kDir;
182 *parent = (UInt32)(Int32)-1; 187 *parent = (UInt32)(Int32)-1;
183 return S_OK; 188 return S_OK;
184} 189}
185 190
186STDMETHODIMP CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps) 191Z7_COM7F_IMF(CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps))
187{ 192{
188 *numProps = 0; 193 *numProps = 0;
189 if (StoreNtSecurity) 194 if (StoreNtSecurity)
@@ -191,25 +196,27 @@ STDMETHODIMP CArchiveUpdateCallback::GetNumRawProps(UInt32 *numProps)
191 return S_OK; 196 return S_OK;
192} 197}
193 198
194STDMETHODIMP CArchiveUpdateCallback::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 199Z7_COM7F_IMF(CArchiveUpdateCallback::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
195{ 200{
196 *name = NULL; 201 *name = NULL;
197 *propID = kpidNtSecure; 202 *propID = kpidNtSecure;
198 return S_OK; 203 return S_OK;
199} 204}
200 205
201STDMETHODIMP CArchiveUpdateCallback::GetRootRawProp(PROPID 206Z7_COM7F_IMF(CArchiveUpdateCallback::GetRootRawProp(PROPID
202 #ifdef _USE_SECURITY_CODE
203 propID 207 propID
204 #endif 208 , const void **data, UInt32 *dataSize, UInt32 *propType))
205 , const void **data, UInt32 *dataSize, UInt32 *propType)
206{ 209{
207 *data = 0; 210 #ifndef Z7_USE_SECURITY_CODE
211 UNUSED_VAR(propID)
212 #endif
213
214 *data = NULL;
208 *dataSize = 0; 215 *dataSize = 0;
209 *propType = 0; 216 *propType = 0;
210 if (!StoreNtSecurity) 217 if (!StoreNtSecurity)
211 return S_OK; 218 return S_OK;
212 #ifdef _USE_SECURITY_CODE 219 #ifdef Z7_USE_SECURITY_CODE
213 if (propID == kpidNtSecure) 220 if (propID == kpidNtSecure)
214 { 221 {
215 if (StdInMode) 222 if (StdInMode)
@@ -233,12 +240,10 @@ STDMETHODIMP CArchiveUpdateCallback::GetRootRawProp(PROPID
233 return S_OK; 240 return S_OK;
234} 241}
235 242
236// #ifdef _USE_SECURITY_CODE
237// #endif
238 243
239STDMETHODIMP CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType) 244Z7_COM7F_IMF(CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, const void **data, UInt32 *dataSize, UInt32 *propType))
240{ 245{
241 *data = 0; 246 *data = NULL;
242 *dataSize = 0; 247 *dataSize = 0;
243 *propType = 0; 248 *propType = 0;
244 249
@@ -265,7 +270,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetRawProp(UInt32 index, PROPID propID, con
265 const CDirItem &di = DirItems->Items[(unsigned)up.DirIndex]; 270 const CDirItem &di = DirItems->Items[(unsigned)up.DirIndex];
266 #endif 271 #endif
267 272
268 #ifdef _USE_SECURITY_CODE 273 #ifdef Z7_USE_SECURITY_CODE
269 if (propID == kpidNtSecure) 274 if (propID == kpidNtSecure)
270 { 275 {
271 if (!StoreNtSecurity) 276 if (!StoreNtSecurity)
@@ -349,7 +354,7 @@ static UString GetRelativePath(const UString &to, const UString &from)
349 354
350#endif 355#endif
351 356
352STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 357Z7_COM7F_IMF(CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
353{ 358{
354 COM_TRY_BEGIN 359 COM_TRY_BEGIN
355 const CUpdatePair2 &up = (*UpdatePairs)[index]; 360 const CUpdatePair2 &up = (*UpdatePairs)[index];
@@ -385,7 +390,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR
385 CReparseAttr attr; 390 CReparseAttr attr;
386 if (attr.Parse(di.ReparseData, di.ReparseData.Size())) 391 if (attr.Parse(di.ReparseData, di.ReparseData.Size()))
387 { 392 {
388 UString simpleName = attr.GetPath(); 393 const UString simpleName = attr.GetPath();
389 if (!attr.IsSymLink_WSL() && attr.IsRelative_Win()) 394 if (!attr.IsSymLink_WSL() && attr.IsRelative_Win())
390 prop = simpleName; 395 prop = simpleName;
391 else 396 else
@@ -484,6 +489,11 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR
484 // case kpidShortName: prop = di.ShortName; break; 489 // case kpidShortName: prop = di.ShortName; break;
485 #else 490 #else
486 491
492 #if defined(__APPLE__)
493 #pragma GCC diagnostic push
494 #pragma GCC diagnostic ignored "-Wsign-conversion"
495 #endif
496
487 case kpidDeviceMajor: 497 case kpidDeviceMajor:
488 /* 498 /*
489 printf("\ndi.mode = %o\n", di.mode); 499 printf("\ndi.mode = %o\n", di.mode);
@@ -499,6 +509,10 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR
499 prop = (UInt32)minor(di.rdev); 509 prop = (UInt32)minor(di.rdev);
500 break; 510 break;
501 511
512 #if defined(__APPLE__)
513 #pragma GCC diagnostic pop
514 #endif
515
502 // case kpidDevice: if (S_ISCHR(di.mode) || S_ISBLK(di.mode)) prop = (UInt64)(di.rdev); break; 516 // case kpidDevice: if (S_ISCHR(di.mode) || S_ISBLK(di.mode)) prop = (UInt64)(di.rdev); break;
503 517
504 case kpidUserId: if (StoreOwnerId) prop = (UInt32)di.uid; break; 518 case kpidUserId: if (StoreOwnerId) prop = (UInt32)di.uid; break;
@@ -519,22 +533,22 @@ STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PR
519 COM_TRY_END 533 COM_TRY_END
520} 534}
521 535
522#ifndef _7ZIP_ST 536#ifndef Z7_ST
523static NSynchronization::CCriticalSection CS; 537static NSynchronization::CCriticalSection g_CS;
524#endif 538#endif
525 539
526void CArchiveUpdateCallback::UpdateProcessedItemStatus(unsigned dirIndex) 540void CArchiveUpdateCallback::UpdateProcessedItemStatus(unsigned dirIndex)
527{ 541{
528 if (ProcessedItemsStatuses) 542 if (ProcessedItemsStatuses)
529 { 543 {
530 #ifndef _7ZIP_ST 544 #ifndef Z7_ST
531 NSynchronization::CCriticalSectionLock lock(CS); 545 NSynchronization::CCriticalSectionLock lock(g_CS);
532 #endif 546 #endif
533 ProcessedItemsStatuses[dirIndex] = 1; 547 ProcessedItemsStatuses[dirIndex] = 1;
534 } 548 }
535} 549}
536 550
537STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode) 551Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStream **inStream, UInt32 mode))
538{ 552{
539 COM_TRY_BEGIN 553 COM_TRY_BEGIN
540 *inStream = NULL; 554 *inStream = NULL;
@@ -542,7 +556,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
542 if (!up.NewData) 556 if (!up.NewData)
543 return E_FAIL; 557 return E_FAIL;
544 558
545 RINOK(Callback->CheckBreak()); 559 RINOK(Callback->CheckBreak())
546 // RINOK(Callback->Finalize()); 560 // RINOK(Callback->Finalize());
547 561
548 bool isDir = IsDir(up); 562 bool isDir = IsDir(up);
@@ -554,7 +568,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
554 name = (*ArcItems)[(unsigned)up.ArcIndex].Name; 568 name = (*ArcItems)[(unsigned)up.ArcIndex].Name;
555 else if (up.DirIndex >= 0) 569 else if (up.DirIndex >= 0)
556 name = DirItems->GetLogPath((unsigned)up.DirIndex); 570 name = DirItems->GetLogPath((unsigned)up.DirIndex);
557 RINOK(Callback->GetStream(name, isDir, true, mode)); 571 RINOK(Callback->GetStream(name, isDir, true, mode))
558 572
559 /* 9.33: fixed. Handlers expect real stream object for files, even for anti-file. 573 /* 9.33: fixed. Handlers expect real stream object for files, even for anti-file.
560 so we return empty stream */ 574 so we return empty stream */
@@ -569,7 +583,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
569 return S_OK; 583 return S_OK;
570 } 584 }
571 585
572 RINOK(Callback->GetStream(DirItems->GetLogPath((unsigned)up.DirIndex), isDir, false, mode)); 586 RINOK(Callback->GetStream(DirItems->GetLogPath((unsigned)up.DirIndex), isDir, false, mode))
573 587
574 if (isDir) 588 if (isDir)
575 return S_OK; 589 return S_OK;
@@ -640,8 +654,9 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
640 #endif 654 #endif
641 655
642 inStreamSpec->SupportHardLinks = StoreHardLinks; 656 inStreamSpec->SupportHardLinks = StoreHardLinks;
643 inStreamSpec->Set_PreserveATime(PreserveATime 657 const bool preserveATime = (PreserveATime
644 || mode == NUpdateNotifyOp::kAnalyze); // 22.00 : we don't change access time in Analyze pass. 658 || mode == NUpdateNotifyOp::kAnalyze); // 22.00 : we don't change access time in Analyze pass.
659 inStreamSpec->Set_PreserveATime(preserveATime);
645 660
646 const FString path = DirItems->GetPhyPath((unsigned)up.DirIndex); 661 const FString path = DirItems->GetPhyPath((unsigned)up.DirIndex);
647 _openFiles_Indexes.Add(index); 662 _openFiles_Indexes.Add(index);
@@ -655,12 +670,32 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
655 670
656 if (!inStreamSpec->OpenShared(path, ShareForWrite)) 671 if (!inStreamSpec->OpenShared(path, ShareForWrite))
657 { 672 {
658 const DWORD error = ::GetLastError(); 673 bool isOpen = false;
659 const HRESULT hres = Callback->OpenFileError(path, error); 674 if (preserveATime)
660 if (StopAfterOpenError) 675 {
676 inStreamSpec->Set_PreserveATime(false);
677 isOpen = inStreamSpec->OpenShared(path, ShareForWrite);
678 }
679 if (!isOpen)
680 {
681 const DWORD error = ::GetLastError();
682 const HRESULT hres = Callback->OpenFileError(path, error);
661 if (hres == S_OK || hres == S_FALSE) 683 if (hres == S_OK || hres == S_FALSE)
684 if (StopAfterOpenError ||
685 // v23: we check also for some critical errors:
686 #ifdef _WIN32
687 error == ERROR_NO_SYSTEM_RESOURCES
688 #else
689 error == EMFILE
690 #endif
691 )
692 {
693 if (error == 0)
694 return E_FAIL;
662 return HRESULT_FROM_WIN32(error); 695 return HRESULT_FROM_WIN32(error);
663 return hres; 696 }
697 return hres;
698 }
664 } 699 }
665 700
666 /* 701 /*
@@ -679,7 +714,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
679 inStreamSpec->ReloadProps(); 714 inStreamSpec->ReloadProps();
680 } 715 }
681 716
682 // #if defined(USE_WIN_FILE) || !defined(_WIN32) 717 // #if defined(Z7_FILE_STREAMS_USE_WIN_FILE) || !defined(_WIN32)
683 if (StoreHardLinks) 718 if (StoreHardLinks)
684 { 719 {
685 CStreamFileProps props; 720 CStreamFileProps props;
@@ -691,8 +726,8 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
691 pair.Key1 = props.VolID; 726 pair.Key1 = props.VolID;
692 pair.Key2 = props.FileID_Low; 727 pair.Key2 = props.FileID_Low;
693 pair.Value = index; 728 pair.Value = index;
694 unsigned numItems = _map.Size(); 729 const unsigned numItems = _map.Size();
695 unsigned pairIndex = _map.AddToUniqueSorted2(pair); 730 const unsigned pairIndex = _map.AddToUniqueSorted2(pair);
696 if (numItems == _map.Size()) 731 if (numItems == _map.Size())
697 { 732 {
698 // const CKeyKeyValPair &pair2 = _map.Pairs[pairIndex]; 733 // const CKeyKeyValPair &pair2 = _map.Pairs[pairIndex];
@@ -714,14 +749,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream2(UInt32 index, ISequentialInStrea
714 COM_TRY_END 749 COM_TRY_END
715} 750}
716 751
717STDMETHODIMP CArchiveUpdateCallback::SetOperationResult(Int32 opRes) 752Z7_COM7F_IMF(CArchiveUpdateCallback::SetOperationResult(Int32 opRes))
718{ 753{
719 COM_TRY_BEGIN 754 COM_TRY_BEGIN
720 return Callback->SetOperationResult(opRes); 755 return Callback->SetOperationResult(opRes);
721 COM_TRY_END 756 COM_TRY_END
722} 757}
723 758
724STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream) 759Z7_COM7F_IMF(CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream))
725{ 760{
726 COM_TRY_BEGIN 761 COM_TRY_BEGIN
727 return GetStream2(index, inStream, 762 return GetStream2(index, inStream,
@@ -731,7 +766,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream
731 COM_TRY_END 766 COM_TRY_END
732} 767}
733 768
734STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 index, UInt32 op) 769Z7_COM7F_IMF(CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 index, UInt32 op))
735{ 770{
736 COM_TRY_BEGIN 771 COM_TRY_BEGIN
737 772
@@ -770,9 +805,9 @@ STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 in
770 } 805 }
771 else if (Arc) 806 else if (Arc)
772 { 807 {
773 RINOK(Arc->GetItem_Path(index, s2)); 808 RINOK(Arc->GetItem_Path(index, s2))
774 s = s2; 809 s = s2;
775 RINOK(Archive_IsItem_Dir(Arc->Archive, index, isDir)); 810 RINOK(Archive_IsItem_Dir(Arc->Archive, index, isDir))
776 } 811 }
777 } 812 }
778 } 813 }
@@ -791,7 +826,7 @@ STDMETHODIMP CArchiveUpdateCallback::ReportOperation(UInt32 indexType, UInt32 in
791 COM_TRY_END 826 COM_TRY_END
792} 827}
793 828
794STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes) 829Z7_COM7F_IMF(CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt32 index, Int32 opRes))
795{ 830{
796 COM_TRY_BEGIN 831 COM_TRY_BEGIN
797 832
@@ -825,12 +860,12 @@ STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt3
825 s = (*ArcItems)[index].Name; 860 s = (*ArcItems)[index].Name;
826 else if (Arc) 861 else if (Arc)
827 { 862 {
828 RINOK(Arc->GetItem_Path(index, s2)); 863 RINOK(Arc->GetItem_Path(index, s2))
829 s = s2; 864 s = s2;
830 } 865 }
831 if (Archive) 866 if (Archive)
832 { 867 {
833 RINOK(Archive_GetItemBoolProp(Archive, index, kpidEncrypted, isEncrypted)); 868 RINOK(Archive_GetItemBoolProp(Archive, index, kpidEncrypted, isEncrypted))
834 } 869 }
835 } 870 }
836 } 871 }
@@ -848,7 +883,7 @@ STDMETHODIMP CArchiveUpdateCallback::ReportExtractResult(UInt32 indexType, UInt3
848 883
849 884
850/* 885/*
851STDMETHODIMP CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer) 886Z7_COM7F_IMF(CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer))
852{ 887{
853 *answer = 0; 888 *answer = 0;
854 if (Need_ArcMTime_Report && propID == kpidComboMTime) 889 if (Need_ArcMTime_Report && propID == kpidComboMTime)
@@ -856,7 +891,7 @@ STDMETHODIMP CArchiveUpdateCallback::DoNeedArcProp(PROPID propID, Int32 *answer)
856 return S_OK; 891 return S_OK;
857} 892}
858 893
859STDMETHODIMP CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) 894Z7_COM7F_IMF(CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value))
860{ 895{
861 if (indexType == NArchive::NEventIndexType::kArcProp) 896 if (indexType == NArchive::NEventIndexType::kArcProp)
862 { 897 {
@@ -879,19 +914,19 @@ STDMETHODIMP CArchiveUpdateCallback::ReportProp(UInt32 indexType, UInt32 index,
879 return Callback->ReportProp(indexType, index, propID, value); 914 return Callback->ReportProp(indexType, index, propID, value);
880} 915}
881 916
882STDMETHODIMP CArchiveUpdateCallback::ReportRawProp(UInt32 indexType, UInt32 index, 917Z7_COM7F_IMF(CArchiveUpdateCallback::ReportRawProp(UInt32 indexType, UInt32 index,
883 PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) 918 PROPID propID, const void *data, UInt32 dataSize, UInt32 propType))
884{ 919{
885 return Callback->ReportRawProp(indexType, index, propID, data, dataSize, propType); 920 return Callback->ReportRawProp(indexType, index, propID, data, dataSize, propType);
886} 921}
887 922
888STDMETHODIMP CArchiveUpdateCallback::ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) 923Z7_COM7F_IMF(CArchiveUpdateCallback::ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes))
889{ 924{
890 return Callback->ReportFinished(indexType, index, opRes); 925 return Callback->ReportFinished(indexType, index, opRes);
891} 926}
892*/ 927*/
893 928
894STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size) 929Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size))
895{ 930{
896 if (VolumesSizes.Size() == 0) 931 if (VolumesSizes.Size() == 0)
897 return S_FALSE; 932 return S_FALSE;
@@ -901,7 +936,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size)
901 return S_OK; 936 return S_OK;
902} 937}
903 938
904STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream) 939Z7_COM7F_IMF(CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream))
905{ 940{
906 COM_TRY_BEGIN 941 COM_TRY_BEGIN
907 char temp[16]; 942 char temp[16];
@@ -910,7 +945,7 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOu
910 while (res.Len() < 2) 945 while (res.Len() < 2)
911 res.InsertAtFront(FTEXT('0')); 946 res.InsertAtFront(FTEXT('0'));
912 FString fileName = VolName; 947 FString fileName = VolName;
913 fileName += '.'; 948 fileName.Add_Dot();
914 fileName += res; 949 fileName += res;
915 fileName += VolExt; 950 fileName += VolExt;
916 COutFileStream *streamSpec = new COutFileStream; 951 COutFileStream *streamSpec = new COutFileStream;
@@ -922,14 +957,14 @@ STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOu
922 COM_TRY_END 957 COM_TRY_END
923} 958}
924 959
925STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) 960Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password))
926{ 961{
927 COM_TRY_BEGIN 962 COM_TRY_BEGIN
928 return Callback->CryptoGetTextPassword2(passwordIsDefined, password); 963 return Callback->CryptoGetTextPassword2(passwordIsDefined, password);
929 COM_TRY_END 964 COM_TRY_END
930} 965}
931 966
932STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword(BSTR *password) 967Z7_COM7F_IMF(CArchiveUpdateCallback::CryptoGetTextPassword(BSTR *password))
933{ 968{
934 COM_TRY_BEGIN 969 COM_TRY_BEGIN
935 return Callback->CryptoGetTextPassword(password); 970 return Callback->CryptoGetTextPassword(password);
@@ -949,7 +984,7 @@ HRESULT CArchiveUpdateCallback::InFileStream_On_Error(UINT_PTR val, DWORD error)
949 { 984 {
950 if (_openFiles_Indexes[i] == index) 985 if (_openFiles_Indexes[i] == index)
951 { 986 {
952 RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error)); 987 RINOK(Callback->ReadingFileError(_openFiles_Paths[i], error))
953 break; 988 break;
954 } 989 }
955 } 990 }
diff --git a/CPP/7zip/UI/Common/UpdateCallback.h b/CPP/7zip/UI/Common/UpdateCallback.h
index 3719c1e..379b814 100644
--- a/CPP/7zip/UI/Common/UpdateCallback.h
+++ b/CPP/7zip/UI/Common/UpdateCallback.h
@@ -1,7 +1,7 @@
1// UpdateCallback.h 1// UpdateCallback.h
2 2
3#ifndef __UPDATE_CALLBACK_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_H
4#define __UPDATE_CALLBACK_H 4#define ZIP7_INC_UPDATE_CALLBACK_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -27,37 +27,38 @@ struct CArcToDoStat
27 } 27 }
28}; 28};
29 29
30#define INTERFACE_IUpdateCallbackUI(x) \ 30
31 virtual HRESULT WriteSfx(const wchar_t *name, UInt64 size) x; \ 31Z7_PURE_INTERFACES_BEGIN
32 virtual HRESULT SetTotal(UInt64 size) x; \ 32
33 virtual HRESULT SetCompleted(const UInt64 *completeValue) x; \ 33#define Z7_IFACEN_IUpdateCallbackUI(x) \
34 virtual HRESULT SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) x; \ 34 virtual HRESULT WriteSfx(const wchar_t *name, UInt64 size) x \
35 virtual HRESULT CheckBreak() x; \ 35 virtual HRESULT SetTotal(UInt64 size) x \
36 /* virtual HRESULT Finalize() x; */ \ 36 virtual HRESULT SetCompleted(const UInt64 *completeValue) x \
37 virtual HRESULT SetNumItems(const CArcToDoStat &stat) x; \ 37 virtual HRESULT SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) x \
38 virtual HRESULT GetStream(const wchar_t *name, bool isDir, bool isAnti, UInt32 mode) x; \ 38 virtual HRESULT CheckBreak() x \
39 virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x; \ 39 /* virtual HRESULT Finalize() x */ \
40 virtual HRESULT ReadingFileError(const FString &path, DWORD systemError) x; \ 40 virtual HRESULT SetNumItems(const CArcToDoStat &stat) x \
41 virtual HRESULT SetOperationResult(Int32 opRes) x; \ 41 virtual HRESULT GetStream(const wchar_t *name, bool isDir, bool isAnti, UInt32 mode) x \
42 virtual HRESULT ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) x; \ 42 virtual HRESULT OpenFileError(const FString &path, DWORD systemError) x \
43 virtual HRESULT ReportUpdateOperation(UInt32 op, const wchar_t *name, bool isDir) x; \ 43 virtual HRESULT ReadingFileError(const FString &path, DWORD systemError) x \
44 /* virtual HRESULT SetPassword(const UString &password) x; */ \ 44 virtual HRESULT SetOperationResult(Int32 opRes) x \
45 virtual HRESULT CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) x; \ 45 virtual HRESULT ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) x \
46 virtual HRESULT CryptoGetTextPassword(BSTR *password) x; \ 46 virtual HRESULT ReportUpdateOperation(UInt32 op, const wchar_t *name, bool isDir) x \
47 virtual HRESULT ShowDeleteFile(const wchar_t *name, bool isDir) x; \ 47 /* virtual HRESULT SetPassword(const UString &password) x */ \
48 virtual HRESULT CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) x \
49 virtual HRESULT CryptoGetTextPassword(BSTR *password) x \
50 virtual HRESULT ShowDeleteFile(const wchar_t *name, bool isDir) x \
48 51
49 /* 52 /*
50 virtual HRESULT ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x; \ 53 virtual HRESULT ReportProp(UInt32 indexType, UInt32 index, PROPID propID, const PROPVARIANT *value) x \
51 virtual HRESULT ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x; \ 54 virtual HRESULT ReportRawProp(UInt32 indexType, UInt32 index, PROPID propID, const void *data, UInt32 dataSize, UInt32 propType) x \
52 virtual HRESULT ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) x; \ 55 virtual HRESULT ReportFinished(UInt32 indexType, UInt32 index, Int32 opRes) x \
53 */ 56 */
54 57
55 /* virtual HRESULT CloseProgress() { return S_OK; } */ 58 /* virtual HRESULT CloseProgress() { return S_OK; } */
56 59
57struct IUpdateCallbackUI 60Z7_IFACE_DECL_PURE(IUpdateCallbackUI)
58{ 61Z7_PURE_INTERFACES_END
59 INTERFACE_IUpdateCallbackUI(=0)
60};
61 62
62struct CKeyKeyValPair 63struct CKeyKeyValPair
63{ 64{
@@ -74,11 +75,11 @@ struct CKeyKeyValPair
74}; 75};
75 76
76 77
77class CArchiveUpdateCallback: 78class CArchiveUpdateCallback Z7_final:
78 public IArchiveUpdateCallback2, 79 public IArchiveUpdateCallback2,
79 public IArchiveUpdateCallbackFile, 80 public IArchiveUpdateCallbackFile,
80 // public IArchiveUpdateCallbackArcProp, 81 // public IArchiveUpdateCallbackArcProp,
81 public IArchiveExtractCallbackMessage, 82 public IArchiveExtractCallbackMessage2,
82 public IArchiveGetRawProps, 83 public IArchiveGetRawProps,
83 public IArchiveGetRootProps, 84 public IArchiveGetRootProps,
84 public ICryptoGetTextPassword2, 85 public ICryptoGetTextPassword2,
@@ -87,54 +88,63 @@ class CArchiveUpdateCallback:
87 public IInFileStream_Callback, 88 public IInFileStream_Callback,
88 public CMyUnknownImp 89 public CMyUnknownImp
89{ 90{
90 #if defined(_WIN32) && !defined(UNDER_CE) 91 Z7_COM_QI_BEGIN2(IArchiveUpdateCallback2)
91 bool _saclEnabled; 92 Z7_COM_QI_ENTRY(IArchiveUpdateCallbackFile)
92 #endif 93 // Z7_COM_QI_ENTRY(IArchiveUpdateCallbackArcProp)
93 CRecordVector<CKeyKeyValPair> _map; 94 Z7_COM_QI_ENTRY(IArchiveExtractCallbackMessage2)
95 Z7_COM_QI_ENTRY(IArchiveGetRawProps)
96 Z7_COM_QI_ENTRY(IArchiveGetRootProps)
97 Z7_COM_QI_ENTRY(ICryptoGetTextPassword2)
98 Z7_COM_QI_ENTRY(ICryptoGetTextPassword)
99 Z7_COM_QI_ENTRY(ICompressProgressInfo)
100 Z7_COM_QI_END
101 Z7_COM_ADDREF_RELEASE
102
103 Z7_IFACE_COM7_IMP(ICompressProgressInfo)
104
105 Z7_IFACE_COM7_IMP(IProgress)
106 Z7_IFACE_COM7_IMP(IArchiveUpdateCallback)
107 Z7_IFACE_COM7_IMP(IArchiveUpdateCallback2)
108 Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackFile)
109 // Z7_IFACE_COM7_IMP(IArchiveUpdateCallbackArcProp)
110 Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage2)
111 Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
112 Z7_IFACE_COM7_IMP(IArchiveGetRootProps)
113 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword2)
114 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
94 115
95 UInt32 _hardIndex_From;
96 UInt32 _hardIndex_To;
97 116
98 void UpdateProcessedItemStatus(unsigned dirIndex); 117 void UpdateProcessedItemStatus(unsigned dirIndex);
99 118
100public: 119public:
101 MY_QUERYINTERFACE_BEGIN2(IArchiveUpdateCallback2) 120 bool PreserveATime;
102 MY_QUERYINTERFACE_ENTRY(IArchiveUpdateCallbackFile) 121 bool ShareForWrite;
103 // MY_QUERYINTERFACE_ENTRY(IArchiveUpdateCallbackArcProp) 122 bool StopAfterOpenError;
104 MY_QUERYINTERFACE_ENTRY(IArchiveExtractCallbackMessage) 123 bool StdInMode;
105 MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) 124
106 MY_QUERYINTERFACE_ENTRY(IArchiveGetRootProps) 125 bool KeepOriginalItemNames;
107 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword2) 126 bool StoreNtSecurity;
108 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) 127 bool StoreHardLinks;
109 MY_QUERYINTERFACE_ENTRY(ICompressProgressInfo) 128 bool StoreSymLinks;
110 MY_QUERYINTERFACE_END 129
111 MY_ADDREF_RELEASE 130 bool StoreOwnerId;
112 131 bool StoreOwnerName;
113 132
114 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); 133 bool Need_LatestMTime;
115 134 bool LatestMTime_Defined;
116 INTERFACE_IArchiveUpdateCallback2(;) 135
117 INTERFACE_IArchiveUpdateCallbackFile(;) 136 /*
118 // INTERFACE_IArchiveUpdateCallbackArcProp(;) 137 bool Need_ArcMTime_Report;
119 INTERFACE_IArchiveExtractCallbackMessage(;) 138 bool ArcMTime_WasReported;
120 INTERFACE_IArchiveGetRawProps(;) 139 */
121 INTERFACE_IArchiveGetRootProps(;)
122
123 STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password);
124 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
125 140
126 CRecordVector<UInt32> _openFiles_Indexes; 141 CRecordVector<UInt32> _openFiles_Indexes;
127 FStringVector _openFiles_Paths; 142 FStringVector _openFiles_Paths;
128 // CRecordVector< CInFileStream* > _openFiles_Streams; 143 // CRecordVector< CInFileStream* > _openFiles_Streams;
129 144
130 bool AreAllFilesClosed() const { return _openFiles_Indexes.IsEmpty(); } 145 bool AreAllFilesClosed() const { return _openFiles_Indexes.IsEmpty(); }
131 virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error); 146 virtual HRESULT InFileStream_On_Error(UINT_PTR val, DWORD error) Z7_override;
132 virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val); 147 virtual void InFileStream_On_Destroy(CInFileStream *stream, UINT_PTR val) Z7_override;
133
134 CRecordVector<UInt64> VolumesSizes;
135 FString VolName;
136 FString VolExt;
137 UString ArcFileName; // without path prefix
138 148
139 IUpdateCallbackUI *Callback; 149 IUpdateCallbackUI *Callback;
140 150
@@ -145,36 +155,24 @@ public:
145 CMyComPtr<IInArchive> Archive; 155 CMyComPtr<IInArchive> Archive;
146 const CObjectVector<CArcItem> *ArcItems; 156 const CObjectVector<CArcItem> *ArcItems;
147 const CRecordVector<CUpdatePair2> *UpdatePairs; 157 const CRecordVector<CUpdatePair2> *UpdatePairs;
148 const UStringVector *NewNames;
149 int CommentIndex;
150 const UString *Comment;
151 158
152 bool PreserveATime; 159 CRecordVector<UInt64> VolumesSizes;
153 bool ShareForWrite; 160 FString VolName;
154 bool StopAfterOpenError; 161 FString VolExt;
155 bool StdInMode; 162 UString ArcFileName; // without path prefix
156
157 bool KeepOriginalItemNames;
158 bool StoreNtSecurity;
159 bool StoreHardLinks;
160 bool StoreSymLinks;
161 163
162 bool StoreOwnerId; 164 const UStringVector *NewNames;
163 bool StoreOwnerName; 165 const UString *Comment;
166 int CommentIndex;
164 167
165 /* 168 /*
166 bool Need_ArcMTime_Report;
167 bool ArcMTime_WasReported;
168 CArcTime Reported_ArcMTime; 169 CArcTime Reported_ArcMTime;
169 */ 170 */
170 bool Need_LatestMTime;
171 bool LatestMTime_Defined;
172 CFiTime LatestMTime; 171 CFiTime LatestMTime;
173 172
174 Byte *ProcessedItemsStatuses; 173 Byte *ProcessedItemsStatuses;
175 174
176 175
177
178 CArchiveUpdateCallback(); 176 CArchiveUpdateCallback();
179 177
180 bool IsDir(const CUpdatePair2 &up) const 178 bool IsDir(const CUpdatePair2 &up) const
@@ -185,6 +183,15 @@ public:
185 return (*ArcItems)[(unsigned)up.ArcIndex].IsDir; 183 return (*ArcItems)[(unsigned)up.ArcIndex].IsDir;
186 return false; 184 return false;
187 } 185 }
186
187private:
188 #if defined(_WIN32) && !defined(UNDER_CE)
189 bool _saclEnabled;
190 #endif
191 CRecordVector<CKeyKeyValPair> _map;
192
193 UInt32 _hardIndex_From;
194 UInt32 _hardIndex_To;
188}; 195};
189 196
190#endif 197#endif
diff --git a/CPP/7zip/UI/Common/UpdatePair.cpp b/CPP/7zip/UI/Common/UpdatePair.cpp
index e9a1644..99b0aaf 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
103static const char * const k_Duplicate_inDir_Message = "Duplicate filename on disk:"; 103static const char * const k_Duplicate_inDir_Message = "Duplicate filename on disk:";
104static const char * const k_NotCensoredCollision_Message = "Internal file name collision (file on disk, file in archive):"; 104static const char * const k_NotCensoredCollision_Message = "Internal file name collision (file on disk, file in archive):";
105 105
106MY_ATTR_NORETURN 106Z7_ATTR_NORETURN
107static 107static
108void ThrowError(const char *message, const UString &s1, const UString &s2) 108void ThrowError(const char *message, const UString &s1, const UString &s2)
109{ 109{
@@ -115,7 +115,7 @@ void ThrowError(const char *message, const UString &s1, const UString &s2)
115 115
116static int CompareArcItemsBase(const CArcItem &ai1, const CArcItem &ai2) 116static int CompareArcItemsBase(const CArcItem &ai1, const CArcItem &ai2)
117{ 117{
118 int res = CompareFileNames(ai1.Name, ai2.Name); 118 const int res = CompareFileNames(ai1.Name, ai2.Name);
119 if (res != 0) 119 if (res != 0)
120 return res; 120 return res;
121 if (ai1.IsDir != ai2.IsDir) 121 if (ai1.IsDir != ai2.IsDir)
@@ -128,7 +128,7 @@ static int CompareArcItems(const unsigned *p1, const unsigned *p2, void *param)
128 const unsigned i1 = *p1; 128 const unsigned i1 = *p1;
129 const unsigned i2 = *p2; 129 const unsigned i2 = *p2;
130 const CObjectVector<CArcItem> &arcItems = *(const CObjectVector<CArcItem> *)param; 130 const CObjectVector<CArcItem> &arcItems = *(const CObjectVector<CArcItem> *)param;
131 int res = CompareArcItemsBase(arcItems[i1], arcItems[i2]); 131 const int res = CompareArcItemsBase(arcItems[i1], arcItems[i2]);
132 if (res != 0) 132 if (res != 0)
133 return res; 133 return res;
134 return MyCompare(i1, i2); 134 return MyCompare(i1, i2);
@@ -259,7 +259,7 @@ void GetUpdatePairInfoList(
259 int compResult = 0; 259 int compResult = 0;
260 if (ai->MTime.Def) 260 if (ai->MTime.Def)
261 { 261 {
262 compResult = MyCompareTime(fileTimeType, di->MTime, ai->MTime); 262 compResult = MyCompareTime((unsigned)fileTimeType, di->MTime, ai->MTime);
263 } 263 }
264 switch (compResult) 264 switch (compResult)
265 { 265 {
@@ -283,7 +283,7 @@ void GetUpdatePairInfoList(
283 { 283 {
284 if (prevHostName) 284 if (prevHostName)
285 { 285 {
286 unsigned hostLen = prevHostName->Len(); 286 const unsigned hostLen = prevHostName->Len();
287 if (name->Len() > hostLen) 287 if (name->Len() > hostLen)
288 if ((*name)[hostLen] == ':' && CompareFileNames(*prevHostName, name->Left(hostLen)) == 0) 288 if ((*name)[hostLen] == ':' && CompareFileNames(*prevHostName, name->Left(hostLen)) == 0)
289 pair.HostIndex = prevHostFile; 289 pair.HostIndex = prevHostFile;
diff --git a/CPP/7zip/UI/Common/UpdatePair.h b/CPP/7zip/UI/Common/UpdatePair.h
index 296d3b0..13228b0 100644
--- a/CPP/7zip/UI/Common/UpdatePair.h
+++ b/CPP/7zip/UI/Common/UpdatePair.h
@@ -1,7 +1,7 @@
1// UpdatePair.h 1// UpdatePair.h
2 2
3#ifndef __UPDATE_PAIR_H 3#ifndef ZIP7_INC_UPDATE_PAIR_H
4#define __UPDATE_PAIR_H 4#define ZIP7_INC_UPDATE_PAIR_H
5 5
6#include "DirItem.h" 6#include "DirItem.h"
7#include "UpdateAction.h" 7#include "UpdateAction.h"
diff --git a/CPP/7zip/UI/Common/UpdateProduce.h b/CPP/7zip/UI/Common/UpdateProduce.h
index 24bb32e..9db6c1e 100644
--- a/CPP/7zip/UI/Common/UpdateProduce.h
+++ b/CPP/7zip/UI/Common/UpdateProduce.h
@@ -1,7 +1,7 @@
1// UpdateProduce.h 1// UpdateProduce.h
2 2
3#ifndef __UPDATE_PRODUCE_H 3#ifndef ZIP7_INC_UPDATE_PRODUCE_H
4#define __UPDATE_PRODUCE_H 4#define ZIP7_INC_UPDATE_PRODUCE_H
5 5
6#include "UpdatePair.h" 6#include "UpdatePair.h"
7 7
@@ -43,10 +43,13 @@ struct CUpdatePair2
43 {} 43 {}
44}; 44};
45 45
46struct IUpdateProduceCallback 46Z7_PURE_INTERFACES_BEGIN
47
48DECLARE_INTERFACE(IUpdateProduceCallback)
47{ 49{
48 virtual HRESULT ShowDeleteFile(unsigned arcIndex) = 0; 50 virtual HRESULT ShowDeleteFile(unsigned arcIndex) = 0;
49}; 51};
52Z7_PURE_INTERFACES_END
50 53
51void UpdateProduce( 54void UpdateProduce(
52 const CRecordVector<CUpdatePair> &updatePairs, 55 const CRecordVector<CUpdatePair> &updatePairs,
diff --git a/CPP/7zip/UI/Common/WorkDir.cpp b/CPP/7zip/UI/Common/WorkDir.cpp
index 1307cee..cfec635 100644
--- a/CPP/7zip/UI/Common/WorkDir.cpp
+++ b/CPP/7zip/UI/Common/WorkDir.cpp
@@ -2,11 +2,8 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../Common/StringConvert.h"
6#include "../../../Common/Wildcard.h"
7
8#include "../../../Windows/FileFind.h"
9#include "../../../Windows/FileName.h" 5#include "../../../Windows/FileName.h"
6#include "../../../Windows/FileSystem.h"
10 7
11#include "WorkDir.h" 8#include "WorkDir.h"
12 9
@@ -22,10 +19,10 @@ FString GetWorkDir(const NWorkDir::CInfo &workDirInfo, const FString &path, FStr
22 if (workDirInfo.ForRemovableOnly) 19 if (workDirInfo.ForRemovableOnly)
23 { 20 {
24 mode = NWorkDir::NMode::kCurrent; 21 mode = NWorkDir::NMode::kCurrent;
25 FString prefix = path.Left(3); 22 const FString prefix = path.Left(3);
26 if (prefix[1] == FTEXT(':') && prefix[2] == FTEXT('\\')) 23 if (NName::IsDrivePath(prefix))
27 { 24 {
28 UINT driveType = GetDriveType(GetSystemString(prefix, ::AreFileApisANSI() ? CP_ACP : CP_OEMCP)); 25 const UINT driveType = NSystem::MyGetDriveType(prefix);
29 if (driveType == DRIVE_CDROM || driveType == DRIVE_REMOVABLE) 26 if (driveType == DRIVE_CDROM || driveType == DRIVE_REMOVABLE)
30 mode = workDirInfo.Mode; 27 mode = workDirInfo.Mode;
31 } 28 }
@@ -39,29 +36,26 @@ FString GetWorkDir(const NWorkDir::CInfo &workDirInfo, const FString &path, FStr
39 } 36 }
40 #endif 37 #endif
41 38
42 int pos = path.ReverseFind_PathSepar() + 1; 39 const int pos = path.ReverseFind_PathSepar() + 1;
43 fileName = path.Ptr((unsigned)pos); 40 fileName = path.Ptr((unsigned)pos);
44 41
45 switch (mode) 42 FString tempDir;
43 switch ((int)mode)
46 { 44 {
47 case NWorkDir::NMode::kCurrent: 45 case NWorkDir::NMode::kCurrent:
48 { 46 tempDir = path.Left((unsigned)pos);
49 return path.Left((unsigned)pos); 47 break;
50 }
51 case NWorkDir::NMode::kSpecified: 48 case NWorkDir::NMode::kSpecified:
52 { 49 tempDir = workDirInfo.Path;
53 FString tempDir = workDirInfo.Path; 50 break;
54 NName::NormalizeDirPathPrefix(tempDir); 51 // case NWorkDir::NMode::kSystem:
55 return tempDir;
56 }
57 default: 52 default:
58 {
59 FString tempDir;
60 if (!MyGetTempPath(tempDir)) 53 if (!MyGetTempPath(tempDir))
61 throw 141717; 54 throw 141717;
62 return tempDir; 55 break;
63 }
64 } 56 }
57 NName::NormalizeDirPathPrefix(tempDir);
58 return tempDir;
65} 59}
66 60
67HRESULT CWorkDirTempFile::CreateTempFile(const FString &originalPath) 61HRESULT CWorkDirTempFile::CreateTempFile(const FString &originalPath)
@@ -69,9 +63,8 @@ HRESULT CWorkDirTempFile::CreateTempFile(const FString &originalPath)
69 NWorkDir::CInfo workDirInfo; 63 NWorkDir::CInfo workDirInfo;
70 workDirInfo.Load(); 64 workDirInfo.Load();
71 FString namePart; 65 FString namePart;
72 FString workDir = GetWorkDir(workDirInfo, originalPath, namePart); 66 const FString workDir = GetWorkDir(workDirInfo, originalPath, namePart);
73 CreateComplexDir(workDir); 67 CreateComplexDir(workDir);
74 CTempFile tempFile;
75 _outStreamSpec = new COutFileStream; 68 _outStreamSpec = new COutFileStream;
76 OutStream = _outStreamSpec; 69 OutStream = _outStreamSpec;
77 if (!_tempFile.Create(workDir + namePart, &_outStreamSpec->File)) 70 if (!_tempFile.Create(workDir + namePart, &_outStreamSpec->File))
diff --git a/CPP/7zip/UI/Common/WorkDir.h b/CPP/7zip/UI/Common/WorkDir.h
index 75850a9..d32ab9d 100644
--- a/CPP/7zip/UI/Common/WorkDir.h
+++ b/CPP/7zip/UI/Common/WorkDir.h
@@ -1,7 +1,7 @@
1// WorkDir.h 1// WorkDir.h
2 2
3#ifndef __WORK_DIR_H 3#ifndef ZIP7_INC_WORK_DIR_H
4#define __WORK_DIR_H 4#define ZIP7_INC_WORK_DIR_H
5 5
6#include "../../../Windows/FileDir.h" 6#include "../../../Windows/FileDir.h"
7 7
diff --git a/CPP/7zip/UI/Common/ZipRegistry.cpp b/CPP/7zip/UI/Common/ZipRegistry.cpp
index a67a99b..6c1b9c8 100644
--- a/CPP/7zip/UI/Common/ZipRegistry.cpp
+++ b/CPP/7zip/UI/Common/ZipRegistry.cpp
@@ -11,6 +11,7 @@
11#include "../../../Windows/Registry.h" 11#include "../../../Windows/Registry.h"
12#include "../../../Windows/Synchronization.h" 12#include "../../../Windows/Synchronization.h"
13 13
14// #include "../Explorer/ContextMenuFlags.h"
14#include "ZipRegistry.h" 15#include "ZipRegistry.h"
15 16
16using namespace NWindows; 17using namespace NWindows;
@@ -191,6 +192,7 @@ static LPCTSTR const kOptionsKeyName = TEXT("Options");
191 192
192static LPCTSTR const kLevel = TEXT("Level"); 193static LPCTSTR const kLevel = TEXT("Level");
193static LPCTSTR const kDictionary = TEXT("Dictionary"); 194static LPCTSTR const kDictionary = TEXT("Dictionary");
195// static LPCTSTR const kDictionaryChain = TEXT("DictionaryChain");
194static LPCTSTR const kOrder = TEXT("Order"); 196static LPCTSTR const kOrder = TEXT("Order");
195static LPCTSTR const kBlockSize = TEXT("BlockSize"); 197static LPCTSTR const kBlockSize = TEXT("BlockSize");
196static LPCTSTR const kNumThreads = TEXT("NumThreads"); 198static LPCTSTR const kNumThreads = TEXT("NumThreads");
@@ -269,6 +271,7 @@ void CInfo::Save() const
269 271
270 Key_Set_UInt32(fk, kLevel, fo.Level); 272 Key_Set_UInt32(fk, kLevel, fo.Level);
271 Key_Set_UInt32(fk, kDictionary, fo.Dictionary); 273 Key_Set_UInt32(fk, kDictionary, fo.Dictionary);
274 // Key_Set_UInt32(fk, kDictionaryChain, fo.DictionaryChain);
272 Key_Set_UInt32(fk, kOrder, fo.Order); 275 Key_Set_UInt32(fk, kOrder, fo.Order);
273 Key_Set_UInt32(fk, kBlockSize, fo.BlockLogSize); 276 Key_Set_UInt32(fk, kBlockSize, fo.BlockLogSize);
274 Key_Set_UInt32(fk, kNumThreads, fo.NumThreads); 277 Key_Set_UInt32(fk, kNumThreads, fo.NumThreads);
@@ -326,6 +329,7 @@ void CInfo::Load()
326 329
327 Key_Get_UInt32(fk, kLevel, fo.Level); 330 Key_Get_UInt32(fk, kLevel, fo.Level);
328 Key_Get_UInt32(fk, kDictionary, fo.Dictionary); 331 Key_Get_UInt32(fk, kDictionary, fo.Dictionary);
332 // Key_Get_UInt32(fk, kDictionaryChain, fo.DictionaryChain);
329 Key_Get_UInt32(fk, kOrder, fo.Order); 333 Key_Get_UInt32(fk, kOrder, fo.Order);
330 Key_Get_UInt32(fk, kBlockSize, fo.BlockLogSize); 334 Key_Get_UInt32(fk, kBlockSize, fo.BlockLogSize);
331 Key_Get_UInt32(fk, kNumThreads, fo.NumThreads); 335 Key_Get_UInt32(fk, kNumThreads, fo.NumThreads);
@@ -549,7 +553,15 @@ void CContextMenuInfo::Load()
549 553
550 WriteZone = (UInt32)(Int32)-1; 554 WriteZone = (UInt32)(Int32)-1;
551 555
552 Flags = (UInt32)(Int32)-1; 556 /* we can disable email items by default,
557 because email code doesn't work in some systems */
558 Flags = (UInt32)(Int32)-1
559 /*
560 & ~NContextMenuFlags::kCompressEmail
561 & ~NContextMenuFlags::kCompressTo7zEmail
562 & ~NContextMenuFlags::kCompressToZipEmail
563 */
564 ;
553 Flags_Def = false; 565 Flags_Def = false;
554 566
555 CS_LOCK 567 CS_LOCK
diff --git a/CPP/7zip/UI/Common/ZipRegistry.h b/CPP/7zip/UI/Common/ZipRegistry.h
index b7075e6..6bc6977 100644
--- a/CPP/7zip/UI/Common/ZipRegistry.h
+++ b/CPP/7zip/UI/Common/ZipRegistry.h
@@ -1,7 +1,7 @@
1// ZipRegistry.h 1// ZipRegistry.h
2 2
3#ifndef __ZIP_REGISTRY_H 3#ifndef ZIP7_INC_ZIP_REGISTRY_H
4#define __ZIP_REGISTRY_H 4#define ZIP7_INC_ZIP_REGISTRY_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
@@ -81,6 +81,7 @@ namespace NCompression
81 { 81 {
82 UInt32 Level; 82 UInt32 Level;
83 UInt32 Dictionary; 83 UInt32 Dictionary;
84 // UInt32 DictionaryChain;
84 UInt32 Order; 85 UInt32 Order;
85 UInt32 BlockLogSize; 86 UInt32 BlockLogSize;
86 UInt32 NumThreads; 87 UInt32 NumThreads;
@@ -116,6 +117,7 @@ namespace NCompression
116 void ResetForLevelChange() 117 void ResetForLevelChange()
117 { 118 {
118 BlockLogSize = NumThreads = Level = Dictionary = Order = (UInt32)(Int32)-1; 119 BlockLogSize = NumThreads = Level = Dictionary = Order = (UInt32)(Int32)-1;
120 // DictionaryChain = (UInt32)(Int32)-1;
119 Method.Empty(); 121 Method.Empty();
120 // Options.Empty(); 122 // Options.Empty();
121 // EncryptionMethod.Empty(); 123 // EncryptionMethod.Empty();
@@ -133,10 +135,6 @@ namespace NCompression
133 UInt32 Level; 135 UInt32 Level;
134 bool ShowPassword; 136 bool ShowPassword;
135 bool EncryptHeaders; 137 bool EncryptHeaders;
136 UString ArcType;
137 UStringVector ArcPaths;
138
139 CObjectVector<CFormatOptions> Formats;
140 138
141 CBoolPair NtSecurity; 139 CBoolPair NtSecurity;
142 CBoolPair AltStreams; 140 CBoolPair AltStreams;
@@ -145,6 +143,11 @@ namespace NCompression
145 143
146 CBoolPair PreserveATime; 144 CBoolPair PreserveATime;
147 145
146 UString ArcType;
147 UStringVector ArcPaths;
148
149 CObjectVector<CFormatOptions> Formats;
150
148 void Save() const; 151 void Save() const;
149 void Load(); 152 void Load();
150 }; 153 };
@@ -164,8 +167,8 @@ namespace NWorkDir
164 struct CInfo 167 struct CInfo
165 { 168 {
166 NMode::EEnum Mode; 169 NMode::EEnum Mode;
167 FString Path;
168 bool ForRemovableOnly; 170 bool ForRemovableOnly;
171 FString Path;
169 172
170 void SetForRemovableOnlyDefault() { ForRemovableOnly = true; } 173 void SetForRemovableOnlyDefault() { ForRemovableOnly = true; }
171 void SetDefault() 174 void SetDefault()
diff --git a/CPP/7zip/UI/Console/BenchCon.cpp b/CPP/7zip/UI/Console/BenchCon.cpp
index a7c9e67..113f584 100644
--- a/CPP/7zip/UI/Console/BenchCon.cpp
+++ b/CPP/7zip/UI/Console/BenchCon.cpp
@@ -7,13 +7,13 @@
7#include "BenchCon.h" 7#include "BenchCon.h"
8#include "ConsoleClose.h" 8#include "ConsoleClose.h"
9 9
10struct CPrintBenchCallback: public IBenchPrintCallback 10struct CPrintBenchCallback Z7_final: public IBenchPrintCallback
11{ 11{
12 FILE *_file; 12 FILE *_file;
13 13
14 void Print(const char *s); 14 void Print(const char *s) Z7_override;
15 void NewLine(); 15 void NewLine() Z7_override;
16 HRESULT CheckBreak(); 16 HRESULT CheckBreak() Z7_override;
17}; 17};
18 18
19void CPrintBenchCallback::Print(const char *s) 19void CPrintBenchCallback::Print(const char *s)
diff --git a/CPP/7zip/UI/Console/BenchCon.h b/CPP/7zip/UI/Console/BenchCon.h
index c9da1de..844cc2a 100644
--- a/CPP/7zip/UI/Console/BenchCon.h
+++ b/CPP/7zip/UI/Console/BenchCon.h
@@ -1,7 +1,7 @@
1// BenchCon.h 1// BenchCon.h
2 2
3#ifndef __BENCH_CON_H 3#ifndef ZIP7_INC_BENCH_CON_H
4#define __BENCH_CON_H 4#define ZIP7_INC_BENCH_CON_H
5 5
6#include <stdio.h> 6#include <stdio.h>
7 7
diff --git a/CPP/7zip/UI/Console/Console.dsp b/CPP/7zip/UI/Console/Console.dsp
index ea336cf..26e8c7f 100644
--- a/CPP/7zip/UI/Console/Console.dsp
+++ b/CPP/7zip/UI/Console/Console.dsp
@@ -44,7 +44,7 @@ RSC=rc.exe
44# PROP Ignore_Export_Lib 0 44# PROP Ignore_Export_Lib 0
45# PROP Target_Dir "" 45# PROP Target_Dir ""
46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c 46# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
47# 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 47# 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
48# ADD BASE RSC /l 0x419 /d "NDEBUG" 48# ADD BASE RSC /l 0x419 /d "NDEBUG"
49# ADD RSC /l 0x419 /d "NDEBUG" 49# ADD RSC /l 0x419 /d "NDEBUG"
50BSC32=bscmake.exe 50BSC32=bscmake.exe
@@ -69,7 +69,7 @@ LINK32=link.exe
69# PROP Ignore_Export_Lib 0 69# PROP Ignore_Export_Lib 0
70# PROP Target_Dir "" 70# PROP Target_Dir ""
71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c 71# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
72# 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 72# 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
73# ADD BASE RSC /l 0x419 /d "_DEBUG" 73# ADD BASE RSC /l 0x419 /d "_DEBUG"
74# ADD RSC /l 0x419 /d "_DEBUG" 74# ADD RSC /l 0x419 /d "_DEBUG"
75BSC32=bscmake.exe 75BSC32=bscmake.exe
@@ -95,7 +95,7 @@ LINK32=link.exe
95# PROP Ignore_Export_Lib 0 95# PROP Ignore_Export_Lib 0
96# PROP Target_Dir "" 96# PROP Target_Dir ""
97# ADD BASE CPP /nologo /Gz /MD /W3 /GX /O1 /I "../../../" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /c 97# ADD BASE CPP /nologo /Gz /MD /W3 /GX /O1 /I "../../../" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /Yu"StdAfx.h" /FD /c
98# 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 98# 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
99# ADD BASE RSC /l 0x419 /d "NDEBUG" 99# ADD BASE RSC /l 0x419 /d "NDEBUG"
100# ADD RSC /l 0x419 /d "NDEBUG" 100# ADD RSC /l 0x419 /d "NDEBUG"
101BSC32=bscmake.exe 101BSC32=bscmake.exe
@@ -121,7 +121,7 @@ LINK32=link.exe
121# PROP Ignore_Export_Lib 0 121# PROP Ignore_Export_Lib 0
122# PROP Target_Dir "" 122# PROP Target_Dir ""
123# 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 123# 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
124# 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 124# 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
125# ADD BASE RSC /l 0x419 /d "_DEBUG" 125# ADD BASE RSC /l 0x419 /d "_DEBUG"
126# ADD RSC /l 0x419 /d "_DEBUG" 126# ADD RSC /l 0x419 /d "_DEBUG"
127BSC32=bscmake.exe 127BSC32=bscmake.exe
@@ -445,6 +445,14 @@ SOURCE=..\..\..\Common\MyCom.h
445# End Source File 445# End Source File
446# Begin Source File 446# Begin Source File
447 447
448SOURCE=..\..\..\Common\MyGuidDef.h
449# End Source File
450# Begin Source File
451
452SOURCE=..\..\..\Common\MyInitGuid.h
453# End Source File
454# Begin Source File
455
448SOURCE=..\..\..\Common\MyString.cpp 456SOURCE=..\..\..\Common\MyString.cpp
449# End Source File 457# End Source File
450# Begin Source File 458# Begin Source File
@@ -465,6 +473,10 @@ SOURCE=..\..\..\Common\MyVector.h
465# End Source File 473# End Source File
466# Begin Source File 474# Begin Source File
467 475
476SOURCE=..\..\..\Common\MyWindows.h
477# End Source File
478# Begin Source File
479
468SOURCE=..\..\..\Common\NewHandler.cpp 480SOURCE=..\..\..\Common\NewHandler.cpp
469# End Source File 481# End Source File
470# Begin Source File 482# Begin Source File
@@ -761,6 +773,14 @@ SOURCE=..\..\Common\MethodProps.h
761# End Source File 773# End Source File
762# Begin Source File 774# Begin Source File
763 775
776SOURCE=..\..\Common\MultiOutStream.cpp
777# End Source File
778# Begin Source File
779
780SOURCE=..\..\Common\MultiOutStream.h
781# End Source File
782# Begin Source File
783
764SOURCE=..\..\Common\ProgressUtils.cpp 784SOURCE=..\..\Common\ProgressUtils.cpp
765# End Source File 785# End Source File
766# Begin Source File 786# Begin Source File
@@ -849,6 +869,10 @@ SOURCE=..\..\..\..\C\7zTypes.h
849# End Source File 869# End Source File
850# Begin Source File 870# Begin Source File
851 871
872SOURCE=..\..\..\..\C\7zWindows.h
873# End Source File
874# Begin Source File
875
852SOURCE=..\..\..\..\C\Alloc.c 876SOURCE=..\..\..\..\C\Alloc.c
853# SUBTRACT CPP /YX /Yc /Yu 877# SUBTRACT CPP /YX /Yc /Yu
854# End Source File 878# End Source File
@@ -858,6 +882,10 @@ SOURCE=..\..\..\..\C\Alloc.h
858# End Source File 882# End Source File
859# Begin Source File 883# Begin Source File
860 884
885SOURCE=..\..\..\..\C\Compiler.h
886# End Source File
887# Begin Source File
888
861SOURCE=..\..\..\..\C\CpuArch.c 889SOURCE=..\..\..\..\C\CpuArch.c
862# SUBTRACT CPP /YX /Yc /Yu 890# SUBTRACT CPP /YX /Yc /Yu
863# End Source File 891# End Source File
diff --git a/CPP/7zip/UI/Console/Console.mak b/CPP/7zip/UI/Console/Console.mak
index bd4c1da..1a47bfa 100644
--- a/CPP/7zip/UI/Console/Console.mak
+++ b/CPP/7zip/UI/Console/Console.mak
@@ -1,7 +1,7 @@
1MY_CONSOLE = 1 1MY_CONSOLE = 1
2 2
3!IFNDEF UNDER_CE 3!IFNDEF UNDER_CE
4CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -D_7ZIP_LARGE_PAGES -DSUPPORT_DEVICE_FILE 4CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_LARGE_PAGES -DZ7_DEVICE_FILE
5!ENDIF 5!ENDIF
6 6
7CONSOLE_OBJS = \ 7CONSOLE_OBJS = \
@@ -41,3 +41,5 @@ UI_COMMON_OBJS = \
41 41
42C_OBJS = $(C_OBJS) \ 42C_OBJS = $(C_OBJS) \
43 $O\DllSecur.obj \ 43 $O\DllSecur.obj \
44
45# 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 58b68ce..c932b28 100644
--- a/CPP/7zip/UI/Console/Console.manifest
+++ b/CPP/7zip/UI/Console/Console.manifest
@@ -10,4 +10,7 @@
10<!-- Win 8.1 --> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> 10<!-- Win 8.1 --> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
11<!-- Win 10 --> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> 11<!-- Win 10 --> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
12</application></compatibility> 12</application></compatibility>
13<application xmlns="urn:schemas-microsoft-com:asm.v3">
14<windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
15<ws2:longPathAware>true</ws2:longPathAware></windowsSettings></application>
13</assembly> \ No newline at end of file 16</assembly> \ No newline at end of file
diff --git a/CPP/7zip/UI/Console/ConsoleClose.h b/CPP/7zip/UI/Console/ConsoleClose.h
index 9c9e035..25c5d0c 100644
--- a/CPP/7zip/UI/Console/ConsoleClose.h
+++ b/CPP/7zip/UI/Console/ConsoleClose.h
@@ -1,7 +1,7 @@
1// ConsoleClose.h 1// ConsoleClose.h
2 2
3#ifndef __CONSOLE_CLOSE_H 3#ifndef ZIP7_INC_CONSOLE_CLOSE_H
4#define __CONSOLE_CLOSE_H 4#define ZIP7_INC_CONSOLE_CLOSE_H
5 5
6namespace NConsoleClose { 6namespace NConsoleClose {
7 7
@@ -21,7 +21,7 @@ inline bool TestBreakSignal()
21 return (g_BreakCounter != 0); 21 return (g_BreakCounter != 0);
22} 22}
23 23
24class CCtrlHandlerSetter 24class CCtrlHandlerSetter Z7_final
25{ 25{
26 #ifndef _WIN32 26 #ifndef _WIN32
27 void (*memo_sig_int)(int); 27 void (*memo_sig_int)(int);
@@ -29,7 +29,7 @@ class CCtrlHandlerSetter
29 #endif 29 #endif
30public: 30public:
31 CCtrlHandlerSetter(); 31 CCtrlHandlerSetter();
32 virtual ~CCtrlHandlerSetter(); 32 ~CCtrlHandlerSetter();
33}; 33};
34 34
35#endif 35#endif
diff --git a/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp b/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp
index 7f791b0..dd7a214 100644
--- a/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp
+++ b/CPP/7zip/UI/Console/ExtractCallbackConsole.cpp
@@ -11,7 +11,7 @@
11#include "../../../Windows/ErrorMsg.h" 11#include "../../../Windows/ErrorMsg.h"
12#include "../../../Windows/PropVariantConv.h" 12#include "../../../Windows/PropVariantConv.h"
13 13
14#ifndef _7ZIP_ST 14#ifndef Z7_ST
15#include "../../../Windows/Synchronization.h" 15#include "../../../Windows/Synchronization.h"
16#endif 16#endif
17 17
@@ -183,7 +183,7 @@ void CExtractScanConsole::PrintStat(const CDirItemsStat &st)
183 183
184 184
185 185
186#ifndef _7ZIP_ST 186#ifndef Z7_ST
187static NSynchronization::CCriticalSection g_CriticalSection; 187static NSynchronization::CCriticalSection g_CriticalSection;
188#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 188#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
189#else 189#else
@@ -235,7 +235,7 @@ static const char * const k_ErrorFlagsMessages[] =
235 , "CRC Error" 235 , "CRC Error"
236}; 236};
237 237
238STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64 size) 238Z7_COM7F_IMF(CExtractCallbackConsole::SetTotal(UInt64 size))
239{ 239{
240 MT_LOCK 240 MT_LOCK
241 241
@@ -247,7 +247,7 @@ STDMETHODIMP CExtractCallbackConsole::SetTotal(UInt64 size)
247 return CheckBreak2(); 247 return CheckBreak2();
248} 248}
249 249
250STDMETHODIMP CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue) 250Z7_COM7F_IMF(CExtractCallbackConsole::SetCompleted(const UInt64 *completeValue))
251{ 251{
252 MT_LOCK 252 MT_LOCK
253 253
@@ -281,14 +281,14 @@ static void PrintFileInfo(CStdOutStream *_so, const wchar_t *path, const FILETIM
281 } 281 }
282} 282}
283 283
284STDMETHODIMP CExtractCallbackConsole::AskOverwrite( 284Z7_COM7F_IMF(CExtractCallbackConsole::AskOverwrite(
285 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, 285 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize,
286 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, 286 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize,
287 Int32 *answer) 287 Int32 *answer))
288{ 288{
289 MT_LOCK 289 MT_LOCK
290 290
291 RINOK(CheckBreak2()); 291 RINOK(CheckBreak2())
292 292
293 ClosePercentsAndFlush(); 293 ClosePercentsAndFlush();
294 294
@@ -302,7 +302,7 @@ STDMETHODIMP CExtractCallbackConsole::AskOverwrite(
302 302
303 NUserAnswerMode::EEnum overwriteAnswer = ScanUserYesNoAllQuit(_so); 303 NUserAnswerMode::EEnum overwriteAnswer = ScanUserYesNoAllQuit(_so);
304 304
305 switch (overwriteAnswer) 305 switch ((int)overwriteAnswer)
306 { 306 {
307 case NUserAnswerMode::kQuit: return E_ABORT; 307 case NUserAnswerMode::kQuit: return E_ABORT;
308 case NUserAnswerMode::kNo: *answer = NOverwriteAnswer::kNo; break; 308 case NUserAnswerMode::kNo: *answer = NOverwriteAnswer::kNo; break;
@@ -325,7 +325,7 @@ STDMETHODIMP CExtractCallbackConsole::AskOverwrite(
325 return CheckBreak2(); 325 return CheckBreak2();
326} 326}
327 327
328STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position) 328Z7_COM7F_IMF(CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 *position))
329{ 329{
330 MT_LOCK 330 MT_LOCK
331 331
@@ -341,7 +341,7 @@ STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int3
341 case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; requiredLevel = 2; break; 341 case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; requiredLevel = 2; break;
342 case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; requiredLevel = 0; break; 342 case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; requiredLevel = 0; break;
343 default: s = "???"; requiredLevel = 2; 343 default: s = "???"; requiredLevel = 2;
344 }; 344 }
345 345
346 bool show2 = (LogLevel >= requiredLevel && _so); 346 bool show2 = (LogLevel >= requiredLevel && _so);
347 347
@@ -394,11 +394,11 @@ STDMETHODIMP CExtractCallbackConsole::PrepareOperation(const wchar_t *name, Int3
394 return CheckBreak2(); 394 return CheckBreak2();
395} 395}
396 396
397STDMETHODIMP CExtractCallbackConsole::MessageError(const wchar_t *message) 397Z7_COM7F_IMF(CExtractCallbackConsole::MessageError(const wchar_t *message))
398{ 398{
399 MT_LOCK 399 MT_LOCK
400 400
401 RINOK(CheckBreak2()); 401 RINOK(CheckBreak2())
402 402
403 NumFileErrors_in_Current++; 403 NumFileErrors_in_Current++;
404 NumFileErrors++; 404 NumFileErrors++;
@@ -460,7 +460,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &dest)
460 } 460 }
461} 461}
462 462
463STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted) 463Z7_COM7F_IMF(CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encrypted))
464{ 464{
465 MT_LOCK 465 MT_LOCK
466 466
@@ -499,7 +499,7 @@ STDMETHODIMP CExtractCallbackConsole::SetOperationResult(Int32 opRes, Int32 encr
499 return CheckBreak2(); 499 return CheckBreak2();
500} 500}
501 501
502STDMETHODIMP CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) 502Z7_COM7F_IMF(CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name))
503{ 503{
504 if (opRes != NArchive::NExtract::NOperationResult::kOK) 504 if (opRes != NArchive::NExtract::NOperationResult::kOK)
505 { 505 {
@@ -512,7 +512,7 @@ STDMETHODIMP CExtractCallbackConsole::ReportExtractResult(Int32 opRes, Int32 enc
512 512
513 513
514 514
515#ifndef _NO_CRYPTO 515#ifndef Z7_NO_CRYPTO
516 516
517HRESULT CExtractCallbackConsole::SetPassword(const UString &password) 517HRESULT CExtractCallbackConsole::SetPassword(const UString &password)
518{ 518{
@@ -521,7 +521,7 @@ HRESULT CExtractCallbackConsole::SetPassword(const UString &password)
521 return S_OK; 521 return S_OK;
522} 522}
523 523
524STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password) 524Z7_COM7F_IMF(CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password))
525{ 525{
526 COM_TRY_BEGIN 526 COM_TRY_BEGIN
527 MT_LOCK 527 MT_LOCK
@@ -533,7 +533,7 @@ STDMETHODIMP CExtractCallbackConsole::CryptoGetTextPassword(BSTR *password)
533 533
534HRESULT CExtractCallbackConsole::BeforeOpen(const wchar_t *name, bool testMode) 534HRESULT CExtractCallbackConsole::BeforeOpen(const wchar_t *name, bool testMode)
535{ 535{
536 RINOK(CheckBreak2()); 536 RINOK(CheckBreak2())
537 537
538 NumTryArcs++; 538 NumTryArcs++;
539 ThereIsError_in_Current = false; 539 ThereIsError_in_Current = false;
@@ -560,7 +560,7 @@ static AString GetOpenArcErrorMessage(UInt32 errorFlags)
560{ 560{
561 AString s; 561 AString s;
562 562
563 for (unsigned i = 0; i < ARRAY_SIZE(k_ErrorFlagsMessages); i++) 563 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_ErrorFlagsMessages); i++)
564 { 564 {
565 UInt32 f = (1 << i); 565 UInt32 f = (1 << i);
566 if ((errorFlags & f) == 0) 566 if ((errorFlags & f) == 0)
@@ -739,7 +739,7 @@ HRESULT CExtractCallbackConsole::OpenResult(
739 { 739 {
740 if (_so) 740 if (_so)
741 { 741 {
742 RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); 742 RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink))
743 *_so << endl; 743 *_so << endl;
744 } 744 }
745 } 745 }
@@ -753,8 +753,8 @@ HRESULT CExtractCallbackConsole::OpenResult(
753 *_se << kError; 753 *_se << kError;
754 _se->NormalizePrint_wstr(name); 754 _se->NormalizePrint_wstr(name);
755 *_se << endl; 755 *_se << endl;
756 HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); 756 const HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink);
757 RINOK(res); 757 RINOK(res)
758 if (result == S_FALSE) 758 if (result == S_FALSE)
759 { 759 {
760 } 760 }
diff --git a/CPP/7zip/UI/Console/ExtractCallbackConsole.h b/CPP/7zip/UI/Console/ExtractCallbackConsole.h
index 7964813..478b293 100644
--- a/CPP/7zip/UI/Console/ExtractCallbackConsole.h
+++ b/CPP/7zip/UI/Console/ExtractCallbackConsole.h
@@ -1,7 +1,7 @@
1// ExtractCallbackConsole.h 1// ExtractCallbackConsole.h
2 2
3#ifndef __EXTRACT_CALLBACK_CONSOLE_H 3#ifndef ZIP7_INC_EXTRACT_CALLBACK_CONSOLE_H
4#define __EXTRACT_CALLBACK_CONSOLE_H 4#define ZIP7_INC_EXTRACT_CALLBACK_CONSOLE_H
5 5
6#include "../../../Common/StdOutStream.h" 6#include "../../../Common/StdOutStream.h"
7 7
@@ -34,8 +34,10 @@ struct CErrorPathCodes2
34}; 34};
35*/ 35*/
36 36
37class CExtractScanConsole: public IDirItemsCallback 37class CExtractScanConsole Z7_final: public IDirItemsCallback
38{ 38{
39 Z7_IFACE_IMP(IDirItemsCallback)
40
39 CStdOutStream *_so; 41 CStdOutStream *_so;
40 CStdOutStream *_se; 42 CStdOutStream *_se;
41 CPercentPrinter _percent; 43 CPercentPrinter _percent;
@@ -54,8 +56,6 @@ class CExtractScanConsole: public IDirItemsCallback
54 56
55public: 57public:
56 58
57 virtual ~CExtractScanConsole() {}
58
59 void Init(CStdOutStream *outStream, CStdOutStream *errorStream, CStdOutStream *percentStream) 59 void Init(CStdOutStream *outStream, CStdOutStream *errorStream, CStdOutStream *percentStream)
60 { 60 {
61 _so = outStream; 61 _so = outStream;
@@ -67,8 +67,6 @@ public:
67 67
68 void StartScanning(); 68 void StartScanning();
69 69
70 INTERFACE_IDirItemsCallback(;)
71
72 void CloseScanning() 70 void CloseScanning()
73 { 71 {
74 if (NeedPercents()) 72 if (NeedPercents())
@@ -81,16 +79,36 @@ public:
81 79
82 80
83 81
84class CExtractCallbackConsole: 82class CExtractCallbackConsole Z7_final:
83 public IFolderArchiveExtractCallback,
85 public IExtractCallbackUI, 84 public IExtractCallbackUI,
86 // public IArchiveExtractCallbackMessage, 85 // public IArchiveExtractCallbackMessage,
87 public IFolderArchiveExtractCallback2, 86 public IFolderArchiveExtractCallback2,
88 #ifndef _NO_CRYPTO 87 #ifndef Z7_NO_CRYPTO
89 public ICryptoGetTextPassword, 88 public ICryptoGetTextPassword,
90 #endif 89 #endif
91 public COpenCallbackConsole, 90 public COpenCallbackConsole,
92 public CMyUnknownImp 91 public CMyUnknownImp
93{ 92{
93 Z7_COM_QI_BEGIN2(IFolderArchiveExtractCallback)
94 // Z7_COM_QI_ENTRY(IArchiveExtractCallbackMessage)
95 Z7_COM_QI_ENTRY(IFolderArchiveExtractCallback2)
96 #ifndef Z7_NO_CRYPTO
97 Z7_COM_QI_ENTRY(ICryptoGetTextPassword)
98 #endif
99 Z7_COM_QI_END
100 Z7_COM_ADDREF_RELEASE
101
102 Z7_IFACE_COM7_IMP(IProgress)
103 Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback)
104 Z7_IFACE_IMP(IExtractCallbackUI)
105 // Z7_IFACE_COM7_IMP(IArchiveExtractCallbackMessage)
106 Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback2)
107 #ifndef Z7_NO_CRYPTO
108 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
109 #endif
110
111
94 AString _tempA; 112 AString _tempA;
95 UString _tempU; 113 UString _tempU;
96 114
@@ -109,32 +127,7 @@ class CExtractCallbackConsole:
109 if (_so) 127 if (_so)
110 _so->Flush(); 128 _so->Flush();
111 } 129 }
112
113public: 130public:
114 MY_QUERYINTERFACE_BEGIN2(IFolderArchiveExtractCallback)
115 // MY_QUERYINTERFACE_ENTRY(IArchiveExtractCallbackMessage)
116 MY_QUERYINTERFACE_ENTRY(IFolderArchiveExtractCallback2)
117 #ifndef _NO_CRYPTO
118 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword)
119 #endif
120 MY_QUERYINTERFACE_END
121 MY_ADDREF_RELEASE
122
123 STDMETHOD(SetTotal)(UInt64 total);
124 STDMETHOD(SetCompleted)(const UInt64 *completeValue);
125
126 INTERFACE_IFolderArchiveExtractCallback(;)
127
128 INTERFACE_IExtractCallbackUI(;)
129 // INTERFACE_IArchiveExtractCallbackMessage(;)
130 INTERFACE_IFolderArchiveExtractCallback2(;)
131
132 #ifndef _NO_CRYPTO
133
134 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
135
136 #endif
137
138 UInt64 NumTryArcs; 131 UInt64 NumTryArcs;
139 132
140 bool ThereIsError_in_Current; 133 bool ThereIsError_in_Current;
diff --git a/CPP/7zip/UI/Console/HashCon.cpp b/CPP/7zip/UI/Console/HashCon.cpp
index 5a34976..c0e69e2 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)
99static void AddMinuses(AString &s, unsigned num) 99static void AddMinuses(AString &s, unsigned num)
100{ 100{
101 for (unsigned i = 0; i < num; i++) 101 for (unsigned i = 0; i < num; i++)
102 s += '-'; 102 s.Add_Minus();
103} 103}
104 104
105static void AddSpaces_if_Positive(AString &s, int num) 105static 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 f926d4d..ebccb6f 100644
--- a/CPP/7zip/UI/Console/HashCon.h
+++ b/CPP/7zip/UI/Console/HashCon.h
@@ -1,14 +1,19 @@
1// HashCon.h 1// HashCon.h
2 2
3#ifndef __HASH_CON_H 3#ifndef ZIP7_INC_HASH_CON_H
4#define __HASH_CON_H 4#define ZIP7_INC_HASH_CON_H
5 5
6#include "../Common/HashCalc.h" 6#include "../Common/HashCalc.h"
7 7
8#include "UpdateCallbackConsole.h" 8#include "UpdateCallbackConsole.h"
9 9
10class CHashCallbackConsole: public IHashCallbackUI, public CCallbackConsoleBase 10class CHashCallbackConsole Z7_final:
11 public IHashCallbackUI,
12 public CCallbackConsoleBase
11{ 13{
14 Z7_IFACE_IMP(IDirItemsCallback)
15 Z7_IFACE_IMP(IHashCallbackUI)
16
12 UString _fileName; 17 UString _fileName;
13 AString _s; 18 AString _s;
14 19
@@ -33,9 +38,7 @@ class CHashCallbackConsole: public IHashCallbackUI, public CCallbackConsoleBase
33 38
34public: 39public:
35 bool PrintNameInPercents; 40 bool PrintNameInPercents;
36
37 bool PrintHeaders; 41 bool PrintHeaders;
38
39 // bool PrintSize; 42 // bool PrintSize;
40 // bool PrintNewLine; // set it too (false), if you need only hash for single file without LF char. 43 // bool PrintNewLine; // set it too (false), if you need only hash for single file without LF char.
41 AString PrintFields; 44 AString PrintFields;
@@ -48,10 +51,6 @@ public:
48 // , PrintSize(true), 51 // , PrintSize(true),
49 // , PrintNewLine(true) 52 // , PrintNewLine(true)
50 {} 53 {}
51
52 virtual ~CHashCallbackConsole() {}
53
54 INTERFACE_IHashCallbackUI(;)
55}; 54};
56 55
57void PrintHashStat(CStdOutStream &so, const CHashBundle &hb); 56void PrintHashStat(CStdOutStream &so, const CHashBundle &hb);
diff --git a/CPP/7zip/UI/Console/List.cpp b/CPP/7zip/UI/Console/List.cpp
index f764f07..46819f1 100644
--- a/CPP/7zip/UI/Console/List.cpp
+++ b/CPP/7zip/UI/Console/List.cpp
@@ -131,6 +131,8 @@ static const char * const kPropIdToName[] =
131 , "Group ID" 131 , "Group ID"
132 , "Device Major" 132 , "Device Major"
133 , "Device Minor" 133 , "Device Minor"
134 , "Dev Major"
135 , "Dev Minor"
134}; 136};
135 137
136static const char kEmptyAttribChar = '.'; 138static const char kEmptyAttribChar = '.';
@@ -405,13 +407,13 @@ void CFieldPrinter::Init(const CFieldInfoInit *standardFieldTable, unsigned numI
405 for (k = 0; k < fii.PrefixSpacesWidth; k++) 407 for (k = 0; k < fii.PrefixSpacesWidth; k++)
406 LinesString.Add_Space(); 408 LinesString.Add_Space();
407 for (k = 0; k < fii.Width; k++) 409 for (k = 0; k < fii.Width; k++)
408 LinesString += '-'; 410 LinesString.Add_Minus();
409 } 411 }
410} 412}
411 413
412static void GetPropName(PROPID propID, const wchar_t *name, AString &nameA, UString &nameU) 414static void GetPropName(PROPID propID, const wchar_t *name, AString &nameA, UString &nameU)
413{ 415{
414 if (propID < ARRAY_SIZE(kPropIdToName)) 416 if (propID < Z7_ARRAY_SIZE(kPropIdToName))
415 { 417 {
416 nameA = kPropIdToName[propID]; 418 nameA = kPropIdToName[propID];
417 return; 419 return;
@@ -455,13 +457,13 @@ void CFieldPrinter::AddProp(const wchar_t *name, PROPID propID, bool isRawProp)
455HRESULT CFieldPrinter::AddMainProps(IInArchive *archive) 457HRESULT CFieldPrinter::AddMainProps(IInArchive *archive)
456{ 458{
457 UInt32 numProps; 459 UInt32 numProps;
458 RINOK(archive->GetNumberOfProperties(&numProps)); 460 RINOK(archive->GetNumberOfProperties(&numProps))
459 for (UInt32 i = 0; i < numProps; i++) 461 for (UInt32 i = 0; i < numProps; i++)
460 { 462 {
461 CMyComBSTR name; 463 CMyComBSTR name;
462 PROPID propID; 464 PROPID propID;
463 VARTYPE vt; 465 VARTYPE vt;
464 RINOK(archive->GetPropertyInfo(i, &name, &propID, &vt)); 466 RINOK(archive->GetPropertyInfo(i, &name, &propID, &vt))
465 AddProp(name, propID, false); 467 AddProp(name, propID, false);
466 } 468 }
467 return S_OK; 469 return S_OK;
@@ -470,12 +472,12 @@ HRESULT CFieldPrinter::AddMainProps(IInArchive *archive)
470HRESULT CFieldPrinter::AddRawProps(IArchiveGetRawProps *getRawProps) 472HRESULT CFieldPrinter::AddRawProps(IArchiveGetRawProps *getRawProps)
471{ 473{
472 UInt32 numProps; 474 UInt32 numProps;
473 RINOK(getRawProps->GetNumRawProps(&numProps)); 475 RINOK(getRawProps->GetNumRawProps(&numProps))
474 for (UInt32 i = 0; i < numProps; i++) 476 for (UInt32 i = 0; i < numProps; i++)
475 { 477 {
476 CMyComBSTR name; 478 CMyComBSTR name;
477 PROPID propID; 479 PROPID propID;
478 RINOK(getRawProps->GetRawPropInfo(i, &name, &propID)); 480 RINOK(getRawProps->GetRawPropInfo(i, &name, &propID))
479 AddProp(name, propID, true); 481 AddProp(name, propID, true);
480 } 482 }
481 return S_OK; 483 return S_OK;
@@ -516,7 +518,7 @@ static void PrintTime(char *dest, const CListFileTimeDef &t, bool showNS)
516 ConvertUtcFileTimeToString2(t.FT, t.Ns100, dest, prec); 518 ConvertUtcFileTimeToString2(t.FT, t.Ns100, dest, prec);
517} 519}
518 520
519#ifndef _SFX 521#ifndef Z7_SFX
520 522
521static inline char GetHex(Byte value) 523static inline char GetHex(Byte value)
522{ 524{
@@ -585,12 +587,12 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st)
585 587
586 if (f.IsRawProp) 588 if (f.IsRawProp)
587 { 589 {
588 #ifndef _SFX 590 #ifndef Z7_SFX
589 591
590 const void *data; 592 const void *data;
591 UInt32 dataSize; 593 UInt32 dataSize;
592 UInt32 propType; 594 UInt32 propType;
593 RINOK(Arc->GetRawProps->GetRawProp(index, f.PropID, &data, &dataSize, &propType)); 595 RINOK(Arc->GetRawProps->GetRawProp(index, f.PropID, &data, &dataSize, &propType))
594 596
595 if (dataSize != 0) 597 if (dataSize != 0)
596 { 598 {
@@ -600,7 +602,7 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st)
600 { 602 {
601 if (propType != NPropDataType::kRaw) 603 if (propType != NPropDataType::kRaw)
602 return E_FAIL; 604 return E_FAIL;
603 #ifndef _SFX 605 #ifndef Z7_SFX
604 ConvertNtSecureToString((const Byte *)data, dataSize, TempAString); 606 ConvertNtSecureToString((const Byte *)data, dataSize, TempAString);
605 g_StdOut << TempAString; 607 g_StdOut << TempAString;
606 needPrint = false; 608 needPrint = false;
@@ -654,7 +656,7 @@ HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st)
654 break; 656 break;
655 } 657 }
656 default: 658 default:
657 RINOK(Arc->Archive->GetProperty(index, f.PropID, &prop)); 659 RINOK(Arc->Archive->GetProperty(index, f.PropID, &prop))
658 } 660 }
659 if (f.PropID == kpidAttrib && (prop.vt == VT_EMPTY || prop.vt == VT_UI4)) 661 if (f.PropID == kpidAttrib && (prop.vt == VT_EMPTY || prop.vt == VT_UI4))
660 { 662 {
@@ -786,7 +788,7 @@ static HRESULT GetUInt64Value(IInArchive *archive, UInt32 index, PROPID propID,
786 value.Val = 0; 788 value.Val = 0;
787 value.Def = false; 789 value.Def = false;
788 CPropVariant prop; 790 CPropVariant prop;
789 RINOK(archive->GetProperty(index, propID, &prop)); 791 RINOK(archive->GetProperty(index, propID, &prop))
790 value.Def = ConvertPropVariantToUInt64(prop, value.Val); 792 value.Def = ConvertPropVariantToUInt64(prop, value.Val);
791 return S_OK; 793 return S_OK;
792} 794}
@@ -798,7 +800,7 @@ static HRESULT GetItemMTime(IInArchive *archive, UInt32 index, CListFileTimeDef
798 t.Clear(); 800 t.Clear();
799 // t.Def = false; 801 // t.Def = false;
800 CPropVariant prop; 802 CPropVariant prop;
801 RINOK(archive->GetProperty(index, kpidMTime, &prop)); 803 RINOK(archive->GetProperty(index, kpidMTime, &prop))
802 if (prop.vt == VT_FILETIME) 804 if (prop.vt == VT_FILETIME)
803 t.Set_From_Prop(prop); 805 t.Set_From_Prop(prop);
804 else if (prop.vt != VT_EMPTY) 806 else if (prop.vt != VT_EMPTY)
@@ -815,7 +817,7 @@ static void PrintPropName_and_Eq(CStdOutStream &so, PROPID propID)
815{ 817{
816 const char *s; 818 const char *s;
817 char temp[16]; 819 char temp[16];
818 if (propID < ARRAY_SIZE(kPropIdToName)) 820 if (propID < Z7_ARRAY_SIZE(kPropIdToName))
819 s = kPropIdToName[propID]; 821 s = kPropIdToName[propID];
820 else 822 else
821 { 823 {
@@ -868,7 +870,7 @@ static void PrintPropVal_MultiLine(CStdOutStream &so, const wchar_t *val)
868 so << "{"; 870 so << "{";
869 so << endl; 871 so << endl;
870 UString_Replace_CRLF_to_LF(s); 872 UString_Replace_CRLF_to_LF(s);
871 so.Normalize_UString__LF_Allowed(s); 873 so.Normalize_UString_LF_Allowed(s);
872 so << s; 874 so << s;
873 so << endl; 875 so << endl;
874 so << "}"; 876 so << "}";
@@ -919,7 +921,7 @@ static void PrintPropertyPair2(CStdOutStream &so, PROPID propID, const wchar_t *
919static HRESULT PrintArcProp(CStdOutStream &so, IInArchive *archive, PROPID propID, const wchar_t *name) 921static HRESULT PrintArcProp(CStdOutStream &so, IInArchive *archive, PROPID propID, const wchar_t *name)
920{ 922{
921 CPropVariant prop; 923 CPropVariant prop;
922 RINOK(archive->GetArchiveProperty(propID, &prop)); 924 RINOK(archive->GetArchiveProperty(propID, &prop))
923 PrintPropertyPair2(so, propID, name, prop); 925 PrintPropertyPair2(so, propID, name, prop);
924 return S_OK; 926 return S_OK;
925} 927}
@@ -973,20 +975,20 @@ HRESULT Print_OpenArchive_Props(CStdOutStream &so, const CCodecs *codecs, const
973 if (offset != 0) 975 if (offset != 0)
974 PrintPropNameAndNumber_Signed(so, kpidOffset, offset); 976 PrintPropNameAndNumber_Signed(so, kpidOffset, offset);
975 IInArchive *archive = arc.Archive; 977 IInArchive *archive = arc.Archive;
976 RINOK(PrintArcProp(so, archive, kpidPhySize, NULL)); 978 RINOK(PrintArcProp(so, archive, kpidPhySize, NULL))
977 if (er.TailSize != 0) 979 if (er.TailSize != 0)
978 PrintPropNameAndNumber(so, kpidTailSize, er.TailSize); 980 PrintPropNameAndNumber(so, kpidTailSize, er.TailSize);
979 { 981 {
980 UInt32 numProps; 982 UInt32 numProps;
981 RINOK(archive->GetNumberOfArchiveProperties(&numProps)); 983 RINOK(archive->GetNumberOfArchiveProperties(&numProps))
982 984
983 for (UInt32 j = 0; j < numProps; j++) 985 for (UInt32 j = 0; j < numProps; j++)
984 { 986 {
985 CMyComBSTR name; 987 CMyComBSTR name;
986 PROPID propID; 988 PROPID propID;
987 VARTYPE vt; 989 VARTYPE vt;
988 RINOK(archive->GetArchivePropertyInfo(j, &name, &propID, &vt)); 990 RINOK(archive->GetArchivePropertyInfo(j, &name, &propID, &vt))
989 RINOK(PrintArcProp(so, archive, propID, name)); 991 RINOK(PrintArcProp(so, archive, propID, name))
990 } 992 }
991 } 993 }
992 994
@@ -1002,9 +1004,9 @@ HRESULT Print_OpenArchive_Props(CStdOutStream &so, const CCodecs *codecs, const
1002 CMyComBSTR name; 1004 CMyComBSTR name;
1003 PROPID propID; 1005 PROPID propID;
1004 VARTYPE vt; 1006 VARTYPE vt;
1005 RINOK(archive->GetPropertyInfo(j, &name, &propID, &vt)); 1007 RINOK(archive->GetPropertyInfo(j, &name, &propID, &vt))
1006 CPropVariant prop; 1008 CPropVariant prop;
1007 RINOK(archive->GetProperty(mainIndex, propID, &prop)); 1009 RINOK(archive->GetProperty(mainIndex, propID, &prop))
1008 PrintPropertyPair2(so, propID, name, prop); 1010 PrintPropertyPair2(so, propID, name, prop);
1009 } 1011 }
1010 } 1012 }
@@ -1016,7 +1018,7 @@ HRESULT Print_OpenArchive_Props(CStdOutStream &so, const CCodecs *codecs, const
1016HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink); 1018HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink);
1017HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink) 1019HRESULT Print_OpenArchive_Error(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink)
1018{ 1020{
1019 #ifndef _NO_CRYPTO 1021 #ifndef Z7_NO_CRYPTO
1020 if (arcLink.PasswordWasAsked) 1022 if (arcLink.PasswordWasAsked)
1021 so << "Cannot open encrypted archive. Wrong password?"; 1023 so << "Cannot open encrypted archive. Wrong password?";
1022 else 1024 else
@@ -1051,10 +1053,10 @@ HRESULT ListArchives(
1051 bool processAltStreams, bool showAltStreams, 1053 bool processAltStreams, bool showAltStreams,
1052 const NWildcard::CCensorNode &wildcardCensor, 1054 const NWildcard::CCensorNode &wildcardCensor,
1053 bool enableHeaders, bool techMode, 1055 bool enableHeaders, bool techMode,
1054 #ifndef _NO_CRYPTO 1056 #ifndef Z7_NO_CRYPTO
1055 bool &passwordEnabled, UString &password, 1057 bool &passwordEnabled, UString &password,
1056 #endif 1058 #endif
1057 #ifndef _SFX 1059 #ifndef Z7_SFX
1058 const CObjectVector<CProperty> *props, 1060 const CObjectVector<CProperty> *props,
1059 #endif 1061 #endif
1060 UInt64 &numErrors, 1062 UInt64 &numErrors,
@@ -1067,7 +1069,7 @@ HRESULT ListArchives(
1067 1069
1068 CFieldPrinter fp; 1070 CFieldPrinter fp;
1069 if (!techMode) 1071 if (!techMode)
1070 fp.Init(kStandardFieldTable, ARRAY_SIZE(kStandardFieldTable)); 1072 fp.Init(kStandardFieldTable, Z7_ARRAY_SIZE(kStandardFieldTable));
1071 1073
1072 CListStat2 stat2total; 1074 CListStat2 stat2total;
1073 1075
@@ -1128,7 +1130,7 @@ HRESULT ListArchives(
1128 COpenCallbackConsole openCallback; 1130 COpenCallbackConsole openCallback;
1129 openCallback.Init(&g_StdOut, g_ErrStream, NULL); 1131 openCallback.Init(&g_StdOut, g_ErrStream, NULL);
1130 1132
1131 #ifndef _NO_CRYPTO 1133 #ifndef Z7_NO_CRYPTO
1132 1134
1133 openCallback.PasswordIsDefined = passwordEnabled; 1135 openCallback.PasswordIsDefined = passwordEnabled;
1134 openCallback.Password = password; 1136 openCallback.Password = password;
@@ -1142,7 +1144,7 @@ HRESULT ListArchives(
1142 */ 1144 */
1143 1145
1144 COpenOptions options; 1146 COpenOptions options;
1145 #ifndef _SFX 1147 #ifndef Z7_SFX
1146 options.props = props; 1148 options.props = props;
1147 #endif 1149 #endif
1148 options.codecs = codecs; 1150 options.codecs = codecs;
@@ -1229,7 +1231,7 @@ HRESULT ListArchives(
1229 1231
1230 if (enableHeaders) 1232 if (enableHeaders)
1231 { 1233 {
1232 RINOK(Print_OpenArchive_Props(g_StdOut, codecs, arcLink)); 1234 RINOK(Print_OpenArchive_Props(g_StdOut, codecs, arcLink))
1233 1235
1234 g_StdOut << endl; 1236 g_StdOut << endl;
1235 if (techMode) 1237 if (techMode)
@@ -1251,17 +1253,17 @@ HRESULT ListArchives(
1251 if (techMode) 1253 if (techMode)
1252 { 1254 {
1253 fp.Clear(); 1255 fp.Clear();
1254 RINOK(fp.AddMainProps(archive)); 1256 RINOK(fp.AddMainProps(archive))
1255 if (arc.GetRawProps) 1257 if (arc.GetRawProps)
1256 { 1258 {
1257 RINOK(fp.AddRawProps(arc.GetRawProps)); 1259 RINOK(fp.AddRawProps(arc.GetRawProps))
1258 } 1260 }
1259 } 1261 }
1260 1262
1261 CListStat2 stat2; 1263 CListStat2 stat2;
1262 1264
1263 UInt32 numItems; 1265 UInt32 numItems;
1264 RINOK(archive->GetNumberOfItems(&numItems)); 1266 RINOK(archive->GetNumberOfItems(&numItems))
1265 1267
1266 CReadArcItem item; 1268 CReadArcItem item;
1267 UStringVector pathParts; 1269 UStringVector pathParts;
@@ -1275,12 +1277,12 @@ HRESULT ListArchives(
1275 1277
1276 if (stdInMode && res == E_INVALIDARG) 1278 if (stdInMode && res == E_INVALIDARG)
1277 break; 1279 break;
1278 RINOK(res); 1280 RINOK(res)
1279 1281
1280 if (arc.Ask_Aux) 1282 if (arc.Ask_Aux)
1281 { 1283 {
1282 bool isAux; 1284 bool isAux;
1283 RINOK(Archive_IsItem_Aux(archive, i, isAux)); 1285 RINOK(Archive_IsItem_Aux(archive, i, isAux))
1284 if (isAux) 1286 if (isAux)
1285 continue; 1287 continue;
1286 } 1288 }
@@ -1288,12 +1290,12 @@ HRESULT ListArchives(
1288 bool isAltStream = false; 1290 bool isAltStream = false;
1289 if (arc.Ask_AltStream) 1291 if (arc.Ask_AltStream)
1290 { 1292 {
1291 RINOK(Archive_IsItem_AltStream(archive, i, isAltStream)); 1293 RINOK(Archive_IsItem_AltStream(archive, i, isAltStream))
1292 if (isAltStream && !processAltStreams) 1294 if (isAltStream && !processAltStreams)
1293 continue; 1295 continue;
1294 } 1296 }
1295 1297
1296 RINOK(Archive_IsItem_Dir(archive, i, fp.IsDir)); 1298 RINOK(Archive_IsItem_Dir(archive, i, fp.IsDir))
1297 1299
1298 if (fp.IsDir ? listOptions.ExcludeDirItems : listOptions.ExcludeFileItems) 1300 if (fp.IsDir ? listOptions.ExcludeDirItems : listOptions.ExcludeFileItems)
1299 continue; 1301 continue;
@@ -1302,7 +1304,7 @@ HRESULT ListArchives(
1302 { 1304 {
1303 if (isAltStream) 1305 if (isAltStream)
1304 { 1306 {
1305 RINOK(arc.GetItem(i, item)); 1307 RINOK(arc.GetItem(i, item))
1306 if (!CensorNode_CheckPath(wildcardCensor, item)) 1308 if (!CensorNode_CheckPath(wildcardCensor, item))
1307 continue; 1309 continue;
1308 } 1310 }
@@ -1319,9 +1321,9 @@ HRESULT ListArchives(
1319 1321
1320 CListStat st; 1322 CListStat st;
1321 1323
1322 RINOK(GetUInt64Value(archive, i, kpidSize, st.Size)); 1324 RINOK(GetUInt64Value(archive, i, kpidSize, st.Size))
1323 RINOK(GetUInt64Value(archive, i, kpidPackSize, st.PackSize)); 1325 RINOK(GetUInt64Value(archive, i, kpidPackSize, st.PackSize))
1324 RINOK(GetItemMTime(archive, i, st.MTime)); 1326 RINOK(GetItemMTime(archive, i, st.MTime))
1325 1327
1326 if (fp.IsDir) 1328 if (fp.IsDir)
1327 stat2.NumDirs++; 1329 stat2.NumDirs++;
@@ -1331,7 +1333,7 @@ HRESULT ListArchives(
1331 1333
1332 if (isAltStream && !showAltStreams) 1334 if (isAltStream && !showAltStreams)
1333 continue; 1335 continue;
1334 RINOK(fp.PrintItemInfo(i, st)); 1336 RINOK(fp.PrintItemInfo(i, st))
1335 } 1337 }
1336 1338
1337 UInt64 numStreams = stat2.GetNumStreams(); 1339 UInt64 numStreams = stat2.GetNumStreams();
diff --git a/CPP/7zip/UI/Console/List.h b/CPP/7zip/UI/Console/List.h
index 79d2ed4..4969c3e 100644
--- a/CPP/7zip/UI/Console/List.h
+++ b/CPP/7zip/UI/Console/List.h
@@ -1,7 +1,7 @@
1// List.h 1// List.h
2 2
3#ifndef __LIST_H 3#ifndef ZIP7_INC_LIST_H
4#define __LIST_H 4#define ZIP7_INC_LIST_H
5 5
6#include "../../../Common/Wildcard.h" 6#include "../../../Common/Wildcard.h"
7 7
@@ -28,10 +28,10 @@ HRESULT ListArchives(
28 bool processAltStreams, bool showAltStreams, 28 bool processAltStreams, bool showAltStreams,
29 const NWildcard::CCensorNode &wildcardCensor, 29 const NWildcard::CCensorNode &wildcardCensor,
30 bool enableHeaders, bool techMode, 30 bool enableHeaders, bool techMode,
31 #ifndef _NO_CRYPTO 31 #ifndef Z7_NO_CRYPTO
32 bool &passwordEnabled, UString &password, 32 bool &passwordEnabled, UString &password,
33 #endif 33 #endif
34 #ifndef _SFX 34 #ifndef Z7_SFX
35 const CObjectVector<CProperty> *props, 35 const CObjectVector<CProperty> *props,
36 #endif 36 #endif
37 UInt64 &errors, 37 UInt64 &errors,
diff --git a/CPP/7zip/UI/Console/Main.cpp b/CPP/7zip/UI/Console/Main.cpp
index d01aa4d..eb9e2a8 100644
--- a/CPP/7zip/UI/Console/Main.cpp
+++ b/CPP/7zip/UI/Console/Main.cpp
@@ -5,13 +5,39 @@
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#ifdef _WIN32 7#ifdef _WIN32
8#include <Psapi.h> 8
9#ifndef Z7_OLD_WIN_SDK
10
11#if defined(__MINGW32__) || defined(__MINGW64__)
12#include <psapi.h>
9#else 13#else
14#include <Psapi.h>
15#endif
16
17#else // Z7_OLD_WIN_SDK
18
19typedef struct _PROCESS_MEMORY_COUNTERS {
20 DWORD cb;
21 DWORD PageFaultCount;
22 SIZE_T PeakWorkingSetSize;
23 SIZE_T WorkingSetSize;
24 SIZE_T QuotaPeakPagedPoolUsage;
25 SIZE_T QuotaPagedPoolUsage;
26 SIZE_T QuotaPeakNonPagedPoolUsage;
27 SIZE_T QuotaNonPagedPoolUsage;
28 SIZE_T PagefileUsage;
29 SIZE_T PeakPagefileUsage;
30} PROCESS_MEMORY_COUNTERS;
31typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS;
32
33#endif // Z7_OLD_WIN_SDK
34
35#else // _WIN32
10#include <unistd.h> 36#include <unistd.h>
11#include <sys/ioctl.h> 37#include <sys/ioctl.h>
12#include <sys/time.h> 38#include <sys/time.h>
13#include <sys/times.h> 39#include <sys/times.h>
14#endif 40#endif // _WIN32
15 41
16#include "../../../../C/CpuArch.h" 42#include "../../../../C/CpuArch.h"
17 43
@@ -28,13 +54,14 @@
28 54
29#include "../../../Windows/ErrorMsg.h" 55#include "../../../Windows/ErrorMsg.h"
30#include "../../../Windows/TimeUtils.h" 56#include "../../../Windows/TimeUtils.h"
57#include "../../../Windows/FileDir.h"
31 58
32#include "../Common/ArchiveCommandLine.h" 59#include "../Common/ArchiveCommandLine.h"
33#include "../Common/Bench.h" 60#include "../Common/Bench.h"
34#include "../Common/ExitCode.h" 61#include "../Common/ExitCode.h"
35#include "../Common/Extract.h" 62#include "../Common/Extract.h"
36 63
37#ifdef EXTERNAL_CODECS 64#ifdef Z7_EXTERNAL_CODECS
38#include "../Common/LoadCodecs.h" 65#include "../Common/LoadCodecs.h"
39#endif 66#endif
40 67
@@ -48,7 +75,7 @@
48#include "OpenCallbackConsole.h" 75#include "OpenCallbackConsole.h"
49#include "UpdateCallbackConsole.h" 76#include "UpdateCallbackConsole.h"
50 77
51#ifdef PROG_VARIANT_R 78#ifdef Z7_PROG_VARIANT_R
52#include "../../../../C/7zVersion.h" 79#include "../../../../C/7zVersion.h"
53#else 80#else
54#include "../../MyVersion.h" 81#include "../../MyVersion.h"
@@ -59,7 +86,9 @@ using namespace NFile;
59using namespace NCommandLineParser; 86using namespace NCommandLineParser;
60 87
61#ifdef _WIN32 88#ifdef _WIN32
62HINSTANCE g_hInstance = 0; 89extern
90HINSTANCE g_hInstance;
91HINSTANCE g_hInstance = NULL;
63#endif 92#endif
64 93
65extern CStdOutStream *g_StdStream; 94extern CStdOutStream *g_StdStream;
@@ -71,19 +100,21 @@ extern const CCodecInfo *g_Codecs[];
71extern unsigned g_NumHashers; 100extern unsigned g_NumHashers;
72extern const CHasherInfo *g_Hashers[]; 101extern const CHasherInfo *g_Hashers[];
73 102
74#ifdef EXTERNAL_CODECS 103#ifdef Z7_EXTERNAL_CODECS
104extern
105const CExternalCodecs *g_ExternalCodecs_Ptr;
75const CExternalCodecs *g_ExternalCodecs_Ptr; 106const CExternalCodecs *g_ExternalCodecs_Ptr;
76#endif 107#endif
77 108
78DECLARE_AND_SET_CLIENT_VERSION_VAR 109DECLARE_AND_SET_CLIENT_VERSION_VAR
79 110
80#if defined(PROG_VARIANT_Z) 111#if defined(Z7_PROG_VARIANT_Z)
81 #define PROG_POSTFIX "z" 112 #define PROG_POSTFIX "z"
82 #define PROG_POSTFIX_2 " (z)" 113 #define PROG_POSTFIX_2 " (z)"
83#elif defined(PROG_VARIANT_R) 114#elif defined(Z7_PROG_VARIANT_R)
84 #define PROG_POSTFIX "r" 115 #define PROG_POSTFIX "r"
85 #define PROG_POSTFIX_2 " (r)" 116 #define PROG_POSTFIX_2 " (r)"
86#elif !defined(EXTERNAL_CODECS) 117#elif !defined(Z7_EXTERNAL_CODECS)
87 #define PROG_POSTFIX "a" 118 #define PROG_POSTFIX "a"
88 #define PROG_POSTFIX_2 " (a)" 119 #define PROG_POSTFIX_2 " (a)"
89#else 120#else
@@ -130,12 +161,12 @@ static const char * const kHelpString =
130 " -mmt[N] : set number of CPU threads\n" 161 " -mmt[N] : set number of CPU threads\n"
131 " -mx[N] : set compression level: -mx1 (fastest) ... -mx9 (ultra)\n" 162 " -mx[N] : set compression level: -mx1 (fastest) ... -mx9 (ultra)\n"
132 " -o{Directory} : set Output directory\n" 163 " -o{Directory} : set Output directory\n"
133 #ifndef _NO_CRYPTO 164 #ifndef Z7_NO_CRYPTO
134 " -p{Password} : set Password\n" 165 " -p{Password} : set Password\n"
135 #endif 166 #endif
136 " -r[-|0] : Recurse subdirectories for name search\n" 167 " -r[-|0] : Recurse subdirectories for name search\n"
137 " -sa{a|e|s} : set Archive name mode\n" 168 " -sa{a|e|s} : set Archive name mode\n"
138 " -scc{UTF-8|WIN|DOS} : set charset for for console input/output\n" 169 " -scc{UTF-8|WIN|DOS} : set charset for console input/output\n"
139 " -scs{UTF-8|UTF-16LE|UTF-16BE|WIN|DOS|{id}} : set charset for list files\n" 170 " -scs{UTF-8|UTF-16LE|UTF-16BE|WIN|DOS|{id}} : set charset for list files\n"
140 " -scrc[CRC32|CRC64|SHA1|SHA256|*] : set hash function for x, e, h commands\n" 171 " -scrc[CRC32|CRC64|SHA1|SHA256|*] : set hash function for x, e, h commands\n"
141 " -sdel : delete files after compression\n" 172 " -sdel : delete files after compression\n"
@@ -151,7 +182,7 @@ static const char * const kHelpString =
151 " -so : write data to stdout\n" 182 " -so : write data to stdout\n"
152 " -spd : disable wildcard matching for file names\n" 183 " -spd : disable wildcard matching for file names\n"
153 " -spe : eliminate duplication of root folder for extract command\n" 184 " -spe : eliminate duplication of root folder for extract command\n"
154 " -spf : use fully qualified file paths\n" 185 " -spf[2] : use fully qualified file paths\n"
155 " -ssc[-] : set sensitive case mode\n" 186 " -ssc[-] : set sensitive case mode\n"
156 " -sse : stop archive creating, if it can't open some input file\n" 187 " -sse : stop archive creating, if it can't open some input file\n"
157 " -ssp : do not change Last Access Time of source files while archiving\n" 188 " -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
177 208
178#define kDefaultSfxModule "7zCon.sfx" 209#define kDefaultSfxModule "7zCon.sfx"
179 210
180MY_ATTR_NORETURN 211Z7_ATTR_NORETURN
181static void ShowMessageAndThrowException(LPCSTR message, NExitCode::EEnum code) 212static void ShowMessageAndThrowException(LPCSTR message, NExitCode::EEnum code)
182{ 213{
183 if (g_ErrStream) 214 if (g_ErrStream)
@@ -247,9 +278,17 @@ static void ShowProgInfo(CStdOutStream *so)
247 { 278 {
248 const UInt32 numCpus = NWindows::NSystem::GetNumberOfProcessors(); 279 const UInt32 numCpus = NWindows::NSystem::GetNumberOfProcessors();
249 *so << " Threads:" << numCpus; 280 *so << " Threads:" << numCpus;
281 const UInt64 openMAX= NWindows::NSystem::Get_File_OPEN_MAX();
282 *so << " OPEN_MAX:" << openMAX;
283 {
284 FString temp;
285 NDir::MyGetTempPath(temp);
286 if (!temp.IsEqualTo(STRING_PATH_SEPARATOR "tmp" STRING_PATH_SEPARATOR))
287 *so << " temp_path:" << temp;
288 }
250 } 289 }
251 290
252 #ifdef _7ZIP_ASM 291 #ifdef Z7_7ZIP_ASM
253 *so << ", ASM"; 292 *so << ", ASM";
254 #endif 293 #endif
255 294
@@ -313,6 +352,17 @@ static void PrintUInt32(CStdOutStream &so, UInt32 val, unsigned size)
313 PrintStringRight(so, s, size); 352 PrintStringRight(so, s, size);
314} 353}
315 354
355#ifdef Z7_EXTERNAL_CODECS
356static void PrintNumber(CStdOutStream &so, UInt32 val, unsigned numDigits)
357{
358 AString s;
359 s.Add_UInt32(val);
360 while (s.Len() < numDigits)
361 s.InsertAtFront('0');
362 so << s;
363}
364#endif
365
316static void PrintLibIndex(CStdOutStream &so, int libIndex) 366static void PrintLibIndex(CStdOutStream &so, int libIndex)
317{ 367{
318 if (libIndex >= 0) 368 if (libIndex >= 0)
@@ -480,8 +530,12 @@ static void PrintMemUsage(const char *s, UInt64 val)
480 *g_StdStream << " " << s << " Memory ="; 530 *g_StdStream << " " << s << " Memory =";
481 PrintNum(SHIFT_SIZE_VALUE(val, 20), 7); 531 PrintNum(SHIFT_SIZE_VALUE(val, 20), 7);
482 *g_StdStream << " MB"; 532 *g_StdStream << " MB";
483 533 /*
484 #ifdef _7ZIP_LARGE_PAGES 534 *g_StdStream << " =";
535 PrintNum(SHIFT_SIZE_VALUE(val, 10), 9);
536 *g_StdStream << " KB";
537 */
538 #ifdef Z7_LARGE_PAGES
485 AString lp; 539 AString lp;
486 Add_LargePages_String(lp); 540 Add_LargePages_String(lp);
487 if (!lp.IsEmpty()) 541 if (!lp.IsEmpty())
@@ -530,22 +584,27 @@ static void PrintStat()
530 The program with K32GetProcessMemoryInfo will not work on systems before Win7 584 The program with K32GetProcessMemoryInfo will not work on systems before Win7
531 // memDefined = GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m)); 585 // memDefined = GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m));
532 */ 586 */
533 587 const HMODULE kern = ::GetModuleHandleW(L"kernel32.dll");
534 HMODULE kern = ::GetModuleHandleW(L"kernel32.dll"); 588 Func_GetProcessMemoryInfo
535 Func_GetProcessMemoryInfo my_GetProcessMemoryInfo = (Func_GetProcessMemoryInfo) 589 my_GetProcessMemoryInfo = Z7_GET_PROC_ADDRESS(
536 (void *)::GetProcAddress(kern, "K32GetProcessMemoryInfo"); 590 Func_GetProcessMemoryInfo, kern,
591 "K32GetProcessMemoryInfo");
537 if (!my_GetProcessMemoryInfo) 592 if (!my_GetProcessMemoryInfo)
538 { 593 {
539 HMODULE lib = LoadLibraryW(L"Psapi.dll"); 594 const HMODULE lib = LoadLibraryW(L"Psapi.dll");
540 if (lib) 595 if (lib)
541 my_GetProcessMemoryInfo = (Func_GetProcessMemoryInfo)(void *)::GetProcAddress(lib, "GetProcessMemoryInfo"); 596 my_GetProcessMemoryInfo = Z7_GET_PROC_ADDRESS(
597 Func_GetProcessMemoryInfo, lib,
598 "GetProcessMemoryInfo");
542 } 599 }
543 if (my_GetProcessMemoryInfo) 600 if (my_GetProcessMemoryInfo)
544 memDefined = my_GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m)); 601 memDefined = my_GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof(m));
545 // FreeLibrary(lib); 602 // FreeLibrary(lib);
546 603 const
547 Func_QueryProcessCycleTime my_QueryProcessCycleTime = (Func_QueryProcessCycleTime) 604 Func_QueryProcessCycleTime
548 (void *)::GetProcAddress(kern, "QueryProcessCycleTime"); 605 my_QueryProcessCycleTime = Z7_GET_PROC_ADDRESS(
606 Func_QueryProcessCycleTime, kern,
607 "QueryProcessCycleTime");
549 if (my_QueryProcessCycleTime) 608 if (my_QueryProcessCycleTime)
550 cycleDefined = my_QueryProcessCycleTime(GetCurrentProcess(), &cycleTime); 609 cycleDefined = my_QueryProcessCycleTime(GetCurrentProcess(), &cycleTime);
551 } 610 }
@@ -595,6 +654,7 @@ static void PrintStat()
595 #ifndef UNDER_CE 654 #ifndef UNDER_CE
596 if (memDefined) PrintMemUsage("Physical", m.PeakWorkingSetSize); 655 if (memDefined) PrintMemUsage("Physical", m.PeakWorkingSetSize);
597 #endif 656 #endif
657 *g_StdStream << endl;
598} 658}
599 659
600 660
@@ -603,7 +663,7 @@ static void PrintStat()
603static UInt64 Get_timeofday_us() 663static UInt64 Get_timeofday_us()
604{ 664{
605 struct timeval now; 665 struct timeval now;
606 if (gettimeofday(&now, 0 ) == 0) 666 if (gettimeofday(&now, NULL) == 0)
607 return (UInt64)now.tv_sec * 1000000 + (UInt64)now.tv_usec; 667 return (UInt64)now.tv_sec * 1000000 + (UInt64)now.tv_usec;
608 return 0; 668 return 0;
609} 669}
@@ -666,7 +726,7 @@ static void PrintTime(const char *s, UInt64 val, UInt64 total_us, UInt64 kFreq)
666 *g_StdStream << '%'; 726 *g_StdStream << '%';
667} 727}
668 728
669static void PrintStat(UInt64 startTime) 729static void PrintStat(const UInt64 startTime)
670{ 730{
671 tms t; 731 tms t;
672 /* clock_t res = */ times(&t); 732 /* clock_t res = */ times(&t);
@@ -722,9 +782,23 @@ int Main2(
722 #endif 782 #endif
723 783
724 #ifndef _WIN32 784 #ifndef _WIN32
725 UInt64 startTime = Get_timeofday_us(); 785 const UInt64 startTime = Get_timeofday_us();
726 #endif 786 #endif
727 787
788 /*
789 {
790 g_StdOut << "DWORD:" << (unsigned)sizeof(DWORD);
791 g_StdOut << " LONG:" << (unsigned)sizeof(LONG);
792 g_StdOut << " long:" << (unsigned)sizeof(long);
793 #ifdef _WIN64
794 // g_StdOut << " long long:" << (unsigned)sizeof(long long);
795 #endif
796 g_StdOut << " int:" << (unsigned)sizeof(int);
797 g_StdOut << " void*:" << (unsigned)sizeof(void *);
798 g_StdOut << endl;
799 }
800 */
801
728 UStringVector commandStrings; 802 UStringVector commandStrings;
729 803
730 #ifdef _WIN32 804 #ifdef _WIN32
@@ -778,7 +852,7 @@ int Main2(
778 852
779 CStdOutStream *percentsStream = NULL; 853 CStdOutStream *percentsStream = NULL;
780 if (options.Number_for_Percents != k_OutStream_disabled) 854 if (options.Number_for_Percents != k_OutStream_disabled)
781 percentsStream = (options.Number_for_Percents == k_OutStream_stderr) ? &g_StdErr : &g_StdOut;; 855 percentsStream = (options.Number_for_Percents == k_OutStream_stderr) ? &g_StdErr : &g_StdOut;
782 856
783 if (options.HelpMode) 857 if (options.HelpMode)
784 { 858 {
@@ -866,9 +940,9 @@ int Main2(
866 ThrowException_if_Error(codecs->Load()); 940 ThrowException_if_Error(codecs->Load());
867 Codecs_AddHashArcHandler(codecs); 941 Codecs_AddHashArcHandler(codecs);
868 942
869 #ifdef EXTERNAL_CODECS 943 #ifdef Z7_EXTERNAL_CODECS
870 { 944 {
871 g_ExternalCodecs_Ptr = &__externalCodecs; 945 g_ExternalCodecs_Ptr = &_externalCodecs;
872 UString s; 946 UString s;
873 codecs->GetCodecsErrorMessage(s); 947 codecs->GetCodecsErrorMessage(s);
874 if (!s.IsEmpty()) 948 if (!s.IsEmpty())
@@ -886,7 +960,7 @@ int Main2(
886 || options.Command.CommandType == NCommandType::kList 960 || options.Command.CommandType == NCommandType::kList
887 || options.Command.IsFromUpdateGroup())) 961 || options.Command.IsFromUpdateGroup()))
888 { 962 {
889 #ifdef EXTERNAL_CODECS 963 #ifdef Z7_EXTERNAL_CODECS
890 if (!codecs->MainDll_ErrorPath.IsEmpty()) 964 if (!codecs->MainDll_ErrorPath.IsEmpty())
891 { 965 {
892 UString s ("Can't load module: "); 966 UString s ("Can't load module: ");
@@ -918,12 +992,12 @@ int Main2(
918 // excludedFormats.Sort(); 992 // excludedFormats.Sort();
919 } 993 }
920 994
921 #ifdef EXTERNAL_CODECS 995 #ifdef Z7_EXTERNAL_CODECS
922 if (isExtractGroupCommand 996 if (isExtractGroupCommand
923 || options.Command.IsFromUpdateGroup() 997 || options.Command.IsFromUpdateGroup()
924 || options.Command.CommandType == NCommandType::kHash 998 || options.Command.CommandType == NCommandType::kHash
925 || options.Command.CommandType == NCommandType::kBenchmark) 999 || options.Command.CommandType == NCommandType::kBenchmark)
926 ThrowException_if_Error(__externalCodecs.Load()); 1000 ThrowException_if_Error(_externalCodecs.Load());
927 #endif 1001 #endif
928 1002
929 int retCode = NExitCode::kSuccess; 1003 int retCode = NExitCode::kSuccess;
@@ -943,12 +1017,16 @@ int Main2(
943 CStdOutStream &so = (g_StdStream ? *g_StdStream : g_StdOut); 1017 CStdOutStream &so = (g_StdStream ? *g_StdStream : g_StdOut);
944 unsigned i; 1018 unsigned i;
945 1019
946 #ifdef EXTERNAL_CODECS 1020 #ifdef Z7_EXTERNAL_CODECS
947 so << endl << "Libs:" << endl; 1021 so << endl << "Libs:" << endl;
948 for (i = 0; i < codecs->Libs.Size(); i++) 1022 for (i = 0; i < codecs->Libs.Size(); i++)
949 { 1023 {
950 PrintLibIndex(so, (int)i); 1024 PrintLibIndex(so, (int)i);
951 so << ' ' << codecs->Libs[i].Path << endl; 1025 const CCodecLib &lib = codecs->Libs[i];
1026 // if (lib.Version != 0)
1027 so << ": " << (lib.Version >> 16) << ".";
1028 PrintNumber(so, lib.Version & 0xffff, 2);
1029 so << " : " << lib.Path << endl;
952 } 1030 }
953 #endif 1031 #endif
954 1032
@@ -963,7 +1041,7 @@ int Main2(
963 { 1041 {
964 const CArcInfoEx &arc = codecs->Formats[i]; 1042 const CArcInfoEx &arc = codecs->Formats[i];
965 1043
966 #ifdef EXTERNAL_CODECS 1044 #ifdef Z7_EXTERNAL_CODECS
967 PrintLibIndex(so, arc.LibIndex); 1045 PrintLibIndex(so, arc.LibIndex);
968 #else 1046 #else
969 so << " "; 1047 so << " ";
@@ -1063,10 +1141,10 @@ int Main2(
1063 } 1141 }
1064 1142
1065 1143
1066 #ifdef EXTERNAL_CODECS 1144 #ifdef Z7_EXTERNAL_CODECS
1067 1145
1068 UInt32 numMethods; 1146 UInt32 numMethods;
1069 if (codecs->GetNumMethods(&numMethods) == S_OK) 1147 if (_externalCodecs.GetCodecs->GetNumMethods(&numMethods) == S_OK)
1070 for (UInt32 j = 0; j < numMethods; j++) 1148 for (UInt32 j = 0; j < numMethods; j++)
1071 { 1149 {
1072 PrintLibIndex(so, codecs->GetCodec_LibIndex(j)); 1150 PrintLibIndex(so, codecs->GetCodec_LibIndex(j));
@@ -1110,9 +1188,9 @@ int Main2(
1110 so << ' ' << codec.Name << endl; 1188 so << ' ' << codec.Name << endl;
1111 } 1189 }
1112 1190
1113 #ifdef EXTERNAL_CODECS 1191 #ifdef Z7_EXTERNAL_CODECS
1114 1192
1115 numMethods = codecs->GetNumHashers(); 1193 numMethods = _externalCodecs.GetHashers->GetNumHashers();
1116 for (UInt32 j = 0; j < numMethods; j++) 1194 for (UInt32 j = 0; j < numMethods; j++)
1117 { 1195 {
1118 PrintLibIndex(so, codecs->GetHasherLibIndex(j)); 1196 PrintLibIndex(so, codecs->GetHasherLibIndex(j));
@@ -1198,7 +1276,7 @@ int Main2(
1198 CExtractCallbackConsole *ecs = new CExtractCallbackConsole; 1276 CExtractCallbackConsole *ecs = new CExtractCallbackConsole;
1199 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs; 1277 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs;
1200 1278
1201 #ifndef _NO_CRYPTO 1279 #ifndef Z7_NO_CRYPTO
1202 ecs->PasswordIsDefined = options.PasswordEnabled; 1280 ecs->PasswordIsDefined = options.PasswordEnabled;
1203 ecs->Password = options.Password; 1281 ecs->Password = options.Password;
1204 #endif 1282 #endif
@@ -1216,7 +1294,7 @@ int Main2(
1216 COpenCallbackConsole openCallback; 1294 COpenCallbackConsole openCallback;
1217 openCallback.Init(g_StdStream, g_ErrStream); 1295 openCallback.Init(g_StdStream, g_ErrStream);
1218 1296
1219 #ifndef _NO_CRYPTO 1297 #ifndef Z7_NO_CRYPTO
1220 openCallback.PasswordIsDefined = options.PasswordEnabled; 1298 openCallback.PasswordIsDefined = options.PasswordEnabled;
1221 openCallback.Password = options.Password; 1299 openCallback.Password = options.Password;
1222 #endif 1300 #endif
@@ -1230,7 +1308,7 @@ int Main2(
1230 eo.YesToAll = options.YesToAll; 1308 eo.YesToAll = options.YesToAll;
1231 eo.TestMode = options.Command.IsTestCommand(); 1309 eo.TestMode = options.Command.IsTestCommand();
1232 1310
1233 #ifndef _SFX 1311 #ifndef Z7_SFX
1234 eo.Properties = options.Properties; 1312 eo.Properties = options.Properties;
1235 #endif 1313 #endif
1236 1314
@@ -1254,7 +1332,9 @@ int Main2(
1254 ArchivePathsSorted, 1332 ArchivePathsSorted,
1255 ArchivePathsFullSorted, 1333 ArchivePathsFullSorted,
1256 options.Censor.Pairs.Front().Head, 1334 options.Censor.Pairs.Front().Head,
1257 eo, ecs, ecs, hashCalc, errorMessage, stat); 1335 eo,
1336 ecs, ecs, ecs,
1337 hashCalc, errorMessage, stat);
1258 1338
1259 ecs->ClosePercents(); 1339 ecs->ClosePercents();
1260 1340
@@ -1379,7 +1459,7 @@ int Main2(
1379 options.Censor.Pairs.Front().Head, 1459 options.Censor.Pairs.Front().Head,
1380 options.EnableHeaders, 1460 options.EnableHeaders,
1381 options.TechMode, 1461 options.TechMode,
1382 #ifndef _NO_CRYPTO 1462 #ifndef Z7_NO_CRYPTO
1383 options.PasswordEnabled, 1463 options.PasswordEnabled,
1384 options.Password, 1464 options.Password,
1385 #endif 1465 #endif
@@ -1408,7 +1488,7 @@ int Main2(
1408 COpenCallbackConsole openCallback; 1488 COpenCallbackConsole openCallback;
1409 openCallback.Init(g_StdStream, g_ErrStream, percentsStream); 1489 openCallback.Init(g_StdStream, g_ErrStream, percentsStream);
1410 1490
1411 #ifndef _NO_CRYPTO 1491 #ifndef Z7_NO_CRYPTO
1412 bool passwordIsDefined = 1492 bool passwordIsDefined =
1413 (options.PasswordEnabled && !options.Password.IsEmpty()); 1493 (options.PasswordEnabled && !options.Password.IsEmpty());
1414 openCallback.PasswordIsDefined = passwordIsDefined; 1494 openCallback.PasswordIsDefined = passwordIsDefined;
@@ -1422,7 +1502,7 @@ int Main2(
1422 if (percentsStream) 1502 if (percentsStream)
1423 callback.SetWindowWidth(consoleWidth); 1503 callback.SetWindowWidth(consoleWidth);
1424 1504
1425 #ifndef _NO_CRYPTO 1505 #ifndef Z7_NO_CRYPTO
1426 callback.PasswordIsDefined = passwordIsDefined; 1506 callback.PasswordIsDefined = passwordIsDefined;
1427 callback.AskPassword = (options.PasswordEnabled && options.Password.IsEmpty()); 1507 callback.AskPassword = (options.PasswordEnabled && options.Password.IsEmpty());
1428 callback.Password = options.Password; 1508 callback.Password = options.Password;
diff --git a/CPP/7zip/UI/Console/MainAr.cpp b/CPP/7zip/UI/Console/MainAr.cpp
index 0e45312..80f84f5 100644
--- a/CPP/7zip/UI/Console/MainAr.cpp
+++ b/CPP/7zip/UI/Console/MainAr.cpp
@@ -5,6 +5,7 @@
5#ifdef _WIN32 5#ifdef _WIN32
6#include "../../../../C/DllSecur.h" 6#include "../../../../C/DllSecur.h"
7#endif 7#endif
8#include "../../../../C/CpuArch.h"
8 9
9#include "../../../Common/MyException.h" 10#include "../../../Common/MyException.h"
10#include "../../../Common/StdOutStream.h" 11#include "../../../Common/StdOutStream.h"
@@ -56,7 +57,44 @@ static void PrintError(const char *message)
56#define NT_CHECK_FAIL_ACTION *g_StdStream << "Unsupported Windows version"; return NExitCode::kFatalError; 57#define NT_CHECK_FAIL_ACTION *g_StdStream << "Unsupported Windows version"; return NExitCode::kFatalError;
57#endif 58#endif
58 59
59int MY_CDECL main 60static inline bool CheckIsa()
61{
62 // __try
63 {
64 #if defined(__AVX2__)
65 if (!CPU_IsSupported_AVX2())
66 return false;
67 #elif defined(__AVX__)
68 if (!CPU_IsSupported_AVX())
69 return false;
70 #elif defined(__SSE2__) && !defined(MY_CPU_AMD64) || defined(_M_IX86_FP) && (_M_IX86_FP >= 2)
71 if (!CPU_IsSupported_SSE2())
72 return false;
73 #elif defined(__SSE__) && !defined(MY_CPU_AMD64) || defined(_M_IX86_FP) && (_M_IX86_FP >= 1)
74 if (!CPU_IsSupported_SSE() ||
75 !CPU_IsSupported_CMOV())
76 return false;
77 #endif
78 /*
79 __asm
80 {
81 _emit 0fH
82 _emit 038H
83 _emit 0cbH
84 _emit (0c0H + 0 * 8 + 0)
85 }
86 */
87 return true;
88 }
89 /*
90 __except (EXCEPTION_EXECUTE_HANDLER)
91 {
92 return false;
93 }
94 */
95}
96
97int Z7_CDECL main
60( 98(
61 #ifndef _WIN32 99 #ifndef _WIN32
62 int numArgs, char *args[] 100 int numArgs, char *args[]
@@ -66,6 +104,14 @@ int MY_CDECL main
66 g_ErrStream = &g_StdErr; 104 g_ErrStream = &g_StdErr;
67 g_StdStream = &g_StdOut; 105 g_StdStream = &g_StdOut;
68 106
107 // #if (defined(_MSC_VER) && defined(_M_IX86))
108 if (!CheckIsa())
109 {
110 PrintError("ERROR: processor doesn't support required ISA extension");
111 return NExitCode::kFatalError;
112 }
113 // #endif
114
69 NT_CHECK 115 NT_CHECK
70 116
71 NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter; 117 NConsoleClose::CCtrlHandlerSetter ctrlHandlerSetter;
@@ -119,7 +165,7 @@ int MY_CDECL main
119 } 165 }
120 return (NExitCode::kFatalError); 166 return (NExitCode::kFatalError);
121 } 167 }
122 catch(NExitCode::EEnum &exitCode) 168 catch(NExitCode::EEnum exitCode)
123 { 169 {
124 FlushStreams(); 170 FlushStreams();
125 if (g_ErrStream) 171 if (g_ErrStream)
diff --git a/CPP/7zip/UI/Console/OpenCallbackConsole.cpp b/CPP/7zip/UI/Console/OpenCallbackConsole.cpp
index a074fa1..1e7adf5 100644
--- a/CPP/7zip/UI/Console/OpenCallbackConsole.cpp
+++ b/CPP/7zip/UI/Console/OpenCallbackConsole.cpp
@@ -77,17 +77,17 @@ HRESULT COpenCallbackConsole::Open_Finished()
77} 77}
78 78
79 79
80#ifndef _NO_CRYPTO 80#ifndef Z7_NO_CRYPTO
81 81
82HRESULT COpenCallbackConsole::Open_CryptoGetTextPassword(BSTR *password) 82HRESULT COpenCallbackConsole::Open_CryptoGetTextPassword(BSTR *password)
83{ 83{
84 *password = NULL; 84 *password = NULL;
85 RINOK(CheckBreak2()); 85 RINOK(CheckBreak2())
86 86
87 if (!PasswordIsDefined) 87 if (!PasswordIsDefined)
88 { 88 {
89 ClosePercents(); 89 ClosePercents();
90 RINOK(GetPassword_HRESULT(_so, Password)); 90 RINOK(GetPassword_HRESULT(_so, Password))
91 PasswordIsDefined = true; 91 PasswordIsDefined = true;
92 } 92 }
93 return StringToBstr(Password, password); 93 return StringToBstr(Password, password);
diff --git a/CPP/7zip/UI/Console/OpenCallbackConsole.h b/CPP/7zip/UI/Console/OpenCallbackConsole.h
index 075d374..c5b4b45 100644
--- a/CPP/7zip/UI/Console/OpenCallbackConsole.h
+++ b/CPP/7zip/UI/Console/OpenCallbackConsole.h
@@ -1,7 +1,7 @@
1// OpenCallbackConsole.h 1// OpenCallbackConsole.h
2 2
3#ifndef __OPEN_CALLBACK_CONSOLE_H 3#ifndef ZIP7_INC_OPEN_CALLBACK_CONSOLE_H
4#define __OPEN_CALLBACK_CONSOLE_H 4#define ZIP7_INC_OPEN_CALLBACK_CONSOLE_H
5 5
6#include "../../../Common/StdOutStream.h" 6#include "../../../Common/StdOutStream.h"
7 7
@@ -17,10 +17,10 @@ protected:
17 CStdOutStream *_so; 17 CStdOutStream *_so;
18 CStdOutStream *_se; 18 CStdOutStream *_se;
19 19
20 bool _totalFilesDefined;
21 // bool _totalBytesDefined;
22 // UInt64 _totalFiles; 20 // UInt64 _totalFiles;
23 UInt64 _totalBytes; 21 UInt64 _totalBytes;
22 bool _totalFilesDefined;
23 // bool _totalBytesDefined;
24 24
25 bool NeedPercents() const { return _percent._so != NULL; } 25 bool NeedPercents() const { return _percent._so != NULL; }
26 26
@@ -35,12 +35,12 @@ public:
35 } 35 }
36 36
37 COpenCallbackConsole(): 37 COpenCallbackConsole():
38 _totalBytes(0),
38 _totalFilesDefined(false), 39 _totalFilesDefined(false),
39 // _totalBytesDefined(false), 40 // _totalBytesDefined(false),
40 _totalBytes(0),
41 MultiArcMode(false) 41 MultiArcMode(false)
42 42
43 #ifndef _NO_CRYPTO 43 #ifndef Z7_NO_CRYPTO
44 , PasswordIsDefined(false) 44 , PasswordIsDefined(false)
45 // , PasswordWasAsked(false) 45 // , PasswordWasAsked(false)
46 #endif 46 #endif
@@ -56,9 +56,9 @@ public:
56 _percent._so = percentStream; 56 _percent._so = percentStream;
57 } 57 }
58 58
59 INTERFACE_IOpenCallbackUI(;) 59 Z7_IFACE_IMP(IOpenCallbackUI)
60 60
61 #ifndef _NO_CRYPTO 61 #ifndef Z7_NO_CRYPTO
62 bool PasswordIsDefined; 62 bool PasswordIsDefined;
63 // bool PasswordWasAsked; 63 // bool PasswordWasAsked;
64 UString Password; 64 UString Password;
diff --git a/CPP/7zip/UI/Console/PercentPrinter.cpp b/CPP/7zip/UI/Console/PercentPrinter.cpp
index 49d0393..9d392ab 100644
--- a/CPP/7zip/UI/Console/PercentPrinter.cpp
+++ b/CPP/7zip/UI/Console/PercentPrinter.cpp
@@ -79,7 +79,7 @@ void CPercentPrinter::GetPercents()
79 79
80 while (size < kPercentsSize) 80 while (size < kPercentsSize)
81 { 81 {
82 _s += ' '; 82 _s.Add_Space();
83 size++; 83 size++;
84 } 84 }
85 85
@@ -125,8 +125,8 @@ void CPercentPrinter::Print()
125 char s[32]; 125 char s[32];
126 ConvertUInt64ToString(Files, s); 126 ConvertUInt64ToString(Files, s);
127 // unsigned size = (unsigned)strlen(s); 127 // unsigned size = (unsigned)strlen(s);
128 // for (; size < 3; size++) _s += ' '; 128 // for (; size < 3; size++) _s.Add_Space();
129 _s += ' '; 129 _s.Add_Space();
130 _s += s; 130 _s += s;
131 // _s += "f"; 131 // _s += "f";
132 } 132 }
@@ -134,13 +134,13 @@ void CPercentPrinter::Print()
134 134
135 if (!Command.IsEmpty()) 135 if (!Command.IsEmpty())
136 { 136 {
137 _s += ' '; 137 _s.Add_Space();
138 _s += Command; 138 _s += Command;
139 } 139 }
140 140
141 if (!FileName.IsEmpty() && _s.Len() < MaxLen) 141 if (!FileName.IsEmpty() && _s.Len() < MaxLen)
142 { 142 {
143 _s += ' '; 143 _s.Add_Space();
144 144
145 _tempU = FileName; 145 _tempU = FileName;
146 _so->Normalize_UString(_tempU); 146 _so->Normalize_UString(_tempU);
diff --git a/CPP/7zip/UI/Console/PercentPrinter.h b/CPP/7zip/UI/Console/PercentPrinter.h
index 95290b3..4debb3b 100644
--- a/CPP/7zip/UI/Console/PercentPrinter.h
+++ b/CPP/7zip/UI/Console/PercentPrinter.h
@@ -1,7 +1,7 @@
1// PercentPrinter.h 1// PercentPrinter.h
2 2
3#ifndef __PERCENT_PRINTER_H 3#ifndef ZIP7_INC_PERCENT_PRINTER_H
4#define __PERCENT_PRINTER_H 4#define ZIP7_INC_PERCENT_PRINTER_H
5 5
6#include "../../../Common/StdOutStream.h" 6#include "../../../Common/StdOutStream.h"
7 7
diff --git a/CPP/7zip/UI/Console/StdAfx.h b/CPP/7zip/UI/Console/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/UI/Console/StdAfx.h
+++ b/CPP/7zip/UI/Console/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp b/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp
index 1a6b820..85496f5 100644
--- a/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp
+++ b/CPP/7zip/UI/Console/UpdateCallbackConsole.cpp
@@ -7,7 +7,7 @@
7#include "../../../Windows/ErrorMsg.h" 7#include "../../../Windows/ErrorMsg.h"
8#include "../../../Windows/FileName.h" 8#include "../../../Windows/FileName.h"
9 9
10#ifndef _7ZIP_ST 10#ifndef Z7_ST
11#include "../../../Windows/Synchronization.h" 11#include "../../../Windows/Synchronization.h"
12#endif 12#endif
13 13
@@ -19,7 +19,7 @@
19 19
20using namespace NWindows; 20using namespace NWindows;
21 21
22#ifndef _7ZIP_ST 22#ifndef Z7_ST
23static NSynchronization::CCriticalSection g_CriticalSection; 23static NSynchronization::CCriticalSection g_CriticalSection;
24#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 24#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
25#else 25#else
@@ -136,7 +136,7 @@ HRESULT CUpdateCallbackConsole::OpenResult(
136 { 136 {
137 if (_so) 137 if (_so)
138 { 138 {
139 RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink)); 139 RINOK(Print_OpenArchive_Props(*_so, codecs, arcLink))
140 *_so << endl; 140 *_so << endl;
141 } 141 }
142 } 142 }
@@ -150,7 +150,7 @@ HRESULT CUpdateCallbackConsole::OpenResult(
150 _se->NormalizePrint_wstr(name); 150 _se->NormalizePrint_wstr(name);
151 *_se << endl; 151 *_se << endl;
152 HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink); 152 HRESULT res = Print_OpenArchive_Error(*_se, codecs, arcLink);
153 RINOK(res); 153 RINOK(res)
154 _se->Flush(); 154 _se->Flush();
155 } 155 }
156 } 156 }
@@ -333,6 +333,12 @@ HRESULT CUpdateCallbackConsole::FinishArchive(const CFinishArchiveStat &st)
333 s += "Archive size: "; 333 s += "Archive size: ";
334 PrintSize_bytes_Smart(s, st.OutArcFileSize); 334 PrintSize_bytes_Smart(s, st.OutArcFileSize);
335 s.Add_LF(); 335 s.Add_LF();
336 if (st.IsMultiVolMode)
337 {
338 s += "Volumes: ";
339 s.Add_UInt32(st.NumVolumes);
340 s.Add_LF();
341 }
336 *_so << endl; 342 *_so << endl;
337 *_so << s; 343 *_so << s;
338 // *_so << endl; 344 // *_so << endl;
@@ -681,12 +687,12 @@ HRESULT CUpdateCallbackConsole::ReportUpdateOperation(UInt32 op, const wchar_t *
681 687
682/* 688/*
683HRESULT CUpdateCallbackConsole::SetPassword(const UString & 689HRESULT CUpdateCallbackConsole::SetPassword(const UString &
684 #ifndef _NO_CRYPTO 690 #ifndef Z7_NO_CRYPTO
685 password 691 password
686 #endif 692 #endif
687 ) 693 )
688{ 694{
689 #ifndef _NO_CRYPTO 695 #ifndef Z7_NO_CRYPTO
690 PasswordIsDefined = true; 696 PasswordIsDefined = true;
691 Password = password; 697 Password = password;
692 #endif 698 #endif
@@ -700,7 +706,7 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword2(Int32 *passwordIsDefined,
700 706
701 *password = NULL; 707 *password = NULL;
702 708
703 #ifdef _NO_CRYPTO 709 #ifdef Z7_NO_CRYPTO
704 710
705 *passwordIsDefined = false; 711 *passwordIsDefined = false;
706 return S_OK; 712 return S_OK;
@@ -711,7 +717,7 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword2(Int32 *passwordIsDefined,
711 { 717 {
712 if (AskPassword) 718 if (AskPassword)
713 { 719 {
714 RINOK(GetPassword_HRESULT(_so, Password)); 720 RINOK(GetPassword_HRESULT(_so, Password))
715 PasswordIsDefined = true; 721 PasswordIsDefined = true;
716 } 722 }
717 } 723 }
@@ -729,7 +735,7 @@ HRESULT CUpdateCallbackConsole::CryptoGetTextPassword(BSTR *password)
729 735
730 *password = NULL; 736 *password = NULL;
731 737
732 #ifdef _NO_CRYPTO 738 #ifdef Z7_NO_CRYPTO
733 739
734 return E_NOTIMPL; 740 return E_NOTIMPL;
735 741
diff --git a/CPP/7zip/UI/Console/UpdateCallbackConsole.h b/CPP/7zip/UI/Console/UpdateCallbackConsole.h
index b7ffef0..b6c1be4 100644
--- a/CPP/7zip/UI/Console/UpdateCallbackConsole.h
+++ b/CPP/7zip/UI/Console/UpdateCallbackConsole.h
@@ -1,7 +1,7 @@
1// UpdateCallbackConsole.h 1// UpdateCallbackConsole.h
2 2
3#ifndef __UPDATE_CALLBACK_CONSOLE_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_CONSOLE_H
4#define __UPDATE_CALLBACK_CONSOLE_H 4#define ZIP7_INC_UPDATE_CALLBACK_CONSOLE_H
5 5
6#include "../../../Common/StdOutStream.h" 6#include "../../../Common/StdOutStream.h"
7 7
@@ -26,6 +26,7 @@ struct CErrorPathCodes
26 } 26 }
27}; 27};
28 28
29
29class CCallbackConsoleBase 30class CCallbackConsoleBase
30{ 31{
31protected: 32protected:
@@ -42,7 +43,7 @@ protected:
42 HRESULT ReadingFileError_Base(const FString &name, DWORD systemError); 43 HRESULT ReadingFileError_Base(const FString &name, DWORD systemError);
43 44
44public: 45public:
45 bool NeedPercents() const { return _percent._so != NULL; }; 46 bool NeedPercents() const { return _percent._so != NULL; }
46 47
47 bool StdOutMode; 48 bool StdOutMode;
48 49
@@ -94,29 +95,32 @@ public:
94 // void PrintPropInfo(UString &s, PROPID propID, const PROPVARIANT *value); 95 // void PrintPropInfo(UString &s, PROPID propID, const PROPVARIANT *value);
95}; 96};
96 97
97class CUpdateCallbackConsole: public IUpdateCallbackUI2, public CCallbackConsoleBase 98
99class CUpdateCallbackConsole Z7_final:
100 public IUpdateCallbackUI2,
101 public CCallbackConsoleBase
98{ 102{
99 // void PrintPropPair(const char *name, const wchar_t *val); 103 // void PrintPropPair(const char *name, const wchar_t *val);
100 104 Z7_IFACE_IMP(IUpdateCallbackUI)
105 Z7_IFACE_IMP(IDirItemsCallback)
106 Z7_IFACE_IMP(IUpdateCallbackUI2)
101public: 107public:
102 bool DeleteMessageWasShown; 108 bool DeleteMessageWasShown;
103 109
104 #ifndef _NO_CRYPTO 110 #ifndef Z7_NO_CRYPTO
105 bool PasswordIsDefined; 111 bool PasswordIsDefined;
106 UString Password;
107 bool AskPassword; 112 bool AskPassword;
113 UString Password;
108 #endif 114 #endif
109 115
110 CUpdateCallbackConsole(): 116 CUpdateCallbackConsole():
111 DeleteMessageWasShown(false) 117 DeleteMessageWasShown(false)
112 #ifndef _NO_CRYPTO 118 #ifndef Z7_NO_CRYPTO
113 , PasswordIsDefined(false) 119 , PasswordIsDefined(false)
114 , AskPassword(false) 120 , AskPassword(false)
115 #endif 121 #endif
116 {} 122 {}
117 123
118 virtual ~CUpdateCallbackConsole() {}
119
120 /* 124 /*
121 void Init(CStdOutStream *outStream) 125 void Init(CStdOutStream *outStream)
122 { 126 {
@@ -124,7 +128,6 @@ public:
124 } 128 }
125 */ 129 */
126 // ~CUpdateCallbackConsole() { if (NeedPercents()) _percent.ClosePrint(); } 130 // ~CUpdateCallbackConsole() { if (NeedPercents()) _percent.ClosePrint(); }
127 INTERFACE_IUpdateCallbackUI2(;)
128}; 131};
129 132
130#endif 133#endif
diff --git a/CPP/7zip/UI/Console/UserInputUtils.cpp b/CPP/7zip/UI/Console/UserInputUtils.cpp
index 93f60eb..04d675e 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)
73 73
74 #ifdef MY_DISABLE_ECHO 74 #ifdef MY_DISABLE_ECHO
75 75
76 HANDLE console = GetStdHandle(STD_INPUT_HANDLE); 76 const HANDLE console = GetStdHandle(STD_INPUT_HANDLE);
77
78 /*
79 GetStdHandle() returns
80 INVALID_HANDLE_VALUE: If the function fails.
81 NULL : If an application does not have associated standard handles,
82 such as a service running on an interactive desktop,
83 and has not redirected them. */
77 bool wasChanged = false; 84 bool wasChanged = false;
78 DWORD mode = 0; 85 DWORD mode = 0;
79 if (console != INVALID_HANDLE_VALUE && console != 0) 86 if (console != INVALID_HANDLE_VALUE && console != NULL)
80 if (GetConsoleMode(console, &mode)) 87 if (GetConsoleMode(console, &mode))
81 wasChanged = (SetConsoleMode(console, mode & ~(DWORD)ENABLE_ECHO_INPUT) != 0); 88 wasChanged = (SetConsoleMode(console, mode & ~(DWORD)ENABLE_ECHO_INPUT) != 0);
82 bool res = g_StdIn.ScanUStringUntilNewLine(psw); 89 const bool res = g_StdIn.ScanUStringUntilNewLine(psw);
83 if (wasChanged) 90 if (wasChanged)
84 SetConsoleMode(console, mode); 91 SetConsoleMode(console, mode);
85 92
86 #else 93 #else
87 94
88 bool res = g_StdIn.ScanUStringUntilNewLine(psw); 95 const bool res = g_StdIn.ScanUStringUntilNewLine(psw);
89 96
90 #endif 97 #endif
91 98
diff --git a/CPP/7zip/UI/Console/UserInputUtils.h b/CPP/7zip/UI/Console/UserInputUtils.h
index 256feaf..695a3e6 100644
--- a/CPP/7zip/UI/Console/UserInputUtils.h
+++ b/CPP/7zip/UI/Console/UserInputUtils.h
@@ -1,7 +1,7 @@
1// UserInputUtils.h 1// UserInputUtils.h
2 2
3#ifndef __USER_INPUT_UTILS_H 3#ifndef ZIP7_INC_USER_INPUT_UTILS_H
4#define __USER_INPUT_UTILS_H 4#define ZIP7_INC_USER_INPUT_UTILS_H
5 5
6#include "../../../Common/StdOutStream.h" 6#include "../../../Common/StdOutStream.h"
7 7
diff --git a/CPP/7zip/UI/Console/makefile b/CPP/7zip/UI/Console/makefile
index acc3f10..a20b0cc 100644
--- a/CPP/7zip/UI/Console/makefile
+++ b/CPP/7zip/UI/Console/makefile
@@ -1,6 +1,6 @@
1PROG = 7z.exe 1PROG = 7z.exe
2CFLAGS = $(CFLAGS) \ 2CFLAGS = $(CFLAGS) \
3 -DEXTERNAL_CODECS \ 3 -DZ7_EXTERNAL_CODECS \
4 4
5COMMON_OBJS = \ 5COMMON_OBJS = \
6 $O\CommandLineParser.obj \ 6 $O\CommandLineParser.obj \
@@ -42,6 +42,7 @@ WIN_OBJS = \
42 $O\FilterCoder.obj \ 42 $O\FilterCoder.obj \
43 $O\LimitedStreams.obj \ 43 $O\LimitedStreams.obj \
44 $O\MethodProps.obj \ 44 $O\MethodProps.obj \
45 $O\MultiOutStream.obj \
45 $O\ProgressUtils.obj \ 46 $O\ProgressUtils.obj \
46 $O\PropId.obj \ 47 $O\PropId.obj \
47 $O\StreamObjects.obj \ 48 $O\StreamObjects.obj \
diff --git a/CPP/7zip/UI/Console/makefile.gcc b/CPP/7zip/UI/Console/makefile.gcc
index d7e4447..8a293d8 100644
--- a/CPP/7zip/UI/Console/makefile.gcc
+++ b/CPP/7zip/UI/Console/makefile.gcc
@@ -20,7 +20,7 @@ endif
20 20
21ifdef ST_MODE 21ifdef ST_MODE
22 22
23LOCAL_FLAGS_ST = -D_7ZIP_ST 23LOCAL_FLAGS_ST = -DZ7_ST
24 24
25ifdef IS_MINGW 25ifdef IS_MINGW
26MT_OBJS = \ 26MT_OBJS = \
@@ -43,9 +43,9 @@ LOCAL_FLAGS_WIN=
43ifdef IS_MINGW 43ifdef IS_MINGW
44 44
45LOCAL_FLAGS_WIN = \ 45LOCAL_FLAGS_WIN = \
46 -D_7ZIP_LARGE_PAGES \ 46 -DZ7_LARGE_PAGES \
47 -DWIN_LONG_PATH \ 47 -DZ7_LONG_PATH \
48 -DSUPPORT_DEVICE_FILE \ 48 -DZ7_DEVICE_FILE \
49 49
50SYS_OBJS = \ 50SYS_OBJS = \
51 $O/FileSystem.o \ 51 $O/FileSystem.o \
@@ -66,7 +66,7 @@ endif
66LOCAL_FLAGS = \ 66LOCAL_FLAGS = \
67 $(LOCAL_FLAGS_WIN) \ 67 $(LOCAL_FLAGS_WIN) \
68 $(LOCAL_FLAGS_ST) \ 68 $(LOCAL_FLAGS_ST) \
69 -DEXTERNAL_CODECS \ 69 -DZ7_EXTERNAL_CODECS \
70 70
71 71
72 72
@@ -147,6 +147,7 @@ WIN_OBJS = \
147 $O/LimitedStreams.o \ 147 $O/LimitedStreams.o \
148 $O/MethodId.o \ 148 $O/MethodId.o \
149 $O/MethodProps.o \ 149 $O/MethodProps.o \
150 $O/MultiOutStream.o \
150 $O/OffsetStream.o \ 151 $O/OffsetStream.o \
151 $O/OutBuffer.o \ 152 $O/OutBuffer.o \
152 $O/ProgressUtils.o \ 153 $O/ProgressUtils.o \
diff --git a/CPP/7zip/UI/Explorer/ContextMenu.cpp b/CPP/7zip/UI/Explorer/ContextMenu.cpp
index 7dbb504..7815e13 100644
--- a/CPP/7zip/UI/Explorer/ContextMenu.cpp
+++ b/CPP/7zip/UI/Explorer/ContextMenu.cpp
@@ -9,12 +9,12 @@
9#include "../../../Windows/COM.h" 9#include "../../../Windows/COM.h"
10#include "../../../Windows/DLL.h" 10#include "../../../Windows/DLL.h"
11#include "../../../Windows/FileDir.h" 11#include "../../../Windows/FileDir.h"
12#include "../../../Windows/FileFind.h"
13#include "../../../Windows/FileName.h" 12#include "../../../Windows/FileName.h"
14#include "../../../Windows/MemoryGlobal.h"
15#include "../../../Windows/Menu.h" 13#include "../../../Windows/Menu.h"
16#include "../../../Windows/ProcessUtils.h" 14#include "../../../Windows/ProcessUtils.h"
17#include "../../../Windows/Shell.h" 15
16// for IS_INTRESOURCE():
17#include "../../../Windows/Window.h"
18 18
19#include "../../PropID.h" 19#include "../../PropID.h"
20 20
@@ -24,11 +24,8 @@
24#include "../Common/ZipRegistry.h" 24#include "../Common/ZipRegistry.h"
25 25
26#include "../FileManager/FormatUtils.h" 26#include "../FileManager/FormatUtils.h"
27#include "../FileManager/PropertyName.h"
28
29#ifdef LANG
30#include "../FileManager/LangUtils.h" 27#include "../FileManager/LangUtils.h"
31#endif 28#include "../FileManager/PropertyName.h"
32 29
33#include "ContextMenu.h" 30#include "ContextMenu.h"
34#include "ContextMenuFlags.h" 31#include "ContextMenuFlags.h"
@@ -36,6 +33,7 @@
36 33
37#include "resource.h" 34#include "resource.h"
38 35
36
39// #define SHOW_DEBUG_CTX_MENU 37// #define SHOW_DEBUG_CTX_MENU
40 38
41#ifdef SHOW_DEBUG_CTX_MENU 39#ifdef SHOW_DEBUG_CTX_MENU
@@ -56,50 +54,117 @@ extern LONG g_DllRefCount;
56extern HINSTANCE g_hInstance; 54extern HINSTANCE g_hInstance;
57#endif 55#endif
58 56
57#ifdef UNDER_CE
58 #define MY_IS_INTRESOURCE(_r) ((((ULONG_PTR)(_r)) >> 16) == 0)
59#else
60 #define MY_IS_INTRESOURCE(_r) IS_INTRESOURCE(_r)
61#endif
62
63
59#ifdef SHOW_DEBUG_CTX_MENU 64#ifdef SHOW_DEBUG_CTX_MENU
60 65
61void Print_Ptr(void *p, char *s) 66static void PrintStringA(const char *name, LPCSTR ptr)
62{ 67{
63 char temp[64]; 68 AString m;
64 ConvertUInt64ToHex((UInt64)(void *)p, temp); 69 m += name;
65 AString s2; 70 m += ": ";
66 s2 += temp; 71 char s[32];
67 s2.Add_Space(); 72 sprintf(s, "%p", (const void *)ptr);
68 s2 += s; 73 m += s;
69 OutputDebugStringA(s2); 74 if (!MY_IS_INTRESOURCE(ptr))
75 {
76 m += ": \"";
77 m += ptr;
78 m += "\"";
79 }
80 OutputDebugStringA(m);
70} 81}
71 82
72void Print_Number(UInt32 number, char *s) 83#if !defined(UNDER_CE)
84static void PrintStringW(const char *name, LPCWSTR ptr)
73{ 85{
74 char temp[64]; 86 UString m;
75 ConvertUInt64ToString(number, temp); 87 m += name;
76 AString s2; 88 m += ": ";
77 s2 += temp; 89 char s[32];
78 s2.Add_Space(); 90 sprintf(s, "%p", (const void *)ptr);
79 s2 += s; 91 m += s;
80 OutputDebugStringA(s2); 92 if (!MY_IS_INTRESOURCE(ptr))
93 {
94 m += ": \"";
95 m += ptr;
96 m += "\"";
97 }
98 OutputDebugStringW(m);
81} 99}
100#endif
82 101
83#define ODS(sz) Print_Ptr(this, sz) 102static void Print_Ptr(const void *p, const char *s)
84#define ODS_U(s) OutputDebugStringW(s); 103{
85// #define ODS(sz) 104 char temp[32];
86// #define ODS_U(s) 105 sprintf(temp, "%p", (const void *)p);
106 AString m;
107 m += temp;
108 m.Add_Space();
109 m += s;
110 OutputDebugStringA(m);
111}
112
113static void Print_Number(UInt32 number, const char *s)
114{
115 AString m;
116 m.Add_UInt32(number);
117 m.Add_Space();
118 m += s;
119 OutputDebugStringA(m);
120}
87 121
88#define ODS2(sz) Print_Ptr(this, sz) 122#define ODS(sz) { Print_Ptr(this, sz); }
123#define ODS_U(s) { OutputDebugStringW(s); }
124#define ODS_(op) { op; }
125#define ODS_SPRF_s(x) { char s[256]; x; OutputDebugStringA(s); }
89 126
90#else 127#else
91 128
92#define Print_Number(number, s)
93#define ODS(sz) 129#define ODS(sz)
94#define ODS_U(s) 130#define ODS_U(s)
95#define ODS2(sz) 131#define ODS_(op)
132#define ODS_SPRF_s(x)
96 133
97#endif 134#endif
98 135
99 136
137/*
138DOCs: In Windows 7 and later, the number of items passed to
139 a verb is limited to 16 when a shortcut menu is queried.
140 The verb is then re-created and re-initialized with the full
141 selection when that verb is invoked.
142win10 tests:
143 if (the number of selected file/dir objects > 16)
144 {
145 Explorer does the following actions:
146 - it creates ctx_menu_1 IContextMenu object
147 - it calls ctx_menu_1->Initialize() with list of only up to 16 items
148 - it calls ctx_menu_1->QueryContextMenu(menu_1)
149 - if (some menu command is pressed)
150 {
151 - it gets shown string from selected menu item : shown_menu_1_string
152 - it creates another ctx_menu_2 IContextMenu object
153 - it calls ctx_menu_2->Initialize() with list of all items
154 - it calls ctx_menu_2->QueryContextMenu(menu_2)
155 - if there is menu item with shown_menu_1_string string in menu_2,
156 Explorer calls ctx_menu_2->InvokeCommand() for that item.
157 Explorer probably doesn't use VERB from first object ctx_menu_1.
158 So we must provide same shown menu strings for both objects:
159 ctx_menu_1 and ctx_menu_2.
160 }
161 }
162*/
163
100 164
101CZipContextMenu::CZipContextMenu(): 165CZipContextMenu::CZipContextMenu():
102 _isMenuForFM(false), 166 _isMenuForFM(true),
167 _fileNames_WereReduced(true),
103 _dropMode(false), 168 _dropMode(false),
104 _bitmap(NULL), 169 _bitmap(NULL),
105 _writeZone((UInt32)(Int32)-1), 170 _writeZone((UInt32)(Int32)-1),
@@ -107,87 +172,81 @@ CZipContextMenu::CZipContextMenu():
107 IsRoot(true), 172 IsRoot(true),
108 CurrentSubCommand(0) 173 CurrentSubCommand(0)
109{ 174{
110 ODS("-- CZipContextMenu()"); 175 ODS("== CZipContextMenu()");
111
112 InterlockedIncrement(&g_DllRefCount); 176 InterlockedIncrement(&g_DllRefCount);
113 _bitmap = ::LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_MENU_LOGO));
114} 177}
115 178
116CZipContextMenu::~CZipContextMenu() 179CZipContextMenu::~CZipContextMenu()
117{ 180{
118 ODS("== ~CZipContextMenu"); 181 ODS("== ~CZipContextMenu");
119 if (_bitmap != NULL) 182 if (_bitmap)
120 DeleteObject(_bitmap); 183 DeleteObject(_bitmap);
121 InterlockedDecrement(&g_DllRefCount); 184 InterlockedDecrement(&g_DllRefCount);
122} 185}
123 186
124HRESULT CZipContextMenu::GetFileNames(LPDATAOBJECT dataObject, UStringVector &fileNames)
125{
126 fileNames.Clear();
127 if (!dataObject)
128 return E_INVALIDARG;
129
130 #ifndef UNDER_CE
131
132 FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
133 NCOM::CStgMedium stgMedium;
134 HRESULT result = dataObject->GetData(&fmte, &stgMedium);
135 if (result != S_OK)
136 return result;
137 stgMedium._mustBeReleased = true;
138
139 NShell::CDrop drop(false);
140 NMemory::CGlobalLock globalLock(stgMedium->hGlobal);
141 drop.Attach((HDROP)globalLock.GetPointer());
142 drop.QueryFileNames(fileNames);
143
144 #endif
145
146 return S_OK;
147}
148
149// IShellExtInit 187// IShellExtInit
150 188
151STDMETHODIMP CZipContextMenu::Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY /* hkeyProgID */) 189/*
190IShellExtInit::Initialize()
191 pidlFolder:
192 - for property sheet extension:
193 NULL
194 - for shortcut menu extensions:
195 pidl of folder that contains the item whose shortcut menu is being displayed:
196 - for nondefault drag-and-drop menu extensions:
197 pidl of target folder: for nondefault drag-and-drop menu extensions
198 pidlFolder == NULL in (win10): for context menu
199*/
200
201Z7_COMWF_B CZipContextMenu::Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY /* hkeyProgID */)
152{ 202{
153 // OutputDebugString(TEXT("::Initialize\r\n")); 203 COM_TRY_BEGIN
204 ODS("==== CZipContextMenu::Initialize START")
205 _isMenuForFM = false;
206 _fileNames_WereReduced = true;
154 _dropMode = false; 207 _dropMode = false;
208 _attribs.Clear();
209 _fileNames.Clear();
155 _dropPath.Empty(); 210 _dropPath.Empty();
156 if (pidlFolder != 0) 211
212 if (pidlFolder)
157 { 213 {
158 #ifndef UNDER_CE 214 ODS("==== CZipContextMenu::Initialize (pidlFolder != 0)")
215 #ifndef UNDER_CE
159 if (NShell::GetPathFromIDList(pidlFolder, _dropPath)) 216 if (NShell::GetPathFromIDList(pidlFolder, _dropPath))
160 { 217 {
161 // OutputDebugString(path); 218 ODS("==== CZipContextMenu::Initialize path from (pidl):")
162 // OutputDebugString(TEXT("\r\n")); 219 ODS_U(_dropPath);
220 /* win10 : path with "\\\\?\\\" prefix is returned by GetPathFromIDList, if path is long
221 we can remove super prefix here. But probably prefix
222 is not problem for following 7-zip code.
223 so we don't remove super prefix */
224 NFile::NName::If_IsSuperPath_RemoveSuperPrefix(_dropPath);
163 NName::NormalizeDirPathPrefix(_dropPath); 225 NName::NormalizeDirPathPrefix(_dropPath);
164 _dropMode = !_dropPath.IsEmpty(); 226 _dropMode = !_dropPath.IsEmpty();
165 } 227 }
166 else 228 else
167 #endif 229 #endif
168 _dropPath.Empty(); 230 _dropPath.Empty();
169 } 231 }
170 232
171 /* 233 if (!dataObject)
172 m_IsFolder = false; 234 return E_INVALIDARG;
173 if (pidlFolder == 0) 235
174 */ 236 #ifndef UNDER_CE
175 // pidlFolder is NULL :( 237
176 return GetFileNames(dataObject, _fileNames); 238 RINOK(NShell::DataObject_GetData_HDROP_or_IDLIST_Names(dataObject, _fileNames))
177} 239 // for (unsigned y = 0; y < 10000; y++)
240 if (NShell::DataObject_GetData_FILE_ATTRS(dataObject, _attribs) != S_OK)
241 _attribs.Clear();
242
243 #endif
244
245 ODS_SPRF_s(sprintf(s, "==== CZipContextMenu::Initialize END _files=%d",
246 _fileNames.Size()))
178 247
179HRESULT CZipContextMenu::InitContextMenu(const wchar_t * /* folder */, const wchar_t * const *names, unsigned numFiles)
180{
181 _isMenuForFM = true;
182 _fileNames.Clear();
183 for (UInt32 i = 0; i < numFiles; i++)
184 {
185 // MessageBoxW(0, names[i], NULL, 0);
186 // OutputDebugStringW(names[i]);
187 _fileNames.Add(names[i]);
188 }
189 _dropMode = false;
190 return S_OK; 248 return S_OK;
249 COM_TRY_END
191} 250}
192 251
193 252
@@ -202,7 +261,7 @@ static LPCSTR const kCheckSumCascadedVerb = "SevenZip.Checksum";
202struct CContextMenuCommand 261struct CContextMenuCommand
203{ 262{
204 UInt32 flag; 263 UInt32 flag;
205 CZipContextMenu::ECommandInternalID CommandInternalID; 264 CZipContextMenu::enum_CommandInternalID CommandInternalID;
206 LPCSTR Verb; 265 LPCSTR Verb;
207 UINT ResourceID; 266 UINT ResourceID;
208}; 267};
@@ -227,7 +286,7 @@ static const CContextMenuCommand g_Commands[] =
227 286
228struct CHashCommand 287struct CHashCommand
229{ 288{
230 CZipContextMenu::ECommandInternalID CommandInternalID; 289 CZipContextMenu::enum_CommandInternalID CommandInternalID;
231 LPCSTR UserName; 290 LPCSTR UserName;
232 LPCSTR MethodName; 291 LPCSTR MethodName;
233}; 292};
@@ -244,19 +303,19 @@ static const CHashCommand g_HashCommands[] =
244}; 303};
245 304
246 305
247static int FindCommand(CZipContextMenu::ECommandInternalID &id) 306static int FindCommand(CZipContextMenu::enum_CommandInternalID &id)
248{ 307{
249 for (unsigned i = 0; i < ARRAY_SIZE(g_Commands); i++) 308 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Commands); i++)
250 if (g_Commands[i].CommandInternalID == id) 309 if (g_Commands[i].CommandInternalID == id)
251 return i; 310 return (int)i;
252 return -1; 311 return -1;
253} 312}
254 313
255 314
256void CZipContextMenu::FillCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi) 315void CZipContextMenu::FillCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi) const
257{ 316{
258 mainString.Empty(); 317 mainString.Empty();
259 int i = FindCommand(id); 318 const int i = FindCommand(id);
260 if (i < 0) 319 if (i < 0)
261 throw 201908; 320 throw 201908;
262 const CContextMenuCommand &command = g_Commands[(unsigned)i]; 321 const CContextMenuCommand &command = g_Commands[(unsigned)i];
@@ -266,7 +325,6 @@ void CZipContextMenu::FillCommand(ECommandInternalID id, UString &mainString, CC
266 // cmi.HelpString = cmi.Verb; 325 // cmi.HelpString = cmi.Verb;
267 LangString(command.ResourceID, mainString); 326 LangString(command.ResourceID, mainString);
268 cmi.UserString = mainString; 327 cmi.UserString = mainString;
269 // return true;
270} 328}
271 329
272 330
@@ -279,14 +337,39 @@ static UString LangStringAlt(UInt32 id, const char *altString)
279} 337}
280 338
281 339
282void CZipContextMenu::AddCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi) 340void CZipContextMenu::AddCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi)
283{ 341{
284 FillCommand(id, mainString, cmi); 342 FillCommand(id, mainString, cmi);
285 _commandMap.Add(cmi); 343 _commandMap.Add(cmi);
286} 344}
287 345
288 346
289static void MyInsertMenu(CMenu &menu, int pos, UINT id, const UString &s, HBITMAP bitmap) 347
348/*
349note: old msdn article:
350Duplicate Menu Items In the File Menu For a Shell Context Menu Extension (214477)
351----------
352 On systems with Shell32.dll version 4.71 or higher, a context menu extension
353 for a file folder that inserts one or more pop-up menus results in duplicates
354 of these menu items.
355 This occurs when the file menu is activated more than once for the selected object.
356
357CAUSE
358 In a context menu extension, if pop-up menus are inserted using InsertMenu
359 or AppendMenu, then the ID for the pop-up menu item cannot be specified.
360 Instead, this field should take in the HMENU of the pop-up menu.
361 Because the ID is not specified for the pop-up menu item, the Shell does
362 not keep track of the menu item if the file menu is pulled down multiple times.
363 As a result, the pop-up menu items are added multiple times in the context menu.
364
365 This problem occurs only when the file menu is pulled down, and does not happen
366 when the context menu is invoked by using the right button or the context menu key.
367RESOLUTION
368 To work around this problem, use InsertMenuItem and specify the ID of the
369 pop-up menu item in the wID member of the MENUITEMINFO structure.
370*/
371
372static void MyInsertMenu(CMenu &menu, unsigned pos, UINT id, const UString &s, HBITMAP bitmap)
290{ 373{
291 if (!menu) 374 if (!menu)
292 return; 375 return;
@@ -310,7 +393,7 @@ static void MyInsertMenu(CMenu &menu, int pos, UINT id, const UString &s, HBITMA
310static void MyAddSubMenu( 393static void MyAddSubMenu(
311 CObjectVector<CZipContextMenu::CCommandMapItem> &_commandMap, 394 CObjectVector<CZipContextMenu::CCommandMapItem> &_commandMap,
312 const char *verb, 395 const char *verb,
313 CMenu &menu, int pos, UINT id, const UString &s, HMENU hSubMenu, HBITMAP bitmap) 396 CMenu &menu, unsigned pos, UINT id, const UString &s, HMENU hSubMenu, HBITMAP bitmap)
314{ 397{
315 CZipContextMenu::CCommandMapItem cmi; 398 CZipContextMenu::CCommandMapItem cmi;
316 cmi.CommandInternalID = CZipContextMenu::kCommandNULL; 399 cmi.CommandInternalID = CZipContextMenu::kCommandNULL;
@@ -349,7 +432,7 @@ static const char * const kArcExts[] =
349 432
350static bool IsItArcExt(const UString &ext) 433static bool IsItArcExt(const UString &ext)
351{ 434{
352 for (unsigned i = 0; i < ARRAY_SIZE(kArcExts); i++) 435 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kArcExts); i++)
353 if (ext.IsEqualTo_Ascii_NoCase(kArcExts[i])) 436 if (ext.IsEqualTo_Ascii_NoCase(kArcExts[i]))
354 return true; 437 return true;
355 return false; 438 return false;
@@ -444,39 +527,21 @@ static const char * const kOpenTypes[] =
444 , "rar" 527 , "rar"
445}; 528};
446 529
447static bool FindExt(const char *p, const FString &name) 530
531bool FindExt(const char *p, const UString &name, CStringFinder &finder);
532bool FindExt(const char *p, const UString &name, CStringFinder &finder)
448{ 533{
449 int dotPos = name.ReverseFind_Dot(); 534 const int dotPos = name.ReverseFind_Dot();
450 if (dotPos < 0 || dotPos == (int)name.Len() - 1) 535 if (dotPos < 0 || dotPos == (int)name.Len() - 1)
451 return false; 536 return false;
452 537 return finder.FindWord_In_LowCaseAsciiList_NoCase(p, name.Ptr(dotPos + 1));
453 AString s;
454
455 for (unsigned pos = dotPos + 1;; pos++)
456 {
457 wchar_t c = name[pos];
458 if (c == 0)
459 break;
460 if (c >= 0x80)
461 return false;
462 s += (char)MyCharLower_Ascii((char)c);
463 }
464
465 for (unsigned i = 0; p[i] != 0;)
466 {
467 unsigned j;
468 for (j = i; p[j] != ' '; j++);
469 if (s.Len() == j - i && memcmp(p + i, (const char *)s, s.Len()) == 0)
470 return true;
471 i = j + 1;
472 }
473
474 return false;
475} 538}
476 539
477static bool DoNeedExtract(const FString &name) 540/* returns false, if extraction of that file extension is not expected */
541static bool DoNeedExtract(const UString &name, CStringFinder &finder)
478{ 542{
479 return !FindExt(kExtractExcludeExtensions, name); 543 // for (int y = 0; y < 1000; y++) FindExt(kExtractExcludeExtensions, name);
544 return !FindExt(kExtractExcludeExtensions, name, finder);
480} 545}
481 546
482// we must use diferent Verbs for Popup subMenu. 547// we must use diferent Verbs for Popup subMenu.
@@ -510,28 +575,24 @@ static HRESULT RETURN_WIN32_LastError_AS_HRESULT()
510*/ 575*/
511 576
512 577
513 578Z7_COMWF_B CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
514STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
515 UINT commandIDFirst, UINT commandIDLast, UINT flags) 579 UINT commandIDFirst, UINT commandIDLast, UINT flags)
516{ 580{
517 ODS("+ QueryContextMenu()"); 581 ODS("+ QueryContextMenu()")
518 COM_TRY_BEGIN 582 COM_TRY_BEGIN
519 try { 583 try {
520 584
521 #ifdef SHOW_DEBUG_CTX_MENU 585 _commandMap.Clear();
522 { char s[256]; sprintf(s, "QueryContextMenu: index=%d first=%d last=%d flags=%x _files=%d",
523 indexMenu, commandIDFirst, commandIDLast, flags, _fileNames.Size()); OutputDebugStringA(s); }
524 586
587 ODS_SPRF_s(sprintf(s, "QueryContextMenu: index=%u first=%u last=%u flags=%x _files=%u",
588 indexMenu, commandIDFirst, commandIDLast, flags, _fileNames.Size()))
525 /* 589 /*
526 for (UInt32 i = 0; i < _fileNames.Size(); i++) 590 for (UInt32 i = 0; i < _fileNames.Size(); i++)
527 { 591 {
528 OutputDebugStringW(_fileNames[i]); 592 ODS_U(_fileNames[i])
529 } 593 }
530 */ 594 */
531 #endif
532 595
533 LoadLangOneTime();
534
535 if (_fileNames.Size() == 0) 596 if (_fileNames.Size() == 0)
536 { 597 {
537 return MAKE_HRESULT(SEVERITY_SUCCESS, 0, 0); 598 return MAKE_HRESULT(SEVERITY_SUCCESS, 0, 0);
@@ -541,7 +602,6 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
541 if (commandIDFirst > commandIDLast) 602 if (commandIDFirst > commandIDLast)
542 return E_INVALIDARG; 603 return E_INVALIDARG;
543 604
544
545 UINT currentCommandID = commandIDFirst; 605 UINT currentCommandID = commandIDFirst;
546 606
547 if ((flags & 0x000F) != CMF_NORMAL 607 if ((flags & 0x000F) != CMF_NORMAL
@@ -552,24 +612,33 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
552 // 19.01 : we changed from (currentCommandID) to (currentCommandID - commandIDFirst) 612 // 19.01 : we changed from (currentCommandID) to (currentCommandID - commandIDFirst)
553 // why it was so before? 613 // why it was so before?
554 614
555 _commandMap.Clear(); 615#ifdef Z7_LANG
616 LoadLangOneTime();
617#endif
556 618
557 CMenu popupMenu; 619 CMenu popupMenu;
558 CMenuDestroyer menuDestroyer; 620 CMenuDestroyer menuDestroyer;
559 621
622 ODS("### 40")
560 CContextMenuInfo ci; 623 CContextMenuInfo ci;
561 ci.Load(); 624 ci.Load();
625 ODS("### 44")
562 626
563 _elimDup = ci.ElimDup; 627 _elimDup = ci.ElimDup;
564 _writeZone = ci.WriteZone; 628 _writeZone = ci.WriteZone;
565 629
566 HBITMAP bitmap = NULL; 630 HBITMAP bitmap = NULL;
567 if (ci.MenuIcons.Val) 631 if (ci.MenuIcons.Val)
632 {
633 ODS("### 45")
634 if (!_bitmap)
635 _bitmap = ::LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_MENU_LOGO));
568 bitmap = _bitmap; 636 bitmap = _bitmap;
637 }
569 638
570 UINT subIndex = indexMenu; 639 UINT subIndex = indexMenu;
571 640
572 ODS("### 50"); 641 ODS("### 50")
573 642
574 if (ci.Cascaded.Val) 643 if (ci.Cascaded.Val)
575 { 644 {
@@ -596,7 +665,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
596 popupMenu.InsertItem(subIndex++, true, mi); 665 popupMenu.InsertItem(subIndex++, true, mi);
597 } 666 }
598 667
599 UInt32 contextMenuFlags = ci.Flags; 668 const UInt32 contextMenuFlags = ci.Flags;
600 669
601 NFind::CFileInfo fi0; 670 NFind::CFileInfo fi0;
602 FString folderPrefix; 671 FString folderPrefix;
@@ -610,7 +679,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
610 { 679 {
611 // CFileInfo::Find can be slow for device files. So we don't call it. 680 // CFileInfo::Find can be slow for device files. So we don't call it.
612 // we need only name here. 681 // we need only name here.
613 fi0.Name = us2fs(fileName.Ptr(NName::kDevicePathPrefixSize)); // change it 4 - must be constant 682 fi0.Name = us2fs(fileName.Ptr(NName::kDevicePathPrefixSize));
614 folderPrefix = 683 folderPrefix =
615 #ifdef UNDER_CE 684 #ifdef UNDER_CE
616 "\\"; 685 "\\";
@@ -630,16 +699,42 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
630 } 699 }
631 } 700 }
632 701
633 ODS("### 100"); 702 ODS("### 100")
634 703
635 UString mainString; 704 UString mainString;
705 CStringFinder finder;
706 UStringVector fileNames_Reduced;
707 const unsigned k_Explorer_NumReducedItems = 16;
708 const bool needReduce = !_isMenuForFM && (_fileNames.Size() >= k_Explorer_NumReducedItems);
709 _fileNames_WereReduced = needReduce;
710 // _fileNames_WereReduced = true; // for debug;
711 const UStringVector *fileNames = &_fileNames;
712 if (needReduce)
713 {
714 for (unsigned i = 0; i < k_Explorer_NumReducedItems
715 && i < _fileNames.Size(); i++)
716 fileNames_Reduced.Add(_fileNames[i]);
717 fileNames = &fileNames_Reduced;
718 }
636 719
720 /*
721 if (_fileNames.Size() == k_Explorer_NumReducedItems) // for debug
722 {
723 for (int i = 0; i < 10; i++)
724 {
725 CCommandMapItem cmi;
726 AddCommand(kCompressToZipEmail, mainString, cmi);
727 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, mainString, bitmap);
728 }
729 }
730 */
731
637 if (_fileNames.Size() == 1 && currentCommandID + 14 <= commandIDLast) 732 if (_fileNames.Size() == 1 && currentCommandID + 14 <= commandIDLast)
638 { 733 {
639 if (!fi0.IsDir() && DoNeedExtract(fi0.Name)) 734 if (!fi0.IsDir() && DoNeedExtract(fs2us(fi0.Name), finder))
640 { 735 {
641 // Open 736 // Open
642 bool thereIsMainOpenItem = ((contextMenuFlags & NContextMenuFlags::kOpen) != 0); 737 const bool thereIsMainOpenItem = ((contextMenuFlags & NContextMenuFlags::kOpen) != 0);
643 if (thereIsMainOpenItem) 738 if (thereIsMainOpenItem)
644 { 739 {
645 CCommandMapItem cmi; 740 CCommandMapItem cmi;
@@ -658,7 +753,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
658 _commandMap.Back().CtxCommandType = CtxCommandType_OpenRoot; 753 _commandMap.Back().CtxCommandType = CtxCommandType_OpenRoot;
659 754
660 UINT subIndex2 = 0; 755 UINT subIndex2 = 0;
661 for (unsigned i = (thereIsMainOpenItem ? 1 : 0); i < ARRAY_SIZE(kOpenTypes); i++) 756 for (unsigned i = (thereIsMainOpenItem ? 1 : 0); i < Z7_ARRAY_SIZE(kOpenTypes); i++)
662 { 757 {
663 CCommandMapItem cmi; 758 CCommandMapItem cmi;
664 if (i == 0) 759 if (i == 0)
@@ -685,29 +780,40 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
685 } 780 }
686 } 781 }
687 782
783 ODS("### 150")
784
688 if (_fileNames.Size() > 0 && currentCommandID + 10 <= commandIDLast) 785 if (_fileNames.Size() > 0 && currentCommandID + 10 <= commandIDLast)
689 { 786 {
690 bool needExtract = (!fi0.IsDir() && DoNeedExtract(fi0.Name)); 787 ODS("### needExtract list START")
691 788 const bool needExtendedVerbs = ((flags & Z7_WIN_CMF_EXTENDEDVERBS) != 0);
692 if (!needExtract) 789 // || _isMenuForFM;
790 bool needExtract = true;
791 bool areDirs = fi0.IsDir() || (unsigned)_attribs.FirstDirIndex < k_Explorer_NumReducedItems;
792 if (!needReduce)
793 areDirs = areDirs || (_attribs.FirstDirIndex != -1);
794 if (areDirs)
795 needExtract = false;
796
797 if (!needExtendedVerbs)
798 if (needExtract)
693 { 799 {
694 for (unsigned i = 1; i < _fileNames.Size(); i++) 800 UString name;
801 const unsigned numItemsCheck = fileNames->Size();
802 for (unsigned i = 0; i < numItemsCheck; i++)
695 { 803 {
696 NFind::CFileInfo fi; 804 const UString &a = (*fileNames)[i];
697 if (!fi.Find(us2fs(_fileNames[i]))) 805 const int slash = a.ReverseFind_PathSepar();
806 name = a.Ptr(slash + 1);
807 // for (int y = 0; y < 600; y++) // for debug
808 const bool needExtr2 = DoNeedExtract(name, finder);
809 if (!needExtr2)
698 { 810 {
699 throw 20190821; 811 needExtract = needExtr2;
700 // return RETURN_WIN32_LastError_AS_HRESULT();
701 }
702 if (!fi.IsDir() && DoNeedExtract(fi.Name))
703 {
704 needExtract = true;
705 break; 812 break;
706 } 813 }
707 } 814 }
708 } 815 }
709 816 ODS("### needExtract list END")
710 // const UString &fileName = _fileNames.Front();
711 817
712 if (needExtract) 818 if (needExtract)
713 { 819 {
@@ -757,16 +863,46 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
757 // Test 863 // Test
758 CCommandMapItem cmi; 864 CCommandMapItem cmi;
759 AddCommand(kTest, mainString, cmi); 865 AddCommand(kTest, mainString, cmi);
866 // if (_fileNames.Size() == 16) mainString += "_[16]"; // for debug
760 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, mainString, bitmap); 867 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, mainString, bitmap);
761 } 868 }
762 } 869 }
763
764 const UString arcName = CreateArchiveName(_fileNames, _fileNames.Size() == 1 ? &fi0 : NULL);
765 870
766 UString arcName7z = arcName; 871 ODS("### CreateArchiveName START")
767 arcName7z += ".7z"; 872 UString arcName_base;
768 UString arcNameZip = arcName; 873 const UString arcName = CreateArchiveName(
769 arcNameZip += ".zip"; 874 *fileNames,
875 false, // isHash
876 fileNames->Size() == 1 ? &fi0 : NULL,
877 arcName_base);
878 ODS("### CreateArchiveName END")
879 UString arcName_Show = arcName;
880 if (needReduce)
881 {
882 /* we need same arcName_Show for two calls from Explorer:
883 1) reduced call (only first 16 items)
884 2) full call with all items (can be >= 16 items)
885 (fileNames) array was reduced to 16 items.
886 So we will have same (arcName) in both reduced and full calls.
887 If caller (Explorer) uses (reduce_to_first_16_items) scheme,
888 we can use (arcName) here instead of (arcName_base).
889 (arcName_base) has no number in name.
890 */
891 arcName_Show = arcName_base; // we can comment that line
892 /* we use "_" in archive name as sign to user
893 that shows that final archive name can be changed. */
894 arcName_Show += "_";
895 }
896
897 UString arcName_7z = arcName;
898 arcName_7z += ".7z";
899 UString arcName_7z_Show = arcName_Show;
900 arcName_7z_Show += ".7z";
901 UString arcName_zip = arcName;
902 arcName_zip += ".zip";
903 UString arcName_zip_Show = arcName_Show;
904 arcName_zip_Show += ".zip";
905
770 906
771 // Compress 907 // Compress
772 if ((contextMenuFlags & NContextMenuFlags::kCompress) != 0) 908 if ((contextMenuFlags & NContextMenuFlags::kCompress) != 0)
@@ -794,7 +930,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
794 930
795 // CompressTo7z 931 // CompressTo7z
796 if (contextMenuFlags & NContextMenuFlags::kCompressTo7z && 932 if (contextMenuFlags & NContextMenuFlags::kCompressTo7z &&
797 !arcName7z.IsEqualTo_NoCase(fs2us(fi0.Name))) 933 !arcName_7z.IsEqualTo_NoCase(fs2us(fi0.Name)))
798 { 934 {
799 CCommandMapItem cmi; 935 CCommandMapItem cmi;
800 UString s; 936 UString s;
@@ -802,10 +938,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
802 cmi.Folder = _dropPath; 938 cmi.Folder = _dropPath;
803 else 939 else
804 cmi.Folder = fs2us(folderPrefix); 940 cmi.Folder = fs2us(folderPrefix);
805 cmi.ArcName = arcName7z; 941 cmi.ArcName = arcName_7z;
806 cmi.ArcType = "7z"; 942 cmi.ArcType = "7z";
807 AddCommand(kCompressTo7z, s, cmi); 943 AddCommand(kCompressTo7z, s, cmi);
808 MyFormatNew_ReducedName(s, arcName7z); 944 MyFormatNew_ReducedName(s, arcName_7z_Show);
809 Set_UserString_in_LastCommand(s); 945 Set_UserString_in_LastCommand(s);
810 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); 946 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap);
811 } 947 }
@@ -816,10 +952,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
816 { 952 {
817 CCommandMapItem cmi; 953 CCommandMapItem cmi;
818 UString s; 954 UString s;
819 cmi.ArcName = arcName7z; 955 cmi.ArcName = arcName_7z;
820 cmi.ArcType = "7z"; 956 cmi.ArcType = "7z";
821 AddCommand(kCompressTo7zEmail, s, cmi); 957 AddCommand(kCompressTo7zEmail, s, cmi);
822 MyFormatNew_ReducedName(s, arcName7z); 958 MyFormatNew_ReducedName(s, arcName_7z_Show);
823 Set_UserString_in_LastCommand(s); 959 Set_UserString_in_LastCommand(s);
824 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); 960 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap);
825 } 961 }
@@ -827,7 +963,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
827 963
828 // CompressToZip 964 // CompressToZip
829 if (contextMenuFlags & NContextMenuFlags::kCompressToZip && 965 if (contextMenuFlags & NContextMenuFlags::kCompressToZip &&
830 !arcNameZip.IsEqualTo_NoCase(fs2us(fi0.Name))) 966 !arcName_zip.IsEqualTo_NoCase(fs2us(fi0.Name)))
831 { 967 {
832 CCommandMapItem cmi; 968 CCommandMapItem cmi;
833 UString s; 969 UString s;
@@ -835,10 +971,10 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
835 cmi.Folder = _dropPath; 971 cmi.Folder = _dropPath;
836 else 972 else
837 cmi.Folder = fs2us(folderPrefix); 973 cmi.Folder = fs2us(folderPrefix);
838 cmi.ArcName = arcNameZip; 974 cmi.ArcName = arcName_zip;
839 cmi.ArcType = "zip"; 975 cmi.ArcType = "zip";
840 AddCommand(kCompressToZip, s, cmi); 976 AddCommand(kCompressToZip, s, cmi);
841 MyFormatNew_ReducedName(s, arcNameZip); 977 MyFormatNew_ReducedName(s, arcName_zip_Show);
842 Set_UserString_in_LastCommand(s); 978 Set_UserString_in_LastCommand(s);
843 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); 979 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap);
844 } 980 }
@@ -849,16 +985,17 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
849 { 985 {
850 CCommandMapItem cmi; 986 CCommandMapItem cmi;
851 UString s; 987 UString s;
852 cmi.ArcName = arcNameZip; 988 cmi.ArcName = arcName_zip;
853 cmi.ArcType = "zip"; 989 cmi.ArcType = "zip";
854 AddCommand(kCompressToZipEmail, s, cmi); 990 AddCommand(kCompressToZipEmail, s, cmi);
855 MyFormatNew_ReducedName(s, arcNameZip); 991 MyFormatNew_ReducedName(s, arcName_zip_Show);
856 Set_UserString_in_LastCommand(s); 992 Set_UserString_in_LastCommand(s);
857 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap); 993 MyInsertMenu(popupMenu, subIndex++, currentCommandID++, s, bitmap);
858 } 994 }
859 #endif 995 #endif
860 } 996 }
861 997
998 ODS("### 300")
862 999
863 // don't use InsertMenu: See MSDN: 1000 // don't use InsertMenu: See MSDN:
864 // PRB: Duplicate Menu Items In the File Menu For a Shell Context Menu Extension 1001 // PRB: Duplicate Menu Items In the File Menu For a Shell Context Menu Extension
@@ -879,6 +1016,8 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
879 indexMenu = subIndex; 1016 indexMenu = subIndex;
880 } 1017 }
881 1018
1019 ODS("### 350")
1020
882 const bool needCrc = ((contextMenuFlags & 1021 const bool needCrc = ((contextMenuFlags &
883 (NContextMenuFlags::kCRC | 1022 (NContextMenuFlags::kCRC |
884 NContextMenuFlags::kCRC_Cascaded)) != 0); 1023 NContextMenuFlags::kCRC_Cascaded)) != 0);
@@ -901,7 +1040,7 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
901 1040
902 CMenu menu; 1041 CMenu menu;
903 { 1042 {
904 int indexInParent; 1043 unsigned indexInParent;
905 if (insertHashMenuTo7zipMenu) 1044 if (insertHashMenuTo7zipMenu)
906 { 1045 {
907 indexInParent = subIndex; 1046 indexInParent = subIndex;
@@ -920,7 +1059,9 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
920 indexMenu = indexInParent; 1059 indexMenu = indexInParent;
921 } 1060 }
922 1061
923 for (unsigned i = 0; i < ARRAY_SIZE(g_HashCommands); i++) 1062 ODS("### HashCommands")
1063
1064 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_HashCommands); i++)
924 { 1065 {
925 if (currentCommandID >= commandIDLast) 1066 if (currentCommandID >= commandIDLast)
926 break; 1067 break;
@@ -928,13 +1069,13 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
928 CCommandMapItem cmi; 1069 CCommandMapItem cmi;
929 cmi.CommandInternalID = hc.CommandInternalID; 1070 cmi.CommandInternalID = hc.CommandInternalID;
930 cmi.Verb = kCheckSumCascadedVerb; 1071 cmi.Verb = kCheckSumCascadedVerb;
931 cmi.Verb += '.'; 1072 cmi.Verb.Add_Dot();
932 cmi.Verb += hc.MethodName;
933 UString s; 1073 UString s;
934 s += hc.UserName; 1074 s += hc.UserName;
935 1075
936 if (hc.CommandInternalID == kHash_Generate_SHA256) 1076 if (hc.CommandInternalID == kHash_Generate_SHA256)
937 { 1077 {
1078 cmi.Verb += "Generate";
938 { 1079 {
939 popupMenu.Attach(hMenu); 1080 popupMenu.Attach(hMenu);
940 CMenuItem mi; 1081 CMenuItem mi;
@@ -944,28 +1085,47 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
944 } 1085 }
945 1086
946 UString name; 1087 UString name;
947 if (_fileNames.Size() > 1) 1088 UString showName;
948 name = CreateArchiveName(_fileNames, _fileNames.Size() == 1 ? &fi0 : NULL); 1089 ODS("### Hash CreateArchiveName Start")
1090 // for (int y = 0; y < 10000; y++) // for debug
1091 // if (fileNames->Size() == 1) name = fs2us(fi0.Name); else
1092 name = CreateArchiveName(
1093 *fileNames,
1094 true, // isHash
1095 fileNames->Size() == 1 ? &fi0 : NULL,
1096 showName);
1097 if (needReduce)
1098 showName += "_";
949 else 1099 else
950 name = fs2us(fi0.Name); 1100 showName = name;
1101
1102 ODS("### Hash CreateArchiveName END")
951 name += ".sha256"; 1103 name += ".sha256";
1104 showName += ".sha256";
952 cmi.Folder = fs2us(folderPrefix); 1105 cmi.Folder = fs2us(folderPrefix);
953 cmi.ArcName = name; 1106 cmi.ArcName = name;
954 s = "SHA-256 -> "; 1107 s = "SHA-256 -> ";
955 s += name; 1108 s += showName;
956 } 1109 }
957 else if (hc.CommandInternalID == kHash_TestArc) 1110 else if (hc.CommandInternalID == kHash_TestArc)
958 { 1111 {
1112 cmi.Verb += "Test";
959 s = LangStringAlt(IDS_CONTEXT_TEST, "Test archive"); 1113 s = LangStringAlt(IDS_CONTEXT_TEST, "Test archive");
960 s += " : "; 1114 s += " : ";
961 s += GetNameOfProperty(kpidChecksum, UString("Checksum")); 1115 s += GetNameOfProperty(kpidChecksum, UString("Checksum"));
962 } 1116 }
1117 else
1118 cmi.Verb += "Calc";
1119
1120 cmi.Verb.Add_Dot();
1121 cmi.Verb += hc.MethodName;
963 1122
964 // cmi.HelpString = cmi.Verb; 1123 // cmi.HelpString = cmi.Verb;
965 cmi.UserString = s; 1124 cmi.UserString = s;
966 cmi.CtxCommandType = CtxCommandType_CrcChild; 1125 cmi.CtxCommandType = CtxCommandType_CrcChild;
967 _commandMap.Add(cmi); 1126 _commandMap.Add(cmi);
968 MyInsertMenu(subMenu, subIndex_CRC++, currentCommandID++, s, bitmap); 1127 MyInsertMenu(subMenu, subIndex_CRC++, currentCommandID++, s, bitmap);
1128 ODS("### 380")
969 } 1129 }
970 1130
971 subMenu.Detach(); 1131 subMenu.Detach();
@@ -973,49 +1133,45 @@ STDMETHODIMP CZipContextMenu::QueryContextMenu(HMENU hMenu, UINT indexMenu,
973 } 1133 }
974 1134
975 popupMenu.Detach(); 1135 popupMenu.Detach();
976
977 /* 1136 /*
978 if (!ci.Cascaded.Val) 1137 if (!ci.Cascaded.Val)
979 indexMenu = subIndex; 1138 indexMenu = subIndex;
980 */ 1139 */
981 1140 const unsigned numCommands = currentCommandID - commandIDFirst;
982 ODS("### 400"); 1141 ODS("+ QueryContextMenu() END")
983 1142 ODS_SPRF_s(sprintf(s, "Commands=%u currentCommandID - commandIDFirst = %u",
984 #ifdef SHOW_DEBUG_CTX_MENU 1143 _commandMap.Size(), numCommands))
985 { char s[256]; sprintf(s, "Commands=%d currentCommandID - commandIDFirst = %d", 1144 if (_commandMap.Size() != numCommands)
986 _commandMap.Size(), currentCommandID - commandIDFirst); OutputDebugStringA(s); }
987 #endif
988
989 if (_commandMap.Size() != currentCommandID - commandIDFirst)
990 throw 20190818; 1145 throw 20190818;
991 return MAKE_HRESULT(SEVERITY_SUCCESS, 0, currentCommandID - commandIDFirst); 1146 /*
992 1147 FOR_VECTOR (k, _commandMap)
1148 {
1149 ODS_U(_commandMap[k].Verb);
1150 }
1151 */
993 } 1152 }
994 catch(...) 1153 catch(...)
995 { 1154 {
1155 ODS_SPRF_s(sprintf(s, "catch() exception: Commands=%u", _commandMap.Size()))
1156 if (_commandMap.Size() == 0)
1157 throw;
1158 }
996 /* we added some menu items already : num_added_menu_items, 1159 /* we added some menu items already : num_added_menu_items,
997 So we MUST return (number_of_defined_ids), where (number_of_defined_ids >= num_added_menu_items) 1160 So we MUST return (number_of_defined_ids), where (number_of_defined_ids >= num_added_menu_items)
998 This will prevent incorrect menu working, when same IDs can be 1161 This will prevent incorrect menu working, when same IDs can be
999 assigned in multiple menu items from different subhandlers. 1162 assigned in multiple menu items from different subhandlers.
1000 And we must add items to _commandMap before adding to menu. 1163 And we must add items to _commandMap before adding to menu.
1001 */ 1164 */
1002 #ifdef SHOW_DEBUG_CTX_MENU 1165 return MAKE_HRESULT(SEVERITY_SUCCESS, 0, _commandMap.Size());
1003 { char s[256]; sprintf(s, "catch() exception: Commands=%d",
1004 _commandMap.Size()); OutputDebugStringA(s); }
1005 #endif
1006 // if (_commandMap.Size() != 0)
1007 return MAKE_HRESULT(SEVERITY_SUCCESS, 0, _commandMap.Size());
1008 // throw;
1009 }
1010 COM_TRY_END 1166 COM_TRY_END
1011} 1167}
1012 1168
1013 1169
1014int CZipContextMenu::FindVerb(const UString &verb) 1170int CZipContextMenu::FindVerb(const UString &verb) const
1015{ 1171{
1016 FOR_VECTOR (i, _commandMap) 1172 FOR_VECTOR (i, _commandMap)
1017 if (_commandMap[i].Verb == verb) 1173 if (_commandMap[i].Verb == verb)
1018 return i; 1174 return (int)i;
1019 return -1; 1175 return -1;
1020} 1176}
1021 1177
@@ -1025,66 +1181,16 @@ static UString Get7zFmPath()
1025} 1181}
1026 1182
1027 1183
1028#ifdef UNDER_CE 1184Z7_COMWF_B CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo)
1029 #define MY__IS_INTRESOURCE(_r) ((((ULONG_PTR)(_r)) >> 16) == 0)
1030#else
1031 #define MY__IS_INTRESOURCE(_r) IS_INTRESOURCE(_r)
1032#endif
1033
1034
1035#ifdef SHOW_DEBUG_CTX_MENU
1036static void PrintStringA(const char *name, LPCSTR ptr)
1037{
1038 AString m;
1039 m += name;
1040 m += ": ";
1041 char s[32];
1042 sprintf(s, "%p", ptr);
1043 m += s;
1044 if (!MY__IS_INTRESOURCE(ptr))
1045 {
1046 m += ": \"";
1047 m += ptr;
1048 m += "\"";
1049 }
1050 OutputDebugStringA(m);
1051}
1052
1053#if !defined(UNDER_CE)
1054static void PrintStringW(const char *name, LPCWSTR ptr)
1055{
1056 UString m;
1057 m += name;
1058 m += ": ";
1059 char s[32];
1060 sprintf(s, "%p", ptr);
1061 m += s;
1062 if (!MY__IS_INTRESOURCE(ptr))
1063 {
1064 m += ": \"";
1065 m += ptr;
1066 m += "\"";
1067 }
1068 OutputDebugStringW(m);
1069}
1070#endif
1071#endif
1072
1073
1074STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo)
1075{ 1185{
1076 COM_TRY_BEGIN 1186 COM_TRY_BEGIN
1077 1187
1188 ODS("==== CZipContextMenu::InvokeCommand()")
1189
1078 #ifdef SHOW_DEBUG_CTX_MENU 1190 #ifdef SHOW_DEBUG_CTX_MENU
1079 1191
1080 { char s[1280]; sprintf(s, 1192 ODS_SPRF_s(sprintf(s, ": InvokeCommand: cbSize=%u flags=%x ",
1081 #ifdef _WIN64 1193 (unsigned)commandInfo->cbSize, (unsigned)commandInfo->fMask))
1082 "64"
1083 #else
1084 "32"
1085 #endif
1086 ": InvokeCommand: cbSize=%d flags=%x "
1087 , commandInfo->cbSize, commandInfo->fMask); OutputDebugStringA(s); }
1088 1194
1089 PrintStringA("Verb", commandInfo->lpVerb); 1195 PrintStringA("Verb", commandInfo->lpVerb);
1090 PrintStringA("Parameters", commandInfo->lpParameters); 1196 PrintStringA("Parameters", commandInfo->lpParameters);
@@ -1094,16 +1200,16 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo)
1094 int commandOffset = -1; 1200 int commandOffset = -1;
1095 1201
1096 // xp64 / Win10 : explorer.exe sends 0 in lpVerbW 1202 // xp64 / Win10 : explorer.exe sends 0 in lpVerbW
1097 // MSDN: if (IS_INTRESOURCE(lpVerbW)), we must use LOWORD(lpVerb) as sommand offset 1203 // MSDN: if (IS_INTRESOURCE(lpVerbW)), we must use LOWORD(lpVerb) as command offset
1098 1204
1099 // FIXME: MINGW doesn't define CMINVOKECOMMANDINFOEX 1205 // FIXME: old MINGW doesn't define CMINVOKECOMMANDINFOEX / CMIC_MASK_UNICODE
1100 #if !defined(UNDER_CE) /* && defined(_MSC_VER) */ 1206 #if !defined(UNDER_CE) && defined(CMIC_MASK_UNICODE)
1101 bool unicodeVerb = false; 1207 bool unicodeVerb = false;
1102 if (commandInfo->cbSize == sizeof(CMINVOKECOMMANDINFOEX) && 1208 if (commandInfo->cbSize == sizeof(CMINVOKECOMMANDINFOEX) &&
1103 (commandInfo->fMask & CMIC_MASK_UNICODE) != 0) 1209 (commandInfo->fMask & CMIC_MASK_UNICODE) != 0)
1104 { 1210 {
1105 LPCMINVOKECOMMANDINFOEX commandInfoEx = (LPCMINVOKECOMMANDINFOEX)commandInfo; 1211 LPCMINVOKECOMMANDINFOEX commandInfoEx = (LPCMINVOKECOMMANDINFOEX)commandInfo;
1106 if (!MY__IS_INTRESOURCE(commandInfoEx->lpVerbW)) 1212 if (!MY_IS_INTRESOURCE(commandInfoEx->lpVerbW))
1107 { 1213 {
1108 unicodeVerb = true; 1214 unicodeVerb = true;
1109 commandOffset = FindVerb(commandInfoEx->lpVerbW); 1215 commandOffset = FindVerb(commandInfoEx->lpVerbW);
@@ -1120,22 +1226,17 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo)
1120 if (!unicodeVerb) 1226 if (!unicodeVerb)
1121 #endif 1227 #endif
1122 { 1228 {
1123 #ifdef SHOW_DEBUG_CTX_MENU 1229 ODS("use non-UNICODE verb")
1124 OutputDebugStringA("use non-UNICODE verb");
1125 #endif
1126 // if (HIWORD(commandInfo->lpVerb) == 0) 1230 // if (HIWORD(commandInfo->lpVerb) == 0)
1127 if (MY__IS_INTRESOURCE(commandInfo->lpVerb)) 1231 if (MY_IS_INTRESOURCE(commandInfo->lpVerb))
1128 commandOffset = LOWORD(commandInfo->lpVerb); 1232 commandOffset = LOWORD(commandInfo->lpVerb);
1129 else 1233 else
1130 commandOffset = FindVerb(GetUnicodeString(commandInfo->lpVerb)); 1234 commandOffset = FindVerb(GetUnicodeString(commandInfo->lpVerb));
1131 } 1235 }
1132 1236
1133 #ifdef SHOW_DEBUG_CTX_MENU 1237 ODS_SPRF_s(sprintf(s, "commandOffset=%d", commandOffset))
1134 { char s[128]; sprintf(s, "commandOffset=%d",
1135 commandOffset); OutputDebugStringA(s); }
1136 #endif
1137 1238
1138 if (commandOffset < 0 || (unsigned)commandOffset >= _commandMap.Size()) 1239 if (/* commandOffset < 0 || */ (unsigned)commandOffset >= _commandMap.Size())
1139 return E_INVALIDARG; 1240 return E_INVALIDARG;
1140 const CCommandMapItem &cmi = _commandMap[(unsigned)commandOffset]; 1241 const CCommandMapItem &cmi = _commandMap[(unsigned)commandOffset];
1141 return InvokeCommandCommon(cmi); 1242 return InvokeCommandCommon(cmi);
@@ -1145,7 +1246,7 @@ STDMETHODIMP CZipContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO commandInfo)
1145 1246
1146HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi) 1247HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1147{ 1248{
1148 const ECommandInternalID cmdID = cmi.CommandInternalID; 1249 const enum_CommandInternalID cmdID = cmi.CommandInternalID;
1149 1250
1150 try 1251 try
1151 { 1252 {
@@ -1167,6 +1268,11 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1167 case kExtractHere: 1268 case kExtractHere:
1168 case kExtractTo: 1269 case kExtractTo:
1169 { 1270 {
1271 if (_attribs.FirstDirIndex != -1)
1272 {
1273 ShowErrorMessageRes(IDS_SELECT_FILES);
1274 break;
1275 }
1170 ExtractArchives(_fileNames, cmi.Folder, 1276 ExtractArchives(_fileNames, cmi.Folder,
1171 (cmdID == kExtract), // showDialog 1277 (cmdID == kExtract), // showDialog
1172 (cmdID == kExtractTo) && _elimDup.Val, // elimDup 1278 (cmdID == kExtractTo) && _elimDup.Val, // elimDup
@@ -1186,16 +1292,37 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1186 case kCompressToZip: 1292 case kCompressToZip:
1187 case kCompressToZipEmail: 1293 case kCompressToZipEmail:
1188 { 1294 {
1295 UString arcName = cmi.ArcName;
1296 if (_fileNames_WereReduced)
1297 {
1298 UString arcName_base;
1299 arcName = CreateArchiveName(
1300 _fileNames,
1301 false, // isHash
1302 NULL, // fi0
1303 arcName_base);
1304 const char *postfix = NULL;
1305 if (cmdID == kCompressTo7z ||
1306 cmdID == kCompressTo7zEmail)
1307 postfix = ".7z";
1308 else if (
1309 cmdID == kCompressToZip ||
1310 cmdID == kCompressToZipEmail)
1311 postfix = ".zip";
1312 if (postfix)
1313 arcName += postfix;
1314 }
1315
1189 const bool email = 1316 const bool email =
1190 (cmdID == kCompressEmail) || 1317 cmdID == kCompressEmail ||
1191 (cmdID == kCompressTo7zEmail) || 1318 cmdID == kCompressTo7zEmail ||
1192 (cmdID == kCompressToZipEmail); 1319 cmdID == kCompressToZipEmail;
1193 const bool showDialog = 1320 const bool showDialog =
1194 (cmdID == kCompress) || 1321 cmdID == kCompress ||
1195 (cmdID == kCompressEmail); 1322 cmdID == kCompressEmail;
1196 const bool addExtension = (cmdID == kCompress || cmdID == kCompressEmail); 1323 const bool addExtension = showDialog;
1197 CompressFiles(cmi.Folder, 1324 CompressFiles(cmi.Folder,
1198 cmi.ArcName, cmi.ArcType, 1325 arcName, cmi.ArcType,
1199 addExtension, 1326 addExtension,
1200 _fileNames, email, showDialog, 1327 _fileNames, email, showDialog,
1201 false // waitFinish 1328 false // waitFinish
@@ -1211,7 +1338,7 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1211 case kHash_Generate_SHA256: 1338 case kHash_Generate_SHA256:
1212 case kHash_TestArc: 1339 case kHash_TestArc:
1213 { 1340 {
1214 for (unsigned i = 0; i < ARRAY_SIZE(g_HashCommands); i++) 1341 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_HashCommands); i++)
1215 { 1342 {
1216 const CHashCommand &hc = g_HashCommands[i]; 1343 const CHashCommand &hc = g_HashCommands[i];
1217 if (hc.CommandInternalID == cmdID) 1344 if (hc.CommandInternalID == cmdID)
@@ -1223,7 +1350,18 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1223 } 1350 }
1224 UString generateName; 1351 UString generateName;
1225 if (cmdID == kHash_Generate_SHA256) 1352 if (cmdID == kHash_Generate_SHA256)
1353 {
1226 generateName = cmi.ArcName; 1354 generateName = cmi.ArcName;
1355 if (_fileNames_WereReduced)
1356 {
1357 UString arcName_base;
1358 generateName = CreateArchiveName(_fileNames,
1359 true, // isHash
1360 NULL, // fi0
1361 arcName_base);
1362 generateName += ".sha256";
1363 }
1364 }
1227 CalcChecksum(_fileNames, (UString)hc.MethodName, 1365 CalcChecksum(_fileNames, (UString)hc.MethodName,
1228 cmi.Folder, generateName); 1366 cmi.Folder, generateName);
1229 break; 1367 break;
@@ -1237,14 +1375,14 @@ HRESULT CZipContextMenu::InvokeCommandCommon(const CCommandMapItem &cmi)
1237 } 1375 }
1238 catch(...) 1376 catch(...)
1239 { 1377 {
1240 ::MessageBoxW(0, L"Error", L"7-Zip", MB_ICONERROR); 1378 ShowErrorMessage(NULL, L"Error");
1241 } 1379 }
1242 return S_OK; 1380 return S_OK;
1243} 1381}
1244 1382
1245 1383
1246 1384
1247static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UINT size) 1385static void MyCopyString_isUnicode(void *dest, UINT size, const UString &src, bool writeInUnicode)
1248{ 1386{
1249 if (size != 0) 1387 if (size != 0)
1250 size--; 1388 size--;
@@ -1253,6 +1391,7 @@ static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UI
1253 UString s = src; 1391 UString s = src;
1254 s.DeleteFrom(size); 1392 s.DeleteFrom(size);
1255 MyStringCopy((wchar_t *)dest, s); 1393 MyStringCopy((wchar_t *)dest, s);
1394 ODS_U(s)
1256 } 1395 }
1257 else 1396 else
1258 { 1397 {
@@ -1263,50 +1402,48 @@ static void MyCopyString(void *dest, const UString &src, bool writeInUnicode, UI
1263} 1402}
1264 1403
1265 1404
1266STDMETHODIMP CZipContextMenu::GetCommandString(UINT_PTR commandOffset, UINT uType, 1405Z7_COMWF_B CZipContextMenu::GetCommandString(
1406 #ifdef Z7_OLD_WIN_SDK
1407 UINT
1408 #else
1409 UINT_PTR
1410 #endif
1411 commandOffset,
1412 UINT uType,
1267 UINT * /* pwReserved */ , LPSTR pszName, UINT cchMax) 1413 UINT * /* pwReserved */ , LPSTR pszName, UINT cchMax)
1268{ 1414{
1269 COM_TRY_BEGIN 1415 COM_TRY_BEGIN
1270 1416
1417 ODS("GetCommandString")
1418
1271 const int cmdOffset = (int)commandOffset; 1419 const int cmdOffset = (int)commandOffset;
1272 1420
1273 #ifdef SHOW_DEBUG_CTX_MENU 1421 ODS_SPRF_s(sprintf(s, "GetCommandString: cmdOffset=%d uType=%d cchMax = %d",
1274 { char s[256]; sprintf(s, "GetCommandString: cmdOffset=%d uType=%d cchMax = %d", 1422 cmdOffset, uType, cchMax))
1275 cmdOffset, uType, cchMax); OutputDebugStringA(s); }
1276 #endif
1277 1423
1278 if (uType == GCS_VALIDATEA || uType == GCS_VALIDATEW) 1424 if ((uType | GCS_UNICODE) == GCS_VALIDATEW)
1279 { 1425 {
1280 if (cmdOffset < 0 || (unsigned)cmdOffset >= _commandMap.Size()) 1426 if (/* cmdOffset < 0 || */ (unsigned)cmdOffset >= _commandMap.Size())
1281 return S_FALSE; 1427 return S_FALSE;
1282 else 1428 return S_OK;
1283 return S_OK;
1284 } 1429 }
1285 1430
1286 if (cmdOffset < 0 || (unsigned)cmdOffset >= _commandMap.Size()) 1431 if (/* cmdOffset < 0 || */ (unsigned)cmdOffset >= _commandMap.Size())
1287 { 1432 {
1288 #ifdef SHOW_DEBUG_CTX_MENU 1433 ODS("------ cmdOffset: E_INVALIDARG")
1289 OutputDebugStringA("---------------- cmdOffset: E_INVALIDARG");
1290 #endif
1291 return E_INVALIDARG; 1434 return E_INVALIDARG;
1292 } 1435 }
1293 1436
1294 const CCommandMapItem &cmi = _commandMap[(unsigned)cmdOffset]; 1437 // we use Verb as HelpString
1295 1438 if (cchMax != 0)
1296 if (uType == GCS_HELPTEXTA || uType == GCS_HELPTEXTW) 1439 if ((uType | GCS_UNICODE) == GCS_VERBW ||
1297 { 1440 (uType | GCS_UNICODE) == GCS_HELPTEXTW)
1298 // we can return "Verb" here for debug purposes.
1299 // HelpString;
1300 MyCopyString(pszName, cmi.Verb, uType == GCS_HELPTEXTW, cchMax);
1301 return S_OK;
1302 }
1303
1304 if (uType == GCS_VERBA || uType == GCS_VERBW)
1305 { 1441 {
1306 MyCopyString(pszName, cmi.Verb, uType == GCS_VERBW, cchMax); 1442 const CCommandMapItem &cmi = _commandMap[(unsigned)cmdOffset];
1443 MyCopyString_isUnicode(pszName, cchMax, cmi.Verb, (uType & GCS_UNICODE) != 0);
1307 return S_OK; 1444 return S_OK;
1308 } 1445 }
1309 1446
1310 return E_INVALIDARG; 1447 return E_INVALIDARG;
1311 1448
1312 COM_TRY_END 1449 COM_TRY_END
@@ -1339,7 +1476,7 @@ static HRESULT WINAPI My_SHStrDupW(LPCWSTR src, LPWSTR *dest)
1339class CCoTaskWSTR 1476class CCoTaskWSTR
1340{ 1477{
1341 LPWSTR m_str; 1478 LPWSTR m_str;
1342 CLASS_NO_COPY(CCoTaskWSTR) 1479 Z7_CLASS_NO_COPY(CCoTaskWSTR)
1343public: 1480public:
1344 CCoTaskWSTR(): m_str(NULL) {} 1481 CCoTaskWSTR(): m_str(NULL) {}
1345 ~CCoTaskWSTR() { ::CoTaskMemFree(m_str); } 1482 ~CCoTaskWSTR() { ::CoTaskMemFree(m_str); }
@@ -1380,41 +1517,47 @@ private:
1380 */ 1517 */
1381}; 1518};
1382 1519
1383static void LoadPaths(IShellItemArray *psiItemArray, UStringVector &paths) 1520static HRESULT LoadPaths(IShellItemArray *psiItemArray, UStringVector &paths)
1384{ 1521{
1385 if (psiItemArray) 1522 if (psiItemArray)
1386 { 1523 {
1387 DWORD numItems = 0; 1524 DWORD numItems = 0;
1388 if (psiItemArray->GetCount(&numItems) == S_OK) 1525 RINOK(psiItemArray->GetCount(&numItems))
1389 { 1526 {
1527 ODS_(Print_Number(numItems, " ==== LoadPaths START === "))
1390 for (DWORD i = 0; i < numItems; i++) 1528 for (DWORD i = 0; i < numItems; i++)
1391 { 1529 {
1392 CMyComPtr<IShellItem> item; 1530 CMyComPtr<IShellItem> item;
1393 if (psiItemArray->GetItemAt(i, &item) == S_OK && item) 1531 RINOK(psiItemArray->GetItemAt(i, &item))
1532 if (item)
1394 { 1533 {
1395 CCoTaskWSTR displayName; 1534 CCoTaskWSTR displayName;
1396 if (item->GetDisplayName(SIGDN_FILESYSPATH, &displayName) == S_OK 1535 if (item->GetDisplayName(SIGDN_FILESYSPATH, &displayName) == S_OK
1397 && (bool)displayName) 1536 && (bool)displayName)
1398 { 1537 {
1399 OutputDebugStringW(displayName); 1538 ODS_U(displayName)
1400 paths.Add((LPCWSTR)displayName); 1539 paths.Add((LPCWSTR)displayName);
1401 } 1540 }
1402 } 1541 }
1403 } 1542 }
1543 ODS_(Print_Number(numItems, " ==== LoadPaths END === "))
1404 } 1544 }
1405 } 1545 }
1546 return S_OK;
1406} 1547}
1407 1548
1408 1549
1409void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray) 1550void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray)
1410{ 1551{
1411 SubCommands.Clear(); 1552 SubCommands.Clear();
1412 1553 _fileNames.Clear();
1413 UStringVector paths; 1554 {
1414 LoadPaths(psiItemArray, paths); 1555 UStringVector paths;
1415 _fileNames = paths; 1556 if (LoadPaths(psiItemArray, paths) != S_OK)
1416 1557 return;
1417 HRESULT res = QueryContextMenu( 1558 _fileNames = paths;
1559 }
1560 const HRESULT res = QueryContextMenu(
1418 NULL, // hMenu, 1561 NULL, // hMenu,
1419 0, // indexMenu, 1562 0, // indexMenu,
1420 0, // commandIDFirst, 1563 0, // commandIDFirst,
@@ -1424,7 +1567,6 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray)
1424 if (FAILED(res)) 1567 if (FAILED(res))
1425 return /* res */; 1568 return /* res */;
1426 1569
1427
1428 CZipExplorerCommand *crcHandler = NULL; 1570 CZipExplorerCommand *crcHandler = NULL;
1429 CZipExplorerCommand *openHandler = NULL; 1571 CZipExplorerCommand *openHandler = NULL;
1430 1572
@@ -1435,7 +1577,6 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray)
1435 { 1577 {
1436 const CCommandMapItem &cmi = _commandMap[i]; 1578 const CCommandMapItem &cmi = _commandMap[i];
1437 1579
1438
1439 if (cmi.IsPopup) 1580 if (cmi.IsPopup)
1440 if (!cmi.IsSubMenu()) 1581 if (!cmi.IsSubMenu())
1441 continue; 1582 continue;
@@ -1459,22 +1600,22 @@ void CZipExplorerCommand::LoadItems(IShellItemArray *psiItemArray)
1459 1600
1460 shellExt->_commandMap_Cur.Add(cmi); 1601 shellExt->_commandMap_Cur.Add(cmi);
1461 1602
1462 ODS_U(cmi.UserString); 1603 ODS_U(cmi.UserString)
1463 1604
1464 if (cmi.CtxCommandType == CtxCommandType_CrcRoot && useCascadedCrc) 1605 if (cmi.CtxCommandType == CtxCommandType_CrcRoot && useCascadedCrc)
1465 crcHandler = shellExt; 1606 crcHandler = shellExt;
1466 if (cmi.CtxCommandType == CtxCommandType_OpenRoot && useCascadedOpen) 1607 if (cmi.CtxCommandType == CtxCommandType_OpenRoot && useCascadedOpen)
1467 { 1608 {
1468 // ODS2("cmi.CtxCommandType == CtxCommandType_OpenRoot"); 1609 // ODS("cmi.CtxCommandType == CtxCommandType_OpenRoot");
1469 openHandler = shellExt; 1610 openHandler = shellExt;
1470 } 1611 }
1471 } 1612 }
1472} 1613}
1473 1614
1474 1615
1475STDMETHODIMP CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR *ppszName) 1616Z7_COMWF_B CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR *ppszName)
1476{ 1617{
1477 ODS("- GetTitle()"); 1618 ODS("- GetTitle()")
1478 // COM_TRY_BEGIN 1619 // COM_TRY_BEGIN
1479 if (IsSeparator) 1620 if (IsSeparator)
1480 { 1621 {
@@ -1505,9 +1646,9 @@ STDMETHODIMP CZipExplorerCommand::GetTitle(IShellItemArray *psiItemArray, LPWSTR
1505} 1646}
1506 1647
1507 1648
1508STDMETHODIMP CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */, LPWSTR *ppszIcon) 1649Z7_COMWF_B CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */, LPWSTR *ppszIcon)
1509{ 1650{
1510 ODS("- GetIcon()"); 1651 ODS("- GetIcon()")
1511 // COM_TRY_BEGIN 1652 // COM_TRY_BEGIN
1512 *ppszIcon = NULL; 1653 *ppszIcon = NULL;
1513 // return E_NOTIMPL; 1654 // return E_NOTIMPL;
@@ -1520,30 +1661,30 @@ STDMETHODIMP CZipExplorerCommand::GetIcon(IShellItemArray * /* psiItemArray */,
1520} 1661}
1521 1662
1522 1663
1523STDMETHODIMP CZipExplorerCommand::GetToolTip (IShellItemArray * /* psiItemArray */, LPWSTR *ppszInfotip) 1664Z7_COMWF_B CZipExplorerCommand::GetToolTip (IShellItemArray * /* psiItemArray */, LPWSTR *ppszInfotip)
1524{ 1665{
1525 // COM_TRY_BEGIN 1666 // COM_TRY_BEGIN
1526 ODS("- GetToolTip()"); 1667 ODS("- GetToolTip()")
1527 *ppszInfotip = NULL; 1668 *ppszInfotip = NULL;
1528 return E_NOTIMPL; 1669 return E_NOTIMPL;
1529 // COM_TRY_END 1670 // COM_TRY_END
1530} 1671}
1531 1672
1532 1673
1533STDMETHODIMP CZipExplorerCommand::GetCanonicalName(GUID *pguidCommandName) 1674Z7_COMWF_B CZipExplorerCommand::GetCanonicalName(GUID *pguidCommandName)
1534{ 1675{
1535 // COM_TRY_BEGIN 1676 // COM_TRY_BEGIN
1536 ODS("- GetCanonicalName()"); 1677 ODS("- GetCanonicalName()")
1537 *pguidCommandName = GUID_NULL; 1678 *pguidCommandName = GUID_NULL;
1538 return E_NOTIMPL; 1679 return E_NOTIMPL;
1539 // COM_TRY_END 1680 // COM_TRY_END
1540} 1681}
1541 1682
1542 1683
1543STDMETHODIMP CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */, BOOL /* fOkToBeSlow */, EXPCMDSTATE *pCmdState) 1684Z7_COMWF_B CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */, BOOL /* fOkToBeSlow */, EXPCMDSTATE *pCmdState)
1544{ 1685{
1545 // COM_TRY_BEGIN 1686 // COM_TRY_BEGIN
1546 ODS("- GetState()"); 1687 ODS("- GetState()")
1547 *pCmdState = ECS_ENABLED; 1688 *pCmdState = ECS_ENABLED;
1548 return S_OK; 1689 return S_OK;
1549 // COM_TRY_END 1690 // COM_TRY_END
@@ -1552,16 +1693,17 @@ STDMETHODIMP CZipExplorerCommand::GetState(IShellItemArray * /* psiItemArray */,
1552 1693
1553 1694
1554 1695
1555STDMETHODIMP CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx * /* pbc */) 1696Z7_COMWF_B CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx * /* pbc */)
1556{ 1697{
1557 COM_TRY_BEGIN 1698 COM_TRY_BEGIN
1558 1699
1559 if (_commandMap_Cur.IsEmpty()) 1700 if (_commandMap_Cur.IsEmpty())
1560 return E_INVALIDARG; 1701 return E_INVALIDARG;
1561 1702
1562 ODS("- Invoke()"); 1703 ODS("- Invoke()")
1704 _fileNames.Clear();
1563 UStringVector paths; 1705 UStringVector paths;
1564 LoadPaths(psiItemArray, paths); 1706 RINOK(LoadPaths(psiItemArray, paths))
1565 _fileNames = paths; 1707 _fileNames = paths;
1566 return InvokeCommandCommon(_commandMap_Cur[0]); 1708 return InvokeCommandCommon(_commandMap_Cur[0]);
1567 1709
@@ -1569,9 +1711,9 @@ STDMETHODIMP CZipExplorerCommand::Invoke(IShellItemArray *psiItemArray, IBindCtx
1569} 1711}
1570 1712
1571 1713
1572STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags) 1714Z7_COMWF_B CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags)
1573{ 1715{
1574 ODS("- GetFlags()"); 1716 ODS("- GetFlags()")
1575 // COM_TRY_BEGIN 1717 // COM_TRY_BEGIN
1576 EXPCMDFLAGS f = ECF_DEFAULT; 1718 EXPCMDFLAGS f = ECF_DEFAULT;
1577 if (IsSeparator) 1719 if (IsSeparator)
@@ -1585,7 +1727,7 @@ STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags)
1585 // const CCommandMapItem &cmi = ; 1727 // const CCommandMapItem &cmi = ;
1586 if (_commandMap_Cur[0].IsSubMenu()) 1728 if (_commandMap_Cur[0].IsSubMenu())
1587 { 1729 {
1588 // ODS("ECF_HASSUBCOMMANDS"); 1730 // ODS("ECF_HASSUBCOMMANDS")
1589 f = ECF_HASSUBCOMMANDS; 1731 f = ECF_HASSUBCOMMANDS;
1590 } 1732 }
1591 } 1733 }
@@ -1596,9 +1738,9 @@ STDMETHODIMP CZipExplorerCommand::GetFlags(EXPCMDFLAGS *pFlags)
1596} 1738}
1597 1739
1598 1740
1599STDMETHODIMP CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum) 1741Z7_COMWF_B CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum)
1600{ 1742{
1601 ODS("- EnumSubCommands()"); 1743 ODS("- EnumSubCommands()")
1602 // COM_TRY_BEGIN 1744 // COM_TRY_BEGIN
1603 *ppEnum = NULL; 1745 *ppEnum = NULL;
1604 1746
@@ -1623,12 +1765,12 @@ STDMETHODIMP CZipExplorerCommand::EnumSubCommands(IEnumExplorerCommand **ppEnum)
1623} 1765}
1624 1766
1625 1767
1626STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched) 1768Z7_COMWF_B CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched)
1627{ 1769{
1628 ODS("CZipContextMenu::Next()"); 1770 ODS("CZipContextMenu::Next()")
1629 Print_Number(celt, "celt"); 1771 ODS_(Print_Number(celt, "celt"))
1630 Print_Number(CurrentSubCommand, "CurrentSubCommand"); 1772 ODS_(Print_Number(CurrentSubCommand, "CurrentSubCommand"))
1631 Print_Number(SubCommands.Size(), "SubCommands.Size()"); 1773 ODS_(Print_Number(SubCommands.Size(), "SubCommands.Size()"))
1632 1774
1633 COM_TRY_BEGIN 1775 COM_TRY_BEGIN
1634 ULONG fetched = 0; 1776 ULONG fetched = 0;
@@ -1649,7 +1791,7 @@ STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, UL
1649 if (pceltFetched) 1791 if (pceltFetched)
1650 *pceltFetched = fetched; 1792 *pceltFetched = fetched;
1651 1793
1652 ODS(fetched == celt ? " === OK === " : "=== ERROR ==="); 1794 ODS(fetched == celt ? " === OK === " : "=== ERROR ===")
1653 1795
1654 // we return S_FALSE for (fetched == 0) 1796 // we return S_FALSE for (fetched == 0)
1655 return (fetched == celt) ? S_OK : S_FALSE; 1797 return (fetched == celt) ? S_OK : S_FALSE;
@@ -1657,25 +1799,24 @@ STDMETHODIMP CZipContextMenu::Next(ULONG celt, IExplorerCommand **pUICommand, UL
1657} 1799}
1658 1800
1659 1801
1660STDMETHODIMP CZipContextMenu::Skip(ULONG celt) 1802Z7_COMWF_B CZipContextMenu::Skip(ULONG /* celt */)
1661{ 1803{
1662 ODS("CZipContextMenu::Skip()"); 1804 ODS("CZipContextMenu::Skip()")
1663 celt = celt;
1664 return E_NOTIMPL; 1805 return E_NOTIMPL;
1665} 1806}
1666 1807
1667 1808
1668STDMETHODIMP CZipContextMenu::Reset(void) 1809Z7_COMWF_B CZipContextMenu::Reset(void)
1669{ 1810{
1670 ODS("CZipContextMenu::Reset()"); 1811 ODS("CZipContextMenu::Reset()")
1671 CurrentSubCommand = 0; 1812 CurrentSubCommand = 0;
1672 return S_OK; 1813 return S_OK;
1673} 1814}
1674 1815
1675 1816
1676STDMETHODIMP CZipContextMenu::Clone(IEnumExplorerCommand **ppenum) 1817Z7_COMWF_B CZipContextMenu::Clone(IEnumExplorerCommand **ppenum)
1677{ 1818{
1678 ODS("CZipContextMenu::Clone()"); 1819 ODS("CZipContextMenu::Clone()")
1679 *ppenum = NULL; 1820 *ppenum = NULL;
1680 return E_NOTIMPL; 1821 return E_NOTIMPL;
1681} 1822}
diff --git a/CPP/7zip/UI/Explorer/ContextMenu.h b/CPP/7zip/UI/Explorer/ContextMenu.h
index 5b56d63..3f25f6a 100644
--- a/CPP/7zip/UI/Explorer/ContextMenu.h
+++ b/CPP/7zip/UI/Explorer/ContextMenu.h
@@ -1,38 +1,77 @@
1// ContextMenu.h 1// ContextMenu.h
2 2
3#ifndef __CONTEXT_MENU_H 3#ifndef ZIP7_INC_CONTEXT_MENU_H
4#define __CONTEXT_MENU_H 4#define ZIP7_INC_CONTEXT_MENU_H
5 5
6#include "../../../Common/MyWindows.h" 6#include "../../../Windows/Shell.h"
7
8#include <ShlObj.h>
9 7
10#include "MyExplorerCommand.h" 8#include "MyExplorerCommand.h"
11 9
12#include "../../../Common/MyString.h"
13
14#include "../FileManager/MyCom2.h" 10#include "../FileManager/MyCom2.h"
15 11
16enum ECtxCommandType 12#ifdef CMF_EXTENDEDVERBS
13#define Z7_WIN_CMF_EXTENDEDVERBS CMF_EXTENDEDVERBS
14#else
15#define Z7_WIN_CMF_EXTENDEDVERBS 0x00000100
16#endif
17
18enum enum_CtxCommandType
17{ 19{
18 CtxCommandType_Normal, 20 CtxCommandType_Normal,
19 CtxCommandType_OpenRoot, 21 CtxCommandType_OpenRoot,
20 CtxCommandType_OpenChild, 22 CtxCommandType_OpenChild,
21 CtxCommandType_CrcRoot, 23 CtxCommandType_CrcRoot,
22 CtxCommandType_CrcChild, 24 CtxCommandType_CrcChild
23}; 25};
24 26
25 27
26class CZipContextMenu: 28class CZipContextMenu Z7_final:
27 public IContextMenu, 29 public IContextMenu,
28 public IShellExtInit, 30 public IShellExtInit,
29 public IExplorerCommand, 31 public IExplorerCommand,
30 public IEnumExplorerCommand, 32 public IEnumExplorerCommand,
31 public CMyUnknownImp 33 public CMyUnknownImp
32{ 34{
35 Z7_COM_UNKNOWN_IMP_4_MT(
36 IContextMenu,
37 IShellExtInit,
38 IExplorerCommand,
39 IEnumExplorerCommand
40 )
41
42 // IShellExtInit
43 STDMETHOD(Initialize)(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY hkeyProgID) Z7_override;
44
45 // IContextMenu
46 STDMETHOD(QueryContextMenu)(HMENU hmenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags) Z7_override;
47 STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO lpici) Z7_override;
48 STDMETHOD(GetCommandString)(
49 #ifdef Z7_OLD_WIN_SDK
50 UINT
51 #else
52 UINT_PTR
53 #endif
54 idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax) Z7_override;
55
56 // IExplorerCommand
57 STDMETHOD (GetTitle) (IShellItemArray *psiItemArray, LPWSTR *ppszName) Z7_override;
58 STDMETHOD (GetIcon) (IShellItemArray *psiItemArray, LPWSTR *ppszIcon) Z7_override;
59 STDMETHOD (GetToolTip) (IShellItemArray *psiItemArray, LPWSTR *ppszInfotip) Z7_override;
60 STDMETHOD (GetCanonicalName) (GUID *pguidCommandName) Z7_override;
61 STDMETHOD (GetState) (IShellItemArray *psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE *pCmdState) Z7_override;
62 STDMETHOD (Invoke) (IShellItemArray *psiItemArray, IBindCtx *pbc) Z7_override;
63 STDMETHOD (GetFlags) (EXPCMDFLAGS *pFlags) Z7_override;
64 STDMETHOD (EnumSubCommands) (IEnumExplorerCommand **ppEnum) Z7_override;
65
66 // IEnumExplorerCommand
67 STDMETHOD (Next) (ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched) Z7_override;
68 STDMETHOD (Skip) (ULONG celt) Z7_override;
69 STDMETHOD (Reset) (void) Z7_override;
70 STDMETHOD (Clone) (IEnumExplorerCommand **ppenum) Z7_override;
71
33public: 72public:
34 73
35 enum ECommandInternalID 74 enum enum_CommandInternalID
36 { 75 {
37 kCommandNULL, 76 kCommandNULL,
38 kOpen, 77 kOpen,
@@ -54,48 +93,22 @@ public:
54 kHash_Generate_SHA256, 93 kHash_Generate_SHA256,
55 kHash_TestArc 94 kHash_TestArc
56 }; 95 };
57
58 MY_UNKNOWN_IMP4_MT(
59 IContextMenu,
60 IShellExtInit,
61 IExplorerCommand,
62 IEnumExplorerCommand
63 )
64
65 // IShellExtInit
66 STDMETHOD(Initialize)(LPCITEMIDLIST pidlFolder, LPDATAOBJECT dataObject, HKEY hkeyProgID);
67 96
68 // IContextMenu 97public:
69 STDMETHOD(QueryContextMenu)(HMENU hmenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags); 98 void Init_For_7zFM()
70 STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO lpici); 99 {
71 STDMETHOD(GetCommandString)(UINT_PTR idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax); 100 // _isMenuForFM = true;
72 101 // _fileNames_WereReduced = false;
73 HRESULT InitContextMenu(const wchar_t *folder, const wchar_t * const *names, unsigned numFiles); 102 }
74 103
75 void LoadItems(IShellItemArray *psiItemArray); 104 void LoadItems(IShellItemArray *psiItemArray);
76 105
77 // IExplorerCommand
78 STDMETHOD (GetTitle) (IShellItemArray *psiItemArray, LPWSTR *ppszName);
79 STDMETHOD (GetIcon) (IShellItemArray *psiItemArray, LPWSTR *ppszIcon);
80 STDMETHOD (GetToolTip) (IShellItemArray *psiItemArray, LPWSTR *ppszInfotip);
81 STDMETHOD (GetCanonicalName) (GUID *pguidCommandName);
82 STDMETHOD (GetState) (IShellItemArray *psiItemArray, BOOL fOkToBeSlow, EXPCMDSTATE *pCmdState);
83 STDMETHOD (Invoke) (IShellItemArray *psiItemArray, IBindCtx *pbc);
84 STDMETHOD (GetFlags) (EXPCMDFLAGS *pFlags);
85 STDMETHOD (EnumSubCommands) (IEnumExplorerCommand **ppEnum);
86
87 // IEnumExplorerCommand
88 STDMETHOD (Next) (ULONG celt, IExplorerCommand **pUICommand, ULONG *pceltFetched);
89 STDMETHOD (Skip) (ULONG celt);
90 STDMETHOD (Reset) (void);
91 STDMETHOD (Clone) (IEnumExplorerCommand **ppenum);
92
93 CZipContextMenu(); 106 CZipContextMenu();
94 ~CZipContextMenu(); 107 ~CZipContextMenu();
95 108
96 struct CCommandMapItem 109 struct CCommandMapItem
97 { 110 {
98 ECommandInternalID CommandInternalID; 111 enum_CommandInternalID CommandInternalID;
99 UString Verb; 112 UString Verb;
100 UString UserString; 113 UString UserString;
101 // UString HelpString; 114 // UString HelpString;
@@ -103,7 +116,7 @@ public:
103 UString ArcName; 116 UString ArcName;
104 UString ArcType; 117 UString ArcType;
105 bool IsPopup; 118 bool IsPopup;
106 ECtxCommandType CtxCommandType; 119 enum_CtxCommandType CtxCommandType;
107 120
108 CCommandMapItem(): 121 CCommandMapItem():
109 IsPopup(false), 122 IsPopup(false),
@@ -118,33 +131,34 @@ public:
118 } 131 }
119 }; 132 };
120 133
121private: 134 UStringVector _fileNames;
135 NWindows::NShell::CFileAttribs _attribs;
122 136
137private:
123 bool _isMenuForFM; 138 bool _isMenuForFM;
124 UStringVector _fileNames; 139 bool _fileNames_WereReduced; // = true, if only first 16 items were used in QueryContextMenu()
125 bool _dropMode; 140 bool _dropMode;
126 UString _dropPath; 141 UString _dropPath;
127 CObjectVector<CCommandMapItem> _commandMap; 142 CObjectVector<CCommandMapItem> _commandMap;
128 CObjectVector<CCommandMapItem> _commandMap_Cur; 143 CObjectVector<CCommandMapItem> _commandMap_Cur;
129 144
130 HBITMAP _bitmap; 145 HBITMAP _bitmap;
131 CBoolPair _elimDup;
132 UInt32 _writeZone; 146 UInt32 _writeZone;
147 CBoolPair _elimDup;
133 148
134 bool IsSeparator; 149 bool IsSeparator;
135 bool IsRoot; 150 bool IsRoot;
136 CObjectVector< CMyComPtr<IExplorerCommand> > SubCommands; 151 CObjectVector< CMyComPtr<IExplorerCommand> > SubCommands;
137 ULONG CurrentSubCommand; 152 unsigned CurrentSubCommand;
138 153
139 void Set_UserString_in_LastCommand(const UString &s) 154 void Set_UserString_in_LastCommand(const UString &s)
140 { 155 {
141 _commandMap.Back().UserString = s; 156 _commandMap.Back().UserString = s;
142 } 157 }
143 158
144 HRESULT GetFileNames(LPDATAOBJECT dataObject, UStringVector &fileNames); 159 int FindVerb(const UString &verb) const;
145 int FindVerb(const UString &verb); 160 void FillCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi) const;
146 void FillCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi); 161 void AddCommand(enum_CommandInternalID id, UString &mainString, CCommandMapItem &cmi);
147 void AddCommand(ECommandInternalID id, UString &mainString, CCommandMapItem &cmi);
148 void AddMapItem_ForSubMenu(const char *ver); 162 void AddMapItem_ForSubMenu(const char *ver);
149 163
150 HRESULT InvokeCommandCommon(const CCommandMapItem &cmi); 164 HRESULT InvokeCommandCommon(const CCommandMapItem &cmi);
diff --git a/CPP/7zip/UI/Explorer/ContextMenuFlags.h b/CPP/7zip/UI/Explorer/ContextMenuFlags.h
index 42b25f3..50c177e 100644
--- a/CPP/7zip/UI/Explorer/ContextMenuFlags.h
+++ b/CPP/7zip/UI/Explorer/ContextMenuFlags.h
@@ -1,7 +1,7 @@
1// ContextMenuFlags.h 1// ContextMenuFlags.h
2 2
3#ifndef __CONTEXT_MENU_FLAGS_H 3#ifndef ZIP7_INC_CONTEXT_MENU_FLAGS_H
4#define __CONTEXT_MENU_FLAGS_H 4#define ZIP7_INC_CONTEXT_MENU_FLAGS_H
5 5
6namespace NContextMenuFlags 6namespace NContextMenuFlags
7{ 7{
diff --git a/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp b/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp
index 91b0da5..7307b07 100644
--- a/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp
+++ b/CPP/7zip/UI/Explorer/DllExportsExplorer.cpp
@@ -1,4 +1,4 @@
1// DLLExports.cpp 1// DLLExportsExplorer.cpp
2// 2//
3// Notes: 3// Notes:
4// Win2000: 4// Win2000:
@@ -9,9 +9,23 @@
9#include "StdAfx.h" 9#include "StdAfx.h"
10 10
11#include "../../../Common/MyWindows.h" 11#include "../../../Common/MyWindows.h"
12// #include "../../../Common/IntToString.h"
13 12
13#if defined(__clang__) && __clang_major__ >= 4
14#pragma GCC diagnostic ignored "-Wnonportable-system-include-path"
15#endif
16// <olectl.h> : in new Windows Kit 10.0.2**** (NTDDI_WIN10_MN is defined)
17// <OleCtl.h> : in another Windows Kit versions
18#if defined(NTDDI_WIN10_MN) || defined(__MINGW32__) || defined(__MINGW64__)
19#include <olectl.h>
20#else
14#include <OleCtl.h> 21#include <OleCtl.h>
22#endif
23
24#if defined(__MINGW32__) || defined(__MINGW64__)
25#include <shlguid.h>
26#else
27#include <ShlGuid.h>
28#endif
15 29
16#include "../../../Common/MyInitGuid.h" 30#include "../../../Common/MyInitGuid.h"
17 31
@@ -32,7 +46,7 @@ static LPCTSTR const k_Approved = TEXT("Software\\Microsoft\\Windows\\CurrentVer
32// {23170F69-40C1-278A-1000-000100020000} 46// {23170F69-40C1-278A-1000-000100020000}
33static LPCTSTR const k_Clsid = TEXT("{23170F69-40C1-278A-1000-000100020000}"); 47static LPCTSTR const k_Clsid = TEXT("{23170F69-40C1-278A-1000-000100020000}");
34 48
35DEFINE_GUID(CLSID_CZipContextMenu, 49Z7_DEFINE_GUID(CLSID_CZipContextMenu,
36 k_7zip_GUID_Data1, 50 k_7zip_GUID_Data1,
37 k_7zip_GUID_Data2, 51 k_7zip_GUID_Data2,
38 k_7zip_GUID_Data3_Common, 52 k_7zip_GUID_Data3_Common,
@@ -42,11 +56,11 @@ using namespace NWindows;
42 56
43extern 57extern
44HINSTANCE g_hInstance; 58HINSTANCE g_hInstance;
45HINSTANCE g_hInstance = 0; 59HINSTANCE g_hInstance = NULL;
46 60
47extern 61extern
48HWND g_HWND; 62HWND g_HWND;
49HWND g_HWND = 0; 63HWND g_HWND = NULL;
50 64
51extern 65extern
52LONG g_DllRefCount; 66LONG g_DllRefCount;
@@ -56,21 +70,20 @@ LONG g_DllRefCount = 0; // Reference count of this DLL.
56// #define ODS(sz) OutputDebugStringW(L#sz) 70// #define ODS(sz) OutputDebugStringW(L#sz)
57#define ODS(sz) 71#define ODS(sz)
58 72
59class CShellExtClassFactory: 73class CShellExtClassFactory Z7_final:
60 public IClassFactory, 74 public IClassFactory,
61 public CMyUnknownImp 75 public CMyUnknownImp
62{ 76{
77 Z7_COM_UNKNOWN_IMP_1_MT(IClassFactory)
78
79 STDMETHOD(CreateInstance)(LPUNKNOWN, REFIID, void**) Z7_override Z7_final;
80 STDMETHOD(LockServer)(BOOL) Z7_override Z7_final;
63public: 81public:
64 CShellExtClassFactory() { InterlockedIncrement(&g_DllRefCount); } 82 CShellExtClassFactory() { InterlockedIncrement(&g_DllRefCount); }
65 ~CShellExtClassFactory() { InterlockedDecrement(&g_DllRefCount); } 83 ~CShellExtClassFactory() { InterlockedDecrement(&g_DllRefCount); }
66
67 MY_UNKNOWN_IMP1_MT(IClassFactory)
68
69 STDMETHODIMP CreateInstance(LPUNKNOWN, REFIID, void**);
70 STDMETHODIMP LockServer(BOOL);
71}; 84};
72 85
73STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, 86Z7_COMWF_B CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter,
74 REFIID riid, void **ppvObj) 87 REFIID riid, void **ppvObj)
75{ 88{
76 ODS("CShellExtClassFactory::CreateInstance()\r\n"); 89 ODS("CShellExtClassFactory::CreateInstance()\r\n");
@@ -92,14 +105,15 @@ STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter,
92 if (!shellExt) 105 if (!shellExt)
93 return E_OUTOFMEMORY; 106 return E_OUTOFMEMORY;
94 107
95 HRESULT res = shellExt->QueryInterface(riid, ppvObj); 108 IContextMenu *ctxm = shellExt;
109 const HRESULT res = ctxm->QueryInterface(riid, ppvObj);
96 if (res != S_OK) 110 if (res != S_OK)
97 delete shellExt; 111 delete shellExt;
98 return res; 112 return res;
99} 113}
100 114
101 115
102STDMETHODIMP CShellExtClassFactory::LockServer(BOOL /* fLock */) 116Z7_COMWF_B CShellExtClassFactory::LockServer(BOOL /* fLock */)
103{ 117{
104 return S_OK; // Check it 118 return S_OK; // Check it
105} 119}
@@ -169,7 +183,8 @@ STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
169 catch(...) { return E_OUTOFMEMORY; } 183 catch(...) { return E_OUTOFMEMORY; }
170 if (!cf) 184 if (!cf)
171 return E_OUTOFMEMORY; 185 return E_OUTOFMEMORY;
172 HRESULT res = cf->QueryInterface(riid, ppv); 186 IClassFactory *cf2 = cf;
187 const HRESULT res = cf2->QueryInterface(riid, ppv);
173 if (res != S_OK) 188 if (res != S_OK)
174 delete cf; 189 delete cf;
175 return res; 190 return res;
@@ -217,7 +232,7 @@ static BOOL RegisterServer()
217 232
218STDAPI DllRegisterServer(void) 233STDAPI DllRegisterServer(void)
219{ 234{
220 return RegisterServer() ? S_OK: SELFREG_E_CLASS; 235 return RegisterServer() ? S_OK: SELFREG_E_CLASS;
221} 236}
222 237
223static BOOL UnregisterServer() 238static BOOL UnregisterServer()
diff --git a/CPP/7zip/UI/Explorer/Explorer.dsp b/CPP/7zip/UI/Explorer/Explorer.dsp
index e390917..ff8503b 100644
--- a/CPP/7zip/UI/Explorer/Explorer.dsp
+++ b/CPP/7zip/UI/Explorer/Explorer.dsp
@@ -45,7 +45,7 @@ RSC=rc.exe
45# PROP Ignore_Export_Lib 1 45# PROP Ignore_Export_Lib 1
46# PROP Target_Dir "" 46# PROP Target_Dir ""
47# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /YX /FD /c 47# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXPLORER_EXPORTS" /YX /FD /c
48# 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 48# 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
49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
51# ADD BASE RSC /l 0x419 /d "NDEBUG" 51# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -72,7 +72,7 @@ LINK32=link.exe
72# PROP Ignore_Export_Lib 1 72# PROP Ignore_Export_Lib 1
73# PROP Target_Dir "" 73# PROP Target_Dir ""
74# 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 74# 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
75# 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 75# 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
76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
78# ADD BASE RSC /l 0x419 /d "_DEBUG" 78# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -98,8 +98,8 @@ LINK32=link.exe
98# PROP Intermediate_Dir "ReleaseU" 98# PROP Intermediate_Dir "ReleaseU"
99# PROP Ignore_Export_Lib 1 99# PROP Ignore_Export_Lib 1
100# PROP Target_Dir "" 100# PROP Target_Dir ""
101# 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 101# 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
102# 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 102# 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
103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
105# ADD BASE RSC /l 0x419 /d "NDEBUG" 105# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -127,8 +127,8 @@ LINK32=link.exe
127# PROP Intermediate_Dir "DebugU" 127# PROP Intermediate_Dir "DebugU"
128# PROP Ignore_Export_Lib 1 128# PROP Ignore_Export_Lib 1
129# PROP Target_Dir "" 129# PROP Target_Dir ""
130# 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 130# 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
131# 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 131# 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
132# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 132# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
133# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 133# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
134# ADD BASE RSC /l 0x419 /d "_DEBUG" 134# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -270,6 +270,10 @@ SOURCE=..\FileManager\LangUtils.h
270# End Source File 270# End Source File
271# Begin Source File 271# Begin Source File
272 272
273SOURCE=..\FileManager\MyCom2.h
274# End Source File
275# Begin Source File
276
273SOURCE=..\FileManager\ProgramLocation.cpp 277SOURCE=..\FileManager\ProgramLocation.cpp
274# End Source File 278# End Source File
275# Begin Source File 279# Begin Source File
@@ -298,6 +302,18 @@ SOURCE=..\FileManager\RegistryUtils.h
298# PROP Default_Filter "" 302# PROP Default_Filter ""
299# Begin Source File 303# Begin Source File
300 304
305SOURCE=..\..\..\..\C\7zTypes.h
306# End Source File
307# Begin Source File
308
309SOURCE=..\..\..\..\C\7zWindows.h
310# End Source File
311# Begin Source File
312
313SOURCE=..\..\..\..\C\Compiler.h
314# End Source File
315# Begin Source File
316
301SOURCE=..\..\..\..\C\CpuArch.c 317SOURCE=..\..\..\..\C\CpuArch.c
302# SUBTRACT CPP /YX /Yc /Yu 318# SUBTRACT CPP /YX /Yc /Yu
303# End Source File 319# End Source File
@@ -307,6 +323,15 @@ SOURCE=..\..\..\..\C\CpuArch.h
307# End Source File 323# End Source File
308# Begin Source File 324# Begin Source File
309 325
326SOURCE=..\..\..\..\C\Sort.c
327# SUBTRACT CPP /YX /Yc /Yu
328# End Source File
329# Begin Source File
330
331SOURCE=..\..\..\..\C\Sort.h
332# End Source File
333# Begin Source File
334
310SOURCE=..\..\..\..\C\Threads.c 335SOURCE=..\..\..\..\C\Threads.c
311# SUBTRACT CPP /YX /Yc /Yu 336# SUBTRACT CPP /YX /Yc /Yu
312# End Source File 337# End Source File
@@ -320,6 +345,10 @@ SOURCE=..\..\..\..\C\Threads.h
320# PROP Default_Filter "" 345# PROP Default_Filter ""
321# Begin Source File 346# Begin Source File
322 347
348SOURCE=..\..\..\Common\Common.h
349# End Source File
350# Begin Source File
351
323SOURCE=..\..\..\Common\IntToString.cpp 352SOURCE=..\..\..\Common\IntToString.cpp
324# End Source File 353# End Source File
325# Begin Source File 354# Begin Source File
@@ -356,6 +385,10 @@ SOURCE=..\..\..\Common\MyVector.h
356# End Source File 385# End Source File
357# Begin Source File 386# Begin Source File
358 387
388SOURCE=..\..\..\Common\MyWindows.h
389# End Source File
390# Begin Source File
391
359SOURCE=..\..\..\Common\NewHandler.cpp 392SOURCE=..\..\..\Common\NewHandler.cpp
360# End Source File 393# End Source File
361# Begin Source File 394# Begin Source File
@@ -440,6 +473,10 @@ SOURCE=..\..\..\Windows\Control\PropertyPage.h
440# End Group 473# End Group
441# Begin Source File 474# Begin Source File
442 475
476SOURCE=..\..\..\Windows\COM.h
477# End Source File
478# Begin Source File
479
443SOURCE=..\..\..\Windows\DLL.cpp 480SOURCE=..\..\..\Windows\DLL.cpp
444# End Source File 481# End Source File
445# Begin Source File 482# Begin Source File
@@ -567,5 +604,9 @@ SOURCE=".\7-zip.dll.manifest"
567 604
568SOURCE=.\ContextMenuFlags.h 605SOURCE=.\ContextMenuFlags.h
569# End Source File 606# End Source File
607# Begin Source File
608
609SOURCE=..\FileManager\FM.ico
610# End Source File
570# End Target 611# End Target
571# End Project 612# End Project
diff --git a/CPP/7zip/UI/Explorer/MyExplorerCommand.h b/CPP/7zip/UI/Explorer/MyExplorerCommand.h
index 227b9e0..11ac247 100644
--- a/CPP/7zip/UI/Explorer/MyExplorerCommand.h
+++ b/CPP/7zip/UI/Explorer/MyExplorerCommand.h
@@ -1,7 +1,7 @@
1// MyExplorerCommand.h 1// MyExplorerCommand.h
2 2
3#ifndef __MY_EXPLORER_COMMAND_H 3#ifndef ZIP7_INC_MY_EXPLORER_COMMAND_H
4#define __MY_EXPLORER_COMMAND_H 4#define ZIP7_INC_MY_EXPLORER_COMMAND_H
5 5
6#if _MSC_VER >= 1910 6#if _MSC_VER >= 1910
7#define USE_SYS_shobjidl_core 7#define USE_SYS_shobjidl_core
@@ -17,7 +17,9 @@
17 ShObjIdl.h : old Windows SDK 17 ShObjIdl.h : old Windows SDK
18 ShObjIdl_core.h : new Windows 10 SDK */ 18 ShObjIdl_core.h : new Windows 10 SDK */
19 19
20#ifndef Z7_OLD_WIN_SDK
20#include <ShObjIdl.h> 21#include <ShObjIdl.h>
22#endif
21 23
22#ifndef __IShellItem_INTERFACE_DEFINED__ 24#ifndef __IShellItem_INTERFACE_DEFINED__
23#define __IShellItem_INTERFACE_DEFINED__ 25#define __IShellItem_INTERFACE_DEFINED__
diff --git a/CPP/7zip/UI/Explorer/MyMessages.cpp b/CPP/7zip/UI/Explorer/MyMessages.cpp
index c912504..daff7de 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)
18 18
19void ShowErrorMessageHwndRes(HWND window, UINT resID) 19void ShowErrorMessageHwndRes(HWND window, UINT resID)
20{ 20{
21 ShowErrorMessage(window, LangString(resID)); 21 UString s = LangString(resID);
22 if (s.IsEmpty())
23 s.Add_UInt32(resID);
24 ShowErrorMessage(window, s);
22} 25}
23 26
24void ShowErrorMessageRes(UINT resID) 27void ShowErrorMessageRes(UINT resID)
25{ 28{
26 ShowErrorMessageHwndRes(0, resID); 29 ShowErrorMessageHwndRes(NULL, resID);
27} 30}
28 31
29static void ShowErrorMessageDWORD(HWND window, DWORD errorCode) 32static void ShowErrorMessageDWORD(HWND window, DWORD errorCode)
diff --git a/CPP/7zip/UI/Explorer/MyMessages.h b/CPP/7zip/UI/Explorer/MyMessages.h
index d5822f4..47d10db 100644
--- a/CPP/7zip/UI/Explorer/MyMessages.h
+++ b/CPP/7zip/UI/Explorer/MyMessages.h
@@ -1,16 +1,16 @@
1// MyMessages.h 1// MyMessages.h
2 2
3#ifndef __MY_MESSAGES_H 3#ifndef ZIP7_INC_MY_MESSAGES_H
4#define __MY_MESSAGES_H 4#define ZIP7_INC_MY_MESSAGES_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
8void ShowErrorMessage(HWND window, LPCWSTR message); 8void ShowErrorMessage(HWND window, LPCWSTR message);
9inline void ShowErrorMessage(LPCWSTR message) { ShowErrorMessage(0, message); } 9inline void ShowErrorMessage(LPCWSTR message) { ShowErrorMessage(NULL, message); }
10 10
11void ShowErrorMessageHwndRes(HWND window, UInt32 langID); 11void ShowErrorMessageHwndRes(HWND window, UInt32 langID);
12void ShowErrorMessageRes(UInt32 langID); 12void ShowErrorMessageRes(UInt32 langID);
13 13
14void ShowLastErrorMessage(HWND window = 0); 14void ShowLastErrorMessage(HWND window = NULL);
15 15
16#endif 16#endif
diff --git a/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp b/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp
index 9f6e44c..bc03d6a 100644
--- a/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp
+++ b/CPP/7zip/UI/Explorer/RegistryContextMenu.cpp
@@ -67,8 +67,9 @@ static Func_RegDeleteKeyExW func_RegDeleteKeyExW;
67static void Init_RegDeleteKeyExW() 67static void Init_RegDeleteKeyExW()
68{ 68{
69 if (!func_RegDeleteKeyExW) 69 if (!func_RegDeleteKeyExW)
70 func_RegDeleteKeyExW = (Func_RegDeleteKeyExW) 70 func_RegDeleteKeyExW = Z7_GET_PROC_ADDRESS(
71 (void *)GetProcAddress(GetModuleHandleW(L"advapi32.dll"), "RegDeleteKeyExW"); 71 Func_RegDeleteKeyExW, GetModuleHandleW(L"advapi32.dll"),
72 "RegDeleteKeyExW");
72} 73}
73 74
74#define INIT_REG_WOW if (wow != 0) Init_RegDeleteKeyExW(); 75#define INIT_REG_WOW if (wow != 0) Init_RegDeleteKeyExW();
@@ -205,7 +206,7 @@ LONG SetContextMenuHandler(bool setMode, const UString &path, UInt32 wow)
205 if (setMode) 206 if (setMode)
206 for (unsigned i = 0; i < 2; i++) 207 for (unsigned i = 0; i < 2; i++)
207 { 208 {
208 for (unsigned k = 0; k < ARRAY_SIZE(k_shellex_Prefixes); k++) 209 for (unsigned k = 0; k < Z7_ARRAY_SIZE(k_shellex_Prefixes); k++)
209 { 210 {
210 CSysString s (k_shellex_Prefixes[k]); 211 CSysString s (k_shellex_Prefixes[k]);
211 s += (i == 0 ? k_KeyPostfix_ContextMenu : k_KeyPostfix_DragDrop); 212 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 8c2acc4..bf3bb5b 100644
--- a/CPP/7zip/UI/Explorer/RegistryContextMenu.h
+++ b/CPP/7zip/UI/Explorer/RegistryContextMenu.h
@@ -1,7 +1,7 @@
1// RegistryContextMenu.h 1// RegistryContextMenu.h
2 2
3#ifndef __REGISTRY_CONTEXT_MENU_H 3#ifndef ZIP7_INC_REGISTRY_CONTEXT_MENU_H
4#define __REGISTRY_CONTEXT_MENU_H 4#define ZIP7_INC_REGISTRY_CONTEXT_MENU_H
5 5
6#ifndef UNDER_CE 6#ifndef UNDER_CE
7 7
diff --git a/CPP/7zip/UI/Explorer/StdAfx.h b/CPP/7zip/UI/Explorer/StdAfx.h
index 5e4dc64..130db8a 100644
--- a/CPP/7zip/UI/Explorer/StdAfx.h
+++ b/CPP/7zip/UI/Explorer/StdAfx.h
@@ -1,14 +1,6 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#if _MSC_VER >= 1800
4#define __STDAFX_H 4#pragma warning(disable : 4464) // relative include path contains '..'
5
6// #define _WIN32_WINNT 0x0400
7#define _WIN32_WINNT 0x0500
8#define WINVER _WIN32_WINNT
9
10#include "../../../Common/Common.h"
11
12#include <ShlObj.h>
13
14#endif 5#endif
6#include "../FileManager/StdAfx.h"
diff --git a/CPP/7zip/UI/Explorer/makefile b/CPP/7zip/UI/Explorer/makefile
index 1e79cc8..da63a5c 100644
--- a/CPP/7zip/UI/Explorer/makefile
+++ b/CPP/7zip/UI/Explorer/makefile
@@ -1,13 +1,13 @@
1PROG = 7-zip.dll 1PROG = 7-zip.dll
2DEF_FILE = Explorer.def 2DEF_FILE = Explorer.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DLANG \ 4 -DZ7_LANG \
5 5
6!IFDEF UNDER_CE 6!IFDEF UNDER_CE
7LIBS = $(LIBS) Commctrl.lib 7LIBS = $(LIBS) Commctrl.lib
8!ELSE 8!ELSE
9LIBS = $(LIBS) htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib 9LIBS = $(LIBS) htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib
10CFLAGS = $(CFLAGS) -DWIN_LONG_PATH 10CFLAGS = $(CFLAGS) -DZ7_LONG_PATH
11!ENDIF 11!ENDIF
12 12
13EXPLORER_OBJS = \ 13EXPLORER_OBJS = \
@@ -70,6 +70,7 @@ FM_OBJS = \
70 70
71C_OBJS = \ 71C_OBJS = \
72 $O\CpuArch.obj \ 72 $O\CpuArch.obj \
73 $O\Sort.obj \
73 $O\Threads.obj \ 74 $O\Threads.obj \
74 75
75!include "../../7zip.mak" 76!include "../../7zip.mak"
diff --git a/CPP/7zip/UI/Explorer/resource.h b/CPP/7zip/UI/Explorer/resource.h
index 8bb8210..bbb28b1 100644
--- a/CPP/7zip/UI/Explorer/resource.h
+++ b/CPP/7zip/UI/Explorer/resource.h
@@ -10,4 +10,6 @@
10#define IDS_CONTEXT_COMPRESS_EMAIL 2329 10#define IDS_CONTEXT_COMPRESS_EMAIL 2329
11#define IDS_CONTEXT_COMPRESS_TO_EMAIL 2330 11#define IDS_CONTEXT_COMPRESS_TO_EMAIL 2330
12 12
13#define IDS_SELECT_FILES 3015
14
13#define IDB_MENU_LOGO 190 15#define IDB_MENU_LOGO 190
diff --git a/CPP/7zip/UI/Explorer/resource2.rc b/CPP/7zip/UI/Explorer/resource2.rc
index c07148f..de34824 100644
--- a/CPP/7zip/UI/Explorer/resource2.rc
+++ b/CPP/7zip/UI/Explorer/resource2.rc
@@ -13,6 +13,7 @@ BEGIN
13 IDS_CONTEXT_COMPRESS_TO "Add to {0}" 13 IDS_CONTEXT_COMPRESS_TO "Add to {0}"
14 IDS_CONTEXT_COMPRESS_EMAIL "Compress and email..." 14 IDS_CONTEXT_COMPRESS_EMAIL "Compress and email..."
15 IDS_CONTEXT_COMPRESS_TO_EMAIL "Compress to {0} and email" 15 IDS_CONTEXT_COMPRESS_TO_EMAIL "Compress to {0} and email"
16 IDS_SELECT_FILES "You must select one or more files"
16END 17END
17 18
18IDB_MENU_LOGO BITMAP "../../UI/Explorer/MenuLogo.bmp" 19IDB_MENU_LOGO BITMAP "../../UI/Explorer/MenuLogo.bmp"
diff --git a/CPP/7zip/UI/Far/ExtractEngine.cpp b/CPP/7zip/UI/Far/ExtractEngine.cpp
index ab5c0de..05e9208 100644
--- a/CPP/7zip/UI/Far/ExtractEngine.cpp
+++ b/CPP/7zip/UI/Far/ExtractEngine.cpp
@@ -2,7 +2,7 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifndef _7ZIP_ST 5#ifndef Z7_ST
6#include "../../../Windows/Synchronization.h" 6#include "../../../Windows/Synchronization.h"
7#endif 7#endif
8 8
@@ -16,7 +16,7 @@
16using namespace NWindows; 16using namespace NWindows;
17using namespace NFar; 17using namespace NFar;
18 18
19#ifndef _7ZIP_ST 19#ifndef Z7_ST
20static NSynchronization::CCriticalSection g_CriticalSection; 20static NSynchronization::CCriticalSection g_CriticalSection;
21#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 21#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
22#else 22#else
@@ -31,10 +31,6 @@ static HRESULT CheckBreak2()
31 31
32extern void PrintMessage(const char *message); 32extern void PrintMessage(const char *message);
33 33
34CExtractCallbackImp::~CExtractCallbackImp()
35{
36}
37
38void CExtractCallbackImp::Init( 34void CExtractCallbackImp::Init(
39 UINT codePage, 35 UINT codePage,
40 CProgressBox *progressBox, 36 CProgressBox *progressBox,
@@ -47,7 +43,7 @@ void CExtractCallbackImp::Init(
47 _percent = progressBox; 43 _percent = progressBox;
48} 44}
49 45
50STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size) 46Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 size))
51{ 47{
52 MT_LOCK 48 MT_LOCK
53 49
@@ -59,7 +55,7 @@ STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 size)
59 return CheckBreak2(); 55 return CheckBreak2();
60} 56}
61 57
62STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue) 58Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *completeValue))
63{ 59{
64 MT_LOCK 60 MT_LOCK
65 61
@@ -72,15 +68,15 @@ STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *completeValue)
72 return CheckBreak2(); 68 return CheckBreak2();
73} 69}
74 70
75STDMETHODIMP CExtractCallbackImp::AskOverwrite( 71Z7_COM7F_IMF(CExtractCallbackImp::AskOverwrite(
76 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, 72 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize,
77 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, 73 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize,
78 Int32 *answer) 74 Int32 *answer))
79{ 75{
80 MT_LOCK 76 MT_LOCK
81 77
82 NOverwriteDialog::CFileInfo oldFileInfo, newFileInfo; 78 NOverwriteDialog::CFileInfo oldFileInfo, newFileInfo;
83 oldFileInfo.TimeIsDefined = (existTime != 0); 79 oldFileInfo.TimeIsDefined = (existTime != NULL);
84 if (oldFileInfo.TimeIsDefined) 80 if (oldFileInfo.TimeIsDefined)
85 oldFileInfo.Time = *existTime; 81 oldFileInfo.Time = *existTime;
86 oldFileInfo.SizeIsDefined = (existSize != NULL); 82 oldFileInfo.SizeIsDefined = (existSize != NULL);
@@ -88,7 +84,7 @@ STDMETHODIMP CExtractCallbackImp::AskOverwrite(
88 oldFileInfo.Size = *existSize; 84 oldFileInfo.Size = *existSize;
89 oldFileInfo.Name = existName; 85 oldFileInfo.Name = existName;
90 86
91 newFileInfo.TimeIsDefined = (newTime != 0); 87 newFileInfo.TimeIsDefined = (newTime != NULL);
92 if (newFileInfo.TimeIsDefined) 88 if (newFileInfo.TimeIsDefined)
93 newFileInfo.Time = *newTime; 89 newFileInfo.Time = *newTime;
94 newFileInfo.SizeIsDefined = (newSize != NULL); 90 newFileInfo.SizeIsDefined = (newSize != NULL);
@@ -99,7 +95,7 @@ STDMETHODIMP CExtractCallbackImp::AskOverwrite(
99 NOverwriteDialog::NResult::EEnum result = 95 NOverwriteDialog::NResult::EEnum result =
100 NOverwriteDialog::Execute(oldFileInfo, newFileInfo); 96 NOverwriteDialog::Execute(oldFileInfo, newFileInfo);
101 97
102 switch (result) 98 switch ((int)result)
103 { 99 {
104 case NOverwriteDialog::NResult::kCancel: 100 case NOverwriteDialog::NResult::kCancel:
105 // *answer = NOverwriteAnswer::kCancel; 101 // *answer = NOverwriteAnswer::kCancel;
@@ -132,7 +128,7 @@ static const char * const kExtractString = "Extracting";
132static const char * const kSkipString = "Skipping"; 128static const char * const kSkipString = "Skipping";
133static const char * const kReadString = "Reading"; 129static const char * const kReadString = "Reading";
134 130
135STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* isFolder */, Int32 askExtractMode, const UInt64 * /* position */) 131Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /* isFolder */, Int32 askExtractMode, const UInt64 * /* position */))
136{ 132{
137 MT_LOCK 133 MT_LOCK
138 134
@@ -146,7 +142,7 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /*
146 case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; break; 142 case NArchive::NExtract::NAskMode::kSkip: s = kSkipString; break;
147 case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; break; 143 case NArchive::NExtract::NAskMode::kReadExternal: s = kReadString; break;
148 default: s = "???"; // return E_FAIL; 144 default: s = "???"; // return E_FAIL;
149 }; 145 }
150 146
151 if (_percent) 147 if (_percent)
152 { 148 {
@@ -158,7 +154,7 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 /*
158 return CheckBreak2(); 154 return CheckBreak2();
159} 155}
160 156
161STDMETHODIMP CExtractCallbackImp::MessageError(const wchar_t *message) 157Z7_COM7F_IMF(CExtractCallbackImp::MessageError(const wchar_t *message))
162{ 158{
163 MT_LOCK 159 MT_LOCK
164 160
@@ -199,7 +195,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s)
199 } 195 }
200 if (messageID != 0) 196 if (messageID != 0)
201 { 197 {
202 s = g_StartupInfo.GetMsgString(messageID); 198 s = g_StartupInfo.GetMsgString((int)messageID);
203 s.Replace((AString)" '%s'", AString()); 199 s.Replace((AString)" '%s'", AString());
204 } 200 }
205 else if (opRes == NArchive::NExtract::NOperationResult::kUnavailable) 201 else if (opRes == NArchive::NExtract::NOperationResult::kUnavailable)
@@ -217,13 +213,13 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s)
217 else 213 else
218 { 214 {
219 s = "Error #"; 215 s = "Error #";
220 s.Add_UInt32(opRes); 216 s.Add_UInt32((UInt32)opRes);
221 } 217 }
222 } 218 }
223 } 219 }
224} 220}
225 221
226STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted) 222Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted))
227{ 223{
228 MT_LOCK 224 MT_LOCK
229 225
@@ -248,7 +244,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypte
248} 244}
249 245
250 246
251STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) 247Z7_COM7F_IMF(CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name))
252{ 248{
253 MT_LOCK 249 MT_LOCK
254 250
@@ -265,13 +261,13 @@ STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypt
265 261
266extern HRESULT GetPassword(UString &password); 262extern HRESULT GetPassword(UString &password);
267 263
268STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) 264Z7_COM7F_IMF(CExtractCallbackImp::CryptoGetTextPassword(BSTR *password))
269{ 265{
270 MT_LOCK 266 MT_LOCK
271 267
272 if (!m_PasswordIsDefined) 268 if (!m_PasswordIsDefined)
273 { 269 {
274 RINOK(GetPassword(m_Password)); 270 RINOK(GetPassword(m_Password))
275 m_PasswordIsDefined = true; 271 m_PasswordIsDefined = true;
276 } 272 }
277 return StringToBstr(m_Password, password); 273 return StringToBstr(m_Password, password);
diff --git a/CPP/7zip/UI/Far/ExtractEngine.h b/CPP/7zip/UI/Far/ExtractEngine.h
index 5861d92..2bee2ee 100644
--- a/CPP/7zip/UI/Far/ExtractEngine.h
+++ b/CPP/7zip/UI/Far/ExtractEngine.h
@@ -1,7 +1,7 @@
1// ExtractEngine.h 1// ExtractEngine.h
2 2
3#ifndef __EXTRACT_ENGINE_H 3#ifndef ZIP7_INC_EXTRACT_ENGINE_H
4#define __EXTRACT_ENGINE_H 4#define ZIP7_INC_EXTRACT_ENGINE_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
@@ -11,26 +11,14 @@
11 11
12#include "ProgressBox.h" 12#include "ProgressBox.h"
13 13
14class CExtractCallbackImp: 14Z7_CLASS_IMP_COM_3(
15 public IFolderArchiveExtractCallback, 15 CExtractCallbackImp
16 public IFolderArchiveExtractCallback2, 16 , IFolderArchiveExtractCallback
17 public ICryptoGetTextPassword, 17 , IFolderArchiveExtractCallback2
18 public CMyUnknownImp 18 , ICryptoGetTextPassword
19{ 19)
20public: 20 Z7_IFACE_COM7_IMP(IProgress)
21 MY_UNKNOWN_IMP2(ICryptoGetTextPassword, IFolderArchiveExtractCallback2)
22
23 // IProgress
24 STDMETHOD(SetTotal)(UInt64 size);
25 STDMETHOD(SetCompleted)(const UInt64 *completeValue);
26
27 INTERFACE_IFolderArchiveExtractCallback(;)
28 INTERFACE_IFolderArchiveExtractCallback2(;)
29
30 // ICryptoGetTextPassword
31 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
32 21
33private:
34 UString m_CurrentFilePath; 22 UString m_CurrentFilePath;
35 23
36 CProgressBox *_percent; 24 CProgressBox *_percent;
@@ -47,8 +35,6 @@ private:
47 */ 35 */
48 void AddErrorMessage(LPCTSTR message); 36 void AddErrorMessage(LPCTSTR message);
49public: 37public:
50 // CExtractCallbackImp() {}
51 ~CExtractCallbackImp();
52 void Init(UINT codePage, 38 void Init(UINT codePage,
53 CProgressBox *progressBox, 39 CProgressBox *progressBox,
54 bool passwordIsDefined, const UString &password); 40 bool passwordIsDefined, const UString &password);
diff --git a/CPP/7zip/UI/Far/Far.cpp b/CPP/7zip/UI/Far/Far.cpp
index a9e4791..74d5e60 100644
--- a/CPP/7zip/UI/Far/Far.cpp
+++ b/CPP/7zip/UI/Far/Far.cpp
@@ -3,12 +3,7 @@
3 3
4#include "StdAfx.h" 4#include "StdAfx.h"
5 5
6#ifdef __clang__
7 #pragma clang diagnostic ignored "-Wmissing-prototypes"
8#endif
9
10#include "../../../Common/MyWindows.h" 6#include "../../../Common/MyWindows.h"
11
12#include "../../../Common/MyInitGuid.h" 7#include "../../../Common/MyInitGuid.h"
13 8
14#include "../../../Common/StringConvert.h" 9#include "../../../Common/StringConvert.h"
@@ -35,10 +30,14 @@ static LPCTSTR const kRegisrtryValueNameEnabled = TEXT("UsedByDefault3");
35static const char * const kHelpTopicConfig = "Config"; 30static const char * const kHelpTopicConfig = "Config";
36static bool kPluginEnabledDefault = true; 31static bool kPluginEnabledDefault = true;
37 32
33extern
34HINSTANCE g_hInstance;
38HINSTANCE g_hInstance; 35HINSTANCE g_hInstance;
39 36
40namespace NFar { 37namespace NFar {
41 38
39extern
40const char *g_PluginName_for_Error;
42const char *g_PluginName_for_Error = "7-Zip"; 41const char *g_PluginName_for_Error = "7-Zip";
43 42
44} 43}
@@ -49,9 +48,16 @@ const char *g_PluginName_for_Error = "7-Zip";
49 48
50BOOL WINAPI DllMain( 49BOOL WINAPI DllMain(
51 #ifdef UNDER_CE 50 #ifdef UNDER_CE
52 HANDLE 51 HANDLE
52 #else
53 HINSTANCE
54 #endif
55 hInstance, DWORD dwReason, LPVOID);
56BOOL WINAPI DllMain(
57 #ifdef UNDER_CE
58 HANDLE
53 #else 59 #else
54 HINSTANCE 60 HINSTANCE
55 #endif 61 #endif
56 hInstance, DWORD dwReason, LPVOID) 62 hInstance, DWORD dwReason, LPVOID)
57{ 63{
@@ -89,7 +95,7 @@ EXTERN_C void WINAPI ExitFAR()
89 95
90EXTERN_C void WINAPI SetStartupInfo(const PluginStartupInfo *info) 96EXTERN_C void WINAPI SetStartupInfo(const PluginStartupInfo *info)
91{ 97{
92 MY_TRY_BEGIN; 98 MY_TRY_BEGIN
93 g_StartupInfo.Init(*info, kPliginNameForRegistry); 99 g_StartupInfo.Init(*info, kPliginNameForRegistry);
94 g_Options.Enabled = g_StartupInfo.QueryRegKeyValue( 100 g_Options.Enabled = g_StartupInfo.QueryRegKeyValue(
95 HKEY_CURRENT_USER, kRegisrtryMainKeyName, 101 HKEY_CURRENT_USER, kRegisrtryMainKeyName,
@@ -98,18 +104,16 @@ EXTERN_C void WINAPI SetStartupInfo(const PluginStartupInfo *info)
98 // OutputDebugStringA("SetStartupInfo"); 104 // OutputDebugStringA("SetStartupInfo");
99 // LoadGlobalCodecs(); 105 // LoadGlobalCodecs();
100 106
101 MY_TRY_END1("SetStartupInfo"); 107 MY_TRY_END1("SetStartupInfo")
102} 108}
103 109
104class COpenArchiveCallback: 110Z7_CLASS_IMP_COM_3(
105 public IArchiveOpenCallback, 111 COpenArchiveCallback
106 public IArchiveOpenVolumeCallback, 112 , IArchiveOpenCallback
107 public IArchiveOpenSetSubArchiveName, 113 , IProgress
108 public IProgress, 114 , ICryptoGetTextPassword
109 public ICryptoGetTextPassword, 115)
110 public CMyUnknownImp 116 // DWORD m_StartTickValue;
111{
112 DWORD m_StartTickValue;
113 bool m_MessageBoxIsShown; 117 bool m_MessageBoxIsShown;
114 118
115 CProgressBox _progressBox; 119 CProgressBox _progressBox;
@@ -117,53 +121,17 @@ class COpenArchiveCallback:
117 bool _numFilesTotalDefined; 121 bool _numFilesTotalDefined;
118 bool _numBytesTotalDefined; 122 bool _numBytesTotalDefined;
119 123
120 NFind::CFileInfo _fileInfo;
121 bool _subArchiveMode;
122 UString _subArchiveName;
123public: 124public:
124 bool PasswordIsDefined; 125 bool PasswordIsDefined;
125 UString Password; 126 UString Password;
126 127
127 FString _folderPrefix; 128 COpenArchiveCallback()
128 129 {}
129public:
130 MY_UNKNOWN_IMP4(
131 IArchiveOpenVolumeCallback,
132 IArchiveOpenSetSubArchiveName,
133 IProgress,
134 ICryptoGetTextPassword
135 )
136
137 // IProgress
138 STDMETHOD(SetTotal)(UInt64 total);
139 STDMETHOD(SetCompleted)(const UInt64 *aCompleteValue);
140
141 // IArchiveOpenCallback
142 STDMETHOD(SetTotal)(const UInt64 *numFiles, const UInt64 *numBytes);
143 STDMETHOD(SetCompleted)(const UInt64 *numFiles, const UInt64 *numBytes);
144
145 // IArchiveOpenVolumeCallback
146 STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value);
147 STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream);
148
149 STDMETHOD(SetSubArchiveName(const wchar_t *name))
150 {
151 _subArchiveMode = true;
152 _subArchiveName = name;
153 return S_OK;
154 }
155
156 // ICryptoGetTextPassword
157 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
158
159 COpenArchiveCallback(): _subArchiveMode(false) {}
160 130
161 void Init() 131 void Init()
162 { 132 {
163 PasswordIsDefined = false; 133 PasswordIsDefined = false;
164 134
165 _subArchiveMode = false;
166
167 _numFilesTotalDefined = false; 135 _numFilesTotalDefined = false;
168 _numBytesTotalDefined = false; 136 _numBytesTotalDefined = false;
169 137
@@ -174,13 +142,6 @@ public:
174 g_StartupInfo.GetMsgString(NMessageID::kReading)); 142 g_StartupInfo.GetMsgString(NMessageID::kReading));
175 } 143 }
176 void ShowMessage(); 144 void ShowMessage();
177
178 void LoadFileInfo(const FString &folderPrefix, const FString &fileName)
179 {
180 _folderPrefix = folderPrefix;
181 if (!_fileInfo.Find(_folderPrefix + fileName))
182 throw 1;
183 }
184}; 145};
185 146
186static HRESULT CheckBreak2() 147static HRESULT CheckBreak2()
@@ -202,7 +163,7 @@ void COpenArchiveCallback::ShowMessage()
202 _progressBox.Print(); 163 _progressBox.Print();
203} 164}
204 165
205STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes) 166Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes))
206{ 167{
207 _numFilesTotalDefined = (numFiles != NULL); 168 _numFilesTotalDefined = (numFiles != NULL);
208 if (_numFilesTotalDefined) 169 if (_numFilesTotalDefined)
@@ -215,7 +176,7 @@ STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64
215 return CheckBreak2(); 176 return CheckBreak2();
216} 177}
217 178
218STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes) 179Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes))
219{ 180{
220 if (numFiles) 181 if (numFiles)
221 _progressBox.Files = *numFiles; 182 _progressBox.Files = *numFiles;
@@ -228,63 +189,18 @@ STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UI
228} 189}
229 190
230 191
231STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 /* total */) 192Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 /* total */))
232{ 193{
233 return CheckBreak2(); 194 return CheckBreak2();
234} 195}
235 196
236STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 * /* completed */) 197Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 * /* completed */))
237{ 198{
238 ShowMessage(); 199 ShowMessage();
239 return CheckBreak2(); 200 return CheckBreak2();
240} 201}
241 202
242STDMETHODIMP COpenArchiveCallback::GetStream(const wchar_t *name, IInStream **inStream) 203HRESULT GetPassword(UString &password);
243{
244 if (WasEscPressed())
245 return E_ABORT;
246 if (_subArchiveMode)
247 return S_FALSE;
248 *inStream = NULL;
249 FString fullPath = _folderPrefix + us2fs(name);
250 if (!_fileInfo.Find(fullPath))
251 return S_FALSE;
252 if (_fileInfo.IsDir())
253 return S_FALSE;
254 CInFileStream *inFile = new CInFileStream;
255 CMyComPtr<IInStream> inStreamTemp = inFile;
256 if (!inFile->Open(fullPath))
257 return ::GetLastError();
258 *inStream = inStreamTemp.Detach();
259 return S_OK;
260}
261
262
263STDMETHODIMP COpenArchiveCallback::GetProperty(PROPID propID, PROPVARIANT *value)
264{
265 NCOM::CPropVariant prop;
266 if (_subArchiveMode)
267 {
268 switch (propID)
269 {
270 case kpidName: prop = _subArchiveName; break;
271 }
272 }
273 else
274 switch (propID)
275 {
276 case kpidName: prop = GetUnicodeString(_fileInfo.Name, CP_OEMCP); break;
277 case kpidIsDir: prop = _fileInfo.IsDir(); break;
278 case kpidSize: prop = _fileInfo.Size; break;
279 case kpidAttrib: prop = (UInt32)_fileInfo.Attrib; break;
280 case kpidCTime: prop = _fileInfo.CTime; break;
281 case kpidATime: prop = _fileInfo.ATime; break;
282 case kpidMTime: prop = _fileInfo.MTime; break;
283 }
284 prop.Detach(value);
285 return S_OK;
286}
287
288HRESULT GetPassword(UString &password) 204HRESULT GetPassword(UString &password)
289{ 205{
290 if (WasEscPressed()) 206 if (WasEscPressed())
@@ -297,7 +213,7 @@ HRESULT GetPassword(UString &password)
297 { DI_PSWEDIT, 5, 3, 70, 3, true, false, 0, true, -1, "", NULL } 213 { DI_PSWEDIT, 5, 3, 70, 3, true, false, 0, true, -1, "", NULL }
298 }; 214 };
299 215
300 const int kNumItems = ARRAY_SIZE(initItems); 216 const int kNumItems = Z7_ARRAY_SIZE(initItems);
301 FarDialogItem dialogItems[kNumItems]; 217 FarDialogItem dialogItems[kNumItems];
302 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumItems); 218 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumItems);
303 219
@@ -309,11 +225,11 @@ HRESULT GetPassword(UString &password)
309 return S_OK; 225 return S_OK;
310} 226}
311 227
312STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password) 228Z7_COM7F_IMF(COpenArchiveCallback::CryptoGetTextPassword(BSTR *password))
313{ 229{
314 if (!PasswordIsDefined) 230 if (!PasswordIsDefined)
315 { 231 {
316 RINOK(GetPassword(Password)); 232 RINOK(GetPassword(Password))
317 PasswordIsDefined = true; 233 PasswordIsDefined = true;
318 } 234 }
319 return StringToBstr(Password, password); 235 return StringToBstr(Password, password);
@@ -357,14 +273,19 @@ static HANDLE MyOpenFilePluginW(const wchar_t *name, bool isAbortCodeSupported)
357 } 273 }
358 274
359 COpenArchiveCallback *openArchiveCallbackSpec = new COpenArchiveCallback; 275 COpenArchiveCallback *openArchiveCallbackSpec = new COpenArchiveCallback;
360 CMyComPtr<IArchiveOpenCallback> openArchiveCallback = openArchiveCallbackSpec; 276 CMyComPtr<IArchiveOpenCallback> uiCallback = openArchiveCallbackSpec;
277
278 /* COpenCallbackImp object will exist after Open stage for multivolume archioves */
279 COpenCallbackImp *impSpec = new COpenCallbackImp;
280 CMyComPtr<IArchiveOpenCallback> impCallback = impSpec;
281 impSpec->ReOpenCallback = openArchiveCallbackSpec; // we set pointer without reference counter
361 282
362 // if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0) 283 // if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0)
363 openArchiveCallbackSpec->Init(); 284 openArchiveCallbackSpec->Init();
364 { 285 {
365 FString dirPrefix, fileName; 286 FString dirPrefix, fileName;
366 GetFullPathAndSplit(fullName, dirPrefix, fileName); 287 GetFullPathAndSplit(fullName, dirPrefix, fileName);
367 openArchiveCallbackSpec->LoadFileInfo(dirPrefix, fileName); 288 impSpec->Init2(dirPrefix, fileName);
368 } 289 }
369 290
370 // ::OutputDebugStringA("before OpenArchive\n"); 291 // ::OutputDebugStringA("before OpenArchive\n");
@@ -373,7 +294,7 @@ static HANDLE MyOpenFilePluginW(const wchar_t *name, bool isAbortCodeSupported)
373 archiveHandler = agent; 294 archiveHandler = agent;
374 CMyComBSTR archiveType; 295 CMyComBSTR archiveType;
375 HRESULT result = archiveHandler->Open(NULL, 296 HRESULT result = archiveHandler->Open(NULL,
376 GetUnicodeString(fullName, CP_OEMCP), UString(), &archiveType, openArchiveCallback); 297 GetUnicodeString(fullName, CP_OEMCP), UString(), &archiveType, impCallback);
377 /* 298 /*
378 HRESULT result = ::OpenArchive(fullName, &archiveHandler, 299 HRESULT result = ::OpenArchive(fullName, &archiveHandler,
379 archiverInfoResult, defaultName, openArchiveCallback); 300 archiverInfoResult, defaultName, openArchiveCallback);
@@ -427,7 +348,7 @@ static HANDLE MyOpenFilePlugin(const char *name, bool isAbortCodeSupported)
427 348
428EXTERN_C HANDLE WINAPI OpenFilePlugin(char *name, const unsigned char * /* data */, int /* dataSize */) 349EXTERN_C HANDLE WINAPI OpenFilePlugin(char *name, const unsigned char * /* data */, int /* dataSize */)
429{ 350{
430 MY_TRY_BEGIN; 351 MY_TRY_BEGIN
431 // OutputDebugStringA("--- OpenFilePlugin"); 352 // OutputDebugStringA("--- OpenFilePlugin");
432 if (name == NULL || (!g_Options.Enabled)) 353 if (name == NULL || (!g_Options.Enabled))
433 { 354 {
@@ -435,13 +356,13 @@ EXTERN_C HANDLE WINAPI OpenFilePlugin(char *name, const unsigned char * /* data
435 return(INVALID_HANDLE_VALUE); 356 return(INVALID_HANDLE_VALUE);
436 } 357 }
437 return MyOpenFilePlugin(name, true); // isAbortCodeSupported 358 return MyOpenFilePlugin(name, true); // isAbortCodeSupported
438 MY_TRY_END2("OpenFilePlugin", INVALID_HANDLE_VALUE); 359 MY_TRY_END2("OpenFilePlugin", INVALID_HANDLE_VALUE)
439} 360}
440 361
441/* 362/*
442EXTERN_C HANDLE WINAPI OpenFilePluginW(const wchar_t *name,const unsigned char *Data,int DataSize,int OpMode) 363EXTERN_C HANDLE WINAPI OpenFilePluginW(const wchar_t *name,const unsigned char *Data,int DataSize,int OpMode)
443{ 364{
444 MY_TRY_BEGIN; 365 MY_TRY_BEGIN
445 if (name == NULL || (!g_Options.Enabled)) 366 if (name == NULL || (!g_Options.Enabled))
446 { 367 {
447 // if (!Opt.ProcessShiftF1) 368 // if (!Opt.ProcessShiftF1)
@@ -455,7 +376,7 @@ EXTERN_C HANDLE WINAPI OpenFilePluginW(const wchar_t *name,const unsigned char *
455 376
456EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item) 377EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item)
457{ 378{
458 MY_TRY_BEGIN; 379 MY_TRY_BEGIN
459 380
460 if (openFrom == OPEN_COMMANDLINE) 381 if (openFrom == OPEN_COMMANDLINE)
461 { 382 {
@@ -511,13 +432,13 @@ EXTERN_C HANDLE WINAPI OpenPlugin(int openFrom, INT_PTR item)
511 } 432 }
512 433
513 return INVALID_HANDLE_VALUE; 434 return INVALID_HANDLE_VALUE;
514 MY_TRY_END2("OpenPlugin", INVALID_HANDLE_VALUE); 435 MY_TRY_END2("OpenPlugin", INVALID_HANDLE_VALUE)
515} 436}
516 437
517EXTERN_C void WINAPI ClosePlugin(HANDLE plugin) 438EXTERN_C void WINAPI ClosePlugin(HANDLE plugin)
518{ 439{
519 // OutputDebugStringA("-- ClosePlugin --- START"); 440 // OutputDebugStringA("-- ClosePlugin --- START");
520 // MY_TRY_BEGIN; 441 // MY_TRY_BEGIN
521 delete (CPlugin *)plugin; 442 delete (CPlugin *)plugin;
522 // OutputDebugStringA("-- ClosePlugin --- END"); 443 // OutputDebugStringA("-- ClosePlugin --- END");
523 // MY_TRY_END1("ClosePlugin"); 444 // MY_TRY_END1("ClosePlugin");
@@ -525,14 +446,14 @@ EXTERN_C void WINAPI ClosePlugin(HANDLE plugin)
525 446
526EXTERN_C int WINAPI GetFindData(HANDLE plugin, struct PluginPanelItem **panelItems, int *itemsNumber, int opMode) 447EXTERN_C int WINAPI GetFindData(HANDLE plugin, struct PluginPanelItem **panelItems, int *itemsNumber, int opMode)
527{ 448{
528 MY_TRY_BEGIN; 449 MY_TRY_BEGIN
529 return(((CPlugin *)plugin)->GetFindData(panelItems, itemsNumber, opMode)); 450 return(((CPlugin *)plugin)->GetFindData(panelItems, itemsNumber, opMode));
530 MY_TRY_END2("GetFindData", FALSE); 451 MY_TRY_END2("GetFindData", FALSE)
531} 452}
532 453
533EXTERN_C void WINAPI FreeFindData(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber) 454EXTERN_C void WINAPI FreeFindData(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber)
534{ 455{
535 // MY_TRY_BEGIN; 456 // MY_TRY_BEGIN
536 ((CPlugin *)plugin)->FreeFindData(panelItems, itemsNumber); 457 ((CPlugin *)plugin)->FreeFindData(panelItems, itemsNumber);
537 // MY_TRY_END1("FreeFindData"); 458 // MY_TRY_END1("FreeFindData");
538} 459}
@@ -540,43 +461,43 @@ EXTERN_C void WINAPI FreeFindData(HANDLE plugin, struct PluginPanelItem *panelIt
540EXTERN_C int WINAPI GetFiles(HANDLE plugin, struct PluginPanelItem *panelItems, 461EXTERN_C int WINAPI GetFiles(HANDLE plugin, struct PluginPanelItem *panelItems,
541 int itemsNumber, int move, char *destPath, int opMode) 462 int itemsNumber, int move, char *destPath, int opMode)
542{ 463{
543 MY_TRY_BEGIN; 464 MY_TRY_BEGIN
544 return(((CPlugin *)plugin)->GetFiles(panelItems, itemsNumber, move, destPath, opMode)); 465 return(((CPlugin *)plugin)->GetFiles(panelItems, (unsigned)itemsNumber, move, destPath, opMode));
545 MY_TRY_END2("GetFiles", NFileOperationReturnCode::kError); 466 MY_TRY_END2("GetFiles", NFileOperationReturnCode::kError)
546} 467}
547 468
548EXTERN_C int WINAPI SetDirectory(HANDLE plugin, const char *dir, int opMode) 469EXTERN_C int WINAPI SetDirectory(HANDLE plugin, const char *dir, int opMode)
549{ 470{
550 MY_TRY_BEGIN; 471 MY_TRY_BEGIN
551 return(((CPlugin *)plugin)->SetDirectory(dir, opMode)); 472 return(((CPlugin *)plugin)->SetDirectory(dir, opMode));
552 MY_TRY_END2("SetDirectory", FALSE); 473 MY_TRY_END2("SetDirectory", FALSE)
553} 474}
554 475
555EXTERN_C void WINAPI GetPluginInfo(struct PluginInfo *info) 476EXTERN_C void WINAPI GetPluginInfo(struct PluginInfo *info)
556{ 477{
557 MY_TRY_BEGIN; 478 MY_TRY_BEGIN
558 479
559 info->StructSize = sizeof(*info); 480 info->StructSize = sizeof(*info);
560 info->Flags = 0; 481 info->Flags = 0;
561 info->DiskMenuStrings = NULL; 482 info->DiskMenuStrings = NULL;
562 info->DiskMenuNumbers = NULL; 483 info->DiskMenuNumbers = NULL;
563 info->DiskMenuStringsNumber = 0; 484 info->DiskMenuStringsNumber = 0;
564 static const char *pluginMenuStrings[2]; 485 static char *pluginMenuStrings[2];
565 pluginMenuStrings[0] = g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString); 486 pluginMenuStrings[0] = const_cast<char *>(g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString));
566 pluginMenuStrings[1] = g_StartupInfo.GetMsgString(NMessageID::kCreateArchiveMenuString); 487 pluginMenuStrings[1] = const_cast<char *>(g_StartupInfo.GetMsgString(NMessageID::kCreateArchiveMenuString));
567 info->PluginMenuStrings = (char **)pluginMenuStrings; 488 info->PluginMenuStrings = (char **)pluginMenuStrings;
568 info->PluginMenuStringsNumber = 2; 489 info->PluginMenuStringsNumber = 2;
569 static const char *pluginCfgStrings[1]; 490 static char *pluginCfgStrings[1];
570 pluginCfgStrings[0] = g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString); 491 pluginCfgStrings[0] = const_cast<char *>(g_StartupInfo.GetMsgString(NMessageID::kOpenArchiveMenuString));
571 info->PluginConfigStrings = (char **)pluginCfgStrings; 492 info->PluginConfigStrings = (char **)pluginCfgStrings;
572 info->PluginConfigStringsNumber = ARRAY_SIZE(pluginCfgStrings); 493 info->PluginConfigStringsNumber = Z7_ARRAY_SIZE(pluginCfgStrings);
573 info->CommandPrefix = (char *)kCommandPrefix; 494 info->CommandPrefix = const_cast<char *>(kCommandPrefix);
574 MY_TRY_END1("GetPluginInfo"); 495 MY_TRY_END1("GetPluginInfo")
575} 496}
576 497
577EXTERN_C int WINAPI Configure(int /* itemNumber */) 498EXTERN_C int WINAPI Configure(int /* itemNumber */)
578{ 499{
579 MY_TRY_BEGIN; 500 MY_TRY_BEGIN
580 501
581 const int kEnabledCheckBoxIndex = 1; 502 const int kEnabledCheckBoxIndex = 1;
582 503
@@ -591,7 +512,7 @@ EXTERN_C int WINAPI Configure(int /* itemNumber */)
591 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }, 512 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL },
592 }; 513 };
593 514
594 const int kNumDialogItems = ARRAY_SIZE(initItems); 515 const int kNumDialogItems = Z7_ARRAY_SIZE(initItems);
595 const int kOkButtonIndex = kNumDialogItems - 2; 516 const int kOkButtonIndex = kNumDialogItems - 2;
596 517
597 FarDialogItem dialogItems[kNumDialogItems]; 518 FarDialogItem dialogItems[kNumDialogItems];
@@ -608,33 +529,59 @@ EXTERN_C int WINAPI Configure(int /* itemNumber */)
608 g_StartupInfo.SetRegKeyValue(HKEY_CURRENT_USER, kRegisrtryMainKeyName, 529 g_StartupInfo.SetRegKeyValue(HKEY_CURRENT_USER, kRegisrtryMainKeyName,
609 kRegisrtryValueNameEnabled, g_Options.Enabled); 530 kRegisrtryValueNameEnabled, g_Options.Enabled);
610 return(TRUE); 531 return(TRUE);
611 MY_TRY_END2("Configure", FALSE); 532 MY_TRY_END2("Configure", FALSE)
612} 533}
613 534
614EXTERN_C void WINAPI GetOpenPluginInfo(HANDLE plugin,struct OpenPluginInfo *info) 535EXTERN_C void WINAPI GetOpenPluginInfo(HANDLE plugin,struct OpenPluginInfo *info)
615{ 536{
616 MY_TRY_BEGIN; 537 MY_TRY_BEGIN
617 ((CPlugin *)plugin)->GetOpenPluginInfo(info); 538 ((CPlugin *)plugin)->GetOpenPluginInfo(info);
618 MY_TRY_END1("GetOpenPluginInfo"); 539 MY_TRY_END1("GetOpenPluginInfo")
619} 540}
620 541
621EXTERN_C int WINAPI PutFiles(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber, int move, int opMode) 542EXTERN_C int WINAPI PutFiles(HANDLE plugin, struct PluginPanelItem *panelItems, int itemsNumber, int move, int opMode)
622{ 543{
623 MY_TRY_BEGIN; 544 MY_TRY_BEGIN
624 return (((CPlugin *)plugin)->PutFiles(panelItems, itemsNumber, move, opMode)); 545 return (((CPlugin *)plugin)->PutFiles(panelItems, (unsigned)itemsNumber, move, opMode));
625 MY_TRY_END2("PutFiles", NFileOperationReturnCode::kError); 546 MY_TRY_END2("PutFiles", NFileOperationReturnCode::kError)
626} 547}
627 548
628EXTERN_C int WINAPI DeleteFiles(HANDLE plugin, PluginPanelItem *panelItems, int itemsNumber, int opMode) 549EXTERN_C int WINAPI DeleteFiles(HANDLE plugin, PluginPanelItem *panelItems, int itemsNumber, int opMode)
629{ 550{
630 MY_TRY_BEGIN; 551 MY_TRY_BEGIN
631 return (((CPlugin *)plugin)->DeleteFiles(panelItems, itemsNumber, opMode)); 552 return (((CPlugin *)plugin)->DeleteFiles(panelItems, (unsigned)itemsNumber, opMode));
632 MY_TRY_END2("DeleteFiles", FALSE); 553 MY_TRY_END2("DeleteFiles", FALSE)
633} 554}
634 555
635EXTERN_C int WINAPI ProcessKey(HANDLE plugin, int key, unsigned int controlState) 556EXTERN_C int WINAPI ProcessKey(HANDLE plugin, int key, unsigned int controlState)
636{ 557{
637 MY_TRY_BEGIN; 558 MY_TRY_BEGIN
559 /* FIXME: after folder creation with F7, it doesn't reload new file list
560 We need some to reload it */
638 return (((CPlugin *)plugin)->ProcessKey(key, controlState)); 561 return (((CPlugin *)plugin)->ProcessKey(key, controlState));
639 MY_TRY_END2("ProcessKey", FALSE); 562 MY_TRY_END2("ProcessKey", FALSE)
563}
564
565/*
566struct MakeDirectoryInfo
567{
568 size_t StructSize;
569 HANDLE hPanel;
570 const wchar_t *Name;
571 OPERATION_MODES OpMode;
572 void* Instance;
573};
574
575typedef INT_PTR MY_intptr_t;
576
577MY_intptr_t WINAPI MakeDirectoryW(struct MakeDirectoryInfo *Info)
578{
579 MY_TRY_BEGIN
580 if (Info->StructSize < sizeof(MakeDirectoryInfo))
581 {
582 return 0;
583 }
584 return 0;
585 MY_TRY_END2("MakeDirectoryW", FALSE);
640} 586}
587*/
diff --git a/CPP/7zip/UI/Far/Far.dsp b/CPP/7zip/UI/Far/Far.dsp
index bd6d8fd..823c728 100644
--- a/CPP/7zip/UI/Far/Far.dsp
+++ b/CPP/7zip/UI/Far/Far.dsp
@@ -43,7 +43,7 @@ RSC=rc.exe
43# PROP Ignore_Export_Lib 1 43# PROP Ignore_Export_Lib 1
44# PROP Target_Dir "" 44# PROP Target_Dir ""
45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /YX /FD /c 45# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "FAR_EXPORTS" /YX /FD /c
46# 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 46# 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
47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 47# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 48# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
49# ADD BASE RSC /l 0x419 /d "NDEBUG" 49# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -70,7 +70,7 @@ LINK32=link.exe
70# PROP Ignore_Export_Lib 1 70# PROP Ignore_Export_Lib 1
71# PROP Target_Dir "" 71# PROP Target_Dir ""
72# 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 72# 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
73# 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 73# 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
74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 74# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 75# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
76# ADD BASE RSC /l 0x419 /d "_DEBUG" 76# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -114,6 +114,10 @@ SOURCE=.\StdAfx.h
114# PROP Default_Filter "" 114# PROP Default_Filter ""
115# Begin Source File 115# Begin Source File
116 116
117SOURCE=..\..\..\Common\Common.h
118# End Source File
119# Begin Source File
120
117SOURCE=..\..\..\Common\CRC.cpp 121SOURCE=..\..\..\Common\CRC.cpp
118# End Source File 122# End Source File
119# Begin Source File 123# Begin Source File
@@ -134,6 +138,10 @@ SOURCE=..\..\..\Common\IntToString.h
134# End Source File 138# End Source File
135# Begin Source File 139# Begin Source File
136 140
141SOURCE=..\..\..\Common\MyCom.h
142# End Source File
143# Begin Source File
144
137SOURCE=..\..\..\Common\MyString.cpp 145SOURCE=..\..\..\Common\MyString.cpp
138# End Source File 146# End Source File
139# Begin Source File 147# Begin Source File
@@ -142,6 +150,10 @@ SOURCE=..\..\..\Common\MyString.h
142# End Source File 150# End Source File
143# Begin Source File 151# Begin Source File
144 152
153SOURCE=..\..\..\Common\MyTypes.h
154# End Source File
155# Begin Source File
156
145SOURCE=..\..\..\Common\MyVector.cpp 157SOURCE=..\..\..\Common\MyVector.cpp
146# End Source File 158# End Source File
147# Begin Source File 159# Begin Source File
@@ -150,6 +162,10 @@ SOURCE=..\..\..\Common\MyVector.h
150# End Source File 162# End Source File
151# Begin Source File 163# Begin Source File
152 164
165SOURCE=..\..\..\Common\MyWindows.h
166# End Source File
167# Begin Source File
168
153SOURCE=..\..\..\Common\NewHandler.cpp 169SOURCE=..\..\..\Common\NewHandler.cpp
154# End Source File 170# End Source File
155# Begin Source File 171# Begin Source File
@@ -334,6 +350,14 @@ SOURCE=..\..\..\Windows\FileName.h
334# End Source File 350# End Source File
335# Begin Source File 351# Begin Source File
336 352
353SOURCE=..\..\..\Windows\FileSystem.cpp
354# End Source File
355# Begin Source File
356
357SOURCE=..\..\..\Windows\FileSystem.h
358# End Source File
359# Begin Source File
360
337SOURCE=..\..\..\Windows\PropVariant.cpp 361SOURCE=..\..\..\Windows\PropVariant.cpp
338# End Source File 362# End Source File
339# Begin Source File 363# Begin Source File
@@ -374,6 +398,14 @@ SOURCE=..\..\..\Windows\Synchronization.h
374# End Source File 398# End Source File
375# Begin Source File 399# Begin Source File
376 400
401SOURCE=..\..\..\Windows\System.cpp
402# End Source File
403# Begin Source File
404
405SOURCE=..\..\..\Windows\System.h
406# End Source File
407# Begin Source File
408
377SOURCE=..\..\..\Windows\TimeUtils.cpp 409SOURCE=..\..\..\Windows\TimeUtils.cpp
378# End Source File 410# End Source File
379# Begin Source File 411# Begin Source File
@@ -562,10 +594,6 @@ SOURCE=..\Agent\ArchiveFolder.cpp
562# End Source File 594# End Source File
563# Begin Source File 595# Begin Source File
564 596
565SOURCE=..\Agent\ArchiveFolderOpen.cpp
566# End Source File
567# Begin Source File
568
569SOURCE=..\Agent\ArchiveFolderOut.cpp 597SOURCE=..\Agent\ArchiveFolderOut.cpp
570# End Source File 598# End Source File
571# Begin Source File 599# Begin Source File
@@ -700,6 +728,14 @@ SOURCE=..\..\..\..\C\7zCrcOpt.c
700# End Source File 728# End Source File
701# Begin Source File 729# Begin Source File
702 730
731SOURCE=..\..\..\..\C\7zTypes.h
732# End Source File
733# Begin Source File
734
735SOURCE=..\..\..\..\C\7zWindows.h
736# End Source File
737# Begin Source File
738
703SOURCE=..\..\..\..\C\Alloc.c 739SOURCE=..\..\..\..\C\Alloc.c
704# SUBTRACT CPP /YX /Yc /Yu 740# SUBTRACT CPP /YX /Yc /Yu
705# End Source File 741# End Source File
@@ -709,6 +745,10 @@ SOURCE=..\..\..\..\C\Alloc.h
709# End Source File 745# End Source File
710# Begin Source File 746# Begin Source File
711 747
748SOURCE=..\..\..\..\C\Compiler.h
749# End Source File
750# Begin Source File
751
712SOURCE=..\..\..\..\C\CpuArch.c 752SOURCE=..\..\..\..\C\CpuArch.c
713# SUBTRACT CPP /YX /Yc /Yu 753# SUBTRACT CPP /YX /Yc /Yu
714# End Source File 754# End Source File
diff --git a/CPP/7zip/UI/Far/FarPlugin.h b/CPP/7zip/UI/Far/FarPlugin.h
index 859d319..ad3ed38 100644
--- a/CPP/7zip/UI/Far/FarPlugin.h
+++ b/CPP/7zip/UI/Far/FarPlugin.h
@@ -16,8 +16,8 @@ typedef struct _CHAR_INFO {
16} CHAR_INFO, *PCHAR_INFO; 16} CHAR_INFO, *PCHAR_INFO;
17#endif 17#endif
18 18
19#ifndef __FAR_PLUGIN_H 19#ifndef ZIP7_INC_FAR_PLUGIN_H
20#define __FAR_PLUGIN_H 20#define ZIP7_INC_FAR_PLUGIN_H
21 21
22#ifndef _WIN64 22#ifndef _WIN64
23#if defined(__BORLANDC__) && (__BORLANDC <= 0x520) 23#if defined(__BORLANDC__) && (__BORLANDC <= 0x520)
@@ -525,5 +525,36 @@ EXTERN_C_BEGIN
525 525
526EXTERN_C_END 526EXTERN_C_END
527*/ 527*/
528EXTERN_C_BEGIN
529
530 void WINAPI _export ClosePlugin(HANDLE hPlugin);
531 int WINAPI _export Compare(HANDLE hPlugin,const struct PluginPanelItem *Item1,const struct PluginPanelItem *Item2,unsigned int Mode);
532 int WINAPI _export Configure(int ItemNumber);
533 int WINAPI _export DeleteFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int OpMode);
534 void WINAPI _export ExitFAR(void);
535 void WINAPI _export FreeFindData(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber);
536 void WINAPI _export FreeVirtualFindData(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber);
537 int WINAPI _export GetFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int Move,char *DestPath,int OpMode);
538 int WINAPI _export GetFindData(HANDLE hPlugin,struct PluginPanelItem **pPanelItem,int *pItemsNumber,int OpMode);
539 int WINAPI _export GetMinFarVersion(void);
540 void WINAPI _export GetOpenPluginInfo(HANDLE hPlugin,struct OpenPluginInfo *Info);
541 void WINAPI _export GetPluginInfo(struct PluginInfo *Info);
542 int WINAPI _export GetVirtualFindData(HANDLE hPlugin,struct PluginPanelItem **pPanelItem,int *pItemsNumber,const char *Path);
543 int WINAPI _export MakeDirectory(HANDLE hPlugin,char *Name,int OpMode);
544 HANDLE WINAPI _export OpenFilePlugin(char *Name,const unsigned char *Data,int DataSize);
545 HANDLE WINAPI _export OpenPlugin(int OpenFrom,INT_PTR Item);
546 int WINAPI _export ProcessDialogEvent(int Event,void *Param);
547 int WINAPI _export ProcessEditorEvent(int Event,void *Param);
548 int WINAPI _export ProcessEditorInput(const INPUT_RECORD *Rec);
549 int WINAPI _export ProcessEvent(HANDLE hPlugin,int Event,void *Param);
550 int WINAPI _export ProcessHostFile(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int OpMode);
551 int WINAPI _export ProcessKey(HANDLE hPlugin,int Key,unsigned int ControlState);
552 int WINAPI _export ProcessViewerEvent(int Event,void *Param);
553 int WINAPI _export PutFiles(HANDLE hPlugin,struct PluginPanelItem *PanelItem,int ItemsNumber,int Move,int OpMode);
554 int WINAPI _export SetDirectory(HANDLE hPlugin,const char *Dir,int OpMode);
555 int WINAPI _export SetFindList(HANDLE hPlugin,const struct PluginPanelItem *PanelItem,int ItemsNumber);
556 void WINAPI _export SetStartupInfo(const struct PluginStartupInfo *Info);
557
558EXTERN_C_END
528 559
529#endif 560#endif
diff --git a/CPP/7zip/UI/Far/FarUtils.cpp b/CPP/7zip/UI/Far/FarUtils.cpp
index 3bdb989..9fddbc1 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)
36} 36}
37 37
38int CStartupInfo::ShowMessage(unsigned int flags, 38int CStartupInfo::ShowMessage(unsigned int flags,
39 const char *helpTopic, const char **items, int numItems, int numButtons) 39 const char *helpTopic, const char **items, unsigned numItems, int numButtons)
40{ 40{
41 return m_Data.Message(m_Data.ModuleNumber, flags, helpTopic, 41 return m_Data.Message(m_Data.ModuleNumber, flags, helpTopic,
42 items, numItems, numButtons); 42 items, (int)numItems, numButtons);
43} 43}
44 44
45namespace NMessageID 45namespace NMessageID
@@ -53,7 +53,7 @@ namespace NMessageID
53 }; 53 };
54} 54}
55 55
56int CStartupInfo::ShowWarningWithOk(const char **items, int numItems) 56int CStartupInfo::ShowWarningWithOk(const char **items, unsigned numItems)
57{ 57{
58 return ShowMessage(FMSG_WARNING | FMSG_MB_OK, NULL, items, numItems, 0); 58 return ShowMessage(FMSG_WARNING | FMSG_MB_OK, NULL, items, numItems, 0);
59} 59}
@@ -76,7 +76,7 @@ int CStartupInfo::ShowErrorMessage(const char *message)
76 AString s; 76 AString s;
77 SetErrorTitle(s); 77 SetErrorTitle(s);
78 const char *items[]= { s, message }; 78 const char *items[]= { s, message };
79 return ShowWarningWithOk(items, ARRAY_SIZE(items)); 79 return ShowWarningWithOk(items, Z7_ARRAY_SIZE(items));
80} 80}
81*/ 81*/
82 82
@@ -85,7 +85,7 @@ int CStartupInfo::ShowErrorMessage2(const char *m1, const char *m2)
85 AString s; 85 AString s;
86 SetErrorTitle(s); 86 SetErrorTitle(s);
87 const char *items[]= { s, m1, m2 }; 87 const char *items[]= { s, m1, m2 };
88 return ShowWarningWithOk(items, ARRAY_SIZE(items)); 88 return ShowWarningWithOk(items, Z7_ARRAY_SIZE(items));
89} 89}
90 90
91static void SplitString(const AString &src, AStringVector &destStrings) 91static void SplitString(const AString &src, AStringVector &destStrings)
@@ -145,14 +145,14 @@ int CStartupInfo::ShowMessage(int messageId)
145} 145}
146 146
147int CStartupInfo::ShowDialog(int X1, int Y1, int X2, int Y2, 147int CStartupInfo::ShowDialog(int X1, int Y1, int X2, int Y2,
148 const char *helpTopic, struct FarDialogItem *items, int numItems) 148 const char *helpTopic, struct FarDialogItem *items, unsigned numItems)
149{ 149{
150 return m_Data.Dialog(m_Data.ModuleNumber, X1, Y1, X2, Y2, (char *)helpTopic, 150 return m_Data.Dialog(m_Data.ModuleNumber, X1, Y1, X2, Y2, const_cast<char *>(helpTopic),
151 items, numItems); 151 items, (int)numItems);
152} 152}
153 153
154int CStartupInfo::ShowDialog(int sizeX, int sizeY, 154int CStartupInfo::ShowDialog(int sizeX, int sizeY,
155 const char *helpTopic, struct FarDialogItem *items, int numItems) 155 const char *helpTopic, struct FarDialogItem *items, unsigned numItems)
156{ 156{
157 return ShowDialog(-1, -1, sizeX, sizeY, helpTopic, items, numItems); 157 return ShowDialog(-1, -1, sizeX, sizeY, helpTopic, items, numItems);
158} 158}
@@ -160,9 +160,9 @@ int CStartupInfo::ShowDialog(int sizeX, int sizeY,
160inline static BOOL GetBOOLValue(bool v) { return (v? TRUE: FALSE); } 160inline static BOOL GetBOOLValue(bool v) { return (v? TRUE: FALSE); }
161 161
162void CStartupInfo::InitDialogItems(const CInitDialogItem *srcItems, 162void CStartupInfo::InitDialogItems(const CInitDialogItem *srcItems,
163 FarDialogItem *destItems, int numItems) 163 FarDialogItem *destItems, unsigned numItems)
164{ 164{
165 for (int i = 0; i < numItems; i++) 165 for (unsigned i = 0; i < numItems; i++)
166 { 166 {
167 const CInitDialogItem &srcItem = srcItems[i]; 167 const CInitDialogItem &srcItem = srcItems[i];
168 FarDialogItem &destItem = destItems[i]; 168 FarDialogItem &destItem = destItems[i];
@@ -356,7 +356,7 @@ bool CStartupInfo::ControlClearPanelSelection()
356 if (!ControlGetActivePanelInfo(panelInfo)) 356 if (!ControlGetActivePanelInfo(panelInfo))
357 return false; 357 return false;
358 for (int i = 0; i < panelInfo.ItemsNumber; i++) 358 for (int i = 0; i < panelInfo.ItemsNumber; i++)
359 panelInfo.PanelItems[i].Flags &= ~PPIF_SELECTED; 359 panelInfo.PanelItems[i].Flags &= ~(DWORD)PPIF_SELECTED;
360 return ControlSetSelection(panelInfo); 360 return ControlSetSelection(panelInfo);
361} 361}
362 362
@@ -374,10 +374,13 @@ int CStartupInfo::Menu(
374 int *breakKeys, 374 int *breakKeys,
375 int *breakCode, 375 int *breakCode,
376 struct FarMenuItem *items, 376 struct FarMenuItem *items,
377 int numItems) 377 unsigned numItems)
378{ 378{
379 return m_Data.Menu(m_Data.ModuleNumber, x, y, maxHeight, flags, (char *)title, 379 return m_Data.Menu(m_Data.ModuleNumber, x, y, maxHeight, flags,
380 (char *)aBottom, (char *)helpTopic, breakKeys, breakCode, items, numItems); 380 const_cast<char *>(title),
381 const_cast<char *>(aBottom),
382 const_cast<char *>(helpTopic),
383 breakKeys, breakCode, items, (int)numItems);
381} 384}
382 385
383int CStartupInfo::Menu( 386int CStartupInfo::Menu(
@@ -385,7 +388,7 @@ int CStartupInfo::Menu(
385 const char *title, 388 const char *title,
386 const char *helpTopic, 389 const char *helpTopic,
387 struct FarMenuItem *items, 390 struct FarMenuItem *items,
388 int numItems) 391 unsigned numItems)
389{ 392{
390 return Menu(-1, -1, 0, flags, title, NULL, helpTopic, NULL, 393 return Menu(-1, -1, 0, flags, title, NULL, helpTopic, NULL,
391 NULL, items, numItems); 394 NULL, items, numItems);
@@ -405,7 +408,7 @@ int CStartupInfo::Menu(
405 item.Checked = 0; 408 item.Checked = 0;
406 item.Separator = 0; 409 item.Separator = 0;
407 item.Selected = ((int)i == selectedItem); 410 item.Selected = ((int)i == selectedItem);
408 const AString reducedString (items[i].Left(ARRAY_SIZE(item.Text) - 1)); 411 const AString reducedString (items[i].Left(Z7_ARRAY_SIZE(item.Text) - 1));
409 MyStringCopy(item.Text, reducedString); 412 MyStringCopy(item.Text, reducedString);
410 farMenuItems.Add(item); 413 farMenuItems.Add(item);
411 } 414 }
@@ -435,7 +438,7 @@ void CScreenRestorer::Restore()
435 g_StartupInfo.RestoreScreen(m_HANDLE); 438 g_StartupInfo.RestoreScreen(m_HANDLE);
436 m_Saved = false; 439 m_Saved = false;
437 } 440 }
438}; 441}
439 442
440int PrintErrorMessage(const char *message, unsigned code) 443int PrintErrorMessage(const char *message, unsigned code)
441{ 444{
@@ -471,7 +474,7 @@ int PrintErrorMessage(const char *message, const wchar_t *name, unsigned maxLen)
471 474
472int ShowSysErrorMessage(DWORD errorCode) 475int ShowSysErrorMessage(DWORD errorCode)
473{ 476{
474 UString message = NError::MyFormatMessage(errorCode); 477 const UString message = NError::MyFormatMessage(errorCode);
475 return g_StartupInfo.ShowErrorMessage(UnicodeStringToMultiByte(message, CP_OEMCP)); 478 return g_StartupInfo.ShowErrorMessage(UnicodeStringToMultiByte(message, CP_OEMCP));
476} 479}
477 480
diff --git a/CPP/7zip/UI/Far/FarUtils.h b/CPP/7zip/UI/Far/FarUtils.h
index 38f64f9..6e6ff3c 100644
--- a/CPP/7zip/UI/Far/FarUtils.h
+++ b/CPP/7zip/UI/Far/FarUtils.h
@@ -1,7 +1,7 @@
1// FarUtils.h 1// FarUtils.h
2 2
3#ifndef __FAR_UTILS_H 3#ifndef ZIP7_INC_FAR_UTILS_H
4#define __FAR_UTILS_H 4#define ZIP7_INC_FAR_UTILS_H
5 5
6#include "FarPlugin.h" 6#include "FarPlugin.h"
7 7
@@ -61,8 +61,8 @@ public:
61 const char *GetMsgString(int messageId); 61 const char *GetMsgString(int messageId);
62 62
63 int ShowMessage(unsigned int flags, const char *helpTopic, 63 int ShowMessage(unsigned int flags, const char *helpTopic,
64 const char **items, int numItems, int numButtons); 64 const char **items, unsigned numItems, int numButtons);
65 int ShowWarningWithOk(const char **items, int numItems); 65 int ShowWarningWithOk(const char **items, unsigned numItems);
66 66
67 void SetErrorTitle(AString &s); 67 void SetErrorTitle(AString &s);
68 int ShowErrorMessage(const char *message); 68 int ShowErrorMessage(const char *message);
@@ -71,12 +71,12 @@ public:
71 int ShowMessage(int messageId); 71 int ShowMessage(int messageId);
72 72
73 int ShowDialog(int X1, int Y1, int X2, int Y2, 73 int ShowDialog(int X1, int Y1, int X2, int Y2,
74 const char *helpTopic, struct FarDialogItem *items, int numItems); 74 const char *helpTopic, struct FarDialogItem *items, unsigned numItems);
75 int ShowDialog(int sizeX, int sizeY, 75 int ShowDialog(int sizeX, int sizeY,
76 const char *helpTopic, struct FarDialogItem *items, int numItems); 76 const char *helpTopic, struct FarDialogItem *items, unsigned numItems);
77 77
78 void InitDialogItems(const CInitDialogItem *srcItems, 78 void InitDialogItems(const CInitDialogItem *srcItems,
79 FarDialogItem *destItems, int numItems); 79 FarDialogItem *destItems, unsigned numItems);
80 80
81 HANDLE SaveScreen(int X1, int Y1, int X2, int Y2); 81 HANDLE SaveScreen(int X1, int Y1, int X2, int Y2);
82 HANDLE SaveScreen(); 82 HANDLE SaveScreen();
@@ -119,13 +119,13 @@ public:
119 int *breakKeys, 119 int *breakKeys,
120 int *breakCode, 120 int *breakCode,
121 FarMenuItem *items, 121 FarMenuItem *items,
122 int numItems); 122 unsigned numItems);
123 int Menu( 123 int Menu(
124 unsigned int flags, 124 unsigned int flags,
125 const char *title, 125 const char *title,
126 const char *helpTopic, 126 const char *helpTopic,
127 FarMenuItem *items, 127 FarMenuItem *items,
128 int numItems); 128 unsigned numItems);
129 129
130 int Menu( 130 int Menu(
131 unsigned int flags, 131 unsigned int flags,
@@ -136,14 +136,14 @@ public:
136 136
137 int Editor(const char *fileName, const char *title, 137 int Editor(const char *fileName, const char *title,
138 int X1, int Y1, int X2, int Y2, DWORD flags, int startLine, int startChar) 138 int X1, int Y1, int X2, int Y2, DWORD flags, int startLine, int startChar)
139 { return m_Data.Editor((char *)fileName, (char *)title, X1, Y1, X2, Y2, 139 { return m_Data.Editor(const_cast<char *>(fileName), const_cast<char *>(title), X1, Y1, X2, Y2,
140 flags, startLine, startChar); } 140 flags, startLine, startChar); }
141 int Editor(const char *fileName) 141 int Editor(const char *fileName)
142 { return Editor(fileName, NULL, 0, 0, -1, -1, 0, -1, -1); } 142 { return Editor(fileName, NULL, 0, 0, -1, -1, 0, -1, -1); }
143 143
144 int Viewer(const char *fileName, const char *title, 144 int Viewer(const char *fileName, const char *title,
145 int X1, int Y1, int X2, int Y2, DWORD flags) 145 int X1, int Y1, int X2, int Y2, DWORD flags)
146 { return m_Data.Viewer((char *)fileName, (char *)title, X1, Y1, X2, Y2, flags); } 146 { return m_Data.Viewer(const_cast<char *>(fileName), const_cast<char *>(title), X1, Y1, X2, Y2, flags); }
147 int Viewer(const char *fileName) 147 int Viewer(const char *fileName)
148 { return Viewer(fileName, NULL, 0, 0, -1, -1, VF_NONMODAL); } 148 { return Viewer(fileName, NULL, 0, 0, -1, -1, VF_NONMODAL); }
149 149
@@ -154,7 +154,7 @@ class CScreenRestorer
154 bool m_Saved; 154 bool m_Saved;
155 HANDLE m_HANDLE; 155 HANDLE m_HANDLE;
156public: 156public:
157 CScreenRestorer(): m_Saved(false){}; 157 CScreenRestorer(): m_Saved(false) {}
158 ~CScreenRestorer(); 158 ~CScreenRestorer();
159 void Save(); 159 void Save();
160 void Restore(); 160 void Restore();
@@ -184,10 +184,16 @@ int PrintErrorMessage(const char *message, const wchar_t *name, unsigned maxLen
184 catch(const wchar_t *s) { PrintErrorMessage(x, s); return y; }\ 184 catch(const wchar_t *s) { PrintErrorMessage(x, s); return y; }\
185 catch(...) { g_StartupInfo.ShowErrorMessage(x); return y; } 185 catch(...) { g_StartupInfo.ShowErrorMessage(x); return y; }
186 186
187
187int ShowSysErrorMessage(DWORD errorCode); 188int ShowSysErrorMessage(DWORD errorCode);
188int ShowSysErrorMessage(DWORD errorCode, const wchar_t *name); 189int ShowSysErrorMessage(DWORD errorCode, const wchar_t *name);
189int ShowLastErrorMessage(); 190int ShowLastErrorMessage();
190 191
192inline int ShowSysErrorMessage(HRESULT errorCode)
193 { return ShowSysErrorMessage((DWORD)errorCode); }
194inline int ShowSysErrorMessage(HRESULT errorCode, const wchar_t *name)
195 { return ShowSysErrorMessage((DWORD)errorCode, name); }
196
191bool WasEscPressed(); 197bool WasEscPressed();
192 198
193void ReduceString(UString &s, unsigned size); 199void ReduceString(UString &s, unsigned size);
diff --git a/CPP/7zip/UI/Far/Messages.h b/CPP/7zip/UI/Far/Messages.h
index 4e5ed8d..f6b20a3 100644
--- a/CPP/7zip/UI/Far/Messages.h
+++ b/CPP/7zip/UI/Far/Messages.h
@@ -1,13 +1,13 @@
1// Far/Messages.h 1// Far/Messages.h
2 2
3#ifndef __7ZIP_FAR_MESSAGES_H 3#ifndef ZIP7_INC_FAR_MESSAGES_H
4#define __7ZIP_FAR_MESSAGES_H 4#define ZIP7_INC_FAR_MESSAGES_H
5 5
6#include "../../PropID.h" 6#include "../../PropID.h"
7 7
8namespace NMessageID { 8namespace NMessageID {
9 9
10const unsigned k_Last_PropId_supported_by_plugin = kpidCopyLink; 10const unsigned k_Last_PropId_supported_by_plugin = kpidDevMinor;
11 11
12enum EEnum 12enum EEnum
13{ 13{
diff --git a/CPP/7zip/UI/Far/OverwriteDialogFar.cpp b/CPP/7zip/UI/Far/OverwriteDialogFar.cpp
index b8fc565..a45d2b2 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,
35 { 35 {
36 ConvertUInt64ToString(fileInfo.Size, buffer); 36 ConvertUInt64ToString(fileInfo.Size, buffer);
37 fileInfoStrings.Size = buffer; 37 fileInfoStrings.Size = buffer;
38 fileInfoStrings.Size += ' '; 38 fileInfoStrings.Size.Add_Space();
39 fileInfoStrings.Size += g_StartupInfo.GetMsgString(NMessageID::kOverwriteBytes); 39 fileInfoStrings.Size += g_StartupInfo.GetMsgString(NMessageID::kOverwriteBytes);
40 } 40 }
41 else 41 else
@@ -49,7 +49,7 @@ static void SetFileInfoStrings(const CFileInfo &fileInfo,
49 char timeString[32]; 49 char timeString[32];
50 ConvertUtcFileTimeToString(fileInfo.Time, timeString); 50 ConvertUtcFileTimeToString(fileInfo.Time, timeString);
51 fileInfoStrings.Time = g_StartupInfo.GetMsgString(NMessageID::kOverwriteModifiedOn); 51 fileInfoStrings.Time = g_StartupInfo.GetMsgString(NMessageID::kOverwriteModifiedOn);
52 fileInfoStrings.Time += ' '; 52 fileInfoStrings.Time.Add_Space();
53 fileInfoStrings.Time += timeString; 53 fileInfoStrings.Time += timeString;
54 } 54 }
55} 55}
@@ -96,12 +96,12 @@ NResult::EEnum Execute(const CFileInfo &oldFileInfo, const CFileInfo &newFileInf
96 ReduceString2(name2, maxNameLen - kNameOffset); 96 ReduceString2(name2, maxNameLen - kNameOffset);
97 } 97 }
98 98
99 AString pref1A (UnicodeStringToMultiByte(pref1, CP_OEMCP)); 99 const AString pref1A (UnicodeStringToMultiByte(pref1, CP_OEMCP));
100 AString pref2A (UnicodeStringToMultiByte(pref2, CP_OEMCP)); 100 const AString pref2A (UnicodeStringToMultiByte(pref2, CP_OEMCP));
101 AString name1A (UnicodeStringToMultiByte(name1, CP_OEMCP)); 101 const AString name1A (UnicodeStringToMultiByte(name1, CP_OEMCP));
102 AString name2A (UnicodeStringToMultiByte(name2, CP_OEMCP)); 102 const AString name2A (UnicodeStringToMultiByte(name2, CP_OEMCP));
103 103
104 struct CInitDialogItem initItems[]={ 104 const struct CInitDialogItem initItems[]={
105 { DI_DOUBLEBOX, 3, 1, kXSize - 4, kYSize - 2, false, false, 0, false, NMessageID::kOverwriteTitle, NULL, NULL }, 105 { DI_DOUBLEBOX, 3, 1, kXSize - 4, kYSize - 2, false, false, 0, false, NMessageID::kOverwriteTitle, NULL, NULL },
106 { DI_TEXT, 5, 2, 0, 0, false, false, 0, false, NMessageID::kOverwriteMessage1, NULL, NULL }, 106 { DI_TEXT, 5, 2, 0, 0, false, false, 0, false, NMessageID::kOverwriteMessage1, NULL, NULL },
107 107
@@ -131,10 +131,10 @@ NResult::EEnum Execute(const CFileInfo &oldFileInfo, const CFileInfo &newFileInf
131 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kOverwriteCancel, NULL, NULL } 131 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kOverwriteCancel, NULL, NULL }
132 }; 132 };
133 133
134 const int kNumDialogItems = ARRAY_SIZE(initItems); 134 const int kNumDialogItems = Z7_ARRAY_SIZE(initItems);
135 FarDialogItem aDialogItems[kNumDialogItems]; 135 FarDialogItem aDialogItems[kNumDialogItems];
136 g_StartupInfo.InitDialogItems(initItems, aDialogItems, kNumDialogItems); 136 g_StartupInfo.InitDialogItems(initItems, aDialogItems, kNumDialogItems);
137 int anAskCode = g_StartupInfo.ShowDialog(kXSize, kYSize, 137 const int anAskCode = g_StartupInfo.ShowDialog(kXSize, kYSize,
138 NULL, aDialogItems, kNumDialogItems); 138 NULL, aDialogItems, kNumDialogItems);
139 const int kButtonStartPos = kNumDialogItems - 6; 139 const int kButtonStartPos = kNumDialogItems - 6;
140 if (anAskCode >= kButtonStartPos && anAskCode < kNumDialogItems) 140 if (anAskCode >= kButtonStartPos && anAskCode < kNumDialogItems)
diff --git a/CPP/7zip/UI/Far/OverwriteDialogFar.h b/CPP/7zip/UI/Far/OverwriteDialogFar.h
index 3494743..bc6e92b 100644
--- a/CPP/7zip/UI/Far/OverwriteDialogFar.h
+++ b/CPP/7zip/UI/Far/OverwriteDialogFar.h
@@ -1,7 +1,7 @@
1// OverwriteDialogFar.h 1// OverwriteDialogFar.h
2 2
3#ifndef __OVERWRITE_DIALOG_FAR_H 3#ifndef ZIP7_INC_OVERWRITE_DIALOG_FAR_H
4#define __OVERWRITE_DIALOG_FAR_H 4#define ZIP7_INC_OVERWRITE_DIALOG_FAR_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7#include "../../../Common/MyTypes.h" 7#include "../../../Common/MyTypes.h"
diff --git a/CPP/7zip/UI/Far/Plugin.cpp b/CPP/7zip/UI/Far/Plugin.cpp
index 8dc1375..fe6fcce 100644
--- a/CPP/7zip/UI/Far/Plugin.cpp
+++ b/CPP/7zip/UI/Far/Plugin.cpp
@@ -20,13 +20,13 @@ using namespace NFile;
20using namespace NDir; 20using namespace NDir;
21using namespace NFar; 21using namespace NFar;
22 22
23// This function is unused 23// This function is used by CAgentFolder
24int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2);
24int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2) 25int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2)
25{ 26{
26 return MyStringCompareNoCase(s1, s2); 27 return MyStringCompareNoCase(s1, s2);
27} 28}
28 29
29
30CPlugin::CPlugin(const FString &fileName, CAgent *agent, UString archiveTypeName): 30CPlugin::CPlugin(const FString &fileName, CAgent *agent, UString archiveTypeName):
31 _agent(agent), 31 _agent(agent),
32 m_FileName(fileName), 32 m_FileName(fileName),
@@ -72,7 +72,7 @@ static void CopyStrLimited(char *dest, const AString &src, unsigned len)
72 dest[len] = 0; 72 dest[len] = 0;
73} 73}
74 74
75#define COPY_STR_LIMITED(dest, src) CopyStrLimited(dest, src, ARRAY_SIZE(dest)) 75#define COPY_STR_LIMITED(dest, src) CopyStrLimited(dest, src, Z7_ARRAY_SIZE(dest))
76 76
77void CPlugin::ReadPluginPanelItem(PluginPanelItem &panelItem, UInt32 itemIndex) 77void CPlugin::ReadPluginPanelItem(PluginPanelItem &panelItem, UInt32 itemIndex)
78{ 78{
@@ -156,7 +156,7 @@ int CPlugin::GetFindData(PluginPanelItem **panelItems, int *itemsNumber, int opM
156 g_StartupInfo.GetMsgString(NMessageID::kWaitTitle), 156 g_StartupInfo.GetMsgString(NMessageID::kWaitTitle),
157 g_StartupInfo.GetMsgString(NMessageID::kReadingList) 157 g_StartupInfo.GetMsgString(NMessageID::kReadingList)
158 }; 158 };
159 g_StartupInfo.ShowMessage(0, NULL, msgItems, ARRAY_SIZE(msgItems), 0); 159 g_StartupInfo.ShowMessage(0, NULL, msgItems, Z7_ARRAY_SIZE(msgItems), 0);
160 */ 160 */
161 } 161 }
162 162
@@ -177,7 +177,7 @@ int CPlugin::GetFindData(PluginPanelItem **panelItems, int *itemsNumber, int opM
177 delete [](*panelItems); 177 delete [](*panelItems);
178 throw; 178 throw;
179 } 179 }
180 *itemsNumber = numItems; 180 *itemsNumber = (int)numItems;
181 return(TRUE); 181 return(TRUE);
182} 182}
183 183
@@ -291,7 +291,7 @@ static int FindPropNameID(PROPID propID)
291{ 291{
292 if (propID > NMessageID::k_Last_PropId_supported_by_plugin) 292 if (propID > NMessageID::k_Last_PropId_supported_by_plugin)
293 return -1; 293 return -1;
294 return NMessageID::kNoProperty + propID; 294 return NMessageID::kNoProperty + (int)propID;
295} 295}
296 296
297/* 297/*
@@ -324,7 +324,7 @@ static CPropertyIDInfo kPropertyIDInfos[] =
324 // { kpidType, L"Type" } 324 // { kpidType, L"Type" }
325}; 325};
326 326
327static const int kNumPropertyIDInfos = ARRAY_SIZE(kPropertyIDInfos); 327static const int kNumPropertyIDInfos = Z7_ARRAY_SIZE(kPropertyIDInfos);
328 328
329static int FindPropertyInfo(PROPID propID) 329static int FindPropertyInfo(PROPID propID)
330{ 330{
@@ -395,7 +395,7 @@ static AString ConvertSizeToString(UInt64 value)
395 char s[32]; 395 char s[32];
396 ConvertUInt64ToString(value, s); 396 ConvertUInt64ToString(value, s);
397 unsigned i = MyStringLen(s); 397 unsigned i = MyStringLen(s);
398 unsigned pos = ARRAY_SIZE(s); 398 unsigned pos = Z7_ARRAY_SIZE(s);
399 s[--pos] = 0; 399 s[--pos] = 0;
400 while (i > 3) 400 while (i > 3)
401 { 401 {
@@ -597,7 +597,7 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info)
597 case -2: propID = kpidType; break; 597 case -2: propID = kpidType; break;
598 case -1: propID = kpidError; break; 598 case -1: propID = kpidError; break;
599 default: 599 default:
600 if (getProps->GetArcPropInfo(level, i, &name, &propID, &vt) != S_OK) 600 if (getProps->GetArcPropInfo(level, (UInt32)i, &name, &propID, &vt) != S_OK)
601 continue; 601 continue;
602 } 602 }
603 NCOM::CPropVariant prop; 603 NCOM::CPropVariant prop;
@@ -619,7 +619,7 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info)
619 CMyComBSTR name; 619 CMyComBSTR name;
620 PROPID propID; 620 PROPID propID;
621 VARTYPE vt; 621 VARTYPE vt;
622 if (getProps->GetArcPropInfo2(level, i, &name, &propID, &vt) != S_OK) 622 if (getProps->GetArcPropInfo2(level, (UInt32)i, &name, &propID, &vt) != S_OK)
623 continue; 623 continue;
624 NCOM::CPropVariant prop; 624 NCOM::CPropVariant prop;
625 if (getProps->GetArcProp2(level, propID, &prop) != S_OK) 625 if (getProps->GetArcProp2(level, propID, &prop) != S_OK)
@@ -636,7 +636,7 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info)
636 //m_InfoLines[1].Separator = 0; 636 //m_InfoLines[1].Separator = 0;
637 637
638 info->InfoLines = m_InfoLines; 638 info->InfoLines = m_InfoLines;
639 info->InfoLinesNumber = numItems; 639 info->InfoLinesNumber = (int)numItems;
640 640
641 641
642 info->DescrFiles = NULL; 642 info->DescrFiles = NULL;
@@ -654,19 +654,19 @@ void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info)
654 AddColumn(kpidATime); 654 AddColumn(kpidATime);
655 AddColumn(kpidAttrib); 655 AddColumn(kpidAttrib);
656 656
657 _PanelMode.ColumnTypes = (char *)(const char *)PanelModeColumnTypes; 657 _panelMode.ColumnTypes = (char *)(const char *)PanelModeColumnTypes;
658 _PanelMode.ColumnWidths = (char *)(const char *)PanelModeColumnWidths; 658 _panelMode.ColumnWidths = (char *)(const char *)PanelModeColumnWidths;
659 _PanelMode.ColumnTitles = NULL; 659 _panelMode.ColumnTitles = NULL;
660 _PanelMode.FullScreen = TRUE; 660 _panelMode.FullScreen = TRUE;
661 _PanelMode.DetailedStatus = FALSE; 661 _panelMode.DetailedStatus = FALSE;
662 _PanelMode.AlignExtensions = FALSE; 662 _panelMode.AlignExtensions = FALSE;
663 _PanelMode.CaseConversion = FALSE; 663 _panelMode.CaseConversion = FALSE;
664 _PanelMode.StatusColumnTypes = "N"; 664 _panelMode.StatusColumnTypes = "N";
665 _PanelMode.StatusColumnWidths = "0"; 665 _panelMode.StatusColumnWidths = "0";
666 _PanelMode.Reserved[0] = 0; 666 _panelMode.Reserved[0] = 0;
667 _PanelMode.Reserved[1] = 0; 667 _panelMode.Reserved[1] = 0;
668 668
669 info->PanelModesArray = &_PanelMode; 669 info->PanelModesArray = &_panelMode;
670 info->PanelModesNumber = 1; 670 info->PanelModesNumber = 1;
671 */ 671 */
672 672
@@ -704,18 +704,18 @@ HRESULT CPlugin::ShowAttributesWindow()
704 if (strcmp(pluginPanelItem.FindData.cFileName, "..") == 0 && 704 if (strcmp(pluginPanelItem.FindData.cFileName, "..") == 0 &&
705 NFind::NAttributes::IsDir(pluginPanelItem.FindData.dwFileAttributes)) 705 NFind::NAttributes::IsDir(pluginPanelItem.FindData.dwFileAttributes))
706 return S_FALSE; 706 return S_FALSE;
707 int itemIndex = (int)pluginPanelItem.UserData; 707 const UInt32 itemIndex = (UInt32)pluginPanelItem.UserData;
708 708
709 CObjectVector<CArchiveItemProperty> properties; 709 CObjectVector<CArchiveItemProperty> properties;
710 UInt32 numProps; 710 UInt32 numProps;
711 RINOK(_folder->GetNumberOfProperties(&numProps)); 711 RINOK(_folder->GetNumberOfProperties(&numProps))
712 unsigned i; 712 unsigned i;
713 for (i = 0; i < numProps; i++) 713 for (i = 0; i < numProps; i++)
714 { 714 {
715 CMyComBSTR name; 715 CMyComBSTR name;
716 PROPID propID; 716 PROPID propID;
717 VARTYPE vt; 717 VARTYPE vt;
718 RINOK(_folder->GetPropertyInfo(i, &name, &propID, &vt)); 718 RINOK(_folder->GetPropertyInfo(i, &name, &propID, &vt))
719 CArchiveItemProperty prop; 719 CArchiveItemProperty prop;
720 prop.Type = vt; 720 prop.Type = vt;
721 prop.ID = propID; 721 prop.ID = propID;
@@ -743,7 +743,7 @@ HRESULT CPlugin::ShowAttributesWindow()
743 { 743 {
744 const CArchiveItemProperty &property = properties[i]; 744 const CArchiveItemProperty &property = properties[i];
745 745
746 int startY = kStartY + values.Size(); 746 const int startY = kStartY + (int)values.Size();
747 747
748 { 748 {
749 CInitDialogItem idi = 749 CInitDialogItem idi =
@@ -755,7 +755,7 @@ HRESULT CPlugin::ShowAttributesWindow()
755 } 755 }
756 756
757 NCOM::CPropVariant prop; 757 NCOM::CPropVariant prop;
758 RINOK(_folder->GetProperty(itemIndex, property.ID, &prop)); 758 RINOK(_folder->GetProperty(itemIndex, property.ID, &prop))
759 values.Add(PropToString(prop, property.ID)); 759 values.Add(PropToString(prop, property.ID));
760 760
761 { 761 {
@@ -834,7 +834,7 @@ HRESULT CPlugin::ShowAttributesWindow()
834 } 834 }
835 } 835 }
836 836
837 int startY = kStartY + values.Size(); 837 const int startY = kStartY + (int)values.Size();
838 838
839 { 839 {
840 CInitDialogItem idi = 840 CInitDialogItem idi =
@@ -856,14 +856,14 @@ HRESULT CPlugin::ShowAttributesWindow()
856 } 856 }
857 } 857 }
858 858
859 unsigned numLines = values.Size(); 859 const unsigned numLines = values.Size();
860 for (i = 0; i < numLines; i++) 860 for (i = 0; i < numLines; i++)
861 { 861 {
862 CInitDialogItem &idi = initDialogItems[1 + i * 2 + 1]; 862 CInitDialogItem &idi = initDialogItems[1 + i * 2 + 1];
863 idi.DataString = values[i]; 863 idi.DataString = values[i];
864 } 864 }
865 865
866 unsigned numDialogItems = initDialogItems.Size(); 866 const unsigned numDialogItems = initDialogItems.Size();
867 867
868 CObjArray<FarDialogItem> dialogItems(numDialogItems); 868 CObjArray<FarDialogItem> dialogItems(numDialogItems);
869 g_StartupInfo.InitDialogItems(&initDialogItems.Front(), dialogItems, numDialogItems); 869 g_StartupInfo.InitDialogItems(&initDialogItems.Front(), dialogItems, numDialogItems);
@@ -884,14 +884,14 @@ HRESULT CPlugin::ShowAttributesWindow()
884 for (i = 0; i < numLines; i++) 884 for (i = 0; i < numLines; i++)
885 { 885 {
886 FarDialogItem &dialogItem = dialogItems[1 + i * 2 + 1]; 886 FarDialogItem &dialogItem = dialogItems[1 + i * 2 + 1];
887 unsigned len = (int)strlen(dialogItem.Data); 887 const unsigned len = (unsigned)strlen(dialogItem.Data);
888 if (len > maxLen2) 888 if (len > maxLen2)
889 maxLen2 = len; 889 maxLen2 = len;
890 dialogItem.X1 = maxLen + kSpace; 890 dialogItem.X1 = (int)(maxLen + kSpace);
891 } 891 }
892 892
893 size = numLines + 6; 893 size = (int)numLines + 6;
894 xSize = maxLen + kSpace + maxLen2 + 5; 894 xSize = (int)(maxLen + kSpace + maxLen2 + 5);
895 FarDialogItem &firstDialogItem = dialogItems[0]; 895 FarDialogItem &firstDialogItem = dialogItems[0];
896 firstDialogItem.Y2 = size - 2; 896 firstDialogItem.Y2 = size - 2;
897 firstDialogItem.X2 = xSize - 4; 897 firstDialogItem.X2 = xSize - 4;
@@ -926,7 +926,7 @@ int CPlugin::ProcessKey(int key, unsigned int controlState)
926 PanelInfo panelInfo; 926 PanelInfo panelInfo;
927 g_StartupInfo.ControlGetActivePanelInfo(panelInfo); 927 g_StartupInfo.ControlGetActivePanelInfo(panelInfo);
928 GetFilesReal(panelInfo.SelectedItems, 928 GetFilesReal(panelInfo.SelectedItems,
929 panelInfo.SelectedItemsNumber, FALSE, 929 (unsigned)panelInfo.SelectedItemsNumber, FALSE,
930 UnicodeStringToMultiByte(fs2us(folderPath), CP_OEMCP), OPM_SILENT, true); 930 UnicodeStringToMultiByte(fs2us(folderPath), CP_OEMCP), OPM_SILENT, true);
931 g_StartupInfo.Control(this, FCTL_UPDATEPANEL, NULL); 931 g_StartupInfo.Control(this, FCTL_UPDATEPANEL, NULL);
932 g_StartupInfo.Control(this, FCTL_REDRAWPANEL, NULL); 932 g_StartupInfo.Control(this, FCTL_REDRAWPANEL, NULL);
diff --git a/CPP/7zip/UI/Far/Plugin.h b/CPP/7zip/UI/Far/Plugin.h
index 1fe190e..00ccc81 100644
--- a/CPP/7zip/UI/Far/Plugin.h
+++ b/CPP/7zip/UI/Far/Plugin.h
@@ -1,7 +1,7 @@
1// 7zip/Far/Plugin.h 1// 7zip/Far/Plugin.h
2 2
3#ifndef __7ZIP_FAR_PLUGIN_H 3#ifndef ZIP7_INC_7ZIP_FAR_PLUGIN_H
4#define __7ZIP_FAR_PLUGIN_H 4#define ZIP7_INC_7ZIP_FAR_PLUGIN_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -40,7 +40,7 @@ class CPlugin
40 40
41 AString PanelModeColumnTypes; 41 AString PanelModeColumnTypes;
42 AString PanelModeColumnWidths; 42 AString PanelModeColumnWidths;
43 // PanelMode _PanelMode; 43 // PanelMode _panelMode;
44 void AddColumn(PROPID aPropID); 44 void AddColumn(PROPID aPropID);
45 45
46 void EnterToDirectory(const UString &dirName); 46 void EnterToDirectory(const UString &dirName);
@@ -62,7 +62,7 @@ public:
62 void FreeFindData(PluginPanelItem *panelItem,int ItemsNumber); 62 void FreeFindData(PluginPanelItem *panelItem,int ItemsNumber);
63 int SetDirectory(const char *aszDir, int opMode); 63 int SetDirectory(const char *aszDir, int opMode);
64 void GetOpenPluginInfo(struct OpenPluginInfo *info); 64 void GetOpenPluginInfo(struct OpenPluginInfo *info);
65 int DeleteFiles(PluginPanelItem *panelItems, int itemsNumber, int opMode); 65 int DeleteFiles(PluginPanelItem *panelItems, unsigned itemsNumber, int opMode);
66 66
67 HRESULT ExtractFiles( 67 HRESULT ExtractFiles(
68 bool decompressAllItems, 68 bool decompressAllItems,
@@ -74,13 +74,13 @@ public:
74 const UString &destPath, 74 const UString &destPath,
75 bool passwordIsDefined, const UString &password); 75 bool passwordIsDefined, const UString &password);
76 76
77 NFar::NFileOperationReturnCode::EEnum GetFiles(struct PluginPanelItem *panelItem, int itemsNumber, 77 NFar::NFileOperationReturnCode::EEnum GetFiles(struct PluginPanelItem *panelItem, unsigned itemsNumber,
78 int move, char *destPath, int opMode); 78 int move, char *destPath, int opMode);
79 79
80 NFar::NFileOperationReturnCode::EEnum GetFilesReal(struct PluginPanelItem *panelItems, 80 NFar::NFileOperationReturnCode::EEnum GetFilesReal(struct PluginPanelItem *panelItems,
81 int itemsNumber, int move, const char *_aDestPath, int opMode, bool showBox); 81 unsigned itemsNumber, int move, const char *_aDestPath, int opMode, bool showBox);
82 82
83 NFar::NFileOperationReturnCode::EEnum PutFiles(struct PluginPanelItem *panelItems, int itemsNumber, 83 NFar::NFileOperationReturnCode::EEnum PutFiles(struct PluginPanelItem *panelItems, unsigned itemsNumber,
84 int move, int opMode); 84 int move, int opMode);
85 HRESULT CreateFolder(); 85 HRESULT CreateFolder();
86 86
diff --git a/CPP/7zip/UI/Far/PluginDelete.cpp b/CPP/7zip/UI/Far/PluginDelete.cpp
index 939a355..fdade1a 100644
--- a/CPP/7zip/UI/Far/PluginDelete.cpp
+++ b/CPP/7zip/UI/Far/PluginDelete.cpp
@@ -13,7 +13,7 @@
13 13
14using namespace NFar; 14using namespace NFar;
15 15
16int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode) 16int CPlugin::DeleteFiles(PluginPanelItem *panelItems, unsigned numItems, int opMode)
17{ 17{
18 if (numItems == 0) 18 if (numItems == 0)
19 return FALSE; 19 return FALSE;
@@ -63,7 +63,7 @@ int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode)
63 // sprintf(msg, g_StartupInfo.GetMsgString(NMessageID::kDeleteNumberOfFiles), numItems); 63 // sprintf(msg, g_StartupInfo.GetMsgString(NMessageID::kDeleteNumberOfFiles), numItems);
64 // msgItems[1] = msg; 64 // msgItems[1] = msg;
65 } 65 }
66 if (g_StartupInfo.ShowMessage(FMSG_WARNING, NULL, msgItems, ARRAY_SIZE(msgItems), 2) != 0) 66 if (g_StartupInfo.ShowMessage(FMSG_WARNING, NULL, msgItems, Z7_ARRAY_SIZE(msgItems), 2) != 0)
67 return (FALSE); 67 return (FALSE);
68 } 68 }
69 69
@@ -87,7 +87,7 @@ int CPlugin::DeleteFiles(PluginPanelItem *panelItems, int numItems, int opMode)
87 */ 87 */
88 88
89 CObjArray<UInt32> indices(numItems); 89 CObjArray<UInt32> indices(numItems);
90 int i; 90 unsigned i;
91 for (i = 0; i < numItems; i++) 91 for (i = 0; i < numItems; i++)
92 indices[i] = (UInt32)panelItems[i].UserData; 92 indices[i] = (UInt32)panelItems[i].UserData;
93 93
diff --git a/CPP/7zip/UI/Far/PluginRead.cpp b/CPP/7zip/UI/Far/PluginRead.cpp
index 70e7e14..7e81ddd 100644
--- a/CPP/7zip/UI/Far/PluginRead.cpp
+++ b/CPP/7zip/UI/Far/PluginRead.cpp
@@ -86,14 +86,14 @@ HRESULT CPlugin::ExtractFiles(
86} 86}
87 87
88NFileOperationReturnCode::EEnum CPlugin::GetFiles(struct PluginPanelItem *panelItems, 88NFileOperationReturnCode::EEnum CPlugin::GetFiles(struct PluginPanelItem *panelItems,
89 int itemsNumber, int move, char *destPath, int opMode) 89 unsigned itemsNumber, int move, char *destPath, int opMode)
90{ 90{
91 return GetFilesReal(panelItems, itemsNumber, move, 91 return GetFilesReal(panelItems, itemsNumber, move,
92 destPath, opMode, (opMode & OPM_SILENT) == 0); 92 destPath, opMode, (opMode & OPM_SILENT) == 0);
93} 93}
94 94
95NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *panelItems, 95NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *panelItems,
96 int itemsNumber, int move, const char *destPathLoc, int opMode, bool showBox) 96 unsigned itemsNumber, int move, const char *destPathLoc, int opMode, bool showBox)
97{ 97{
98 if (move != 0) 98 if (move != 0)
99 { 99 {
@@ -112,7 +112,7 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa
112 extractionInfo.PathMode = NExtract::NPathMode::kCurPaths; 112 extractionInfo.PathMode = NExtract::NPathMode::kCurPaths;
113 extractionInfo.OverwriteMode = NExtract::NOverwriteMode::kOverwrite; 113 extractionInfo.OverwriteMode = NExtract::NOverwriteMode::kOverwrite;
114 114
115 bool silent = (opMode & OPM_SILENT) != 0; 115 const bool silent = (opMode & OPM_SILENT) != 0;
116 bool decompressAllItems = false; 116 bool decompressAllItems = false;
117 UString password = Password; 117 UString password = Password;
118 bool passwordIsDefined = PasswordIsDefined; 118 bool passwordIsDefined = PasswordIsDefined;
@@ -184,9 +184,9 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa
184 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kExtractCancel, NULL, NULL } 184 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kExtractCancel, NULL, NULL }
185 }; 185 };
186 186
187 const int kNumDialogItems = ARRAY_SIZE(initItems); 187 const unsigned kNumDialogItems = Z7_ARRAY_SIZE(initItems);
188 const int kOkButtonIndex = kNumDialogItems - 2; 188 const unsigned kOkButtonIndex = kNumDialogItems - 2;
189 const int kPasswordIndex = kNumDialogItems - 4; 189 const unsigned kPasswordIndex = kNumDialogItems - 4;
190 190
191 FarDialogItem dialogItems[kNumDialogItems]; 191 FarDialogItem dialogItems[kNumDialogItems];
192 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems); 192 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems);
@@ -275,10 +275,10 @@ NFileOperationReturnCode::EEnum CPlugin::GetFilesReal(struct PluginPanelItem *pa
275 GetRealIndexes(panelItems, itemsNumber, realIndices); 275 GetRealIndexes(panelItems, itemsNumber, realIndices);
276 */ 276 */
277 CObjArray<UInt32> indices(itemsNumber); 277 CObjArray<UInt32> indices(itemsNumber);
278 for (int i = 0; i < itemsNumber; i++) 278 for (unsigned i = 0; i < itemsNumber; i++)
279 indices[i] = (UInt32)panelItems[i].UserData; 279 indices[i] = (UInt32)panelItems[i].UserData;
280 280
281 HRESULT result = ExtractFiles(decompressAllItems, indices, itemsNumber, 281 const HRESULT result = ExtractFiles(decompressAllItems, indices, itemsNumber,
282 !showBox, extractionInfo.PathMode, extractionInfo.OverwriteMode, 282 !showBox, extractionInfo.PathMode, extractionInfo.OverwriteMode,
283 destPathU, 283 destPathU,
284 passwordIsDefined, password); 284 passwordIsDefined, password);
diff --git a/CPP/7zip/UI/Far/PluginWrite.cpp b/CPP/7zip/UI/Far/PluginWrite.cpp
index 8a76bb4..3f1fba8 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)
49 */ 49 */
50 NCOM::CPropVariant value = (UInt32)method; 50 NCOM::CPropVariant value = (UInt32)method;
51 const wchar_t *name = L"x"; 51 const wchar_t *name = L"x";
52 RINOK(setProperties->SetProperties(&name, &value, 1)); 52 RINOK(setProperties->SetProperties(&name, &value, 1))
53 } 53 }
54 return S_OK; 54 return S_OK;
55} 55}
@@ -78,7 +78,7 @@ HRESULT CPlugin::AfterUpdate(CWorkDirTempFile &tempFile, const UStringVector &pa
78*/ 78*/
79 79
80NFileOperationReturnCode::EEnum CPlugin::PutFiles( 80NFileOperationReturnCode::EEnum CPlugin::PutFiles(
81 struct PluginPanelItem *panelItems, int numItems, 81 struct PluginPanelItem *panelItems, unsigned numItems,
82 int moveMode, int opMode) 82 int moveMode, int opMode)
83{ 83{
84 if (moveMode != 0 84 if (moveMode != 0
@@ -106,7 +106,7 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles(
106 unsigned methodIndex = 0; 106 unsigned methodIndex = 0;
107 107
108 unsigned i; 108 unsigned i;
109 for (i = ARRAY_SIZE(g_MethodMap); i != 0;) 109 for (i = Z7_ARRAY_SIZE(g_MethodMap); i != 0;)
110 { 110 {
111 i--; 111 i--;
112 if (compressionInfo.Level >= g_MethodMap[i]) 112 if (compressionInfo.Level >= g_MethodMap[i])
@@ -144,17 +144,17 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles(
144 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } 144 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }
145 }; 145 };
146 146
147 const int kNumDialogItems = ARRAY_SIZE(initItems); 147 const int kNumDialogItems = Z7_ARRAY_SIZE(initItems);
148 const int kOkButtonIndex = kNumDialogItems - 2; 148 const int kOkButtonIndex = kNumDialogItems - 2;
149 FarDialogItem dialogItems[kNumDialogItems]; 149 FarDialogItem dialogItems[kNumDialogItems];
150 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems); 150 g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems);
151 int askCode = g_StartupInfo.ShowDialog(76, kYSize, 151 const int askCode = g_StartupInfo.ShowDialog(76, kYSize,
152 kHelpTopic, dialogItems, kNumDialogItems); 152 kHelpTopic, dialogItems, kNumDialogItems);
153 if (askCode != kOkButtonIndex) 153 if (askCode != kOkButtonIndex)
154 return NFileOperationReturnCode::kInterruptedByUser; 154 return NFileOperationReturnCode::kInterruptedByUser;
155 155
156 compressionInfo.Level = g_MethodMap[0]; 156 compressionInfo.Level = g_MethodMap[0];
157 for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++) 157 for (i = 0; i < Z7_ARRAY_SIZE(g_MethodMap); i++)
158 if (dialogItems[kMethodRadioIndex + i].Selected) 158 if (dialogItems[kMethodRadioIndex + i].Selected)
159 compressionInfo.Level = g_MethodMap[i]; 159 compressionInfo.Level = g_MethodMap[i];
160 160
@@ -168,7 +168,7 @@ NFileOperationReturnCode::EEnum CPlugin::PutFiles(
168 168
169 compressionInfo.Save(); 169 compressionInfo.Save();
170 170
171 CWorkDirTempFile tempFile;; 171 CWorkDirTempFile tempFile;
172 if (tempFile.CreateTempFile(m_FileName) != S_OK) 172 if (tempFile.CreateTempFile(m_FileName) != S_OK)
173 return NFileOperationReturnCode::kError; 173 return NFileOperationReturnCode::kError;
174 174
@@ -337,7 +337,7 @@ void CParsedPath::ParsePath(const UString &path)
337 // the bug was fixed: 337 // the bug was fixed:
338 curPos = path.Find((wchar_t)kDirDelimiter, 2); 338 curPos = path.Find((wchar_t)kDirDelimiter, 2);
339 if (curPos < 0) 339 if (curPos < 0)
340 curPos = path.Len(); 340 curPos = (int)path.Len();
341 else 341 else
342 curPos++; 342 curPos++;
343 } 343 }
@@ -368,7 +368,7 @@ static void SetArcName(UString &arcName, const CArcInfoEx &arcInfo)
368 if (dotPos > slashPos + 1) 368 if (dotPos > slashPos + 1)
369 arcName.DeleteFrom(dotPos); 369 arcName.DeleteFrom(dotPos);
370 } 370 }
371 arcName += '.'; 371 arcName.Add_Dot();
372 arcName += arcInfo.GetMainExt(); 372 arcName += arcInfo.GetMainExt();
373} 373}
374 374
@@ -420,9 +420,9 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
420 if (arcInfo.UpdateEnabled) 420 if (arcInfo.UpdateEnabled)
421 { 421 {
422 if (archiverIndex == -1) 422 if (archiverIndex == -1)
423 archiverIndex = i; 423 archiverIndex = (int)i;
424 if (MyStringCompareNoCase(arcInfo.Name, compressionInfo.ArcType) == 0) 424 if (MyStringCompareNoCase(arcInfo.Name, compressionInfo.ArcType) == 0)
425 archiverIndex = i; 425 archiverIndex = (int)i;
426 } 426 }
427 } 427 }
428 } 428 }
@@ -480,7 +480,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
480 480
481 unsigned methodIndex = 0; 481 unsigned methodIndex = 0;
482 unsigned i; 482 unsigned i;
483 for (i = ARRAY_SIZE(g_MethodMap); i != 0;) 483 for (i = Z7_ARRAY_SIZE(g_MethodMap); i != 0;)
484 { 484 {
485 i--; 485 i--;
486 if (compressionInfo.Level >= g_MethodMap[i]) 486 if (compressionInfo.Level >= g_MethodMap[i])
@@ -522,7 +522,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
522 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } 522 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }
523 }; 523 };
524 524
525 const int kNumDialogItems = ARRAY_SIZE(initItems); 525 const int kNumDialogItems = Z7_ARRAY_SIZE(initItems);
526 526
527 const int kOkButtonIndex = kNumDialogItems - 3; 527 const int kOkButtonIndex = kNumDialogItems - 3;
528 const int kSelectarchiverButtonIndex = kNumDialogItems - 2; 528 const int kSelectarchiverButtonIndex = kNumDialogItems - 2;
@@ -537,7 +537,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
537 MultiByteToUnicodeString2(arcName, archiveNameA, CP_OEMCP); 537 MultiByteToUnicodeString2(arcName, archiveNameA, CP_OEMCP);
538 538
539 compressionInfo.Level = g_MethodMap[0]; 539 compressionInfo.Level = g_MethodMap[0];
540 for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++) 540 for (i = 0; i < Z7_ARRAY_SIZE(g_MethodMap); i++)
541 if (dialogItems[kMethodRadioIndex + i].Selected) 541 if (dialogItems[kMethodRadioIndex + i].Selected)
542 compressionInfo.Level = g_MethodMap[i]; 542 compressionInfo.Level = g_MethodMap[i];
543 543
@@ -549,7 +549,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
549 549
550 if (askCode == kSelectarchiverButtonIndex) 550 if (askCode == kSelectarchiverButtonIndex)
551 { 551 {
552 CIntVector indices; 552 CUIntVector indices;
553 AStringVector archiverNames; 553 AStringVector archiverNames;
554 FOR_VECTOR (k, codecs->Formats) 554 FOR_VECTOR (k, codecs->Formats)
555 { 555 {
@@ -561,7 +561,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
561 } 561 }
562 } 562 }
563 563
564 int index = g_StartupInfo.Menu(FMENU_AUTOHIGHLIGHT, 564 const int index = g_StartupInfo.Menu(FMENU_AUTOHIGHLIGHT,
565 g_StartupInfo.GetMsgString(NMessageID::kUpdateSelectArchiverMenuTitle), 565 g_StartupInfo.GetMsgString(NMessageID::kUpdateSelectArchiverMenuTitle),
566 NULL, archiverNames, archiverIndex); 566 NULL, archiverNames, archiverIndex);
567 if (index >= 0) 567 if (index >= 0)
@@ -574,7 +574,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
574 if (arcName.Len() >= prevExtensionLen && 574 if (arcName.Len() >= prevExtensionLen &&
575 MyStringCompareNoCase(arcName.RightPtr(prevExtensionLen), prevExtension) == 0) 575 MyStringCompareNoCase(arcName.RightPtr(prevExtensionLen), prevExtension) == 0)
576 { 576 {
577 int pos = arcName.Len() - prevExtensionLen; 577 const unsigned pos = arcName.Len() - prevExtensionLen;
578 if (pos > 2) 578 if (pos > 2)
579 { 579 {
580 if (arcName[pos - 1] == '.') 580 if (arcName[pos - 1] == '.')
@@ -583,7 +583,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
583 } 583 }
584 } 584 }
585 585
586 archiverIndex = indices[index]; 586 archiverIndex = (int)indices[index];
587 const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex]; 587 const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex];
588 prevFormat = archiverIndex; 588 prevFormat = archiverIndex;
589 589
@@ -612,8 +612,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
612 return E_FAIL; 612 return E_FAIL;
613 613
614 CWorkDirTempFile tempFile; 614 CWorkDirTempFile tempFile;
615 RINOK(tempFile.CreateTempFile(fullArcName)); 615 RINOK(tempFile.CreateTempFile(fullArcName))
616
617 CScreenRestorer screenRestorer; 616 CScreenRestorer screenRestorer;
618 CProgressBox progressBox; 617 CProgressBox progressBox;
619 CProgressBox *progressBoxPointer = NULL; 618 CProgressBox *progressBoxPointer = NULL;
@@ -640,15 +639,15 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
640 archiveHandler = agentSpec; 639 archiveHandler = agentSpec;
641 // CLSID realClassID; 640 // CLSID realClassID;
642 CMyComBSTR archiveType; 641 CMyComBSTR archiveType;
643 RINOK(agentSpec->Open(NULL, 642 RINOK(archiveHandler->Open(NULL,
644 GetUnicodeString(fullArcName, CP_OEMCP), UString(), 643 GetUnicodeString(fullArcName, CP_OEMCP), UString(),
645 // &realClassID, 644 // &realClassID,
646 &archiveType, 645 &archiveType,
647 NULL)); 646 NULL))
648 647
649 if (MyStringCompareNoCase(archiverInfoFinal.Name, (const wchar_t *)archiveType) != 0) 648 if (MyStringCompareNoCase(archiverInfoFinal.Name, (const wchar_t *)archiveType) != 0)
650 throw "Type of existing archive differs from specified type"; 649 throw "Type of existing archive differs from specified type";
651 HRESULT result = archiveHandler.QueryInterface( 650 const HRESULT result = archiveHandler.QueryInterface(
652 IID_IOutFolderArchive, &outArchive); 651 IID_IOutFolderArchive, &outArchive);
653 if (result != S_OK) 652 if (result != S_OK)
654 { 653 {
@@ -690,7 +689,7 @@ HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
690 updateCallbackSpec->Init(/* archiveHandler, */ progressBoxPointer); 689 updateCallbackSpec->Init(/* archiveHandler, */ progressBoxPointer);
691 690
692 691
693 RINOK(SetOutProperties(outArchive, compressionInfo.Level)); 692 RINOK(SetOutProperties(outArchive, compressionInfo.Level))
694 693
695 // FStringVector requestedPaths; 694 // FStringVector requestedPaths;
696 // FStringVector processedPaths; 695 // FStringVector processedPaths;
@@ -754,7 +753,7 @@ HRESULT CPlugin::CreateFolder()
754 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL } 753 { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }
755 }; 754 };
756 755
757 const int kNumDialogItems = ARRAY_SIZE(initItems); 756 const int kNumDialogItems = Z7_ARRAY_SIZE(initItems);
758 const int kOkButtonIndex = kNumDialogItems - 2; 757 const int kOkButtonIndex = kNumDialogItems - 2;
759 758
760 FarDialogItem dialogItems[kNumDialogItems]; 759 FarDialogItem dialogItems[kNumDialogItems];
diff --git a/CPP/7zip/UI/Far/ProgressBox.cpp b/CPP/7zip/UI/Far/ProgressBox.cpp
index 6efb132..ab25a10 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)
67 67
68static void GetTimeString(UInt64 timeValue, char *s) 68static void GetTimeString(UInt64 timeValue, char *s)
69{ 69{
70 UInt64 hours = timeValue / 3600; 70 const UInt64 hours = timeValue / 3600;
71 UInt32 seconds = (UInt32)(timeValue - hours * 3600); 71 UInt32 seconds = (UInt32)(timeValue - hours * 3600);
72 UInt32 minutes = seconds / 60; 72 const UInt32 minutes = seconds / 60;
73 seconds %= 60; 73 seconds %= 60;
74 if (hours > 99) 74 if (hours > 99)
75 { 75 {
@@ -78,11 +78,11 @@ static void GetTimeString(UInt64 timeValue, char *s)
78 } 78 }
79 else 79 else
80 { 80 {
81 UInt32 hours32 = (UInt32)hours; 81 const UInt32 hours32 = (UInt32)hours;
82 UINT_TO_STR_2(hours32); 82 UINT_TO_STR_2(hours32)
83 } 83 }
84 *s++ = ':'; UINT_TO_STR_2(minutes); 84 *s++ = ':'; UINT_TO_STR_2(minutes)
85 *s++ = ':'; UINT_TO_STR_2(seconds); 85 *s++ = ':'; UINT_TO_STR_2(seconds)
86 *s = 0; 86 *s = 0;
87} 87}
88 88
@@ -280,10 +280,10 @@ void CProgressBox::Print()
280 else 280 else
281 */ 281 */
282 { 282 {
283 int slashPos = FileName.ReverseFind_PathSepar(); 283 const int slashPos = FileName.ReverseFind_PathSepar();
284 if (slashPos >= 0) 284 if (slashPos >= 0)
285 { 285 {
286 _name1U.SetFrom(FileName, slashPos + 1); 286 _name1U.SetFrom(FileName, (unsigned)(slashPos + 1));
287 _name2U = FileName.Ptr(slashPos + 1); 287 _name2U = FileName.Ptr(slashPos + 1);
288 } 288 }
289 else 289 else
@@ -295,7 +295,7 @@ void CProgressBox::Print()
295 295
296 { 296 {
297 const char *strings[] = { _title, _timeStr, _files, _sizesStr, Command, _name1, _name2, _perc }; 297 const char *strings[] = { _title, _timeStr, _files, _sizesStr, Command, _name1, _name2, _perc };
298 NFar::g_StartupInfo.ShowMessage(FMSG_LEFTALIGN, NULL, strings, ARRAY_SIZE(strings), 0); 298 NFar::g_StartupInfo.ShowMessage(FMSG_LEFTALIGN, NULL, strings, Z7_ARRAY_SIZE(strings), 0);
299 } 299 }
300 300
301 _wasPrinted = true; 301 _wasPrinted = true;
diff --git a/CPP/7zip/UI/Far/ProgressBox.h b/CPP/7zip/UI/Far/ProgressBox.h
index 54bdb4f..6e8b487 100644
--- a/CPP/7zip/UI/Far/ProgressBox.h
+++ b/CPP/7zip/UI/Far/ProgressBox.h
@@ -1,7 +1,7 @@
1// ProgressBox.h 1// ProgressBox.h
2 2
3#ifndef __PROGRESS_BOX_H 3#ifndef ZIP7_INC_PROGRESS_BOX_H
4#define __PROGRESS_BOX_H 4#define ZIP7_INC_PROGRESS_BOX_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7#include "../../../Common/MyTypes.h" 7#include "../../../Common/MyTypes.h"
diff --git a/CPP/7zip/UI/Far/StdAfx.h b/CPP/7zip/UI/Far/StdAfx.h
index 2854ff3..035267c 100644
--- a/CPP/7zip/UI/Far/StdAfx.h
+++ b/CPP/7zip/UI/Far/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../../Common/Common.h" 9#include "../../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/7zip/UI/Far/UpdateCallbackFar.cpp b/CPP/7zip/UI/Far/UpdateCallbackFar.cpp
index 3f0f206..94f0a47 100644
--- a/CPP/7zip/UI/Far/UpdateCallbackFar.cpp
+++ b/CPP/7zip/UI/Far/UpdateCallbackFar.cpp
@@ -2,7 +2,7 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifndef _7ZIP_ST 5#ifndef Z7_ST
6#include "../../../Windows/Synchronization.h" 6#include "../../../Windows/Synchronization.h"
7#endif 7#endif
8 8
@@ -14,7 +14,7 @@
14using namespace NWindows; 14using namespace NWindows;
15using namespace NFar; 15using namespace NFar;
16 16
17#ifndef _7ZIP_ST 17#ifndef Z7_ST
18static NSynchronization::CCriticalSection g_CriticalSection; 18static NSynchronization::CCriticalSection g_CriticalSection;
19#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 19#define MT_LOCK NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
20#else 20#else
@@ -27,7 +27,7 @@ static HRESULT CheckBreak2()
27} 27}
28 28
29 29
30STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */) 30Z7_COM7F_IMF(CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */))
31{ 31{
32 MT_LOCK 32 MT_LOCK
33 33
@@ -43,14 +43,14 @@ STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 numFolders, UInt64 numFi
43 return CheckBreak2(); 43 return CheckBreak2();
44} 44}
45 45
46STDMETHODIMP CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode) 46Z7_COM7F_IMF(CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode))
47{ 47{
48 if (ShowSysErrorMessage(errorCode, path) == -1) 48 if (ShowSysErrorMessage(errorCode, path) == -1)
49 return E_ABORT; 49 return E_ABORT;
50 return CheckBreak2(); 50 return CheckBreak2();
51} 51}
52 52
53STDMETHODIMP CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles) 53Z7_COM7F_IMF(CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles))
54{ 54{
55 MT_LOCK 55 MT_LOCK
56 56
@@ -63,12 +63,12 @@ STDMETHODIMP CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles)
63} 63}
64 64
65 65
66STDMETHODIMP CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) 66Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */))
67{ 67{
68 return S_OK; 68 return S_OK;
69} 69}
70 70
71STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) 71Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */))
72{ 72{
73 MT_LOCK 73 MT_LOCK
74 return CheckBreak2(); 74 return CheckBreak2();
@@ -76,7 +76,7 @@ STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, con
76 76
77 77
78 78
79STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) 79Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(UInt64 size))
80{ 80{
81 MT_LOCK 81 MT_LOCK
82 82
@@ -88,7 +88,7 @@ STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size)
88 return CheckBreak2(); 88 return CheckBreak2();
89} 89}
90 90
91STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue) 91Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue))
92{ 92{
93 MT_LOCK 93 MT_LOCK
94 94
@@ -101,7 +101,7 @@ STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completeValue)
101 return CheckBreak2(); 101 return CheckBreak2();
102} 102}
103 103
104STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) 104Z7_COM7F_IMF(CUpdateCallback100Imp::CompressOperation(const wchar_t *name))
105{ 105{
106 MT_LOCK 106 MT_LOCK
107 107
@@ -111,10 +111,10 @@ STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name)
111 _percent->FileName = name; 111 _percent->FileName = name;
112 _percent->Print(); 112 _percent->Print();
113 } 113 }
114 return CheckBreak2();; 114 return CheckBreak2();
115} 115}
116 116
117STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name) 117Z7_COM7F_IMF(CUpdateCallback100Imp::DeleteOperation(const wchar_t *name))
118{ 118{
119 MT_LOCK 119 MT_LOCK
120 120
@@ -124,10 +124,10 @@ STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name)
124 _percent->FileName = name; 124 _percent->FileName = name;
125 _percent->Print(); 125 _percent->Print();
126 } 126 }
127 return CheckBreak2();; 127 return CheckBreak2();
128} 128}
129 129
130STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* opRes */) 130Z7_COM7F_IMF(CUpdateCallback100Imp::OperationResult(Int32 /* opRes */))
131{ 131{
132 MT_LOCK 132 MT_LOCK
133 133
@@ -138,7 +138,7 @@ STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* opRes */)
138 return CheckBreak2(); 138 return CheckBreak2();
139} 139}
140 140
141STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) 141Z7_COM7F_IMF(CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message))
142{ 142{
143 MT_LOCK 143 MT_LOCK
144 144
@@ -147,14 +147,14 @@ STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message)
147 return CheckBreak2(); 147 return CheckBreak2();
148} 148}
149 149
150HRESULT CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode) 150Z7_COM7F_IMF(CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode))
151{ 151{
152 if (ShowSysErrorMessage(errorCode, path) == -1) 152 if (ShowSysErrorMessage(errorCode, path) == -1)
153 return E_ABORT; 153 return E_ABORT;
154 return CheckBreak2(); 154 return CheckBreak2();
155} 155}
156 156
157STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode) 157Z7_COM7F_IMF(CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode))
158{ 158{
159 if (ShowSysErrorMessage(errorCode, path) == -1) 159 if (ShowSysErrorMessage(errorCode, path) == -1)
160 return E_ABORT; 160 return E_ABORT;
@@ -163,7 +163,7 @@ STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESUL
163 163
164void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s); 164void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, AString &s);
165 165
166STDMETHODIMP CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) 166Z7_COM7F_IMF(CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name))
167{ 167{
168 MT_LOCK 168 MT_LOCK
169 169
@@ -179,7 +179,7 @@ STDMETHODIMP CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEnc
179} 179}
180 180
181 181
182STDMETHODIMP CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar_t *name, Int32 /* isDir */) 182Z7_COM7F_IMF(CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar_t *name, Int32 /* isDir */))
183{ 183{
184 const char *s; 184 const char *s;
185 switch (op) 185 switch (op)
@@ -206,26 +206,26 @@ STDMETHODIMP CUpdateCallback100Imp::ReportUpdateOperation(UInt32 op, const wchar
206 _percent->Print(); 206 _percent->Print();
207 } 207 }
208 208
209 return CheckBreak2();; 209 return CheckBreak2();
210} 210}
211 211
212 212
213extern HRESULT GetPassword(UString &password); 213extern HRESULT GetPassword(UString &password);
214 214
215STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password) 215Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password))
216{ 216{
217 MT_LOCK 217 MT_LOCK
218 218
219 *password = NULL; 219 *password = NULL;
220 if (!PasswordIsDefined) 220 if (!PasswordIsDefined)
221 { 221 {
222 RINOK(GetPassword(Password)); 222 RINOK(GetPassword(Password))
223 PasswordIsDefined = true; 223 PasswordIsDefined = true;
224 } 224 }
225 return StringToBstr(Password, password); 225 return StringToBstr(Password, password);
226} 226}
227 227
228STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) 228Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password))
229{ 229{
230 MT_LOCK 230 MT_LOCK
231 231
diff --git a/CPP/7zip/UI/Far/UpdateCallbackFar.h b/CPP/7zip/UI/Far/UpdateCallbackFar.h
index d2c2c8e..4ec5eed 100644
--- a/CPP/7zip/UI/Far/UpdateCallbackFar.h
+++ b/CPP/7zip/UI/Far/UpdateCallbackFar.h
@@ -1,7 +1,7 @@
1// UpdateCallbackFar.h 1// UpdateCallbackFar.h
2 2
3#ifndef __UPDATE_CALLBACK_FAR_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_FAR_H
4#define __UPDATE_CALLBACK_FAR_H 4#define ZIP7_INC_UPDATE_CALLBACK_FAR_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -11,43 +11,27 @@
11 11
12#include "ProgressBox.h" 12#include "ProgressBox.h"
13 13
14class CUpdateCallback100Imp: 14Z7_CLASS_IMP_COM_6(
15 public IFolderArchiveUpdateCallback, 15 CUpdateCallback100Imp
16 public IFolderArchiveUpdateCallback2, 16 , IFolderArchiveUpdateCallback
17 public IFolderScanProgress, 17 , IFolderArchiveUpdateCallback2
18 public ICryptoGetTextPassword2, 18 , IFolderScanProgress
19 public ICryptoGetTextPassword, 19 , ICryptoGetTextPassword2
20 public IArchiveOpenCallback, 20 , ICryptoGetTextPassword
21 public CMyUnknownImp 21 , IArchiveOpenCallback
22{ 22)
23 Z7_IFACE_COM7_IMP(IProgress)
24
23 // CMyComPtr<IInFolderArchive> _archiveHandler; 25 // CMyComPtr<IInFolderArchive> _archiveHandler;
24 CProgressBox *_percent; 26 CProgressBox *_percent;
25 UInt64 _total; 27 // UInt64 _total;
26
27public: 28public:
28
29 bool PasswordIsDefined; 29 bool PasswordIsDefined;
30 UString Password; 30 UString Password;
31 31
32 MY_UNKNOWN_IMP6( 32 CUpdateCallback100Imp()
33 IFolderArchiveUpdateCallback, 33 // : _total(0)
34 IFolderArchiveUpdateCallback2, 34 {}
35 IFolderScanProgress,
36 ICryptoGetTextPassword2,
37 ICryptoGetTextPassword,
38 IArchiveOpenCallback
39 )
40
41 INTERFACE_IProgress(;)
42 INTERFACE_IFolderArchiveUpdateCallback(;)
43 INTERFACE_IFolderArchiveUpdateCallback2(;)
44 INTERFACE_IFolderScanProgress(;)
45 INTERFACE_IArchiveOpenCallback(;)
46
47 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
48 STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password);
49
50 CUpdateCallback100Imp(): _total(0) {}
51 void Init(/* IInFolderArchive *archiveHandler, */ CProgressBox *progressBox) 35 void Init(/* IInFolderArchive *archiveHandler, */ CProgressBox *progressBox)
52 { 36 {
53 // _archiveHandler = archiveHandler; 37 // _archiveHandler = archiveHandler;
diff --git a/CPP/7zip/UI/Far/makefile b/CPP/7zip/UI/Far/makefile
index 0db2274..f3809a8 100644
--- a/CPP/7zip/UI/Far/makefile
+++ b/CPP/7zip/UI/Far/makefile
@@ -1,11 +1,10 @@
1PROG = 7-ZipFar.dll 1PROG = 7-ZipFar.dll
2DEF_FILE = Far.def 2DEF_FILE = Far.def
3CFLAGS = $(CFLAGS) \ 3CFLAGS = $(CFLAGS) \
4 -DEXTERNAL_CODECS \ 4 -DZ7_EXTERNAL_CODECS \
5 -DNEW_FOLDER_INTERFACE
6 5
7!IFNDEF UNDER_CE 6!IFNDEF UNDER_CE
8CFLAGS = $(CFLAGS) -DWIN_LONG_PATH 7CFLAGS = $(CFLAGS) -DZ7_LONG_PATH
9!ENDIF 8!ENDIF
10 9
11CURRENT_OBJS = \ 10CURRENT_OBJS = \
@@ -40,11 +39,13 @@ WIN_OBJS = \
40 $O\FileIO.obj \ 39 $O\FileIO.obj \
41 $O\FileLink.obj \ 40 $O\FileLink.obj \
42 $O\FileName.obj \ 41 $O\FileName.obj \
42 $O\FileSystem.obj \
43 $O\PropVariant.obj \ 43 $O\PropVariant.obj \
44 $O\PropVariantConv.obj \ 44 $O\PropVariantConv.obj \
45 $O\Registry.obj \ 45 $O\Registry.obj \
46 $O\ResourceString.obj \ 46 $O\ResourceString.obj \
47 $O\Synchronization.obj \ 47 $O\Synchronization.obj \
48 $O\System.obj \
48 $O\TimeUtils.obj \ 49 $O\TimeUtils.obj \
49 50
507ZIP_COMMON_OBJS = \ 517ZIP_COMMON_OBJS = \
@@ -88,7 +89,6 @@ AGENT_OBJS = \
88 $O\AgentOut.obj \ 89 $O\AgentOut.obj \
89 $O\AgentProxy.obj \ 90 $O\AgentProxy.obj \
90 $O\ArchiveFolder.obj \ 91 $O\ArchiveFolder.obj \
91 $O\ArchiveFolderOpen.obj \
92 $O\ArchiveFolderOut.obj \ 92 $O\ArchiveFolderOut.obj \
93 $O\UpdateCallbackAgent.obj \ 93 $O\UpdateCallbackAgent.obj \
94 94
diff --git a/CPP/7zip/UI/FileManager/7zFM.exe.manifest b/CPP/7zip/UI/FileManager/7zFM.exe.manifest
index 6a13c92..69c7f0b 100644
--- a/CPP/7zip/UI/FileManager/7zFM.exe.manifest
+++ b/CPP/7zip/UI/FileManager/7zFM.exe.manifest
@@ -17,4 +17,7 @@
17 <dpiAware>true</dpiAware> 17 <dpiAware>true</dpiAware>
18 </asmv3:windowsSettings> 18 </asmv3:windowsSettings>
19 </asmv3:application> 19 </asmv3:application>
20<application xmlns="urn:schemas-microsoft-com:asm.v3">
21<windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
22<ws2:longPathAware>true</ws2:longPathAware></windowsSettings></application>
20</assembly> 23</assembly>
diff --git a/CPP/7zip/UI/FileManager/AboutDialog.cpp b/CPP/7zip/UI/FileManager/AboutDialog.cpp
index 082902e..efc74cc 100644
--- a/CPP/7zip/UI/FileManager/AboutDialog.cpp
+++ b/CPP/7zip/UI/FileManager/AboutDialog.cpp
@@ -14,10 +14,12 @@
14#include "HelpUtils.h" 14#include "HelpUtils.h"
15#include "LangUtils.h" 15#include "LangUtils.h"
16 16
17#ifdef Z7_LANG
17static const UInt32 kLangIDs[] = 18static const UInt32 kLangIDs[] =
18{ 19{
19 IDT_ABOUT_INFO 20 IDT_ABOUT_INFO
20}; 21};
22#endif
21 23
22#define kHomePageURL TEXT("https://www.7-zip.org/") 24#define kHomePageURL TEXT("https://www.7-zip.org/")
23#define kHelpTopic "start.htm" 25#define kHelpTopic "start.htm"
@@ -29,7 +31,7 @@ extern CCodecs *g_CodecsObj;
29 31
30bool CAboutDialog::OnInit() 32bool CAboutDialog::OnInit()
31{ 33{
32 #ifdef EXTERNAL_CODECS 34 #ifdef Z7_EXTERNAL_CODECS
33 if (g_CodecsObj) 35 if (g_CodecsObj)
34 { 36 {
35 UString s; 37 UString s;
@@ -39,11 +41,13 @@ bool CAboutDialog::OnInit()
39 } 41 }
40 #endif 42 #endif
41 43
42 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 44 #ifdef Z7_LANG
45 LangSetWindowText(*this, IDD_ABOUT);
46 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
47 #endif
43 SetItemText(IDT_ABOUT_VERSION, UString("7-Zip " MY_VERSION_CPU)); 48 SetItemText(IDT_ABOUT_VERSION, UString("7-Zip " MY_VERSION_CPU));
44 SetItemText(IDT_ABOUT_DATE, LLL(MY_DATE)); 49 SetItemText(IDT_ABOUT_DATE, LLL(MY_DATE));
45 50
46 LangSetWindowText(*this, IDD_ABOUT);
47 NormalizePosition(); 51 NormalizePosition();
48 return CModalDialog::OnInit(); 52 return CModalDialog::OnInit();
49} 53}
@@ -53,7 +57,7 @@ void CAboutDialog::OnHelp()
53 ShowHelpWindow(kHelpTopic); 57 ShowHelpWindow(kHelpTopic);
54} 58}
55 59
56bool CAboutDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 60bool CAboutDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
57{ 61{
58 LPCTSTR url; 62 LPCTSTR url;
59 switch (buttonID) 63 switch (buttonID)
diff --git a/CPP/7zip/UI/FileManager/AboutDialog.h b/CPP/7zip/UI/FileManager/AboutDialog.h
index 39fd3ba..1d11d74 100644
--- a/CPP/7zip/UI/FileManager/AboutDialog.h
+++ b/CPP/7zip/UI/FileManager/AboutDialog.h
@@ -1,7 +1,7 @@
1// AboutDialog.h 1// AboutDialog.h
2 2
3#ifndef __ABOUT_DIALOG_H 3#ifndef ZIP7_INC_ABOUT_DIALOG_H
4#define __ABOUT_DIALOG_H 4#define ZIP7_INC_ABOUT_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7 7
@@ -10,10 +10,10 @@
10class CAboutDialog: public NWindows::NControl::CModalDialog 10class CAboutDialog: public NWindows::NControl::CModalDialog
11{ 11{
12public: 12public:
13 virtual bool OnInit(); 13 virtual bool OnInit() Z7_override;
14 virtual void OnHelp(); 14 virtual void OnHelp() Z7_override;
15 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 15 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
16 INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_ABOUT, wndParent); } 16 INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_ABOUT, wndParent); }
17}; 17};
18 18
19#endif 19#endif
diff --git a/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp b/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp
index e1c99d3..b3d354d 100644
--- a/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp
+++ b/CPP/7zip/UI/FileManager/AltStreamsFolder.cpp
@@ -2,10 +2,32 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifdef __MINGW32_VERSION
6// #if !defined(_MSC_VER) && (__GNUC__) && (__GNUC__ < 10)
7// for old mingw
8#include <ddk/ntddk.h>
9#else
10#ifndef Z7_OLD_WIN_SDK
11 #if !defined(_M_IA64)
12 #include <winternl.h>
13 #endif
14#else
15typedef LONG NTSTATUS;
16typedef struct _IO_STATUS_BLOCK {
17 union {
18 NTSTATUS Status;
19 PVOID Pointer;
20 };
21 ULONG_PTR Information;
22} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
23#endif
24#endif
25
5#include "../../../Common/ComTry.h" 26#include "../../../Common/ComTry.h"
6#include "../../../Common/StringConvert.h" 27#include "../../../Common/StringConvert.h"
7#include "../../../Common/Wildcard.h" 28#include "../../../Common/Wildcard.h"
8 29
30#include "../../../Windows/DLL.h"
9#include "../../../Windows/ErrorMsg.h" 31#include "../../../Windows/ErrorMsg.h"
10#include "../../../Windows/FileDir.h" 32#include "../../../Windows/FileDir.h"
11#include "../../../Windows/FileIO.h" 33#include "../../../Windows/FileIO.h"
@@ -54,7 +76,7 @@ static unsigned GetFsParentPrefixSize(const FString &path)
54{ 76{
55 if (IsNetworkShareRootPath(path)) 77 if (IsNetworkShareRootPath(path))
56 return 0; 78 return 0;
57 unsigned prefixSize = GetRootPrefixSize(path); 79 const unsigned prefixSize = GetRootPrefixSize(path);
58 if (prefixSize == 0 || prefixSize >= path.Len()) 80 if (prefixSize == 0 || prefixSize >= path.Len())
59 return 0; 81 return 0;
60 FString parentPath = path; 82 FString parentPath = path;
@@ -70,7 +92,7 @@ static unsigned GetFsParentPrefixSize(const FString &path)
70 } 92 }
71 if ((unsigned)pos + 1 < prefixSize) 93 if ((unsigned)pos + 1 < prefixSize)
72 return 0; 94 return 0;
73 return pos + 1; 95 return (unsigned)pos + 1;
74} 96}
75 97
76HRESULT CAltStreamsFolder::Init(const FString &path /* , IFolderFolder *parentFolder */) 98HRESULT CAltStreamsFolder::Init(const FString &path /* , IFolderFolder *parentFolder */)
@@ -115,7 +137,7 @@ HRESULT CAltStreamsFolder::Init(const FString &path /* , IFolderFolder *parentFo
115 return S_OK; 137 return S_OK;
116} 138}
117 139
118STDMETHODIMP CAltStreamsFolder::LoadItems() 140Z7_COM7F_IMF(CAltStreamsFolder::LoadItems())
119{ 141{
120 Int32 dummy; 142 Int32 dummy;
121 WasChanged(&dummy); 143 WasChanged(&dummy);
@@ -152,7 +174,7 @@ STDMETHODIMP CAltStreamsFolder::LoadItems()
152 return S_OK; 174 return S_OK;
153} 175}
154 176
155STDMETHODIMP CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems) 177Z7_COM7F_IMF(CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems))
156{ 178{
157 *numItems = Streams.Size(); 179 *numItems = Streams.Size();
158 return S_OK; 180 return S_OK;
@@ -160,16 +182,16 @@ STDMETHODIMP CAltStreamsFolder::GetNumberOfItems(UInt32 *numItems)
160 182
161#ifdef USE_UNICODE_FSTRING 183#ifdef USE_UNICODE_FSTRING
162 184
163STDMETHODIMP CAltStreamsFolder::GetItemPrefix(UInt32 /* index */, const wchar_t **name, unsigned *len) 185Z7_COM7F_IMF(CAltStreamsFolder::GetItemPrefix(UInt32 /* index */, const wchar_t **name, unsigned *len))
164{ 186{
165 *name = 0; 187 *name = NULL;
166 *len = 0; 188 *len = 0;
167 return S_OK; 189 return S_OK;
168} 190}
169 191
170STDMETHODIMP CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) 192Z7_COM7F_IMF(CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len))
171{ 193{
172 *name = 0; 194 *name = NULL;
173 *len = 0; 195 *len = 0;
174 { 196 {
175 const CAltStream &ss = Streams[index]; 197 const CAltStream &ss = Streams[index];
@@ -179,7 +201,7 @@ STDMETHODIMP CAltStreamsFolder::GetItemName(UInt32 index, const wchar_t **name,
179 return S_OK; 201 return S_OK;
180} 202}
181 203
182STDMETHODIMP_(UInt64) CAltStreamsFolder::GetItemSize(UInt32 index) 204Z7_COM7F_IMF2(UInt64, CAltStreamsFolder::GetItemSize(UInt32 index))
183{ 205{
184 return Streams[index].Size; 206 return Streams[index].Size;
185} 207}
@@ -187,7 +209,7 @@ STDMETHODIMP_(UInt64) CAltStreamsFolder::GetItemSize(UInt32 index)
187#endif 209#endif
188 210
189 211
190STDMETHODIMP CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 212Z7_COM7F_IMF(CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
191{ 213{
192 NCOM::CPropVariant prop; 214 NCOM::CPropVariant prop;
193 { 215 {
@@ -223,11 +245,11 @@ STDMETHODIMP CAltStreamsFolder::GetProperty(UInt32 index, PROPID propID, PROPVAR
223 245
224static inline const wchar_t *GetExtensionPtr(const UString &name) 246static inline const wchar_t *GetExtensionPtr(const UString &name)
225{ 247{
226 int dotPos = name.ReverseFind_Dot(); 248 const int dotPos = name.ReverseFind_Dot();
227 return name.Ptr((dotPos < 0) ? name.Len() : dotPos); 249 return name.Ptr(dotPos < 0 ? name.Len() : (unsigned)dotPos);
228} 250}
229 251
230STDMETHODIMP_(Int32) CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */) 252Z7_COM7F_IMF2(Int32, CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */))
231{ 253{
232 const CAltStream &ss1 = Streams[index1]; 254 const CAltStream &ss1 = Streams[index1];
233 const CAltStream &ss2 = Streams[index2]; 255 const CAltStream &ss2 = Streams[index2];
@@ -262,23 +284,23 @@ STDMETHODIMP_(Int32) CAltStreamsFolder::CompareItems(UInt32 index1, UInt32 index
262 return 0; 284 return 0;
263} 285}
264 286
265STDMETHODIMP CAltStreamsFolder::BindToFolder(UInt32 /* index */, IFolderFolder **resultFolder) 287Z7_COM7F_IMF(CAltStreamsFolder::BindToFolder(UInt32 /* index */, IFolderFolder **resultFolder))
266{ 288{
267 *resultFolder = 0; 289 *resultFolder = NULL;
268 return E_INVALIDARG; 290 return E_INVALIDARG;
269} 291}
270 292
271STDMETHODIMP CAltStreamsFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder **resultFolder) 293Z7_COM7F_IMF(CAltStreamsFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder **resultFolder))
272{ 294{
273 *resultFolder = 0; 295 *resultFolder = NULL;
274 return E_INVALIDARG; 296 return E_INVALIDARG;
275} 297}
276 298
277// static CFSTR const kSuperPrefix = FTEXT("\\\\?\\"); 299// static CFSTR const kSuperPrefix = FTEXT("\\\\?\\");
278 300
279STDMETHODIMP CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder) 301Z7_COM7F_IMF(CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder))
280{ 302{
281 *resultFolder = 0; 303 *resultFolder = NULL;
282 /* 304 /*
283 if (_parentFolder) 305 if (_parentFolder)
284 { 306 {
@@ -338,15 +360,9 @@ STDMETHODIMP CAltStreamsFolder::BindToParentFolder(IFolderFolder **resultFolder)
338 return S_OK; 360 return S_OK;
339} 361}
340 362
341STDMETHODIMP CAltStreamsFolder::GetNumberOfProperties(UInt32 *numProperties) 363IMP_IFolderFolder_Props(CAltStreamsFolder)
342{
343 *numProperties = ARRAY_SIZE(kProps);
344 return S_OK;
345}
346
347STDMETHODIMP CAltStreamsFolder::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps)
348 364
349STDMETHODIMP CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 365Z7_COM7F_IMF(CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value))
350{ 366{
351 COM_TRY_BEGIN 367 COM_TRY_BEGIN
352 NWindows::NCOM::CPropVariant prop; 368 NWindows::NCOM::CPropVariant prop;
@@ -360,7 +376,7 @@ STDMETHODIMP CAltStreamsFolder::GetFolderProperty(PROPID propID, PROPVARIANT *va
360 COM_TRY_END 376 COM_TRY_END
361} 377}
362 378
363STDMETHODIMP CAltStreamsFolder::WasChanged(Int32 *wasChanged) 379Z7_COM7F_IMF(CAltStreamsFolder::WasChanged(Int32 *wasChanged))
364{ 380{
365 bool wasChangedMain = false; 381 bool wasChangedMain = false;
366 for (;;) 382 for (;;)
@@ -385,7 +401,7 @@ STDMETHODIMP CAltStreamsFolder::WasChanged(Int32 *wasChanged)
385 return S_OK; 401 return S_OK;
386} 402}
387 403
388STDMETHODIMP CAltStreamsFolder::Clone(IFolderFolder **resultFolder) 404Z7_COM7F_IMF(CAltStreamsFolder::Clone(IFolderFolder **resultFolder))
389{ 405{
390 CAltStreamsFolder *folderSpec = new CAltStreamsFolder; 406 CAltStreamsFolder *folderSpec = new CAltStreamsFolder;
391 CMyComPtr<IFolderFolder> folderNew = folderSpec; 407 CMyComPtr<IFolderFolder> folderNew = folderSpec;
@@ -436,39 +452,31 @@ static HRESULT SendMessageError(IFolderArchiveUpdateCallback *callback,
436} 452}
437*/ 453*/
438 454
439STDMETHODIMP CAltStreamsFolder::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */) 455Z7_COM7F_IMF(CAltStreamsFolder::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */))
440{ 456{
441 return E_NOTIMPL; 457 return E_NOTIMPL;
442} 458}
443 459
444STDMETHODIMP CAltStreamsFolder::CreateFile(const wchar_t *name, IProgress * /* progress */) 460Z7_COM7F_IMF(CAltStreamsFolder::CreateFile(const wchar_t *name, IProgress * /* progress */))
445{ 461{
446 FString absPath; 462 FString absPath;
447 GetAbsPath(name, absPath); 463 GetAbsPath(name, absPath);
448 NIO::COutFile outFile; 464 NIO::COutFile outFile;
449 if (!outFile.Create(absPath, false)) 465 if (!outFile.Create(absPath, false))
450 return ::GetLastError(); 466 return GetLastError_noZero_HRESULT();
451 return S_OK; 467 return S_OK;
452} 468}
453 469
454static DWORD Return_LastError_or_FAIL()
455{
456 DWORD errorCode = GetLastError();
457 if (errorCode == 0)
458 errorCode = (DWORD)E_FAIL;
459 return errorCode;
460}
461
462static UString GetLastErrorMessage() 470static UString GetLastErrorMessage()
463{ 471{
464 return NError::MyFormatMessage(Return_LastError_or_FAIL()); 472 return NError::MyFormatMessage(GetLastError_noZero_HRESULT());
465} 473}
466 474
467static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR outPath, IFolderArchiveUpdateCallback *callback) 475static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR outPath, IFolderArchiveUpdateCallback *callback)
468{ 476{
469 if (NFind::DoesFileOrDirExist(outPath)) 477 if (NFind::DoesFileOrDirExist(outPath))
470 { 478 {
471 RINOK(SendMessageError(callback, NError::MyFormatMessage(ERROR_ALREADY_EXISTS), FString(outPath))); 479 RINOK(SendMessageError(callback, NError::MyFormatMessage(ERROR_ALREADY_EXISTS), FString(outPath)))
472 CFileInfo fi; 480 CFileInfo fi;
473 if (fi.Find(inPath)) 481 if (fi.Find(inPath))
474 { 482 {
@@ -480,8 +488,8 @@ static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR ou
480 488
481 { 489 {
482 if (callback) 490 if (callback)
483 RINOK(callback->CompressOperation(fs2us(inPath))); 491 RINOK(callback->CompressOperation(fs2us(inPath)))
484 RINOK(state.MyCopyFile(inPath, outPath)); 492 RINOK(state.MyCopyFile(inPath, outPath))
485 if (state.ErrorFileIndex >= 0) 493 if (state.ErrorFileIndex >= 0)
486 { 494 {
487 if (state.ErrorMessage.IsEmpty()) 495 if (state.ErrorMessage.IsEmpty())
@@ -492,31 +500,136 @@ static HRESULT UpdateFile(NFsFolder::CCopyStateIO &state, CFSTR inPath, CFSTR ou
492 else 500 else
493 errorName = outPath; 501 errorName = outPath;
494 if (callback) 502 if (callback)
495 RINOK(SendMessageError(callback, state.ErrorMessage, errorName)); 503 RINOK(SendMessageError(callback, state.ErrorMessage, errorName))
496 } 504 }
497 if (callback) 505 if (callback)
498 RINOK(callback->OperationResult(0)); 506 RINOK(callback->OperationResult(0))
499 } 507 }
500 508
501 return S_OK; 509 return S_OK;
502} 510}
503 511
504STDMETHODIMP CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress) 512EXTERN_C_BEGIN
513
514typedef enum
505{ 515{
506 CMyComPtr<IFolderArchiveUpdateCallback> callback; 516 Z7_WIN_FileRenameInformation = 10
507 if (progress) 517}
518Z7_WIN_FILE_INFORMATION_CLASS;
519
520
521typedef struct
522{
523 // #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10_RS1)
524 union
508 { 525 {
509 RINOK(progress->QueryInterface(IID_IFolderArchiveUpdateCallback, (void **)&callback)); 526 BOOLEAN ReplaceIfExists; // FileRenameInformation
510 } 527 ULONG Flags; // FileRenameInformationEx
528 } DUMMYUNIONNAME;
529 // #else
530 // BOOLEAN ReplaceIfExists;
531 // #endif
532 HANDLE RootDirectory;
533 ULONG FileNameLength;
534 WCHAR FileName[1];
535} Z7_WIN_FILE_RENAME_INFORMATION;
536
537#if (_WIN32_WINNT >= 0x0500) && !defined(_M_IA64)
538#define Z7_WIN_NTSTATUS NTSTATUS
539#define Z7_WIN_IO_STATUS_BLOCK IO_STATUS_BLOCK
540#else
541typedef LONG Z7_WIN_NTSTATUS;
542typedef struct
543{
544 union
545 {
546 Z7_WIN_NTSTATUS Status;
547 PVOID Pointer;
548 } DUMMYUNIONNAME;
549 ULONG_PTR Information;
550} Z7_WIN_IO_STATUS_BLOCK;
551#endif
552
553typedef Z7_WIN_NTSTATUS (WINAPI *Func_NtSetInformationFile)(
554 HANDLE FileHandle,
555 Z7_WIN_IO_STATUS_BLOCK *IoStatusBlock,
556 PVOID FileInformation,
557 ULONG Length,
558 Z7_WIN_FILE_INFORMATION_CLASS FileInformationClass);
559
560// NTAPI
561typedef ULONG (WINAPI *Func_RtlNtStatusToDosError)(Z7_WIN_NTSTATUS Status);
562
563#define MY_STATUS_SUCCESS 0
564
565EXTERN_C_END
566
567// static Func_NtSetInformationFile f_NtSetInformationFile;
568// static bool g_NtSetInformationFile_WasRequested = false;
511 569
512 FString destPath = _pathPrefix + us2fs(newName);
513 570
571Z7_COM7F_IMF(CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *progress))
572{
514 const CAltStream &ss = Streams[index]; 573 const CAltStream &ss = Streams[index];
574 const FString srcPath = _pathPrefix + us2fs(ss.Name);
575
576 const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll");
577 // if (!g_NtSetInformationFile_WasRequested) {
578 // g_NtSetInformationFile_WasRequested = true;
579 const
580 Func_NtSetInformationFile
581 f_NtSetInformationFile = Z7_GET_PROC_ADDRESS(
582 Func_NtSetInformationFile, ntdll,
583 "NtSetInformationFile");
584 if (f_NtSetInformationFile)
585 {
586 NIO::CInFile inFile;
587 if (inFile.Open_for_FileRenameInformation(srcPath))
588 {
589 UString destPath (':');
590 destPath += newName;
591 const ULONG len = (ULONG)sizeof(wchar_t) * destPath.Len();
592 CByteBuffer buffer(sizeof(Z7_WIN_FILE_RENAME_INFORMATION) + len);
593 // buffer is 4 bytes larger than required.
594 Z7_WIN_FILE_RENAME_INFORMATION *fri = (Z7_WIN_FILE_RENAME_INFORMATION *)(void *)(Byte *)buffer;
595 memset(fri, 0, sizeof(Z7_WIN_FILE_RENAME_INFORMATION));
596 /* DOCS: If ReplaceIfExists is set to TRUE, the rename operation will succeed only
597 if a stream with the same name does not exist or is a zero-length data stream. */
598 fri->ReplaceIfExists = FALSE;
599 fri->RootDirectory = NULL;
600 fri->FileNameLength = len;
601 memcpy(fri->FileName, destPath.Ptr(), len);
602 Z7_WIN_IO_STATUS_BLOCK iosb;
603 const Z7_WIN_NTSTATUS status = f_NtSetInformationFile (inFile.GetHandle(),
604 &iosb, fri, (ULONG)buffer.Size(), Z7_WIN_FileRenameInformation);
605 if (status != MY_STATUS_SUCCESS)
606 {
607 const
608 Func_RtlNtStatusToDosError
609 f_RtlNtStatusToDosError = Z7_GET_PROC_ADDRESS(
610 Func_RtlNtStatusToDosError, ntdll,
611 "RtlNtStatusToDosError");
612 if (f_RtlNtStatusToDosError)
613 {
614 const ULONG res = f_RtlNtStatusToDosError(status);
615 if (res != ERROR_MR_MID_NOT_FOUND)
616 return HRESULT_FROM_WIN32(res);
617 }
618 }
619 return status;
620 }
621 }
622
623 CMyComPtr<IFolderArchiveUpdateCallback> callback;
624 if (progress)
625 {
626 RINOK(progress->QueryInterface(IID_IFolderArchiveUpdateCallback, (void **)&callback))
627 }
515 628
516 if (callback) 629 if (callback)
517 { 630 {
518 RINOK(callback->SetNumFiles(1)); 631 RINOK(callback->SetNumFiles(1))
519 RINOK(callback->SetTotal(ss.Size)); 632 RINOK(callback->SetTotal(ss.Size))
520 } 633 }
521 634
522 NFsFolder::CCopyStateIO state; 635 NFsFolder::CCopyStateIO state;
@@ -524,32 +637,33 @@ STDMETHODIMP CAltStreamsFolder::Rename(UInt32 index, const wchar_t *newName, IPr
524 state.TotalSize = 0; 637 state.TotalSize = 0;
525 state.DeleteSrcFile = true; 638 state.DeleteSrcFile = true;
526 639
527 return UpdateFile(state, _pathPrefix + us2fs(ss.Name), destPath, callback); 640 const FString destPath = _pathPrefix + us2fs(newName);
641 return UpdateFile(state, srcPath, destPath, callback);
528} 642}
529 643
530STDMETHODIMP CAltStreamsFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress) 644Z7_COM7F_IMF(CAltStreamsFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress))
531{ 645{
532 RINOK(progress->SetTotal(numItems)); 646 RINOK(progress->SetTotal(numItems))
533 for (UInt32 i = 0; i < numItems; i++) 647 for (UInt32 i = 0; i < numItems; i++)
534 { 648 {
535 const CAltStream &ss = Streams[indices[i]]; 649 const CAltStream &ss = Streams[indices[i]];
536 const FString fullPath = _pathPrefix + us2fs(ss.Name); 650 const FString fullPath = _pathPrefix + us2fs(ss.Name);
537 bool result = DeleteFileAlways(fullPath); 651 const bool result = DeleteFileAlways(fullPath);
538 if (!result) 652 if (!result)
539 return Return_LastError_or_FAIL(); 653 return GetLastError_noZero_HRESULT();
540 UInt64 completed = i; 654 const UInt64 completed = i;
541 RINOK(progress->SetCompleted(&completed)); 655 RINOK(progress->SetCompleted(&completed))
542 } 656 }
543 return S_OK; 657 return S_OK;
544} 658}
545 659
546STDMETHODIMP CAltStreamsFolder::SetProperty(UInt32 /* index */, PROPID /* propID */, 660Z7_COM7F_IMF(CAltStreamsFolder::SetProperty(UInt32 /* index */, PROPID /* propID */,
547 const PROPVARIANT * /* value */, IProgress * /* progress */) 661 const PROPVARIANT * /* value */, IProgress * /* progress */))
548{ 662{
549 return E_NOTIMPL; 663 return E_NOTIMPL;
550} 664}
551 665
552STDMETHODIMP CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) 666Z7_COM7F_IMF(CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
553{ 667{
554 const CAltStream &ss = Streams[index]; 668 const CAltStream &ss = Streams[index];
555 *iconIndex = 0; 669 *iconIndex = 0;
@@ -561,30 +675,28 @@ STDMETHODIMP CAltStreamsFolder::GetSystemIconIndex(UInt32 index, Int32 *iconInde
561 *iconIndex = iconIndexTemp; 675 *iconIndex = iconIndexTemp;
562 return S_OK; 676 return S_OK;
563 } 677 }
564 return Return_LastError_or_FAIL(); 678 return GetLastError_noZero_HRESULT();
565} 679}
566 680
567/* 681/*
568class CGetProp: 682Z7_CLASS_IMP_COM_1(
569 public IGetProp, 683 CGetProp
570 public CMyUnknownImp 684 , IGetProp
571{ 685)
572public: 686public:
573 // const CArc *Arc; 687 // const CArc *Arc;
574 // UInt32 IndexInArc; 688 // UInt32 IndexInArc;
575 UString Name; // relative path 689 UString Name; // relative path
576 UInt64 Size; 690 UInt64 Size;
577
578 MY_UNKNOWN_IMP1(IGetProp)
579 INTERFACE_IGetProp(;)
580}; 691};
581 692
582STDMETHODIMP CGetProp::GetProp(PROPID propID, PROPVARIANT *value) 693Z7_COM7F_IMF(CGetProp::GetProp(PROPID propID, PROPVARIANT *value))
583{ 694{
584 if (propID == kpidName) 695 if (propID == kpidName)
585 { 696 {
586 COM_TRY_BEGIN 697 COM_TRY_BEGIN
587 NCOM::CPropVariant prop = Name; 698 NCOM::CPropVariant prop;
699 prop = Name;
588 prop.Detach(value); 700 prop.Detach(value);
589 return S_OK; 701 return S_OK;
590 COM_TRY_END 702 COM_TRY_END
@@ -612,7 +724,7 @@ static HRESULT CopyStream(
612 FString destPath = destPathSpec; 724 FString destPath = destPathSpec;
613 if (CompareFileNames(destPath, srcPath) == 0) 725 if (CompareFileNames(destPath, srcPath) == 0)
614 { 726 {
615 RINOK(SendMessageError(callback, "Cannot copy file onto itself", destPath)); 727 RINOK(SendMessageError(callback, "Cannot copy file onto itself", destPath))
616 return E_ABORT; 728 return E_ABORT;
617 } 729 }
618 730
@@ -624,13 +736,13 @@ static HRESULT CopyStream(
624 &srcFileInfo.MTime, &srcAltStream.Size, 736 &srcFileInfo.MTime, &srcAltStream.Size,
625 fs2us(destPath), 737 fs2us(destPath),
626 &destPathResult, 738 &destPathResult,
627 &writeAskResult)); 739 &writeAskResult))
628 740
629 if (IntToBool(writeAskResult)) 741 if (IntToBool(writeAskResult))
630 { 742 {
631 RINOK(callback->SetCurrentFilePath(fs2us(srcPath))); 743 RINOK(callback->SetCurrentFilePath(fs2us(srcPath)))
632 FString destPathNew (us2fs((LPCOLESTR)destPathResult)); 744 FString destPathNew (us2fs((LPCOLESTR)destPathResult));
633 RINOK(state.MyCopyFile(srcPath, destPathNew)); 745 RINOK(state.MyCopyFile(srcPath, destPathNew))
634 if (state.ErrorFileIndex >= 0) 746 if (state.ErrorFileIndex >= 0)
635 { 747 {
636 if (state.ErrorMessage.IsEmpty()) 748 if (state.ErrorMessage.IsEmpty())
@@ -640,7 +752,7 @@ static HRESULT CopyStream(
640 errorName = srcPath; 752 errorName = srcPath;
641 else 753 else
642 errorName = destPathNew; 754 errorName = destPathNew;
643 RINOK(SendMessageError(callback, state.ErrorMessage, errorName)); 755 RINOK(SendMessageError(callback, state.ErrorMessage, errorName))
644 return E_ABORT; 756 return E_ABORT;
645 } 757 }
646 state.StartPos += state.CurrentSize; 758 state.StartPos += state.CurrentSize;
@@ -650,22 +762,23 @@ static HRESULT CopyStream(
650 if (state.TotalSize >= srcAltStream.Size) 762 if (state.TotalSize >= srcAltStream.Size)
651 { 763 {
652 state.TotalSize -= srcAltStream.Size; 764 state.TotalSize -= srcAltStream.Size;
653 RINOK(state.Progress->SetTotal(state.TotalSize)); 765 RINOK(state.Progress->SetTotal(state.TotalSize))
654 } 766 }
655 } 767 }
656 return S_OK; 768 return S_OK;
657} 769}
658 770
659STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, 771Z7_COM7F_IMF(CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems,
660 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, 772 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */,
661 const wchar_t *path, IFolderOperationsExtractCallback *callback) 773 const wchar_t *path, IFolderOperationsExtractCallback *callback))
662{ 774{
663 if (numItems == 0) 775 if (numItems == 0)
664 return S_OK; 776 return S_OK;
665 777
666 /* 778 /*
667 CMyComPtr<IFolderExtractToStreamCallback> ExtractToStreamCallback; 779 Z7_DECL_CMyComPtr_QI_FROM(
668 RINOK(callback->QueryInterface(IID_IFolderExtractToStreamCallback, (void **)&ExtractToStreamCallback)); 780 IFolderExtractToStreamCallback,
781 ExtractToStreamCallback, callback)
669 if (ExtractToStreamCallback) 782 if (ExtractToStreamCallback)
670 { 783 {
671 Int32 useStreams = 0; 784 Int32 useStreams = 0;
@@ -683,8 +796,8 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI
683 { 796 {
684 totalSize += Streams[indices[i]].Size; 797 totalSize += Streams[indices[i]].Size;
685 } 798 }
686 RINOK(callback->SetTotal(totalSize)); 799 RINOK(callback->SetTotal(totalSize))
687 RINOK(callback->SetNumFiles(numItems)); 800 RINOK(callback->SetNumFiles(numItems))
688 } 801 }
689 802
690 /* 803 /*
@@ -716,8 +829,8 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI
716 if (destPath.IsEmpty() /* && !ExtractToStreamCallback */) 829 if (destPath.IsEmpty() /* && !ExtractToStreamCallback */)
717 return E_INVALIDARG; 830 return E_INVALIDARG;
718 831
719 bool isAltDest = NName::IsAltPathPrefix(destPath); 832 const bool isAltDest = NName::IsAltPathPrefix(destPath);
720 bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); 833 const bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back()));
721 834
722 if (isDirectPath) 835 if (isDirectPath)
723 { 836 {
@@ -727,7 +840,7 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI
727 840
728 CFileInfo fi; 841 CFileInfo fi;
729 if (!fi.Find(_pathBaseFile)) 842 if (!fi.Find(_pathBaseFile))
730 return GetLastError(); 843 return GetLastError_noZero_HRESULT();
731 844
732 NFsFolder::CCopyStateIO state; 845 NFsFolder::CCopyStateIO state;
733 state.Progress = callback; 846 state.Progress = callback;
@@ -736,21 +849,21 @@ STDMETHODIMP CAltStreamsFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UI
736 849
737 for (UInt32 i = 0; i < numItems; i++) 850 for (UInt32 i = 0; i < numItems; i++)
738 { 851 {
739 UInt32 index = indices[i]; 852 const UInt32 index = indices[i];
740 const CAltStream &ss = Streams[index]; 853 const CAltStream &ss = Streams[index];
741 FString destPath2 = destPath; 854 FString destPath2 = destPath;
742 if (!isDirectPath) 855 if (!isDirectPath)
743 destPath2 += us2fs(Get_Correct_FsFile_Name(ss.Name)); 856 destPath2 += us2fs(Get_Correct_FsFile_Name(ss.Name));
744 FString srcPath; 857 FString srcPath;
745 GetFullPath(ss, srcPath); 858 GetFullPath(ss, srcPath);
746 RINOK(CopyStream(state, srcPath, fi, ss, destPath2, callback)); 859 RINOK(CopyStream(state, srcPath, fi, ss, destPath2, callback))
747 } 860 }
748 861
749 return S_OK; 862 return S_OK;
750} 863}
751 864
752STDMETHODIMP CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, 865Z7_COM7F_IMF(CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */,
753 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) 866 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */))
754{ 867{
755 /* 868 /*
756 if (numItems == 0) 869 if (numItems == 0)
@@ -831,7 +944,7 @@ STDMETHODIMP CAltStreamsFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /
831 return E_NOTIMPL; 944 return E_NOTIMPL;
832} 945}
833 946
834STDMETHODIMP CAltStreamsFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) 947Z7_COM7F_IMF(CAltStreamsFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */))
835{ 948{
836 return E_NOTIMPL; 949 return E_NOTIMPL;
837} 950}
diff --git a/CPP/7zip/UI/FileManager/AltStreamsFolder.h b/CPP/7zip/UI/FileManager/AltStreamsFolder.h
index ccd0a58..ccb6d6f 100644
--- a/CPP/7zip/UI/FileManager/AltStreamsFolder.h
+++ b/CPP/7zip/UI/FileManager/AltStreamsFolder.h
@@ -1,7 +1,7 @@
1// AltStreamsFolder.h 1// AltStreamsFolder.h
2 2
3#ifndef __ALT_STREAMS_FOLDER_H 3#ifndef ZIP7_INC_ALT_STREAMS_FOLDER_H
4#define __ALT_STREAMS_FOLDER_H 4#define ZIP7_INC_ALT_STREAMS_FOLDER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -24,12 +24,12 @@ struct CAltStream
24}; 24};
25 25
26 26
27class CAltStreamsFolder: 27class CAltStreamsFolder Z7_final:
28 public IFolderFolder, 28 public IFolderFolder,
29 public IFolderCompare, 29 public IFolderCompare,
30 #ifdef USE_UNICODE_FSTRING 30 #ifdef USE_UNICODE_FSTRING
31 public IFolderGetItemName, 31 public IFolderGetItemName,
32 #endif 32 #endif
33 public IFolderWasChanged, 33 public IFolderWasChanged,
34 public IFolderOperations, 34 public IFolderOperations,
35 // public IFolderOperationsDeleteToRecycleBin, 35 // public IFolderOperationsDeleteToRecycleBin,
@@ -37,35 +37,29 @@ class CAltStreamsFolder:
37 public IFolderGetSystemIconIndex, 37 public IFolderGetSystemIconIndex,
38 public CMyUnknownImp 38 public CMyUnknownImp
39{ 39{
40public: 40 Z7_COM_QI_BEGIN2(IFolderFolder)
41 MY_QUERYINTERFACE_BEGIN2(IFolderFolder) 41 Z7_COM_QI_ENTRY(IFolderCompare)
42 MY_QUERYINTERFACE_ENTRY(IFolderCompare)
43 #ifdef USE_UNICODE_FSTRING 42 #ifdef USE_UNICODE_FSTRING
44 MY_QUERYINTERFACE_ENTRY(IFolderGetItemName) 43 Z7_COM_QI_ENTRY(IFolderGetItemName)
45 #endif 44 #endif
46 MY_QUERYINTERFACE_ENTRY(IFolderWasChanged) 45 Z7_COM_QI_ENTRY(IFolderWasChanged)
47 // MY_QUERYINTERFACE_ENTRY(IFolderOperationsDeleteToRecycleBin) 46 // Z7_COM_QI_ENTRY(IFolderOperationsDeleteToRecycleBin)
48 MY_QUERYINTERFACE_ENTRY(IFolderOperations) 47 Z7_COM_QI_ENTRY(IFolderOperations)
49 MY_QUERYINTERFACE_ENTRY(IFolderClone) 48 Z7_COM_QI_ENTRY(IFolderClone)
50 MY_QUERYINTERFACE_ENTRY(IFolderGetSystemIconIndex) 49 Z7_COM_QI_ENTRY(IFolderGetSystemIconIndex)
51 MY_QUERYINTERFACE_END 50 Z7_COM_QI_END
52 MY_ADDREF_RELEASE 51 Z7_COM_ADDREF_RELEASE
53 52
54 53 Z7_IFACE_COM7_IMP(IFolderFolder)
55 INTERFACE_FolderFolder(;) 54 Z7_IFACE_COM7_IMP(IFolderCompare)
56 INTERFACE_FolderOperations(;) 55 #ifdef USE_UNICODE_FSTRING
57 56 Z7_IFACE_COM7_IMP(IFolderGetItemName)
58 STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw); 57 #endif
58 Z7_IFACE_COM7_IMP(IFolderWasChanged)
59 Z7_IFACE_COM7_IMP(IFolderOperations)
60 Z7_IFACE_COM7_IMP(IFolderClone)
61 Z7_IFACE_COM7_IMP(IFolderGetSystemIconIndex)
59 62
60 #ifdef USE_UNICODE_FSTRING
61 INTERFACE_IFolderGetItemName(;)
62 #endif
63 STDMETHOD(WasChanged)(Int32 *wasChanged);
64 STDMETHOD(Clone)(IFolderFolder **resultFolder);
65
66 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex);
67
68private:
69 FString _pathBaseFile; // folder 63 FString _pathBaseFile; // folder
70 FString _pathPrefix; // folder: 64 FString _pathPrefix; // folder:
71 65
@@ -81,8 +75,6 @@ public:
81 // path must be with ':' at tail 75 // path must be with ':' at tail
82 HRESULT Init(const FString &path /* , IFolderFolder *parentFolder */); 76 HRESULT Init(const FString &path /* , IFolderFolder *parentFolder */);
83 77
84 CAltStreamsFolder() {}
85
86 void GetFullPath(const CAltStream &item, FString &path) const 78 void GetFullPath(const CAltStream &item, FString &path) const
87 { 79 {
88 path = _pathPrefix; 80 path = _pathPrefix;
diff --git a/CPP/7zip/UI/FileManager/App.cpp b/CPP/7zip/UI/FileManager/App.cpp
index 512acc5..3461c92 100644
--- a/CPP/7zip/UI/FileManager/App.cpp
+++ b/CPP/7zip/UI/FileManager/App.cpp
@@ -49,7 +49,7 @@ void CPanelCallbackImp::OnTab()
49 49
50void CPanelCallbackImp::SetFocusToPath(unsigned index) 50void CPanelCallbackImp::SetFocusToPath(unsigned index)
51{ 51{
52 int newPanelIndex = index; 52 unsigned newPanelIndex = index;
53 if (g_App.NumPanels == 1) 53 if (g_App.NumPanels == 1)
54 newPanelIndex = g_App.LastFocusedPanel; 54 newPanelIndex = g_App.LastFocusedPanel;
55 _app->RefreshTitle(); 55 _app->RefreshTitle();
@@ -66,7 +66,7 @@ void CPanelCallbackImp::DragBegin() { _app->DragBegin(_index); }
66void CPanelCallbackImp::DragEnd() { _app->DragEnd(); } 66void CPanelCallbackImp::DragEnd() { _app->DragEnd(); }
67void CPanelCallbackImp::RefreshTitle(bool always) { _app->RefreshTitlePanel(_index, always); } 67void CPanelCallbackImp::RefreshTitle(bool always) { _app->RefreshTitlePanel(_index, always); }
68 68
69void CApp::ReloadLang() 69void CApp::ReloadLangItems()
70{ 70{
71 LangString(IDS_N_SELECTED_ITEMS, LangString_N_SELECTED_ITEMS); 71 LangString(IDS_N_SELECTED_ITEMS, LangString_N_SELECTED_ITEMS);
72} 72}
@@ -101,11 +101,11 @@ void CApp::SetListSettings()
101 panel._showRealFileIcons = st.ShowRealFileIcons; 101 panel._showRealFileIcons = st.ShowRealFileIcons;
102 panel._exStyle = extendedStyle; 102 panel._exStyle = extendedStyle;
103 103
104 DWORD style = (DWORD)panel._listView.GetStyle(); 104 LONG_PTR style = panel._listView.GetStyle();
105 if (st.AlternativeSelection) 105 if (st.AlternativeSelection)
106 style |= LVS_SINGLESEL; 106 style |= LVS_SINGLESEL;
107 else 107 else
108 style &= ~LVS_SINGLESEL; 108 style &= ~(LONG_PTR)(DWORD)LVS_SINGLESEL;
109 panel._listView.SetStyle(style); 109 panel._listView.SetStyle(style);
110 panel.SetExtendedStyle(); 110 panel.SetExtendedStyle();
111 } 111 }
@@ -115,7 +115,7 @@ void CApp::SetListSettings()
115#define ILC_COLOR32 0x0020 115#define ILC_COLOR32 0x0020
116#endif 116#endif
117 117
118HRESULT CApp::CreateOnePanel(int panelIndex, const UString &mainPath, const UString &arcFormat, 118HRESULT CApp::CreateOnePanel(unsigned panelIndex, const UString &mainPath, const UString &arcFormat,
119 bool needOpenArc, 119 bool needOpenArc,
120 COpenResult &openRes) 120 COpenResult &openRes)
121{ 121{
@@ -133,7 +133,7 @@ HRESULT CApp::CreateOnePanel(int panelIndex, const UString &mainPath, const UStr
133 else 133 else
134 path = mainPath; 134 path = mainPath;
135 135
136 int id = 1000 + 100 * panelIndex; 136 const unsigned id = 1000 + 100 * panelIndex; // check it
137 137
138 return Panels[panelIndex].Create(_window, _window, 138 return Panels[panelIndex].Create(_window, _window,
139 id, path, arcFormat, &m_PanelCallbackImp[panelIndex], &AppState, 139 id, path, arcFormat, &m_PanelCallbackImp[panelIndex], &AppState,
@@ -214,9 +214,9 @@ static bool SetButtonText(int commandID, const CButtonInfo *buttons, unsigned nu
214 214
215static void SetButtonText(int commandID, UString &s) 215static void SetButtonText(int commandID, UString &s)
216{ 216{
217 if (SetButtonText(commandID, g_StandardButtons, ARRAY_SIZE(g_StandardButtons), s)) 217 if (SetButtonText(commandID, g_StandardButtons, Z7_ARRAY_SIZE(g_StandardButtons), s))
218 return; 218 return;
219 SetButtonText(commandID, g_ArchiveButtons, ARRAY_SIZE(g_ArchiveButtons), s); 219 SetButtonText(commandID, g_ArchiveButtons, Z7_ARRAY_SIZE(g_ArchiveButtons), s);
220} 220}
221 221
222static void AddButton( 222static void AddButton(
@@ -241,7 +241,7 @@ static void AddButton(
241 large ? 241 large ?
242 MAKEINTRESOURCE(butInfo.BitmapResID): 242 MAKEINTRESOURCE(butInfo.BitmapResID):
243 MAKEINTRESOURCE(butInfo.Bitmap2ResID)); 243 MAKEINTRESOURCE(butInfo.Bitmap2ResID));
244 if (b != 0) 244 if (b)
245 { 245 {
246 imageList.AddMasked(b, RGB(255, 0, 255)); 246 imageList.AddMasked(b, RGB(255, 0, 255));
247 ::DeleteObject(b); 247 ::DeleteObject(b);
@@ -264,10 +264,10 @@ void CApp::ReloadToolbars()
264 CreateToolbar(_window, _buttonsImageList, _toolBar, LargeButtons); 264 CreateToolbar(_window, _buttonsImageList, _toolBar, LargeButtons);
265 unsigned i; 265 unsigned i;
266 if (ShowArchiveToolbar) 266 if (ShowArchiveToolbar)
267 for (i = 0; i < ARRAY_SIZE(g_ArchiveButtons); i++) 267 for (i = 0; i < Z7_ARRAY_SIZE(g_ArchiveButtons); i++)
268 AddButton(_buttonsImageList, _toolBar, g_ArchiveButtons[i], ShowButtonsLables, LargeButtons); 268 AddButton(_buttonsImageList, _toolBar, g_ArchiveButtons[i], ShowButtonsLables, LargeButtons);
269 if (ShowStandardToolbar) 269 if (ShowStandardToolbar)
270 for (i = 0; i < ARRAY_SIZE(g_StandardButtons); i++) 270 for (i = 0; i < Z7_ARRAY_SIZE(g_StandardButtons); i++)
271 AddButton(_buttonsImageList, _toolBar, g_StandardButtons[i], ShowButtonsLables, LargeButtons); 271 AddButton(_buttonsImageList, _toolBar, g_StandardButtons[i], ShowButtonsLables, LargeButtons);
272 272
273 _toolBar.AutoSize(); 273 _toolBar.AutoSize();
@@ -290,7 +290,7 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma
290 _commandBar.Create(g_hInstance, hwnd, 1); 290 _commandBar.Create(g_hInstance, hwnd, 1);
291 #endif 291 #endif
292 292
293 MyLoadMenu(); 293 MyLoadMenu(false); // needResetMenu
294 294
295 #ifdef UNDER_CE 295 #ifdef UNDER_CE
296 _commandBar.AutoSize(); 296 _commandBar.AutoSize();
@@ -317,7 +317,7 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma
317 for (i = 0; i < kNumPanelsMax; i++) 317 for (i = 0; i < kNumPanelsMax; i++)
318 { 318 {
319 CPanel &panel = Panels[i]; 319 CPanel &panel = Panels[i];
320 panel._ListViewMode = listMode.Panels[i]; 320 panel._listViewMode = listMode.Panels[i];
321 panel._xSize = xSizes[i]; 321 panel._xSize = xSizes[i];
322 panel._flatModeForArc = ReadFlatView(i); 322 panel._flatModeForArc = ReadFlatView(i);
323 } 323 }
@@ -342,7 +342,7 @@ HRESULT CApp::Create(HWND hwnd, const UString &mainPath, const UString &arcForma
342 342
343 RINOK(CreateOnePanel(panelIndex, path, arcFormat, 343 RINOK(CreateOnePanel(panelIndex, path, arcFormat,
344 isMainPanel && needOpenArc, 344 isMainPanel && needOpenArc,
345 *(isMainPanel ? &openRes : &openRes2))); 345 *(isMainPanel ? &openRes : &openRes2)))
346 346
347 if (isMainPanel) 347 if (isMainPanel)
348 { 348 {
@@ -366,7 +366,7 @@ HRESULT CApp::SwitchOnOffOnePanel()
366 COpenResult openRes; 366 COpenResult openRes;
367 RINOK(CreateOnePanel(1 - LastFocusedPanel, UString(), UString(), 367 RINOK(CreateOnePanel(1 - LastFocusedPanel, UString(), UString(),
368 false, // needOpenArc 368 false, // needOpenArc
369 openRes)); 369 openRes))
370 Panels[1 - LastFocusedPanel].Enable(true); 370 Panels[1 - LastFocusedPanel].Enable(true);
371 Panels[1 - LastFocusedPanel].Show(SW_SHOWNORMAL); 371 Panels[1 - LastFocusedPanel].Show(SW_SHOWNORMAL);
372 } 372 }
@@ -479,7 +479,7 @@ void AddValuePair2(UString &s, UINT resourceID, UInt64 num, UInt64 size)
479 s.Add_LF(); 479 s.Add_LF();
480} 480}
481 481
482static void AddPropValueToSum(IFolderFolder *folder, int index, PROPID propID, UInt64 &sum) 482static void AddPropValueToSum(IFolderFolder *folder, UInt32 index, PROPID propID, UInt64 &sum)
483{ 483{
484 if (sum == (UInt64)(Int64)-1) 484 if (sum == (UInt64)(Int64)-1)
485 return; 485 return;
@@ -501,7 +501,7 @@ UString CPanel::GetItemsInfoString(const CRecordVector<UInt32> &indices)
501 unsigned i; 501 unsigned i;
502 for (i = 0; i < indices.Size(); i++) 502 for (i = 0; i < indices.Size(); i++)
503 { 503 {
504 int index = indices[i]; 504 const UInt32 index = indices[i];
505 if (IsItem_Folder(index)) 505 if (IsItem_Folder(index))
506 { 506 {
507 AddPropValueToSum(_folder, index, kpidSize, foldersSize); 507 AddPropValueToSum(_folder, index, kpidSize, foldersSize);
@@ -528,7 +528,7 @@ UString CPanel::GetItemsInfoString(const CRecordVector<UInt32> &indices)
528 { 528 {
529 info.Add_LF(); 529 info.Add_LF();
530 info += " "; 530 info += " ";
531 int index = indices[i]; 531 const UInt32 index = indices[i];
532 info += GetItemRelPath(index); 532 info += GetItemRelPath(index);
533 if (IsItem_Folder(index)) 533 if (IsItem_Folder(index))
534 info.Add_PathSepar(); 534 info.Add_PathSepar();
@@ -557,9 +557,9 @@ static bool IsFsPath(const FString &path)
557} 557}
558*/ 558*/
559 559
560void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex) 560void CApp::OnCopy(bool move, bool copyToSame, unsigned srcPanelIndex)
561{ 561{
562 unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); 562 const unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex);
563 CPanel &srcPanel = Panels[srcPanelIndex]; 563 CPanel &srcPanel = Panels[srcPanelIndex];
564 CPanel &destPanel = Panels[destPanelIndex]; 564 CPanel &destPanel = Panels[destPanelIndex];
565 565
@@ -584,10 +584,10 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
584 { 584 {
585 if (copyToSame) 585 if (copyToSame)
586 { 586 {
587 int focusedItem = srcPanel._listView.GetFocusedItem(); 587 const int focusedItem = srcPanel._listView.GetFocusedItem();
588 if (focusedItem < 0) 588 if (focusedItem < 0)
589 return; 589 return;
590 int realIndex = srcPanel.GetRealItemIndex(focusedItem); 590 const unsigned realIndex = srcPanel.GetRealItemIndex(focusedItem);
591 if (realIndex == kParentIndex) 591 if (realIndex == kParentIndex)
592 return; 592 return;
593 indices.Add(realIndex); 593 indices.Add(realIndex);
@@ -595,7 +595,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
595 } 595 }
596 else 596 else
597 { 597 {
598 srcPanel.GetOperatedIndicesSmart(indices); 598 srcPanel.Get_ItemIndices_OperSmart(indices);
599 if (indices.Size() == 0) 599 if (indices.Size() == 0)
600 return; 600 return;
601 destPath = destPanel.GetFsPath(); 601 destPath = destPanel.GetFsPath();
@@ -607,7 +607,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
607 UStringVector copyFolders; 607 UStringVector copyFolders;
608 ReadCopyHistory(copyFolders); 608 ReadCopyHistory(copyFolders);
609 609
610 bool useFullItemPaths = srcPanel.Is_IO_FS_Folder(); // maybe we need flat also here ?? 610 const bool useFullItemPaths = srcPanel.Is_IO_FS_Folder(); // maybe we need flat also here ??
611 611
612 { 612 {
613 CCopyDialog copyDialog; 613 CCopyDialog copyDialog;
@@ -722,7 +722,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
722 UString prefix = destPath.Left(pos + 1); 722 UString prefix = destPath.Left(pos + 1);
723 if (!CreateComplexDir(us2fs(prefix))) 723 if (!CreateComplexDir(us2fs(prefix)))
724 { 724 {
725 DWORD lastError = ::GetLastError(); 725 const HRESULT lastError = GetLastError_noZero_HRESULT();
726 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(prefix, lastError); 726 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(prefix, lastError);
727 return; 727 return;
728 } 728 }
@@ -734,7 +734,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
734 NName::NormalizeDirPathPrefix(destPath); 734 NName::NormalizeDirPathPrefix(destPath);
735 if (!CreateComplexDir(us2fs(destPath))) 735 if (!CreateComplexDir(us2fs(destPath)))
736 { 736 {
737 DWORD lastError = ::GetLastError(); 737 const HRESULT lastError = GetLastError_noZero_HRESULT();
738 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(destPath, lastError); 738 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(destPath, lastError);
739 return; 739 return;
740 } 740 }
@@ -815,7 +815,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
815 filePaths.AddInReserved(s); 815 filePaths.AddInReserved(s);
816 } 816 }
817 817
818 result = destPanel.CopyFrom(move, folderPrefix, filePaths, true, 0); 818 result = destPanel.CopyFrom(move, folderPrefix, filePaths, true, NULL);
819 } 819 }
820 820
821 if (result != S_OK) 821 if (result != S_OK)
@@ -849,7 +849,7 @@ void CApp::OnCopy(bool move, bool copyToSame, int srcPanelIndex)
849 srcPanel.SetFocusToList(); 849 srcPanel.SetFocusToList();
850} 850}
851 851
852void CApp::OnSetSameFolder(int srcPanelIndex) 852void CApp::OnSetSameFolder(unsigned srcPanelIndex)
853{ 853{
854 if (NumPanels <= 1) 854 if (NumPanels <= 1)
855 return; 855 return;
@@ -858,17 +858,17 @@ void CApp::OnSetSameFolder(int srcPanelIndex)
858 destPanel.BindToPathAndRefresh(srcPanel._currentFolderPrefix); 858 destPanel.BindToPathAndRefresh(srcPanel._currentFolderPrefix);
859} 859}
860 860
861void CApp::OnSetSubFolder(int srcPanelIndex) 861void CApp::OnSetSubFolder(unsigned srcPanelIndex)
862{ 862{
863 if (NumPanels <= 1) 863 if (NumPanels <= 1)
864 return; 864 return;
865 const CPanel &srcPanel = Panels[srcPanelIndex]; 865 const CPanel &srcPanel = Panels[srcPanelIndex];
866 CPanel &destPanel = Panels[1 - srcPanelIndex]; 866 CPanel &destPanel = Panels[1 - srcPanelIndex];
867 867
868 int focusedItem = srcPanel._listView.GetFocusedItem(); 868 const int focusedItem = srcPanel._listView.GetFocusedItem();
869 if (focusedItem < 0) 869 if (focusedItem < 0)
870 return; 870 return;
871 int realIndex = srcPanel.GetRealItemIndex(focusedItem); 871 const unsigned realIndex = srcPanel.GetRealItemIndex(focusedItem);
872 if (!srcPanel.IsItem_Folder(realIndex)) 872 if (!srcPanel.IsItem_Folder(realIndex))
873 return; 873 return;
874 874
@@ -933,7 +933,7 @@ void CApp::OnNotify(int /* ctrlID */, LPNMHDR pnmh)
933 if (pnmh->code == TTN_GETDISPINFO) 933 if (pnmh->code == TTN_GETDISPINFO)
934 { 934 {
935 LPNMTTDISPINFO info = (LPNMTTDISPINFO)pnmh; 935 LPNMTTDISPINFO info = (LPNMTTDISPINFO)pnmh;
936 info->hinst = 0; 936 info->hinst = NULL;
937 g_ToolTipBuffer.Empty(); 937 g_ToolTipBuffer.Empty();
938 SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer); 938 SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer);
939 g_ToolTipBufferSys = GetSystemString(g_ToolTipBuffer); 939 g_ToolTipBufferSys = GetSystemString(g_ToolTipBuffer);
@@ -944,7 +944,7 @@ void CApp::OnNotify(int /* ctrlID */, LPNMHDR pnmh)
944 if (pnmh->code == TTN_GETDISPINFOW) 944 if (pnmh->code == TTN_GETDISPINFOW)
945 { 945 {
946 LPNMTTDISPINFOW info = (LPNMTTDISPINFOW)pnmh; 946 LPNMTTDISPINFOW info = (LPNMTTDISPINFOW)pnmh;
947 info->hinst = 0; 947 info->hinst = NULL;
948 g_ToolTipBuffer.Empty(); 948 g_ToolTipBuffer.Empty();
949 SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer); 949 SetButtonText((int)info->hdr.idFrom, g_ToolTipBuffer);
950 info->lpszText = g_ToolTipBuffer.Ptr_non_const(); 950 info->lpszText = g_ToolTipBuffer.Ptr_non_const();
diff --git a/CPP/7zip/UI/FileManager/App.h b/CPP/7zip/UI/FileManager/App.h
index 3c3c5ef..fc54501 100644
--- a/CPP/7zip/UI/FileManager/App.h
+++ b/CPP/7zip/UI/FileManager/App.h
@@ -1,7 +1,7 @@
1// App.h 1// App.h
2 2
3#ifndef __APP_H 3#ifndef ZIP7_INC_APP_H
4#define __APP_H 4#define ZIP7_INC_APP_H
5 5
6#include "../../../Windows/Control/CommandBar.h" 6#include "../../../Windows/Control/CommandBar.h"
7#include "../../../Windows/Control/ImageList.h" 7#include "../../../Windows/Control/ImageList.h"
@@ -30,7 +30,7 @@ enum
30 kMenuCmdID_Toolbar_End 30 kMenuCmdID_Toolbar_End
31}; 31};
32 32
33class CPanelCallbackImp: public CPanelCallback 33class CPanelCallbackImp Z7_final: public CPanelCallback
34{ 34{
35 CApp *_app; 35 CApp *_app;
36 unsigned _index; 36 unsigned _index;
@@ -40,79 +40,26 @@ public:
40 _app = app; 40 _app = app;
41 _index = index; 41 _index = index;
42 } 42 }
43 virtual void OnTab(); 43 virtual void OnTab() Z7_override;
44 virtual void SetFocusToPath(unsigned index); 44 virtual void SetFocusToPath(unsigned index) Z7_override;
45 virtual void OnCopy(bool move, bool copyToSame); 45 virtual void OnCopy(bool move, bool copyToSame) Z7_override;
46 virtual void OnSetSameFolder(); 46 virtual void OnSetSameFolder() Z7_override;
47 virtual void OnSetSubFolder(); 47 virtual void OnSetSubFolder() Z7_override;
48 virtual void PanelWasFocused(); 48 virtual void PanelWasFocused() Z7_override;
49 virtual void DragBegin(); 49 virtual void DragBegin() Z7_override;
50 virtual void DragEnd(); 50 virtual void DragEnd() Z7_override;
51 virtual void RefreshTitle(bool always); 51 virtual void RefreshTitle(bool always) Z7_override;
52}; 52};
53 53
54class CApp;
55
56class CDropTarget:
57 public IDropTarget,
58 public CMyUnknownImp
59{
60 CMyComPtr<IDataObject> m_DataObject;
61 UStringVector m_SourcePaths;
62 int m_SelectionIndex;
63 bool m_DropIsAllowed; // = true, if data contain fillist
64 bool m_PanelDropIsAllowed; // = false, if current target_panel is source_panel.
65 // check it only if m_DropIsAllowed == true
66 int m_SubFolderIndex;
67 UString m_SubFolderName;
68
69 CPanel *m_Panel;
70 bool m_IsAppTarget; // true, if we want to drop to app window (not to panel).
71
72 bool m_SetPathIsOK;
73
74 bool IsItSameDrive() const;
75
76 void QueryGetData(IDataObject *dataObject);
77 bool IsFsFolderPath() const;
78 DWORD GetEffect(DWORD keyState, POINTL pt, DWORD allowedEffect);
79 void RemoveSelection();
80 void PositionCursor(POINTL ptl);
81 UString GetTargetPath() const;
82 bool SetPath(bool enablePath) const;
83 bool SetPath();
84
85public:
86 MY_UNKNOWN_IMP1_MT(IDropTarget)
87 STDMETHOD(DragEnter)(IDataObject * dataObject, DWORD keyState, POINTL pt, DWORD *effect);
88 STDMETHOD(DragOver)(DWORD keyState, POINTL pt, DWORD * effect);
89 STDMETHOD(DragLeave)();
90 STDMETHOD(Drop)(IDataObject * dataObject, DWORD keyState, POINTL pt, DWORD *effect);
91
92 CDropTarget():
93 m_SelectionIndex(-1),
94 m_DropIsAllowed(false),
95 m_PanelDropIsAllowed(false),
96 m_SubFolderIndex(-1),
97 m_Panel(NULL),
98 m_IsAppTarget(false),
99 m_SetPathIsOK(false),
100 App(NULL),
101 SrcPanelIndex(-1),
102 TargetPanelIndex(-1)
103 {}
104
105 CApp *App;
106 int SrcPanelIndex; // index of D&D source_panel
107 int TargetPanelIndex; // what panel to use as target_panel of Application
108};
109 54
55class CDropTarget;
110 56
111class CApp 57class CApp
112{ 58{
113public: 59public:
114 NWindows::CWindow _window; 60 NWindows::CWindow _window;
115 bool ShowSystemMenu; 61 bool ShowSystemMenu;
62 bool AutoRefresh_Mode;
116 // bool ShowDeletedFiles; 63 // bool ShowDeletedFiles;
117 unsigned NumPanels; 64 unsigned NumPanels;
118 unsigned LastFocusedPanel; 65 unsigned LastFocusedPanel;
@@ -138,45 +85,27 @@ public:
138 85
139 UString LangString_N_SELECTED_ITEMS; 86 UString LangString_N_SELECTED_ITEMS;
140 87
141 void ReloadLang(); 88 void ReloadLangItems();
142 89
143 CApp(): _window(0), NumPanels(2), LastFocusedPanel(0), 90 CApp():
144 AutoRefresh_Mode(true) 91 _window(NULL),
92 AutoRefresh_Mode(true),
93 NumPanels(2),
94 LastFocusedPanel(0)
145 { 95 {
146 SetPanels_AutoRefresh_Mode(); 96 SetPanels_AutoRefresh_Mode();
147 } 97 }
148 98
149 void CreateDragTarget() 99 void CreateDragTarget();
150 { 100 void SetFocusedPanel(unsigned index);
151 _dropTargetSpec = new CDropTarget(); 101 void DragBegin(unsigned panelIndex);
152 _dropTarget = _dropTargetSpec; 102 void DragEnd();
153 _dropTargetSpec->App = (this);
154 }
155
156 void SetFocusedPanel(unsigned index)
157 {
158 LastFocusedPanel = index;
159 _dropTargetSpec->TargetPanelIndex = LastFocusedPanel;
160 }
161
162 void DragBegin(unsigned panelIndex)
163 {
164 _dropTargetSpec->TargetPanelIndex = (NumPanels > 1) ? 1 - panelIndex : panelIndex;
165 _dropTargetSpec->SrcPanelIndex = panelIndex;
166 }
167
168 void DragEnd()
169 {
170 _dropTargetSpec->TargetPanelIndex = LastFocusedPanel;
171 _dropTargetSpec->SrcPanelIndex = -1;
172 }
173
174 103
175 void OnCopy(bool move, bool copyToSame, int srcPanelIndex); 104 void OnCopy(bool move, bool copyToSame, unsigned srcPanelIndex);
176 void OnSetSameFolder(int srcPanelIndex); 105 void OnSetSameFolder(unsigned srcPanelIndex);
177 void OnSetSubFolder(int srcPanelIndex); 106 void OnSetSubFolder(unsigned srcPanelIndex);
178 107
179 HRESULT CreateOnePanel(int panelIndex, const UString &mainPath, const UString &arcFormat, bool needOpenArc, COpenResult &openRes); 108 HRESULT CreateOnePanel(unsigned panelIndex, const UString &mainPath, const UString &arcFormat, bool needOpenArc, COpenResult &openRes);
180 HRESULT Create(HWND hwnd, const UString &mainPath, const UString &arcFormat, int xSizes[2], bool needOpenArc, COpenResult &openRes); 109 HRESULT Create(HWND hwnd, const UString &mainPath, const UString &arcFormat, int xSizes[2], bool needOpenArc, COpenResult &openRes);
181 void Read(); 110 void Read();
182 void Save(); 111 void Save();
@@ -290,7 +219,6 @@ public:
290 // void Change_ShowNtfsStrems_Mode() { Panels[LastFocusedPanel].Change_ShowNtfsStrems_Mode(); } 219 // void Change_ShowNtfsStrems_Mode() { Panels[LastFocusedPanel].Change_ShowNtfsStrems_Mode(); }
291 // void Change_ShowDeleted() { ShowDeletedFiles = !ShowDeletedFiles; } 220 // void Change_ShowDeleted() { ShowDeletedFiles = !ShowDeletedFiles; }
292 221
293 bool AutoRefresh_Mode;
294 bool Get_AutoRefresh_Mode() 222 bool Get_AutoRefresh_Mode()
295 { 223 {
296 // return Panels[LastFocusedPanel].Get_ShowNtfsStrems_Mode(); 224 // return Panels[LastFocusedPanel].Get_ShowNtfsStrems_Mode();
@@ -307,13 +235,13 @@ public:
307 Panels[i].Set_AutoRefresh_Mode(AutoRefresh_Mode); 235 Panels[i].Set_AutoRefresh_Mode(AutoRefresh_Mode);
308 } 236 }
309 237
310 void OpenBookmark(int index) { GetFocusedPanel().OpenBookmark(index); } 238 void OpenBookmark(unsigned index) { GetFocusedPanel().OpenBookmark(index); }
311 void SetBookmark(int index) { GetFocusedPanel().SetBookmark(index); } 239 void SetBookmark(unsigned index) { GetFocusedPanel().SetBookmark(index); }
312 240
313 void ReloadToolbars(); 241 void ReloadToolbars();
314 void ReadToolbar() 242 void ReadToolbar()
315 { 243 {
316 UInt32 mask = ReadToolbarsMask(); 244 const UInt32 mask = ReadToolbarsMask();
317 if (mask & ((UInt32)1 << 31)) 245 if (mask & ((UInt32)1 << 31))
318 { 246 {
319 ShowButtonsLables = !g_IsSmallScreen; 247 ShowButtonsLables = !g_IsSmallScreen;
diff --git a/CPP/7zip/UI/FileManager/AppState.h b/CPP/7zip/UI/FileManager/AppState.h
index cc88715..6630b96 100644
--- a/CPP/7zip/UI/FileManager/AppState.h
+++ b/CPP/7zip/UI/FileManager/AppState.h
@@ -1,7 +1,7 @@
1// AppState.h 1// AppState.h
2 2
3#ifndef __APP_STATE_H 3#ifndef ZIP7_INC_APP_STATE_H
4#define __APP_STATE_H 4#define ZIP7_INC_APP_STATE_H
5 5
6#include "../../../Windows/Synchronization.h" 6#include "../../../Windows/Synchronization.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/BrowseDialog.cpp b/CPP/7zip/UI/FileManager/BrowseDialog.cpp
index 6d2b6b5..5170302 100644
--- a/CPP/7zip/UI/FileManager/BrowseDialog.cpp
+++ b/CPP/7zip/UI/FileManager/BrowseDialog.cpp
@@ -4,7 +4,7 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#include <CommCtrl.h> 7#include "../../../Common/IntToString.h"
8 8
9#ifndef UNDER_CE 9#ifndef UNDER_CE
10#include "../../../Windows/CommonDialog.h" 10#include "../../../Windows/CommonDialog.h"
@@ -25,7 +25,6 @@
25#ifdef USE_MY_BROWSE_DIALOG 25#ifdef USE_MY_BROWSE_DIALOG
26 26
27#include "../../../Common/Defs.h" 27#include "../../../Common/Defs.h"
28#include "../../../Common/IntToString.h"
29#include "../../../Common/Wildcard.h" 28#include "../../../Common/Wildcard.h"
30 29
31#include "../../../Windows/FileDir.h" 30#include "../../../Windows/FileDir.h"
@@ -40,11 +39,11 @@
40#include "PropertyNameRes.h" 39#include "PropertyNameRes.h"
41#include "SysIconUtils.h" 40#include "SysIconUtils.h"
42 41
43#ifndef _SFX 42#ifndef Z7_SFX
44#include "RegistryUtils.h" 43#include "RegistryUtils.h"
45#endif 44#endif
46 45
47#endif 46#endif // USE_MY_BROWSE_DIALOG
48 47
49#include "ComboDialog.h" 48#include "ComboDialog.h"
50#include "LangUtils.h" 49#include "LangUtils.h"
@@ -56,6 +55,11 @@ using namespace NFile;
56using namespace NName; 55using namespace NName;
57using namespace NFind; 56using namespace NFind;
58 57
58static void MessageBox_Error_Global(HWND wnd, const wchar_t *message)
59{
60 ::MessageBoxW(wnd, message, L"7-Zip", MB_ICONERROR);
61}
62
59#ifdef USE_MY_BROWSE_DIALOG 63#ifdef USE_MY_BROWSE_DIALOG
60 64
61extern bool g_LVN_ITEMACTIVATE_Support; 65extern bool g_LVN_ITEMACTIVATE_Support;
@@ -63,19 +67,8 @@ extern bool g_LVN_ITEMACTIVATE_Support;
63static const int kParentIndex = -1; 67static const int kParentIndex = -1;
64static const UINT k_Message_RefreshPathEdit = WM_APP + 1; 68static const UINT k_Message_RefreshPathEdit = WM_APP + 1;
65 69
66static HRESULT GetNormalizedError()
67{
68 DWORD errorCode = GetLastError();
69 return errorCode == 0 ? E_FAIL : errorCode;
70}
71
72extern UString HResultToMessage(HRESULT errorCode); 70extern UString HResultToMessage(HRESULT errorCode);
73 71
74static void MessageBox_Error_Global(HWND wnd, const wchar_t *message)
75{
76 ::MessageBoxW(wnd, message, L"7-Zip", MB_ICONERROR);
77}
78
79static void MessageBox_HResError(HWND wnd, HRESULT errorCode, const wchar_t *name) 72static void MessageBox_HResError(HWND wnd, HRESULT errorCode, const wchar_t *name)
80{ 73{
81 UString s = HResultToMessage(errorCode); 74 UString s = HResultToMessage(errorCode);
@@ -98,17 +91,21 @@ class CBrowseDialog: public NControl::CModalDialog
98 CExtToIconMap _extToIconMap; 91 CExtToIconMap _extToIconMap;
99 int _sortIndex; 92 int _sortIndex;
100 bool _ascending; 93 bool _ascending;
94 #ifndef Z7_SFX
101 bool _showDots; 95 bool _showDots;
96 #endif
102 UString _topDirPrefix; // we don't open parent of that folder 97 UString _topDirPrefix; // we don't open parent of that folder
103 UString DirPrefix; 98 UString DirPrefix;
104 99
105 virtual bool OnInit(); 100 virtual bool OnInit() Z7_override;
106 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 101 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
107 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 102 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
108 virtual bool OnNotify(UINT controlID, LPNMHDR header); 103 virtual bool OnNotify(UINT controlID, LPNMHDR header) Z7_override;
109 virtual bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo); 104 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override;
110 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 105 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
111 virtual void OnOK(); 106 virtual void OnOK() Z7_override;
107
108 bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo);
112 109
113 void Post_RefreshPathEdit() { PostMsg(k_Message_RefreshPathEdit); } 110 void Post_RefreshPathEdit() { PostMsg(k_Message_RefreshPathEdit); }
114 111
@@ -126,59 +123,37 @@ class CBrowseDialog: public NControl::CModalDialog
126 int GetRealItemIndex(int indexInListView) const 123 int GetRealItemIndex(int indexInListView) const
127 { 124 {
128 LPARAM param; 125 LPARAM param;
129 if (!_list.GetItemParam(indexInListView, param)) 126 if (!_list.GetItemParam((unsigned)indexInListView, param))
130 return (int)-1; 127 return (int)-1;
131 return (int)param; 128 return (int)param;
132 } 129 }
133 130
134public: 131public:
132
133 bool SaveMode;
135 bool FolderMode; 134 bool FolderMode;
135 int FilterIndex; // [in / out]
136 CObjectVector<CBrowseFilterInfo> Filters;
137
138 UString FilePath; // [in / out]
136 UString Title; 139 UString Title;
137 UString FilePath; // input/ result path 140
138 bool ShowAllFiles; 141 CBrowseDialog():
139 UStringVector Filters; 142 #ifndef Z7_SFX
140 UString FilterDescription; 143 _showDots(false),
141 144 #endif
142 CBrowseDialog(): _showDots(false), FolderMode(false), ShowAllFiles(true) {} 145 SaveMode(false)
143 void SetFilter(const UString &s); 146 , FolderMode(false)
144 INT_PTR Create(HWND parent = 0) { return CModalDialog::Create(IDD_BROWSE, parent); } 147 , FilterIndex(-1)
145 int CompareItems(LPARAM lParam1, LPARAM lParam2); 148 {}
149 INT_PTR Create(HWND parent = NULL) { return CModalDialog::Create(IDD_BROWSE, parent); }
150 int CompareItems(LPARAM lParam1, LPARAM lParam2) const;
146}; 151};
147 152
148void CBrowseDialog::SetFilter(const UString &s)
149{
150 Filters.Clear();
151 UString mask;
152 unsigned i;
153 for (i = 0; i < s.Len(); i++)
154 {
155 wchar_t c = s[i];
156 if (c == ';')
157 {
158 if (!mask.IsEmpty())
159 Filters.Add(mask);
160 mask.Empty();
161 }
162 else
163 mask += c;
164 }
165 if (!mask.IsEmpty())
166 Filters.Add(mask);
167 ShowAllFiles = Filters.IsEmpty();
168 for (i = 0; i < Filters.Size(); i++)
169 {
170 const UString &f = Filters[i];
171 if (f == L"*.*" || f == L"*")
172 {
173 ShowAllFiles = true;
174 break;
175 }
176 }
177}
178 153
179bool CBrowseDialog::OnInit() 154bool CBrowseDialog::OnInit()
180{ 155{
181 #ifdef LANG 156 #ifdef Z7_LANG
182 LangSetDlgItems(*this, NULL, 0); 157 LangSetDlgItems(*this, NULL, 0);
183 #endif 158 #endif
184 if (!Title.IsEmpty()) 159 if (!Title.IsEmpty())
@@ -187,16 +162,11 @@ bool CBrowseDialog::OnInit()
187 _filterCombo.Attach(GetItem(IDC_BROWSE_FILTER)); 162 _filterCombo.Attach(GetItem(IDC_BROWSE_FILTER));
188 _pathEdit.Attach(GetItem(IDE_BROWSE_PATH)); 163 _pathEdit.Attach(GetItem(IDE_BROWSE_PATH));
189 164
190 if (FolderMode)
191 HideItem(IDC_BROWSE_FILTER);
192 else
193 EnableItem(IDC_BROWSE_FILTER, false);
194
195 #ifndef UNDER_CE 165 #ifndef UNDER_CE
196 _list.SetUnicodeFormat(); 166 _list.SetUnicodeFormat();
197 #endif 167 #endif
198 168
199 #ifndef _SFX 169 #ifndef Z7_SFX
200 CFmSettings st; 170 CFmSettings st;
201 st.Load(); 171 st.Load();
202 if (st.SingleClick) 172 if (st.SingleClick)
@@ -205,22 +175,34 @@ bool CBrowseDialog::OnInit()
205 #endif 175 #endif
206 176
207 { 177 {
208 UString s; 178 /*
209 if (!FilterDescription.IsEmpty()) 179 Filters.Clear(); // for debug
210 s = FilterDescription; 180 if (Filters.IsEmpty() && !FolderMode)
211 else if (ShowAllFiles)
212 s = "*.*";
213 else
214 { 181 {
215 FOR_VECTOR (i, Filters) 182 CBrowseFilterInfo &f = Filters.AddNew();
216 { 183 const UString mask("*.*");
217 if (i != 0) 184 f.Masks.Add(mask);
218 s.Add_Space(); 185 // f.Description = "(";
219 s += Filters[i]; 186 f.Description += mask;
220 } 187 // f.Description += ")";
188 }
189 */
190
191 FOR_VECTOR (i, Filters)
192 {
193 _filterCombo.AddString(Filters[i].Description);
194 }
195
196 if (Filters.Size() <= 1)
197 {
198 if (FolderMode)
199 HideItem(IDC_BROWSE_FILTER);
200 else
201 EnableItem(IDC_BROWSE_FILTER, false);
221 } 202 }
222 _filterCombo.AddString(s); 203
223 _filterCombo.SetCurSel(0); 204 if (/* FilterIndex >= 0 && */ (unsigned)FilterIndex < Filters.Size())
205 _filterCombo.SetCurSel(FilterIndex);
224 } 206 }
225 207
226 _list.SetImageList(GetSysImageList(true), LVSIL_SMALL); 208 _list.SetImageList(GetSysImageList(true), LVSIL_SMALL);
@@ -261,7 +243,7 @@ bool CBrowseDialog::OnInit()
261 243
262 _topDirPrefix.Empty(); 244 _topDirPrefix.Empty();
263 { 245 {
264 int rootSize = GetRootPrefixSize(FilePath); 246 unsigned rootSize = GetRootPrefixSize(FilePath);
265 #if defined(_WIN32) && !defined(UNDER_CE) 247 #if defined(_WIN32) && !defined(UNDER_CE)
266 // We can go up from root folder to drives list 248 // We can go up from root folder to drives list
267 if (IsDrivePath(FilePath)) 249 if (IsDrivePath(FilePath))
@@ -301,7 +283,7 @@ bool CBrowseDialog::OnInit()
301 #ifndef UNDER_CE 283 #ifndef UNDER_CE
302 /* If we clear UISF_HIDEFOCUS, the focus rectangle in ListView will be visible, 284 /* If we clear UISF_HIDEFOCUS, the focus rectangle in ListView will be visible,
303 even if we use mouse for pressing the button to open this dialog. */ 285 even if we use mouse for pressing the button to open this dialog. */
304 PostMsg(MY__WM_UPDATEUISTATE, MAKEWPARAM(MY__UIS_CLEAR, MY__UISF_HIDEFOCUS)); 286 PostMsg(Z7_WIN_WM_UPDATEUISTATE, MAKEWPARAM(Z7_WIN_UIS_CLEAR, Z7_WIN_UISF_HIDEFOCUS));
305 #endif 287 #endif
306 288
307 return CModalDialog::OnInit(); 289 return CModalDialog::OnInit();
@@ -368,6 +350,24 @@ bool CBrowseDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
368 return CModalDialog::OnMessage(message, wParam, lParam); 350 return CModalDialog::OnMessage(message, wParam, lParam);
369} 351}
370 352
353
354bool CBrowseDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
355{
356 if (code == CBN_SELCHANGE)
357 {
358 switch (itemID)
359 {
360 case IDC_BROWSE_FILTER:
361 {
362 Reload();
363 return true;
364 }
365 }
366 }
367 return CModalDialog::OnCommand(code, itemID, lParam);
368}
369
370
371bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header) 371bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header)
372{ 372{
373 if (header->hwndFrom != _list) 373 if (header->hwndFrom != _list)
@@ -385,7 +385,7 @@ bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header)
385 break; 385 break;
386 case LVN_COLUMNCLICK: 386 case LVN_COLUMNCLICK:
387 { 387 {
388 int index = LPNMLISTVIEW(header)->iSubItem; 388 const int index = LPNMLISTVIEW(header)->iSubItem;
389 if (index == _sortIndex) 389 if (index == _sortIndex)
390 _ascending = !_ascending; 390 _ascending = !_ascending;
391 else 391 else
@@ -413,7 +413,7 @@ bool CBrowseDialog::OnNotify(UINT /* controlID */, LPNMHDR header)
413 413
414bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo) 414bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo)
415{ 415{
416 bool ctrl = IsKeyDown(VK_CONTROL); 416 const bool ctrl = IsKeyDown(VK_CONTROL);
417 417
418 switch (keyDownInfo->wVKey) 418 switch (keyDownInfo->wVKey)
419 { 419 {
@@ -434,7 +434,8 @@ bool CBrowseDialog::OnKeyDown(LPNMLVKEYDOWN keyDownInfo)
434 return false; 434 return false;
435} 435}
436 436
437bool CBrowseDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 437
438bool CBrowseDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
438{ 439{
439 switch (buttonID) 440 switch (buttonID)
440 { 441 {
@@ -474,21 +475,21 @@ bool CBrowseDialog::GetParentPath(const UString &path, UString &parentPrefix, US
474 return false; 475 return false;
475 if (IS_PATH_SEPAR(s.Back())) 476 if (IS_PATH_SEPAR(s.Back()))
476 return false; 477 return false;
477 int pos = s.ReverseFind_PathSepar(); 478 const unsigned pos1 = (unsigned)(s.ReverseFind_PathSepar() + 1);
478 parentPrefix.SetFrom(s, pos + 1); 479 parentPrefix.SetFrom(s, pos1);
479 name = s.Ptr((unsigned)(pos + 1)); 480 name = s.Ptr(pos1);
480 return true; 481 return true;
481} 482}
482 483
483int CBrowseDialog::CompareItems(LPARAM lParam1, LPARAM lParam2) 484int CBrowseDialog::CompareItems(LPARAM lParam1, LPARAM lParam2) const
484{ 485{
485 if (lParam1 == kParentIndex) return -1; 486 if (lParam1 == kParentIndex) return -1;
486 if (lParam2 == kParentIndex) return 1; 487 if (lParam2 == kParentIndex) return 1;
487 const CFileInfo &f1 = _files[(int)lParam1]; 488 const CFileInfo &f1 = _files[(int)lParam1];
488 const CFileInfo &f2 = _files[(int)lParam2]; 489 const CFileInfo &f2 = _files[(int)lParam2];
489 490
490 bool isDir1 = f1.IsDir(); 491 const bool isDir1 = f1.IsDir();
491 bool isDir2 = f2.IsDir(); 492 const bool isDir2 = f2.IsDir();
492 if (isDir1 && !isDir2) return -1; 493 if (isDir1 && !isDir2) return -1;
493 if (isDir2 && !isDir1) return 1; 494 if (isDir2 && !isDir1) return 1;
494 495
@@ -509,16 +510,16 @@ static int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
509 510
510static void ConvertSizeToString(UInt64 v, wchar_t *s) 511static void ConvertSizeToString(UInt64 v, wchar_t *s)
511{ 512{
512 Byte c = 0; 513 char c = 0;
513 if (v >= ((UInt64)10000 << 20)) { v >>= 30; c = 'G'; } 514 if (v >= ((UInt64)10000 << 20)) { v >>= 30; c = 'G'; }
514 else if (v >= ((UInt64)10000 << 10)) { v >>= 20; c = 'M'; } 515 else if (v >= ((UInt64)10000 << 10)) { v >>= 20; c = 'M'; }
515 else if (v >= ((UInt64)10000 << 0)) { v >>= 10; c = 'K'; } 516 else if (v >= ((UInt64)10000 << 0)) { v >>= 10; c = 'K'; }
516 ConvertUInt64ToString(v, s); 517 s = ConvertUInt64ToString(v, s);
517 if (c != 0) 518 if (c != 0)
518 { 519 {
519 s += MyStringLen(s);
520 *s++ = ' '; 520 *s++ = ' ';
521 *s++ = c; 521 *s++ = (wchar_t)c;
522 *s++ = 'B';
522 *s++ = 0; 523 *s++ = 0;
523 } 524 }
524} 525}
@@ -536,42 +537,57 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected
536 isDrive = true; 537 isDrive = true;
537 FStringVector drives; 538 FStringVector drives;
538 if (!MyGetLogicalDriveStrings(drives)) 539 if (!MyGetLogicalDriveStrings(drives))
539 return GetNormalizedError(); 540 return GetLastError_noZero_HRESULT();
540 FOR_VECTOR (i, drives) 541 FOR_VECTOR (i, drives)
541 { 542 {
542 FString d = drives[i]; 543 const FString &d = drives[i];
543 if (d.Len() < 3 || d.Back() != '\\') 544 if (d.Len() < 2 || d.Back() != '\\')
544 return E_FAIL; 545 return E_FAIL;
545 d.DeleteBack();
546 CFileInfo &fi = files.AddNew(); 546 CFileInfo &fi = files.AddNew();
547 fi.SetAsDir(); 547 fi.SetAsDir();
548 fi.Name = d; 548 fi.Name = d;
549 fi.Name.DeleteBack();
549 } 550 }
550 } 551 }
551 else 552 else
552 #endif 553 #endif
553 { 554 {
555 const UStringVector *masks = NULL;
556 if (!Filters.IsEmpty() && _filterCombo.GetCount() > 0)
557 {
558 const int selected = _filterCombo.GetCurSel();
559 // GetItemData_of_CurSel(); // we don't use data field
560 if (/* selected >= 0 && */ (unsigned)selected < Filters.Size())
561 {
562 const UStringVector &m = Filters[selected].Masks;
563 if (m.Size() > 1 || (m.Size() == 1
564 && !m[0].IsEqualTo("*.*")
565 && !m[0].IsEqualTo("*")))
566 masks = &m;
567 }
568 }
554 CEnumerator enumerator; 569 CEnumerator enumerator;
555 enumerator.SetDirPrefix(us2fs(pathPrefix)); 570 enumerator.SetDirPrefix(us2fs(pathPrefix));
571 CFileInfo fi;
556 for (;;) 572 for (;;)
557 { 573 {
558 bool found; 574 bool found;
559 CFileInfo fi;
560 if (!enumerator.Next(fi, found)) 575 if (!enumerator.Next(fi, found))
561 return GetNormalizedError(); 576 return GetLastError_noZero_HRESULT();
562 if (!found) 577 if (!found)
563 break; 578 break;
564 if (!fi.IsDir()) 579 if (!fi.IsDir())
565 { 580 {
566 if (FolderMode) 581 if (FolderMode)
567 continue; 582 continue;
568 if (!ShowAllFiles) 583 if (masks)
569 { 584 {
570 unsigned i; 585 unsigned i;
571 for (i = 0; i < Filters.Size(); i++) 586 const unsigned numMasks = masks->Size();
572 if (DoesWildcardMatchName(Filters[i], fs2us(fi.Name))) 587 for (i = 0; i < numMasks; i++)
588 if (DoesWildcardMatchName((*masks)[i], fs2us(fi.Name)))
573 break; 589 break;
574 if (i == Filters.Size()) 590 if (i == numMasks)
575 continue; 591 continue;
576 } 592 }
577 } 593 }
@@ -590,19 +606,19 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected
590 606
591 LVITEMW item; 607 LVITEMW item;
592 608
593 int index = 0; 609 unsigned index = 0;
594 int cursorIndex = -1; 610 int cursorIndex = -1;
595 611
596 #ifndef _SFX 612 #ifndef Z7_SFX
597 if (_showDots && _topDirPrefix != DirPrefix) 613 if (_showDots && _topDirPrefix != DirPrefix)
598 { 614 {
599 item.iItem = index; 615 item.iItem = (int)index;
600 const UString itemName (".."); 616 const UString itemName ("..");
601 if (selectedName.IsEmpty()) 617 if (selectedName.IsEmpty())
602 cursorIndex = index; 618 cursorIndex = (int)index;
603 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; 619 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
604 int subItem = 0; 620 unsigned subItem = 0;
605 item.iSubItem = subItem++; 621 item.iSubItem = (int)(subItem++);
606 item.lParam = kParentIndex; 622 item.lParam = kParentIndex;
607 item.pszText = itemName.Ptr_non_const(); 623 item.pszText = itemName.Ptr_non_const();
608 item.iImage = _extToIconMap.GetIconIndex(FILE_ATTRIBUTE_DIRECTORY, DirPrefix); 624 item.iImage = _extToIconMap.GetIconIndex(FILE_ATTRIBUTE_DIRECTORY, DirPrefix);
@@ -617,15 +633,15 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected
617 633
618 for (unsigned i = 0; i < _files.Size(); i++, index++) 634 for (unsigned i = 0; i < _files.Size(); i++, index++)
619 { 635 {
620 item.iItem = index; 636 item.iItem = (int)index;
621 const CFileInfo &fi = _files[i]; 637 const CFileInfo &fi = _files[i];
622 const UString name = fs2us(fi.Name); 638 const UString name = fs2us(fi.Name);
623 if (!selectedName.IsEmpty() && CompareFileNames(name, selectedName) == 0) 639 if (!selectedName.IsEmpty() && CompareFileNames(name, selectedName) == 0)
624 cursorIndex = index; 640 cursorIndex = (int)index;
625 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; 641 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
626 int subItem = 0; 642 unsigned subItem = 0;
627 item.iSubItem = subItem++; 643 item.iSubItem = (int)(subItem++);
628 item.lParam = i; 644 item.lParam = (LPARAM)i;
629 item.pszText = name.Ptr_non_const(); 645 item.pszText = name.Ptr_non_const();
630 646
631 const UString fullPath = DirPrefix + name; 647 const UString fullPath = DirPrefix + name;
@@ -675,14 +691,14 @@ HRESULT CBrowseDialog::Reload(const UString &pathPrefix, const UString &selected
675HRESULT CBrowseDialog::Reload() 691HRESULT CBrowseDialog::Reload()
676{ 692{
677 UString selected; 693 UString selected;
678 int index = _list.GetNextSelectedItem(-1); 694 const int index = _list.GetNextSelectedItem(-1);
679 if (index >= 0) 695 if (index >= 0)
680 { 696 {
681 int fileIndex = GetRealItemIndex(index); 697 const int fileIndex = GetRealItemIndex(index);
682 if (fileIndex != kParentIndex) 698 if (fileIndex != kParentIndex)
683 selected = fs2us(_files[fileIndex].Name); 699 selected = fs2us(_files[fileIndex].Name);
684 } 700 }
685 UString dirPathTemp = DirPrefix; 701 const UString dirPathTemp = DirPrefix;
686 return Reload(dirPathTemp, selected); 702 return Reload(dirPathTemp, selected);
687} 703}
688 704
@@ -698,14 +714,14 @@ void CBrowseDialog::OpenParentFolder()
698 714
699void CBrowseDialog::SetPathEditText() 715void CBrowseDialog::SetPathEditText()
700{ 716{
701 int index = _list.GetNextSelectedItem(-1); 717 const int index = _list.GetNextSelectedItem(-1);
702 if (index < 0) 718 if (index < 0)
703 { 719 {
704 if (FolderMode) 720 if (FolderMode)
705 _pathEdit.SetText(DirPrefix); 721 _pathEdit.SetText(DirPrefix);
706 return; 722 return;
707 } 723 }
708 int fileIndex = GetRealItemIndex(index); 724 const int fileIndex = GetRealItemIndex(index);
709 if (fileIndex == kParentIndex) 725 if (fileIndex == kParentIndex)
710 { 726 {
711 if (FolderMode) 727 if (FolderMode)
@@ -745,7 +761,7 @@ void CBrowseDialog::OnCreateDir()
745 { 761 {
746 if (!NDir::CreateComplexDir(destPath)) 762 if (!NDir::CreateComplexDir(destPath))
747 { 763 {
748 MessageBox_HResError((HWND)*this, GetNormalizedError(), fs2us(destPath)); 764 MessageBox_HResError((HWND)*this, GetLastError_noZero_HRESULT(), fs2us(destPath));
749 } 765 }
750 else 766 else
751 { 767 {
@@ -759,10 +775,10 @@ void CBrowseDialog::OnCreateDir()
759 775
760void CBrowseDialog::OnItemEnter() 776void CBrowseDialog::OnItemEnter()
761{ 777{
762 int index = _list.GetNextSelectedItem(-1); 778 const int index = _list.GetNextSelectedItem(-1);
763 if (index < 0) 779 if (index < 0)
764 return; 780 return;
765 int fileIndex = GetRealItemIndex(index); 781 const int fileIndex = GetRealItemIndex(index);
766 if (fileIndex == kParentIndex) 782 if (fileIndex == kParentIndex)
767 OpenParentFolder(); 783 OpenParentFolder();
768 else 784 else
@@ -782,7 +798,7 @@ void CBrowseDialog::OnItemEnter()
782 UString s = DirPrefix; 798 UString s = DirPrefix;
783 s += fs2us(file.Name); 799 s += fs2us(file.Name);
784 s.Add_PathSepar(); 800 s.Add_PathSepar();
785 HRESULT res = Reload(s, UString()); 801 const HRESULT res = Reload(s, UString());
786 if (res != S_OK) 802 if (res != S_OK)
787 MessageBox_HResError(*this, res, s); 803 MessageBox_HResError(*this, res, s);
788 SetPathEditText(); 804 SetPathEditText();
@@ -802,10 +818,13 @@ void CBrowseDialog::FinishOnOK()
802 FilePath = fs2us(destPath); 818 FilePath = fs2us(destPath);
803 if (FolderMode) 819 if (FolderMode)
804 NormalizeDirPathPrefix(FilePath); 820 NormalizeDirPathPrefix(FilePath);
821 FilterIndex = _filterCombo.GetCurSel();
805 End(IDOK); 822 End(IDOK);
806} 823}
807 824
808#endif 825#endif // USE_MY_BROWSE_DIALOG
826
827
809 828
810bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath) 829bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath)
811{ 830{
@@ -813,12 +832,13 @@ bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultP
813 832
814 #ifndef UNDER_CE 833 #ifndef UNDER_CE
815 834
816 #ifdef USE_MY_BROWSE_DIALOG 835#ifdef USE_MY_BROWSE_DIALOG
817 if (!IsSuperOrDevicePath(path)) 836 if (!IsSuperOrDevicePath(path))
818 #endif 837 if (MyStringLen(path) < MAX_PATH)
838#endif
819 return NShell::BrowseForFolder(owner, title, path, resultPath); 839 return NShell::BrowseForFolder(owner, title, path, resultPath);
820 840
821 #endif 841 #endif // UNDER_CE
822 842
823 #ifdef USE_MY_BROWSE_DIALOG 843 #ifdef USE_MY_BROWSE_DIALOG
824 844
@@ -831,64 +851,107 @@ bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultP
831 if (dialog.Create(owner) != IDOK) 851 if (dialog.Create(owner) != IDOK)
832 return false; 852 return false;
833 resultPath = dialog.FilePath; 853 resultPath = dialog.FilePath;
834 #endif
835
836 return true; 854 return true;
855
856 #endif
837} 857}
838 858
839bool MyBrowseForFile(HWND owner, LPCWSTR title, LPCWSTR path,
840 LPCWSTR filterDescription, LPCWSTR filter, UString &resultPath)
841{
842 resultPath.Empty();
843 859
844 #ifndef UNDER_CE 860// LPCWSTR filterDescription, LPCWSTR filter,
845 861
846 #ifdef USE_MY_BROWSE_DIALOG 862bool CBrowseInfo::BrowseForFile(const CObjectVector<CBrowseFilterInfo> &filters)
847 if (!IsSuperOrDevicePath(path)) 863{
848 #endif 864#ifndef UNDER_CE
865#ifdef USE_MY_BROWSE_DIALOG
866 /* win10:
867 GetOpenFileName() for FilePath doesn't support super prefix "\\\\?\\"
868 GetOpenFileName() for FilePath doesn't support long path
869 */
870 if (!IsSuperOrDevicePath(FilePath))
871 // if (filters.Size() > 100) // for debug
872#endif
849 { 873 {
850 if (MyGetOpenFileName(owner, title, NULL, path, filterDescription, filter, resultPath)) 874 const UString filePath_Store = FilePath;
875 UString dirPrefix;
876 {
877 FString prefix, name;
878 if (NDir::GetFullPathAndSplit(us2fs(FilePath), prefix, name))
879 {
880 dirPrefix = fs2us(prefix);
881 FilePath = fs2us(name);
882 }
883 }
884 UStringVector filters2;
885 FOR_VECTOR (i, filters)
886 {
887 const CBrowseFilterInfo &fi = filters[i];
888 filters2.Add(fi.Description);
889 UString s;
890 FOR_VECTOR (k, fi.Masks)
891 {
892 if (k != 0)
893 s += ";";
894 s += fi.Masks[k];
895 }
896 filters2.Add(s);
897 }
898 if (CommonDlg_BrowseForFile(!dirPrefix.IsEmpty() ? dirPrefix.Ptr(): NULL, filters2))
851 return true; 899 return true;
852 #ifdef UNDER_CE 900 FilePath = filePath_Store;
901
902 #ifdef UNDER_CE
853 return false; 903 return false;
854 #else 904 #else
855 // maybe we must use GetLastError in WinCE. 905 // maybe we must use GetLastError in WinCE.
856 DWORD errorCode = CommDlgExtendedError(); 906 const DWORD errorCode = CommDlgExtendedError();
857 const char *errorMessage = NULL; 907 #ifdef USE_MY_BROWSE_DIALOG
858 switch (errorCode) 908 // FNERR_INVALIDFILENAME is expected error, if long path was used
859 { 909 if (errorCode != FNERR_INVALIDFILENAME
860 case 0: return false; // cancel or close obn dialog 910 || FilePath.Len() < MAX_PATH)
861 case FNERR_INVALIDFILENAME: errorMessage = "Invalid File Name"; break; 911 #endif
862 default: errorMessage = "Open Dialog Error";
863 }
864 if (!errorMessage)
865 return false;
866 { 912 {
867 UString s (errorMessage); 913 if (errorCode == 0) // cancel or close on dialog
914 return false;
915 const char *message = NULL;
916 if (errorCode == FNERR_INVALIDFILENAME)
917 message = "Invalid file name";
918 UString s ("Open Dialog Error:");
919 s.Add_LF();
920 if (message)
921 s += message;
922 else
923 {
924 char temp[16];
925 ConvertUInt32ToHex8Digits(errorCode, temp);
926 s += "Error #";
927 s += temp;
928 }
868 s.Add_LF(); 929 s.Add_LF();
869 s += path; 930 s += FilePath;
870 MessageBox_Error_Global(owner, s); 931 MessageBox_Error_Global(hwndOwner, s);
871 } 932 }
872 #endif 933 #endif // UNDER_CE
873 } 934 }
874 935
875 #endif 936#endif // UNDER_CE
876 937
877 #ifdef USE_MY_BROWSE_DIALOG 938#ifdef USE_MY_BROWSE_DIALOG
939
878 CBrowseDialog dialog; 940 CBrowseDialog dialog;
879 if (title) 941
880 dialog.Title = title;
881 if (path)
882 dialog.FilePath = path;
883 dialog.FolderMode = false; 942 dialog.FolderMode = false;
884 if (filter) 943 dialog.SaveMode = SaveMode;
885 dialog.SetFilter(filter); 944 dialog.FilterIndex = FilterIndex;
886 if (filterDescription) 945 dialog.Filters = filters;
887 dialog.FilterDescription = filterDescription; 946
888 if (dialog.Create(owner) != IDOK) 947 if (lpstrTitle)
948 dialog.Title = lpstrTitle;
949 dialog.FilePath = FilePath;
950 if (dialog.Create(hwndOwner) != IDOK)
889 return false; 951 return false;
890 resultPath = dialog.FilePath; 952 FilePath = dialog.FilePath;
891 #endif 953 FilterIndex = dialog.FilterIndex;
954#endif
892 955
893 return true; 956 return true;
894} 957}
@@ -913,7 +976,9 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result
913 result.Empty(); 976 result.Empty();
914 977
915 UString path = path2; 978 UString path = path2;
979 #ifdef _WIN32
916 path.Replace(L'/', WCHAR_PATH_SEPARATOR); 980 path.Replace(L'/', WCHAR_PATH_SEPARATOR);
981 #endif
917 unsigned start = 0; 982 unsigned start = 0;
918 UString base; 983 UString base;
919 984
@@ -926,9 +991,7 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result
926 return true; 991 return true;
927 } 992 }
928 #endif 993 #endif
929 int pos = GetRootPrefixSize(path); 994 start = GetRootPrefixSize(path);
930 if (pos > 0)
931 start = pos;
932 } 995 }
933 else 996 else
934 { 997 {
@@ -973,8 +1036,8 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result
973 { 1036 {
974 if (start == path.Len()) 1037 if (start == path.Len())
975 break; 1038 break;
976 int slashPos = path.Find(WCHAR_PATH_SEPARATOR, start); 1039 const int slashPos = path.Find(WCHAR_PATH_SEPARATOR, start);
977 cur.SetFrom(path.Ptr(start), (slashPos < 0 ? path.Len() : slashPos) - start); 1040 cur.SetFrom(path.Ptr(start), (slashPos < 0 ? path.Len() : (unsigned)slashPos) - start);
978 if (checkExist) 1041 if (checkExist)
979 { 1042 {
980 CFileInfo fi; 1043 CFileInfo fi;
@@ -994,8 +1057,8 @@ bool CorrectFsPath(const UString &relBase, const UString &path2, UString &result
994 result += cur; 1057 result += cur;
995 if (slashPos < 0) 1058 if (slashPos < 0)
996 break; 1059 break;
1060 start = (unsigned)(slashPos + 1);
997 result.Add_PathSepar(); 1061 result.Add_PathSepar();
998 start = slashPos + 1;
999 } 1062 }
1000 1063
1001 return true; 1064 return true;
diff --git a/CPP/7zip/UI/FileManager/BrowseDialog.h b/CPP/7zip/UI/FileManager/BrowseDialog.h
index 957af2e..2ad8d54 100644
--- a/CPP/7zip/UI/FileManager/BrowseDialog.h
+++ b/CPP/7zip/UI/FileManager/BrowseDialog.h
@@ -1,12 +1,23 @@
1// BrowseDialog.h 1// BrowseDialog.h
2 2
3#ifndef __BROWSE_DIALOG_H 3#ifndef ZIP7_INC_BROWSE_DIALOG_H
4#define __BROWSE_DIALOG_H 4#define ZIP7_INC_BROWSE_DIALOG_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Windows/CommonDialog.h"
7 7
8bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath); 8bool MyBrowseForFolder(HWND owner, LPCWSTR title, LPCWSTR path, UString &resultPath);
9bool MyBrowseForFile(HWND owner, LPCWSTR title, LPCWSTR path, LPCWSTR filterDescription, LPCWSTR filter, UString &resultPath); 9
10struct CBrowseFilterInfo
11{
12 UStringVector Masks;
13 UString Description;
14};
15
16struct CBrowseInfo: public NWindows::CCommonDialogInfo
17{
18 bool BrowseForFile(const CObjectVector<CBrowseFilterInfo> &filters);
19};
20
10 21
11/* CorrectFsPath removes undesirable characters in names (dots and spaces at the end of file) 22/* CorrectFsPath removes undesirable characters in names (dots and spaces at the end of file)
12 But it doesn't change "bad" name in any of the following cases: 23 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 729743e..921972e 100644
--- a/CPP/7zip/UI/FileManager/ComboDialog.cpp
+++ b/CPP/7zip/UI/FileManager/ComboDialog.cpp
@@ -5,7 +5,7 @@
5 5
6#include "../../../Windows/Control/Static.h" 6#include "../../../Windows/Control/Static.h"
7 7
8#ifdef LANG 8#ifdef Z7_LANG
9#include "LangUtils.h" 9#include "LangUtils.h"
10#endif 10#endif
11 11
@@ -13,7 +13,7 @@ using namespace NWindows;
13 13
14bool CComboDialog::OnInit() 14bool CComboDialog::OnInit()
15{ 15{
16 #ifdef LANG 16 #ifdef Z7_LANG
17 LangSetDlgItems(*this, NULL, 0); 17 LangSetDlgItems(*this, NULL, 0);
18 #endif 18 #endif
19 _comboBox.Attach(GetItem(IDC_COMBO)); 19 _comboBox.Attach(GetItem(IDC_COMBO));
diff --git a/CPP/7zip/UI/FileManager/ComboDialog.h b/CPP/7zip/UI/FileManager/ComboDialog.h
index 29b28b5..bb0fda8 100644
--- a/CPP/7zip/UI/FileManager/ComboDialog.h
+++ b/CPP/7zip/UI/FileManager/ComboDialog.h
@@ -1,7 +1,7 @@
1// ComboDialog.h 1// ComboDialog.h
2 2
3#ifndef __COMBO_DIALOG_H 3#ifndef ZIP7_INC_COMBO_DIALOG_H
4#define __COMBO_DIALOG_H 4#define ZIP7_INC_COMBO_DIALOG_H
5 5
6#include "../../../Windows/Control/ComboBox.h" 6#include "../../../Windows/Control/ComboBox.h"
7#include "../../../Windows/Control/Dialog.h" 7#include "../../../Windows/Control/Dialog.h"
@@ -11,9 +11,9 @@
11class CComboDialog: public NWindows::NControl::CModalDialog 11class CComboDialog: public NWindows::NControl::CModalDialog
12{ 12{
13 NWindows::NControl::CComboBox _comboBox; 13 NWindows::NControl::CComboBox _comboBox;
14 virtual void OnOK(); 14 virtual void OnOK() Z7_override;
15 virtual bool OnInit(); 15 virtual bool OnInit() Z7_override;
16 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 16 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
17public: 17public:
18 // bool Sorted; 18 // bool Sorted;
19 UString Title; 19 UString Title;
@@ -22,7 +22,7 @@ public:
22 UStringVector Strings; 22 UStringVector Strings;
23 23
24 // CComboDialog(): Sorted(false) {}; 24 // CComboDialog(): Sorted(false) {};
25 INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_COMBO, parentWindow); } 25 INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_COMBO, parentWindow); }
26}; 26};
27 27
28#endif 28#endif
diff --git a/CPP/7zip/UI/FileManager/CopyDialog.cpp b/CPP/7zip/UI/FileManager/CopyDialog.cpp
index 4b17110..9bc01d0 100644
--- a/CPP/7zip/UI/FileManager/CopyDialog.cpp
+++ b/CPP/7zip/UI/FileManager/CopyDialog.cpp
@@ -8,16 +8,13 @@
8 8
9#include "BrowseDialog.h" 9#include "BrowseDialog.h"
10#include "CopyDialog.h" 10#include "CopyDialog.h"
11
12#ifdef LANG
13#include "LangUtils.h" 11#include "LangUtils.h"
14#endif
15 12
16using namespace NWindows; 13using namespace NWindows;
17 14
18bool CCopyDialog::OnInit() 15bool CCopyDialog::OnInit()
19{ 16{
20 #ifdef LANG 17 #ifdef Z7_LANG
21 LangSetDlgItems(*this, NULL, 0); 18 LangSetDlgItems(*this, NULL, 0);
22 #endif 19 #endif
23 _path.Attach(GetItem(IDC_COPY)); 20 _path.Attach(GetItem(IDC_COPY));
@@ -45,15 +42,15 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
45 int bx1, bx2, by; 42 int bx1, bx2, by;
46 GetItemSizes(IDCANCEL, bx1, by); 43 GetItemSizes(IDCANCEL, bx1, by);
47 GetItemSizes(IDOK, bx2, by); 44 GetItemSizes(IDOK, bx2, by);
48 int y = ySize - my - by; 45 const int y = ySize - my - by;
49 int x = xSize - mx - bx1; 46 const int x = xSize - mx - bx1;
50 47
51 InvalidateRect(NULL); 48 InvalidateRect(NULL);
52 49
53 { 50 {
54 RECT r; 51 RECT r;
55 GetClientRectOfItem(IDB_COPY_SET_PATH, r); 52 GetClientRectOfItem(IDB_COPY_SET_PATH, r);
56 int bx = RECT_SIZE_X(r); 53 const int bx = RECT_SIZE_X(r);
57 MoveItem(IDB_COPY_SET_PATH, xSize - mx - bx, r.top, bx, RECT_SIZE_Y(r)); 54 MoveItem(IDB_COPY_SET_PATH, xSize - mx - bx, r.top, bx, RECT_SIZE_Y(r));
58 ChangeSubWindowSizeX(_path, xSize - mx - mx - bx - mx); 55 ChangeSubWindowSizeX(_path, xSize - mx - mx - bx - mx);
59 } 56 }
@@ -63,7 +60,7 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
63 GetClientRectOfItem(IDT_COPY_INFO, r); 60 GetClientRectOfItem(IDT_COPY_INFO, r);
64 NControl::CStatic staticContol; 61 NControl::CStatic staticContol;
65 staticContol.Attach(GetItem(IDT_COPY_INFO)); 62 staticContol.Attach(GetItem(IDT_COPY_INFO));
66 int yPos = r.top; 63 const int yPos = r.top;
67 staticContol.Move(mx, yPos, xSize - mx * 2, y - 2 - yPos); 64 staticContol.Move(mx, yPos, xSize - mx * 2, y - 2 - yPos);
68 } 65 }
69 66
@@ -73,7 +70,7 @@ bool CCopyDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
73 return false; 70 return false;
74} 71}
75 72
76bool CCopyDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 73bool CCopyDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
77{ 74{
78 switch (buttonID) 75 switch (buttonID)
79 { 76 {
diff --git a/CPP/7zip/UI/FileManager/CopyDialog.h b/CPP/7zip/UI/FileManager/CopyDialog.h
index 30fde71..3782420 100644
--- a/CPP/7zip/UI/FileManager/CopyDialog.h
+++ b/CPP/7zip/UI/FileManager/CopyDialog.h
@@ -1,7 +1,7 @@
1// CopyDialog.h 1// CopyDialog.h
2 2
3#ifndef __COPY_DIALOG_H 3#ifndef ZIP7_INC_COPY_DIALOG_H
4#define __COPY_DIALOG_H 4#define ZIP7_INC_COPY_DIALOG_H
5 5
6#include "../../../Windows/Control/ComboBox.h" 6#include "../../../Windows/Control/ComboBox.h"
7#include "../../../Windows/Control/Dialog.h" 7#include "../../../Windows/Control/Dialog.h"
@@ -13,11 +13,11 @@ const int kCopyDialog_NumInfoLines = 11;
13class CCopyDialog: public NWindows::NControl::CModalDialog 13class CCopyDialog: public NWindows::NControl::CModalDialog
14{ 14{
15 NWindows::NControl::CComboBox _path; 15 NWindows::NControl::CComboBox _path;
16 virtual void OnOK(); 16 virtual void OnOK() Z7_override;
17 virtual bool OnInit(); 17 virtual bool OnInit() Z7_override;
18 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 18 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
19 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
19 void OnButtonSetPath(); 20 void OnButtonSetPath();
20 bool OnButtonClicked(int buttonID, HWND buttonHWND);
21public: 21public:
22 UString Title; 22 UString Title;
23 UString Static; 23 UString Static;
@@ -25,7 +25,7 @@ public:
25 UString Info; 25 UString Info;
26 UStringVector Strings; 26 UStringVector Strings;
27 27
28 INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_COPY, parentWindow); } 28 INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_COPY, parentWindow); }
29}; 29};
30 30
31#endif 31#endif
diff --git a/CPP/7zip/UI/FileManager/DialogSize.h b/CPP/7zip/UI/FileManager/DialogSize.h
index 504541b..9f2270b 100644
--- a/CPP/7zip/UI/FileManager/DialogSize.h
+++ b/CPP/7zip/UI/FileManager/DialogSize.h
@@ -1,7 +1,7 @@
1// DialogSize.h 1// DialogSize.h
2 2
3#ifndef __DIALOG_SIZE_H 3#ifndef ZIP7_INC_DIALOG_SIZE_H
4#define __DIALOG_SIZE_H 4#define ZIP7_INC_DIALOG_SIZE_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/EditDialog.cpp b/CPP/7zip/UI/FileManager/EditDialog.cpp
index 7f59672..e97d9ea 100644
--- a/CPP/7zip/UI/FileManager/EditDialog.cpp
+++ b/CPP/7zip/UI/FileManager/EditDialog.cpp
@@ -4,13 +4,13 @@
4 4
5#include "EditDialog.h" 5#include "EditDialog.h"
6 6
7#ifdef LANG 7#ifdef Z7_LANG
8#include "LangUtils.h" 8#include "LangUtils.h"
9#endif 9#endif
10 10
11bool CEditDialog::OnInit() 11bool CEditDialog::OnInit()
12{ 12{
13 #ifdef LANG 13 #ifdef Z7_LANG
14 LangSetDlgItems(*this, NULL, 0); 14 LangSetDlgItems(*this, NULL, 0);
15 #endif 15 #endif
16 _edit.Attach(GetItem(IDE_EDIT)); 16 _edit.Attach(GetItem(IDE_EDIT));
@@ -22,21 +22,21 @@ bool CEditDialog::OnInit()
22 return CModalDialog::OnInit(); 22 return CModalDialog::OnInit();
23} 23}
24 24
25// #define MY_CLOSE_BUTTON__ID IDCANCEL 25// #define MY_CLOSE_BUTTON_ID IDCANCEL
26#define MY_CLOSE_BUTTON__ID IDCLOSE 26#define MY_CLOSE_BUTTON_ID IDCLOSE
27 27
28bool CEditDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize) 28bool CEditDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
29{ 29{
30 int mx, my; 30 int mx, my;
31 GetMargins(8, mx, my); 31 GetMargins(8, mx, my);
32 int bx1, by; 32 int bx1, by;
33 GetItemSizes(MY_CLOSE_BUTTON__ID, bx1, by); 33 GetItemSizes(MY_CLOSE_BUTTON_ID, bx1, by);
34 34
35 // int bx2; 35 // int bx2;
36 // GetItemSizes(IDOK, bx2, by); 36 // GetItemSizes(IDOK, bx2, by);
37 37
38 int y = ySize - my - by; 38 const int y = ySize - my - by;
39 int x = xSize - mx - bx1; 39 const int x = xSize - mx - bx1;
40 40
41 /* 41 /*
42 RECT rect; 42 RECT rect;
@@ -46,7 +46,7 @@ bool CEditDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
46 */ 46 */
47 InvalidateRect(NULL); 47 InvalidateRect(NULL);
48 48
49 MoveItem(MY_CLOSE_BUTTON__ID, x, y, bx1, by); 49 MoveItem(MY_CLOSE_BUTTON_ID, x, y, bx1, by);
50 // MoveItem(IDOK, x - mx - bx2, y, bx2, by); 50 // MoveItem(IDOK, x - mx - bx2, y, bx2, by);
51 /* 51 /*
52 if (wParam == SIZE_MAXSHOW || wParam == SIZE_MAXIMIZED || wParam == SIZE_MAXHIDE) 52 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 d820516..6970b14 100644
--- a/CPP/7zip/UI/FileManager/EditDialog.h
+++ b/CPP/7zip/UI/FileManager/EditDialog.h
@@ -1,7 +1,7 @@
1// EditDialog.h 1// EditDialog.h
2 2
3#ifndef __EDIT_DIALOG_H 3#ifndef ZIP7_INC_EDIT_DIALOG_H
4#define __EDIT_DIALOG_H 4#define ZIP7_INC_EDIT_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/Edit.h" 7#include "../../../Windows/Control/Edit.h"
@@ -11,13 +11,13 @@
11class CEditDialog: public NWindows::NControl::CModalDialog 11class CEditDialog: public NWindows::NControl::CModalDialog
12{ 12{
13 NWindows::NControl::CEdit _edit; 13 NWindows::NControl::CEdit _edit;
14 virtual bool OnInit(); 14 virtual bool OnInit() Z7_override;
15 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 15 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
16public: 16public:
17 UString Title; 17 UString Title;
18 UString Text; 18 UString Text;
19 19
20 INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_EDIT_DLG, wndParent); } 20 INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_EDIT_DLG, wndParent); }
21 21
22 CEditDialog() {} 22 CEditDialog() {}
23}; 23};
diff --git a/CPP/7zip/UI/FileManager/EditPage.cpp b/CPP/7zip/UI/FileManager/EditPage.cpp
index 0108904..a2a0321 100644
--- a/CPP/7zip/UI/FileManager/EditPage.cpp
+++ b/CPP/7zip/UI/FileManager/EditPage.cpp
@@ -12,6 +12,7 @@
12 12
13using namespace NWindows; 13using namespace NWindows;
14 14
15#ifdef Z7_LANG
15static const UInt32 kLangIDs[] = 16static const UInt32 kLangIDs[] =
16{ 17{
17 IDT_EDIT_EDITOR, 18 IDT_EDIT_EDITOR,
@@ -22,6 +23,7 @@ static const UInt32 kLangIDs_Colon[] =
22{ 23{
23 IDT_EDIT_VIEWER 24 IDT_EDIT_VIEWER
24}; 25};
26#endif
25 27
26#define kEditTopic "FM/options.htm#editor" 28#define kEditTopic "FM/options.htm#editor"
27 29
@@ -29,8 +31,10 @@ bool CEditPage::OnInit()
29{ 31{
30 _initMode = true; 32 _initMode = true;
31 33
32 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 34 #ifdef Z7_LANG
33 LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); 35 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
36 LangSetDlgItems_Colon(*this, kLangIDs_Colon, Z7_ARRAY_SIZE(kLangIDs_Colon));
37 #endif
34 38
35 _ctrls[0].Ctrl = IDE_EDIT_VIEWER; _ctrls[0].Button = IDB_EDIT_VIEWER; 39 _ctrls[0].Ctrl = IDE_EDIT_VIEWER; _ctrls[0].Button = IDB_EDIT_VIEWER;
36 _ctrls[1].Ctrl = IDE_EDIT_EDITOR; _ctrls[1].Button = IDB_EDIT_EDITOR; 40 _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)
91 95
92 SplitCmdLineSmart(cmd, prg, param); 96 SplitCmdLineSmart(cmd, prg, param);
93 97
94 UString resPath; 98 CObjectVector<CBrowseFilterInfo> filters;
95 99 CBrowseFilterInfo &bfi = filters.AddNew();
96 if (MyBrowseForFile(hwnd, 0, prg, NULL, L"*.exe", resPath)) 100 bfi.Description = "*.exe";
101 bfi.Masks.Add(UString("*.exe"));
102
103 CBrowseInfo bi;
104 bi.FilterIndex = 0;
105 bi.FilePath = prg;
106 bi.hwndOwner = hwnd;
107
108 if (bi.BrowseForFile(filters))
97 { 109 {
98 resPath.Trim(); 110 cmd = bi.FilePath;
99 cmd = resPath; 111 cmd.Trim();
100 /* 112 /*
101 if (!param.IsEmpty() && !resPath.IsEmpty()) 113 if (!param.IsEmpty() && !resPath.IsEmpty())
102 { 114 {
@@ -112,7 +124,7 @@ static void Edit_BrowseForFile(NWindows::NControl::CEdit &edit, HWND hwnd)
112 } 124 }
113} 125}
114 126
115bool CEditPage::OnButtonClicked(int buttonID, HWND buttonHWND) 127bool CEditPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
116{ 128{
117 for (unsigned i = 0; i < 3; i++) 129 for (unsigned i = 0; i < 3; i++)
118 { 130 {
@@ -127,7 +139,7 @@ bool CEditPage::OnButtonClicked(int buttonID, HWND buttonHWND)
127 return CPropertyPage::OnButtonClicked(buttonID, buttonHWND); 139 return CPropertyPage::OnButtonClicked(buttonID, buttonHWND);
128} 140}
129 141
130bool CEditPage::OnCommand(int code, int itemID, LPARAM param) 142bool CEditPage::OnCommand(unsigned code, unsigned itemID, LPARAM param)
131{ 143{
132 if (!_initMode && code == EN_CHANGE) 144 if (!_initMode && code == EN_CHANGE)
133 { 145 {
diff --git a/CPP/7zip/UI/FileManager/EditPage.h b/CPP/7zip/UI/FileManager/EditPage.h
index 208edd8..a70fad7 100644
--- a/CPP/7zip/UI/FileManager/EditPage.h
+++ b/CPP/7zip/UI/FileManager/EditPage.h
@@ -1,7 +1,7 @@
1// EditPage.h 1// EditPage.h
2 2
3#ifndef __EDIT_PAGE_H 3#ifndef ZIP7_INC_EDIT_PAGE_H
4#define __EDIT_PAGE_H 4#define ZIP7_INC_EDIT_PAGE_H
5 5
6#include "../../../Windows/Control/PropertyPage.h" 6#include "../../../Windows/Control/PropertyPage.h"
7#include "../../../Windows/Control/Edit.h" 7#include "../../../Windows/Control/Edit.h"
@@ -10,8 +10,8 @@ struct CEditPageCtrl
10{ 10{
11 NWindows::NControl::CEdit Edit; 11 NWindows::NControl::CEdit Edit;
12 bool WasChanged; 12 bool WasChanged;
13 int Ctrl; 13 unsigned Ctrl;
14 int Button; 14 unsigned Button;
15}; 15};
16 16
17class CEditPage: public NWindows::NControl::CPropertyPage 17class CEditPage: public NWindows::NControl::CPropertyPage
@@ -20,11 +20,11 @@ class CEditPage: public NWindows::NControl::CPropertyPage
20 20
21 bool _initMode; 21 bool _initMode;
22public: 22public:
23 virtual bool OnInit(); 23 virtual bool OnInit() Z7_override;
24 virtual void OnNotifyHelp(); 24 virtual void OnNotifyHelp() Z7_override;
25 virtual bool OnCommand(int code, int itemID, LPARAM param); 25 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override;
26 virtual LONG OnApply(); 26 virtual LONG OnApply() Z7_override;
27 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 27 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
28}; 28};
29 29
30#endif 30#endif
diff --git a/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp b/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp
index 389aa3e..fc2fd6c 100644
--- a/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp
+++ b/CPP/7zip/UI/FileManager/EnumFormatEtc.cpp
@@ -3,28 +3,27 @@
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "EnumFormatEtc.h" 5#include "EnumFormatEtc.h"
6#include "../../IDecl.h"
6#include "MyCom2.h" 7#include "MyCom2.h"
7 8
8class CEnumFormatEtc : 9class CEnumFormatEtc Z7_final:
9public IEnumFORMATETC, 10 public IEnumFORMATETC,
10public CMyUnknownImp 11 public CMyUnknownImp
11{ 12{
12public: 13 Z7_COM_UNKNOWN_IMP_1_MT(IEnumFORMATETC)
13 MY_UNKNOWN_IMP1_MT(IEnumFORMATETC)
14 14
15 STDMETHOD(Next)(ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched); 15 STDMETHOD(Next)(ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) Z7_override;
16 STDMETHOD(Skip)(ULONG celt); 16 STDMETHOD(Skip)(ULONG celt) Z7_override;
17 STDMETHOD(Reset)(void); 17 STDMETHOD(Reset)(void) Z7_override;
18 STDMETHOD(Clone)(IEnumFORMATETC **ppEnumFormatEtc); 18 STDMETHOD(Clone)(IEnumFORMATETC **ppEnumFormatEtc) Z7_override;
19 19
20 CEnumFormatEtc(const FORMATETC *pFormatEtc, ULONG numFormats);
21 ~CEnumFormatEtc();
22
23private:
24 LONG m_RefCount; 20 LONG m_RefCount;
25 ULONG m_NumFormats; 21 ULONG m_NumFormats;
26 FORMATETC *m_Formats; 22 FORMATETC *m_Formats;
27 ULONG m_Index; 23 ULONG m_Index;
24public:
25 CEnumFormatEtc(const FORMATETC *pFormatEtc, ULONG numFormats);
26 ~CEnumFormatEtc();
28}; 27};
29 28
30static void DeepCopyFormatEtc(FORMATETC *dest, const FORMATETC *src) 29static void DeepCopyFormatEtc(FORMATETC *dest, const FORMATETC *src)
@@ -62,10 +61,10 @@ CEnumFormatEtc::~CEnumFormatEtc()
62 } 61 }
63} 62}
64 63
65STDMETHODIMP CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pceltFetched) 64Z7_COMWF_B CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pceltFetched)
66{ 65{
67 ULONG copied = 0; 66 ULONG copied = 0;
68 if (celt == 0 || pFormatEtc == 0) 67 if (celt == 0 || !pFormatEtc)
69 return E_INVALIDARG; 68 return E_INVALIDARG;
70 while (m_Index < m_NumFormats && copied < celt) 69 while (m_Index < m_NumFormats && copied < celt)
71 { 70 {
@@ -73,24 +72,24 @@ STDMETHODIMP CEnumFormatEtc::Next(ULONG celt, FORMATETC *pFormatEtc, ULONG *pcel
73 copied++; 72 copied++;
74 m_Index++; 73 m_Index++;
75 } 74 }
76 if (pceltFetched != 0) 75 if (pceltFetched)
77 *pceltFetched = copied; 76 *pceltFetched = copied;
78 return (copied == celt) ? S_OK : S_FALSE; 77 return (copied == celt) ? S_OK : S_FALSE;
79} 78}
80 79
81STDMETHODIMP CEnumFormatEtc::Skip(ULONG celt) 80Z7_COMWF_B CEnumFormatEtc::Skip(ULONG celt)
82{ 81{
83 m_Index += celt; 82 m_Index += celt;
84 return (m_Index <= m_NumFormats) ? S_OK : S_FALSE; 83 return (m_Index <= m_NumFormats) ? S_OK : S_FALSE;
85} 84}
86 85
87STDMETHODIMP CEnumFormatEtc::Reset(void) 86Z7_COMWF_B CEnumFormatEtc::Reset(void)
88{ 87{
89 m_Index = 0; 88 m_Index = 0;
90 return S_OK; 89 return S_OK;
91} 90}
92 91
93STDMETHODIMP CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc) 92Z7_COMWF_B CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc)
94{ 93{
95 HRESULT hResult = CreateEnumFormatEtc(m_NumFormats, m_Formats, ppEnumFormatEtc); 94 HRESULT hResult = CreateEnumFormatEtc(m_NumFormats, m_Formats, ppEnumFormatEtc);
96 if (hResult == S_OK) 95 if (hResult == S_OK)
@@ -101,7 +100,7 @@ STDMETHODIMP CEnumFormatEtc::Clone(IEnumFORMATETC ** ppEnumFormatEtc)
101// replacement for SHCreateStdEnumFmtEtc 100// replacement for SHCreateStdEnumFmtEtc
102HRESULT CreateEnumFormatEtc(UINT numFormats, const FORMATETC *formats, IEnumFORMATETC **enumFormat) 101HRESULT CreateEnumFormatEtc(UINT numFormats, const FORMATETC *formats, IEnumFORMATETC **enumFormat)
103{ 102{
104 if (numFormats == 0 || formats == 0 || enumFormat == 0) 103 if (numFormats == 0 || !formats || !enumFormat)
105 return E_INVALIDARG; 104 return E_INVALIDARG;
106 *enumFormat = new CEnumFormatEtc(formats, numFormats); 105 *enumFormat = new CEnumFormatEtc(formats, numFormats);
107 return (*enumFormat) ? S_OK : E_OUTOFMEMORY; 106 return (*enumFormat) ? S_OK : E_OUTOFMEMORY;
diff --git a/CPP/7zip/UI/FileManager/EnumFormatEtc.h b/CPP/7zip/UI/FileManager/EnumFormatEtc.h
index 93a53cb..12df225 100644
--- a/CPP/7zip/UI/FileManager/EnumFormatEtc.h
+++ b/CPP/7zip/UI/FileManager/EnumFormatEtc.h
@@ -1,7 +1,7 @@
1// EnumFormatEtc.h 1// EnumFormatEtc.h
2 2
3#ifndef __ENUMFORMATETC_H 3#ifndef ZIP7_INC_ENUMFORMATETC_H
4#define __ENUMFORMATETC_H 4#define ZIP7_INC_ENUMFORMATETC_H
5 5
6#include "../../../Common/MyWindows.h" 6#include "../../../Common/MyWindows.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/ExtractCallback.cpp b/CPP/7zip/UI/FileManager/ExtractCallback.cpp
index 232717f..f674044 100644
--- a/CPP/7zip/UI/FileManager/ExtractCallback.cpp
+++ b/CPP/7zip/UI/FileManager/ExtractCallback.cpp
@@ -17,7 +17,7 @@
17#include "../../Common/StreamUtils.h" 17#include "../../Common/StreamUtils.h"
18#include "../Common/ExtractingFilePath.h" 18#include "../Common/ExtractingFilePath.h"
19 19
20#ifndef _SFX 20#ifndef Z7_SFX
21#include "../Common/ZipRegistry.h" 21#include "../Common/ZipRegistry.h"
22#endif 22#endif
23 23
@@ -28,7 +28,7 @@
28#include "FormatUtils.h" 28#include "FormatUtils.h"
29#include "LangUtils.h" 29#include "LangUtils.h"
30#include "OverwriteDialog.h" 30#include "OverwriteDialog.h"
31#ifndef _NO_CRYPTO 31#ifndef Z7_NO_CRYPTO
32#include "PasswordDialog.h" 32#include "PasswordDialog.h"
33#endif 33#endif
34#include "PropertyName.h" 34#include "PropertyName.h"
@@ -48,7 +48,7 @@ void CExtractCallbackImp::Init()
48 48
49 NumArchiveErrors = 0; 49 NumArchiveErrors = 0;
50 ThereAreMessageErrors = false; 50 ThereAreMessageErrors = false;
51 #ifndef _SFX 51 #ifndef Z7_SFX
52 NumFolders = NumFiles = 0; 52 NumFolders = NumFiles = 0;
53 NeedAddFile = false; 53 NeedAddFile = false;
54 #endif 54 #endif
@@ -60,29 +60,27 @@ void CExtractCallbackImp::AddError_Message(LPCWSTR s)
60 ProgressDialog->Sync.AddError_Message(s); 60 ProgressDialog->Sync.AddError_Message(s);
61} 61}
62 62
63#ifndef _SFX 63#ifndef Z7_SFX
64 64
65STDMETHODIMP CExtractCallbackImp::SetNumFiles(UInt64 65Z7_COM7F_IMF(CExtractCallbackImp::SetNumFiles(UInt64 numFiles))
66 #ifndef _SFX
67 numFiles
68 #endif
69 )
70{ 66{
71 #ifndef _SFX 67 #ifdef Z7_SFX
68 UNUSED_VAR(numFiles)
69 #else
72 ProgressDialog->Sync.Set_NumFilesTotal(numFiles); 70 ProgressDialog->Sync.Set_NumFilesTotal(numFiles);
73 #endif 71 #endif
74 return S_OK; 72 return S_OK;
75} 73}
76 74
77#endif 75#endif
78 76
79STDMETHODIMP CExtractCallbackImp::SetTotal(UInt64 total) 77Z7_COM7F_IMF(CExtractCallbackImp::SetTotal(UInt64 total))
80{ 78{
81 ProgressDialog->Sync.Set_NumBytesTotal(total); 79 ProgressDialog->Sync.Set_NumBytesTotal(total);
82 return S_OK; 80 return S_OK;
83} 81}
84 82
85STDMETHODIMP CExtractCallbackImp::SetCompleted(const UInt64 *value) 83Z7_COM7F_IMF(CExtractCallbackImp::SetCompleted(const UInt64 *value))
86{ 84{
87 return ProgressDialog->Sync.Set_NumBytesCur(value); 85 return ProgressDialog->Sync.Set_NumBytesCur(value);
88} 86}
@@ -139,7 +137,7 @@ HRESULT CExtractCallbackImp::Open_Finished()
139 return ProgressDialog->Sync.CheckStop(); 137 return ProgressDialog->Sync.CheckStop();
140} 138}
141 139
142#ifndef _NO_CRYPTO 140#ifndef Z7_NO_CRYPTO
143 141
144HRESULT CExtractCallbackImp::Open_CryptoGetTextPassword(BSTR *password) 142HRESULT CExtractCallbackImp::Open_CryptoGetTextPassword(BSTR *password)
145{ 143{
@@ -168,8 +166,8 @@ void CExtractCallbackImp::Open_Clear_PasswordWasAsked_Flag()
168#endif 166#endif
169 167
170 168
171#ifndef _SFX 169#ifndef Z7_SFX
172STDMETHODIMP CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 170Z7_COM7F_IMF(CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
173{ 171{
174 ProgressDialog->Sync.Set_Ratio(inSize, outSize); 172 ProgressDialog->Sync.Set_Ratio(inSize, outSize);
175 return S_OK; 173 return S_OK;
@@ -177,13 +175,13 @@ STDMETHODIMP CExtractCallbackImp::SetRatioInfo(const UInt64 *inSize, const UInt6
177#endif 175#endif
178 176
179/* 177/*
180STDMETHODIMP CExtractCallbackImp::SetTotalFiles(UInt64 total) 178Z7_COM7F_IMF(CExtractCallbackImp::SetTotalFiles(UInt64 total)
181{ 179{
182 ProgressDialog->Sync.SetNumFilesTotal(total); 180 ProgressDialog->Sync.SetNumFilesTotal(total);
183 return S_OK; 181 return S_OK;
184} 182}
185 183
186STDMETHODIMP CExtractCallbackImp::SetCompletedFiles(const UInt64 *value) 184Z7_COM7F_IMF(CExtractCallbackImp::SetCompletedFiles(const UInt64 *value)
187{ 185{
188 if (value != NULL) 186 if (value != NULL)
189 ProgressDialog->Sync.SetNumFilesCur(*value); 187 ProgressDialog->Sync.SetNumFilesCur(*value);
@@ -191,10 +189,10 @@ STDMETHODIMP CExtractCallbackImp::SetCompletedFiles(const UInt64 *value)
191} 189}
192*/ 190*/
193 191
194STDMETHODIMP CExtractCallbackImp::AskOverwrite( 192Z7_COM7F_IMF(CExtractCallbackImp::AskOverwrite(
195 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize, 193 const wchar_t *existName, const FILETIME *existTime, const UInt64 *existSize,
196 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize, 194 const wchar_t *newName, const FILETIME *newTime, const UInt64 *newSize,
197 Int32 *answer) 195 Int32 *answer))
198{ 196{
199 COverwriteDialog dialog; 197 COverwriteDialog dialog;
200 198
@@ -223,7 +221,7 @@ STDMETHODIMP CExtractCallbackImp::AskOverwrite(
223} 221}
224 222
225 223
226STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 * /* position */) 224Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 isFolder, Int32 askExtractMode, const UInt64 * /* position */))
227{ 225{
228 _isFolder = IntToBool(isFolder); 226 _isFolder = IntToBool(isFolder);
229 _currentFilePath = name; 227 _currentFilePath = name;
@@ -241,7 +239,7 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation(const wchar_t *name, Int32 is
241 return ProgressDialog->Sync.Set_Status2(*msg, name, IntToBool(isFolder)); 239 return ProgressDialog->Sync.Set_Status2(*msg, name, IntToBool(isFolder));
242} 240}
243 241
244STDMETHODIMP CExtractCallbackImp::MessageError(const wchar_t *s) 242Z7_COM7F_IMF(CExtractCallbackImp::MessageError(const wchar_t *s))
245{ 243{
246 AddError_Message(s); 244 AddError_Message(s);
247 return S_OK; 245 return S_OK;
@@ -254,9 +252,9 @@ HRESULT CExtractCallbackImp::MessageError(const char *message, const FString &pa
254 return S_OK; 252 return S_OK;
255} 253}
256 254
257#ifndef _SFX 255#ifndef Z7_SFX
258 256
259STDMETHODIMP CExtractCallbackImp::ShowMessage(const wchar_t *s) 257Z7_COM7F_IMF(CExtractCallbackImp::ShowMessage(const wchar_t *s))
260{ 258{
261 AddError_Message(s); 259 AddError_Message(s);
262 return S_OK; 260 return S_OK;
@@ -272,25 +270,33 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam
272 if (opRes == NArchive::NExtract::NOperationResult::kOK) 270 if (opRes == NArchive::NExtract::NOperationResult::kOK)
273 return; 271 return;
274 272
273 #ifndef Z7_SFX
275 UINT messageID = 0; 274 UINT messageID = 0;
275 #endif
276 UINT id = 0; 276 UINT id = 0;
277 277
278 switch (opRes) 278 switch (opRes)
279 { 279 {
280 case NArchive::NExtract::NOperationResult::kUnsupportedMethod: 280 case NArchive::NExtract::NOperationResult::kUnsupportedMethod:
281 #ifndef Z7_SFX
281 messageID = IDS_EXTRACT_MESSAGE_UNSUPPORTED_METHOD; 282 messageID = IDS_EXTRACT_MESSAGE_UNSUPPORTED_METHOD;
283 #endif
282 id = IDS_EXTRACT_MSG_UNSUPPORTED_METHOD; 284 id = IDS_EXTRACT_MSG_UNSUPPORTED_METHOD;
283 break; 285 break;
284 case NArchive::NExtract::NOperationResult::kDataError: 286 case NArchive::NExtract::NOperationResult::kDataError:
287 #ifndef Z7_SFX
285 messageID = encrypted ? 288 messageID = encrypted ?
286 IDS_EXTRACT_MESSAGE_DATA_ERROR_ENCRYPTED: 289 IDS_EXTRACT_MESSAGE_DATA_ERROR_ENCRYPTED:
287 IDS_EXTRACT_MESSAGE_DATA_ERROR; 290 IDS_EXTRACT_MESSAGE_DATA_ERROR;
291 #endif
288 id = IDS_EXTRACT_MSG_DATA_ERROR; 292 id = IDS_EXTRACT_MSG_DATA_ERROR;
289 break; 293 break;
290 case NArchive::NExtract::NOperationResult::kCRCError: 294 case NArchive::NExtract::NOperationResult::kCRCError:
295 #ifndef Z7_SFX
291 messageID = encrypted ? 296 messageID = encrypted ?
292 IDS_EXTRACT_MESSAGE_CRC_ERROR_ENCRYPTED: 297 IDS_EXTRACT_MESSAGE_CRC_ERROR_ENCRYPTED:
293 IDS_EXTRACT_MESSAGE_CRC_ERROR; 298 IDS_EXTRACT_MESSAGE_CRC_ERROR;
299 #endif
294 id = IDS_EXTRACT_MSG_CRC_ERROR; 300 id = IDS_EXTRACT_MSG_CRC_ERROR;
295 break; 301 break;
296 case NArchive::NExtract::NOperationResult::kUnavailable: 302 case NArchive::NExtract::NOperationResult::kUnavailable:
@@ -319,18 +325,19 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam
319 } 325 }
320 326
321 UString msg; 327 UString msg;
322 UString msgOld;
323 328
324 #ifndef _SFX 329 #ifndef Z7_SFX
330 UString msgOld;
331 #ifdef Z7_LANG
325 if (id != 0) 332 if (id != 0)
326 LangString_OnlyFromLangFile(id, msg); 333 LangString_OnlyFromLangFile(id, msg);
327 if (messageID != 0 && msg.IsEmpty()) 334 if (messageID != 0 && msg.IsEmpty())
328 LangString_OnlyFromLangFile(messageID, msgOld); 335 LangString_OnlyFromLangFile(messageID, msgOld);
329 #endif 336 #endif
330
331 if (msg.IsEmpty() && !msgOld.IsEmpty()) 337 if (msg.IsEmpty() && !msgOld.IsEmpty())
332 s = MyFormatNew(msgOld, fileName); 338 s = MyFormatNew(msgOld, fileName);
333 else 339 else
340 #endif
334 { 341 {
335 if (msg.IsEmpty() && id != 0) 342 if (msg.IsEmpty() && id != 0)
336 LangString(id, msg); 343 LangString(id, msg);
@@ -339,7 +346,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam
339 else 346 else
340 { 347 {
341 s += "Error #"; 348 s += "Error #";
342 s.Add_UInt32(opRes); 349 s.Add_UInt32((UInt32)opRes);
343 } 350 }
344 351
345 if (encrypted && opRes != NArchive::NExtract::NOperationResult::kWrongPassword) 352 if (encrypted && opRes != NArchive::NExtract::NOperationResult::kWrongPassword)
@@ -354,7 +361,7 @@ void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileNam
354 } 361 }
355} 362}
356 363
357STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted) 364Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypted))
358{ 365{
359 switch (opRes) 366 switch (opRes)
360 { 367 {
@@ -369,7 +376,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypte
369 } 376 }
370 } 377 }
371 378
372 #ifndef _SFX 379 #ifndef Z7_SFX
373 if (_isFolder) 380 if (_isFolder)
374 NumFolders++; 381 NumFolders++;
375 else 382 else
@@ -380,7 +387,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(Int32 opRes, Int32 encrypte
380 return S_OK; 387 return S_OK;
381} 388}
382 389
383STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name) 390Z7_COM7F_IMF(CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypted, const wchar_t *name))
384{ 391{
385 if (opRes != NArchive::NExtract::NOperationResult::kOK) 392 if (opRes != NArchive::NExtract::NOperationResult::kOK)
386 { 393 {
@@ -397,8 +404,8 @@ STDMETHODIMP CExtractCallbackImp::ReportExtractResult(Int32 opRes, Int32 encrypt
397 404
398HRESULT CExtractCallbackImp::BeforeOpen(const wchar_t *name, bool /* testMode */) 405HRESULT CExtractCallbackImp::BeforeOpen(const wchar_t *name, bool /* testMode */)
399{ 406{
400 #ifndef _SFX 407 #ifndef Z7_SFX
401 RINOK(ProgressDialog->Sync.CheckStop()); 408 RINOK(ProgressDialog->Sync.CheckStop())
402 ProgressDialog->Sync.Set_TitleFileName(name); 409 ProgressDialog->Sync.Set_TitleFileName(name);
403 #endif 410 #endif
404 _currentArchivePath = name; 411 _currentArchivePath = name;
@@ -408,17 +415,17 @@ HRESULT CExtractCallbackImp::BeforeOpen(const wchar_t *name, bool /* testMode */
408HRESULT CExtractCallbackImp::SetCurrentFilePath2(const wchar_t *path) 415HRESULT CExtractCallbackImp::SetCurrentFilePath2(const wchar_t *path)
409{ 416{
410 _currentFilePath = path; 417 _currentFilePath = path;
411 #ifndef _SFX 418 #ifndef Z7_SFX
412 ProgressDialog->Sync.Set_FilePath(path); 419 ProgressDialog->Sync.Set_FilePath(path);
413 #endif 420 #endif
414 return S_OK; 421 return S_OK;
415} 422}
416 423
417#ifndef _SFX 424#ifndef Z7_SFX
418 425
419HRESULT CExtractCallbackImp::SetCurrentFilePath(const wchar_t *path) 426Z7_COM7F_IMF(CExtractCallbackImp::SetCurrentFilePath(const wchar_t *path))
420{ 427{
421 #ifndef _SFX 428 #ifndef Z7_SFX
422 if (NeedAddFile) 429 if (NeedAddFile)
423 NumFiles++; 430 NumFiles++;
424 NeedAddFile = true; 431 NeedAddFile = true;
@@ -457,7 +464,7 @@ UString GetOpenArcErrorMessage(UInt32 errorFlags)
457{ 464{
458 UString s; 465 UString s;
459 466
460 for (unsigned i = 0; i < ARRAY_SIZE(k_ErrorFlagsIds); i++) 467 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_ErrorFlagsIds); i++)
461 { 468 {
462 UInt32 f = ((UInt32)1 << i); 469 UInt32 f = ((UInt32)1 << i);
463 if ((errorFlags & f) == 0) 470 if ((errorFlags & f) == 0)
@@ -649,7 +656,7 @@ HRESULT CExtractCallbackImp::ExtractResult(HRESULT result)
649 return S_OK; 656 return S_OK;
650} 657}
651 658
652#ifndef _NO_CRYPTO 659#ifndef Z7_NO_CRYPTO
653 660
654HRESULT CExtractCallbackImp::SetPassword(const UString &password) 661HRESULT CExtractCallbackImp::SetPassword(const UString &password)
655{ 662{
@@ -658,14 +665,14 @@ HRESULT CExtractCallbackImp::SetPassword(const UString &password)
658 return S_OK; 665 return S_OK;
659} 666}
660 667
661STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password) 668Z7_COM7F_IMF(CExtractCallbackImp::CryptoGetTextPassword(BSTR *password))
662{ 669{
663 PasswordWasAsked = true; 670 PasswordWasAsked = true;
664 if (!PasswordIsDefined) 671 if (!PasswordIsDefined)
665 { 672 {
666 CPasswordDialog dialog; 673 CPasswordDialog dialog;
667 #ifndef _SFX 674 #ifndef Z7_SFX
668 bool showPassword = NExtract::Read_ShowPassword(); 675 const bool showPassword = NExtract::Read_ShowPassword();
669 dialog.ShowPassword = showPassword; 676 dialog.ShowPassword = showPassword;
670 #endif 677 #endif
671 ProgressDialog->WaitCreating(); 678 ProgressDialog->WaitCreating();
@@ -673,7 +680,7 @@ STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password)
673 return E_ABORT; 680 return E_ABORT;
674 Password = dialog.Password; 681 Password = dialog.Password;
675 PasswordIsDefined = true; 682 PasswordIsDefined = true;
676 #ifndef _SFX 683 #ifndef Z7_SFX
677 if (dialog.ShowPassword != showPassword) 684 if (dialog.ShowPassword != showPassword)
678 NExtract::Save_ShowPassword(dialog.ShowPassword); 685 NExtract::Save_ShowPassword(dialog.ShowPassword);
679 #endif 686 #endif
@@ -683,24 +690,24 @@ STDMETHODIMP CExtractCallbackImp::CryptoGetTextPassword(BSTR *password)
683 690
684#endif 691#endif
685 692
686#ifndef _SFX 693#ifndef Z7_SFX
687 694
688STDMETHODIMP CExtractCallbackImp::AskWrite( 695Z7_COM7F_IMF(CExtractCallbackImp::AskWrite(
689 const wchar_t *srcPath, Int32 srcIsFolder, 696 const wchar_t *srcPath, Int32 srcIsFolder,
690 const FILETIME *srcTime, const UInt64 *srcSize, 697 const FILETIME *srcTime, const UInt64 *srcSize,
691 const wchar_t *destPath, 698 const wchar_t *destPath,
692 BSTR *destPathResult, 699 BSTR *destPathResult,
693 Int32 *writeAnswer) 700 Int32 *writeAnswer))
694{ 701{
695 UString destPathResultTemp = destPath; 702 UString destPathResultTemp = destPath;
696 703
697 // RINOK(StringToBstr(destPath, destPathResult)); 704 // RINOK(StringToBstr(destPath, destPathResult));
698 705
699 *destPathResult = 0; 706 *destPathResult = NULL;
700 *writeAnswer = BoolToInt(false); 707 *writeAnswer = BoolToInt(false);
701 708
702 FString destPathSys = us2fs(destPath); 709 FString destPathSys = us2fs(destPath);
703 bool srcIsFolderSpec = IntToBool(srcIsFolder); 710 const bool srcIsFolderSpec = IntToBool(srcIsFolder);
704 CFileInfo destFileInfo; 711 CFileInfo destFileInfo;
705 712
706 if (destFileInfo.Find(destPathSys)) 713 if (destFileInfo.Find(destPathSys))
@@ -709,7 +716,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
709 { 716 {
710 if (!destFileInfo.IsDir()) 717 if (!destFileInfo.IsDir())
711 { 718 {
712 RINOK(MessageError("Cannot replace file with folder with same name", destPathSys)); 719 RINOK(MessageError("Cannot replace file with folder with same name", destPathSys))
713 return E_ABORT; 720 return E_ABORT;
714 } 721 }
715 *writeAnswer = BoolToInt(false); 722 *writeAnswer = BoolToInt(false);
@@ -718,12 +725,12 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
718 725
719 if (destFileInfo.IsDir()) 726 if (destFileInfo.IsDir())
720 { 727 {
721 RINOK(MessageError("Cannot replace folder with file with same name", destPathSys)); 728 RINOK(MessageError("Cannot replace folder with file with same name", destPathSys))
722 *writeAnswer = BoolToInt(false); 729 *writeAnswer = BoolToInt(false);
723 return S_OK; 730 return S_OK;
724 } 731 }
725 732
726 switch (OverwriteMode) 733 switch ((int)OverwriteMode)
727 { 734 {
728 case NExtract::NOverwriteMode::kSkip: 735 case NExtract::NOverwriteMode::kSkip:
729 return S_OK; 736 return S_OK;
@@ -731,7 +738,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
731 { 738 {
732 Int32 overwriteResult; 739 Int32 overwriteResult;
733 UString destPathSpec = destPath; 740 UString destPathSpec = destPath;
734 int slashPos = destPathSpec.ReverseFind_PathSepar(); 741 const int slashPos = destPathSpec.ReverseFind_PathSepar();
735 destPathSpec.DeleteFrom((unsigned)(slashPos + 1)); 742 destPathSpec.DeleteFrom((unsigned)(slashPos + 1));
736 destPathSpec += fs2us(destFileInfo.Name); 743 destPathSpec += fs2us(destFileInfo.Name);
737 744
@@ -740,7 +747,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
740 &destFileInfo.MTime, &destFileInfo.Size, 747 &destFileInfo.MTime, &destFileInfo.Size,
741 srcPath, 748 srcPath,
742 srcTime, srcSize, 749 srcTime, srcSize,
743 &overwriteResult)); 750 &overwriteResult))
744 751
745 switch (overwriteResult) 752 switch (overwriteResult)
746 { 753 {
@@ -763,7 +770,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
763 { 770 {
764 if (!AutoRenamePath(destPathSys)) 771 if (!AutoRenamePath(destPathSys))
765 { 772 {
766 RINOK(MessageError("Cannot create name for file", destPathSys)); 773 RINOK(MessageError("Cannot create name for file", destPathSys))
767 return E_ABORT; 774 return E_ABORT;
768 } 775 }
769 destPathResultTemp = fs2us(destPathSys); 776 destPathResultTemp = fs2us(destPathSys);
@@ -774,7 +781,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
774 if (!NDir::DeleteFileAlways(destPathSys)) 781 if (!NDir::DeleteFileAlways(destPathSys))
775 if (GetLastError() != ERROR_FILE_NOT_FOUND) 782 if (GetLastError() != ERROR_FILE_NOT_FOUND)
776 { 783 {
777 RINOK(MessageError("Cannot delete output file", destPathSys)); 784 RINOK(MessageError("Cannot delete output file", destPathSys))
778 return E_ABORT; 785 return E_ABORT;
779 } 786 }
780 } 787 }
@@ -784,7 +791,7 @@ STDMETHODIMP CExtractCallbackImp::AskWrite(
784} 791}
785 792
786 793
787STDMETHODIMP CExtractCallbackImp::UseExtractToStream(Int32 *res) 794Z7_COM7F_IMF(CExtractCallbackImp::UseExtractToStream(Int32 *res))
788{ 795{
789 *res = BoolToInt(StreamMode); 796 *res = BoolToInt(StreamMode);
790 return S_OK; 797 return S_OK;
@@ -794,7 +801,7 @@ static HRESULT GetTime(IGetProp *getProp, PROPID propID, FILETIME &ft, bool &ftD
794{ 801{
795 ftDefined = false; 802 ftDefined = false;
796 NCOM::CPropVariant prop; 803 NCOM::CPropVariant prop;
797 RINOK(getProp->GetProp(propID, &prop)); 804 RINOK(getProp->GetProp(propID, &prop))
798 if (prop.vt == VT_FILETIME) 805 if (prop.vt == VT_FILETIME)
799 { 806 {
800 ft = prop.filetime; 807 ft = prop.filetime;
@@ -810,7 +817,7 @@ static HRESULT GetItemBoolProp(IGetProp *getProp, PROPID propID, bool &result)
810{ 817{
811 NCOM::CPropVariant prop; 818 NCOM::CPropVariant prop;
812 result = false; 819 result = false;
813 RINOK(getProp->GetProp(propID, &prop)); 820 RINOK(getProp->GetProp(propID, &prop))
814 if (prop.vt == VT_BOOL) 821 if (prop.vt == VT_BOOL)
815 result = VARIANT_BOOLToBool(prop.boolVal); 822 result = VARIANT_BOOLToBool(prop.boolVal);
816 else if (prop.vt != VT_EMPTY) 823 else if (prop.vt != VT_EMPTY)
@@ -819,13 +826,13 @@ static HRESULT GetItemBoolProp(IGetProp *getProp, PROPID propID, bool &result)
819} 826}
820 827
821 828
822STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name, 829Z7_COM7F_IMF(CExtractCallbackImp::GetStream7(const wchar_t *name,
823 Int32 isDir, 830 Int32 isDir,
824 ISequentialOutStream **outStream, Int32 askExtractMode, 831 ISequentialOutStream **outStream, Int32 askExtractMode,
825 IGetProp *getProp) 832 IGetProp *getProp))
826{ 833{
827 COM_TRY_BEGIN 834 COM_TRY_BEGIN
828 *outStream = 0; 835 *outStream = NULL;
829 _newVirtFileWasAdded = false; 836 _newVirtFileWasAdded = false;
830 _hashStreamWasUsed = false; 837 _hashStreamWasUsed = false;
831 _needUpdateStat = false; 838 _needUpdateStat = false;
@@ -841,20 +848,20 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name,
841 _filePath = name; 848 _filePath = name;
842 _isFolder = IntToBool(isDir); 849 _isFolder = IntToBool(isDir);
843 _curSize = 0; 850 _curSize = 0;
844 _curSizeDefined = false; 851 _curSize_Defined = false;
845 852
846 UInt64 size = 0; 853 UInt64 size = 0;
847 bool sizeDefined; 854 bool sizeDefined;
848 { 855 {
849 NCOM::CPropVariant prop; 856 NCOM::CPropVariant prop;
850 RINOK(getProp->GetProp(kpidSize, &prop)); 857 RINOK(getProp->GetProp(kpidSize, &prop))
851 sizeDefined = ConvertPropVariantToUInt64(prop, size); 858 sizeDefined = ConvertPropVariantToUInt64(prop, size);
852 } 859 }
853 860
854 if (sizeDefined) 861 if (sizeDefined)
855 { 862 {
856 _curSize = size; 863 _curSize = size;
857 _curSizeDefined = true; 864 _curSize_Defined = true;
858 } 865 }
859 866
860 if (askExtractMode != NArchive::NExtract::NAskMode::kExtract && 867 if (askExtractMode != NArchive::NExtract::NAskMode::kExtract &&
@@ -874,12 +881,12 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name,
874 file.IsAltStream = _isAltStream; 881 file.IsAltStream = _isAltStream;
875 file.Size = 0; 882 file.Size = 0;
876 883
877 RINOK(GetTime(getProp, kpidCTime, file.CTime, file.CTimeDefined)); 884 RINOK(GetTime(getProp, kpidCTime, file.CTime, file.CTimeDefined))
878 RINOK(GetTime(getProp, kpidATime, file.ATime, file.ATimeDefined)); 885 RINOK(GetTime(getProp, kpidATime, file.ATime, file.ATimeDefined))
879 RINOK(GetTime(getProp, kpidMTime, file.MTime, file.MTimeDefined)); 886 RINOK(GetTime(getProp, kpidMTime, file.MTime, file.MTimeDefined))
880 887
881 NCOM::CPropVariant prop; 888 NCOM::CPropVariant prop;
882 RINOK(getProp->GetProp(kpidAttrib, &prop)); 889 RINOK(getProp->GetProp(kpidAttrib, &prop))
883 if (prop.vt == VT_UI4) 890 if (prop.vt == VT_UI4)
884 { 891 {
885 file.Attrib = prop.ulVal; 892 file.Attrib = prop.ulVal;
@@ -909,7 +916,7 @@ STDMETHODIMP CExtractCallbackImp::GetStream7(const wchar_t *name,
909 COM_TRY_END 916 COM_TRY_END
910} 917}
911 918
912STDMETHODIMP CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode) 919Z7_COM7F_IMF(CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode))
913{ 920{
914 COM_TRY_BEGIN 921 COM_TRY_BEGIN
915 _needUpdateStat = ( 922 _needUpdateStat = (
@@ -934,21 +941,21 @@ STDMETHODIMP CExtractCallbackImp::PrepareOperation7(Int32 askExtractMode)
934 COM_TRY_END 941 COM_TRY_END
935} 942}
936 943
937STDMETHODIMP CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypted, UInt64 size) 944Z7_COM7F_IMF(CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypted, UInt64 size))
938{ 945{
939 COM_TRY_BEGIN 946 COM_TRY_BEGIN
940 if (VirtFileSystem && _newVirtFileWasAdded) 947 if (VirtFileSystem && _newVirtFileWasAdded)
941 { 948 {
942 // FIXME: probably we must request file size from VirtFileSystem 949 // FIXME: probably we must request file size from VirtFileSystem
943 // _curSize = VirtFileSystem->GetLastFileSize() 950 // _curSize = VirtFileSystem->GetLastFileSize()
944 // _curSizeDefined = true; 951 // _curSize_Defined = true;
945 RINOK(VirtFileSystemSpec->CloseMemFile()); 952 RINOK(VirtFileSystemSpec->CloseMemFile())
946 } 953 }
947 if (_hashStream && _hashStreamWasUsed) 954 if (_hashStream && _hashStreamWasUsed)
948 { 955 {
949 _hashStreamSpec->_hash->Final(_isFolder, _isAltStream, _filePath); 956 _hashStreamSpec->_hash->Final(_isFolder, _isAltStream, _filePath);
950 _curSize = _hashStreamSpec->GetSize(); 957 _curSize = _hashStreamSpec->GetSize();
951 _curSizeDefined = true; 958 _curSize_Defined = true;
952 _hashStreamSpec->ReleaseStream(); 959 _hashStreamSpec->ReleaseStream();
953 _hashStreamWasUsed = false; 960 _hashStreamWasUsed = false;
954 } 961 }
@@ -965,7 +972,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult8(Int32 opRes, Int32 encrypt
965 972
966// static const UInt32 kBlockSize = ((UInt32)1 << 31); 973// static const UInt32 kBlockSize = ((UInt32)1 << 31);
967 974
968STDMETHODIMP CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *processedSize) 975Z7_COM7F_IMF(CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *processedSize))
969{ 976{
970 if (processedSize) 977 if (processedSize)
971 *processedSize = 0; 978 *processedSize = 0;
@@ -1002,7 +1009,7 @@ STDMETHODIMP CVirtFileSystem::Write(const void *data, UInt32 size, UInt32 *proce
1002 } 1009 }
1003 _fileMode = true; 1010 _fileMode = true;
1004 } 1011 }
1005 RINOK(FlushToDisk(false)); 1012 RINOK(FlushToDisk(false))
1006 return _outFileStream->Write(data, size, processedSize); 1013 return _outFileStream->Write(data, size, processedSize);
1007} 1014}
1008 1015
@@ -1026,7 +1033,7 @@ HRESULT CVirtFileSystem::FlushToDisk(bool closeLast)
1026 // MessageBoxMyError(UString("Can't create file ") + fs2us(tempFilePath)); 1033 // MessageBoxMyError(UString("Can't create file ") + fs2us(tempFilePath));
1027 } 1034 }
1028 _fileIsOpen = true; 1035 _fileIsOpen = true;
1029 RINOK(WriteStream(_outFileStream, file.Data, (size_t)file.Size)); 1036 RINOK(WriteStream(_outFileStream, file.Data, (size_t)file.Size))
1030 } 1037 }
1031 if (_numFlushed == Files.Size() - 1 && !closeLast) 1038 if (_numFlushed == Files.Size() - 1 && !closeLast)
1032 break; 1039 break;
diff --git a/CPP/7zip/UI/FileManager/ExtractCallback.h b/CPP/7zip/UI/FileManager/ExtractCallback.h
index 02578bb..c2aa470 100644
--- a/CPP/7zip/UI/FileManager/ExtractCallback.h
+++ b/CPP/7zip/UI/FileManager/ExtractCallback.h
@@ -1,42 +1,42 @@
1// ExtractCallback.h 1// ExtractCallback.h
2 2
3#ifndef __EXTRACT_CALLBACK_H 3#ifndef ZIP7_INC_EXTRACT_CALLBACK_H
4#define __EXTRACT_CALLBACK_H 4#define ZIP7_INC_EXTRACT_CALLBACK_H
5 5
6#include "../../../../C/Alloc.h" 6#include "../../../../C/Alloc.h"
7 7
8#include "../../../Common/MyCom.h" 8#include "../../../Common/MyCom.h"
9#include "../../../Common/StringConvert.h" 9#include "../../../Common/StringConvert.h"
10 10
11#ifndef _SFX 11#ifndef Z7_SFX
12#include "../Agent/IFolderArchive.h" 12#include "../Agent/IFolderArchive.h"
13#endif 13#endif
14 14
15#include "../Common/ArchiveExtractCallback.h" 15#include "../Common/ArchiveExtractCallback.h"
16#include "../Common/ArchiveOpenCallback.h" 16#include "../Common/ArchiveOpenCallback.h"
17 17
18#ifndef _NO_CRYPTO 18#ifndef Z7_NO_CRYPTO
19#include "../../IPassword.h" 19#include "../../IPassword.h"
20#endif 20#endif
21 21
22#ifndef _SFX 22#ifndef Z7_SFX
23#include "IFolder.h" 23#include "IFolder.h"
24#endif 24#endif
25 25
26#include "ProgressDialog2.h" 26#include "ProgressDialog2.h"
27 27
28#ifdef LANG 28#ifdef Z7_LANG
29#include "LangUtils.h" 29// #include "LangUtils.h"
30#endif 30#endif
31 31
32#ifndef _SFX 32#ifndef Z7_SFX
33 33
34class CGrowBuf 34class CGrowBuf
35{ 35{
36 Byte *_items; 36 Byte *_items;
37 size_t _size; 37 size_t _size;
38 38
39 CLASS_NO_COPY(CGrowBuf); 39 Z7_CLASS_NO_COPY(CGrowBuf)
40 40
41public: 41public:
42 bool ReAlloc_KeepData(size_t newSize, size_t keepSize) 42 bool ReAlloc_KeepData(size_t newSize, size_t keepSize)
@@ -52,7 +52,7 @@ public:
52 return true; 52 return true;
53 } 53 }
54 54
55 CGrowBuf(): _items(0), _size(0) {} 55 CGrowBuf(): _items(NULL), _size(0) {}
56 ~CGrowBuf() { MyFree(_items); } 56 ~CGrowBuf() { MyFree(_items); }
57 57
58 operator Byte *() { return _items; } 58 operator Byte *() { return _items; }
@@ -92,10 +92,11 @@ struct CVirtFile
92 IsAltStream(false) {} 92 IsAltStream(false) {}
93}; 93};
94 94
95class CVirtFileSystem: 95
96 public ISequentialOutStream, 96Z7_CLASS_IMP_NOQIB_1(
97 public CMyUnknownImp 97 CVirtFileSystem,
98{ 98 ISequentialOutStream
99)
99 UInt64 _totalAllocSize; 100 UInt64 _totalAllocSize;
100 101
101 size_t _pos; 102 size_t _pos;
@@ -156,104 +157,86 @@ public:
156 HRESULT CloseFile(const FString &path); 157 HRESULT CloseFile(const FString &path);
157 HRESULT FlushToDisk(bool closeLast); 158 HRESULT FlushToDisk(bool closeLast);
158 size_t GetPos() const { return _pos; } 159 size_t GetPos() const { return _pos; }
159
160 MY_UNKNOWN_IMP
161 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
162}; 160};
163 161
164#endif 162#endif
165 163
166class CExtractCallbackImp: 164class CExtractCallbackImp Z7_final:
167 public IExtractCallbackUI, // it includes IFolderArchiveExtractCallback 165 public IFolderArchiveExtractCallback,
168 public IOpenCallbackUI, 166 /* IExtractCallbackUI:
167 before v23.00 : it included IFolderArchiveExtractCallback
168 since v23.00 : it doesn't include IFolderArchiveExtractCallback
169 */
170 public IExtractCallbackUI, // NON-COM interface since 23.00
171 public IOpenCallbackUI, // NON-COM interface
169 public IFolderArchiveExtractCallback2, 172 public IFolderArchiveExtractCallback2,
170 #ifndef _SFX 173 #ifndef Z7_SFX
171 public IFolderOperationsExtractCallback, 174 public IFolderOperationsExtractCallback,
172 public IFolderExtractToStreamCallback, 175 public IFolderExtractToStreamCallback,
173 public ICompressProgressInfo, 176 public ICompressProgressInfo,
174 #endif 177 #endif
175 #ifndef _NO_CRYPTO 178 #ifndef Z7_NO_CRYPTO
176 public ICryptoGetTextPassword, 179 public ICryptoGetTextPassword,
177 #endif 180 #endif
178 public CMyUnknownImp 181 public CMyUnknownImp
179{ 182{
180 HRESULT MessageError(const char *message, const FString &path); 183 Z7_COM_QI_BEGIN2(IFolderArchiveExtractCallback)
181 void Add_ArchiveName_Error(); 184 Z7_COM_QI_ENTRY(IFolderArchiveExtractCallback2)
182public: 185 #ifndef Z7_SFX
183 MY_QUERYINTERFACE_BEGIN2(IFolderArchiveExtractCallback) 186 Z7_COM_QI_ENTRY(IFolderOperationsExtractCallback)
184 MY_QUERYINTERFACE_ENTRY(IFolderArchiveExtractCallback2) 187 Z7_COM_QI_ENTRY(IFolderExtractToStreamCallback)
185 #ifndef _SFX 188 Z7_COM_QI_ENTRY(ICompressProgressInfo)
186 MY_QUERYINTERFACE_ENTRY(IFolderOperationsExtractCallback) 189 #endif
187 MY_QUERYINTERFACE_ENTRY(IFolderExtractToStreamCallback) 190 #ifndef Z7_NO_CRYPTO
188 MY_QUERYINTERFACE_ENTRY(ICompressProgressInfo) 191 Z7_COM_QI_ENTRY(ICryptoGetTextPassword)
189 #endif 192 #endif
190 #ifndef _NO_CRYPTO 193 Z7_COM_QI_END
191 MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) 194 Z7_COM_ADDREF_RELEASE
192 #endif 195
193 MY_QUERYINTERFACE_END 196 Z7_IFACE_IMP(IExtractCallbackUI)
194 MY_ADDREF_RELEASE 197 Z7_IFACE_IMP(IOpenCallbackUI)
195 198 Z7_IFACE_COM7_IMP(IProgress)
196 INTERFACE_IProgress(;) 199 Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback)
197 INTERFACE_IOpenCallbackUI(;) 200 Z7_IFACE_COM7_IMP(IFolderArchiveExtractCallback2)
198 INTERFACE_IFolderArchiveExtractCallback(;) 201 #ifndef Z7_SFX
199 INTERFACE_IFolderArchiveExtractCallback2(;) 202 Z7_IFACE_COM7_IMP(IFolderOperationsExtractCallback)
200 // STDMETHOD(SetTotalFiles)(UInt64 total); 203 Z7_IFACE_COM7_IMP(IFolderExtractToStreamCallback)
201 // STDMETHOD(SetCompletedFiles)(const UInt64 *value); 204 Z7_IFACE_COM7_IMP(ICompressProgressInfo)
202 205 #endif
203 INTERFACE_IExtractCallbackUI(;) 206 #ifndef Z7_NO_CRYPTO
204 207 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
205 #ifndef _SFX 208 #endif
206 // IFolderOperationsExtractCallback
207 STDMETHOD(AskWrite)(
208 const wchar_t *srcPath,
209 Int32 srcIsFolder,
210 const FILETIME *srcTime,
211 const UInt64 *srcSize,
212 const wchar_t *destPathRequest,
213 BSTR *destPathResult,
214 Int32 *writeAnswer);
215 STDMETHOD(ShowMessage)(const wchar_t *message);
216 STDMETHOD(SetCurrentFilePath)(const wchar_t *filePath);
217 STDMETHOD(SetNumFiles)(UInt64 numFiles);
218 INTERFACE_IFolderExtractToStreamCallback(;)
219 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
220 #endif
221 209
222 // ICryptoGetTextPassword
223 #ifndef _NO_CRYPTO
224 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
225 #endif
226 210
227private:
228 UString _currentArchivePath; 211 UString _currentArchivePath;
229 bool _needWriteArchivePath; 212 bool _needWriteArchivePath;
230 213
231 UString _currentFilePath;
232 bool _isFolder; 214 bool _isFolder;
215 UString _currentFilePath;
216 UString _filePath;
233 217
218 #ifndef Z7_SFX
219 bool _needUpdateStat;
220 bool _newVirtFileWasAdded;
234 bool _isAltStream; 221 bool _isAltStream;
222 bool _curSize_Defined;
235 UInt64 _curSize; 223 UInt64 _curSize;
236 bool _curSizeDefined;
237 UString _filePath;
238 // bool _extractMode; 224 // bool _extractMode;
239 // bool _testMode; 225 // bool _testMode;
240 bool _newVirtFileWasAdded;
241 bool _needUpdateStat;
242
243
244 HRESULT SetCurrentFilePath2(const wchar_t *filePath);
245 void AddError_Message(LPCWSTR message);
246
247 #ifndef _SFX
248 bool _hashStreamWasUsed; 226 bool _hashStreamWasUsed;
249 COutStreamWithHash *_hashStreamSpec; 227 COutStreamWithHash *_hashStreamSpec;
250 CMyComPtr<ISequentialOutStream> _hashStream; 228 CMyComPtr<ISequentialOutStream> _hashStream;
251 IHashCalc *_hashCalc; // it's for stat in Test operation 229 IHashCalc *_hashCalc; // it's for stat in Test operation
252 #endif 230 #endif
231
232 HRESULT SetCurrentFilePath2(const wchar_t *filePath);
233 void AddError_Message(LPCWSTR message);
234 HRESULT MessageError(const char *message, const FString &path);
235 void Add_ArchiveName_Error();
253 236
254public: 237public:
255 238
256 #ifndef _SFX 239 #ifndef Z7_SFX
257 CVirtFileSystem *VirtFileSystemSpec; 240 CVirtFileSystem *VirtFileSystemSpec;
258 CMyComPtr<ISequentialOutStream> VirtFileSystem; 241 CMyComPtr<ISequentialOutStream> VirtFileSystem;
259 #endif 242 #endif
@@ -263,7 +246,7 @@ public:
263 bool StreamMode; 246 bool StreamMode;
264 247
265 CProgressDialog *ProgressDialog; 248 CProgressDialog *ProgressDialog;
266 #ifndef _SFX 249 #ifndef Z7_SFX
267 UInt64 NumFolders; 250 UInt64 NumFolders;
268 UInt64 NumFiles; 251 UInt64 NumFiles;
269 bool NeedAddFile; 252 bool NeedAddFile;
@@ -272,7 +255,7 @@ public:
272 bool ThereAreMessageErrors; 255 bool ThereAreMessageErrors;
273 NExtract::NOverwriteMode::EEnum OverwriteMode; 256 NExtract::NOverwriteMode::EEnum OverwriteMode;
274 257
275 #ifndef _NO_CRYPTO 258 #ifndef Z7_NO_CRYPTO
276 bool PasswordIsDefined; 259 bool PasswordIsDefined;
277 bool PasswordWasAsked; 260 bool PasswordWasAsked;
278 UString Password; 261 UString Password;
@@ -290,13 +273,13 @@ public:
290 bool MultiArcMode; 273 bool MultiArcMode;
291 274
292 CExtractCallbackImp(): 275 CExtractCallbackImp():
293 #ifndef _SFX 276 #ifndef Z7_SFX
294 _hashCalc(NULL), 277 _hashCalc(NULL),
295 #endif 278 #endif
296 ProcessAltStreams(true), 279 ProcessAltStreams(true),
297 StreamMode(false), 280 StreamMode(false),
298 OverwriteMode(NExtract::NOverwriteMode::kAsk), 281 OverwriteMode(NExtract::NOverwriteMode::kAsk),
299 #ifndef _NO_CRYPTO 282 #ifndef Z7_NO_CRYPTO
300 PasswordIsDefined(false), 283 PasswordIsDefined(false),
301 PasswordWasAsked(false), 284 PasswordWasAsked(false),
302 #endif 285 #endif
@@ -308,7 +291,7 @@ public:
308 ~CExtractCallbackImp(); 291 ~CExtractCallbackImp();
309 void Init(); 292 void Init();
310 293
311 #ifndef _SFX 294 #ifndef Z7_SFX
312 void SetHashCalc(IHashCalc *hashCalc) { _hashCalc = hashCalc; } 295 void SetHashCalc(IHashCalc *hashCalc) { _hashCalc = hashCalc; }
313 296
314 void SetHashMethods(IHashCalc *hash) 297 void SetHashMethods(IHashCalc *hash)
diff --git a/CPP/7zip/UI/FileManager/FM.cpp b/CPP/7zip/UI/FileManager/FM.cpp
index 812eff6..13189a7 100644
--- a/CPP/7zip/UI/FileManager/FM.cpp
+++ b/CPP/7zip/UI/FileManager/FM.cpp
@@ -4,8 +4,13 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#if defined(__MINGW32__) || defined(__MINGW64__)
8#include <shlwapi.h>
9#else
7#include <Shlwapi.h> 10#include <Shlwapi.h>
11#endif
8 12
13#include "../../../../C/Compiler.h"
9#include "../../../../C/Alloc.h" 14#include "../../../../C/Alloc.h"
10#ifdef _WIN32 15#ifdef _WIN32
11#include "../../../../C/DllSecur.h" 16#include "../../../../C/DllSecur.h"
@@ -46,7 +51,9 @@ extern
46bool g_RAM_Size_Defined; 51bool g_RAM_Size_Defined;
47bool g_RAM_Size_Defined; 52bool g_RAM_Size_Defined;
48 53
49static bool g_LargePagesMode = false; 54extern
55bool g_LargePagesMode;
56bool g_LargePagesMode = false;
50// static bool g_OpenArchive = false; 57// static bool g_OpenArchive = false;
51 58
52static bool g_Maximized = false; 59static bool g_Maximized = false;
@@ -78,20 +85,23 @@ DWORD g_ComCtl32Version;
78static DWORD GetDllVersion(LPCTSTR dllName) 85static DWORD GetDllVersion(LPCTSTR dllName)
79{ 86{
80 DWORD dwVersion = 0; 87 DWORD dwVersion = 0;
81 HINSTANCE hinstDll = LoadLibrary(dllName); 88 const HMODULE hmodule = LoadLibrary(dllName);
82 if (hinstDll) 89 if (hmodule)
83 { 90 {
84 DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)(void *)GetProcAddress(hinstDll, "DllGetVersion"); 91 const
85 if (pDllGetVersion) 92 DLLGETVERSIONPROC f_DllGetVersion = Z7_GET_PROC_ADDRESS(
93 DLLGETVERSIONPROC, hmodule,
94 "DllGetVersion");
95 if (f_DllGetVersion)
86 { 96 {
87 DLLVERSIONINFO dvi; 97 DLLVERSIONINFO dvi;
88 ZeroMemory(&dvi, sizeof(dvi)); 98 ZeroMemory(&dvi, sizeof(dvi));
89 dvi.cbSize = sizeof(dvi); 99 dvi.cbSize = sizeof(dvi);
90 HRESULT hr = (*pDllGetVersion)(&dvi); 100 const HRESULT hr = f_DllGetVersion(&dvi);
91 if (SUCCEEDED(hr)) 101 if (SUCCEEDED(hr))
92 dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); 102 dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion);
93 } 103 }
94 FreeLibrary(hinstDll); 104 FreeLibrary(hmodule);
95 } 105 }
96 return dwVersion; 106 return dwVersion;
97} 107}
@@ -180,7 +190,7 @@ CApp g_App;
180 190
181LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); 191LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
182 192
183static const wchar_t * const kWindowClass = L"FM"; 193static const wchar_t * const kWindowClass = L"7-Zip::FM";
184 194
185#ifdef UNDER_CE 195#ifdef UNDER_CE
186#define WS_OVERLAPPEDWINDOW ( \ 196#define WS_OVERLAPPEDWINDOW ( \
@@ -222,7 +232,7 @@ static BOOL InitInstance(int nCmdShow)
222 wc.hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON)); 232 wc.hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON));
223 233
224 // wc.hCursor = LoadCursor (NULL, IDC_ARROW); 234 // wc.hCursor = LoadCursor (NULL, IDC_ARROW);
225 wc.hCursor = ::LoadCursor(0, IDC_SIZEWE); 235 wc.hCursor = ::LoadCursor(NULL, IDC_SIZEWE);
226 // wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); 236 // wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
227 wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); 237 wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
228 238
@@ -236,7 +246,8 @@ static BOOL InitInstance(int nCmdShow)
236 246
237 wc.lpszClassName = kWindowClass; 247 wc.lpszClassName = kWindowClass;
238 248
239 MyRegisterClass(&wc); 249 if (MyRegisterClass(&wc) == 0)
250 return FALSE;
240 251
241 // RECT rect; 252 // RECT rect;
242 // GetClientRect(hWnd, &rect); 253 // GetClientRect(hWnd, &rect);
@@ -305,7 +316,7 @@ static BOOL InitInstance(int nCmdShow)
305 { 316 {
306 if (windowPosIsRead) 317 if (windowPosIsRead)
307 placement.rcNormalPosition = info.rect; 318 placement.rcNormalPosition = info.rect;
308 placement.showCmd = nCmdShow; 319 placement.showCmd = (UINT)nCmdShow;
309 wnd.SetPlacement(&placement); 320 wnd.SetPlacement(&placement);
310 } 321 }
311 else 322 else
@@ -343,6 +354,8 @@ static void GetCommands(const UString &aCommandLine, UString &aCommands)
343 354
344#if defined(_WIN32) && !defined(_WIN64) && !defined(UNDER_CE) 355#if defined(_WIN32) && !defined(_WIN64) && !defined(UNDER_CE)
345 356
357extern
358bool g_Is_Wow64;
346bool g_Is_Wow64; 359bool g_Is_Wow64;
347 360
348typedef BOOL (WINAPI *Func_IsWow64Process)(HANDLE, PBOOL); 361typedef BOOL (WINAPI *Func_IsWow64Process)(HANDLE, PBOOL);
@@ -350,18 +363,27 @@ typedef BOOL (WINAPI *Func_IsWow64Process)(HANDLE, PBOOL);
350static void Set_Wow64() 363static void Set_Wow64()
351{ 364{
352 g_Is_Wow64 = false; 365 g_Is_Wow64 = false;
353 Func_IsWow64Process fnIsWow64Process = (Func_IsWow64Process)(void *)GetProcAddress( 366 const
354 GetModuleHandleA("kernel32.dll"), "IsWow64Process"); 367 Func_IsWow64Process fn = Z7_GET_PROC_ADDRESS(
355 if (fnIsWow64Process) 368 Func_IsWow64Process, GetModuleHandleA("kernel32.dll"),
369 "IsWow64Process");
370 if (fn)
356 { 371 {
357 BOOL isWow; 372 BOOL isWow;
358 if (fnIsWow64Process(GetCurrentProcess(), &isWow)) 373 if (fn(GetCurrentProcess(), &isWow))
359 g_Is_Wow64 = (isWow != FALSE); 374 g_Is_Wow64 = (isWow != FALSE);
360 } 375 }
361} 376}
362 377
363#endif 378#endif
364 379
380#if _MSC_VER > 1400 /* && _MSC_VER <= 1900 */
381 // GetVersion was declared deprecated
382 #pragma warning(disable : 4996)
383#endif
384#ifdef __clang__
385 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
386#endif
365 387
366bool IsLargePageSupported(); 388bool IsLargePageSupported();
367bool IsLargePageSupported() 389bool IsLargePageSupported()
@@ -369,18 +391,17 @@ bool IsLargePageSupported()
369 #ifdef _WIN64 391 #ifdef _WIN64
370 return true; 392 return true;
371 #else 393 #else
372 OSVERSIONINFO vi; 394
373 vi.dwOSVersionInfoSize = sizeof(vi); 395 DWORD v = GetVersion();
374 if (!::GetVersionEx(&vi)) 396 // low byte is major version:
375 return false; 397 // next byte is minor version:
376 if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT) 398 v = ((v & 0xff) << 8) | ((v >> 8) & 0xFF);
377 return false; 399 return (v > 0x501);
378 if (vi.dwMajorVersion < 5) return false; 400 // if ((Byte)v < 5) return false;
379 if (vi.dwMajorVersion > 5) return true; 401 // if ((Byte)v > 5) return true;
380 if (vi.dwMinorVersion < 1) return false; 402 // return ((Byte)(v >> 8) > 1);
381 if (vi.dwMinorVersion > 1) return true; 403 /* large pages work in 5.1 (XP-32bit) if it's (g_Is_Wow64) mode;
382 // return g_Is_Wow64; 404 but here we don't enable them in (XP-32bit). */
383 return false;
384 #endif 405 #endif
385} 406}
386 407
@@ -407,12 +428,10 @@ bool g_SymLink_Supported = false;
407 428
408static void Set_SymLink_Supported() 429static void Set_SymLink_Supported()
409{ 430{
410 g_SymLink_Supported = false; 431 // g_SymLink_Supported = false;
411 OSVERSIONINFO vi; 432 const DWORD v = GetVersion();
412 vi.dwOSVersionInfoSize = sizeof(vi); 433 // low byte is major version:
413 if (!::GetVersionEx(&vi)) 434 if ((Byte)v < 6)
414 return;
415 if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT || vi.dwMajorVersion < 6)
416 return; 435 return;
417 g_SymLink_Supported = true; 436 g_SymLink_Supported = true;
418 // if (g_SymLink_Supported) 437 // if (g_SymLink_Supported)
@@ -444,7 +463,7 @@ static const CSwitchForm kSwitchForms[kNumSwitches] =
444 463
445static void ErrorMessage(const wchar_t *s) 464static void ErrorMessage(const wchar_t *s)
446{ 465{
447 MessageBoxW(0, s, L"7-Zip", MB_ICONERROR); 466 MessageBoxW(NULL, s, L"7-Zip", MB_ICONERROR);
448} 467}
449 468
450static void ErrorMessage(const char *s) 469static void ErrorMessage(const char *s)
@@ -488,11 +507,15 @@ static int WINAPI WinMain2(int nCmdShow)
488 */ 507 */
489 508
490 NT_CHECK 509 NT_CHECK
510 #ifdef Z7_LARGE_PAGES
491 SetLargePageSize(); 511 SetLargePageSize();
512 #endif
492 513
493 #endif 514 #endif
494 515
516 #ifdef Z7_LANG
495 LoadLangOneTime(); 517 LoadLangOneTime();
518 #endif
496 519
497 InitCommonControls(); 520 InitCommonControls();
498 521
@@ -516,7 +539,7 @@ static int WINAPI WinMain2(int nCmdShow)
516 // NCOM::CComInitializer comInitializer; 539 // NCOM::CComInitializer comInitializer;
517 540
518 UString commandsString; 541 UString commandsString;
519 // MessageBoxW(0, GetCommandLineW(), L"", 0); 542 // MessageBoxW(NULL, GetCommandLineW(), L"", 0);
520 543
521 #ifdef UNDER_CE 544 #ifdef UNDER_CE
522 commandsString = GetCommandLineW(); 545 commandsString = GetCommandLineW();
@@ -577,7 +600,7 @@ static int WINAPI WinMain2(int nCmdShow)
577 g_MainPath = paramString; 600 g_MainPath = paramString;
578 // return WinMain2(hInstance, hPrevInstance, lpCmdLine, nCmdShow); 601 // return WinMain2(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
579 602
580 // MessageBoxW(0, paramString, L"", 0); 603 // MessageBoxW(NULL, paramString, L"", 0);
581 } 604 }
582 /* 605 /*
583 UStringVector commandStrings; 606 UStringVector commandStrings;
@@ -608,7 +631,7 @@ static int WINAPI WinMain2(int nCmdShow)
608 Set_SymLink_Supported(); 631 Set_SymLink_Supported();
609 #endif 632 #endif
610 633
611 g_App.ReloadLang(); 634 g_App.ReloadLangItems();
612 635
613 MSG msg; 636 MSG msg;
614 if (!InitInstance (nCmdShow)) 637 if (!InitInstance (nCmdShow))
@@ -654,7 +677,7 @@ static int WINAPI WinMain2(int nCmdShow)
654 // But we suppose that it's better to release DLLs here (before destructor). 677 // But we suppose that it's better to release DLLs here (before destructor).
655 FreeGlobalCodecs(); 678 FreeGlobalCodecs();
656 679
657 g_HWND = 0; 680 g_HWND = NULL;
658 #ifndef UNDER_CE 681 #ifndef UNDER_CE
659 OleUninitialize(); 682 OleUninitialize();
660 #endif 683 #endif
@@ -714,7 +737,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
714 catch(int v) 737 catch(int v)
715 { 738 {
716 AString e ("Error: "); 739 AString e ("Error: ");
717 e.Add_UInt32(v); 740 e.Add_UInt32((unsigned)v);
718 ErrorMessage(e); 741 ErrorMessage(e);
719 return 1; 742 return 1;
720 } 743 }
@@ -748,7 +771,7 @@ static void SaveWindowInfo(HWND aWnd)
748 771
749 info.numPanels = g_App.NumPanels; 772 info.numPanels = g_App.NumPanels;
750 info.currentPanel = g_App.LastFocusedPanel; 773 info.currentPanel = g_App.LastFocusedPanel;
751 info.splitterPos = g_Splitter.GetPos(); 774 info.splitterPos = (unsigned)g_Splitter.GetPos();
752 775
753 info.Save(); 776 info.Save();
754} 777}
@@ -825,23 +848,23 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
825 WS_CHILD | WS_BORDER | WS_VISIBLE | TBSTYLE_TOOLTIPS, // | TBSTYLE_FLAT 848 WS_CHILD | WS_BORDER | WS_VISIBLE | TBSTYLE_TOOLTIPS, // | TBSTYLE_FLAT
826 baseID + 2, 11, 849 baseID + 2, 11,
827 (HINSTANCE)HINST_COMMCTRL, IDB_VIEW_SMALL_COLOR, 850 (HINSTANCE)HINST_COMMCTRL, IDB_VIEW_SMALL_COLOR,
828 (LPCTBBUTTON)&tbb, ARRAY_SIZE(tbb), 851 (LPCTBBUTTON)&tbb, Z7_ARRAY_SIZE(tbb),
829 0, 0, 100, 30, sizeof (TBBUTTON))); 852 0, 0, 100, 30, sizeof (TBBUTTON)));
830 */ 853 */
831 // HCURSOR cursor = ::LoadCursor(0, IDC_SIZEWE); 854 // HCURSOR cursor = ::LoadCursor(0, IDC_SIZEWE);
832 // ::SetCursor(cursor); 855 // ::SetCursor(cursor);
833 856
834 if (g_PanelsInfoDefined) 857 if (g_PanelsInfoDefined)
835 g_Splitter.SetPos(hWnd, g_SplitterPos); 858 g_Splitter.SetPos(hWnd, (int)g_SplitterPos);
836 else 859 else
837 { 860 {
838 g_Splitter.SetRatio(hWnd, kSplitterRateMax / 2); 861 g_Splitter.SetRatio(hWnd, kSplitterRateMax / 2);
839 g_SplitterPos = g_Splitter.GetPos(); 862 g_SplitterPos = (unsigned)g_Splitter.GetPos();
840 } 863 }
841 864
842 RECT rect; 865 RECT rect;
843 ::GetClientRect(hWnd, &rect); 866 ::GetClientRect(hWnd, &rect);
844 int xSize = rect.right; 867 const int xSize = rect.right;
845 int xSizes[2]; 868 int xSizes[2];
846 xSizes[0] = g_Splitter.GetPos(); 869 xSizes[0] = g_Splitter.GetPos();
847 xSizes[1] = xSize - kSplitterWidth - xSizes[0]; 870 xSizes[1] = xSize - kSplitterWidth - xSizes[0];
@@ -954,7 +977,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
954 g_Splitter.SetPosFromRatio(hWnd); 977 g_Splitter.SetPosFromRatio(hWnd);
955 else 978 else
956 { 979 {
957 g_Splitter.SetPos(hWnd, g_SplitterPos ); 980 g_Splitter.SetPos(hWnd, (int)g_SplitterPos );
958 g_CanChangeSplitter = true; 981 g_CanChangeSplitter = true;
959 } 982 }
960 983
@@ -1047,7 +1070,7 @@ void CApp::MoveSubWindows()
1047{ 1070{
1048 HWND hWnd = _window; 1071 HWND hWnd = _window;
1049 RECT rect; 1072 RECT rect;
1050 if (hWnd == 0) 1073 if (!hWnd)
1051 return; 1074 return;
1052 ::GetClientRect(hWnd, &rect); 1075 ::GetClientRect(hWnd, &rect);
1053 int xSize = rect.right; 1076 int xSize = rect.right;
diff --git a/CPP/7zip/UI/FileManager/FM.dsp b/CPP/7zip/UI/FileManager/FM.dsp
index a12d330..1ae054d 100644
--- a/CPP/7zip/UI/FileManager/FM.dsp
+++ b/CPP/7zip/UI/FileManager/FM.dsp
@@ -45,7 +45,7 @@ RSC=rc.exe
45# PROP Ignore_Export_Lib 0 45# PROP Ignore_Export_Lib 0
46# PROP Target_Dir "" 46# PROP Target_Dir ""
47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c 47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
48# 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 48# 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
49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
51# ADD BASE RSC /l 0x419 /d "NDEBUG" 51# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -72,7 +72,7 @@ LINK32=link.exe
72# PROP Ignore_Export_Lib 0 72# PROP Ignore_Export_Lib 0
73# PROP Target_Dir "" 73# PROP Target_Dir ""
74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c 74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
75# 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 75# 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
76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
78# ADD BASE RSC /l 0x419 /d "_DEBUG" 78# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -99,7 +99,7 @@ LINK32=link.exe
99# PROP Ignore_Export_Lib 0 99# PROP Ignore_Export_Lib 0
100# PROP Target_Dir "" 100# PROP Target_Dir ""
101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c 101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /c
102# 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 102# 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
103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
105# ADD BASE RSC /l 0x419 /d "NDEBUG" 105# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -127,7 +127,7 @@ LINK32=link.exe
127# PROP Ignore_Export_Lib 0 127# PROP Ignore_Export_Lib 0
128# PROP Target_Dir "" 128# PROP Target_Dir ""
129# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c 129# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"StdAfx.h" /FD /GZ /c
130# 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 130# 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
131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
133# ADD BASE RSC /l 0x419 /d "_DEBUG" 133# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -707,6 +707,10 @@ SOURCE=..\..\..\..\C\7zTypes.h
707# End Source File 707# End Source File
708# Begin Source File 708# Begin Source File
709 709
710SOURCE=..\..\..\..\C\7zWindows.h
711# End Source File
712# Begin Source File
713
710SOURCE=..\..\..\..\C\Alloc.c 714SOURCE=..\..\..\..\C\Alloc.c
711# SUBTRACT CPP /YX /Yc /Yu 715# SUBTRACT CPP /YX /Yc /Yu
712# End Source File 716# End Source File
@@ -716,6 +720,10 @@ SOURCE=..\..\..\..\C\Alloc.h
716# End Source File 720# End Source File
717# Begin Source File 721# Begin Source File
718 722
723SOURCE=..\..\..\..\C\Compiler.h
724# End Source File
725# Begin Source File
726
719SOURCE=..\..\..\..\C\CpuArch.c 727SOURCE=..\..\..\..\C\CpuArch.c
720# SUBTRACT CPP /YX /Yc /Yu 728# SUBTRACT CPP /YX /Yc /Yu
721# End Source File 729# End Source File
@@ -1112,6 +1120,10 @@ SOURCE=..\..\..\Common\MyCom.h
1112# End Source File 1120# End Source File
1113# Begin Source File 1121# Begin Source File
1114 1122
1123SOURCE=..\..\..\Common\MyInitGuid.h
1124# End Source File
1125# Begin Source File
1126
1115SOURCE=..\..\..\Common\MyString.cpp 1127SOURCE=..\..\..\Common\MyString.cpp
1116# End Source File 1128# End Source File
1117# Begin Source File 1129# Begin Source File
@@ -1132,6 +1144,10 @@ SOURCE=..\..\..\Common\MyVector.h
1132# End Source File 1144# End Source File
1133# Begin Source File 1145# Begin Source File
1134 1146
1147SOURCE=..\..\..\Common\MyWindows.h
1148# End Source File
1149# Begin Source File
1150
1135SOURCE=..\..\..\Common\NewHandler.cpp 1151SOURCE=..\..\..\Common\NewHandler.cpp
1136# End Source File 1152# End Source File
1137# Begin Source File 1153# Begin Source File
@@ -1431,6 +1447,14 @@ SOURCE=..\Explorer\MyExplorerCommand.h
1431# End Source File 1447# End Source File
1432# Begin Source File 1448# Begin Source File
1433 1449
1450SOURCE=..\Explorer\MyMessages.cpp
1451# End Source File
1452# Begin Source File
1453
1454SOURCE=..\Explorer\MyMessages.h
1455# End Source File
1456# Begin Source File
1457
1434SOURCE=..\Explorer\RegistryContextMenu.cpp 1458SOURCE=..\Explorer\RegistryContextMenu.cpp
1435# End Source File 1459# End Source File
1436# Begin Source File 1460# Begin Source File
diff --git a/CPP/7zip/UI/FileManager/FM.mak b/CPP/7zip/UI/FileManager/FM.mak
index 8b3d97a..8331285 100644
--- a/CPP/7zip/UI/FileManager/FM.mak
+++ b/CPP/7zip/UI/FileManager/FM.mak
@@ -1,12 +1,11 @@
1CFLAGS = $(CFLAGS) \ 1CFLAGS = $(CFLAGS) \
2 -DLANG \ 2 -DZ7_LANG \
3 -DNEW_FOLDER_INTERFACE \
4 3
5!IFDEF UNDER_CE 4!IFDEF UNDER_CE
6LIBS = $(LIBS) ceshell.lib Commctrl.lib 5LIBS = $(LIBS) ceshell.lib Commctrl.lib
7!ELSE 6!ELSE
8LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib 7LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib
9CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -DSUPPORT_DEVICE_FILE 8CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_DEVICE_FILE
10LFLAGS = $(LFLAGS) /DELAYLOAD:mpr.dll 9LFLAGS = $(LFLAGS) /DELAYLOAD:mpr.dll
11LIBS = $(LIBS) delayimp.lib 10LIBS = $(LIBS) delayimp.lib
12!ENDIF 11!ENDIF
@@ -47,7 +46,6 @@ FM_OBJS = \
47 $O\ProgramLocation.obj \ 46 $O\ProgramLocation.obj \
48 $O\PropertyName.obj \ 47 $O\PropertyName.obj \
49 $O\RegistryAssociations.obj \ 48 $O\RegistryAssociations.obj \
50 $O\RegistryPlugins.obj \
51 $O\RegistryUtils.obj \ 49 $O\RegistryUtils.obj \
52 $O\RootFolder.obj \ 50 $O\RootFolder.obj \
53 $O\SplitUtils.obj \ 51 $O\SplitUtils.obj \
@@ -98,3 +96,5 @@ AGENT_OBJS = \
98 $O\ArchiveFolderOpen.obj \ 96 $O\ArchiveFolderOpen.obj \
99 $O\ArchiveFolderOut.obj \ 97 $O\ArchiveFolderOut.obj \
100 $O\UpdateCallbackAgent.obj \ 98 $O\UpdateCallbackAgent.obj \
99
100# 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 c563907..985d7c4 100644
--- a/CPP/7zip/UI/FileManager/FSDrives.cpp
+++ b/CPP/7zip/UI/FileManager/FSDrives.cpp
@@ -41,7 +41,7 @@ FString CDriveInfo::GetDeviceFileIoName() const
41struct CPhysTempBuffer 41struct CPhysTempBuffer
42{ 42{
43 void *buffer; 43 void *buffer;
44 CPhysTempBuffer(): buffer(0) {} 44 CPhysTempBuffer(): buffer(NULL) {}
45 ~CPhysTempBuffer() { MidFree(buffer); } 45 ~CPhysTempBuffer() { MidFree(buffer); }
46}; 46};
47 47
@@ -50,22 +50,22 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt
50{ 50{
51 NIO::CInFile inFile; 51 NIO::CInFile inFile;
52 if (!inFile.Open(fromPath)) 52 if (!inFile.Open(fromPath))
53 return GetLastError(); 53 return GetLastError_noZero_HRESULT();
54 if (fileSize == (UInt64)(Int64)-1) 54 if (fileSize == (UInt64)(Int64)-1)
55 { 55 {
56 if (!inFile.GetLength(fileSize)) 56 if (!inFile.GetLength(fileSize))
57 ::GetLastError(); 57 return GetLastError_noZero_HRESULT();
58 } 58 }
59 59
60 NIO::COutFile outFile; 60 NIO::COutFile outFile;
61 if (writeToDisk) 61 if (writeToDisk)
62 { 62 {
63 if (!outFile.Open(toPath, FILE_SHARE_WRITE, OPEN_EXISTING, 0)) 63 if (!outFile.Open(toPath, FILE_SHARE_WRITE, OPEN_EXISTING, 0))
64 return GetLastError(); 64 return GetLastError_noZero_HRESULT();
65 } 65 }
66 else 66 else
67 if (!outFile.Create(toPath, true)) 67 if (!outFile.Create(toPath, true))
68 return GetLastError(); 68 return GetLastError_noZero_HRESULT();
69 69
70 CPhysTempBuffer tempBuffer; 70 CPhysTempBuffer tempBuffer;
71 tempBuffer.buffer = MidAlloc(bufferSize); 71 tempBuffer.buffer = MidAlloc(bufferSize);
@@ -75,12 +75,12 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt
75 for (UInt64 pos = 0; pos < fileSize;) 75 for (UInt64 pos = 0; pos < fileSize;)
76 { 76 {
77 UInt64 progressCur = progressStart + pos; 77 UInt64 progressCur = progressStart + pos;
78 RINOK(progress->SetCompleted(&progressCur)); 78 RINOK(progress->SetCompleted(&progressCur))
79 UInt64 rem = fileSize - pos; 79 UInt64 rem = fileSize - pos;
80 UInt32 curSize = (UInt32)MyMin(rem, (UInt64)bufferSize); 80 UInt32 curSize = (UInt32)MyMin(rem, (UInt64)bufferSize);
81 UInt32 processedSize; 81 UInt32 processedSize;
82 if (!inFile.Read(tempBuffer.buffer, curSize, processedSize)) 82 if (!inFile.Read(tempBuffer.buffer, curSize, processedSize))
83 return GetLastError(); 83 return GetLastError_noZero_HRESULT();
84 if (processedSize == 0) 84 if (processedSize == 0)
85 break; 85 break;
86 curSize = processedSize; 86 curSize = processedSize;
@@ -93,7 +93,7 @@ static HRESULT CopyFileSpec(CFSTR fromPath, CFSTR toPath, bool writeToDisk, UInt
93 } 93 }
94 94
95 if (!outFile.Write(tempBuffer.buffer, curSize, processedSize)) 95 if (!outFile.Write(tempBuffer.buffer, curSize, processedSize))
96 return GetLastError(); 96 return GetLastError_noZero_HRESULT();
97 if (curSize != processedSize) 97 if (curSize != processedSize)
98 return E_FAIL; 98 return E_FAIL;
99 pos += curSize; 99 pos += curSize;
@@ -125,7 +125,7 @@ static const char * const kDriveTypes[] =
125 , "RAM disk" 125 , "RAM disk"
126}; 126};
127 127
128STDMETHODIMP CFSDrives::LoadItems() 128Z7_COM7F_IMF(CFSDrives::LoadItems())
129{ 129{
130 _drives.Clear(); 130 _drives.Clear();
131 131
@@ -209,13 +209,13 @@ STDMETHODIMP CFSDrives::LoadItems()
209 return S_OK; 209 return S_OK;
210} 210}
211 211
212STDMETHODIMP CFSDrives::GetNumberOfItems(UInt32 *numItems) 212Z7_COM7F_IMF(CFSDrives::GetNumberOfItems(UInt32 *numItems))
213{ 213{
214 *numItems = _drives.Size(); 214 *numItems = _drives.Size();
215 return S_OK; 215 return S_OK;
216} 216}
217 217
218STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) 218Z7_COM7F_IMF(CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value))
219{ 219{
220 if (itemIndex >= (UInt32)_drives.Size()) 220 if (itemIndex >= (UInt32)_drives.Size())
221 return E_INVALIDARG; 221 return E_INVALIDARG;
@@ -239,7 +239,7 @@ STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT
239 case kpidFreeSpace: if (di.KnownSizes) prop = di.FreeSpace; break; 239 case kpidFreeSpace: if (di.KnownSizes) prop = di.FreeSpace; break;
240 case kpidClusterSize: if (di.KnownSizes) prop = di.ClusterSize; break; 240 case kpidClusterSize: if (di.KnownSizes) prop = di.ClusterSize; break;
241 case kpidType: 241 case kpidType:
242 if (di.DriveType < ARRAY_SIZE(kDriveTypes)) 242 if (di.DriveType < Z7_ARRAY_SIZE(kDriveTypes))
243 prop = kDriveTypes[di.DriveType]; 243 prop = kDriveTypes[di.DriveType];
244 break; 244 break;
245 case kpidVolumeName: prop = di.VolumeName; break; 245 case kpidVolumeName: prop = di.VolumeName; break;
@@ -251,7 +251,7 @@ STDMETHODIMP CFSDrives::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT
251 251
252HRESULT CFSDrives::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder) 252HRESULT CFSDrives::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder)
253{ 253{
254 *resultFolder = 0; 254 *resultFolder = NULL;
255 if (_volumeMode) 255 if (_volumeMode)
256 return S_OK; 256 return S_OK;
257 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; 257 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder;
@@ -260,14 +260,14 @@ HRESULT CFSDrives::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder)
260 if (_superMode) 260 if (_superMode)
261 path = kSuperPrefix; 261 path = kSuperPrefix;
262 path += name; 262 path += name;
263 RINOK(fsFolderSpec->Init(path)); 263 RINOK(fsFolderSpec->Init(path))
264 *resultFolder = subFolder.Detach(); 264 *resultFolder = subFolder.Detach();
265 return S_OK; 265 return S_OK;
266} 266}
267 267
268STDMETHODIMP CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 268Z7_COM7F_IMF(CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder))
269{ 269{
270 *resultFolder = 0; 270 *resultFolder = NULL;
271 if (index >= (UInt32)_drives.Size()) 271 if (index >= (UInt32)_drives.Size())
272 return E_INVALIDARG; 272 return E_INVALIDARG;
273 const CDriveInfo &di = _drives[index]; 273 const CDriveInfo &di = _drives[index];
@@ -285,20 +285,20 @@ STDMETHODIMP CFSDrives::BindToFolder(UInt32 index, IFolderFolder **resultFolder)
285 return BindToFolderSpec(di.FullSystemName, resultFolder); 285 return BindToFolderSpec(di.FullSystemName, resultFolder);
286} 286}
287 287
288STDMETHODIMP CFSDrives::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) 288Z7_COM7F_IMF(CFSDrives::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder))
289{ 289{
290 return BindToFolderSpec(us2fs(name), resultFolder); 290 return BindToFolderSpec(us2fs(name), resultFolder);
291} 291}
292 292
293STDMETHODIMP CFSDrives::BindToParentFolder(IFolderFolder **resultFolder) 293Z7_COM7F_IMF(CFSDrives::BindToParentFolder(IFolderFolder **resultFolder))
294{ 294{
295 *resultFolder = 0; 295 *resultFolder = NULL;
296 return S_OK; 296 return S_OK;
297} 297}
298 298
299IMP_IFolderFolder_Props(CFSDrives) 299IMP_IFolderFolder_Props(CFSDrives)
300 300
301STDMETHODIMP CFSDrives::GetFolderProperty(PROPID propID, PROPVARIANT *value) 301Z7_COM7F_IMF(CFSDrives::GetFolderProperty(PROPID propID, PROPVARIANT *value))
302{ 302{
303 COM_TRY_BEGIN 303 COM_TRY_BEGIN
304 NCOM::CPropVariant prop; 304 NCOM::CPropVariant prop;
@@ -320,7 +320,7 @@ STDMETHODIMP CFSDrives::GetFolderProperty(PROPID propID, PROPVARIANT *value)
320} 320}
321 321
322 322
323STDMETHODIMP CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) 323Z7_COM7F_IMF(CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
324{ 324{
325 *iconIndex = 0; 325 *iconIndex = 0;
326 const CDriveInfo &di = _drives[index]; 326 const CDriveInfo &di = _drives[index];
@@ -332,39 +332,64 @@ STDMETHODIMP CFSDrives::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)
332 *iconIndex = iconIndexTemp; 332 *iconIndex = iconIndexTemp;
333 return S_OK; 333 return S_OK;
334 } 334 }
335 return GetLastError(); 335 return GetLastError_noZero_HRESULT();
336} 336}
337 337
338void CFSDrives::AddExt(FString &s, unsigned index) const 338void CFSDrives::AddExt(FString &s, unsigned index) const
339{ 339{
340 s += '.'; 340 s.Add_Dot();
341 const CDriveInfo &di = _drives[index]; 341 const CDriveInfo &di = _drives[index];
342 UString n = di.FileSystemName;
343 n.MakeLower_Ascii();
342 const char *ext; 344 const char *ext;
343 if (di.DriveType == DRIVE_CDROM) 345 if (di.DriveType == DRIVE_CDROM)
344 ext = "iso"; 346 ext = "iso";
345 else if (di.FileSystemName.IsPrefixedBy_Ascii_NoCase("NTFS"))
346 ext = "ntfs";
347 else if (di.FileSystemName.IsPrefixedBy_Ascii_NoCase("FAT"))
348 ext = "fat";
349 else 347 else
348 {
349 unsigned i;
350 for (i = 0; i < n.Len(); i++)
351 {
352 const wchar_t c = n[i];
353 if (c < 'a' || c > 'z')
354 break;
355 }
356 if (i != 0)
357 {
358 n.DeleteFrom(i);
359 s += us2fs(n);
360 return;
361 }
350 ext = "img"; 362 ext = "img";
363 }
364 /*
365 if (n.IsPrefixedBy_Ascii_NoCase("NTFS")) ext = "ntfs";
366 else if (n.IsPrefixedBy_Ascii_NoCase("UDF")) ext = "udf";
367 else if (n.IsPrefixedBy_Ascii_NoCase("exFAT")) ext = "exfat";
368 */
351 s += ext; 369 s += ext;
352} 370}
353 371
354HRESULT CFSDrives::GetFileSize(unsigned index, UInt64 &fileSize) const 372HRESULT CFSDrives::GetFileSize(unsigned index, UInt64& fileSize) const
355{ 373{
374#ifdef Z7_DEVICE_FILE
356 NIO::CInFile inFile; 375 NIO::CInFile inFile;
357 if (!inFile.Open(_drives[index].GetDeviceFileIoName())) 376 if (!inFile.Open(_drives[index].GetDeviceFileIoName()))
358 return GetLastError(); 377 return GetLastError_noZero_HRESULT();
359 if (!inFile.SizeDefined) 378 if (inFile.SizeDefined)
360 return E_FAIL; 379 {
361 fileSize = inFile.Size; 380 fileSize = inFile.Size;
362 return S_OK; 381 return S_OK;
382 }
383#else
384 UNUSED_VAR(index)
385#endif
386 fileSize = 0;
387 return E_FAIL;
363} 388}
364 389
365STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, 390Z7_COM7F_IMF(CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems,
366 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, 391 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */,
367 const wchar_t *path, IFolderOperationsExtractCallback *callback) 392 const wchar_t *path, IFolderOperationsExtractCallback *callback))
368{ 393{
369 if (numItems == 0) 394 if (numItems == 0)
370 return S_OK; 395 return S_OK;
@@ -383,8 +408,8 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num
383 if (di.KnownSize) 408 if (di.KnownSize)
384 totalSize += di.DriveSize; 409 totalSize += di.DriveSize;
385 } 410 }
386 RINOK(callback->SetTotal(totalSize)); 411 RINOK(callback->SetTotal(totalSize))
387 RINOK(callback->SetNumFiles(numItems)); 412 RINOK(callback->SetNumFiles(numItems))
388 413
389 FString destPath = us2fs(path); 414 FString destPath = us2fs(path);
390 if (destPath.IsEmpty()) 415 if (destPath.IsEmpty())
@@ -400,8 +425,7 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num
400 } 425 }
401 426
402 UInt64 completedSize = 0; 427 UInt64 completedSize = 0;
403 RINOK(callback->SetCompleted(&completedSize)); 428 RINOK(callback->SetCompleted(&completedSize))
404
405 for (i = 0; i < numItems; i++) 429 for (i = 0; i < numItems; i++)
406 { 430 {
407 unsigned index = indices[i]; 431 unsigned index = indices[i];
@@ -429,66 +453,66 @@ STDMETHODIMP CFSDrives::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num
429 if (!di.KnownSize) 453 if (!di.KnownSize)
430 { 454 {
431 totalSize += fileSize; 455 totalSize += fileSize;
432 RINOK(callback->SetTotal(totalSize)); 456 RINOK(callback->SetTotal(totalSize))
433 } 457 }
434 458
435 Int32 writeAskResult; 459 Int32 writeAskResult;
436 CMyComBSTR destPathResult; 460 CMyComBSTR destPathResult;
437 RINOK(callback->AskWrite(fs2us(srcPath), BoolToInt(false), NULL, &fileSize, 461 RINOK(callback->AskWrite(fs2us(srcPath), BoolToInt(false), NULL, &fileSize,
438 fs2us(destPath2), &destPathResult, &writeAskResult)); 462 fs2us(destPath2), &destPathResult, &writeAskResult))
439 463
440 if (!IntToBool(writeAskResult)) 464 if (!IntToBool(writeAskResult))
441 { 465 {
442 if (totalSize >= fileSize) 466 if (totalSize >= fileSize)
443 totalSize -= fileSize; 467 totalSize -= fileSize;
444 RINOK(callback->SetTotal(totalSize)); 468 RINOK(callback->SetTotal(totalSize))
445 continue; 469 continue;
446 } 470 }
447 471
448 RINOK(callback->SetCurrentFilePath(fs2us(srcPath))); 472 RINOK(callback->SetCurrentFilePath(fs2us(srcPath)))
449 473
450 static const UInt32 kBufferSize = (4 << 20); 474 const UInt32 kBufferSize = (4 << 20);
451 UInt32 bufferSize = (di.DriveType == DRIVE_REMOVABLE) ? (18 << 10) * 4 : kBufferSize; 475 const UInt32 bufferSize = (di.DriveType == DRIVE_REMOVABLE) ? (18 << 10) * 4 : kBufferSize;
452 RINOK(CopyFileSpec(srcPath, us2fs(destPathResult), false, fileSize, bufferSize, completedSize, callback)); 476 RINOK(CopyFileSpec(srcPath, us2fs(destPathResult), false, fileSize, bufferSize, completedSize, callback))
453 completedSize += fileSize; 477 completedSize += fileSize;
454 } 478 }
455 479
456 return S_OK; 480 return S_OK;
457} 481}
458 482
459STDMETHODIMP CFSDrives::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, 483Z7_COM7F_IMF(CFSDrives::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */,
460 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) 484 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */))
461{ 485{
462 return E_NOTIMPL; 486 return E_NOTIMPL;
463} 487}
464 488
465STDMETHODIMP CFSDrives::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) 489Z7_COM7F_IMF(CFSDrives::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */))
466{ 490{
467 return E_NOTIMPL; 491 return E_NOTIMPL;
468} 492}
469 493
470STDMETHODIMP CFSDrives::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */) 494Z7_COM7F_IMF(CFSDrives::CreateFolder(const wchar_t * /* name */, IProgress * /* progress */))
471{ 495{
472 return E_NOTIMPL; 496 return E_NOTIMPL;
473} 497}
474 498
475STDMETHODIMP CFSDrives::CreateFile(const wchar_t * /* name */, IProgress * /* progress */) 499Z7_COM7F_IMF(CFSDrives::CreateFile(const wchar_t * /* name */, IProgress * /* progress */))
476{ 500{
477 return E_NOTIMPL; 501 return E_NOTIMPL;
478} 502}
479 503
480STDMETHODIMP CFSDrives::Rename(UInt32 /* index */, const wchar_t * /* newName */, IProgress * /* progress */) 504Z7_COM7F_IMF(CFSDrives::Rename(UInt32 /* index */, const wchar_t * /* newName */, IProgress * /* progress */))
481{ 505{
482 return E_NOTIMPL; 506 return E_NOTIMPL;
483} 507}
484 508
485STDMETHODIMP CFSDrives::Delete(const UInt32 * /* indices */, UInt32 /* numItems */, IProgress * /* progress */) 509Z7_COM7F_IMF(CFSDrives::Delete(const UInt32 * /* indices */, UInt32 /* numItems */, IProgress * /* progress */))
486{ 510{
487 return E_NOTIMPL; 511 return E_NOTIMPL;
488} 512}
489 513
490STDMETHODIMP CFSDrives::SetProperty(UInt32 /* index */, PROPID /* propID */, 514Z7_COM7F_IMF(CFSDrives::SetProperty(UInt32 /* index */, PROPID /* propID */,
491 const PROPVARIANT * /* value */, IProgress * /* progress */) 515 const PROPVARIANT * /* value */, IProgress * /* progress */))
492{ 516{
493 return E_NOTIMPL; 517 return E_NOTIMPL;
494} 518}
diff --git a/CPP/7zip/UI/FileManager/FSDrives.h b/CPP/7zip/UI/FileManager/FSDrives.h
index f12e4da..8ae831c 100644
--- a/CPP/7zip/UI/FileManager/FSDrives.h
+++ b/CPP/7zip/UI/FileManager/FSDrives.h
@@ -1,7 +1,7 @@
1// FSDrives.h 1// FSDrives.h
2 2
3#ifndef __FS_DRIVES_H 3#ifndef ZIP7_INC_FS_DRIVES_H
4#define __FS_DRIVES_H 4#define ZIP7_INC_FS_DRIVES_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
@@ -28,12 +28,12 @@ struct CDriveInfo
28 CDriveInfo(): KnownSize(false), KnownSizes(false), IsPhysicalDrive(false) {} 28 CDriveInfo(): KnownSize(false), KnownSizes(false), IsPhysicalDrive(false) {}
29}; 29};
30 30
31class CFSDrives: 31Z7_CLASS_IMP_NOQIB_3(
32 public IFolderFolder, 32 CFSDrives
33 public IFolderOperations, 33 , IFolderFolder
34 public IFolderGetSystemIconIndex, 34 , IFolderOperations
35 public CMyUnknownImp 35 , IFolderGetSystemIconIndex
36{ 36)
37 CObjectVector<CDriveInfo> _drives; 37 CObjectVector<CDriveInfo> _drives;
38 bool _volumeMode; 38 bool _volumeMode;
39 bool _superMode; 39 bool _superMode;
@@ -42,13 +42,6 @@ class CFSDrives:
42 void AddExt(FString &s, unsigned index) const; 42 void AddExt(FString &s, unsigned index) const;
43 HRESULT GetFileSize(unsigned index, UInt64 &fileSize) const; 43 HRESULT GetFileSize(unsigned index, UInt64 &fileSize) const;
44public: 44public:
45 MY_UNKNOWN_IMP2(IFolderGetSystemIconIndex, IFolderOperations)
46
47 INTERFACE_FolderFolder(;)
48 INTERFACE_FolderOperations(;)
49
50 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex);
51
52 void Init(bool volMode = false, bool superMode = false) 45 void Init(bool volMode = false, bool superMode = false)
53 { 46 {
54 _volumeMode = volMode; 47 _volumeMode = volMode;
diff --git a/CPP/7zip/UI/FileManager/FSFolder.cpp b/CPP/7zip/UI/FileManager/FSFolder.cpp
index f603061..06c572d 100644
--- a/CPP/7zip/UI/FileManager/FSFolder.cpp
+++ b/CPP/7zip/UI/FileManager/FSFolder.cpp
@@ -2,15 +2,24 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#if defined(_MSC_VER) 5#ifdef __MINGW32_VERSION
6#include <winternl.h> 6// #if !defined(_MSC_VER) && (__GNUC__) && (__GNUC__ < 10)
7// for old mingw
8#include <ddk/ntddk.h>
7#else 9#else
8#if defined(__GNUC__) && (__GNUC__ >= 10) 10#ifndef Z7_OLD_WIN_SDK
9 // new mingw: 11 #if !defined(_M_IA64)
10 #include <winternl.h> 12 #include <winternl.h>
13 #endif
11#else 14#else
12 // old mingw: 15typedef LONG NTSTATUS;
13 #include <ddk/winddk.h> 16typedef struct _IO_STATUS_BLOCK {
17 union {
18 NTSTATUS Status;
19 PVOID Pointer;
20 };
21 ULONG_PTR Information;
22} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
14#endif 23#endif
15#endif 24#endif
16 25
@@ -106,7 +115,7 @@ HRESULT CFSFolder::Init(const FString &path /* , IFolderFolder *parentFolder */)
106 115
107 if (!_findChangeNotification.IsHandleAllocated()) 116 if (!_findChangeNotification.IsHandleAllocated())
108 { 117 {
109 DWORD lastError = GetLastError(); 118 const HRESULT lastError = GetLastError_noZero_HRESULT();
110 CFindFile findFile; 119 CFindFile findFile;
111 CFileInfo fi; 120 CFileInfo fi;
112 FString path2 = _path; 121 FString path2 = _path;
@@ -125,7 +134,7 @@ HRESULT CFsFolderStat::Enumerate()
125{ 134{
126 if (Progress) 135 if (Progress)
127 { 136 {
128 RINOK(Progress->SetCompleted(NULL)); 137 RINOK(Progress->SetCompleted(NULL))
129 } 138 }
130 Path.Add_PathSepar(); 139 Path.Add_PathSepar();
131 const unsigned len = Path.Len(); 140 const unsigned len = Path.Len();
@@ -139,7 +148,7 @@ HRESULT CFsFolderStat::Enumerate()
139 NumFolders++; 148 NumFolders++;
140 Path.DeleteFrom(len); 149 Path.DeleteFrom(len);
141 Path += fi.Name; 150 Path += fi.Name;
142 RINOK(Enumerate()); 151 RINOK(Enumerate())
143 } 152 }
144 else 153 else
145 { 154 {
@@ -166,7 +175,7 @@ bool MyGetCompressedFileSizeW(CFSTR path, UInt64 &size)
166 return true; 175 return true;
167 } 176 }
168 } 177 }
169 #ifdef WIN_LONG_PATH 178 #ifdef Z7_LONG_PATH
170 if (USE_SUPER_PATH) 179 if (USE_SUPER_PATH)
171 { 180 {
172 UString superPath; 181 UString superPath;
@@ -285,16 +294,16 @@ HRESULT CFSFolder::LoadSubItems(int dirItem, const FString &relPrefix)
285 294
286 const unsigned endIndex = Folders.Size(); 295 const unsigned endIndex = Folders.Size();
287 for (unsigned i = startIndex; i < endIndex; i++) 296 for (unsigned i = startIndex; i < endIndex; i++)
288 LoadSubItems(i, Folders[i]); 297 LoadSubItems((int)i, Folders[i]);
289 return S_OK; 298 return S_OK;
290} 299}
291 300
292STDMETHODIMP CFSFolder::LoadItems() 301Z7_COM7F_IMF(CFSFolder::LoadItems())
293{ 302{
294 Int32 dummy; 303 Int32 dummy;
295 WasChanged(&dummy); 304 WasChanged(&dummy);
296 Clear(); 305 Clear();
297 RINOK(LoadSubItems(-1, FString())); 306 RINOK(LoadSubItems(-1, FString()))
298 _commentsAreLoaded = false; 307 _commentsAreLoaded = false;
299 return S_OK; 308 return S_OK;
300} 309}
@@ -356,7 +365,7 @@ bool CFSFolder::SaveComments()
356 return true; 365 return true;
357} 366}
358 367
359STDMETHODIMP CFSFolder::GetNumberOfItems(UInt32 *numItems) 368Z7_COM7F_IMF(CFSFolder::GetNumberOfItems(UInt32 *numItems))
360{ 369{
361 *numItems = Files.Size() /* + Streams.Size() */; 370 *numItems = Files.Size() /* + Streams.Size() */;
362 return S_OK; 371 return S_OK;
@@ -364,9 +373,9 @@ STDMETHODIMP CFSFolder::GetNumberOfItems(UInt32 *numItems)
364 373
365#ifdef USE_UNICODE_FSTRING 374#ifdef USE_UNICODE_FSTRING
366 375
367STDMETHODIMP CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len) 376Z7_COM7F_IMF(CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len))
368{ 377{
369 *name = 0; 378 *name = NULL;
370 *len = 0; 379 *len = 0;
371 /* 380 /*
372 if (index >= Files.Size()) 381 if (index >= Files.Size())
@@ -383,9 +392,9 @@ STDMETHODIMP CFSFolder::GetItemPrefix(UInt32 index, const wchar_t **name, unsign
383 return S_OK; 392 return S_OK;
384} 393}
385 394
386STDMETHODIMP CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len) 395Z7_COM7F_IMF(CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned *len))
387{ 396{
388 *name = 0; 397 *name = NULL;
389 *len = 0; 398 *len = 0;
390 if (index < Files.Size()) 399 if (index < Files.Size())
391 { 400 {
@@ -405,7 +414,7 @@ STDMETHODIMP CFSFolder::GetItemName(UInt32 index, const wchar_t **name, unsigned
405 return S_OK; 414 return S_OK;
406} 415}
407 416
408STDMETHODIMP_(UInt64) CFSFolder::GetItemSize(UInt32 index) 417Z7_COM7F_IMF2(UInt64, CFSFolder::GetItemSize(UInt32 index))
409{ 418{
410 /* 419 /*
411 if (index >= Files.Size()) 420 if (index >= Files.Size())
@@ -434,6 +443,8 @@ bool CFSFolder::ReadFileInfo(CDirItem &di)
434} 443}
435 444
436 445
446EXTERN_C_BEGIN
447
437typedef struct 448typedef struct
438{ 449{
439 LARGE_INTEGER CreationTime; 450 LARGE_INTEGER CreationTime;
@@ -443,37 +454,57 @@ typedef struct
443 ULONG FileAttributes; 454 ULONG FileAttributes;
444 UInt32 Reserved; // it's expected for alignment 455 UInt32 Reserved; // it's expected for alignment
445} 456}
446MY__FILE_BASIC_INFORMATION; 457Z7_WIN_FILE_BASIC_INFORMATION;
447 458
448 459
449typedef enum 460typedef enum
450{ 461{
451 MY__FileDirectoryInformation = 1, 462 Z7_WIN_FileDirectoryInformation = 1,
452 MY__FileFullDirectoryInformation, 463 Z7_WIN_FileFullDirectoryInformation,
453 MY__FileBothDirectoryInformation, 464 Z7_WIN_FileBothDirectoryInformation,
454 MY__FileBasicInformation 465 Z7_WIN_FileBasicInformation
455} 466}
456MY__FILE_INFORMATION_CLASS; 467Z7_WIN_FILE_INFORMATION_CLASS;
468
457 469
470#if (_WIN32_WINNT >= 0x0500) && !defined(_M_IA64)
471#define Z7_WIN_NTSTATUS NTSTATUS
472#define Z7_WIN_IO_STATUS_BLOCK IO_STATUS_BLOCK
473#else
474typedef LONG Z7_WIN_NTSTATUS;
475typedef struct
476{
477 union
478 {
479 Z7_WIN_NTSTATUS Status;
480 PVOID Pointer;
481 } DUMMYUNIONNAME;
482 ULONG_PTR Information;
483} Z7_WIN_IO_STATUS_BLOCK;
484#endif
458 485
459typedef NTSTATUS (WINAPI * Func_NtQueryInformationFile)(
460 HANDLE handle, IO_STATUS_BLOCK *io,
461 void *ptr, LONG len, MY__FILE_INFORMATION_CLASS cls);
462 486
463#define MY__STATUS_SUCCESS 0 487typedef Z7_WIN_NTSTATUS (WINAPI * Func_NtQueryInformationFile)(
488 HANDLE handle, Z7_WIN_IO_STATUS_BLOCK *io,
489 void *ptr, LONG len, Z7_WIN_FILE_INFORMATION_CLASS cls);
490
491#define MY_STATUS_SUCCESS 0
492
493EXTERN_C_END
464 494
465static Func_NtQueryInformationFile f_NtQueryInformationFile; 495static Func_NtQueryInformationFile f_NtQueryInformationFile;
466static bool g_NtQueryInformationFile_WasRequested = false; 496static bool g_NtQueryInformationFile_WasRequested = false;
467 497
498
468void CFSFolder::ReadChangeTime(CDirItem &di) 499void CFSFolder::ReadChangeTime(CDirItem &di)
469{ 500{
470 di.ChangeTime_WasRequested = true; 501 di.ChangeTime_WasRequested = true;
471 502
472 if (!g_NtQueryInformationFile_WasRequested) 503 if (!g_NtQueryInformationFile_WasRequested)
473 { 504 {
474 g_NtQueryInformationFile_WasRequested = true; 505 g_NtQueryInformationFile_WasRequested = true;
475 f_NtQueryInformationFile = (Func_NtQueryInformationFile) 506 f_NtQueryInformationFile = Z7_GET_PROC_ADDRESS(
476 My_GetProcAddress(::GetModuleHandleW(L"ntdll.dll"), 507 Func_NtQueryInformationFile, ::GetModuleHandleW(L"ntdll.dll"),
477 "NtQueryInformationFile"); 508 "NtQueryInformationFile");
478 } 509 }
479 if (!f_NtQueryInformationFile) 510 if (!f_NtQueryInformationFile)
@@ -482,23 +513,23 @@ void CFSFolder::ReadChangeTime(CDirItem &di)
482 NIO::CInFile file; 513 NIO::CInFile file;
483 if (!file.Open_for_ReadAttributes(_path + GetRelPath(di))) 514 if (!file.Open_for_ReadAttributes(_path + GetRelPath(di)))
484 return; 515 return;
485 MY__FILE_BASIC_INFORMATION fbi; 516 Z7_WIN_FILE_BASIC_INFORMATION fbi;
486 IO_STATUS_BLOCK IoStatusBlock; 517 Z7_WIN_IO_STATUS_BLOCK IoStatusBlock;
487 const NTSTATUS status = f_NtQueryInformationFile(file.GetHandle(), &IoStatusBlock, 518 const Z7_WIN_NTSTATUS status = f_NtQueryInformationFile(file.GetHandle(), &IoStatusBlock,
488 &fbi, sizeof(fbi), MY__FileBasicInformation); 519 &fbi, sizeof(fbi), Z7_WIN_FileBasicInformation);
489 if (status != MY__STATUS_SUCCESS) 520 if (status != MY_STATUS_SUCCESS)
490 return; 521 return;
491 if (IoStatusBlock.Information != sizeof(fbi)) 522 if (IoStatusBlock.Information != sizeof(fbi))
492 return; 523 return;
493 di.ChangeTime.dwLowDateTime = fbi.ChangeTime.u.LowPart; 524 di.ChangeTime.dwLowDateTime = fbi.ChangeTime.u.LowPart;
494 di.ChangeTime.dwHighDateTime = fbi.ChangeTime.u.HighPart; 525 di.ChangeTime.dwHighDateTime = (DWORD)fbi.ChangeTime.u.HighPart;
495 di.ChangeTime_Defined = true; 526 di.ChangeTime_Defined = true;
496} 527}
497 528
498#endif // FS_SHOW_LINKS_INFO 529#endif // FS_SHOW_LINKS_INFO
499 530
500 531
501STDMETHODIMP CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) 532Z7_COM7F_IMF(CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value))
502{ 533{
503 NCOM::CPropVariant prop; 534 NCOM::CPropVariant prop;
504 /* 535 /*
@@ -622,34 +653,32 @@ STDMETHODIMP CFSFolder::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *va
622// ---------- IArchiveGetRawProps ---------- 653// ---------- IArchiveGetRawProps ----------
623 654
624 655
625STDMETHODIMP CFSFolder::GetNumRawProps(UInt32 *numProps) 656Z7_COM7F_IMF(CFSFolder::GetNumRawProps(UInt32 *numProps))
626{ 657{
627 *numProps = 1; 658 *numProps = 1;
628 return S_OK; 659 return S_OK;
629} 660}
630 661
631STDMETHODIMP CFSFolder::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID) 662Z7_COM7F_IMF(CFSFolder::GetRawPropInfo(UInt32 /* index */, BSTR *name, PROPID *propID))
632{ 663{
633 *name = NULL; 664 *name = NULL;
634 *propID = kpidNtReparse; 665 *propID = kpidNtReparse;
635 return S_OK; 666 return S_OK;
636} 667}
637 668
638STDMETHODIMP CFSFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */) 669Z7_COM7F_IMF(CFSFolder::GetParent(UInt32 /* index */, UInt32 * /* parent */, UInt32 * /* parentType */))
639{ 670{
640 return E_FAIL; 671 return E_FAIL;
641} 672}
642 673
643STDMETHODIMP CFSFolder::GetRawProp(UInt32 674Z7_COM7F_IMF(CFSFolder::GetRawProp(UInt32 index, PROPID propID,
644 #ifndef UNDER_CE 675 const void **data, UInt32 *dataSize, UInt32 *propType))
645 index
646 #endif
647 , PROPID
648 #ifndef UNDER_CE
649 propID
650 #endif
651 , const void **data, UInt32 *dataSize, UInt32 *propType)
652{ 676{
677 #ifdef UNDER_CE
678 UNUSED(index)
679 UNUSED(propID)
680 #endif
681
653 *data = NULL; 682 *data = NULL;
654 *dataSize = 0; 683 *dataSize = 0;
655 *propType = 0; 684 *propType = 0;
@@ -676,11 +705,11 @@ STDMETHODIMP CFSFolder::GetRawProp(UInt32
676 705
677static inline CFSTR GetExtensionPtr(const FString &name) 706static inline CFSTR GetExtensionPtr(const FString &name)
678{ 707{
679 int dotPos = name.ReverseFind_Dot(); 708 const int dotPos = name.ReverseFind_Dot();
680 return name.Ptr((dotPos < 0) ? name.Len() : dotPos); 709 return name.Ptr((dotPos < 0) ? name.Len() : (unsigned)dotPos);
681} 710}
682 711
683STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */) 712Z7_COM7F_IMF2(Int32, CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 /* propIsRaw */))
684{ 713{
685 /* 714 /*
686 const CAltStream *ss1 = NULL; 715 const CAltStream *ss1 = NULL;
@@ -695,7 +724,7 @@ STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPI
695 { 724 {
696 case kpidName: 725 case kpidName:
697 { 726 {
698 int comp = CompareFileNames_ForFolderList(fi1.Name, fi2.Name); 727 const int comp = CompareFileNames_ForFolderList(fi1.Name, fi2.Name);
699 /* 728 /*
700 if (comp != 0) 729 if (comp != 0)
701 return comp; 730 return comp;
@@ -783,10 +812,10 @@ STDMETHODIMP_(Int32) CFSFolder::CompareItems(UInt32 index1, UInt32 index2, PROPI
783 812
784HRESULT CFSFolder::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder) 813HRESULT CFSFolder::BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder)
785{ 814{
786 *resultFolder = 0; 815 *resultFolder = NULL;
787 CFSFolder *folderSpec = new CFSFolder; 816 CFSFolder *folderSpec = new CFSFolder;
788 CMyComPtr<IFolderFolder> subFolder = folderSpec; 817 CMyComPtr<IFolderFolder> subFolder = folderSpec;
789 RINOK(folderSpec->Init(_path + name + FCHAR_PATH_SEPARATOR)); 818 RINOK(folderSpec->Init(_path + name + FCHAR_PATH_SEPARATOR))
790 *resultFolder = subFolder.Detach(); 819 *resultFolder = subFolder.Detach();
791 return S_OK; 820 return S_OK;
792} 821}
@@ -836,23 +865,23 @@ FString CFSFolder::GetRelPath(const CDirItem &item) const
836 return Folders[item.Parent] + item.Name; 865 return Folders[item.Parent] + item.Name;
837} 866}
838 867
839STDMETHODIMP CFSFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 868Z7_COM7F_IMF(CFSFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder))
840{ 869{
841 *resultFolder = 0; 870 *resultFolder = NULL;
842 const CDirItem &fi = Files[index]; 871 const CDirItem &fi = Files[index];
843 if (!fi.IsDir()) 872 if (!fi.IsDir())
844 return E_INVALIDARG; 873 return E_INVALIDARG;
845 return BindToFolderSpec(GetRelPath(fi), resultFolder); 874 return BindToFolderSpec(GetRelPath(fi), resultFolder);
846} 875}
847 876
848STDMETHODIMP CFSFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) 877Z7_COM7F_IMF(CFSFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder))
849{ 878{
850 return BindToFolderSpec(us2fs(name), resultFolder); 879 return BindToFolderSpec(us2fs(name), resultFolder);
851} 880}
852 881
853STDMETHODIMP CFSFolder::BindToParentFolder(IFolderFolder **resultFolder) 882Z7_COM7F_IMF(CFSFolder::BindToParentFolder(IFolderFolder **resultFolder))
854{ 883{
855 *resultFolder = 0; 884 *resultFolder = NULL;
856 /* 885 /*
857 if (_parentFolder) 886 if (_parentFolder)
858 { 887 {
@@ -914,17 +943,17 @@ STDMETHODIMP CFSFolder::BindToParentFolder(IFolderFolder **resultFolder)
914 return S_OK; 943 return S_OK;
915} 944}
916 945
917STDMETHODIMP CFSFolder::GetNumberOfProperties(UInt32 *numProperties) 946Z7_COM7F_IMF(CFSFolder::GetNumberOfProperties(UInt32 *numProperties))
918{ 947{
919 *numProperties = ARRAY_SIZE(kProps); 948 *numProperties = Z7_ARRAY_SIZE(kProps);
920 if (!_flatMode) 949 if (!_flatMode)
921 (*numProperties)--; 950 (*numProperties)--;
922 return S_OK; 951 return S_OK;
923} 952}
924 953
925STDMETHODIMP CFSFolder::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) 954IMP_IFolderFolder_GetProp(CFSFolder::GetPropertyInfo, kProps)
926 955
927STDMETHODIMP CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 956Z7_COM7F_IMF(CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value))
928{ 957{
929 COM_TRY_BEGIN 958 COM_TRY_BEGIN
930 NWindows::NCOM::CPropVariant prop; 959 NWindows::NCOM::CPropVariant prop;
@@ -938,7 +967,7 @@ STDMETHODIMP CFSFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)
938 COM_TRY_END 967 COM_TRY_END
939} 968}
940 969
941STDMETHODIMP CFSFolder::WasChanged(Int32 *wasChanged) 970Z7_COM7F_IMF(CFSFolder::WasChanged(Int32 *wasChanged))
942{ 971{
943 bool wasChangedMain = false; 972 bool wasChangedMain = false;
944 973
@@ -961,7 +990,7 @@ STDMETHODIMP CFSFolder::WasChanged(Int32 *wasChanged)
961 return S_OK; 990 return S_OK;
962} 991}
963 992
964STDMETHODIMP CFSFolder::Clone(IFolderFolder **resultFolder) 993Z7_COM7F_IMF(CFSFolder::Clone(IFolderFolder **resultFolder))
965{ 994{
966 CFSFolder *fsFolderSpec = new CFSFolder; 995 CFSFolder *fsFolderSpec = new CFSFolder;
967 CMyComPtr<IFolderFolder> folderNew = fsFolderSpec; 996 CMyComPtr<IFolderFolder> folderNew = fsFolderSpec;
@@ -970,35 +999,6 @@ STDMETHODIMP CFSFolder::Clone(IFolderFolder **resultFolder)
970 return S_OK; 999 return S_OK;
971} 1000}
972 1001
973HRESULT CFSFolder::GetItemsFullSize(const UInt32 *indices, UInt32 numItems, CFsFolderStat &stat)
974{
975 for (UInt32 i = 0; i < numItems; i++)
976 {
977 UInt32 index = indices[i];
978 /*
979 if (index >= Files.Size())
980 {
981 size += Streams[index - Files.Size()].Size;
982 // numFiles++;
983 continue;
984 }
985 */
986 const CDirItem &fi = Files[index];
987 if (fi.IsDir())
988 {
989 stat.Path = _path;
990 stat.Path += GetRelPath(fi);
991 RINOK(stat.Enumerate());
992 stat.NumFolders++;
993 }
994 else
995 {
996 stat.NumFiles++;
997 stat.Size += fi.Size;
998 }
999 }
1000 return S_OK;
1001}
1002 1002
1003/* 1003/*
1004HRESULT CFSFolder::GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress) 1004HRESULT CFSFolder::GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress)
@@ -1019,7 +1019,7 @@ HRESULT CFSFolder::GetItemFullSize(unsigned index, UInt64 &size, IProgress *prog
1019 return S_OK; 1019 return S_OK;
1020} 1020}
1021 1021
1022STDMETHODIMP CFSFolder::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress) 1022Z7_COM7F_IMF(CFSFolder::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress)
1023{ 1023{
1024 NCOM::CPropVariant prop; 1024 NCOM::CPropVariant prop;
1025 UInt64 size = 0; 1025 UInt64 size = 0;
@@ -1030,7 +1030,7 @@ STDMETHODIMP CFSFolder::GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgr
1030} 1030}
1031*/ 1031*/
1032 1032
1033STDMETHODIMP CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress) 1033Z7_COM7F_IMF(CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress))
1034{ 1034{
1035 if (index >= (UInt32)Files.Size()) 1035 if (index >= (UInt32)Files.Size())
1036 return S_OK; 1036 return S_OK;
@@ -1038,7 +1038,7 @@ STDMETHODIMP CFSFolder::CalcItemFullSize(UInt32 index, IProgress *progress)
1038 if (!fi.IsDir()) 1038 if (!fi.IsDir())
1039 return S_OK; 1039 return S_OK;
1040 CFsFolderStat stat(_path + GetRelPath(fi), progress); 1040 CFsFolderStat stat(_path + GetRelPath(fi), progress);
1041 RINOK(stat.Enumerate()); 1041 RINOK(stat.Enumerate())
1042 fi.Size = stat.Size; 1042 fi.Size = stat.Size;
1043 fi.NumFolders = stat.NumFolders; 1043 fi.NumFolders = stat.NumFolders;
1044 fi.NumFiles = stat.NumFiles; 1044 fi.NumFiles = stat.NumFiles;
@@ -1054,30 +1054,29 @@ void CFSFolder::GetAbsPath(const wchar_t *name, FString &absPath)
1054 absPath += us2fs(name); 1054 absPath += us2fs(name);
1055} 1055}
1056 1056
1057STDMETHODIMP CFSFolder::CreateFolder(const wchar_t *name, IProgress * /* progress */) 1057Z7_COM7F_IMF(CFSFolder::CreateFolder(const wchar_t *name, IProgress * /* progress */))
1058{ 1058{
1059 FString absPath; 1059 FString absPath;
1060 GetAbsPath(name, absPath); 1060 GetAbsPath(name, absPath);
1061 if (CreateDir(absPath)) 1061 if (CreateDir(absPath))
1062 return S_OK; 1062 return S_OK;
1063 if (::GetLastError() == ERROR_ALREADY_EXISTS) 1063 if (::GetLastError() != ERROR_ALREADY_EXISTS)
1064 return ::GetLastError(); 1064 if (CreateComplexDir(absPath))
1065 if (!CreateComplexDir(absPath)) 1065 return S_OK;
1066 return ::GetLastError(); 1066 return GetLastError_noZero_HRESULT();
1067 return S_OK;
1068} 1067}
1069 1068
1070STDMETHODIMP CFSFolder::CreateFile(const wchar_t *name, IProgress * /* progress */) 1069Z7_COM7F_IMF(CFSFolder::CreateFile(const wchar_t *name, IProgress * /* progress */))
1071{ 1070{
1072 FString absPath; 1071 FString absPath;
1073 GetAbsPath(name, absPath); 1072 GetAbsPath(name, absPath);
1074 NIO::COutFile outFile; 1073 NIO::COutFile outFile;
1075 if (!outFile.Create(absPath, false)) 1074 if (!outFile.Create(absPath, false))
1076 return ::GetLastError(); 1075 return GetLastError_noZero_HRESULT();
1077 return S_OK; 1076 return S_OK;
1078} 1077}
1079 1078
1080STDMETHODIMP CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress * /* progress */) 1079Z7_COM7F_IMF(CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress * /* progress */))
1081{ 1080{
1082 if (index >= (UInt32)Files.Size()) 1081 if (index >= (UInt32)Files.Size())
1083 return E_NOTIMPL; 1082 return E_NOTIMPL;
@@ -1088,13 +1087,13 @@ STDMETHODIMP CFSFolder::Rename(UInt32 index, const wchar_t *newName, IProgress *
1088 if (fi.Parent >= 0) 1087 if (fi.Parent >= 0)
1089 fullPrefix += Folders[fi.Parent]; 1088 fullPrefix += Folders[fi.Parent];
1090 if (!MyMoveFile(fullPrefix + fi.Name, fullPrefix + us2fs(newName))) 1089 if (!MyMoveFile(fullPrefix + fi.Name, fullPrefix + us2fs(newName)))
1091 return GetLastError(); 1090 return GetLastError_noZero_HRESULT();
1092 return S_OK; 1091 return S_OK;
1093} 1092}
1094 1093
1095STDMETHODIMP CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress) 1094Z7_COM7F_IMF(CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress *progress))
1096{ 1095{
1097 RINOK(progress->SetTotal(numItems)); 1096 RINOK(progress->SetTotal(numItems))
1098 // int prevDeletedFileIndex = -1; 1097 // int prevDeletedFileIndex = -1;
1099 for (UInt32 i = 0; i < numItems; i++) 1098 for (UInt32 i = 0; i < numItems; i++)
1100 { 1099 {
@@ -1123,15 +1122,15 @@ STDMETHODIMP CFSFolder::Delete(const UInt32 *indices, UInt32 numItems,IProgress
1123 result = DeleteFileAlways(fullPath); 1122 result = DeleteFileAlways(fullPath);
1124 } 1123 }
1125 if (!result) 1124 if (!result)
1126 return GetLastError(); 1125 return GetLastError_noZero_HRESULT();
1127 UInt64 completed = i; 1126 const UInt64 completed = i;
1128 RINOK(progress->SetCompleted(&completed)); 1127 RINOK(progress->SetCompleted(&completed))
1129 } 1128 }
1130 return S_OK; 1129 return S_OK;
1131} 1130}
1132 1131
1133STDMETHODIMP CFSFolder::SetProperty(UInt32 index, PROPID propID, 1132Z7_COM7F_IMF(CFSFolder::SetProperty(UInt32 index, PROPID propID,
1134 const PROPVARIANT *value, IProgress * /* progress */) 1133 const PROPVARIANT *value, IProgress * /* progress */))
1135{ 1134{
1136 if (index >= (UInt32)Files.Size()) 1135 if (index >= (UInt32)Files.Size())
1137 return E_INVALIDARG; 1136 return E_INVALIDARG;
@@ -1169,7 +1168,7 @@ STDMETHODIMP CFSFolder::SetProperty(UInt32 index, PROPID propID,
1169 return S_OK; 1168 return S_OK;
1170} 1169}
1171 1170
1172STDMETHODIMP CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) 1171Z7_COM7F_IMF(CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
1173{ 1172{
1174 if (index >= (UInt32)Files.Size()) 1173 if (index >= (UInt32)Files.Size())
1175 return E_INVALIDARG; 1174 return E_INVALIDARG;
@@ -1181,17 +1180,17 @@ STDMETHODIMP CFSFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)
1181 *iconIndex = iconIndexTemp; 1180 *iconIndex = iconIndexTemp;
1182 return S_OK; 1181 return S_OK;
1183 } 1182 }
1184 return GetLastError(); 1183 return GetLastError_noZero_HRESULT();
1185} 1184}
1186 1185
1187STDMETHODIMP CFSFolder::SetFlatMode(Int32 flatMode) 1186Z7_COM7F_IMF(CFSFolder::SetFlatMode(Int32 flatMode))
1188{ 1187{
1189 _flatMode = IntToBool(flatMode); 1188 _flatMode = IntToBool(flatMode);
1190 return S_OK; 1189 return S_OK;
1191} 1190}
1192 1191
1193/* 1192/*
1194STDMETHODIMP CFSFolder::SetShowNtfsStreamsMode(Int32 showStreamsMode) 1193Z7_COM7F_IMF(CFSFolder::SetShowNtfsStreamsMode(Int32 showStreamsMode)
1195{ 1194{
1196 _scanAltStreams = IntToBool(showStreamsMode); 1195 _scanAltStreams = IntToBool(showStreamsMode);
1197 return S_OK; 1196 return S_OK;
diff --git a/CPP/7zip/UI/FileManager/FSFolder.h b/CPP/7zip/UI/FileManager/FSFolder.h
index 4f8c344..fe8538a 100644
--- a/CPP/7zip/UI/FileManager/FSFolder.h
+++ b/CPP/7zip/UI/FileManager/FSFolder.h
@@ -1,7 +1,7 @@
1// FSFolder.h 1// FSFolder.h
2 2
3#ifndef __FS_FOLDER_H 3#ifndef ZIP7_INC_FS_FOLDER_H
4#define __FS_FOLDER_H 4#define ZIP7_INC_FS_FOLDER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7#include "../../../Common/MyBuffer.h" 7#include "../../../Common/MyBuffer.h"
@@ -78,7 +78,7 @@ struct CFsFolderStat
78 HRESULT Enumerate(); 78 HRESULT Enumerate();
79}; 79};
80 80
81class CFSFolder: 81class CFSFolder Z7_final:
82 public IFolderFolder, 82 public IFolderFolder,
83 public IArchiveGetRawProps, 83 public IArchiveGetRawProps,
84 public IFolderCompare, 84 public IFolderCompare,
@@ -95,42 +95,36 @@ class CFSFolder:
95 // public IFolderSetShowNtfsStreamsMode, 95 // public IFolderSetShowNtfsStreamsMode,
96 public CMyUnknownImp 96 public CMyUnknownImp
97{ 97{
98public: 98 Z7_COM_QI_BEGIN2(IFolderFolder)
99 MY_QUERYINTERFACE_BEGIN2(IFolderFolder) 99 Z7_COM_QI_ENTRY(IArchiveGetRawProps)
100 MY_QUERYINTERFACE_ENTRY(IArchiveGetRawProps) 100 Z7_COM_QI_ENTRY(IFolderCompare)
101 MY_QUERYINTERFACE_ENTRY(IFolderCompare)
102 #ifdef USE_UNICODE_FSTRING 101 #ifdef USE_UNICODE_FSTRING
103 MY_QUERYINTERFACE_ENTRY(IFolderGetItemName) 102 Z7_COM_QI_ENTRY(IFolderGetItemName)
104 #endif 103 #endif
105 MY_QUERYINTERFACE_ENTRY(IFolderWasChanged) 104 Z7_COM_QI_ENTRY(IFolderWasChanged)
106 // MY_QUERYINTERFACE_ENTRY(IFolderOperationsDeleteToRecycleBin) 105 // Z7_COM_QI_ENTRY(IFolderOperationsDeleteToRecycleBin)
107 MY_QUERYINTERFACE_ENTRY(IFolderOperations) 106 Z7_COM_QI_ENTRY(IFolderOperations)
108 MY_QUERYINTERFACE_ENTRY(IFolderCalcItemFullSize) 107 Z7_COM_QI_ENTRY(IFolderCalcItemFullSize)
109 MY_QUERYINTERFACE_ENTRY(IFolderClone) 108 Z7_COM_QI_ENTRY(IFolderClone)
110 MY_QUERYINTERFACE_ENTRY(IFolderGetSystemIconIndex) 109 Z7_COM_QI_ENTRY(IFolderGetSystemIconIndex)
111 MY_QUERYINTERFACE_ENTRY(IFolderSetFlatMode) 110 Z7_COM_QI_ENTRY(IFolderSetFlatMode)
112 // MY_QUERYINTERFACE_ENTRY(IFolderSetShowNtfsStreamsMode) 111 // Z7_COM_QI_ENTRY(IFolderSetShowNtfsStreamsMode)
113 MY_QUERYINTERFACE_END 112 Z7_COM_QI_END
114 MY_ADDREF_RELEASE 113 Z7_COM_ADDREF_RELEASE
115 114
116 115 Z7_IFACE_COM7_IMP(IFolderFolder)
117 INTERFACE_FolderFolder(;) 116 Z7_IFACE_COM7_IMP(IArchiveGetRawProps)
118 INTERFACE_IArchiveGetRawProps(;) 117 Z7_IFACE_COM7_IMP(IFolderCompare)
119 INTERFACE_FolderOperations(;)
120
121 STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw);
122
123 #ifdef USE_UNICODE_FSTRING 118 #ifdef USE_UNICODE_FSTRING
124 INTERFACE_IFolderGetItemName(;) 119 Z7_IFACE_COM7_IMP(IFolderGetItemName)
125 #endif 120 #endif
126 STDMETHOD(WasChanged)(Int32 *wasChanged); 121 Z7_IFACE_COM7_IMP(IFolderWasChanged)
127 STDMETHOD(Clone)(IFolderFolder **resultFolder); 122 Z7_IFACE_COM7_IMP(IFolderOperations)
128 STDMETHOD(CalcItemFullSize)(UInt32 index, IProgress *progress); 123 Z7_IFACE_COM7_IMP(IFolderCalcItemFullSize)
129 124 Z7_IFACE_COM7_IMP(IFolderClone)
130 STDMETHOD(SetFlatMode)(Int32 flatMode); 125 Z7_IFACE_COM7_IMP(IFolderGetSystemIconIndex)
131 // STDMETHOD(SetShowNtfsStreamsMode)(Int32 showStreamsMode); 126 Z7_IFACE_COM7_IMP(IFolderSetFlatMode)
132 127 // Z7_IFACE_COM7_IMP(IFolderSetShowNtfsStreamsMode)
133 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex);
134 128
135private: 129private:
136 FString _path; 130 FString _path;
@@ -150,9 +144,7 @@ private:
150 NWindows::NFile::NFind::CFindChangeNotification _findChangeNotification; 144 NWindows::NFile::NFind::CFindChangeNotification _findChangeNotification;
151 #endif 145 #endif
152 146
153 HRESULT GetItemsFullSize(const UInt32 *indices, UInt32 numItems, CFsFolderStat &stat); 147 // HRESULT GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress);
154
155 HRESULT GetItemFullSize(unsigned index, UInt64 &size, IProgress *progress);
156 void GetAbsPath(const wchar_t *name, FString &absPath); 148 void GetAbsPath(const wchar_t *name, FString &absPath);
157 HRESULT BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder); 149 HRESULT BindToFolderSpec(CFSTR name, IFolderFolder **resultFolder);
158 150
@@ -215,6 +207,15 @@ struct CCopyStateIO
215 207
216HRESULT SendLastErrorMessage(IFolderOperationsExtractCallback *callback, const FString &fileName); 208HRESULT SendLastErrorMessage(IFolderOperationsExtractCallback *callback, const FString &fileName);
217 209
210/* destDirPrefix is allowed to be:
211 "full_path\" or "full_path:" for alt streams */
212
213HRESULT CopyFileSystemItems(
214 const UStringVector &itemsPaths,
215 const FString &destDirPrefix,
216 bool moveMode,
217 IFolderOperationsExtractCallback *callback);
218
218} 219}
219 220
220#endif 221#endif
diff --git a/CPP/7zip/UI/FileManager/FSFolderCopy.cpp b/CPP/7zip/UI/FileManager/FSFolderCopy.cpp
index 4ca931b..db4ae0a 100644
--- a/CPP/7zip/UI/FileManager/FSFolderCopy.cpp
+++ b/CPP/7zip/UI/FileManager/FSFolderCopy.cpp
@@ -4,8 +4,6 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#include <WinBase.h>
8
9#include "../../../Common/Defs.h" 7#include "../../../Common/Defs.h"
10#include "../../../Common/StringConvert.h" 8#include "../../../Common/StringConvert.h"
11#include "../../../Common/Wildcard.h" 9#include "../../../Common/Wildcard.h"
@@ -29,11 +27,11 @@ using namespace NFind;
29extern bool g_IsNT; 27extern bool g_IsNT;
30#endif 28#endif
31 29
32#define MY_CAST_FUNC (void(*)())
33// #define MY_CAST_FUNC
34
35namespace NFsFolder { 30namespace NFsFolder {
36 31
32static const char * const k_CannotCopyDirToAltStream = "Cannot copy folder as alternate stream";
33
34
37HRESULT CCopyStateIO::MyCopyFile(CFSTR inPath, CFSTR outPath, DWORD attrib) 35HRESULT CCopyStateIO::MyCopyFile(CFSTR inPath, CFSTR outPath, DWORD attrib)
38{ 36{
39 ErrorFileIndex = -1; 37 ErrorFileIndex = -1;
@@ -85,11 +83,15 @@ HRESULT CCopyStateIO::MyCopyFile(CFSTR inPath, CFSTR outPath, DWORD attrib)
85 if (Progress) 83 if (Progress)
86 { 84 {
87 UInt64 completed = StartPos + CurrentSize; 85 UInt64 completed = StartPos + CurrentSize;
88 RINOK(Progress->SetCompleted(&completed)); 86 RINOK(Progress->SetCompleted(&completed))
89 } 87 }
90 } 88 }
91 } 89 }
92 90
91 /* SetFileAttrib("path:alt_stream_name") sets attributes for main file "path".
92 But we don't want to change attributes of main file, when we write alt stream.
93 So we need INVALID_FILE_ATTRIBUTES for alt stream here */
94
93 if (attrib != INVALID_FILE_ATTRIBUTES) 95 if (attrib != INVALID_FILE_ATTRIBUTES)
94 SetFileAttrib(outPath, attrib); 96 SetFileAttrib(outPath, attrib);
95 97
@@ -177,7 +179,7 @@ static DWORD CALLBACK CopyProgressRoutine(
177 pi.FileSize = (UInt64)TotalFileSize.QuadPart; 179 pi.FileSize = (UInt64)TotalFileSize.QuadPart;
178 pi.ProgressResult = pi.Progress->SetTotal(pi.TotalSize); 180 pi.ProgressResult = pi.Progress->SetTotal(pi.TotalSize);
179 } 181 }
180 UInt64 completed = pi.StartPos + TotalBytesTransferred.QuadPart; 182 const UInt64 completed = pi.StartPos + (UInt64)TotalBytesTransferred.QuadPart;
181 pi.ProgressResult = pi.Progress->SetCompleted(&completed); 183 pi.ProgressResult = pi.Progress->SetCompleted(&completed);
182 return (pi.ProgressResult == S_OK ? PROGRESS_CONTINUE : PROGRESS_CANCEL); 184 return (pi.ProgressResult == S_OK ? PROGRESS_CONTINUE : PROGRESS_CANCEL);
183} 185}
@@ -214,6 +216,7 @@ struct CCopyState
214 IFolderOperationsExtractCallback *Callback; 216 IFolderOperationsExtractCallback *Callback;
215 bool MoveMode; 217 bool MoveMode;
216 bool UseReadWriteMode; 218 bool UseReadWriteMode;
219 bool IsAltStreamsDest;
217 220
218 Func_CopyFileExW my_CopyFileExW; 221 Func_CopyFileExW my_CopyFileExW;
219 #ifndef UNDER_CE 222 #ifndef UNDER_CE
@@ -248,23 +251,27 @@ void CCopyState::Prepare()
248 my_CopyFileExA = NULL; 251 my_CopyFileExA = NULL;
249 if (!g_IsNT) 252 if (!g_IsNT)
250 { 253 {
251 my_CopyFileExA = (Func_CopyFileExA) 254 my_CopyFileExA = Z7_GET_PROC_ADDRESS(
252 MY_CAST_FUNC 255 Func_CopyFileExA, ::GetModuleHandleA("kernel32.dll"),
253 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "CopyFileExA"); 256 "CopyFileExA");
254 } 257 }
255 else 258 else
256 #endif 259 #endif
257 { 260 {
258 HMODULE module = ::GetModuleHandleW( 261 const HMODULE module = ::GetModuleHandleW(
259 #ifdef UNDER_CE 262 #ifdef UNDER_CE
260 L"coredll.dll" 263 L"coredll.dll"
261 #else 264 #else
262 L"kernel32.dll" 265 L"kernel32.dll"
263 #endif 266 #endif
264 ); 267 );
265 my_CopyFileExW = (Func_CopyFileExW)My_GetProcAddress(module, "CopyFileExW"); 268 my_CopyFileExW = Z7_GET_PROC_ADDRESS(
269 Func_CopyFileExW, module,
270 "CopyFileExW");
266 #ifndef UNDER_CE 271 #ifndef UNDER_CE
267 my_MoveFileWithProgressW = (Func_MoveFileWithProgressW)My_GetProcAddress(module, "MoveFileWithProgressW"); 272 my_MoveFileWithProgressW = Z7_GET_PROC_ADDRESS(
273 Func_MoveFileWithProgressW, module,
274 "MoveFileWithProgressW");
268 #endif 275 #endif
269 } 276 }
270} 277}
@@ -308,7 +315,7 @@ bool CCopyState::CopyFile_Sys(CFSTR oldFile, CFSTR newFile)
308 if (CopyFile_NT(fs2us(oldFile), fs2us(newFile))) 315 if (CopyFile_NT(fs2us(oldFile), fs2us(newFile)))
309 return true; 316 return true;
310 } 317 }
311 #ifdef WIN_LONG_PATH 318 #ifdef Z7_LONG_PATH
312 if (USE_SUPER_PATH_2) 319 if (USE_SUPER_PATH_2)
313 { 320 {
314 if (IsCallbackProgressError()) 321 if (IsCallbackProgressError())
@@ -337,7 +344,7 @@ bool CCopyState::MoveFile_Sys(CFSTR oldFile, CFSTR newFile)
337 &ProgressInfo, MOVEFILE_COPY_ALLOWED)) 344 &ProgressInfo, MOVEFILE_COPY_ALLOWED))
338 return true; 345 return true;
339 } 346 }
340 #ifdef WIN_LONG_PATH 347 #ifdef Z7_LONG_PATH
341 if ((!(USE_MAIN_PATH_2) || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) && USE_SUPER_PATH_2) 348 if ((!(USE_MAIN_PATH_2) || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) && USE_SUPER_PATH_2)
342 { 349 {
343 if (IsCallbackProgressError()) 350 if (IsCallbackProgressError())
@@ -404,7 +411,7 @@ static HRESULT CopyFile_Ask(
404 state.MoveMode ? 411 state.MoveMode ?
405 "Cannot move file onto itself" : 412 "Cannot move file onto itself" :
406 "Cannot copy file onto itself" 413 "Cannot copy file onto itself"
407 , destPath)); 414 , destPath))
408 return E_ABORT; 415 return E_ABORT;
409 } 416 }
410 417
@@ -416,12 +423,12 @@ static HRESULT CopyFile_Ask(
416 &srcFileInfo.MTime, &srcFileInfo.Size, 423 &srcFileInfo.MTime, &srcFileInfo.Size,
417 fs2us(destPath), 424 fs2us(destPath),
418 &destPathResult, 425 &destPathResult,
419 &writeAskResult)); 426 &writeAskResult))
420 427
421 if (IntToBool(writeAskResult)) 428 if (IntToBool(writeAskResult))
422 { 429 {
423 FString destPathNew = us2fs((LPCOLESTR)destPathResult); 430 FString destPathNew = us2fs((LPCOLESTR)destPathResult);
424 RINOK(state.Callback->SetCurrentFilePath(fs2us(srcPath))); 431 RINOK(state.Callback->SetCurrentFilePath(fs2us(srcPath)))
425 432
426 if (state.UseReadWriteMode) 433 if (state.UseReadWriteMode)
427 { 434 {
@@ -431,7 +438,8 @@ static HRESULT CopyFile_Ask(
431 state2.TotalSize = state.ProgressInfo.TotalSize; 438 state2.TotalSize = state.ProgressInfo.TotalSize;
432 state2.StartPos = state.ProgressInfo.StartPos; 439 state2.StartPos = state.ProgressInfo.StartPos;
433 440
434 RINOK(state2.MyCopyFile(srcPath, destPathNew, srcFileInfo.Attrib)); 441 RINOK(state2.MyCopyFile(srcPath, destPathNew,
442 state.IsAltStreamsDest ? INVALID_FILE_ATTRIBUTES: srcFileInfo.Attrib))
435 443
436 if (state2.ErrorFileIndex >= 0) 444 if (state2.ErrorFileIndex >= 0)
437 { 445 {
@@ -442,7 +450,7 @@ static HRESULT CopyFile_Ask(
442 errorName = srcPath; 450 errorName = srcPath;
443 else 451 else
444 errorName = destPathNew; 452 errorName = destPathNew;
445 RINOK(SendMessageError(state.Callback, state2.ErrorMessage, errorName)); 453 RINOK(SendMessageError(state.Callback, state2.ErrorMessage, errorName))
446 return E_ABORT; 454 return E_ABORT;
447 } 455 }
448 state.ProgressInfo.StartPos += state2.CurrentSize; 456 state.ProgressInfo.StartPos += state2.CurrentSize;
@@ -455,11 +463,11 @@ static HRESULT CopyFile_Ask(
455 res = state.MoveFile_Sys(srcPath, destPathNew); 463 res = state.MoveFile_Sys(srcPath, destPathNew);
456 else 464 else
457 res = state.CopyFile_Sys(srcPath, destPathNew); 465 res = state.CopyFile_Sys(srcPath, destPathNew);
458 RINOK(state.ProgressInfo.ProgressResult); 466 RINOK(state.ProgressInfo.ProgressResult)
459 if (!res) 467 if (!res)
460 { 468 {
461 // GetLastError() is ERROR_REQUEST_ABORTED in case of PROGRESS_CANCEL. 469 // GetLastError() is ERROR_REQUEST_ABORTED in case of PROGRESS_CANCEL.
462 RINOK(SendMessageError(state.Callback, GetLastErrorMessage(), destPathNew)); 470 RINOK(SendMessageError(state.Callback, GetLastErrorMessage(), destPathNew))
463 return E_ABORT; 471 return E_ABORT;
464 } 472 }
465 state.ProgressInfo.StartPos += state.ProgressInfo.FileSize; 473 state.ProgressInfo.StartPos += state.ProgressInfo.FileSize;
@@ -470,7 +478,7 @@ static HRESULT CopyFile_Ask(
470 if (state.ProgressInfo.TotalSize >= srcFileInfo.Size) 478 if (state.ProgressInfo.TotalSize >= srcFileInfo.Size)
471 { 479 {
472 state.ProgressInfo.TotalSize -= srcFileInfo.Size; 480 state.ProgressInfo.TotalSize -= srcFileInfo.Size;
473 RINOK(state.ProgressInfo.Progress->SetTotal(state.ProgressInfo.TotalSize)); 481 RINOK(state.ProgressInfo.Progress->SetTotal(state.ProgressInfo.TotalSize))
474 } 482 }
475 } 483 }
476 return state.CallProgress(); 484 return state.CallProgress();
@@ -499,7 +507,7 @@ static HRESULT CopyFolder(
499 const FString &srcPath, // without TAIL separator 507 const FString &srcPath, // without TAIL separator
500 const FString &destPath) // without TAIL separator 508 const FString &destPath) // without TAIL separator
501{ 509{
502 RINOK(state.CallProgress()); 510 RINOK(state.CallProgress())
503 511
504 if (IsDestChild(srcPath, destPath)) 512 if (IsDestChild(srcPath, destPath))
505 { 513 {
@@ -507,7 +515,7 @@ static HRESULT CopyFolder(
507 state.MoveMode ? 515 state.MoveMode ?
508 "Cannot copy folder onto itself" : 516 "Cannot copy folder onto itself" :
509 "Cannot move folder onto itself" 517 "Cannot move folder onto itself"
510 , destPath)); 518 , destPath))
511 return E_ABORT; 519 return E_ABORT;
512 } 520 }
513 521
@@ -521,7 +529,7 @@ static HRESULT CopyFolder(
521 529
522 if (!CreateComplexDir(destPath)) 530 if (!CreateComplexDir(destPath))
523 { 531 {
524 RINOK(SendMessageError(state.Callback, "Cannot create folder", destPath)); 532 RINOK(SendMessageError(state.Callback, "Cannot create folder", destPath))
525 return E_ABORT; 533 return E_ABORT;
526 } 534 }
527 535
@@ -547,7 +555,7 @@ static HRESULT CopyFolder(
547 } 555 }
548 else 556 else
549 { 557 {
550 RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2)); 558 RINOK(CopyFile_Ask(state, srcPath2, fi, destPath2))
551 } 559 }
552 } 560 }
553 561
@@ -555,7 +563,7 @@ static HRESULT CopyFolder(
555 { 563 {
556 if (!RemoveDir(srcPath)) 564 if (!RemoveDir(srcPath))
557 { 565 {
558 RINOK(SendMessageError(state.Callback, "Cannot remove folder", srcPath)); 566 RINOK(SendMessageError(state.Callback, "Cannot remove folder", srcPath))
559 return E_ABORT; 567 return E_ABORT;
560 } 568 }
561 } 569 }
@@ -563,38 +571,67 @@ static HRESULT CopyFolder(
563 return S_OK; 571 return S_OK;
564} 572}
565 573
566STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, 574Z7_COM7F_IMF(CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems,
567 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */, 575 Int32 /* includeAltStreams */, Int32 /* replaceAltStreamColon */,
568 const wchar_t *path, IFolderOperationsExtractCallback *callback) 576 const wchar_t *path, IFolderOperationsExtractCallback *callback))
569{ 577{
570 if (numItems == 0) 578 if (numItems == 0)
571 return S_OK; 579 return S_OK;
572 580
573 FString destPath = us2fs(path); 581 const FString destPath = us2fs(path);
574 if (destPath.IsEmpty()) 582 if (destPath.IsEmpty())
575 return E_INVALIDARG; 583 return E_INVALIDARG;
576 584
577 bool isAltDest = NName::IsAltPathPrefix(destPath); 585 const bool isAltDest = NName::IsAltPathPrefix(destPath);
578 bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back())); 586 const bool isDirectPath = (!isAltDest && !IsPathSepar(destPath.Back()));
579 587
580 if (isDirectPath) 588 if (isDirectPath)
581 {
582 if (numItems > 1) 589 if (numItems > 1)
583 return E_INVALIDARG; 590 return E_INVALIDARG;
584 }
585 591
586 CFsFolderStat stat; 592 CFsFolderStat stat;
587 stat.Progress = callback; 593 stat.Progress = callback;
588 RINOK(GetItemsFullSize(indices, numItems, stat));
589 594
595 UInt32 i;
596 for (i = 0; i < numItems; i++)
597 {
598 const UInt32 index = indices[i];
599 /*
600 if (index >= Files.Size())
601 {
602 size += Streams[index - Files.Size()].Size;
603 // numFiles++;
604 continue;
605 }
606 */
607 const CDirItem &fi = Files[index];
608 if (fi.IsDir())
609 {
610 if (!isAltDest)
611 {
612 stat.Path = _path;
613 stat.Path += GetRelPath(fi);
614 RINOK(stat.Enumerate())
615 }
616 stat.NumFolders++;
617 }
618 else
619 {
620 stat.NumFiles++;
621 stat.Size += fi.Size;
622 }
623 }
624
625 /*
590 if (stat.NumFolders != 0 && isAltDest) 626 if (stat.NumFolders != 0 && isAltDest)
591 return E_NOTIMPL; 627 return E_NOTIMPL;
628 */
592 629
593 RINOK(callback->SetTotal(stat.Size)); 630 RINOK(callback->SetTotal(stat.Size))
594 RINOK(callback->SetNumFiles(stat.NumFiles)); 631 RINOK(callback->SetNumFiles(stat.NumFiles))
595 632
596 UInt64 completedSize = 0; 633 UInt64 completedSize = 0;
597 RINOK(callback->SetCompleted(&completedSize)); 634 RINOK(callback->SetCompleted(&completedSize))
598 635
599 CCopyState state; 636 CCopyState state;
600 state.ProgressInfo.TotalSize = stat.Size; 637 state.ProgressInfo.TotalSize = stat.Size;
@@ -603,12 +640,16 @@ STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num
603 state.ProgressInfo.Init(); 640 state.ProgressInfo.Init();
604 state.Callback = callback; 641 state.Callback = callback;
605 state.MoveMode = IntToBool(moveMode); 642 state.MoveMode = IntToBool(moveMode);
643 state.IsAltStreamsDest = isAltDest;
644 /* CopyFileW(fromFile, toFile:altStream) returns ERROR_INVALID_PARAMETER,
645 if there are alt streams in fromFile.
646 So we don't use CopyFileW() for alt Streams. */
606 state.UseReadWriteMode = isAltDest; 647 state.UseReadWriteMode = isAltDest;
607 state.Prepare(); 648 state.Prepare();
608 649
609 for (UInt32 i = 0; i < numItems; i++) 650 for (i = 0; i < numItems; i++)
610 { 651 {
611 UInt32 index = indices[i]; 652 const UInt32 index = indices[i];
612 if (index >= (UInt32)Files.Size()) 653 if (index >= (UInt32)Files.Size())
613 continue; 654 continue;
614 const CDirItem &fi = Files[index]; 655 const CDirItem &fi = Files[index];
@@ -620,57 +661,148 @@ STDMETHODIMP CFSFolder::CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 num
620 661
621 if (fi.IsDir()) 662 if (fi.IsDir())
622 { 663 {
623 RINOK(CopyFolder(state, srcPath, destPath2)); 664 if (isAltDest)
665 {
666 RINOK(SendMessageError(callback, k_CannotCopyDirToAltStream, srcPath))
667 }
668 else
669 {
670 RINOK(CopyFolder(state, srcPath, destPath2))
671 }
624 } 672 }
625 else 673 else
626 { 674 {
627 RINOK(CopyFile_Ask(state, srcPath, fi, destPath2)); 675 RINOK(CopyFile_Ask(state, srcPath, fi, destPath2))
628 } 676 }
629 } 677 }
630 return S_OK; 678 return S_OK;
631} 679}
632 680
633STDMETHODIMP CFSFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */, 681
634 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */) 682
683/* we can call CopyFileSystemItems() from CDropTarget::Drop() */
684
685HRESULT CopyFileSystemItems(
686 const UStringVector &itemsPaths,
687 const FString &destDirPrefix,
688 bool moveMode,
689 IFolderOperationsExtractCallback *callback)
635{ 690{
636 /* 691 if (itemsPaths.IsEmpty())
637 UInt64 numFolders, numFiles, totalSize; 692 return S_OK;
638 numFiles = numFolders = totalSize = 0; 693
639 UInt32 i; 694 if (destDirPrefix.IsEmpty())
640 for (i = 0; i < numItems; i++) 695 return E_INVALIDARG;
641 {
642 UString path = (UString)fromFolderPath + itemsPaths[i];
643 696
697 const bool isAltDest = NName::IsAltPathPrefix(destDirPrefix);
698
699 CFsFolderStat stat;
700 stat.Progress = callback;
701
702 {
703 FOR_VECTOR (i, itemsPaths)
704 {
705 const UString &path = itemsPaths[i];
644 CFileInfo fi; 706 CFileInfo fi;
645 if (!FindFile(path, fi)) 707 if (!fi.Find(us2fs(path)))
646 return ::GetLastError(); 708 continue;
647 if (fi.IsDir()) 709 if (fi.IsDir())
648 { 710 {
649 UInt64 subFolders, subFiles, subSize; 711 if (!isAltDest)
650 RINOK(GetFolderSize(CombinePath(path, fi.Name), subFolders, subFiles, subSize, progress)); 712 {
651 numFolders += subFolders; 713 stat.Path = us2fs(path);
652 numFolders++; 714 RINOK(stat.Enumerate())
653 numFiles += subFiles; 715 }
654 totalSize += subSize; 716 stat.NumFolders++;
655 } 717 }
656 else 718 else
657 { 719 {
658 numFiles++; 720 stat.NumFiles++;
659 totalSize += fi.Size; 721 stat.Size += fi.Size;
660 } 722 }
661 } 723 }
662 RINOK(progress->SetTotal(totalSize)); 724 }
663 RINOK(callback->SetNumFiles(numFiles)); 725
664 for (i = 0; i < numItems; i++) 726 /*
727 if (stat.NumFolders != 0 && isAltDest)
728 return E_NOTIMPL;
729 */
730
731 RINOK(callback->SetTotal(stat.Size))
732 // RINOK(progress->SetNumFiles(stat.NumFiles));
733
734 UInt64 completedSize = 0;
735 RINOK(callback->SetCompleted(&completedSize))
736
737 CCopyState state;
738 state.ProgressInfo.TotalSize = stat.Size;
739 state.ProgressInfo.StartPos = 0;
740 state.ProgressInfo.Progress = callback;
741 state.ProgressInfo.Init();
742 state.Callback = callback;
743 state.MoveMode = moveMode;
744 state.IsAltStreamsDest = isAltDest;
745 /* CopyFileW(fromFile, toFile:altStream) returns ERROR_INVALID_PARAMETER,
746 if there are alt streams in fromFile.
747 So we don't use CopyFileW() for alt Streams. */
748 state.UseReadWriteMode = isAltDest;
749 state.Prepare();
750
751 FOR_VECTOR (i, itemsPaths)
665 { 752 {
666 UString path = (UString)fromFolderPath + itemsPaths[i]; 753 const UString path = itemsPaths[i];
754 CFileInfo fi;
755
756 if (!fi.Find(us2fs(path)))
757 {
758 RINOK(SendMessageError(callback, "Cannot find the file", us2fs(path)))
759 continue;
760 }
761
762 FString destPath = destDirPrefix;
763 destPath += fi.Name;
764
765 if (fi.IsDir())
766 {
767 if (isAltDest)
768 {
769 RINOK(SendMessageError(callback, k_CannotCopyDirToAltStream, us2fs(path)))
770 }
771 else
772 {
773 RINOK(CopyFolder(state, us2fs(path), destPath))
774 }
775 }
776 else
777 {
778 RINOK(CopyFile_Ask(state, us2fs(path), fi, destPath))
779 }
667 } 780 }
668 return S_OK; 781 return S_OK;
782}
783
784
785/* we don't use CFSFolder::CopyFrom() because the caller of CopyFrom()
786 is optimized for IFolderArchiveUpdateCallback interface,
787 but we want to use IFolderOperationsExtractCallback interface instead */
788
789Z7_COM7F_IMF(CFSFolder::CopyFrom(Int32 /* moveMode */, const wchar_t * /* fromFolderPath */,
790 const wchar_t * const * /* itemsPaths */, UInt32 /* numItems */, IProgress * /* progress */))
791{
792 /*
793 Z7_DECL_CMyComPtr_QI_FROM(
794 IFolderOperationsExtractCallback,
795 callback, progress)
796 if (!callback)
797 return E_NOTIMPL;
798 return CopyFileSystemItems(_path,
799 moveMode, fromDirPrefix,
800 itemsPaths, numItems, callback);
669 */ 801 */
670 return E_NOTIMPL; 802 return E_NOTIMPL;
671} 803}
672 804
673STDMETHODIMP CFSFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */) 805Z7_COM7F_IMF(CFSFolder::CopyFromFile(UInt32 /* index */, const wchar_t * /* fullFilePath */, IProgress * /* progress */))
674{ 806{
675 return E_NOTIMPL; 807 return E_NOTIMPL;
676} 808}
diff --git a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp
index a7873fe..e4e9997 100644
--- a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp
+++ b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.cpp
@@ -26,8 +26,15 @@ struct CThreadArchiveOpen
26 UString ArcFormat; 26 UString ArcFormat;
27 CMyComPtr<IInStream> InStream; 27 CMyComPtr<IInStream> InStream;
28 CMyComPtr<IFolderManager> FolderManager; 28 CMyComPtr<IFolderManager> FolderManager;
29 CMyComPtr<IProgress> OpenCallback; 29 CMyComPtr<IProgress> OpenCallbackProgress;
30
30 COpenArchiveCallback *OpenCallbackSpec; 31 COpenArchiveCallback *OpenCallbackSpec;
32 /*
33 CMyComPtr<IUnknown>
34 // CMyComPtr<IProgress>
35 // CMyComPtr<IArchiveOpenCallback>
36 OpenCallbackSpec_Ref;
37 */
31 38
32 CMyComPtr<IFolderFolder> Folder; 39 CMyComPtr<IFolderFolder> Folder;
33 HRESULT Result; 40 HRESULT Result;
@@ -37,7 +44,7 @@ struct CThreadArchiveOpen
37 try 44 try
38 { 45 {
39 CProgressCloser closer(OpenCallbackSpec->ProgressDialog); 46 CProgressCloser closer(OpenCallbackSpec->ProgressDialog);
40 Result = FolderManager->OpenFolderFile(InStream, Path, ArcFormat, &Folder, OpenCallback); 47 Result = FolderManager->OpenFolderFile(InStream, Path, ArcFormat, &Folder, OpenCallbackProgress);
41 } 48 }
42 catch(...) { Result = E_FAIL; } 49 catch(...) { Result = E_FAIL; }
43 } 50 }
@@ -62,7 +69,7 @@ static int FindPlugin(const CObjectVector<CPluginInfo> &plugins, const UString &
62static void SplitNameToPureNameAndExtension(const FString &fullName, 69static void SplitNameToPureNameAndExtension(const FString &fullName,
63 FString &pureName, FString &extensionDelimiter, FString &extension) 70 FString &pureName, FString &extensionDelimiter, FString &extension)
64{ 71{
65 int index = fullName.ReverseFind_Dot(); 72 const int index = fullName.ReverseFind_Dot();
66 if (index < 0) 73 if (index < 0)
67 { 74 {
68 pureName = fullName; 75 pureName = fullName;
@@ -71,7 +78,7 @@ static void SplitNameToPureNameAndExtension(const FString &fullName,
71 } 78 }
72 else 79 else
73 { 80 {
74 pureName.SetFrom(fullName, index); 81 pureName.SetFrom(fullName, (unsigned)index);
75 extensionDelimiter = '.'; 82 extensionDelimiter = '.';
76 extension = fullName.Ptr((unsigned)index + 1); 83 extension = fullName.Ptr((unsigned)index + 1);
77 } 84 }
@@ -229,16 +236,21 @@ static void GetFolderError(CMyComPtr<IFolderFolder> &folder, UString &open_Error
229 } 236 }
230} 237}
231 238
239#ifdef _MSC_VER
240#pragma warning(error : 4702) // unreachable code
241#endif
232 242
233HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream, 243HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream,
234 const FString &path, const UString &arcFormat, HWND parentWindow) 244 const FString &path, const UString &arcFormat, HWND parentWindow)
235{ 245{
246 /*
236 CObjectVector<CPluginInfo> plugins; 247 CObjectVector<CPluginInfo> plugins;
237 ReadFileFolderPluginInfoList(plugins); 248 ReadFileFolderPluginInfoList(plugins);
249 */
238 250
239 FString extension, name, pureName, dot; 251 FString extension, name, pureName, dot;
240 252
241 int slashPos = path.ReverseFind_PathSepar(); 253 const int slashPos = path.ReverseFind_PathSepar();
242 FString dirPrefix; 254 FString dirPrefix;
243 FString fileName; 255 FString fileName;
244 if (slashPos >= 0) 256 if (slashPos >= 0)
@@ -273,31 +285,48 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream,
273 285
274 ErrorMessage.Empty(); 286 ErrorMessage.Empty();
275 287
276 FOR_VECTOR (i, plugins) 288 // FOR_VECTOR (i, plugins)
277 { 289 // {
290 /*
278 const CPluginInfo &plugin = plugins[i]; 291 const CPluginInfo &plugin = plugins[i];
279 if (!plugin.ClassIDDefined) 292 if (!plugin.ClassID_Defined && !plugin.FilePath.IsEmpty())
280 continue; 293 continue;
294 */
281 CPluginLibrary library; 295 CPluginLibrary library;
282 296
283 CThreadArchiveOpen t; 297 CThreadArchiveOpen t;
284 298
285 if (plugin.FilePath.IsEmpty()) 299 // if (plugin.FilePath.IsEmpty())
286 t.FolderManager = new CArchiveFolderManager; 300 t.FolderManager = new CArchiveFolderManager;
301 /*
287 else if (library.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &t.FolderManager) != S_OK) 302 else if (library.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &t.FolderManager) != S_OK)
288 continue; 303 continue;
304 */
289 305
306 COpenArchiveCallback OpenCallbackSpec_loc;
307 t.OpenCallbackSpec = &OpenCallbackSpec_loc;
308 /*
290 t.OpenCallbackSpec = new COpenArchiveCallback; 309 t.OpenCallbackSpec = new COpenArchiveCallback;
291 t.OpenCallback = t.OpenCallbackSpec; 310 t.OpenCallbackSpec_Ref = t.OpenCallbackSpec;
311 */
292 t.OpenCallbackSpec->PasswordIsDefined = Encrypted; 312 t.OpenCallbackSpec->PasswordIsDefined = Encrypted;
293 t.OpenCallbackSpec->Password = Password; 313 t.OpenCallbackSpec->Password = Password;
294 t.OpenCallbackSpec->ParentWindow = parentWindow; 314 t.OpenCallbackSpec->ParentWindow = parentWindow;
295 315
316 /* COpenCallbackImp object will exist after Open stage for multivolume archives */
317 COpenCallbackImp *openCallbackSpec = new COpenCallbackImp;
318 t.OpenCallbackProgress = openCallbackSpec;
319 // openCallbackSpec->Callback_Ref = t.OpenCallbackSpec;
320 // we set pointer without reference counter:
321 openCallbackSpec->Callback =
322 // openCallbackSpec->ReOpenCallback =
323 t.OpenCallbackSpec;
324
296 if (inStream) 325 if (inStream)
297 t.OpenCallbackSpec->SetSubArchiveName(fs2us(fileName)); 326 openCallbackSpec->SetSubArchiveName(fs2us(fileName));
298 else 327 else
299 { 328 {
300 RINOK(t.OpenCallbackSpec->LoadFileInfo2(dirPrefix, fileName)); 329 RINOK(openCallbackSpec->Init2(dirPrefix, fileName))
301 } 330 }
302 331
303 t.InStream = inStream; 332 t.InStream = inStream;
@@ -315,10 +344,20 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream,
315 344
316 { 345 {
317 NWindows::CThread thread; 346 NWindows::CThread thread;
318 RINOK(thread.Create(CThreadArchiveOpen::MyThreadFunction, &t)); 347 const WRes wres = thread.Create(CThreadArchiveOpen::MyThreadFunction, &t);
348 if (wres != 0)
349 return HRESULT_FROM_WIN32(wres);
319 t.OpenCallbackSpec->StartProgressDialog(progressTitle, thread); 350 t.OpenCallbackSpec->StartProgressDialog(progressTitle, thread);
320 } 351 }
321 352
353 /*
354 if archive is multivolume:
355 COpenCallbackImp object will exist after Open stage.
356 COpenCallbackImp object will be deleted when last reference
357 from each volume object (CInFileStreamVol) will be closed (when archive will be closed).
358 */
359 t.OpenCallbackProgress.Release();
360
322 if (t.Result != S_FALSE && t.Result != S_OK) 361 if (t.Result != S_FALSE && t.Result != S_OK)
323 return t.Result; 362 return t.Result;
324 363
@@ -351,7 +390,5 @@ HRESULT CFfpOpen::OpenFileFolderPlugin(IInStream *inStream,
351 } 390 }
352 391
353 return t.Result; 392 return t.Result;
354 } 393 // }
355
356 return S_FALSE;
357} 394}
diff --git a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h
index a1f2f10..8802765 100644
--- a/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h
+++ b/CPP/7zip/UI/FileManager/FileFolderPluginOpen.h
@@ -1,13 +1,13 @@
1// FileFolderPluginOpen.h 1// FileFolderPluginOpen.h
2 2
3#ifndef __FILE_FOLDER_PLUGIN_OPEN_H 3#ifndef ZIP7_INC_FILE_FOLDER_PLUGIN_OPEN_H
4#define __FILE_FOLDER_PLUGIN_OPEN_H 4#define ZIP7_INC_FILE_FOLDER_PLUGIN_OPEN_H
5 5
6#include "../../../Windows/DLL.h" 6#include "../../../Windows/DLL.h"
7 7
8struct CFfpOpen 8struct CFfpOpen
9{ 9{
10 CLASS_NO_COPY(CFfpOpen) 10 Z7_CLASS_NO_COPY(CFfpOpen)
11public: 11public:
12 // out: 12 // out:
13 bool Encrypted; 13 bool Encrypted;
diff --git a/CPP/7zip/UI/FileManager/FilePlugins.cpp b/CPP/7zip/UI/FileManager/FilePlugins.cpp
index 4600030..cf20970 100644
--- a/CPP/7zip/UI/FileManager/FilePlugins.cpp
+++ b/CPP/7zip/UI/FileManager/FilePlugins.cpp
@@ -8,28 +8,37 @@
8#include "PluginLoader.h" 8#include "PluginLoader.h"
9#include "StringUtils.h" 9#include "StringUtils.h"
10 10
11int CExtDatabase::FindExt(const UString &ext) 11int CExtDatabase::FindExt(const UString &ext) const
12{ 12{
13 FOR_VECTOR (i, Exts) 13 FOR_VECTOR (i, Exts)
14 if (Exts[i].Ext.IsEqualTo_NoCase(ext)) 14 if (Exts[i].Ext.IsEqualTo_NoCase(ext))
15 return i; 15 return (int)i;
16 return -1; 16 return -1;
17} 17}
18 18
19void CExtDatabase::Read() 19void CExtDatabase::Read()
20{ 20{
21 /*
21 ReadFileFolderPluginInfoList(Plugins); 22 ReadFileFolderPluginInfoList(Plugins);
22 FOR_VECTOR (pluginIndex, Plugins) 23 FOR_VECTOR (pluginIndex, Plugins)
24 */
23 { 25 {
24 const CPluginInfo &plugin = Plugins[pluginIndex]; 26 // const CPluginInfo &plugin = Plugins[pluginIndex];
25 27
26 CPluginLibrary pluginLib; 28 CPluginLibrary pluginLib;
27 CMyComPtr<IFolderManager> folderManager; 29 CMyComPtr<IFolderManager> folderManager;
28 30
29 if (plugin.FilePath.IsEmpty()) 31 // if (plugin.FilePath.IsEmpty())
30 folderManager = new CArchiveFolderManager; 32 folderManager = new CArchiveFolderManager;
31 else if (pluginLib.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &folderManager) != S_OK) 33 /*
32 continue; 34 else
35 {
36 if (!plugin.ClassID_Defined)
37 continue;
38 if (pluginLib.LoadAndCreateManager(plugin.FilePath, plugin.ClassID, &folderManager) != S_OK)
39 continue;
40 }
41 */
33 CMyComBSTR extBSTR; 42 CMyComBSTR extBSTR;
34 if (folderManager->GetExtensions(&extBSTR) != S_OK) 43 if (folderManager->GetExtensions(&extBSTR) != S_OK)
35 return; 44 return;
@@ -46,15 +55,15 @@ void CExtDatabase::Read()
46 Int32 iconIndex; 55 Int32 iconIndex;
47 CMyComBSTR iconPath; 56 CMyComBSTR iconPath;
48 CPluginToIcon plugPair; 57 CPluginToIcon plugPair;
49 plugPair.PluginIndex = pluginIndex; 58 // plugPair.PluginIndex = pluginIndex;
50 if (folderManager->GetIconPath(ext, &iconPath, &iconIndex) == S_OK) 59 if (folderManager->GetIconPath(ext, &iconPath, &iconIndex) == S_OK)
51 if (iconPath != 0) 60 if (iconPath)
52 { 61 {
53 plugPair.IconPath = (const wchar_t *)iconPath; 62 plugPair.IconPath = (const wchar_t *)iconPath;
54 plugPair.IconIndex = iconIndex; 63 plugPair.IconIndex = iconIndex;
55 } 64 }
56 65
57 int index = FindExt(ext); 66 const int index = FindExt(ext);
58 if (index >= 0) 67 if (index >= 0)
59 Exts[index].Plugins.Add(plugPair); 68 Exts[index].Plugins.Add(plugPair);
60 else 69 else
diff --git a/CPP/7zip/UI/FileManager/FilePlugins.h b/CPP/7zip/UI/FileManager/FilePlugins.h
index 43b05f9..db8ec39 100644
--- a/CPP/7zip/UI/FileManager/FilePlugins.h
+++ b/CPP/7zip/UI/FileManager/FilePlugins.h
@@ -1,15 +1,15 @@
1// FilePlugins.h 1// FilePlugins.h
2 2
3#ifndef __FILE_PLUGINS_H 3#ifndef ZIP7_INC_FILE_PLUGINS_H
4#define __FILE_PLUGINS_H 4#define ZIP7_INC_FILE_PLUGINS_H
5 5
6#include "RegistryPlugins.h" 6#include "RegistryPlugins.h"
7 7
8struct CPluginToIcon 8struct CPluginToIcon
9{ 9{
10 int PluginIndex; 10 // unsigned PluginIndex;
11 UString IconPath;
12 int IconIndex; 11 int IconIndex;
12 UString IconPath;
13 13
14 CPluginToIcon(): IconIndex(-1) {} 14 CPluginToIcon(): IconIndex(-1) {}
15}; 15};
@@ -22,10 +22,10 @@ struct CExtPlugins
22 22
23class CExtDatabase 23class CExtDatabase
24{ 24{
25 int FindExt(const UString &ext); 25 int FindExt(const UString &ext) const;
26public: 26public:
27 CObjectVector<CExtPlugins> Exts; 27 CObjectVector<CExtPlugins> Exts;
28 CObjectVector<CPluginInfo> Plugins; 28 // CObjectVector<CPluginInfo> Plugins;
29 29
30 void Read(); 30 void Read();
31}; 31};
diff --git a/CPP/7zip/UI/FileManager/FoldersPage.cpp b/CPP/7zip/UI/FileManager/FoldersPage.cpp
index d019bab..7e74635 100644
--- a/CPP/7zip/UI/FileManager/FoldersPage.cpp
+++ b/CPP/7zip/UI/FileManager/FoldersPage.cpp
@@ -11,6 +11,7 @@
11 11
12using namespace NWindows; 12using namespace NWindows;
13 13
14#ifdef Z7_LANG
14static const UInt32 kLangIDs[] = 15static const UInt32 kLangIDs[] =
15{ 16{
16 IDT_FOLDERS_WORKING_FOLDER, 17 IDT_FOLDERS_WORKING_FOLDER,
@@ -19,8 +20,9 @@ static const UInt32 kLangIDs[] =
19 IDR_FOLDERS_WORK_SPECIFIED, 20 IDR_FOLDERS_WORK_SPECIFIED,
20 IDX_FOLDERS_WORK_FOR_REMOVABLE 21 IDX_FOLDERS_WORK_FOR_REMOVABLE
21}; 22};
23#endif
22 24
23static const int kWorkModeButtons[] = 25static const unsigned kWorkModeButtons[] =
24{ 26{
25 IDR_FOLDERS_WORK_SYSTEM, 27 IDR_FOLDERS_WORK_SYSTEM,
26 IDR_FOLDERS_WORK_CURRENT, 28 IDR_FOLDERS_WORK_CURRENT,
@@ -29,19 +31,23 @@ static const int kWorkModeButtons[] =
29 31
30#define kFoldersTopic "fm/options.htm#folders" 32#define kFoldersTopic "fm/options.htm#folders"
31 33
32static const unsigned kNumWorkModeButtons = ARRAY_SIZE(kWorkModeButtons); 34static const unsigned kNumWorkModeButtons = Z7_ARRAY_SIZE(kWorkModeButtons);
33 35
34bool CFoldersPage::OnInit() 36bool CFoldersPage::OnInit()
35{ 37{
36 _initMode = true; 38 _initMode = true;
37 _needSave = false; 39 _needSave = false;
38 40
39 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 41 #ifdef Z7_LANG
42 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
43 #endif
40 m_WorkDirInfo.Load(); 44 m_WorkDirInfo.Load();
41 45
42 CheckButton(IDX_FOLDERS_WORK_FOR_REMOVABLE, m_WorkDirInfo.ForRemovableOnly); 46 CheckButton(IDX_FOLDERS_WORK_FOR_REMOVABLE, m_WorkDirInfo.ForRemovableOnly);
43 47
44 CheckRadioButton(kWorkModeButtons[0], kWorkModeButtons[kNumWorkModeButtons - 1], 48 CheckRadioButton(
49 kWorkModeButtons[0],
50 kWorkModeButtons[kNumWorkModeButtons - 1],
45 kWorkModeButtons[m_WorkDirInfo.Mode]); 51 kWorkModeButtons[m_WorkDirInfo.Mode]);
46 52
47 m_WorkPath.Init(*this, IDE_FOLDERS_WORK_PATH); 53 m_WorkPath.Init(*this, IDE_FOLDERS_WORK_PATH);
@@ -58,7 +64,7 @@ int CFoldersPage::GetWorkMode() const
58{ 64{
59 for (unsigned i = 0; i < kNumWorkModeButtons; i++) 65 for (unsigned i = 0; i < kNumWorkModeButtons; i++)
60 if (IsButtonCheckedBool(kWorkModeButtons[i])) 66 if (IsButtonCheckedBool(kWorkModeButtons[i]))
61 return i; 67 return (int)i;
62 throw 0; 68 throw 0;
63} 69}
64 70
@@ -104,7 +110,7 @@ void CFoldersPage::ModifiedEvent()
104 */ 110 */
105} 111}
106 112
107bool CFoldersPage::OnButtonClicked(int buttonID, HWND buttonHWND) 113bool CFoldersPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
108{ 114{
109 for (unsigned i = 0; i < kNumWorkModeButtons; i++) 115 for (unsigned i = 0; i < kNumWorkModeButtons; i++)
110 if (buttonID == kWorkModeButtons[i]) 116 if (buttonID == kWorkModeButtons[i])
@@ -129,7 +135,7 @@ bool CFoldersPage::OnButtonClicked(int buttonID, HWND buttonHWND)
129 return true; 135 return true;
130} 136}
131 137
132bool CFoldersPage::OnCommand(int code, int itemID, LPARAM lParam) 138bool CFoldersPage::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
133{ 139{
134 if (code == EN_CHANGE && itemID == IDE_FOLDERS_WORK_PATH) 140 if (code == EN_CHANGE && itemID == IDE_FOLDERS_WORK_PATH)
135 { 141 {
diff --git a/CPP/7zip/UI/FileManager/FoldersPage.h b/CPP/7zip/UI/FileManager/FoldersPage.h
index 71c7bfc..09b6cdd 100644
--- a/CPP/7zip/UI/FileManager/FoldersPage.h
+++ b/CPP/7zip/UI/FileManager/FoldersPage.h
@@ -1,7 +1,7 @@
1// FoldersPage.h 1// FoldersPage.h
2 2
3#ifndef __FOLDERS_PAGE_H 3#ifndef ZIP7_INC_FOLDERS_PAGE_H
4#define __FOLDERS_PAGE_H 4#define ZIP7_INC_FOLDERS_PAGE_H
5 5
6#include "../../../Windows/Control/PropertyPage.h" 6#include "../../../Windows/Control/PropertyPage.h"
7 7
@@ -22,11 +22,11 @@ class CFoldersPage : public NWindows::NControl::CPropertyPage
22 int GetWorkMode() const; 22 int GetWorkMode() const;
23 void GetWorkDir(NWorkDir::CInfo &workDirInfo); 23 void GetWorkDir(NWorkDir::CInfo &workDirInfo);
24 // bool WasChanged(); 24 // bool WasChanged();
25 virtual bool OnInit(); 25 virtual bool OnInit() Z7_override;
26 virtual bool OnCommand(int code, int itemID, LPARAM lParam); 26 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override;
27 virtual void OnNotifyHelp(); 27 virtual void OnNotifyHelp() Z7_override;
28 virtual LONG OnApply(); 28 virtual LONG OnApply() Z7_override;
29 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 29 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
30}; 30};
31 31
32#endif 32#endif
diff --git a/CPP/7zip/UI/FileManager/FormatUtils.h b/CPP/7zip/UI/FileManager/FormatUtils.h
index 993e803..1db08ef 100644
--- a/CPP/7zip/UI/FileManager/FormatUtils.h
+++ b/CPP/7zip/UI/FileManager/FormatUtils.h
@@ -1,7 +1,7 @@
1// FormatUtils.h 1// FormatUtils.h
2 2
3#ifndef __FORMAT_UTILS_H 3#ifndef ZIP7_INC_FORMAT_UTILS_H
4#define __FORMAT_UTILS_H 4#define ZIP7_INC_FORMAT_UTILS_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
diff --git a/CPP/7zip/UI/FileManager/HelpUtils.cpp b/CPP/7zip/UI/FileManager/HelpUtils.cpp
index 5cb78fc..d5b6a58 100644
--- a/CPP/7zip/UI/FileManager/HelpUtils.cpp
+++ b/CPP/7zip/UI/FileManager/HelpUtils.cpp
@@ -4,7 +4,7 @@
4 4
5#include "HelpUtils.h" 5#include "HelpUtils.h"
6 6
7#if defined(UNDER_CE) || !defined(_WIN32) /* || !defined(_MSC_VER) */ 7#if defined(UNDER_CE) || defined(__MINGW32_VERSION)
8 8
9void ShowHelpWindow(LPCSTR) 9void ShowHelpWindow(LPCSTR)
10{ 10{
@@ -12,11 +12,15 @@ void ShowHelpWindow(LPCSTR)
12 12
13#else 13#else
14 14
15// #define USE_EXTERNAL_HELP 15/* USE_EXTERNAL_HELP creates new help process window for each HtmlHelp() call.
16 HtmlHelp() call uses one window. */
16 17
17#if defined(_MSC_VER) 18#if defined(__MINGW32_VERSION) /* || defined(Z7_OLD_WIN_SDK) */
19#define USE_EXTERNAL_HELP
18#endif 20#endif
19 21
22// #define USE_EXTERNAL_HELP
23
20#ifdef USE_EXTERNAL_HELP 24#ifdef USE_EXTERNAL_HELP
21 25
22#include "../../../Windows/ProcessUtils.h" 26#include "../../../Windows/ProcessUtils.h"
diff --git a/CPP/7zip/UI/FileManager/HelpUtils.h b/CPP/7zip/UI/FileManager/HelpUtils.h
index 90c5f7d..d7bdf45 100644
--- a/CPP/7zip/UI/FileManager/HelpUtils.h
+++ b/CPP/7zip/UI/FileManager/HelpUtils.h
@@ -1,7 +1,7 @@
1// HelpUtils.h 1// HelpUtils.h
2 2
3#ifndef __HELP_UTILS_H 3#ifndef ZIP7_INC_HELP_UTILS_H
4#define __HELP_UTILS_H 4#define ZIP7_INC_HELP_UTILS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/IFolder.h b/CPP/7zip/UI/FileManager/IFolder.h
index c5cff06..1ebdf7e 100644
--- a/CPP/7zip/UI/FileManager/IFolder.h
+++ b/CPP/7zip/UI/FileManager/IFolder.h
@@ -1,13 +1,19 @@
1// IFolder.h 1// IFolder.h
2 2
3#ifndef __IFOLDER_H 3#ifndef ZIP7_INC_IFOLDER_H
4#define __IFOLDER_H 4#define ZIP7_INC_IFOLDER_H
5 5
6#include "../../IProgress.h" 6#include "../../IProgress.h"
7#include "../../IStream.h" 7#include "../../IStream.h"
8 8
9#define FOLDER_INTERFACE_SUB(i, b, x) DECL_INTERFACE_SUB(i, b, 8, x) 9Z7_PURE_INTERFACES_BEGIN
10#define FOLDER_INTERFACE(i, x) FOLDER_INTERFACE_SUB(i, IUnknown, x) 10
11#define Z7_IFACE_CONSTR_FOLDER_SUB(i, base, n) \
12 Z7_DECL_IFACE_7ZIP_SUB(i, base, 8, n) \
13 { Z7_IFACE_COM7_PURE(i) };
14
15#define Z7_IFACE_CONSTR_FOLDER(i, n) \
16 Z7_IFACE_CONSTR_FOLDER_SUB(i, IUnknown, n)
11 17
12namespace NPlugin 18namespace NPlugin
13{ 19{
@@ -20,199 +26,162 @@ namespace NPlugin
20 }; 26 };
21} 27}
22 28
23#define INTERFACE_FolderFolder(x) \ 29#define Z7_IFACEM_IFolderFolder(x) \
24 STDMETHOD(LoadItems)() x; \ 30 x(LoadItems()) \
25 STDMETHOD(GetNumberOfItems)(UInt32 *numItems) x; \ 31 x(GetNumberOfItems(UInt32 *numItems)) \
26 STDMETHOD(GetProperty)(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) x; \ 32 x(GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value)) \
27 STDMETHOD(BindToFolder)(UInt32 index, IFolderFolder **resultFolder) x; \ 33 x(BindToFolder(UInt32 index, IFolderFolder **resultFolder)) \
28 STDMETHOD(BindToFolder)(const wchar_t *name, IFolderFolder **resultFolder) x; \ 34 x(BindToFolder(const wchar_t *name, IFolderFolder **resultFolder)) \
29 STDMETHOD(BindToParentFolder)(IFolderFolder **resultFolder) x; \ 35 x(BindToParentFolder(IFolderFolder **resultFolder)) \
30 STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ 36 x(GetNumberOfProperties(UInt32 *numProperties)) \
31 STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ 37 x(GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
32 STDMETHOD(GetFolderProperty)(PROPID propID, PROPVARIANT *value) x; \ 38 x(GetFolderProperty(PROPID propID, PROPVARIANT *value)) \
33 39
34FOLDER_INTERFACE(IFolderFolder, 0x00) 40Z7_IFACE_CONSTR_FOLDER(IFolderFolder, 0x00)
35{
36 INTERFACE_FolderFolder(PURE)
37};
38 41
39/* 42/*
40 IFolderAltStreams:: 43 IFolderAltStreams::
41 BindToAltStreams((UInt32)(Int32)-1, ... ) means alt streams of that folder 44 BindToAltStreams((UInt32)(Int32)-1, ... ) means alt streams of that folder
42*/ 45*/
43 46
44#define INTERFACE_FolderAltStreams(x) \ 47#define Z7_IFACEM_IFolderAltStreams(x) \
45 STDMETHOD(BindToAltStreams)(UInt32 index, IFolderFolder **resultFolder) x; \ 48 x(BindToAltStreams(UInt32 index, IFolderFolder **resultFolder)) \
46 STDMETHOD(BindToAltStreams)(const wchar_t *name, IFolderFolder **resultFolder) x; \ 49 x(BindToAltStreams(const wchar_t *name, IFolderFolder **resultFolder)) \
47 STDMETHOD(AreAltStreamsSupported)(UInt32 index, Int32 *isSupported) x; \ 50 x(AreAltStreamsSupported(UInt32 index, Int32 *isSupported)) \
48 51
49FOLDER_INTERFACE(IFolderAltStreams, 0x17) 52Z7_IFACE_CONSTR_FOLDER(IFolderAltStreams, 0x17)
50{ 53
51 INTERFACE_FolderAltStreams(PURE) 54#define Z7_IFACEM_IFolderWasChanged(x) \
52}; 55 x(WasChanged(Int32 *wasChanged))
53 56Z7_IFACE_CONSTR_FOLDER(IFolderWasChanged, 0x04)
54FOLDER_INTERFACE(IFolderWasChanged, 0x04) 57
55{ 58 /* x(SetTotalFiles(UInt64 total)) */ \
56 STDMETHOD(WasChanged)(Int32 *wasChanged) PURE; 59 /* x(SetCompletedFiles(const UInt64 *completedValue)) */ \
57}; 60#define Z7_IFACEM_IFolderOperationsExtractCallback(x) \
58 61 x(AskWrite( \
59FOLDER_INTERFACE_SUB(IFolderOperationsExtractCallback, IProgress, 0x0B) 62 const wchar_t *srcPath, \
60{ 63 Int32 srcIsFolder, \
61 // STDMETHOD(SetTotalFiles)(UInt64 total) PURE; 64 const FILETIME *srcTime, \
62 // STDMETHOD(SetCompletedFiles)(const UInt64 *completedValue) PURE; 65 const UInt64 *srcSize, \
63 STDMETHOD(AskWrite)( 66 const wchar_t *destPathRequest, \
64 const wchar_t *srcPath, 67 BSTR *destPathResult, \
65 Int32 srcIsFolder, 68 Int32 *writeAnswer)) \
66 const FILETIME *srcTime, 69 x(ShowMessage(const wchar_t *message)) \
67 const UInt64 *srcSize, 70 x(SetCurrentFilePath(const wchar_t *filePath)) \
68 const wchar_t *destPathRequest, 71 x(SetNumFiles(UInt64 numFiles)) \
69 BSTR *destPathResult, 72
70 Int32 *writeAnswer) PURE; 73Z7_IFACE_CONSTR_FOLDER_SUB(IFolderOperationsExtractCallback, IProgress, 0x0B)
71 STDMETHOD(ShowMessage)(const wchar_t *message) PURE; 74
72 STDMETHOD(SetCurrentFilePath)(const wchar_t *filePath) PURE; 75
73 STDMETHOD(SetNumFiles)(UInt64 numFiles) PURE; 76#define Z7_IFACEM_IFolderOperations(x) \
74}; 77 x(CreateFolder(const wchar_t *name, IProgress *progress)) \
75 78 x(CreateFile(const wchar_t *name, IProgress *progress)) \
76#define INTERFACE_FolderOperations(x) \ 79 x(Rename(UInt32 index, const wchar_t *newName, IProgress *progress)) \
77 STDMETHOD(CreateFolder)(const wchar_t *name, IProgress *progress) x; \ 80 x(Delete(const UInt32 *indices, UInt32 numItems, IProgress *progress)) \
78 STDMETHOD(CreateFile)(const wchar_t *name, IProgress *progress) x; \ 81 x(CopyTo(Int32 moveMode, const UInt32 *indices, UInt32 numItems, \
79 STDMETHOD(Rename)(UInt32 index, const wchar_t *newName, IProgress *progress) x; \
80 STDMETHOD(Delete)(const UInt32 *indices, UInt32 numItems, IProgress *progress) x; \
81 STDMETHOD(CopyTo)(Int32 moveMode, const UInt32 *indices, UInt32 numItems, \
82 Int32 includeAltStreams, Int32 replaceAltStreamCharsMode, \ 82 Int32 includeAltStreams, Int32 replaceAltStreamCharsMode, \
83 const wchar_t *path, IFolderOperationsExtractCallback *callback) x; \ 83 const wchar_t *path, IFolderOperationsExtractCallback *callback)) \
84 STDMETHOD(CopyFrom)(Int32 moveMode, const wchar_t *fromFolderPath, \ 84 x(CopyFrom(Int32 moveMode, const wchar_t *fromFolderPath, \
85 const wchar_t * const *itemsPaths, UInt32 numItems, IProgress *progress) x; \ 85 const wchar_t * const *itemsPaths, UInt32 numItems, IProgress *progress)) \
86 STDMETHOD(SetProperty)(UInt32 index, PROPID propID, const PROPVARIANT *value, IProgress *progress) x; \ 86 x(SetProperty(UInt32 index, PROPID propID, const PROPVARIANT *value, IProgress *progress)) \
87 STDMETHOD(CopyFromFile)(UInt32 index, const wchar_t *fullFilePath, IProgress *progress) x; \ 87 x(CopyFromFile(UInt32 index, const wchar_t *fullFilePath, IProgress *progress)) \
88 88
89FOLDER_INTERFACE(IFolderOperations, 0x13) 89Z7_IFACE_CONSTR_FOLDER(IFolderOperations, 0x13)
90{
91 INTERFACE_FolderOperations(PURE)
92};
93 90
94/* 91/*
95FOLDER_INTERFACE2(IFolderOperationsDeleteToRecycleBin, 0x06, 0x03) 92FOLDER_INTERFACE2(IFolderOperationsDeleteToRecycleBin, 0x06, 0x03)
96{ 93{
97 STDMETHOD(DeleteToRecycleBin)(const UInt32 *indices, UInt32 numItems, IProgress *progress) PURE; 94 x(DeleteToRecycleBin(const UInt32 *indices, UInt32 numItems, IProgress *progress)) \
98}; 95};
99*/ 96*/
100 97
101FOLDER_INTERFACE(IFolderGetSystemIconIndex, 0x07) 98#define Z7_IFACEM_IFolderGetSystemIconIndex(x) \
102{ 99 x(GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
103 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex) PURE; 100Z7_IFACE_CONSTR_FOLDER(IFolderGetSystemIconIndex, 0x07)
104};
105 101
106FOLDER_INTERFACE(IFolderGetItemFullSize, 0x08) 102#define Z7_IFACEM_IFolderGetItemFullSize(x) \
107{ 103 x(GetItemFullSize(UInt32 index, PROPVARIANT *value, IProgress *progress))
108 STDMETHOD(GetItemFullSize)(UInt32 index, PROPVARIANT *value, IProgress *progress) PURE; 104Z7_IFACE_CONSTR_FOLDER(IFolderGetItemFullSize, 0x08)
109};
110 105
111FOLDER_INTERFACE(IFolderCalcItemFullSize, 0x14) 106#define Z7_IFACEM_IFolderCalcItemFullSize(x) \
112{ 107 x(CalcItemFullSize(UInt32 index, IProgress *progress))
113 STDMETHOD(CalcItemFullSize)(UInt32 index, IProgress *progress) PURE; 108Z7_IFACE_CONSTR_FOLDER(IFolderCalcItemFullSize, 0x14)
114};
115 109
116FOLDER_INTERFACE(IFolderClone, 0x09) 110#define Z7_IFACEM_IFolderClone(x) \
117{ 111 x(Clone(IFolderFolder **resultFolder))
118 STDMETHOD(Clone)(IFolderFolder **resultFolder) PURE; 112Z7_IFACE_CONSTR_FOLDER(IFolderClone, 0x09)
119};
120 113
121FOLDER_INTERFACE(IFolderSetFlatMode, 0x0A) 114#define Z7_IFACEM_IFolderSetFlatMode(x) \
122{ 115 x(SetFlatMode(Int32 flatMode))
123 STDMETHOD(SetFlatMode)(Int32 flatMode) PURE; 116Z7_IFACE_CONSTR_FOLDER(IFolderSetFlatMode, 0x0A)
124};
125 117
126/* 118/*
127FOLDER_INTERFACE(IFolderSetShowNtfsStreamsMode, 0xFA) 119#define Z7_IFACEM_IFolderSetShowNtfsStreamsMode(x) \
128{ 120 x(SetShowNtfsStreamsMode(Int32 showStreamsMode))
129 STDMETHOD(SetShowNtfsStreamsMode)(Int32 showStreamsMode) PURE; 121Z7_IFACE_CONSTR_FOLDER(IFolderSetShowNtfsStreamsMode, 0xFA)
130};
131*/ 122*/
132 123
133#define INTERFACE_FolderProperties(x) \ 124#define Z7_IFACEM_IFolderProperties(x) \
134 STDMETHOD(GetNumberOfFolderProperties)(UInt32 *numProperties) x; \ 125 x(GetNumberOfFolderProperties(UInt32 *numProperties)) \
135 STDMETHOD(GetFolderPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ 126 x(GetFolderPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
136 127
137FOLDER_INTERFACE(IFolderProperties, 0x0E) 128Z7_IFACE_CONSTR_FOLDER(IFolderProperties, 0x0E)
138{
139 INTERFACE_FolderProperties(PURE)
140};
141 129
142#define INTERFACE_IFolderArcProps(x) \ 130#define Z7_IFACEM_IFolderArcProps(x) \
143 STDMETHOD(GetArcNumLevels)(UInt32 *numLevels) x; \ 131 x(GetArcNumLevels(UInt32 *numLevels)) \
144 STDMETHOD(GetArcProp)(UInt32 level, PROPID propID, PROPVARIANT *value) x; \ 132 x(GetArcProp(UInt32 level, PROPID propID, PROPVARIANT *value)) \
145 STDMETHOD(GetArcNumProps)(UInt32 level, UInt32 *numProps) x; \ 133 x(GetArcNumProps(UInt32 level, UInt32 *numProps)) \
146 STDMETHOD(GetArcPropInfo)(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ 134 x(GetArcPropInfo(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
147 STDMETHOD(GetArcProp2)(UInt32 level, PROPID propID, PROPVARIANT *value) x; \ 135 x(GetArcProp2(UInt32 level, PROPID propID, PROPVARIANT *value)) \
148 STDMETHOD(GetArcNumProps2)(UInt32 level, UInt32 *numProps) x; \ 136 x(GetArcNumProps2(UInt32 level, UInt32 *numProps)) \
149 STDMETHOD(GetArcPropInfo2)(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ 137 x(GetArcPropInfo2(UInt32 level, UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
150 138
151FOLDER_INTERFACE(IFolderArcProps, 0x10) 139Z7_IFACE_CONSTR_FOLDER(IFolderArcProps, 0x10)
152{
153 INTERFACE_IFolderArcProps(PURE)
154};
155 140
156FOLDER_INTERFACE(IGetFolderArcProps, 0x11) 141#define Z7_IFACEM_IGetFolderArcProps(x) \
157{ 142 x(GetFolderArcProps(IFolderArcProps **object))
158 STDMETHOD(GetFolderArcProps)(IFolderArcProps **object) PURE; 143Z7_IFACE_CONSTR_FOLDER(IGetFolderArcProps, 0x11)
159};
160 144
161FOLDER_INTERFACE(IFolderCompare, 0x15) 145#define Z7_IFACEM_IFolderCompare(x) \
162{ 146 x##2(Int32, CompareItems(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw))
163 STDMETHOD_(Int32, CompareItems)(UInt32 index1, UInt32 index2, PROPID propID, Int32 propIsRaw) PURE; 147Z7_IFACE_CONSTR_FOLDER(IFolderCompare, 0x15)
164};
165 148
166#define INTERFACE_IFolderGetItemName(x) \ 149#define Z7_IFACEM_IFolderGetItemName(x) \
167 STDMETHOD(GetItemName)(UInt32 index, const wchar_t **name, unsigned *len) x; \ 150 x(GetItemName(UInt32 index, const wchar_t **name, unsigned *len)) \
168 STDMETHOD(GetItemPrefix)(UInt32 index, const wchar_t **name, unsigned *len) x; \ 151 x(GetItemPrefix(UInt32 index, const wchar_t **name, unsigned *len)) \
169 STDMETHOD_(UInt64, GetItemSize)(UInt32 index) x; \ 152 x##2(UInt64, GetItemSize(UInt32 index)) \
170 153
171FOLDER_INTERFACE(IFolderGetItemName, 0x16) 154Z7_IFACE_CONSTR_FOLDER(IFolderGetItemName, 0x16)
172{
173 INTERFACE_IFolderGetItemName(PURE)
174};
175 155
176#define FOLDER_MANAGER_INTERFACE(i, x) DECL_INTERFACE(i, 9, x)
177 156
178#define INTERFACE_IFolderManager(x) \ 157#define Z7_IFACEM_IFolderManager(x) \
179 STDMETHOD(OpenFolderFile)(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, IFolderFolder **resultFolder, IProgress *progress) x; \ 158 x(OpenFolderFile(IInStream *inStream, const wchar_t *filePath, const wchar_t *arcFormat, IFolderFolder **resultFolder, IProgress *progress)) \
180 STDMETHOD(GetExtensions)(BSTR *extensions) x; \ 159 x(GetExtensions(BSTR *extensions)) \
181 STDMETHOD(GetIconPath)(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex) x; \ 160 x(GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex)) \
182 161
183 // STDMETHOD(GetTypes)(BSTR *types) PURE; 162 // x(GetTypes(BSTR *types))
184 // STDMETHOD(CreateFolderFile)(const wchar_t *type, const wchar_t *filePath, IProgress *progress) PURE; 163 // x(CreateFolderFile(const wchar_t *type, const wchar_t *filePath, IProgress *progress))
185 164
186FOLDER_MANAGER_INTERFACE(IFolderManager, 0x05) 165Z7_DECL_IFACE_7ZIP(IFolderManager, 9, 5)
187{ 166 { Z7_IFACE_COM7_PURE(IFolderManager) };
188 INTERFACE_IFolderManager(PURE);
189};
190 167
191/* 168/*
192#define IMP_IFolderFolder_GetProp(k) \
193 (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \
194 { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \
195 const CMy_STATPROPSTG_2 &srcItem = k[index]; \ 169 const CMy_STATPROPSTG_2 &srcItem = k[index]; \
196 *propID = srcItem.propid; *varType = srcItem.vt; *name = 0; return S_OK; } \ 170 *propID = srcItem.propid; *varType = srcItem.vt; *name = 0; return S_OK; } \
197
198#define IMP_IFolderFolder_Props(c) \
199 STDMETHODIMP c::GetNumberOfProperties(UInt32 *numProperties) \
200 { *numProperties = ARRAY_SIZE(kProps); return S_OK; } \
201 STDMETHODIMP c::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps)
202*/ 171*/
203 172#define IMP_IFolderFolder_GetProp(fn, k) \
204#define IMP_IFolderFolder_GetProp(k) \ 173 Z7_COM7F_IMF(fn(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType)) \
205 (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ 174 { if (index >= Z7_ARRAY_SIZE(k)) return E_INVALIDARG; \
206 { if (index >= ARRAY_SIZE(k)) return E_INVALIDARG; \ 175 *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = NULL; return S_OK; } \
207 *propID = k[index]; *varType = k7z_PROPID_To_VARTYPE[(unsigned)*propID]; *name = 0; return S_OK; } \
208 176
209#define IMP_IFolderFolder_Props(c) \ 177#define IMP_IFolderFolder_Props(c) \
210 STDMETHODIMP c::GetNumberOfProperties(UInt32 *numProperties) \ 178 Z7_COM7F_IMF(c::GetNumberOfProperties(UInt32 *numProperties)) \
211 { *numProperties = ARRAY_SIZE(kProps); return S_OK; } \ 179 { *numProperties = Z7_ARRAY_SIZE(kProps); return S_OK; } \
212 STDMETHODIMP c::GetPropertyInfo IMP_IFolderFolder_GetProp(kProps) 180 IMP_IFolderFolder_GetProp(c::GetPropertyInfo, kProps)
213 181
214 182
215int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2); 183int CompareFileNames_ForFolderList(const wchar_t *s1, const wchar_t *s2);
216// int CompareFileNames_ForFolderList(const FChar *s1, const FChar *s2); 184// int CompareFileNames_ForFolderList(const FChar *s1, const FChar *s2);
217 185
186Z7_PURE_INTERFACES_END
218#endif 187#endif
diff --git a/CPP/7zip/UI/FileManager/LangPage.cpp b/CPP/7zip/UI/FileManager/LangPage.cpp
index 47e7894..ec1dd2e 100644
--- a/CPP/7zip/UI/FileManager/LangPage.cpp
+++ b/CPP/7zip/UI/FileManager/LangPage.cpp
@@ -15,13 +15,37 @@
15 15
16using namespace NWindows; 16using namespace NWindows;
17 17
18
19static const unsigned k_NumLangLines_EN = 429;
20
21#ifdef Z7_LANG
18static const UInt32 kLangIDs[] = 22static const UInt32 kLangIDs[] =
19{ 23{
20 IDT_LANG_LANG 24 IDT_LANG_LANG
21}; 25};
26#endif
22 27
23#define kLangTopic "fm/options.htm#language" 28#define kLangTopic "fm/options.htm#language"
24 29
30
31struct CLangListRecord
32{
33 int Order;
34 unsigned LangInfoIndex;
35 bool IsSelected;
36 UString Mark;
37 UString Name;
38
39 CLangListRecord(): Order (10), IsSelected(false) {}
40 int Compare(const CLangListRecord &a) const
41 {
42 if (Order < a.Order) return -1;
43 if (Order > a.Order) return 1;
44 return MyStringCompareNoCase(Name, a.Name);
45 }
46};
47
48
25static void NativeLangString(UString &dest, const wchar_t *s) 49static void NativeLangString(UString &dest, const wchar_t *s)
26{ 50{
27 dest += " ("; 51 dest += " (";
@@ -33,23 +57,51 @@ bool LangOpen(CLang &lang, CFSTR fileName);
33 57
34bool CLangPage::OnInit() 58bool CLangPage::OnInit()
35{ 59{
36 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 60#ifdef Z7_LANG
37 61 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
62#endif
38 _langCombo.Attach(GetItem(IDC_LANG_LANG)); 63 _langCombo.Attach(GetItem(IDC_LANG_LANG));
39 64
40 UString temp = MyLoadString(IDS_LANG_ENGLISH); 65
41 NativeLangString(temp, MyLoadString(IDS_LANG_NATIVE)); 66 unsigned listRecords_SelectedIndex = 0;
42 int index = (int)_langCombo.AddString(temp); 67
43 _langCombo.SetItemData(index, _paths.Size()); 68 CObjectVector<CLangListRecord> listRecords;
44 _paths.Add(L"-"); 69 {
45 _langCombo.SetCurSel(0); 70 CLangListRecord listRecord;
71 listRecord.Order = 0;
72 listRecord.Mark = "---";
73 listRecord.Name = MyLoadString(IDS_LANG_ENGLISH);
74 NativeLangString(listRecord.Name, MyLoadString(IDS_LANG_NATIVE));
75 listRecord.LangInfoIndex = _langs.Size();
76 listRecords.Add(listRecord);
77 }
78
79 AStringVector names;
80 unsigned subLangIndex = 0;
81 Lang_GetShortNames_for_DefaultLang(names, subLangIndex);
46 82
47 const FString dirPrefix = GetLangDirPrefix(); 83 const FString dirPrefix = GetLangDirPrefix();
48 NFile::NFind::CEnumerator enumerator; 84 NFile::NFind::CEnumerator enumerator;
49 enumerator.SetDirPrefix(dirPrefix); 85 enumerator.SetDirPrefix(dirPrefix);
50 NFile::NFind::CFileInfo fi; 86 NFile::NFind::CFileInfo fi;
87
88 CLang lang_en;
89 {
90 CLangInfo &langInfo = _langs.AddNew();
91 langInfo.Name = "-";
92 if (LangOpen(lang_en, dirPrefix + FTEXT("en.ttt")))
93 {
94 langInfo.NumLines = lang_en._ids.Size();
95 // langInfo.Comments = lang_en.Comments;
96 }
97 else
98 langInfo.NumLines = k_NumLangLines_EN;
99 NumLangLines_EN = langInfo.NumLines;
100 }
101
51 CLang lang; 102 CLang lang;
52 UString error; 103 UString error;
104 UString n;
53 105
54 while (enumerator.Next(fi)) 106 while (enumerator.Next(fi))
55 { 107 {
@@ -73,6 +125,39 @@ bool CLangPage::OnInit()
73 } 125 }
74 126
75 const UString shortName = fs2us(fi.Name.Left(pos)); 127 const UString shortName = fs2us(fi.Name.Left(pos));
128
129 CLangListRecord listRecord;
130 if (!names.IsEmpty())
131 {
132 for (unsigned i = 0; i < names.Size(); i++)
133 if (shortName.IsEqualTo_Ascii_NoCase(names[i]))
134 {
135 if (subLangIndex == i || names.Size() == 1)
136 {
137 listRecord.Mark = "***";
138 // listRecord.Order = 1;
139 }
140 else
141 {
142 listRecord.Mark = "+++";
143 // listRecord.Order = 2;
144 }
145 break;
146 }
147 if (listRecord.Mark.IsEmpty())
148 {
149 const int minusPos = shortName.Find(L'-');
150 if (minusPos >= 0)
151 {
152 const UString shortName2 = shortName.Left(minusPos);
153 if (shortName2.IsEqualTo_Ascii_NoCase(names[0]))
154 {
155 listRecord.Mark = "+++";
156 // listRecord.Order = 3;
157 }
158 }
159 }
160 }
76 UString s = shortName; 161 UString s = shortName;
77 const wchar_t *eng = lang.Get(IDS_LANG_ENGLISH); 162 const wchar_t *eng = lang.Get(IDS_LANG_ENGLISH);
78 if (eng) 163 if (eng)
@@ -80,25 +165,119 @@ bool CLangPage::OnInit()
80 const wchar_t *native = lang.Get(IDS_LANG_NATIVE); 165 const wchar_t *native = lang.Get(IDS_LANG_NATIVE);
81 if (native) 166 if (native)
82 NativeLangString(s, native); 167 NativeLangString(s, native);
83 index = (int)_langCombo.AddString(s); 168
84 _langCombo.SetItemData(index, _paths.Size()); 169 listRecord.Name = s;
85 _paths.Add(shortName); 170 listRecord.LangInfoIndex = _langs.Size();
171 listRecords.Add(listRecord);
86 if (g_LangID.IsEqualTo_NoCase(shortName)) 172 if (g_LangID.IsEqualTo_NoCase(shortName))
173 listRecords_SelectedIndex = listRecords.Size() - 1;
174
175 CLangInfo &langInfo = _langs.AddNew();
176 langInfo.Comments = lang.Comments;
177 langInfo.Name = shortName;
178 unsigned numLines = lang._ids.Size();
179 if (!lang_en.IsEmpty())
180 {
181 numLines = 0;
182 unsigned i1 = 0;
183 unsigned i2 = 0;
184 for (;;)
185 {
186 UInt32 id1 = (UInt32)0 - 1;
187 UInt32 id2 = (UInt32)0 - 1;
188 bool id1_defined = false;
189 bool id2_defined = false;
190 if (i1 < lang_en._ids.Size())
191 {
192 id1 = lang_en._ids[i1];
193 id1_defined = true;
194 }
195 if (i2 < lang._ids.Size())
196 {
197 id2 = lang._ids[i2];
198 id2_defined = true;
199 }
200
201 bool id1_is_smaller = true;
202 if (id1_defined)
203 {
204 if (id2_defined)
205 {
206 if (id1 == id2)
207 {
208 i1++;
209 i2++;
210 numLines++;
211 continue;
212 }
213 if (id1 > id2)
214 id1_is_smaller = false;
215 }
216 }
217 else if (!id2_defined)
218 break;
219 else
220 id1_is_smaller = false;
221
222 n.Empty();
223 if (id1_is_smaller)
224 {
225 n.Add_UInt32(id1);
226 n += " : ";
227 n += lang_en.Get_by_index(i1);
228 langInfo.MissingLines.Add(n);
229 i1++;
230 }
231 else
232 {
233 n.Add_UInt32(id2);
234 n += " : ";
235 n += lang.Get_by_index(i2);
236 langInfo.ExtraLines.Add(n);
237 i2++;
238 }
239 }
240 }
241 langInfo.NumLines = numLines + langInfo.ExtraLines.Size();
242 }
243
244 listRecords[listRecords_SelectedIndex].IsSelected = true;
245
246 listRecords.Sort();
247 FOR_VECTOR (i, listRecords)
248 {
249 const CLangListRecord &rec= listRecords[i];
250 UString temp = rec.Name;
251 if (!rec.Mark.IsEmpty())
252 {
253 temp += " ";
254 temp += rec.Mark;
255 }
256 const int index = (int)_langCombo.AddString(temp);
257 _langCombo.SetItemData(index, (LPARAM)rec.LangInfoIndex);
258 if (rec.IsSelected)
87 _langCombo.SetCurSel(index); 259 _langCombo.SetCurSel(index);
88 } 260 }
261
262 ShowLangInfo();
89 263
90 if (!error.IsEmpty()) 264 if (!error.IsEmpty())
91 MessageBoxW(0, error, L"Error in Lang file", MB_ICONERROR); 265 MessageBoxW(NULL, error, L"Error in Lang file", MB_ICONERROR);
92 return CPropertyPage::OnInit(); 266 return CPropertyPage::OnInit();
93} 267}
94 268
95LONG CLangPage::OnApply() 269LONG CLangPage::OnApply()
96{ 270{
97 int pathIndex = (int)_langCombo.GetItemData_of_CurSel();
98 if (_needSave) 271 if (_needSave)
99 SaveRegLang(_paths[pathIndex]); 272 {
273 const int pathIndex = (int)_langCombo.GetItemData_of_CurSel();
274 if ((unsigned)pathIndex < _langs.Size())
275 SaveRegLang(_langs[pathIndex].Name);
276 }
100 _needSave = false; 277 _needSave = false;
278 #ifdef Z7_LANG
101 ReloadLang(); 279 ReloadLang();
280 #endif
102 LangWasChanged = true; 281 LangWasChanged = true;
103 return PSNRET_NOERROR; 282 return PSNRET_NOERROR;
104} 283}
@@ -108,13 +287,75 @@ void CLangPage::OnNotifyHelp()
108 ShowHelpWindow(kLangTopic); 287 ShowHelpWindow(kLangTopic);
109} 288}
110 289
111bool CLangPage::OnCommand(int code, int itemID, LPARAM param) 290bool CLangPage::OnCommand(unsigned code, unsigned itemID, LPARAM param)
112{ 291{
113 if (code == CBN_SELCHANGE && itemID == IDC_LANG_LANG) 292 if (code == CBN_SELCHANGE && itemID == IDC_LANG_LANG)
114 { 293 {
115 _needSave = true; 294 _needSave = true;
116 Changed(); 295 Changed();
296 ShowLangInfo();
117 return true; 297 return true;
118 } 298 }
119 return CPropertyPage::OnCommand(code, itemID, param); 299 return CPropertyPage::OnCommand(code, itemID, param);
120} 300}
301
302static void AddVectorToString(UString &s, const UStringVector &v)
303{
304 UString a;
305 FOR_VECTOR (i, v)
306 {
307 if (i >= 50)
308 break;
309 a = v[i];
310 if (a.Len() > 1500)
311 continue;
312 if (a[0] == ';')
313 {
314 a.DeleteFrontal(1);
315 a.Trim();
316 }
317 s += a;
318 s.Add_LF();
319 }
320}
321
322static void AddVectorToString2(UString &s, const char *name, const UStringVector &v)
323{
324 if (v.IsEmpty())
325 return;
326 s.Add_LF();
327 s += "------ ";
328 s += name;
329 s += ": ";
330 s.Add_UInt32(v.Size());
331 s += " :";
332 s.Add_LF();
333 AddVectorToString(s, v);
334}
335
336void CLangPage::ShowLangInfo()
337{
338 UString s;
339 const int pathIndex = (int)_langCombo.GetItemData_of_CurSel();
340 if ((unsigned)pathIndex < _langs.Size())
341 {
342 const CLangInfo &langInfo = _langs[pathIndex];
343 const unsigned numLines = langInfo.NumLines;
344 s += langInfo.Name;
345 s += " : ";
346 s.Add_UInt32(numLines);
347 if (NumLangLines_EN != 0)
348 {
349 s += " / ";
350 s.Add_UInt32(NumLangLines_EN);
351 s += " = ";
352 s.Add_UInt32(numLines * 100 / NumLangLines_EN);
353 s += "%";
354 }
355 s.Add_LF();
356 AddVectorToString(s, langInfo.Comments);
357 AddVectorToString2(s, "Missing lines", langInfo.MissingLines);
358 AddVectorToString2(s, "Extra lines", langInfo.ExtraLines);
359 }
360 SetItemText(IDT_LANG_INFO, s);
361}
diff --git a/CPP/7zip/UI/FileManager/LangPage.h b/CPP/7zip/UI/FileManager/LangPage.h
index b806257..e37ba05 100644
--- a/CPP/7zip/UI/FileManager/LangPage.h
+++ b/CPP/7zip/UI/FileManager/LangPage.h
@@ -1,25 +1,36 @@
1// LangPage.h 1// LangPage.h
2 2
3#ifndef __LANG_PAGE_H 3#ifndef ZIP7_INC_LANG_PAGE_H
4#define __LANG_PAGE_H 4#define ZIP7_INC_LANG_PAGE_H
5 5
6#include "../../../Windows/Control/PropertyPage.h" 6#include "../../../Windows/Control/PropertyPage.h"
7#include "../../../Windows/Control/ComboBox.h" 7#include "../../../Windows/Control/ComboBox.h"
8 8
9struct CLangInfo
10{
11 unsigned NumLines;
12 UString Name;
13 UStringVector Comments;
14 UStringVector MissingLines;
15 UStringVector ExtraLines;
16};
17
9class CLangPage: public NWindows::NControl::CPropertyPage 18class CLangPage: public NWindows::NControl::CPropertyPage
10{ 19{
11 NWindows::NControl::CComboBox _langCombo; 20 NWindows::NControl::CComboBox _langCombo;
12 UStringVector _paths; 21 CObjectVector<CLangInfo> _langs;
13 22 unsigned NumLangLines_EN;
14 bool _needSave; 23 bool _needSave;
24
25 void ShowLangInfo();
15public: 26public:
16 bool LangWasChanged; 27 bool LangWasChanged;
17 28
18 CLangPage(): _needSave(false), LangWasChanged(false) {} 29 CLangPage(): _needSave(false), LangWasChanged(false) {}
19 virtual bool OnInit(); 30 virtual bool OnInit() Z7_override;
20 virtual void OnNotifyHelp(); 31 virtual void OnNotifyHelp() Z7_override;
21 virtual bool OnCommand(int code, int itemID, LPARAM param); 32 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override;
22 virtual LONG OnApply(); 33 virtual LONG OnApply() Z7_override;
23}; 34};
24 35
25#endif 36#endif
diff --git a/CPP/7zip/UI/FileManager/LangPage.rc b/CPP/7zip/UI/FileManager/LangPage.rc
index 164e2d3..506f102 100644
--- a/CPP/7zip/UI/FileManager/LangPage.rc
+++ b/CPP/7zip/UI/FileManager/LangPage.rc
@@ -1,14 +1,17 @@
1#include "LangPageRes.h" 1#include "LangPageRes.h"
2#include "../../GuiCommon.rc" 2#include "../../GuiCommon.rc"
3 3
4#define xc 160 4#define xc 240
5#define yc 100 5#define yc 252
6
7#define y 32
6 8
7IDD_LANG DIALOG 0, 0, xs, ys MY_PAGE_STYLE MY_FONT 9IDD_LANG DIALOG 0, 0, xs, ys MY_PAGE_STYLE MY_FONT
8CAPTION "Language" 10CAPTION "Language"
9{ 11{
10 LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8 12 LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8
11 COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO_SORTED 13 COMBOBOX IDC_LANG_LANG, m, 20, 160, yc - 20, MY_COMBO // MY_COMBO_SORTED
14 LTEXT "", IDT_LANG_INFO, m, m + y, xc, yc - y, SS_NOPREFIX
12} 15}
13 16
14 17
@@ -24,7 +27,7 @@ IDD_LANG_2 MY_PAGE
24CAPTION "Language" 27CAPTION "Language"
25{ 28{
26 LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8 29 LTEXT "Language:", IDT_LANG_LANG, m, m, xc, 8
27 COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO_SORTED 30 COMBOBOX IDC_LANG_LANG, m, 20, xc, yc - 20, MY_COMBO // MY_COMBO_SORTED
28} 31}
29 32
30#endif 33#endif
diff --git a/CPP/7zip/UI/FileManager/LangPageRes.h b/CPP/7zip/UI/FileManager/LangPageRes.h
index d7a39d7..a1ad30f 100644
--- a/CPP/7zip/UI/FileManager/LangPageRes.h
+++ b/CPP/7zip/UI/FileManager/LangPageRes.h
@@ -6,3 +6,4 @@
6 6
7#define IDT_LANG_LANG 2102 7#define IDT_LANG_LANG 2102
8#define IDC_LANG_LANG 100 8#define IDC_LANG_LANG 100
9#define IDT_LANG_INFO 101
diff --git a/CPP/7zip/UI/FileManager/LangUtils.cpp b/CPP/7zip/UI/FileManager/LangUtils.cpp
index 83d5aa7..4c9d16f 100644
--- a/CPP/7zip/UI/FileManager/LangUtils.cpp
+++ b/CPP/7zip/UI/FileManager/LangUtils.cpp
@@ -19,7 +19,8 @@ extern bool g_IsNT;
19 19
20UString g_LangID; 20UString g_LangID;
21 21
22static CLang g_Lang; 22// static
23CLang g_Lang;
23static bool g_Loaded = false; 24static bool g_Loaded = false;
24static NSynchronization::CCriticalSection g_CriticalSection; 25static NSynchronization::CCriticalSection g_CriticalSection;
25 26
@@ -34,6 +35,8 @@ FString GetLangDirPrefix()
34 return NDLL::GetModuleDirPrefix() + FTEXT("Lang") FSTRING_PATH_SEPARATOR; 35 return NDLL::GetModuleDirPrefix() + FTEXT("Lang") FSTRING_PATH_SEPARATOR;
35} 36}
36 37
38#ifdef Z7_LANG
39
37void LoadLangOneTime() 40void LoadLangOneTime()
38{ 41{
39 NSynchronization::CCriticalSectionLock lock(g_CriticalSection); 42 NSynchronization::CCriticalSectionLock lock(g_CriticalSection);
@@ -48,7 +51,7 @@ void LangSetDlgItemText(HWND dialog, UInt32 controlID, UInt32 langID)
48 const wchar_t *s = g_Lang.Get(langID); 51 const wchar_t *s = g_Lang.Get(langID);
49 if (s) 52 if (s)
50 { 53 {
51 CWindow window(GetDlgItem(dialog, controlID)); 54 CWindow window(GetDlgItem(dialog, (int)controlID));
52 window.SetText(s); 55 window.SetText(s);
53 } 56 }
54} 57}
@@ -67,10 +70,10 @@ static const CIDLangPair kLangPairs[] =
67void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems) 70void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems)
68{ 71{
69 unsigned i; 72 unsigned i;
70 for (i = 0; i < ARRAY_SIZE(kLangPairs); i++) 73 for (i = 0; i < Z7_ARRAY_SIZE(kLangPairs); i++)
71 { 74 {
72 const CIDLangPair &pair = kLangPairs[i]; 75 const CIDLangPair &pair = kLangPairs[i];
73 CWindow window(GetDlgItem(dialog, pair.ControlID)); 76 CWindow window(GetDlgItem(dialog, (int)pair.ControlID));
74 if (window) 77 if (window)
75 { 78 {
76 const wchar_t *s = g_Lang.Get(pair.LangID); 79 const wchar_t *s = g_Lang.Get(pair.LangID);
@@ -81,7 +84,7 @@ void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems)
81 84
82 for (i = 0; i < numItems; i++) 85 for (i = 0; i < numItems; i++)
83 { 86 {
84 UInt32 id = ids[i]; 87 const UInt32 id = ids[i];
85 LangSetDlgItemText(dialog, id, id); 88 LangSetDlgItemText(dialog, id, id);
86 } 89 }
87} 90}
@@ -90,11 +93,11 @@ void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems)
90{ 93{
91 for (unsigned i = 0; i < numItems; i++) 94 for (unsigned i = 0; i < numItems; i++)
92 { 95 {
93 UInt32 id = ids[i]; 96 const UInt32 id = ids[i];
94 const wchar_t *s = g_Lang.Get(id); 97 const wchar_t *s = g_Lang.Get(id);
95 if (s) 98 if (s)
96 { 99 {
97 CWindow window(GetDlgItem(dialog, id)); 100 CWindow window(GetDlgItem(dialog, (int)id));
98 UString s2 = s; 101 UString s2 = s;
99 s2 += ':'; 102 s2 += ':';
100 window.SetText(s2); 103 window.SetText(s2);
@@ -102,6 +105,23 @@ void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems)
102 } 105 }
103} 106}
104 107
108void LangSetDlgItems_RemoveColon(HWND dialog, const UInt32 *ids, unsigned numItems)
109{
110 for (unsigned i = 0; i < numItems; i++)
111 {
112 const UInt32 id = ids[i];
113 const wchar_t *s = g_Lang.Get(id);
114 if (s)
115 {
116 CWindow window(GetDlgItem(dialog, (int)id));
117 UString s2 = s;
118 if (!s2.IsEmpty() && s2.Back() == ':')
119 s2.DeleteBack();
120 window.SetText(s2);
121 }
122 }
123}
124
105void LangSetWindowText(HWND window, UInt32 langID) 125void LangSetWindowText(HWND window, UInt32 langID)
106{ 126{
107 const wchar_t *s = g_Lang.Get(langID); 127 const wchar_t *s = g_Lang.Get(langID);
@@ -214,14 +234,18 @@ static struct CC1Lang
214 234
215// typedef LANGID (WINAPI *GetUserDefaultUILanguageP)(); 235// typedef LANGID (WINAPI *GetUserDefaultUILanguageP)();
216 236
217static void OpenDefaultLang() 237void Lang_GetShortNames_for_DefaultLang(AStringVector &names, unsigned &subLang)
218{ 238{
219 LANGID sysLang = GetSystemDefaultLangID(); // "Language for non-Unicode programs" in XP64 239 names.Clear();
220 LANGID userLang = GetUserDefaultLangID(); // "Standards and formats" language in XP64 240 subLang = 0;
241 const LANGID sysLang = GetSystemDefaultLangID(); // "Language for non-Unicode programs" in XP64
242 const LANGID userLang = GetUserDefaultLangID(); // "Standards and formats" language in XP64
221 243
222 if (sysLang != userLang) 244 if (sysLang != userLang)
223 return; 245 return;
224 LANGID langID = userLang; 246 const LANGID langID = userLang;
247
248 // const LANGID langID = MAKELANGID(0x1a, 1); // for debug
225 249
226 /* 250 /*
227 LANGID sysUILang; // english in XP64 251 LANGID sysUILang; // english in XP64
@@ -237,15 +261,22 @@ static void OpenDefaultLang()
237 sysUILang = fn(); 261 sysUILang = fn();
238 */ 262 */
239 263
240 WORD primLang = (WORD)(PRIMARYLANGID(langID)); 264 const WORD primLang = (WORD)(PRIMARYLANGID(langID));
241 WORD subLang = (WORD)(SUBLANGID(langID)); 265 subLang = SUBLANGID(langID);
266 FindShortNames(primLang, names);
267}
268
269
270static void OpenDefaultLang()
271{
272 AStringVector names;
273 unsigned subLang;
274 Lang_GetShortNames_for_DefaultLang(names, subLang);
242 { 275 {
243 AStringVector names;
244 FindShortNames(primLang, names);
245 const FString dirPrefix (GetLangDirPrefix()); 276 const FString dirPrefix (GetLangDirPrefix());
246 for (unsigned i = 0; i < 2; i++) 277 for (unsigned i = 0; i < 2; i++)
247 { 278 {
248 unsigned index = (i == 0 ? subLang : 0); 279 const unsigned index = (i == 0 ? subLang : 0);
249 if (index < names.Size()) 280 if (index < names.Size())
250 { 281 {
251 const AString &name = names[index]; 282 const AString &name = names[index];
@@ -282,12 +313,14 @@ void ReloadLang()
282 if (g_LangID.Len() > 1 || g_LangID[0] != L'-') 313 if (g_LangID.Len() > 1 || g_LangID[0] != L'-')
283 { 314 {
284 FString s = us2fs(g_LangID); 315 FString s = us2fs(g_LangID);
285 if (s.Find(FCHAR_PATH_SEPARATOR) < 0) 316 if (s.ReverseFind_PathSepar() < 0)
286 { 317 {
287 if (s.Find(FTEXT('.')) < 0) 318 if (s.ReverseFind_Dot() < 0)
288 s += ".txt"; 319 s += ".txt";
289 s.Insert(0, GetLangDirPrefix()); 320 s.Insert(0, GetLangDirPrefix());
321 LangOpen(g_Lang, s);
290 } 322 }
291 LangOpen(g_Lang, s);
292 } 323 }
293} 324}
325
326#endif
diff --git a/CPP/7zip/UI/FileManager/LangUtils.h b/CPP/7zip/UI/FileManager/LangUtils.h
index d63a443..d53d270 100644
--- a/CPP/7zip/UI/FileManager/LangUtils.h
+++ b/CPP/7zip/UI/FileManager/LangUtils.h
@@ -1,13 +1,16 @@
1// LangUtils.h 1// LangUtils.h
2 2
3#ifndef __LANG_UTILS_H 3#ifndef ZIP7_INC_LANG_UTILS_H
4#define __LANG_UTILS_H 4#define ZIP7_INC_LANG_UTILS_H
5 5
6#include "../../../Windows/ResourceString.h" 6#include "../../../Common/Lang.h"
7 7
8#ifdef LANG 8#include "../../../Windows/ResourceString.h"
9 9
10extern UString g_LangID; 10extern UString g_LangID;
11extern CLang g_Lang;
12
13#ifdef Z7_LANG
11 14
12struct CIDLangPair 15struct CIDLangPair
13{ 16{
@@ -17,11 +20,11 @@ struct CIDLangPair
17 20
18void ReloadLang(); 21void ReloadLang();
19void LoadLangOneTime(); 22void LoadLangOneTime();
20FString GetLangDirPrefix();
21 23
22void LangSetDlgItemText(HWND dialog, UInt32 controlID, UInt32 langID); 24void LangSetDlgItemText(HWND dialog, UInt32 controlID, UInt32 langID);
23void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems); 25void LangSetDlgItems(HWND dialog, const UInt32 *ids, unsigned numItems);
24void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems); 26void LangSetDlgItems_Colon(HWND dialog, const UInt32 *ids, unsigned numItems);
27void LangSetDlgItems_RemoveColon(HWND dialog, const UInt32 *ids, unsigned numItems);
25void LangSetWindowText(HWND window, UInt32 langID); 28void LangSetWindowText(HWND window, UInt32 langID);
26 29
27UString LangString(UInt32 langID); 30UString LangString(UInt32 langID);
@@ -37,4 +40,9 @@ inline void AddLangString(UString &s, UInt32 langID) { s += NWindows::MyLoadStri
37 40
38#endif 41#endif
39 42
43FString GetLangDirPrefix();
44// bool LangOpen(CLang &lang, CFSTR fileName);
45
46void Lang_GetShortNames_for_DefaultLang(AStringVector &names, unsigned &subLang);
47
40#endif 48#endif
diff --git a/CPP/7zip/UI/FileManager/LinkDialog.cpp b/CPP/7zip/UI/FileManager/LinkDialog.cpp
index 07f1f06..0f24761 100644
--- a/CPP/7zip/UI/FileManager/LinkDialog.cpp
+++ b/CPP/7zip/UI/FileManager/LinkDialog.cpp
@@ -8,9 +8,7 @@
8#include "../../../Windows/FileIO.h" 8#include "../../../Windows/FileIO.h"
9#include "../../../Windows/FileName.h" 9#include "../../../Windows/FileName.h"
10 10
11#ifdef LANG
12#include "LangUtils.h" 11#include "LangUtils.h"
13#endif
14 12
15#include "BrowseDialog.h" 13#include "BrowseDialog.h"
16#include "CopyDialogRes.h" 14#include "CopyDialogRes.h"
@@ -26,7 +24,7 @@ extern bool g_SymLink_Supported;
26using namespace NWindows; 24using namespace NWindows;
27using namespace NFile; 25using namespace NFile;
28 26
29#ifdef LANG 27#ifdef Z7_LANG
30static const UInt32 kLangIDs[] = 28static const UInt32 kLangIDs[] =
31{ 29{
32 IDB_LINK_LINK, 30 IDB_LINK_LINK,
@@ -73,7 +71,7 @@ static bool GetSymLink(CFSTR path, CReparseAttr &attr, UString &errorMessage)
73} 71}
74 72
75 73
76static const int k_LinkType_Buttons[] = 74static const unsigned k_LinkType_Buttons[] =
77{ 75{
78 IDR_LINK_TYPE_HARD, 76 IDR_LINK_TYPE_HARD,
79 IDR_LINK_TYPE_SYM_FILE, 77 IDR_LINK_TYPE_SYM_FILE,
@@ -82,16 +80,19 @@ static const int k_LinkType_Buttons[] =
82 IDR_LINK_TYPE_WSL 80 IDR_LINK_TYPE_WSL
83}; 81};
84 82
85void CLinkDialog::Set_LinkType_Radio(int idb) 83void CLinkDialog::Set_LinkType_Radio(unsigned idb)
86{ 84{
87 CheckRadioButton(k_LinkType_Buttons[0], k_LinkType_Buttons[ARRAY_SIZE(k_LinkType_Buttons) - 1], idb); 85 CheckRadioButton(
86 k_LinkType_Buttons[0],
87 k_LinkType_Buttons[Z7_ARRAY_SIZE(k_LinkType_Buttons) - 1],
88 idb);
88} 89}
89 90
90bool CLinkDialog::OnInit() 91bool CLinkDialog::OnInit()
91{ 92{
92 #ifdef LANG 93 #ifdef Z7_LANG
93 LangSetWindowText(*this, IDD_LINK); 94 LangSetWindowText(*this, IDD_LINK);
94 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 95 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
95 #endif 96 #endif
96 97
97 _pathFromCombo.Attach(GetItem(IDC_LINK_PATH_FROM)); 98 _pathFromCombo.Attach(GetItem(IDC_LINK_PATH_FROM));
@@ -100,7 +101,7 @@ bool CLinkDialog::OnInit()
100 if (!FilePath.IsEmpty()) 101 if (!FilePath.IsEmpty())
101 { 102 {
102 NFind::CFileInfo fi; 103 NFind::CFileInfo fi;
103 int linkType = 0; 104 unsigned linkType = 0;
104 if (!fi.Find(us2fs(FilePath))) 105 if (!fi.Find(us2fs(FilePath)))
105 linkType = IDR_LINK_TYPE_SYM_FILE; 106 linkType = IDR_LINK_TYPE_SYM_FILE;
106 else 107 else
@@ -109,7 +110,7 @@ bool CLinkDialog::OnInit()
109 { 110 {
110 CReparseAttr attr; 111 CReparseAttr attr;
111 UString error; 112 UString error;
112 bool res = GetSymLink(us2fs(FilePath), attr, error); 113 const bool res = GetSymLink(us2fs(FilePath), attr, error);
113 if (!res && error.IsEmpty()) 114 if (!res && error.IsEmpty())
114 { 115 {
115 DWORD lastError = GetLastError(); 116 DWORD lastError = GetLastError();
@@ -138,7 +139,7 @@ bool CLinkDialog::OnInit()
138 139
139 SetItemText(IDT_LINK_PATH_TO_CUR, s); 140 SetItemText(IDT_LINK_PATH_TO_CUR, s);
140 141
141 UString destPath = attr.GetPath(); 142 const UString destPath = attr.GetPath();
142 _pathFromCombo.SetText(FilePath); 143 _pathFromCombo.SetText(FilePath);
143 _pathToCombo.SetText(destPath); 144 _pathToCombo.SetText(destPath);
144 145
@@ -215,7 +216,7 @@ bool CLinkDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
215 return false; 216 return false;
216} 217}
217 218
218bool CLinkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 219bool CLinkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
219{ 220{
220 switch (buttonID) 221 switch (buttonID)
221 { 222 {
@@ -240,7 +241,7 @@ void CLinkDialog::OnButton_SetPath(bool to)
240 _pathFromCombo; 241 _pathFromCombo;
241 combo.GetText(currentPath); 242 combo.GetText(currentPath);
242 // UString title = "Specify a location for output folder"; 243 // UString title = "Specify a location for output folder";
243 UString title = LangString(IDS_SET_FOLDER); 244 const UString title = LangString(IDS_SET_FOLDER);
244 245
245 UString resultPath; 246 UString resultPath;
246 if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) 247 if (!MyBrowseForFolder(*this, title, currentPath, resultPath))
@@ -271,10 +272,10 @@ void CLinkDialog::OnButton_Link()
271 if (!NName::IsAbsolutePath(from)) 272 if (!NName::IsAbsolutePath(from))
272 from.Insert(0, CurDirPrefix); 273 from.Insert(0, CurDirPrefix);
273 274
274 int idb = -1; 275 unsigned idb = 0;
275 for (unsigned i = 0;; i++) 276 for (unsigned i = 0;; i++)
276 { 277 {
277 if (i >= ARRAY_SIZE(k_LinkType_Buttons)) 278 if (i >= Z7_ARRAY_SIZE(k_LinkType_Buttons))
278 return; 279 return;
279 idb = k_LinkType_Buttons[i]; 280 idb = k_LinkType_Buttons[i];
280 if (IsButtonCheckedBool(idb)) 281 if (IsButtonCheckedBool(idb))
@@ -355,7 +356,7 @@ void CLinkDialog::OnButton_Link()
355 356
356void CApp::Link() 357void CApp::Link()
357{ 358{
358 unsigned srcPanelIndex = GetFocusedPanelIndex(); 359 const unsigned srcPanelIndex = GetFocusedPanelIndex();
359 CPanel &srcPanel = Panels[srcPanelIndex]; 360 CPanel &srcPanel = Panels[srcPanelIndex];
360 if (!srcPanel.IsFSFolder()) 361 if (!srcPanel.IsFSFolder())
361 { 362 {
@@ -363,7 +364,7 @@ void CApp::Link()
363 return; 364 return;
364 } 365 }
365 CRecordVector<UInt32> indices; 366 CRecordVector<UInt32> indices;
366 srcPanel.GetOperatedItemIndices(indices); 367 srcPanel.Get_ItemIndices_Operated(indices);
367 if (indices.IsEmpty()) 368 if (indices.IsEmpty())
368 return; 369 return;
369 if (indices.Size() != 1) 370 if (indices.Size() != 1)
@@ -371,14 +372,14 @@ void CApp::Link()
371 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); 372 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE);
372 return; 373 return;
373 } 374 }
374 int index = indices[0]; 375 const UInt32 index = indices[0];
375 const UString itemName = srcPanel.GetItemName(index); 376 const UString itemName = srcPanel.GetItemName(index);
376 377
377 const UString fsPrefix = srcPanel.GetFsPath(); 378 const UString fsPrefix = srcPanel.GetFsPath();
378 const UString srcPath = fsPrefix + srcPanel.GetItemPrefix(index); 379 const UString srcPath = fsPrefix + srcPanel.GetItemPrefix(index);
379 UString path = srcPath; 380 UString path = srcPath;
380 { 381 {
381 unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); 382 const unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex);
382 CPanel &destPanel = Panels[destPanelIndex]; 383 CPanel &destPanel = Panels[destPanelIndex];
383 if (NumPanels > 1) 384 if (NumPanels > 1)
384 if (destPanel.IsFSFolder()) 385 if (destPanel.IsFSFolder())
diff --git a/CPP/7zip/UI/FileManager/LinkDialog.h b/CPP/7zip/UI/FileManager/LinkDialog.h
index 56deec9..dd768f7 100644
--- a/CPP/7zip/UI/FileManager/LinkDialog.h
+++ b/CPP/7zip/UI/FileManager/LinkDialog.h
@@ -1,7 +1,7 @@
1// LinkDialog.h 1// LinkDialog.h
2 2
3#ifndef __LINK_DIALOG_H 3#ifndef ZIP7_INC_LINK_DIALOG_H
4#define __LINK_DIALOG_H 4#define ZIP7_INC_LINK_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/ComboBox.h" 7#include "../../../Windows/Control/ComboBox.h"
@@ -13,21 +13,21 @@ class CLinkDialog: public NWindows::NControl::CModalDialog
13 NWindows::NControl::CComboBox _pathFromCombo; 13 NWindows::NControl::CComboBox _pathFromCombo;
14 NWindows::NControl::CComboBox _pathToCombo; 14 NWindows::NControl::CComboBox _pathToCombo;
15 15
16 virtual bool OnInit(); 16 virtual bool OnInit() Z7_override;
17 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 17 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
18 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 18 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
19 void OnButton_SetPath(bool to); 19 void OnButton_SetPath(bool to);
20 void OnButton_Link(); 20 void OnButton_Link();
21 21
22 void ShowLastErrorMessage(); 22 void ShowLastErrorMessage();
23 void ShowError(const wchar_t *s); 23 void ShowError(const wchar_t *s);
24 void Set_LinkType_Radio(int idb); 24 void Set_LinkType_Radio(unsigned idb);
25public: 25public:
26 UString CurDirPrefix; 26 UString CurDirPrefix;
27 UString FilePath; 27 UString FilePath;
28 UString AnotherPath; 28 UString AnotherPath;
29 29
30 INT_PTR Create(HWND parentWindow = 0) 30 INT_PTR Create(HWND parentWindow = NULL)
31 { return CModalDialog::Create(IDD_LINK, parentWindow); } 31 { return CModalDialog::Create(IDD_LINK, parentWindow); }
32}; 32};
33 33
diff --git a/CPP/7zip/UI/FileManager/ListViewDialog.cpp b/CPP/7zip/UI/FileManager/ListViewDialog.cpp
index a42e790..6767e4c 100644
--- a/CPP/7zip/UI/FileManager/ListViewDialog.cpp
+++ b/CPP/7zip/UI/FileManager/ListViewDialog.cpp
@@ -8,7 +8,7 @@
8#include "ListViewDialog.h" 8#include "ListViewDialog.h"
9#include "RegistryUtils.h" 9#include "RegistryUtils.h"
10 10
11#ifdef LANG 11#ifdef Z7_LANG
12#include "LangUtils.h" 12#include "LangUtils.h"
13#endif 13#endif
14 14
@@ -26,14 +26,14 @@ static void ListView_GetSelected(NControl::CListView &listView, CUIntVector &vec
26 index = listView.GetNextSelectedItem(index); 26 index = listView.GetNextSelectedItem(index);
27 if (index < 0) 27 if (index < 0)
28 break; 28 break;
29 vector.Add(index); 29 vector.Add((unsigned)index);
30 } 30 }
31} 31}
32 32
33 33
34bool CListViewDialog::OnInit() 34bool CListViewDialog::OnInit()
35{ 35{
36 #ifdef LANG 36 #ifdef Z7_LANG
37 LangSetDlgItems(*this, NULL, 0); 37 LangSetDlgItems(*this, NULL, 0);
38 #endif 38 #endif
39 _listView.Attach(GetItem(IDL_LISTVIEW)); 39 _listView.Attach(GetItem(IDL_LISTVIEW));
@@ -227,17 +227,17 @@ void CListViewDialog::DeleteItems()
227{ 227{
228 for (;;) 228 for (;;)
229 { 229 {
230 int index = _listView.GetNextSelectedItem(-1); 230 const int index = _listView.GetNextSelectedItem(-1);
231 if (index < 0) 231 if (index < 0)
232 break; 232 break;
233 StringsWereChanged = true; 233 StringsWereChanged = true;
234 _listView.DeleteItem(index); 234 _listView.DeleteItem((unsigned)index);
235 if ((unsigned)index < Strings.Size()) 235 if ((unsigned)index < Strings.Size())
236 Strings.Delete(index); 236 Strings.Delete((unsigned)index);
237 if ((unsigned)index < Values.Size()) 237 if ((unsigned)index < Values.Size())
238 Values.Delete(index); 238 Values.Delete((unsigned)index);
239 } 239 }
240 int focusedIndex = _listView.GetFocusedItem(); 240 const int focusedIndex = _listView.GetFocusedItem();
241 if (focusedIndex >= 0) 241 if (focusedIndex >= 0)
242 _listView.SetItemState_FocusedSelected(focusedIndex); 242 _listView.SetItemState_FocusedSelected(focusedIndex);
243 _listView.SetColumnWidthAuto(0); 243 _listView.SetColumnWidthAuto(0);
diff --git a/CPP/7zip/UI/FileManager/ListViewDialog.h b/CPP/7zip/UI/FileManager/ListViewDialog.h
index 00206af..5f0b66d 100644
--- a/CPP/7zip/UI/FileManager/ListViewDialog.h
+++ b/CPP/7zip/UI/FileManager/ListViewDialog.h
@@ -1,7 +1,7 @@
1// ListViewDialog.h 1// ListViewDialog.h
2 2
3#ifndef __LISTVIEW_DIALOG_H 3#ifndef ZIP7_INC_LISTVIEW_DIALOG_H
4#define __LISTVIEW_DIALOG_H 4#define ZIP7_INC_LISTVIEW_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/ListView.h" 7#include "../../../Windows/Control/ListView.h"
@@ -11,10 +11,10 @@
11class CListViewDialog: public NWindows::NControl::CModalDialog 11class CListViewDialog: public NWindows::NControl::CModalDialog
12{ 12{
13 NWindows::NControl::CListView _listView; 13 NWindows::NControl::CListView _listView;
14 virtual void OnOK(); 14 virtual void OnOK() Z7_override;
15 virtual bool OnInit(); 15 virtual bool OnInit() Z7_override;
16 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 16 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
17 virtual bool OnNotify(UINT controlID, LPNMHDR header); 17 virtual bool OnNotify(UINT controlID, LPNMHDR header) Z7_override;
18 void CopyToClipboard(); 18 void CopyToClipboard();
19 void DeleteItems(); 19 void DeleteItems();
20 void ShowItemInfo(); 20 void ShowItemInfo();
@@ -32,7 +32,7 @@ public:
32 int FocusedItemIndex; 32 int FocusedItemIndex;
33 unsigned NumColumns; 33 unsigned NumColumns;
34 34
35 INT_PTR Create(HWND wndParent = 0) { return CModalDialog::Create(IDD_LISTVIEW, wndParent); } 35 INT_PTR Create(HWND wndParent = NULL) { return CModalDialog::Create(IDD_LISTVIEW, wndParent); }
36 36
37 CListViewDialog(): 37 CListViewDialog():
38 SelectFirst(false), 38 SelectFirst(false),
diff --git a/CPP/7zip/UI/FileManager/MenuPage.cpp b/CPP/7zip/UI/FileManager/MenuPage.cpp
index 32dabae..2da7f3a 100644
--- a/CPP/7zip/UI/FileManager/MenuPage.cpp
+++ b/CPP/7zip/UI/FileManager/MenuPage.cpp
@@ -26,6 +26,7 @@
26using namespace NWindows; 26using namespace NWindows;
27using namespace NContextMenuFlags; 27using namespace NContextMenuFlags;
28 28
29#ifdef Z7_LANG
29static const UInt32 kLangIDs[] = 30static const UInt32 kLangIDs[] =
30{ 31{
31 IDX_SYSTEM_INTEGRATE_TO_MENU, 32 IDX_SYSTEM_INTEGRATE_TO_MENU,
@@ -35,12 +36,13 @@ static const UInt32 kLangIDs[] =
35 IDT_SYSTEM_ZONE, 36 IDT_SYSTEM_ZONE,
36 IDT_SYSTEM_CONTEXT_MENU_ITEMS 37 IDT_SYSTEM_CONTEXT_MENU_ITEMS
37}; 38};
39#endif
38 40
39#define kMenuTopic "fm/options.htm#sevenZip" 41#define kMenuTopic "fm/options.htm#sevenZip"
40 42
41struct CContextMenuItem 43struct CContextMenuItem
42{ 44{
43 int ControlID; 45 unsigned ControlID;
44 UInt32 Flag; 46 UInt32 Flag;
45}; 47};
46 48
@@ -97,7 +99,9 @@ bool CMenuPage::OnInit()
97 99
98 Clear_MenuChanged(); 100 Clear_MenuChanged();
99 101
100 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 102#ifdef Z7_LANG
103 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
104#endif
101 105
102 #ifdef UNDER_CE 106 #ifdef UNDER_CE
103 107
@@ -219,7 +223,7 @@ bool CMenuPage::OnInit()
219 if (i == 0) 223 if (i == 0)
220 s.Insert(0, L"* "); 224 s.Insert(0, L"* ");
221 const int index = (int)_zoneCombo.AddString(s); 225 const int index = (int)_zoneCombo.AddString(s);
222 _zoneCombo.SetItemData(index, val); 226 _zoneCombo.SetItemData(index, (LPARAM)val);
223 if (val == wz) 227 if (val == wz)
224 _zoneCombo.SetCurSel(index); 228 _zoneCombo.SetCurSel(index);
225 } 229 }
@@ -231,7 +235,7 @@ bool CMenuPage::OnInit()
231 235
232 _listView.InsertColumn(0, L"", 200); 236 _listView.InsertColumn(0, L"", 200);
233 237
234 for (unsigned i = 0; i < ARRAY_SIZE(kMenuItems); i++) 238 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kMenuItems); i++)
235 { 239 {
236 const CContextMenuItem &menuItem = kMenuItems[i]; 240 const CContextMenuItem &menuItem = kMenuItems[i];
237 241
@@ -272,8 +276,8 @@ bool CMenuPage::OnInit()
272 } 276 }
273 } 277 }
274 278
275 int itemIndex = _listView.InsertItem(i, s); 279 const int itemIndex = _listView.InsertItem(i, s);
276 _listView.SetCheckState(itemIndex, ((ci.Flags & menuItem.Flag) != 0)); 280 _listView.SetCheckState((unsigned)itemIndex, ((ci.Flags & menuItem.Flag) != 0));
277 } 281 }
278 282
279 _listView.SetColumnWidthAuto(0); 283 _listView.SetColumnWidthAuto(0);
@@ -303,8 +307,8 @@ LONG CMenuPage::OnApply()
303 CShellDll &dll = _dlls[d]; 307 CShellDll &dll = _dlls[d];
304 if (dll.wasChanged && !dll.Path.IsEmpty()) 308 if (dll.wasChanged && !dll.Path.IsEmpty())
305 { 309 {
306 bool newVal = IsButtonCheckedBool(dll.ctrl); 310 const bool newVal = IsButtonCheckedBool(dll.ctrl);
307 LONG res = SetContextMenuHandler(newVal, fs2us(dll.Path), dll.wow); 311 const LONG res = SetContextMenuHandler(newVal, fs2us(dll.Path), dll.wow);
308 if (res != ERROR_SUCCESS && (dll.prevValue != newVal || newVal)) 312 if (res != ERROR_SUCCESS && (dll.prevValue != newVal || newVal))
309 ShowMenuErrorMessage(NError::MyFormatMessage(res), *this); 313 ShowMenuErrorMessage(NError::MyFormatMessage(res), *this);
310 dll.prevValue = CheckContextMenuHandler(fs2us(dll.Path), dll.wow); 314 dll.prevValue = CheckContextMenuHandler(fs2us(dll.Path), dll.wow);
@@ -340,7 +344,7 @@ LONG CMenuPage::OnApply()
340 344
341 ci.Flags = 0; 345 ci.Flags = 0;
342 346
343 for (unsigned i = 0; i < ARRAY_SIZE(kMenuItems); i++) 347 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kMenuItems); i++)
344 if (_listView.GetCheckState(i)) 348 if (_listView.GetCheckState(i))
345 ci.Flags |= kMenuItems[i].Flag; 349 ci.Flags |= kMenuItems[i].Flag;
346 350
@@ -360,7 +364,7 @@ void CMenuPage::OnNotifyHelp()
360 ShowHelpWindow(kMenuTopic); 364 ShowHelpWindow(kMenuTopic);
361} 365}
362 366
363bool CMenuPage::OnButtonClicked(int buttonID, HWND buttonHWND) 367bool CMenuPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
364{ 368{
365 switch (buttonID) 369 switch (buttonID)
366 { 370 {
@@ -392,7 +396,7 @@ bool CMenuPage::OnButtonClicked(int buttonID, HWND buttonHWND)
392} 396}
393 397
394 398
395bool CMenuPage::OnCommand(int code, int itemID, LPARAM param) 399bool CMenuPage::OnCommand(unsigned code, unsigned itemID, LPARAM param)
396{ 400{
397 if (code == CBN_SELCHANGE && itemID == IDC_SYSTEM_ZONE) 401 if (code == CBN_SELCHANGE && itemID == IDC_SYSTEM_ZONE)
398 { 402 {
diff --git a/CPP/7zip/UI/FileManager/MenuPage.h b/CPP/7zip/UI/FileManager/MenuPage.h
index 02aee6d..3b62a8b 100644
--- a/CPP/7zip/UI/FileManager/MenuPage.h
+++ b/CPP/7zip/UI/FileManager/MenuPage.h
@@ -1,7 +1,7 @@
1// MenuPage.h 1// MenuPage.h
2 2
3#ifndef __MENU_PAGE_H 3#ifndef ZIP7_INC_MENU_PAGE_H
4#define __MENU_PAGE_H 4#define ZIP7_INC_MENU_PAGE_H
5 5
6#include "../../../Windows/Control/PropertyPage.h" 6#include "../../../Windows/Control/PropertyPage.h"
7#include "../../../Windows/Control/ComboBox.h" 7#include "../../../Windows/Control/ComboBox.h"
@@ -12,7 +12,7 @@ struct CShellDll
12 FString Path; 12 FString Path;
13 bool wasChanged; 13 bool wasChanged;
14 bool prevValue; 14 bool prevValue;
15 int ctrl; 15 unsigned ctrl;
16 UInt32 wow; 16 UInt32 wow;
17 17
18 CShellDll(): wasChanged (false), prevValue(false), ctrl(0), wow(0) {} 18 CShellDll(): wasChanged (false), prevValue(false), ctrl(0), wow(0) {}
@@ -44,14 +44,14 @@ class CMenuPage: public NWindows::NControl::CPropertyPage
44 NWindows::NControl::CListView _listView; 44 NWindows::NControl::CListView _listView;
45 NWindows::NControl::CComboBox _zoneCombo; 45 NWindows::NControl::CComboBox _zoneCombo;
46 46
47 virtual bool OnInit(); 47 virtual bool OnInit() Z7_override;
48 virtual void OnNotifyHelp(); 48 virtual void OnNotifyHelp() Z7_override;
49 virtual bool OnNotify(UINT controlID, LPNMHDR lParam); 49 virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override;
50 virtual bool OnItemChanged(const NMLISTVIEW *info); 50 virtual LONG OnApply() Z7_override;
51 virtual LONG OnApply(); 51 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
52 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 52 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override;
53 virtual bool OnCommand(int code, int itemID, LPARAM param); 53
54public: 54 bool OnItemChanged(const NMLISTVIEW* info);
55}; 55};
56 56
57#endif 57#endif
diff --git a/CPP/7zip/UI/FileManager/MessagesDialog.cpp b/CPP/7zip/UI/FileManager/MessagesDialog.cpp
index 4124827..57e56bc 100644
--- a/CPP/7zip/UI/FileManager/MessagesDialog.cpp
+++ b/CPP/7zip/UI/FileManager/MessagesDialog.cpp
@@ -16,9 +16,9 @@ using namespace NWindows;
16 16
17void CMessagesDialog::AddMessageDirect(LPCWSTR message) 17void CMessagesDialog::AddMessageDirect(LPCWSTR message)
18{ 18{
19 int i = _messageList.GetItemCount(); 19 const unsigned i = (unsigned)_messageList.GetItemCount();
20 wchar_t sz[16]; 20 wchar_t sz[16];
21 ConvertUInt32ToString((UInt32)i, sz); 21 ConvertUInt32ToString(i, sz);
22 _messageList.InsertItem(i, sz); 22 _messageList.InsertItem(i, sz);
23 _messageList.SetSubItem(i, 1, message); 23 _messageList.SetSubItem(i, 1, message);
24} 24}
@@ -28,18 +28,18 @@ void CMessagesDialog::AddMessage(LPCWSTR message)
28 UString s = message; 28 UString s = message;
29 while (!s.IsEmpty()) 29 while (!s.IsEmpty())
30 { 30 {
31 int pos = s.Find(L'\n'); 31 const int pos = s.Find(L'\n');
32 if (pos < 0) 32 if (pos < 0)
33 break; 33 break;
34 AddMessageDirect(s.Left(pos)); 34 AddMessageDirect(s.Left(pos));
35 s.DeleteFrontal(pos + 1); 35 s.DeleteFrontal((unsigned)pos + 1);
36 } 36 }
37 AddMessageDirect(s); 37 AddMessageDirect(s);
38} 38}
39 39
40bool CMessagesDialog::OnInit() 40bool CMessagesDialog::OnInit()
41{ 41{
42 #ifdef LANG 42 #ifdef Z7_LANG
43 LangSetWindowText(*this, IDD_MESSAGES); 43 LangSetWindowText(*this, IDD_MESSAGES);
44 LangSetDlgItems(*this, NULL, 0); 44 LangSetDlgItems(*this, NULL, 0);
45 SetItemText(IDOK, LangString(IDS_CLOSE)); 45 SetItemText(IDOK, LangString(IDS_CLOSE));
diff --git a/CPP/7zip/UI/FileManager/MessagesDialog.h b/CPP/7zip/UI/FileManager/MessagesDialog.h
index 5c017eb..40b0379 100644
--- a/CPP/7zip/UI/FileManager/MessagesDialog.h
+++ b/CPP/7zip/UI/FileManager/MessagesDialog.h
@@ -1,7 +1,7 @@
1// MessagesDialog.h 1// MessagesDialog.h
2 2
3#ifndef __MESSAGES_DIALOG_H 3#ifndef ZIP7_INC_MESSAGES_DIALOG_H
4#define __MESSAGES_DIALOG_H 4#define ZIP7_INC_MESSAGES_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/ListView.h" 7#include "../../../Windows/Control/ListView.h"
@@ -14,12 +14,12 @@ class CMessagesDialog: public NWindows::NControl::CModalDialog
14 14
15 void AddMessageDirect(LPCWSTR message); 15 void AddMessageDirect(LPCWSTR message);
16 void AddMessage(LPCWSTR message); 16 void AddMessage(LPCWSTR message);
17 virtual bool OnInit(); 17 virtual bool OnInit() Z7_override;
18 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 18 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
19public: 19public:
20 const UStringVector *Messages; 20 const UStringVector *Messages;
21 21
22 INT_PTR Create(HWND parent = 0) { return CModalDialog::Create(IDD_MESSAGES, parent); } 22 INT_PTR Create(HWND parent = NULL) { return CModalDialog::Create(IDD_MESSAGES, parent); }
23}; 23};
24 24
25#endif 25#endif
diff --git a/CPP/7zip/UI/FileManager/MyCom2.h b/CPP/7zip/UI/FileManager/MyCom2.h
index 5fe1ef7..d3b49fe 100644
--- a/CPP/7zip/UI/FileManager/MyCom2.h
+++ b/CPP/7zip/UI/FileManager/MyCom2.h
@@ -1,48 +1,55 @@
1// MyCom2.h 1// MyCom2.h
2 2
3#ifndef __MYCOM2_H 3#ifndef ZIP7_INC_MYCOM2_H
4#define __MYCOM2_H 4#define ZIP7_INC_MYCOM2_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
8#define MY_ADDREF_RELEASE_MT \ 8#define Z7_COM_ADDREF_RELEASE_MT \
9STDMETHOD_(ULONG, AddRef)() { InterlockedIncrement((LONG *)&__m_RefCount); return __m_RefCount; } \ 9 private: \
10STDMETHOD_(ULONG, Release)() { InterlockedDecrement((LONG *)&__m_RefCount); \ 10 STDMETHOD_(ULONG, AddRef)() Z7_override Z7_final \
11 if (__m_RefCount != 0) return __m_RefCount; \ 11 { return (ULONG)InterlockedIncrement((LONG *)&_m_RefCount); } \
12 delete this; return 0; } 12 STDMETHOD_(ULONG, Release)() Z7_override Z7_final \
13 13 { const LONG v = InterlockedDecrement((LONG *)&_m_RefCount); \
14#define MY_UNKNOWN_IMP_SPEC_MT2(i1, i) \ 14 if (v != 0) return (ULONG)v; \
15 MY_QUERYINTERFACE_BEGIN \ 15 delete this; return 0; }
16 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 16
17#define Z7_COM_UNKNOWN_IMP_SPEC_MT2(i1, i) \
18 Z7_COM_QI_BEGIN \
19 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
17 i \ 20 i \
18 MY_QUERYINTERFACE_END \ 21 Z7_COM_QI_END \
19 MY_ADDREF_RELEASE_MT 22 Z7_COM_ADDREF_RELEASE_MT
20 23
21 24
22#define MY_UNKNOWN_IMP1_MT(i) MY_UNKNOWN_IMP_SPEC_MT2( \ 25#define Z7_COM_UNKNOWN_IMP_1_MT(i) \
26 Z7_COM_UNKNOWN_IMP_SPEC_MT2( \
23 i, \ 27 i, \
24 MY_QUERYINTERFACE_ENTRY(i) \ 28 Z7_COM_QI_ENTRY(i) \
25 ) 29 )
26 30
27#define MY_UNKNOWN_IMP2_MT(i1, i2) MY_UNKNOWN_IMP_SPEC_MT2( \ 31#define Z7_COM_UNKNOWN_IMP_2_MT(i1, i2) \
32 Z7_COM_UNKNOWN_IMP_SPEC_MT2( \
28 i1, \ 33 i1, \
29 MY_QUERYINTERFACE_ENTRY(i1) \ 34 Z7_COM_QI_ENTRY(i1) \
30 MY_QUERYINTERFACE_ENTRY(i2) \ 35 Z7_COM_QI_ENTRY(i2) \
31 ) 36 )
32 37
33#define MY_UNKNOWN_IMP3_MT(i1, i2, i3) MY_UNKNOWN_IMP_SPEC_MT2( \ 38#define Z7_COM_UNKNOWN_IMP_3_MT(i1, i2, i3) \
39 Z7_COM_UNKNOWN_IMP_SPEC_MT2( \
34 i1, \ 40 i1, \
35 MY_QUERYINTERFACE_ENTRY(i1) \ 41 Z7_COM_QI_ENTRY(i1) \
36 MY_QUERYINTERFACE_ENTRY(i2) \ 42 Z7_COM_QI_ENTRY(i2) \
37 MY_QUERYINTERFACE_ENTRY(i3) \ 43 Z7_COM_QI_ENTRY(i3) \
38 ) 44 )
39 45
40#define MY_UNKNOWN_IMP4_MT(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC_MT2( \ 46#define Z7_COM_UNKNOWN_IMP_4_MT(i1, i2, i3, i4) \
47 Z7_COM_UNKNOWN_IMP_SPEC_MT2( \
41 i1, \ 48 i1, \
42 MY_QUERYINTERFACE_ENTRY(i1) \ 49 Z7_COM_QI_ENTRY(i1) \
43 MY_QUERYINTERFACE_ENTRY(i2) \ 50 Z7_COM_QI_ENTRY(i2) \
44 MY_QUERYINTERFACE_ENTRY(i3) \ 51 Z7_COM_QI_ENTRY(i3) \
45 MY_QUERYINTERFACE_ENTRY(i4) \ 52 Z7_COM_QI_ENTRY(i4) \
46 ) 53 )
47 54
48#endif 55#endif
diff --git a/CPP/7zip/UI/FileManager/MyLoadMenu.cpp b/CPP/7zip/UI/FileManager/MyLoadMenu.cpp
index 3973bb2..9453536 100644
--- a/CPP/7zip/UI/FileManager/MyLoadMenu.cpp
+++ b/CPP/7zip/UI/FileManager/MyLoadMenu.cpp
@@ -17,14 +17,15 @@
17#include "MyLoadMenu.h" 17#include "MyLoadMenu.h"
18#include "RegistryUtils.h" 18#include "RegistryUtils.h"
19 19
20#include "PropertyNameRes.h"
20#include "resource.h" 21#include "resource.h"
21 22
22using namespace NWindows; 23using namespace NWindows;
23 24
24static const UINT kOpenBookmarkMenuID = 830; 25static const UINT k_MenuID_OpenBookmark = 830;
25static const UINT kSetBookmarkMenuID = 810; 26static const UINT k_MenuID_SetBookmark = 810;
26static const UINT kMenuID_Time_Parent = 760; 27static const UINT k_MenuID_TimePopup = IDM_VIEW_TIME_POPUP;
27static const UINT kMenuID_Time = 761; 28static const UINT k_MenuID_Time = IDM_VIEW_TIME;
28 29
29extern HINSTANCE g_hInstance; 30extern HINSTANCE g_hInstance;
30 31
@@ -34,35 +35,45 @@ extern void OptionsDialog(HWND hwndOwner, HINSTANCE hInstance);
34 35
35enum 36enum
36{ 37{
37 kMenuIndex_File = 0, 38 k_MenuIndex_File = 0,
38 kMenuIndex_Edit, 39 k_MenuIndex_Edit,
39 kMenuIndex_View, 40 k_MenuIndex_View,
40 kMenuIndex_Bookmarks 41 k_MenuIndex_Bookmarks
41}; 42};
42 43
43static const UInt32 kTopMenuLangIDs[] = { 500, 501, 502, 503, 504, 505 }; 44#ifdef Z7_LANG
45static const UInt32 k_LangID_TopMenuItems[] =
46{
47 IDM_FILE,
48 IDM_EDIT,
49 IDM_VIEW,
50 IDM_FAVORITES,
51 IDM_TOOLS,
52 IDM_HELP
53};
44 54
45static const UInt32 kAddToFavoritesLangID = 800; 55static const UInt32 k_LangID_Toolbars = IDM_VIEW_TOOLBARS;
46static const UInt32 kToolbarsLangID = 733; 56static const UInt32 k_LangID_AddToFavorites = IDM_ADD_TO_FAVORITES;
47 57
48static const CIDLangPair kIDLangPairs[] = 58static const CIDLangPair kIDLangPairs[] =
49{ 59{
50 { IDCLOSE, 557 }, 60 { IDCLOSE, 557 }, // IDM_EXIT
51 { IDM_VIEW_ARANGE_BY_NAME, 1004 }, 61 { IDM_VIEW_ARANGE_BY_NAME, IDS_PROP_NAME },
52 { IDM_VIEW_ARANGE_BY_TYPE, 1020 }, 62 { IDM_VIEW_ARANGE_BY_TYPE, IDS_PROP_FILE_TYPE },
53 { IDM_VIEW_ARANGE_BY_DATE, 1012 }, 63 { IDM_VIEW_ARANGE_BY_DATE, IDS_PROP_MTIME },
54 { IDM_VIEW_ARANGE_BY_SIZE, 1007 } 64 { IDM_VIEW_ARANGE_BY_SIZE, IDS_PROP_SIZE }
55}; 65};
56 66
57static int FindLangItem(unsigned controlID) 67static int FindLangItem(unsigned controlID)
58{ 68{
59 for (unsigned i = 0; i < ARRAY_SIZE(kIDLangPairs); i++) 69 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kIDLangPairs); i++)
60 if (kIDLangPairs[i].ControlID == controlID) 70 if (kIDLangPairs[i].ControlID == controlID)
61 return i; 71 return (int)i;
62 return -1; 72 return -1;
63} 73}
74#endif
64 75
65static int GetSortControlID(PROPID propID) 76static unsigned GetSortControlID(PROPID propID)
66{ 77{
67 switch (propID) 78 switch (propID)
68 { 79 {
@@ -72,54 +83,55 @@ static int GetSortControlID(PROPID propID)
72 case kpidSize: return IDM_VIEW_ARANGE_BY_SIZE; 83 case kpidSize: return IDM_VIEW_ARANGE_BY_SIZE;
73 case kpidNoProperty: return IDM_VIEW_ARANGE_NO_SORT; 84 case kpidNoProperty: return IDM_VIEW_ARANGE_NO_SORT;
74 } 85 }
75 return -1; 86 return IDM_VIEW_ARANGE_BY_NAME;
87 // IDM_VIEW_ARANGE_NO_SORT;
88 // return -1;
76} 89}
77 90
78/* 91/*
79static bool g_IsNew_fMask = true; 92#if _MSC_VER > 1400
93// GetVersion was declared deprecated
94#pragma warning(disable : 4996)
95#endif
80 96
81class CInit_fMask 97static bool g_IsNew_fMask = false;
98static class CInit_fMask
82{ 99{
83public: 100public:
84 CInit_fMask() 101 CInit_fMask()
85 { 102 {
86 g_IsNew_fMask = false; 103 DWORD v = GetVersion();
87 OSVERSIONINFO vi; 104 v = ((v & 0xff) << 8) | ((v >> 8) & 0xFF);
88 vi.dwOSVersionInfoSize = sizeof(vi); 105 g_IsNew_fMask = (v > 0x400); // (win98/win2000) or newer
89 if (::GetVersionEx(&vi))
90 {
91 g_IsNew_fMask = (vi.dwMajorVersion > 4 ||
92 (vi.dwMajorVersion == 4 && vi.dwMinorVersion > 0));
93 }
94 g_IsNew_fMask = false;
95 } 106 }
96} g_Init_fMask; 107} g_Init_fMask;
97
98// it's hack for supporting Windows NT
99// constants are from WinUser.h
100
101#if (WINVER < 0x0500)
102#define MIIM_STRING 0x00000040
103#define MIIM_BITMAP 0x00000080
104#define MIIM_FTYPE 0x00000100
105#endif
106
107static UINT Get_fMask_for_String() 108static UINT Get_fMask_for_String()
108{ 109 { return g_IsNew_fMask ? MIIM_STRING : MIIM_TYPE; }
109 return g_IsNew_fMask ? MIIM_STRING : MIIM_TYPE;
110}
111
112static UINT Get_fMask_for_FType_and_String() 110static UINT Get_fMask_for_FType_and_String()
113{ 111 { return g_IsNew_fMask ? (MIIM_STRING | MIIM_FTYPE) : MIIM_TYPE; }
114 return g_IsNew_fMask ? (MIIM_STRING | MIIM_FTYPE) : MIIM_TYPE;
115}
116*/ 112*/
117 113
114/*
115We can use new MIIM_STRING / MIIM_FTYPE flags in the following conditions:
116 1) we run at new Windows (win98/win2000) or newer
117 2) also we probably must set MENUITEMINFO::cbSize as sizeof of full
118 (MENUITEMINFO) that was compiled with (WINVER >= 0x0500)
119But it's simpler to use old MIIM_TYPE without these complex checks.
120*/
121
122// /*
118static inline UINT Get_fMask_for_String() { return MIIM_TYPE; } 123static inline UINT Get_fMask_for_String() { return MIIM_TYPE; }
119static inline UINT Get_fMask_for_FType_and_String() { return MIIM_TYPE; } 124static inline UINT Get_fMask_for_FType_and_String() { return MIIM_TYPE; }
125// */
120 126
127static bool Is_MenuItem_TimePopup(const CMenuItem &item)
128{
129 return item.wID == k_MenuID_TimePopup ||
130 item.StringValue.IsPrefixedBy_Ascii_NoCase("20");
131}
121 132
122static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex) 133#ifdef Z7_LANG
134static void MyChangeMenu(HMENU menuLoc, unsigned menuID, unsigned level, unsigned menuIndex)
123{ 135{
124 CMenu menu; 136 CMenu menu;
125 menu.Attach(menuLoc); 137 menu.Attach(menuLoc);
@@ -127,55 +139,90 @@ static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex)
127 for (unsigned i = 0;; i++) 139 for (unsigned i = 0;; i++)
128 { 140 {
129 CMenuItem item; 141 CMenuItem item;
130 item.fMask = Get_fMask_for_String() | MIIM_SUBMENU | MIIM_ID; 142 /* here we can use
131 item.fType = MFT_STRING; 143 Get_fMask_for_String() or
144 Get_fMask_for_FType_and_String()
145 We want to change only String of menu item.
146 It's not required to change (fType) of menu item.
147 We can look (fType) to check for SEPARATOR item.
148 But String of separator is empty and (wID == 0).
149 So we can check for SEPARATOR without (fType) requesting.
150 So it's enough to use Get_fMask_for_String() here */
151 item.fMask =
152 Get_fMask_for_String()
153 // Get_fMask_for_FType_and_String()
154 | MIIM_SUBMENU | MIIM_ID;
132 if (!menu.GetItem(i, true, item)) 155 if (!menu.GetItem(i, true, item))
133 break; 156 break;
134 { 157 {
135 UString newString; 158 UString newString;
136 if (item.hSubMenu) 159 if (item.hSubMenu)
137 { 160 {
138 UInt32 langID = 0; 161 /* in win10:
139 if (level == 1 && menuIndex == kMenuIndex_Bookmarks) 162 MENU+POPUP:
140 langID = kAddToFavoritesLangID; 163 (wID == item.hSubMenu)
141 else 164 MENUEX+POPUP where ID is not set:
165 (wID == 0)
166 MENU+SEPARATOR
167 (wID == 0)
168 */
169 UInt32 langID = item.wID;
170 if (langID >= (1 << 16))
171 {
172 // here we try to exclude the case (wID == item.hSubMenu) if (MENU+POPUP)
173 continue;
174 }
175 if (langID == 0)
142 { 176 {
143 MyChangeMenu(item.hSubMenu, level + 1, i); 177 if (level == 0)
144 if (level == 1 && menuIndex == kMenuIndex_View)
145 { 178 {
146 if (item.wID == kMenuID_Time_Parent || item.StringValue.IsPrefixedBy_Ascii_NoCase("20")) 179 if (i < Z7_ARRAY_SIZE(k_LangID_TopMenuItems))
147 continue; 180 langID = k_LangID_TopMenuItems[i];
148 else 181 }
149 langID = kToolbarsLangID; 182 else if (level == 1)
183 {
184 if (menuID == IDM_FAVORITES || (menuID == 0 && menuIndex == k_MenuIndex_Bookmarks))
185 langID = k_LangID_AddToFavorites;
186 else if (menuID == IDM_VIEW || (menuID == 0 && menuIndex == k_MenuIndex_View))
187 {
188 if (Is_MenuItem_TimePopup(item))
189 langID = k_MenuID_TimePopup;
190 else
191 langID = k_LangID_Toolbars;
192 }
150 } 193 }
151 else if (level == 0 && i < ARRAY_SIZE(kTopMenuLangIDs))
152 langID = kTopMenuLangIDs[i];
153 else
154 continue;
155 } 194 }
156 195 if (langID == k_MenuID_TimePopup)
196 continue;
197 if (langID != k_LangID_AddToFavorites)
198 MyChangeMenu(item.hSubMenu, langID, level + 1, i);
199 if (langID == 0)
200 continue;
157 LangString_OnlyFromLangFile(langID, newString); 201 LangString_OnlyFromLangFile(langID, newString);
158
159 if (newString.IsEmpty()) 202 if (newString.IsEmpty())
160 continue; 203 continue;
161 } 204 }
162 else 205 else
163 { 206 {
207 if (item.fMask & (MIIM_TYPE | MIIM_FTYPE))
164 if (item.IsSeparator()) 208 if (item.IsSeparator())
165 continue; 209 continue;
166 int langPos = FindLangItem(item.wID); 210 if (item.StringValue.IsEmpty())
167 211 continue;
212 const int langPos = FindLangItem(item.wID);
168 // we don't need lang change for CRC items!!! 213 // we don't need lang change for CRC items!!!
214 const UInt32 langID = langPos >= 0 ? kIDLangPairs[langPos].LangID : item.wID;
215 if (langID == 0)
216 continue;
169 217
170 UInt32 langID = langPos >= 0 ? kIDLangPairs[langPos].LangID : item.wID; 218 if (langID == IDM_OPEN_INSIDE_ONE ||
171 219 langID == IDM_OPEN_INSIDE_PARSER)
172 if (langID == IDM_OPEN_INSIDE_ONE || langID == IDM_OPEN_INSIDE_PARSER)
173 { 220 {
174 LangString_OnlyFromLangFile(IDM_OPEN_INSIDE, newString); 221 LangString_OnlyFromLangFile(IDM_OPEN_INSIDE, newString);
175 if (newString.IsEmpty()) 222 if (newString.IsEmpty())
176 continue; 223 continue;
177 newString.Replace(L"&", L""); 224 newString.Replace(L"&", L"");
178 int tabPos = newString.Find(L"\t"); 225 const int tabPos = newString.Find(L"\t");
179 if (tabPos >= 0) 226 if (tabPos >= 0)
180 newString.DeleteFrom(tabPos); 227 newString.DeleteFrom(tabPos);
181 newString += (langID == IDM_OPEN_INSIDE_ONE ? " *" : " #"); 228 newString += (langID == IDM_OPEN_INSIDE_ONE ? " *" : " #");
@@ -186,37 +233,40 @@ static void MyChangeMenu(HMENU menuLoc, int level, int menuIndex)
186 if (newString.IsEmpty()) 233 if (newString.IsEmpty())
187 continue; 234 continue;
188 newString.Replace(L"&", L""); 235 newString.Replace(L"&", L"");
189 int tabPos = newString.Find(L"\t"); 236 const int tabPos = newString.Find(L"\t");
190 if (tabPos >= 0) 237 if (tabPos >= 0)
191 newString.DeleteFrom(tabPos); 238 newString.DeleteFrom(tabPos);
192 newString += " 2"; 239 newString += " 2";
193 } 240 }
194 else 241 else
242 {
195 LangString_OnlyFromLangFile(langID, newString); 243 LangString_OnlyFromLangFile(langID, newString);
244 }
196 245
197 if (newString.IsEmpty()) 246 if (newString.IsEmpty())
198 continue; 247 continue;
199 248
200 int tabPos = item.StringValue.ReverseFind(L'\t'); 249 const int tabPos = item.StringValue.ReverseFind(L'\t');
201 if (tabPos >= 0) 250 if (tabPos >= 0)
202 newString += item.StringValue.Ptr(tabPos); 251 newString += item.StringValue.Ptr(tabPos);
203 } 252 }
204 253
205 { 254 {
206 item.StringValue = newString; 255 item.StringValue = newString;
256 // we want to change only String
207 item.fMask = Get_fMask_for_String(); 257 item.fMask = Get_fMask_for_String();
208 item.fType = MFT_STRING;
209 menu.SetItem(i, true, item); 258 menu.SetItem(i, true, item);
210 } 259 }
211 } 260 }
212 } 261 }
213} 262}
263#endif
214 264
215static CMenu g_FileMenu; 265static CMenu g_FileMenu;
216 266
217static struct CFileMenuDestroyer 267static struct CFileMenuDestroyer
218{ 268{
219 ~CFileMenuDestroyer() { if ((HMENU)g_FileMenu != 0) g_FileMenu.Destroy(); } 269 ~CFileMenuDestroyer() { if ((HMENU)g_FileMenu) g_FileMenu.Destroy(); }
220} g_FileMenuDestroyer; 270} g_FileMenuDestroyer;
221 271
222 272
@@ -224,6 +274,12 @@ static void CopyMenu(HMENU srcMenuSpec, HMENU destMenuSpec);
224 274
225static void CopyPopMenu_IfRequired(CMenuItem &item) 275static void CopyPopMenu_IfRequired(CMenuItem &item)
226{ 276{
277 /* if (item.hSubMenu) is defined
278 {
279 - it creates new (popup) menu
280 - it copies menu items from old item.hSubMenu menu to new (popup) menu
281 - it sets item.hSubMenu to handle of created (popup) menu
282 } */
227 if (item.hSubMenu) 283 if (item.hSubMenu)
228 { 284 {
229 CMenu popup; 285 CMenu popup;
@@ -233,64 +289,91 @@ static void CopyPopMenu_IfRequired(CMenuItem &item)
233 } 289 }
234} 290}
235 291
292/* destMenuSpec must be non-NULL handle to created empty popup menu */
236static void CopyMenu(HMENU srcMenuSpec, HMENU destMenuSpec) 293static void CopyMenu(HMENU srcMenuSpec, HMENU destMenuSpec)
237{ 294{
238 CMenu srcMenu; 295 CMenu srcMenu;
239 srcMenu.Attach(srcMenuSpec); 296 srcMenu.Attach(srcMenuSpec);
240 CMenu destMenu; 297 CMenu destMenu;
241 destMenu.Attach(destMenuSpec); 298 destMenu.Attach(destMenuSpec);
242 int startPos = 0; 299 unsigned startPos = 0;
243 for (int i = 0;; i++) 300 for (unsigned i = 0;; i++)
244 { 301 {
245 CMenuItem item; 302 CMenuItem item;
246 item.fMask = MIIM_SUBMENU | MIIM_STATE | MIIM_ID | Get_fMask_for_FType_and_String(); 303 item.fMask = MIIM_SUBMENU | MIIM_STATE | MIIM_ID | Get_fMask_for_FType_and_String();
247 item.fType = MFT_STRING;
248
249 if (!srcMenu.GetItem(i, true, item)) 304 if (!srcMenu.GetItem(i, true, item))
250 break; 305 break;
251
252 CopyPopMenu_IfRequired(item); 306 CopyPopMenu_IfRequired(item);
253 if (destMenu.InsertItem(startPos, true, item)) 307 if (destMenu.InsertItem(startPos, true, item))
254 startPos++; 308 startPos++;
255 } 309 }
256} 310}
257 311
258void MyLoadMenu()
259{
260 HMENU baseMenu;
261 312
313/* use for (needResetMenu):
314 false : for call from program window creation code
315 true : for another calls : (from Options language change)
316*/
317void MyLoadMenu(bool needResetMenu)
318{
262 #ifdef UNDER_CE 319 #ifdef UNDER_CE
263 320
264 HMENU oldMenu = g_App._commandBar.GetMenu(0); 321 const HMENU oldMenu = g_App._commandBar.GetMenu(0);
265 if (oldMenu) 322 if (oldMenu)
266 ::DestroyMenu(oldMenu); 323 ::DestroyMenu(oldMenu);
267 /* BOOL b = */ g_App._commandBar.InsertMenubar(g_hInstance, IDM_MENU, 0); 324 /* BOOL b = */ g_App._commandBar.InsertMenubar(g_hInstance, IDM_MENU, 0);
268 baseMenu = g_App._commandBar.GetMenu(0); 325 const HMENU baseMenu = g_App._commandBar.GetMenu(0);
269 // if (startInit) 326 // if (startInit)
270 // SetIdsForSubMenes(baseMenu, 0, 0); 327 // SetIdsForSubMenus(baseMenu, 0, 0);
271 if (!g_LangID.IsEmpty()) 328 if (!g_LangID.IsEmpty())
272 MyChangeMenu(baseMenu, 0, 0); 329 MyChangeMenu(baseMenu, 0, 0);
273 g_App._commandBar.DrawMenuBar(0); 330 g_App._commandBar.DrawMenuBar(0);
274 331
275 #else 332 #else // UNDER_CE
276 333
277 HWND hWnd = g_HWND; 334 const HWND hWnd = g_HWND;
278 HMENU oldMenu = ::GetMenu(hWnd); 335 bool menuWasChanged = false;
279 ::SetMenu(hWnd, ::LoadMenu(g_hInstance, MAKEINTRESOURCE(IDM_MENU))); 336 /*
280 ::DestroyMenu(oldMenu); 337 We must reload to english default menu for at least two cases:
281 baseMenu = ::GetMenu(hWnd); 338 - if some submenu was changed (File or another submenu can be changed after menu activating).
339 - for change from non-english lang to another partial non-english lang,
340 where we still need some english strings.
341 But we reload menu to default menu everytime except of program starting stage.
342 That scheme is simpler than complex checks for exact conditions for menu reload.
343 */
344 if (needResetMenu)
345 {
346 const HMENU oldMenu = ::GetMenu(hWnd);
347 const HMENU newMenu = ::LoadMenu(g_hInstance, MAKEINTRESOURCE(IDM_MENU));
348 // docs for SetMenu(): the window is redrawn to reflect the menu change.
349 if (newMenu && ::SetMenu(hWnd, newMenu))
350 ::DestroyMenu(oldMenu);
351 menuWasChanged = true;
352 }
353 const HMENU baseMenu = ::GetMenu(hWnd);
282 // if (startInit) 354 // if (startInit)
283 // SetIdsForSubMenes(baseMenu, 0, 0); 355 // SetIdsForSubMenus(baseMenu, 0, 0);
284 if (!g_LangID.IsEmpty()) 356 #ifdef Z7_LANG
285 MyChangeMenu(baseMenu, 0, 0); 357 if (!g_Lang.IsEmpty()) // !g_LangID.IsEmpty() &&
286 ::DrawMenuBar(hWnd); 358 {
287 359 MyChangeMenu(baseMenu, 0, 0, 0);
360 menuWasChanged = true;
361 }
288 #endif 362 #endif
289 363
290 if ((HMENU)g_FileMenu != 0) 364 if (menuWasChanged)
291 g_FileMenu.Destroy(); 365 ::DrawMenuBar(hWnd);
292 g_FileMenu.CreatePopup(); 366
293 CopyMenu(::GetSubMenu(baseMenu, 0), g_FileMenu); 367 #endif // UNDER_CE
368
369 // menuWasChanged = false; // for debug
370 if (menuWasChanged || !(HMENU)g_FileMenu)
371 {
372 if ((HMENU)g_FileMenu)
373 g_FileMenu.Destroy();
374 g_FileMenu.CreatePopup();
375 CopyMenu(::GetSubMenu(baseMenu, k_MenuIndex_File), g_FileMenu);
376 }
294} 377}
295 378
296void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position) 379void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
@@ -306,14 +389,14 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
306 if (::GetSubMenu(mainMenu, position) != hMenu) 389 if (::GetSubMenu(mainMenu, position) != hMenu)
307 return; 390 return;
308 391
309 if (position == kMenuIndex_File) 392 if (position == k_MenuIndex_File)
310 { 393 {
311 CMenu menu; 394 CMenu menu;
312 menu.Attach(hMenu); 395 menu.Attach(hMenu);
313 menu.RemoveAllItems(); 396 menu.RemoveAllItems();
314 g_App.GetFocusedPanel().CreateFileMenu(hMenu); 397 g_App.GetFocusedPanel().CreateFileMenu(hMenu);
315 } 398 }
316 else if (position == kMenuIndex_Edit) 399 else if (position == k_MenuIndex_Edit)
317 { 400 {
318 /* 401 /*
319 CMenu menu; 402 CMenu menu;
@@ -323,16 +406,20 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
323 menu.EnableItem(IDM_EDIT_PASTE, IsClipboardFormatAvailableHDROP() ? MF_ENABLED : MF_GRAYED); 406 menu.EnableItem(IDM_EDIT_PASTE, IsClipboardFormatAvailableHDROP() ? MF_ENABLED : MF_GRAYED);
324 */ 407 */
325 } 408 }
326 else if (position == kMenuIndex_View) 409 else if (position == k_MenuIndex_View)
327 { 410 {
328 // View; 411 // View;
329 CMenu menu; 412 CMenu menu;
330 menu.Attach(hMenu); 413 menu.Attach(hMenu);
331 menu.CheckRadioItem(IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS, 414 menu.CheckRadioItem(
332 IDM_VIEW_LARGE_ICONS + g_App.GetListViewMode(), MF_BYCOMMAND); 415 IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS,
333 416 IDM_VIEW_LARGE_ICONS + g_App.GetListViewMode(), MF_BYCOMMAND);
334 menu.CheckRadioItem(IDM_VIEW_ARANGE_BY_NAME, IDM_VIEW_ARANGE_NO_SORT, 417
335 GetSortControlID(g_App.GetSortID()), MF_BYCOMMAND); 418 menu.CheckRadioItem(
419 IDM_VIEW_ARANGE_BY_NAME,
420 IDM_VIEW_ARANGE_NO_SORT,
421 GetSortControlID(g_App.GetSortID()),
422 MF_BYCOMMAND);
336 423
337 menu.CheckItemByID(IDM_VIEW_TWO_PANELS, g_App.NumPanels == 2); 424 menu.CheckItemByID(IDM_VIEW_TWO_PANELS, g_App.NumPanels == 2);
338 menu.CheckItemByID(IDM_VIEW_FLAT_VIEW, g_App.GetFlatMode()); 425 menu.CheckItemByID(IDM_VIEW_FLAT_VIEW, g_App.GetFlatMode());
@@ -344,16 +431,14 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
344 // menu.CheckItemByID(IDM_VIEW_SHOW_STREAMS, g_App.Get_ShowNtfsStrems_Mode()); 431 // menu.CheckItemByID(IDM_VIEW_SHOW_STREAMS, g_App.Get_ShowNtfsStrems_Mode());
345 // menu.CheckItemByID(IDM_VIEW_SHOW_DELETED, g_App.ShowDeletedFiles); 432 // menu.CheckItemByID(IDM_VIEW_SHOW_DELETED, g_App.ShowDeletedFiles);
346 433
347 for (int i = 0;; i++) 434 for (unsigned i = 0;; i++)
348 { 435 {
349 CMenuItem item; 436 CMenuItem item;
350 item.fMask = Get_fMask_for_String() | MIIM_SUBMENU | MIIM_ID; 437 item.fMask = Get_fMask_for_String() | MIIM_SUBMENU | MIIM_ID;
351 item.fType = MFT_STRING; 438 item.fType = MFT_STRING;
352 if (!menu.GetItem(i, true, item)) 439 if (!menu.GetItem(i, true, item))
353 break; 440 break;
354 if (item.hSubMenu && (item.wID == kMenuID_Time_Parent 441 if (item.hSubMenu && Is_MenuItem_TimePopup(item))
355 || item.StringValue.IsPrefixedBy_Ascii_NoCase("20")
356 ))
357 { 442 {
358 FILETIME ft; 443 FILETIME ft;
359 NTime::GetCurUtcFileTime(ft); 444 NTime::GetCurUtcFileTime(ft);
@@ -367,11 +452,11 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
367 452
368 item.fMask = Get_fMask_for_String() | MIIM_ID; 453 item.fMask = Get_fMask_for_String() | MIIM_ID;
369 item.fType = MFT_STRING; 454 item.fType = MFT_STRING;
370 item.wID = kMenuID_Time_Parent; 455 item.wID = k_MenuID_TimePopup;
371 menu.SetItem(i, true, item); 456 menu.SetItem(i, true, item);
372 457
373 CMenu subMenu; 458 CMenu subMenu;
374 subMenu.Attach(menu.GetSubMenu(i)); 459 subMenu.Attach(menu.GetSubMenu((int)i));
375 subMenu.RemoveAllItems(); 460 subMenu.RemoveAllItems();
376 461
377 const int k_TimeLevels[] = 462 const int k_TimeLevels[] =
@@ -384,16 +469,16 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
384 kTimestampPrintLevel_NS 469 kTimestampPrintLevel_NS
385 }; 470 };
386 471
387 unsigned last = kMenuID_Time; 472 unsigned last = k_MenuID_Time;
388 unsigned selectedCommand = 0; 473 unsigned selectedCommand = 0;
389 g_App._timestampLevels.Clear(); 474 g_App._timestampLevels.Clear();
390 unsigned id = kMenuID_Time; 475 unsigned id = k_MenuID_Time;
391 476
392 for (unsigned k = 0; k < ARRAY_SIZE(k_TimeLevels); k++) 477 for (unsigned k = 0; k < Z7_ARRAY_SIZE(k_TimeLevels); k++)
393 { 478 {
394 wchar_t s[64]; 479 wchar_t s[64];
395 s[0] = 0; 480 s[0] = 0;
396 int timestampLevel = k_TimeLevels[k]; 481 const int timestampLevel = k_TimeLevels[k];
397 if (ConvertUtcFileTimeToString(ft, s, timestampLevel)) 482 if (ConvertUtcFileTimeToString(ft, s, timestampLevel))
398 { 483 {
399 if (subMenu.AppendItem(MF_STRING, id, s)) 484 if (subMenu.AppendItem(MF_STRING, id, s))
@@ -407,11 +492,11 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
407 } 492 }
408 } 493 }
409 if (selectedCommand != 0) 494 if (selectedCommand != 0)
410 menu.CheckRadioItem(kMenuID_Time, last, selectedCommand, MF_BYCOMMAND); 495 menu.CheckRadioItem(k_MenuID_Time, last, selectedCommand, MF_BYCOMMAND);
411 } 496 }
412 } 497 }
413 } 498 }
414 else if (position == kMenuIndex_Bookmarks) 499 else if (position == k_MenuIndex_Bookmarks)
415 { 500 {
416 CMenu menu; 501 CMenu menu;
417 menu.Attach(hMenu); 502 menu.Attach(hMenu);
@@ -419,17 +504,17 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
419 CMenu subMenu; 504 CMenu subMenu;
420 subMenu.Attach(menu.GetSubMenu(0)); 505 subMenu.Attach(menu.GetSubMenu(0));
421 subMenu.RemoveAllItems(); 506 subMenu.RemoveAllItems();
422 int i; 507 unsigned i;
423 508
424 for (i = 0; i < 10; i++) 509 for (i = 0; i < 10; i++)
425 { 510 {
426 UString s = LangString(IDS_BOOKMARK); 511 UString s = LangString(IDS_BOOKMARK);
427 s.Add_Space(); 512 s.Add_Space();
428 char c = (char)(L'0' + i); 513 const char c = (char)(L'0' + i);
429 s += c; 514 s += c;
430 s += "\tAlt+Shift+"; 515 s += "\tAlt+Shift+";
431 s += c; 516 s += c;
432 subMenu.AppendItem(MF_STRING, kSetBookmarkMenuID + i, s); 517 subMenu.AppendItem(MF_STRING, k_MenuID_SetBookmark + i, s);
433 } 518 }
434 519
435 menu.RemoveAllItemsFrom(2); 520 menu.RemoveAllItemsFrom(2);
@@ -448,7 +533,7 @@ void OnMenuActivating(HWND /* hWnd */, HMENU hMenu, int position)
448 s = '-'; 533 s = '-';
449 s += "\tAlt+"; 534 s += "\tAlt+";
450 s += (char)('0' + i); 535 s += (char)('0' + i);
451 menu.AppendItem(MF_STRING, kOpenBookmarkMenuID + i, s); 536 menu.AppendItem(MF_STRING, k_MenuID_OpenBookmark + i, s);
452 } 537 }
453 } 538 }
454} 539}
@@ -596,7 +681,7 @@ void CFileMenu::Load(HMENU hMenu, unsigned startPos)
596 NFile::NFind::CFileInfo fi; 681 NFile::NFind::CFileInfo fi;
597 if (fi.Find(FilePath) && fi.Size < ((UInt32)1 << 31) && !fi.IsDir()) 682 if (fi.Find(FilePath) && fi.Size < ((UInt32)1 << 31) && !fi.IsDir())
598 { 683 {
599 for (unsigned k = 0; k < ARRAY_SIZE(g_Zvc_IDs); k++) 684 for (unsigned k = 0; k < Z7_ARRAY_SIZE(g_Zvc_IDs); k++)
600 { 685 {
601 const unsigned id = g_Zvc_IDs[k]; 686 const unsigned id = g_Zvc_IDs[k];
602 if (fi.IsReadOnly()) 687 if (fi.IsReadOnly())
@@ -756,7 +841,7 @@ bool OnMenuCommand(HWND hWnd, unsigned id)
756 g_App.SetListViewMode(index); 841 g_App.SetListViewMode(index);
757 /* 842 /*
758 CMenu menu; 843 CMenu menu;
759 menu.Attach(::GetSubMenu(::GetMenu(hWnd), kMenuIndex_View)); 844 menu.Attach(::GetSubMenu(::GetMenu(hWnd), k_MenuIndex_View));
760 menu.CheckRadioItem(IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS, 845 menu.CheckRadioItem(IDM_VIEW_LARGE_ICONS, IDM_VIEW_DETAILS,
761 id, MF_BYCOMMAND); 846 id, MF_BYCOMMAND);
762 */ 847 */
@@ -811,20 +896,19 @@ bool OnMenuCommand(HWND hWnd, unsigned id)
811 } 896 }
812 default: 897 default:
813 { 898 {
814 if (id >= kOpenBookmarkMenuID && id <= kOpenBookmarkMenuID + 9) 899 if (id >= k_MenuID_OpenBookmark && id <= k_MenuID_OpenBookmark + 9)
815 { 900 {
816 g_App.OpenBookmark(id - kOpenBookmarkMenuID); 901 g_App.OpenBookmark(id - k_MenuID_OpenBookmark);
817 return true; 902 return true;
818 } 903 }
819 else if (id >= kSetBookmarkMenuID && id <= kSetBookmarkMenuID + 9) 904 else if (id >= k_MenuID_SetBookmark && id <= k_MenuID_SetBookmark + 9)
820 { 905 {
821 g_App.SetBookmark(id - kSetBookmarkMenuID); 906 g_App.SetBookmark(id - k_MenuID_SetBookmark);
822 return true; 907 return true;
823 } 908 }
824 else if (id >= kMenuID_Time && (unsigned)id <= kMenuID_Time + g_App._timestampLevels.Size()) 909 else if (id >= k_MenuID_Time && (unsigned)id < k_MenuID_Time + g_App._timestampLevels.Size())
825 { 910 {
826 unsigned index = id - kMenuID_Time; 911 g_App.SetTimestampLevel(g_App._timestampLevels[id - k_MenuID_Time]);
827 g_App.SetTimestampLevel(g_App._timestampLevels[index]);
828 return true; 912 return true;
829 } 913 }
830 return false; 914 return false;
diff --git a/CPP/7zip/UI/FileManager/MyLoadMenu.h b/CPP/7zip/UI/FileManager/MyLoadMenu.h
index 764bf7c..e71dbbf 100644
--- a/CPP/7zip/UI/FileManager/MyLoadMenu.h
+++ b/CPP/7zip/UI/FileManager/MyLoadMenu.h
@@ -1,14 +1,14 @@
1// MyLoadMenu.h 1// MyLoadMenu.h
2 2
3#ifndef __MY_LOAD_MENU_H 3#ifndef ZIP7_INC_MY_LOAD_MENU_H
4#define __MY_LOAD_MENU_H 4#define ZIP7_INC_MY_LOAD_MENU_H
5 5
6void OnMenuActivating(HWND hWnd, HMENU hMenu, int position); 6void OnMenuActivating(HWND hWnd, HMENU hMenu, int position);
7// void OnMenuUnActivating(HWND hWnd, HMENU hMenu, int id); 7// void OnMenuUnActivating(HWND hWnd, HMENU hMenu, int id);
8// void OnMenuUnActivating(HWND hWnd); 8// void OnMenuUnActivating(HWND hWnd);
9 9
10bool OnMenuCommand(HWND hWnd, unsigned id); 10bool OnMenuCommand(HWND hWnd, unsigned id);
11void MyLoadMenu(); 11void MyLoadMenu(bool needResetMenu);
12 12
13struct CFileMenu 13struct CFileMenu
14{ 14{
@@ -18,7 +18,7 @@ struct CFileMenu
18 bool isFsFolder; 18 bool isFsFolder;
19 bool allAreFiles; 19 bool allAreFiles;
20 bool isAltStreamsSupported; 20 bool isAltStreamsSupported;
21 int numItems; 21 unsigned numItems;
22 22
23 FString FilePath; 23 FString FilePath;
24 24
diff --git a/CPP/7zip/UI/FileManager/MyWindowsNew.h b/CPP/7zip/UI/FileManager/MyWindowsNew.h
index 48a9535..325babc 100644
--- a/CPP/7zip/UI/FileManager/MyWindowsNew.h
+++ b/CPP/7zip/UI/FileManager/MyWindowsNew.h
@@ -1,11 +1,54 @@
1// MyWindowsNew.h 1// MyWindowsNew.h
2 2
3#ifndef __MY_WINDOWS_NEW_H 3#ifndef ZIP7_INC_MY_WINDOWS_NEW_H
4#define __MY_WINDOWS_NEW_H 4#define ZIP7_INC_MY_WINDOWS_NEW_H
5 5
6#ifdef _MSC_VER 6#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__MINGW32_VERSION)
7#include <shobjidl.h>
7 8
9#if defined(__MINGW32_VERSION) && !defined(__ITaskbarList3_INTERFACE_DEFINED__)
10// for old mingw
11extern "C" {
12DEFINE_GUID(IID_ITaskbarList3, 0xEA1AFB91, 0x9E28, 0x4B86, 0x90, 0xE9, 0x9E, 0x9F, 0x8A, 0x5E, 0xEF, 0xAF);
13DEFINE_GUID(CLSID_TaskbarList, 0x56fdf344, 0xfd6d, 0x11d0, 0x95,0x8a, 0x00,0x60,0x97,0xc9,0xa0,0x90);
14}
15#endif
16
17#else // is not __MINGW*
18
19#ifndef Z7_OLD_WIN_SDK
8#include <ShObjIdl.h> 20#include <ShObjIdl.h>
21#else
22
23#ifndef HIMAGELIST
24struct _IMAGELIST;
25typedef struct _IMAGELIST* HIMAGELIST;
26#endif
27
28#ifndef __ITaskbarList_INTERFACE_DEFINED__
29#define __ITaskbarList_INTERFACE_DEFINED__
30DEFINE_GUID(IID_ITaskbarList, 0x56FDF342, 0xFD6D, 0x11d0, 0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90);
31struct ITaskbarList: public IUnknown
32{
33 STDMETHOD(HrInit)(void) = 0;
34 STDMETHOD(AddTab)(HWND hwnd) = 0;
35 STDMETHOD(DeleteTab)(HWND hwnd) = 0;
36 STDMETHOD(ActivateTab)(HWND hwnd) = 0;
37 STDMETHOD(SetActiveAlt)(HWND hwnd) = 0;
38};
39#endif // __ITaskbarList_INTERFACE_DEFINED__
40
41#ifndef __ITaskbarList2_INTERFACE_DEFINED__
42#define __ITaskbarList2_INTERFACE_DEFINED__
43DEFINE_GUID(IID_ITaskbarList2, 0x602D4995, 0xB13A, 0x429b, 0xA6, 0x6E, 0x19, 0x35, 0xE4, 0x4F, 0x43, 0x17);
44struct ITaskbarList2: public ITaskbarList
45{
46 STDMETHOD(MarkFullscreenWindow)(HWND hwnd, BOOL fFullscreen) = 0;
47};
48#endif // __ITaskbarList2_INTERFACE_DEFINED__
49
50#endif // Z7_OLD_WIN_SDK
51
9 52
10#ifndef __ITaskbarList3_INTERFACE_DEFINED__ 53#ifndef __ITaskbarList3_INTERFACE_DEFINED__
11#define __ITaskbarList3_INTERFACE_DEFINED__ 54#define __ITaskbarList3_INTERFACE_DEFINED__
@@ -69,8 +112,8 @@ struct ITaskbarList3: public ITaskbarList2
69 STDMETHOD(SetThumbnailClip)(HWND hwnd, RECT *prcClip) = 0; 112 STDMETHOD(SetThumbnailClip)(HWND hwnd, RECT *prcClip) = 0;
70}; 113};
71 114
72#endif 115#endif // __ITaskbarList3_INTERFACE_DEFINED__
73 116
74#endif 117#endif // __MINGW*
75 118
76#endif 119#endif
diff --git a/CPP/7zip/UI/FileManager/NetFolder.cpp b/CPP/7zip/UI/FileManager/NetFolder.cpp
index a941e73..879f1db 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)
55 UString systemPathPart; 55 UString systemPathPart;
56 DWORD result = GetResourceInformation(resource, destResource, systemPathPart); 56 DWORD result = GetResourceInformation(resource, destResource, systemPathPart);
57 if (result == NO_ERROR) 57 if (result == NO_ERROR)
58 Init(&destResource, 0, path); 58 Init(&destResource, NULL, path);
59 else 59 else
60 Init(0, 0 , L""); 60 Init(NULL, NULL , L"");
61 return; 61 return;
62} 62}
63 63
@@ -65,8 +65,8 @@ void CNetFolder::Init(const NWindows::NNet::CResourceW *netResource,
65 IFolderFolder *parentFolder, const UString &path) 65 IFolderFolder *parentFolder, const UString &path)
66{ 66{
67 _path = path; 67 _path = path;
68 if (netResource == 0) 68 if (!netResource)
69 _netResourcePointer = 0; 69 _netResourcePointer = NULL;
70 else 70 else
71 { 71 {
72 _netResource = *netResource; 72 _netResource = *netResource;
@@ -86,7 +86,7 @@ void CNetFolder::Init(const NWindows::NNet::CResourceW *netResource,
86 _parentFolder = parentFolder; 86 _parentFolder = parentFolder;
87} 87}
88 88
89STDMETHODIMP CNetFolder::LoadItems() 89Z7_COM7F_IMF(CNetFolder::LoadItems())
90{ 90{
91 _items.Clear(); 91 _items.Clear();
92 CEnum enumerator; 92 CEnum enumerator;
@@ -102,35 +102,35 @@ STDMETHODIMP CNetFolder::LoadItems()
102 if (result == NO_ERROR) 102 if (result == NO_ERROR)
103 break; 103 break;
104 if (result != ERROR_ACCESS_DENIED) 104 if (result != ERROR_ACCESS_DENIED)
105 return result; 105 return HRESULT_FROM_WIN32(result);
106 if (_netResourcePointer != 0) 106 if (_netResourcePointer)
107 result = AddConnection2(_netResource, 107 result = AddConnection2(_netResource,
108 0, 0, CONNECT_INTERACTIVE); 108 NULL, NULL, CONNECT_INTERACTIVE);
109 if (result != NO_ERROR) 109 if (result != NO_ERROR)
110 return result; 110 return HRESULT_FROM_WIN32(result);
111 } 111 }
112 112
113 for (;;) 113 for (;;)
114 { 114 {
115 CResourceEx resource; 115 CResourceEx resource;
116 DWORD result = enumerator.Next(resource); 116 const DWORD result = enumerator.Next(resource);
117 if (result == NO_ERROR) 117 if (result == NO_ERROR)
118 { 118 {
119 if (!resource.RemoteNameIsDefined) // For Win 98, I don't know what's wrong 119 if (!resource.RemoteNameIsDefined) // For Win 98, I don't know what's wrong
120 resource.RemoteName = resource.Comment; 120 resource.RemoteName = resource.Comment;
121 resource.Name = resource.RemoteName; 121 resource.Name = resource.RemoteName;
122 int pos = resource.Name.ReverseFind_PathSepar(); 122 const int pos = resource.Name.ReverseFind_PathSepar();
123 if (pos >= 0) 123 if (pos >= 0)
124 { 124 {
125 // _path = resource.Name.Left(pos + 1); 125 // _path = resource.Name.Left(pos + 1);
126 resource.Name.DeleteFrontal(pos + 1); 126 resource.Name.DeleteFrontal((unsigned)pos + 1);
127 } 127 }
128 _items.Add(resource); 128 _items.Add(resource);
129 } 129 }
130 else if (result == ERROR_NO_MORE_ITEMS) 130 else if (result == ERROR_NO_MORE_ITEMS)
131 break; 131 break;
132 else 132 else
133 return result; 133 return HRESULT_FROM_WIN32(result);
134 } 134 }
135 135
136 /* 136 /*
@@ -160,13 +160,13 @@ STDMETHODIMP CNetFolder::LoadItems()
160} 160}
161 161
162 162
163STDMETHODIMP CNetFolder::GetNumberOfItems(UInt32 *numItems) 163Z7_COM7F_IMF(CNetFolder::GetNumberOfItems(UInt32 *numItems))
164{ 164{
165 *numItems = _items.Size(); 165 *numItems = _items.Size();
166 return S_OK; 166 return S_OK;
167} 167}
168 168
169STDMETHODIMP CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) 169Z7_COM7F_IMF(CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value))
170{ 170{
171 NCOM::CPropVariant prop; 171 NCOM::CPropVariant prop;
172 const CResourceEx &item = _items[itemIndex]; 172 const CResourceEx &item = _items[itemIndex];
@@ -185,16 +185,16 @@ STDMETHODIMP CNetFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIAN
185 return S_OK; 185 return S_OK;
186} 186}
187 187
188STDMETHODIMP CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 188Z7_COM7F_IMF(CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder))
189{ 189{
190 *resultFolder = 0; 190 *resultFolder = NULL;
191 const CResourceEx &resource = _items[index]; 191 const CResourceEx &resource = _items[index];
192 if (resource.Usage == RESOURCEUSAGE_CONNECTABLE || 192 if (resource.Usage == RESOURCEUSAGE_CONNECTABLE ||
193 resource.DisplayType == RESOURCEDISPLAYTYPE_SHARE) 193 resource.DisplayType == RESOURCEDISPLAYTYPE_SHARE)
194 { 194 {
195 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; 195 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder;
196 CMyComPtr<IFolderFolder> subFolder = fsFolderSpec; 196 CMyComPtr<IFolderFolder> subFolder = fsFolderSpec;
197 RINOK(fsFolderSpec->Init(us2fs(resource.RemoteName + WCHAR_PATH_SEPARATOR))); // , this 197 RINOK(fsFolderSpec->Init(us2fs(resource.RemoteName + WCHAR_PATH_SEPARATOR))) // , this
198 *resultFolder = subFolder.Detach(); 198 *resultFolder = subFolder.Detach();
199 } 199 }
200 else 200 else
@@ -207,32 +207,32 @@ STDMETHODIMP CNetFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder
207 return S_OK; 207 return S_OK;
208} 208}
209 209
210STDMETHODIMP CNetFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder ** /* resultFolder */) 210Z7_COM7F_IMF(CNetFolder::BindToFolder(const wchar_t * /* name */, IFolderFolder ** /* resultFolder */))
211{ 211{
212 return E_NOTIMPL; 212 return E_NOTIMPL;
213} 213}
214 214
215STDMETHODIMP CNetFolder::BindToParentFolder(IFolderFolder **resultFolder) 215Z7_COM7F_IMF(CNetFolder::BindToParentFolder(IFolderFolder **resultFolder))
216{ 216{
217 *resultFolder = 0; 217 *resultFolder = NULL;
218 if (_parentFolder) 218 if (_parentFolder)
219 { 219 {
220 CMyComPtr<IFolderFolder> parentFolder = _parentFolder; 220 CMyComPtr<IFolderFolder> parentFolder = _parentFolder;
221 *resultFolder = parentFolder.Detach(); 221 *resultFolder = parentFolder.Detach();
222 return S_OK; 222 return S_OK;
223 } 223 }
224 if (_netResourcePointer != 0) 224 if (_netResourcePointer)
225 { 225 {
226 CResourceW resourceParent; 226 CResourceW resourceParent;
227 DWORD result = GetResourceParent(_netResource, resourceParent); 227 const DWORD result = GetResourceParent(_netResource, resourceParent);
228 if (result != NO_ERROR) 228 if (result != NO_ERROR)
229 return result; 229 return HRESULT_FROM_WIN32(result);
230 if (!_netResource.RemoteNameIsDefined) 230 if (!_netResource.RemoteNameIsDefined)
231 return S_OK; 231 return S_OK;
232 232
233 CNetFolder *netFolder = new CNetFolder; 233 CNetFolder *netFolder = new CNetFolder;
234 CMyComPtr<IFolderFolder> subFolder = netFolder; 234 CMyComPtr<IFolderFolder> subFolder = netFolder;
235 netFolder->Init(&resourceParent, 0, WSTRING_PATH_SEPARATOR); 235 netFolder->Init(&resourceParent, NULL, WSTRING_PATH_SEPARATOR);
236 *resultFolder = subFolder.Detach(); 236 *resultFolder = subFolder.Detach();
237 } 237 }
238 return S_OK; 238 return S_OK;
@@ -240,7 +240,7 @@ STDMETHODIMP CNetFolder::BindToParentFolder(IFolderFolder **resultFolder)
240 240
241IMP_IFolderFolder_Props(CNetFolder) 241IMP_IFolderFolder_Props(CNetFolder)
242 242
243STDMETHODIMP CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 243Z7_COM7F_IMF(CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value))
244{ 244{
245 NWindows::NCOM::CPropVariant prop; 245 NWindows::NCOM::CPropVariant prop;
246 switch (propID) 246 switch (propID)
@@ -252,7 +252,7 @@ STDMETHODIMP CNetFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)
252 return S_OK; 252 return S_OK;
253} 253}
254 254
255STDMETHODIMP CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) 255Z7_COM7F_IMF(CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
256{ 256{
257 if (index >= (UInt32)_items.Size()) 257 if (index >= (UInt32)_items.Size())
258 return E_INVALIDARG; 258 return E_INVALIDARG;
@@ -277,5 +277,5 @@ STDMETHODIMP CNetFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex)
277 } 277 }
278 // *anIconIndex = GetRealIconIndex(0, L"\\\\HOME"); 278 // *anIconIndex = GetRealIconIndex(0, L"\\\\HOME");
279 } 279 }
280 return GetLastError(); 280 return GetLastError_noZero_HRESULT();
281} 281}
diff --git a/CPP/7zip/UI/FileManager/NetFolder.h b/CPP/7zip/UI/FileManager/NetFolder.h
index 151dd09..352f5bd 100644
--- a/CPP/7zip/UI/FileManager/NetFolder.h
+++ b/CPP/7zip/UI/FileManager/NetFolder.h
@@ -1,7 +1,7 @@
1// NetFolder.h 1// NetFolder.h
2 2
3#ifndef __NET_FOLDER_H 3#ifndef ZIP7_INC_NET_FOLDER_H
4#define __NET_FOLDER_H 4#define ZIP7_INC_NET_FOLDER_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -14,11 +14,11 @@ struct CResourceEx: public NWindows::NNet::CResourceW
14 UString Name; 14 UString Name;
15}; 15};
16 16
17class CNetFolder: 17Z7_CLASS_IMP_NOQIB_2(
18 public IFolderFolder, 18 CNetFolder
19 public IFolderGetSystemIconIndex, 19 , IFolderFolder
20 public CMyUnknownImp 20 , IFolderGetSystemIconIndex
21{ 21)
22 NWindows::NNet::CResourceW _netResource; 22 NWindows::NNet::CResourceW _netResource;
23 NWindows::NNet::CResourceW *_netResourcePointer; 23 NWindows::NNet::CResourceW *_netResourcePointer;
24 24
@@ -27,11 +27,7 @@ class CNetFolder:
27 CMyComPtr<IFolderFolder> _parentFolder; 27 CMyComPtr<IFolderFolder> _parentFolder;
28 UString _path; 28 UString _path;
29public: 29public:
30 MY_UNKNOWN_IMP1(IFolderGetSystemIconIndex) 30 CNetFolder(): _netResourcePointer(NULL) {}
31 INTERFACE_FolderFolder(;)
32 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex);
33
34 CNetFolder(): _netResourcePointer(0) {}
35 void Init(const UString &path); 31 void Init(const UString &path);
36 void Init(const NWindows::NNet::CResourceW *netResource, 32 void Init(const NWindows::NNet::CResourceW *netResource,
37 IFolderFolder *parentFolder, const UString &path); 33 IFolderFolder *parentFolder, const UString &path);
diff --git a/CPP/7zip/UI/FileManager/OpenCallback.cpp b/CPP/7zip/UI/FileManager/OpenCallback.cpp
index e2e03f5..5b6df50 100644
--- a/CPP/7zip/UI/FileManager/OpenCallback.cpp
+++ b/CPP/7zip/UI/FileManager/OpenCallback.cpp
@@ -17,9 +17,11 @@
17 17
18using namespace NWindows; 18using namespace NWindows;
19 19
20STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes) 20HRESULT COpenArchiveCallback::Open_SetTotal(const UInt64 *numFiles, const UInt64 *numBytes)
21// Z7_COM7F_IMF(COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64 *numBytes))
21{ 22{
22 RINOK(ProgressDialog.Sync.CheckStop()); 23 // COM_TRY_BEGIN
24 RINOK(ProgressDialog.Sync.CheckStop())
23 { 25 {
24 // NSynchronization::CCriticalSectionLock lock(_criticalSection); 26 // NSynchronization::CCriticalSectionLock lock(_criticalSection);
25 ProgressDialog.Sync.Set_NumFilesTotal(numFiles ? *numFiles : (UInt64)(Int64)-1); 27 ProgressDialog.Sync.Set_NumFilesTotal(numFiles ? *numFiles : (UInt64)(Int64)-1);
@@ -31,83 +33,37 @@ STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 *numFiles, const UInt64
31 ProgressDialog.Sync.Set_NumBytesTotal(*numBytes); 33 ProgressDialog.Sync.Set_NumBytesTotal(*numBytes);
32 } 34 }
33 return S_OK; 35 return S_OK;
36 // COM_TRY_END
34} 37}
35 38
36STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes) 39HRESULT COpenArchiveCallback::Open_SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes)
40// Z7_COM7F_IMF(COpenArchiveCallback::SetCompleted(const UInt64 *numFiles, const UInt64 *numBytes))
37{ 41{
42 // COM_TRY_BEGIN
38 // NSynchronization::CCriticalSectionLock lock(_criticalSection); 43 // NSynchronization::CCriticalSectionLock lock(_criticalSection);
39 if (numFiles) 44 if (numFiles)
40 ProgressDialog.Sync.Set_NumFilesCur(*numFiles); 45 ProgressDialog.Sync.Set_NumFilesCur(*numFiles);
41 if (numBytes) 46 if (numBytes)
42 ProgressDialog.Sync.Set_NumBytesCur(*numBytes); 47 ProgressDialog.Sync.Set_NumBytesCur(*numBytes);
43 return ProgressDialog.Sync.CheckStop(); 48 return ProgressDialog.Sync.CheckStop();
49 // COM_TRY_END
44} 50}
45 51
46STDMETHODIMP COpenArchiveCallback::SetTotal(const UInt64 total) 52HRESULT COpenArchiveCallback::Open_CheckBreak()
47{ 53{
48 RINOK(ProgressDialog.Sync.CheckStop()); 54 return ProgressDialog.Sync.CheckStop();
49 ProgressDialog.Sync.Set_NumBytesTotal(total);
50 return S_OK;
51}
52
53STDMETHODIMP COpenArchiveCallback::SetCompleted(const UInt64 *completed)
54{
55 return ProgressDialog.Sync.Set_NumBytesCur(completed);
56}
57
58STDMETHODIMP COpenArchiveCallback::GetProperty(PROPID propID, PROPVARIANT *value)
59{
60 NCOM::CPropVariant prop;
61 if (_subArchiveMode)
62 {
63 switch (propID)
64 {
65 case kpidName: prop = _subArchiveName; break;
66 }
67 }
68 else
69 {
70 switch (propID)
71 {
72 case kpidName: prop = fs2us(_fileInfo.Name); break;
73 case kpidIsDir: prop = _fileInfo.IsDir(); break;
74 case kpidSize: prop = _fileInfo.Size; break;
75 case kpidAttrib: prop = (UInt32)_fileInfo.Attrib; break;
76 case kpidCTime: prop = _fileInfo.CTime; break;
77 case kpidATime: prop = _fileInfo.ATime; break;
78 case kpidMTime: prop = _fileInfo.MTime; break;
79 }
80 }
81 prop.Detach(value);
82 return S_OK;
83} 55}
84 56
85STDMETHODIMP COpenArchiveCallback::GetStream(const wchar_t *name, IInStream **inStream) 57HRESULT COpenArchiveCallback::Open_Finished()
86{ 58{
87 COM_TRY_BEGIN 59 return ProgressDialog.Sync.CheckStop();
88 *inStream = NULL;
89 if (_subArchiveMode)
90 return S_FALSE;
91
92 FString fullPath;
93 if (!NFile::NName::GetFullPath(_folderPrefix, us2fs(name), fullPath))
94 return S_FALSE;
95 if (!_fileInfo.Find_FollowLink(fullPath))
96 return S_FALSE;
97 if (_fileInfo.IsDir())
98 return S_FALSE;
99 CInFileStream *inFile = new CInFileStream;
100 CMyComPtr<IInStream> inStreamTemp = inFile;
101 if (!inFile->Open(fullPath))
102 return ::GetLastError();
103 *inStream = inStreamTemp.Detach();
104 return S_OK;
105 COM_TRY_END
106} 60}
107 61
108STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password) 62#ifndef Z7_NO_CRYPTO
63HRESULT COpenArchiveCallback::Open_CryptoGetTextPassword(BSTR *password)
64// Z7_COM7F_IMF(COpenArchiveCallback::CryptoGetTextPassword(BSTR *password))
109{ 65{
110 COM_TRY_BEGIN 66 // COM_TRY_BEGIN
111 PasswordWasAsked = true; 67 PasswordWasAsked = true;
112 if (!PasswordIsDefined) 68 if (!PasswordIsDefined)
113 { 69 {
@@ -125,5 +81,6 @@ STDMETHODIMP COpenArchiveCallback::CryptoGetTextPassword(BSTR *password)
125 NExtract::Save_ShowPassword(dialog.ShowPassword); 81 NExtract::Save_ShowPassword(dialog.ShowPassword);
126 } 82 }
127 return StringToBstr(Password, password); 83 return StringToBstr(Password, password);
128 COM_TRY_END 84 // COM_TRY_END
129} 85}
86#endif
diff --git a/CPP/7zip/UI/FileManager/OpenCallback.h b/CPP/7zip/UI/FileManager/OpenCallback.h
index 9aa5d43..8f4638c 100644
--- a/CPP/7zip/UI/FileManager/OpenCallback.h
+++ b/CPP/7zip/UI/FileManager/OpenCallback.h
@@ -1,37 +1,28 @@
1// OpenCallback.h 1// OpenCallback.h
2 2
3#ifndef __OPEN_CALLBACK_H 3#ifndef ZIP7_INC_OPEN_CALLBACK_H
4#define __OPEN_CALLBACK_H 4#define ZIP7_INC_OPEN_CALLBACK_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../Common/ArchiveOpenCallback.h"
7 7
8#include "../../../Windows/FileFind.h" 8#ifdef Z7_SFX
9
10#include "../../IPassword.h"
11
12#include "../../Archive/IArchive.h"
13
14#ifdef _SFX
15#include "ProgressDialog.h" 9#include "ProgressDialog.h"
16#else 10#else
17#include "ProgressDialog2.h" 11#include "ProgressDialog2.h"
18#endif 12#endif
19 13
14/* we can use IArchiveOpenCallback or IOpenCallbackUI here */
20 15
21class COpenArchiveCallback: 16class COpenArchiveCallback Z7_final:
17 /*
22 public IArchiveOpenCallback, 18 public IArchiveOpenCallback,
23 public IArchiveOpenVolumeCallback,
24 public IArchiveOpenSetSubArchiveName,
25 public IProgress, 19 public IProgress,
26 public ICryptoGetTextPassword, 20 public ICryptoGetTextPassword,
27 public CMyUnknownImp 21 public CMyUnknownImp
22 */
23 public IOpenCallbackUI
28{ 24{
29 FString _folderPrefix;
30 NWindows::NFile::NFind::CFileInfo _fileInfo;
31 // NWindows::NSynchronization::CCriticalSection _criticalSection; 25 // NWindows::NSynchronization::CCriticalSection _criticalSection;
32 bool _subArchiveMode;
33 UString _subArchiveName;
34
35public: 26public:
36 bool PasswordIsDefined; 27 bool PasswordIsDefined;
37 bool PasswordWasAsked; 28 bool PasswordWasAsked;
@@ -39,31 +30,25 @@ public:
39 HWND ParentWindow; 30 HWND ParentWindow;
40 CProgressDialog ProgressDialog; 31 CProgressDialog ProgressDialog;
41 32
42 MY_UNKNOWN_IMP5( 33 /*
43 IArchiveOpenCallback, 34 Z7_COM_UNKNOWN_IMP_3(
44 IArchiveOpenVolumeCallback, 35 IArchiveOpenVolumeCallback,
45 IArchiveOpenSetSubArchiveName, 36 IProgress
46 IProgress, 37 ICryptoGetTextPassword
47 ICryptoGetTextPassword) 38 )
48
49 INTERFACE_IProgress(;)
50 INTERFACE_IArchiveOpenCallback(;)
51 INTERFACE_IArchiveOpenVolumeCallback(;)
52 39
40 Z7_IFACE_COM7_IMP(IProgress)
41 Z7_IFACE_COM7_IMP(IArchiveOpenCallback)
53 // ICryptoGetTextPassword 42 // ICryptoGetTextPassword
54 STDMETHOD(CryptoGetTextPassword)(BSTR *password); 43 Z7_COM7F_IMP(CryptoGetTextPassword(BSTR *password))
44 */
55 45
56 STDMETHOD(SetSubArchiveName(const wchar_t *name)) 46 Z7_IFACE_IMP(IOpenCallbackUI)
57 {
58 _subArchiveMode = true;
59 _subArchiveName = name;
60 return S_OK;
61 }
62 47
63 COpenArchiveCallback(): 48 COpenArchiveCallback():
64 ParentWindow(0) 49 ParentWindow(NULL)
65 { 50 {
66 _subArchiveMode = false; 51 // _subArchiveMode = false;
67 PasswordIsDefined = false; 52 PasswordIsDefined = false;
68 PasswordWasAsked = false; 53 PasswordWasAsked = false;
69 } 54 }
@@ -75,18 +60,6 @@ public:
75 } 60 }
76 */ 61 */
77 62
78 HRESULT LoadFileInfo2(const FString &folderPrefix, const FString &fileName)
79 {
80 _folderPrefix = folderPrefix;
81 if (!_fileInfo.Find_FollowLink(_folderPrefix + fileName))
82 {
83 return GetLastError_noZero_HRESULT();
84 }
85 return S_OK;
86 }
87
88 void ShowMessage(const UInt64 *completed);
89
90 INT_PTR StartProgressDialog(const UString &title, NWindows::CThread &thread) 63 INT_PTR StartProgressDialog(const UString &title, NWindows::CThread &thread)
91 { 64 {
92 return ProgressDialog.Create(title, thread, ParentWindow); 65 return ProgressDialog.Create(title, thread, ParentWindow);
diff --git a/CPP/7zip/UI/FileManager/OptionsDialog.cpp b/CPP/7zip/UI/FileManager/OptionsDialog.cpp
index c42e0f8..b71c323 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 */)
51 51
52 NControl::CPropertyPage *pagePointers[] = { &systemPage, &menuPage, &foldersPage, &editPage, &settingsPage, &langPage }; 52 NControl::CPropertyPage *pagePointers[] = { &systemPage, &menuPage, &foldersPage, &editPage, &settingsPage, &langPage };
53 53
54 for (unsigned i = 0; i < ARRAY_SIZE(pageIDs); i++) 54 for (unsigned i = 0; i < Z7_ARRAY_SIZE(pageIDs); i++)
55 { 55 {
56 NControl::CPageInfo &page = pages.AddNew(); 56 NControl::CPageInfo &page = pages.AddNew();
57 page.ID = pageIDs[i]; 57 page.ID = pageIDs[i];
58 #ifdef Z7_LANG
58 LangString_OnlyFromLangFile(page.ID, page.Title); 59 LangString_OnlyFromLangFile(page.ID, page.Title);
60 #endif
59 page.Page = pagePointers[i]; 61 page.Page = pagePointers[i];
60 } 62 }
61 63
62 INT_PTR res = NControl::MyPropertySheet(pages, hwndOwner, LangString(IDS_OPTIONS)); 64 const INT_PTR res = NControl::MyPropertySheet(pages, hwndOwner, LangString(IDS_OPTIONS));
63 65
64 if (res != -1 && res != 0) 66 if (res != -1 && res != 0)
65 { 67 {
66 if (langPage.LangWasChanged) 68 if (langPage.LangWasChanged)
67 { 69 {
68 // g_App._window.SetText(LangString(IDS_APP_TITLE, 0x03000000)); 70 // g_App._window.SetText(LangString(IDS_APP_TITLE, 0x03000000));
69 MyLoadMenu(); 71 MyLoadMenu(true); // needResetMenu
70 g_App.ReloadToolbars(); 72 g_App.ReloadToolbars();
71 g_App.MoveSubWindows(); // we need it to change list window aafter _toolBar.AutoSize(); 73 g_App.MoveSubWindows(); // we need it to change list window aafter _toolBar.AutoSize();
72 g_App.ReloadLang(); 74 g_App.ReloadLangItems();
73 } 75 }
74 76
75 /* 77 /*
diff --git a/CPP/7zip/UI/FileManager/OverwriteDialog.cpp b/CPP/7zip/UI/FileManager/OverwriteDialog.cpp
index b455b14..096527c 100644
--- a/CPP/7zip/UI/FileManager/OverwriteDialog.cpp
+++ b/CPP/7zip/UI/FileManager/OverwriteDialog.cpp
@@ -17,7 +17,7 @@
17 17
18using namespace NWindows; 18using namespace NWindows;
19 19
20#ifdef LANG 20#ifdef Z7_LANG
21static const UInt32 kLangIDs[] = 21static const UInt32 kLangIDs[] =
22{ 22{
23 IDT_OVERWRITE_HEADER, 23 IDT_OVERWRITE_HEADER,
@@ -48,7 +48,7 @@ void COverwriteDialog::ReduceString(UString &s)
48 } 48 }
49} 49}
50 50
51void COverwriteDialog::SetFileInfoControl(int textID, int iconID, 51void COverwriteDialog::SetFileInfoControl(unsigned textID, unsigned iconID,
52 const NOverwriteDialog::CFileInfo &fileInfo) 52 const NOverwriteDialog::CFileInfo &fileInfo)
53{ 53{
54 UString sizeString; 54 UString sizeString;
@@ -96,9 +96,9 @@ void COverwriteDialog::SetFileInfoControl(int textID, int iconID,
96 96
97bool COverwriteDialog::OnInit() 97bool COverwriteDialog::OnInit()
98{ 98{
99 #ifdef LANG 99 #ifdef Z7_LANG
100 LangSetWindowText(*this, IDD_OVERWRITE); 100 LangSetWindowText(*this, IDD_OVERWRITE);
101 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 101 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
102 #endif 102 #endif
103 SetFileInfoControl(IDT_OVERWRITE_OLD_FILE_SIZE_TIME, IDI_OVERWRITE_OLD_FILE, OldFileInfo); 103 SetFileInfoControl(IDT_OVERWRITE_OLD_FILE_SIZE_TIME, IDI_OVERWRITE_OLD_FILE, OldFileInfo);
104 SetFileInfoControl(IDT_OVERWRITE_NEW_FILE_SIZE_TIME, IDI_OVERWRITE_NEW_FILE, NewFileInfo); 104 SetFileInfoControl(IDT_OVERWRITE_NEW_FILE_SIZE_TIME, IDI_OVERWRITE_NEW_FILE, NewFileInfo);
@@ -122,7 +122,7 @@ bool COverwriteDialog::OnInit()
122 return CModalDialog::OnInit(); 122 return CModalDialog::OnInit();
123} 123}
124 124
125bool COverwriteDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 125bool COverwriteDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
126{ 126{
127 switch (buttonID) 127 switch (buttonID)
128 { 128 {
@@ -131,7 +131,7 @@ bool COverwriteDialog::OnButtonClicked(int buttonID, HWND buttonHWND)
131 case IDB_YES_TO_ALL: 131 case IDB_YES_TO_ALL:
132 case IDB_NO_TO_ALL: 132 case IDB_NO_TO_ALL:
133 case IDB_AUTO_RENAME: 133 case IDB_AUTO_RENAME:
134 End(buttonID); 134 End((INT_PTR)buttonID);
135 return true; 135 return true;
136 } 136 }
137 return CModalDialog::OnButtonClicked(buttonID, buttonHWND); 137 return CModalDialog::OnButtonClicked(buttonID, buttonHWND);
diff --git a/CPP/7zip/UI/FileManager/OverwriteDialog.h b/CPP/7zip/UI/FileManager/OverwriteDialog.h
index 24e56ca..a9ca991 100644
--- a/CPP/7zip/UI/FileManager/OverwriteDialog.h
+++ b/CPP/7zip/UI/FileManager/OverwriteDialog.h
@@ -1,7 +1,7 @@
1// OverwriteDialog.h 1// OverwriteDialog.h
2 2
3#ifndef __OVERWRITE_DIALOG_H 3#ifndef ZIP7_INC_OVERWRITE_DIALOG_H
4#define __OVERWRITE_DIALOG_H 4#define ZIP7_INC_OVERWRITE_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7 7
@@ -49,9 +49,9 @@ class COverwriteDialog: public NWindows::NControl::CModalDialog
49{ 49{
50 bool _isBig; 50 bool _isBig;
51 51
52 void SetFileInfoControl(int textID, int iconID, const NOverwriteDialog::CFileInfo &fileInfo); 52 void SetFileInfoControl(unsigned textID, unsigned iconID, const NOverwriteDialog::CFileInfo &fileInfo);
53 virtual bool OnInit(); 53 virtual bool OnInit() Z7_override;
54 bool OnButtonClicked(int buttonID, HWND buttonHWND); 54 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
55 void ReduceString(UString &s); 55 void ReduceString(UString &s);
56 56
57public: 57public:
@@ -61,7 +61,7 @@ public:
61 61
62 COverwriteDialog(): ShowExtraButtons(true), DefaultButton_is_NO(false) {} 62 COverwriteDialog(): ShowExtraButtons(true), DefaultButton_is_NO(false) {}
63 63
64 INT_PTR Create(HWND parent = 0) 64 INT_PTR Create(HWND parent = NULL)
65 { 65 {
66 BIG_DIALOG_SIZE(280, 200); 66 BIG_DIALOG_SIZE(280, 200);
67 #ifdef UNDER_CE 67 #ifdef UNDER_CE
diff --git a/CPP/7zip/UI/FileManager/Panel.cpp b/CPP/7zip/UI/FileManager/Panel.cpp
index f7cdb5b..72b72c6 100644
--- a/CPP/7zip/UI/FileManager/Panel.cpp
+++ b/CPP/7zip/UI/FileManager/Panel.cpp
@@ -2,8 +2,7 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include <WindowsX.h> 5#include <windowsx.h>
6// #include <stdio.h>
7 6
8#include "../../../Common/IntToString.h" 7#include "../../../Common/IntToString.h"
9#include "../../../Common/StringConvert.h" 8#include "../../../Common/StringConvert.h"
@@ -28,6 +27,7 @@
28#include "ExtractCallback.h" 27#include "ExtractCallback.h"
29#include "FSFolder.h" 28#include "FSFolder.h"
30#include "FormatUtils.h" 29#include "FormatUtils.h"
30#include "LangUtils.h"
31#include "Panel.h" 31#include "Panel.h"
32#include "RootFolder.h" 32#include "RootFolder.h"
33 33
@@ -65,8 +65,8 @@ CPanel::~CPanel()
65 65
66HWND CPanel::GetParent() const 66HWND CPanel::GetParent() const
67{ 67{
68 HWND h = CWindow2::GetParent(); 68 const HWND h = CWindow2::GetParent();
69 return (h == 0) ? _mainWindow : h; 69 return h ? h : _mainWindow;
70} 70}
71 71
72#define kClassName L"7-Zip::Panel" 72#define kClassName L"7-Zip::Panel"
@@ -101,12 +101,12 @@ HRESULT CPanel::Create(HWND mainWindow, HWND parentWindow, UINT id,
101 cfp = fs2us(cfpF); 101 cfp = fs2us(cfpF);
102 } 102 }
103 103
104 RINOK(BindToPath(cfp, arcFormat, openRes)); 104 RINOK(BindToPath(cfp, arcFormat, openRes))
105 105
106 if (needOpenArc && !openRes.ArchiveIsOpened) 106 if (needOpenArc && !openRes.ArchiveIsOpened)
107 return S_OK; 107 return S_OK;
108 108
109 if (!CreateEx(0, kClassName, 0, WS_CHILD | WS_VISIBLE, 109 if (!CreateEx(0, kClassName, NULL, WS_CHILD | WS_VISIBLE,
110 0, 0, _xSize, 260, 110 0, 0, _xSize, 260,
111 parentWindow, (HMENU)(UINT_PTR)id, g_hInstance)) 111 parentWindow, (HMENU)(UINT_PTR)id, g_hInstance))
112 return E_FAIL; 112 return E_FAIL;
@@ -318,6 +318,16 @@ LRESULT CMyComboBoxEdit::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
318 } 318 }
319 break; 319 break;
320 } 320 }
321 case 'W':
322 {
323 bool ctrl = IsKeyDown(VK_CONTROL);
324 if (ctrl)
325 {
326 PostMessage(g_HWND, WM_COMMAND, IDCLOSE, 0);
327 return 0;
328 }
329 break;
330 }
321 } 331 }
322 break; 332 break;
323 case WM_CHAR: 333 case WM_CHAR:
@@ -336,6 +346,40 @@ LRESULT CMyComboBoxEdit::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
336 return CallWindowProc(_origWindowProc, *this, message, wParam, lParam); 346 return CallWindowProc(_origWindowProc, *this, message, wParam, lParam);
337} 347}
338 348
349
350/*
351 REBARBANDINFO in vista (_WIN32_WINNT >= 0x0600) has additional fields
352 we want 2000/xp compatibility.
353 so we must use reduced structure, if we compile with (_WIN32_WINNT >= 0x0600)
354 Also there are additional fields, if (_WIN32_IE >= 0x0400).
355 but (_WIN32_IE >= 0x0400) is expected.
356 note:
357 in x64 (64-bit):
358 {
359 (108 == REBARBANDINFO_V6_SIZE)
360 (112 == sizeof(REBARBANDINFO) // for (_WIN32_WINNT < 0x0600)
361 (128 == sizeof(REBARBANDINFO) // for (_WIN32_WINNT >= 0x0600)
362 there is difference in sizes, because REBARBANDINFO size was
363 not aligned for 8-bytes in (_WIN32_WINNT < 0x0600).
364 We hope that WinVista+ support support both (108 and 112) sizes.
365 But does WinXP-x64 support (108 == REBARBANDINFO_V6_SIZE)?
366 {
367 96 LPARAM lParam;
368 104 UINT cxHeader;
369 #if (_WIN32_WINNT >= 0x0600)
370 108 RECT rcChevronLocation;
371 124 UINT uChevronState;
372 #endif
373 }
374*/
375
376#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && defined(REBARBANDINFOA_V6_SIZE)
377 #define my_compatib_REBARBANDINFO_size REBARBANDINFO_V6_SIZE
378#else
379 #define my_compatib_REBARBANDINFO_size sizeof(REBARBANDINFO)
380#endif
381
382
339bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */) 383bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
340{ 384{
341 // _virtualMode = false; 385 // _virtualMode = false;
@@ -351,11 +395,11 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
351 style |= WS_CLIPCHILDREN; 395 style |= WS_CLIPCHILDREN;
352 style |= WS_CLIPSIBLINGS; 396 style |= WS_CLIPSIBLINGS;
353 397
354 const UInt32 kNumListModes = ARRAY_SIZE(kStyles); 398 const UInt32 kNumListModes = Z7_ARRAY_SIZE(kStyles);
355 if (_ListViewMode >= kNumListModes) 399 if (_listViewMode >= kNumListModes)
356 _ListViewMode = kNumListModes - 1; 400 _listViewMode = kNumListModes - 1;
357 401
358 style |= kStyles[_ListViewMode] 402 style |= kStyles[_listViewMode]
359 | WS_TABSTOP 403 | WS_TABSTOP
360 | LVS_EDITLABELS; 404 | LVS_EDITLABELS;
361 if (_mySelectMode) 405 if (_mySelectMode)
@@ -397,7 +441,7 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
397 icex.dwICC = ICC_BAR_CLASSES; 441 icex.dwICC = ICC_BAR_CLASSES;
398 InitCommonControlsEx(&icex); 442 InitCommonControlsEx(&icex);
399 443
400 TBBUTTON tbb [ ] = 444 const TBBUTTON tbb[] =
401 { 445 {
402 // {0, 0, TBSTATE_ENABLED, BTNS_SEP, 0L, 0}, 446 // {0, 0, TBSTATE_ENABLED, BTNS_SEP, 0L, 0},
403 {VIEW_PARENTFOLDER, kParentFolderID, TBSTATE_ENABLED, BTNS_BUTTON, { 0, 0 }, 0, 0 }, 447 {VIEW_PARENTFOLDER, kParentFolderID, TBSTATE_ENABLED, BTNS_BUTTON, { 0, 0 }, 0, 0 },
@@ -445,7 +489,7 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
445 _baseID + 2, 11, 489 _baseID + 2, 11,
446 (HINSTANCE)HINST_COMMCTRL, 490 (HINSTANCE)HINST_COMMCTRL,
447 IDB_VIEW_SMALL_COLOR, 491 IDB_VIEW_SMALL_COLOR,
448 (LPCTBBUTTON)&tbb, ARRAY_SIZE(tbb), 492 (LPCTBBUTTON)&tbb, Z7_ARRAY_SIZE(tbb),
449 0, 0, 0, 0, sizeof (TBBUTTON))); 493 0, 0, 0, 0, sizeof (TBBUTTON)));
450 494
451 #ifndef UNDER_CE 495 #ifndef UNDER_CE
@@ -464,7 +508,7 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
464 , NULL, 508 , NULL,
465 WS_BORDER | WS_VISIBLE |WS_CHILD | CBS_DROPDOWN | CBS_AUTOHSCROLL, 509 WS_BORDER | WS_VISIBLE |WS_CHILD | CBS_DROPDOWN | CBS_AUTOHSCROLL,
466 0, 0, 100, 520, 510 0, 0, 100, 520,
467 ((_headerReBar == 0) ? (HWND)*this : _headerToolBar), 511 (_headerReBar ? _headerToolBar : (HWND)*this),
468 (HMENU)(UINT_PTR)(_comboBoxID), 512 (HMENU)(UINT_PTR)(_comboBoxID),
469 g_hInstance, NULL); 513 g_hInstance, NULL);
470 #ifndef UNDER_CE 514 #ifndef UNDER_CE
@@ -513,20 +557,23 @@ bool CPanel::OnCreate(CREATESTRUCT * /* createStruct */)
513 _headerToolBar.GetMaxSize(&size); 557 _headerToolBar.GetMaxSize(&size);
514 558
515 REBARBANDINFO rbBand; 559 REBARBANDINFO rbBand;
516 rbBand.cbSize = sizeof(REBARBANDINFO); // Required 560 memset(&rbBand, 0, sizeof(rbBand));
561 // rbBand.cbSize = sizeof(rbBand); // for debug
562 // rbBand.cbSize = REBARBANDINFO_V3_SIZE; // for debug
563 rbBand.cbSize = my_compatib_REBARBANDINFO_size;
517 rbBand.fMask = RBBIM_STYLE | RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_SIZE; 564 rbBand.fMask = RBBIM_STYLE | RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_SIZE;
518 rbBand.fStyle = RBBS_NOGRIPPER; 565 rbBand.fStyle = RBBS_NOGRIPPER;
519 rbBand.cxMinChild = size.cx; 566 rbBand.cxMinChild = (UINT)size.cx;
520 rbBand.cyMinChild = size.cy; 567 rbBand.cyMinChild = (UINT)size.cy;
521 rbBand.cyChild = size.cy; 568 rbBand.cyChild = (UINT)size.cy;
522 rbBand.cx = size.cx; 569 rbBand.cx = (UINT)size.cx;
523 rbBand.hwndChild = _headerToolBar; 570 rbBand.hwndChild = _headerToolBar;
524 _headerReBar.InsertBand(-1, &rbBand); 571 _headerReBar.InsertBand(-1, &rbBand);
525 572
526 RECT rc; 573 RECT rc;
527 ::GetWindowRect(_headerComboBox, &rc); 574 ::GetWindowRect(_headerComboBox, &rc);
528 rbBand.cxMinChild = 30; 575 rbBand.cxMinChild = 30;
529 rbBand.cyMinChild = rc.bottom - rc.top; 576 rbBand.cyMinChild = (UINT)(rc.bottom - rc.top);
530 rbBand.cx = 1000; 577 rbBand.cx = 1000;
531 rbBand.hwndChild = _headerComboBox; 578 rbBand.hwndChild = _headerComboBox;
532 _headerReBar.InsertBand(-1, &rbBand); 579 _headerReBar.InsertBand(-1, &rbBand);
@@ -562,7 +609,7 @@ void CPanel::OnDestroy()
562 609
563void CPanel::ChangeWindowSize(int xSize, int ySize) 610void CPanel::ChangeWindowSize(int xSize, int ySize)
564{ 611{
565 if ((HWND)*this == 0) 612 if (!(HWND)*this)
566 return; 613 return;
567 int kHeaderSize; 614 int kHeaderSize;
568 int kStatusBarSize; 615 int kStatusBarSize;
@@ -601,7 +648,7 @@ void CPanel::ChangeWindowSize(int xSize, int ySize)
601 648
602bool CPanel::OnSize(WPARAM /* wParam */, int xSize, int ySize) 649bool CPanel::OnSize(WPARAM /* wParam */, int xSize, int ySize)
603{ 650{
604 if ((HWND)*this == 0) 651 if (!(HWND)*this)
605 return true; 652 return true;
606 if (_headerReBar) 653 if (_headerReBar)
607 _headerReBar.Move(0, 0, xSize, 0); 654 _headerReBar.Move(0, 0, xSize, 0);
@@ -682,7 +729,7 @@ bool CPanel::OnNotify(UINT /* controlID */, LPNMHDR header, LRESULT &result)
682 return false; 729 return false;
683} 730}
684 731
685bool CPanel::OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result) 732bool CPanel::OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result)
686{ 733{
687 if (itemID == kParentFolderID) 734 if (itemID == kParentFolderID)
688 { 735 {
@@ -745,7 +792,7 @@ void CPanel::MessageBox_Error_2Lines_Message_HRESULT(LPCWSTR message, HRESULT er
745} 792}
746 793
747void CPanel::MessageBox_LastError(LPCWSTR caption) const 794void CPanel::MessageBox_LastError(LPCWSTR caption) const
748 { MessageBox_Error_HRESULT_Caption(::GetLastError(), caption); } 795 { MessageBox_Error_HRESULT_Caption(GetLastError_noZero_HRESULT(), caption); }
749 796
750void CPanel::MessageBox_LastError() const 797void CPanel::MessageBox_LastError() const
751 { MessageBox_LastError(L"7-Zip"); } 798 { MessageBox_LastError(L"7-Zip"); }
@@ -830,13 +877,13 @@ void CPanel::SetListViewMode(UInt32 index)
830{ 877{
831 if (index >= 4) 878 if (index >= 4)
832 return; 879 return;
833 _ListViewMode = index; 880 _listViewMode = index;
834 DWORD oldStyle = (DWORD)_listView.GetStyle(); 881 const LONG_PTR oldStyle = _listView.GetStyle();
835 DWORD newStyle = kStyles[index]; 882 const DWORD newStyle = kStyles[index];
836 883
837 // DWORD tickCount1 = GetTickCount(); 884 // DWORD tickCount1 = GetTickCount();
838 if ((oldStyle & LVS_TYPEMASK) != newStyle) 885 if ((oldStyle & LVS_TYPEMASK) != (LONG_PTR)newStyle)
839 _listView.SetStyle((oldStyle & ~LVS_TYPEMASK) | newStyle); 886 _listView.SetStyle((oldStyle & ~(LONG_PTR)(DWORD)LVS_TYPEMASK) | (LONG_PTR)newStyle);
840 // RefreshListCtrlSaveFocused(); 887 // RefreshListCtrlSaveFocused();
841 /* 888 /*
842 DWORD tickCount2 = GetTickCount(); 889 DWORD tickCount2 = GetTickCount();
@@ -879,33 +926,34 @@ void CPanel::Post_Refresh_StatusBar()
879 926
880void CPanel::AddToArchive() 927void CPanel::AddToArchive()
881{ 928{
882 CRecordVector<UInt32> indices;
883 GetOperatedItemIndices(indices);
884 if (!Is_IO_FS_Folder()) 929 if (!Is_IO_FS_Folder())
885 { 930 {
886 MessageBox_Error_UnsupportOperation(); 931 MessageBox_Error_UnsupportOperation();
887 return; 932 return;
888 } 933 }
934 CRecordVector<UInt32> indices;
935 Get_ItemIndices_Operated(indices);
889 if (indices.Size() == 0) 936 if (indices.Size() == 0)
890 { 937 {
891 MessageBox_Error_LangID(IDS_SELECT_FILES); 938 MessageBox_Error_LangID(IDS_SELECT_FILES);
892 return; 939 return;
893 } 940 }
894 UStringVector names; 941 UString destCurDirPrefix = GetFsPath();
895
896 const UString curPrefix = GetFsPath();
897 UString destCurDirPrefix = curPrefix;
898 if (IsFSDrivesFolder()) 942 if (IsFSDrivesFolder())
899 destCurDirPrefix = ROOT_FS_FOLDER; 943 destCurDirPrefix = ROOT_FS_FOLDER;
900 944 UStringVector names;
901 FOR_VECTOR (i, indices) 945 GetFilePaths(indices, names);
902 names.Add(curPrefix + GetItemRelPath2(indices[i])); 946 UString baseName;
903 947 const UString arcName = CreateArchiveName(names,
904 const UString arcName = CreateArchiveName(names); 948 false, // isHash
905 949 NULL, // CFileInfo *fi
906 HRESULT res = CompressFiles(destCurDirPrefix, arcName, L"", 950 baseName);
907 true, // addExtension 951 const HRESULT res = CompressFiles(destCurDirPrefix, arcName, L"",
908 names, false, true, false); 952 true, // addExtension
953 names,
954 false, // email
955 true, // showDialog
956 false); // waitFinish
909 if (res != S_OK) 957 if (res != S_OK)
910 { 958 {
911 if (destCurDirPrefix.Len() >= MAX_PATH) 959 if (destCurDirPrefix.Len() >= MAX_PATH)
@@ -931,26 +979,37 @@ static UString GetSubFolderNameForExtract2(const UString &arcPath)
931 return s; 979 return s;
932} 980}
933 981
934void CPanel::GetFilePaths(const CRecordVector<UInt32> &indices, UStringVector &paths, bool allowFolders) 982
983int CPanel::FindDir_InOperatedList(const CRecordVector<UInt32> &operatedIndices) const
935{ 984{
936 const UString prefix = GetFsPath(); 985 const bool *isDirVector = &_isDirVector.Front();
937 FOR_VECTOR (i, indices) 986 const UInt32 *indices = &operatedIndices.Front();
938 { 987 const unsigned numItems = operatedIndices.Size();
939 int index = indices[i]; 988 for (unsigned i = 0; i < numItems; i++)
940 if (!allowFolders && IsItem_Folder(index)) 989 if (isDirVector[indices[i]])
941 { 990 return (int)i;
942 paths.Clear(); 991 return -1;
943 break; 992}
944 } 993
945 paths.Add(prefix + GetItemRelPath2(index)); 994
946 } 995void CPanel::GetFilePaths(const CRecordVector<UInt32> &operatedIndices, UStringVector &paths) const
947 if (paths.Size() == 0) 996{
997 paths.ClearAndReserve(operatedIndices.Size());
998 UString path = GetFsPath();
999 const unsigned prefixLen = path.Len();
1000 const UInt32 *indices = &operatedIndices.Front();
1001 const unsigned numItems = operatedIndices.Size();
1002 // for (unsigned y = 0; y < 10000; y++, paths.Clear())
1003 for (unsigned i = 0; i < numItems; i++)
948 { 1004 {
949 MessageBox_Error_LangID(IDS_SELECT_FILES); 1005 path.DeleteFrom(prefixLen);
950 return; 1006 Add_ItemRelPath2_To_String(indices[i], path);
1007 // ODS_U(path)
1008 paths.AddInReserved(path);
951 } 1009 }
952} 1010}
953 1011
1012
954void CPanel::ExtractArchives() 1013void CPanel::ExtractArchives()
955{ 1014{
956 if (_parentFolders.Size() > 0) 1015 if (_parentFolders.Size() > 0)
@@ -959,12 +1018,14 @@ void CPanel::ExtractArchives()
959 return; 1018 return;
960 } 1019 }
961 CRecordVector<UInt32> indices; 1020 CRecordVector<UInt32> indices;
962 GetOperatedItemIndices(indices); 1021 Get_ItemIndices_Operated(indices);
1022 if (indices.IsEmpty() || FindDir_InOperatedList(indices) != -1)
1023 {
1024 MessageBox_Error_LangID(IDS_SELECT_FILES);
1025 return;
1026 }
963 UStringVector paths; 1027 UStringVector paths;
964 GetFilePaths(indices, paths); 1028 GetFilePaths(indices, paths);
965 if (paths.IsEmpty())
966 return;
967
968 UString outFolder = GetFsPath(); 1029 UString outFolder = GetFsPath();
969 if (indices.Size() == 1) 1030 if (indices.Size() == 1)
970 outFolder += GetSubFolderNameForExtract2(GetItemRelPath(indices[0])); 1031 outFolder += GetSubFolderNameForExtract2(GetItemRelPath(indices[0]));
@@ -976,8 +1037,8 @@ void CPanel::ExtractArchives()
976 ci.Load(); 1037 ci.Load();
977 1038
978 ::ExtractArchives(paths, outFolder 1039 ::ExtractArchives(paths, outFolder
979 , true // showDialog 1040 , true // showDialog
980 , false // elimDup 1041 , false // elimDup
981 , ci.WriteZone 1042 , ci.WriteZone
982 ); 1043 );
983} 1044}
@@ -1047,7 +1108,7 @@ static void AddSizePair(UInt32 langID, UInt64 value, UString &s)
1047void CPanel::TestArchives() 1108void CPanel::TestArchives()
1048{ 1109{
1049 CRecordVector<UInt32> indices; 1110 CRecordVector<UInt32> indices;
1050 GetOperatedIndicesSmart(indices); 1111 Get_ItemIndices_OperSmart(indices);
1051 CMyComPtr<IArchiveFolder> archiveFolder; 1112 CMyComPtr<IArchiveFolder> archiveFolder;
1052 _folder.QueryInterface(IID_IArchiveFolder, &archiveFolder); 1113 _folder.QueryInterface(IID_IArchiveFolder, &archiveFolder);
1053 if (archiveFolder) 1114 if (archiveFolder)
@@ -1086,7 +1147,7 @@ void CPanel::TestArchives()
1086 1147
1087 extracter.Indices = indices; 1148 extracter.Indices = indices;
1088 1149
1089 UString title = LangString(IDS_PROGRESS_TESTING); 1150 const UString title = LangString(IDS_PROGRESS_TESTING);
1090 1151
1091 extracter.ProgressDialog.CompressingMode = false; 1152 extracter.ProgressDialog.CompressingMode = false;
1092 extracter.ProgressDialog.MainWindow = GetParent(); 1153 extracter.ProgressDialog.MainWindow = GetParent();
@@ -1111,8 +1172,11 @@ void CPanel::TestArchives()
1111 return; 1172 return;
1112 } 1173 }
1113 UStringVector paths; 1174 UStringVector paths;
1114 GetFilePaths(indices, paths, true); 1175 GetFilePaths(indices, paths);
1115 if (paths.IsEmpty()) 1176 if (paths.IsEmpty())
1177 {
1178 MessageBox_Error_LangID(IDS_SELECT_FILES);
1116 return; 1179 return;
1180 }
1117 ::TestArchives(paths); 1181 ::TestArchives(paths);
1118} 1182}
diff --git a/CPP/7zip/UI/FileManager/Panel.h b/CPP/7zip/UI/FileManager/Panel.h
index 4755678..e512cad 100644
--- a/CPP/7zip/UI/FileManager/Panel.h
+++ b/CPP/7zip/UI/FileManager/Panel.h
@@ -1,11 +1,15 @@
1// Panel.h 1// Panel.h
2 2
3#ifndef __PANEL_H 3#ifndef ZIP7_INC_PANEL_H
4#define __PANEL_H 4#define ZIP7_INC_PANEL_H
5 5
6#include "../../../Common/MyWindows.h" 6#include "../../../Common/MyWindows.h"
7 7
8#if defined(__MINGW32__) || defined(__MINGW64__)
9#include <shlobj.h>
10#else
8#include <ShlObj.h> 11#include <ShlObj.h>
12#endif
9 13
10#include "../../../../C/Alloc.h" 14#include "../../../../C/Alloc.h"
11 15
@@ -47,7 +51,7 @@
47 51
48const int kParentFolderID = 100; 52const int kParentFolderID = 100;
49 53
50const int kParentIndex = -1; 54const unsigned kParentIndex = (unsigned)(int)-1;
51const UInt32 kParentIndex_UInt32 = (UInt32)(Int32)kParentIndex; 55const UInt32 kParentIndex_UInt32 = (UInt32)(Int32)kParentIndex;
52 56
53#if !defined(_WIN32) || defined(UNDER_CE) 57#if !defined(_WIN32) || defined(UNDER_CE)
@@ -56,7 +60,9 @@ const UInt32 kParentIndex_UInt32 = (UInt32)(Int32)kParentIndex;
56#define ROOT_FS_FOLDER L"C:\\" 60#define ROOT_FS_FOLDER L"C:\\"
57#endif 61#endif
58 62
59struct CPanelCallback 63Z7_PURE_INTERFACES_BEGIN
64
65DECLARE_INTERFACE(CPanelCallback)
60{ 66{
61 virtual void OnTab() = 0; 67 virtual void OnTab() = 0;
62 virtual void SetFocusToPath(unsigned index) = 0; 68 virtual void SetFocusToPath(unsigned index) = 0;
@@ -68,6 +74,7 @@ struct CPanelCallback
68 virtual void DragEnd() = 0; 74 virtual void DragEnd() = 0;
69 virtual void RefreshTitle(bool always) = 0; 75 virtual void RefreshTitle(bool always) = 0;
70}; 76};
77Z7_PURE_INTERFACES_END
71 78
72void PanelCopyItems(); 79void PanelCopyItems();
73 80
@@ -116,7 +123,7 @@ public:
116 { 123 {
117 FOR_VECTOR (i, (*this)) 124 FOR_VECTOR (i, (*this))
118 if ((*this)[i].ID == id) 125 if ((*this)[i].ID == id)
119 return i; 126 return (int)i;
120 return -1; 127 return -1;
121 } 128 }
122 129
@@ -194,11 +201,15 @@ UString GetFolderPath(IFolderFolder *folder);
194 201
195class CPanel; 202class CPanel;
196 203
197class CMyListView: public NWindows::NControl::CListView2 204class CMyListView Z7_final: public NWindows::NControl::CListView2
198{ 205{
206 // ~CMyListView() ZIP7_eq_delete;
207 // CMyListView() ZIP7_eq_delete;
199public: 208public:
209 // CMyListView() {}
210 // ~CMyListView() Z7_DESTRUCTOR_override {} // change it
200 CPanel *_panel; 211 CPanel *_panel;
201 LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 212 LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
202}; 213};
203 214
204/* 215/*
@@ -223,10 +234,16 @@ struct CSelectedState
223 int FocusedItem; 234 int FocusedItem;
224 bool SelectFocused; 235 bool SelectFocused;
225 bool FocusedName_Defined; 236 bool FocusedName_Defined;
237 bool CalledFromTimer;
226 UString FocusedName; 238 UString FocusedName;
227 UStringVector SelectedNames; 239 UStringVector SelectedNames;
228 240
229 CSelectedState(): FocusedItem(-1), SelectFocused(true), FocusedName_Defined(false) {} 241 CSelectedState():
242 FocusedItem(-1),
243 SelectFocused(true),
244 FocusedName_Defined(false),
245 CalledFromTimer(false)
246 {}
230}; 247};
231 248
232#ifdef UNDER_CE 249#ifdef UNDER_CE
@@ -286,21 +303,21 @@ struct COpenResult
286 303
287 304
288 305
289class CPanel: public NWindows::NControl::CWindow2 306class CPanel Z7_final: public NWindows::NControl::CWindow2
290{ 307{
291 CExtToIconMap _extToIconMap; 308 CExtToIconMap _extToIconMap;
292 UINT _baseID; 309 UINT _baseID;
293 int _comboBoxID; 310 unsigned _comboBoxID;
294 UINT _statusBarID; 311 UINT _statusBarID;
295 312
296 CAppState *_appState; 313 CAppState *_appState;
297 314
298 bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result); 315 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result) Z7_override;
299 LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 316 virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
300 virtual bool OnCreate(CREATESTRUCT *createStruct); 317 virtual bool OnCreate(CREATESTRUCT *createStruct) Z7_override;
301 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 318 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
302 virtual void OnDestroy(); 319 virtual void OnDestroy() Z7_override;
303 virtual bool OnNotify(UINT controlID, LPNMHDR lParam, LRESULT &result); 320 virtual bool OnNotify(UINT controlID, LPNMHDR lParam, LRESULT &result) Z7_override;
304 321
305 void AddComboBoxItem(const UString &name, int iconIndex, int indent, bool addToList); 322 void AddComboBoxItem(const UString &name, int iconIndex, int indent, bool addToList);
306 323
@@ -321,7 +338,7 @@ class CPanel: public NWindows::NControl::CWindow2
321 void OnItemChanged(NMLISTVIEW *item); 338 void OnItemChanged(NMLISTVIEW *item);
322 void OnNotifyActivateItems(); 339 void OnNotifyActivateItems();
323 bool OnNotifyList(LPNMHDR lParam, LRESULT &result); 340 bool OnNotifyList(LPNMHDR lParam, LRESULT &result);
324 void OnDrag(LPNMLISTVIEW nmListView); 341 void OnDrag(LPNMLISTVIEW nmListView, bool isRightButton = false);
325 bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result); 342 bool OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result);
326 BOOL OnBeginLabelEdit(LV_DISPINFOW * lpnmh); 343 BOOL OnBeginLabelEdit(LV_DISPINFOW * lpnmh);
327 BOOL OnEndLabelEdit(LV_DISPINFOW * lpnmh); 344 BOOL OnEndLabelEdit(LV_DISPINFOW * lpnmh);
@@ -437,19 +454,19 @@ public:
437 return (UInt32)item.lParam; 454 return (UInt32)item.lParam;
438 } 455 }
439 456
440 int GetRealItemIndex(int indexInListView) const 457 unsigned GetRealItemIndex(int indexInListView) const
441 { 458 {
442 /* 459 /*
443 if (_virtualMode) 460 if (_virtualMode)
444 return indexInListView; 461 return indexInListView;
445 */ 462 */
446 LPARAM param; 463 LPARAM param;
447 if (!_listView.GetItemParam(indexInListView, param)) 464 if (!_listView.GetItemParam((unsigned)indexInListView, param))
448 throw 1; 465 throw 1;
449 return (int)param; 466 return (unsigned)param;
450 } 467 }
451 468
452 UInt32 _ListViewMode; 469 UInt32 _listViewMode;
453 int _xSize; 470 int _xSize;
454 471
455 bool _flatMode; 472 bool _flatMode;
@@ -469,12 +486,19 @@ public:
469 NWindows::NDLL::CLibrary _library; 486 NWindows::NDLL::CLibrary _library;
470 487
471 CMyComPtr<IFolderFolder> _folder; 488 CMyComPtr<IFolderFolder> _folder;
489 CBoolVector _isDirVector;
472 CMyComPtr<IFolderCompare> _folderCompare; 490 CMyComPtr<IFolderCompare> _folderCompare;
473 CMyComPtr<IFolderGetItemName> _folderGetItemName; 491 CMyComPtr<IFolderGetItemName> _folderGetItemName;
474 CMyComPtr<IArchiveGetRawProps> _folderRawProps; 492 CMyComPtr<IArchiveGetRawProps> _folderRawProps;
475 CMyComPtr<IFolderAltStreams> _folderAltStreams; 493 CMyComPtr<IFolderAltStreams> _folderAltStreams;
476 CMyComPtr<IFolderOperations> _folderOperations; 494 CMyComPtr<IFolderOperations> _folderOperations;
477 495
496
497 // for drag and drop highliting
498 int m_DropHighlighted_SelectionIndex;
499 // int m_SubFolderIndex; // realIndex of item in m_Panel list (if drop cursor to that item)
500 UString m_DropHighlighted_SubFolderName; // name of folder in m_Panel list (if drop cursor to that folder)
501
478 void ReleaseFolder(); 502 void ReleaseFolder();
479 void SetNewFolder(IFolderFolder *newFolder); 503 void SetNewFolder(IFolderFolder *newFolder);
480 504
@@ -485,22 +509,28 @@ public:
485 void GetSelectedNames(UStringVector &selectedNames); 509 void GetSelectedNames(UStringVector &selectedNames);
486 void SaveSelectedState(CSelectedState &s); 510 void SaveSelectedState(CSelectedState &s);
487 HRESULT RefreshListCtrl(const CSelectedState &s); 511 HRESULT RefreshListCtrl(const CSelectedState &s);
488 HRESULT RefreshListCtrl_SaveFocused(); 512 HRESULT RefreshListCtrl_SaveFocused(bool onTimer = false);
513
514 // UInt32 GetItem_Attrib(UInt32 itemIndex) const;
489 515
490 bool GetItem_BoolProp(UInt32 itemIndex, PROPID propID) const; 516 bool GetItem_BoolProp(UInt32 itemIndex, PROPID propID) const;
491 bool IsItem_Deleted(int itemIndex) const; 517
492 bool IsItem_Folder(int itemIndex) const; 518 bool IsItem_Deleted(unsigned itemIndex) const;
493 bool IsItem_AltStream(int itemIndex) const; 519 bool IsItem_Folder(unsigned itemIndex) const;
494 520 bool IsItem_AltStream(unsigned itemIndex) const;
495 UString GetItemName(int itemIndex) const; 521
496 UString GetItemName_for_Copy(int itemIndex) const; 522 UString GetItemName(unsigned itemIndex) const;
497 void GetItemName(int itemIndex, UString &s) const; 523 UString GetItemName_for_Copy(unsigned itemIndex) const;
498 UString GetItemPrefix(int itemIndex) const; 524 void GetItemName(unsigned itemIndex, UString &s) const;
499 UString GetItemRelPath(int itemIndex) const; 525 UString GetItemPrefix(unsigned itemIndex) const;
500 UString GetItemRelPath2(int itemIndex) const; 526 UString GetItemRelPath(unsigned itemIndex) const;
501 UString GetItemFullPath(int itemIndex) const; 527 UString GetItemRelPath2(unsigned itemIndex) const;
502 UInt64 GetItem_UInt64Prop(int itemIndex, PROPID propID) const; 528
503 UInt64 GetItemSize(int itemIndex) const; 529 void Add_ItemRelPath2_To_String(unsigned itemIndex, UString &s) const;
530
531 UString GetItemFullPath(unsigned itemIndex) const;
532 UInt64 GetItem_UInt64Prop(unsigned itemIndex, PROPID propID) const;
533 UInt64 GetItemSize(unsigned itemIndex) const;
504 534
505 //////////////////////// 535 ////////////////////////
506 // PanelFolderChange.cpp 536 // PanelFolderChange.cpp
@@ -552,7 +582,7 @@ public:
552 _markDeletedItems(true), 582 _markDeletedItems(true),
553 PanelCreated(false), 583 PanelCreated(false),
554 584
555 _ListViewMode(3), 585 _listViewMode(3),
556 _xSize(300), 586 _xSize(300),
557 587
558 _flatMode(false), 588 _flatMode(false),
@@ -565,6 +595,8 @@ public:
565 595
566 _dontShowMode(false), 596 _dontShowMode(false),
567 597
598 m_DropHighlighted_SelectionIndex(-1),
599
568 _needSaveInfo(false), 600 _needSaveInfo(false),
569 _startGroupSelect(0), 601 _startGroupSelect(0),
570 _selectionIsDefined(false) 602 _selectionIsDefined(false)
@@ -572,7 +604,7 @@ public:
572 604
573 void SetExtendedStyle() 605 void SetExtendedStyle()
574 { 606 {
575 if (_listView != 0) 607 if (_listView)
576 _listView.SetExtendedListViewStyle(_exStyle); 608 _listView.SetExtendedListViewStyle(_exStyle);
577 } 609 }
578 610
@@ -592,30 +624,38 @@ public:
592 void SetSortRawStatus(); 624 void SetSortRawStatus();
593 625
594 void Release(); 626 void Release();
595 ~CPanel(); 627 ~CPanel() Z7_DESTRUCTOR_override;
596 void OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate); 628 void OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate);
597 bool OnRightClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate, LRESULT &result); 629 bool OnRightClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate, LRESULT &result);
598 void ShowColumnsContextMenu(int x, int y); 630 void ShowColumnsContextMenu(int x, int y);
599 631
600 void OnTimer(); 632 void OnTimer();
601 void OnReload(); 633 void OnReload(bool onTimer = false);
602 bool OnContextMenu(HANDLE windowHandle, int xPos, int yPos); 634 bool OnContextMenu(HANDLE windowHandle, int xPos, int yPos);
603 635
604 CMyComPtr<IContextMenu> _sevenZipContextMenu; 636 CMyComPtr<IContextMenu> _sevenZipContextMenu;
605 CMyComPtr<IContextMenu> _systemContextMenu; 637 CMyComPtr<IContextMenu> _systemContextMenu;
638
606 HRESULT CreateShellContextMenu( 639 HRESULT CreateShellContextMenu(
607 const CRecordVector<UInt32> &operatedIndices, 640 const CRecordVector<UInt32> &operatedIndices,
608 CMyComPtr<IContextMenu> &systemContextMenu); 641 CMyComPtr<IContextMenu> &systemContextMenu);
642
609 void CreateSystemMenu(HMENU menu, 643 void CreateSystemMenu(HMENU menu,
644 bool showExtendedVerbs,
610 const CRecordVector<UInt32> &operatedIndices, 645 const CRecordVector<UInt32> &operatedIndices,
611 CMyComPtr<IContextMenu> &systemContextMenu); 646 CMyComPtr<IContextMenu> &systemContextMenu);
647
612 void CreateSevenZipMenu(HMENU menu, 648 void CreateSevenZipMenu(HMENU menu,
649 bool showExtendedVerbs,
613 const CRecordVector<UInt32> &operatedIndices, 650 const CRecordVector<UInt32> &operatedIndices,
651 int firstDirIndex,
614 CMyComPtr<IContextMenu> &sevenZipContextMenu); 652 CMyComPtr<IContextMenu> &sevenZipContextMenu);
653
615 void CreateFileMenu(HMENU menu, 654 void CreateFileMenu(HMENU menu,
616 CMyComPtr<IContextMenu> &sevenZipContextMenu, 655 CMyComPtr<IContextMenu> &sevenZipContextMenu,
617 CMyComPtr<IContextMenu> &systemContextMenu, 656 CMyComPtr<IContextMenu> &systemContextMenu,
618 bool programMenu); 657 bool programMenu);
658
619 void CreateFileMenu(HMENU menu); 659 void CreateFileMenu(HMENU menu);
620 bool InvokePluginCommand(unsigned id); 660 bool InvokePluginCommand(unsigned id);
621 bool InvokePluginCommand(unsigned id, IContextMenu *sevenZipContextMenu, 661 bool InvokePluginCommand(unsigned id, IContextMenu *sevenZipContextMenu,
@@ -637,10 +677,10 @@ public:
637 // void SortItems(int index); 677 // void SortItems(int index);
638 void SortItemsWithPropID(PROPID propID); 678 void SortItemsWithPropID(PROPID propID);
639 679
640 void GetSelectedItemsIndices(CRecordVector<UInt32> &indices) const; 680 void Get_ItemIndices_Selected(CRecordVector<UInt32> &indices) const;
641 void GetOperatedItemIndices(CRecordVector<UInt32> &indices) const; 681 void Get_ItemIndices_Operated(CRecordVector<UInt32> &indices) const;
642 void GetAllItemIndices(CRecordVector<UInt32> &indices) const; 682 void Get_ItemIndices_All(CRecordVector<UInt32> &indices) const;
643 void GetOperatedIndicesSmart(CRecordVector<UInt32> &indices) const; 683 void Get_ItemIndices_OperSmart(CRecordVector<UInt32> &indices) const;
644 // void GetOperatedListViewIndices(CRecordVector<UInt32> &indices) const; 684 // void GetOperatedListViewIndices(CRecordVector<UInt32> &indices) const;
645 void KillSelection(); 685 void KillSelection();
646 686
@@ -712,12 +752,11 @@ public:
712 752
713 class CDisableTimerProcessing 753 class CDisableTimerProcessing
714 { 754 {
715 CLASS_NO_COPY(CDisableTimerProcessing); 755 Z7_CLASS_NO_COPY(CDisableTimerProcessing)
716 756
717 bool _processTimer; 757 bool _processTimer;
718
719 CPanel &_panel; 758 CPanel &_panel;
720 759
721 public: 760 public:
722 761
723 CDisableTimerProcessing(CPanel &panel): _panel(panel) { Disable(); } 762 CDisableTimerProcessing(CPanel &panel): _panel(panel) { Disable(); }
@@ -733,9 +772,38 @@ public:
733 } 772 }
734 }; 773 };
735 774
775 class CDisableTimerProcessing2
776 {
777 Z7_CLASS_NO_COPY(CDisableTimerProcessing2)
778
779 bool _processTimer;
780 CPanel *_panel;
781
782 public:
783
784 CDisableTimerProcessing2(CPanel *panel): _processTimer(true), _panel(panel) { Disable(); }
785 ~CDisableTimerProcessing2() { Restore(); }
786 void Disable()
787 {
788 if (_panel)
789 {
790 _processTimer = _panel->_processTimer;
791 _panel->_processTimer = false;
792 }
793 }
794 void Restore()
795 {
796 if (_panel)
797 {
798 _panel->_processTimer = _processTimer;
799 _panel = NULL;
800 }
801 }
802 };
803
736 class CDisableNotify 804 class CDisableNotify
737 { 805 {
738 CLASS_NO_COPY(CDisableNotify); 806 Z7_CLASS_NO_COPY(CDisableNotify)
739 807
740 bool _processNotify; 808 bool _processNotify;
741 bool _processStatusBar; 809 bool _processStatusBar;
@@ -789,9 +857,9 @@ public:
789 void OpenFocusedItemAsInternal(const wchar_t *type = NULL); 857 void OpenFocusedItemAsInternal(const wchar_t *type = NULL);
790 void OpenSelectedItems(bool internal); 858 void OpenSelectedItems(bool internal);
791 859
792 void OpenFolderExternal(int index); 860 void OpenFolderExternal(unsigned index);
793 861
794 void OpenFolder(int index); 862 void OpenFolder(unsigned index);
795 HRESULT OpenParentArchiveFolder(); 863 HRESULT OpenParentArchiveFolder();
796 864
797 HRESULT OpenAsArc(IInStream *inStream, 865 HRESULT OpenAsArc(IInStream *inStream,
@@ -810,26 +878,26 @@ public:
810 HRESULT OpenAsArc_Name(const UString &relPath, const UString &arcFormat 878 HRESULT OpenAsArc_Name(const UString &relPath, const UString &arcFormat
811 // , bool showErrorMessage 879 // , bool showErrorMessage
812 ); 880 );
813 HRESULT OpenAsArc_Index(int index, const wchar_t *type /* = NULL */ 881 HRESULT OpenAsArc_Index(unsigned index, const wchar_t *type /* = NULL */
814 // , bool showErrorMessage 882 // , bool showErrorMessage
815 ); 883 );
816 884
817 void OpenItemInArchive(int index, bool tryInternal, bool tryExternal, 885 void OpenItemInArchive(unsigned index, bool tryInternal, bool tryExternal,
818 bool editMode, bool useEditor, const wchar_t *type = NULL); 886 bool editMode, bool useEditor, const wchar_t *type = NULL);
819 887
820 HRESULT OnOpenItemChanged(UInt32 index, const wchar_t *fullFilePath, bool usePassword, const UString &password); 888 HRESULT OnOpenItemChanged(UInt32 index, const wchar_t *fullFilePath, bool usePassword, const UString &password);
821 LRESULT OnOpenItemChanged(LPARAM lParam); 889 LRESULT OnOpenItemChanged(LPARAM lParam);
822 890
823 bool IsVirus_Message(const UString &name); 891 bool IsVirus_Message(const UString &name);
824 void OpenItem(int index, bool tryInternal, bool tryExternal, const wchar_t *type = NULL); 892 void OpenItem(unsigned index, bool tryInternal, bool tryExternal, const wchar_t *type = NULL);
825 void EditItem(bool useEditor); 893 void EditItem(bool useEditor);
826 void EditItem(int index, bool useEditor); 894 void EditItem(unsigned index, bool useEditor);
827 895
828 void RenameFile(); 896 void RenameFile();
829 void ChangeComment(); 897 void ChangeComment();
830 898
831 void SetListViewMode(UInt32 index); 899 void SetListViewMode(UInt32 index);
832 UInt32 GetListViewMode() const { return _ListViewMode; } 900 UInt32 GetListViewMode() const { return _listViewMode; }
833 PROPID GetSortID() const { return _sortID; } 901 PROPID GetSortID() const { return _sortID; }
834 902
835 void ChangeFlatMode(); 903 void ChangeFlatMode();
@@ -848,16 +916,21 @@ public:
848 916
849 void AddToArchive(); 917 void AddToArchive();
850 918
851 void GetFilePaths(const CRecordVector<UInt32> &indices, UStringVector &paths, bool allowFolders = false); 919 int FindDir_InOperatedList(const CRecordVector<UInt32> &indices) const;
920 void GetFilePaths(const CRecordVector<UInt32> &indices, UStringVector &paths) const;
852 void ExtractArchives(); 921 void ExtractArchives();
853 void TestArchives(); 922 void TestArchives();
854 923
924
855 HRESULT CopyTo(CCopyToOptions &options, 925 HRESULT CopyTo(CCopyToOptions &options,
856 const CRecordVector<UInt32> &indices, 926 const CRecordVector<UInt32> &indices,
857 UStringVector *messages, 927 UStringVector *messages,
858 bool &usePassword, UString &password); 928 bool &usePassword, UString &password,
929 const UStringVector *filePaths = NULL);
859 930
860 HRESULT CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &indices, UStringVector *messages) 931 HRESULT CopyTo(CCopyToOptions &options,
932 const CRecordVector<UInt32> &indices,
933 UStringVector *messages)
861 { 934 {
862 bool usePassword = false; 935 bool usePassword = false;
863 UString password; 936 UString password;
@@ -870,17 +943,29 @@ public:
870 return CopyTo(options, indices, messages, usePassword, password); 943 return CopyTo(options, indices, messages, usePassword, password);
871 } 944 }
872 945
946 HRESULT CopyFsItems(CCopyToOptions &options,
947 const UStringVector &filePaths,
948 UStringVector *messages)
949 {
950 bool usePassword = false;
951 UString password;
952 CRecordVector<UInt32> indices;
953 return CopyTo(options, indices, messages, usePassword, password, &filePaths);
954 }
955
956
873 HRESULT CopyFrom(bool moveMode, const UString &folderPrefix, const UStringVector &filePaths, 957 HRESULT CopyFrom(bool moveMode, const UString &folderPrefix, const UStringVector &filePaths,
874 bool showErrorMessages, UStringVector *messages); 958 bool showErrorMessages, UStringVector *messages);
875 959
876 void CopyFromNoAsk(const UStringVector &filePaths); 960 void CopyFromNoAsk(bool moveMode, const UStringVector &filePaths);
877 void CopyFromAsk(const UStringVector &filePaths);
878
879 // empty folderPath means create new Archive to path of first fileName.
880 void DropObject(IDataObject * dataObject, const UString &folderPath);
881 961
882 // empty folderPath means create new Archive to path of first fileName. 962 void CompressDropFiles(
883 void CompressDropFiles(const UStringVector &fileNames, const UString &folderPath); 963 const UStringVector &filePaths,
964 const UString &folderPath,
965 bool createNewArchive,
966 bool moveMode,
967 UInt32 sourceFlags,
968 UInt32 &targetFlags);
884 969
885 void RefreshTitle(bool always = false) { _panelCallback->RefreshTitle(always); } 970 void RefreshTitle(bool always = false) { _panelCallback->RefreshTitle(always); }
886 void RefreshTitleAlways() { RefreshTitle(true); } 971 void RefreshTitleAlways() { RefreshTitle(true); }
@@ -892,14 +977,14 @@ class CMyBuffer
892{ 977{
893 void *_data; 978 void *_data;
894public: 979public:
895 CMyBuffer(): _data(0) {} 980 CMyBuffer(): _data(NULL) {}
896 operator void *() { return _data; } 981 operator void *() { return _data; }
897 bool Allocate(size_t size) 982 bool Allocate(size_t size)
898 { 983 {
899 if (_data != 0) 984 if (_data)
900 return false; 985 return false;
901 _data = ::MidAlloc(size); 986 _data = ::MidAlloc(size);
902 return _data != 0; 987 return _data != NULL;
903 } 988 }
904 ~CMyBuffer() { ::MidFree(_data); } 989 ~CMyBuffer() { ::MidFree(_data); }
905}; 990};
@@ -919,7 +1004,7 @@ public:
919 throw 9387173; 1004 throw 9387173;
920 _needExit = true; 1005 _needExit = true;
921 _numActiveThreads = 0; 1006 _numActiveThreads = 0;
922 }; 1007 }
923 1008
924 ~CExitEventLauncher() { Exit(true); } 1009 ~CExitEventLauncher() { Exit(true); }
925 1010
diff --git a/CPP/7zip/UI/FileManager/PanelCopy.cpp b/CPP/7zip/UI/FileManager/PanelCopy.cpp
index 2ea3e3b..de3d764 100644
--- a/CPP/7zip/UI/FileManager/PanelCopy.cpp
+++ b/CPP/7zip/UI/FileManager/PanelCopy.cpp
@@ -2,29 +2,29 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../../../Common/MyException.h"
6
7#include "../Common/ZipRegistry.h" 5#include "../Common/ZipRegistry.h"
8 6
9#include "../GUI/HashGUI.h" 7#include "../GUI/HashGUI.h"
10 8
9#include "FSFolder.h"
11#include "ExtractCallback.h" 10#include "ExtractCallback.h"
12#include "LangUtils.h" 11#include "LangUtils.h"
13#include "Panel.h" 12#include "Panel.h"
14#include "resource.h"
15#include "UpdateCallback100.h" 13#include "UpdateCallback100.h"
16 14
17using namespace NWindows; 15#include "resource.h"
16
18 17
19class CPanelCopyThread: public CProgressThreadVirt 18class CPanelCopyThread: public CProgressThreadVirt
20{ 19{
21 bool ResultsWereShown; 20 bool ResultsWereShown;
22 bool NeedShowRes; 21 bool NeedShowRes;
23 22
24 HRESULT ProcessVirt(); 23 HRESULT ProcessVirt() Z7_override;
25 virtual void ProcessWasFinished_GuiVirt(); 24 virtual void ProcessWasFinished_GuiVirt() Z7_override;
26public: 25public:
27 const CCopyToOptions *options; 26 const CCopyToOptions *options;
27 const UStringVector *CopyFrom_Paths;
28 CMyComPtr<IFolderOperations> FolderOperations; 28 CMyComPtr<IFolderOperations> FolderOperations;
29 CRecordVector<UInt32> Indices; 29 CRecordVector<UInt32> Indices;
30 CExtractCallbackImp *ExtractCallbackSpec; 30 CExtractCallbackImp *ExtractCallbackSpec;
@@ -39,7 +39,8 @@ public:
39 39
40 CPanelCopyThread(): 40 CPanelCopyThread():
41 ResultsWereShown(false), 41 ResultsWereShown(false),
42 NeedShowRes(false) 42 NeedShowRes(false),
43 CopyFrom_Paths(NULL)
43 // , Result2(E_FAIL) 44 // , Result2(E_FAIL)
44 {} 45 {}
45}; 46};
@@ -72,23 +73,32 @@ HRESULT CPanelCopyThread::ProcessVirt()
72 73
73 HRESULT result2; 74 HRESULT result2;
74 75
76 if (FolderOperations)
75 { 77 {
76 CMyComPtr<IFolderSetZoneIdMode> setZoneMode; 78 CMyComPtr<IFolderSetZoneIdMode> setZoneMode;
77 FolderOperations.QueryInterface(IID_IFolderSetZoneIdMode, &setZoneMode); 79 FolderOperations.QueryInterface(IID_IFolderSetZoneIdMode, &setZoneMode);
78 if (setZoneMode) 80 if (setZoneMode)
79 { 81 {
80 RINOK(setZoneMode->SetZoneIdMode(options->ZoneIdMode)); 82 RINOK(setZoneMode->SetZoneIdMode(options->ZoneIdMode))
81 } 83 }
82 } 84 }
83 85
84 if (options->testMode) 86 if (CopyFrom_Paths)
87 {
88 result2 = NFsFolder::CopyFileSystemItems(
89 *CopyFrom_Paths,
90 us2fs(options->folder),
91 options->moveMode,
92 (IFolderOperationsExtractCallback *)ExtractCallbackSpec);
93 }
94 else if (options->testMode)
85 { 95 {
86 CMyComPtr<IArchiveFolder> archiveFolder; 96 CMyComPtr<IArchiveFolder> archiveFolder;
87 FolderOperations.QueryInterface(IID_IArchiveFolder, &archiveFolder); 97 FolderOperations.QueryInterface(IID_IArchiveFolder, &archiveFolder);
88 if (!archiveFolder) 98 if (!archiveFolder)
89 return E_NOTIMPL; 99 return E_NOTIMPL;
90 CMyComPtr<IFolderArchiveExtractCallback> extractCallback2; 100 CMyComPtr<IFolderArchiveExtractCallback> extractCallback2;
91 RINOK(ExtractCallback.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2)); 101 RINOK(ExtractCallback.QueryInterface(IID_IFolderArchiveExtractCallback, &extractCallback2))
92 NExtract::NPathMode::EEnum pathMode = 102 NExtract::NPathMode::EEnum pathMode =
93 NExtract::NPathMode::kCurPaths; 103 NExtract::NPathMode::kCurPaths;
94 // NExtract::NPathMode::kFullPathnames; 104 // NExtract::NPathMode::kFullPathnames;
@@ -122,7 +132,7 @@ HRESULT CPanelCopyThread::ProcessVirt()
122 132
123 133
124/* 134/*
125#ifdef EXTERNAL_CODECS 135#ifdef Z7_EXTERNAL_CODECS
126 136
127static void ThrowException_if_Error(HRESULT res) 137static void ThrowException_if_Error(HRESULT res)
128{ 138{
@@ -133,9 +143,11 @@ static void ThrowException_if_Error(HRESULT res)
133#endif 143#endif
134*/ 144*/
135 145
136HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &indices, 146HRESULT CPanel::CopyTo(CCopyToOptions &options,
147 const CRecordVector<UInt32> &indices,
137 UStringVector *messages, 148 UStringVector *messages,
138 bool &usePassword, UString &password) 149 bool &usePassword, UString &password,
150 const UStringVector *filePaths)
139{ 151{
140 if (options.NeedRegistryZone && !options.testMode) 152 if (options.NeedRegistryZone && !options.testMode)
141 { 153 {
@@ -151,9 +163,10 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &ind
151 return E_NOTIMPL; 163 return E_NOTIMPL;
152 } 164 }
153 165
166 if (!filePaths)
154 if (!_folderOperations) 167 if (!_folderOperations)
155 { 168 {
156 UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); 169 const UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED);
157 if (options.showErrorMessages) 170 if (options.showErrorMessages)
158 MessageBox_Error(errorMessage); 171 MessageBox_Error(errorMessage);
159 else if (messages) 172 else if (messages)
@@ -165,7 +178,7 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &ind
165 178
166 { 179 {
167 /* 180 /*
168 #ifdef EXTERNAL_CODECS 181 #ifdef Z7_EXTERNAL_CODECS
169 CExternalCodecs g_ExternalCodecs; 182 CExternalCodecs g_ExternalCodecs;
170 #endif 183 #endif
171 */ 184 */
@@ -203,7 +216,7 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &ind
203 But new code uses global codecs so we don't need to call LoadGlobalCodecs again */ 216 But new code uses global codecs so we don't need to call LoadGlobalCodecs again */
204 217
205 /* 218 /*
206 #ifdef EXTERNAL_CODECS 219 #ifdef Z7_EXTERNAL_CODECS
207 ThrowException_if_Error(LoadGlobalCodecs()); 220 ThrowException_if_Error(LoadGlobalCodecs());
208 #endif 221 #endif
209 */ 222 */
@@ -248,13 +261,18 @@ HRESULT CPanel::CopyTo(CCopyToOptions &options, const CRecordVector<UInt32> &ind
248 261
249 extracter.ExtractCallbackSpec->OverwriteMode = NExtract::NOverwriteMode::kAsk; 262 extracter.ExtractCallbackSpec->OverwriteMode = NExtract::NOverwriteMode::kAsk;
250 extracter.ExtractCallbackSpec->Init(); 263 extracter.ExtractCallbackSpec->Init();
251 extracter.Indices = indices; 264
252 extracter.FolderOperations = _folderOperations; 265 extracter.CopyFrom_Paths = filePaths;
266 if (!filePaths)
267 {
268 extracter.Indices = indices;
269 extracter.FolderOperations = _folderOperations;
270 }
253 271
254 extracter.ExtractCallbackSpec->PasswordIsDefined = usePassword; 272 extracter.ExtractCallbackSpec->PasswordIsDefined = usePassword;
255 extracter.ExtractCallbackSpec->Password = password; 273 extracter.ExtractCallbackSpec->Password = password;
256 274
257 RINOK(extracter.Create(title, GetParent())); 275 RINOK(extracter.Create(title, GetParent()))
258 276
259 277
260 if (messages) 278 if (messages)
@@ -335,8 +353,8 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri
335 353
336 updater.UpdateCallbackSpec->ProgressDialog = &updater.ProgressDialog; 354 updater.UpdateCallbackSpec->ProgressDialog = &updater.ProgressDialog;
337 355
338 UString title = LangString(IDS_COPYING); 356 const UString title = LangString(IDS_COPYING);
339 UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE); 357 const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE);
340 358
341 updater.ProgressDialog.MainWindow = GetParent(); 359 updater.ProgressDialog.MainWindow = GetParent();
342 updater.ProgressDialog.MainTitle = progressWindowTitle; 360 updater.ProgressDialog.MainTitle = progressWindowTitle;
@@ -363,7 +381,9 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri
363 381
364 { 382 {
365 NWindows::CThread thread; 383 NWindows::CThread thread;
366 RINOK(thread.Create(CThreadUpdate::MyThreadFunction, &updater)); 384 const WRes wres = thread.Create(CThreadUpdate::MyThreadFunction, &updater);
385 if (wres != 0)
386 return HRESULT_FROM_WIN32(wres);
367 updater.ProgressDialog.Create(title, thread, GetParent()); 387 updater.ProgressDialog.Create(title, thread, GetParent());
368 } 388 }
369 389
@@ -375,7 +395,7 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri
375 395
376 if (res == E_NOINTERFACE) 396 if (res == E_NOINTERFACE)
377 { 397 {
378 UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED); 398 const UString errorMessage = LangString(IDS_OPERATION_IS_NOT_SUPPORTED);
379 if (showErrorMessages) 399 if (showErrorMessages)
380 MessageBox_Error(errorMessage); 400 MessageBox_Error(errorMessage);
381 else if (messages) 401 else if (messages)
@@ -387,7 +407,7 @@ HRESULT CPanel::CopyFrom(bool moveMode, const UString &folderPrefix, const UStri
387 return res; 407 return res;
388} 408}
389 409
390void CPanel::CopyFromNoAsk(const UStringVector &filePaths) 410void CPanel::CopyFromNoAsk(bool moveMode, const UStringVector &filePaths)
391{ 411{
392 CDisableTimerProcessing disableTimerProcessing(*this); 412 CDisableTimerProcessing disableTimerProcessing(*this);
393 413
@@ -396,7 +416,7 @@ void CPanel::CopyFromNoAsk(const UStringVector &filePaths)
396 416
397 CDisableNotify disableNotify(*this); 417 CDisableNotify disableNotify(*this);
398 418
399 HRESULT result = CopyFrom(false, L"", filePaths, true, 0); 419 const HRESULT result = CopyFrom(moveMode, L"", filePaths, true, NULL);
400 420
401 if (result != S_OK) 421 if (result != S_OK)
402 { 422 {
@@ -413,17 +433,3 @@ void CPanel::CopyFromNoAsk(const UStringVector &filePaths)
413 disableNotify.Restore(); 433 disableNotify.Restore();
414 SetFocusToList(); 434 SetFocusToList();
415} 435}
416
417void CPanel::CopyFromAsk(const UStringVector &filePaths)
418{
419 UString title = LangString(IDS_CONFIRM_FILE_COPY);
420 UString message = LangString(IDS_WANT_TO_COPY_FILES);
421 message += "\n\'";
422 message += _currentFolderPrefix;
423 message += "\' ?";
424 int res = ::MessageBoxW(*(this), message, title, MB_YESNOCANCEL | MB_ICONQUESTION);
425 if (res != IDYES)
426 return;
427
428 CopyFromNoAsk(filePaths);
429}
diff --git a/CPP/7zip/UI/FileManager/PanelCrc.cpp b/CPP/7zip/UI/FileManager/PanelCrc.cpp
index 32948d8..df0b733 100644
--- a/CPP/7zip/UI/FileManager/PanelCrc.cpp
+++ b/CPP/7zip/UI/FileManager/PanelCrc.cpp
@@ -20,7 +20,7 @@
20using namespace NWindows; 20using namespace NWindows;
21using namespace NFile; 21using namespace NFile;
22 22
23#ifdef EXTERNAL_CODECS 23#ifdef Z7_EXTERNAL_CODECS
24extern CExternalCodecs g_ExternalCodecs; 24extern CExternalCodecs g_ExternalCodecs;
25HRESULT LoadGlobalCodecs(); 25HRESULT LoadGlobalCodecs();
26#endif 26#endif
@@ -38,7 +38,7 @@ struct CDirEnumerator
38 FStringVector Prefixes; 38 FStringVector Prefixes;
39 unsigned Index; 39 unsigned Index;
40 40
41 CDirEnumerator(): EnterToDirs(false), Index(0) {}; 41 CDirEnumerator(): EnterToDirs(false), Index(0) {}
42 42
43 void Init(); 43 void Init();
44 DWORD GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath); 44 DWORD GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath);
@@ -53,8 +53,8 @@ void CDirEnumerator::Init()
53 53
54static DWORD GetNormalizedError() 54static DWORD GetNormalizedError()
55{ 55{
56 DWORD error = GetLastError(); 56 const DWORD error = GetLastError();
57 return (error == 0) ? E_FAIL : error; 57 return (error == 0) ? (DWORD)E_FAIL : error;
58} 58}
59 59
60DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath) 60DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &resPath)
@@ -73,9 +73,9 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r
73 if (Index >= FilePaths.Size()) 73 if (Index >= FilePaths.Size())
74 return S_OK; 74 return S_OK;
75 const FString &path = FilePaths[Index++]; 75 const FString &path = FilePaths[Index++];
76 int pos = path.ReverseFind_PathSepar(); 76 const int pos = path.ReverseFind_PathSepar();
77 if (pos >= 0) 77 if (pos >= 0)
78 resPath.SetFrom(path, pos + 1); 78 resPath.SetFrom(path, (unsigned)pos + 1);
79 79
80 #if defined(_WIN32) && !defined(UNDER_CE) 80 #if defined(_WIN32) && !defined(UNDER_CE)
81 if (isRootPrefix && path.Len() == 2 && NName::IsDrivePath2(path)) 81 if (isRootPrefix && path.Len() == 2 && NName::IsDrivePath2(path))
@@ -90,7 +90,7 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r
90 #endif 90 #endif
91 if (!fi.Find(BasePrefix + path)) 91 if (!fi.Find(BasePrefix + path))
92 { 92 {
93 DWORD error = GetNormalizedError(); 93 const DWORD error = GetNormalizedError();
94 resPath = path; 94 resPath = path;
95 return error; 95 return error;
96 } 96 }
@@ -110,7 +110,7 @@ DWORD CDirEnumerator::GetNextFile(NFind::CFileInfo &fi, bool &filled, FString &r
110 } 110 }
111 else 111 else
112 { 112 {
113 DWORD error = GetNormalizedError(); 113 const DWORD error = GetNormalizedError();
114 resPath = Prefixes.Back(); 114 resPath = Prefixes.Back();
115 Enumerators.DeleteBack(); 115 Enumerators.DeleteBack();
116 Prefixes.DeleteBack(); 116 Prefixes.DeleteBack();
@@ -142,8 +142,8 @@ class CThreadCrc: public CProgressThreadVirt
142 bool ResultsWereShown; 142 bool ResultsWereShown;
143 bool WasFinished; 143 bool WasFinished;
144 144
145 HRESULT ProcessVirt(); 145 HRESULT ProcessVirt() Z7_override;
146 virtual void ProcessWasFinished_GuiVirt(); 146 virtual void ProcessWasFinished_GuiVirt() Z7_override;
147public: 147public:
148 CDirEnumerator Enumerator; 148 CDirEnumerator Enumerator;
149 CHashBundle Hash; 149 CHashBundle Hash;
@@ -176,7 +176,7 @@ void CThreadCrc::ProcessWasFinished_GuiVirt()
176 176
177void CThreadCrc::AddErrorMessage(DWORD systemError, const FChar *name) 177void CThreadCrc::AddErrorMessage(DWORD systemError, const FChar *name)
178{ 178{
179 Sync.AddError_Code_Name(systemError, fs2us(Enumerator.BasePrefix + name)); 179 Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(Enumerator.BasePrefix + name));
180 Hash.NumErrors++; 180 Hash.NumErrors++;
181} 181}
182 182
@@ -214,7 +214,7 @@ HRESULT CThreadCrc::ProcessVirt()
214 for (;;) 214 for (;;)
215 { 215 {
216 bool filled; 216 bool filled;
217 DWORD error = Enumerator.GetNextFile(fi, filled, path); 217 const DWORD error = Enumerator.GetNextFile(fi, filled, path);
218 if (error != 0) 218 if (error != 0)
219 { 219 {
220 AddErrorMessage(error, path); 220 AddErrorMessage(error, path);
@@ -246,10 +246,10 @@ HRESULT CThreadCrc::ProcessVirt()
246 */ 246 */
247 if (needPrint) 247 if (needPrint)
248 { 248 {
249 RINOK(sync.ScanProgress(numFiles, totalSize, path, fi.IsDir())); 249 RINOK(sync.ScanProgress(numFiles, totalSize, path, fi.IsDir()))
250 } 250 }
251 } 251 }
252 RINOK(sync.ScanProgress(numFiles, totalSize, FString(), false)); 252 RINOK(sync.ScanProgress(numFiles, totalSize, FString(), false))
253 // sync.SetNumFilesTotal(numFiles); 253 // sync.SetNumFilesTotal(numFiles);
254 // sync.SetProgress(totalSize, 0); 254 // sync.SetProgress(totalSize, 0);
255 // SetStatus(LangString(IDS_CHECKSUM_CALCULATING)); 255 // SetStatus(LangString(IDS_CHECKSUM_CALCULATING));
@@ -312,16 +312,16 @@ HRESULT CThreadCrc::ProcessVirt()
312 Hash.Update(buf, size); 312 Hash.Update(buf, size);
313 if (Hash.CurSize - progress_Prev >= ((UInt32)1 << 21)) 313 if (Hash.CurSize - progress_Prev >= ((UInt32)1 << 21))
314 { 314 {
315 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize + Hash.CurSize)); 315 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize + Hash.CurSize))
316 progress_Prev = Hash.CurSize; 316 progress_Prev = Hash.CurSize;
317 } 317 }
318 } 318 }
319 } 319 }
320 if (error == 0) 320 if (error == 0)
321 Hash.Final(fi.IsDir(), false, fs2us(path)); 321 Hash.Final(fi.IsDir(), false, fs2us(path));
322 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)); 322 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize))
323 } 323 }
324 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize)); 324 RINOK(sync.Set_NumBytesCur(errorsFilesSize + Hash.FilesSize))
325 sync.Set_NumFilesCur(Hash.NumFiles); 325 sync.Set_NumFilesCur(Hash.NumFiles);
326 if (Hash.NumFiles != 1) 326 if (Hash.NumFiles != 1)
327 sync.Set_FilePath(L""); 327 sync.Set_FilePath(L"");
@@ -341,7 +341,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName)
341 CPanel &srcPanel = Panels[srcPanelIndex]; 341 CPanel &srcPanel = Panels[srcPanelIndex];
342 342
343 CRecordVector<UInt32> indices; 343 CRecordVector<UInt32> indices;
344 srcPanel.GetOperatedIndicesSmart(indices); 344 srcPanel.Get_ItemIndices_OperSmart(indices);
345 if (indices.IsEmpty()) 345 if (indices.IsEmpty())
346 return S_OK; 346 return S_OK;
347 347
@@ -357,7 +357,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName)
357 return srcPanel.CopyTo(options, indices, &messages); 357 return srcPanel.CopyTo(options, indices, &messages);
358 } 358 }
359 359
360 #ifdef EXTERNAL_CODECS 360 #ifdef Z7_EXTERNAL_CODECS
361 361
362 LoadGlobalCodecs(); 362 LoadGlobalCodecs();
363 363
@@ -369,7 +369,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName)
369 { 369 {
370 UStringVector methods; 370 UStringVector methods;
371 methods.Add(methodName); 371 methods.Add(methodName);
372 RINOK(t.Hash.SetMethods(EXTERNAL_CODECS_VARS_G methods)); 372 RINOK(t.Hash.SetMethods(EXTERNAL_CODECS_VARS_G methods))
373 } 373 }
374 374
375 FOR_VECTOR (i, indices) 375 FOR_VECTOR (i, indices)
@@ -382,7 +382,7 @@ HRESULT CApp::CalculateCrc2(const UString &methodName)
382 UString basePrefix2 = basePrefix; 382 UString basePrefix2 = basePrefix;
383 if (basePrefix2.Back() == ':') 383 if (basePrefix2.Back() == ':')
384 { 384 {
385 int pos = basePrefix2.ReverseFind_PathSepar(); 385 const int pos = basePrefix2.ReverseFind_PathSepar();
386 if (pos >= 0) 386 if (pos >= 0)
387 basePrefix2.DeleteFrom((unsigned)(pos + 1)); 387 basePrefix2.DeleteFrom((unsigned)(pos + 1));
388 } 388 }
@@ -394,14 +394,14 @@ HRESULT CApp::CalculateCrc2(const UString &methodName)
394 394
395 t.ShowCompressionInfo = false; 395 t.ShowCompressionInfo = false;
396 396
397 UString title = LangString(IDS_CHECKSUM_CALCULATING); 397 const UString title = LangString(IDS_CHECKSUM_CALCULATING);
398 398
399 t.MainWindow = _window; 399 t.MainWindow = _window;
400 t.MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE); 400 t.MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE);
401 t.MainAddTitle = title; 401 t.MainAddTitle = title;
402 t.MainAddTitle.Add_Space(); 402 t.MainAddTitle.Add_Space();
403 403
404 RINOK(t.Create(title, _window)); 404 RINOK(t.Create(title, _window))
405 405
406 t.ShowFinalResults(_window); 406 t.ShowFinalResults(_window);
407 } 407 }
diff --git a/CPP/7zip/UI/FileManager/PanelDrag.cpp b/CPP/7zip/UI/FileManager/PanelDrag.cpp
index af8799c..040444c 100644
--- a/CPP/7zip/UI/FileManager/PanelDrag.cpp
+++ b/CPP/7zip/UI/FileManager/PanelDrag.cpp
@@ -6,10 +6,15 @@
6#include <winuserm.h> 6#include <winuserm.h>
7#endif 7#endif
8 8
9#include "../../../../C/7zVersion.h"
10#include "../../../../C/CpuArch.h"
11
9#include "../../../Common/StringConvert.h" 12#include "../../../Common/StringConvert.h"
10#include "../../../Common/Wildcard.h" 13#include "../../../Common/Wildcard.h"
11 14
15#include "../../../Windows/COM.h"
12#include "../../../Windows/MemoryGlobal.h" 16#include "../../../Windows/MemoryGlobal.h"
17#include "../../../Windows/Menu.h"
13#include "../../../Windows/FileDir.h" 18#include "../../../Windows/FileDir.h"
14#include "../../../Windows/FileName.h" 19#include "../../../Windows/FileName.h"
15#include "../../../Windows/Shell.h" 20#include "../../../Windows/Shell.h"
@@ -22,6 +27,11 @@
22 27
23#include "App.h" 28#include "App.h"
24#include "EnumFormatEtc.h" 29#include "EnumFormatEtc.h"
30#include "FormatUtils.h"
31#include "LangUtils.h"
32
33#include "resource.h"
34#include "../Explorer/resource.h"
25 35
26using namespace NWindows; 36using namespace NWindows;
27using namespace NFile; 37using namespace NFile;
@@ -31,88 +41,1003 @@ using namespace NDir;
31extern bool g_IsNT; 41extern bool g_IsNT;
32#endif 42#endif
33 43
34#define kTempDirPrefix FTEXT("7zE") 44#define PRF(x)
45#define PRF_W(x)
46// #define PRF2(x)
47#define PRF3(x)
48#define PRF3_W(x)
49#define PRF4(x)
50// #define PRF4(x) OutputDebugStringA(x)
51// #define PRF4_W(x) OutputDebugStringW(x)
35 52
36static LPCTSTR const kSvenZipSetFolderFormat = TEXT("7-Zip::SetTargetFolder"); 53// #define SHOW_DEBUG_DRAG
37 54
38//////////////////////////////////////////////////////// 55#ifdef SHOW_DEBUG_DRAG
56
57#define PRF_(x) { x; }
58
59static void Print_Point(const char *name, DWORD keyState, const POINTL &pt, DWORD effect)
60{
61 AString s (name);
62 s += " x="; s.Add_UInt32((unsigned)pt.x);
63 s += " y="; s.Add_UInt32((unsigned)pt.y);
64 s += " k="; s.Add_UInt32(keyState);
65 s += " e="; s.Add_UInt32(effect);
66 PRF4(s);
67}
68
69#else
70
71#define PRF_(x)
72
73#endif
74
75
76#define kTempDirPrefix FTEXT("7zE")
77
78// all versions: k_Format_7zip_SetTargetFolder format to transfer folder path from target to source
79static LPCTSTR const k_Format_7zip_SetTargetFolder = TEXT("7-Zip::SetTargetFolder");
80// new v23 formats:
81static LPCTSTR const k_Format_7zip_SetTransfer = TEXT("7-Zip::SetTransfer");
82static LPCTSTR const k_Format_7zip_GetTransfer = TEXT("7-Zip::GetTransfer");
83
84/*
85 Win10: clipboard formats.
86 There are about 16K free ids (formats) per system that can be
87 registered with RegisterClipboardFormat() with different names.
88 Probably that 16K ids space is common for ids registering for both
89 formats: RegisterClipboardFormat(), and registered window classes:
90 RegisterClass(). But ids for window classes will be deleted from
91 the list after process finishing. And registered clipboard
92 formats probably will be deleted from the list only after reboot.
93*/
94
95// static bool const g_CreateArchive_for_Drag_from_7zip = false;
96// static bool const g_CreateArchive_for_Drag_from_Explorer = true;
97 // = false; // for debug
98
99/*
100How DoDragDrop() works:
101{
102 IDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0
103 IDropTarget::Enter()
104 IDropSource::GiveFeedback()
105 IDropTarget::DragOver()
106 IDropSource::GiveFeedback()
107
108 for()
109 {
110 IDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0
111 IDropTarget::DragOver() (keyState & MK_LBUTTON) != 0
112 IDropSource::GiveFeedback()
113 }
114
115 {
116 // DoDragDrop() in Win10 before calling // QueryContinueDrag()
117 // with (*(keyState & MK_LBUTTON) == 0) probably calls:
118 // 1) IDropTarget::DragOver() with same point values (x,y), but (keyState & MK_LBUTTON) != 0)
119 // 2) IDropSource::GiveFeedback().
120 // so DropSource can know exact GiveFeedback(effect) mode just before LBUTTON releasing.
121
122 if (IDropSource::QueryContinueDrag() for (keyState & MK_LBUTTON) == 0
123 returns DRAGDROP_S_DROP), it will call
124 IDropTarget::Drop()
125 }
126 or
127 {
128 IDropSource::QueryContinueDrag()
129 IDropTarget::DragLeave()
130 IDropSource::GiveFeedback(0)
131 }
132 or
133 {
134 if (IDropSource::QueryContinueDrag()
135 returns DRAGDROP_S_CANCEL)
136 IDropTarget::DragLeave()
137 }
138}
139*/
140
141
142// ---------- CDropTarget ----------
143
144static const UInt32 k_Struct_Id_SetTranfer = 2; // it's our selected id
145static const UInt32 k_Struct_Id_GetTranfer = 3; // it's our selected id
146
147static const UInt64 k_Program_Id = 1; // "7-Zip"
148
149enum E_Program_ISA
150{
151 k_Program_ISA_x86 = 2,
152 k_Program_ISA_x64 = 3,
153 k_Program_ISA_armt = 4,
154 k_Program_ISA_arm64 = 5,
155 k_Program_ISA_arm32 = 6,
156 k_Program_ISA_ia64 = 9
157};
158
159#define k_Program_Ver ((MY_VER_MAJOR << 16) | MY_VER_MINOR)
160
161
162// k_SourceFlags_* are flags that are sent from Source to Target
163
164static const UInt32 k_SourceFlags_DoNotProcessInTarget = 1 << 1;
165/* Do not process in Target. Source will process operation instead of Target.
166 By default Target processes Drop opearation. */
167// static const UInt32 k_SourceFlags_ProcessInTarget = 1 << 2;
168
169static const UInt32 k_SourceFlags_DoNotWaitFinish = 1 << 3;
170static const UInt32 k_SourceFlags_WaitFinish = 1 << 4;
171/* usually Source needs WaitFinish, if temp files were created. */
172
173static const UInt32 k_SourceFlags_TempFiles = 1 << 6;
174static const UInt32 k_SourceFlags_NamesAreParent = 1 << 7;
175/* if returned path list for GetData(CF_HDROP) contains
176 path of parent temp folder instead of final paths of items
177 that will be extracted later from archive */
178
179static const UInt32 k_SourceFlags_SetTargetFolder = 1 << 8;
180/* SetData::("SetTargetFolder") was called (with empty or non-empty string) */
181
182static const UInt32 k_SourceFlags_SetTargetFolder_NonEmpty = 1 << 9;
183/* SetData::("SetTargetFolder") was called with non-empty string */
184
185static const UInt32 k_SourceFlags_NeedExtractOpToFs = 1 << 10;
186
187static const UInt32 k_SourceFlags_Copy_WasCalled = 1 << 11;
188
189static const UInt32 k_SourceFlags_LeftButton = 1 << 14;
190static const UInt32 k_SourceFlags_RightButton = 1 << 15;
191
192
193static const UInt32 k_TargetFlags_WasCanceled = 1 << 0;
194static const UInt32 k_TargetFlags_MustBeProcessedBySource = 1 << 1;
195static const UInt32 k_TargetFlags_WasProcessed = 1 << 2;
196static const UInt32 k_TargetFlags_DoNotWaitFinish = 1 << 3;
197static const UInt32 k_TargetFlags_WaitFinish = 1 << 4;
198static const UInt32 k_TargetFlags_MenuWasShown = 1 << 16;
199
200struct CDataObject_TransferBase
201{
202 UInt32 Struct_Id;
203 UInt32 Struct_Size;
204
205 UInt64 Program_Id;
206 UInt32 Program_Ver_Main;
207 UInt32 Program_Ver_Build;
208 UInt32 Program_ISA;
209 UInt32 Program_Flags;
210
211 UInt32 ProcessId;
212 UInt32 _reserved1[7];
213
214protected:
215 void Init_Program();
216};
217
218
219void CDataObject_TransferBase::Init_Program()
220{
221 Program_Id = k_Program_Id;
222 Program_ISA =
223 #if defined(MY_CPU_AMD64)
224 k_Program_ISA_x64
225 #elif defined(MY_CPU_X86)
226 k_Program_ISA_x86
227 #elif defined(MY_CPU_ARM64)
228 k_Program_ISA_arm64
229 #elif defined(MY_CPU_ARM32)
230 k_Program_ISA_arm32
231 #elif defined(MY_CPU_ARMT) || defined(MY_CPU_ARM)
232 k_Program_ISA_armt
233 #elif defined(MY_CPU_IA64)
234 k_Program_ISA_ia64
235 #else
236 0
237 #endif
238 ;
239 Program_Flags = sizeof(size_t);
240 Program_Ver_Main = k_Program_Ver;
241 // Program_Ver_Build = 0;
242 ProcessId = GetCurrentProcessId();
243}
244
245
246#if defined(__GNUC__) && !defined(__clang__)
247/* 'void* memset(void*, int, size_t)' clearing an object
248 of non-trivial type 'struct CDataObject_SetTransfer' */
249#pragma GCC diagnostic ignored "-Wclass-memaccess"
250#endif
251
252
253struct CDataObject_GetTransfer:
254public CDataObject_TransferBase
255{
256 UInt32 Flags;
257
258 UInt32 _reserved2[11];
259
260 CDataObject_GetTransfer()
261 {
262 memset(this, 0, sizeof(*this));
263 Init_Program();
264 Struct_Id = k_Struct_Id_GetTranfer;
265 Struct_Size = sizeof(*this);
266 }
267
268 bool Check() const
269 {
270 return Struct_Size >= sizeof(*this) && Struct_Id == k_Struct_Id_GetTranfer;
271 }
272};
273
274
275enum Enum_FolderType
276{
277 k_FolderType_None,
278 k_FolderType_Unknown = 1,
279 k_FolderType_Fs = 2,
280 k_FolderType_AltStreams = 3,
281 k_FolderType_Archive = 4
282};
283
284struct CTargetTransferInfo
285{
286 UInt32 Flags;
287 UInt32 FuncType;
288
289 UInt32 KeyState;
290 UInt32 OkEffects;
291 POINTL Point;
292
293 UInt32 Cmd_Effect;
294 UInt32 Cmd_Type;
295 UInt32 FolderType;
296 UInt32 _reserved3[3];
297
298 CTargetTransferInfo()
299 {
300 memset(this, 0, sizeof(*this));
301 }
302};
303
304struct CDataObject_SetTransfer:
305public CDataObject_TransferBase
306{
307 CTargetTransferInfo Target;
308
309 void Init()
310 {
311 memset(this, 0, sizeof(*this));
312 Init_Program();
313 Struct_Id = k_Struct_Id_SetTranfer;
314 Struct_Size = sizeof(*this);
315 }
316
317 bool Check() const
318 {
319 return Struct_Size >= sizeof(*this) && Struct_Id == k_Struct_Id_SetTranfer;
320 }
321};
322
323
324
325
326
327enum Enum_DragTargetMode
328{
329 k_DragTargetMode_None = 0,
330 k_DragTargetMode_Leave = 1,
331 k_DragTargetMode_Enter = 2,
332 k_DragTargetMode_Over = 3,
333 k_DragTargetMode_Drop_Begin = 4,
334 k_DragTargetMode_Drop_End = 5
335};
336
337
338// ---- menu ----
339
340namespace NDragMenu {
341
342enum Enum_CmdId
343{
344 k_None = 0,
345 k_Cancel = 1,
346 k_Copy_Base = 2, // to fs
347 k_Copy_ToArc = 3,
348 k_AddToArc = 4
349 /*
350 k_OpenArc = 8,
351 k_TestArc = 9,
352 k_ExtractFiles = 10,
353 k_ExtractHere = 11
354 */
355};
356
357struct CCmdLangPair
358{
359 unsigned CmdId_and_Flags;
360 unsigned LangId;
361};
362
363static const UInt32 k_MenuFlags_CmdMask = (1 << 7) - 1;
364static const UInt32 k_MenuFlag_Copy = 1 << 14;
365static const UInt32 k_MenuFlag_Move = 1 << 15;
366// #define IDS_CANCEL (IDCANCEL + 400)
367#define IDS_CANCEL 402
368
369static const CCmdLangPair g_Pairs[] =
370{
371 { k_Copy_Base | k_MenuFlag_Copy, IDS_COPY },
372 { k_Copy_Base | k_MenuFlag_Move, IDS_MOVE },
373 { k_Copy_ToArc | k_MenuFlag_Copy, IDS_COPY_TO },
374 // { k_Copy_ToArc | k_MenuFlag_Move, IDS_MOVE_TO }, // IDS_CONTEXT_COMPRESS_TO
375 // { k_OpenArc, IDS_CONTEXT_OPEN },
376 // { k_ExtractFiles, IDS_CONTEXT_EXTRACT },
377 // { k_ExtractHere, IDS_CONTEXT_EXTRACT_HERE },
378 // { k_TestArc, IDS_CONTEXT_TEST },
379 { k_AddToArc | k_MenuFlag_Copy, IDS_CONTEXT_COMPRESS },
380 { k_Cancel, IDS_CANCEL }
381};
382
383}
384
385
386class CDropTarget Z7_final:
387 public IDropTarget,
388 public CMyUnknownImp
389{
390 Z7_COM_UNKNOWN_IMP_1_MT(IDropTarget)
391 STDMETHOD(DragEnter)(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect) Z7_override;
392 STDMETHOD(DragOver)(DWORD keyState, POINTL pt, DWORD *effect) Z7_override;
393 STDMETHOD(DragLeave)() Z7_override;
394 STDMETHOD(Drop)(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect) Z7_override;
395
396 bool m_IsRightButton;
397 bool m_GetTransfer_WasSuccess;
398 bool m_DropIsAllowed; // = true, if data IDataObject can return CF_HDROP (so we can get list of paths)
399 bool m_PanelDropIsAllowed; // = false, if current target_panel is source_panel.
400 // check it only if m_DropIsAllowed == true
401 // we use it to show icon effect that drop is not allowed here.
402
403 CMyComPtr<IDataObject> m_DataObject; // we set it in DragEnter()
404 UStringVector m_SourcePaths;
405
406 // int m_DropHighlighted_SelectionIndex;
407 // int m_SubFolderIndex; // realIndex of item in m_Panel list (if drop cursor to that item)
408 // UString m_DropHighlighted_SubFolderName; // name of folder in m_Panel list (if drop cursor to that folder)
409
410 CPanel *m_Panel;
411 bool m_IsAppTarget; // true, if we want to drop to app window (not to panel)
412
413 bool m_TargetPath_WasSent_ToDataObject; // true, if TargetPath was sent
414 bool m_TargetPath_NonEmpty_WasSent_ToDataObject; // true, if non-empty TargetPath was sent
415 bool m_Transfer_WasSent_ToDataObject; // true, if Transfer was sent
416 UINT m_Format_7zip_SetTargetFolder;
417 UINT m_Format_7zip_SetTransfer;
418 UINT m_Format_7zip_GetTransfer;
419
420 UInt32 m_ProcessId; // for sending
421
422 bool IsItSameDrive() const;
423
424 // void Try_QueryGetData(IDataObject *dataObject);
425 void LoadNames_From_DataObject(IDataObject *dataObject);
426
427 UInt32 GetFolderType() const;
428 bool IsFsFolderPath() const;
429 DWORD GetEffect(DWORD keyState, POINTL pt, DWORD allowedEffect) const;
430 void RemoveSelection();
431 void PositionCursor(const POINTL &ptl);
432 UString GetTargetPath() const;
433 bool SendToSource_TargetPath_enable(IDataObject *dataObject, bool enablePath);
434 bool SendToSource_UInt32(IDataObject *dataObject, UINT format, UInt32 value);
435 bool SendToSource_TransferInfo(IDataObject *dataObject,
436 const CTargetTransferInfo &info);
437 void SendToSource_auto(IDataObject *dataObject,
438 const CTargetTransferInfo &info);
439 void SendToSource_Drag(CTargetTransferInfo &info)
440 {
441 SendToSource_auto(m_DataObject, info);
442 }
443
444 void ClearState();
445
446public:
447 CDropTarget();
448
449 CApp *App;
450 int SrcPanelIndex; // index of D&D source_panel
451 int TargetPanelIndex; // what panel to use as target_panel of Application
452};
453
454
455
456
457// ---------- CDataObject ----------
458
459/*
460 Some programs (like Sticky Notes in Win10) do not like
461 virtual non-existing items (files/dirs) in CF_HDROP format.
462 So we use two versions of CF_HDROP data:
463 m_hGlobal_HDROP_Pre : the list contains only destination path of temp directory.
464 That directory later will be filled with extracted items.
465 m_hGlobal_HDROP_Final : the list contains paths of all root items that
466 will be created in temp directory by archive extraction operation,
467 or the list of existing fs items, if source is filesystem directory.
468
469 The DRAWBACK: some programs (like Edge in Win10) can use names from IDataObject::GetData()
470 call that was called before IDropSource::QueryContinueDrag() where we set (UseFinalGlobal = true)
471 So such programs will use non-relevant m_hGlobal_HDROP_Pre item,
472 instead of m_hGlobal_HDROP_Final items.
473*/
39 474
40class CDataObject: 475class CDataObject Z7_final:
41 public IDataObject, 476 public IDataObject,
42 public CMyUnknownImp 477 public CMyUnknownImp
43{ 478{
479 Z7_COM_UNKNOWN_IMP_1_MT(IDataObject)
480
481 Z7_COMWF_B GetData(LPFORMATETC pformatetcIn, LPSTGMEDIUM medium) Z7_override;
482 Z7_COMWF_B GetDataHere(LPFORMATETC pformatetc, LPSTGMEDIUM medium) Z7_override;
483 Z7_COMWF_B QueryGetData(LPFORMATETC pformatetc) Z7_override;
484
485 Z7_COMWF_B GetCanonicalFormatEtc(LPFORMATETC /* pformatetc */, LPFORMATETC pformatetcOut) Z7_override
486 {
487 if (!pformatetcOut)
488 return E_INVALIDARG;
489 pformatetcOut->ptd = NULL;
490 return E_NOTIMPL;
491 }
492
493 Z7_COMWF_B SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release) Z7_override;
494 Z7_COMWF_B EnumFormatEtc(DWORD drection, LPENUMFORMATETC *enumFormatEtc) Z7_override;
495
496 Z7_COMWF_B DAdvise(FORMATETC * /* etc */, DWORD /* advf */, LPADVISESINK /* pAdvSink */, DWORD * /* pdwConnection */) Z7_override
497 { return OLE_E_ADVISENOTSUPPORTED; }
498 Z7_COMWF_B DUnadvise(DWORD /* dwConnection */) Z7_override
499 { return OLE_E_ADVISENOTSUPPORTED; }
500 Z7_COMWF_B EnumDAdvise(LPENUMSTATDATA *ppenumAdvise) Z7_override
501 {
502 if (ppenumAdvise)
503 *ppenumAdvise = NULL;
504 return OLE_E_ADVISENOTSUPPORTED;
505 }
506
507 bool m_PerformedDropEffect_WasSet;
508 bool m_LogicalPerformedDropEffect_WasSet;
509 bool m_DestDirPrefix_FromTarget_WasSet;
510public:
511 bool m_Transfer_WasSet;
44private: 512private:
513 // GetData formats (source to target):
45 FORMATETC m_Etc; 514 FORMATETC m_Etc;
46 UINT m_SetFolderFormat; 515 // UINT m_Format_FileOpFlags;
516 // UINT m_Format_PreferredDropEffect;
517
518 // SetData() formats (target to source):
519 // 7-Zip's format:
520 UINT m_Format_7zip_SetTargetFolder;
521 UINT m_Format_7zip_SetTransfer;
522 UINT m_Format_7zip_GetTransfer; // for GetData()
523
524 UINT m_Format_PerformedDropEffect;
525 UINT m_Format_LogicalPerformedDropEffect;
526 UINT m_Format_DisableDragText;
527 UINT m_Format_IsShowingLayered;
528 UINT m_Format_IsShowingText;
529 UINT m_Format_DropDescription;
530 UINT m_Format_TargetCLSID;
531
532 DWORD m_PerformedDropEffect;
533 DWORD m_LogicalPerformedDropEffect;
534
535 void CopyFromPanelTo_Folder();
536 HRESULT SetData2(const FORMATETC *formatetc, const STGMEDIUM *medium);
47 537
48public: 538public:
49 MY_UNKNOWN_IMP1_MT(IDataObject) 539 bool IsRightButton;
540 bool IsTempFiles;
50 541
51 STDMETHODIMP GetData(LPFORMATETC pformatetcIn, LPSTGMEDIUM medium); 542 bool UsePreGlobal;
52 STDMETHODIMP GetDataHere(LPFORMATETC pformatetc, LPSTGMEDIUM medium); 543 bool DoNotProcessInTarget;
53 STDMETHODIMP QueryGetData(LPFORMATETC pformatetc );
54 544
55 STDMETHODIMP GetCanonicalFormatEtc ( LPFORMATETC /* pformatetc */, LPFORMATETC pformatetcOut) 545 bool NeedCall_Copy;
56 { pformatetcOut->ptd = NULL; return ResultFromScode(E_NOTIMPL); } 546 bool Copy_WasCalled;
57 547
58 STDMETHODIMP SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release); 548 NMemory::CGlobal m_hGlobal_HDROP_Pre;
59 STDMETHODIMP EnumFormatEtc(DWORD drection, LPENUMFORMATETC *enumFormatEtc); 549 NMemory::CGlobal m_hGlobal_HDROP_Final;
550 // NMemory::CGlobal m_hGlobal_FileOpFlags;
551 // NMemory::CGlobal m_hGlobal_PreferredDropEffect;
60 552
61 STDMETHODIMP DAdvise(FORMATETC * /* etc */, DWORD /* advf */, LPADVISESINK /* pAdvSink */, DWORD * /* pdwConnection */) 553 CPanel *Panel;
62 { return OLE_E_ADVISENOTSUPPORTED; } 554 CRecordVector<UInt32> Indices;
63 STDMETHODIMP DUnadvise(DWORD /* dwConnection */) { return OLE_E_ADVISENOTSUPPORTED; }
64 STDMETHODIMP EnumDAdvise( LPENUMSTATDATA * /* ppenumAdvise */) { return OLE_E_ADVISENOTSUPPORTED; }
65 555
66 CDataObject(); 556 UString SrcDirPrefix_Temp; // FS directory with source files or Temp
557 UString DestDirPrefix_FromTarget;
558 /* destination Path that was sent by Target via SetData().
559 it can be altstreams prefix.
560 if (!DestDirPrefix_FromTarget.IsEmpty()) m_Panel->CompressDropFiles() was not called by Target.
561 So we must do drop actions in Source */
562 HRESULT Copy_HRESULT;
563 UStringVector Messages;
67 564
68 NMemory::CGlobal hGlobal; 565 CDataObject();
69 UString Path; 566public:
567 CDataObject_SetTransfer m_Transfer;
70}; 568};
71 569
570
571// for old mingw:
572#ifndef CFSTR_LOGICALPERFORMEDDROPEFFECT
573#define CFSTR_LOGICALPERFORMEDDROPEFFECT TEXT("Logical Performed DropEffect")
574#endif
575#ifndef CFSTR_TARGETCLSID
576#define CFSTR_TARGETCLSID TEXT("TargetCLSID") // HGLOBAL with a CLSID of the drop target
577#endif
578
579
580
72CDataObject::CDataObject() 581CDataObject::CDataObject()
73{ 582{
74 m_SetFolderFormat = RegisterClipboardFormat(kSvenZipSetFolderFormat); 583 // GetData formats (source to target):
584 // and we use CF_HDROP format to transfer file paths from source to target:
75 m_Etc.cfFormat = CF_HDROP; 585 m_Etc.cfFormat = CF_HDROP;
76 m_Etc.ptd = NULL; 586 m_Etc.ptd = NULL;
77 m_Etc.dwAspect = DVASPECT_CONTENT; 587 m_Etc.dwAspect = DVASPECT_CONTENT;
78 m_Etc.lindex = -1; 588 m_Etc.lindex = -1;
79 m_Etc.tymed = TYMED_HGLOBAL; 589 m_Etc.tymed = TYMED_HGLOBAL;
590
591 // m_Format_FileOpFlags = RegisterClipboardFormat(TEXT("FileOpFlags"));
592 // m_Format_PreferredDropEffect = RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); // "Preferred DropEffect"
593
594 // SetData() formats (target to source):
595 m_Format_7zip_SetTargetFolder = RegisterClipboardFormat(k_Format_7zip_SetTargetFolder);
596 m_Format_7zip_SetTransfer = RegisterClipboardFormat(k_Format_7zip_SetTransfer);
597 m_Format_7zip_GetTransfer = RegisterClipboardFormat(k_Format_7zip_GetTransfer);
598
599 m_Format_PerformedDropEffect = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT); // "Performed DropEffect"
600 m_Format_LogicalPerformedDropEffect = RegisterClipboardFormat(CFSTR_LOGICALPERFORMEDDROPEFFECT); // "Logical Performed DropEffect"
601 m_Format_DisableDragText = RegisterClipboardFormat(TEXT("DisableDragText"));
602 m_Format_IsShowingLayered = RegisterClipboardFormat(TEXT("IsShowingLayered"));
603 m_Format_IsShowingText = RegisterClipboardFormat(TEXT("IsShowingText"));
604 m_Format_DropDescription = RegisterClipboardFormat(TEXT("DropDescription"));
605 m_Format_TargetCLSID = RegisterClipboardFormat(CFSTR_TARGETCLSID);
606
607 m_PerformedDropEffect = 0;
608 m_LogicalPerformedDropEffect = 0;
609
610 m_PerformedDropEffect_WasSet = false;
611 m_LogicalPerformedDropEffect_WasSet = false;
612
613 m_DestDirPrefix_FromTarget_WasSet = false;
614 m_Transfer_WasSet = false;
615
616 IsRightButton = false;
617 IsTempFiles = false;
618
619 UsePreGlobal = false;
620 DoNotProcessInTarget = false;
621
622 NeedCall_Copy = false;
623 Copy_WasCalled = false;
624
625 Copy_HRESULT = S_OK;
80} 626}
81 627
82STDMETHODIMP CDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL /* release */) 628
629
630void CDataObject::CopyFromPanelTo_Folder()
83{ 631{
84 if (etc->cfFormat == m_SetFolderFormat 632 try
85 && etc->tymed == TYMED_HGLOBAL
86 && etc->dwAspect == DVASPECT_CONTENT
87 && medium->tymed == TYMED_HGLOBAL)
88 { 633 {
89 Path.Empty(); 634 CCopyToOptions options;
90 if (!medium->hGlobal) 635 options.folder = SrcDirPrefix_Temp;
91 return S_OK; 636 /* 15.13: fixed problem with mouse cursor for password window.
92 size_t size = GlobalSize(medium->hGlobal) / sizeof(wchar_t); 637 DoDragDrop() probably calls SetCapture() to some hidden window.
93 const wchar_t *src = (const wchar_t *)GlobalLock(medium->hGlobal); 638 But it's problem, if we show some modal window, like MessageBox.
94 if (src) 639 So we return capture to our window.
640 If you know better way to solve the problem, please notify 7-Zip developer.
641 */
642 // MessageBoxW(*Panel, L"test", L"test", 0);
643 /* HWND oldHwnd = */ SetCapture(*Panel);
644 Copy_WasCalled = true;
645 Copy_HRESULT = E_FAIL;
646 Copy_HRESULT = Panel->CopyTo(options, Indices, &Messages);
647 // do we need to restore capture?
648 // ReleaseCapture();
649 // oldHwnd = SetCapture(oldHwnd);
650 }
651 catch(...)
652 {
653 Copy_HRESULT = E_FAIL;
654 }
655}
656
657
658#ifdef SHOW_DEBUG_DRAG
659
660static void PrintFormat2(AString &s, unsigned format)
661{
662 s += " ";
663 s += "= format=";
664 s.Add_UInt32(format);
665 s += " ";
666 const int k_len = 512;
667 CHAR temp[k_len];
668 if (GetClipboardFormatNameA(format, temp, k_len) && strlen(temp) != 0)
669 s += temp;
670}
671
672static void PrintFormat(const char *title, unsigned format)
673{
674 AString s (title);
675 PrintFormat2(s, format);
676 PRF4(s);
677}
678
679static void PrintFormat_AndData(const char *title, unsigned format, const void *data, size_t size)
680{
681 AString s (title);
682 PrintFormat2(s, format);
683 s += " size=";
684 s.Add_UInt32((UInt32)size);
685 for (size_t i = 0; i < size && i < 16; i++)
686 {
687 s += " ";
688 s.Add_UInt32(((const Byte *)data)[i]);
689 }
690 PRF4(s);
691}
692
693static void PrintFormat_GUIDToStringW(const void *p)
694{
695 const GUID *guid = (const GUID *)p;
696 UString s;
697 const unsigned kSize = 48;
698 StringFromGUID2(*guid, s.GetBuf(kSize), kSize);
699 s.ReleaseBuf_CalcLen(kSize);
700 PRF3_W(s);
701}
702
703// Vista
704typedef enum
705{
706 MY_DROPIMAGE_INVALID = -1, // no image preference (use default)
707 MY_DROPIMAGE_NONE = 0, // red "no" circle
708 MY_DROPIMAGE_COPY = DROPEFFECT_COPY, // plus for copy
709 MY_DROPIMAGE_MOVE = DROPEFFECT_MOVE, // movement arrow for move
710 MY_DROPIMAGE_LINK = DROPEFFECT_LINK, // link arrow for link
711 MY_DROPIMAGE_LABEL = 6, // tag icon to indicate metadata will be changed
712 MY_DROPIMAGE_WARNING = 7, // yellow exclamation, something is amiss with the operation
713 MY_DROPIMAGE_NOIMAGE = 8 // no image at all
714} MY_DROPIMAGETYPE;
715
716typedef struct {
717 MY_DROPIMAGETYPE type;
718 WCHAR szMessage[MAX_PATH];
719 WCHAR szInsert[MAX_PATH];
720} MY_DROPDESCRIPTION;
721
722#endif
723
724
725/*
726IDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release)
727======================================================================
728
729 Main purpose of CDataObject is to transfer data from source to target
730 of drag and drop operation.
731 But also CDataObject can be used to transfer data in backward direction
732 from target to source (even if target and source are different processes).
733 There are some predefined Explorer's formats to transfer some data from target to source.
734 And 7-Zip uses 7-Zip's format k_Format_7zip_SetTargetFolder to transfer
735 destination directory path from target to source.
736
737 Our CDataObject::SetData() function here is used only to transfer data from target to source.
738 Usual source_to_target data is filled to m_hGlobal_* objects directly without SetData() calling.
739
740The main problem of SetData() is ownership of medium for (release == TRUE) case.
741
742SetData(,, release = TRUE) from different processes (DropSource and DropTarget)
743===============================================================================
744{
745 MS DOCs about (STGMEDIUM *medium) ownership:
746 The data object called does not take ownership of the data
747 until it has successfully received it and no error code is returned.
748
749 Each of processes (Source and Target) has own copy of medium allocated.
750 Windows code creates proxy IDataObject object in Target process to transferr
751 SetData() call between Target and Source processes via special proxies:
752 DropTarget ->
753 proxy_DataObject_in_Target ->
754 proxy_in_Source ->
755 DataObject_in_Source
756 when Target calls SetData() with proxy_DataObject_in_Target,
757 the system and proxy_in_Source
758 - allocates proxy-medium-in-Source process
759 - copies medium data from Target to that proxy-medium-in-Source
760 - sends proxy-medium-in-Source to DataObject_in_Source->SetData().
761
762 after returning from SetData() to Target process:
763 Win10 proxy_DataObject_in_Target releases original medium in Target process,
764 only if SetData() in Source returns S_OK. It's consistent with DOCs above.
765
766 for unsupported cfFormat:
767 [DropSource is 7-Zip 22.01 (old) : (etc->cfFormat != m_Format_7zip_SetTargetFolder && release == TRUE)]
768 (DropSource is WinRAR case):
769 Source doesn't release medium and returns error (for example, E_NOTIMPL)
770 {
771 Then Win10 proxy_in_Source also doesn't release proxy-medium-in-Source.
772 So there is memory leak in Source process.
773 Probably Win10 proxy_in_Source tries to avoid possible double releasing
774 that can be more fatal than memory leak.
775
776 Then Win10 proxy_DataObject_in_Target also doesn't release
777 original medium, that was allocated by DropTarget.
778 So if DropTarget also doesn't release medium, there is memory leak in
779 DropTarget process too.
780 DropTarget is Win10-Explorer probably doesn't release medium in that case.
781 }
782
783 [DropSource is 7-Zip 22.01 (old) : (etc->cfFormat == m_Format_7zip_SetTargetFolder && release == TRUE)]
784 DropSource returns S_OK and doesn't release medium:
785 {
786 then there is memory leak in DropSource process only.
787 }
788
789 (DropSource is 7-Zip v23 (new)):
790 (DropSource is Win10-Explorer case)
791 {
792 Win10-Explorer-DropSource probably always releases medium,
793 and then it always returns S_OK.
794 So Win10 proxy_DataObject_in_Target also releases
795 original medium, that was allocated by DropTarget.
796 So there is no memory leak in Source and Target processes.
797 }
798
799 if (DropTarget is Win10-Explorer)
800 {
801 Explorer Target uses SetData(,, (release = TRUE)) and
802 Explorer Target probably doesn't free memory after SetData(),
803 even if SetData(,, (release = TRUE)) returns E_NOTIMPL;
804 }
805
806 if (DropSource is Win10-Explorer)
807 {
808 (release == FALSE) doesn't work, and SetData() returns E_NOTIMPL;
809 (release == TRUE) works, and SetData() returns S_OK, and
810 it returns S_OK even for formats unsupported by Explorer.
811 }
812
813 To be more compatible with DOCs and Win10-Explorer and to avoid memory leaks,
814 we use the following scheme for our IDataObject::SetData(,, release == TRUE)
815 in DropSource code:
816 if (release == TRUE) { our SetData() always releases medium
817 with ReleaseStgMedium() and returns S_OK; }
818 The DRAWBACK of that scheme:
819 The caller always receives S_OK,
820 so the caller doesn't know about any error in SetData() in that case.
821
822for 7zip-Target to 7zip-Source calls:
823 we use (release == FALSE)
824 So we avoid (release == TRUE) memory leak problems,
825 and we can get real return code from SetData().
826
827for 7zip-Target to Explorer-Source calls:
828 we use (release == TRUE).
829 beacuse Explorer-Source doesn't accept (release == FALSE).
830}
831*/
832
833/*
834https://github.com/MicrosoftDocs/win32/blob/docs/desktop-src/shell/datascenarios.md
835CFSTR_PERFORMEDDROPEFFECT:
836 is used by the target to inform the data object through its
837 IDataObject::SetData method of the outcome of a data transfer.
838CFSTR_PREFERREDDROPEFFECT:
839 is used by the source to specify whether its preferred method of data transfer is move or copy.
840*/
841
842Z7_COMWF_B CDataObject::SetData(LPFORMATETC etc, STGMEDIUM *medium, BOOL release)
843{
844 try {
845 const HRESULT hres = SetData2(etc, medium);
846 // PrintFormat(release ? "SetData RELEASE=TRUE" : "SetData RELEASE=FALSE" , etc->cfFormat);
847 if (release)
848 {
849 /*
850 const DWORD tymed = medium->tymed;
851 IUnknown *pUnkForRelease = medium->pUnkForRelease;
852 */
853 // medium->tymed = NULL; // for debug
854 // return E_NOTIMPL; // for debug
855 ReleaseStgMedium(medium);
856 /* ReleaseStgMedium() will change STGMEDIUM::tymed to (TYMED_NULL = 0).
857 but we also can clear (medium.hGlobal = NULL),
858 to prevent some incorrect releasing, if the caller will try to release the data */
859 /*
860 if (medium->tymed == TYMED_NULL && tymed == TYMED_HGLOBAL && !pUnkForRelease)
861 medium->hGlobal = NULL;
862 */
863 // do we need return S_OK; for (tymed != TYMED_HGLOBAL) cases ?
864 /* we return S_OK here to shows that we take ownership of the data in (medium),
865 so the caller will not try to release (medium) */
866 return S_OK; // to be more compatible with Win10-Explorer and DOCs.
867 }
868 return hres;
869 } catch(...) { return E_FAIL; }
870}
871
872
873
874HRESULT CDataObject::SetData2(const FORMATETC *etc, const STGMEDIUM *medium)
875{
876 // PRF3("== CDataObject::SetData()");
877
878 HRESULT hres = S_OK;
879
880 if (etc->cfFormat == 0)
881 return DV_E_FORMATETC;
882 if (etc->tymed != TYMED_HGLOBAL)
883 return E_NOTIMPL; // DV_E_TYMED;
884 if (etc->dwAspect != DVASPECT_CONTENT)
885 return E_NOTIMPL; // DV_E_DVASPECT;
886 if (medium->tymed != TYMED_HGLOBAL)
887 return E_NOTIMPL; // DV_E_TYMED;
888
889 if (!medium->hGlobal)
890 return S_OK;
891
892 if (etc->cfFormat == m_Format_7zip_SetTargetFolder)
893 {
894 DestDirPrefix_FromTarget.Empty();
895 m_DestDirPrefix_FromTarget_WasSet = true;
896 }
897 else if (etc->cfFormat == m_Format_7zip_SetTransfer)
898 m_Transfer_WasSet = false;
899
900 const size_t size = GlobalSize(medium->hGlobal);
901 // GlobalLock() can return NULL, if memory block has a zero size
902 if (size == 0)
903 return S_OK;
904 const void *src = (const Byte *)GlobalLock(medium->hGlobal);
905 if (!src)
906 return E_FAIL;
907
908 PRF_(PrintFormat_AndData("SetData", etc->cfFormat, src, size))
909
910 if (etc->cfFormat == m_Format_7zip_SetTargetFolder)
911 {
912 /* this is our registered k_Format_7zip_SetTargetFolder format.
913 so it's call from 7-zip's CDropTarget */
914 /* 7-zip's CDropTarget calls SetData() for m_Format_7zip_SetTargetFolder
915 with (release == FALSE) */
916 const size_t num = size / sizeof(wchar_t);
917 if (size != num * sizeof(wchar_t))
918 return E_FAIL;
919 // if (num == 0) return S_OK;
920 // GlobalLock() can return NULL, if memory block has a zero-byte size
921 const wchar_t *s = (const wchar_t *)src;
922 UString &dest = DestDirPrefix_FromTarget;
923 for (size_t i = 0; i < num; i++)
924 {
925 const wchar_t c = s[i];
926 if (c == 0)
927 break;
928 dest += c;
929 }
930 // PRF_(PrintFormat_AndData("SetData", etc->cfFormat, src, size))
931 PRF3_W(DestDirPrefix_FromTarget);
932 }
933 else if (etc->cfFormat == m_Format_7zip_SetTransfer)
934 {
935 /* 7-zip's CDropTarget calls SetData() for m_Format_7zip_SetTransfer
936 with (release == FALSE) */
937 if (size < sizeof(CDataObject_SetTransfer))
938 return E_FAIL;
939 const CDataObject_SetTransfer *t = (const CDataObject_SetTransfer *)src;
940 if (!t->Check())
941 return E_FAIL;
942 m_Transfer = *t;
943 if (t->Target.FuncType != k_DragTargetMode_Leave)
944 m_Transfer_WasSet = true;
945 bool needProcessBySource = !DestDirPrefix_FromTarget.IsEmpty();
946 if (t->Target.FuncType == k_DragTargetMode_Drop_Begin)
947 {
948 if (t->Target.Cmd_Type != NDragMenu::k_Copy_Base
949 // || t->Target.Cmd_Effect != DROPEFFECT_COPY
950 )
951 needProcessBySource = false;
952 }
953 if (t->Target.FuncType == k_DragTargetMode_Drop_End)
95 { 954 {
96 for (size_t i = 0; i < size; i++) 955 if (t->Target.Flags & k_TargetFlags_MustBeProcessedBySource)
956 needProcessBySource = true;
957 else if (t->Target.Flags & k_TargetFlags_WasProcessed)
958 needProcessBySource = false;
959 }
960 DoNotProcessInTarget = needProcessBySource;
961 }
962 else
963 {
964 // SetData() from Explorer Target:
965 if (etc->cfFormat == m_Format_PerformedDropEffect)
966 {
967 m_PerformedDropEffect_WasSet = false;
968 if (size == sizeof(DWORD))
97 { 969 {
98 wchar_t c = src[i]; 970 m_PerformedDropEffect = *(const DWORD *)src;
99 if (c == 0) 971 m_PerformedDropEffect_WasSet = true;
100 break; 972 }
101 Path += c; 973 }
974 else if (etc->cfFormat == m_Format_LogicalPerformedDropEffect)
975 {
976 m_LogicalPerformedDropEffect_WasSet = false;
977 if (size == sizeof(DWORD))
978 {
979 m_LogicalPerformedDropEffect = *(const DWORD *)src;
980 m_LogicalPerformedDropEffect_WasSet = true;
102 } 981 }
103 GlobalUnlock(medium->hGlobal);
104 return S_OK;
105 } 982 }
983 else if (etc->cfFormat == m_Format_DropDescription)
984 {
985 // drop description contains only name of dest folder without full path
986 #ifdef SHOW_DEBUG_DRAG
987 if (size == sizeof(MY_DROPDESCRIPTION))
988 {
989 // const MY_DROPDESCRIPTION *s = (const MY_DROPDESCRIPTION *)src;
990 // PRF3_W(s->szMessage);
991 // PRF3_W(s->szInsert);
992 }
993 #endif
994 }
995 else if (etc->cfFormat == m_Format_TargetCLSID)
996 {
997 // it's called after call QueryContinueDrag() (keyState & MK_LBUTTON) == 0
998 // Shell File System Folder (explorer) guid: F3364BA0-65B9-11CE-A9BA-00AA004AE837
999 #ifdef SHOW_DEBUG_DRAG
1000 if (size == 16)
1001 {
1002 PrintFormat_GUIDToStringW((const Byte *)src);
1003 }
1004 #endif
1005 }
1006 else if (etc->cfFormat == m_Format_DisableDragText)
1007 {
1008 // (size == 4) (UInt32 value)
1009 // value==0 : if drag to folder item or folder
1010 // value==1 : if drag to file or non list_view */
1011 }
1012 else if (
1013 etc->cfFormat == m_Format_IsShowingLayered ||
1014 etc->cfFormat == m_Format_IsShowingText)
1015 {
1016 // (size == 4) (UInt32 value) value==0 :
1017 }
1018 else
1019 hres = DV_E_FORMATETC;
1020 // hres = E_NOTIMPL; // for debug
1021 // hres = DV_E_FORMATETC; // for debug
106 } 1022 }
107 return E_NOTIMPL; 1023
1024 GlobalUnlock(medium->hGlobal);
1025 return hres;
108} 1026}
109 1027
1028
1029
110static HGLOBAL DuplicateGlobalMem(HGLOBAL srcGlobal) 1030static HGLOBAL DuplicateGlobalMem(HGLOBAL srcGlobal)
111{ 1031{
112 SIZE_T size = GlobalSize(srcGlobal); 1032 /* GlobalSize() returns 0: If the specified handle
1033 is not valid or if the object has been discarded */
1034 const SIZE_T size = GlobalSize(srcGlobal);
1035 if (size == 0)
1036 return NULL;
1037 // GlobalLock() can return NULL, if memory block has a zero-byte size
113 const void *src = GlobalLock(srcGlobal); 1038 const void *src = GlobalLock(srcGlobal);
114 if (!src) 1039 if (!src)
115 return 0; 1040 return NULL;
116 HGLOBAL destGlobal = GlobalAlloc(GHND | GMEM_SHARE, size); 1041 HGLOBAL destGlobal = GlobalAlloc(GHND | GMEM_SHARE, size);
117 if (destGlobal) 1042 if (destGlobal)
118 { 1043 {
@@ -120,7 +1045,7 @@ static HGLOBAL DuplicateGlobalMem(HGLOBAL srcGlobal)
120 if (!dest) 1045 if (!dest)
121 { 1046 {
122 GlobalFree(destGlobal); 1047 GlobalFree(destGlobal);
123 destGlobal = 0; 1048 destGlobal = NULL;
124 } 1049 }
125 else 1050 else
126 { 1051 {
@@ -132,118 +1057,370 @@ static HGLOBAL DuplicateGlobalMem(HGLOBAL srcGlobal)
132 return destGlobal; 1057 return destGlobal;
133} 1058}
134 1059
135STDMETHODIMP CDataObject::GetData(LPFORMATETC etc, LPSTGMEDIUM medium) 1060
1061static bool Medium_CopyFrom(LPSTGMEDIUM medium, const void *data, size_t size)
136{ 1062{
137 RINOK(QueryGetData(etc)); 1063 medium->tymed = TYMED_NULL;
1064 medium->pUnkForRelease = NULL;
1065 medium->hGlobal = NULL;
1066 const HGLOBAL global = GlobalAlloc(GHND | GMEM_SHARE, size);
1067 if (!global)
1068 return false;
1069 void *dest = GlobalLock(global);
1070 if (!dest)
1071 {
1072 GlobalFree(global);
1073 return false;
1074 }
1075 memcpy(dest, data, size);
1076 GlobalUnlock(global);
1077 medium->hGlobal = global;
1078 medium->tymed = TYMED_HGLOBAL;
1079 return true;
1080}
1081
1082
1083Z7_COMWF_B CDataObject::GetData(LPFORMATETC etc, LPSTGMEDIUM medium)
1084{
1085 try {
1086 PRF_(PrintFormat("-- GetData", etc->cfFormat))
1087
1088 medium->tymed = TYMED_NULL;
1089 medium->pUnkForRelease = NULL;
1090 medium->hGlobal = NULL;
1091
1092 if (NeedCall_Copy && !Copy_WasCalled)
1093 CopyFromPanelTo_Folder();
1094
1095 // PRF3("+ CDataObject::GetData");
1096 // PrintFormat(etc->cfFormat);
1097 HGLOBAL global;
1098 RINOK(QueryGetData(etc))
1099
1100 /*
1101 if (etc->cfFormat == m_Format_FileOpFlags)
1102 global = m_hGlobal_FileOpFlags;
1103 else if (etc->cfFormat == m_Format_PreferredDropEffect)
1104 {
1105 // Explorer requests PreferredDropEffect only if Move/Copy selection is possible:
1106 // Shift is not pressed and Ctrl is not pressed
1107 PRF3("------ CDataObject::GetData() PreferredDropEffect");
1108 global = m_hGlobal_PreferredDropEffect;
1109 }
1110 else
1111 */
1112 if (etc->cfFormat == m_Etc.cfFormat) // CF_HDROP
1113 global = UsePreGlobal ? m_hGlobal_HDROP_Pre : m_hGlobal_HDROP_Final;
1114 else if (etc->cfFormat == m_Format_7zip_GetTransfer)
1115 {
1116 CDataObject_GetTransfer transfer;
1117 if (m_DestDirPrefix_FromTarget_WasSet)
1118 {
1119 transfer.Flags |= k_SourceFlags_SetTargetFolder;
1120 }
1121 if (!DestDirPrefix_FromTarget.IsEmpty())
1122 {
1123 transfer.Flags |= k_SourceFlags_SetTargetFolder_NonEmpty;
1124 }
1125 if (IsTempFiles)
1126 {
1127 transfer.Flags |= k_SourceFlags_TempFiles;
1128 transfer.Flags |= k_SourceFlags_WaitFinish;
1129 transfer.Flags |= k_SourceFlags_NeedExtractOpToFs;
1130 if (UsePreGlobal)
1131 transfer.Flags |= k_SourceFlags_NamesAreParent;
1132 }
1133 else
1134 transfer.Flags |= k_SourceFlags_DoNotWaitFinish;
1135
1136 if (IsRightButton)
1137 transfer.Flags |= k_SourceFlags_RightButton;
1138 else
1139 transfer.Flags |= k_SourceFlags_LeftButton;
1140
1141 if (DoNotProcessInTarget)
1142 transfer.Flags |= k_SourceFlags_DoNotProcessInTarget;
1143 if (Copy_WasCalled)
1144 transfer.Flags |= k_SourceFlags_Copy_WasCalled;
1145
1146 if (Medium_CopyFrom(medium, &transfer, sizeof(transfer)))
1147 return S_OK;
1148 return E_OUTOFMEMORY;
1149 }
1150 else
1151 return DV_E_FORMATETC;
1152
1153 if (!global)
1154 return DV_E_FORMATETC;
138 medium->tymed = m_Etc.tymed; 1155 medium->tymed = m_Etc.tymed;
139 medium->pUnkForRelease = 0; 1156 medium->hGlobal = DuplicateGlobalMem(global);
140 medium->hGlobal = DuplicateGlobalMem(hGlobal);
141 if (!medium->hGlobal) 1157 if (!medium->hGlobal)
142 return E_OUTOFMEMORY; 1158 return E_OUTOFMEMORY;
143 return S_OK; 1159 return S_OK;
1160 } catch(...) { return E_FAIL; }
144} 1161}
145 1162
146STDMETHODIMP CDataObject::GetDataHere(LPFORMATETC /* etc */, LPSTGMEDIUM /* medium */) 1163Z7_COMWF_B CDataObject::GetDataHere(LPFORMATETC /* etc */, LPSTGMEDIUM /* medium */)
147{ 1164{
1165 PRF3("CDataObject::GetDataHere()");
148 // Seems Windows doesn't call it, so we will not implement it. 1166 // Seems Windows doesn't call it, so we will not implement it.
149 return E_UNEXPECTED; 1167 return E_UNEXPECTED;
150} 1168}
151 1169
152 1170
153STDMETHODIMP CDataObject::QueryGetData(LPFORMATETC etc) 1171/*
1172 IDataObject::QueryGetData() Determines whether the data object is capable of
1173 rendering the data as specified. Objects attempting a paste or drop
1174 operation can call this method before calling IDataObject::GetData
1175 to get an indication of whether the operation may be successful.
1176
1177 The client of a data object calls QueryGetData to determine whether
1178 passing the specified FORMATETC structure to a subsequent call to
1179 IDataObject::GetData is likely to be successful.
1180
1181 we check Try_QueryGetData with CF_HDROP
1182*/
1183
1184Z7_COMWF_B CDataObject::QueryGetData(LPFORMATETC etc)
154{ 1185{
155 if ((m_Etc.tymed & etc->tymed) && 1186 PRF3("-- CDataObject::QueryGetData()");
156 m_Etc.cfFormat == etc->cfFormat && 1187 if ( etc->cfFormat == m_Etc.cfFormat // CF_HDROP
157 m_Etc.dwAspect == etc->dwAspect) 1188 || etc->cfFormat == m_Format_7zip_GetTransfer
158 return S_OK; 1189 // || (etc->cfFormat == m_Format_FileOpFlags && (HGLOBAL)m_hGlobal_FileOpFlags)
159 return DV_E_FORMATETC; 1190 // || (etc->cfFormat == m_Format_PreferredDropEffect && (HGLOBAL)m_hGlobal_PreferredDropEffect)
1191 )
1192 {
1193 }
1194 else
1195 return DV_E_FORMATETC;
1196 if (etc->dwAspect != m_Etc.dwAspect)
1197 return DV_E_DVASPECT;
1198 /* GetData(): It is possible to specify more than one medium by using the Boolean OR
1199 operator, allowing the method to choose the best medium among those specified. */
1200 if ((etc->tymed & m_Etc.tymed) == 0)
1201 return DV_E_TYMED;
1202 return S_OK;
160} 1203}
161 1204
162STDMETHODIMP CDataObject::EnumFormatEtc(DWORD direction, LPENUMFORMATETC FAR* enumFormatEtc) 1205Z7_COMWF_B CDataObject::EnumFormatEtc(DWORD direction, LPENUMFORMATETC FAR* enumFormatEtc)
163{ 1206{
1207 // we don't enumerate for DATADIR_SET. Seems it can work without it.
164 if (direction != DATADIR_GET) 1208 if (direction != DATADIR_GET)
165 return E_NOTIMPL; 1209 return E_NOTIMPL;
1210 // we don't enumerate for m_Format_FileOpFlags also. Seems it can work without it.
166 return CreateEnumFormatEtc(1, &m_Etc, enumFormatEtc); 1211 return CreateEnumFormatEtc(1, &m_Etc, enumFormatEtc);
167} 1212}
168 1213
1214
1215
169//////////////////////////////////////////////////////// 1216////////////////////////////////////////////////////////
170 1217
171class CDropSource: 1218class CDropSource Z7_final:
172 public IDropSource, 1219 public IDropSource,
173 public CMyUnknownImp 1220 public CMyUnknownImp
174{ 1221{
1222 Z7_COM_UNKNOWN_IMP_1_MT(IDropSource)
1223 STDMETHOD(QueryContinueDrag)(BOOL escapePressed, DWORD keyState) Z7_override;
1224 STDMETHOD(GiveFeedback)(DWORD effect) Z7_override;
1225
175 DWORD m_Effect; 1226 DWORD m_Effect;
176public: 1227public:
177 MY_UNKNOWN_IMP1_MT(IDropSource)
178 STDMETHOD(QueryContinueDrag)(BOOL escapePressed, DWORD keyState);
179 STDMETHOD(GiveFeedback)(DWORD effect);
180
181
182 bool NeedExtract;
183 CPanel *Panel;
184 CRecordVector<UInt32> Indices;
185 UString Folder;
186 CDataObject *DataObjectSpec; 1228 CDataObject *DataObjectSpec;
187 CMyComPtr<IDataObject> DataObject; 1229 CMyComPtr<IDataObject> DataObject;
188 1230
189 bool NeedPostCopy; 1231 HRESULT DragProcessing_HRESULT;
190 HRESULT Result; 1232 bool DragProcessing_WasFinished;
191 UStringVector Messages; 1233
192 1234 CDropSource():
193 CDropSource(): m_Effect(DROPEFFECT_NONE), Panel(NULL), NeedPostCopy(false), Result(S_OK) {} 1235 m_Effect(DROPEFFECT_NONE),
1236 // Panel(NULL),
1237 DragProcessing_HRESULT(S_OK),
1238 DragProcessing_WasFinished(false)
1239 {}
194}; 1240};
195 1241
196STDMETHODIMP CDropSource::QueryContinueDrag(BOOL escapePressed, DWORD keyState) 1242// static bool g_Debug = 0;
1243
1244
1245Z7_COMWF_B CDropSource::QueryContinueDrag(BOOL escapePressed, DWORD keyState)
197{ 1246{
198 if (escapePressed == TRUE) 1247 // try {
199 return DRAGDROP_S_CANCEL; 1248
1249 /* Determines whether a drag-and-drop operation should be continued, canceled, or completed.
1250 escapePressed : Indicates whether the Esc key has been pressed
1251 since the previous call to QueryContinueDrag
1252 or to DoDragDrop if this is the first call to QueryContinueDrag:
1253 TRUE : the end user has pressed the escape key;
1254 FALSE : it has not been pressed.
1255 keyState : The current state of the keyboard modifier keys on the keyboard.
1256 Possible values can be a combination of any of the flags:
1257 MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.
1258 */
1259 #ifdef SHOW_DEBUG_DRAG
1260 {
1261 AString s ("CDropSource::QueryContinueDrag()");
1262 s.Add_Space();
1263 s += "keystate=";
1264 s.Add_UInt32(keyState);
1265 PRF4(s);
1266 }
1267 #endif
1268
1269 /*
200 if ((keyState & MK_LBUTTON) == 0) 1270 if ((keyState & MK_LBUTTON) == 0)
201 { 1271 {
202 if (m_Effect == DROPEFFECT_NONE) 1272 // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) == 0");
203 return DRAGDROP_S_CANCEL; 1273 g_Debug = true;
204 Result = S_OK; 1274 }
205 bool needExtract = NeedExtract; 1275 else
206 // MoveMode = (((keyState & MK_SHIFT) != 0) && MoveIsAllowed); 1276 {
207 if (!DataObjectSpec->Path.IsEmpty()) 1277 // PRF4("CDropSource::QueryContinueDrag() (keyState & MK_LBUTTON) != 0");
208 { 1278 }
209 needExtract = false; 1279 */
210 NeedPostCopy = true;
211 }
212 if (needExtract)
213 {
214 CCopyToOptions options;
215 options.folder = Folder;
216 1280
217 // 15.13: fixed problem with mouse cursor for password window. 1281 if (escapePressed)
218 // DoDragDrop() probably calls SetCapture() to some hidden window. 1282 {
219 // But it's problem, if we show some modal window, like MessageBox. 1283 // The drag operation should be canceled with no drop operation occurring.
220 // So we return capture to our window. 1284 DragProcessing_WasFinished = true;
221 // If you know better way to solve the problem, please notify 7-Zip developer. 1285 DragProcessing_HRESULT = DRAGDROP_S_CANCEL;
222 1286 return DRAGDROP_S_CANCEL;
223 // MessageBoxW(*Panel, L"test", L"test", 0); 1287 }
224 1288
225 /* HWND oldHwnd = */ SetCapture(*Panel); 1289 if (DragProcessing_WasFinished)
1290 return DragProcessing_HRESULT;
226 1291
227 Result = Panel->CopyTo(options, Indices, &Messages); 1292 if ((keyState & MK_RBUTTON) != 0)
1293 {
1294 if (!DataObjectSpec->IsRightButton)
1295 {
1296 DragProcessing_WasFinished = true;
1297 DragProcessing_HRESULT = DRAGDROP_S_CANCEL;
1298 return DRAGDROP_S_CANCEL;
1299 }
1300 return S_OK;
1301 }
1302
1303 if ((keyState & MK_LBUTTON) != 0)
1304 {
1305 if (DataObjectSpec->IsRightButton)
1306 {
1307 DragProcessing_WasFinished = true;
1308 DragProcessing_HRESULT = DRAGDROP_S_CANCEL;
1309 return DRAGDROP_S_CANCEL;
1310 }
1311 /* The drag operation should continue. This result occurs if no errors are detected,
1312 the mouse button starting the drag-and-drop operation has not been released,
1313 and the Esc key has not been detected. */
1314 return S_OK;
1315 }
1316 {
1317 // the mouse button starting the drag-and-drop operation has been released.
1318
1319 /* Win10 probably calls DragOver()/GiveFeedback() just before LBUTTON releasing.
1320 so m_Effect is effect returned by DropTarget::DragOver()
1321 just before LBUTTON releasing.
1322 So here we can use Effect sent to last GiveFeedback() */
228 1323
229 // do we need to restore capture? 1324 if (m_Effect == DROPEFFECT_NONE)
230 // ReleaseCapture(); 1325 {
231 // oldHwnd = SetCapture(oldHwnd); 1326 DragProcessing_WasFinished = true;
1327 DragProcessing_HRESULT = DRAGDROP_S_CANCEL;
1328 // Drop target cannot accept the data. So we cancel drag and drop
1329 // maybe return DRAGDROP_S_DROP also OK here ?
1330 // return DRAGDROP_S_DROP; // for debug
1331 return DRAGDROP_S_CANCEL;
1332 }
232 1333
233 if (Result != S_OK || !Messages.IsEmpty()) 1334 // we switch to real names for items that will be created in temp folder
234 return DRAGDROP_S_CANCEL; 1335 DataObjectSpec->UsePreGlobal = false;
1336 DataObjectSpec->Copy_HRESULT = S_OK;
1337 // MoveMode = (((keyState & MK_SHIFT) != 0) && MoveIsAllowed);
1338 /*
1339 if (DataObjectSpec->IsRightButton)
1340 return DRAGDROP_S_DROP;
1341 */
1342
1343 if (DataObjectSpec->IsTempFiles)
1344 {
1345 if (!DataObjectSpec->DestDirPrefix_FromTarget.IsEmpty())
1346 {
1347 /* we know the destination Path.
1348 So we can copy or extract items later in Source with simpler code. */
1349 DataObjectSpec->DoNotProcessInTarget = true;
1350 // return DRAGDROP_S_CANCEL;
1351 }
1352 else
1353 {
1354 DataObjectSpec->NeedCall_Copy = true;
1355 /*
1356 if (Copy_HRESULT != S_OK || !Messages.IsEmpty())
1357 {
1358 DragProcessing_WasFinished = true;
1359 DragProcessing_HRESULT = DRAGDROP_S_CANCEL;
1360 return DRAGDROP_S_CANCEL;
1361 }
1362 */
1363 }
235 } 1364 }
1365 DragProcessing_HRESULT = DRAGDROP_S_DROP;
1366 DragProcessing_WasFinished = true;
236 return DRAGDROP_S_DROP; 1367 return DRAGDROP_S_DROP;
237 } 1368 }
238 return S_OK; 1369 // } catch(...) { return E_FAIL; }
239} 1370}
240 1371
241STDMETHODIMP CDropSource::GiveFeedback(DWORD effect) 1372
1373Z7_COMWF_B CDropSource::GiveFeedback(DWORD effect)
242{ 1374{
1375 // PRF3("CDropSource::GiveFeedback");
1376 /* Enables a source application to give visual feedback to the end user
1377 during a drag-and-drop operation by providing the DoDragDrop function
1378 with an enumeration value specifying the visual effect.
1379 in (effect):
1380 The DROPEFFECT value returned by the most recent call to
1381 IDropTarget::DragEnter,
1382 IDropTarget::DragOver,
1383 or DROPEFFECT_NONE after IDropTarget::DragLeave.
1384 0: DROPEFFECT_NONE
1385 1: DROPEFFECT_COPY
1386 2: DROPEFFECT_MOVE
1387 4: DROPEFFECT_LINK
1388 0x80000000: DROPEFFECT_SCROLL
1389 The dwEffect parameter can include DROPEFFECT_SCROLL, indicating that the
1390 source should put up the drag-scrolling variation of the appropriate pointer.
1391 */
243 m_Effect = effect; 1392 m_Effect = effect;
1393
1394 #ifdef SHOW_DEBUG_DRAG
1395 AString w ("GiveFeedback effect=");
1396 if (effect & DROPEFFECT_SCROLL)
1397 w += " SCROLL ";
1398 w.Add_UInt32(effect & ~DROPEFFECT_SCROLL);
1399 // if (g_Debug)
1400 PRF4(w);
1401 #endif
1402
1403 /* S_OK : no special drag and drop cursors.
1404 Maybe it's for case where we created custom custom cursors.
1405 DRAGDROP_S_USEDEFAULTCURSORS: Indicates successful completion of the method,
1406 and requests OLE to update the cursor using the OLE-provided default cursors. */
1407 // return S_OK; // for debug
244 return DRAGDROP_S_USEDEFAULTCURSORS; 1408 return DRAGDROP_S_USEDEFAULTCURSORS;
245} 1409}
246 1410
1411
1412
1413/*
1414static bool Global_SetUInt32(NMemory::CGlobal &hg, const UInt32 v)
1415{
1416 if (!hg.Alloc(GHND | GMEM_SHARE, sizeof(v)))
1417 return false;
1418 NMemory::CGlobalLock dropLock(hg);
1419 *(UInt32 *)dropLock.GetPointer() = v;
1420 return true;
1421}
1422*/
1423
247static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &names) 1424static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &names)
248{ 1425{
249 size_t totalLen = 1; 1426 size_t totalLen = 1;
@@ -255,14 +1432,14 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na
255 unsigned i; 1432 unsigned i;
256 for (i = 0; i < names.Size(); i++) 1433 for (i = 0; i < names.Size(); i++)
257 namesA.Add(GetSystemString(names[i])); 1434 namesA.Add(GetSystemString(names[i]));
258 for (i = 0; i < names.Size(); i++) 1435 for (i = 0; i < namesA.Size(); i++)
259 totalLen += namesA[i].Len() + 1; 1436 totalLen += namesA[i].Len() + 1;
260 1437
261 if (!hgDrop.Alloc(GHND | GMEM_SHARE, totalLen * sizeof(CHAR) + sizeof(DROPFILES))) 1438 if (!hgDrop.Alloc(GHND | GMEM_SHARE, totalLen * sizeof(CHAR) + sizeof(DROPFILES)))
262 return false; 1439 return false;
263 1440
264 NMemory::CGlobalLock dropLock(hgDrop); 1441 NMemory::CGlobalLock dropLock(hgDrop);
265 DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); 1442 DROPFILES *dropFiles = (DROPFILES *)dropLock.GetPointer();
266 if (!dropFiles) 1443 if (!dropFiles)
267 return false; 1444 return false;
268 dropFiles->fNC = FALSE; 1445 dropFiles->fNC = FALSE;
@@ -270,11 +1447,11 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na
270 dropFiles->pt.y = 0; 1447 dropFiles->pt.y = 0;
271 dropFiles->pFiles = sizeof(DROPFILES); 1448 dropFiles->pFiles = sizeof(DROPFILES);
272 dropFiles->fWide = FALSE; 1449 dropFiles->fWide = FALSE;
273 CHAR *p = (CHAR *)((BYTE *)dropFiles + sizeof(DROPFILES)); 1450 CHAR *p = (CHAR *) (void *) ((BYTE *)dropFiles + sizeof(DROPFILES));
274 for (i = 0; i < names.Size(); i++) 1451 for (i = 0; i < namesA.Size(); i++)
275 { 1452 {
276 const AString &s = namesA[i]; 1453 const AString &s = namesA[i];
277 unsigned fullLen = s.Len() + 1; 1454 const unsigned fullLen = s.Len() + 1;
278 MyStringCopy(p, (const char *)s); 1455 MyStringCopy(p, (const char *)s);
279 p += fullLen; 1456 p += fullLen;
280 totalLen -= fullLen; 1457 totalLen -= fullLen;
@@ -292,9 +1469,13 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na
292 return false; 1469 return false;
293 1470
294 NMemory::CGlobalLock dropLock(hgDrop); 1471 NMemory::CGlobalLock dropLock(hgDrop);
295 DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); 1472 DROPFILES *dropFiles = (DROPFILES *)dropLock.GetPointer();
296 if (!dropFiles) 1473 if (!dropFiles)
297 return false; 1474 return false;
1475 /* fNC:
1476 TRUE : pt specifies the screen coordinates of a point in a window's nonclient area.
1477 FALSE : pt specifies the client coordinates of a point in the client area.
1478 */
298 dropFiles->fNC = FALSE; 1479 dropFiles->fNC = FALSE;
299 dropFiles->pt.x = 0; 1480 dropFiles->pt.x = 0;
300 dropFiles->pt.y = 0; 1481 dropFiles->pt.y = 0;
@@ -304,38 +1485,74 @@ static bool CopyNamesToHGlobal(NMemory::CGlobal &hgDrop, const UStringVector &na
304 for (i = 0; i < names.Size(); i++) 1485 for (i = 0; i < names.Size(); i++)
305 { 1486 {
306 const UString &s = names[i]; 1487 const UString &s = names[i];
307 unsigned fullLen = s.Len() + 1; 1488 const unsigned fullLen = s.Len() + 1;
308 MyStringCopy(p, (const WCHAR *)s); 1489 MyStringCopy(p, (const WCHAR *)s);
309 p += fullLen; 1490 p += fullLen;
310 totalLen -= fullLen; 1491 totalLen -= fullLen;
311 } 1492 }
312 *p = 0; 1493 *p = 0;
313 } 1494 }
1495 // if (totalLen != 1) return false;
314 return true; 1496 return true;
315} 1497}
316 1498
317void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */) 1499
1500void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */, bool isRightButton)
318{ 1501{
1502 PRF("CPanel::OnDrag");
319 if (!DoesItSupportOperations()) 1503 if (!DoesItSupportOperations())
320 return; 1504 return;
321 1505
322 CDisableTimerProcessing disableTimerProcessing2(*this); 1506 CDisableTimerProcessing disableTimerProcessing2(*this);
323 1507
324 CRecordVector<UInt32> indices; 1508 CRecordVector<UInt32> indices;
325 GetOperatedItemIndices(indices); 1509 Get_ItemIndices_Operated(indices);
326 if (indices.Size() == 0) 1510 if (indices.Size() == 0)
327 return; 1511 return;
328 1512
329 // CSelectedState selState; 1513 // CSelectedState selState;
330 // SaveSelectedState(selState); 1514 // SaveSelectedState(selState);
331 1515
332 // FString dirPrefix2; 1516 const bool isFSFolder = IsFSFolder();
333 FString dirPrefix; 1517 // why we don't allow drag with rightButton from archive?
1518 if (!isFSFolder && isRightButton)
1519 return;
1520
1521 UString dirPrefix;
334 CTempDir tempDirectory; 1522 CTempDir tempDirectory;
335 1523
336 bool isFSFolder = IsFSFolder(); 1524 CDataObject *dataObjectSpec = new CDataObject;
1525 CMyComPtr<IDataObject> dataObject = dataObjectSpec;
1526 dataObjectSpec->IsRightButton = isRightButton;
1527
1528 {
1529 /* we can change confirmation mode and another options.
1530 Explorer target requests that FILEOP_FLAGS value. */
1531 /*
1532 const FILEOP_FLAGS fopFlags =
1533 FOF_NOCONFIRMATION
1534 | FOF_NOCONFIRMMKDIR
1535 | FOF_NOERRORUI
1536 | FOF_SILENT;
1537 // | FOF_SIMPLEPROGRESS; // it doesn't work as expected in Win10
1538 Global_SetUInt32(dataObjectSpec->m_hGlobal_FileOpFlags, fopFlags);
1539 // dataObjectSpec->m_hGlobal_FileOpFlags.Free(); // for debug : disable these options
1540 */
1541 }
1542 {
1543 /* we can change Preferred DropEffect.
1544 Explorer target requests that FILEOP_FLAGS value. */
1545 /*
1546 const DWORD effect = DROPEFFECT_MOVE; // DROPEFFECT_COPY;
1547 Global_SetUInt32(dataObjectSpec->m_hGlobal_PreferredDropEffect, effect);
1548 */
1549 }
337 if (isFSFolder) 1550 if (isFSFolder)
338 dirPrefix = us2fs(GetFsPath()); 1551 {
1552 dirPrefix = GetFsPath(); // why this in 22.01 ?
1553 dataObjectSpec->UsePreGlobal = false;
1554 // dataObjectSpec->IsTempFiles = false;
1555 }
339 else 1556 else
340 { 1557 {
341 if (!tempDirectory.Create(kTempDirPrefix)) 1558 if (!tempDirectory.Create(kTempDirPrefix))
@@ -343,23 +1560,32 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
343 MessageBox_Error(L"Can't create temp folder"); 1560 MessageBox_Error(L"Can't create temp folder");
344 return; 1561 return;
345 } 1562 }
346 dirPrefix = tempDirectory.GetPath(); 1563 dirPrefix = fs2us(tempDirectory.GetPath());
347 // dirPrefix2 = dirPrefix; 1564 {
1565 UStringVector names;
1566 names.Add(dirPrefix);
1567 dataObjectSpec->IsTempFiles = true;
1568 dataObjectSpec->UsePreGlobal = true;
1569 if (!CopyNamesToHGlobal(dataObjectSpec->m_hGlobal_HDROP_Pre, names))
1570 return;
1571 }
348 NFile::NName::NormalizeDirPathPrefix(dirPrefix); 1572 NFile::NName::NormalizeDirPathPrefix(dirPrefix);
1573 /*
1574 {
1575 FString path2 = dirPrefix;
1576 path2 += "1.txt";
1577 CopyFileW(L"C:\\1\\1.txt", path2, FALSE);
1578 }
1579 */
349 } 1580 }
350 1581
351 CDataObject *dataObjectSpec = new CDataObject;
352 CMyComPtr<IDataObject> dataObject = dataObjectSpec;
353
354 { 1582 {
355 UStringVector names; 1583 UStringVector names;
356
357 // names variable is USED for drag and drop from 7-zip to Explorer or to 7-zip archive folder. 1584 // names variable is USED for drag and drop from 7-zip to Explorer or to 7-zip archive folder.
358 // names variable is NOT USED for drag and drop from 7-zip to 7-zip File System folder. 1585 // names variable is NOT USED for drag and drop from 7-zip to 7-zip File System folder.
359
360 FOR_VECTOR (i, indices) 1586 FOR_VECTOR (i, indices)
361 { 1587 {
362 UInt32 index = indices[i]; 1588 const UInt32 index = indices[i];
363 UString s; 1589 UString s;
364 if (isFSFolder) 1590 if (isFSFolder)
365 s = GetItemRelPath(index); 1591 s = GetItemRelPath(index);
@@ -370,14 +1596,12 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
370 // We use (keepAndReplaceEmptyPrefixes = true) in CAgentFolder::Extract 1596 // We use (keepAndReplaceEmptyPrefixes = true) in CAgentFolder::Extract
371 // So the following code is not required. 1597 // So the following code is not required.
372 // Maybe we also can change IFolder interface and send some flag also. 1598 // Maybe we also can change IFolder interface and send some flag also.
373
374 if (s.IsEmpty()) 1599 if (s.IsEmpty())
375 { 1600 {
376 // Correct_FsFile_Name("") returns "_". 1601 // Correct_FsFile_Name("") returns "_".
377 // If extracting code removes empty folder prefixes from path (as it was in old version), 1602 // If extracting code removes empty folder prefixes from path (as it was in old version),
378 // Explorer can't find "_" folder in temp folder. 1603 // Explorer can't find "_" folder in temp folder.
379 // We can ask Explorer to copy parent temp folder "7zE" instead. 1604 // We can ask Explorer to copy parent temp folder "7zE" instead.
380
381 names.Clear(); 1605 names.Clear();
382 names.Add(dirPrefix2); 1606 names.Add(dirPrefix2);
383 break; 1607 break;
@@ -385,18 +1609,18 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
385 */ 1609 */
386 s = Get_Correct_FsFile_Name(s); 1610 s = Get_Correct_FsFile_Name(s);
387 } 1611 }
388 names.Add(fs2us(dirPrefix) + s); 1612 names.Add(dirPrefix + s);
389 } 1613 }
390 if (!CopyNamesToHGlobal(dataObjectSpec->hGlobal, names)) 1614 if (!CopyNamesToHGlobal(dataObjectSpec->m_hGlobal_HDROP_Final, names))
391 return; 1615 return;
392 } 1616 }
393 1617
394 CDropSource *dropSourceSpec = new CDropSource; 1618 CDropSource *dropSourceSpec = new CDropSource;
395 CMyComPtr<IDropSource> dropSource = dropSourceSpec; 1619 CMyComPtr<IDropSource> dropSource = dropSourceSpec;
396 dropSourceSpec->NeedExtract = !isFSFolder; 1620 dataObjectSpec->Panel = this;
397 dropSourceSpec->Panel = this; 1621 dataObjectSpec->Indices = indices;
398 dropSourceSpec->Indices = indices; 1622 dataObjectSpec->SrcDirPrefix_Temp = dirPrefix;
399 dropSourceSpec->Folder = fs2us(dirPrefix); 1623
400 dropSourceSpec->DataObjectSpec = dataObjectSpec; 1624 dropSourceSpec->DataObjectSpec = dataObjectSpec;
401 dropSourceSpec->DataObject = dataObjectSpec; 1625 dropSourceSpec->DataObject = dataObjectSpec;
402 1626
@@ -404,17 +1628,17 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
404 /* 1628 /*
405 CTime - file creation timestamp. 1629 CTime - file creation timestamp.
406 There are two operations in Windows with Drag and Drop: 1630 There are two operations in Windows with Drag and Drop:
407 COPY_OPERATION - icon with Plus sign - CTime will be set as current_time. 1631 COPY_OPERATION : icon with Plus sign : CTime will be set as current_time.
408 MOVE_OPERATION - icon without Plus sign - CTime will be preserved 1632 MOVE_OPERATION : icon without Plus sign : CTime will be preserved.
409 1633
410 Note: if we call DoDragDrop() with (effectsOK = DROPEFFECT_MOVE), then 1634 Note: if we call DoDragDrop() with (effectsOK = DROPEFFECT_MOVE), then
411 it will use MOVE_OPERATION and CTime will be preserved. 1635 it will use MOVE_OPERATION and CTime will be preserved.
412 But MoveFile() function doesn't preserve CTime, if different volumes are used. 1636 But MoveFile() function doesn't preserve CTime, if different volumes are used.
413 Why it's so? 1637 Why it's so?
414 Does DoDragDrop() use some another function (not MoveFile())? 1638 Does DoDragDrop() use some another function (not MoveFile())?
415 1639
416 if (effectsOK == DROPEFFECT_COPY) it works as COPY_OPERATION 1640 if (effectsOK == DROPEFFECT_COPY) it works as COPY_OPERATION
417 1641
418 if (effectsOK == DROPEFFECT_MOVE) drag works as MOVE_OPERATION 1642 if (effectsOK == DROPEFFECT_MOVE) drag works as MOVE_OPERATION
419 1643
420 if (effectsOK == (DROPEFFECT_COPY | DROPEFFECT_MOVE)) 1644 if (effectsOK == (DROPEFFECT_COPY | DROPEFFECT_MOVE))
@@ -431,7 +1655,7 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
431 We want to use MOVE_OPERATION for extracting from archive (open in 7-Zip) to Explorer: 1655 We want to use MOVE_OPERATION for extracting from archive (open in 7-Zip) to Explorer:
432 It has the following advantages: 1656 It has the following advantages:
433 1) it uses fast MOVE_OPERATION instead of slow COPY_OPERATION and DELETE, if same volume. 1657 1) it uses fast MOVE_OPERATION instead of slow COPY_OPERATION and DELETE, if same volume.
434 2) it preserved CTime 1658 2) it preserves CTime
435 1659
436 Some another programs support only COPY_OPERATION. 1660 Some another programs support only COPY_OPERATION.
437 So we can use (DROPEFFECT_COPY | DROPEFFECT_MOVE) 1661 So we can use (DROPEFFECT_COPY | DROPEFFECT_MOVE)
@@ -444,252 +1668,401 @@ void CPanel::OnDrag(LPNMLISTVIEW /* nmListView */)
444 IDropSource *dropSource 1668 IDropSource *dropSource
445 IDataObject *dataObject 1669 IDataObject *dataObject
446 if DropTarget is 7-Zip window, then 7-Zip's 1670 if DropTarget is 7-Zip window, then 7-Zip's
447 IDropTarget::DragOver() sets Path in IDataObject. 1671 IDropTarget::DragOver() sets DestDirPrefix_FromTarget in IDataObject.
448 and 1672 and
449 IDropSource::QueryContinueDrag() sets NeedPostCopy, if Path is not epmty. 1673 IDropSource::QueryContinueDrag() sets DoNotProcessInTarget, if DestDirPrefix_FromTarget is not empty.
450 So we can detect destination path after DoDragDrop(). 1674 So we can detect destination path after DoDragDrop().
451 Now we don't know any good way to detect destination path for D&D to Explorer. 1675 Now we don't know any good way to detect destination path for D&D to Explorer.
452 */ 1676 */
453 1677
454 bool moveIsAllowed = isFSFolder;
455 /* 1678 /*
456 DWORD effectsOK = DROPEFFECT_COPY; 1679 DWORD effectsOK = DROPEFFECT_COPY;
457 if (moveIsAllowed) 1680 if (moveIsAllowed)
458 effectsOK |= DROPEFFECT_MOVE; 1681 effectsOK |= DROPEFFECT_MOVE;
459 */ 1682 */
460 1683 const bool moveIsAllowed = isFSFolder;
461 // 18.04: was changed
462 DWORD effectsOK = DROPEFFECT_MOVE | DROPEFFECT_COPY;
463
464 DWORD effect;
465 _panelCallback->DragBegin(); 1684 _panelCallback->DragBegin();
466 1685 PRF("=== DoDragDrop()");
467 HRESULT res = DoDragDrop(dataObject, dropSource, effectsOK, &effect); 1686 DWORD effect = 0;
468 1687 // 18.04: was changed
1688 const DWORD effectsOK = DROPEFFECT_MOVE | DROPEFFECT_COPY;
1689 // effectsOK |= (1 << 8); // for debug
1690 HRESULT res = ::DoDragDrop(dataObject, dropSource, effectsOK, &effect);
1691 PRF("=== After DoDragDrop()");
469 _panelCallback->DragEnd(); 1692 _panelCallback->DragEnd();
470 bool canceled = (res == DRAGDROP_S_CANCEL); 1693
1694 /*
1695 Win10 drag and drop to Explorer:
1696 DoDragDrop() output variables:
1697 for MOVE operation:
1698 {
1699 effect == DROPEFFECT_NONE;
1700 dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_MOVE;
1701 }
1702 for COPY operation:
1703 {
1704 effect == DROPEFFECT_COPY;
1705 dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_COPY;
1706 }
1707 DOCs: The source inspects the two values that can be returned by the target.
1708 If both are set to DROPEFFECT_MOVE, it completes the unoptimized move
1709 by deleting the original data. Otherwise, the target did an optimized
1710 move and the original data has been deleted.
1711
1712 We didn't see "unoptimized move" case (two values of DROPEFFECT_MOVE),
1713 where we still need to delete source files.
1714 So we don't delete files after DoDragDrop().
1715
1716 Also DOCs say for "optimized move":
1717 The target also calls the data object's IDataObject::SetData method and passes
1718 it a CFSTR_PERFORMEDDROPEFFECT format identifier set to DROPEFFECT_NONE.
1719 but actually in Win10 we always have
1720 (dropSourceSpec->m_PerformedDropEffect == DROPEFFECT_MOVE)
1721 for any MOVE operation.
1722 */
1723
1724 const bool canceled = (res == DRAGDROP_S_CANCEL);
471 1725
472 CDisableNotify disableNotify(*this); 1726 CDisableNotify disableNotify(*this);
473 1727
474 if (res == DRAGDROP_S_DROP) 1728 if (res == DRAGDROP_S_DROP)
475 { 1729 {
476 res = dropSourceSpec->Result; 1730 /* DRAGDROP_S_DROP is returned. It means that
477 if (dropSourceSpec->NeedPostCopy) 1731 - IDropTarget::Drop() was called,
478 if (!dataObjectSpec->Path.IsEmpty()) 1732 - IDropTarget::Drop() returned (ret_code >= 0)
1733 */
1734 res = dataObjectSpec->Copy_HRESULT;
1735 bool need_Process = dataObjectSpec->DoNotProcessInTarget;
1736 if (dataObjectSpec->m_Transfer_WasSet)
1737 {
1738 if (dataObjectSpec->m_Transfer.Target.FuncType == k_DragTargetMode_Drop_End)
1739 {
1740 if (dataObjectSpec->m_Transfer.Target.Flags & k_TargetFlags_MustBeProcessedBySource)
1741 need_Process = true;
1742 }
1743 }
1744
1745 if (need_Process)
1746 if (!dataObjectSpec->DestDirPrefix_FromTarget.IsEmpty())
479 { 1747 {
480 NFile::NName::NormalizeDirPathPrefix(dataObjectSpec->Path); 1748 if (!NFile::NName::IsAltStreamPrefixWithColon(dataObjectSpec->DestDirPrefix_FromTarget))
1749 NFile::NName::NormalizeDirPathPrefix(dataObjectSpec->DestDirPrefix_FromTarget);
481 CCopyToOptions options; 1750 CCopyToOptions options;
482 options.folder = dataObjectSpec->Path; 1751 options.folder = dataObjectSpec->DestDirPrefix_FromTarget;
483 // if MOVE is not allowed, we just use COPY operation 1752 // if MOVE is not allowed, we just use COPY operation
484 options.moveMode = (effect == DROPEFFECT_MOVE && moveIsAllowed); 1753 /* it was 7-zip's Target that set non-empty dataObjectSpec->DestDirPrefix_FromTarget.
485 res = CopyTo(options, indices, &dropSourceSpec->Messages); 1754 it means that target didn't completed operation,
1755 and we can use (effect) value returned by target via DoDragDrop().
1756 as indicator of type of operation
1757 */
1758 // options.moveMode = (moveIsAllowed && effect == DROPEFFECT_MOVE) // before v23.00:
1759 options.moveMode = moveIsAllowed;
1760 if (moveIsAllowed)
1761 {
1762 if (dataObjectSpec->m_Transfer_WasSet)
1763 options.moveMode = (
1764 dataObjectSpec->m_Transfer.Target.Cmd_Effect == DROPEFFECT_MOVE);
1765 else
1766 options.moveMode = (effect == DROPEFFECT_MOVE);
1767 // we expect (DROPEFFECT_MOVE) as indicator of move operation for Drag&Drop MOVE ver 22.01.
1768 }
1769 res = CopyTo(options, indices, &dataObjectSpec->Messages);
486 } 1770 }
487 /* 1771 /*
488 if (effect == DROPEFFECT_MOVE) 1772 if (effect & DROPEFFECT_MOVE)
489 RefreshListCtrl(selState); 1773 RefreshListCtrl(selState);
490 */ 1774 */
491 } 1775 }
492 else 1776 else
493 { 1777 {
494 // we ignore E_UNEXPECTED that is returned if we drag file to printer 1778 // we ignore E_UNEXPECTED that is returned if we drag file to printer
495 if (res != DRAGDROP_S_CANCEL && res != S_OK 1779 if (res != DRAGDROP_S_CANCEL
1780 && res != S_OK
496 && res != E_UNEXPECTED) 1781 && res != E_UNEXPECTED)
497 MessageBox_Error_HRESULT(res); 1782 MessageBox_Error_HRESULT(res);
498 1783 res = dataObjectSpec->Copy_HRESULT;
499 res = dropSourceSpec->Result;
500 } 1784 }
501 1785
502 if (!dropSourceSpec->Messages.IsEmpty()) 1786 if (!dataObjectSpec->Messages.IsEmpty())
503 { 1787 {
504 CMessagesDialog messagesDialog; 1788 CMessagesDialog messagesDialog;
505 messagesDialog.Messages = &dropSourceSpec->Messages; 1789 messagesDialog.Messages = &dataObjectSpec->Messages;
506 messagesDialog.Create((*this)); 1790 messagesDialog.Create((*this));
507 } 1791 }
508 1792
509 if (res != S_OK && res != E_ABORT) 1793 if (res != S_OK && res != E_ABORT)
510 { 1794 {
511 // we restore Notify before MessageBox_Error_HRESULT. So we will se files selection 1795 // we restore Notify before MessageBox_Error_HRESULT. So we will see files selection
512 disableNotify.Restore(); 1796 disableNotify.Restore();
513 // SetFocusToList(); 1797 // SetFocusToList();
514 MessageBox_Error_HRESULT(res); 1798 MessageBox_Error_HRESULT(res);
515 } 1799 }
516 if (res == S_OK && dropSourceSpec->Messages.IsEmpty() && !canceled) 1800 if (res == S_OK && dataObjectSpec->Messages.IsEmpty() && !canceled)
517 KillSelection(); 1801 KillSelection();
518} 1802}
519 1803
520void CDropTarget::QueryGetData(IDataObject *dataObject) 1804
1805
1806
1807
1808CDropTarget::CDropTarget():
1809 m_IsRightButton(false),
1810 m_GetTransfer_WasSuccess(false),
1811 m_DropIsAllowed(false),
1812 m_PanelDropIsAllowed(false),
1813 // m_DropHighlighted_SelectionIndex(-1),
1814 // m_SubFolderIndex(-1),
1815 m_Panel(NULL),
1816 m_IsAppTarget(false),
1817 m_TargetPath_WasSent_ToDataObject(false),
1818 m_TargetPath_NonEmpty_WasSent_ToDataObject(false),
1819 m_Transfer_WasSent_ToDataObject(false),
1820 App(NULL),
1821 SrcPanelIndex(-1),
1822 TargetPanelIndex(-1)
1823{
1824 m_Format_7zip_SetTargetFolder = RegisterClipboardFormat(k_Format_7zip_SetTargetFolder);
1825 m_Format_7zip_SetTransfer = RegisterClipboardFormat(k_Format_7zip_SetTransfer);
1826 m_Format_7zip_GetTransfer = RegisterClipboardFormat(k_Format_7zip_GetTransfer);
1827
1828 m_ProcessId = GetCurrentProcessId();
1829 // m_TransactionId = ((UInt64)m_ProcessId << 32) + 1;
1830 // ClearState();
1831}
1832
1833// clear internal state
1834void CDropTarget::ClearState()
1835{
1836 m_DataObject.Release();
1837 m_SourcePaths.Clear();
1838
1839 m_IsRightButton = false;
1840
1841 m_GetTransfer_WasSuccess = false;
1842 m_DropIsAllowed = false;
1843
1844 m_PanelDropIsAllowed = false;
1845 // m_SubFolderIndex = -1;
1846 // m_DropHighlighted_SubFolderName.Empty();
1847 m_Panel = NULL;
1848 m_IsAppTarget = false;
1849 m_TargetPath_WasSent_ToDataObject = false;
1850 m_TargetPath_NonEmpty_WasSent_ToDataObject = false;
1851 m_Transfer_WasSent_ToDataObject = false;
1852}
1853
1854/*
1855 IDataObject::QueryGetData() Determines whether the data object is capable of
1856 rendering the data as specified. Objects attempting a paste or drop
1857 operation can call this method before calling IDataObject::GetData
1858 to get an indication of whether the operation may be successful.
1859
1860 The client of a data object calls QueryGetData to determine whether
1861 passing the specified FORMATETC structure to a subsequent call to
1862 IDataObject::GetData is likely to be successful.
1863
1864 We check Try_QueryGetData with CF_HDROP
1865*/
1866/*
1867void CDropTarget::Try_QueryGetData(IDataObject *dataObject)
521{ 1868{
522 FORMATETC etc = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; 1869 FORMATETC etc = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
523 m_DropIsAllowed = (dataObject->QueryGetData(&etc) == S_OK); 1870 m_DropIsAllowed = (dataObject->QueryGetData(&etc) == S_OK);
524
525} 1871}
1872*/
526 1873
527static void MySetDropHighlighted(HWND hWnd, int index, bool enable) 1874static void ListView_SetItemState_DropHighlighted(
1875 NControl::CListView &listView, int index, bool highlighted)
528{ 1876{
1877 // LVIS_DROPHILITED : The item is highlighted as a drag-and-drop target
1878 /*
529 LVITEM item; 1879 LVITEM item;
530 item.mask = LVIF_STATE; 1880 item.mask = LVIF_STATE;
531 item.iItem = index; 1881 item.iItem = index;
532 item.iSubItem = 0; 1882 item.iSubItem = 0;
533 item.state = enable ? LVIS_DROPHILITED : 0; 1883 item.state = enable ? LVIS_DROPHILITED : 0;
534 item.stateMask = LVIS_DROPHILITED; 1884 item.stateMask = LVIS_DROPHILITED;
535 item.pszText = 0; 1885 item.pszText = NULL;
536 ListView_SetItem(hWnd, &item); 1886 listView.SetItem(&item);
1887 */
1888 listView.SetItemState(index, highlighted ? LVIS_DROPHILITED : 0, LVIS_DROPHILITED);
537} 1889}
538 1890
1891// Removes DropHighlighted state in ListView item, if it was set before
539void CDropTarget::RemoveSelection() 1892void CDropTarget::RemoveSelection()
540{ 1893{
541 if (m_SelectionIndex >= 0 && m_Panel) 1894 if (m_Panel)
542 MySetDropHighlighted(m_Panel->_listView, m_SelectionIndex, false); 1895 {
543 m_SelectionIndex = -1; 1896 m_Panel->m_DropHighlighted_SubFolderName.Empty();
1897 if (m_Panel->m_DropHighlighted_SelectionIndex >= 0)
1898 {
1899 ListView_SetItemState_DropHighlighted(m_Panel->_listView,
1900 m_Panel->m_DropHighlighted_SelectionIndex, false);
1901 m_Panel->m_DropHighlighted_SelectionIndex = -1;
1902 }
1903 }
544} 1904}
545 1905
546#ifdef UNDER_CE 1906#ifdef UNDER_CE
547#define ChildWindowFromPointEx(hwndParent, pt, uFlags) ChildWindowFromPoint(hwndParent, pt) 1907#define ChildWindowFromPointEx(hwndParent, pt, uFlags) ChildWindowFromPoint(hwndParent, pt)
548#endif 1908#endif
549 1909
550void CDropTarget::PositionCursor(POINTL ptl)
551{
552 m_SubFolderIndex = -1;
553 POINT pt;
554 pt.x = ptl.x;
555 pt.y = ptl.y;
556 1910
1911/*
1912 PositionCursor() function sets m_Panel under cursor drop, and
1913 m_SubFolderIndex/m_DropHighlighted_SubFolderName, if drop to some folder in Panel list.
1914*/
1915/*
1916PositionCursor() uses as input variables:
1917 m_DropIsAllowed must be set before PositionCursor()
1918 if (m_DropHighlighted_SelectionIndex >= 0 && m_Panel) it uses m_Panel and removes previous selection
1919PositionCursor() sets
1920 m_PanelDropIsAllowed
1921 m_Panel
1922 m_IsAppTarget
1923 m_SubFolderIndex
1924 m_DropHighlighted_SubFolderName
1925 m_DropHighlighted_SelectionIndex
1926*/
1927void CDropTarget::PositionCursor(const POINTL &ptl)
1928{
557 RemoveSelection(); 1929 RemoveSelection();
1930
1931 // m_SubFolderIndex = -1;
1932 // m_DropHighlighted_SubFolderName.Empty();
558 m_IsAppTarget = true; 1933 m_IsAppTarget = true;
559 m_Panel = NULL; 1934 m_Panel = NULL;
1935 m_PanelDropIsAllowed = false;
560 1936
561 m_PanelDropIsAllowed = true;
562 if (!m_DropIsAllowed) 1937 if (!m_DropIsAllowed)
563 return; 1938 return;
1939
1940 POINT pt;
1941 pt.x = ptl.x;
1942 pt.y = ptl.y;
564 { 1943 {
565 POINT pt2 = pt; 1944 POINT pt2 = pt;
566 App->_window.ScreenToClient(&pt2); 1945 if (App->_window.ScreenToClient(&pt2))
567 for (unsigned i = 0; i < kNumPanelsMax; i++) 1946 for (unsigned i = 0; i < kNumPanelsMax; i++)
568 if (App->IsPanelVisible(i)) 1947 if (App->IsPanelVisible(i))
569 if (App->Panels[i].IsEnabled()) 1948 {
570 if (ChildWindowFromPointEx(App->_window, pt2, 1949 CPanel *panel = &App->Panels[i];
571 CWP_SKIPINVISIBLE | CWP_SKIPDISABLED) == (HWND)App->Panels[i]) 1950 if (panel->IsEnabled())
1951 if (::ChildWindowFromPointEx(App->_window, pt2,
1952 CWP_SKIPINVISIBLE | CWP_SKIPDISABLED) == (HWND)*panel)
572 { 1953 {
573 m_Panel = &App->Panels[i]; 1954 m_Panel = panel;
574 m_IsAppTarget = false; 1955 m_IsAppTarget = false;
575 if ((int)i == SrcPanelIndex) 1956 if ((int)i == SrcPanelIndex)
576 { 1957 return; // we don't allow to drop to source panel
577 m_PanelDropIsAllowed = false;
578 return;
579 }
580 break; 1958 break;
581 } 1959 }
582 if (m_IsAppTarget) 1960 }
583 { 1961 }
584 if (TargetPanelIndex >= 0) 1962
585 m_Panel = &App->Panels[TargetPanelIndex]; 1963 m_PanelDropIsAllowed = true;
586 return; 1964
587 } 1965 if (!m_Panel)
1966 {
1967 if (TargetPanelIndex >= 0)
1968 m_Panel = &App->Panels[TargetPanelIndex];
1969 // we don't need to find item in panel
1970 return;
588 } 1971 }
589 1972
1973 // we will try to find and highlight drop folder item in listView under cursor
590 /* 1974 /*
591 m_PanelDropIsAllowed = m_Panel->DoesItSupportOperations(); 1975 m_PanelDropIsAllowed = m_Panel->DoesItSupportOperations();
592 if (!m_PanelDropIsAllowed) 1976 if (!m_PanelDropIsAllowed)
593 return; 1977 return;
594 */ 1978 */
595 1979 /* now we don't allow drop to subfolder under cursor, if dest panel is archive.
1980 Another code must be fixed for that case, where we must use m_SubFolderIndex/m_DropHighlighted_SubFolderName */
596 if (!m_Panel->IsFsOrPureDrivesFolder()) 1981 if (!m_Panel->IsFsOrPureDrivesFolder())
597 return; 1982 return;
598 1983
599 if (WindowFromPoint(pt) != (HWND)m_Panel->_listView) 1984 if (::WindowFromPoint(pt) != (HWND)m_Panel->_listView)
600 return; 1985 return;
601 1986
602 LVHITTESTINFO info; 1987 LVHITTESTINFO info;
603 m_Panel->_listView.ScreenToClient(&pt); 1988 m_Panel->_listView.ScreenToClient(&pt);
604 info.pt = pt; 1989 info.pt = pt;
605 int index = ListView_HitTest(m_Panel->_listView, &info); 1990 const int index = ListView_HitTest(m_Panel->_listView, &info);
606 if (index < 0) 1991 if (index < 0)
607 return; 1992 return;
608 int realIndex = m_Panel->GetRealItemIndex(index); 1993 const unsigned realIndex = m_Panel->GetRealItemIndex(index);
609 if (realIndex == kParentIndex) 1994 if (realIndex == kParentIndex)
610 return; 1995 return;
611 if (!m_Panel->IsItem_Folder(realIndex)) 1996 if (!m_Panel->IsItem_Folder(realIndex))
612 return; 1997 return;
613 m_SubFolderIndex = realIndex; 1998 // m_SubFolderIndex = (int)realIndex;
614 m_SubFolderName = m_Panel->GetItemName(m_SubFolderIndex); 1999 m_Panel->m_DropHighlighted_SubFolderName = m_Panel->GetItemName(realIndex);
615 MySetDropHighlighted(m_Panel->_listView, index, true); 2000 ListView_SetItemState_DropHighlighted(m_Panel->_listView, index, true);
616 m_SelectionIndex = index; 2001 m_Panel->m_DropHighlighted_SelectionIndex = index;
617} 2002}
618 2003
619bool CDropTarget::IsFsFolderPath() const
620{
621 if (!m_IsAppTarget && m_Panel)
622 return (m_Panel->IsFSFolder() || (m_Panel->IsFSDrivesFolder() && m_SelectionIndex >= 0));
623 return false;
624}
625 2004
626static void ReadUnicodeStrings(const wchar_t *p, size_t size, UStringVector &names) 2005/* returns true, if !m_IsAppTarget
2006 and target is FS folder or altStream folder
2007*/
2008
2009UInt32 CDropTarget::GetFolderType() const
627{ 2010{
628 names.Clear(); 2011 if (m_IsAppTarget || !m_Panel)
629 UString name; 2012 return k_FolderType_None;
630 for (;size > 0; size--) 2013 if (m_Panel->IsFSFolder() ||
631 { 2014 (m_Panel->IsFSDrivesFolder()
632 wchar_t c = *p++; 2015 && m_Panel->m_DropHighlighted_SelectionIndex >= 0))
633 if (c == 0) 2016 return k_FolderType_Fs;
634 { 2017 if (m_Panel->IsAltStreamsFolder())
635 if (name.IsEmpty()) 2018 return k_FolderType_AltStreams;
636 break; 2019 if (m_Panel->IsArcFolder())
637 names.Add(name); 2020 return k_FolderType_Archive;
638 name.Empty(); 2021 return k_FolderType_Unknown;
639 }
640 else
641 name += c;
642 }
643} 2022}
644 2023
645static void ReadAnsiStrings(const char *p, size_t size, UStringVector &names) 2024bool CDropTarget::IsFsFolderPath() const
646{ 2025{
647 names.Clear(); 2026 if (m_IsAppTarget || !m_Panel)
648 AString name; 2027 return false;
649 for (;size > 0; size--) 2028 if (m_Panel->IsFSFolder())
650 { 2029 return true;
651 char c = *p++; 2030 if (m_Panel->IsAltStreamsFolder())
652 if (c == 0) 2031 return true;
653 { 2032 return m_Panel->IsFSDrivesFolder() &&
654 if (name.IsEmpty()) 2033 m_Panel->m_DropHighlighted_SelectionIndex >= 0;
655 break;
656 names.Add(GetUnicodeString(name));
657 name.Empty();
658 }
659 else
660 name += c;
661 }
662} 2034}
663 2035
664static void GetNamesFromDataObject(IDataObject *dataObject, UStringVector &names) 2036
2037#define INIT_FORMATETC_HGLOBAL(type) { (type), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }
2038
2039static bool DataObject_GetData_GetTransfer(IDataObject *dataObject,
2040 UINT a_Format_7zip_GetTransfer, CDataObject_GetTransfer &transfer)
665{ 2041{
666 names.Clear(); 2042 FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)a_Format_7zip_GetTransfer);
667 FORMATETC etc = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; 2043 NCOM::CStgMedium medium;
668 STGMEDIUM medium; 2044 const HRESULT res = dataObject->GetData(&etc, &medium);
669 HRESULT res = dataObject->GetData(&etc, &medium);
670 if (res != S_OK) 2045 if (res != S_OK)
671 return; 2046 return false;
672 if (medium.tymed != TYMED_HGLOBAL) 2047 if (medium.tymed != TYMED_HGLOBAL)
673 return; 2048 return false;
674 { 2049 const size_t size = GlobalSize(medium.hGlobal);
675 NMemory::CGlobal global; 2050 if (size < sizeof(transfer))
676 global.Attach(medium.hGlobal); 2051 return false;
677 size_t blockSize = GlobalSize(medium.hGlobal); 2052 NMemory::CGlobalLock dropLock(medium.hGlobal);
678 NMemory::CGlobalLock dropLock(medium.hGlobal); 2053 const CDataObject_GetTransfer *t = (const CDataObject_GetTransfer *)dropLock.GetPointer();
679 const DROPFILES* dropFiles = (DROPFILES*)dropLock.GetPointer(); 2054 if (!t)
680 if (!dropFiles) 2055 return false;
681 return; 2056 if (!t->Check()) // isSetData
682 if (blockSize < dropFiles->pFiles) 2057 return false;
683 return; 2058 transfer = *t;
684 size_t size = blockSize - dropFiles->pFiles; 2059 return true;
685 const void *namesData = (const Byte *)dropFiles + dropFiles->pFiles;
686 if (dropFiles->fWide)
687 ReadUnicodeStrings((const wchar_t *)namesData, size / sizeof(wchar_t), names);
688 else
689 ReadAnsiStrings((const char *)namesData, size, names);
690 }
691} 2060}
692 2061
2062/*
2063 returns true, if all m_SourcePaths[] items are same drive
2064 as destination drop path in m_Panel
2065*/
693bool CDropTarget::IsItSameDrive() const 2066bool CDropTarget::IsItSameDrive() const
694{ 2067{
695 if (!m_Panel) 2068 if (!m_Panel)
@@ -705,9 +2078,10 @@ bool CDropTarget::IsItSameDrive() const
705 if (drive.IsEmpty()) 2078 if (drive.IsEmpty())
706 return false; 2079 return false;
707 } 2080 }
708 else if (m_Panel->IsFSDrivesFolder() && m_SelectionIndex >= 0) 2081 else if (m_Panel->IsFSDrivesFolder()
2082 && m_Panel->m_DropHighlighted_SelectionIndex >= 0)
709 { 2083 {
710 drive = m_SubFolderName; 2084 drive = m_Panel->m_DropHighlighted_SubFolderName;
711 drive.Add_PathSepar(); 2085 drive.Add_PathSepar();
712 } 2086 }
713 else 2087 else
@@ -721,16 +2095,18 @@ bool CDropTarget::IsItSameDrive() const
721 if (!m_SourcePaths[i].IsPrefixedBy_NoCase(drive)) 2095 if (!m_SourcePaths[i].IsPrefixedBy_NoCase(drive))
722 return false; 2096 return false;
723 } 2097 }
724
725 return true; 2098 return true;
726} 2099}
727 2100
728 2101
729/* 2102/*
730 There are 2 different actions, when we drag to 7-Zip: 2103 There are 2 different actions, when we drag to 7-Zip:
731 1) Drag from any external program except of Explorer to "7-Zip" FS folder. 2104 1) if target panel is "7-Zip" FS and any of the 2 cases:
732 We want to create new archive for that operation. 2105 - Drag from any non "7-Zip" program;
733 2) all another operation work as usual file COPY/MOVE 2106 or
2107 - Drag from "7-Zip" to non-panel area of "7-Zip".
2108 We want to create new archive for that operation with "Add to Archive" window.
2109 2) all another operations work as usual file COPY/MOVE
734 - Drag from "7-Zip" FS to "7-Zip" FS. 2110 - Drag from "7-Zip" FS to "7-Zip" FS.
735 COPY/MOVE are supported. 2111 COPY/MOVE are supported.
736 - Drag to open archive in 7-Zip. 2112 - Drag to open archive in 7-Zip.
@@ -740,217 +2116,891 @@ bool CDropTarget::IsItSameDrive() const
740 We replace COPY to MOVE. 2116 We replace COPY to MOVE.
741*/ 2117*/
742 2118
743DWORD CDropTarget::GetEffect(DWORD keyState, POINTL /* pt */, DWORD allowedEffect) 2119// we try to repeat Explorer's effects.
2120// out: 0 - means that use default effect
2121static DWORD GetEffect_ForKeys(DWORD keyState)
744{ 2122{
745 if (!m_DropIsAllowed || !m_PanelDropIsAllowed) 2123 if (keyState & MK_CONTROL)
746 return DROPEFFECT_NONE; 2124 {
2125 if (keyState & MK_ALT)
2126 return 0;
2127 if (keyState & MK_SHIFT)
2128 return DROPEFFECT_LINK; // CONTROL + SHIFT
2129 return DROPEFFECT_COPY; // CONTROL
2130 }
2131 // no CONTROL
2132 if (keyState & MK_SHIFT)
2133 {
2134 if (keyState & MK_ALT)
2135 return 0;
2136 return DROPEFFECT_MOVE; // SHIFT
2137 }
2138 // no CONTROL, no SHIFT
2139 if (keyState & MK_ALT)
2140 return DROPEFFECT_LINK; // ALT
2141 return 0;
2142}
747 2143
748 if (!IsFsFolderPath() || !m_SetPathIsOK)
749 allowedEffect &= ~DROPEFFECT_MOVE;
750 2144
751 DWORD effect = 0; 2145/* GetEffect() uses m_TargetPath_WasSentToDataObject
752 2146 to disale MOVE operation, if Source is not 7-Zip
753 if (keyState & MK_CONTROL) 2147*/
754 effect = allowedEffect & DROPEFFECT_COPY; 2148DWORD CDropTarget::GetEffect(DWORD keyState, POINTL /* pt */, DWORD allowedEffect) const
755 else if (keyState & MK_SHIFT) 2149{
756 effect = allowedEffect & DROPEFFECT_MOVE; 2150 // (DROPEFFECT_NONE == 0)
757 2151 if (!m_DropIsAllowed || !m_PanelDropIsAllowed)
2152 return 0;
2153 if (!IsFsFolderPath() || !m_TargetPath_WasSent_ToDataObject)
2154 {
2155 // we don't allow MOVE, if Target is archive or Source is not 7-Zip
2156 // disabled for debug:
2157 // allowedEffect &= ~DROPEFFECT_MOVE;
2158 }
2159 DWORD effect;
2160 {
2161 effect = GetEffect_ForKeys(keyState);
2162 if (effect == DROPEFFECT_LINK)
2163 return 0;
2164 effect &= allowedEffect;
2165 }
758 if (effect == 0) 2166 if (effect == 0)
759 { 2167 {
760 if (allowedEffect & DROPEFFECT_COPY) 2168 if (allowedEffect & DROPEFFECT_COPY)
761 effect = DROPEFFECT_COPY; 2169 effect = DROPEFFECT_COPY;
762 if (allowedEffect & DROPEFFECT_MOVE) 2170 if (allowedEffect & DROPEFFECT_MOVE)
763 { 2171 {
2172 /* MOVE operation can be optimized. So MOVE is preferred way
2173 for default action, if Source and Target are at same drive */
764 if (IsItSameDrive()) 2174 if (IsItSameDrive())
765 effect = DROPEFFECT_MOVE; 2175 effect = DROPEFFECT_MOVE;
766 } 2176 }
767 } 2177 }
768 if (effect == 0)
769 return DROPEFFECT_NONE;
770 return effect; 2178 return effect;
771} 2179}
772 2180
2181
2182/* returns:
2183 - target folder path prefix, if target is FS folder
2184 - empty string, if target is not FS folder
2185*/
773UString CDropTarget::GetTargetPath() const 2186UString CDropTarget::GetTargetPath() const
774{ 2187{
775 if (!IsFsFolderPath()) 2188 if (!IsFsFolderPath())
776 return UString(); 2189 return UString();
777 UString path = m_Panel->GetFsPath(); 2190 UString path = m_Panel->GetFsPath();
778 if (m_SubFolderIndex >= 0 && !m_SubFolderName.IsEmpty()) 2191 if (/* m_SubFolderIndex >= 0 && */
2192 !m_Panel->m_DropHighlighted_SubFolderName.IsEmpty())
779 { 2193 {
780 path += m_SubFolderName; 2194 path += m_Panel->m_DropHighlighted_SubFolderName;
781 path.Add_PathSepar(); 2195 path.Add_PathSepar();
782 } 2196 }
783 return path; 2197 return path;
784} 2198}
785 2199
786bool CDropTarget::SetPath(bool enablePath) const 2200
2201/*
2202if IDropSource is Win10-Explorer
2203--------------------------------
2204 As in MS DOCs:
2205 The source inspects the two (effect) values that can be returned by the target:
2206 1) SetData(CFSTR_PERFORMEDDROPEFFECT)
2207 2) returned value (*effect) by
2208 CDropTarget::Drop(IDataObject *dataObject, DWORD keyState,
2209 POINTL pt, DWORD *effect)
2210 If both are set to DROPEFFECT_MOVE, Explorer completes the unoptimized move by deleting
2211 the original data.
2212 // Otherwise, the target did an optimized move and the original data has been deleted.
2213*/
2214
2215
2216/*
2217 Send targetPath from target to dataObject (to Source)
2218 input: set (enablePath = false) to send empty path
2219 returns true, if SetData() returns S_OK : (source is 7-zip)
2220 returns false, if SetData() doesn't return S_OK : (source is Explorer)
2221*/
2222bool CDropTarget::SendToSource_TargetPath_enable(IDataObject *dataObject, bool enablePath)
787{ 2223{
788 UINT setFolderFormat = RegisterClipboardFormat(kSvenZipSetFolderFormat); 2224 m_TargetPath_NonEmpty_WasSent_ToDataObject = false;
789
790 FORMATETC etc = { (CLIPFORMAT)setFolderFormat, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
791 STGMEDIUM medium;
792 medium.tymed = etc.tymed;
793 medium.pUnkForRelease = 0;
794 UString path; 2225 UString path;
795 if (enablePath) 2226 if (enablePath)
796 path = GetTargetPath(); 2227 path = GetTargetPath();
797 size_t size = path.Len() + 1; 2228 PRF("CDropTarget::SetPath");
798 medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size * sizeof(wchar_t)); 2229 PRF_W(path);
2230 if (!dataObject || m_Format_7zip_SetTargetFolder == 0)
2231 return false;
2232 FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)m_Format_7zip_SetTargetFolder);
2233 STGMEDIUM medium;
2234 medium.tymed = etc.tymed;
2235 medium.pUnkForRelease = NULL;
2236 const size_t num = path.Len() + 1; // + (1 << 19) // for debug
2237 medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, num * sizeof(wchar_t));
799 if (!medium.hGlobal) 2238 if (!medium.hGlobal)
800 return false; 2239 return false;
2240 // Sleep(1000);
801 wchar_t *dest = (wchar_t *)GlobalLock(medium.hGlobal); 2241 wchar_t *dest = (wchar_t *)GlobalLock(medium.hGlobal);
802 if (!dest) 2242 // Sleep(1000);
2243 bool res = false;
2244 if (dest)
2245 {
2246 MyStringCopy(dest, (const wchar_t *)path);
2247 GlobalUnlock(medium.hGlobal);
2248 // OutputDebugString("m_DataObject->SetData");
2249 const BOOL release = FALSE; // that way is more simple for correct releasing.
2250 // TRUE; // for debug : is not good for some cases.
2251 /* If DropSource is Win10-Explorer, dataObject->SetData() returns E_NOTIMPL; */
2252 const HRESULT hres = dataObject->SetData(&etc, &medium, release);
2253 // Sleep(1000);
2254 res = (hres == S_OK);
2255 }
2256
2257 ReleaseStgMedium(&medium);
2258 if (res && !path.IsEmpty())
2259 m_TargetPath_NonEmpty_WasSent_ToDataObject = true;
2260 // Sleep(1000);
2261 return res;
2262}
2263
2264
2265void CDropTarget::SendToSource_auto(IDataObject *dataObject,
2266 const CTargetTransferInfo &info)
2267{
2268 /* we try to send target path to Source.
2269 If Source is 7-Zip, then it will accept k_Format_7zip_SetTargetFolder.
2270 That sent path will be non-Empty, if this target is FS folder and drop is allowed */
2271 bool need_Send = false;
2272 if ( info.FuncType == k_DragTargetMode_Enter
2273 || info.FuncType == k_DragTargetMode_Over
2274 || (info.FuncType == k_DragTargetMode_Drop_Begin
2275 // && targetOp_Cmd != NDragMenu::k_None
2276 && info.Cmd_Type != NDragMenu::k_Cancel))
2277 // if (!g_CreateArchive_for_Drag_from_7zip)
2278 need_Send = m_DropIsAllowed && m_PanelDropIsAllowed && IsFsFolderPath();
2279 m_TargetPath_WasSent_ToDataObject = SendToSource_TargetPath_enable(dataObject, need_Send);
2280 SendToSource_TransferInfo(dataObject, info);
2281}
2282
2283
2284bool CDropTarget::SendToSource_TransferInfo(IDataObject *dataObject,
2285 const CTargetTransferInfo &info)
2286{
2287 m_Transfer_WasSent_ToDataObject = false;
2288 PRF("CDropTarget::SendToSource_TransferInfo");
2289
2290 if (!dataObject || m_Format_7zip_SetTransfer == 0)
2291 return false;
2292 FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)m_Format_7zip_SetTransfer);
2293 STGMEDIUM medium;
2294 medium.tymed = etc.tymed;
2295 medium.pUnkForRelease = NULL;
2296 CDataObject_SetTransfer transfer;
2297 const size_t size = sizeof(transfer); // + (1 << 19) // for debug
2298 // OutputDebugString("GlobalAlloc");
2299 medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size);
2300 // Sleep(1000);
2301 if (!medium.hGlobal)
2302 return false;
2303 // OutputDebugString("GlobalLock");
2304 void *dest = (wchar_t *)GlobalLock(medium.hGlobal);
2305 // Sleep(1000);
2306 bool res = false;
2307 if (dest)
803 { 2308 {
2309 transfer.Init();
2310 transfer.Target = info;
2311
2312 memcpy(dest, &transfer, sizeof(transfer));
804 GlobalUnlock(medium.hGlobal); 2313 GlobalUnlock(medium.hGlobal);
2314 // OutputDebugString("m_DataObject->SetData");
2315 const BOOL release = FALSE; // that way is more simple for correct releasing.
2316 // TRUE; // for debug : is not good for some cases
2317 const HRESULT hres = dataObject->SetData(&etc, &medium, release);
2318 res = (hres == S_OK);
2319 }
2320
2321 ReleaseStgMedium(&medium);
2322 if (res)
2323 m_Transfer_WasSent_ToDataObject = true;
2324 return res;
2325}
2326
2327
2328bool CDropTarget::SendToSource_UInt32(IDataObject *dataObject, UINT format, UInt32 value)
2329{
2330 PRF("CDropTarget::Send_UInt32 (Performed)");
2331
2332 if (!dataObject || format == 0)
805 return false; 2333 return false;
2334 FORMATETC etc = INIT_FORMATETC_HGLOBAL((CLIPFORMAT)format);
2335 STGMEDIUM medium;
2336 medium.tymed = etc.tymed;
2337 medium.pUnkForRelease = NULL;
2338 const size_t size = 4;
2339 medium.hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size);
2340 if (!medium.hGlobal)
2341 return false;
2342 void *dest = GlobalLock(medium.hGlobal);
2343 bool res = false;
2344 if (dest)
2345 {
2346 *(UInt32 *)dest = value;
2347 GlobalUnlock(medium.hGlobal);
2348 // OutputDebugString("m_DataObject->SetData");
2349 const BOOL release = TRUE;
2350 // FALSE; // for debug
2351 /* If DropSource is Win10-Explorer, then (release == FALSE) doesn't work
2352 and dataObject->SetData() returns E_NOTIMPL;
2353 So we use release = TRUE; here */
2354 const HRESULT hres = dataObject->SetData(&etc, &medium, release);
2355 // we return here without calling ReleaseStgMedium().
2356 return (hres == S_OK);
2357 // Sleep(1000);
2358 /*
2359 if (we use release = TRUE), we expect that
2360 - SetData() will release medium, and
2361 - SetData() will set STGMEDIUM::tymed to (TYMED_NULL = 0).
2362 but some "incorrect" SetData() implementations can keep STGMEDIUM::tymed unchanged.
2363 And it's not safe to call ReleaseStgMedium() here for that case,
2364 because DropSource also could release medium.
2365 We can reset (medium.tymed = TYMED_NULL) manually here to disable
2366 unsafe medium releasing in ReleaseStgMedium().
2367 */
2368 /*
2369 if (release)
2370 {
2371 medium.tymed = TYMED_NULL;
2372 medium.pUnkForRelease = NULL;
2373 medium.hGlobal = NULL;
2374 }
2375 res = (hres == S_OK);
2376 */
806 } 2377 }
807 MyStringCopy(dest, (const wchar_t *)path); 2378 ReleaseStgMedium(&medium);
808 GlobalUnlock(medium.hGlobal);
809 bool res = m_DataObject->SetData(&etc, &medium, FALSE) == S_OK;
810 GlobalFree(medium.hGlobal);
811 return res; 2379 return res;
812} 2380}
813 2381
814bool CDropTarget::SetPath() 2382
2383void CDropTarget::LoadNames_From_DataObject(IDataObject *dataObject)
815{ 2384{
816 m_SetPathIsOK = SetPath(m_DropIsAllowed && m_PanelDropIsAllowed && IsFsFolderPath()); 2385 // "\\\\.\\" prefix is possible for long names
817 return m_SetPathIsOK; 2386 m_DropIsAllowed = NShell::DataObject_GetData_HDROP_or_IDLIST_Names(dataObject, m_SourcePaths) == S_OK;
818} 2387}
819 2388
820STDMETHODIMP CDropTarget::DragEnter(IDataObject * dataObject, DWORD keyState, 2389
821 POINTL pt, DWORD *effect) 2390Z7_COMWF_B CDropTarget::DragEnter(IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect)
822{ 2391{
823 GetNamesFromDataObject(dataObject, m_SourcePaths); 2392 /* *(effect):
824 QueryGetData(dataObject); 2393 - on input : value of the dwOKEffects parameter of the DoDragDrop() function.
2394 - on return : must contain one of the DROPEFFECT flags, which indicates
2395 what the result of the drop operation would be.
2396 (pt): the current cursor coordinates in screen coordinates.
2397 */
2398 PRF_(Print_Point("CDropTarget::DragEnter", keyState, pt, *effect))
2399 try {
2400
2401 if ((keyState & (MK_RBUTTON | MK_MBUTTON)) != 0)
2402 m_IsRightButton = true;
2403
2404 LoadNames_From_DataObject(dataObject);
2405 // Try_QueryGetData(dataObject);
2406 // we will use (m_DataObject) later in DragOver() and DragLeave().
825 m_DataObject = dataObject; 2407 m_DataObject = dataObject;
826 return DragOver(keyState, pt, effect); 2408 // return DragOver(keyState, pt, effect);
2409 PositionCursor(pt);
2410 CTargetTransferInfo target;
2411 target.FuncType = k_DragTargetMode_Enter;
2412 target.KeyState = keyState;
2413 target.Point = pt;
2414 target.OkEffects = *effect;
2415 SendToSource_Drag(target);
2416
2417 CDataObject_GetTransfer transfer;
2418 m_GetTransfer_WasSuccess = DataObject_GetData_GetTransfer(
2419 dataObject, m_Format_7zip_GetTransfer, transfer);
2420 if (m_GetTransfer_WasSuccess)
2421 {
2422 if (transfer.Flags & k_SourceFlags_LeftButton)
2423 m_IsRightButton = false;
2424 else if (transfer.Flags & k_SourceFlags_RightButton)
2425 m_IsRightButton = true;
2426 }
2427
2428 *effect = GetEffect(keyState, pt, *effect);
2429 return S_OK;
2430 } catch(...) { return E_FAIL; }
827} 2431}
828 2432
829 2433
830STDMETHODIMP CDropTarget::DragOver(DWORD keyState, POINTL pt, DWORD *effect) 2434Z7_COMWF_B CDropTarget::DragOver(DWORD keyState, POINTL pt, DWORD *effect)
831{ 2435{
2436 PRF_(Print_Point("CDropTarget::DragOver", keyState, pt, *effect))
2437 /*
2438 For efficiency reasons, a data object is not passed in IDropTarget::DragOver.
2439 The data object passed in the most recent call to IDropTarget::DragEnter
2440 is available and can be used.
2441
2442 When IDropTarget::DragOver has completed its operation, the DoDragDrop
2443 function calls IDropSource::GiveFeedback so the source application can display
2444 the appropriate visual feedback to the user.
2445 */
2446 /*
2447 we suppose that it's unexpected that (keyState) shows that mouse
2448 button is not pressed, because such cases will be processed by
2449 IDropSource::QueryContinueDrag() that returns DRAGDROP_S_DROP or DRAGDROP_S_CANCEL.
2450 So DragOver() will not be called.
2451 */
2452
2453 if ((keyState & MK_LBUTTON) == 0)
2454 {
2455 PRF4("CDropTarget::DragOver() (keyState & MK_LBUTTON) == 0");
2456 // g_Debug = true;
2457 }
2458
2459 try {
2460 /* we suppose that source names were not changed after DragEnter()
2461 so we don't request GetNames_From_DataObject() for each call of DragOver() */
832 PositionCursor(pt); 2462 PositionCursor(pt);
833 SetPath(); 2463 CTargetTransferInfo target;
2464 target.FuncType = k_DragTargetMode_Over;
2465 target.KeyState = keyState;
2466 target.Point = pt;
2467 target.OkEffects = *effect;
2468 SendToSource_Drag(target);
834 *effect = GetEffect(keyState, pt, *effect); 2469 *effect = GetEffect(keyState, pt, *effect);
2470 // *effect = 1 << 8; // for debug
835 return S_OK; 2471 return S_OK;
2472 } catch(...) { return E_FAIL; }
836} 2473}
837 2474
838 2475
839STDMETHODIMP CDropTarget::DragLeave() 2476Z7_COMWF_B CDropTarget::DragLeave()
840{ 2477{
2478 PRF4("CDropTarget::DragLeave");
2479 try {
841 RemoveSelection(); 2480 RemoveSelection();
842 SetPath(false); 2481 // we send empty TargetPath to 7-Zip Source to clear value of TargetPath that was sent before
843 m_DataObject.Release(); 2482
2483 CTargetTransferInfo target;
2484 target.FuncType = k_DragTargetMode_Leave;
2485 /*
2486 target.KeyState = 0;
2487 target.Point = pt;
2488 pt.x = 0; // -1
2489 pt.y = 0; // -1
2490 target.Effect = 0;
2491 */
2492 SendToSource_Drag(target);
2493 ClearState();
844 return S_OK; 2494 return S_OK;
2495 } catch(...) { return E_FAIL; }
845} 2496}
846 2497
847// We suppose that there was ::DragOver for same POINTL_pt before ::Drop
848// So SetPath() is same as in Drop.
849 2498
850STDMETHODIMP CDropTarget::Drop(IDataObject *dataObject, DWORD keyState, 2499static unsigned Drag_OnContextMenu(int xPos, int yPos, UInt32 cmdFlags);
851 POINTL pt, DWORD * effect) 2500
2501/*
2502 We suppose that there was DragEnter/DragOver for same (POINTL pt) before Drop().
2503 But we can work without DragEnter/DragOver too.
2504*/
2505Z7_COMWF_B CDropTarget::Drop(IDataObject *dataObject, DWORD keyState,
2506 POINTL pt, DWORD *effect)
852{ 2507{
853 QueryGetData(dataObject); 2508 PRF_(Print_Point("CDropTarget::Drop", keyState, pt, *effect))
2509 /* Drop() is called after SourceDrop::QueryContinueDrag() returned DRAGDROP_S_DROP.
2510 So it's possible that Source have done some operations already.
2511 */
2512 HRESULT hres = S_OK;
2513 bool needDrop_by_Source = false;
2514 DWORD opEffect = DROPEFFECT_NONE;
2515
2516 try {
2517 // we don't need m_DataObject reference anymore, because we use local (dataObject)
2518 m_DataObject.Release();
2519
2520 /* in normal case : we called LoadNames_From_DataObject() in DragEnter() already.
2521 But if by some reason DragEnter() was not called,
2522 we need to call LoadNames_From_DataObject() before PositionCursor().
2523 */
2524 if (!m_DropIsAllowed) LoadNames_From_DataObject(dataObject);
854 PositionCursor(pt); 2525 PositionCursor(pt);
855 m_DataObject = dataObject; 2526
856 bool needDrop = true; 2527 CPanel::CDisableTimerProcessing2 disableTimerProcessing(m_Panel);
857 if (m_DropIsAllowed && m_PanelDropIsAllowed) 2528 // CDisableNotify disableNotify2(m_Panel);
858 if (IsFsFolderPath()) 2529
859 needDrop = !SetPath(); 2530 UInt32 cmd = NDragMenu::k_None;
860 *effect = GetEffect(keyState, pt, *effect); 2531 UInt32 cmdEffect = DROPEFFECT_NONE;
861 if (m_DropIsAllowed && m_PanelDropIsAllowed) 2532 bool menu_WasShown = false;
2533 if (m_IsRightButton && m_Panel)
862 { 2534 {
863 if (needDrop) 2535 UInt32 flagsMask;
2536 if (m_Panel->IsArcFolder())
2537 flagsMask = (UInt32)1 << NDragMenu::k_Copy_ToArc;
2538 else
864 { 2539 {
865 UString path = GetTargetPath(); 2540 flagsMask = (UInt32)1 << NDragMenu::k_AddToArc;
866 if (m_IsAppTarget && m_Panel) 2541 if (IsFsFolderPath())
867 if (m_Panel->IsFSFolder()) 2542 flagsMask |= (UInt32)1 << NDragMenu::k_Copy_Base;
868 path = m_Panel->GetFsPath();
869 m_Panel->DropObject(dataObject, path);
870 } 2543 }
2544 // flagsMask |= (UInt32)1 << NDragMenu::k_Cancel;
2545 const UInt32 cmd32 = Drag_OnContextMenu(pt.x, pt.y, flagsMask);
2546 cmd = cmd32 & NDragMenu::k_MenuFlags_CmdMask;
2547 if (cmd32 & NDragMenu::k_MenuFlag_Copy)
2548 cmdEffect = DROPEFFECT_COPY;
2549 else if (cmd32 & NDragMenu::k_MenuFlag_Move)
2550 cmdEffect = DROPEFFECT_MOVE;
2551 opEffect = cmdEffect;
2552 menu_WasShown = true;
2553 }
2554 else
2555 {
2556 opEffect = GetEffect(keyState, pt, *effect);
2557 if (m_IsAppTarget)
2558 cmd = NDragMenu::k_AddToArc;
2559 else if (m_Panel)
2560 {
2561 if (IsFsFolderPath())
2562 {
2563 const bool is7zip = m_TargetPath_WasSent_ToDataObject;
2564 bool createNewArchive = false;
2565 if (is7zip)
2566 createNewArchive = false; // g_CreateArchive_for_Drag_from_7zip;
2567 else
2568 createNewArchive = true; // g_CreateArchive_for_Drag_from_Explorer;
2569
2570 if (createNewArchive)
2571 cmd = NDragMenu::k_AddToArc;
2572 else
2573 {
2574 if (opEffect != 0)
2575 cmd = NDragMenu::k_Copy_Base;
2576 cmdEffect = opEffect;
2577 }
2578 }
2579 else
2580 {
2581 /* if we are inside open archive:
2582 if archive support operations -> we will call operations
2583 if archive doesn't support operations -> we will create new archove
2584 */
2585 if (m_Panel->IsArcFolder()
2586 || m_Panel->DoesItSupportOperations())
2587 {
2588 cmd = NDragMenu::k_Copy_ToArc;
2589 // we don't want move to archive operation here.
2590 // so we force to DROPEFFECT_COPY.
2591 if (opEffect != DROPEFFECT_NONE)
2592 opEffect = DROPEFFECT_COPY;
2593 cmdEffect = opEffect;
2594 }
2595 else
2596 cmd = NDragMenu::k_AddToArc;
2597 }
2598 }
2599 }
2600
2601 if (cmd == 0)
2602 cmd = NDragMenu::k_AddToArc;
2603
2604 if (cmd == NDragMenu::k_AddToArc)
2605 {
2606 opEffect = DROPEFFECT_COPY;
2607 cmdEffect = DROPEFFECT_COPY;
2608 }
2609
2610 if (m_Panel)
2611 if (cmd == NDragMenu::k_Copy_ToArc)
2612 {
2613 const UString title = LangString(IDS_CONFIRM_FILE_COPY);
2614 UString s = LangString(cmdEffect == DROPEFFECT_MOVE ?
2615 IDS_MOVE_TO : IDS_COPY_TO);
2616 s.Add_LF();
2617 s += "\'";
2618 s += m_Panel->_currentFolderPrefix;
2619 s += "\'";
2620 s.Add_LF();
2621 s += LangString(IDS_WANT_TO_COPY_FILES);
2622 s += " ?";
2623 const int res = ::MessageBoxW(*m_Panel, s, title, MB_YESNOCANCEL | MB_ICONQUESTION);
2624 if (res != IDYES)
2625 cmd = NDragMenu::k_Cancel;
2626 }
2627
2628 CTargetTransferInfo target;
2629 target.FuncType = k_DragTargetMode_Drop_Begin;
2630 target.KeyState = keyState;
2631 target.Point = pt;
2632 target.OkEffects = *effect;
2633 target.Flags = 0;
2634
2635 target.Cmd_Effect = cmdEffect;
2636 target.Cmd_Type = cmd;
2637 target.FolderType = GetFolderType();
2638
2639 if (cmd == NDragMenu::k_Cancel)
2640 target.Flags |= k_TargetFlags_WasCanceled;
2641 if (menu_WasShown)
2642 target.Flags |= k_TargetFlags_MenuWasShown;
2643
2644 SendToSource_auto(dataObject, target);
2645
2646 CDataObject_GetTransfer transfer;
2647 m_GetTransfer_WasSuccess = DataObject_GetData_GetTransfer(
2648 dataObject, m_Format_7zip_GetTransfer, transfer);
2649
2650 /* The Source (for example, 7-zip) could change file names when drop was confirmed.
2651 So we must reload source file paths here */
2652 if (cmd != NDragMenu::k_Cancel)
2653 LoadNames_From_DataObject(dataObject);
2654
2655 if (cmd == NDragMenu::k_Cancel)
2656 {
2657 opEffect = DROPEFFECT_NONE;
2658 cmdEffect = DROPEFFECT_NONE;
2659 }
2660 else
2661 {
2662 if (m_GetTransfer_WasSuccess)
2663 needDrop_by_Source = ((transfer.Flags & k_SourceFlags_DoNotProcessInTarget) != 0);
2664 if (!needDrop_by_Source)
2665 {
2666 bool moveMode = (cmdEffect == DROPEFFECT_MOVE);
2667 bool needDrop = false;
2668 if (m_IsRightButton && m_Panel)
2669 needDrop = true;
2670 if (m_DropIsAllowed && m_PanelDropIsAllowed)
2671 {
2672 /* if non-empty TargetPath was sent successfully to DataObject,
2673 then the Source is 7-Zip, and that 7zip-Source can copy to FS operation.
2674 So we can disable Drop operation here for such case.
2675 */
2676 needDrop_by_Source = (cmd != NDragMenu::k_AddToArc
2677 && m_TargetPath_WasSent_ToDataObject
2678 && m_TargetPath_NonEmpty_WasSent_ToDataObject);
2679 needDrop = !(needDrop_by_Source);
2680 }
2681 if (needDrop)
2682 {
2683 UString path = GetTargetPath();
2684 if (m_IsAppTarget && m_Panel)
2685 if (m_Panel->IsFSFolder())
2686 path = m_Panel->GetFsPath();
2687
2688 UInt32 sourceFlags = 0;
2689 if (m_GetTransfer_WasSuccess)
2690 sourceFlags = transfer.Flags;
2691
2692 if (menu_WasShown)
2693 target.Flags |= k_TargetFlags_MenuWasShown;
2694
2695 target.Flags |= k_TargetFlags_WasProcessed;
2696
2697 RemoveSelection();
2698 // disableTimerProcessing.Restore();
2699 m_Panel->CompressDropFiles(m_SourcePaths, path,
2700 (cmd == NDragMenu::k_AddToArc), // createNewArchive,
2701 moveMode, sourceFlags,
2702 target.Flags
2703 );
2704 }
2705 }
2706 } // end of if (cmd != NDragMenu::k_Cancel)
2707 {
2708 /* note that, if (we send CFSTR_PERFORMEDDROPEFFECT as DROPEFFECT_MOVE
2709 and Drop() returns (*effect == DROPEFFECT_MOVE), then
2710 Win10-Explorer-Source will try to remove files just after Drop() exit.
2711 But our CompressFiles() could be run without waiting finishing.
2712 DOCs say, that we must send CFSTR_PERFORMEDDROPEFFECT
2713 - DROPEFFECT_NONE : for optimized move
2714 - DROPEFFECT_MOVE : for unoptimized move.
2715 But actually Win10-Explorer-Target sends (DROPEFFECT_MOVE) for move operation.
2716 And it still works as in optimized mode, because "unoptimized" deleting by Source will be performed
2717 if both conditions are met:
2718 1) DROPEFFECT_MOVE is sent to (CFSTR_PERFORMEDDROPEFFECT) and
2719 2) (*effect == DROPEFFECT_MOVE) is returend by Drop().
2720 We don't want to send DROPEFFECT_MOVE here to protect from
2721 deleting file by Win10-Explorer.
2722 We are not sure that allfile fieree processed by move.
2723 */
2724
2725 // for debug: we test the case when source tries to delete original files
2726 // bool res;
2727 // only CFSTR_PERFORMEDDROPEFFECT affects file removing in Win10-Explorer.
2728 // res = SendToSource_UInt32(dataObject, RegisterClipboardFormat(CFSTR_LOGICALPERFORMEDDROPEFFECT), DROPEFFECT_MOVE); // for debug
2729 /* res = */ SendToSource_UInt32(dataObject,
2730 RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT),
2731 cmd == NDragMenu::k_Cancel ? DROPEFFECT_NONE : DROPEFFECT_COPY);
2732 // res = res;
871 } 2733 }
872 RemoveSelection(); 2734 RemoveSelection();
873 m_DataObject.Release();
874 return S_OK;
875}
876 2735
877void CPanel::DropObject(IDataObject *dataObject, const UString &folderPath) 2736 target.FuncType = k_DragTargetMode_Drop_End;
878{ 2737 target.Cmd_Type = cmd;
879 UStringVector names; 2738 if (needDrop_by_Source)
880 GetNamesFromDataObject(dataObject, names); 2739 target.Flags |= k_TargetFlags_MustBeProcessedBySource;
881 CompressDropFiles(names, folderPath);
882}
883 2740
884/* 2741 SendToSource_TransferInfo(dataObject, target);
885void CPanel::CompressDropFiles(HDROP dr) 2742 } catch(...) { hres = E_FAIL; }
886{ 2743
887 UStringVector fileNames; 2744 ClearState();
2745 // *effect |= (1 << 10); // for debug
2746 // *effect = DROPEFFECT_COPY; // for debug
2747
2748 /*
2749 if we return (*effect == DROPEFFECT_MOVE) here,
2750 Explorer-Source at some conditions can treat it as (unoptimized move) mode,
2751 and Explorer-Source will remove source files after DoDragDrop()
2752 in that (unoptimized move) mode.
2753 We want to avoid such (unoptimized move) cases.
2754 So we don't return (*effect == DROPEFFECT_MOVE), here if Source is not 7-Zip.
2755 If source is 7-Zip that will do acual opeartion, then we can return DROPEFFECT_MOVE.
2756 */
2757 if (hres != S_OK || (opEffect == DROPEFFECT_MOVE && !needDrop_by_Source))
888 { 2758 {
889 NShell::CDrop drop(true); 2759 // opEffect = opEffect;
890 drop.Attach(dr); 2760 // opEffect = DROPEFFECT_NONE; // for debug disabled
891 drop.QueryFileNames(fileNames);
892 } 2761 }
893 CompressDropFiles(fileNamesUnicode); 2762
2763 *effect = opEffect;
2764 /* if (hres < 0), DoDragDrop() also will return (hres).
2765 if (hres >= 0), DoDragDrop() will return DRAGDROP_S_DROP;
2766 */
2767 return hres;
894} 2768}
895*/
896 2769
897static bool IsFolderInTemp(const FString &path) 2770
2771
2772// ---------- CPanel ----------
2773
2774
2775static bool Is_Path1_Prefixed_by_Path2(const UString &path, const UString &prefix)
898{ 2776{
899 FString tempPath; 2777 const unsigned len = prefix.Len();
900 if (!MyGetTempPath(tempPath)) 2778 if (path.Len() < len)
901 return false; 2779 return false;
902 if (tempPath.IsEmpty()) 2780 return CompareFileNames(path.Left(len), prefix) == 0;
2781}
2782
2783static bool IsFolderInTemp(const UString &path)
2784{
2785 FString tempPathF;
2786 if (!MyGetTempPath(tempPathF))
903 return false; 2787 return false;
904 unsigned len = tempPath.Len(); 2788 const UString tempPath = fs2us(tempPathF);
905 if (path.Len() < len) 2789 if (tempPath.IsEmpty())
906 return false; 2790 return false;
907 return CompareFileNames(path.Left(len), tempPath) == 0; 2791 return Is_Path1_Prefixed_by_Path2(path, tempPath);
908} 2792}
909 2793
910static bool AreThereNamesFromTemp(const UStringVector &fileNames) 2794static bool AreThereNamesFromTemp(const UStringVector &filePaths)
911{ 2795{
912 FString tempPathF; 2796 FString tempPathF;
913 if (!MyGetTempPath(tempPathF)) 2797 if (!MyGetTempPath(tempPathF))
914 return false; 2798 return false;
915 UString tempPath = fs2us(tempPathF); 2799 const UString tempPath = fs2us(tempPathF);
916 if (tempPath.IsEmpty()) 2800 if (tempPath.IsEmpty())
917 return false; 2801 return false;
918 FOR_VECTOR (i, fileNames) 2802 FOR_VECTOR (i, filePaths)
919 if (fileNames[i].IsPrefixedBy_NoCase(tempPath)) 2803 if (Is_Path1_Prefixed_by_Path2(filePaths[i], tempPath))
920 return true; 2804 return true;
921 return false; 2805 return false;
922} 2806}
923 2807
924void CPanel::CompressDropFiles(const UStringVector &fileNames, const UString &folderPath) 2808
2809/*
2810 empty folderPath means create new Archive to path of first fileName.
2811 createNewArchive == true : show "Add to archive ..." dialog with external program
2812 folderPath.IsEmpty() : create archive in folder of filePaths[0].
2813 createNewArchive == false :
2814 folderPath.IsEmpty() : copy to archive folder that is open in panel
2815 !folderPath.IsEmpty() : CopyFsItems() to folderPath.
2816*/
2817void CPanel::CompressDropFiles(
2818 const UStringVector &filePaths,
2819 const UString &folderPath,
2820 bool createNewArchive,
2821 bool moveMode,
2822 UInt32 sourceFlags,
2823 UInt32 &targetFlags
2824 )
925{ 2825{
926 if (fileNames.Size() == 0) 2826 if (filePaths.Size() == 0)
927 return; 2827 return;
928 bool createNewArchive = true; 2828 // createNewArchive = false; // for debug
929 if (!IsFSFolder())
930 createNewArchive = !DoesItSupportOperations();
931 2829
932 if (createNewArchive) 2830 if (createNewArchive)
933 { 2831 {
934 UString folderPath2 = folderPath; 2832 UString folderPath2 = folderPath;
2833 // folderPath2.Empty(); // for debug
935 if (folderPath2.IsEmpty()) 2834 if (folderPath2.IsEmpty())
936 { 2835 {
937 FString folderPath2F; 2836 {
938 GetOnlyDirPrefix(us2fs(fileNames.Front()), folderPath2F); 2837 FString folderPath2F;
939 folderPath2 = fs2us(folderPath2F); 2838 GetOnlyDirPrefix(us2fs(filePaths.Front()), folderPath2F);
940 if (IsFolderInTemp(folderPath2F)) 2839 folderPath2 = fs2us(folderPath2F);
2840 }
2841 if (IsFolderInTemp(folderPath2))
2842 {
2843 /* we don't want archive to be created in temp directory.
2844 so we change the path to root folder (non-temp) */
941 folderPath2 = ROOT_FS_FOLDER; 2845 folderPath2 = ROOT_FS_FOLDER;
2846 }
942 } 2847 }
2848
2849 UString arcName_base;
2850 const UString arcName = CreateArchiveName(filePaths,
2851 false, // isHash
2852 NULL, // CFileInfo *fi
2853 arcName_base);
943 2854
944 const UString arcName = CreateArchiveName(fileNames); 2855 bool needWait;
945 2856 if (sourceFlags & k_SourceFlags_WaitFinish)
946 CompressFiles(folderPath2, arcName, L"", 2857 needWait = true;
947 true, // addExtension 2858 else if (sourceFlags & k_SourceFlags_DoNotWaitFinish)
948 fileNames, 2859 needWait = false;
949 false, // email 2860 else if (sourceFlags & k_SourceFlags_TempFiles)
950 true, // showDialog 2861 needWait = true;
951 AreThereNamesFromTemp(fileNames) // waitFinish 2862 else
952 ); 2863 needWait = AreThereNamesFromTemp(filePaths);
2864
2865 targetFlags |= (needWait ?
2866 k_TargetFlags_WaitFinish :
2867 k_TargetFlags_DoNotWaitFinish);
2868
2869 CompressFiles(folderPath2, arcName,
2870 L"", // arcType
2871 true, // addExtension
2872 filePaths,
2873 false, // email
2874 true, // showDialog
2875 needWait);
953 } 2876 }
954 else 2877 else
955 CopyFromAsk(fileNames); 2878 {
2879 targetFlags |= k_TargetFlags_WaitFinish;
2880 if (!folderPath.IsEmpty())
2881 {
2882 CCopyToOptions options;
2883 options.moveMode = moveMode;
2884 options.folder = folderPath;
2885 options.showErrorMessages = true; // showErrorMessages is not used for this operation
2886 options.NeedRegistryZone = false;
2887 options.ZoneIdMode = NExtract::NZoneIdMode::kNone;
2888 // maybe we need more options here: FIXME
2889 /* HRESULT hres = */ CopyFsItems(options,
2890 filePaths,
2891 NULL // UStringVector *messages
2892 );
2893 // hres = hres;
2894 }
2895 else
2896 {
2897 CopyFromNoAsk(moveMode, filePaths);
2898 }
2899 }
2900}
2901
2902
2903
2904static unsigned Drag_OnContextMenu(int xPos, int yPos, UInt32 cmdFlags)
2905{
2906 CMenu menu;
2907 CMenuDestroyer menuDestroyer(menu);
2908 /*
2909 Esc key in shown menu doesn't work if we call Drag_OnContextMenu from ::Drop().
2910 We call SetFocus() tp solve that problem.
2911 But the focus will be changed to Target Window after Drag and Drop.
2912 Is it OK to use SetFocus() here ?
2913 Is there another way to enable Esc key ?
2914 */
2915 // _listView.SetFocus(); // for debug
2916 ::SetFocus(g_HWND);
2917 menu.CreatePopup();
2918 /*
2919 int defaultCmd; // = NDragMenu::k_Move;
2920 defaultCmd = NDragMenu::k_None;
2921 */
2922 for (unsigned i = 0; i < Z7_ARRAY_SIZE(NDragMenu::g_Pairs); i++)
2923 {
2924 const NDragMenu::CCmdLangPair &pair = NDragMenu::g_Pairs[i];
2925 const UInt32 cmdAndFlags = pair.CmdId_and_Flags;
2926 const UInt32 cmdId = cmdAndFlags & NDragMenu::k_MenuFlags_CmdMask;
2927 if (cmdId != NDragMenu::k_Cancel)
2928 if ((cmdFlags & ((UInt32)1 << cmdId)) == 0)
2929 continue;
2930 const UINT flags = MF_STRING;
2931 /*
2932 if (prop.IsVisible)
2933 flags |= MF_CHECKED;
2934 if (i == 0)
2935 flags |= MF_GRAYED;
2936 */
2937 // MF_DEFAULT doesn't work
2938 // if (i == 2) flags |= MF_DEFAULT;
2939 // if (i == 4) flags |= MF_HILITE;
2940 // if (cmd == defaultCmd) flags |= MF_HILITE;
2941 UString name = LangString(pair.LangId);
2942 if (name.IsEmpty())
2943 {
2944 if (cmdId == NDragMenu::k_Cancel)
2945 name = "Cancel";
2946 else
2947 name.Add_UInt32(pair.LangId);
2948 }
2949 if (cmdId == NDragMenu::k_Copy_ToArc)
2950 {
2951 // UString destPath = _currentFolderPrefix;
2952 /*
2953 UString destPath = LangString(IDS_CONTEXT_ARCHIVE);
2954 name = MyFormatNew(name, destPath);
2955 */
2956 name.Add_Space();
2957 name += LangString(IDS_CONTEXT_ARCHIVE);
2958 }
2959 if (cmdId == NDragMenu::k_Cancel)
2960 menu.AppendItem(MF_SEPARATOR, 0, (LPCTSTR)NULL);
2961 menu.AppendItem(flags, cmdAndFlags, name);
2962 }
2963 /*
2964 if (defaultCmd != 0)
2965 SetMenuDefaultItem(menu, (unsigned)defaultCmd,
2966 FALSE); // byPos
2967 */
2968 int menuResult = menu.Track(
2969 TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY,
2970 xPos, yPos,
2971 g_HWND
2972 // _listView // for debug
2973 );
2974 /* menu.Track() return value is zero, if the user cancels
2975 the menu without making a selection, or if an error occurs */
2976 if (menuResult <= 0)
2977 menuResult = NDragMenu::k_Cancel;
2978 return (unsigned)menuResult;
2979}
2980
2981
2982
2983void CApp::CreateDragTarget()
2984{
2985 _dropTargetSpec = new CDropTarget();
2986 _dropTarget = _dropTargetSpec;
2987 _dropTargetSpec->App = (this);
2988}
2989
2990void CApp::SetFocusedPanel(unsigned index)
2991{
2992 LastFocusedPanel = index;
2993 _dropTargetSpec->TargetPanelIndex = (int)LastFocusedPanel;
2994}
2995
2996void CApp::DragBegin(unsigned panelIndex)
2997{
2998 _dropTargetSpec->TargetPanelIndex = (int)(NumPanels > 1 ? 1 - panelIndex : panelIndex);
2999 _dropTargetSpec->SrcPanelIndex = (int)panelIndex;
3000}
3001
3002void CApp::DragEnd()
3003{
3004 _dropTargetSpec->TargetPanelIndex = (int)LastFocusedPanel;
3005 _dropTargetSpec->SrcPanelIndex = -1;
956} 3006}
diff --git a/CPP/7zip/UI/FileManager/PanelFolderChange.cpp b/CPP/7zip/UI/FileManager/PanelFolderChange.cpp
index b91195f..a13b88d 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
133 133
134 CloseOpenFolders(); 134 CloseOpenFolders();
135 UString sysPath = path; 135 UString sysPath = path;
136 136 /* we will Empty() sysPath variable, if we need to BindToFolder()
137 unsigned prefixSize = NName::GetRootPrefixSize(sysPath); 137 directly with (path) variable */
138 const unsigned prefixSize = NName::GetRootPrefixSize(sysPath);
138 if (prefixSize == 0 || sysPath[prefixSize] == 0) 139 if (prefixSize == 0 || sysPath[prefixSize] == 0)
139 sysPath.Empty(); 140 sysPath.Empty();
140 141
@@ -142,6 +143,7 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO
142 if (!sysPath.IsEmpty() && sysPath.Back() == ':' && 143 if (!sysPath.IsEmpty() && sysPath.Back() == ':' &&
143 (sysPath.Len() != 2 || !NName::IsDrivePath2(sysPath))) 144 (sysPath.Len() != 2 || !NName::IsDrivePath2(sysPath)))
144 { 145 {
146 // if base item for alt streams prefix "base:" exists, we will use it
145 UString baseFile = sysPath; 147 UString baseFile = sysPath;
146 baseFile.DeleteBack(); 148 baseFile.DeleteBack();
147 if (NFind::DoesFileOrDirExist(us2fs(baseFile))) 149 if (NFind::DoesFileOrDirExist(us2fs(baseFile)))
@@ -153,22 +155,50 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO
153 155
154 while (!sysPath.IsEmpty()) 156 while (!sysPath.IsEmpty())
155 { 157 {
158 if (sysPath.Len() <= prefixSize)
159 {
160 path.DeleteFrom(prefixSize);
161 sysPath.Empty();
162 break;
163 }
164
165 fileInfo.ClearBase();
166 if (IsPathSepar(sysPath.Back()))
167 {
168 /* Windows 10 by default doesn't allow look "Local Settings" that is junction to "AppData\Local",
169 but it does allow look "Local Settings\Temp\*"
170 22.02: at first we try to use paths with slashes "path\" */
171 CFileInfo fi;
172 // CFindFile findFile;
173 // FString path2 = us2fs(sysPath);
174 // path2 += '*'; // CHAR_ANY_MASK;
175 // if (findFile.FindFirst(path2, fi))
176 CEnumerator enumerator;
177 enumerator.SetDirPrefix(us2fs(sysPath));
178 bool found = false;
179 if (enumerator.Next(fi, found))
180 {
181 // sysPath.DeleteBack();
182 fileInfo.SetAsDir();
183 fileInfo.Size = 0;
184 fileInfo.Name.Empty();
185 break;
186 }
187 sysPath.DeleteBack();
188 continue;
189 }
190
156 if (fileInfo.Find(us2fs(sysPath))) 191 if (fileInfo.Find(us2fs(sysPath)))
157 break; 192 break;
158 int pos = sysPath.ReverseFind_PathSepar(); 193 int pos = sysPath.ReverseFind_PathSepar();
159 if (pos < 0) 194 if (pos < 0)
195 {
160 sysPath.Empty(); 196 sysPath.Empty();
161 else 197 break;
198 }
162 { 199 {
163 /* 200 if ((unsigned)pos != sysPath.Len() - 1)
164 if (reducedParts.Size() > 0 || pos < (int)sysPath.Len() - 1)
165 reducedParts.Add(sysPath.Ptr(pos + 1));
166 */
167 #if defined(_WIN32) && !defined(UNDER_CE)
168 if (pos == 2 && NName::IsDrivePath2(sysPath) && sysPath.Len() > 3)
169 pos++; 201 pos++;
170 #endif
171
172 sysPath.DeleteFrom((unsigned)pos); 202 sysPath.DeleteFrom((unsigned)pos);
173 } 203 }
174 } 204 }
@@ -225,7 +255,7 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO
225 _folder->BindToFolder(fs2us(dirPrefix), &newFolder); 255 _folder->BindToFolder(fs2us(dirPrefix), &newFolder);
226 else 256 else
227 { 257 {
228 RINOK(res); 258 RINOK(res)
229 openRes.ArchiveIsOpened = true; 259 openRes.ArchiveIsOpened = true;
230 _parentFolders.Back().ParentFolderPath = fs2us(dirPrefix); 260 _parentFolders.Back().ParentFolderPath = fs2us(dirPrefix);
231 path.DeleteFrontal(sysPath.Len()); 261 path.DeleteFrontal(sysPath.Len());
@@ -248,12 +278,12 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO
248 for (unsigned curPos = 0; curPos != path.Len();) 278 for (unsigned curPos = 0; curPos != path.Len();)
249 { 279 {
250 UString s = path.Ptr(curPos); 280 UString s = path.Ptr(curPos);
251 int slashPos = NName::FindSepar(s); 281 const int slashPos = NName::FindSepar(s);
252 unsigned skipLen = s.Len(); 282 unsigned skipLen = s.Len();
253 if (slashPos >= 0) 283 if (slashPos >= 0)
254 { 284 {
255 s.DeleteFrom((unsigned)slashPos); 285 s.DeleteFrom((unsigned)slashPos);
256 skipLen = slashPos + 1; 286 skipLen = (unsigned)slashPos + 1;
257 } 287 }
258 288
259 CMyComPtr<IFolderFolder> newFolder; 289 CMyComPtr<IFolderFolder> newFolder;
@@ -262,13 +292,13 @@ HRESULT CPanel::BindToPath(const UString &fullPath, const UString &arcFormat, CO
262 curPos += skipLen; 292 curPos += skipLen;
263 else if (_folderAltStreams) 293 else if (_folderAltStreams)
264 { 294 {
265 int pos = s.Find(L':'); 295 const int pos = s.Find(L':');
266 if (pos >= 0) 296 if (pos >= 0)
267 { 297 {
268 UString baseName = s; 298 UString baseName = s;
269 baseName.DeleteFrom((unsigned)pos); 299 baseName.DeleteFrom((unsigned)pos);
270 if (_folderAltStreams->BindToAltStreams(baseName, &newFolder) == S_OK && newFolder) 300 if (_folderAltStreams->BindToAltStreams(baseName, &newFolder) == S_OK && newFolder)
271 curPos += pos + 1; 301 curPos += (unsigned)pos + 1;
272 } 302 }
273 } 303 }
274 304
@@ -516,14 +546,18 @@ bool CPanel::OnComboBoxCommand(UINT code, LPARAM /* param */, LRESULT &result)
516 pathParts.DeleteBack(); 546 pathParts.DeleteBack();
517 for (i = 0; i < pathParts.Size(); i++) 547 for (i = 0; i < pathParts.Size(); i++)
518 { 548 {
519 UString name = pathParts[i]; 549 const UString name = pathParts[i];
520 sumPass += name; 550 sumPass += name;
521 sumPass.Add_PathSepar(); 551 sumPass.Add_PathSepar();
522 CFileInfo info; 552 CFileInfo info;
523 DWORD attrib = FILE_ATTRIBUTE_DIRECTORY; 553 DWORD attrib = FILE_ATTRIBUTE_DIRECTORY;
524 if (info.Find(us2fs(sumPass))) 554 if (info.Find(us2fs(sumPass)))
525 attrib = info.Attrib; 555 attrib = info.Attrib;
526 AddComboBoxItem(name.IsEmpty() ? L"\\" : name, GetRealIconIndex(us2fs(sumPass), attrib), i, false); 556 AddComboBoxItem(
557 name.IsEmpty() ? L"\\" : name,
558 GetRealIconIndex(us2fs(sumPass), attrib),
559 (int)i, // iIndent
560 false); // addToList
527 ComboBoxPaths.Add(sumPass); 561 ComboBoxPaths.Add(sumPass);
528 } 562 }
529 563
@@ -633,7 +667,7 @@ void CPanel::FoldersHistory()
633 if (listViewDialog.StringsWereChanged) 667 if (listViewDialog.StringsWereChanged)
634 { 668 {
635 _appState->FolderHistory.RemoveAll(); 669 _appState->FolderHistory.RemoveAll();
636 for (int i = listViewDialog.Strings.Size() - 1; i >= 0; i--) 670 for (int i = (int)listViewDialog.Strings.Size() - 1; i >= 0; i--)
637 _appState->FolderHistory.AddString(listViewDialog.Strings[i]); 671 _appState->FolderHistory.AddString(listViewDialog.Strings[i]);
638 if (listViewDialog.FocusedItemIndex >= 0) 672 if (listViewDialog.FocusedItemIndex >= 0)
639 selectString = listViewDialog.Strings[listViewDialog.FocusedItemIndex]; 673 selectString = listViewDialog.Strings[listViewDialog.FocusedItemIndex];
@@ -695,12 +729,12 @@ void CPanel::OpenParentFolder()
695 if (focusedName != L"\\\\." && 729 if (focusedName != L"\\\\." &&
696 focusedName != L"\\\\?") 730 focusedName != L"\\\\?")
697 { 731 {
698 int pos = focusedName.ReverseFind_PathSepar(); 732 const int pos = focusedName.ReverseFind_PathSepar();
699 if (pos >= 0) 733 if (pos >= 0)
700 { 734 {
701 parentFolderPrefix = focusedName; 735 parentFolderPrefix = focusedName;
702 parentFolderPrefix.DeleteFrom((unsigned)(pos + 1)); 736 parentFolderPrefix.DeleteFrom((unsigned)(pos + 1));
703 focusedName.DeleteFrontal(pos + 1); 737 focusedName.DeleteFrontal((unsigned)(pos + 1));
704 } 738 }
705 } 739 }
706 } 740 }
@@ -812,7 +846,7 @@ void CPanel::OpenDrivesFolder()
812 RefreshListCtrl(); 846 RefreshListCtrl();
813} 847}
814 848
815void CPanel::OpenFolder(int index) 849void CPanel::OpenFolder(unsigned index)
816{ 850{
817 if (index == kParentIndex) 851 if (index == kParentIndex)
818 { 852 {
@@ -820,7 +854,7 @@ void CPanel::OpenFolder(int index)
820 return; 854 return;
821 } 855 }
822 CMyComPtr<IFolderFolder> newFolder; 856 CMyComPtr<IFolderFolder> newFolder;
823 HRESULT res = _folder->BindToFolder(index, &newFolder); 857 const HRESULT res = _folder->BindToFolder((unsigned)index, &newFolder);
824 if (res != 0) 858 if (res != 0)
825 { 859 {
826 MessageBox_Error_HRESULT(res); 860 MessageBox_Error_HRESULT(res);
@@ -839,17 +873,17 @@ void CPanel::OpenFolder(int index)
839void CPanel::OpenAltStreams() 873void CPanel::OpenAltStreams()
840{ 874{
841 CRecordVector<UInt32> indices; 875 CRecordVector<UInt32> indices;
842 GetOperatedItemIndices(indices); 876 Get_ItemIndices_Operated(indices);
843 Int32 realIndex = -1; 877 Int32 realIndex = -1;
844 if (indices.Size() > 1) 878 if (indices.Size() > 1)
845 return; 879 return;
846 if (indices.Size() == 1) 880 if (indices.Size() == 1)
847 realIndex = indices[0]; 881 realIndex = (Int32)indices[0];
848 882
849 if (_folderAltStreams) 883 if (_folderAltStreams)
850 { 884 {
851 CMyComPtr<IFolderFolder> newFolder; 885 CMyComPtr<IFolderFolder> newFolder;
852 _folderAltStreams->BindToAltStreams(realIndex, &newFolder); 886 _folderAltStreams->BindToAltStreams((UInt32)realIndex, &newFolder);
853 if (newFolder) 887 if (newFolder)
854 { 888 {
855 CDisableTimerProcessing disableTimerProcessing(*this); 889 CDisableTimerProcessing disableTimerProcessing(*this);
@@ -864,7 +898,7 @@ void CPanel::OpenAltStreams()
864 #if defined(_WIN32) && !defined(UNDER_CE) 898 #if defined(_WIN32) && !defined(UNDER_CE)
865 UString path; 899 UString path;
866 if (realIndex >= 0) 900 if (realIndex >= 0)
867 path = GetItemFullPath(realIndex); 901 path = GetItemFullPath((UInt32)realIndex);
868 else 902 else
869 { 903 {
870 path = GetFsPath(); 904 path = GetFsPath();
diff --git a/CPP/7zip/UI/FileManager/PanelItemOpen.cpp b/CPP/7zip/UI/FileManager/PanelItemOpen.cpp
index 17301b5..bd65aef 100644
--- a/CPP/7zip/UI/FileManager/PanelItemOpen.cpp
+++ b/CPP/7zip/UI/FileManager/PanelItemOpen.cpp
@@ -68,7 +68,7 @@ class CProcessSnapshot
68{ 68{
69 HANDLE _handle; 69 HANDLE _handle;
70public: 70public:
71 CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {}; 71 CProcessSnapshot(): _handle(INVALID_HANDLE_VALUE) {}
72 ~CProcessSnapshot() { Close(); } 72 ~CProcessSnapshot() { Close(); }
73 73
74 bool Close() 74 bool Close()
@@ -136,7 +136,7 @@ public:
136 void SetFromExtension(const char *ext) // ext must be low case 136 void SetFromExtension(const char *ext) // ext must be low case
137 { 137 {
138 ProgNames.Clear(); 138 ProgNames.Clear();
139 for (unsigned i = 0; i < ARRAY_SIZE(g_Progs); i++) 139 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Progs); i++)
140 if (FindExtProg(g_Progs[i].Ext, ext)) 140 if (FindExtProg(g_Progs[i].Ext, ext))
141 { 141 {
142 ProgNames.Add(g_Progs[i].Prog); 142 ProgNames.Add(g_Progs[i].Prog);
@@ -220,22 +220,25 @@ static void My_GetProcessFileName(HANDLE hProcess, UString &path)
220 const unsigned maxPath = 1024; 220 const unsigned maxPath = 1024;
221 WCHAR temp[maxPath + 1]; 221 WCHAR temp[maxPath + 1];
222 222
223 const char *func_name = "GetProcessImageFileNameW"; 223 const char *func_name =
224 Func_GetProcessImageFileNameW my_func = (Func_GetProcessImageFileNameW) 224 "GetProcessImageFileNameW";
225 (void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), func_name); 225 Func_GetProcessImageFileNameW my_func = Z7_GET_PROC_ADDRESS(
226 Func_GetProcessImageFileNameW, ::GetModuleHandleA("kernel32.dll"), func_name);
226 227
227 if (!my_func) 228 if (!my_func)
228 { 229 {
229 if (!g_Psapi_dll_module) 230 if (!g_Psapi_dll_module)
230 g_Psapi_dll_module = LoadLibraryW(L"Psapi.dll"); 231 g_Psapi_dll_module = LoadLibraryW(L"Psapi.dll");
231 if (g_Psapi_dll_module) 232 if (g_Psapi_dll_module)
232 my_func = (Func_GetProcessImageFileNameW)(void *)::GetProcAddress(g_Psapi_dll_module, func_name); 233 my_func = Z7_GET_PROC_ADDRESS(
234 Func_GetProcessImageFileNameW, g_Psapi_dll_module, func_name);
233 } 235 }
234 236
235 if (my_func) 237 if (my_func)
236 { 238 {
237 // DWORD num = GetProcessImageFileNameW(hProcess, temp, maxPath); 239 const DWORD num =
238 DWORD num = my_func(hProcess, temp, maxPath); 240 // GetProcessImageFileNameW(hProcess, temp, maxPath);
241 my_func(hProcess, temp, maxPath);
239 if (num != 0) 242 if (num != 0)
240 path = temp; 243 path = temp;
241 } 244 }
@@ -318,11 +321,13 @@ public:
318 void SetMainProcess(HANDLE h) 321 void SetMainProcess(HANDLE h)
319 { 322 {
320 #ifndef UNDER_CE 323 #ifndef UNDER_CE
321 324 const
322 Func_GetProcessId func = (Func_GetProcessId)(void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "GetProcessId"); 325 Func_GetProcessId func = Z7_GET_PROC_ADDRESS(
326 Func_GetProcessId, ::GetModuleHandleA("kernel32.dll"),
327 "GetProcessId");
323 if (func) 328 if (func)
324 { 329 {
325 DWORD id = func(h); 330 const DWORD id = func(h);
326 if (id != 0) 331 if (id != 0)
327 _ids.AddToUniqueSorted(id); 332 _ids.AddToUniqueSorted(id);
328 } 333 }
@@ -462,7 +467,7 @@ HRESULT CPanel::OpenAsArc(IInStream *inStream,
462 else 467 else
463 { 468 {
464 if (!folderLink.FileInfo.Find(folderLink.FilePath)) 469 if (!folderLink.FileInfo.Find(folderLink.FilePath))
465 return ::GetLastError(); 470 return GetLastError_noZero_HRESULT();
466 if (folderLink.FileInfo.IsDir()) 471 if (folderLink.FileInfo.IsDir())
467 return S_FALSE; 472 return S_FALSE;
468 folderLink.IsVirtual = false; 473 folderLink.IsVirtual = false;
@@ -471,14 +476,14 @@ HRESULT CPanel::OpenAsArc(IInStream *inStream,
471 folderLink.VirtualPath = virtualFilePath; 476 folderLink.VirtualPath = virtualFilePath;
472 477
473 CFfpOpen ffp; 478 CFfpOpen ffp;
474 HRESULT res = ffp.OpenFileFolderPlugin(inStream, 479 const HRESULT res = ffp.OpenFileFolderPlugin(inStream,
475 folderLink.FilePath.IsEmpty() ? us2fs(virtualFilePath) : folderLink.FilePath, 480 folderLink.FilePath.IsEmpty() ? us2fs(virtualFilePath) : folderLink.FilePath,
476 arcFormat, GetParent()); 481 arcFormat, GetParent());
477 482
478 openRes.Encrypted = ffp.Encrypted; 483 openRes.Encrypted = ffp.Encrypted;
479 openRes.ErrorMessage = ffp.ErrorMessage; 484 openRes.ErrorMessage = ffp.ErrorMessage;
480 485
481 RINOK(res); 486 RINOK(res)
482 487
483 folderLink.Password = ffp.Password; 488 folderLink.Password = ffp.Password;
484 folderLink.UsePassword = ffp.Encrypted; 489 folderLink.UsePassword = ffp.Encrypted;
@@ -571,7 +576,7 @@ HRESULT CPanel::OpenAsArc_Name(const UString &relPath, const UString &arcFormat
571} 576}
572 577
573 578
574HRESULT CPanel::OpenAsArc_Index(int index, const wchar_t *type 579HRESULT CPanel::OpenAsArc_Index(unsigned index, const wchar_t *type
575 // , bool showErrorMessage 580 // , bool showErrorMessage
576 ) 581 )
577{ 582{
@@ -653,36 +658,13 @@ static const char * const kStartExtensions =
653 " mak clw csproj vcproj sln dsp dsw" 658 " mak clw csproj vcproj sln dsp dsw"
654 " "; 659 " ";
655 660
656static bool FindExt(const char *p, const UString &name) 661// bool FindExt(const char *p, const UString &name, AString &s);
657{ 662bool FindExt(const char *p, const UString &name, CStringFinder &finder);
658 int dotPos = name.ReverseFind_Dot();
659 if (dotPos < 0 || dotPos == (int)name.Len() - 1)
660 return false;
661
662 AString s;
663 for (unsigned pos = dotPos + 1;; pos++)
664 {
665 wchar_t c = name[pos];
666 if (c == 0)
667 break;
668 if (c >= 0x80)
669 return false;
670 s += (char)MyCharLower_Ascii((char)c);
671 }
672 for (unsigned i = 0; p[i] != 0;)
673 {
674 unsigned j;
675 for (j = i; p[j] != ' '; j++);
676 if (s.Len() == j - i && memcmp(p + i, (const char *)s, s.Len()) == 0)
677 return true;
678 i = j + 1;
679 }
680 return false;
681}
682 663
683static bool DoItemAlwaysStart(const UString &name) 664static bool DoItemAlwaysStart(const UString &name)
684{ 665{
685 return FindExt(kStartExtensions, name); 666 CStringFinder finder;
667 return FindExt(kStartExtensions, name, finder);
686} 668}
687 669
688UString GetQuotedString(const UString &s); 670UString GetQuotedString(const UString &s);
@@ -754,10 +736,10 @@ static HRESULT StartEditApplication(const UString &path, bool useEditor, HWND wi
754 UStringVector params; 736 UStringVector params;
755 params.Add(path); 737 params.Add(path);
756 738
757 HRESULT res = StartAppWithParams(command, params, process); 739 const WRes res = StartAppWithParams(command, params, process);
758 if (res != SZ_OK) 740 if (res != 0)
759 ::MessageBoxW(window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP); 741 ::MessageBoxW(window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP);
760 return res; 742 return HRESULT_FROM_WIN32(res);
761} 743}
762 744
763 745
@@ -772,7 +754,7 @@ void CApp::DiffFiles()
772 } 754 }
773 755
774 CRecordVector<UInt32> indices; 756 CRecordVector<UInt32> indices;
775 panel.GetSelectedItemsIndices(indices); 757 panel.Get_ItemIndices_Selected(indices);
776 758
777 UString path1, path2; 759 UString path1, path2;
778 if (indices.Size() == 2) 760 if (indices.Size() == 2)
@@ -792,7 +774,7 @@ void CApp::DiffFiles()
792 774
793 path1 = panel.GetItemFullPath(indices[0]); 775 path1 = panel.GetItemFullPath(indices[0]);
794 CRecordVector<UInt32> indices2; 776 CRecordVector<UInt32> indices2;
795 destPanel.GetSelectedItemsIndices(indices2); 777 destPanel.Get_ItemIndices_Selected(indices2);
796 if (indices2.Size() == 1) 778 if (indices2.Size() == 1)
797 path2 = destPanel.GetItemFullPath(indices2[0]); 779 path2 = destPanel.GetItemFullPath(indices2[0]);
798 else 780 else
@@ -820,19 +802,19 @@ void CApp::DiffFiles(const UString &path1, const UString &path2)
820 params.Add(path1); 802 params.Add(path1);
821 params.Add(path2); 803 params.Add(path2);
822 804
823 HRESULT res; 805 WRes res;
824 { 806 {
825 CProcess process; 807 CProcess process;
826 res = StartAppWithParams(command, params, process); 808 res = StartAppWithParams(command, params, process);
827 } 809 }
828 if (res == SZ_OK) 810 if (res == 0)
829 return; 811 return;
830 ::MessageBoxW(_window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP); 812 ::MessageBoxW(_window, LangString(IDS_CANNOT_START_EDITOR), L"7-Zip", MB_OK | MB_ICONSTOP);
831} 813}
832 814
833 815
834#ifndef _UNICODE 816#ifndef _UNICODE
835typedef BOOL (WINAPI * ShellExecuteExWP)(LPSHELLEXECUTEINFOW lpExecInfo); 817typedef BOOL (WINAPI * Func_ShellExecuteExW)(LPSHELLEXECUTEINFOW lpExecInfo);
836#endif 818#endif
837 819
838static HRESULT StartApplication(const UString &dir, const UString &path, HWND window, CProcess &process) 820static HRESULT StartApplication(const UString &dir, const UString &path, HWND window, CProcess &process)
@@ -844,7 +826,7 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi
844 int dot = path2.ReverseFind_Dot(); 826 int dot = path2.ReverseFind_Dot();
845 int separ = path2.ReverseFind_PathSepar(); 827 int separ = path2.ReverseFind_PathSepar();
846 if (dot < 0 || dot < separ) 828 if (dot < 0 || dot < separ)
847 path2 += '.'; 829 path2.Add_Dot();
848 } 830 }
849 #endif 831 #endif
850 832
@@ -862,12 +844,15 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi
862 execInfo.lpParameters = NULL; 844 execInfo.lpParameters = NULL;
863 execInfo.lpDirectory = dir.IsEmpty() ? NULL : (LPCWSTR)dir; 845 execInfo.lpDirectory = dir.IsEmpty() ? NULL : (LPCWSTR)dir;
864 execInfo.nShow = SW_SHOWNORMAL; 846 execInfo.nShow = SW_SHOWNORMAL;
865 execInfo.hProcess = 0; 847 execInfo.hProcess = NULL;
866 ShellExecuteExWP shellExecuteExW = (ShellExecuteExWP) 848 const
867 (void *)::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "ShellExecuteExW"); 849 Func_ShellExecuteExW
868 if (!shellExecuteExW) 850 f_ShellExecuteExW = Z7_GET_PROC_ADDRESS(
851 Func_ShellExecuteExW, ::GetModuleHandleW(L"shell32.dll"),
852 "ShellExecuteExW");
853 if (!f_ShellExecuteExW)
869 return 0; 854 return 0;
870 shellExecuteExW(&execInfo); 855 f_ShellExecuteExW(&execInfo);
871 result = (UINT32)(UINT_PTR)execInfo.hInstApp; 856 result = (UINT32)(UINT_PTR)execInfo.hInstApp;
872 process.Attach(execInfo.hProcess); 857 process.Attach(execInfo.hProcess);
873 } 858 }
@@ -895,7 +880,7 @@ static HRESULT StartApplication(const UString &dir, const UString &path, HWND wi
895 #endif 880 #endif
896 ; 881 ;
897 execInfo.nShow = SW_SHOWNORMAL; 882 execInfo.nShow = SW_SHOWNORMAL;
898 execInfo.hProcess = 0; 883 execInfo.hProcess = NULL;
899 ::ShellExecuteEx(&execInfo); 884 ::ShellExecuteEx(&execInfo);
900 result = (UINT32)(UINT_PTR)execInfo.hInstApp; 885 result = (UINT32)(UINT_PTR)execInfo.hInstApp;
901 process.Attach(execInfo.hProcess); 886 process.Attach(execInfo.hProcess);
@@ -927,7 +912,7 @@ static void StartApplicationDontWait(const UString &dir, const UString &path, HW
927 StartApplication(dir, path, window, process); 912 StartApplication(dir, path, window, process);
928} 913}
929 914
930void CPanel::EditItem(int index, bool useEditor) 915void CPanel::EditItem(unsigned index, bool useEditor)
931{ 916{
932 if (!_parentFolders.IsEmpty()) 917 if (!_parentFolders.IsEmpty())
933 { 918 {
@@ -939,7 +924,7 @@ void CPanel::EditItem(int index, bool useEditor)
939} 924}
940 925
941 926
942void CPanel::OpenFolderExternal(int index) 927void CPanel::OpenFolderExternal(unsigned index)
943{ 928{
944 UString prefix = GetFsPath(); 929 UString prefix = GetFsPath();
945 UString path = prefix; 930 UString path = prefix;
@@ -1010,9 +995,10 @@ bool CPanel::IsVirus_Message(const UString &name)
1010 } 995 }
1011 if (i != name2.Len()) 996 if (i != name2.Len())
1012 { 997 {
998 CStringFinder finder;
1013 UString name3 = name2; 999 UString name3 = name2;
1014 name3.DeleteFrom(i); 1000 name3.DeleteFrom(i);
1015 if (FindExt(kExeExtensions, name3)) 1001 if (FindExt(kExeExtensions, name3, finder))
1016 isVirus = true; 1002 isVirus = true;
1017 } 1003 }
1018 } 1004 }
@@ -1025,13 +1011,13 @@ bool CPanel::IsVirus_Message(const UString &name)
1025 1011
1026 if (!isSpaceError) 1012 if (!isSpaceError)
1027 { 1013 {
1028 int pos1 = s.Find(L'('); 1014 const int pos1 = s.Find(L'(');
1029 if (pos1 >= 0) 1015 if (pos1 >= 0)
1030 { 1016 {
1031 int pos2 = s.Find(L')', pos1 + 1); 1017 const int pos2 = s.Find(L')', (unsigned)pos1 + 1);
1032 if (pos2 >= 0) 1018 if (pos2 >= 0)
1033 { 1019 {
1034 s.Delete(pos1, pos2 + 1 - pos1); 1020 s.Delete((unsigned)pos1, (unsigned)pos2 + 1 - (unsigned)pos1);
1035 if (pos1 > 0 && s[pos1 - 1] == ' ' && s[pos1] == '.') 1021 if (pos1 > 0 && s[pos1 - 1] == ' ' && s[pos1] == '.')
1036 s.Delete(pos1 - 1); 1022 s.Delete(pos1 - 1);
1037 } 1023 }
@@ -1050,10 +1036,10 @@ bool CPanel::IsVirus_Message(const UString &name)
1050} 1036}
1051 1037
1052 1038
1053void CPanel::OpenItem(int index, bool tryInternal, bool tryExternal, const wchar_t *type) 1039void CPanel::OpenItem(unsigned index, bool tryInternal, bool tryExternal, const wchar_t *type)
1054{ 1040{
1055 CDisableTimerProcessing disableTimerProcessing(*this); 1041 CDisableTimerProcessing disableTimerProcessing(*this);
1056 UString name = GetItemRelPath2(index); 1042 const UString name = GetItemRelPath2(index);
1057 1043
1058 if (tryExternal) 1044 if (tryExternal)
1059 if (IsVirus_Message(name)) 1045 if (IsVirus_Message(name))
@@ -1096,7 +1082,7 @@ void CPanel::OpenItem(int index, bool tryInternal, bool tryExternal, const wchar
1096 1082
1097class CThreadCopyFrom: public CProgressThreadVirt 1083class CThreadCopyFrom: public CProgressThreadVirt
1098{ 1084{
1099 HRESULT ProcessVirt(); 1085 HRESULT ProcessVirt() Z7_override;
1100public: 1086public:
1101 UString FullPath; 1087 UString FullPath;
1102 UInt32 ItemIndex; 1088 UInt32 ItemIndex;
@@ -1133,7 +1119,7 @@ HRESULT CPanel::OnOpenItemChanged(UInt32 index, const wchar_t *fullFilePath,
1133 t.UpdateCallbackSpec->Password = password; 1119 t.UpdateCallbackSpec->Password = password;
1134 1120
1135 1121
1136 RINOK(t.Create(GetItemName(index), (HWND)*this)); 1122 RINOK(t.Create(GetItemName(index), (HWND)*this))
1137 return t.Result; 1123 return t.Result;
1138} 1124}
1139 1125
@@ -1292,7 +1278,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param)
1292 1278
1293 if (firstPass && indices.Size() == 1) 1279 if (firstPass && indices.Size() == 1)
1294 { 1280 {
1295 DWORD curTime = GetTickCount() - startTime; 1281 const DWORD curTime = GetTickCount() - startTime;
1296 1282
1297 /* 1283 /*
1298 if (curTime > 5 * 1000) 1284 if (curTime > 5 * 1000)
@@ -1312,7 +1298,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param)
1312 DEBUG_PRINT_NUM(" -- firstPass -- time = ", curTime) 1298 DEBUG_PRINT_NUM(" -- firstPass -- time = ", curTime)
1313 } 1299 }
1314 1300
1315 processes.DisableWait(indices[waitResult]); 1301 processes.DisableWait(indices[(unsigned)waitResult]);
1316 } 1302 }
1317 1303
1318 firstPass = false; 1304 firstPass = false;
@@ -1324,7 +1310,7 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param)
1324 } 1310 }
1325 1311
1326 1312
1327 DWORD curTime = GetTickCount() - startTime; 1313 const DWORD curTime = GetTickCount() - startTime;
1328 1314
1329 DEBUG_PRINT_NUM("after time = ", curTime) 1315 DEBUG_PRINT_NUM("after time = ", curTime)
1330 1316
@@ -1444,15 +1430,14 @@ static bool WriteZoneFile(CFSTR fileName, const CByteBuffer &buf)
1444*/ 1430*/
1445 1431
1446/* 1432/*
1447class CBufSeqOutStream_WithFile: 1433Z7_CLASS_IMP_COM_1(
1448 public ISequentialOutStream, 1434 CBufSeqOutStream_WithFile
1449 public CMyUnknownImp 1435 , ISequentialOutStream
1450{ 1436)
1451 Byte *_buffer; 1437 Byte *_buffer;
1452 size_t _size; 1438 size_t _size;
1453 size_t _pos; 1439 size_t _pos;
1454 1440
1455
1456 size_t _fileWritePos; 1441 size_t _fileWritePos;
1457 bool fileMode; 1442 bool fileMode;
1458public: 1443public:
@@ -1478,9 +1463,6 @@ public:
1478 1463
1479 HRESULT FlushToFile(); 1464 HRESULT FlushToFile();
1480 size_t GetPos() const { return _pos; } 1465 size_t GetPos() const { return _pos; }
1481
1482 MY_UNKNOWN_IMP
1483 STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
1484}; 1466};
1485 1467
1486static const UInt32 kBlockSize = ((UInt32)1 << 31); 1468static const UInt32 kBlockSize = ((UInt32)1 << 31);
@@ -1565,7 +1547,7 @@ tryInternal tryExternal
1565 alwaysStart(name) : external 1547 alwaysStart(name) : external
1566*/ 1548*/
1567 1549
1568void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bool editMode, bool useEditor, const wchar_t *type) 1550void CPanel::OpenItemInArchive(unsigned index, bool tryInternal, bool tryExternal, bool editMode, bool useEditor, const wchar_t *type)
1569{ 1551{
1570 // we don't want to change hash data here 1552 // we don't want to change hash data here
1571 if (IsHashFolder()) 1553 if (IsHashFolder())
@@ -1830,7 +1812,7 @@ void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bo
1830 // win7 / win10 work so for some extensions (pdf, html ..); 1812 // win7 / win10 work so for some extensions (pdf, html ..);
1831 DEBUG_PRINT("#### (HANDLE)process == 0"); 1813 DEBUG_PRINT("#### (HANDLE)process == 0");
1832 // return; 1814 // return;
1833 if (res != SZ_OK) 1815 if (res != S_OK)
1834 return; 1816 return;
1835 } 1817 }
1836 1818
@@ -1839,7 +1821,7 @@ void CPanel::OpenItemInArchive(int index, bool tryInternal, bool tryExternal, bo
1839 tpi->FileIndex = index; 1821 tpi->FileIndex = index;
1840 tpi->RelPath = relPath; 1822 tpi->RelPath = relPath;
1841 1823
1842 if ((HANDLE)process != 0) 1824 if ((HANDLE)process)
1843 tpi->Processes.SetMainProcess(process.Detach()); 1825 tpi->Processes.SetMainProcess(process.Detach());
1844 1826
1845 ::CThread th; 1827 ::CThread th;
diff --git a/CPP/7zip/UI/FileManager/PanelItems.cpp b/CPP/7zip/UI/FileManager/PanelItems.cpp
index 3cccf27..0cb33d8 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)
41 return true; 41 return true;
42} 42}
43 43
44static int GetColumnWidth(PROPID propID, VARTYPE /* varType */) 44static unsigned GetColumnWidth(PROPID propID, VARTYPE /* varType */)
45{ 45{
46 switch (propID) 46 switch (propID)
47 { 47 {
@@ -216,7 +216,7 @@ HRESULT CPanel::InitColumns()
216 item.IsVisible = isVisible; 216 item.IsVisible = isVisible;
217 item.Width = columnInfo.Width; 217 item.Width = columnInfo.Width;
218 if (isVisible) 218 if (isVisible)
219 item.Order = order++; 219 item.Order = (int)(order++);
220 continue; 220 continue;
221 } 221 }
222 } 222 }
@@ -225,14 +225,14 @@ HRESULT CPanel::InitColumns()
225 { 225 {
226 CPropColumn &item = _columns[i]; 226 CPropColumn &item = _columns[i];
227 if (item.IsVisible && item.Order < 0) 227 if (item.IsVisible && item.Order < 0)
228 item.Order = order++; 228 item.Order = (int)(order++);
229 } 229 }
230 230
231 for (i = 0; i < _columns.Size(); i++) 231 for (i = 0; i < _columns.Size(); i++)
232 { 232 {
233 CPropColumn &item = _columns[i]; 233 CPropColumn &item = _columns[i];
234 if (item.Order < 0) 234 if (item.Order < 0)
235 item.Order = order++; 235 item.Order = (int)(order++);
236 } 236 }
237 237
238 CPropColumns newColumns; 238 CPropColumns newColumns;
@@ -285,14 +285,14 @@ HRESULT CPanel::InitColumns()
285 { 285 {
286 const CPropColumn &prop = newColumns[i]; 286 const CPropColumn &prop = newColumns[i];
287 if (prop.Order < (int)newColumns.Size() && columns[prop.Order] == -1) 287 if (prop.Order < (int)newColumns.Size() && columns[prop.Order] == -1)
288 columns[prop.Order] = i; 288 columns[prop.Order] = (int)i;
289 else 289 else
290 orderError = true; 290 orderError = true;
291 } 291 }
292 292
293 for (;;) 293 for (;;)
294 { 294 {
295 unsigned numColumns = _visibleColumns.Size(); 295 const unsigned numColumns = _visibleColumns.Size();
296 if (numColumns == 0) 296 if (numColumns == 0)
297 break; 297 break;
298 DeleteColumn(numColumns - 1); 298 DeleteColumn(numColumns - 1);
@@ -319,14 +319,14 @@ void CPanel::DeleteColumn(unsigned index)
319 319
320void CPanel::AddColumn(const CPropColumn &prop) 320void CPanel::AddColumn(const CPropColumn &prop)
321{ 321{
322 const int index = _visibleColumns.Size(); 322 const unsigned index = _visibleColumns.Size();
323 323
324 LV_COLUMNW column; 324 LV_COLUMNW column;
325 column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM | LVCF_ORDER; 325 column.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM | LVCF_ORDER;
326 column.cx = prop.Width; 326 column.cx = (int)prop.Width;
327 column.fmt = GetColumnAlign(prop.ID, prop.Type); 327 column.fmt = GetColumnAlign(prop.ID, prop.Type);
328 column.iOrder = index; // must be <= _listView.ItemCount 328 column.iOrder = (int)index; // must be <= _listView.ItemCount
329 column.iSubItem = index; // must be <= _listView.ItemCount 329 column.iSubItem = (int)index; // must be <= _listView.ItemCount
330 column.pszText = const_cast<wchar_t *>((const wchar_t *)prop.Name); 330 column.pszText = const_cast<wchar_t *>((const wchar_t *)prop.Name);
331 331
332 _visibleColumns.Add(prop); 332 _visibleColumns.Add(prop);
@@ -346,7 +346,7 @@ int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData);
346void CPanel::GetSelectedNames(UStringVector &selectedNames) 346void CPanel::GetSelectedNames(UStringVector &selectedNames)
347{ 347{
348 CRecordVector<UInt32> indices; 348 CRecordVector<UInt32> indices;
349 GetSelectedItemsIndices(indices); 349 Get_ItemIndices_Selected(indices);
350 selectedNames.ClearAndReserve(indices.Size()); 350 selectedNames.ClearAndReserve(indices.Size());
351 FOR_VECTOR (i, indices) 351 FOR_VECTOR (i, indices)
352 selectedNames.AddInReserved(GetItemRelPath(indices[i])); 352 selectedNames.AddInReserved(GetItemRelPath(indices[i]));
@@ -364,7 +364,7 @@ void CPanel::GetSelectedNames(UStringVector &selectedNames)
364 item.mask = LVIF_TEXT | LVIF_PARAM; 364 item.mask = LVIF_TEXT | LVIF_PARAM;
365 if (!_listView.GetItem(&item)) 365 if (!_listView.GetItem(&item))
366 continue; 366 continue;
367 int realIndex = GetRealIndex(item); 367 const unsigned realIndex = GetRealIndex(item);
368 if (realIndex == kParentIndex) 368 if (realIndex == kParentIndex)
369 continue; 369 continue;
370 if (_selectedStatusVector[realIndex]) 370 if (_selectedStatusVector[realIndex])
@@ -384,7 +384,7 @@ void CPanel::SaveSelectedState(CSelectedState &s)
384 { 384 {
385 if (s.FocusedItem >= 0) 385 if (s.FocusedItem >= 0)
386 { 386 {
387 int realIndex = GetRealItemIndex(s.FocusedItem); 387 const unsigned realIndex = GetRealItemIndex(s.FocusedItem);
388 if (realIndex != kParentIndex) 388 if (realIndex != kParentIndex)
389 { 389 {
390 s.FocusedName = GetItemRelPath(realIndex); 390 s.FocusedName = GetItemRelPath(realIndex);
@@ -422,10 +422,11 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &s)
422} 422}
423*/ 423*/
424 424
425HRESULT CPanel::RefreshListCtrl_SaveFocused() 425HRESULT CPanel::RefreshListCtrl_SaveFocused(bool onTimer)
426{ 426{
427 CSelectedState state; 427 CSelectedState state;
428 SaveSelectedState(state); 428 SaveSelectedState(state);
429 state.CalledFromTimer = onTimer;
429 return RefreshListCtrl(state); 430 return RefreshListCtrl(state);
430} 431}
431 432
@@ -437,7 +438,7 @@ void CPanel::SetFocusedSelectedItem(int index, bool select)
437 _listView.SetItemState(index, state, state); 438 _listView.SetItemState(index, state, state);
438 if (!_mySelectMode && select) 439 if (!_mySelectMode && select)
439 { 440 {
440 int realIndex = GetRealItemIndex(index); 441 const unsigned realIndex = GetRealItemIndex(index);
441 if (realIndex != kParentIndex) 442 if (realIndex != kParentIndex)
442 _selectedStatusVector[realIndex] = true; 443 _selectedStatusVector[realIndex] = true;
443 } 444 }
@@ -464,6 +465,9 @@ extern UInt32 g_NumMessages;
464 465
465HRESULT CPanel::RefreshListCtrl(const CSelectedState &state) 466HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
466{ 467{
468 m_DropHighlighted_SelectionIndex = -1;
469 m_DropHighlighted_SubFolderName.Empty();
470
467 if (!_folder) 471 if (!_folder)
468 return S_OK; 472 return S_OK;
469 473
@@ -474,7 +478,8 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
474 */ 478 */
475 479
476 _dontShowMode = false; 480 _dontShowMode = false;
477 LoadFullPathAndShow(); 481 if (!state.CalledFromTimer)
482 LoadFullPathAndShow();
478 // OutputDebugStringA("=======\n"); 483 // OutputDebugStringA("=======\n");
479 // OutputDebugStringA("s1 \n"); 484 // OutputDebugStringA("s1 \n");
480 CDisableTimerProcessing timerProcessing(*this); 485 CDisableTimerProcessing timerProcessing(*this);
@@ -506,11 +511,13 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
506 511
507 // m_Files.Clear(); 512 // m_Files.Clear();
508 513
514 /*
509 if (!_folder) 515 if (!_folder)
510 { 516 {
511 // throw 1; 517 // throw 1;
512 SetToRootFolder(); 518 SetToRootFolder();
513 } 519 }
520 */
514 521
515 _headerToolBar.EnableButton(kParentFolderID, !IsRootFolder()); 522 _headerToolBar.EnableButton(kParentFolderID, !IsRootFolder());
516 523
@@ -530,16 +537,44 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
530 } 537 }
531 */ 538 */
532 539
540 _isDirVector.Clear();
533 // DWORD tickCount1 = GetTickCount(); 541 // DWORD tickCount1 = GetTickCount();
534 RINOK(_folder->LoadItems()); 542 IFolderFolder *folder = _folder;
543 RINOK(_folder->LoadItems())
535 // DWORD tickCount2 = GetTickCount(); 544 // DWORD tickCount2 = GetTickCount();
536 RINOK(InitColumns());
537
538 // OutputDebugString(TEXT("Start Dir\n")); 545 // OutputDebugString(TEXT("Start Dir\n"));
546 RINOK(InitColumns())
547
539 UInt32 numItems; 548 UInt32 numItems;
540 _folder->GetNumberOfItems(&numItems); 549 _folder->GetNumberOfItems(&numItems);
550 {
551 NCOM::CPropVariant prop;
552 _isDirVector.ClearAndSetSize(numItems);
553 bool *vec = (bool *)&_isDirVector.Front();
554 HRESULT hres = S_OK;
555 unsigned i;
556 for (i = 0; i < numItems; i++)
557 {
558 hres = folder->GetProperty(i, kpidIsDir, &prop);
559 if (hres != S_OK)
560 break;
561 bool v = false;
562 if (prop.vt == VT_BOOL)
563 v = VARIANT_BOOLToBool(prop.boolVal);
564 else if (prop.vt != VT_EMPTY)
565 break;
566 vec[i] = v;
567 }
568 if (i != numItems)
569 {
570 _isDirVector.Clear();
571 if (hres == S_OK)
572 hres = E_FAIL;
573 }
574 RINOK(hres)
575 }
541 576
542 bool showDots = _showDots && !IsRootFolder(); 577 const bool showDots = _showDots && !IsRootFolder();
543 578
544 _listView.SetItemCount(numItems + (showDots ? 1 : 0)); 579 _listView.SetItemCount(numItems + (showDots ? 1 : 0));
545 580
@@ -582,20 +617,20 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
582 617
583 if (showDots) 618 if (showDots)
584 { 619 {
585 UString itemName (".."); 620 const UString itemName ("..");
586 item.iItem = listViewItemCount; 621 item.iItem = listViewItemCount;
587 if (itemName == state.FocusedName) 622 if (itemName == state.FocusedName)
588 cursorIndex = listViewItemCount; 623 cursorIndex = listViewItemCount;
589 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; 624 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
590 int subItem = 0; 625 int subItem = 0;
591 item.iSubItem = subItem++; 626 item.iSubItem = subItem++;
592 item.lParam = kParentIndex; 627 item.lParam = (LPARAM)(int)kParentIndex;
593 #ifdef USE_EMBED_ITEM 628 #ifdef USE_EMBED_ITEM
594 item.pszText = const_cast<wchar_t *>((const wchar_t *)itemName); 629 item.pszText = const_cast<wchar_t *>((const wchar_t *)itemName);
595 #else 630 #else
596 item.pszText = LPSTR_TEXTCALLBACKW; 631 item.pszText = LPSTR_TEXTCALLBACKW;
597 #endif 632 #endif
598 UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY; 633 const UInt32 attrib = FILE_ATTRIBUTE_DIRECTORY;
599 item.iImage = _extToIconMap.GetIconIndex(attrib, itemName); 634 item.iImage = _extToIconMap.GetIconIndex(attrib, itemName);
600 if (item.iImage < 0) 635 if (item.iImage < 0)
601 item.iImage = 0; 636 item.iImage = 0;
@@ -671,7 +706,7 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
671 item.iItem = listViewItemCount; 706 item.iItem = listViewItemCount;
672 707
673 item.iSubItem = subItem++; 708 item.iSubItem = subItem++;
674 item.lParam = i; 709 item.lParam = (LPARAM)i;
675 710
676 /* 711 /*
677 int finish = nameLen - 4; 712 int finish = nameLen - 4;
@@ -731,7 +766,7 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
731 UInt32 attrib = 0; 766 UInt32 attrib = 0;
732 { 767 {
733 NCOM::CPropVariant prop; 768 NCOM::CPropVariant prop;
734 RINOK(_folder->GetProperty(i, kpidAttrib, &prop)); 769 RINOK(_folder->GetProperty(i, kpidAttrib, &prop))
735 if (prop.vt == VT_UI4) 770 if (prop.vt == VT_UI4)
736 attrib = prop.ulVal; 771 attrib = prop.ulVal;
737 } 772 }
@@ -844,7 +879,7 @@ HRESULT CPanel::RefreshListCtrl(const CSelectedState &state)
844} 879}
845 880
846 881
847void CPanel::GetSelectedItemsIndices(CRecordVector<UInt32> &indices) const 882void CPanel::Get_ItemIndices_Selected(CRecordVector<UInt32> &indices) const
848{ 883{
849 indices.Clear(); 884 indices.Clear();
850 /* 885 /*
@@ -858,46 +893,49 @@ void CPanel::GetSelectedItemsIndices(CRecordVector<UInt32> &indices) const
858 HeapSort(&indices.Front(), indices.Size()); 893 HeapSort(&indices.Front(), indices.Size());
859 */ 894 */
860 const bool *v = &_selectedStatusVector.Front(); 895 const bool *v = &_selectedStatusVector.Front();
861 unsigned size = _selectedStatusVector.Size(); 896 const unsigned size = _selectedStatusVector.Size();
862 for (unsigned i = 0; i < size; i++) 897 for (unsigned i = 0; i < size; i++)
863 if (v[i]) 898 if (v[i])
864 indices.Add(i); 899 indices.Add(i);
865} 900}
866 901
867 902
868void CPanel::GetOperatedItemIndices(CRecordVector<UInt32> &indices) const 903void CPanel::Get_ItemIndices_Operated(CRecordVector<UInt32> &indices) const
869{ 904{
870 GetSelectedItemsIndices(indices); 905 Get_ItemIndices_Selected(indices);
871 if (!indices.IsEmpty()) 906 if (!indices.IsEmpty())
872 return; 907 return;
873 if (_listView.GetSelectedCount() == 0) 908 if (_listView.GetSelectedCount() == 0)
874 return; 909 return;
875 int focusedItem = _listView.GetFocusedItem(); 910 const int focusedItem = _listView.GetFocusedItem();
876 if (focusedItem >= 0) 911 if (focusedItem >= 0)
877 { 912 {
878 if (_listView.IsItemSelected(focusedItem)) 913 if (_listView.IsItemSelected(focusedItem))
879 { 914 {
880 int realIndex = GetRealItemIndex(focusedItem); 915 const unsigned realIndex = GetRealItemIndex(focusedItem);
881 if (realIndex != kParentIndex) 916 if (realIndex != kParentIndex)
882 indices.Add(realIndex); 917 indices.Add(realIndex);
883 } 918 }
884 } 919 }
885} 920}
886 921
887void CPanel::GetAllItemIndices(CRecordVector<UInt32> &indices) const 922void CPanel::Get_ItemIndices_All(CRecordVector<UInt32> &indices) const
888{ 923{
889 indices.Clear(); 924 indices.Clear();
890 UInt32 numItems; 925 UInt32 numItems;
891 if (_folder->GetNumberOfItems(&numItems) == S_OK) 926 if (_folder->GetNumberOfItems(&numItems) != S_OK)
892 for (UInt32 i = 0; i < numItems; i++) 927 return;
893 indices.Add(i); 928 indices.ClearAndSetSize(numItems);
929 UInt32 *vec = (UInt32 *)&indices.Front();
930 for (UInt32 i = 0; i < numItems; i++)
931 vec[i] = i;
894} 932}
895 933
896void CPanel::GetOperatedIndicesSmart(CRecordVector<UInt32> &indices) const 934void CPanel::Get_ItemIndices_OperSmart(CRecordVector<UInt32> &indices) const
897{ 935{
898 GetOperatedItemIndices(indices); 936 Get_ItemIndices_Operated(indices);
899 if (indices.IsEmpty() || (indices.Size() == 1 && indices[0] == (UInt32)(Int32)-1)) 937 if (indices.IsEmpty() || (indices.Size() == 1 && indices[0] == (UInt32)(Int32)-1))
900 GetAllItemIndices(indices); 938 Get_ItemIndices_All(indices);
901} 939}
902 940
903/* 941/*
@@ -907,14 +945,14 @@ void CPanel::GetOperatedListViewIndices(CRecordVector<UInt32> &indices) const
907 int numItems = _listView.GetItemCount(); 945 int numItems = _listView.GetItemCount();
908 for (int i = 0; i < numItems; i++) 946 for (int i = 0; i < numItems; i++)
909 { 947 {
910 int realIndex = GetRealItemIndex(i); 948 const unsigned realIndex = GetRealItemIndex(i);
911 if (realIndex >= 0) 949 if (realIndex >= 0)
912 if (_selectedStatusVector[realIndex]) 950 if (_selectedStatusVector[realIndex])
913 indices.Add(i); 951 indices.Add(i);
914 } 952 }
915 if (indices.IsEmpty()) 953 if (indices.IsEmpty())
916 { 954 {
917 int focusedItem = _listView.GetFocusedItem(); 955 const int focusedItem = _listView.GetFocusedItem();
918 if (focusedItem >= 0) 956 if (focusedItem >= 0)
919 indices.Add(focusedItem); 957 indices.Add(focusedItem);
920 } 958 }
@@ -931,7 +969,7 @@ void CPanel::EditItem(bool useEditor)
931 { 969 {
932 bool needRefresh = false; 970 bool needRefresh = false;
933 CRecordVector<UInt32> indices; 971 CRecordVector<UInt32> indices;
934 GetOperatedItemIndices(indices); 972 Get_ItemIndices_Operated(indices);
935 FOR_VECTOR (i, indices) 973 FOR_VECTOR (i, indices)
936 { 974 {
937 UInt32 index = indices[i]; 975 UInt32 index = indices[i];
@@ -952,10 +990,10 @@ void CPanel::EditItem(bool useEditor)
952 } 990 }
953 991
954 992
955 int focusedItem = _listView.GetFocusedItem(); 993 const int focusedItem = _listView.GetFocusedItem();
956 if (focusedItem < 0) 994 if (focusedItem < 0)
957 return; 995 return;
958 int realIndex = GetRealItemIndex(focusedItem); 996 const unsigned realIndex = GetRealItemIndex(focusedItem);
959 if (realIndex == kParentIndex) 997 if (realIndex == kParentIndex)
960 return; 998 return;
961 if (!IsItem_Folder(realIndex)) 999 if (!IsItem_Folder(realIndex))
@@ -964,10 +1002,10 @@ void CPanel::EditItem(bool useEditor)
964 1002
965void CPanel::OpenFocusedItemAsInternal(const wchar_t *type) 1003void CPanel::OpenFocusedItemAsInternal(const wchar_t *type)
966{ 1004{
967 int focusedItem = _listView.GetFocusedItem(); 1005 const int focusedItem = _listView.GetFocusedItem();
968 if (focusedItem < 0) 1006 if (focusedItem < 0)
969 return; 1007 return;
970 int realIndex = GetRealItemIndex(focusedItem); 1008 const unsigned realIndex = GetRealItemIndex(focusedItem);
971 if (IsItem_Folder(realIndex)) 1009 if (IsItem_Folder(realIndex))
972 OpenFolder(realIndex); 1010 OpenFolder(realIndex);
973 else 1011 else
@@ -977,17 +1015,17 @@ void CPanel::OpenFocusedItemAsInternal(const wchar_t *type)
977void CPanel::OpenSelectedItems(bool tryInternal) 1015void CPanel::OpenSelectedItems(bool tryInternal)
978{ 1016{
979 CRecordVector<UInt32> indices; 1017 CRecordVector<UInt32> indices;
980 GetOperatedItemIndices(indices); 1018 Get_ItemIndices_Operated(indices);
981 if (indices.Size() > 20) 1019 if (indices.Size() > 20)
982 { 1020 {
983 MessageBox_Error_LangID(IDS_TOO_MANY_ITEMS); 1021 MessageBox_Error_LangID(IDS_TOO_MANY_ITEMS);
984 return; 1022 return;
985 } 1023 }
986 1024
987 int focusedItem = _listView.GetFocusedItem(); 1025 const int focusedItem = _listView.GetFocusedItem();
988 if (focusedItem >= 0) 1026 if (focusedItem >= 0)
989 { 1027 {
990 int realIndex = GetRealItemIndex(focusedItem); 1028 const unsigned realIndex = GetRealItemIndex(focusedItem);
991 if (realIndex == kParentIndex && (tryInternal || indices.Size() == 0) && _listView.IsItemSelected(focusedItem)) 1029 if (realIndex == kParentIndex && (tryInternal || indices.Size() == 0) && _listView.IsItemSelected(focusedItem))
992 indices.Insert(0, realIndex); 1030 indices.Insert(0, realIndex);
993 } 1031 }
@@ -1016,7 +1054,7 @@ void CPanel::OpenSelectedItems(bool tryInternal)
1016 } 1054 }
1017} 1055}
1018 1056
1019UString CPanel::GetItemName(int itemIndex) const 1057UString CPanel::GetItemName(unsigned itemIndex) const
1020{ 1058{
1021 if (itemIndex == kParentIndex) 1059 if (itemIndex == kParentIndex)
1022 return L".."; 1060 return L"..";
@@ -1028,7 +1066,7 @@ UString CPanel::GetItemName(int itemIndex) const
1028 return prop.bstrVal; 1066 return prop.bstrVal;
1029} 1067}
1030 1068
1031UString CPanel::GetItemName_for_Copy(int itemIndex) const 1069UString CPanel::GetItemName_for_Copy(unsigned itemIndex) const
1032{ 1070{
1033 if (itemIndex == kParentIndex) 1071 if (itemIndex == kParentIndex)
1034 return L".."; 1072 return L"..";
@@ -1048,7 +1086,7 @@ UString CPanel::GetItemName_for_Copy(int itemIndex) const
1048 return Get_Correct_FsFile_Name(s); 1086 return Get_Correct_FsFile_Name(s);
1049} 1087}
1050 1088
1051void CPanel::GetItemName(int itemIndex, UString &s) const 1089void CPanel::GetItemName(unsigned itemIndex, UString &s) const
1052{ 1090{
1053 if (itemIndex == kParentIndex) 1091 if (itemIndex == kParentIndex)
1054 { 1092 {
@@ -1063,7 +1101,7 @@ void CPanel::GetItemName(int itemIndex, UString &s) const
1063 s.SetFromBstr(prop.bstrVal); 1101 s.SetFromBstr(prop.bstrVal);
1064} 1102}
1065 1103
1066UString CPanel::GetItemPrefix(int itemIndex) const 1104UString CPanel::GetItemPrefix(unsigned itemIndex) const
1067{ 1105{
1068 if (itemIndex == kParentIndex) 1106 if (itemIndex == kParentIndex)
1069 return UString(); 1107 return UString();
@@ -1076,12 +1114,12 @@ UString CPanel::GetItemPrefix(int itemIndex) const
1076 return prefix; 1114 return prefix;
1077} 1115}
1078 1116
1079UString CPanel::GetItemRelPath(int itemIndex) const 1117UString CPanel::GetItemRelPath(unsigned itemIndex) const
1080{ 1118{
1081 return GetItemPrefix(itemIndex) + GetItemName(itemIndex); 1119 return GetItemPrefix(itemIndex) + GetItemName(itemIndex);
1082} 1120}
1083 1121
1084UString CPanel::GetItemRelPath2(int itemIndex) const 1122UString CPanel::GetItemRelPath2(unsigned itemIndex) const
1085{ 1123{
1086 UString s = GetItemRelPath(itemIndex); 1124 UString s = GetItemRelPath(itemIndex);
1087 #if defined(_WIN32) && !defined(UNDER_CE) 1125 #if defined(_WIN32) && !defined(UNDER_CE)
@@ -1094,7 +1132,50 @@ UString CPanel::GetItemRelPath2(int itemIndex) const
1094 return s; 1132 return s;
1095} 1133}
1096 1134
1097UString CPanel::GetItemFullPath(int itemIndex) const 1135
1136void CPanel::Add_ItemRelPath2_To_String(unsigned itemIndex, UString &s) const
1137{
1138 if (itemIndex == kParentIndex)
1139 {
1140 s += "..";
1141 return;
1142 }
1143
1144 const unsigned start = s.Len();
1145 NCOM::CPropVariant prop;
1146 if (_folder->GetProperty(itemIndex, kpidPrefix, &prop) != S_OK)
1147 throw 2723400;
1148 if (prop.vt == VT_BSTR)
1149 s += prop.bstrVal;
1150
1151 const wchar_t *name = NULL;
1152 unsigned nameLen = 0;
1153
1154 if (_folderGetItemName)
1155 _folderGetItemName->GetItemName(itemIndex, &name, &nameLen);
1156 if (name)
1157 s += name;
1158 else
1159 {
1160 prop.Clear();
1161 if (_folder->GetProperty(itemIndex, kpidName, &prop) != S_OK)
1162 throw 2723400;
1163 if (prop.vt != VT_BSTR)
1164 throw 2723401;
1165 s += prop.bstrVal;
1166 }
1167
1168 #if defined(_WIN32) && !defined(UNDER_CE)
1169 if (s.Len() - start == 2 && NFile::NName::IsDrivePath2(s.Ptr(start)))
1170 {
1171 if (IsFSDrivesFolder() && !IsDeviceDrivesPrefix())
1172 s.Add_PathSepar();
1173 }
1174 #endif
1175}
1176
1177
1178UString CPanel::GetItemFullPath(unsigned itemIndex) const
1098{ 1179{
1099 return GetFsPath() + GetItemRelPath2(itemIndex); 1180 return GetFsPath() + GetItemRelPath2(itemIndex);
1100} 1181}
@@ -1111,28 +1192,30 @@ bool CPanel::GetItem_BoolProp(UInt32 itemIndex, PROPID propID) const
1111 throw 2723401; 1192 throw 2723401;
1112} 1193}
1113 1194
1114bool CPanel::IsItem_Deleted(int itemIndex) const 1195bool CPanel::IsItem_Deleted(unsigned itemIndex) const
1115{ 1196{
1116 if (itemIndex == kParentIndex) 1197 if (itemIndex == kParentIndex)
1117 return false; 1198 return false;
1118 return GetItem_BoolProp(itemIndex, kpidIsDeleted); 1199 return GetItem_BoolProp(itemIndex, kpidIsDeleted);
1119} 1200}
1120 1201
1121bool CPanel::IsItem_Folder(int itemIndex) const 1202bool CPanel::IsItem_Folder(unsigned itemIndex) const
1122{ 1203{
1123 if (itemIndex == kParentIndex) 1204 if (itemIndex == kParentIndex)
1124 return true; 1205 return true;
1206 if (itemIndex < _isDirVector.Size())
1207 return _isDirVector[itemIndex];
1125 return GetItem_BoolProp(itemIndex, kpidIsDir); 1208 return GetItem_BoolProp(itemIndex, kpidIsDir);
1126} 1209}
1127 1210
1128bool CPanel::IsItem_AltStream(int itemIndex) const 1211bool CPanel::IsItem_AltStream(unsigned itemIndex) const
1129{ 1212{
1130 if (itemIndex == kParentIndex) 1213 if (itemIndex == kParentIndex)
1131 return false; 1214 return false;
1132 return GetItem_BoolProp(itemIndex, kpidIsAltStream); 1215 return GetItem_BoolProp(itemIndex, kpidIsAltStream);
1133} 1216}
1134 1217
1135UInt64 CPanel::GetItem_UInt64Prop(int itemIndex, PROPID propID) const 1218UInt64 CPanel::GetItem_UInt64Prop(unsigned itemIndex, PROPID propID) const
1136{ 1219{
1137 if (itemIndex == kParentIndex) 1220 if (itemIndex == kParentIndex)
1138 return 0; 1221 return 0;
@@ -1145,7 +1228,7 @@ UInt64 CPanel::GetItem_UInt64Prop(int itemIndex, PROPID propID) const
1145 return 0; 1228 return 0;
1146} 1229}
1147 1230
1148UInt64 CPanel::GetItemSize(int itemIndex) const 1231UInt64 CPanel::GetItemSize(unsigned itemIndex) const
1149{ 1232{
1150 if (itemIndex == kParentIndex) 1233 if (itemIndex == kParentIndex)
1151 return 0; 1234 return 0;
@@ -1169,7 +1252,7 @@ void CPanel::SaveListViewInfo()
1169 if (!_listView.GetColumn(i, &winColumnInfo)) 1252 if (!_listView.GetColumn(i, &winColumnInfo))
1170 throw 1; 1253 throw 1;
1171 prop.Order = winColumnInfo.iOrder; 1254 prop.Order = winColumnInfo.iOrder;
1172 prop.Width = winColumnInfo.cx; 1255 prop.Width = (UInt32)(Int32)winColumnInfo.cx;
1173 } 1256 }
1174 1257
1175 CListViewInfo viewInfo; 1258 CListViewInfo viewInfo;
@@ -1247,22 +1330,22 @@ void CPanel::ShowColumnsContextMenu(int x, int y)
1247 menu.AppendItem(flags, kCommandStart + i, prop.Name); 1330 menu.AppendItem(flags, kCommandStart + i, prop.Name);
1248 } 1331 }
1249 1332
1250 int menuResult = menu.Track(TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, x, y, _listView); 1333 const int menuResult = menu.Track(TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, x, y, _listView);
1251 1334
1252 if (menuResult >= kCommandStart && menuResult <= kCommandStart + (int)_columns.Size()) 1335 if (menuResult >= kCommandStart && menuResult <= kCommandStart + (int)_columns.Size())
1253 { 1336 {
1254 int index = menuResult - kCommandStart; 1337 const unsigned index = (unsigned)(menuResult - kCommandStart);
1255 CPropColumn &prop = _columns[index]; 1338 CPropColumn &prop = _columns[index];
1256 prop.IsVisible = !prop.IsVisible; 1339 prop.IsVisible = !prop.IsVisible;
1257 1340
1258 if (prop.IsVisible) 1341 if (prop.IsVisible)
1259 { 1342 {
1260 prop.Order = _visibleColumns.Size(); 1343 prop.Order = (int)_visibleColumns.Size();
1261 AddColumn(prop); 1344 AddColumn(prop);
1262 } 1345 }
1263 else 1346 else
1264 { 1347 {
1265 int visibleIndex = _visibleColumns.FindItem_for_PropID(prop.ID); 1348 const int visibleIndex = _visibleColumns.FindItem_for_PropID(prop.ID);
1266 if (visibleIndex >= 0) 1349 if (visibleIndex >= 0)
1267 { 1350 {
1268 /* 1351 /*
@@ -1277,15 +1360,15 @@ void CPanel::ShowColumnsContextMenu(int x, int y)
1277 _sortID = kpidName; 1360 _sortID = kpidName;
1278 _ascending = true; 1361 _ascending = true;
1279 } 1362 }
1280 DeleteColumn(visibleIndex); 1363 DeleteColumn((unsigned)visibleIndex);
1281 } 1364 }
1282 } 1365 }
1283 } 1366 }
1284} 1367}
1285 1368
1286void CPanel::OnReload() 1369void CPanel::OnReload(bool onTimer)
1287{ 1370{
1288 HRESULT res = RefreshListCtrl_SaveFocused(); 1371 const HRESULT res = RefreshListCtrl_SaveFocused(onTimer);
1289 if (res != S_OK) 1372 if (res != S_OK)
1290 MessageBox_Error_HRESULT(res); 1373 MessageBox_Error_HRESULT(res);
1291} 1374}
@@ -1304,5 +1387,5 @@ void CPanel::OnTimer()
1304 return; 1387 return;
1305 if (wasChanged == 0) 1388 if (wasChanged == 0)
1306 return; 1389 return;
1307 OnReload(); 1390 OnReload(true); // onTimer
1308} 1391}
diff --git a/CPP/7zip/UI/FileManager/PanelKey.cpp b/CPP/7zip/UI/FileManager/PanelKey.cpp
index 3ab478e..a4ea489 100644
--- a/CPP/7zip/UI/FileManager/PanelKey.cpp
+++ b/CPP/7zip/UI/FileManager/PanelKey.cpp
@@ -29,9 +29,9 @@ static const CVKeyPropIDPair g_VKeyPropIDPairs[] =
29 29
30static int FindVKeyPropIDPair(WORD vKey) 30static int FindVKeyPropIDPair(WORD vKey)
31{ 31{
32 for (unsigned i = 0; i < ARRAY_SIZE(g_VKeyPropIDPairs); i++) 32 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_VKeyPropIDPairs); i++)
33 if (g_VKeyPropIDPairs[i].VKey == vKey) 33 if (g_VKeyPropIDPairs[i].VKey == vKey)
34 return i; 34 return (int)i;
35 return -1; 35 return -1;
36} 36}
37 37
@@ -43,17 +43,18 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result)
43 _panelCallback->OnTab(); 43 _panelCallback->OnTab();
44 return false; 44 return false;
45 } 45 }
46 bool alt = IsKeyDown(VK_MENU); 46 const bool alt = IsKeyDown(VK_MENU);
47 bool ctrl = IsKeyDown(VK_CONTROL); 47 const bool ctrl = IsKeyDown(VK_CONTROL);
48 // bool leftCtrl = IsKeyDown(VK_LCONTROL); 48 // const bool leftCtrl = IsKeyDown(VK_LCONTROL);
49 bool rightCtrl = IsKeyDown(VK_RCONTROL); 49 const bool rightCtrl = IsKeyDown(VK_RCONTROL);
50 bool shift = IsKeyDown(VK_SHIFT); 50 const bool shift = IsKeyDown(VK_SHIFT);
51 result = 0; 51 result = 0;
52 52
53 if (keyDownInfo->wVKey >= '0' && keyDownInfo->wVKey <= '9' && 53 if (keyDownInfo->wVKey >= '0' &&
54 keyDownInfo->wVKey <= '9' &&
54 (rightCtrl || alt)) 55 (rightCtrl || alt))
55 { 56 {
56 int index = keyDownInfo->wVKey - '0'; 57 const unsigned index = (unsigned)(keyDownInfo->wVKey - '0');
57 if (shift) 58 if (shift)
58 { 59 {
59 SetBookmark(index); 60 SetBookmark(index);
@@ -67,7 +68,8 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result)
67 } 68 }
68 69
69 if ((keyDownInfo->wVKey == VK_F2 || 70 if ((keyDownInfo->wVKey == VK_F2 ||
70 keyDownInfo->wVKey == VK_F1) && alt && !ctrl && !shift) 71 keyDownInfo->wVKey == VK_F1)
72 && alt && !ctrl && !shift)
71 { 73 {
72 _panelCallback->SetFocusToPath(keyDownInfo->wVKey == VK_F1 ? 0 : 1); 74 _panelCallback->SetFocusToPath(keyDownInfo->wVKey == VK_F1 ? 0 : 1);
73 return true; 75 return true;
@@ -80,7 +82,7 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result)
80 82
81 if (keyDownInfo->wVKey >= VK_F3 && keyDownInfo->wVKey <= VK_F12 && ctrl) 83 if (keyDownInfo->wVKey >= VK_F3 && keyDownInfo->wVKey <= VK_F12 && ctrl)
82 { 84 {
83 int index = FindVKeyPropIDPair(keyDownInfo->wVKey); 85 const int index = FindVKeyPropIDPair(keyDownInfo->wVKey);
84 if (index >= 0) 86 if (index >= 0)
85 SortItemsWithPropID(g_VKeyPropIDPairs[index].PropID); 87 SortItemsWithPropID(g_VKeyPropIDPairs[index].PropID);
86 } 88 }
@@ -313,6 +315,14 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result)
313 return true; 315 return true;
314 } 316 }
315 return false; 317 return false;
318 case 'W':
319 if (ctrl)
320 {
321 // SendMessage();
322 PostMessage(g_HWND, WM_COMMAND, IDCLOSE, 0);
323 return true;
324 }
325 return false;
316 case 'Z': 326 case 'Z':
317 if (ctrl) 327 if (ctrl)
318 { 328 {
@@ -326,7 +336,7 @@ bool CPanel::OnKeyDown(LPNMLVKEYDOWN keyDownInfo, LRESULT &result)
326 case '4': 336 case '4':
327 if (ctrl) 337 if (ctrl)
328 { 338 {
329 int styleIndex = keyDownInfo->wVKey - '1'; 339 const unsigned styleIndex = (unsigned)(keyDownInfo->wVKey - '1');
330 SetListViewMode(styleIndex); 340 SetListViewMode(styleIndex);
331 return true; 341 return true;
332 } 342 }
diff --git a/CPP/7zip/UI/FileManager/PanelListNotify.cpp b/CPP/7zip/UI/FileManager/PanelListNotify.cpp
index d2114f1..2fb0e87 100644
--- a/CPP/7zip/UI/FileManager/PanelListNotify.cpp
+++ b/CPP/7zip/UI/FileManager/PanelListNotify.cpp
@@ -289,8 +289,8 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
289 const void *data; 289 const void *data;
290 UInt32 dataSize; 290 UInt32 dataSize;
291 UInt32 propType; 291 UInt32 propType;
292 RINOK(_folderRawProps->GetRawProp(realIndex, propID, &data, &dataSize, &propType)); 292 RINOK(_folderRawProps->GetRawProp(realIndex, propID, &data, &dataSize, &propType))
293 unsigned limit = item.cchTextMax - 1; 293 const unsigned limit = (unsigned)item.cchTextMax - 1;
294 if (dataSize == 0) 294 if (dataSize == 0)
295 { 295 {
296 text[0] = 0; 296 text[0] = 0;
@@ -425,11 +425,11 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
425 if (name) 425 if (name)
426 { 426 {
427 unsigned dest = 0; 427 unsigned dest = 0;
428 unsigned limit = item.cchTextMax - 1; 428 const unsigned limit = (unsigned)item.cchTextMax - 1;
429 429
430 for (unsigned i = 0; dest < limit;) 430 for (unsigned i = 0; dest < limit;)
431 { 431 {
432 wchar_t c = name[i++]; 432 const wchar_t c = name[i++];
433 if (c == 0) 433 if (c == 0)
434 break; 434 break;
435 text[dest++] = c; 435 text[dest++] = c;
@@ -488,10 +488,10 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
488 if (name) 488 if (name)
489 { 489 {
490 unsigned dest = 0; 490 unsigned dest = 0;
491 unsigned limit = item.cchTextMax - 1; 491 const unsigned limit = (unsigned)item.cchTextMax - 1;
492 for (unsigned i = 0; dest < limit;) 492 for (unsigned i = 0; dest < limit;)
493 { 493 {
494 wchar_t c = name[i++]; 494 const wchar_t c = name[i++];
495 if (c == 0) 495 if (c == 0)
496 break; 496 break;
497 text[dest++] = c; 497 text[dest++] = c;
@@ -502,7 +502,7 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
502 } 502 }
503 } 503 }
504 504
505 HRESULT res = _folder->GetProperty(realIndex, propID, &prop); 505 const HRESULT res = _folder->GetProperty(realIndex, propID, &prop);
506 506
507 if (res != S_OK) 507 if (res != S_OK)
508 { 508 {
@@ -517,7 +517,7 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
517 } 517 }
518 else if (prop.vt == VT_BSTR) 518 else if (prop.vt == VT_BSTR)
519 { 519 {
520 unsigned limit = item.cchTextMax - 1; 520 const unsigned limit = (unsigned)item.cchTextMax - 1;
521 const wchar_t *src = prop.bstrVal; 521 const wchar_t *src = prop.bstrVal;
522 unsigned i; 522 unsigned i;
523 for (i = 0; i < limit; i++) 523 for (i = 0; i < limit; i++)
@@ -535,10 +535,10 @@ LRESULT CPanel::SetItemText(LVITEMW &item)
535 char temp[64]; 535 char temp[64];
536 ConvertPropertyToShortString2(temp, prop, propID, _timestampLevel); 536 ConvertPropertyToShortString2(temp, prop, propID, _timestampLevel);
537 unsigned i; 537 unsigned i;
538 unsigned limit = item.cchTextMax - 1; 538 const unsigned limit = (unsigned)item.cchTextMax - 1;
539 for (i = 0; i < limit; i++) 539 for (i = 0; i < limit; i++)
540 { 540 {
541 wchar_t c = (Byte)temp[i]; 541 const wchar_t c = (Byte)temp[i];
542 if (c == 0) 542 if (c == 0)
543 break; 543 break;
544 text[i] = c; 544 text[i] = c;
@@ -555,11 +555,11 @@ extern DWORD g_ComCtl32Version;
555 555
556void CPanel::OnItemChanged(NMLISTVIEW *item) 556void CPanel::OnItemChanged(NMLISTVIEW *item)
557{ 557{
558 int index = (int)item->lParam; 558 const unsigned index = (unsigned)item->lParam;
559 if (index == kParentIndex) 559 if (index == kParentIndex)
560 return; 560 return;
561 bool oldSelected = (item->uOldState & LVIS_SELECTED) != 0; 561 const bool oldSelected = (item->uOldState & LVIS_SELECTED) != 0;
562 bool newSelected = (item->uNewState & LVIS_SELECTED) != 0; 562 const bool newSelected = (item->uNewState & LVIS_SELECTED) != 0;
563 // Don't change this code. It works only with such check 563 // Don't change this code. It works only with such check
564 if (oldSelected != newSelected) 564 if (oldSelected != newSelected)
565 _selectedStatusVector[index] = newSelected; 565 _selectedStatusVector[index] = newSelected;
@@ -712,7 +712,13 @@ bool CPanel::OnNotifyList(LPNMHDR header, LRESULT &result)
712 } 712 }
713 case LVN_BEGINDRAG: 713 case LVN_BEGINDRAG:
714 { 714 {
715 OnDrag((LPNMLISTVIEW)header); 715 OnDrag((LPNMLISTVIEW)header, false);
716 Post_Refresh_StatusBar();
717 break;
718 }
719 case LVN_BEGINRDRAG:
720 {
721 OnDrag((LPNMLISTVIEW)header, true);
716 Post_Refresh_StatusBar(); 722 Post_Refresh_StatusBar();
717 break; 723 break;
718 } 724 }
@@ -739,7 +745,7 @@ bool CPanel::OnCustomDraw(LPNMLVCUSTOMDRAW lplvcd, LRESULT &result)
739 lplvcd->clrTextBk = GetBkColorForItem(lplvcd->nmcd.dwItemSpec, 745 lplvcd->clrTextBk = GetBkColorForItem(lplvcd->nmcd.dwItemSpec,
740 lplvcd->nmcd.lItemlParam); 746 lplvcd->nmcd.lItemlParam);
741 */ 747 */
742 int realIndex = (int)lplvcd->nmcd.lItemlParam; 748 const unsigned realIndex = (unsigned)lplvcd->nmcd.lItemlParam;
743 lplvcd->clrTextBk = _listView.GetBkColor(); 749 lplvcd->clrTextBk = _listView.GetBkColor();
744 if (_mySelectMode) 750 if (_mySelectMode)
745 { 751 {
@@ -793,40 +799,44 @@ void CPanel::Refresh_StatusBar()
793 // DWORD dw = GetTickCount(); 799 // DWORD dw = GetTickCount();
794 800
795 CRecordVector<UInt32> indices; 801 CRecordVector<UInt32> indices;
796 GetOperatedItemIndices(indices); 802 Get_ItemIndices_Operated(indices);
797
798 wchar_t temp[32];
799 ConvertUInt32ToString(indices.Size(), temp);
800 wcscat(temp, L" / ");
801 ConvertUInt32ToString(_selectedStatusVector.Size(), temp + wcslen(temp));
802
803 // UString s1 = MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, NumberToString(indices.Size()));
804 // UString s1 = MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size()));
805 _statusBar.SetText(0, MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, temp));
806 // _statusBar.SetText(0, MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size())));
807 803
808 wchar_t selectSizeString[32]; 804 {
809 selectSizeString[0] = 0; 805 UString s;
806 s.Add_UInt32(indices.Size());
807 s += " / ";
808 s.Add_UInt32(_selectedStatusVector.Size());
809
810 // UString s1 = MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, NumberToString(indices.Size()));
811 // UString s1 = MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size()));
812 _statusBar.SetText(0, MyFormatNew(g_App.LangString_N_SELECTED_ITEMS, s));
813 // _statusBar.SetText(0, MyFormatNew(IDS_N_SELECTED_ITEMS, NumberToString(indices.Size())));
814 }
810 815
811 if (indices.Size() > 0)
812 { 816 {
813 // for (unsigned ttt = 0; ttt < 1000; ttt++) { 817 wchar_t selectSizeString[32];
814 UInt64 totalSize = 0; 818 selectSizeString[0] = 0;
815 FOR_VECTOR (i, indices) 819
816 totalSize += GetItemSize(indices[i]); 820 if (indices.Size() > 0)
817 ConvertSizeToString(totalSize, selectSizeString); 821 {
818 // } 822 // for (unsigned ttt = 0; ttt < 1000; ttt++) {
823 UInt64 totalSize = 0;
824 FOR_VECTOR (i, indices)
825 totalSize += GetItemSize(indices[i]);
826 ConvertSizeToString(totalSize, selectSizeString);
827 // }
828 }
829 _statusBar.SetText(1, selectSizeString);
819 } 830 }
820 _statusBar.SetText(1, selectSizeString);
821 831
822 int focusedItem = _listView.GetFocusedItem(); 832 const int focusedItem = _listView.GetFocusedItem();
823 wchar_t sizeString[32]; 833 wchar_t sizeString[32];
824 sizeString[0] = 0; 834 sizeString[0] = 0;
825 wchar_t dateString[32]; 835 wchar_t dateString[32];
826 dateString[0] = 0; 836 dateString[0] = 0;
827 if (focusedItem >= 0 && _listView.GetSelectedCount() > 0) 837 if (focusedItem >= 0 && _listView.GetSelectedCount() > 0)
828 { 838 {
829 int realIndex = GetRealItemIndex(focusedItem); 839 const unsigned realIndex = GetRealItemIndex(focusedItem);
830 if (realIndex != kParentIndex) 840 if (realIndex != kParentIndex)
831 { 841 {
832 ConvertSizeToString(GetItemSize(realIndex), sizeString); 842 ConvertSizeToString(GetItemSize(realIndex), sizeString);
diff --git a/CPP/7zip/UI/FileManager/PanelMenu.cpp b/CPP/7zip/UI/FileManager/PanelMenu.cpp
index 9e86951..f0afe15 100644
--- a/CPP/7zip/UI/FileManager/PanelMenu.cpp
+++ b/CPP/7zip/UI/FileManager/PanelMenu.cpp
@@ -20,8 +20,10 @@
20#include "MyLoadMenu.h" 20#include "MyLoadMenu.h"
21#include "PropertyName.h" 21#include "PropertyName.h"
22 22
23#include "resource.h"
24#include "PropertyNameRes.h" 23#include "PropertyNameRes.h"
24#include "resource.h"
25
26// #define SHOW_DEBUG_PANEL_MENU
25 27
26using namespace NWindows; 28using namespace NWindows;
27 29
@@ -32,13 +34,33 @@ LONG g_DllRefCount = 0;
32static const UINT kSevenZipStartMenuID = kMenuCmdID_Plugin_Start; 34static const UINT kSevenZipStartMenuID = kMenuCmdID_Plugin_Start;
33static const UINT kSystemStartMenuID = kMenuCmdID_Plugin_Start + 400; 35static const UINT kSystemStartMenuID = kMenuCmdID_Plugin_Start + 400;
34 36
37
38#ifdef SHOW_DEBUG_PANEL_MENU
39static void Print_Ptr(void *p, const char *s)
40{
41 char temp[32];
42 ConvertUInt64ToHex((UInt64)(void *)p, temp);
43 AString m;
44 m += temp;
45 m.Add_Space();
46 m += s;
47 OutputDebugStringA(m);
48}
49#define ODS(sz) { Print_Ptr(this, sz); }
50#define ODS_U(s) { OutputDebugStringW(s); }
51#else
52#define ODS(sz)
53#define ODS_U(s)
54#endif
55
56
35void CPanel::InvokeSystemCommand(const char *command) 57void CPanel::InvokeSystemCommand(const char *command)
36{ 58{
37 NCOM::CComInitializer comInitializer; 59 NCOM::CComInitializer comInitializer;
38 if (!IsFsOrPureDrivesFolder()) 60 if (!IsFsOrPureDrivesFolder())
39 return; 61 return;
40 CRecordVector<UInt32> operatedIndices; 62 CRecordVector<UInt32> operatedIndices;
41 GetOperatedItemIndices(operatedIndices); 63 Get_ItemIndices_Operated(operatedIndices);
42 if (operatedIndices.IsEmpty()) 64 if (operatedIndices.IsEmpty())
43 return; 65 return;
44 CMyComPtr<IContextMenu> contextMenu; 66 CMyComPtr<IContextMenu> contextMenu;
@@ -173,7 +195,7 @@ void CPanel::Properties()
173 // message.SelectFirst = false; 195 // message.SelectFirst = false;
174 196
175 CRecordVector<UInt32> operatedIndices; 197 CRecordVector<UInt32> operatedIndices;
176 GetOperatedItemIndices(operatedIndices); 198 Get_ItemIndices_Operated(operatedIndices);
177 199
178 if (operatedIndices.Size() == 1) 200 if (operatedIndices.Size() == 1)
179 { 201 {
@@ -346,7 +368,7 @@ void CPanel::Properties()
346 UInt32 numProps; 368 UInt32 numProps;
347 if (getProps->GetArcNumProps(level, &numProps) == S_OK) 369 if (getProps->GetArcNumProps(level, &numProps) == S_OK)
348 { 370 {
349 const int kNumSpecProps = ARRAY_SIZE(kSpecProps); 371 const int kNumSpecProps = Z7_ARRAY_SIZE(kSpecProps);
350 372
351 AddSeparator(message); 373 AddSeparator(message);
352 374
@@ -357,7 +379,7 @@ void CPanel::Properties()
357 VARTYPE vt; 379 VARTYPE vt;
358 if (i < 0) 380 if (i < 0)
359 propID = kSpecProps[i + kNumSpecProps]; 381 propID = kSpecProps[i + kNumSpecProps];
360 else if (getProps->GetArcPropInfo(level, i, &name, &propID, &vt) != S_OK) 382 else if (getProps->GetArcPropInfo(level, (UInt32)i, &name, &propID, &vt) != S_OK)
361 continue; 383 continue;
362 NCOM::CPropVariant prop; 384 NCOM::CPropVariant prop;
363 if (getProps->GetArcProp(level, propID, &prop) != S_OK) 385 if (getProps->GetArcProp(level, propID, &prop) != S_OK)
@@ -369,12 +391,12 @@ void CPanel::Properties()
369 391
370 if (level2 < numLevels - 1) 392 if (level2 < numLevels - 1)
371 { 393 {
372 UInt32 level = numLevels - 1 - level2; 394 const UInt32 level = numLevels - 1 - level2;
373 UInt32 numProps; 395 UInt32 numProps;
374 if (getProps->GetArcNumProps2(level, &numProps) == S_OK) 396 if (getProps->GetArcNumProps2(level, &numProps) == S_OK)
375 { 397 {
376 AddSeparatorSmall(message); 398 AddSeparatorSmall(message);
377 for (Int32 i = 0; i < (Int32)numProps; i++) 399 for (UInt32 i = 0; i < numProps; i++)
378 { 400 {
379 CMyComBSTR name; 401 CMyComBSTR name;
380 PROPID propID; 402 PROPID propID;
@@ -393,11 +415,11 @@ void CPanel::Properties()
393 { 415 {
394 // we ERROR message for NonOpen level 416 // we ERROR message for NonOpen level
395 bool needSep = true; 417 bool needSep = true;
396 const int kNumSpecProps = ARRAY_SIZE(kSpecProps); 418 const int kNumSpecProps = Z7_ARRAY_SIZE(kSpecProps);
397 for (Int32 i = -(int)kNumSpecProps; i < 0; i++) 419 for (Int32 i = -(int)kNumSpecProps; i < 0; i++)
398 { 420 {
399 CMyComBSTR name; 421 CMyComBSTR name;
400 PROPID propID = kSpecProps[i + kNumSpecProps]; 422 const PROPID propID = kSpecProps[i + kNumSpecProps];
401 NCOM::CPropVariant prop; 423 NCOM::CPropVariant prop;
402 if (getProps->GetArcProp(numLevels, propID, &prop) != S_OK) 424 if (getProps->GetArcProp(numLevels, propID, &prop) != S_OK)
403 continue; 425 continue;
@@ -440,7 +462,7 @@ void CPanel::EditCopy()
440 */ 462 */
441 UString s; 463 UString s;
442 CRecordVector<UInt32> indices; 464 CRecordVector<UInt32> indices;
443 GetSelectedItemsIndices(indices); 465 Get_ItemIndices_Selected(indices);
444 FOR_VECTOR (i, indices) 466 FOR_VECTOR (i, indices)
445 { 467 {
446 if (i != 0) 468 if (i != 0)
@@ -486,15 +508,25 @@ struct CFolderPidls
486}; 508};
487 509
488 510
511static HRESULT ShellFolder_ParseDisplayName(IShellFolder *shellFolder,
512 HWND hwnd, const UString &path, LPITEMIDLIST *ppidl)
513{
514 ULONG eaten = 0;
515 return shellFolder->ParseDisplayName(hwnd, NULL,
516 path.Ptr_non_const(), &eaten, ppidl, NULL);
517}
518
519
489HRESULT CPanel::CreateShellContextMenu( 520HRESULT CPanel::CreateShellContextMenu(
490 const CRecordVector<UInt32> &operatedIndices, 521 const CRecordVector<UInt32> &operatedIndices,
491 CMyComPtr<IContextMenu> &systemContextMenu) 522 CMyComPtr<IContextMenu> &systemContextMenu)
492{ 523{
524 ODS("==== CPanel::CreateShellContextMenu");
493 systemContextMenu.Release(); 525 systemContextMenu.Release();
494 const UString folderPath = GetFsPath(); 526 UString folderPath = GetFsPath();
495 527
496 CMyComPtr<IShellFolder> desktopFolder; 528 CMyComPtr<IShellFolder> desktopFolder;
497 RINOK(::SHGetDesktopFolder(&desktopFolder)); 529 RINOK(::SHGetDesktopFolder(&desktopFolder))
498 if (!desktopFolder) 530 if (!desktopFolder)
499 { 531 {
500 // ShowMessage("Failed to get Desktop folder"); 532 // ShowMessage("Failed to get Desktop folder");
@@ -502,24 +534,37 @@ HRESULT CPanel::CreateShellContextMenu(
502 } 534 }
503 535
504 CFolderPidls pidls; 536 CFolderPidls pidls;
505 DWORD eaten; 537 // NULL is allowed for parentHWND in ParseDisplayName()
506 538 const HWND parentHWND_for_ParseDisplayName = GetParent();
507 // if (folderPath.IsEmpty()), then ParseDisplayName returns pidls of "My Computer" 539 // if (folderPath.IsEmpty()), then ParseDisplayName returns pidls of "My Computer"
508 RINOK(desktopFolder->ParseDisplayName( 540 /* win10: ParseDisplayName() supports folder path with tail slash
509 GetParent(), NULL, folderPath.Ptr_non_const(), 541 ParseDisplayName() returns {
510 &eaten, &pidls.parent, NULL)); 542 E_INVALIDARG : path with super path prefix "\\\\?\\"
543 ERROR_FILE_NOT_FOUND : path for network share (\\server\path1\long path2") larger than MAX_PATH
544 } */
545 const HRESULT res = ShellFolder_ParseDisplayName(desktopFolder,
546 parentHWND_for_ParseDisplayName,
547 folderPath, &pidls.parent);
548 if (res != S_OK)
549 {
550 ODS_U(folderPath);
551 if (res != E_INVALIDARG)
552 return res;
553 if (!NFile::NName::If_IsSuperPath_RemoveSuperPrefix(folderPath))
554 return res;
555 RINOK(ShellFolder_ParseDisplayName(desktopFolder,
556 parentHWND_for_ParseDisplayName,
557 folderPath, &pidls.parent))
558 }
559 if (!pidls.parent)
560 return E_FAIL;
511 561
512 /* 562 /*
513 STRRET pName; 563 UString path2;
514 res = desktopFolder->GetDisplayNameOf(pidls.parent, SHGDN_NORMAL, &pName); 564 NShell::GetPathFromIDList(pidls.parent, path2);
515 WCHAR dir[MAX_PATH]; 565 ODS_U(path2);
516 if (!SHGetPathFromIDListW(pidls.parent, dir))
517 dir[0] = 0;
518 */ 566 */
519 567
520 if (!pidls.parent)
521 return E_FAIL;
522
523 if (operatedIndices.IsEmpty()) 568 if (operatedIndices.IsEmpty())
524 { 569 {
525 // how to get IContextMenu, if there are no selected files? 570 // how to get IContextMenu, if there are no selected files?
@@ -549,28 +594,37 @@ HRESULT CPanel::CreateShellContextMenu(
549 594
550 CMyComPtr<IShellFolder> parentFolder; 595 CMyComPtr<IShellFolder> parentFolder;
551 RINOK(desktopFolder->BindToObject(pidls.parent, 596 RINOK(desktopFolder->BindToObject(pidls.parent,
552 NULL, IID_IShellFolder, (void**)&parentFolder)); 597 NULL, IID_IShellFolder, (void**)&parentFolder))
553 if (!parentFolder) 598 if (!parentFolder)
554 {
555 // ShowMessage("Invalid file name");
556 return E_FAIL; 599 return E_FAIL;
557 } 600
601 ODS("==== CPanel::CreateShellContextMenu pidls START");
558 602
559 pidls.items.ClearAndReserve(operatedIndices.Size()); 603 pidls.items.ClearAndReserve(operatedIndices.Size());
604 UString fileName;
560 FOR_VECTOR (i, operatedIndices) 605 FOR_VECTOR (i, operatedIndices)
561 { 606 {
562 LPITEMIDLIST pidl; 607 fileName.Empty();
563 const UString fileName = GetItemRelPath2(operatedIndices[i]); 608 Add_ItemRelPath2_To_String(operatedIndices[i], fileName);
564 RINOK(parentFolder->ParseDisplayName(GetParent(), 0, 609 /* ParseDisplayName() in win10 returns:
565 fileName.Ptr_non_const(), &eaten, &pidl, 0)); 610 E_INVALIDARG : if empty name, or path with dots only: "." , ".."
611 HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) : if there is no such file
612 */
613 LPITEMIDLIST pidl = NULL;
614 RINOK(ShellFolder_ParseDisplayName(parentFolder,
615 parentHWND_for_ParseDisplayName,
616 fileName, &pidl))
617 if (!pidl)
618 return E_FAIL;
566 pidls.items.AddInReserved(pidl); 619 pidls.items.AddInReserved(pidl);
567 } 620 }
568
569 // Get IContextMenu for items
570 621
571 RINOK(parentFolder->GetUIObjectOf(GetParent(), pidls.items.Size(), 622 ODS("==== CPanel::CreateShellContextMenu pidls END");
572 (LPCITEMIDLIST *)(void *)&pidls.items.Front(), IID_IContextMenu, 0, (void**)&systemContextMenu)); 623 // Get IContextMenu for items
573 624 RINOK(parentFolder->GetUIObjectOf(GetParent(),
625 pidls.items.Size(), (LPCITEMIDLIST *)(void *)&pidls.items.Front(),
626 IID_IContextMenu, NULL, (void**)&systemContextMenu))
627 ODS("==== CPanel::CreateShellContextMenu GetUIObjectOf finished");
574 if (!systemContextMenu) 628 if (!systemContextMenu)
575 { 629 {
576 // ShowMessage("Unable to get context menu interface"); 630 // ShowMessage("Unable to get context menu interface");
@@ -579,14 +633,11 @@ HRESULT CPanel::CreateShellContextMenu(
579 return S_OK; 633 return S_OK;
580} 634}
581 635
636
582// #define SHOW_DEBUG_FM_CTX_MENU 637// #define SHOW_DEBUG_FM_CTX_MENU
583 638
584#ifdef SHOW_DEBUG_FM_CTX_MENU 639#ifdef SHOW_DEBUG_FM_CTX_MENU
585 640
586#include <stdio.h>
587
588// #include Common/IntToString.h"
589
590static void PrintHex(UString &s, UInt32 v) 641static void PrintHex(UString &s, UInt32 v)
591{ 642{
592 char sz[32]; 643 char sz[32];
@@ -597,16 +648,14 @@ static void PrintHex(UString &s, UInt32 v)
597static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned id, const char *name) 648static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned id, const char *name)
598{ 649{
599 s += " | "; 650 s += " | ";
600 name = name; 651 s += name;
601 // s += name; 652 s += ": ";
602 // s += ": ";
603
604 UString s1; 653 UString s1;
605 { 654 {
606 char buf[256]; 655 char buf[256];
607 buf[0] = 0; 656 buf[0] = 0;
608 HRESULT res = ctxm->GetCommandString(i, id, 657 const HRESULT res = ctxm->GetCommandString(i, id,
609 NULL, buf, ARRAY_SIZE(buf) - 1); 658 NULL, buf, Z7_ARRAY_SIZE(buf) - 1);
610 if (res != S_OK) 659 if (res != S_OK)
611 { 660 {
612 PrintHex(s1, res); 661 PrintHex(s1, res);
@@ -614,13 +663,12 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned
614 } 663 }
615 s1 += GetUnicodeString(buf); 664 s1 += GetUnicodeString(buf);
616 } 665 }
617
618 UString s2; 666 UString s2;
619 { 667 {
620 wchar_t buf2[256]; 668 wchar_t buf2[256];
621 buf2[0] = 0; 669 buf2[0] = 0;
622 HRESULT res = ctxm->GetCommandString(i, id | GCS_UNICODE, 670 const HRESULT res = ctxm->GetCommandString(i, id | GCS_UNICODE,
623 NULL, (char *)buf2, ARRAY_SIZE(buf2) - 1); 671 NULL, (char *)buf2, Z7_ARRAY_SIZE(buf2) - sizeof(wchar_t));
624 if (res != S_OK) 672 if (res != S_OK)
625 { 673 {
626 PrintHex(s2, res); 674 PrintHex(s2, res);
@@ -628,7 +676,6 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned
628 } 676 }
629 s2 += buf2; 677 s2 += buf2;
630 } 678 }
631
632 s += s1; 679 s += s1;
633 if (s2.Compare(s1) != 0) 680 if (s2.Compare(s1) != 0)
634 { 681 {
@@ -637,7 +684,6 @@ static void PrintContextStr(UString &s, IContextMenu *ctxm, unsigned i, unsigned
637 } 684 }
638} 685}
639 686
640
641static void PrintAllContextItems(IContextMenu *ctxm, unsigned num) 687static void PrintAllContextItems(IContextMenu *ctxm, unsigned num)
642{ 688{
643 for (unsigned i = 0; i < num; i++) 689 for (unsigned i = 0; i < num; i++)
@@ -645,35 +691,18 @@ static void PrintAllContextItems(IContextMenu *ctxm, unsigned num)
645 UString s; 691 UString s;
646 s.Add_UInt32(i); 692 s.Add_UInt32(i);
647 s += ": "; 693 s += ": ";
648
649 /*
650 UString valid;
651 {
652 char name[256];
653 HRESULT res = ctxm->GetCommandString(i, GCS_VALIDATEA,
654 NULL, name, ARRAY_SIZE(name) - 1);
655
656 if (res == S_OK)
657 {
658 // valid = "valid";
659 }
660 else if (res == S_FALSE)
661 valid = "non-valid";
662 else
663 PrintHex(valid, res);
664 }
665 s += valid;
666 */
667
668 PrintContextStr(s, ctxm, i, GCS_VALIDATEA, "valid"); 694 PrintContextStr(s, ctxm, i, GCS_VALIDATEA, "valid");
669 PrintContextStr(s, ctxm, i, GCS_VERBA, "v"); 695 PrintContextStr(s, ctxm, i, GCS_VERBA, "verb");
670 PrintContextStr(s, ctxm, i, GCS_HELPTEXTA, "h"); 696 PrintContextStr(s, ctxm, i, GCS_HELPTEXTA, "helptext");
671 OutputDebugStringW(s); 697 OutputDebugStringW(s);
672 } 698 }
673} 699}
700
674#endif 701#endif
675 702
703
676void CPanel::CreateSystemMenu(HMENU menuSpec, 704void CPanel::CreateSystemMenu(HMENU menuSpec,
705 bool showExtendedVerbs,
677 const CRecordVector<UInt32> &operatedIndices, 706 const CRecordVector<UInt32> &operatedIndices,
678 CMyComPtr<IContextMenu> &systemContextMenu) 707 CMyComPtr<IContextMenu> &systemContextMenu)
679{ 708{
@@ -722,19 +751,13 @@ void CPanel::CreateSystemMenu(HMENU menuSpec,
722 CMenuDestroyer menuDestroyer(popupMenu); 751 CMenuDestroyer menuDestroyer(popupMenu);
723 if (!popupMenu.CreatePopup()) 752 if (!popupMenu.CreatePopup())
724 throw 210503; 753 throw 210503;
725 754 const HMENU hMenu = popupMenu;
726 HMENU hMenu = popupMenu; 755 DWORD flags = CMF_EXPLORE;
727 756 if (showExtendedVerbs)
728 DWORD Flags = CMF_EXPLORE; 757 flags |= Z7_WIN_CMF_EXTENDEDVERBS;
729 // Optionally the shell will show the extended 758 ODS("=== systemContextMenu->QueryContextMenu START");
730 // context menu on some operating systems when 759 const HRESULT res = systemContextMenu->QueryContextMenu(hMenu, 0, kSystemStartMenuID, 0x7FFF, flags);
731 // the shift key is held down at the time the 760 ODS("=== systemContextMenu->QueryContextMenu END");
732 // context menu is invoked. The following is
733 // commented out but you can uncommnent this
734 // line to show the extended context menu.
735 // Flags |= 0x00000080;
736 HRESULT res = systemContextMenu->QueryContextMenu(hMenu, 0, kSystemStartMenuID, 0x7FFF, Flags);
737
738 if (SUCCEEDED(res)) 761 if (SUCCEEDED(res))
739 { 762 {
740 #ifdef SHOW_DEBUG_FM_CTX_MENU 763 #ifdef SHOW_DEBUG_FM_CTX_MENU
@@ -779,11 +802,13 @@ void CPanel::CreateSystemMenu(HMENU menuSpec,
779 802
780void CPanel::CreateFileMenu(HMENU menuSpec) 803void CPanel::CreateFileMenu(HMENU menuSpec)
781{ 804{
782 CreateFileMenu(menuSpec, _sevenZipContextMenu, _systemContextMenu, true); 805 CreateFileMenu(menuSpec, _sevenZipContextMenu, _systemContextMenu, true); // programMenu
783} 806}
784 807
785void CPanel::CreateSevenZipMenu(HMENU menuSpec, 808void CPanel::CreateSevenZipMenu(HMENU menuSpec,
809 bool showExtendedVerbs,
786 const CRecordVector<UInt32> &operatedIndices, 810 const CRecordVector<UInt32> &operatedIndices,
811 int firstDirIndex,
787 CMyComPtr<IContextMenu> &sevenZipContextMenu) 812 CMyComPtr<IContextMenu> &sevenZipContextMenu)
788{ 813{
789 sevenZipContextMenu.Release(); 814 sevenZipContextMenu.Release();
@@ -802,22 +827,23 @@ void CPanel::CreateSevenZipMenu(HMENU menuSpec,
802 if (contextMenu.QueryInterface(IID_IInitContextMenu, &initContextMenu) != S_OK) 827 if (contextMenu.QueryInterface(IID_IInitContextMenu, &initContextMenu) != S_OK)
803 return; 828 return;
804 */ 829 */
805 UString currentFolderUnicode = GetFsPath(); 830 ODS("=== FileName List Add START")
806 UStringVector names; 831 // for (unsigned y = 0; y < 10000; y++, contextMenuSpec->_fileNames.Clear())
807 unsigned i; 832 GetFilePaths(operatedIndices, contextMenuSpec->_fileNames);
808 for (i = 0; i < operatedIndices.Size(); i++) 833 ODS("=== FileName List Add END")
809 names.Add(currentFolderUnicode + GetItemRelPath2(operatedIndices[i])); 834 contextMenuSpec->Init_For_7zFM();
810 CRecordVector<const wchar_t *> namePointers; 835 contextMenuSpec->_attribs.FirstDirIndex = firstDirIndex;
811 for (i = 0; i < operatedIndices.Size(); i++)
812 namePointers.Add(names[i]);
813
814 // NFile::NDirectory::MySetCurrentDirectory(currentFolderUnicode);
815 if (contextMenuSpec->InitContextMenu(currentFolderUnicode, &namePointers.Front(),
816 operatedIndices.Size()) == S_OK)
817 { 836 {
818 HRESULT res = contextMenu->QueryContextMenu(menu, 0, kSevenZipStartMenuID, 837 DWORD flags = CMF_EXPLORE;
819 kSystemStartMenuID - 1, 0); 838 if (showExtendedVerbs)
820 bool sevenZipMenuCreated = SUCCEEDED(res); 839 flags |= Z7_WIN_CMF_EXTENDEDVERBS;
840 const HRESULT res = contextMenu->QueryContextMenu(menu,
841 0, // indexMenu
842 kSevenZipStartMenuID, // first
843 kSystemStartMenuID - 1, // last
844 flags);
845 ODS("=== contextMenu->QueryContextMenu END")
846 const bool sevenZipMenuCreated = SUCCEEDED(res);
821 if (sevenZipMenuCreated) 847 if (sevenZipMenuCreated)
822 { 848 {
823 // if (res != 0) 849 // if (res != 0)
@@ -834,7 +860,6 @@ void CPanel::CreateSevenZipMenu(HMENU menuSpec,
834 { 860 {
835 // MessageBox_Error_HRESULT_Caption(res, L"QueryContextMenu"); 861 // MessageBox_Error_HRESULT_Caption(res, L"QueryContextMenu");
836 } 862 }
837
838 // int code = HRESULT_CODE(res); 863 // int code = HRESULT_CODE(res);
839 // int nextItemID = code; 864 // int nextItemID = code;
840 } 865 }
@@ -917,19 +942,22 @@ void CPanel::CreateFileMenu(HMENU menuSpec,
917 sevenZipContextMenu.Release(); 942 sevenZipContextMenu.Release();
918 systemContextMenu.Release(); 943 systemContextMenu.Release();
919 944
945 const bool showExtendedVerbs = IsKeyDown(VK_SHIFT);
946
920 CRecordVector<UInt32> operatedIndices; 947 CRecordVector<UInt32> operatedIndices;
921 GetOperatedItemIndices(operatedIndices); 948 Get_ItemIndices_Operated(operatedIndices);
949 const int firstDirIndex = FindDir_InOperatedList(operatedIndices);
922 950
923 CMenu menu; 951 CMenu menu;
924 menu.Attach(menuSpec); 952 menu.Attach(menuSpec);
925 953
926 if (!IsArcFolder()) 954 if (!IsArcFolder())
927 { 955 {
928 CreateSevenZipMenu(menu, operatedIndices, sevenZipContextMenu); 956 CreateSevenZipMenu(menu, showExtendedVerbs, operatedIndices, firstDirIndex, sevenZipContextMenu);
929 // CreateSystemMenu is very slow if you call it inside ZIP archive with big number of files 957 // CreateSystemMenu is very slow if you call it inside ZIP archive with big number of files
930 // Windows probably can parse items inside ZIP archive. 958 // Windows probably can parse items inside ZIP archive.
931 if (g_App.ShowSystemMenu) 959 if (g_App.ShowSystemMenu)
932 CreateSystemMenu(menu, operatedIndices, systemContextMenu); 960 CreateSystemMenu(menu, showExtendedVerbs, operatedIndices, systemContextMenu);
933 } 961 }
934 962
935 /* 963 /*
@@ -937,19 +965,13 @@ void CPanel::CreateFileMenu(HMENU menuSpec,
937 menu.AppendItem(MF_SEPARATOR, 0, (LPCTSTR)0); 965 menu.AppendItem(MF_SEPARATOR, 0, (LPCTSTR)0);
938 */ 966 */
939 967
940 unsigned i;
941 for (i = 0; i < operatedIndices.Size(); i++)
942 if (IsItem_Folder(operatedIndices[i]))
943 break;
944 bool allAreFiles = (i == operatedIndices.Size());
945
946 CFileMenu fm; 968 CFileMenu fm;
947 969
948 fm.readOnly = IsThereReadOnlyFolder(); 970 fm.readOnly = IsThereReadOnlyFolder();
949 fm.isHashFolder = IsHashFolder(); 971 fm.isHashFolder = IsHashFolder();
950 fm.isFsFolder = Is_IO_FS_Folder(); 972 fm.isFsFolder = Is_IO_FS_Folder();
951 fm.programMenu = programMenu; 973 fm.programMenu = programMenu;
952 fm.allAreFiles = allAreFiles; 974 fm.allAreFiles = (firstDirIndex == -1);
953 fm.numItems = operatedIndices.Size(); 975 fm.numItems = operatedIndices.Size();
954 976
955 fm.isAltStreamsSupported = false; 977 fm.isAltStreamsSupported = false;
@@ -961,7 +983,7 @@ void CPanel::CreateFileMenu(HMENU menuSpec,
961 { 983 {
962 if (operatedIndices.Size() <= 1) 984 if (operatedIndices.Size() <= 1)
963 { 985 {
964 Int32 realIndex = -1; 986 UInt32 realIndex = (UInt32)(Int32)-1;
965 if (operatedIndices.Size() == 1) 987 if (operatedIndices.Size() == 1)
966 realIndex = operatedIndices[0]; 988 realIndex = operatedIndices[0];
967 Int32 val = 0; 989 Int32 val = 0;
@@ -977,7 +999,7 @@ void CPanel::CreateFileMenu(HMENU menuSpec,
977 fm.isAltStreamsSupported = IsFolder_with_FsItems(); 999 fm.isAltStreamsSupported = IsFolder_with_FsItems();
978 } 1000 }
979 1001
980 fm.Load(menu, menu.GetItemCount()); 1002 fm.Load(menu, (unsigned)menu.GetItemCount());
981} 1003}
982 1004
983bool CPanel::InvokePluginCommand(unsigned id) 1005bool CPanel::InvokePluginCommand(unsigned id)
@@ -987,6 +1009,7 @@ bool CPanel::InvokePluginCommand(unsigned id)
987 1009
988#if defined(_MSC_VER) && !defined(UNDER_CE) 1010#if defined(_MSC_VER) && !defined(UNDER_CE)
989#define use_CMINVOKECOMMANDINFOEX 1011#define use_CMINVOKECOMMANDINFOEX
1012/* CMINVOKECOMMANDINFOEX depends from (_WIN32_IE >= 0x0400) */
990#endif 1013#endif
991 1014
992bool CPanel::InvokePluginCommand(unsigned id, 1015bool CPanel::InvokePluginCommand(unsigned id,
@@ -1096,7 +1119,7 @@ bool CPanel::OnContextMenu(HANDLE windowHandle, int xPos, int yPos)
1096 */ 1119 */
1097 1120
1098 CRecordVector<UInt32> operatedIndices; 1121 CRecordVector<UInt32> operatedIndices;
1099 GetOperatedItemIndices(operatedIndices); 1122 Get_ItemIndices_Operated(operatedIndices);
1100 1123
1101 // negative x,y are possible for multi-screen modes. 1124 // negative x,y are possible for multi-screen modes.
1102 // x=-1 && y=-1 for keyboard call (SHIFT+F10 and others). 1125 // x=-1 && y=-1 for keyboard call (SHIFT+F10 and others).
@@ -1130,9 +1153,9 @@ bool CPanel::OnContextMenu(HANDLE windowHandle, int xPos, int yPos)
1130 1153
1131 CMyComPtr<IContextMenu> sevenZipContextMenu; 1154 CMyComPtr<IContextMenu> sevenZipContextMenu;
1132 CMyComPtr<IContextMenu> systemContextMenu; 1155 CMyComPtr<IContextMenu> systemContextMenu;
1133 CreateFileMenu(menu, sevenZipContextMenu, systemContextMenu, false); 1156 CreateFileMenu(menu, sevenZipContextMenu, systemContextMenu, false); // programMenu
1134 1157
1135 unsigned id = menu.Track(TPM_LEFTALIGN 1158 const unsigned id = (unsigned)menu.Track(TPM_LEFTALIGN
1136 #ifndef UNDER_CE 1159 #ifndef UNDER_CE
1137 | TPM_RIGHTBUTTON 1160 | TPM_RIGHTBUTTON
1138 #endif 1161 #endif
diff --git a/CPP/7zip/UI/FileManager/PanelOperations.cpp b/CPP/7zip/UI/FileManager/PanelOperations.cpp
index a683b5e..b61f4e9 100644
--- a/CPP/7zip/UI/FileManager/PanelOperations.cpp
+++ b/CPP/7zip/UI/FileManager/PanelOperations.cpp
@@ -24,9 +24,6 @@ using namespace NWindows;
24using namespace NFile; 24using namespace NFile;
25using namespace NName; 25using namespace NName;
26 26
27#define MY_CAST_FUNC (void(*)())
28// #define MY_CAST_FUNC
29
30#ifndef _UNICODE 27#ifndef _UNICODE
31extern bool g_IsNT; 28extern bool g_IsNT;
32#endif 29#endif
@@ -40,7 +37,7 @@ enum EFolderOpType
40 37
41class CThreadFolderOperations: public CProgressThreadVirt 38class CThreadFolderOperations: public CProgressThreadVirt
42{ 39{
43 HRESULT ProcessVirt(); 40 HRESULT ProcessVirt() Z7_override;
44public: 41public:
45 EFolderOpType OpType; 42 EFolderOpType OpType;
46 UString Name; 43 UString Name;
@@ -58,7 +55,7 @@ public:
58HRESULT CThreadFolderOperations::ProcessVirt() 55HRESULT CThreadFolderOperations::ProcessVirt()
59{ 56{
60 NCOM::CComInitializer comInitializer; 57 NCOM::CComInitializer comInitializer;
61 switch (OpType) 58 switch ((int)OpType)
62 { 59 {
63 case FOLDER_TYPE_CREATE_FOLDER: 60 case FOLDER_TYPE_CREATE_FOLDER:
64 return FolderOperations->CreateFolder(Name, UpdateCallback); 61 return FolderOperations->CreateFolder(Name, UpdateCallback);
@@ -94,7 +91,7 @@ HRESULT CThreadFolderOperations::DoOperation(CPanel &panel, const UString &progr
94 MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE); 91 MainTitle = "7-Zip"; // LangString(IDS_APP_TITLE);
95 MainAddTitle = progressTitle + L' '; 92 MainAddTitle = progressTitle + L' ';
96 93
97 RINOK(Create(progressTitle, MainWindow)); 94 RINOK(Create(progressTitle, MainWindow))
98 return Result; 95 return Result;
99} 96}
100 97
@@ -116,7 +113,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
116{ 113{
117 CDisableTimerProcessing disableTimerProcessing(*this); 114 CDisableTimerProcessing disableTimerProcessing(*this);
118 CRecordVector<UInt32> indices; 115 CRecordVector<UInt32> indices;
119 GetOperatedItemIndices(indices); 116 Get_ItemIndices_Operated(indices);
120 if (indices.IsEmpty()) 117 if (indices.IsEmpty())
121 return; 118 return;
122 CSelectedState state; 119 CSelectedState state;
@@ -141,7 +138,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
141 fo.hwnd = GetParent(); 138 fo.hwnd = GetParent();
142 fo.wFunc = FO_DELETE; 139 fo.wFunc = FO_DELETE;
143 fo.pFrom = (const CHAR *)buffer; 140 fo.pFrom = (const CHAR *)buffer;
144 fo.pTo = 0; 141 fo.pTo = NULL;
145 fo.fFlags = 0; 142 fo.fFlags = 0;
146 if (toRecycleBin) 143 if (toRecycleBin)
147 fo.fFlags |= FOF_ALLOWUNDO; 144 fo.fFlags |= FOF_ALLOWUNDO;
@@ -150,8 +147,8 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
150 // fo.fFlags |= FOF_SILENT; 147 // fo.fFlags |= FOF_SILENT;
151 // fo.fFlags |= FOF_WANTNUKEWARNING; 148 // fo.fFlags |= FOF_WANTNUKEWARNING;
152 fo.fAnyOperationsAborted = FALSE; 149 fo.fAnyOperationsAborted = FALSE;
153 fo.hNameMappings = 0; 150 fo.hNameMappings = NULL;
154 fo.lpszProgressTitle = 0; 151 fo.lpszProgressTitle = NULL;
155 /* int res = */ ::SHFileOperationA(&fo); 152 /* int res = */ ::SHFileOperationA(&fo);
156 } 153 }
157 else 154 else
@@ -184,23 +181,24 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
184 fo.hwnd = GetParent(); 181 fo.hwnd = GetParent();
185 fo.wFunc = FO_DELETE; 182 fo.wFunc = FO_DELETE;
186 fo.pFrom = (const WCHAR *)buffer; 183 fo.pFrom = (const WCHAR *)buffer;
187 fo.pTo = 0; 184 fo.pTo = NULL;
188 fo.fFlags = 0; 185 fo.fFlags = 0;
189 if (toRecycleBin) 186 if (toRecycleBin)
190 fo.fFlags |= FOF_ALLOWUNDO; 187 fo.fFlags |= FOF_ALLOWUNDO;
191 fo.fAnyOperationsAborted = FALSE; 188 fo.fAnyOperationsAborted = FALSE;
192 fo.hNameMappings = 0; 189 fo.hNameMappings = NULL;
193 fo.lpszProgressTitle = 0; 190 fo.lpszProgressTitle = NULL;
194 // int res; 191 // int res;
195 #ifdef _UNICODE 192 #ifdef _UNICODE
196 /* res = */ ::SHFileOperationW(&fo); 193 /* res = */ ::SHFileOperationW(&fo);
197 #else 194 #else
198 Func_SHFileOperationW shFileOperationW = (Func_SHFileOperationW) 195 Func_SHFileOperationW
199 MY_CAST_FUNC 196 f_SHFileOperationW = Z7_GET_PROC_ADDRESS(
200 ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHFileOperationW"); 197 Func_SHFileOperationW, ::GetModuleHandleW(L"shell32.dll"),
201 if (!shFileOperationW) 198 "SHFileOperationW");
199 if (!f_SHFileOperationW)
202 return; 200 return;
203 /* res = */ shFileOperationW(&fo); 201 /* res = */ f_SHFileOperationW(&fo);
204 #endif 202 #endif
205 } 203 }
206 } 204 }
@@ -225,7 +223,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
225 UString messageParam; 223 UString messageParam;
226 if (indices.Size() == 1) 224 if (indices.Size() == 1)
227 { 225 {
228 int index = indices[0]; 226 const unsigned index = indices[0];
229 messageParam = GetItemRelPath2(index); 227 messageParam = GetItemRelPath2(index);
230 if (IsItem_Folder(index)) 228 if (IsItem_Folder(index))
231 { 229 {
@@ -262,7 +260,7 @@ void CPanel::DeleteItems(bool NON_CE_VAR(toRecycleBin))
262 260
263BOOL CPanel::OnBeginLabelEdit(LV_DISPINFOW * lpnmh) 261BOOL CPanel::OnBeginLabelEdit(LV_DISPINFOW * lpnmh)
264{ 262{
265 int realIndex = GetRealIndex(lpnmh->item); 263 const unsigned realIndex = GetRealIndex(lpnmh->item);
266 if (realIndex == kParentIndex) 264 if (realIndex == kParentIndex)
267 return TRUE; 265 return TRUE;
268 if (IsThereReadOnlyFolder()) 266 if (IsThereReadOnlyFolder())
@@ -314,7 +312,7 @@ BOOL CPanel::OnEndLabelEdit(LV_DISPINFOW * lpnmh)
314 312
315 SaveSelectedState(_selectedState); 313 SaveSelectedState(_selectedState);
316 314
317 int realIndex = GetRealIndex(lpnmh->item); 315 const unsigned realIndex = GetRealIndex(lpnmh->item);
318 if (realIndex == kParentIndex) 316 if (realIndex == kParentIndex)
319 return FALSE; 317 return FALSE;
320 const UString prefix = GetItemPrefix(realIndex); 318 const UString prefix = GetItemPrefix(realIndex);
@@ -454,14 +452,14 @@ void CPanel::CreateFile()
454 newName = correctName; 452 newName = correctName;
455 } 453 }
456 454
457 HRESULT result = _folderOperations->CreateFile(newName, 0); 455 const HRESULT result = _folderOperations->CreateFile(newName, NULL);
458 if (result != S_OK) 456 if (result != S_OK)
459 { 457 {
460 MessageBox_Error_HRESULT_Caption(result, LangString(IDS_CREATE_FILE_ERROR)); 458 MessageBox_Error_HRESULT_Caption(result, LangString(IDS_CREATE_FILE_ERROR));
461 // MessageBoxErrorForUpdate(result, IDS_CREATE_FILE_ERROR); 459 // MessageBoxErrorForUpdate(result, IDS_CREATE_FILE_ERROR);
462 return; 460 return;
463 } 461 }
464 int pos = newName.Find(WCHAR_PATH_SEPARATOR); 462 const int pos = newName.Find(WCHAR_PATH_SEPARATOR);
465 if (pos >= 0) 463 if (pos >= 0)
466 newName.DeleteFrom((unsigned)pos); 464 newName.DeleteFrom((unsigned)pos);
467 if (!_mySelectMode) 465 if (!_mySelectMode)
@@ -488,10 +486,10 @@ void CPanel::ChangeComment()
488 if (!CheckBeforeUpdate(IDS_COMMENT)) 486 if (!CheckBeforeUpdate(IDS_COMMENT))
489 return; 487 return;
490 CDisableTimerProcessing disableTimerProcessing2(*this); 488 CDisableTimerProcessing disableTimerProcessing2(*this);
491 int index = _listView.GetFocusedItem(); 489 const int index = _listView.GetFocusedItem();
492 if (index < 0) 490 if (index < 0)
493 return; 491 return;
494 int realIndex = GetRealItemIndex(index); 492 const unsigned realIndex = GetRealItemIndex(index);
495 if (realIndex == kParentIndex) 493 if (realIndex == kParentIndex)
496 return; 494 return;
497 CSelectedState state; 495 CSelectedState state;
@@ -506,7 +504,7 @@ void CPanel::ChangeComment()
506 else if (propVariant.vt != VT_EMPTY) 504 else if (propVariant.vt != VT_EMPTY)
507 return; 505 return;
508 } 506 }
509 UString name = GetItemRelPath2(realIndex); 507 const UString name = GetItemRelPath2(realIndex);
510 CComboDialog dlg; 508 CComboDialog dlg;
511 dlg.Title = name; 509 dlg.Title = name;
512 dlg.Title += " : "; 510 dlg.Title += " : ";
@@ -518,7 +516,7 @@ void CPanel::ChangeComment()
518 NCOM::CPropVariant propVariant (dlg.Value); 516 NCOM::CPropVariant propVariant (dlg.Value);
519 517
520 CDisableNotify disableNotify(*this); 518 CDisableNotify disableNotify(*this);
521 HRESULT result = _folderOperations->SetProperty(realIndex, kpidComment, &propVariant, NULL); 519 const HRESULT result = _folderOperations->SetProperty(realIndex, kpidComment, &propVariant, NULL);
522 if (result != S_OK) 520 if (result != S_OK)
523 { 521 {
524 if (result == E_NOINTERFACE) 522 if (result == E_NOINTERFACE)
diff --git a/CPP/7zip/UI/FileManager/PanelSelect.cpp b/CPP/7zip/UI/FileManager/PanelSelect.cpp
index eab9e1a..f7a16dd 100644
--- a/CPP/7zip/UI/FileManager/PanelSelect.cpp
+++ b/CPP/7zip/UI/FileManager/PanelSelect.cpp
@@ -15,7 +15,7 @@ void CPanel::OnShiftSelectMessage()
15{ 15{
16 if (!_mySelectMode) 16 if (!_mySelectMode)
17 return; 17 return;
18 int focusedItem = _listView.GetFocusedItem(); 18 const int focusedItem = _listView.GetFocusedItem();
19 if (focusedItem < 0) 19 if (focusedItem < 0)
20 return; 20 return;
21 if (!_selectionIsDefined) 21 if (!_selectionIsDefined)
@@ -26,7 +26,7 @@ void CPanel::OnShiftSelectMessage()
26 int numItems = _listView.GetItemCount(); 26 int numItems = _listView.GetItemCount();
27 for (int i = 0; i < numItems; i++) 27 for (int i = 0; i < numItems; i++)
28 { 28 {
29 int realIndex = GetRealItemIndex(i); 29 const unsigned realIndex = GetRealItemIndex(i);
30 if (realIndex == kParentIndex) 30 if (realIndex == kParentIndex)
31 continue; 31 continue;
32 if (i >= startItem && i <= finishItem) 32 if (i >= startItem && i <= finishItem)
@@ -44,10 +44,10 @@ void CPanel::OnArrowWithShift()
44{ 44{
45 if (!_mySelectMode) 45 if (!_mySelectMode)
46 return; 46 return;
47 int focusedItem = _listView.GetFocusedItem(); 47 const int focusedItem = _listView.GetFocusedItem();
48 if (focusedItem < 0) 48 if (focusedItem < 0)
49 return; 49 return;
50 int realIndex = GetRealItemIndex(focusedItem); 50 const unsigned realIndex = GetRealItemIndex(focusedItem);
51 51
52 if (_selectionIsDefined) 52 if (_selectionIsDefined)
53 { 53 {
@@ -84,11 +84,11 @@ void CPanel::OnInsert()
84 // _listView.SetItemState_Selected(focusedItem); 84 // _listView.SetItemState_Selected(focusedItem);
85 */ 85 */
86 86
87 int focusedItem = _listView.GetFocusedItem(); 87 const int focusedItem = _listView.GetFocusedItem();
88 if (focusedItem < 0) 88 if (focusedItem < 0)
89 return; 89 return;
90 90
91 int realIndex = GetRealItemIndex(focusedItem); 91 const unsigned realIndex = GetRealItemIndex(focusedItem);
92 if (realIndex != kParentIndex) 92 if (realIndex != kParentIndex)
93 { 93 {
94 bool isSelected = !_selectedStatusVector[realIndex]; 94 bool isSelected = !_selectedStatusVector[realIndex];
@@ -109,10 +109,10 @@ void CPanel::OnInsert()
109/* 109/*
110void CPanel::OnUpWithShift() 110void CPanel::OnUpWithShift()
111{ 111{
112 int focusedItem = _listView.GetFocusedItem(); 112 const int focusedItem = _listView.GetFocusedItem();
113 if (focusedItem < 0) 113 if (focusedItem < 0)
114 return; 114 return;
115 int index = GetRealItemIndex(focusedItem); 115 const int index = GetRealItemIndex(focusedItem);
116 if (index == kParentIndex) 116 if (index == kParentIndex)
117 return; 117 return;
118 _selectedStatusVector[index] = !_selectedStatusVector[index]; 118 _selectedStatusVector[index] = !_selectedStatusVector[index];
@@ -121,10 +121,10 @@ void CPanel::OnUpWithShift()
121 121
122void CPanel::OnDownWithShift() 122void CPanel::OnDownWithShift()
123{ 123{
124 int focusedItem = _listView.GetFocusedItem(); 124 const int focusedItem = _listView.GetFocusedItem();
125 if (focusedItem < 0) 125 if (focusedItem < 0)
126 return; 126 return;
127 int index = GetRealItemIndex(focusedItem); 127 const int index = GetRealItemIndex(focusedItem);
128 if (index == kParentIndex) 128 if (index == kParentIndex)
129 return; 129 return;
130 _selectedStatusVector[index] = !_selectedStatusVector[index]; 130 _selectedStatusVector[index] = !_selectedStatusVector[index];
@@ -141,7 +141,7 @@ void CPanel::UpdateSelection()
141 int numItems = _listView.GetItemCount(); 141 int numItems = _listView.GetItemCount();
142 for (int i = 0; i < numItems; i++) 142 for (int i = 0; i < numItems; i++)
143 { 143 {
144 int realIndex = GetRealItemIndex(i); 144 const unsigned realIndex = GetRealItemIndex(i);
145 if (realIndex != kParentIndex) 145 if (realIndex != kParentIndex)
146 _listView.SetItemState_Selected(i, _selectedStatusVector[realIndex]); 146 _listView.SetItemState_Selected(i, _selectedStatusVector[realIndex]);
147 } 147 }
@@ -168,10 +168,10 @@ void CPanel::SelectSpec(bool selectMode)
168 168
169void CPanel::SelectByType(bool selectMode) 169void CPanel::SelectByType(bool selectMode)
170{ 170{
171 int focusedItem = _listView.GetFocusedItem(); 171 const int focusedItem = _listView.GetFocusedItem();
172 if (focusedItem < 0) 172 if (focusedItem < 0)
173 return; 173 return;
174 int realIndex = GetRealItemIndex(focusedItem); 174 const unsigned realIndex = GetRealItemIndex(focusedItem);
175 UString name = GetItemName(realIndex); 175 UString name = GetItemName(realIndex);
176 bool isItemFolder = IsItem_Folder(realIndex); 176 bool isItemFolder = IsItem_Folder(realIndex);
177 177
@@ -214,10 +214,12 @@ void CPanel::InvertSelection()
214{ 214{
215 if (!_mySelectMode) 215 if (!_mySelectMode)
216 { 216 {
217 /*
217 unsigned numSelected = 0; 218 unsigned numSelected = 0;
218 FOR_VECTOR (i, _selectedStatusVector) 219 FOR_VECTOR (i, _selectedStatusVector)
219 if (_selectedStatusVector[i]) 220 if (_selectedStatusVector[i])
220 numSelected++; 221 numSelected++;
222 */
221 // 17.02: fixed : now we invert item even, if single item is selected 223 // 17.02: fixed : now we invert item even, if single item is selected
222 /* 224 /*
223 if (numSelected == 1) 225 if (numSelected == 1)
@@ -225,7 +227,7 @@ void CPanel::InvertSelection()
225 int focused = _listView.GetFocusedItem(); 227 int focused = _listView.GetFocusedItem();
226 if (focused >= 0) 228 if (focused >= 0)
227 { 229 {
228 int realIndex = GetRealItemIndex(focused); 230 const unsigned realIndex = GetRealItemIndex(focused);
229 if (realIndex >= 0) 231 if (realIndex >= 0)
230 if (_selectedStatusVector[realIndex]) 232 if (_selectedStatusVector[realIndex])
231 _selectedStatusVector[realIndex] = false; 233 _selectedStatusVector[realIndex] = false;
@@ -251,7 +253,7 @@ void CPanel::KillSelection()
251 { 253 {
252 // CPanel::OnItemChanged notify for LVIS_SELECTED change doesn't work here. Why? 254 // CPanel::OnItemChanged notify for LVIS_SELECTED change doesn't work here. Why?
253 // so we change _selectedStatusVector[realIndex] here. 255 // so we change _selectedStatusVector[realIndex] here.
254 int realIndex = GetRealItemIndex(focused); 256 const unsigned realIndex = GetRealItemIndex(focused);
255 if (realIndex != kParentIndex) 257 if (realIndex != kParentIndex)
256 _selectedStatusVector[realIndex] = true; 258 _selectedStatusVector[realIndex] = true;
257 _listView.SetItemState_Selected(focused); 259 _listView.SetItemState_Selected(focused);
@@ -273,19 +275,19 @@ void CPanel::OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate)
273 if ((itemActivate->uKeyFlags & LVKF_SHIFT) != 0) 275 if ((itemActivate->uKeyFlags & LVKF_SHIFT) != 0)
274 { 276 {
275 // int focusedIndex = _listView.GetFocusedItem(); 277 // int focusedIndex = _listView.GetFocusedItem();
276 int focusedIndex = _startGroupSelect; 278 const int focusedIndex = _startGroupSelect;
277 if (focusedIndex < 0) 279 if (focusedIndex < 0)
278 return; 280 return;
279 int startItem = MyMin(focusedIndex, indexInList); 281 const int startItem = MyMin(focusedIndex, indexInList);
280 int finishItem = MyMax(focusedIndex, indexInList); 282 const int finishItem = MyMax(focusedIndex, indexInList);
281 283
282 int numItems = _listView.GetItemCount(); 284 const int numItems = _listView.GetItemCount();
283 for (int i = 0; i < numItems; i++) 285 for (int i = 0; i < numItems; i++)
284 { 286 {
285 int realIndex = GetRealItemIndex(i); 287 const unsigned realIndex = GetRealItemIndex(i);
286 if (realIndex == kParentIndex) 288 if (realIndex == kParentIndex)
287 continue; 289 continue;
288 bool selected = (i >= startItem && i <= finishItem); 290 const bool selected = (i >= startItem && i <= finishItem);
289 if (_selectedStatusVector[realIndex] != selected) 291 if (_selectedStatusVector[realIndex] != selected)
290 { 292 {
291 _selectedStatusVector[realIndex] = selected; 293 _selectedStatusVector[realIndex] = selected;
@@ -301,7 +303,7 @@ void CPanel::OnLeftClick(MY_NMLISTVIEW_NMITEMACTIVATE *itemActivate)
301 #ifndef UNDER_CE 303 #ifndef UNDER_CE
302 if ((itemActivate->uKeyFlags & LVKF_CONTROL) != 0) 304 if ((itemActivate->uKeyFlags & LVKF_CONTROL) != 0)
303 { 305 {
304 int realIndex = GetRealItemIndex(indexInList); 306 const unsigned realIndex = GetRealItemIndex(indexInList);
305 if (realIndex != kParentIndex) 307 if (realIndex != kParentIndex)
306 { 308 {
307 _selectedStatusVector[realIndex] = !_selectedStatusVector[realIndex]; 309 _selectedStatusVector[realIndex] = !_selectedStatusVector[realIndex];
diff --git a/CPP/7zip/UI/FileManager/PanelSort.cpp b/CPP/7zip/UI/FileManager/PanelSort.cpp
index d26acb7..f95f8ee 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)
52 52
53static int CompareFileNames_Le16(const Byte *s1, unsigned size1, const Byte *s2, unsigned size2) 53static int CompareFileNames_Le16(const Byte *s1, unsigned size1, const Byte *s2, unsigned size2)
54{ 54{
55 size1 &= ~1; 55 size1 &= ~1u;
56 size2 &= ~1; 56 size2 &= ~1u;
57 for (unsigned i = 0;; i += 2) 57 for (unsigned i = 0;; i += 2)
58 { 58 {
59 if (i >= size1) 59 if (i >= size1)
@@ -76,8 +76,8 @@ static int CompareFileNames_Le16(const Byte *s1, unsigned size1, const Byte *s2,
76 76
77static inline const wchar_t *GetExtensionPtr(const UString &name) 77static inline const wchar_t *GetExtensionPtr(const UString &name)
78{ 78{
79 int dotPos = name.ReverseFind_Dot(); 79 const int dotPos = name.ReverseFind_Dot();
80 return name.Ptr((dotPos < 0) ? name.Len() : dotPos); 80 return name.Ptr(dotPos < 0 ? name.Len() : (unsigned)dotPos);
81} 81}
82 82
83void CPanel::SetSortRawStatus() 83void CPanel::SetSortRawStatus()
@@ -142,9 +142,9 @@ static int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
142 // if (panel->_sortIndex == 0) 142 // if (panel->_sortIndex == 0)
143 case kpidName: 143 case kpidName:
144 { 144 {
145 const UString name1 = panel->GetItemName((int)lParam1); 145 const UString name1 = panel->GetItemName((unsigned)lParam1);
146 const UString name2 = panel->GetItemName((int)lParam2); 146 const UString name2 = panel->GetItemName((unsigned)lParam2);
147 int res = CompareFileNames_ForFolderList(name1, name2); 147 const int res = CompareFileNames_ForFolderList(name1, name2);
148 /* 148 /*
149 if (res != 0 || !panel->_flatMode) 149 if (res != 0 || !panel->_flatMode)
150 return res; 150 return res;
@@ -156,8 +156,8 @@ static int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
156 } 156 }
157 case kpidExtension: 157 case kpidExtension:
158 { 158 {
159 const UString name1 = panel->GetItemName((int)lParam1); 159 const UString name1 = panel->GetItemName((unsigned)lParam1);
160 const UString name2 = panel->GetItemName((int)lParam2); 160 const UString name2 = panel->GetItemName((unsigned)lParam2);
161 return CompareFileNames_ForFolderList( 161 return CompareFileNames_ForFolderList(
162 GetExtensionPtr(name1), 162 GetExtensionPtr(name1),
163 GetExtensionPtr(name2)); 163 GetExtensionPtr(name2));
@@ -186,18 +186,18 @@ int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData);
186int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData) 186int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
187{ 187{
188 if (lpData == 0) return 0; 188 if (lpData == 0) return 0;
189 if (lParam1 == kParentIndex) return -1; 189 if (lParam1 == (int)kParentIndex) return -1;
190 if (lParam2 == kParentIndex) return 1; 190 if (lParam2 == (int)kParentIndex) return 1;
191 191
192 CPanel *panel = (CPanel*)lpData; 192 CPanel *panel = (CPanel*)lpData;
193 193
194 bool isDir1 = panel->IsItem_Folder((int)lParam1); 194 const bool isDir1 = panel->IsItem_Folder((unsigned)lParam1);
195 bool isDir2 = panel->IsItem_Folder((int)lParam2); 195 const bool isDir2 = panel->IsItem_Folder((unsigned)lParam2);
196 196
197 if (isDir1 && !isDir2) return -1; 197 if (isDir1 && !isDir2) return -1;
198 if (isDir2 && !isDir1) return 1; 198 if (isDir2 && !isDir1) return 1;
199 199
200 int result = CompareItems2(lParam1, lParam2, lpData); 200 const int result = CompareItems2(lParam1, lParam2, lpData);
201 return panel->_ascending ? result: (-result); 201 return panel->_ascending ? result: (-result);
202} 202}
203 203
diff --git a/CPP/7zip/UI/FileManager/PanelSplitFile.cpp b/CPP/7zip/UI/FileManager/PanelSplitFile.cpp
index 00a0d80..64aa039 100644
--- a/CPP/7zip/UI/FileManager/PanelSplitFile.cpp
+++ b/CPP/7zip/UI/FileManager/PanelSplitFile.cpp
@@ -30,7 +30,7 @@ struct CVolSeqName
30{ 30{
31 UString UnchangedPart; 31 UString UnchangedPart;
32 UString ChangedPart; 32 UString ChangedPart;
33 CVolSeqName(): ChangedPart("000") {}; 33 CVolSeqName(): ChangedPart("000") {}
34 34
35 void SetNumDigits(UInt64 numVolumes) 35 void SetNumDigits(UInt64 numVolumes)
36 { 36 {
@@ -64,13 +64,13 @@ UString CVolSeqName::GetNextName()
64{ 64{
65 for (int i = (int)ChangedPart.Len() - 1; i >= 0; i--) 65 for (int i = (int)ChangedPart.Len() - 1; i >= 0; i--)
66 { 66 {
67 wchar_t c = ChangedPart[i]; 67 const wchar_t c = ChangedPart[i];
68 if (c != L'9') 68 if (c != L'9')
69 { 69 {
70 ChangedPart.ReplaceOneCharAtPos(i, (wchar_t)(c + 1)); 70 ChangedPart.ReplaceOneCharAtPos((unsigned)i, (wchar_t)(c + 1));
71 break; 71 break;
72 } 72 }
73 ChangedPart.ReplaceOneCharAtPos(i, L'0'); 73 ChangedPart.ReplaceOneCharAtPos((unsigned)i, L'0');
74 if (i == 0) 74 if (i == 0)
75 ChangedPart.InsertAtFront(L'1'); 75 ChangedPart.InsertAtFront(L'1');
76 } 76 }
@@ -79,7 +79,7 @@ UString CVolSeqName::GetNextName()
79 79
80class CThreadSplit: public CProgressThreadVirt 80class CThreadSplit: public CProgressThreadVirt
81{ 81{
82 HRESULT ProcessVirt(); 82 HRESULT ProcessVirt() Z7_override;
83public: 83public:
84 FString FilePath; 84 FString FilePath;
85 FString VolBasePath; 85 FString VolBasePath;
@@ -142,7 +142,7 @@ HRESULT CThreadSplit::ProcessVirt()
142{ 142{
143 NIO::CInFile inFile; 143 NIO::CInFile inFile;
144 if (!inFile.Open(FilePath)) 144 if (!inFile.Open(FilePath))
145 return GetLastError(); 145 return GetLastError_noZero_HRESULT();
146 146
147 CPreAllocOutFile outFile; 147 CPreAllocOutFile outFile;
148 148
@@ -155,7 +155,7 @@ HRESULT CThreadSplit::ProcessVirt()
155 155
156 UInt64 length; 156 UInt64 length;
157 if (!inFile.GetLength(length)) 157 if (!inFile.GetLength(length))
158 return GetLastError(); 158 return GetLastError_noZero_HRESULT();
159 159
160 CProgressSync &sync = Sync; 160 CProgressSync &sync = Sync;
161 sync.Set_NumBytesTotal(length); 161 sync.Set_NumBytesTotal(length);
@@ -181,7 +181,7 @@ HRESULT CThreadSplit::ProcessVirt()
181 } 181 }
182 UInt32 processedSize; 182 UInt32 processedSize;
183 if (!inFile.Read(buffer, needSize, processedSize)) 183 if (!inFile.Read(buffer, needSize, processedSize))
184 return GetLastError(); 184 return GetLastError_noZero_HRESULT();
185 if (processedSize == 0) 185 if (processedSize == 0)
186 return S_OK; 186 return S_OK;
187 needSize = processedSize; 187 needSize = processedSize;
@@ -189,12 +189,12 @@ HRESULT CThreadSplit::ProcessVirt()
189 if (outFile.Written == 0) 189 if (outFile.Written == 0)
190 { 190 {
191 FString name = VolBasePath; 191 FString name = VolBasePath;
192 name += '.'; 192 name.Add_Dot();
193 name += us2fs(seqName.GetNextName()); 193 name += us2fs(seqName.GetNextName());
194 sync.Set_FilePath(fs2us(name)); 194 sync.Set_FilePath(fs2us(name));
195 if (!outFile.File.Create(name, false)) 195 if (!outFile.File.Create(name, false))
196 { 196 {
197 HRESULT res = GetLastError(); 197 const HRESULT res = GetLastError_noZero_HRESULT();
198 AddErrorPath(name); 198 AddErrorPath(name);
199 return res; 199 return res;
200 } 200 }
@@ -209,7 +209,7 @@ HRESULT CThreadSplit::ProcessVirt()
209 } 209 }
210 210
211 if (!outFile.Write(buffer, needSize, processedSize)) 211 if (!outFile.Write(buffer, needSize, processedSize))
212 return GetLastError(); 212 return GetLastError_noZero_HRESULT();
213 if (needSize != processedSize) 213 if (needSize != processedSize)
214 throw g_Message_FileWriteError; 214 throw g_Message_FileWriteError;
215 215
@@ -225,7 +225,7 @@ HRESULT CThreadSplit::ProcessVirt()
225 225
226 if (pos - prev >= ((UInt32)1 << 22) || outFile.Written == 0) 226 if (pos - prev >= ((UInt32)1 << 22) || outFile.Written == 0)
227 { 227 {
228 RINOK(sync.Set_NumBytesCur(pos)); 228 RINOK(sync.Set_NumBytesCur(pos))
229 prev = pos; 229 prev = pos;
230 } 230 }
231 } 231 }
@@ -234,7 +234,7 @@ HRESULT CThreadSplit::ProcessVirt()
234 234
235void CApp::Split() 235void CApp::Split()
236{ 236{
237 int srcPanelIndex = GetFocusedPanelIndex(); 237 const unsigned srcPanelIndex = GetFocusedPanelIndex();
238 CPanel &srcPanel = Panels[srcPanelIndex]; 238 CPanel &srcPanel = Panels[srcPanelIndex];
239 if (!srcPanel.Is_IO_FS_Folder()) 239 if (!srcPanel.Is_IO_FS_Folder())
240 { 240 {
@@ -242,7 +242,7 @@ void CApp::Split()
242 return; 242 return;
243 } 243 }
244 CRecordVector<UInt32> indices; 244 CRecordVector<UInt32> indices;
245 srcPanel.GetOperatedItemIndices(indices); 245 srcPanel.Get_ItemIndices_Operated(indices);
246 if (indices.IsEmpty()) 246 if (indices.IsEmpty())
247 return; 247 return;
248 if (indices.Size() != 1) 248 if (indices.Size() != 1)
@@ -250,7 +250,7 @@ void CApp::Split()
250 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); 250 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE);
251 return; 251 return;
252 } 252 }
253 int index = indices[0]; 253 const unsigned index = indices[0];
254 if (srcPanel.IsItem_Folder(index)) 254 if (srcPanel.IsItem_Folder(index))
255 { 255 {
256 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); 256 srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE);
@@ -258,7 +258,7 @@ void CApp::Split()
258 } 258 }
259 const UString itemName = srcPanel.GetItemName(index); 259 const UString itemName = srcPanel.GetItemName(index);
260 260
261 UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index); 261 const UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index);
262 UString path = srcPath; 262 UString path = srcPath;
263 unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); 263 unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex);
264 CPanel &destPanel = Panels[destPanelIndex]; 264 CPanel &destPanel = Panels[destPanelIndex];
@@ -297,7 +297,7 @@ void CApp::Split()
297 NName::NormalizeDirPathPrefix(path); 297 NName::NormalizeDirPathPrefix(path);
298 if (!CreateComplexDir(us2fs(path))) 298 if (!CreateComplexDir(us2fs(path)))
299 { 299 {
300 DWORD lastError = ::GetLastError(); 300 const HRESULT lastError = GetLastError_noZero_HRESULT();
301 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); 301 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError);
302 return; 302 return;
303 } 303 }
@@ -308,8 +308,8 @@ void CApp::Split()
308 308
309 CProgressDialog &progressDialog = spliter; 309 CProgressDialog &progressDialog = spliter;
310 310
311 UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); 311 const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000);
312 UString title = LangString(IDS_SPLITTING); 312 const UString title = LangString(IDS_SPLITTING);
313 313
314 progressDialog.ShowCompressionInfo = false; 314 progressDialog.ShowCompressionInfo = false;
315 315
@@ -344,7 +344,7 @@ void CApp::Split()
344 344
345class CThreadCombine: public CProgressThreadVirt 345class CThreadCombine: public CProgressThreadVirt
346{ 346{
347 HRESULT ProcessVirt(); 347 HRESULT ProcessVirt() Z7_override;
348public: 348public:
349 FString InputDirPrefix; 349 FString InputDirPrefix;
350 FStringVector Names; 350 FStringVector Names;
@@ -357,7 +357,7 @@ HRESULT CThreadCombine::ProcessVirt()
357 NIO::COutFile outFile; 357 NIO::COutFile outFile;
358 if (!outFile.Create(OutputPath, false)) 358 if (!outFile.Create(OutputPath, false))
359 { 359 {
360 HRESULT res = GetLastError(); 360 const HRESULT res = GetLastError_noZero_HRESULT();
361 AddErrorPath(OutputPath); 361 AddErrorPath(OutputPath);
362 return res; 362 return res;
363 } 363 }
@@ -376,7 +376,7 @@ HRESULT CThreadCombine::ProcessVirt()
376 const FString nextName = InputDirPrefix + Names[i]; 376 const FString nextName = InputDirPrefix + Names[i];
377 if (!inFile.Open(nextName)) 377 if (!inFile.Open(nextName))
378 { 378 {
379 HRESULT res = GetLastError(); 379 const HRESULT res = GetLastError_noZero_HRESULT();
380 AddErrorPath(nextName); 380 AddErrorPath(nextName);
381 return res; 381 return res;
382 } 382 }
@@ -386,23 +386,23 @@ HRESULT CThreadCombine::ProcessVirt()
386 UInt32 processedSize; 386 UInt32 processedSize;
387 if (!inFile.Read(buffer, kBufSize, processedSize)) 387 if (!inFile.Read(buffer, kBufSize, processedSize))
388 { 388 {
389 HRESULT res = GetLastError(); 389 const HRESULT res = GetLastError_noZero_HRESULT();
390 AddErrorPath(nextName); 390 AddErrorPath(nextName);
391 return res; 391 return res;
392 } 392 }
393 if (processedSize == 0) 393 if (processedSize == 0)
394 break; 394 break;
395 UInt32 needSize = processedSize; 395 const UInt32 needSize = processedSize;
396 if (!outFile.Write(buffer, needSize, processedSize)) 396 if (!outFile.Write(buffer, needSize, processedSize))
397 { 397 {
398 HRESULT res = GetLastError(); 398 const HRESULT res = GetLastError_noZero_HRESULT();
399 AddErrorPath(OutputPath); 399 AddErrorPath(OutputPath);
400 return res; 400 return res;
401 } 401 }
402 if (needSize != processedSize) 402 if (needSize != processedSize)
403 throw g_Message_FileWriteError; 403 throw g_Message_FileWriteError;
404 pos += processedSize; 404 pos += processedSize;
405 RINOK(sync.Set_NumBytesCur(pos)); 405 RINOK(sync.Set_NumBytesCur(pos))
406 } 406 }
407 } 407 }
408 return S_OK; 408 return S_OK;
@@ -418,7 +418,7 @@ static void AddInfoFileName(UString &dest, const UString &name)
418 418
419void CApp::Combine() 419void CApp::Combine()
420{ 420{
421 int srcPanelIndex = GetFocusedPanelIndex(); 421 const unsigned srcPanelIndex = GetFocusedPanelIndex();
422 CPanel &srcPanel = Panels[srcPanelIndex]; 422 CPanel &srcPanel = Panels[srcPanelIndex];
423 if (!srcPanel.IsFSFolder()) 423 if (!srcPanel.IsFSFolder())
424 { 424 {
@@ -426,10 +426,10 @@ void CApp::Combine()
426 return; 426 return;
427 } 427 }
428 CRecordVector<UInt32> indices; 428 CRecordVector<UInt32> indices;
429 srcPanel.GetOperatedItemIndices(indices); 429 srcPanel.Get_ItemIndices_Operated(indices);
430 if (indices.IsEmpty()) 430 if (indices.IsEmpty())
431 return; 431 return;
432 int index = indices[0]; 432 const unsigned index = indices[0];
433 if (indices.Size() != 1 || srcPanel.IsItem_Folder(index)) 433 if (indices.Size() != 1 || srcPanel.IsItem_Folder(index))
434 { 434 {
435 srcPanel.MessageBox_Error_LangID(IDS_COMBINE_SELECT_ONE_FILE); 435 srcPanel.MessageBox_Error_LangID(IDS_COMBINE_SELECT_ONE_FILE);
@@ -510,7 +510,7 @@ void CApp::Combine()
510 NName::NormalizeDirPathPrefix(path); 510 NName::NormalizeDirPathPrefix(path);
511 if (!CreateComplexDir(us2fs(path))) 511 if (!CreateComplexDir(us2fs(path)))
512 { 512 {
513 DWORD lastError = ::GetLastError(); 513 const HRESULT lastError = GetLastError_noZero_HRESULT();
514 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); 514 srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError);
515 return; 515 return;
516 } 516 }
@@ -537,8 +537,8 @@ void CApp::Combine()
537 CProgressDialog &progressDialog = combiner; 537 CProgressDialog &progressDialog = combiner;
538 progressDialog.ShowCompressionInfo = false; 538 progressDialog.ShowCompressionInfo = false;
539 539
540 UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000); 540 const UString progressWindowTitle ("7-Zip"); // LangString(IDS_APP_TITLE, 0x03000000);
541 UString title = LangString(IDS_COMBINING); 541 const UString title = LangString(IDS_COMBINING);
542 542
543 progressDialog.MainWindow = _window; 543 progressDialog.MainWindow = _window;
544 progressDialog.MainTitle = progressWindowTitle; 544 progressDialog.MainTitle = progressWindowTitle;
diff --git a/CPP/7zip/UI/FileManager/PasswordDialog.cpp b/CPP/7zip/UI/FileManager/PasswordDialog.cpp
index 6ead39c..bf99580 100644
--- a/CPP/7zip/UI/FileManager/PasswordDialog.cpp
+++ b/CPP/7zip/UI/FileManager/PasswordDialog.cpp
@@ -4,11 +4,11 @@
4 4
5#include "PasswordDialog.h" 5#include "PasswordDialog.h"
6 6
7#ifdef LANG 7#ifdef Z7_LANG
8#include "LangUtils.h" 8#include "LangUtils.h"
9#endif 9#endif
10 10
11#ifdef LANG 11#ifdef Z7_LANG
12static const UInt32 kLangIDs[] = 12static const UInt32 kLangIDs[] =
13{ 13{
14 IDT_PASSWORD_ENTER, 14 IDT_PASSWORD_ENTER,
@@ -30,9 +30,9 @@ void CPasswordDialog::SetTextSpec()
30 30
31bool CPasswordDialog::OnInit() 31bool CPasswordDialog::OnInit()
32{ 32{
33 #ifdef LANG 33 #ifdef Z7_LANG
34 LangSetWindowText(*this, IDD_PASSWORD); 34 LangSetWindowText(*this, IDD_PASSWORD);
35 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 35 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
36 #endif 36 #endif
37 _passwordEdit.Attach(GetItem(IDE_PASSWORD_PASSWORD)); 37 _passwordEdit.Attach(GetItem(IDE_PASSWORD_PASSWORD));
38 CheckButton(IDX_PASSWORD_SHOW, ShowPassword); 38 CheckButton(IDX_PASSWORD_SHOW, ShowPassword);
@@ -40,7 +40,7 @@ bool CPasswordDialog::OnInit()
40 return CModalDialog::OnInit(); 40 return CModalDialog::OnInit();
41} 41}
42 42
43bool CPasswordDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 43bool CPasswordDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
44{ 44{
45 if (buttonID == IDX_PASSWORD_SHOW) 45 if (buttonID == IDX_PASSWORD_SHOW)
46 { 46 {
diff --git a/CPP/7zip/UI/FileManager/PasswordDialog.h b/CPP/7zip/UI/FileManager/PasswordDialog.h
index 339ebda..e05c4ad 100644
--- a/CPP/7zip/UI/FileManager/PasswordDialog.h
+++ b/CPP/7zip/UI/FileManager/PasswordDialog.h
@@ -1,7 +1,7 @@
1// PasswordDialog.h 1// PasswordDialog.h
2 2
3#ifndef __PASSWORD_DIALOG_H 3#ifndef ZIP7_INC_PASSWORD_DIALOG_H
4#define __PASSWORD_DIALOG_H 4#define ZIP7_INC_PASSWORD_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/Edit.h" 7#include "../../../Windows/Control/Edit.h"
@@ -12,9 +12,9 @@ class CPasswordDialog: public NWindows::NControl::CModalDialog
12{ 12{
13 NWindows::NControl::CEdit _passwordEdit; 13 NWindows::NControl::CEdit _passwordEdit;
14 14
15 virtual void OnOK(); 15 virtual void OnOK() Z7_override;
16 virtual bool OnInit(); 16 virtual bool OnInit() Z7_override;
17 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 17 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
18 void SetTextSpec(); 18 void SetTextSpec();
19 void ReadControls(); 19 void ReadControls();
20public: 20public:
@@ -22,7 +22,7 @@ public:
22 bool ShowPassword; 22 bool ShowPassword;
23 23
24 CPasswordDialog(): ShowPassword(false) {} 24 CPasswordDialog(): ShowPassword(false) {}
25 INT_PTR Create(HWND parentWindow = 0) { return CModalDialog::Create(IDD_PASSWORD, parentWindow); } 25 INT_PTR Create(HWND parentWindow = NULL) { return CModalDialog::Create(IDD_PASSWORD, parentWindow); }
26}; 26};
27 27
28#endif 28#endif
diff --git a/CPP/7zip/UI/FileManager/PluginInterface.h b/CPP/7zip/UI/FileManager/PluginInterface.h
index 37654a0..dcb1b4b 100644
--- a/CPP/7zip/UI/FileManager/PluginInterface.h
+++ b/CPP/7zip/UI/FileManager/PluginInterface.h
@@ -1,31 +1,32 @@
1// PluginInterface.h 1// PluginInterface.h
2 2
3#ifndef __PLUGIN_INTERFACE_H 3#ifndef ZIP7_INC_PLUGIN_INTERFACE_H
4#define __PLUGIN_INTERFACE_H 4#define ZIP7_INC_PLUGIN_INTERFACE_H
5 5
6/* 6/*
7#include "../../../Common/Types.h" 7#include "../../../../C/7zTypes.h"
8#include "../../IDecl.h" 8#include "../../IDecl.h"
9 9
10#define PLUGIN_INTERFACE(i, x) DECL_INTERFACE(i, 0x0A, x) 10#define Z7_IFACE_CONSTR_PLUGIN(i, n) \
11 11 Z7_DECL_IFACE_7ZIP(i, 0x0A, n) \
12PLUGIN_INTERFACE(IInitContextMenu, 0x00) 12 { Z7_IFACE_COM7_PURE(i) };
13{ 13
14 STDMETHOD(InitContextMenu)(const wchar_t *folder, const wchar_t * const *names, UInt32 numFiles) PURE; 14#define Z7_IFACEM_IInitContextMenu(x) \
15}; 15 x(InitContextMenu(const wchar_t *folder, const wchar_t * const *names, UInt32 numFiles)) \
16 16
17PLUGIN_INTERFACE(IPluginOptionsCallback, 0x01) 17Z7_IFACE_CONSTR_PLUGIN(IInitContextMenu, 0x00)
18{ 18
19 STDMETHOD(GetProgramFolderPath)(BSTR *value) PURE; 19#define Z7_IFACEM_IPluginOptionsCallback(x) \
20 STDMETHOD(GetProgramPath)(BSTR *value) PURE; 20 x(GetProgramFolderPath(BSTR *value)) \
21 STDMETHOD(GetRegistryCUPath)(BSTR *value) PURE; 21 x(GetProgramPath(BSTR *value)) \
22}; 22 x(GetRegistryCUPath(BSTR *value)) \
23
24PLUGIN_INTERFACE(IPluginOptions, 0x02)
25{
26 STDMETHOD(PluginOptions)(HWND hWnd, IPluginOptionsCallback *callback) PURE;
27 // STDMETHOD(GetFileExtensions)(BSTR *extensions) PURE;
28};
29*/
30 23
24Z7_IFACE_CONSTR_PLUGIN(IPluginOptionsCallback, 0x01)
25
26#define Z7_IFACEM_IPluginOptions(x) \
27 x(PluginOptions(HWND hWnd, IPluginOptionsCallback *callback)) \
28 // x(GetFileExtensions(BSTR *extensions))
29
30Z7_IFACE_CONSTR_PLUGIN(IPluginOptions, 0x02)
31*/
31#endif 32#endif
diff --git a/CPP/7zip/UI/FileManager/PluginLoader.h b/CPP/7zip/UI/FileManager/PluginLoader.h
index fed38d6..d9309f2 100644
--- a/CPP/7zip/UI/FileManager/PluginLoader.h
+++ b/CPP/7zip/UI/FileManager/PluginLoader.h
@@ -1,7 +1,7 @@
1// PluginLoader.h 1// PluginLoader.h
2 2
3#ifndef __PLUGIN_LOADER_H 3#ifndef ZIP7_INC_PLUGIN_LOADER_H
4#define __PLUGIN_LOADER_H 4#define ZIP7_INC_PLUGIN_LOADER_H
5 5
6#include "../../../Windows/DLL.h" 6#include "../../../Windows/DLL.h"
7 7
@@ -12,15 +12,18 @@ class CPluginLibrary: public NWindows::NDLL::CLibrary
12public: 12public:
13 HRESULT CreateManager(REFGUID clsID, IFolderManager **manager) 13 HRESULT CreateManager(REFGUID clsID, IFolderManager **manager)
14 { 14 {
15 Func_CreateObject createObject = (Func_CreateObject)GetProc("CreateObject"); 15 const
16 Func_CreateObject createObject = Z7_GET_PROC_ADDRESS(
17 Func_CreateObject, Get_HMODULE(),
18 "CreateObject");
16 if (!createObject) 19 if (!createObject)
17 return GetLastError(); 20 return GetLastError_noZero_HRESULT();
18 return createObject(&clsID, &IID_IFolderManager, (void **)manager); 21 return createObject(&clsID, &IID_IFolderManager, (void **)manager);
19 } 22 }
20 HRESULT LoadAndCreateManager(CFSTR filePath, REFGUID clsID, IFolderManager **manager) 23 HRESULT LoadAndCreateManager(CFSTR filePath, REFGUID clsID, IFolderManager **manager)
21 { 24 {
22 if (!Load(filePath)) 25 if (!Load(filePath))
23 return GetLastError(); 26 return GetLastError_noZero_HRESULT();
24 return CreateManager(clsID, manager); 27 return CreateManager(clsID, manager);
25 } 28 }
26}; 29};
diff --git a/CPP/7zip/UI/FileManager/ProgramLocation.h b/CPP/7zip/UI/FileManager/ProgramLocation.h
index 6bfb711..0cd9c74 100644
--- a/CPP/7zip/UI/FileManager/ProgramLocation.h
+++ b/CPP/7zip/UI/FileManager/ProgramLocation.h
@@ -1,6 +1,6 @@
1// ProgramLocation.h 1// ProgramLocation.h
2 2
3#ifndef __PROGRAM_LOCATION_H 3#ifndef ZIP7_INC_PROGRAM_LOCATION_H
4#define __PROGRAM_LOCATION_H 4#define ZIP7_INC_PROGRAM_LOCATION_H
5 5
6#endif 6#endif
diff --git a/CPP/7zip/UI/FileManager/ProgressDialog.cpp b/CPP/7zip/UI/FileManager/ProgressDialog.cpp
index b688a90..fc6f559 100644
--- a/CPP/7zip/UI/FileManager/ProgressDialog.cpp
+++ b/CPP/7zip/UI/FileManager/ProgressDialog.cpp
@@ -15,7 +15,7 @@ extern HINSTANCE g_hInstance;
15static const UINT_PTR kTimerID = 3; 15static const UINT_PTR kTimerID = 3;
16static const UINT kTimerElapse = 100; 16static const UINT kTimerElapse = 100;
17 17
18#ifdef LANG 18#ifdef Z7_LANG
19#include "LangUtils.h" 19#include "LangUtils.h"
20#endif 20#endif
21 21
@@ -32,7 +32,7 @@ HRESULT CProgressSync::ProcessStopAndPause()
32 return S_OK; 32 return S_OK;
33} 33}
34 34
35#ifndef _SFX 35#ifndef Z7_SFX
36CProgressDialog::~CProgressDialog() 36CProgressDialog::~CProgressDialog()
37{ 37{
38 AddToTitle(L""); 38 AddToTitle(L"");
@@ -45,15 +45,17 @@ void CProgressDialog::AddToTitle(LPCWSTR s)
45#endif 45#endif
46 46
47 47
48#define UNDEFINED_VAL ((UInt64)(Int64)-1)
49
48bool CProgressDialog::OnInit() 50bool CProgressDialog::OnInit()
49{ 51{
50 _range = (UInt64)(Int64)-1; 52 _range = UNDEFINED_VAL;
51 _prevPercentValue = -1; 53 _prevPercentValue = UNDEFINED_VAL;
52 54
53 _wasCreated = true; 55 _wasCreated = true;
54 _dialogCreatedEvent.Set(); 56 _dialogCreatedEvent.Set();
55 57
56 #ifdef LANG 58 #ifdef Z7_LANG
57 LangSetDlgItems(*this, NULL, 0); 59 LangSetDlgItems(*this, NULL, 0);
58 #endif 60 #endif
59 61
@@ -114,7 +116,7 @@ bool CProgressDialog::OnTimer(WPARAM /* timerID */, LPARAM /* callback */)
114 if (total == 0) 116 if (total == 0)
115 total = 1; 117 total = 1;
116 118
117 int percentValue = (int)(completed * 100 / total); 119 const UInt64 percentValue = completed * 100 / total;
118 if (percentValue != _prevPercentValue) 120 if (percentValue != _prevPercentValue)
119 { 121 {
120 wchar_t s[64]; 122 wchar_t s[64];
@@ -122,7 +124,7 @@ bool CProgressDialog::OnTimer(WPARAM /* timerID */, LPARAM /* callback */)
122 UString title = s; 124 UString title = s;
123 title += "% "; 125 title += "% ";
124 SetText(title + _title); 126 SetText(title + _title);
125 #ifndef _SFX 127 #ifndef Z7_SFX
126 AddToTitle(title + MainAddTitle); 128 AddToTitle(title + MainAddTitle);
127 #endif 129 #endif
128 _prevPercentValue = percentValue; 130 _prevPercentValue = percentValue;
@@ -159,7 +161,7 @@ bool CProgressDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
159 return CModalDialog::OnMessage(message, wParam, lParam); 161 return CModalDialog::OnMessage(message, wParam, lParam);
160} 162}
161 163
162bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 164bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
163{ 165{
164 switch (buttonID) 166 switch (buttonID)
165 { 167 {
diff --git a/CPP/7zip/UI/FileManager/ProgressDialog.h b/CPP/7zip/UI/FileManager/ProgressDialog.h
index 35c182a..1fe9587 100644
--- a/CPP/7zip/UI/FileManager/ProgressDialog.h
+++ b/CPP/7zip/UI/FileManager/ProgressDialog.h
@@ -1,7 +1,7 @@
1// ProgressDialog.h 1// ProgressDialog.h
2 2
3#ifndef __PROGRESS_DIALOG_H 3#ifndef ZIP7_INC_PROGRESS_DIALOG_H
4#define __PROGRESS_DIALOG_H 4#define ZIP7_INC_PROGRESS_DIALOG_H
5 5
6#include "../../../Windows/Synchronization.h" 6#include "../../../Windows/Synchronization.h"
7#include "../../../Windows/Thread.h" 7#include "../../../Windows/Thread.h"
@@ -85,24 +85,27 @@ private:
85 UInt64 _range; 85 UInt64 _range;
86 NWindows::NControl::CProgressBar m_ProgressBar; 86 NWindows::NControl::CProgressBar m_ProgressBar;
87 87
88 int _prevPercentValue; 88 UInt64 _prevPercentValue;
89 89
90 bool _wasCreated; 90 bool _wasCreated;
91 bool _needClose; 91 bool _needClose;
92 bool _inCancelMessageBox; 92 bool _inCancelMessageBox;
93 bool _externalCloseMessageWasReceived; 93 bool _externalCloseMessageWasReceived;
94 94
95 bool OnTimer(WPARAM timerID, LPARAM callback); 95 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
96 virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override;
97 virtual bool OnInit() Z7_override;
98 virtual void OnCancel() Z7_override;
99 virtual void OnOK() Z7_override;
100 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
101
96 void SetRange(UInt64 range); 102 void SetRange(UInt64 range);
97 void SetPos(UInt64 pos); 103 void SetPos(UInt64 pos);
98 virtual bool OnInit(); 104
99 virtual void OnCancel();
100 virtual void OnOK();
101 NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent; 105 NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent;
102 #ifndef _SFX 106 #ifndef Z7_SFX
103 void AddToTitle(LPCWSTR string); 107 void AddToTitle(LPCWSTR string);
104 #endif 108 #endif
105 bool OnButtonClicked(int buttonID, HWND buttonHWND);
106 109
107 void WaitCreating() { _dialogCreatedEvent.Lock(); } 110 void WaitCreating() { _dialogCreatedEvent.Lock(); }
108 void CheckNeedClose(); 111 void CheckNeedClose();
@@ -111,7 +114,7 @@ public:
111 CProgressSync Sync; 114 CProgressSync Sync;
112 int IconID; 115 int IconID;
113 116
114 #ifndef _SFX 117 #ifndef Z7_SFX
115 HWND MainWindow; 118 HWND MainWindow;
116 UString MainTitle; 119 UString MainTitle;
117 UString MainAddTitle; 120 UString MainAddTitle;
@@ -119,8 +122,8 @@ public:
119 #endif 122 #endif
120 123
121 CProgressDialog(): _timer(0) 124 CProgressDialog(): _timer(0)
122 #ifndef _SFX 125 #ifndef Z7_SFX
123 ,MainWindow(0) 126 ,MainWindow(NULL)
124 #endif 127 #endif
125 { 128 {
126 IconID = -1; 129 IconID = -1;
@@ -133,7 +136,7 @@ public:
133 throw 1334987; 136 throw 1334987;
134 } 137 }
135 138
136 INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = 0) 139 INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = NULL)
137 { 140 {
138 _title = title; 141 _title = title;
139 INT_PTR res = CModalDialog::Create(IDD_PROGRESS, wndParent); 142 INT_PTR res = CModalDialog::Create(IDD_PROGRESS, wndParent);
@@ -146,8 +149,6 @@ public:
146 kCloseMessage = WM_APP + 1 149 kCloseMessage = WM_APP + 1
147 }; 150 };
148 151
149 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
150
151 void ProcessWasFinished() 152 void ProcessWasFinished()
152 { 153 {
153 WaitCreating(); 154 WaitCreating();
@@ -155,7 +156,7 @@ public:
155 PostMsg(kCloseMessage); 156 PostMsg(kCloseMessage);
156 else 157 else
157 _needClose = true; 158 _needClose = true;
158 }; 159 }
159}; 160};
160 161
161 162
diff --git a/CPP/7zip/UI/FileManager/ProgressDialog2.cpp b/CPP/7zip/UI/FileManager/ProgressDialog2.cpp
index 54273d0..1521d83 100644
--- a/CPP/7zip/UI/FileManager/ProgressDialog2.cpp
+++ b/CPP/7zip/UI/FileManager/ProgressDialog2.cpp
@@ -2,6 +2,10 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifdef Z7_OLD_WIN_SDK
6#include <ShlGuid.h>
7#endif
8
5#include "../../../Common/IntToString.h" 9#include "../../../Common/IntToString.h"
6#include "../../../Common/StringConvert.h" 10#include "../../../Common/StringConvert.h"
7 11
@@ -43,7 +47,7 @@ static const UINT kCreateDelay =
43 47
44static const DWORD kPauseSleepTime = 100; 48static const DWORD kPauseSleepTime = 100;
45 49
46#ifdef LANG 50#ifdef Z7_LANG
47 51
48static const UInt32 kLangIDs[] = 52static const UInt32 kLangIDs[] =
49{ 53{
@@ -67,19 +71,19 @@ static const UInt32 kLangIDs_Colon[] =
67#endif 71#endif
68 72
69 73
70#define UNDEFINED_VAL ((UInt64)(Int64)-1) 74#define UNDEFINED_VAL ((UInt64)(Int64)-1)
71#define INIT_AS_UNDEFINED(v) v = UNDEFINED_VAL; 75#define INIT_AS_UNDEFINED(v) v = UNDEFINED_VAL;
72#define IS_UNDEFINED_VAL(v) ((v) == UNDEFINED_VAL) 76#define IS_UNDEFINED_VAL(v) ((v) == UNDEFINED_VAL)
73#define IS_DEFINED_VAL(v) ((v) != UNDEFINED_VAL) 77#define IS_DEFINED_VAL(v) ((v) != UNDEFINED_VAL)
74 78
75CProgressSync::CProgressSync(): 79CProgressSync::CProgressSync():
76 _stopped(false), _paused(false), 80 _stopped(false), _paused(false),
77 _bytesProgressMode(true), 81 _bytesProgressMode(true),
82 _isDir(false),
78 _totalBytes(UNDEFINED_VAL), _completedBytes(0), 83 _totalBytes(UNDEFINED_VAL), _completedBytes(0),
79 _totalFiles(UNDEFINED_VAL), _curFiles(0), 84 _totalFiles(UNDEFINED_VAL), _curFiles(0),
80 _inSize(UNDEFINED_VAL), 85 _inSize(UNDEFINED_VAL),
81 _outSize(UNDEFINED_VAL), 86 _outSize(UNDEFINED_VAL)
82 _isDir(false)
83 {} 87 {}
84 88
85#define CHECK_STOP if (_stopped) return E_ABORT; if (!_paused) return S_OK; 89#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
228 AddError_Message(s); 232 AddError_Message(s);
229} 233}
230 234
231void CProgressSync::AddError_Code_Name(DWORD systemError, const wchar_t *name) 235void CProgressSync::AddError_Code_Name(HRESULT systemError, const wchar_t *name)
232{ 236{
233 UString s = NError::MyFormatMessage(systemError); 237 UString s = NError::MyFormatMessage(systemError);
234 if (systemError == 0) 238 if (systemError == 0)
@@ -262,20 +266,20 @@ CProgressDialog::CProgressDialog():
262 throw 1334987; 266 throw 1334987;
263 if (_createDialogEvent.Create() != S_OK) 267 if (_createDialogEvent.Create() != S_OK)
264 throw 1334987; 268 throw 1334987;
265 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 269 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
266 CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (void**)&_taskbarList); 270 CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (void**)&_taskbarList);
267 if (_taskbarList) 271 if (_taskbarList)
268 _taskbarList->HrInit(); 272 _taskbarList->HrInit();
269 #endif 273 // #endif
270} 274}
271 275
272#ifndef _SFX 276#ifndef Z7_SFX
273 277
274CProgressDialog::~CProgressDialog() 278CProgressDialog::~CProgressDialog()
275{ 279{
276 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 280 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
277 SetTaskbarProgressState(TBPF_NOPROGRESS); 281 SetTaskbarProgressState(TBPF_NOPROGRESS);
278 #endif 282 // #endif
279 AddToTitle(L""); 283 AddToTitle(L"");
280} 284}
281void CProgressDialog::AddToTitle(LPCWSTR s) 285void CProgressDialog::AddToTitle(LPCWSTR s)
@@ -292,7 +296,7 @@ void CProgressDialog::AddToTitle(LPCWSTR s)
292 296
293void CProgressDialog::SetTaskbarProgressState() 297void CProgressDialog::SetTaskbarProgressState()
294{ 298{
295 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 299 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
296 if (_taskbarList && _hwndForTaskbar) 300 if (_taskbarList && _hwndForTaskbar)
297 { 301 {
298 TBPFLAG tbpFlags; 302 TBPFLAG tbpFlags;
@@ -302,7 +306,7 @@ void CProgressDialog::SetTaskbarProgressState()
302 tbpFlags = _errorsWereDisplayed ? TBPF_ERROR: TBPF_NORMAL; 306 tbpFlags = _errorsWereDisplayed ? TBPF_ERROR: TBPF_NORMAL;
303 SetTaskbarProgressState(tbpFlags); 307 SetTaskbarProgressState(tbpFlags);
304 } 308 }
305 #endif 309 // #endif
306} 310}
307 311
308static const unsigned kTitleFileNameSizeLimit = 36; 312static const unsigned kTitleFileNameSizeLimit = 36;
@@ -331,23 +335,23 @@ bool CProgressDialog::OnInit()
331 if (!_hwndForTaskbar) 335 if (!_hwndForTaskbar)
332 _hwndForTaskbar = *this; 336 _hwndForTaskbar = *this;
333 337
334 INIT_AS_UNDEFINED(_progressBar_Range); 338 INIT_AS_UNDEFINED(_progressBar_Range)
335 INIT_AS_UNDEFINED(_progressBar_Pos); 339 INIT_AS_UNDEFINED(_progressBar_Pos)
336 340
337 INIT_AS_UNDEFINED(_prevPercentValue); 341 INIT_AS_UNDEFINED(_prevPercentValue)
338 INIT_AS_UNDEFINED(_prevElapsedSec); 342 INIT_AS_UNDEFINED(_prevElapsedSec)
339 INIT_AS_UNDEFINED(_prevRemainingSec); 343 INIT_AS_UNDEFINED(_prevRemainingSec)
340 344
341 INIT_AS_UNDEFINED(_prevSpeed); 345 INIT_AS_UNDEFINED(_prevSpeed)
342 _prevSpeed_MoveBits = 0; 346 _prevSpeed_MoveBits = 0;
343 347
344 _prevTime = ::GetTickCount(); 348 _prevTime = ::GetTickCount();
345 _elapsedTime = 0; 349 _elapsedTime = 0;
346 350
347 INIT_AS_UNDEFINED(_totalBytes_Prev); 351 INIT_AS_UNDEFINED(_totalBytes_Prev)
348 INIT_AS_UNDEFINED(_processed_Prev); 352 INIT_AS_UNDEFINED(_processed_Prev)
349 INIT_AS_UNDEFINED(_packed_Prev); 353 INIT_AS_UNDEFINED(_packed_Prev)
350 INIT_AS_UNDEFINED(_ratio_Prev); 354 INIT_AS_UNDEFINED(_ratio_Prev)
351 355
352 _filesStr_Prev.Empty(); 356 _filesStr_Prev.Empty();
353 _filesTotStr_Prev.Empty(); 357 _filesTotStr_Prev.Empty();
@@ -362,9 +366,9 @@ bool CProgressDialog::OnInit()
362 _wasCreated = true; 366 _wasCreated = true;
363 _dialogCreatedEvent.Set(); 367 _dialogCreatedEvent.Set();
364 368
365 #ifdef LANG 369 #ifdef Z7_LANG
366 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 370 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
367 LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); 371 LangSetDlgItems_Colon(*this, kLangIDs_Colon, Z7_ARRAY_SIZE(kLangIDs_Colon));
368 #endif 372 #endif
369 373
370 CWindow window(GetItem(IDB_PROGRESS_BACKGROUND)); 374 CWindow window(GetItem(IDB_PROGRESS_BACKGROUND));
@@ -453,12 +457,12 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
453 457
454 InvalidateRect(NULL); 458 InvalidateRect(NULL);
455 459
456 int xSizeClient = xSize - mx * 2; 460 const int xSizeClient = xSize - mx * 2;
457 461
458 { 462 {
459 int i; 463 unsigned i;
460 for (i = 800; i > 40; i = i * 9 / 10) 464 for (i = 800; i > 40; i = i * 9 / 10)
461 if (Units_To_Pixels_X(i) <= xSizeClient) 465 if (Units_To_Pixels_X((int)i) <= xSizeClient)
462 break; 466 break;
463 _numReduceSymbols = i / 4; 467 _numReduceSymbols = i / 4;
464 } 468 }
@@ -473,7 +477,7 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
473 int mx2 = mx; 477 int mx2 = mx;
474 for (;; mx2--) 478 for (;; mx2--)
475 { 479 {
476 int bSize2 = bSizeX * 3 + mx2 * 2; 480 const int bSize2 = bSizeX * 3 + mx2 * 2;
477 if (bSize2 <= xSizeClient) 481 if (bSize2 <= xSizeClient)
478 break; 482 break;
479 if (mx2 < 5) 483 if (mx2 < 5)
@@ -488,7 +492,7 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
488 { 492 {
489 RECT r; 493 RECT r;
490 GetClientRectOfItem(IDL_PROGRESS_MESSAGES, r); 494 GetClientRectOfItem(IDL_PROGRESS_MESSAGES, r);
491 int y = r.top; 495 const int y = r.top;
492 int ySize2 = yPos - my - y; 496 int ySize2 = yPos - my - y;
493 const int kMinYSize = _buttonSizeY + _buttonSizeY * 3 / 4; 497 const int kMinYSize = _buttonSizeY + _buttonSizeY * 3 / 4;
494 int xx = xSize - mx * 2; 498 int xx = xSize - mx * 2;
@@ -519,13 +523,13 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
519 labelSize = Units_To_Pixels_X(MY_PROGRESS_LABEL_UNITS_MIN); 523 labelSize = Units_To_Pixels_X(MY_PROGRESS_LABEL_UNITS_MIN);
520 valueSize = Units_To_Pixels_X(MY_PROGRESS_VAL_UNITS); 524 valueSize = Units_To_Pixels_X(MY_PROGRESS_VAL_UNITS);
521 padSize = Units_To_Pixels_X(MY_PROGRESS_PAD_UNITS); 525 padSize = Units_To_Pixels_X(MY_PROGRESS_PAD_UNITS);
522 int requiredSize = (labelSize + valueSize) * 2 + padSize; 526 const int requiredSize = (labelSize + valueSize) * 2 + padSize;
523 527
524 int gSize; 528 int gSize;
525 { 529 {
526 if (requiredSize < xSizeClient) 530 if (requiredSize < xSizeClient)
527 { 531 {
528 int incr = (xSizeClient - requiredSize) / 3; 532 const int incr = (xSizeClient - requiredSize) / 3;
529 labelSize += incr; 533 labelSize += incr;
530 } 534 }
531 else 535 else
@@ -540,7 +544,7 @@ bool CProgressDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
540 labelSize = gSize - valueSize; 544 labelSize = gSize - valueSize;
541 545
542 yPos = my; 546 yPos = my;
543 for (unsigned i = 0; i < ARRAY_SIZE(kIDs); i += 2) 547 for (unsigned i = 0; i < Z7_ARRAY_SIZE(kIDs); i += 2)
544 { 548 {
545 int x = mx; 549 int x = mx;
546 const unsigned kNumColumn1Items = 5 * 2; 550 const unsigned kNumColumn1Items = 5 * 2;
@@ -566,7 +570,7 @@ void CProgressDialog::SetProgressRange(UInt64 range)
566 if (range == _progressBar_Range) 570 if (range == _progressBar_Range)
567 return; 571 return;
568 _progressBar_Range = range; 572 _progressBar_Range = range;
569 INIT_AS_UNDEFINED(_progressBar_Pos); 573 INIT_AS_UNDEFINED(_progressBar_Pos)
570 _progressConv.Init(range); 574 _progressConv.Init(range);
571 m_ProgressBar.SetRange32(0, _progressConv.Count(range)); 575 m_ProgressBar.SetRange32(0, _progressConv.Count(range));
572} 576}
@@ -578,10 +582,10 @@ void CProgressDialog::SetProgressPos(UInt64 pos)
578 pos - _progressBar_Pos >= (_progressBar_Range >> 10)) 582 pos - _progressBar_Pos >= (_progressBar_Range >> 10))
579 { 583 {
580 m_ProgressBar.SetPos(_progressConv.Count(pos)); 584 m_ProgressBar.SetPos(_progressConv.Count(pos));
581 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 585 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
582 if (_taskbarList && _hwndForTaskbar) 586 if (_taskbarList && _hwndForTaskbar)
583 _taskbarList->SetProgressValue(_hwndForTaskbar, pos, _progressBar_Range); 587 _taskbarList->SetProgressValue(_hwndForTaskbar, pos, _progressBar_Range);
584 #endif 588 // #endif
585 _progressBar_Pos = pos; 589 _progressBar_Pos = pos;
586 } 590 }
587} 591}
@@ -603,10 +607,10 @@ void GetTimeString(UInt64 timeValue, wchar_t *s)
603 else 607 else
604 { 608 {
605 UInt32 hours32 = (UInt32)hours; 609 UInt32 hours32 = (UInt32)hours;
606 UINT_TO_STR_2(hours32); 610 UINT_TO_STR_2(hours32)
607 } 611 }
608 *s++ = ':'; UINT_TO_STR_2(minutes); 612 *s++ = ':'; UINT_TO_STR_2(minutes)
609 *s++ = ':'; UINT_TO_STR_2(seconds); 613 *s++ = ':'; UINT_TO_STR_2(seconds)
610 *s = 0; 614 *s = 0;
611} 615}
612 616
@@ -627,7 +631,7 @@ static void ConvertSizeToString(UInt64 v, wchar_t *s)
627 } 631 }
628} 632}
629 633
630void CProgressDialog::ShowSize(int id, UInt64 val, UInt64 &prev) 634void CProgressDialog::ShowSize(unsigned id, UInt64 val, UInt64 &prev)
631{ 635{
632 if (val == prev) 636 if (val == prev)
633 return; 637 return;
@@ -771,7 +775,7 @@ void CProgressDialog::UpdateStatInfo(bool showAll)
771 { 775 {
772 if (IS_DEFINED_VAL(_prevRemainingSec)) 776 if (IS_DEFINED_VAL(_prevRemainingSec))
773 { 777 {
774 INIT_AS_UNDEFINED(_prevRemainingSec); 778 INIT_AS_UNDEFINED(_prevRemainingSec)
775 SetItemText(IDT_PROGRESS_REMAINING_VAL, L""); 779 SetItemText(IDT_PROGRESS_REMAINING_VAL, L"");
776 } 780 }
777 } 781 }
@@ -790,8 +794,9 @@ void CProgressDialog::UpdateStatInfo(bool showAll)
790 } 794 }
791 } 795 }
792 { 796 {
793 UInt64 elapsedTime = (_elapsedTime == 0) ? 1 : _elapsedTime; 797 const UInt64 elapsedTime = (_elapsedTime == 0) ? 1 : _elapsedTime;
794 UInt64 v = (progressCompleted * 1000) / elapsedTime; 798 // 22.02: progressCompleted can be for number of files
799 UInt64 v = (completed * 1000) / elapsedTime;
795 Byte c = 0; 800 Byte c = 0;
796 unsigned moveBits = 0; 801 unsigned moveBits = 0;
797 if (v >= ((UInt64)10000 << 10)) { moveBits = 20; c = 'M'; } 802 if (v >= ((UInt64)10000 << 10)) { moveBits = 20; c = 'M'; }
@@ -957,7 +962,7 @@ INT_PTR CProgressDialog::Create(const UString &title, NWindows::CThread &thread,
957 CWaitCursor waitCursor; 962 CWaitCursor waitCursor;
958 HANDLE h[] = { thread, _createDialogEvent }; 963 HANDLE h[] = { thread, _createDialogEvent };
959 964
960 DWORD res2 = WaitForMultipleObjects(ARRAY_SIZE(h), h, FALSE, kCreateDelay); 965 const DWORD res2 = WaitForMultipleObjects(Z7_ARRAY_SIZE(h), h, FALSE, kCreateDelay);
961 if (res2 == WAIT_OBJECT_0 && !Sync.ThereIsMessage()) 966 if (res2 == WAIT_OBJECT_0 && !Sync.ThereIsMessage())
962 return 0; 967 return 0;
963 } 968 }
@@ -979,9 +984,9 @@ INT_PTR CProgressDialog::Create(const UString &title, NWindows::CThread &thread,
979bool CProgressDialog::OnExternalCloseMessage() 984bool CProgressDialog::OnExternalCloseMessage()
980{ 985{
981 // it doesn't work if there is MessageBox. 986 // it doesn't work if there is MessageBox.
982 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 987 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
983 SetTaskbarProgressState(TBPF_NOPROGRESS); 988 SetTaskbarProgressState(TBPF_NOPROGRESS);
984 #endif 989 // #endif
985 // AddToTitle(L"Finished "); 990 // AddToTitle(L"Finished ");
986 // SetText(L"Finished2 "); 991 // SetText(L"Finished2 ");
987 992
@@ -1088,7 +1093,7 @@ void CProgressDialog::SetTitleText()
1088 } 1093 }
1089 1094
1090 s.Add_Space(); 1095 s.Add_Space();
1091 #ifndef _SFX 1096 #ifndef Z7_SFX
1092 { 1097 {
1093 unsigned len = s.Len(); 1098 unsigned len = s.Len();
1094 s += MainAddTitle; 1099 s += MainAddTitle;
@@ -1150,9 +1155,9 @@ void CProgressDialog::AddMessageDirect(LPCWSTR message, bool needNumber)
1150 if (needNumber) 1155 if (needNumber)
1151 ConvertUInt32ToString(_numMessages + 1, sz); 1156 ConvertUInt32ToString(_numMessages + 1, sz);
1152 const unsigned itemIndex = _messageStrings.Size(); // _messageList.GetItemCount(); 1157 const unsigned itemIndex = _messageStrings.Size(); // _messageList.GetItemCount();
1153 if (_messageList.InsertItem((int)itemIndex, sz) == (int)itemIndex) 1158 if (_messageList.InsertItem(itemIndex, sz) == (int)itemIndex)
1154 { 1159 {
1155 _messageList.SetSubItem((int)itemIndex, 1, message); 1160 _messageList.SetSubItem(itemIndex, 1, message);
1156 _messageStrings.Add(message); 1161 _messageStrings.Add(message);
1157 } 1162 }
1158} 1163}
@@ -1163,12 +1168,12 @@ void CProgressDialog::AddMessage(LPCWSTR message)
1163 bool needNumber = true; 1168 bool needNumber = true;
1164 while (!s.IsEmpty()) 1169 while (!s.IsEmpty())
1165 { 1170 {
1166 int pos = s.Find(L'\n'); 1171 const int pos = s.Find(L'\n');
1167 if (pos < 0) 1172 if (pos < 0)
1168 break; 1173 break;
1169 AddMessageDirect(s.Left(pos), needNumber); 1174 AddMessageDirect(s.Left((unsigned)pos), needNumber);
1170 needNumber = false; 1175 needNumber = false;
1171 s.DeleteFrontal(pos + 1); 1176 s.DeleteFrontal((unsigned)pos + 1);
1172 } 1177 }
1173 AddMessageDirect(s, needNumber); 1178 AddMessageDirect(s, needNumber);
1174 _numMessages++; 1179 _numMessages++;
@@ -1210,7 +1215,7 @@ void CProgressDialog::UpdateMessagesDialog()
1210} 1215}
1211 1216
1212 1217
1213bool CProgressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 1218bool CProgressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
1214{ 1219{
1215 switch (buttonID) 1220 switch (buttonID)
1216 { 1221 {
@@ -1340,7 +1345,7 @@ static void ListView_GetSelected(NControl::CListView &listView, CUIntVector &vec
1340 index = listView.GetNextSelectedItem(index); 1345 index = listView.GetNextSelectedItem(index);
1341 if (index < 0) 1346 if (index < 0)
1342 break; 1347 break;
1343 vector.Add(index); 1348 vector.Add((unsigned)index);
1344 } 1349 }
1345} 1350}
1346 1351
@@ -1352,7 +1357,7 @@ void CProgressDialog::CopyToClipboard()
1352 UString s; 1357 UString s;
1353 unsigned numIndexes = indexes.Size(); 1358 unsigned numIndexes = indexes.Size();
1354 if (numIndexes == 0) 1359 if (numIndexes == 0)
1355 numIndexes = _messageList.GetItemCount(); 1360 numIndexes = (unsigned)_messageList.GetItemCount();
1356 1361
1357 for (unsigned i = 0; i < numIndexes; i++) 1362 for (unsigned i = 0; i < numIndexes; i++)
1358 { 1363 {
@@ -1391,7 +1396,9 @@ static THREAD_FUNC_DECL MyThreadFunction(void *param)
1391HRESULT CProgressThreadVirt::Create(const UString &title, HWND parentWindow) 1396HRESULT CProgressThreadVirt::Create(const UString &title, HWND parentWindow)
1392{ 1397{
1393 NWindows::CThread thread; 1398 NWindows::CThread thread;
1394 RINOK(thread.Create(MyThreadFunction, this)); 1399 const WRes wres = thread.Create(MyThreadFunction, this);
1400 if (wres != 0)
1401 return HRESULT_FROM_WIN32(wres);
1395 CProgressDialog::Create(title, thread, parentWindow); 1402 CProgressDialog::Create(title, thread, parentWindow);
1396 return S_OK; 1403 return S_OK;
1397} 1404}
@@ -1417,7 +1424,7 @@ void CProgressThreadVirt::Process()
1417 catch(int v) 1424 catch(int v)
1418 { 1425 {
1419 m = "Error #"; 1426 m = "Error #";
1420 m.Add_UInt32(v); 1427 m.Add_UInt32((unsigned)v);
1421 } 1428 }
1422 catch(...) { m = "Error"; } 1429 catch(...) { m = "Error"; }
1423 if (Result != E_ABORT) 1430 if (Result != E_ABORT)
diff --git a/CPP/7zip/UI/FileManager/ProgressDialog2.h b/CPP/7zip/UI/FileManager/ProgressDialog2.h
index d8259d6..4ca9be7 100644
--- a/CPP/7zip/UI/FileManager/ProgressDialog2.h
+++ b/CPP/7zip/UI/FileManager/ProgressDialog2.h
@@ -1,7 +1,7 @@
1// ProgressDialog2.h 1// ProgressDialog2.h
2 2
3#ifndef __PROGRESS_DIALOG_2_H 3#ifndef ZIP7_INC_PROGRESS_DIALOG_2_H
4#define __PROGRESS_DIALOG_2_H 4#define ZIP7_INC_PROGRESS_DIALOG_2_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -36,6 +36,7 @@ class CProgressSync
36 36
37public: 37public:
38 bool _bytesProgressMode; 38 bool _bytesProgressMode;
39 bool _isDir;
39 UInt64 _totalBytes; 40 UInt64 _totalBytes;
40 UInt64 _completedBytes; 41 UInt64 _completedBytes;
41 UInt64 _totalFiles; 42 UInt64 _totalFiles;
@@ -46,7 +47,6 @@ public:
46 UString _titleFileName; 47 UString _titleFileName;
47 UString _status; 48 UString _status;
48 UString _filePath; 49 UString _filePath;
49 bool _isDir;
50 50
51 UStringVector Messages; 51 UStringVector Messages;
52 CProgressFinalMessage FinalMessage; 52 CProgressFinalMessage FinalMessage;
@@ -96,7 +96,8 @@ public:
96 96
97 void AddError_Message(const wchar_t *message); 97 void AddError_Message(const wchar_t *message);
98 void AddError_Message_Name(const wchar_t *message, const wchar_t *name); 98 void AddError_Message_Name(const wchar_t *message, const wchar_t *name);
99 void AddError_Code_Name(DWORD systemError, const wchar_t *name); 99 // void AddError_Code_Name(DWORD systemError, const wchar_t *name);
100 void AddError_Code_Name(HRESULT systemError, const wchar_t *name);
100 101
101 bool ThereIsMessage() const { return !Messages.IsEmpty() || FinalMessage.ThereIsMessage(); } 102 bool ThereIsMessage() const { return !Messages.IsEmpty() || FinalMessage.ThereIsMessage(); }
102}; 103};
@@ -151,12 +152,12 @@ class CProgressDialog: public NWindows::NControl::CModalDialog
151 NWindows::NControl::CProgressBar m_ProgressBar; 152 NWindows::NControl::CProgressBar m_ProgressBar;
152 NWindows::NControl::CListView _messageList; 153 NWindows::NControl::CListView _messageList;
153 154
154 int _numMessages; 155 unsigned _numMessages;
155 UStringVector _messageStrings; 156 UStringVector _messageStrings;
156 157
157 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 158 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
158 CMyComPtr<ITaskbarList3> _taskbarList; 159 CMyComPtr<ITaskbarList3> _taskbarList;
159 #endif 160 // #endif
160 HWND _hwndForTaskbar; 161 HWND _hwndForTaskbar;
161 162
162 UInt32 _prevTime; 163 UInt32 _prevTime;
@@ -196,29 +197,29 @@ class CProgressDialog: public NWindows::NControl::CModalDialog
196 bool _externalCloseMessageWasReceived; 197 bool _externalCloseMessageWasReceived;
197 198
198 199
199 #ifdef __ITaskbarList3_INTERFACE_DEFINED__ 200 // #ifdef __ITaskbarList3_INTERFACE_DEFINED__
200 void SetTaskbarProgressState(TBPFLAG tbpFlags) 201 void SetTaskbarProgressState(TBPFLAG tbpFlags)
201 { 202 {
202 if (_taskbarList && _hwndForTaskbar) 203 if (_taskbarList && _hwndForTaskbar)
203 _taskbarList->SetProgressState(_hwndForTaskbar, tbpFlags); 204 _taskbarList->SetProgressState(_hwndForTaskbar, tbpFlags);
204 } 205 }
205 #endif 206 // #endif
206 void SetTaskbarProgressState(); 207 void SetTaskbarProgressState();
207 208
208 void UpdateStatInfo(bool showAll); 209 void UpdateStatInfo(bool showAll);
209 bool OnTimer(WPARAM timerID, LPARAM callback);
210 void SetProgressRange(UInt64 range); 210 void SetProgressRange(UInt64 range);
211 void SetProgressPos(UInt64 pos); 211 void SetProgressPos(UInt64 pos);
212 virtual bool OnInit(); 212 virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override;
213 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 213 virtual bool OnInit() Z7_override;
214 virtual void OnCancel(); 214 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
215 virtual void OnOK(); 215 virtual void OnCancel() Z7_override;
216 virtual bool OnNotify(UINT /* controlID */, LPNMHDR header); 216 virtual void OnOK() Z7_override;
217 virtual bool OnNotify(UINT /* controlID */, LPNMHDR header) Z7_override;
217 void CopyToClipboard(); 218 void CopyToClipboard();
218 219
219 NWindows::NSynchronization::CManualResetEvent _createDialogEvent; 220 NWindows::NSynchronization::CManualResetEvent _createDialogEvent;
220 NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent; 221 NWindows::NSynchronization::CManualResetEvent _dialogCreatedEvent;
221 #ifndef _SFX 222 #ifndef Z7_SFX
222 void AddToTitle(LPCWSTR string); 223 void AddToTitle(LPCWSTR string);
223 #endif 224 #endif
224 225
@@ -226,11 +227,11 @@ class CProgressDialog: public NWindows::NControl::CModalDialog
226 void SetPriorityText(); 227 void SetPriorityText();
227 void OnPauseButton(); 228 void OnPauseButton();
228 void OnPriorityButton(); 229 void OnPriorityButton();
229 bool OnButtonClicked(int buttonID, HWND buttonHWND); 230 bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
230 bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 231 bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
231 232
232 void SetTitleText(); 233 void SetTitleText();
233 void ShowSize(int id, UInt64 val, UInt64 &prev); 234 void ShowSize(unsigned id, UInt64 val, UInt64 &prev);
234 235
235 void UpdateMessagesDialog(); 236 void UpdateMessagesDialog();
236 237
@@ -252,10 +253,10 @@ public:
252 int IconID; 253 int IconID;
253 254
254 HWND MainWindow; 255 HWND MainWindow;
255 #ifndef _SFX 256 #ifndef Z7_SFX
256 UString MainTitle; 257 UString MainTitle;
257 UString MainAddTitle; 258 UString MainAddTitle;
258 ~CProgressDialog(); 259 ~CProgressDialog() Z7_DESTRUCTOR_override;
259 #endif 260 #endif
260 261
261 CProgressDialog(); 262 CProgressDialog();
@@ -265,7 +266,7 @@ public:
265 _dialogCreatedEvent.Lock(); 266 _dialogCreatedEvent.Lock();
266 } 267 }
267 268
268 INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = 0); 269 INT_PTR Create(const UString &title, NWindows::CThread &thread, HWND wndParent = NULL);
269 270
270 271
271 /* how it works: 272 /* how it works:
@@ -306,7 +307,7 @@ public:
306 void Process(); 307 void Process();
307 void AddErrorPath(const FString &path) { ErrorPaths.Add(path); } 308 void AddErrorPath(const FString &path) { ErrorPaths.Add(path); }
308 309
309 HRESULT Create(const UString &title, HWND parentWindow = 0); 310 HRESULT Create(const UString &title, HWND parentWindow = NULL);
310 CProgressThreadVirt(): Result(E_FAIL), ThreadFinishedOK(false) {} 311 CProgressThreadVirt(): Result(E_FAIL), ThreadFinishedOK(false) {}
311 312
312 CProgressMessageBoxPair &GetMessagePair(bool isError) { return isError ? FinalMessage.ErrorMessage : FinalMessage.OkMessage; } 313 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 4f0d6dc..fa6e5c5 100644
--- a/CPP/7zip/UI/FileManager/PropertyName.h
+++ b/CPP/7zip/UI/FileManager/PropertyName.h
@@ -1,7 +1,7 @@
1// PropertyName.h 1// PropertyName.h
2 2
3#ifndef __PROPERTY_NAME_H 3#ifndef ZIP7_INC_PROPERTY_NAME_H
4#define __PROPERTY_NAME_H 4#define ZIP7_INC_PROPERTY_NAME_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/PropertyName.rc b/CPP/7zip/UI/FileManager/PropertyName.rc
index e16c526..618875b 100644
--- a/CPP/7zip/UI/FileManager/PropertyName.rc
+++ b/CPP/7zip/UI/FileManager/PropertyName.rc
@@ -104,4 +104,6 @@ BEGIN
104 IDS_PROP_GROUP_ID "Group ID" 104 IDS_PROP_GROUP_ID "Group ID"
105 IDS_PROP_DEVICE_MAJOR "Device Major" 105 IDS_PROP_DEVICE_MAJOR "Device Major"
106 IDS_PROP_DEVICE_MINOR "Device Minor" 106 IDS_PROP_DEVICE_MINOR "Device Minor"
107 IDS_PROP_DEV_MAJOR "Dev Major"
108 IDS_PROP_DEV_MINOR "Dev Minor"
107END 109END
diff --git a/CPP/7zip/UI/FileManager/PropertyNameRes.h b/CPP/7zip/UI/FileManager/PropertyNameRes.h
index e3d08db..913887e 100644
--- a/CPP/7zip/UI/FileManager/PropertyNameRes.h
+++ b/CPP/7zip/UI/FileManager/PropertyNameRes.h
@@ -100,3 +100,5 @@
100#define IDS_PROP_GROUP_ID 1100 100#define IDS_PROP_GROUP_ID 1100
101#define IDS_PROP_DEVICE_MAJOR 1101 101#define IDS_PROP_DEVICE_MAJOR 1101
102#define IDS_PROP_DEVICE_MINOR 1102 102#define IDS_PROP_DEVICE_MINOR 1102
103#define IDS_PROP_DEV_MAJOR 1103
104#define IDS_PROP_DEV_MINOR 1104
diff --git a/CPP/7zip/UI/FileManager/RegistryAssociations.cpp b/CPP/7zip/UI/FileManager/RegistryAssociations.cpp
index e48dbb4..16e4675 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)
65 UString value; 65 UString value;
66 if (iconKey.QueryValue(NULL, value) == ERROR_SUCCESS) 66 if (iconKey.QueryValue(NULL, value) == ERROR_SUCCESS)
67 { 67 {
68 int pos = value.ReverseFind(L','); 68 const int pos = value.ReverseFind(L',');
69 IconPath = value; 69 IconPath = value;
70 if (pos >= 0) 70 if (pos >= 0)
71 { 71 {
72 const wchar_t *end; 72 const wchar_t *end;
73 Int32 index = ConvertStringToInt32((const wchar_t *)value + pos + 1, &end); 73 const Int32 index = ConvertStringToInt32((const wchar_t *)value + pos + 1, &end);
74 if (*end == 0) 74 if (*end == 0)
75 { 75 {
76 // 9.31: if there is no icon index, we use -1. Is it OK? 76 // 9.31: if there is no icon index, we use -1. Is it OK?
77 if (pos != (int)value.Len() - 1) 77 if (pos != (int)value.Len() - 1)
78 IconIndex = (int)index; 78 IconIndex = (int)index;
79 IconPath.SetFrom(value, pos); 79 IconPath.SetFrom(value, (unsigned)pos);
80 } 80 }
81 } 81 }
82 } 82 }
diff --git a/CPP/7zip/UI/FileManager/RegistryAssociations.h b/CPP/7zip/UI/FileManager/RegistryAssociations.h
index 975c9d5..3d7b63d 100644
--- a/CPP/7zip/UI/FileManager/RegistryAssociations.h
+++ b/CPP/7zip/UI/FileManager/RegistryAssociations.h
@@ -1,7 +1,7 @@
1// RegistryAssociations.h 1// RegistryAssociations.h
2 2
3#ifndef __REGISTRY_ASSOCIATIONS_H 3#ifndef ZIP7_INC_REGISTRY_ASSOCIATIONS_H
4#define __REGISTRY_ASSOCIATIONS_H 4#define ZIP7_INC_REGISTRY_ASSOCIATIONS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
diff --git a/CPP/7zip/UI/FileManager/RegistryPlugins.cpp b/CPP/7zip/UI/FileManager/RegistryPlugins.cpp
index 76a5787..87e5fa1 100644
--- a/CPP/7zip/UI/FileManager/RegistryPlugins.cpp
+++ b/CPP/7zip/UI/FileManager/RegistryPlugins.cpp
@@ -2,138 +2,144 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5/*
5#include "../../../Windows/DLL.h" 6#include "../../../Windows/DLL.h"
6#include "../../../Windows/FileFind.h" 7#include "../../../Windows/FileFind.h"
7#include "../../../Windows/PropVariant.h" 8#include "../../../Windows/PropVariant.h"
8 9
9#include "IFolder.h" 10#include "IFolder.h"
11*/
10#include "RegistryPlugins.h" 12#include "RegistryPlugins.h"
11 13
12using namespace NWindows; 14// using namespace NWindows;
13using namespace NFile; 15// using namespace NFile;
14 16
15/* 17/*
16static LPCTSTR const kLMBasePath = TEXT("Software\\7-Zip\\FM"); 18typedef UINT32 (WINAPI * Func_GetPluginProperty)(PROPID propID, PROPVARIANT *value);
17 19
18static LPCTSTR const kPluginsKeyName = TEXT("Plugins"); 20static bool ReadPluginInfo(CPluginInfo &plugin, bool needCheckDll)
19static LPCTSTR const kPluginsOpenClassIDValue = TEXT("CLSID");
20static LPCTSTR const kPluginsOptionsClassIDValue = TEXT("Options");
21static LPCTSTR const kPluginsTypeValue = TEXT("Type");
22
23static CSysString GetFileFolderPluginsKeyName()
24{
25 return CSysString(kLMBasePath) + CSysString(TEXT('\\')) +
26 CSysString(kPluginsKeyName);
27}
28
29*/
30
31typedef UINT32 (WINAPI * GetPluginPropertyFunc)(PROPID propID, PROPVARIANT *value);
32
33static bool ReadPluginInfo(CPluginInfo &pluginInfo, bool needCheckDll)
34{ 21{
35 if (needCheckDll) 22 if (needCheckDll)
36 { 23 {
37 NDLL::CLibrary lib; 24 NDLL::CLibrary lib;
38 if (!lib.LoadEx(pluginInfo.FilePath, LOAD_LIBRARY_AS_DATAFILE)) 25 if (!lib.LoadEx(plugin.FilePath, LOAD_LIBRARY_AS_DATAFILE))
39 return false; 26 return false;
40 } 27 }
41 NDLL::CLibrary lib; 28 NDLL::CLibrary lib;
42 if (!lib.Load(pluginInfo.FilePath)) 29 if (!lib.Load(plugin.FilePath))
43 return false; 30 return false;
44 GetPluginPropertyFunc getPluginProperty = (GetPluginPropertyFunc)lib.GetProc("GetPluginProperty"); 31 const
45 if (getPluginProperty == NULL) 32 Func_GetPluginProperty
33 f_GetPluginProperty = ZIP7_GET_PROC_ADDRESS(
34 Func_GetPluginProperty, lib.Get_HMODULE(),
35 "GetPluginProperty");
36 if (!f_GetPluginProperty)
46 return false; 37 return false;
47 38
48 NCOM::CPropVariant prop; 39 NCOM::CPropVariant prop;
49 if (getPluginProperty(NPlugin::kName, &prop) != S_OK) 40 if (f_GetPluginProperty(NPlugin::kType, &prop) != S_OK)
41 return false;
42 if (prop.vt == VT_EMPTY)
43 plugin.Type = kPluginTypeFF;
44 else if (prop.vt == VT_UI4)
45 plugin.Type = (EPluginType)prop.ulVal;
46 else
47 return false;
48 prop.Clear();
49
50 if (f_GetPluginProperty(NPlugin::kName, &prop) != S_OK)
50 return false; 51 return false;
51 if (prop.vt != VT_BSTR) 52 if (prop.vt != VT_BSTR)
52 return false; 53 return false;
53 pluginInfo.Name = prop.bstrVal; 54 plugin.Name = prop.bstrVal;
54 prop.Clear(); 55 prop.Clear();
55 56
56 if (getPluginProperty(NPlugin::kClassID, &prop) != S_OK) 57 if (f_GetPluginProperty(NPlugin::kClassID, &prop) != S_OK)
57 return false; 58 return false;
58 if (prop.vt == VT_EMPTY) 59 if (prop.vt == VT_EMPTY)
59 pluginInfo.ClassIDDefined = false; 60 plugin.ClassID_Defined = false;
60 else if (prop.vt != VT_BSTR) 61 else if (prop.vt != VT_BSTR)
61 return false; 62 return false;
62 else 63 else
63 { 64 {
64 pluginInfo.ClassIDDefined = true; 65 plugin.ClassID_Defined = true;
65 pluginInfo.ClassID = *(const GUID *)(const void *)prop.bstrVal; 66 plugin.ClassID = *(const GUID *)(const void *)prop.bstrVal;
66 } 67 }
67 prop.Clear(); 68 prop.Clear();
69 return true;
70*/
68 71
69 if (getPluginProperty(NPlugin::kOptionsClassID, &prop) != S_OK) 72/*
73{
74 if (f_GetPluginProperty(NPlugin::kOptionsClassID, &prop) != S_OK)
70 return false; 75 return false;
71 if (prop.vt == VT_EMPTY) 76 if (prop.vt == VT_EMPTY)
72 pluginInfo.OptionsClassIDDefined = false; 77 plugin.OptionsClassID_Defined = false;
73 else if (prop.vt != VT_BSTR) 78 else if (prop.vt != VT_BSTR)
74 return false; 79 return false;
75 else 80 else
76 { 81 {
77 pluginInfo.OptionsClassIDDefined = true; 82 plugin.OptionsClassID_Defined = true;
78 pluginInfo.OptionsClassID = *(const GUID *)(const void *)prop.bstrVal; 83 plugin.OptionsClassID = *(const GUID *)(const void *)prop.bstrVal;
79 } 84 }
80 prop.Clear();
81
82 if (getPluginProperty(NPlugin::kType, &prop) != S_OK)
83 return false;
84 if (prop.vt == VT_EMPTY)
85 pluginInfo.Type = kPluginTypeFF;
86 else if (prop.vt == VT_UI4)
87 pluginInfo.Type = (EPluginType)prop.ulVal;
88 else
89 return false;
90 return true;
91} 85}
86*/
92 87
93void ReadPluginInfoList(CObjectVector<CPluginInfo> &plugins) 88 /*
94{ 89 {
95 plugins.Clear(); 90 // very old 7-zip used agent plugin in "7-zip.dll"
91 // but then agent code was moved to 7zfm.
92 // so now we don't need to load "7-zip.dll" here
93 CPluginInfo plugin;
94 plugin.FilePath = baseFolderPrefix + FTEXT("7-zip.dll");
95 if (::ReadPluginInfo(plugin, false))
96 if (plugin.Type == kPluginTypeFF)
97 plugins.Add(plugin);
98 }
99 */
100 /*
101 FString folderPath = NDLL::GetModuleDirPrefix();
102 folderPath += "Plugins" STRING_PATH_SEPARATOR;
103 NFind::CEnumerator enumerator;
104 enumerator.SetDirPrefix(folderPath);
105 NFind::CFileInfo fi;
106 while (enumerator.Next(fi))
107 {
108 if (fi.IsDir())
109 continue;
110 CPluginInfo plugin;
111 plugin.FilePath = folderPath + fi.Name;
112 if (::ReadPluginInfo(plugin, true))
113 if (plugin.Type == kPluginTypeFF)
114 plugins.Add(plugin);
115 }
116 */
96 117
97 FString baseFolderPrefix = NDLL::GetModuleDirPrefix(); 118 /*
98 {
99 CPluginInfo pluginInfo;
100 pluginInfo.FilePath = baseFolderPrefix + FTEXT("7-zip.dll");
101 if (::ReadPluginInfo(pluginInfo, false))
102 plugins.Add(pluginInfo);
103 }
104 FString folderPath = baseFolderPrefix;
105 folderPath += "Plugins" STRING_PATH_SEPARATOR;
106 NFind::CEnumerator enumerator;
107 enumerator.SetDirPrefix(folderPath);
108 NFind::CFileInfo fileInfo;
109 while (enumerator.Next(fileInfo))
110 {
111 if (fileInfo.IsDir())
112 continue;
113 CPluginInfo pluginInfo;
114 pluginInfo.FilePath = folderPath + fileInfo.Name;
115 if (::ReadPluginInfo(pluginInfo, true))
116 plugins.Add(pluginInfo);
117 }
118}
119
120void ReadFileFolderPluginInfoList(CObjectVector<CPluginInfo> &plugins)
121{
122 ReadPluginInfoList(plugins); 119 ReadPluginInfoList(plugins);
123 for (unsigned i = 0; i < plugins.Size();) 120 for (unsigned i = 0; i < plugins.Size();)
124 if (plugins[i].Type != kPluginTypeFF) 121 if (plugins[i].Type != kPluginTypeFF)
125 plugins.Delete(i); 122 plugins.Delete(i);
126 else 123 else
127 i++; 124 i++;
125 */
126
127/*
128void ReadFileFolderPluginInfoList(CObjectVector<CPluginInfo> &plugins)
129{
130 plugins.Clear();
131 {
132 }
133
128 { 134 {
129 CPluginInfo p; 135 CPluginInfo &plugin = plugins.AddNew();
130 // p.FilePath.Empty(); 136 // p.FilePath.Empty();
131 p.Type = kPluginTypeFF; 137 plugin.Type = kPluginTypeFF;
132 p.Name = "7-Zip"; 138 plugin.Name = "7-Zip";
133 // p.ClassID = CLSID_CAgentArchiveHandler; 139 // plugin.ClassID = CLSID_CAgentArchiveHandler;
134 p.ClassIDDefined = true; 140 // plugin.ClassID_Defined = true;
135 // p.OptionsClassID; 141 // plugin.ClassID_Defined = false;
136 p.OptionsClassIDDefined = false; 142 // plugin.OptionsClassID_Defined = false;
137 plugins.Add(p);
138 } 143 }
139} 144}
145*/
diff --git a/CPP/7zip/UI/FileManager/RegistryPlugins.h b/CPP/7zip/UI/FileManager/RegistryPlugins.h
index dfa6de5..1cb765a 100644
--- a/CPP/7zip/UI/FileManager/RegistryPlugins.h
+++ b/CPP/7zip/UI/FileManager/RegistryPlugins.h
@@ -1,10 +1,11 @@
1// RegistryPlugins.h 1// RegistryPlugins.h
2 2
3#ifndef __REGISTRY_PLUGINS_H 3#ifndef ZIP7_INC_REGISTRY_PLUGINS_H
4#define __REGISTRY_PLUGINS_H 4#define ZIP7_INC_REGISTRY_PLUGINS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
8/*
8enum EPluginType 9enum EPluginType
9{ 10{
10 kPluginTypeFF = 0 11 kPluginTypeFF = 0
@@ -12,21 +13,17 @@ enum EPluginType
12 13
13struct CPluginInfo 14struct CPluginInfo
14{ 15{
15 FString FilePath;
16 EPluginType Type; 16 EPluginType Type;
17 UString Name; 17 // bool ClassID_Defined;
18 CLSID ClassID; 18 // bool OptionsClassID_Defined;
19 CLSID OptionsClassID; 19 // FString FilePath;
20 bool ClassIDDefined; 20 // UString Name;
21 bool OptionsClassIDDefined; 21 // CLSID ClassID;
22 22 // CLSID OptionsClassID;
23 // CSysString Extension;
24 // CSysString AddExtension;
25 // bool UpdateEnabled;
26 // bool KeepName;
27}; 23};
28 24
29void ReadPluginInfoList(CObjectVector<CPluginInfo> &plugins); 25// void ReadPluginInfoList(CObjectVector<CPluginInfo> &plugins);
30void ReadFileFolderPluginInfoList(CObjectVector<CPluginInfo> &plugins); 26// void ReadFileFolderPluginInfoList(CObjectVector<CPluginInfo> &plugins);
27*/
31 28
32#endif 29#endif
diff --git a/CPP/7zip/UI/FileManager/RegistryUtils.cpp b/CPP/7zip/UI/FileManager/RegistryUtils.cpp
index a2fc201..7e61998 100644
--- a/CPP/7zip/UI/FileManager/RegistryUtils.cpp
+++ b/CPP/7zip/UI/FileManager/RegistryUtils.cpp
@@ -137,6 +137,11 @@ void CFmSettings::Load()
137{ 137{
138 ShowDots = false; 138 ShowDots = false;
139 ShowRealFileIcons = false; 139 ShowRealFileIcons = false;
140 /* if (FullRow == false), we can use mouse click on another columns
141 to select group of files. We need to implement additional
142 way to select files in any column as in Explorer.
143 Then we can enable (FullRow == true) default mode. */
144 // FullRow = true;
140 FullRow = false; 145 FullRow = false;
141 ShowGrid = false; 146 ShowGrid = false;
142 SingleClick = false; 147 SingleClick = false;
diff --git a/CPP/7zip/UI/FileManager/RegistryUtils.h b/CPP/7zip/UI/FileManager/RegistryUtils.h
index b85d670..8b4cdf0 100644
--- a/CPP/7zip/UI/FileManager/RegistryUtils.h
+++ b/CPP/7zip/UI/FileManager/RegistryUtils.h
@@ -1,7 +1,7 @@
1// RegistryUtils.h 1// RegistryUtils.h
2 2
3#ifndef __REGISTRY_UTILS_H 3#ifndef ZIP7_INC_REGISTRY_UTILS_H
4#define __REGISTRY_UTILS_H 4#define ZIP7_INC_REGISTRY_UTILS_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
diff --git a/CPP/7zip/UI/FileManager/RootFolder.cpp b/CPP/7zip/UI/FileManager/RootFolder.cpp
index 84844c7..34dd638 100644
--- a/CPP/7zip/UI/FileManager/RootFolder.cpp
+++ b/CPP/7zip/UI/FileManager/RootFolder.cpp
@@ -4,7 +4,11 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#if defined(__MINGW32__) || defined(__MINGW64__)
8#include <shlobj.h>
9#else
7#include <ShlObj.h> 10#include <ShlObj.h>
11#endif
8 12
9#include "../../../Common/StringConvert.h" 13#include "../../../Common/StringConvert.h"
10 14
@@ -96,19 +100,19 @@ void CRootFolder::Init()
96 #endif 100 #endif
97} 101}
98 102
99STDMETHODIMP CRootFolder::LoadItems() 103Z7_COM7F_IMF(CRootFolder::LoadItems())
100{ 104{
101 Init(); 105 Init();
102 return S_OK; 106 return S_OK;
103} 107}
104 108
105STDMETHODIMP CRootFolder::GetNumberOfItems(UInt32 *numItems) 109Z7_COM7F_IMF(CRootFolder::GetNumberOfItems(UInt32 *numItems))
106{ 110{
107 *numItems = kNumRootFolderItems; 111 *numItems = kNumRootFolderItems;
108 return S_OK; 112 return S_OK;
109} 113}
110 114
111STDMETHODIMP CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value) 115Z7_COM7F_IMF(CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIANT *value))
112{ 116{
113 NCOM::CPropVariant prop; 117 NCOM::CPropVariant prop;
114 switch (propID) 118 switch (propID)
@@ -120,28 +124,31 @@ STDMETHODIMP CRootFolder::GetProperty(UInt32 itemIndex, PROPID propID, PROPVARIA
120 return S_OK; 124 return S_OK;
121} 125}
122 126
123typedef BOOL (WINAPI *SHGetSpecialFolderPathWp)(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); 127typedef BOOL (WINAPI *Func_SHGetSpecialFolderPathW)(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate);
124typedef BOOL (WINAPI *SHGetSpecialFolderPathAp)(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); 128typedef BOOL (WINAPI *Func_SHGetSpecialFolderPathA)(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate);
125 129
126static UString GetMyDocsPath() 130static UString GetMyDocsPath()
127{ 131{
128 UString us; 132 UString us;
129 WCHAR s[MAX_PATH + 1]; 133 WCHAR s[MAX_PATH + 1];
130 SHGetSpecialFolderPathWp getW = (SHGetSpecialFolderPathWp) 134#ifdef UNDER_CE
131 #ifdef UNDER_CE 135 #define shell_name TEXT("coredll.dll")
132 My_GetProcAddress(GetModuleHandle(TEXT("coredll.dll")), "SHGetSpecialFolderPath"); 136#else
133 #else 137 #define shell_name TEXT("shell32.dll")
134 My_GetProcAddress(GetModuleHandle(TEXT("shell32.dll")), "SHGetSpecialFolderPathW"); 138#endif
135 #endif 139 Func_SHGetSpecialFolderPathW getW = Z7_GET_PROC_ADDRESS(
136 if (getW && getW(0, s, CSIDL_PERSONAL, FALSE)) 140 Func_SHGetSpecialFolderPathW, GetModuleHandle(shell_name),
141 "SHGetSpecialFolderPathW");
142 if (getW && getW(NULL, s, CSIDL_PERSONAL, FALSE))
137 us = s; 143 us = s;
138 #ifndef _UNICODE 144 #ifndef _UNICODE
139 else 145 else
140 { 146 {
141 SHGetSpecialFolderPathAp getA = (SHGetSpecialFolderPathAp) 147 Func_SHGetSpecialFolderPathA getA = Z7_GET_PROC_ADDRESS(
142 (void *)::GetProcAddress(::GetModuleHandleA("shell32.dll"), "SHGetSpecialFolderPathA"); 148 Func_SHGetSpecialFolderPathA, ::GetModuleHandleA("shell32.dll"),
149 "SHGetSpecialFolderPathA");
143 CHAR s2[MAX_PATH + 1]; 150 CHAR s2[MAX_PATH + 1];
144 if (getA && getA(0, s2, CSIDL_PERSONAL, FALSE)) 151 if (getA && getA(NULL, s2, CSIDL_PERSONAL, FALSE))
145 us = GetUnicodeString(s2); 152 us = GetUnicodeString(s2);
146 } 153 }
147 #endif 154 #endif
@@ -149,7 +156,7 @@ static UString GetMyDocsPath()
149 return us; 156 return us;
150} 157}
151 158
152STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder) 159Z7_COM7F_IMF(CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolder))
153{ 160{
154 *resultFolder = NULL; 161 *resultFolder = NULL;
155 CMyComPtr<IFolderFolder> subFolder; 162 CMyComPtr<IFolderFolder> subFolder;
@@ -165,7 +172,7 @@ STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolde
165 { 172 {
166 CNetFolder *netFolderSpec = new CNetFolder; 173 CNetFolder *netFolderSpec = new CNetFolder;
167 subFolder = netFolderSpec; 174 subFolder = netFolderSpec;
168 netFolderSpec->Init(0, 0, _names[ROOT_INDEX_NETWORK] + WCHAR_PATH_SEPARATOR); 175 netFolderSpec->Init(NULL, NULL, _names[ROOT_INDEX_NETWORK] + WCHAR_PATH_SEPARATOR);
169 } 176 }
170 else if (index == ROOT_INDEX_DOCUMENTS) 177 else if (index == ROOT_INDEX_DOCUMENTS)
171 { 178 {
@@ -174,7 +181,7 @@ STDMETHODIMP CRootFolder::BindToFolder(UInt32 index, IFolderFolder **resultFolde
174 { 181 {
175 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder; 182 NFsFolder::CFSFolder *fsFolderSpec = new NFsFolder::CFSFolder;
176 subFolder = fsFolderSpec; 183 subFolder = fsFolderSpec;
177 RINOK(fsFolderSpec->Init(us2fs(s))); 184 RINOK(fsFolderSpec->Init(us2fs(s)))
178 } 185 }
179 } 186 }
180 #else 187 #else
@@ -202,9 +209,9 @@ static bool AreEqualNames(const UString &path, const wchar_t *name)
202 return path.IsPrefixedBy(name); 209 return path.IsPrefixedBy(name);
203} 210}
204 211
205STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder) 212Z7_COM7F_IMF(CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resultFolder))
206{ 213{
207 *resultFolder = 0; 214 *resultFolder = NULL;
208 UString name2 = name; 215 UString name2 = name;
209 name2.Trim(); 216 name2.Trim();
210 217
@@ -259,7 +266,8 @@ STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resu
259 subFolder = folderSpec; 266 subFolder = folderSpec;
260 folderSpec->Init(false, true); 267 folderSpec->Init(false, true);
261 } 268 }
262 else if (name2.Back() == ':') 269 else if (name2.Back() == ':'
270 && (name2.Len() != 2 || !NFile::NName::IsDrivePath2(name2)))
263 { 271 {
264 NAltStreamsFolder::CAltStreamsFolder *folderSpec = new NAltStreamsFolder::CAltStreamsFolder; 272 NAltStreamsFolder::CAltStreamsFolder *folderSpec = new NAltStreamsFolder::CAltStreamsFolder;
265 subFolder = folderSpec; 273 subFolder = folderSpec;
@@ -291,15 +299,15 @@ STDMETHODIMP CRootFolder::BindToFolder(const wchar_t *name, IFolderFolder **resu
291 return S_OK; 299 return S_OK;
292} 300}
293 301
294STDMETHODIMP CRootFolder::BindToParentFolder(IFolderFolder **resultFolder) 302Z7_COM7F_IMF(CRootFolder::BindToParentFolder(IFolderFolder **resultFolder))
295{ 303{
296 *resultFolder = 0; 304 *resultFolder = NULL;
297 return S_OK; 305 return S_OK;
298} 306}
299 307
300IMP_IFolderFolder_Props(CRootFolder) 308IMP_IFolderFolder_Props(CRootFolder)
301 309
302STDMETHODIMP CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value) 310Z7_COM7F_IMF(CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value))
303{ 311{
304 NCOM::CPropVariant prop; 312 NCOM::CPropVariant prop;
305 switch (propID) 313 switch (propID)
@@ -311,7 +319,7 @@ STDMETHODIMP CRootFolder::GetFolderProperty(PROPID propID, PROPVARIANT *value)
311 return S_OK; 319 return S_OK;
312} 320}
313 321
314STDMETHODIMP CRootFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex) 322Z7_COM7F_IMF(CRootFolder::GetSystemIconIndex(UInt32 index, Int32 *iconIndex))
315{ 323{
316 *iconIndex = _iconIndices[index]; 324 *iconIndex = _iconIndices[index];
317 return S_OK; 325 return S_OK;
diff --git a/CPP/7zip/UI/FileManager/RootFolder.h b/CPP/7zip/UI/FileManager/RootFolder.h
index e253783..3f0a31b 100644
--- a/CPP/7zip/UI/FileManager/RootFolder.h
+++ b/CPP/7zip/UI/FileManager/RootFolder.h
@@ -1,26 +1,23 @@
1// RootFolder.h 1// RootFolder.h
2 2
3#ifndef __ROOT_FOLDER_H 3#ifndef ZIP7_INC_ROOT_FOLDER_H
4#define __ROOT_FOLDER_H 4#define ZIP7_INC_ROOT_FOLDER_H
5 5
6#include "../../../Common/MyCom.h"
6#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
7 8
8#include "IFolder.h" 9#include "IFolder.h"
9 10
10const unsigned kNumRootFolderItems_Max = 4; 11const unsigned kNumRootFolderItems_Max = 4;
11 12
12class CRootFolder: 13Z7_CLASS_IMP_NOQIB_2(
13 public IFolderFolder, 14 CRootFolder
14 public IFolderGetSystemIconIndex, 15 , IFolderFolder
15 public CMyUnknownImp 16 , IFolderGetSystemIconIndex
16{ 17)
17 UString _names[kNumRootFolderItems_Max]; 18 UString _names[kNumRootFolderItems_Max];
18 int _iconIndices[kNumRootFolderItems_Max]; 19 int _iconIndices[kNumRootFolderItems_Max];
19
20public: 20public:
21 MY_UNKNOWN_IMP1(IFolderGetSystemIconIndex)
22 INTERFACE_FolderFolder(;)
23 STDMETHOD(GetSystemIconIndex)(UInt32 index, Int32 *iconIndex);
24 void Init(); 21 void Init();
25}; 22};
26 23
diff --git a/CPP/7zip/UI/FileManager/SettingsPage.cpp b/CPP/7zip/UI/FileManager/SettingsPage.cpp
index 2868721..784b8c7 100644
--- a/CPP/7zip/UI/FileManager/SettingsPage.cpp
+++ b/CPP/7zip/UI/FileManager/SettingsPage.cpp
@@ -20,6 +20,7 @@
20 20
21using namespace NWindows; 21using namespace NWindows;
22 22
23#ifdef Z7_LANG
23static const UInt32 kLangIDs[] = 24static const UInt32 kLangIDs[] =
24{ 25{
25 IDX_SETTINGS_SHOW_DOTS, 26 IDX_SETTINGS_SHOW_DOTS,
@@ -32,6 +33,7 @@ static const UInt32 kLangIDs[] =
32 IDX_SETTINGS_LARGE_PAGES 33 IDX_SETTINGS_LARGE_PAGES
33 // , IDT_COMPRESS_MEMORY 34 // , IDT_COMPRESS_MEMORY
34}; 35};
36#endif
35 37
36#define kSettingsTopic "FM/options.htm#settings" 38#define kSettingsTopic "FM/options.htm#settings"
37 39
@@ -112,7 +114,9 @@ bool CSettingsPage::OnInit()
112 _memCombo.Attach(GetItem(IDC_SETTINGS_MEM)); 114 _memCombo.Attach(GetItem(IDC_SETTINGS_MEM));
113 */ 115 */
114 116
115 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 117#ifdef Z7_LANG
118 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
119#endif
116 120
117 CFmSettings st; 121 CFmSettings st;
118 st.Load(); 122 st.Load();
@@ -225,7 +229,7 @@ LONG CSettingsPage::OnApply()
225 { 229 {
226 if (IsLargePageSupported()) 230 if (IsLargePageSupported())
227 { 231 {
228 bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); 232 const bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES);
229 NSecurity::EnablePrivilege_LockMemory(enable); 233 NSecurity::EnablePrivilege_LockMemory(enable);
230 SaveLockMemoryEnable(enable); 234 SaveLockMemoryEnable(enable);
231 } 235 }
@@ -301,7 +305,7 @@ void CSettingsPage::OnNotifyHelp()
301} 305}
302 306
303/* 307/*
304bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param) 308bool CSettingsPage::OnCommand(unsigned code, unsigned itemID, LPARAM param)
305{ 309{
306 if (code == CBN_SELCHANGE) 310 if (code == CBN_SELCHANGE)
307 { 311 {
@@ -319,7 +323,7 @@ bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param)
319} 323}
320*/ 324*/
321 325
322bool CSettingsPage::OnButtonClicked(int buttonID, HWND buttonHWND) 326bool CSettingsPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
323{ 327{
324 switch (buttonID) 328 switch (buttonID)
325 { 329 {
diff --git a/CPP/7zip/UI/FileManager/SettingsPage.h b/CPP/7zip/UI/FileManager/SettingsPage.h
index f3f57a4..91b9828 100644
--- a/CPP/7zip/UI/FileManager/SettingsPage.h
+++ b/CPP/7zip/UI/FileManager/SettingsPage.h
@@ -1,7 +1,7 @@
1// SettingsPage.h 1// SettingsPage.h
2 2
3#ifndef __SETTINGS_PAGE_H 3#ifndef ZIP7_INC_SETTINGS_PAGE_H
4#define __SETTINGS_PAGE_H 4#define ZIP7_INC_SETTINGS_PAGE_H
5 5
6#include "../../../Windows/Control/PropertyPage.h" 6#include "../../../Windows/Control/PropertyPage.h"
7#include "../../../Windows/Control/ComboBox.h" 7#include "../../../Windows/Control/ComboBox.h"
@@ -22,11 +22,11 @@ class CSettingsPage: public NWindows::NControl::CPropertyPage
22 */ 22 */
23 23
24 // void EnableSubItems(); 24 // void EnableSubItems();
25 // bool OnCommand(int code, int itemID, LPARAM param); 25 // bool OnCommand(unsigned code, unsigned itemID, LPARAM param) Z7_override;
26 bool OnButtonClicked(int buttonID, HWND buttonHWND); 26 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
27 virtual bool OnInit(); 27 virtual bool OnInit() Z7_override;
28 virtual void OnNotifyHelp(); 28 virtual void OnNotifyHelp() Z7_override;
29 virtual LONG OnApply(); 29 virtual LONG OnApply() Z7_override;
30public: 30public:
31}; 31};
32 32
diff --git a/CPP/7zip/UI/FileManager/SplitDialog.cpp b/CPP/7zip/UI/FileManager/SplitDialog.cpp
index 0c9fdd1..21d812c 100644
--- a/CPP/7zip/UI/FileManager/SplitDialog.cpp
+++ b/CPP/7zip/UI/FileManager/SplitDialog.cpp
@@ -4,9 +4,7 @@
4 4
5#include "../../../Windows/FileName.h" 5#include "../../../Windows/FileName.h"
6 6
7#ifdef LANG
8#include "LangUtils.h" 7#include "LangUtils.h"
9#endif
10 8
11#include "BrowseDialog.h" 9#include "BrowseDialog.h"
12#include "CopyDialogRes.h" 10#include "CopyDialogRes.h"
@@ -16,7 +14,7 @@
16 14
17using namespace NWindows; 15using namespace NWindows;
18 16
19#ifdef LANG 17#ifdef Z7_LANG
20static const UInt32 kLangIDs[] = 18static const UInt32 kLangIDs[] =
21{ 19{
22 IDT_SPLIT_PATH, 20 IDT_SPLIT_PATH,
@@ -27,9 +25,9 @@ static const UInt32 kLangIDs[] =
27 25
28bool CSplitDialog::OnInit() 26bool CSplitDialog::OnInit()
29{ 27{
30 #ifdef LANG 28 #ifdef Z7_LANG
31 LangSetWindowText(*this, IDD_SPLIT); 29 LangSetWindowText(*this, IDD_SPLIT);
32 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 30 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
33 #endif 31 #endif
34 _pathCombo.Attach(GetItem(IDC_SPLIT_PATH)); 32 _pathCombo.Attach(GetItem(IDC_SPLIT_PATH));
35 _volumeCombo.Attach(GetItem(IDC_SPLIT_VOLUME)); 33 _volumeCombo.Attach(GetItem(IDC_SPLIT_VOLUME));
@@ -75,7 +73,7 @@ bool CSplitDialog::OnSize(WPARAM /* wParam */, int xSize, int ySize)
75 return false; 73 return false;
76} 74}
77 75
78bool CSplitDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 76bool CSplitDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
79{ 77{
80 switch (buttonID) 78 switch (buttonID)
81 { 79 {
@@ -91,7 +89,7 @@ void CSplitDialog::OnButtonSetPath()
91 UString currentPath; 89 UString currentPath;
92 _pathCombo.GetText(currentPath); 90 _pathCombo.GetText(currentPath);
93 // UString title = "Specify a location for output folder"; 91 // UString title = "Specify a location for output folder";
94 UString title = LangString(IDS_SET_FOLDER); 92 const UString title = LangString(IDS_SET_FOLDER);
95 93
96 UString resultPath; 94 UString resultPath;
97 if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) 95 if (!MyBrowseForFolder(*this, title, currentPath, resultPath))
diff --git a/CPP/7zip/UI/FileManager/SplitDialog.h b/CPP/7zip/UI/FileManager/SplitDialog.h
index 00aae65..f897136 100644
--- a/CPP/7zip/UI/FileManager/SplitDialog.h
+++ b/CPP/7zip/UI/FileManager/SplitDialog.h
@@ -1,7 +1,7 @@
1// SplitDialog.h 1// SplitDialog.h
2 2
3#ifndef __SPLIT_DIALOG_H 3#ifndef ZIP7_INC_SPLIT_DIALOG_H
4#define __SPLIT_DIALOG_H 4#define ZIP7_INC_SPLIT_DIALOG_H
5 5
6#include "../../../Windows/Control/Dialog.h" 6#include "../../../Windows/Control/Dialog.h"
7#include "../../../Windows/Control/ComboBox.h" 7#include "../../../Windows/Control/ComboBox.h"
@@ -12,16 +12,16 @@ class CSplitDialog: public NWindows::NControl::CModalDialog
12{ 12{
13 NWindows::NControl::CComboBox _pathCombo; 13 NWindows::NControl::CComboBox _pathCombo;
14 NWindows::NControl::CComboBox _volumeCombo; 14 NWindows::NControl::CComboBox _volumeCombo;
15 virtual void OnOK(); 15 virtual void OnOK() Z7_override;
16 virtual bool OnInit(); 16 virtual bool OnInit() Z7_override;
17 virtual bool OnSize(WPARAM wParam, int xSize, int ySize); 17 virtual bool OnSize(WPARAM wParam, int xSize, int ySize) Z7_override;
18 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 18 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
19 void OnButtonSetPath(); 19 void OnButtonSetPath();
20public: 20public:
21 UString FilePath; 21 UString FilePath;
22 UString Path; 22 UString Path;
23 CRecordVector<UInt64> VolumeSizes; 23 CRecordVector<UInt64> VolumeSizes;
24 INT_PTR Create(HWND parentWindow = 0) 24 INT_PTR Create(HWND parentWindow = NULL)
25 { return CModalDialog::Create(IDD_SPLIT, parentWindow); } 25 { return CModalDialog::Create(IDD_SPLIT, parentWindow); }
26}; 26};
27 27
diff --git a/CPP/7zip/UI/FileManager/SplitUtils.cpp b/CPP/7zip/UI/FileManager/SplitUtils.cpp
index 4b6235b..1982afb 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[] =
74 74
75void AddVolumeItems(NWindows::NControl::CComboBox &combo) 75void AddVolumeItems(NWindows::NControl::CComboBox &combo)
76{ 76{
77 for (unsigned i = 0; i < ARRAY_SIZE(k_Sizes); i++) 77 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_Sizes); i++)
78 combo.AddString(CSysString(k_Sizes[i])); 78 combo.AddString(CSysString(k_Sizes[i]));
79} 79}
80 80
diff --git a/CPP/7zip/UI/FileManager/SplitUtils.h b/CPP/7zip/UI/FileManager/SplitUtils.h
index 641dfe6..d1d44e4 100644
--- a/CPP/7zip/UI/FileManager/SplitUtils.h
+++ b/CPP/7zip/UI/FileManager/SplitUtils.h
@@ -1,7 +1,7 @@
1// SplitUtils.h 1// SplitUtils.h
2 2
3#ifndef __SPLIT_UTILS_H 3#ifndef ZIP7_INC_SPLIT_UTILS_H
4#define __SPLIT_UTILS_H 4#define ZIP7_INC_SPLIT_UTILS_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
diff --git a/CPP/7zip/UI/FileManager/StdAfx.h b/CPP/7zip/UI/FileManager/StdAfx.h
index 0e6d446..789cc6e 100644
--- a/CPP/7zip/UI/FileManager/StdAfx.h
+++ b/CPP/7zip/UI/FileManager/StdAfx.h
@@ -1,21 +1,83 @@
1// stdafx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6/* we used 0x0400 for Windows NT supporting (MENUITEMINFOW) 6#if defined(_MSC_VER) && _MSC_VER >= 1800
7 But now menu problem is fixed. So it's OK to use 0x0500 (Windows 2000) */ 7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
9
10#include "../../../../C/Compiler.h"
8 11
12Z7_DIAGNOSCTIC_IGNORE_BEGIN_RESERVED_MACRO_IDENTIFIER
13#ifndef _WIN32_WINNT
9// #define _WIN32_WINNT 0x0400 14// #define _WIN32_WINNT 0x0400
10#define _WIN32_WINNT 0x0500 15#define _WIN32_WINNT 0x0500
16// #define _WIN32_WINNT 0x0600
17// #define _WIN32_WINNT 0x0A00
18#endif
19#ifndef WINVER
11#define WINVER _WIN32_WINNT 20#define WINVER _WIN32_WINNT
21#endif
22// #define _WIN32_IE 0x400 // for debug
23Z7_DIAGNOSCTIC_IGNORE_END_RESERVED_MACRO_IDENTIFIER
12 24
13#include "../../../Common/Common.h" 25#include "../../../Common/Common.h"
26#include "../../../Common/MyWindows.h"
27
28#endif
14 29
15// #include "../../../Common/MyWindows.h" 30/*
31WINVER and _WIN32_WINNT
16 32
17// #include <CommCtrl.h> 33MSVC6 / 2003sdk:
18// #include <ShlObj.h> 34{
19// #include <Shlwapi.h> 35 <windows.h> doesn't set _WIN32_WINNT
36 if WINVER is not set <windows.h> sets WINVER to value:
37 0x0400 : MSVC6
38 0x0501 : Windows Server 2003 PSDK / 2003 R2 PSDK
39}
20 40
41SDK for Win7 (and later)
42{
43 <windows.h> sets _WIN32_WINNT if it's not set.
44 <windows.h> sets WINVER if it's not set.
45<windows.h> includes <sdkddkver.h> that does:
46#if !defined(_WIN32_WINNT) && !defined(_CHICAGO_)
47 #define _WIN32_WINNT 0x0601 // in win7 sdk
48 #define _WIN32_WINNT 0x0A00 // in win10 sdk
21#endif 49#endif
50#ifndef WINVER
51 #ifdef _WIN32_WINNT
52 #define WINVER _WIN32_WINNT
53 else
54 #define WINVER 0x0601 // in win7 sdk
55 #define WINVER 0x0A00 // in win10 sdk
56 endif
57#endif
58}
59
60Some GUI structures defined by windows will be larger,
61If (_WIN32_WINNT) value is larger.
62
63Also if we send sizeof(win_gui_struct) to some windows function,
64and we compile that code with big (_WIN32_WINNT) value,
65the window function in old Windows can fail, if that old Windows
66doesn't understand new big version of (win_gui_struct) compiled
67with big (_WIN32_WINNT) value.
68
69So it's better to define smallest (_WIN32_WINNT) value here.
70In 7-Zip FM we use some functions that require (_WIN32_WINNT == 0x0500).
71So it's simpler to define (_WIN32_WINNT == 0x0500) here.
72If we define (_WIN32_WINNT == 0x0400) here, we need some manual
73declarations for functions and macros that require (0x0500) functions.
74Also libs must contain these (0x0500+) functions.
75
76Some code in 7-zip FM uses also CommCtrl.h structures
77that depend from (_WIN32_IE) value. But default
78(_WIN32_IE) value from <windows.h> probably is OK for us.
79So we don't set _WIN32_IE here.
80default _WIN32_IE value set by <windows.h>:
81 0x501 2003sdk
82 0xa00 win10 sdk
83*/
diff --git a/CPP/7zip/UI/FileManager/StringUtils.cpp b/CPP/7zip/UI/FileManager/StringUtils.cpp
index 0478399..4641d15 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)
24 } 24 }
25} 25}
26 26
27void SplitString(const UString &srcString, UStringVector &destStrings)
28{
29 destStrings.Clear();
30 unsigned len = srcString.Len();
31 if (len == 0)
32 return;
33 UString s;
34 for (unsigned i = 0; i < len; i++)
35 {
36 wchar_t c = srcString[i];
37 if (c == ' ')
38 {
39 if (!s.IsEmpty())
40 {
41 destStrings.Add(s);
42 s.Empty();
43 }
44 }
45 else
46 s += c;
47 }
48 if (!s.IsEmpty())
49 destStrings.Add(s);
50}
51
52/* 27/*
53UString JoinStrings(const UStringVector &srcStrings) 28UString JoinStrings(const UStringVector &srcStrings)
54{ 29{
55
56 UString s; 30 UString s;
57 FOR_VECTOR (i, srcStrings) 31 FOR_VECTOR (i, srcStrings)
58 { 32 {
diff --git a/CPP/7zip/UI/FileManager/StringUtils.h b/CPP/7zip/UI/FileManager/StringUtils.h
index fc070de..37aad3a 100644
--- a/CPP/7zip/UI/FileManager/StringUtils.h
+++ b/CPP/7zip/UI/FileManager/StringUtils.h
@@ -1,13 +1,11 @@
1// StringUtils.h 1// StringUtils.h
2 2
3#ifndef __STRING_UTILS_H 3#ifndef ZIP7_INC_STRING_UTILS_H
4#define __STRING_UTILS_H 4#define ZIP7_INC_STRING_UTILS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
8void SplitStringToTwoStrings(const UString &src, UString &dest1, UString &dest2); 8void SplitStringToTwoStrings(const UString &src, UString &dest1, UString &dest2);
9 9// UString JoinStrings(const UStringVector &srcStrings);
10void SplitString(const UString &srcString, UStringVector &destStrings);
11UString JoinStrings(const UStringVector &srcStrings);
12 10
13#endif 11#endif
diff --git a/CPP/7zip/UI/FileManager/SysIconUtils.cpp b/CPP/7zip/UI/FileManager/SysIconUtils.cpp
index d8e0f8b..1c7cab0 100644
--- a/CPP/7zip/UI/FileManager/SysIconUtils.cpp
+++ b/CPP/7zip/UI/FileManager/SysIconUtils.cpp
@@ -10,10 +10,11 @@
10 10
11#include "SysIconUtils.h" 11#include "SysIconUtils.h"
12 12
13#if defined(__MINGW32__) || defined(__MINGW64__)
14#include <shlobj.h>
15#else
13#include <ShlObj.h> 16#include <ShlObj.h>
14 17#endif
15#define MY_CAST_FUNC (void(*)())
16// #define MY_CAST_FUNC
17 18
18#ifndef _UNICODE 19#ifndef _UNICODE
19extern bool g_IsNT; 20extern bool g_IsNT;
@@ -21,49 +22,55 @@ extern bool g_IsNT;
21 22
22int GetIconIndexForCSIDL(int csidl) 23int GetIconIndexForCSIDL(int csidl)
23{ 24{
24 LPITEMIDLIST pidl = 0; 25 LPITEMIDLIST pidl = NULL;
25 SHGetSpecialFolderLocation(NULL, csidl, &pidl); 26 SHGetSpecialFolderLocation(NULL, csidl, &pidl);
26 if (pidl) 27 if (pidl)
27 { 28 {
28 SHFILEINFO shellInfo; 29 SHFILEINFO shellInfo;
29 SHGetFileInfo((LPCTSTR)(const void *)(pidl), FILE_ATTRIBUTE_NORMAL, 30 shellInfo.iIcon = 0;
30 &shellInfo, sizeof(shellInfo), 31 const DWORD_PTR res = SHGetFileInfo((LPCTSTR)(const void *)(pidl), FILE_ATTRIBUTE_NORMAL,
31 SHGFI_PIDL | SHGFI_SYSICONINDEX); 32 &shellInfo, sizeof(shellInfo),
32 IMalloc *pMalloc; 33 SHGFI_PIDL | SHGFI_SYSICONINDEX);
34 /*
35 IMalloc *pMalloc;
33 SHGetMalloc(&pMalloc); 36 SHGetMalloc(&pMalloc);
34 if (pMalloc) 37 if (pMalloc)
35 { 38 {
36 pMalloc->Free(pidl); 39 pMalloc->Free(pidl);
37 pMalloc->Release(); 40 pMalloc->Release();
38 } 41 }
39 return shellInfo.iIcon; 42 */
43 // we use OLE2.dll function here
44 CoTaskMemFree(pidl);
45 if (res)
46 return shellInfo.iIcon;
40 } 47 }
41 return 0; 48 return 0;
42} 49}
43 50
44#ifndef _UNICODE 51#ifndef _UNICODE
45typedef int (WINAPI * Func_SHGetFileInfoW)(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags); 52typedef DWORD_PTR (WINAPI * Func_SHGetFileInfoW)(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags);
46 53
47static struct CSHGetFileInfoInit 54static struct C_SHGetFileInfo_Init
48{ 55{
49 Func_SHGetFileInfoW shGetFileInfoW; 56 Func_SHGetFileInfoW f_SHGetFileInfoW;
50 CSHGetFileInfoInit() 57 C_SHGetFileInfo_Init()
51 { 58 {
52 shGetFileInfoW = (Func_SHGetFileInfoW) 59 f_SHGetFileInfoW = Z7_GET_PROC_ADDRESS(
53 MY_CAST_FUNC 60 Func_SHGetFileInfoW, ::GetModuleHandleW(L"shell32.dll"),
54 ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHGetFileInfoW"); 61 "SHGetFileInfoW");
55 } 62 }
56} g_SHGetFileInfoInit; 63} g_SHGetFileInfo_Init;
57#endif 64#endif
58 65
59static DWORD_PTR MySHGetFileInfoW(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags) 66static DWORD_PTR My_SHGetFileInfoW(LPCWSTR pszPath, DWORD attrib, SHFILEINFOW *psfi, UINT cbFileInfo, UINT uFlags)
60{ 67{
61 #ifdef _UNICODE 68 #ifdef _UNICODE
62 return SHGetFileInfo 69 return SHGetFileInfo
63 #else 70 #else
64 if (g_SHGetFileInfoInit.shGetFileInfoW == 0) 71 if (!g_SHGetFileInfo_Init.f_SHGetFileInfoW)
65 return 0; 72 return 0;
66 return g_SHGetFileInfoInit.shGetFileInfoW 73 return g_SHGetFileInfo_Init.f_SHGetFileInfoW
67 #endif 74 #endif
68 (pszPath, attrib, psfi, cbFileInfo, uFlags); 75 (pszPath, attrib, psfi, cbFileInfo, uFlags);
69} 76}
@@ -74,7 +81,7 @@ DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex)
74 if (!g_IsNT) 81 if (!g_IsNT)
75 { 82 {
76 SHFILEINFO shellInfo; 83 SHFILEINFO shellInfo;
77 DWORD_PTR res = ::SHGetFileInfo(fs2fas(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, 84 const DWORD_PTR res = ::SHGetFileInfo(fs2fas(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo,
78 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX); 85 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX);
79 iconIndex = shellInfo.iIcon; 86 iconIndex = shellInfo.iIcon;
80 return res; 87 return res;
@@ -83,7 +90,7 @@ DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex)
83 #endif 90 #endif
84 { 91 {
85 SHFILEINFOW shellInfo; 92 SHFILEINFOW shellInfo;
86 DWORD_PTR res = ::MySHGetFileInfoW(fs2us(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, 93 const DWORD_PTR res = ::My_SHGetFileInfoW(fs2us(path), FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo,
87 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX); 94 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX);
88 iconIndex = shellInfo.iIcon; 95 iconIndex = shellInfo.iIcon;
89 return res; 96 return res;
@@ -110,7 +117,7 @@ DWORD_PTR GetRealIconIndex(const UString &fileName, DWORD attrib, int &iconIndex
110 { 117 {
111 SHFILEINFOW shellInfo; 118 SHFILEINFOW shellInfo;
112 shellInfo.szTypeName[0] = 0; 119 shellInfo.szTypeName[0] = 0;
113 DWORD_PTR res = ::MySHGetFileInfoW(fileName, FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo, 120 DWORD_PTR res = ::My_SHGetFileInfoW(fileName, FILE_ATTRIBUTE_NORMAL | attrib, &shellInfo,
114 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | SHGFI_TYPENAME); 121 sizeof(shellInfo), SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | SHGFI_TYPENAME);
115 if (typeName) 122 if (typeName)
116 *typeName = shellInfo.szTypeName; 123 *typeName = shellInfo.szTypeName;
@@ -120,15 +127,15 @@ DWORD_PTR GetRealIconIndex(const UString &fileName, DWORD attrib, int &iconIndex
120} 127}
121*/ 128*/
122 129
123static int FindInSorted_Attrib(const CRecordVector<CAttribIconPair> &vect, DWORD attrib, int &insertPos) 130static int FindInSorted_Attrib(const CRecordVector<CAttribIconPair> &vect, DWORD attrib, unsigned &insertPos)
124{ 131{
125 unsigned left = 0, right = vect.Size(); 132 unsigned left = 0, right = vect.Size();
126 while (left != right) 133 while (left != right)
127 { 134 {
128 unsigned mid = (left + right) / 2; 135 const unsigned mid = (left + right) / 2;
129 DWORD midAttrib = vect[mid].Attrib; 136 const DWORD midAttrib = vect[mid].Attrib;
130 if (attrib == midAttrib) 137 if (attrib == midAttrib)
131 return mid; 138 return (int)mid;
132 if (attrib < midAttrib) 139 if (attrib < midAttrib)
133 right = mid; 140 right = mid;
134 else 141 else
@@ -138,15 +145,15 @@ static int FindInSorted_Attrib(const CRecordVector<CAttribIconPair> &vect, DWORD
138 return -1; 145 return -1;
139} 146}
140 147
141static int FindInSorted_Ext(const CObjectVector<CExtIconPair> &vect, const wchar_t *ext, int &insertPos) 148static int FindInSorted_Ext(const CObjectVector<CExtIconPair> &vect, const wchar_t *ext, unsigned &insertPos)
142{ 149{
143 unsigned left = 0, right = vect.Size(); 150 unsigned left = 0, right = vect.Size();
144 while (left != right) 151 while (left != right)
145 { 152 {
146 unsigned mid = (left + right) / 2; 153 const unsigned mid = (left + right) / 2;
147 int compare = MyStringCompareNoCase(ext, vect[mid].Ext); 154 const int compare = MyStringCompareNoCase(ext, vect[mid].Ext);
148 if (compare == 0) 155 if (compare == 0)
149 return mid; 156 return (int)mid;
150 if (compare < 0) 157 if (compare < 0)
151 right = mid; 158 right = mid;
152 else 159 else
@@ -162,11 +169,11 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin
162 unsigned i; 169 unsigned i;
163 for (i = 0;; i++) 170 for (i = 0;; i++)
164 { 171 {
165 wchar_t c = fileName[i]; 172 const wchar_t c = fileName[i];
166 if (c == 0) 173 if (c == 0)
167 break; 174 break;
168 if (c == '.') 175 if (c == '.')
169 dotPos = i; 176 dotPos = (int)i;
170 } 177 }
171 178
172 /* 179 /*
@@ -181,12 +188,12 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin
181 188
182 if ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0 || dotPos < 0) 189 if ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0 || dotPos < 0)
183 { 190 {
184 int insertPos = 0; 191 unsigned insertPos = 0;
185 int index = FindInSorted_Attrib(_attribMap, attrib, insertPos); 192 const int index = FindInSorted_Attrib(_attribMap, attrib, insertPos);
186 if (index >= 0) 193 if (index >= 0)
187 { 194 {
188 // if (typeName) *typeName = _attribMap[index].TypeName; 195 // if (typeName) *typeName = _attribMap[index].TypeName;
189 return _attribMap[index].IconIndex; 196 return _attribMap[(unsigned)index].IconIndex;
190 } 197 }
191 CAttribIconPair pair; 198 CAttribIconPair pair;
192 GetRealIconIndex( 199 GetRealIconIndex(
@@ -211,8 +218,8 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin
211 } 218 }
212 219
213 const wchar_t *ext = fileName + dotPos + 1; 220 const wchar_t *ext = fileName + dotPos + 1;
214 int insertPos = 0; 221 unsigned insertPos = 0;
215 int index = FindInSorted_Ext(_extMap, ext, insertPos); 222 const int index = FindInSorted_Ext(_extMap, ext, insertPos);
216 if (index >= 0) 223 if (index >= 0)
217 { 224 {
218 const CExtIconPair &pa = _extMap[index]; 225 const CExtIconPair &pa = _extMap[index];
@@ -222,7 +229,7 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const wchar_t *fileName /*, UStrin
222 229
223 for (i = 0;; i++) 230 for (i = 0;; i++)
224 { 231 {
225 wchar_t c = ext[i]; 232 const wchar_t c = ext[i];
226 if (c == 0) 233 if (c == 0)
227 break; 234 break;
228 if (c < L'0' || c > L'9') 235 if (c < L'0' || c > L'9')
@@ -257,3 +264,15 @@ int CExtToIconMap::GetIconIndex(DWORD attrib, const UString &fileName)
257 return GetIconIndex(attrib, fileName, NULL); 264 return GetIconIndex(attrib, fileName, NULL);
258} 265}
259*/ 266*/
267
268HIMAGELIST GetSysImageList(bool smallIcons)
269{
270 SHFILEINFO shellInfo;
271 return (HIMAGELIST)SHGetFileInfo(TEXT(""),
272 FILE_ATTRIBUTE_NORMAL |
273 FILE_ATTRIBUTE_DIRECTORY,
274 &shellInfo, sizeof(shellInfo),
275 SHGFI_USEFILEATTRIBUTES |
276 SHGFI_SYSICONINDEX |
277 (smallIcons ? SHGFI_SMALLICON : SHGFI_ICON));
278}
diff --git a/CPP/7zip/UI/FileManager/SysIconUtils.h b/CPP/7zip/UI/FileManager/SysIconUtils.h
index fde16e4..1d34ef6 100644
--- a/CPP/7zip/UI/FileManager/SysIconUtils.h
+++ b/CPP/7zip/UI/FileManager/SysIconUtils.h
@@ -1,7 +1,7 @@
1// SysIconUtils.h 1// SysIconUtils.h
2 2
3#ifndef __SYS_ICON_UTILS_H 3#ifndef ZIP7_INC_SYS_ICON_UTILS_H
4#define __SYS_ICON_UTILS_H 4#define ZIP7_INC_SYS_ICON_UTILS_H
5 5
6#include "../../../Common/MyWindows.h" 6#include "../../../Common/MyWindows.h"
7 7
@@ -50,13 +50,6 @@ public:
50DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex); 50DWORD_PTR GetRealIconIndex(CFSTR path, DWORD attrib, int &iconIndex);
51int GetIconIndexForCSIDL(int csidl); 51int GetIconIndexForCSIDL(int csidl);
52 52
53inline HIMAGELIST GetSysImageList(bool smallIcons) 53HIMAGELIST GetSysImageList(bool smallIcons);
54{
55 SHFILEINFO shellInfo;
56 return (HIMAGELIST)SHGetFileInfo(TEXT(""),
57 FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_DIRECTORY,
58 &shellInfo, sizeof(shellInfo),
59 SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | (smallIcons ? SHGFI_SMALLICON : SHGFI_ICON));
60}
61 54
62#endif 55#endif
diff --git a/CPP/7zip/UI/FileManager/SystemPage.cpp b/CPP/7zip/UI/FileManager/SystemPage.cpp
index a95999f..09d8a72 100644
--- a/CPP/7zip/UI/FileManager/SystemPage.cpp
+++ b/CPP/7zip/UI/FileManager/SystemPage.cpp
@@ -4,7 +4,11 @@
4 4
5#include "../../../Common/MyWindows.h" 5#include "../../../Common/MyWindows.h"
6 6
7#if defined(__MINGW32__) || defined(__MINGW64__)
8#include <shlobj.h>
9#else
7#include <ShlObj.h> 10#include <ShlObj.h>
11#endif
8 12
9#include "../../../Common/Defs.h" 13#include "../../../Common/Defs.h"
10#include "../../../Common/StringConvert.h" 14#include "../../../Common/StringConvert.h"
@@ -25,10 +29,12 @@ using namespace NWindows;
25extern bool g_IsNT; 29extern bool g_IsNT;
26#endif 30#endif
27 31
32#ifdef Z7_LANG
28static const UInt32 kLangIDs[] = 33static const UInt32 kLangIDs[] =
29{ 34{
30 IDT_SYSTEM_ASSOCIATE 35 IDT_SYSTEM_ASSOCIATE
31}; 36};
37#endif
32 38
33#define kSystemTopic "FM/options.htm#system" 39#define kSystemTopic "FM/options.htm#system"
34 40
@@ -44,7 +50,7 @@ CSysString CModifiedExtInfo::GetString() const
44 else 50 else
45 return ProgramKey; 51 return ProgramKey;
46 return CSysString (s); 52 return CSysString (s);
47}; 53}
48 54
49 55
50int CSystemPage::AddIcon(const UString &iconPath, int iconIndex) 56int CSystemPage::AddIcon(const UString &iconPath, int iconIndex)
@@ -62,19 +68,19 @@ int CSystemPage::AddIcon(const UString &iconPath, int iconIndex)
62 #else 68 #else
63 // we expand path from REG_EXPAND_SZ registry item. 69 // we expand path from REG_EXPAND_SZ registry item.
64 UString path; 70 UString path;
65 DWORD size = MAX_PATH + 10; 71 const DWORD size = MAX_PATH + 10;
66 DWORD needLen = ::ExpandEnvironmentStringsW(iconPath, path.GetBuf(size + 2), size); 72 const DWORD needLen = ::ExpandEnvironmentStringsW(iconPath, path.GetBuf(size + 2), size);
67 path.ReleaseBuf_CalcLen(size); 73 path.ReleaseBuf_CalcLen(size);
68 if (needLen == 0 || needLen >= size) 74 if (needLen == 0 || needLen >= size)
69 path = iconPath; 75 path = iconPath;
70 int num = ExtractIconExW(path, iconIndex, NULL, &hicon, 1); 76 const UINT num = ExtractIconExW(path, iconIndex, NULL, &hicon, 1);
71 if (num != 1 || !hicon) 77 if (num != 1 || !hicon)
72 #endif 78 #endif
73 return -1; 79 return -1;
74 80
75 _imageList.AddIcon(hicon); 81 _imageList.AddIcon(hicon);
76 DestroyIcon(hicon); 82 DestroyIcon(hicon);
77 return _numIcons++; 83 return (int)(_numIcons++);
78} 84}
79 85
80 86
@@ -84,7 +90,7 @@ void CSystemPage::RefreshListItem(unsigned group, unsigned listIndex)
84 _listView.SetSubItem(listIndex, group + 1, assoc.Pair[group].GetString()); 90 _listView.SetSubItem(listIndex, group + 1, assoc.Pair[group].GetString());
85 LVITEMW newItem; 91 LVITEMW newItem;
86 memset(&newItem, 0, sizeof(newItem)); 92 memset(&newItem, 0, sizeof(newItem));
87 newItem.iItem = listIndex; 93 newItem.iItem = (int)listIndex;
88 newItem.mask = LVIF_IMAGE; 94 newItem.mask = LVIF_IMAGE;
89 newItem.iImage = assoc.GetIconIndex(); 95 newItem.iImage = assoc.GetIconIndex();
90 _listView.SetItem(&newItem); 96 _listView.SetItem(&newItem);
@@ -151,7 +157,9 @@ bool CSystemPage::OnInit()
151{ 157{
152 _needSave = false; 158 _needSave = false;
153 159
154 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 160#ifdef Z7_LANG
161 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
162#endif
155 163
156 _listView.Attach(GetItem(IDL_SYSTEM_ASSOCIATE)); 164 _listView.Attach(GetItem(IDL_SYSTEM_ASSOCIATE));
157 _listView.SetUnicodeFormat(); 165 _listView.SetUnicodeFormat();
@@ -221,9 +229,9 @@ bool CSystemPage::OnInit()
221 const CExtPlugins &extInfo = _extDB.Exts[i]; 229 const CExtPlugins &extInfo = _extDB.Exts[i];
222 230
223 LVITEMW item; 231 LVITEMW item;
224 item.iItem = i; 232 item.iItem = (int)i;
225 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; 233 item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
226 item.lParam = i; 234 item.lParam = (LPARAM)i;
227 item.iSubItem = 0; 235 item.iSubItem = 0;
228 // ListView always uses internal iImage that is 0 by default? 236 // ListView always uses internal iImage that is 0 by default?
229 // so we always use LVIF_IMAGE. 237 // so we always use LVIF_IMAGE.
@@ -245,9 +253,9 @@ bool CSystemPage::OnInit()
245 texts[g] = mi.GetString(); 253 texts[g] = mi.GetString();
246 } 254 }
247 item.iImage = assoc.GetIconIndex(); 255 item.iImage = assoc.GetIconIndex();
248 int itemIndex = _listView.InsertItem(&item); 256 const int itemIndex = _listView.InsertItem(&item);
249 for (g = 0; g < NUM_EXT_GROUPS; g++) 257 for (g = 0; g < NUM_EXT_GROUPS; g++)
250 _listView.SetSubItem(itemIndex, 1 + g, texts[g]); 258 _listView.SetSubItem((unsigned)itemIndex, 1 + g, texts[g]);
251 _items.Add(assoc); 259 _items.Add(assoc);
252 } 260 }
253 261
@@ -334,7 +342,7 @@ void CSystemPage::OnNotifyHelp()
334} 342}
335 343
336 344
337bool CSystemPage::OnButtonClicked(int buttonID, HWND buttonHWND) 345bool CSystemPage::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
338{ 346{
339 switch (buttonID) 347 switch (buttonID)
340 { 348 {
@@ -379,7 +387,7 @@ bool CSystemPage::OnNotify(UINT controlID, LPNMHDR lParam)
379 if (item->iSubItem >= 1 && item->iSubItem <= 2) 387 if (item->iSubItem >= 1 && item->iSubItem <= 2)
380 { 388 {
381 CUIntVector indices; 389 CUIntVector indices;
382 indices.Add(item->iItem); 390 indices.Add((unsigned)item->iItem);
383 ChangeState(item->iSubItem < 2 ? 0 : 1, indices); 391 ChangeState(item->iSubItem < 2 ? 0 : 1, indices);
384 } 392 }
385 } 393 }
@@ -414,7 +422,7 @@ void CSystemPage::ChangeState(unsigned group)
414 422
415 int itemIndex = -1; 423 int itemIndex = -1;
416 while ((itemIndex = _listView.GetNextSelectedItem(itemIndex)) != -1) 424 while ((itemIndex = _listView.GetNextSelectedItem(itemIndex)) != -1)
417 indices.Add(itemIndex); 425 indices.Add((unsigned)itemIndex);
418 426
419 if (indices.IsEmpty()) 427 if (indices.IsEmpty())
420 FOR_VECTOR (i, _items) 428 FOR_VECTOR (i, _items)
diff --git a/CPP/7zip/UI/FileManager/SystemPage.h b/CPP/7zip/UI/FileManager/SystemPage.h
index 765214c..6f2ed0c 100644
--- a/CPP/7zip/UI/FileManager/SystemPage.h
+++ b/CPP/7zip/UI/FileManager/SystemPage.h
@@ -1,7 +1,7 @@
1// SystemPage.h 1// SystemPage.h
2 2
3#ifndef __SYSTEM_PAGE_H 3#ifndef ZIP7_INC_SYSTEM_PAGE_H
4#define __SYSTEM_PAGE_H 4#define ZIP7_INC_SYSTEM_PAGE_H
5 5
6#include "../../../Windows/Control/ImageList.h" 6#include "../../../Windows/Control/ImageList.h"
7#include "../../../Windows/Control/ListView.h" 7#include "../../../Windows/Control/ListView.h"
@@ -49,7 +49,7 @@ struct CModifiedExtInfo: public NRegistryAssoc::CShellExtInfo
49 } 49 }
50 } 50 }
51 OldState = State; 51 OldState = State;
52 }; 52 }
53}; 53};
54 54
55struct CAssoc 55struct CAssoc
@@ -116,11 +116,11 @@ public:
116 116
117 CSystemPage(): WasChanged(false) {} 117 CSystemPage(): WasChanged(false) {}
118 118
119 virtual bool OnInit(); 119 virtual bool OnInit() Z7_override;
120 virtual void OnNotifyHelp(); 120 virtual void OnNotifyHelp() Z7_override;
121 virtual bool OnNotify(UINT controlID, LPNMHDR lParam); 121 virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override;
122 virtual LONG OnApply(); 122 virtual LONG OnApply() Z7_override;
123 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 123 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
124}; 124};
125 125
126#endif 126#endif
diff --git a/CPP/7zip/UI/FileManager/TextPairs.cpp b/CPP/7zip/UI/FileManager/TextPairs.cpp
index 4edf025..1ac7098 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)
100static int ComparePairItems(void *const *a1, void *const *a2, void * /* param */) 100static int ComparePairItems(void *const *a1, void *const *a2, void * /* param */)
101 { return ComparePairItems(**(const CTextPair *const *)a1, **(const CTextPair *const *)a2); } 101 { return ComparePairItems(**(const CTextPair *const *)a1, **(const CTextPair *const *)a2); }
102 102
103void CPairsStorage::Sort() { Pairs.Sort(ComparePairItems, 0); } 103void CPairsStorage::Sort() { Pairs.Sort(ComparePairItems, NULL); }
104 104
105int CPairsStorage::FindID(const UString &id, int &insertPos) const 105int CPairsStorage::FindID(const UString &id, unsigned &insertPos) const
106{ 106{
107 unsigned left = 0, right = Pairs.Size(); 107 unsigned left = 0, right = Pairs.Size();
108 while (left != right) 108 while (left != right)
@@ -112,7 +112,7 @@ int CPairsStorage::FindID(const UString &id, int &insertPos) const
112 if (compResult == 0) 112 if (compResult == 0)
113 { 113 {
114 insertPos = mid; // to disable GCC warning 114 insertPos = mid; // to disable GCC warning
115 return mid; 115 return (int)mid;
116 } 116 }
117 if (compResult < 0) 117 if (compResult < 0)
118 right = mid; 118 right = mid;
@@ -125,13 +125,13 @@ int CPairsStorage::FindID(const UString &id, int &insertPos) const
125 125
126int CPairsStorage::FindID(const UString &id) const 126int CPairsStorage::FindID(const UString &id) const
127{ 127{
128 int pos; 128 unsigned pos;
129 return FindID(id, pos); 129 return FindID(id, pos);
130} 130}
131 131
132void CPairsStorage::AddPair(const CTextPair &pair) 132void CPairsStorage::AddPair(const CTextPair &pair)
133{ 133{
134 int insertPos; 134 unsigned insertPos;
135 const int pos = FindID(pair.ID, insertPos); 135 const int pos = FindID(pair.ID, insertPos);
136 if (pos >= 0) 136 if (pos >= 0)
137 Pairs[pos] = pair; 137 Pairs[pos] = pair;
@@ -143,7 +143,7 @@ void CPairsStorage::DeletePair(const UString &id)
143{ 143{
144 const int pos = FindID(id); 144 const int pos = FindID(id);
145 if (pos >= 0) 145 if (pos >= 0)
146 Pairs.Delete(pos); 146 Pairs.Delete((unsigned)pos);
147} 147}
148 148
149bool CPairsStorage::GetValue(const UString &id, UString &value) const 149bool CPairsStorage::GetValue(const UString &id, UString &value) const
@@ -185,7 +185,7 @@ void CPairsStorage::SaveToString(UString &text) const
185 text += pair.ID; 185 text += pair.ID;
186 if (multiWord) 186 if (multiWord)
187 text += '\"'; 187 text += '\"';
188 text += ' '; 188 text.Add_Space();
189 text += pair.Value; 189 text += pair.Value;
190 text += '\x0D'; 190 text += '\x0D';
191 text.Add_LF(); 191 text.Add_LF();
diff --git a/CPP/7zip/UI/FileManager/TextPairs.h b/CPP/7zip/UI/FileManager/TextPairs.h
index 0a71d04..d18233d 100644
--- a/CPP/7zip/UI/FileManager/TextPairs.h
+++ b/CPP/7zip/UI/FileManager/TextPairs.h
@@ -1,7 +1,7 @@
1// TextPairs.h 1// TextPairs.h
2 2
3#ifndef __FM_TEXT_PAIRS_H 3#ifndef ZIP7_INC_FM_TEXT_PAIRS_H
4#define __FM_TEXT_PAIRS_H 4#define ZIP7_INC_FM_TEXT_PAIRS_H
5 5
6#include "../../../Common/MyString.h" 6#include "../../../Common/MyString.h"
7 7
@@ -15,7 +15,7 @@ class CPairsStorage
15{ 15{
16 CObjectVector<CTextPair> Pairs; 16 CObjectVector<CTextPair> Pairs;
17 17
18 int FindID(const UString &id, int &insertPos) const; 18 int FindID(const UString &id, unsigned &insertPos) const;
19 int FindID(const UString &id) const; 19 int FindID(const UString &id) const;
20 void Sort(); 20 void Sort();
21public: 21public:
diff --git a/CPP/7zip/UI/FileManager/UpdateCallback100.cpp b/CPP/7zip/UI/FileManager/UpdateCallback100.cpp
index 67e70fb..71ad710 100644
--- a/CPP/7zip/UI/FileManager/UpdateCallback100.cpp
+++ b/CPP/7zip/UI/FileManager/UpdateCallback100.cpp
@@ -9,50 +9,50 @@
9#include "LangUtils.h" 9#include "LangUtils.h"
10#include "UpdateCallback100.h" 10#include "UpdateCallback100.h"
11 11
12STDMETHODIMP CUpdateCallback100Imp::ScanProgress(UInt64 /* numFolders */, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */) 12Z7_COM7F_IMF(CUpdateCallback100Imp::ScanProgress(UInt64 /* numFolders */, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, Int32 /* isDir */))
13{ 13{
14 return ProgressDialog->Sync.ScanProgress(numFiles, totalSize, us2fs(path)); 14 return ProgressDialog->Sync.ScanProgress(numFiles, totalSize, us2fs(path));
15} 15}
16 16
17STDMETHODIMP CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode) 17Z7_COM7F_IMF(CUpdateCallback100Imp::ScanError(const wchar_t *path, HRESULT errorCode))
18{ 18{
19 ProgressDialog->Sync.AddError_Code_Name(errorCode, path); 19 ProgressDialog->Sync.AddError_Code_Name(errorCode, path);
20 return S_OK; 20 return S_OK;
21} 21}
22 22
23STDMETHODIMP CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles) 23Z7_COM7F_IMF(CUpdateCallback100Imp::SetNumFiles(UInt64 numFiles))
24{ 24{
25 return ProgressDialog->Sync.Set_NumFilesTotal(numFiles); 25 return ProgressDialog->Sync.Set_NumFilesTotal(numFiles);
26} 26}
27 27
28STDMETHODIMP CUpdateCallback100Imp::SetTotal(UInt64 size) 28Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(UInt64 size))
29{ 29{
30 ProgressDialog->Sync.Set_NumBytesTotal(size); 30 ProgressDialog->Sync.Set_NumBytesTotal(size);
31 return S_OK; 31 return S_OK;
32} 32}
33 33
34STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 *completed) 34Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 *completed))
35{ 35{
36 return ProgressDialog->Sync.Set_NumBytesCur(completed); 36 return ProgressDialog->Sync.Set_NumBytesCur(completed);
37} 37}
38 38
39STDMETHODIMP CUpdateCallback100Imp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) 39Z7_COM7F_IMF(CUpdateCallback100Imp::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize))
40{ 40{
41 ProgressDialog->Sync.Set_Ratio(inSize, outSize); 41 ProgressDialog->Sync.Set_Ratio(inSize, outSize);
42 return S_OK; 42 return S_OK;
43} 43}
44 44
45STDMETHODIMP CUpdateCallback100Imp::CompressOperation(const wchar_t *name) 45Z7_COM7F_IMF(CUpdateCallback100Imp::CompressOperation(const wchar_t *name))
46{ 46{
47 return SetOperation_Base(NUpdateNotifyOp::kAdd, name, false); 47 return SetOperation_Base(NUpdateNotifyOp::kAdd, name, false);
48} 48}
49 49
50STDMETHODIMP CUpdateCallback100Imp::DeleteOperation(const wchar_t *name) 50Z7_COM7F_IMF(CUpdateCallback100Imp::DeleteOperation(const wchar_t *name))
51{ 51{
52 return SetOperation_Base(NUpdateNotifyOp::kDelete, name, false); 52 return SetOperation_Base(NUpdateNotifyOp::kDelete, name, false);
53} 53}
54 54
55STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */) 55Z7_COM7F_IMF(CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */))
56{ 56{
57 ProgressDialog->Sync.Set_NumFilesCur(++NumFiles); 57 ProgressDialog->Sync.Set_NumFilesCur(++NumFiles);
58 return S_OK; 58 return S_OK;
@@ -60,7 +60,7 @@ STDMETHODIMP CUpdateCallback100Imp::OperationResult(Int32 /* operationResult */)
60 60
61void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileName, UString &s); 61void SetExtractErrorMessage(Int32 opRes, Int32 encrypted, const wchar_t *fileName, UString &s);
62 62
63HRESULT CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name) 63Z7_COM7F_IMF(CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypted, const wchar_t *name))
64{ 64{
65 if (opRes != NArchive::NExtract::NOperationResult::kOK) 65 if (opRes != NArchive::NExtract::NOperationResult::kOK)
66 { 66 {
@@ -71,30 +71,30 @@ HRESULT CUpdateCallback100Imp::ReportExtractResult(Int32 opRes, Int32 isEncrypte
71 return S_OK; 71 return S_OK;
72} 72}
73 73
74HRESULT CUpdateCallback100Imp::ReportUpdateOperation(UInt32 notifyOp, const wchar_t *name, Int32 isDir) 74Z7_COM7F_IMF(CUpdateCallback100Imp::ReportUpdateOperation(UInt32 notifyOp, const wchar_t *name, Int32 isDir))
75{ 75{
76 return SetOperation_Base(notifyOp, name, IntToBool(isDir)); 76 return SetOperation_Base(notifyOp, name, IntToBool(isDir));
77} 77}
78 78
79STDMETHODIMP CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message) 79Z7_COM7F_IMF(CUpdateCallback100Imp::UpdateErrorMessage(const wchar_t *message))
80{ 80{
81 ProgressDialog->Sync.AddError_Message(message); 81 ProgressDialog->Sync.AddError_Message(message);
82 return S_OK; 82 return S_OK;
83} 83}
84 84
85HRESULT CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode) 85Z7_COM7F_IMF(CUpdateCallback100Imp::OpenFileError(const wchar_t *path, HRESULT errorCode))
86{ 86{
87 ProgressDialog->Sync.AddError_Code_Name(errorCode, path); 87 ProgressDialog->Sync.AddError_Code_Name(errorCode, path);
88 return S_OK; 88 return S_OK;
89} 89}
90 90
91STDMETHODIMP CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode) 91Z7_COM7F_IMF(CUpdateCallback100Imp::ReadingFileError(const wchar_t *path, HRESULT errorCode))
92{ 92{
93 ProgressDialog->Sync.AddError_Code_Name(errorCode, path); 93 ProgressDialog->Sync.AddError_Code_Name(errorCode, path);
94 return S_OK; 94 return S_OK;
95} 95}
96 96
97STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password) 97Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password))
98{ 98{
99 *password = NULL; 99 *password = NULL;
100 *passwordIsDefined = BoolToInt(PasswordIsDefined); 100 *passwordIsDefined = BoolToInt(PasswordIsDefined);
@@ -103,17 +103,17 @@ STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword2(Int32 *passwordIsDefi
103 return StringToBstr(Password, password); 103 return StringToBstr(Password, password);
104} 104}
105 105
106STDMETHODIMP CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) 106Z7_COM7F_IMF(CUpdateCallback100Imp::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */))
107{ 107{
108 return S_OK; 108 return S_OK;
109} 109}
110 110
111STDMETHODIMP CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) 111Z7_COM7F_IMF(CUpdateCallback100Imp::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */))
112{ 112{
113 return ProgressDialog->Sync.CheckStop(); 113 return ProgressDialog->Sync.CheckStop();
114} 114}
115 115
116STDMETHODIMP CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password) 116Z7_COM7F_IMF(CUpdateCallback100Imp::CryptoGetTextPassword(BSTR *password))
117{ 117{
118 *password = NULL; 118 *password = NULL;
119 if (!PasswordIsDefined) 119 if (!PasswordIsDefined)
diff --git a/CPP/7zip/UI/FileManager/UpdateCallback100.h b/CPP/7zip/UI/FileManager/UpdateCallback100.h
index 7cbc11e..5d56dfb 100644
--- a/CPP/7zip/UI/FileManager/UpdateCallback100.h
+++ b/CPP/7zip/UI/FileManager/UpdateCallback100.h
@@ -1,7 +1,7 @@
1// UpdateCallback100.h 1// UpdateCallback100.h
2 2
3#ifndef __UPDATE_CALLBACK100_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK100_H
4#define __UPDATE_CALLBACK100_H 4#define ZIP7_INC_UPDATE_CALLBACK100_H
5 5
6#include "../../../Common/MyCom.h" 6#include "../../../Common/MyCom.h"
7 7
@@ -13,7 +13,7 @@
13 13
14#include "ProgressDialog2.h" 14#include "ProgressDialog2.h"
15 15
16class CUpdateCallback100Imp: 16class CUpdateCallback100Imp Z7_final:
17 public IFolderArchiveUpdateCallback, 17 public IFolderArchiveUpdateCallback,
18 public IFolderArchiveUpdateCallback2, 18 public IFolderArchiveUpdateCallback2,
19 public IFolderScanProgress, 19 public IFolderScanProgress,
@@ -24,11 +24,7 @@ class CUpdateCallback100Imp:
24 public CUpdateCallbackGUI2, 24 public CUpdateCallbackGUI2,
25 public CMyUnknownImp 25 public CMyUnknownImp
26{ 26{
27public: 27 Z7_COM_UNKNOWN_IMP_7(
28
29 // CUpdateCallback100Imp() {}
30
31 MY_UNKNOWN_IMP7(
32 IFolderArchiveUpdateCallback, 28 IFolderArchiveUpdateCallback,
33 IFolderArchiveUpdateCallback2, 29 IFolderArchiveUpdateCallback2,
34 IFolderScanProgress, 30 IFolderScanProgress,
@@ -37,16 +33,14 @@ public:
37 IArchiveOpenCallback, 33 IArchiveOpenCallback,
38 ICompressProgressInfo) 34 ICompressProgressInfo)
39 35
40 INTERFACE_IProgress(;) 36 Z7_IFACE_COM7_IMP(IProgress)
41 INTERFACE_IArchiveOpenCallback(;) 37 Z7_IFACE_COM7_IMP(IFolderArchiveUpdateCallback)
42 INTERFACE_IFolderArchiveUpdateCallback(;) 38 Z7_IFACE_COM7_IMP(IFolderArchiveUpdateCallback2)
43 INTERFACE_IFolderArchiveUpdateCallback2(;) 39 Z7_IFACE_COM7_IMP(IFolderScanProgress)
44 INTERFACE_IFolderScanProgress(;) 40 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword2)
45 41 Z7_IFACE_COM7_IMP(ICryptoGetTextPassword)
46 STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); 42 Z7_IFACE_COM7_IMP(IArchiveOpenCallback)
47 43 Z7_IFACE_COM7_IMP(ICompressProgressInfo)
48 STDMETHOD(CryptoGetTextPassword)(BSTR *password);
49 STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password);
50}; 44};
51 45
52#endif 46#endif
diff --git a/CPP/7zip/UI/FileManager/VerCtrl.cpp b/CPP/7zip/UI/FileManager/VerCtrl.cpp
index 4bb034f..0c894b8 100644
--- a/CPP/7zip/UI/FileManager/VerCtrl.cpp
+++ b/CPP/7zip/UI/FileManager/VerCtrl.cpp
@@ -149,7 +149,7 @@ void CApp::VerCtrl(unsigned id)
149 } 149 }
150 150
151 CRecordVector<UInt32> indices; 151 CRecordVector<UInt32> indices;
152 panel.GetSelectedItemsIndices(indices); 152 panel.Get_ItemIndices_Selected(indices);
153 153
154 if (indices.Size() != 1) 154 if (indices.Size() != 1)
155 { 155 {
@@ -223,7 +223,7 @@ void CApp::VerCtrl(unsigned id)
223 if (!ParseNumberString(fi.Name, val)) 223 if (!ParseNumberString(fi.Name, val))
224 continue; 224 continue;
225 if ((Int32)val > maxVal) 225 if ((Int32)val > maxVal)
226 maxVal = val; 226 maxVal = (Int32)val;
227 } 227 }
228 228
229 UInt32 next = (UInt32)maxVal + 1; 229 UInt32 next = (UInt32)maxVal + 1;
@@ -320,7 +320,7 @@ void CApp::VerCtrl(unsigned id)
320 const UInt64 k_Ntfs_prec = 10000000; 320 const UInt64 k_Ntfs_prec = 10000000;
321 UInt64 timeStamp = timeStampOriginal; 321 UInt64 timeStamp = timeStampOriginal;
322 const UInt32 k_precs[] = { 60 * 60, 60, 2, 1 }; 322 const UInt32 k_precs[] = { 60 * 60, 60, 2, 1 };
323 for (unsigned i = 0; i < ARRAY_SIZE(k_precs); i++) 323 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_precs); i++)
324 { 324 {
325 timeStamp = timeStampOriginal; 325 timeStamp = timeStampOriginal;
326 const UInt64 prec = k_Ntfs_prec * k_precs[i]; 326 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 0f87711..3d64602 100644
--- a/CPP/7zip/UI/FileManager/ViewSettings.cpp
+++ b/CPP/7zip/UI/FileManager/ViewSettings.cpp
@@ -36,7 +36,8 @@ static NSynchronization::CCriticalSection g_CS;
36#define Set32(p, v) SetUi32(((Byte *)p), v) 36#define Set32(p, v) SetUi32(((Byte *)p), v)
37#define SetBool(p, v) Set32(p, ((v) ? 1 : 0)) 37#define SetBool(p, v) Set32(p, ((v) ? 1 : 0))
38 38
39#define Get32(p, dest) dest = GetUi32((const Byte *)p) 39#define Get32(p, dest) dest = GetUi32((const Byte *)p);
40#define Get32_LONG(p, dest) dest = (LONG)GetUi32((const Byte *)p);
40#define GetBool(p, dest) dest = (GetUi32(p) != 0); 41#define GetBool(p, dest) dest = (GetUi32(p) != 0);
41 42
42/* 43/*
@@ -57,16 +58,16 @@ void CListViewInfo::Save(const UString &id) const
57 const UInt32 dataSize = kListViewHeaderSize + kColumnInfoSize * Columns.Size(); 58 const UInt32 dataSize = kListViewHeaderSize + kColumnInfoSize * Columns.Size();
58 CByteArr buf(dataSize); 59 CByteArr buf(dataSize);
59 60
60 Set32(buf, kListViewVersion); 61 Set32(buf, kListViewVersion)
61 Set32(buf + 4, SortID); 62 Set32(buf + 4, SortID)
62 SetBool(buf + 8, Ascending); 63 SetBool(buf + 8, Ascending)
63 FOR_VECTOR (i, Columns) 64 FOR_VECTOR (i, Columns)
64 { 65 {
65 const CColumnInfo &column = Columns[i]; 66 const CColumnInfo &column = Columns[i];
66 Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize; 67 Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize;
67 Set32(p, column.PropID); 68 Set32(p, column.PropID)
68 SetBool(p + 4, column.IsVisible); 69 SetBool(p + 4, column.IsVisible)
69 Set32(p + 8, column.Width); 70 Set32(p + 8, column.Width)
70 } 71 }
71 { 72 {
72 NSynchronization::CCriticalSectionLock lock(g_CS); 73 NSynchronization::CCriticalSectionLock lock(g_CS);
@@ -92,11 +93,11 @@ void CListViewInfo::Read(const UString &id)
92 if (size < kListViewHeaderSize) 93 if (size < kListViewHeaderSize)
93 return; 94 return;
94 UInt32 version; 95 UInt32 version;
95 Get32(buf, version); 96 Get32(buf, version)
96 if (version != kListViewVersion) 97 if (version != kListViewVersion)
97 return; 98 return;
98 Get32(buf + 4, SortID); 99 Get32(buf + 4, SortID)
99 GetBool(buf + 8, Ascending); 100 GetBool(buf + 8, Ascending)
100 101
101 IsLoaded = true; 102 IsLoaded = true;
102 103
@@ -109,9 +110,9 @@ void CListViewInfo::Read(const UString &id)
109 { 110 {
110 CColumnInfo column; 111 CColumnInfo column;
111 const Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize; 112 const Byte *p = buf + kListViewHeaderSize + i * kColumnInfoSize;
112 Get32(p, column.PropID); 113 Get32(p, column.PropID)
113 GetBool(p + 4, column.IsVisible); 114 GetBool(p + 4, column.IsVisible)
114 Get32(p + 8, column.Width); 115 Get32(p + 8, column.Width)
115 Columns.AddInReserved(column); 116 Columns.AddInReserved(column);
116 } 117 }
117} 118}
@@ -142,18 +143,18 @@ void CWindowInfo::Save() const
142 key.Create(HKEY_CURRENT_USER, kCUBasePath); 143 key.Create(HKEY_CURRENT_USER, kCUBasePath);
143 { 144 {
144 Byte buf[kWindowPositionHeaderSize]; 145 Byte buf[kWindowPositionHeaderSize];
145 Set32(buf, rect.left); 146 Set32(buf, (UInt32)rect.left)
146 Set32(buf + 4, rect.top); 147 Set32(buf + 4, (UInt32)rect.top)
147 Set32(buf + 8, rect.right); 148 Set32(buf + 8, (UInt32)rect.right)
148 Set32(buf + 12, rect.bottom); 149 Set32(buf + 12, (UInt32)rect.bottom)
149 SetBool(buf + 16, maximized); 150 SetBool(buf + 16, maximized)
150 key.SetValue(kPositionValueName, buf, kWindowPositionHeaderSize); 151 key.SetValue(kPositionValueName, buf, kWindowPositionHeaderSize);
151 } 152 }
152 { 153 {
153 Byte buf[kPanelsInfoHeaderSize]; 154 Byte buf[kPanelsInfoHeaderSize];
154 Set32(buf, numPanels); 155 Set32(buf, numPanels)
155 Set32(buf + 4, currentPanel); 156 Set32(buf + 4, currentPanel)
156 Set32(buf + 8, splitterPos); 157 Set32(buf + 8, splitterPos)
157 key.SetValue(kPanelsInfoValueName, buf, kPanelsInfoHeaderSize); 158 key.SetValue(kPanelsInfoValueName, buf, kPanelsInfoHeaderSize);
158 } 159 }
159} 160}
@@ -175,18 +176,18 @@ void CWindowInfo::Read(bool &windowPosDefined, bool &panelInfoDefined)
175 CByteBuffer buf; 176 CByteBuffer buf;
176 if (QueryBuf(key, kPositionValueName, buf, kWindowPositionHeaderSize)) 177 if (QueryBuf(key, kPositionValueName, buf, kWindowPositionHeaderSize))
177 { 178 {
178 Get32(buf, rect.left); 179 Get32_LONG(buf, rect.left)
179 Get32(buf + 4, rect.top); 180 Get32_LONG(buf + 4, rect.top)
180 Get32(buf + 8, rect.right); 181 Get32_LONG(buf + 8, rect.right)
181 Get32(buf + 12, rect.bottom); 182 Get32_LONG(buf + 12, rect.bottom)
182 GetBool(buf + 16, maximized); 183 GetBool(buf + 16, maximized)
183 windowPosDefined = true; 184 windowPosDefined = true;
184 } 185 }
185 if (QueryBuf(key, kPanelsInfoValueName, buf, kPanelsInfoHeaderSize)) 186 if (QueryBuf(key, kPanelsInfoValueName, buf, kPanelsInfoHeaderSize))
186 { 187 {
187 Get32(buf, numPanels); 188 Get32(buf, numPanels)
188 Get32(buf + 4, currentPanel); 189 Get32(buf + 4, currentPanel)
189 Get32(buf + 8, splitterPos); 190 Get32(buf + 8, splitterPos)
190 panelInfoDefined = true; 191 panelInfoDefined = true;
191 } 192 }
192 return; 193 return;
diff --git a/CPP/7zip/UI/FileManager/ViewSettings.h b/CPP/7zip/UI/FileManager/ViewSettings.h
index aeb6897..02af0a1 100644
--- a/CPP/7zip/UI/FileManager/ViewSettings.h
+++ b/CPP/7zip/UI/FileManager/ViewSettings.h
@@ -1,7 +1,7 @@
1// ViewSettings.h 1// ViewSettings.h
2 2
3#ifndef __VIEW_SETTINGS_H 3#ifndef ZIP7_INC_VIEW_SETTINGS_H
4#define __VIEW_SETTINGS_H 4#define ZIP7_INC_VIEW_SETTINGS_H
5 5
6#include "../../../Common/MyTypes.h" 6#include "../../../Common/MyTypes.h"
7#include "../../../Common/MyString.h" 7#include "../../../Common/MyString.h"
diff --git a/CPP/7zip/UI/FileManager/makefile b/CPP/7zip/UI/FileManager/makefile
index dd2a2f2..df08c98 100644
--- a/CPP/7zip/UI/FileManager/makefile
+++ b/CPP/7zip/UI/FileManager/makefile
@@ -1,6 +1,6 @@
1PROG = 7zFM.exe 1PROG = 7zFM.exe
2CFLAGS = $(CFLAGS) \ 2CFLAGS = $(CFLAGS) \
3 -DEXTERNAL_CODECS \ 3 -DZ7_EXTERNAL_CODECS \
4 4
5!include "FM.mak" 5!include "FM.mak"
6 6
@@ -85,6 +85,7 @@ UI_COMMON_OBJS = \
85 85
86EXPLORER_OBJS = \ 86EXPLORER_OBJS = \
87 $O\ContextMenu.obj \ 87 $O\ContextMenu.obj \
88 $O\MyMessages.obj \
88 $O\RegistryContextMenu.obj \ 89 $O\RegistryContextMenu.obj \
89 90
90GUI_OBJS = \ 91GUI_OBJS = \
diff --git a/CPP/7zip/UI/FileManager/resource.h b/CPP/7zip/UI/FileManager/resource.h
index 98cb4fd..9d605c6 100644
--- a/CPP/7zip/UI/FileManager/resource.h
+++ b/CPP/7zip/UI/FileManager/resource.h
@@ -26,6 +26,14 @@
26#define IDM_SHA1 104 26#define IDM_SHA1 104
27#define IDM_SHA256 105 27#define IDM_SHA256 105
28 28
29
30#define IDM_FILE 500
31#define IDM_EDIT 501
32#define IDM_VIEW 502
33#define IDM_FAVORITES 503
34#define IDM_TOOLS 504
35#define IDM_HELP 505
36
29#define IDM_OPEN 540 37#define IDM_OPEN 540
30#define IDM_OPEN_INSIDE 541 38#define IDM_OPEN_INSIDE 541
31#define IDM_OPEN_OUTSIDE 542 39#define IDM_OPEN_OUTSIDE 542
@@ -90,8 +98,10 @@
90#define IDM_VIEW_TOOLBARS_LARGE_BUTTONS 752 98#define IDM_VIEW_TOOLBARS_LARGE_BUTTONS 752
91#define IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT 753 99#define IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT 753
92 100
101#define IDM_VIEW_TIME_POPUP 760
93#define IDM_VIEW_TIME 761 102#define IDM_VIEW_TIME 761
94 103
104#define IDM_ADD_TO_FAVORITES 800
95#define IDS_BOOKMARK 801 105#define IDS_BOOKMARK 801
96 106
97#define IDM_OPTIONS 900 107#define IDM_OPTIONS 900
diff --git a/CPP/7zip/UI/FileManager/resource.rc b/CPP/7zip/UI/FileManager/resource.rc
index fc2c840..002265a 100644
--- a/CPP/7zip/UI/FileManager/resource.rc
+++ b/CPP/7zip/UI/FileManager/resource.rc
@@ -12,10 +12,27 @@ BEGIN
12// VK_F7, IDM_CREATE_FOLDER, VIRTKEY, NOINVERT 12// VK_F7, IDM_CREATE_FOLDER, VIRTKEY, NOINVERT
13END 13END
14 14
15// for MENUEX:
16// /*
17#define MY_MENUITEM_SEPARATOR MENUITEM "", 0, MFT_SEPARATOR
18#define MY_MFT_MENUBREAK MFT_MENUBREAK
19#define MY_MFT_MENUBARBREAK MFT_MENUBARBREAK
20#define MY_MFS_CHECKED MFT_STRING, MFS_CHECKED
21#define MY_MENUITEM_ID(x) , x
22// */
15 23
16IDM_MENU MENU 24// for MENU:
25/*
26#define MY_MENUITEM_SEPARATOR MENUITEM SEPARATOR
27#define MY_MFT_MENUBREAK MENUBREAK
28#define MY_MFT_MENUBARBREAK MENUBARBREAK
29#define MY_MFS_CHECKED CHECKED
30#define MY_MENUITEM_ID(x)
31*/
32
33IDM_MENU MENUEX
17BEGIN 34BEGIN
18 POPUP "&File" 35 POPUP "&File" MY_MENUITEM_ID(IDM_FILE)
19 BEGIN 36 BEGIN
20 MENUITEM "&Open\tEnter", IDM_OPEN 37 MENUITEM "&Open\tEnter", IDM_OPEN
21 MENUITEM "Open &Inside\tCtrl+PgDn", IDM_OPEN_INSIDE 38 MENUITEM "Open &Inside\tCtrl+PgDn", IDM_OPEN_INSIDE
@@ -24,19 +41,19 @@ BEGIN
24 MENUITEM "Open O&utside\tShift+Enter", IDM_OPEN_OUTSIDE 41 MENUITEM "Open O&utside\tShift+Enter", IDM_OPEN_OUTSIDE
25 MENUITEM "&View\tF3", IDM_FILE_VIEW 42 MENUITEM "&View\tF3", IDM_FILE_VIEW
26 MENUITEM "&Edit\tF4", IDM_FILE_EDIT 43 MENUITEM "&Edit\tF4", IDM_FILE_EDIT
27 MENUITEM SEPARATOR 44 MY_MENUITEM_SEPARATOR
28 MENUITEM "Rena&me\tF2", IDM_RENAME 45 MENUITEM "Rena&me\tF2", IDM_RENAME
29 MENUITEM "&Copy To...\tF5", IDM_COPY_TO 46 MENUITEM "&Copy To...\tF5", IDM_COPY_TO
30 MENUITEM "&Move To...\tF6", IDM_MOVE_TO 47 MENUITEM "&Move To...\tF6", IDM_MOVE_TO
31 MENUITEM "&Delete\tDel", IDM_DELETE 48 MENUITEM "&Delete\tDel", IDM_DELETE
32 MENUITEM SEPARATOR 49 MY_MENUITEM_SEPARATOR
33 MENUITEM "&Split file...", IDM_SPLIT 50 MENUITEM "&Split file...", IDM_SPLIT
34 MENUITEM "Com&bine files...", IDM_COMBINE 51 MENUITEM "Com&bine files...", IDM_COMBINE
35 MENUITEM SEPARATOR 52 MY_MENUITEM_SEPARATOR
36 MENUITEM "P&roperties\tAlt+Enter", IDM_PROPERTIES 53 MENUITEM "P&roperties\tAlt+Enter", IDM_PROPERTIES
37 MENUITEM "Comme&nt...\tCtrl+Z", IDM_COMMENT 54 MENUITEM "Comme&nt...\tCtrl+Z", IDM_COMMENT
38 // MENUITEM "Calculate checksum", IDM_CRC 55 // MENUITEM "Calculate checksum", IDM_CRC
39 POPUP "CRC" 56 POPUP "CRC" MY_MENUITEM_ID(0)
40 BEGIN 57 BEGIN
41 MENUITEM "CRC-32", IDM_CRC32 58 MENUITEM "CRC-32", IDM_CRC32
42 MENUITEM "CRC-64", IDM_CRC64 59 MENUITEM "CRC-64", IDM_CRC64
@@ -45,55 +62,56 @@ BEGIN
45 MENUITEM "*", IDM_HASH_ALL 62 MENUITEM "*", IDM_HASH_ALL
46 END 63 END
47 MENUITEM "Di&ff", IDM_DIFF 64 MENUITEM "Di&ff", IDM_DIFF
48 MENUITEM SEPARATOR 65 MY_MENUITEM_SEPARATOR
49 MENUITEM "Create Folder\tF7", IDM_CREATE_FOLDER 66 MENUITEM "Create Folder\tF7", IDM_CREATE_FOLDER
50 MENUITEM "Create File\tCtrl+N", IDM_CREATE_FILE 67 MENUITEM "Create File\tCtrl+N", IDM_CREATE_FILE
51 MENUITEM SEPARATOR 68 MY_MENUITEM_SEPARATOR
52 MENUITEM "&Link...", IDM_LINK 69 MENUITEM "&Link...", IDM_LINK
53 MENUITEM "&Alternate streams", IDM_ALT_STREAMS 70 MENUITEM "&Alternate streams", IDM_ALT_STREAMS
54 MENUITEM SEPARATOR 71 MY_MENUITEM_SEPARATOR
55 MENUITEM "E&xit\tAlt+F4", IDCLOSE 72 MENUITEM "E&xit\tAlt+F4", IDCLOSE
56 END 73 END
57 POPUP "&Edit" 74 POPUP "&Edit" MY_MENUITEM_ID(IDM_EDIT)
58 BEGIN 75 BEGIN
59 // MENUITEM "Cu&t\tCtrl+X", IDM_EDIT_CUT, GRAYED 76 // MENUITEM "Cu&t\tCtrl+X", IDM_EDIT_CUT, GRAYED
60 // MENUITEM "&Copy\tCtrl+C", IDM_EDIT_COPY, GRAYED 77 // MENUITEM "&Copy\tCtrl+C", IDM_EDIT_COPY, GRAYED
61 // MENUITEM "&Paste\tCtrl+V", IDM_EDIT_PASTE, GRAYED 78 // MENUITEM "&Paste\tCtrl+V", IDM_EDIT_PASTE, GRAYED
62 // MENUITEM SEPARATOR 79 // MY_MENUITEM_SEPARATOR
63 MENUITEM "Select &All\tShift+[Grey +]", IDM_SELECT_ALL 80 MENUITEM "Select &All\tShift+[Grey +]", IDM_SELECT_ALL
64 MENUITEM "Deselect All\tShift+[Grey -]", IDM_DESELECT_ALL 81 MENUITEM "Deselect All\tShift+[Grey -]", IDM_DESELECT_ALL
65 MENUITEM "&Invert Selection\tGrey *", IDM_INVERT_SELECTION 82 MENUITEM "&Invert Selection\tGrey *", IDM_INVERT_SELECTION
66 MENUITEM "Select...\tGrey +", IDM_SELECT 83 MENUITEM "Select...\tGrey +", IDM_SELECT
67 MENUITEM "Deselect...\tGrey -", IDM_DESELECT 84 MENUITEM "Deselect...\tGrey -", IDM_DESELECT
85 MENUITEM "", 0, MY_MFT_MENUBARBREAK
68 MENUITEM "Select by Type\tAlt+[Grey+]", IDM_SELECT_BY_TYPE 86 MENUITEM "Select by Type\tAlt+[Grey+]", IDM_SELECT_BY_TYPE
69 MENUITEM "Deselect by Type\tAlt+[Grey -]", IDM_DESELECT_BY_TYPE 87 MENUITEM "Deselect by Type\tAlt+[Grey -]", IDM_DESELECT_BY_TYPE
70 END 88 END
71 POPUP "&View" 89 POPUP "&View" MY_MENUITEM_ID(IDM_VIEW)
72 BEGIN 90 BEGIN
73 MENUITEM "Lar&ge Icons\tCtrl+1", IDM_VIEW_LARGE_ICONS 91 MENUITEM "Lar&ge Icons\tCtrl+1", IDM_VIEW_LARGE_ICONS
74 MENUITEM "S&mall Icons\tCtrl+2", IDM_VIEW_SMALL_ICONS 92 MENUITEM "S&mall Icons\tCtrl+2", IDM_VIEW_SMALL_ICONS
75 MENUITEM "&List\tCtrl+3", IDM_VIEW_LIST 93 MENUITEM "&List\tCtrl+3", IDM_VIEW_LIST
76 MENUITEM "&Details\tCtrl+4", IDM_VIEW_DETAILS, CHECKED 94 MENUITEM "&Details\tCtrl+4", IDM_VIEW_DETAILS, MY_MFS_CHECKED
77 MENUITEM SEPARATOR 95 MY_MENUITEM_SEPARATOR
78 MENUITEM "Name\tCtrl+F3", IDM_VIEW_ARANGE_BY_NAME 96 MENUITEM "Name\tCtrl+F3", IDM_VIEW_ARANGE_BY_NAME
79 MENUITEM "Type\tCtrl+F4", IDM_VIEW_ARANGE_BY_TYPE 97 MENUITEM "Type\tCtrl+F4", IDM_VIEW_ARANGE_BY_TYPE
80 MENUITEM "Date\tCtrl+F5", IDM_VIEW_ARANGE_BY_DATE 98 MENUITEM "Date\tCtrl+F5", IDM_VIEW_ARANGE_BY_DATE
81 MENUITEM "Size\tCtrl+F6", IDM_VIEW_ARANGE_BY_SIZE 99 MENUITEM "Size\tCtrl+F6", IDM_VIEW_ARANGE_BY_SIZE
82 MENUITEM "Unsorted\tCtrl+F7", IDM_VIEW_ARANGE_NO_SORT 100 MENUITEM "Unsorted\tCtrl+F7", IDM_VIEW_ARANGE_NO_SORT
83 MENUITEM SEPARATOR 101 MY_MENUITEM_SEPARATOR
84 MENUITEM "Flat View", IDM_VIEW_FLAT_VIEW 102 MENUITEM "Flat View", IDM_VIEW_FLAT_VIEW
85 MENUITEM "&2 Panels\tF9", IDM_VIEW_TWO_PANELS 103 MENUITEM "&2 Panels\tF9", IDM_VIEW_TWO_PANELS
86 104
87 POPUP "2017" 105 POPUP "2017" MY_MENUITEM_ID(IDM_VIEW_TIME_POPUP)
88 BEGIN 106 BEGIN
89 MENUITEM "Time", IDM_VIEW_TIME 107 MENUITEM "Time", IDM_VIEW_TIME
90 END 108 END
91 109
92 POPUP "Toolbars" 110 POPUP "Toolbars" MY_MENUITEM_ID(IDM_VIEW_TOOLBARS)
93 BEGIN 111 BEGIN
94 MENUITEM "Archive Toolbar", IDM_VIEW_ARCHIVE_TOOLBAR 112 MENUITEM "Archive Toolbar", IDM_VIEW_ARCHIVE_TOOLBAR
95 MENUITEM "Standard Toolbar", IDM_VIEW_STANDARD_TOOLBAR 113 MENUITEM "Standard Toolbar", IDM_VIEW_STANDARD_TOOLBAR
96 MENUITEM SEPARATOR 114 MY_MENUITEM_SEPARATOR
97 MENUITEM "Large Buttons", IDM_VIEW_TOOLBARS_LARGE_BUTTONS 115 MENUITEM "Large Buttons", IDM_VIEW_TOOLBARS_LARGE_BUTTONS
98 MENUITEM "Show Buttons Text", IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT 116 MENUITEM "Show Buttons Text", IDM_VIEW_TOOLBARS_SHOW_BUTTONS_TEXT
99 END 117 END
@@ -107,29 +125,29 @@ BEGIN
107 // MENUITEM "Show deleted files", IDM_VIEW_SHOW_DELETED 125 // MENUITEM "Show deleted files", IDM_VIEW_SHOW_DELETED
108 126
109 END 127 END
110 POPUP "F&avorites" 128 POPUP "F&avorites" MY_MENUITEM_ID(IDM_FAVORITES)
111 BEGIN 129 BEGIN
112 POPUP "&Add folder to Favorites as" 130 POPUP "&Add folder to Favorites as" MY_MENUITEM_ID(IDM_ADD_TO_FAVORITES)
113 BEGIN 131 BEGIN
114 MENUITEM SEPARATOR 132 MY_MENUITEM_SEPARATOR
115 END 133 END
116 MENUITEM SEPARATOR 134 MY_MENUITEM_SEPARATOR
117 END 135 END
118 POPUP "&Tools" 136 POPUP "&Tools" MY_MENUITEM_ID(IDM_TOOLS)
119 BEGIN 137 BEGIN
120 MENUITEM "&Options...", IDM_OPTIONS 138 MENUITEM "&Options...", IDM_OPTIONS
121 MENUITEM SEPARATOR 139 MY_MENUITEM_SEPARATOR
122 MENUITEM "&Benchmark", IDM_BENCHMARK 140 MENUITEM "&Benchmark", IDM_BENCHMARK
123 #ifdef UNDER_CE 141 #ifdef UNDER_CE
124 MENUITEM "Benchmark 2", IDM_BENCHMARK2 142 MENUITEM "Benchmark 2", IDM_BENCHMARK2
125 #endif 143 #endif
126 #ifndef UNDER_CE 144 #ifndef UNDER_CE
127 END 145 END
128 POPUP "&Help" 146 POPUP "&Help" MY_MENUITEM_ID(IDM_HELP)
129 BEGIN 147 BEGIN
130 MENUITEM "&Contents...\tF1", IDM_HELP_CONTENTS 148 MENUITEM "&Contents...\tF1", IDM_HELP_CONTENTS
131 #endif 149 #endif
132 MENUITEM SEPARATOR 150 MY_MENUITEM_SEPARATOR
133 MENUITEM "&About 7-Zip...", IDM_ABOUT 151 MENUITEM "&About 7-Zip...", IDM_ABOUT
134 END 152 END
135END 153END
@@ -172,7 +190,7 @@ BEGIN
172 IDS_VIRUS "The file looks like a virus (the file name contains long spaces in name)." 190 IDS_VIRUS "The file looks like a virus (the file name contains long spaces in name)."
173 IDS_MESSAGE_UNSUPPORTED_OPERATION_FOR_LONG_PATH_FOLDER "The operation cannot be called from a folder that has a long path." 191 IDS_MESSAGE_UNSUPPORTED_OPERATION_FOR_LONG_PATH_FOLDER "The operation cannot be called from a folder that has a long path."
174 IDS_SELECT_ONE_FILE "You must select one file" 192 IDS_SELECT_ONE_FILE "You must select one file"
175 IDS_SELECT_FILES "You must select one or more files" 193 // IDS_SELECT_FILES "You must select one or more files"
176 IDS_TOO_MANY_ITEMS "Too many items" 194 IDS_TOO_MANY_ITEMS "Too many items"
177 195
178 IDS_COPY "Copy" 196 IDS_COPY "Copy"
diff --git a/CPP/7zip/UI/GUI/7zG.exe.manifest b/CPP/7zip/UI/GUI/7zG.exe.manifest
index 39f516c..ae964d8 100644
--- a/CPP/7zip/UI/GUI/7zG.exe.manifest
+++ b/CPP/7zip/UI/GUI/7zG.exe.manifest
@@ -17,4 +17,7 @@
17 <dpiAware>true</dpiAware> 17 <dpiAware>true</dpiAware>
18 </asmv3:windowsSettings> 18 </asmv3:windowsSettings>
19 </asmv3:application> 19 </asmv3:application>
20<application xmlns="urn:schemas-microsoft-com:asm.v3">
21<windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
22<ws2:longPathAware>true</ws2:longPathAware></windowsSettings></application>
20</assembly> 23</assembly>
diff --git a/CPP/7zip/UI/GUI/BenchmarkDialog.cpp b/CPP/7zip/UI/GUI/BenchmarkDialog.cpp
index 71d28e8..539d689 100644
--- a/CPP/7zip/UI/GUI/BenchmarkDialog.cpp
+++ b/CPP/7zip/UI/GUI/BenchmarkDialog.cpp
@@ -22,9 +22,7 @@
22 22
23#include "../FileManager/DialogSize.h" 23#include "../FileManager/DialogSize.h"
24#include "../FileManager/HelpUtils.h" 24#include "../FileManager/HelpUtils.h"
25#ifdef LANG
26#include "../FileManager/LangUtils.h" 25#include "../FileManager/LangUtils.h"
27#endif
28 26
29#include "../../MyVersion.h" 27#include "../../MyVersion.h"
30 28
@@ -156,7 +154,7 @@ void CSyncData::Init()
156 NeedPrint_Dec_1 = 154 NeedPrint_Dec_1 =
157 NeedPrint_Dec = 155 NeedPrint_Dec =
158 NeedPrint_Tot = false; 156 NeedPrint_Tot = false;
159}; 157}
160 158
161 159
162struct CBenchProgressSync 160struct CBenchProgressSync
@@ -243,7 +241,7 @@ class CBenchmarkDialog;
243struct CThreadBenchmark 241struct CThreadBenchmark
244{ 242{
245 CBenchmarkDialog *BenchmarkDialog; 243 CBenchmarkDialog *BenchmarkDialog;
246 DECL_EXTERNAL_CODECS_LOC_VARS2; 244 DECL_EXTERNAL_CODECS_LOC_VARS_DECL
247 // HRESULT Result; 245 // HRESULT Result;
248 246
249 HRESULT Process(); 247 HRESULT Process();
@@ -290,15 +288,15 @@ class CBenchmarkDialog:
290 Sync.Init(); 288 Sync.Init();
291 } 289 }
292 290
293 virtual bool OnInit(); 291 virtual bool OnInit() Z7_override;
294 virtual bool OnDestroy(); 292 virtual bool OnDestroy() Z7_override;
295 virtual bool OnSize(WPARAM /* wParam */, int xSize, int ySize); 293 virtual bool OnSize(WPARAM /* wParam */, int xSize, int ySize) Z7_override;
296 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 294 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
297 virtual bool OnCommand(int code, int itemID, LPARAM lParam); 295 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override;
298 virtual void OnHelp(); 296 virtual void OnHelp() Z7_override;
299 virtual void OnCancel(); 297 virtual void OnCancel() Z7_override;
300 virtual bool OnTimer(WPARAM timerID, LPARAM callback); 298 virtual bool OnTimer(WPARAM timerID, LPARAM callback) Z7_override;
301 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 299 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
302 300
303 void Disable_Stop_Button(); 301 void Disable_Stop_Button();
304 void OnStopButton(); 302 void OnStopButton();
@@ -315,7 +313,7 @@ class CBenchmarkDialog:
315 UInt32 GetNumberOfThreads(); 313 UInt32 GetNumberOfThreads();
316 size_t OnChangeDictionary(); 314 size_t OnChangeDictionary();
317 315
318 void SetItemText_Number(int itemID, UInt64 val, LPCTSTR post = NULL); 316 void SetItemText_Number(unsigned itemID, UInt64 val, LPCTSTR post = NULL);
319 void Print_MemUsage(UString &s, UInt64 memUsage) const; 317 void Print_MemUsage(UString &s, UInt64 memUsage) const;
320 bool IsMemoryUsageOK(UInt64 memUsage) const 318 bool IsMemoryUsageOK(UInt64 memUsage) const
321 { return memUsage + (1 << 20) <= RamSize_Limit; } 319 { return memUsage + (1 << 20) <= RamSize_Limit; }
@@ -347,17 +345,17 @@ public:
347 TotalMode(false) 345 TotalMode(false)
348 {} 346 {}
349 347
350 ~CBenchmarkDialog(); 348 ~CBenchmarkDialog() Z7_DESTRUCTOR_override;
351 349
352 bool PostMsg_Finish(LPARAM param) 350 bool PostMsg_Finish(WPARAM wparam)
353 { 351 {
354 if ((HWND)*this) 352 if ((HWND)*this)
355 return PostMsg(k_Message_Finished, param); 353 return PostMsg(k_Message_Finished, wparam);
356 // the (HWND)*this is NULL only for some internal code failure 354 // the (HWND)*this is NULL only for some internal code failure
357 return true; 355 return true;
358 } 356 }
359 357
360 INT_PTR Create(HWND wndParent = 0) 358 INT_PTR Create(HWND wndParent = NULL)
361 { 359 {
362 BIG_DIALOG_SIZE(332, 228); 360 BIG_DIALOG_SIZE(332, 228);
363 return CModalDialog::Create(TotalMode ? IDD_BENCH_TOTAL : SIZED_DIALOG(IDD_BENCH), wndParent); 361 return CModalDialog::Create(TotalMode ? IDD_BENCH_TOTAL : SIZED_DIALOG(IDD_BENCH), wndParent);
@@ -385,13 +383,13 @@ public:
385 383
386UString HResultToMessage(HRESULT errorCode); 384UString HResultToMessage(HRESULT errorCode);
387 385
388#ifdef LANG 386#ifdef Z7_LANG
389static const UInt32 kLangIDs[] = 387static const UInt32 kLangIDs[] =
390{ 388{
391 IDT_BENCH_DICTIONARY, 389 IDT_BENCH_DICTIONARY,
392 IDT_BENCH_MEMORY, 390 IDT_BENCH_MEMORY,
393 IDT_BENCH_NUM_THREADS, 391 IDT_BENCH_NUM_THREADS,
394 IDT_BENCH_SPEED, 392 IDT_BENCH_SIZE,
395 IDT_BENCH_RATING_LABEL, 393 IDT_BENCH_RATING_LABEL,
396 IDT_BENCH_USAGE_LABEL, 394 IDT_BENCH_USAGE_LABEL,
397 IDT_BENCH_RPU_LABEL, 395 IDT_BENCH_RPU_LABEL,
@@ -406,9 +404,9 @@ static const UInt32 kLangIDs[] =
406 IDB_RESTART 404 IDB_RESTART
407}; 405};
408 406
409static const UInt32 kLangIDs_Colon[] = 407static const UInt32 kLangIDs_RemoveColon[] =
410{ 408{
411 IDT_BENCH_SIZE 409 IDT_BENCH_SPEED
412}; 410};
413 411
414#endif 412#endif
@@ -439,18 +437,18 @@ static int ComboBox_Add_UInt32(NWindows::NControl::CComboBox &cb, UInt32 v)
439{ 437{
440 TCHAR s[16]; 438 TCHAR s[16];
441 ConvertUInt32ToString(v, s); 439 ConvertUInt32ToString(v, s);
442 int index = (int)cb.AddString(s); 440 const int index = (int)cb.AddString(s);
443 cb.SetItemData(index, v); 441 cb.SetItemData(index, (LPARAM)v);
444 return index; 442 return index;
445} 443}
446 444
447 445
448bool CBenchmarkDialog::OnInit() 446bool CBenchmarkDialog::OnInit()
449{ 447{
450 #ifdef LANG 448 #ifdef Z7_LANG
451 LangSetWindowText(*this, IDD_BENCH); 449 LangSetWindowText(*this, IDD_BENCH);
452 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 450 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
453 // LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); 451 LangSetDlgItems_RemoveColon(*this, kLangIDs_RemoveColon, Z7_ARRAY_SIZE(kLangIDs_RemoveColon));
454 LangSetDlgItemText(*this, IDT_BENCH_CURRENT2, IDT_BENCH_CURRENT); 452 LangSetDlgItemText(*this, IDT_BENCH_CURRENT2, IDT_BENCH_CURRENT);
455 LangSetDlgItemText(*this, IDT_BENCH_RESULTING2, IDT_BENCH_RESULTING); 453 LangSetDlgItemText(*this, IDT_BENCH_RESULTING2, IDT_BENCH_RESULTING);
456 #endif 454 #endif
@@ -486,7 +484,7 @@ bool CBenchmarkDialog::OnInit()
486 NSystem::CProcessAffinity threadsInfo; 484 NSystem::CProcessAffinity threadsInfo;
487 threadsInfo.InitST(); 485 threadsInfo.InitST();
488 486
489 #ifndef _7ZIP_ST 487 #ifndef Z7_ST
490 if (threadsInfo.Get() && threadsInfo.processAffinityMask != 0) 488 if (threadsInfo.Get() && threadsInfo.processAffinityMask != 0)
491 numCPUs = threadsInfo.GetNumProcessThreads(); 489 numCPUs = threadsInfo.GetNumProcessThreads();
492 else 490 else
@@ -531,7 +529,7 @@ bool CBenchmarkDialog::OnInit()
531 if (numThreads == (UInt32)(Int32)-1) 529 if (numThreads == (UInt32)(Int32)-1)
532 numThreads = numCPUs; 530 numThreads = numCPUs;
533 if (numThreads > 1) 531 if (numThreads > 1)
534 numThreads &= ~1; 532 numThreads &= ~(UInt32)1;
535 const UInt32 kNumThreadsMax = (1 << 12); 533 const UInt32 kNumThreadsMax = (1 << 12);
536 if (numThreads > kNumThreadsMax) 534 if (numThreads > kNumThreadsMax)
537 numThreads = kNumThreadsMax; 535 numThreads = kNumThreadsMax;
@@ -603,7 +601,7 @@ bool CBenchmarkDialog::OnInit()
603 ConvertUInt32ToString(d, s); 601 ConvertUInt32ToString(d, s);
604 lstrcat(s, post); 602 lstrcat(s, post);
605 const int index = (int)m_Dictionary.AddString(s); 603 const int index = (int)m_Dictionary.AddString(s);
606 m_Dictionary.SetItemData(index, dict); 604 m_Dictionary.SetItemData(index, (LPARAM)dict);
607 if (dict <= Sync.DictSize) 605 if (dict <= Sync.DictSize)
608 cur = index; 606 cur = index;
609 if (dict >= kMaxDicSize) 607 if (dict >= kMaxDicSize)
@@ -711,18 +709,18 @@ UInt32 CBenchmarkDialog::GetNumberOfThreads()
711 s[0] = (wchar_t)('0' + (val) / 100); \ 709 s[0] = (wchar_t)('0' + (val) / 100); \
712 s[1] = (wchar_t)('0' + (val) % 100 / 10); \ 710 s[1] = (wchar_t)('0' + (val) % 100 / 10); \
713 s[2] = (wchar_t)('0' + (val) % 10); \ 711 s[2] = (wchar_t)('0' + (val) % 10); \
714 s[3] = 0; } 712 s += 3; s[0] = 0; }
715 713
716static void NumberToDot3(UInt64 val, WCHAR *s) 714static WCHAR *NumberToDot3(UInt64 val, WCHAR *s)
717{ 715{
718 ConvertUInt64ToString(val / 1000, s); 716 s = ConvertUInt64ToString(val / 1000, s);
719 const UInt32 rem = (UInt32)(val % 1000); 717 const UInt32 rem = (UInt32)(val % 1000);
720 s += MyStringLen(s);
721 *s++ = '.'; 718 *s++ = '.';
722 UINT_TO_STR_3(s, rem); 719 UINT_TO_STR_3(s, rem)
720 return s;
723} 721}
724 722
725void CBenchmarkDialog::SetItemText_Number(int itemID, UInt64 val, LPCTSTR post) 723void CBenchmarkDialog::SetItemText_Number(unsigned itemID, UInt64 val, LPCTSTR post)
726{ 724{
727 TCHAR s[64]; 725 TCHAR s[64];
728 ConvertUInt64ToString(val, s); 726 ConvertUInt64ToString(val, s);
@@ -758,7 +756,7 @@ size_t CBenchmarkDialog::OnChangeDictionary()
758 UString s; 756 UString s;
759 Print_MemUsage(s, memUsage); 757 Print_MemUsage(s, memUsage);
760 758
761 #ifdef _7ZIP_LARGE_PAGES 759 #ifdef Z7_LARGE_PAGES
762 { 760 {
763 AString s2; 761 AString s2;
764 Add_LargePages_String(s2); 762 Add_LargePages_String(s2);
@@ -875,7 +873,7 @@ void CBenchmarkDialog::StartBenchmark()
875 const UInt32 numThreads = GetNumberOfThreads(); 873 const UInt32 numThreads = GetNumberOfThreads();
876 const UInt32 numPasses = (UInt32)m_NumPasses.GetItemData_of_CurSel(); 874 const UInt32 numPasses = (UInt32)m_NumPasses.GetItemData_of_CurSel();
877 875
878 for (unsigned i = 0; i < ARRAY_SIZE(g_IDs); i++) 876 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_IDs); i++)
879 SetItemText(g_IDs[i], kProcessingString); 877 SetItemText(g_IDs[i], kProcessingString);
880 878
881 SetItemText_Empty(IDT_BENCH_LOG); 879 SetItemText_Empty(IDT_BENCH_LOG);
@@ -916,7 +914,7 @@ void CBenchmarkDialog::StartBenchmark()
916 { 914 {
917 MyKillTimer(); 915 MyKillTimer();
918 MessageBoxError_Status(L"Can't create thread"); 916 MessageBoxError_Status(L"Can't create thread");
919 }; 917 }
920 return; 918 return;
921} 919}
922 920
@@ -1000,19 +998,17 @@ void CBenchmarkDialog::PrintTime()
1000 998
1001 WCHAR s[64]; 999 WCHAR s[64];
1002 1000
1003 // GetTimeString(elapsedTime / 1000, s); 1001 WCHAR *p = ConvertUInt32ToString(elapsedTime / 1000, s);
1004 ConvertUInt32ToString(elapsedTime / 1000, s);
1005 1002
1006 if (_finishTime_WasSet) 1003 if (_finishTime_WasSet)
1007 { 1004 {
1008 WCHAR *p = s + MyStringLen(s);
1009 *p++ = '.'; 1005 *p++ = '.';
1010 UINT_TO_STR_3(p, elapsedTime % 1000); 1006 UINT_TO_STR_3(p, elapsedTime % 1000)
1011 } 1007 }
1012 1008
1013 // NumberToDot3((UInt64)elapsedTime, s); 1009 // p = NumberToDot3((UInt64)elapsedTime, s);
1014 1010
1015 wcscat(s, L" s"); 1011 MyStringCopy(p, L" s");
1016 1012
1017 // if (WasStopped_in_GUI) wcscat(s, L" X"); // for debug 1013 // if (WasStopped_in_GUI) wcscat(s, L" X"); // for debug
1018 1014
@@ -1051,7 +1047,7 @@ static UInt32 GetRating(const CTotalBenchRes &info)
1051 if (rating32 != rating64) 1047 if (rating32 != rating64)
1052 rating32 = (UInt32)(Int32)-1; 1048 rating32 = (UInt32)(Int32)-1;
1053 return rating32; 1049 return rating32;
1054}; 1050}
1055 1051
1056 1052
1057static void AddUsageString(UString &s, const CTotalBenchRes &info) 1053static void AddUsageString(UString &s, const CTotalBenchRes &info)
@@ -1088,7 +1084,7 @@ static void AddRatingString(UString &s, const CTotalBenchRes &info)
1088 // s += " "; 1084 // s += " ";
1089 // s.Add_UInt32(GetRating(info)); 1085 // s.Add_UInt32(GetRating(info));
1090 Add_Dot3String(s, GetRating(info)); 1086 Add_Dot3String(s, GetRating(info));
1091}; 1087}
1092 1088
1093 1089
1094static void AddRatingsLine(UString &s, const CTotalBenchRes &enc, const CTotalBenchRes &dec 1090static void AddRatingsLine(UString &s, const CTotalBenchRes &enc, const CTotalBenchRes &dec
@@ -1127,8 +1123,7 @@ void CBenchmarkDialog::PrintRating(UInt64 rating, UINT controlID)
1127{ 1123{
1128 // SetItemText_Number(controlID, GetMips(rating), kMIPS); 1124 // SetItemText_Number(controlID, GetMips(rating), kMIPS);
1129 WCHAR s[64]; 1125 WCHAR s[64];
1130 NumberToDot3(GetMips(rating), s); 1126 MyStringCopy(NumberToDot3(GetMips(rating), s), L" GIPS");
1131 MyStringCat(s, L" GIPS");
1132 SetItemText(controlID, s); 1127 SetItemText(controlID, s);
1133} 1128}
1134 1129
@@ -1391,7 +1386,7 @@ void CBenchmarkDialog::UpdateGui()
1391} 1386}
1392 1387
1393 1388
1394bool CBenchmarkDialog::OnCommand(int code, int itemID, LPARAM lParam) 1389bool CBenchmarkDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
1395{ 1390{
1396 if (code == CBN_SELCHANGE && 1391 if (code == CBN_SELCHANGE &&
1397 (itemID == IDC_BENCH_DICTIONARY || 1392 (itemID == IDC_BENCH_DICTIONARY ||
@@ -1405,7 +1400,7 @@ bool CBenchmarkDialog::OnCommand(int code, int itemID, LPARAM lParam)
1405} 1400}
1406 1401
1407 1402
1408bool CBenchmarkDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 1403bool CBenchmarkDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
1409{ 1404{
1410 switch (buttonID) 1405 switch (buttonID)
1411 { 1406 {
@@ -1425,14 +1420,14 @@ bool CBenchmarkDialog::OnButtonClicked(int buttonID, HWND buttonHWND)
1425 1420
1426// ---------- Benchmark Thread ---------- 1421// ---------- Benchmark Thread ----------
1427 1422
1428struct CBenchCallback: public IBenchCallback 1423struct CBenchCallback Z7_final: public IBenchCallback
1429{ 1424{
1430 UInt64 dictionarySize; 1425 UInt64 dictionarySize;
1431 CBenchProgressSync *Sync; 1426 CBenchProgressSync *Sync;
1432 CBenchmarkDialog *BenchmarkDialog; 1427 CBenchmarkDialog *BenchmarkDialog;
1433 1428
1434 HRESULT SetEncodeResult(const CBenchInfo &info, bool final); 1429 HRESULT SetEncodeResult(const CBenchInfo &info, bool final) Z7_override;
1435 HRESULT SetDecodeResult(const CBenchInfo &info, bool final); 1430 HRESULT SetDecodeResult(const CBenchInfo &info, bool final) Z7_override;
1436}; 1431};
1437 1432
1438HRESULT CBenchCallback::SetEncodeResult(const CBenchInfo &info, bool final) 1433HRESULT CBenchCallback::SetEncodeResult(const CBenchInfo &info, bool final)
@@ -1494,14 +1489,14 @@ HRESULT CBenchCallback::SetDecodeResult(const CBenchInfo &info, bool final)
1494} 1489}
1495 1490
1496 1491
1497struct CBenchCallback2: public IBenchPrintCallback 1492struct CBenchCallback2 Z7_final: public IBenchPrintCallback
1498{ 1493{
1499 CBenchProgressSync *Sync; 1494 CBenchProgressSync *Sync;
1500 bool TotalMode; 1495 bool TotalMode;
1501 1496
1502 void Print(const char *s); 1497 void Print(const char *s) Z7_override;
1503 void NewLine(); 1498 void NewLine() Z7_override;
1504 HRESULT CheckBreak(); 1499 HRESULT CheckBreak() Z7_override;
1505}; 1500};
1506 1501
1507void CBenchCallback2::Print(const char *s) 1502void CBenchCallback2::Print(const char *s)
@@ -1528,12 +1523,12 @@ HRESULT CBenchCallback2::CheckBreak()
1528 1523
1529 1524
1530 1525
1531struct CFreqCallback: public IBenchFreqCallback 1526struct CFreqCallback Z7_final: public IBenchFreqCallback
1532{ 1527{
1533 CBenchmarkDialog *BenchmarkDialog; 1528 CBenchmarkDialog *BenchmarkDialog;
1534 1529
1535 virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage); 1530 virtual HRESULT AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) Z7_override;
1536 virtual HRESULT FreqsFinished(unsigned numThreads); 1531 virtual HRESULT FreqsFinished(unsigned numThreads) Z7_override;
1537}; 1532};
1538 1533
1539HRESULT CFreqCallback::AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage) 1534HRESULT CFreqCallback::AddCpuFreq(unsigned numThreads, UInt64 freq, UInt64 usage)
@@ -1839,7 +1834,7 @@ HRESULT Benchmark(
1839 COneMethodInfo method; 1834 COneMethodInfo method;
1840 1835
1841 UInt32 numCPUs = 1; 1836 UInt32 numCPUs = 1;
1842 #ifndef _7ZIP_ST 1837 #ifndef Z7_ST
1843 numCPUs = NSystem::GetNumberOfProcessors(); 1838 numCPUs = NSystem::GetNumberOfProcessors();
1844 #endif 1839 #endif
1845 UInt32 numThreads = numCPUs; 1840 UInt32 numThreads = numCPUs;
@@ -1860,8 +1855,8 @@ HRESULT Benchmark(
1860 ParseNumberString(prop.Value, propVariant); 1855 ParseNumberString(prop.Value, propVariant);
1861 if (name.IsPrefixedBy(L"mt")) 1856 if (name.IsPrefixedBy(L"mt"))
1862 { 1857 {
1863 #ifndef _7ZIP_ST 1858 #ifndef Z7_ST
1864 RINOK(ParseMtProp(name.Ptr(2), propVariant, numCPUs, numThreads)); 1859 RINOK(ParseMtProp(name.Ptr(2), propVariant, numCPUs, numThreads))
1865 if (numThreads != numCPUs) 1860 if (numThreads != numCPUs)
1866 bd.Sync.NumThreads = numThreads; 1861 bd.Sync.NumThreads = numThreads;
1867 #endif 1862 #endif
@@ -1893,14 +1888,14 @@ HRESULT Benchmark(
1893 if (method.Get_DicSize(dict)) 1888 if (method.Get_DicSize(dict))
1894 bd.Sync.DictSize = dict; 1889 bd.Sync.DictSize = dict;
1895 } 1890 }
1896 bd.Sync.Level = method.GetLevel(); 1891 bd.Sync.Level = (int)method.GetLevel();
1897 1892
1898 // Dummy(1000 * 1000 * 1); 1893 // Dummy(1000 * 1000 * 1);
1899 1894
1900 { 1895 {
1901 CThreadBenchmark &benchmarker = bd._threadBenchmark; 1896 CThreadBenchmark &benchmarker = bd._threadBenchmark;
1902 #ifdef EXTERNAL_CODECS 1897 #ifdef Z7_EXTERNAL_CODECS
1903 benchmarker.__externalCodecs = __externalCodecs; 1898 benchmarker._externalCodecs = _externalCodecs;
1904 #endif 1899 #endif
1905 benchmarker.BenchmarkDialog = &bd; 1900 benchmarker.BenchmarkDialog = &bd;
1906 } 1901 }
diff --git a/CPP/7zip/UI/GUI/BenchmarkDialog.h b/CPP/7zip/UI/GUI/BenchmarkDialog.h
index a280592..63c6ded 100644
--- a/CPP/7zip/UI/GUI/BenchmarkDialog.h
+++ b/CPP/7zip/UI/GUI/BenchmarkDialog.h
@@ -1,7 +1,7 @@
1// BenchmarkDialog.h 1// BenchmarkDialog.h
2 2
3#ifndef __BENCHMARK_DIALOG_H 3#ifndef ZIP7_INC_BENCHMARK_DIALOG_H
4#define __BENCHMARK_DIALOG_H 4#define ZIP7_INC_BENCHMARK_DIALOG_H
5 5
6#include "../../Common/CreateCoder.h" 6#include "../../Common/CreateCoder.h"
7#include "../../UI/Common/Property.h" 7#include "../../UI/Common/Property.h"
diff --git a/CPP/7zip/UI/GUI/CompressDialog.cpp b/CPP/7zip/UI/GUI/CompressDialog.cpp
index b85ae1e..c2aee6c 100644
--- a/CPP/7zip/UI/GUI/CompressDialog.cpp
+++ b/CPP/7zip/UI/GUI/CompressDialog.cpp
@@ -29,14 +29,15 @@
29extern bool g_IsNT; 29extern bool g_IsNT;
30#endif 30#endif
31 31
32#ifdef LANG
33#include "../FileManager/LangUtils.h" 32#include "../FileManager/LangUtils.h"
34#endif
35 33
36#include "CompressDialogRes.h" 34#include "CompressDialogRes.h"
37#include "ExtractRes.h" 35#include "ExtractRes.h"
36#include "resource2.h"
37
38// #define PRINT_PARAMS
38 39
39#ifdef LANG 40#ifdef Z7_LANG
40 41
41// #define IDS_OPTIONS 2100 42// #define IDS_OPTIONS 2100
42 43
@@ -88,6 +89,21 @@ static const UInt32 kSolidLog_FullSolid = 64;
88 89
89static const UInt32 kLzmaMaxDictSize = (UInt32)15 << 28; 90static const UInt32 kLzmaMaxDictSize = (UInt32)15 << 28;
90 91
92static const UINT k_Message_ArcChanged = WM_APP + 1;
93
94/*
95static const UInt32 kZstd_MAX_DictSize = (UInt32)1 << MY_ZSTD_WINDOWLOG_MAX;
96*/
97
98/* The top value for windowLog_Chain:
99 (MY_ZSTD_CHAINLOG_MAX - 1): in BT mode
100 (MY_ZSTD_CHAINLOG_MAX) : in non-BT mode. But such big value is useless in most cases.
101 So we always reduce top value to (MY_ZSTD_CHAINLOG_MAX - 1) */
102/*
103static const unsigned kMaxDictChain = MY_ZSTD_CHAINLOG_MAX - 1;
104static const UInt32 kZstd_MAX_DictSize_Chain = (UInt32)1 << kMaxDictChain;
105*/
106
91static LPCSTR const kExeExt = ".exe"; 107static LPCSTR const kExeExt = ".exe";
92 108
93static const UInt32 g_Levels[] = 109static const UInt32 g_Levels[] =
@@ -114,6 +130,7 @@ enum EMethodID
114 kDeflate, 130 kDeflate,
115 kDeflate64, 131 kDeflate64,
116 kPPMdZip, 132 kPPMdZip,
133 // kZSTD,
117 kSha256, 134 kSha256,
118 kSha1, 135 kSha1,
119 kCrc32, 136 kCrc32,
@@ -132,6 +149,7 @@ static LPCSTR const kMethodsNames[] =
132 , "Deflate" 149 , "Deflate"
133 , "Deflate64" 150 , "Deflate64"
134 , "PPMd" 151 , "PPMd"
152 // , "ZSTD"
135 , "SHA256" 153 , "SHA256"
136 , "SHA1" 154 , "SHA1"
137 , "CRC32" 155 , "CRC32"
@@ -148,6 +166,7 @@ static const EMethodID g_7zMethods[] =
148 kBZip2 166 kBZip2
149 , kDeflate 167 , kDeflate
150 , kDeflate64 168 , kDeflate64
169 // , kZSTD
151 , kCopy 170 , kCopy
152}; 171};
153 172
@@ -166,6 +185,7 @@ static const EMethodID g_ZipMethods[] =
166 kBZip2, 185 kBZip2,
167 kLZMA, 186 kLZMA,
168 kPPMdZip 187 kPPMdZip
188 // , kZSTD
169}; 189};
170 190
171static const EMethodID g_GZipMethods[] = 191static const EMethodID g_GZipMethods[] =
@@ -183,6 +203,13 @@ static const EMethodID g_XzMethods[] =
183 kLZMA2 203 kLZMA2
184}; 204};
185 205
206/*
207static const EMethodID g_ZstdMethods[] =
208{
209 kZSTD
210};
211*/
212
186static const EMethodID g_SwfcMethods[] = 213static const EMethodID g_SwfcMethods[] =
187{ 214{
188 kDeflate 215 kDeflate
@@ -236,7 +263,7 @@ struct CFormatInfo
236 bool SFX_() const { return (Flags & kFF_SFX) != 0; } 263 bool SFX_() const { return (Flags & kFF_SFX) != 0; }
237}; 264};
238 265
239#define METHODS_PAIR(x) ARRAY_SIZE(x), x 266#define METHODS_PAIR(x) Z7_ARRAY_SIZE(x), x
240 267
241static const CFormatInfo g_Formats[] = 268static const CFormatInfo g_Formats[] =
242{ 269{
@@ -282,6 +309,17 @@ static const CFormatInfo g_Formats[] =
282 METHODS_PAIR(g_XzMethods), 309 METHODS_PAIR(g_XzMethods),
283 kFF_Solid | kFF_MultiThread | kFF_MemUse 310 kFF_Solid | kFF_MultiThread | kFF_MemUse
284 }, 311 },
312 /*
313 {
314 "zstd",
315 // (1 << (MY_ZSTD_LEVEL_MAX + 1)) - 1,
316 (1 << (9 + 1)) - 1,
317 METHODS_PAIR(g_ZstdMethods),
318 // kFF_Solid |
319 kFF_MultiThread
320 | kFF_MemUse
321 },
322 */
285 { 323 {
286 "Swfc", 324 "Swfc",
287 (1 << 1) | (1 << 3) | (1 << 5) | (1 << 7) | (1 << 9), 325 (1 << 1) | (1 << 3) | (1 << 5) | (1 << 7) | (1 << 9),
@@ -312,7 +350,7 @@ static const CFormatInfo g_Formats[] =
312 350
313static bool IsMethodSupportedBySfx(int methodID) 351static bool IsMethodSupportedBySfx(int methodID)
314{ 352{
315 for (unsigned i = 0; i < ARRAY_SIZE(g_7zSfxMethods); i++) 353 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_7zSfxMethods); i++)
316 if (methodID == g_7zSfxMethods[i]) 354 if (methodID == g_7zSfxMethods[i])
317 return true; 355 return true;
318 return false; 356 return false;
@@ -370,10 +408,10 @@ void CCompressDialog::SetMethods(const CObjectVector<CCodecInfoUser> &userCodecs
370 || c.NumStreams != 1) 408 || c.NumStreams != 1)
371 continue; 409 continue;
372 unsigned k; 410 unsigned k;
373 for (k = 0; k < ARRAY_SIZE(g_7zMethods); k++) 411 for (k = 0; k < Z7_ARRAY_SIZE(g_7zMethods); k++)
374 if (c.Name.IsEqualTo_Ascii_NoCase(kMethodsNames[g_7zMethods[k]])) 412 if (c.Name.IsEqualTo_Ascii_NoCase(kMethodsNames[g_7zMethods[k]]))
375 break; 413 break;
376 if (k != ARRAY_SIZE(g_7zMethods)) 414 if (k != Z7_ARRAY_SIZE(g_7zMethods))
377 continue; 415 continue;
378 ExternalMethods.Add(c.Name); 416 ExternalMethods.Add(c.Name);
379 } 417 }
@@ -383,9 +421,9 @@ void CCompressDialog::SetMethods(const CObjectVector<CCodecInfoUser> &userCodecs
383 421
384bool CCompressDialog::OnInit() 422bool CCompressDialog::OnInit()
385{ 423{
386 #ifdef LANG 424 #ifdef Z7_LANG
387 LangSetWindowText(*this, IDD_COMPRESS); 425 LangSetWindowText(*this, IDD_COMPRESS);
388 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 426 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
389 // LangSetDlgItemText(*this, IDB_COMPRESS_OPTIONS, IDS_OPTIONS); // IDG_COMPRESS_OPTIONS 427 // LangSetDlgItemText(*this, IDB_COMPRESS_OPTIONS, IDS_OPTIONS); // IDG_COMPRESS_OPTIONS
390 #endif 428 #endif
391 429
@@ -420,10 +458,21 @@ bool CCompressDialog::OnInit()
420 _default_encryptionMethod_Index = -1; 458 _default_encryptionMethod_Index = -1;
421 459
422 m_ArchivePath.Attach(GetItem(IDC_COMPRESS_ARCHIVE)); 460 m_ArchivePath.Attach(GetItem(IDC_COMPRESS_ARCHIVE));
423 m_Format.Attach(GetItem(IDC_COMPRESS_FORMAT)); 461 m_Format.Attach(GetItem(IDC_COMPRESS_FORMAT)); // that combo has CBS_SORT style in resources
424 m_Level.Attach(GetItem(IDC_COMPRESS_LEVEL)); 462 m_Level.Attach(GetItem(IDC_COMPRESS_LEVEL));
425 m_Method.Attach(GetItem(IDC_COMPRESS_METHOD)); 463 m_Method.Attach(GetItem(IDC_COMPRESS_METHOD));
426 m_Dictionary.Attach(GetItem(IDC_COMPRESS_DICTIONARY)); 464 m_Dictionary.Attach(GetItem(IDC_COMPRESS_DICTIONARY));
465
466 /*
467 {
468 RECT r;
469 GetClientRectOfItem(IDC_COMPRESS_DICTIONARY, r);
470 _dictionaryCombo_left = r.left;
471 }
472 */
473 _dictionaryCombo_left = 0; // 230;
474
475 // m_Dictionary_Chain.Attach(GetItem(IDC_COMPRESS_DICTIONARY2));
427 m_Order.Attach(GetItem(IDC_COMPRESS_ORDER)); 476 m_Order.Attach(GetItem(IDC_COMPRESS_ORDER));
428 m_Solid.Attach(GetItem(IDC_COMPRESS_SOLID)); 477 m_Solid.Attach(GetItem(IDC_COMPRESS_SOLID));
429 m_NumThreads.Attach(GetItem(IDC_COMPRESS_THREADS)); 478 m_NumThreads.Attach(GetItem(IDC_COMPRESS_THREADS));
@@ -444,13 +493,13 @@ bool CCompressDialog::OnInit()
444 UpdatePasswordControl(); 493 UpdatePasswordControl();
445 494
446 { 495 {
447 bool needSetMain = (Info.FormatIndex < 0); 496 const bool needSetMain = (Info.FormatIndex < 0);
448 FOR_VECTOR(i, ArcIndices) 497 FOR_VECTOR(i, ArcIndices)
449 { 498 {
450 unsigned arcIndex = ArcIndices[i]; 499 const unsigned arcIndex = ArcIndices[i];
451 const CArcInfoEx &ai = (*ArcFormats)[arcIndex]; 500 const CArcInfoEx &ai = (*ArcFormats)[arcIndex];
452 int index = (int)m_Format.AddString(ai.Name); 501 const int index = (int)m_Format.AddString(ai.Name);
453 m_Format.SetItemData(index, arcIndex); 502 m_Format.SetItemData(index, (LPARAM)arcIndex);
454 if (!needSetMain) 503 if (!needSetMain)
455 { 504 {
456 if (Info.FormatIndex == (int)arcIndex) 505 if (Info.FormatIndex == (int)arcIndex)
@@ -460,7 +509,7 @@ bool CCompressDialog::OnInit()
460 if (i == 0 || ai.Name.IsEqualTo_NoCase(m_RegistryInfo.ArcType)) 509 if (i == 0 || ai.Name.IsEqualTo_NoCase(m_RegistryInfo.ArcType))
461 { 510 {
462 m_Format.SetCurSel(index); 511 m_Format.SetCurSel(index);
463 Info.FormatIndex = arcIndex; 512 Info.FormatIndex = (int)arcIndex;
464 } 513 }
465 } 514 }
466 } 515 }
@@ -477,10 +526,10 @@ bool CCompressDialog::OnInit()
477 for (unsigned i = 0; i < m_RegistryInfo.ArcPaths.Size() && i < kHistorySize; i++) 526 for (unsigned i = 0; i < m_RegistryInfo.ArcPaths.Size() && i < kHistorySize; i++)
478 m_ArchivePath.AddString(m_RegistryInfo.ArcPaths[i]); 527 m_ArchivePath.AddString(m_RegistryInfo.ArcPaths[i]);
479 528
480 AddComboItems(m_UpdateMode, k_UpdateMode_IDs, ARRAY_SIZE(k_UpdateMode_IDs), 529 AddComboItems(m_UpdateMode, k_UpdateMode_IDs, Z7_ARRAY_SIZE(k_UpdateMode_IDs),
481 k_UpdateMode_Vals, Info.UpdateMode); 530 k_UpdateMode_Vals, Info.UpdateMode);
482 531
483 AddComboItems(m_PathMode, k_PathMode_IDs, ARRAY_SIZE(k_PathMode_IDs), 532 AddComboItems(m_PathMode, k_PathMode_IDs, Z7_ARRAY_SIZE(k_PathMode_IDs),
484 k_PathMode_Vals, Info.PathMode); 533 k_PathMode_Vals, Info.PathMode);
485 534
486 535
@@ -518,10 +567,10 @@ namespace NCompressDialog
518 567
519void CCompressDialog::UpdatePasswordControl() 568void CCompressDialog::UpdatePasswordControl()
520{ 569{
521 bool showPassword = IsShowPasswordChecked(); 570 const bool showPassword = IsShowPasswordChecked();
522 TCHAR c = showPassword ? (TCHAR)0: TEXT('*'); 571 const TCHAR c = showPassword ? (TCHAR)0: TEXT('*');
523 _password1Control.SetPasswordChar(c); 572 _password1Control.SetPasswordChar((WPARAM)c);
524 _password2Control.SetPasswordChar(c); 573 _password2Control.SetPasswordChar((WPARAM)c);
525 UString password; 574 UString password;
526 _password1Control.GetText(password); 575 _password1Control.GetText(password);
527 _password1Control.SetText(password); 576 _password1Control.SetText(password);
@@ -532,7 +581,7 @@ void CCompressDialog::UpdatePasswordControl()
532 _password2Control.Show_Bool(!showPassword); 581 _password2Control.Show_Bool(!showPassword);
533} 582}
534 583
535bool CCompressDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 584bool CCompressDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
536{ 585{
537 switch (buttonID) 586 switch (buttonID)
538 { 587 {
@@ -703,13 +752,13 @@ void CCompressDialog::FormatChanged(bool isChanged)
703 752
704bool CCompressDialog::IsSFX() 753bool CCompressDialog::IsSFX()
705{ 754{
706 CWindow sfxButton = GetItem(IDX_COMPRESS_SFX); 755 return IsWindowEnabled(GetItem(IDX_COMPRESS_SFX))
707 return sfxButton.IsEnabled() && IsButtonCheckedBool(IDX_COMPRESS_SFX); 756 && IsButtonCheckedBool(IDX_COMPRESS_SFX);
708} 757}
709 758
710static int GetExtDotPos(const UString &s) 759static int GetExtDotPos(const UString &s)
711{ 760{
712 int dotPos = s.ReverseFind_Dot(); 761 const int dotPos = s.ReverseFind_Dot();
713 if (dotPos > s.ReverseFind_PathSepar() + 1) 762 if (dotPos > s.ReverseFind_PathSepar() + 1)
714 return dotPos; 763 return dotPos;
715 return -1; 764 return -1;
@@ -719,7 +768,7 @@ void CCompressDialog::OnButtonSFX()
719{ 768{
720 UString fileName; 769 UString fileName;
721 m_ArchivePath.GetText(fileName); 770 m_ArchivePath.GetText(fileName);
722 int dotPos = GetExtDotPos(fileName); 771 const int dotPos = GetExtDotPos(fileName);
723 if (IsSFX()) 772 if (IsSFX())
724 { 773 {
725 if (dotPos >= 0) 774 if (dotPos >= 0)
@@ -731,7 +780,7 @@ void CCompressDialog::OnButtonSFX()
731 { 780 {
732 if (dotPos >= 0) 781 if (dotPos >= 0)
733 { 782 {
734 UString ext = fileName.Ptr(dotPos); 783 const UString ext = fileName.Ptr(dotPos);
735 if (ext.IsEqualTo_Ascii_NoCase(kExeExt)) 784 if (ext.IsEqualTo_Ascii_NoCase(kExeExt))
736 { 785 {
737 fileName.DeleteFrom(dotPos); 786 fileName.DeleteFrom(dotPos);
@@ -744,36 +793,38 @@ void CCompressDialog::OnButtonSFX()
744 // CheckVolumeEnable(); 793 // CheckVolumeEnable();
745} 794}
746 795
747bool CCompressDialog::GetFinalPath_Smart(UString &resPath) 796
797bool CCompressDialog::GetFinalPath_Smart(UString &resPath) const
748{ 798{
799 resPath.Empty();
749 UString name; 800 UString name;
750 m_ArchivePath.GetText(name); 801 m_ArchivePath.GetText(name);
751 name.Trim(); 802 name.Trim();
752 UString tempPath = name; 803 FString fullPath;
753 if (!IsAbsolutePath(name)) 804 UString dirPrefx = DirPrefix;
754 { 805 if (dirPrefx.IsEmpty())
755 UString newDirPrefix = DirPrefix; 806 dirPrefx = StartDirPrefix;
756 if (newDirPrefix.IsEmpty()) 807 const bool res = !dirPrefx.IsEmpty() ?
757 newDirPrefix = StartDirPrefix; 808 NName::GetFullPath(us2fs(dirPrefx), us2fs(name), fullPath):
758 FString resultF; 809 NName::GetFullPath( us2fs(name), fullPath);
759 if (!MyGetFullPathName(us2fs(newDirPrefix + name), resultF)) 810 if (res)
760 return false; 811 resPath = fs2us(fullPath);
761 tempPath = fs2us(resultF); 812 return res;
762 } 813}
763 if (!SetArcPathFields(tempPath, name, false)) 814
764 return false; 815
765 FString resultF; 816bool CCompressDialog::SetArcPathFields(const UString &path)
766 if (!MyGetFullPathName(us2fs(DirPrefix + name), resultF)) 817{
767 return false; 818 UString name;
768 resPath = fs2us(resultF); 819 return SetArcPathFields(path, name, true); // always
769 return true;
770} 820}
771 821
822
772bool CCompressDialog::SetArcPathFields(const UString &path, UString &name, bool always) 823bool CCompressDialog::SetArcPathFields(const UString &path, UString &name, bool always)
773{ 824{
774 FString resDirPrefix; 825 FString resDirPrefix;
775 FString resFileName; 826 FString resFileName;
776 bool res = GetFullPathAndSplit(us2fs(path), resDirPrefix, resFileName); 827 const bool res = GetFullPathAndSplit(us2fs(path), resDirPrefix, resFileName);
777 if (res) 828 if (res)
778 { 829 {
779 DirPrefix = fs2us(resDirPrefix); 830 DirPrefix = fs2us(resDirPrefix);
@@ -791,8 +842,26 @@ bool CCompressDialog::SetArcPathFields(const UString &path, UString &name, bool
791 return res; 842 return res;
792} 843}
793 844
845
794static const wchar_t * const k_IncorrectPathMessage = L"Incorrect archive path"; 846static const wchar_t * const k_IncorrectPathMessage = L"Incorrect archive path";
795 847
848static void AddFilter(CObjectVector<CBrowseFilterInfo> &filters,
849 const UString &description, const UString &ext)
850{
851 CBrowseFilterInfo &f = filters.AddNew();
852 UString mask ("*.");
853 mask += ext;
854 f.Masks.Add(mask);
855 f.Description = description;
856 f.Description += " (";
857 f.Description += mask;
858 f.Description += ")";
859}
860
861
862static const char * const k_DontSave_Exts =
863 "xpi odt ods docx xlsx ";
864
796void CCompressDialog::OnButtonSetArchive() 865void CCompressDialog::OnButtonSetArchive()
797{ 866{
798 UString path; 867 UString path;
@@ -802,23 +871,133 @@ void CCompressDialog::OnButtonSetArchive()
802 return; 871 return;
803 } 872 }
804 873
805 UString title = LangString(IDS_COMPRESS_SET_ARCHIVE_BROWSE); 874 int filterIndex;
806 UString filterDescription = LangString(IDS_OPEN_TYPE_ALL_FILES); 875 CObjectVector<CBrowseFilterInfo> filters;
807 filterDescription += " (*.*)"; 876 unsigned numFormats = 0;
808 UString resPath; 877
809 CurrentDirWasChanged = true; 878 const bool isSFX = IsSFX();
810 if (!MyBrowseForFile(*this, title, 879 if (isSFX)
811 // DirPrefix.IsEmpty() ? NULL : (const wchar_t *)DirPrefix, 880 {
812 // NULL, 881 filterIndex = 0;
813 path, 882 const UString ext ("exe");
814 filterDescription, 883 AddFilter(filters, ext, ext);
815 NULL, // L"*.*", 884 }
816 resPath)) 885 else
886 {
887 filterIndex = m_Format.GetCurSel();
888 numFormats = (unsigned)m_Format.GetCount();
889
890 // filters [0, ... numFormats - 1] corresponds to items in m_Format combo
891 UString desc;
892 UStringVector masks;
893 CStringFinder finder;
894
895 for (unsigned i = 0; i < numFormats; i++)
896 {
897 const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData(i)];
898 CBrowseFilterInfo &f = filters.AddNew();
899 f.Description = ai.Name;
900 f.Description += " (";
901 bool needSpace_desc = false;
902
903 FOR_VECTOR (k, ai.Exts)
904 {
905 const UString &ext = ai.Exts[k].Ext;
906 UString mask ("*.");
907 mask += ext;
908
909 if (finder.FindWord_In_LowCaseAsciiList_NoCase(k_DontSave_Exts, ext))
910 continue;
911
912 f.Masks.Add(mask);
913 masks.Add(mask);
914 if (needSpace_desc)
915 f.Description.Add_Space();
916 needSpace_desc = true;
917 f.Description += ext;
918 }
919 f.Description += ")";
920 // we use only main ext in desc to reduce the size of list
921 if (i != 0)
922 desc.Add_Space();
923 desc += ai.GetMainExt();
924 }
925
926 CBrowseFilterInfo &f = filters.AddNew();
927 f.Description = LangString(IDT_COMPRESS_ARCHIVE); // IDS_ARCHIVES_COLON;
928 if (f.Description.IsEmpty())
929 GetItemText(IDT_COMPRESS_ARCHIVE, f.Description);
930 f.Description.RemoveChar(L'&');
931 // f.Description = "archive";
932 f.Description += " (";
933 f.Description += desc;
934 f.Description += ")";
935 f.Masks = masks;
936 }
937
938 AddFilter(filters, LangString(IDS_OPEN_TYPE_ALL_FILES), UString("*"));
939 if (filterIndex < 0)
940 filterIndex = (int)filters.Size() - 1;
941
942 const UString title = LangString(IDS_COMPRESS_SET_ARCHIVE_BROWSE);
943 CBrowseInfo bi;
944 bi.lpstrTitle = title;
945 bi.SaveMode = true;
946 bi.FilterIndex = filterIndex;
947 bi.hwndOwner = *this;
948 bi.FilePath = path;
949
950 if (!bi.BrowseForFile(filters))
951 return;
952
953 path = bi.FilePath;
954
955 if (isSFX)
956 {
957 const int dotPos = GetExtDotPos(path);
958 if (dotPos >= 0)
959 path.DeleteFrom(dotPos);
960 path += kExeExt;
961 }
962 else
963 // if (bi.FilterIndex >= 0)
964 // if (bi.FilterIndex != filterIndex)
965 if ((unsigned)bi.FilterIndex < numFormats)
966 {
967 // archive format was confirmed. So we try to set format extension
968 bool needAddExt = true;
969 const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData((unsigned)bi.FilterIndex)];
970 const int dotPos = GetExtDotPos(path);
971 if (dotPos >= 0)
972 {
973 const UString ext = path.Ptr(dotPos + 1);
974 if (ai.FindExtension(ext) >= 0)
975 needAddExt = false;
976 }
977 if (needAddExt)
978 {
979 if (path.IsEmpty() || path.Back() != '.')
980 path.Add_Dot();
981 path += ai.GetMainExt();
982 }
983 }
984
985 SetArcPathFields(path);
986
987 if (!isSFX)
988 if ((unsigned)bi.FilterIndex < numFormats)
989 if (bi.FilterIndex != m_Format.GetCurSel())
990 {
991 m_Format.SetCurSel(bi.FilterIndex);
992 SaveOptionsInMem();
993 FormatChanged(true); // isChanged
817 return; 994 return;
818 UString dummyName; 995 }
819 SetArcPathFields(resPath, dummyName, true); 996
997 ArcPath_WasChanged(path);
820} 998}
821 999
1000
822// in ExtractDialog.cpp 1001// in ExtractDialog.cpp
823extern void AddUniqueString(UStringVector &strings, const UString &srcString); 1002extern void AddUniqueString(UStringVector &strings, const UString &srcString);
824 1003
@@ -826,7 +1005,7 @@ static bool IsAsciiString(const UString &s)
826{ 1005{
827 for (unsigned i = 0; i < s.Len(); i++) 1006 for (unsigned i = 0; i < s.Len(); i++)
828 { 1007 {
829 wchar_t c = s[i]; 1008 const wchar_t c = s[i];
830 if (c < 0x20 || c > 0x7F) 1009 if (c < 0x20 || c > 0x7F)
831 return false; 1010 return false;
832 } 1011 }
@@ -844,6 +1023,7 @@ static void AddSize_MB(UString &s, UInt64 size)
844} 1023}
845 1024
846 1025
1026void SetErrorMessage_MemUsage(UString &s, UInt64 reqSize, UInt64 ramSize, UInt64 ramLimit, const UString &usageString);
847void SetErrorMessage_MemUsage(UString &s, UInt64 reqSize, UInt64 ramSize, UInt64 ramLimit, const UString &usageString) 1027void SetErrorMessage_MemUsage(UString &s, UInt64 reqSize, UInt64 ramSize, UInt64 ramLimit, const UString &usageString)
848{ 1028{
849 s += "The operation was blocked by 7-Zip"; 1029 s += "The operation was blocked by 7-Zip";
@@ -927,6 +1107,8 @@ void CCompressDialog::OnOK()
927 } 1107 }
928 1108
929 SaveOptionsInMem(); 1109 SaveOptionsInMem();
1110
1111 UStringVector arcPaths;
930 { 1112 {
931 UString s; 1113 UString s;
932 if (!GetFinalPath_Smart(s)) 1114 if (!GetFinalPath_Smart(s))
@@ -934,17 +1116,16 @@ void CCompressDialog::OnOK()
934 ShowErrorMessage(*this, k_IncorrectPathMessage); 1116 ShowErrorMessage(*this, k_IncorrectPathMessage);
935 return; 1117 return;
936 } 1118 }
937
938 m_RegistryInfo.ArcPaths.Clear();
939 AddUniqueString(m_RegistryInfo.ArcPaths, s);
940 Info.ArcPath = s; 1119 Info.ArcPath = s;
1120 AddUniqueString(arcPaths, s);
941 } 1121 }
942 1122
943 Info.UpdateMode = (NCompressDialog::NUpdateMode::EEnum)k_UpdateMode_Vals[m_UpdateMode.GetCurSel()];; 1123 Info.UpdateMode = (NCompressDialog::NUpdateMode::EEnum)k_UpdateMode_Vals[m_UpdateMode.GetCurSel()];
944 Info.PathMode = (NWildcard::ECensorPathMode)k_PathMode_Vals[m_PathMode.GetCurSel()]; 1124 Info.PathMode = (NWildcard::ECensorPathMode)k_PathMode_Vals[m_PathMode.GetCurSel()];
945 1125
946 Info.Level = GetLevelSpec(); 1126 Info.Level = GetLevelSpec();
947 Info.Dict64 = GetDictSpec(); 1127 Info.Dict64 = GetDictSpec();
1128 // Info.Dict64_Chain = GetDictChainSpec();
948 Info.Order = GetOrderSpec(); 1129 Info.Order = GetOrderSpec();
949 Info.OrderMode = GetOrderMode(); 1130 Info.OrderMode = GetOrderMode();
950 Info.NumThreads = GetNumThreadsSpec(); 1131 Info.NumThreads = GetNumThreadsSpec();
@@ -975,7 +1156,7 @@ void CCompressDialog::OnOK()
975 1156
976 Info.Method = GetMethodSpec(); 1157 Info.Method = GetMethodSpec();
977 Info.EncryptionMethod = GetEncryptionMethodSpec(); 1158 Info.EncryptionMethod = GetEncryptionMethodSpec();
978 Info.FormatIndex = GetFormatIndex(); 1159 Info.FormatIndex = (int)GetFormatIndex();
979 Info.SFXMode = IsSFX(); 1160 Info.SFXMode = IsSFX();
980 Info.OpenShareForWrite = IsButtonCheckedBool(IDX_COMPRESS_SHARED); 1161 Info.OpenShareForWrite = IsButtonCheckedBool(IDX_COMPRESS_SHARED);
981 Info.DeleteAfterCompressing = IsButtonCheckedBool(IDX_COMPRESS_DEL); 1162 Info.DeleteAfterCompressing = IsButtonCheckedBool(IDX_COMPRESS_DEL);
@@ -1040,34 +1221,83 @@ void CCompressDialog::OnOK()
1040 } 1221 }
1041 } 1222 }
1042 1223
1043 for (int i = 0; i < m_ArchivePath.GetCount(); i++)
1044 {
1045 UString sTemp;
1046 m_ArchivePath.GetLBText(i, sTemp);
1047 sTemp.Trim();
1048 AddUniqueString(m_RegistryInfo.ArcPaths, sTemp);
1049 }
1050
1051 if (m_RegistryInfo.ArcPaths.Size() > kHistorySize)
1052 m_RegistryInfo.ArcPaths.DeleteBack();
1053
1054 if (Info.FormatIndex >= 0) 1224 if (Info.FormatIndex >= 0)
1055 m_RegistryInfo.ArcType = (*ArcFormats)[Info.FormatIndex].Name; 1225 m_RegistryInfo.ArcType = (*ArcFormats)[Info.FormatIndex].Name;
1056 m_RegistryInfo.ShowPassword = IsShowPasswordChecked(); 1226 m_RegistryInfo.ShowPassword = IsShowPasswordChecked();
1057 1227
1228 FOR_VECTOR (i, m_RegistryInfo.ArcPaths)
1229 {
1230 if (arcPaths.Size() >= kHistorySize)
1231 break;
1232 AddUniqueString(arcPaths, m_RegistryInfo.ArcPaths[i]);
1233 }
1234 m_RegistryInfo.ArcPaths = arcPaths;
1235
1058 m_RegistryInfo.Save(); 1236 m_RegistryInfo.Save();
1059 1237
1060 CModalDialog::OnOK(); 1238 CModalDialog::OnOK();
1061} 1239}
1062 1240
1063#define kHelpTopic "fm/plugins/7-zip/add.htm" 1241#define kHelpTopic "fm/plugins/7-zip/add.htm"
1242#define kHelpTopic_Options "fm/plugins/7-zip/add.htm#options"
1064 1243
1065void CCompressDialog::OnHelp() 1244void CCompressDialog::OnHelp()
1066{ 1245{
1067 ShowHelpWindow(kHelpTopic); 1246 ShowHelpWindow(kHelpTopic);
1068} 1247}
1069 1248
1070bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam) 1249
1250void CCompressDialog::ArcPath_WasChanged(const UString &path)
1251{
1252 const int dotPos = GetExtDotPos(path);
1253 if (dotPos < 0)
1254 return;
1255 const UString ext = path.Ptr(dotPos + 1);
1256 {
1257 const CArcInfoEx &ai = Get_ArcInfoEx();
1258 if (ai.FindExtension(ext) >= 0)
1259 return;
1260 }
1261
1262 const unsigned count = (unsigned)m_Format.GetCount();
1263 for (unsigned i = 0; i < count; i++)
1264 {
1265 const CArcInfoEx &ai = (*ArcFormats)[(unsigned)m_Format.GetItemData(i)];
1266 if (ai.FindExtension(ext) >= 0)
1267 {
1268 m_Format.SetCurSel(i);
1269 SaveOptionsInMem();
1270 FormatChanged(true); // isChanged
1271 return;
1272 }
1273 }
1274}
1275
1276
1277bool CCompressDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
1278{
1279 switch (message)
1280 {
1281 case k_Message_ArcChanged:
1282 {
1283 // UString path;
1284 // m_ArchivePath.GetText(path);
1285 const int select = m_ArchivePath.GetCurSel();
1286 if ((unsigned)select < m_RegistryInfo.ArcPaths.Size())
1287 // if (path == m_RegistryInfo.ArcPaths[select])
1288 {
1289 const UString &path = m_RegistryInfo.ArcPaths[select];
1290 SetArcPathFields(path);
1291 // ArcPath_WasChanged(path);
1292 }
1293 return 0;
1294 }
1295 }
1296 return CModalDialog::OnMessage(message, wParam, lParam);
1297}
1298
1299
1300bool CCompressDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
1071{ 1301{
1072 if (code == CBN_SELCHANGE) 1302 if (code == CBN_SELCHANGE)
1073 { 1303 {
@@ -1075,21 +1305,21 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam)
1075 { 1305 {
1076 case IDC_COMPRESS_ARCHIVE: 1306 case IDC_COMPRESS_ARCHIVE:
1077 { 1307 {
1078 // we can 't change m_ArchivePath in that handler ! 1308 /* CBN_SELCHANGE is called before actual value of combo text will be changed.
1079 DirPrefix.Empty(); 1309 So GetText() here returns old value (before change) of combo text.
1080 SetItemText(IDT_COMPRESS_ARCHIVE_FOLDER, DirPrefix); 1310 So here we can change all controls except of m_ArchivePath.
1081 1311 */
1082 /* 1312 const int select = m_ArchivePath.GetCurSel();
1083 UString path; 1313 if ((unsigned)select < m_RegistryInfo.ArcPaths.Size())
1084 m_ArchivePath.GetText(path);
1085 m_ArchivePath.SetText(L"");
1086 if (IsAbsolutePath(path))
1087 { 1314 {
1088 UString fileName; 1315 // DirPrefix.Empty();
1089 SetArcPathFields(path, fileName); 1316 // SetItemText(IDT_COMPRESS_ARCHIVE_FOLDER, DirPrefix);
1090 SetArchiveName(fileName); 1317 const UString &path = m_RegistryInfo.ArcPaths[select];
1318 // SetArcPathFields(path);
1319 ArcPath_WasChanged(path);
1320 // we use PostMessage(k_Message_ArcChanged) here that later will change m_ArchivePath control
1321 PostMsg(k_Message_ArcChanged);
1091 } 1322 }
1092 */
1093 return true; 1323 return true;
1094 } 1324 }
1095 1325
@@ -1106,7 +1336,17 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam)
1106 { 1336 {
1107 Get_FormatOptions().ResetForLevelChange(); 1337 Get_FormatOptions().ResetForLevelChange();
1108 1338
1109 SetMethod(); 1339 SetMethod(); // call it if level changes method
1340
1341 // call the following if level change keeps old method
1342 /*
1343 {
1344 // try to keep old method
1345 SetMethod(GetMethodID());
1346 MethodChanged();
1347 }
1348 */
1349
1110 SetSolidBlockSize(); 1350 SetSolidBlockSize();
1111 SetNumThreads(); 1351 SetNumThreads();
1112 CheckSFXNameChange(); 1352 CheckSFXNameChange();
@@ -1128,6 +1368,7 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam)
1128 } 1368 }
1129 1369
1130 case IDC_COMPRESS_DICTIONARY: 1370 case IDC_COMPRESS_DICTIONARY:
1371 // case IDC_COMPRESS_DICTIONARY2:
1131 { 1372 {
1132 /* we want to change the reported threads for Auto line 1373 /* we want to change the reported threads for Auto line
1133 and keep selected NumThreads option 1374 and keep selected NumThreads option
@@ -1142,6 +1383,7 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam)
1142 // SetSolidBlockSize(true); 1383 // SetSolidBlockSize(true);
1143 } 1384 }
1144 1385
1386 SetDictionary2();
1145 SetSolidBlockSize(); 1387 SetSolidBlockSize();
1146 SetNumThreads(); // we want to change the reported threads for Auto line only 1388 SetNumThreads(); // we want to change the reported threads for Auto line only
1147 SetMemoryUsage(); 1389 SetMemoryUsage();
@@ -1149,7 +1391,12 @@ bool CCompressDialog::OnCommand(int code, int itemID, LPARAM lParam)
1149 } 1391 }
1150 1392
1151 case IDC_COMPRESS_ORDER: 1393 case IDC_COMPRESS_ORDER:
1394 {
1395 #ifdef PRINT_PARAMS
1396 Print_Params();
1397 #endif
1152 return true; 1398 return true;
1399 }
1153 1400
1154 case IDC_COMPRESS_SOLID: 1401 case IDC_COMPRESS_SOLID:
1155 { 1402 {
@@ -1199,7 +1446,7 @@ void CCompressDialog::SetArchiveName2(bool prevWasSFX)
1199 prevExtension = kExeExt; 1446 prevExtension = kExeExt;
1200 else 1447 else
1201 { 1448 {
1202 prevExtension += '.'; 1449 prevExtension.Add_Dot();
1203 prevExtension += prevArchiverInfo.GetMainExt(); 1450 prevExtension += prevArchiverInfo.GetMainExt();
1204 } 1451 }
1205 const unsigned prevExtensionLen = prevExtension.Len(); 1452 const unsigned prevExtensionLen = prevExtension.Len();
@@ -1217,7 +1464,7 @@ void CCompressDialog::SetArchiveName2(bool prevWasSFX)
1217void CCompressDialog::SetArchiveName(const UString &name) 1464void CCompressDialog::SetArchiveName(const UString &name)
1218{ 1465{
1219 UString fileName = name; 1466 UString fileName = name;
1220 Info.FormatIndex = GetFormatIndex(); 1467 Info.FormatIndex = (int)GetFormatIndex();
1221 const CArcInfoEx &ai = (*ArcFormats)[Info.FormatIndex]; 1468 const CArcInfoEx &ai = (*ArcFormats)[Info.FormatIndex];
1222 m_PrevFormat = Info.FormatIndex; 1469 m_PrevFormat = Info.FormatIndex;
1223 if (ai.Flags_KeepName()) 1470 if (ai.Flags_KeepName())
@@ -1238,7 +1485,7 @@ void CCompressDialog::SetArchiveName(const UString &name)
1238 fileName += kExeExt; 1485 fileName += kExeExt;
1239 else 1486 else
1240 { 1487 {
1241 fileName += '.'; 1488 fileName.Add_Dot();
1242 UString ext = ai.GetMainExt(); 1489 UString ext = ai.GetMainExt();
1243 if (ai.Flags_HashHandler()) 1490 if (ai.Flags_HashHandler())
1244 { 1491 {
@@ -1262,7 +1509,7 @@ int CCompressDialog::FindRegistryFormat(const UString &name)
1262 { 1509 {
1263 const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[i]; 1510 const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[i];
1264 if (name.IsEqualTo_NoCase(GetUnicodeString(fo.FormatID))) 1511 if (name.IsEqualTo_NoCase(GetUnicodeString(fo.FormatID)))
1265 return i; 1512 return (int)i;
1266 } 1513 }
1267 return -1; 1514 return -1;
1268} 1515}
@@ -1270,14 +1517,14 @@ int CCompressDialog::FindRegistryFormat(const UString &name)
1270 1517
1271unsigned CCompressDialog::FindRegistryFormat_Always(const UString &name) 1518unsigned CCompressDialog::FindRegistryFormat_Always(const UString &name)
1272{ 1519{
1273 int index = FindRegistryFormat(name); 1520 const int index = FindRegistryFormat(name);
1274 if (index < 0) 1521 if (index >= 0)
1522 return (unsigned)index;
1275 { 1523 {
1276 NCompression::CFormatOptions fo; 1524 NCompression::CFormatOptions fo;
1277 fo.FormatID = GetSystemString(name); 1525 fo.FormatID = GetSystemString(name);
1278 index = m_RegistryInfo.Formats.Add(fo); 1526 return m_RegistryInfo.Formats.Add(fo);
1279 } 1527 }
1280 return index;
1281} 1528}
1282 1529
1283 1530
@@ -1288,10 +1535,10 @@ NCompression::CFormatOptions &CCompressDialog::Get_FormatOptions()
1288} 1535}
1289 1536
1290 1537
1291int CCompressDialog::GetStaticFormatIndex() 1538unsigned CCompressDialog::GetStaticFormatIndex()
1292{ 1539{
1293 const CArcInfoEx &ai = Get_ArcInfoEx(); 1540 const CArcInfoEx &ai = Get_ArcInfoEx();
1294 for (unsigned i = 0; i < ARRAY_SIZE(g_Formats); i++) 1541 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_Formats); i++)
1295 if (ai.Name.IsEqualTo_Ascii_NoCase(g_Formats[i].Name)) 1542 if (ai.Name.IsEqualTo_Ascii_NoCase(g_Formats[i].Name))
1296 return i; 1543 return i;
1297 return 0; // -1; 1544 return 0; // -1;
@@ -1329,18 +1576,25 @@ void CCompressDialog::SetLevel2()
1329 } 1576 }
1330 } 1577 }
1331 1578
1579 const bool isZstd = ai.Is_Zstd();
1580
1332 for (unsigned i = 0; i < sizeof(UInt32) * 8; i++) 1581 for (unsigned i = 0; i < sizeof(UInt32) * 8; i++)
1333 { 1582 {
1334 const UInt32 mask = (UInt32)1 << i; 1583 const UInt32 mask = (UInt32)1 << i;
1335 if ((fi.LevelsMask & mask) != 0) 1584 if ((fi.LevelsMask & mask) != 0)
1336 { 1585 {
1337 UInt32 langID = g_Levels[i]; 1586 const UInt32 langID = g_Levels[i];
1338 UString s; 1587 UString s;
1339 s.Add_UInt32(i); 1588 s.Add_UInt32(i);
1340 s += " - "; 1589 // if (fi.LevelsMask < (1 << (MY_ZSTD_LEVEL_MAX + 1)) - 1)
1341 s += LangString(langID); 1590 if (langID)
1342 int index = (int)m_Level.AddString(s); 1591 if (i != 0 || !isZstd)
1343 m_Level.SetItemData(index, i); 1592 {
1593 s += " - ";
1594 s += LangString(langID);
1595 }
1596 const int index = (int)m_Level.AddString(s);
1597 m_Level.SetItemData(index, (LPARAM)i);
1344 } 1598 }
1345 if (fi.LevelsMask <= mask) 1599 if (fi.LevelsMask <= mask)
1346 break; 1600 break;
@@ -1354,12 +1608,11 @@ static LRESULT ComboBox_AddStringAscii(NControl::CComboBox &cb, const char *s)
1354 return cb.AddString((CSysString)s); 1608 return cb.AddString((CSysString)s);
1355} 1609}
1356 1610
1357// static const char *k_Auto = "- "; // "auto : "; 1611static const char *k_Auto_Prefix = "* ";
1358 1612
1359static void Modify_Auto(AString &s) 1613static void Modify_Auto(AString &s)
1360{ 1614{
1361 s.Insert(0, "* "); 1615 s.Insert(0, k_Auto_Prefix);
1362 // s += " -";
1363} 1616}
1364 1617
1365void CCompressDialog::SetMethod2(int keepMethodId) 1618void CCompressDialog::SetMethod2(int keepMethodId)
@@ -1370,7 +1623,8 @@ void CCompressDialog::SetMethod2(int keepMethodId)
1370 const CArcInfoEx &ai = Get_ArcInfoEx(); 1623 const CArcInfoEx &ai = Get_ArcInfoEx();
1371 if (GetLevel() == 0 && !ai.Flags_HashHandler()) 1624 if (GetLevel() == 0 && !ai.Flags_HashHandler())
1372 { 1625 {
1373 if (!ai.Is_Tar()) 1626 if (!ai.Is_Tar() &&
1627 !ai.Is_Zstd())
1374 { 1628 {
1375 MethodChanged(); 1629 MethodChanged();
1376 return; 1630 return;
@@ -1409,10 +1663,10 @@ void CCompressDialog::SetMethod2(int keepMethodId)
1409 { 1663 {
1410 if (!is7z) 1664 if (!is7z)
1411 break; 1665 break;
1412 unsigned extIndex = m - fi.NumMethods; 1666 const unsigned extIndex = m - fi.NumMethods;
1413 if (extIndex >= ExternalMethods.Size()) 1667 if (extIndex >= ExternalMethods.Size())
1414 break; 1668 break;
1415 methodID = ARRAY_SIZE(kMethodsNames) + extIndex; 1669 methodID = (int)(Z7_ARRAY_SIZE(kMethodsNames) + extIndex);
1416 method = ExternalMethods[extIndex].Ptr(); 1670 method = ExternalMethods[extIndex].Ptr();
1417 } 1671 }
1418 if (isSfx) 1672 if (isSfx)
@@ -1516,10 +1770,10 @@ UString CCompressDialog::GetMethodSpec(UString &estimatedName)
1516 UString s; 1770 UString s;
1517 if (methodId >= 0) 1771 if (methodId >= 0)
1518 { 1772 {
1519 if ((unsigned)methodId < ARRAY_SIZE(kMethodsNames)) 1773 if ((unsigned)methodId < Z7_ARRAY_SIZE(kMethodsNames))
1520 estimatedName = kMethodsNames[methodId]; 1774 estimatedName = kMethodsNames[methodId];
1521 else 1775 else
1522 estimatedName = ExternalMethods[methodId - ARRAY_SIZE(kMethodsNames)]; 1776 estimatedName = ExternalMethods[(unsigned)methodId - (unsigned)Z7_ARRAY_SIZE(kMethodsNames)];
1523 if (methodIdRaw >= 0) 1777 if (methodIdRaw >= 0)
1524 s = estimatedName; 1778 s = estimatedName;
1525 } 1779 }
@@ -1556,10 +1810,10 @@ UString CCompressDialog::GetEncryptionMethodSpec()
1556 return s; 1810 return s;
1557} 1811}
1558 1812
1559static const size_t k_Auto_Dict = (size_t)0 - 1;
1560 1813
1814static const size_t k_Auto_Dict = (size_t)0 - 1;
1561 1815
1562int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow) 1816static int Combo_AddDict2(NWindows::NControl::CComboBox &cb, size_t sizeReal, size_t sizeShow)
1563{ 1817{
1564 char c = 0; 1818 char c = 0;
1565 unsigned moveBits = 0; 1819 unsigned moveBits = 0;
@@ -1568,43 +1822,106 @@ int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow)
1568 AString s; 1822 AString s;
1569 s.Add_UInt64(sizeShow >> moveBits); 1823 s.Add_UInt64(sizeShow >> moveBits);
1570 s.Add_Space(); 1824 s.Add_Space();
1571 if (moveBits != 0) 1825 if (c != 0)
1572 s += c; 1826 s += c;
1573 s += 'B'; 1827 s += 'B';
1574 if (sizeReal == k_Auto_Dict) 1828 if (sizeReal == k_Auto_Dict)
1575 Modify_Auto(s); 1829 Modify_Auto(s);
1576 const int index = (int)ComboBox_AddStringAscii(m_Dictionary, s); 1830 const int index = (int)ComboBox_AddStringAscii(cb, s);
1577 m_Dictionary.SetItemData(index, sizeReal); 1831 cb.SetItemData(index, (LPARAM)sizeReal);
1578 return index; 1832 return index;
1579} 1833}
1580 1834
1835int CCompressDialog::AddDict2(size_t sizeReal, size_t sizeShow)
1836{
1837 return Combo_AddDict2(m_Dictionary, sizeReal, sizeShow);
1838}
1581 1839
1582int CCompressDialog::AddDict(size_t size) 1840int CCompressDialog::AddDict(size_t size)
1583{ 1841{
1584 return AddDict2(size, size); 1842 return AddDict2(size, size);
1585} 1843}
1586 1844
1845/*
1846int CCompressDialog::AddDict_Chain(size_t size)
1847{
1848 return Combo_AddDict2(m_Dictionary_Chain, size, size);
1849}
1850*/
1587 1851
1588void CCompressDialog::SetDictionary2() 1852void CCompressDialog::SetDictionary2()
1589{ 1853{
1590 m_Dictionary.ResetContent(); 1854 m_Dictionary.ResetContent();
1855 // m_Dictionary_Chain.ResetContent();
1856
1591 // _auto_Dict = (UInt32)1 << 24; // we can use this dictSize to calculate _auto_Solid for unknown method for 7z 1857 // _auto_Dict = (UInt32)1 << 24; // we can use this dictSize to calculate _auto_Solid for unknown method for 7z
1592 _auto_Dict = (UInt32)(Int32)-1; // for debug: 1858 _auto_Dict = (UInt32)(Int32)-1; // for debug
1859 // _auto_Dict_Chain = (UInt32)(Int32)-1; // for debug
1593 1860
1594 const CArcInfoEx &ai = Get_ArcInfoEx(); 1861 const CArcInfoEx &ai = Get_ArcInfoEx();
1595 UInt32 defaultDict = (UInt32)(Int32)-1; 1862 UInt32 defaultDict = (UInt32)(Int32)-1;
1863 // UInt32 defaultDict_Chain = (UInt32)(Int32)-1;
1596 { 1864 {
1597 const int index = FindRegistryFormat(ai.Name); 1865 const int index = FindRegistryFormat(ai.Name);
1598 if (index >= 0) 1866 if (index >= 0)
1599 { 1867 {
1600 const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[index]; 1868 const NCompression::CFormatOptions &fo = m_RegistryInfo.Formats[index];
1601 if (IsMethodEqualTo(fo.Method)) 1869 if (IsMethodEqualTo(fo.Method))
1870 {
1602 defaultDict = fo.Dictionary; 1871 defaultDict = fo.Dictionary;
1872 // defaultDict_Chain = fo.DictionaryChain;
1873 }
1603 } 1874 }
1604 } 1875 }
1605 1876
1606 const int methodID = GetMethodID(); 1877 const int methodID = GetMethodID();
1607 const UInt32 level = GetLevel2(); 1878 const UInt32 level = GetLevel2();
1879
1880 {
1881 RECT r, rLabel;
1882 GetClientRectOfItem(IDT_COMPRESS_DICTIONARY, rLabel);
1883 GetClientRectOfItem(IDC_COMPRESS_DICTIONARY, r);
1884 if (_dictionaryCombo_left == 0)
1885 _dictionaryCombo_left = r.left;
1886
1887 // bool showDict2;
1888 int newLableRight;
1889 int newDictLeft;
1890
1891 /*
1892 if (methodID == kZSTD)
1893 {
1894 showDict2 = true;
1895 newDictLeft = _dictionaryCombo_left;
1896 RECT r2;
1897 GetClientRectOfItem(IDC_COMPRESS_DICTIONARY2, r2);
1898 newLableRight = r2.left;
1899 }
1900 else
1901 */
1902 {
1903 // showDict2 = false;
1904 RECT rBig;
1905 GetClientRectOfItem(IDC_COMPRESS_METHOD, rBig);
1906 newDictLeft= rBig.left;
1907 newLableRight = newDictLeft;
1908 }
1909
1910 if (newLableRight != rLabel.right)
1911 {
1912 rLabel.right = newLableRight;
1913 MoveItem_RECT(IDT_COMPRESS_DICTIONARY, rLabel);
1914 InvalidateRect(&rLabel);
1915 }
1916 if (newDictLeft != r.left)
1917 {
1918 r.left = newDictLeft;
1919 MoveItem_RECT(IDC_COMPRESS_DICTIONARY, r);
1920 // InvalidateRect(&r);
1921 }
1922 // ShowItem_Bool(IDC_COMPRESS_DICTIONARY2, showDict2);
1923 }
1924
1608 if (methodID < 0) 1925 if (methodID < 0)
1609 return; 1926 return;
1610 1927
@@ -1659,6 +1976,86 @@ void CCompressDialog::SetDictionary2()
1659 m_Dictionary.SetCurSel(curSel); 1976 m_Dictionary.SetCurSel(curSel);
1660 break; 1977 break;
1661 } 1978 }
1979
1980 /*
1981 case kZSTD:
1982 {
1983 if (defaultDict != (UInt32)(Int32)-1 &&
1984 defaultDict > kZstd_MAX_DictSize)
1985 defaultDict = kZstd_MAX_DictSize;
1986
1987 if (defaultDict_Chain != (UInt32)(Int32)-1 &&
1988 defaultDict_Chain > kZstd_MAX_DictSize_Chain)
1989 defaultDict_Chain = kZstd_MAX_DictSize_Chain;
1990
1991 {
1992 CZstdEncProps props;
1993 ZstdEncProps_Init(&props);
1994 // props.level_zstd = level;
1995 props.level_7z = level;
1996 ZstdEncProps_Set_WindowSize(&props, defaultDict != (UInt32)(Int32)-1 ? defaultDict: 0);
1997 ZstdEncProps_NormalizeFull(&props);
1998 _auto_Dict_Chain = (UInt32)1 << props.windowLog_Chain;
1999 }
2000 {
2001 CZstdEncProps props;
2002 ZstdEncProps_Init(&props);
2003 // props.level_zstd = level;
2004 props.level_7z = level;
2005 ZstdEncProps_Set_WindowChainSize(&props, defaultDict_Chain != (UInt32)(Int32)-1 ? defaultDict_Chain: 0);
2006 ZstdEncProps_NormalizeFull(&props);
2007 _auto_Dict = (UInt32)1 << props.windowLog;
2008 }
2009
2010 // if there is collision of two window sizes, we reduce dict_Chain
2011 if (defaultDict != (UInt32)(Int32)-1 &&
2012 defaultDict_Chain != (UInt32)(Int32)-1 &&
2013 defaultDict < defaultDict_Chain)
2014 defaultDict_Chain = defaultDict;
2015
2016 {
2017 int curSel = AddDict2(k_Auto_Dict, _auto_Dict);
2018
2019 // defaultDict = 12 << 10; // for debug
2020 const UInt32 kWinStart = 18;
2021 if (defaultDict != 0 && defaultDict < ((UInt32)1 << kWinStart))
2022 curSel = AddDict(defaultDict);
2023
2024 for (unsigned i = kWinStart; i <= MY_ZSTD_WINDOWLOG_MAX; i++)
2025 {
2026 const size_t dict = (size_t)1 << i;
2027 const int index = AddDict(dict);
2028 if (defaultDict != (UInt32)(Int32)-1)
2029 if (dict <= defaultDict || curSel <= 0)
2030 curSel = index;
2031 }
2032 m_Dictionary.SetCurSel(curSel);
2033 }
2034
2035 {
2036 int curSel = Combo_AddDict2(m_Dictionary_Chain, k_Auto_Dict, _auto_Dict_Chain);
2037
2038 // defaultDict_Chain = 10 << 10; // for debug
2039 const UInt32 kWinChainStart = 15;
2040 if (defaultDict_Chain != 0 && defaultDict_Chain < ((UInt32)1 << kWinChainStart))
2041 curSel = AddDict_Chain(defaultDict_Chain);
2042
2043 for (unsigned i = kWinChainStart; i <= kMaxDictChain; i++)
2044 {
2045 const size_t dict = (size_t)1 << i;
2046 if (defaultDict != (UInt32)(Int32)-1 && dict > defaultDict)
2047 break;
2048 const int index = AddDict_Chain(dict);
2049 if (defaultDict_Chain != (UInt32)(Int32)-1)
2050 if (dict <= defaultDict_Chain || curSel <= 0)
2051 curSel = index;
2052 }
2053 m_Dictionary_Chain.SetCurSel(curSel);
2054 }
2055
2056 break;
2057 }
2058 */
1662 2059
1663 case kPPMd: 2060 case kPPMd:
1664 { 2061 {
@@ -1795,8 +2192,8 @@ int CCompressDialog::AddOrder(UInt32 size)
1795{ 2192{
1796 char s[32]; 2193 char s[32];
1797 ConvertUInt32ToString(size, s); 2194 ConvertUInt32ToString(size, s);
1798 int index = (int)ComboBox_AddStringAscii(m_Order, s); 2195 const int index = (int)ComboBox_AddStringAscii(m_Order, s);
1799 m_Order.SetItemData(index, size); 2196 m_Order.SetItemData(index, (LPARAM)size);
1800 return index; 2197 return index;
1801} 2198}
1802 2199
@@ -1855,6 +2252,39 @@ void CCompressDialog::SetOrder2()
1855 break; 2252 break;
1856 } 2253 }
1857 2254
2255 /*
2256 case kZSTD:
2257 {
2258 {
2259 CZstdEncProps props;
2260 ZstdEncProps_Init(&props);
2261 // props.level_zstd = level;
2262 props.level_7z = level;
2263 ZstdEncProps_NormalizeFull(&props);
2264 _auto_Order = props.targetLength;
2265 if (props.strategy < ZSTD_strategy_btopt)
2266 {
2267 // ZSTD_strategy_fast uses targetLength to change fast level.
2268 // targetLength probably is used only in ZSTD_strategy_btopt and higher
2269 break;
2270 }
2271 }
2272 int curSel = AddOrder_Auto();
2273
2274 for (unsigned i = 6; i <= 9 * 2; i++)
2275 {
2276 UInt32 order = ((UInt32)(2 + (i & 1)) << (i / 2));
2277 // if (order > 999) order = 999;
2278 const int index = AddOrder(order);
2279 if (defaultOrder != (UInt32)(Int32)-1)
2280 if (order <= defaultOrder || curSel <= 0)
2281 curSel = index;
2282 }
2283 m_Order.SetCurSel(curSel);
2284 break;
2285 }
2286 */
2287
1858 case kDeflate: 2288 case kDeflate:
1859 case kDeflate64: 2289 case kDeflate64:
1860 { 2290 {
@@ -2051,8 +2481,8 @@ void CCompressDialog::SetSolidBlockSize2()
2051 AString s; 2481 AString s;
2052 Add_Size(s, _auto_Solid); 2482 Add_Size(s, _auto_Solid);
2053 Modify_Auto(s); 2483 Modify_Auto(s);
2054 int index = (int)ComboBox_AddStringAscii(m_Solid, s); 2484 const int index = (int)ComboBox_AddStringAscii(m_Solid, s);
2055 m_Solid.SetItemData(index, (UInt32)(Int32)-1); 2485 m_Solid.SetItemData(index, (LPARAM)(UInt32)(Int32)-1);
2056 curSel = index; 2486 curSel = index;
2057 } 2487 }
2058 2488
@@ -2063,7 +2493,7 @@ void CCompressDialog::SetSolidBlockSize2()
2063 if (is7z) 2493 if (is7z)
2064 LangString(IDS_COMPRESS_NON_SOLID, s); 2494 LangString(IDS_COMPRESS_NON_SOLID, s);
2065 const int index = (int)m_Solid.AddString(s); 2495 const int index = (int)m_Solid.AddString(s);
2066 m_Solid.SetItemData(index, (UInt32)kSolidLog_NoSolid); 2496 m_Solid.SetItemData(index, (LPARAM)(UInt32)kSolidLog_NoSolid);
2067 if (defaultBlockSize == kSolidLog_NoSolid) 2497 if (defaultBlockSize == kSolidLog_NoSolid)
2068 curSel = index; 2498 curSel = index;
2069 } 2499 }
@@ -2073,7 +2503,7 @@ void CCompressDialog::SetSolidBlockSize2()
2073 AString s; 2503 AString s;
2074 Add_Size(s, (UInt64)1 << i); 2504 Add_Size(s, (UInt64)1 << i);
2075 const int index = (int)ComboBox_AddStringAscii(m_Solid, s); 2505 const int index = (int)ComboBox_AddStringAscii(m_Solid, s);
2076 m_Solid.SetItemData(index, (UInt32)i); 2506 m_Solid.SetItemData(index, (LPARAM)(UInt32)i);
2077 if (defaultBlockSize != (UInt32)(Int32)-1) 2507 if (defaultBlockSize != (UInt32)(Int32)-1)
2078 if (i <= defaultBlockSize || index <= 1) 2508 if (i <= defaultBlockSize || index <= 1)
2079 curSel = index; 2509 curSel = index;
@@ -2081,7 +2511,7 @@ void CCompressDialog::SetSolidBlockSize2()
2081 2511
2082 { 2512 {
2083 const int index = (int)m_Solid.AddString(LangString(IDS_COMPRESS_SOLID)); 2513 const int index = (int)m_Solid.AddString(LangString(IDS_COMPRESS_SOLID));
2084 m_Solid.SetItemData(index, kSolidLog_FullSolid); 2514 m_Solid.SetItemData(index, (LPARAM)kSolidLog_FullSolid);
2085 if (defaultBlockSize == kSolidLog_FullSolid) 2515 if (defaultBlockSize == kSolidLog_FullSolid)
2086 curSel = index; 2516 curSel = index;
2087 } 2517 }
@@ -2090,6 +2520,43 @@ void CCompressDialog::SetSolidBlockSize2()
2090} 2520}
2091 2521
2092 2522
2523/*
2524static void ZstdEncProps_SetDictProps_From_CompressDialog(CZstdEncProps *props, CCompressDialog &cd)
2525{
2526 {
2527 const UInt64 d64 = cd.GetDictSpec();
2528 UInt32 d32 = 0; // 0 is default for ZstdEncProps::windowLog
2529 if (d64 != (UInt64)(Int64)-1)
2530 {
2531 d32 = (UInt32)d64;
2532 if (d32 != d64)
2533 d32 = (UInt32)(Int32)-2;
2534 }
2535 ZstdEncProps_Set_WindowSize(props, d32);
2536 }
2537 {
2538 const UInt64 d64 = cd.GetDictChainSpec();
2539 UInt32 d32 = 0; // 0 is default for ZstdEncProps::windowLog_Chain
2540 if (d64 != (UInt64)(Int64)-1)
2541 {
2542 d32 = (UInt32)d64;
2543 if (d32 != d64)
2544 d32 = (UInt32)(Int32)-2;
2545 }
2546 ZstdEncProps_Set_WindowChainSize(props, d32);
2547 }
2548}
2549
2550static bool Is_Zstd_Mt_Supported()
2551{
2552 if (!GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "InitializeConditionVariable"))
2553 return false;
2554 return true;
2555}
2556*/
2557
2558static const char *k_ST_Threads = " (ST)";
2559
2093void CCompressDialog::SetNumThreads2() 2560void CCompressDialog::SetNumThreads2()
2094{ 2561{
2095 _auto_NumThreads = 1; 2562 _auto_NumThreads = 1;
@@ -2119,13 +2586,17 @@ void CCompressDialog::SetNumThreads2()
2119 } 2586 }
2120 } 2587 }
2121 2588
2589 // const UInt32 num_ZSTD_threads_MAX = Is_Zstd_Mt_Supported() ? MY_ZSTDMT_NBWORKERS_MAX : 0;
2590
2122 UInt32 numAlgoThreadsMax = numHardwareThreads * 2; 2591 UInt32 numAlgoThreadsMax = numHardwareThreads * 2;
2123 const int methodID = GetMethodID(); 2592 const int methodID = GetMethodID();
2593
2124 switch (methodID) 2594 switch (methodID)
2125 { 2595 {
2126 case kLZMA: numAlgoThreadsMax = 2; break; 2596 case kLZMA: numAlgoThreadsMax = 2; break;
2127 case kLZMA2: numAlgoThreadsMax = 256; break; 2597 case kLZMA2: numAlgoThreadsMax = 256; break;
2128 case kBZip2: numAlgoThreadsMax = 32; break; 2598 case kBZip2: numAlgoThreadsMax = 32; break;
2599 // case kZSTD: numAlgoThreadsMax = num_ZSTD_threads_MAX; break;
2129 case kCopy: 2600 case kCopy:
2130 case kPPMd: 2601 case kPPMd:
2131 case kDeflate: 2602 case kDeflate:
@@ -2150,7 +2621,10 @@ void CCompressDialog::SetNumThreads2()
2150 2621
2151 const UInt64 memUse_Limit = Get_MemUse_Bytes(); 2622 const UInt64 memUse_Limit = Get_MemUse_Bytes();
2152 2623
2153 if (autoThreads > 1 && _ramSize_Defined) 2624 if (_ramSize_Defined)
2625 if (autoThreads > 1
2626 // || (autoThreads == 0 && methodID == kZSTD)
2627 )
2154 { 2628 {
2155 if (isZip) 2629 if (isZip)
2156 { 2630 {
@@ -2178,6 +2652,20 @@ void CCompressDialog::SetNumThreads2()
2178 } 2652 }
2179 autoThreads = numBlockThreads * numThreads1; 2653 autoThreads = numBlockThreads * numThreads1;
2180 } 2654 }
2655 /*
2656 else if (methodID == kZSTD)
2657 {
2658 if (num_ZSTD_threads_MAX != 0)
2659 {
2660 CZstdEncProps props;
2661 ZstdEncProps_Init(&props);
2662 // props.level_zstd = level;
2663 props.level_7z = GetLevel2();
2664 ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this);
2665 autoThreads = ZstdEncProps_GetNumThreads_for_MemUsageLimit(&props, memUse_Limit, autoThreads);
2666 }
2667 }
2668 */
2181 } 2669 }
2182 2670
2183 _auto_NumThreads = autoThreads; 2671 _auto_NumThreads = autoThreads;
@@ -2186,8 +2674,9 @@ void CCompressDialog::SetNumThreads2()
2186 { 2674 {
2187 AString s; 2675 AString s;
2188 s.Add_UInt32(autoThreads); 2676 s.Add_UInt32(autoThreads);
2677 if (autoThreads == 0) s += k_ST_Threads;
2189 Modify_Auto(s); 2678 Modify_Auto(s);
2190 int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); 2679 const int index = (int)ComboBox_AddStringAscii(m_NumThreads, s);
2191 m_NumThreads.SetItemData(index, (LPARAM)(INT_PTR)(-1)); 2680 m_NumThreads.SetItemData(index, (LPARAM)(INT_PTR)(-1));
2192 // m_NumThreads.SetItemData(index, autoThreads); 2681 // m_NumThreads.SetItemData(index, autoThreads);
2193 if (useAutoThreads) 2682 if (useAutoThreads)
@@ -2195,12 +2684,16 @@ void CCompressDialog::SetNumThreads2()
2195 } 2684 }
2196 2685
2197 if (numAlgoThreadsMax != autoThreads || autoThreads != 1) 2686 if (numAlgoThreadsMax != autoThreads || autoThreads != 1)
2198 for (UInt32 i = 1; i <= numHardwareThreads * 2 && i <= numAlgoThreadsMax; i++) 2687 for (UInt32 i =
2688 // (methodID == kZSTD) ? 0 :
2689 1;
2690 i <= numHardwareThreads * 2 && i <= numAlgoThreadsMax; i++)
2199 { 2691 {
2200 char s[32]; 2692 AString s;
2201 ConvertUInt32ToString(i, s); 2693 s.Add_UInt32(i);
2202 int index = (int)ComboBox_AddStringAscii(m_NumThreads, s); 2694 if (i == 0) s += k_ST_Threads;
2203 m_NumThreads.SetItemData(index, (UInt32)i); 2695 const int index = (int)ComboBox_AddStringAscii(m_NumThreads, s);
2696 m_NumThreads.SetItemData(index, (LPARAM)(UInt32)i);
2204 if (!useAutoThreads && i == defaultValue) 2697 if (!useAutoThreads && i == defaultValue)
2205 curSel = index; 2698 curSel = index;
2206 } 2699 }
@@ -2236,7 +2729,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault)
2236 s.Add_UInt64(val); 2729 s.Add_UInt64(val);
2237 s += '%'; 2730 s += '%';
2238 if (isDefault) 2731 if (isDefault)
2239 sUser = "* "; 2732 sUser = k_Auto_Prefix;
2240 else 2733 else
2241 sRegistry = s; 2734 sRegistry = s;
2242 sUser += s; 2735 sUser += s;
@@ -2247,7 +2740,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault)
2247 sRegistry = sUser; 2740 sRegistry = sUser;
2248 for (;;) 2741 for (;;)
2249 { 2742 {
2250 int pos = sRegistry.Find(L' '); 2743 const int pos = sRegistry.Find(L' ');
2251 if (pos < 0) 2744 if (pos < 0)
2252 break; 2745 break;
2253 sRegistry.Delete(pos); 2746 sRegistry.Delete(pos);
@@ -2258,7 +2751,7 @@ int CCompressDialog::AddMemComboItem(UInt64 val, bool isPercent, bool isDefault)
2258 } 2751 }
2259 const unsigned dataIndex = _memUse_Strings.Add(sRegistry); 2752 const unsigned dataIndex = _memUse_Strings.Add(sRegistry);
2260 const int index = (int)m_MemUse.AddString(sUser); 2753 const int index = (int)m_MemUse.AddString(sUser);
2261 m_MemUse.SetItemData(index, dataIndex); 2754 m_MemUse.SetItemData(index, (LPARAM)dataIndex);
2262 return index; 2755 return index;
2263} 2756}
2264 2757
@@ -2382,11 +2875,16 @@ UInt64 CCompressDialog::GetMemoryUsage_DecompMem(UInt64 &decompressMemory)
2382 return GetMemoryUsage_Dict_DecompMem(GetDict2(), decompressMemory); 2875 return GetMemoryUsage_Dict_DecompMem(GetDict2(), decompressMemory);
2383} 2876}
2384 2877
2878
2879/*
2880we could use that function to reduce the dictionary if small RAM
2385UInt64 CCompressDialog::GetMemoryUsageComp_Threads_Dict(UInt32 numThreads, UInt64 dict64) 2881UInt64 CCompressDialog::GetMemoryUsageComp_Threads_Dict(UInt32 numThreads, UInt64 dict64)
2386{ 2882{
2387 UInt64 decompressMemory; 2883 UInt64 decompressMemory;
2388 return GetMemoryUsage_Threads_Dict_DecompMem(numThreads, dict64, decompressMemory); 2884 return GetMemoryUsage_Threads_Dict_DecompMem(numThreads, dict64, decompressMemory);
2389} 2885}
2886*/
2887
2390 2888
2391UInt64 CCompressDialog::GetMemoryUsage_Dict_DecompMem(UInt64 dict64, UInt64 &decompressMemory) 2889UInt64 CCompressDialog::GetMemoryUsage_Dict_DecompMem(UInt64 dict64, UInt64 &decompressMemory)
2392{ 2890{
@@ -2396,11 +2894,9 @@ UInt64 CCompressDialog::GetMemoryUsage_Dict_DecompMem(UInt64 dict64, UInt64 &dec
2396UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads, UInt64 dict64, UInt64 &decompressMemory) 2894UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads, UInt64 dict64, UInt64 &decompressMemory)
2397{ 2895{
2398 decompressMemory = (UInt64)(Int64)-1; 2896 decompressMemory = (UInt64)(Int64)-1;
2399 if (dict64 == (UInt64)(Int64)-1)
2400 return (UInt64)(Int64)-1;
2401 2897
2402 UInt32 level = GetLevel2(); 2898 const UInt32 level = GetLevel2();
2403 if (level == 0) 2899 if (level == 0 && !Get_ArcInfoEx().Is_Zstd())
2404 { 2900 {
2405 decompressMemory = (1 << 20); 2901 decompressMemory = (1 << 20);
2406 return decompressMemory; 2902 return decompressMemory;
@@ -2427,6 +2923,12 @@ UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads,
2427 } 2923 }
2428 2924
2429 const int methodId = GetMethodID(); 2925 const int methodId = GetMethodID();
2926
2927 if (dict64 == (UInt64)(Int64)-1
2928 // && methodId != kZSTD
2929 )
2930 return (UInt64)(Int64)-1;
2931
2430 2932
2431 switch (methodId) 2933 switch (methodId)
2432 { 2934 {
@@ -2507,7 +3009,23 @@ UInt64 CCompressDialog::GetMemoryUsage_Threads_Dict_DecompMem(UInt32 numThreads,
2507 decompressMemory = dict + (2 << 20); 3009 decompressMemory = dict + (2 << 20);
2508 return size; 3010 return size;
2509 } 3011 }
2510 3012
3013 /*
3014 case kZSTD:
3015 {
3016 CZstdEncProps props;
3017 ZstdEncProps_Init(&props);
3018 // props.level_zstd = level;
3019 props.level_7z = level;
3020 props.nbWorkers = numThreads;
3021 ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this);
3022 ZstdEncProps_NormalizeFull(&props);
3023 size = ZstdEncProps_GetMemUsage(&props);
3024 decompressMemory = (UInt64)1 << props.windowLog;
3025 return size;
3026 }
3027 */
3028
2511 case kPPMd: 3029 case kPPMd:
2512 { 3030 {
2513 decompressMemory = dict64 + (2 << 20); 3031 decompressMemory = dict64 + (2 << 20);
@@ -2613,8 +3131,109 @@ void CCompressDialog::SetMemoryUsage()
2613 const UInt64 memUsage = GetMemoryUsage_DecompMem(decompressMem); 3131 const UInt64 memUsage = GetMemoryUsage_DecompMem(decompressMem);
2614 PrintMemUsage(IDT_COMPRESS_MEMORY_VALUE, memUsage); 3132 PrintMemUsage(IDT_COMPRESS_MEMORY_VALUE, memUsage);
2615 PrintMemUsage(IDT_COMPRESS_MEMORY_DE_VALUE, decompressMem); 3133 PrintMemUsage(IDT_COMPRESS_MEMORY_DE_VALUE, decompressMem);
3134 #ifdef PRINT_PARAMS
3135 Print_Params();
3136 #endif
2616} 3137}
2617 3138
3139
3140
3141#ifdef PRINT_PARAMS
3142
3143static const char kPropDelimeter = ' '; // ':'
3144
3145static void AddPropName(AString &s, const char *name)
3146{
3147 if (!s.IsEmpty())
3148 s += kPropDelimeter;
3149 s += name;
3150}
3151
3152static void AddProp(AString &s, const char *name, unsigned v)
3153{
3154 AddPropName(s, name);
3155 s.Add_UInt32(v);
3156}
3157
3158static void AddProp_switch(AString &s, const char *name, E_ZSTD_paramSwitch_e e)
3159{
3160 AddPropName(s, name);
3161 s += e == k_ZSTD_ps_enable ? "" : "-";
3162}
3163
3164static void PrintPropAsLog(AString &s, const char *name, size_t v)
3165{
3166 AddPropName(s, name);
3167 for (unsigned i = 0; i < sizeof(size_t) * 8; i++)
3168 {
3169 if (((size_t)1 << i) == v)
3170 {
3171 s.Add_UInt32(i);
3172 return;
3173 }
3174 }
3175 char c = 'b';
3176 if ((v & 0x3FFFFFFF) == 0) { v >>= 30; c = 'G'; }
3177 else if ((v & 0xFFFFF) == 0) { v >>= 20; c = 'M'; }
3178 else if ((v & 0x3FF) == 0) { v >>= 10; c = 'K'; }
3179 s.Add_UInt64(v);
3180 s += c;
3181}
3182
3183static void ZstdEncProps_Print(CZstdEncProps *props, AString &s)
3184{
3185 if (props->level_zstd >= 0)
3186 AddProp(s, "zx", props->level_zstd);
3187 else
3188 AddProp(s, "zf", -(props->level_zstd));
3189 AddProp(s, "a", props->strategy);
3190 AddProp(s, "d", props->windowLog);
3191 AddProp(s, "zclog", props->chainLog);
3192 AddProp(s, "zhb", props->hashLog);
3193 AddProp(s, "mml", props->minMatch);
3194 AddProp(s, "mcb", props->searchLog);
3195 AddProp(s, "fb", props->targetLength);
3196 AddProp(s, "mt", props->nbWorkers);
3197 PrintPropAsLog(s, "c", props->jobSize);
3198 AddProp(s, "zov", props->overlapLog);
3199 PrintPropAsLog(s, "ztps", props->targetPrefixSize);
3200 AddProp_switch(s, "zmfr", props->useRowMatchFinder);
3201 if (props->ldmParams.enableLdm == k_ZSTD_ps_enable)
3202 {
3203 AddProp_switch(s, "zle", props->ldmParams.enableLdm);
3204 AddProp(s, "zlhb", props->ldmParams.hashLog);
3205 AddProp(s, "zlbb", props->ldmParams.bucketSizeLog);
3206 AddProp(s, "zlmml", props->ldmParams.minMatchLength);
3207 AddProp(s, "zlhrb", props->ldmParams.hashRateLog);
3208 }
3209}
3210
3211void CCompressDialog::Print_Params()
3212{
3213 {
3214 CZstdEncProps props;
3215 ZstdEncProps_Init(&props);
3216 // props.level_zstd = level;
3217 props.level_7z = GetLevel2();
3218 ZstdEncProps_SetDictProps_From_CompressDialog(&props, *this);
3219 {
3220 UInt32 order = GetOrderSpec();
3221 if (order != (UInt32)(Int32)-1)
3222 props.targetLength = GetOrderSpec();
3223 }
3224 props.nbWorkers = GetNumThreads2();
3225 // props.windowLog = 18; // for debug
3226 ZstdEncProps_NormalizeFull(&props);
3227 AString s;
3228 ZstdEncProps_Print(&props, s);
3229 SetItemTextA(IDT_COMPRESS_PARAMS_INFO, s);
3230 }
3231}
3232
3233#endif // PRINT_PARAMS
3234
3235
3236
2618void CCompressDialog::SetParams() 3237void CCompressDialog::SetParams()
2619{ 3238{
2620 const CArcInfoEx &ai = Get_ArcInfoEx(); 3239 const CArcInfoEx &ai = Get_ArcInfoEx();
@@ -2663,6 +3282,24 @@ void CCompressDialog::SaveOptionsInMem()
2663 } 3282 }
2664 fo.Dictionary = dict32; 3283 fo.Dictionary = dict32;
2665 } 3284 }
3285 /*
3286 {
3287 const UInt64 dict64 = GetDictChainSpec();
3288 UInt32 dict32;
3289 if (dict64 == (UInt64)(Int64)-1)
3290 dict32 = (UInt32)(Int32)-1;
3291 else
3292 {
3293 dict32 = (UInt32)dict64;
3294 if (dict64 != dict32)
3295 {
3296 dict32 = (UInt32)(Int32)-2;
3297 // dict32 = k_Zstd_MAX_DictSize; // it must be larger than threshold
3298 }
3299 }
3300 fo.DictionaryChain = dict32;
3301 }
3302 */
2666 3303
2667 fo.Order = GetOrderSpec(); 3304 fo.Order = GetOrderSpec();
2668 fo.Method = GetMethodSpec(); 3305 fo.Method = GetMethodSpec();
@@ -2836,7 +3473,7 @@ int COptionsDialog::AddPrec(unsigned prec, bool isDefault)
2836 else 3473 else
2837 s.Add_UInt32(prec); 3474 s.Add_UInt32(prec);
2838 const int index = (int)m_Prec.AddString(s); 3475 const int index = (int)m_Prec.AddString(s);
2839 m_Prec.SetItemData(index, writePrec); 3476 m_Prec.SetItemData(index, (LPARAM)writePrec);
2840 return index; 3477 return index;
2841} 3478}
2842 3479
@@ -2874,7 +3511,7 @@ void COptionsDialog::SetPrec()
2874 // flags = (UInt32)1 << kTimePrec_Unix; 3511 // flags = (UInt32)1 << kTimePrec_Unix;
2875 3512
2876 s += ":"; 3513 s += ":";
2877 if (methodID >= 0 && (unsigned)methodID < ARRAY_SIZE(kMethodsNames)) 3514 if (methodID >= 0 && (unsigned)methodID < Z7_ARRAY_SIZE(kMethodsNames))
2878 s += kMethodsNames[methodID]; 3515 s += kMethodsNames[methodID];
2879 if (methodID == kPosix) 3516 if (methodID == kPosix)
2880 { 3517 {
@@ -3038,7 +3675,7 @@ void COptionsDialog::On_CheckBoxSet_Clicked(const CBoolBox &bb)
3038 3675
3039 3676
3040 3677
3041#ifdef LANG 3678#ifdef Z7_LANG
3042static const UInt32 kLangIDs_Options[] = 3679static const UInt32 kLangIDs_Options[] =
3043{ 3680{
3044 IDX_COMPRESS_NT_SYM_LINKS, 3681 IDX_COMPRESS_NT_SYM_LINKS,
@@ -3059,9 +3696,9 @@ static const UInt32 kLangIDs_Options[] =
3059 3696
3060bool COptionsDialog::OnInit() 3697bool COptionsDialog::OnInit()
3061{ 3698{
3062 #ifdef LANG 3699 #ifdef Z7_LANG
3063 LangSetWindowText(*this, IDB_COMPRESS_OPTIONS); // IDS_OPTIONS 3700 LangSetWindowText(*this, IDB_COMPRESS_OPTIONS); // IDS_OPTIONS
3064 LangSetDlgItems(*this, kLangIDs_Options, ARRAY_SIZE(kLangIDs_Options)); 3701 LangSetDlgItems(*this, kLangIDs_Options, Z7_ARRAY_SIZE(kLangIDs_Options));
3065 // LangSetDlgItemText(*this, IDB_COMPRESS_TIME_DEFAULT, IDB_COMPRESS_TIME_DEFAULT); 3702 // LangSetDlgItemText(*this, IDB_COMPRESS_TIME_DEFAULT, IDB_COMPRESS_TIME_DEFAULT);
3066 // LangSetDlgItemText(*this, IDX_COMPRESS_TIME_DEFAULT, IDX_COMPRESS_TIME_DEFAULT); 3703 // LangSetDlgItemText(*this, IDX_COMPRESS_TIME_DEFAULT, IDX_COMPRESS_TIME_DEFAULT);
3067 #endif 3704 #endif
@@ -3124,7 +3761,7 @@ bool COptionsDialog::OnInit()
3124} 3761}
3125 3762
3126 3763
3127bool COptionsDialog::OnCommand(int code, int itemID, LPARAM lParam) 3764bool COptionsDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
3128{ 3765{
3129 if (code == CBN_SELCHANGE) 3766 if (code == CBN_SELCHANGE)
3130 { 3767 {
@@ -3142,7 +3779,7 @@ bool COptionsDialog::OnCommand(int code, int itemID, LPARAM lParam)
3142} 3779}
3143 3780
3144 3781
3145bool COptionsDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 3782bool COptionsDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
3146{ 3783{
3147 switch (buttonID) 3784 switch (buttonID)
3148 { 3785 {
@@ -3179,5 +3816,5 @@ void COptionsDialog::OnOK()
3179 3816
3180void COptionsDialog::OnHelp() 3817void COptionsDialog::OnHelp()
3181{ 3818{
3182 ShowHelpWindow(kHelpTopic); 3819 ShowHelpWindow(kHelpTopic_Options);
3183} 3820}
diff --git a/CPP/7zip/UI/GUI/CompressDialog.h b/CPP/7zip/UI/GUI/CompressDialog.h
index d4590c9..c2d2699 100644
--- a/CPP/7zip/UI/GUI/CompressDialog.h
+++ b/CPP/7zip/UI/GUI/CompressDialog.h
@@ -1,7 +1,7 @@
1// CompressDialog.h 1// CompressDialog.h
2 2
3#ifndef __COMPRESS_DIALOG_H 3#ifndef ZIP7_INC_COMPRESS_DIALOG_H
4#define __COMPRESS_DIALOG_H 4#define ZIP7_INC_COMPRESS_DIALOG_H
5 5
6#include "../../../Common/Wildcard.h" 6#include "../../../Common/Wildcard.h"
7 7
@@ -45,6 +45,7 @@ namespace NCompressDialog
45 UInt32 Level; 45 UInt32 Level;
46 UString Method; 46 UString Method;
47 UInt64 Dict64; 47 UInt64 Dict64;
48 // UInt64 Dict64_Chain;
48 bool OrderMode; 49 bool OrderMode;
49 UInt32 Order; 50 UInt32 Order;
50 UString Options; 51 UString Options;
@@ -93,6 +94,7 @@ namespace NCompressDialog
93 NumThreads = (UInt32)(Int32)-1; 94 NumThreads = (UInt32)(Int32)-1;
94 SolidIsSpecified = false; 95 SolidIsSpecified = false;
95 Dict64 = (UInt64)(Int64)(-1); 96 Dict64 = (UInt64)(Int64)(-1);
97 // Dict64_Chain = (UInt64)(Int64)(-1);
96 OrderMode = false; 98 OrderMode = false;
97 Method.Empty(); 99 Method.Empty();
98 Options.Empty(); 100 Options.Empty();
@@ -144,12 +146,15 @@ class CCompressDialog: public NWindows::NControl::CModalDialog
144 NWindows::NControl::CComboBox m_Level; 146 NWindows::NControl::CComboBox m_Level;
145 NWindows::NControl::CComboBox m_Method; 147 NWindows::NControl::CComboBox m_Method;
146 NWindows::NControl::CComboBox m_Dictionary; 148 NWindows::NControl::CComboBox m_Dictionary;
149 // NWindows::NControl::CComboBox m_Dictionary_Chain;
147 NWindows::NControl::CComboBox m_Order; 150 NWindows::NControl::CComboBox m_Order;
148 NWindows::NControl::CComboBox m_Solid; 151 NWindows::NControl::CComboBox m_Solid;
149 NWindows::NControl::CComboBox m_NumThreads; 152 NWindows::NControl::CComboBox m_NumThreads;
150 NWindows::NControl::CComboBox m_MemUse; 153 NWindows::NControl::CComboBox m_MemUse;
151 NWindows::NControl::CComboBox m_Volume; 154 NWindows::NControl::CComboBox m_Volume;
152 155
156 int _dictionaryCombo_left;
157
153 UStringVector _memUse_Strings; 158 UStringVector _memUse_Strings;
154 159
155 NWindows::NControl::CDialogChildControl m_Params; 160 NWindows::NControl::CDialogChildControl m_Params;
@@ -163,6 +168,7 @@ class CCompressDialog: public NWindows::NControl::CModalDialog
163 168
164 int _auto_MethodId; 169 int _auto_MethodId;
165 UInt32 _auto_Dict; // (UInt32)(Int32)-1 means unknown 170 UInt32 _auto_Dict; // (UInt32)(Int32)-1 means unknown
171 UInt32 _auto_Dict_Chain; // (UInt32)(Int32)-1 means unknown
166 UInt32 _auto_Order; 172 UInt32 _auto_Order;
167 UInt64 _auto_Solid; 173 UInt64 _auto_Solid;
168 UInt32 _auto_NumThreads; 174 UInt32 _auto_NumThreads;
@@ -201,7 +207,7 @@ public:
201 void CheckSFXNameChange(); 207 void CheckSFXNameChange();
202 void SetArchiveName2(bool prevWasSFX); 208 void SetArchiveName2(bool prevWasSFX);
203 209
204 int GetStaticFormatIndex(); 210 unsigned GetStaticFormatIndex();
205 211
206 void SetNearestSelectComboBox(NWindows::NControl::CComboBox &comboBox, UInt32 value); 212 void SetNearestSelectComboBox(NWindows::NControl::CComboBox &comboBox, UInt32 value);
207 213
@@ -224,6 +230,7 @@ public:
224 { 230 {
225 SetDictionary2(); 231 SetDictionary2();
226 EnableMultiCombo(IDC_COMPRESS_DICTIONARY); 232 EnableMultiCombo(IDC_COMPRESS_DICTIONARY);
233 // EnableMultiCombo(IDC_COMPRESS_DICTIONARY2);
227 SetOrder2(); 234 SetOrder2();
228 EnableMultiCombo(IDC_COMPRESS_ORDER); 235 EnableMultiCombo(IDC_COMPRESS_ORDER);
229 } 236 }
@@ -243,6 +250,7 @@ public:
243 250
244 int AddDict2(size_t sizeReal, size_t sizeShow); 251 int AddDict2(size_t sizeReal, size_t sizeShow);
245 int AddDict(size_t size); 252 int AddDict(size_t size);
253 // int AddDict_Chain(size_t size);
246 254
247 void SetDictionary2(); 255 void SetDictionary2();
248 256
@@ -254,6 +262,8 @@ public:
254 UInt32 GetLevel2(); 262 UInt32 GetLevel2();
255 263
256 UInt64 GetDictSpec() { return GetComboValue_64(m_Dictionary, 1); } 264 UInt64 GetDictSpec() { return GetComboValue_64(m_Dictionary, 1); }
265 // UInt64 GetDictChainSpec() { return GetComboValue_64(m_Dictionary_Chain, 1); }
266
257 UInt64 GetDict2() 267 UInt64 GetDict2()
258 { 268 {
259 UInt64 num = GetDictSpec(); 269 UInt64 num = GetDictSpec();
@@ -319,6 +329,8 @@ public:
319 329
320 void PrintMemUsage(UINT res, UInt64 value); 330 void PrintMemUsage(UINT res, UInt64 value);
321 void SetMemoryUsage(); 331 void SetMemoryUsage();
332 void Print_Params();
333
322 void SetParams(); 334 void SetParams();
323 335
324 void SaveOptionsInMem(); 336 void SaveOptionsInMem();
@@ -328,7 +340,9 @@ public:
328 340
329 unsigned GetFormatIndex(); 341 unsigned GetFormatIndex();
330 bool SetArcPathFields(const UString &path, UString &name, bool always); 342 bool SetArcPathFields(const UString &path, UString &name, bool always);
331 bool GetFinalPath_Smart(UString &resPath); 343 bool SetArcPathFields(const UString &path);
344 bool GetFinalPath_Smart(UString &resPath) const;
345 void ArcPath_WasChanged(const UString &newPath);
332 346
333 void CheckSFXControlsEnable(); 347 void CheckSFXControlsEnable();
334 // void CheckVolumeEnable(); 348 // void CheckVolumeEnable();
@@ -339,11 +353,12 @@ public:
339 bool IsSFX(); 353 bool IsSFX();
340 void OnButtonSFX(); 354 void OnButtonSFX();
341 355
342 virtual bool OnInit(); 356 virtual bool OnInit() Z7_override;
343 virtual bool OnCommand(int code, int itemID, LPARAM lParam); 357 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam) Z7_override;
344 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 358 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override;
345 virtual void OnOK(); 359 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
346 virtual void OnHelp(); 360 virtual void OnOK() Z7_override;
361 virtual void OnHelp() Z7_override;
347 362
348 void MessageBoxError(LPCWSTR message) 363 void MessageBoxError(LPCWSTR message)
349 { 364 {
@@ -361,15 +376,14 @@ public:
361 376
362 NCompressDialog::CInfo Info; 377 NCompressDialog::CInfo Info;
363 UString OriginalFileName; // for bzip2, gzip2 378 UString OriginalFileName; // for bzip2, gzip2
364 bool CurrentDirWasChanged;
365 379
366 INT_PTR Create(HWND wndParent = 0) 380 INT_PTR Create(HWND wndParent = NULL)
367 { 381 {
368 BIG_DIALOG_SIZE(400, 320); 382 BIG_DIALOG_SIZE(400, 320);
369 return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS), wndParent); 383 return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS), wndParent);
370 } 384 }
371 385
372 CCompressDialog(): CurrentDirWasChanged(false) {}; 386 CCompressDialog() {}
373}; 387};
374 388
375 389
@@ -383,10 +397,10 @@ class COptionsDialog: public NWindows::NControl::CModalDialog
383 bool DefaultVal; 397 bool DefaultVal;
384 CBoolPair BoolPair; 398 CBoolPair BoolPair;
385 399
386 int Id; 400 unsigned Id;
387 int Set_Id; 401 unsigned Set_Id;
388 402
389 void SetIDs(int id, int set_Id) 403 void SetIDs(unsigned id, unsigned set_Id)
390 { 404 {
391 Id = id; 405 Id = id;
392 Set_Id = set_Id; 406 Set_Id = set_Id;
@@ -442,15 +456,15 @@ class COptionsDialog: public NWindows::NControl::CModalDialog
442 void On_CheckBoxSet_Prec_Clicked(); 456 void On_CheckBoxSet_Prec_Clicked();
443 void On_CheckBoxSet_Clicked(const CBoolBox &bb); 457 void On_CheckBoxSet_Clicked(const CBoolBox &bb);
444 458
445 virtual bool OnInit(); 459 virtual bool OnInit() Z7_override;
446 virtual bool OnCommand(int code, int itemID, LPARAM lParam); 460 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam) Z7_override;
447 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 461 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
448 virtual void OnOK(); 462 virtual void OnOK() Z7_override;
449 virtual void OnHelp(); 463 virtual void OnHelp() Z7_override;
450 464
451public: 465public:
452 466
453 INT_PTR Create(HWND wndParent = 0) 467 INT_PTR Create(HWND wndParent = NULL)
454 { 468 {
455 BIG_DIALOG_SIZE(240, 232); 469 BIG_DIALOG_SIZE(240, 232);
456 return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS_OPTIONS), wndParent); 470 return CModalDialog::Create(SIZED_DIALOG(IDD_COMPRESS_OPTIONS), wndParent);
@@ -461,7 +475,7 @@ public:
461 // , TimePrec(0) 475 // , TimePrec(0)
462 { 476 {
463 Reset_TimePrec(); 477 Reset_TimePrec();
464 }; 478 }
465}; 479};
466 480
467#endif 481#endif
diff --git a/CPP/7zip/UI/GUI/CompressDialog.rc b/CPP/7zip/UI/GUI/CompressDialog.rc
index d47a3ed..f04329e 100644
--- a/CPP/7zip/UI/GUI/CompressDialog.rc
+++ b/CPP/7zip/UI/GUI/CompressDialog.rc
@@ -48,6 +48,11 @@
48#define GROUP_Y_SIZE_ENCRYPT 128 48#define GROUP_Y_SIZE_ENCRYPT 128
49#endif 49#endif
50 50
51// #define DICT_SIZE_SPACE 8
52// #define DICT_SIZE 54
53// #define DICT_x (g1x + g1xs - DICT_SIZE)
54// #define DICT2_x (DICT_x - DICT_SIZE_SPACE - DICT_SIZE)
55
51#define yPsw (yOpt + GROUP_Y_SIZE + 8) 56#define yPsw (yOpt + GROUP_Y_SIZE + 8)
52 57
53IDD_COMPRESS DIALOG 0, 0, xs, ys MY_MODAL_DIALOG_STYLE MY_FONT 58IDD_COMPRESS DIALOG 0, 0, xs, ys MY_MODAL_DIALOG_STYLE MY_FONT
@@ -69,9 +74,14 @@ BEGIN
69 74
70 LTEXT "&Dictionary size:", IDT_COMPRESS_DICTIONARY, m, 104, g0xs, 8 75 LTEXT "&Dictionary size:", IDT_COMPRESS_DICTIONARY, m, 104, g0xs, 8
71 COMBOBOX IDC_COMPRESS_DICTIONARY, g1x, 102, g1xs, 167, MY_COMBO 76 COMBOBOX IDC_COMPRESS_DICTIONARY, g1x, 102, g1xs, 167, MY_COMBO
77 // LTEXT "&Dictionary size:", IDT_COMPRESS_DICTIONARY, m, 104, DICT_x - m, 16 // 8, SS_LEFTNOWORDWRAP
78 // LTEXT "", IDT_COMPRESS_PARAMS_INFO, m, 283, xs, MY_TEXT_NOPREFIX
79 // CTEXT "-", 0, DICT_x - DICT_SIZE_SPACE, 104, DICT_SIZE_SPACE, 8
80 // COMBOBOX IDC_COMPRESS_DICTIONARY2, DICT2_x, 102, DICT_SIZE, 140, MY_COMBO
81 // COMBOBOX IDC_COMPRESS_DICTIONARY, DICT_x, 102, DICT_SIZE, 140, MY_COMBO
72 82
73 LTEXT "&Word size:", IDT_COMPRESS_ORDER, m, 125, g0xs, 8 83 LTEXT "&Word size:", IDT_COMPRESS_ORDER, m, 125, g0xs, 8
74 COMBOBOX IDC_COMPRESS_ORDER, g1x, 123, g1xs, 141, MY_COMBO 84 COMBOBOX IDC_COMPRESS_ORDER, g1x, 123, g1xs, 140, MY_COMBO
75 85
76 LTEXT "&Solid Block size:", IDT_COMPRESS_SOLID, m, 146, g0xs, 8 86 LTEXT "&Solid Block size:", IDT_COMPRESS_SOLID, m, 146, g0xs, 8
77 COMBOBOX IDC_COMPRESS_SOLID, g1x, 144, g1xs, 140, MY_COMBO 87 COMBOBOX IDC_COMPRESS_SOLID, g1x, 144, g1xs, 140, MY_COMBO
diff --git a/CPP/7zip/UI/GUI/CompressDialogRes.h b/CPP/7zip/UI/GUI/CompressDialogRes.h
index 80b39be..aa25b89 100644
--- a/CPP/7zip/UI/GUI/CompressDialogRes.h
+++ b/CPP/7zip/UI/GUI/CompressDialogRes.h
@@ -22,6 +22,7 @@
22#define IDG_COMPRESS_NTFS 115 22#define IDG_COMPRESS_NTFS 115
23#define IDC_COMPRESS_PATH_MODE 116 23#define IDC_COMPRESS_PATH_MODE 116
24#define IDC_COMPRESS_MEM_USE 117 24#define IDC_COMPRESS_MEM_USE 117
25// #define IDC_COMPRESS_DICTIONARY2 118
25 26
26#define IDE_COMPRESS_PASSWORD1 120 27#define IDE_COMPRESS_PASSWORD1 120
27#define IDE_COMPRESS_PASSWORD2 121 28#define IDE_COMPRESS_PASSWORD2 121
@@ -32,6 +33,7 @@
32// #define IDB_COMPRESS_OPTIONS 140 33// #define IDB_COMPRESS_OPTIONS 140
33#define IDB_COMPRESS_OPTIONS 2100 34#define IDB_COMPRESS_OPTIONS 2100
34#define IDT_COMPRESS_OPTIONS 141 35#define IDT_COMPRESS_OPTIONS 141
36// #define IDT_COMPRESS_PARAMS_INFO 142
35 37
36#define IDT_COMPRESS_PATH_MODE 3410 38#define IDT_COMPRESS_PATH_MODE 3410
37 39
diff --git a/CPP/7zip/UI/GUI/ExtractDialog.cpp b/CPP/7zip/UI/GUI/ExtractDialog.cpp
index 5132084..4628482 100644
--- a/CPP/7zip/UI/GUI/ExtractDialog.cpp
+++ b/CPP/7zip/UI/GUI/ExtractDialog.cpp
@@ -9,7 +9,7 @@
9#include "../../../Windows/FileDir.h" 9#include "../../../Windows/FileDir.h"
10#include "../../../Windows/ResourceString.h" 10#include "../../../Windows/ResourceString.h"
11 11
12#ifndef NO_REGISTRY 12#ifndef Z7_NO_REGISTRY
13#include "../FileManager/HelpUtils.h" 13#include "../FileManager/HelpUtils.h"
14#endif 14#endif
15 15
@@ -28,7 +28,7 @@ using namespace NName;
28 28
29extern HINSTANCE g_hInstance; 29extern HINSTANCE g_hInstance;
30 30
31#ifndef _SFX 31#ifndef Z7_SFX
32 32
33static const UInt32 kPathMode_IDs[] = 33static const UInt32 kPathMode_IDs[] =
34{ 34{
@@ -70,7 +70,7 @@ static const
70 70
71#endif 71#endif
72 72
73#ifdef LANG 73#ifdef Z7_LANG
74 74
75static const UInt32 kLangIDs[] = 75static const UInt32 kLangIDs[] =
76{ 76{
@@ -87,23 +87,23 @@ static const UInt32 kLangIDs[] =
87 87
88// static const int kWildcardsButtonIndex = 2; 88// static const int kWildcardsButtonIndex = 2;
89 89
90#ifndef NO_REGISTRY 90#ifndef Z7_NO_REGISTRY
91static const unsigned kHistorySize = 16; 91static const unsigned kHistorySize = 16;
92#endif 92#endif
93 93
94#ifndef _SFX 94#ifndef Z7_SFX
95 95
96// it's used in CompressDialog also 96// it's used in CompressDialog also
97void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal); 97void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal);
98void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal) 98void AddComboItems(NControl::CComboBox &combo, const UInt32 *langIDs, unsigned numItems, const int *values, int curVal)
99{ 99{
100 int curSel = 0; 100 unsigned curSel = 0;
101 for (unsigned i = 0; i < numItems; i++) 101 for (unsigned i = 0; i < numItems; i++)
102 { 102 {
103 UString s = LangString(langIDs[i]); 103 UString s = LangString(langIDs[i]);
104 s.RemoveChar(L'&'); 104 s.RemoveChar(L'&');
105 int index = (int)combo.AddString(s); 105 const int index = (int)combo.AddString(s);
106 combo.SetItemData(index, i); 106 combo.SetItemData(index, (LPARAM)i);
107 if (values[i] == curVal) 107 if (values[i] == curVal)
108 curSel = i; 108 curSel = i;
109 } 109 }
@@ -126,8 +126,8 @@ void CExtractDialog::CheckButton_TwoBools(UINT id, const CBoolPair &b1, const CB
126 126
127void CExtractDialog::GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2) 127void CExtractDialog::GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2)
128{ 128{
129 bool val = IsButtonCheckedBool(id); 129 const bool val = IsButtonCheckedBool(id);
130 bool oldVal = GetBoolsVal(b1, b2); 130 const bool oldVal = GetBoolsVal(b1, b2);
131 if (val != oldVal) 131 if (val != oldVal)
132 b1.Def = b2.Def = true; 132 b1.Def = b2.Def = true;
133 b1.Val = b2.Val = val; 133 b1.Val = b2.Val = val;
@@ -137,7 +137,7 @@ void CExtractDialog::GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2)
137 137
138bool CExtractDialog::OnInit() 138bool CExtractDialog::OnInit()
139{ 139{
140 #ifdef LANG 140 #ifdef Z7_LANG
141 { 141 {
142 UString s; 142 UString s;
143 LangString_OnlyFromLangFile(IDD_EXTRACT, s); 143 LangString_OnlyFromLangFile(IDD_EXTRACT, s);
@@ -150,18 +150,18 @@ bool CExtractDialog::OnInit()
150 } 150 }
151 SetText(s); 151 SetText(s);
152 // LangSetWindowText(*this, IDD_EXTRACT); 152 // LangSetWindowText(*this, IDD_EXTRACT);
153 LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); 153 LangSetDlgItems(*this, kLangIDs, Z7_ARRAY_SIZE(kLangIDs));
154 } 154 }
155 #endif 155 #endif
156 156
157 #ifndef _SFX 157 #ifndef Z7_SFX
158 _passwordControl.Attach(GetItem(IDE_EXTRACT_PASSWORD)); 158 _passwordControl.Attach(GetItem(IDE_EXTRACT_PASSWORD));
159 _passwordControl.SetText(Password); 159 _passwordControl.SetText(Password);
160 _passwordControl.SetPasswordChar(TEXT('*')); 160 _passwordControl.SetPasswordChar(TEXT('*'));
161 _pathName.Attach(GetItem(IDE_EXTRACT_NAME)); 161 _pathName.Attach(GetItem(IDE_EXTRACT_NAME));
162 #endif 162 #endif
163 163
164 #ifdef NO_REGISTRY 164 #ifdef Z7_NO_REGISTRY
165 165
166 PathMode = NExtract::NPathMode::kFullPaths; 166 PathMode = NExtract::NPathMode::kFullPaths;
167 OverwriteMode = NExtract::NOverwriteMode::kAsk; 167 OverwriteMode = NExtract::NOverwriteMode::kAsk;
@@ -191,7 +191,7 @@ bool CExtractDialog::OnInit()
191 191
192 UString pathPrefix = DirPath; 192 UString pathPrefix = DirPath;
193 193
194 #ifndef _SFX 194 #ifndef Z7_SFX
195 195
196 if (_info.SplitDest.Val) 196 if (_info.SplitDest.Val)
197 { 197 {
@@ -210,7 +210,7 @@ bool CExtractDialog::OnInit()
210 210
211 _path.SetText(pathPrefix); 211 _path.SetText(pathPrefix);
212 212
213 #ifndef NO_REGISTRY 213 #ifndef Z7_NO_REGISTRY
214 for (unsigned i = 0; i < _info.Paths.Size() && i < kHistorySize; i++) 214 for (unsigned i = 0; i < _info.Paths.Size() && i < kHistorySize; i++)
215 _path.AddString(_info.Paths[i]); 215 _path.AddString(_info.Paths[i]);
216 #endif 216 #endif
@@ -222,13 +222,13 @@ bool CExtractDialog::OnInit()
222 _path.SetCurSel(-1); 222 _path.SetCurSel(-1);
223 */ 223 */
224 224
225 #ifndef _SFX 225 #ifndef Z7_SFX
226 226
227 _pathMode.Attach(GetItem(IDC_EXTRACT_PATH_MODE)); 227 _pathMode.Attach(GetItem(IDC_EXTRACT_PATH_MODE));
228 _overwriteMode.Attach(GetItem(IDC_EXTRACT_OVERWRITE_MODE)); 228 _overwriteMode.Attach(GetItem(IDC_EXTRACT_OVERWRITE_MODE));
229 229
230 AddComboItems(_pathMode, kPathMode_IDs, ARRAY_SIZE(kPathMode_IDs), kPathModeButtonsVals, PathMode); 230 AddComboItems(_pathMode, kPathMode_IDs, Z7_ARRAY_SIZE(kPathMode_IDs), kPathModeButtonsVals, PathMode);
231 AddComboItems(_overwriteMode, kOverwriteMode_IDs, ARRAY_SIZE(kOverwriteMode_IDs), kOverwriteButtonsVals, OverwriteMode); 231 AddComboItems(_overwriteMode, kOverwriteMode_IDs, Z7_ARRAY_SIZE(kOverwriteMode_IDs), kOverwriteButtonsVals, OverwriteMode);
232 232
233 #endif 233 #endif
234 234
@@ -243,7 +243,7 @@ bool CExtractDialog::OnInit()
243 return CModalDialog::OnInit(); 243 return CModalDialog::OnInit();
244} 244}
245 245
246#ifndef _SFX 246#ifndef Z7_SFX
247void CExtractDialog::UpdatePasswordControl() 247void CExtractDialog::UpdatePasswordControl()
248{ 248{
249 _passwordControl.SetPasswordChar(IsShowPasswordChecked() ? 0 : TEXT('*')); 249 _passwordControl.SetPasswordChar(IsShowPasswordChecked() ? 0 : TEXT('*'));
@@ -253,14 +253,14 @@ void CExtractDialog::UpdatePasswordControl()
253} 253}
254#endif 254#endif
255 255
256bool CExtractDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 256bool CExtractDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
257{ 257{
258 switch (buttonID) 258 switch (buttonID)
259 { 259 {
260 case IDB_EXTRACT_SET_PATH: 260 case IDB_EXTRACT_SET_PATH:
261 OnButtonSetPath(); 261 OnButtonSetPath();
262 return true; 262 return true;
263 #ifndef _SFX 263 #ifndef Z7_SFX
264 case IDX_EXTRACT_NAME_ENABLE: 264 case IDX_EXTRACT_NAME_ENABLE:
265 ShowItem_Bool(IDE_EXTRACT_NAME, IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE)); 265 ShowItem_Bool(IDE_EXTRACT_NAME, IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE));
266 return true; 266 return true;
@@ -282,7 +282,7 @@ void CExtractDialog::OnButtonSetPath()
282 UString resultPath; 282 UString resultPath;
283 if (!MyBrowseForFolder(*this, title, currentPath, resultPath)) 283 if (!MyBrowseForFolder(*this, title, currentPath, resultPath))
284 return; 284 return;
285 #ifndef NO_REGISTRY 285 #ifndef Z7_NO_REGISTRY
286 _path.SetCurSel(-1); 286 _path.SetCurSel(-1);
287 #endif 287 #endif
288 _path.SetText(resultPath); 288 _path.SetText(resultPath);
@@ -299,7 +299,7 @@ void AddUniqueString(UStringVector &list, const UString &s)
299 299
300void CExtractDialog::OnOK() 300void CExtractDialog::OnOK()
301{ 301{
302 #ifndef _SFX 302 #ifndef Z7_SFX
303 int pathMode2 = kPathModeButtonsVals[_pathMode.GetCurSel()]; 303 int pathMode2 = kPathModeButtonsVals[_pathMode.GetCurSel()];
304 if (PathMode != NExtract::NPathMode::kCurPaths || 304 if (PathMode != NExtract::NPathMode::kCurPaths ||
305 pathMode2 != NExtract::NPathMode::kFullPaths) 305 pathMode2 != NExtract::NPathMode::kFullPaths)
@@ -313,7 +313,7 @@ void CExtractDialog::OnOK()
313 313
314 #endif 314 #endif
315 315
316 #ifndef NO_REGISTRY 316 #ifndef Z7_NO_REGISTRY
317 317
318 // GetButton_Bools(IDX_EXTRACT_ALT_STREAMS, AltStreams, _info.AltStreams); 318 // GetButton_Bools(IDX_EXTRACT_ALT_STREAMS, AltStreams, _info.AltStreams);
319 GetButton_Bools(IDX_EXTRACT_NT_SECUR, NtSecurity, _info.NtSecurity); 319 GetButton_Bools(IDX_EXTRACT_NT_SECUR, NtSecurity, _info.NtSecurity);
@@ -350,7 +350,7 @@ void CExtractDialog::OnOK()
350 350
351 UString s; 351 UString s;
352 352
353 #ifdef NO_REGISTRY 353 #ifdef Z7_NO_REGISTRY
354 354
355 _path.GetText(s); 355 _path.GetText(s);
356 356
@@ -371,9 +371,9 @@ void CExtractDialog::OnOK()
371 s.Trim(); 371 s.Trim();
372 NName::NormalizeDirPathPrefix(s); 372 NName::NormalizeDirPathPrefix(s);
373 373
374 #ifndef _SFX 374 #ifndef Z7_SFX
375 375
376 bool splitDest = IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE); 376 const bool splitDest = IsButtonCheckedBool(IDX_EXTRACT_NAME_ENABLE);
377 if (splitDest) 377 if (splitDest)
378 { 378 {
379 UString pathName; 379 UString pathName;
@@ -392,9 +392,9 @@ void CExtractDialog::OnOK()
392 392
393 DirPath = s; 393 DirPath = s;
394 394
395 #ifndef NO_REGISTRY 395 #ifndef Z7_NO_REGISTRY
396 _info.Paths.Clear(); 396 _info.Paths.Clear();
397 #ifndef _SFX 397 #ifndef Z7_SFX
398 AddUniqueString(_info.Paths, s); 398 AddUniqueString(_info.Paths, s);
399 #endif 399 #endif
400 for (int i = 0; i < _path.GetCount(); i++) 400 for (int i = 0; i < _path.GetCount(); i++)
@@ -411,7 +411,7 @@ void CExtractDialog::OnOK()
411 CModalDialog::OnOK(); 411 CModalDialog::OnOK();
412} 412}
413 413
414#ifndef NO_REGISTRY 414#ifndef Z7_NO_REGISTRY
415#define kHelpTopic "fm/plugins/7-zip/extract.htm" 415#define kHelpTopic "fm/plugins/7-zip/extract.htm"
416void CExtractDialog::OnHelp() 416void CExtractDialog::OnHelp()
417{ 417{
diff --git a/CPP/7zip/UI/GUI/ExtractDialog.h b/CPP/7zip/UI/GUI/ExtractDialog.h
index 33349ff..1565fb8 100644
--- a/CPP/7zip/UI/GUI/ExtractDialog.h
+++ b/CPP/7zip/UI/GUI/ExtractDialog.h
@@ -1,7 +1,7 @@
1// ExtractDialog.h 1// ExtractDialog.h
2 2
3#ifndef __EXTRACT_DIALOG_H 3#ifndef ZIP7_INC_EXTRACT_DIALOG_H
4#define __EXTRACT_DIALOG_H 4#define ZIP7_INC_EXTRACT_DIALOG_H
5 5
6#include "ExtractDialogRes.h" 6#include "ExtractDialogRes.h"
7 7
@@ -12,7 +12,7 @@
12 12
13#include "../FileManager/DialogSize.h" 13#include "../FileManager/DialogSize.h"
14 14
15#ifndef NO_REGISTRY 15#ifndef Z7_NO_REGISTRY
16#include "../Common/ZipRegistry.h" 16#include "../Common/ZipRegistry.h"
17#endif 17#endif
18 18
@@ -33,20 +33,20 @@ namespace NExtractionDialog
33 33
34class CExtractDialog: public NWindows::NControl::CModalDialog 34class CExtractDialog: public NWindows::NControl::CModalDialog
35{ 35{
36 #ifdef NO_REGISTRY 36 #ifdef Z7_NO_REGISTRY
37 NWindows::NControl::CDialogChildControl _path; 37 NWindows::NControl::CDialogChildControl _path;
38 #else 38 #else
39 NWindows::NControl::CComboBox _path; 39 NWindows::NControl::CComboBox _path;
40 #endif 40 #endif
41 41
42 #ifndef _SFX 42 #ifndef Z7_SFX
43 NWindows::NControl::CEdit _pathName; 43 NWindows::NControl::CEdit _pathName;
44 NWindows::NControl::CEdit _passwordControl; 44 NWindows::NControl::CEdit _passwordControl;
45 NWindows::NControl::CComboBox _pathMode; 45 NWindows::NControl::CComboBox _pathMode;
46 NWindows::NControl::CComboBox _overwriteMode; 46 NWindows::NControl::CComboBox _overwriteMode;
47 #endif 47 #endif
48 48
49 #ifndef _SFX 49 #ifndef Z7_SFX
50 // int GetFilesMode() const; 50 // int GetFilesMode() const;
51 void UpdatePasswordControl(); 51 void UpdatePasswordControl();
52 #endif 52 #endif
@@ -55,13 +55,13 @@ class CExtractDialog: public NWindows::NControl::CModalDialog
55 55
56 void CheckButton_TwoBools(UINT id, const CBoolPair &b1, const CBoolPair &b2); 56 void CheckButton_TwoBools(UINT id, const CBoolPair &b1, const CBoolPair &b2);
57 void GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2); 57 void GetButton_Bools(UINT id, CBoolPair &b1, CBoolPair &b2);
58 virtual bool OnInit(); 58 virtual bool OnInit() Z7_override;
59 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 59 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND) Z7_override;
60 virtual void OnOK(); 60 virtual void OnOK() Z7_override;
61 61
62 #ifndef NO_REGISTRY 62 #ifndef Z7_NO_REGISTRY
63 63
64 virtual void OnHelp(); 64 virtual void OnHelp() Z7_override;
65 65
66 NExtract::CInfo _info; 66 NExtract::CInfo _info;
67 67
@@ -76,7 +76,7 @@ public:
76 UString DirPath; 76 UString DirPath;
77 UString ArcPath; 77 UString ArcPath;
78 78
79 #ifndef _SFX 79 #ifndef Z7_SFX
80 UString Password; 80 UString Password;
81 #endif 81 #endif
82 bool PathMode_Force; 82 bool PathMode_Force;
@@ -84,16 +84,16 @@ public:
84 NExtract::NPathMode::EEnum PathMode; 84 NExtract::NPathMode::EEnum PathMode;
85 NExtract::NOverwriteMode::EEnum OverwriteMode; 85 NExtract::NOverwriteMode::EEnum OverwriteMode;
86 86
87 #ifndef _SFX 87 #ifndef Z7_SFX
88 // CBoolPair AltStreams; 88 // CBoolPair AltStreams;
89 CBoolPair NtSecurity; 89 CBoolPair NtSecurity;
90 #endif 90 #endif
91 91
92 CBoolPair ElimDup; 92 CBoolPair ElimDup;
93 93
94 INT_PTR Create(HWND aWndParent = 0) 94 INT_PTR Create(HWND aWndParent = NULL)
95 { 95 {
96 #ifdef _SFX 96 #ifdef Z7_SFX
97 BIG_DIALOG_SIZE(240, 64); 97 BIG_DIALOG_SIZE(240, 64);
98 #else 98 #else
99 BIG_DIALOG_SIZE(300, 160); 99 BIG_DIALOG_SIZE(300, 160);
diff --git a/CPP/7zip/UI/GUI/ExtractGUI.cpp b/CPP/7zip/UI/GUI/ExtractGUI.cpp
index a9191a8..fdf3cc7 100644
--- a/CPP/7zip/UI/GUI/ExtractGUI.cpp
+++ b/CPP/7zip/UI/GUI/ExtractGUI.cpp
@@ -36,7 +36,7 @@ using namespace NDir;
36 36
37static const wchar_t * const kIncorrectOutDir = L"Incorrect output directory path"; 37static const wchar_t * const kIncorrectOutDir = L"Incorrect output directory path";
38 38
39#ifndef _SFX 39#ifndef Z7_SFX
40 40
41static void AddValuePair(UString &s, UINT resourceID, UInt64 value, bool addColon = true) 41static void AddValuePair(UString &s, UINT resourceID, UInt64 value, bool addColon = true)
42{ 42{
@@ -60,10 +60,10 @@ static void AddSizePair(UString &s, UINT resourceID, UInt64 value)
60 60
61class CThreadExtracting: public CProgressThreadVirt 61class CThreadExtracting: public CProgressThreadVirt
62{ 62{
63 HRESULT ProcessVirt(); 63 HRESULT ProcessVirt() Z7_override;
64public: 64public:
65 /* 65 /*
66 #ifdef EXTERNAL_CODECS 66 #ifdef Z7_EXTERNAL_CODECS
67 const CExternalCodecs *externalCodecs; 67 const CExternalCodecs *externalCodecs;
68 #endif 68 #endif
69 */ 69 */
@@ -78,19 +78,19 @@ public:
78 const NWildcard::CCensorNode *WildcardCensor; 78 const NWildcard::CCensorNode *WildcardCensor;
79 const CExtractOptions *Options; 79 const CExtractOptions *Options;
80 80
81 #ifndef _SFX 81 #ifndef Z7_SFX
82 CHashBundle *HashBundle; 82 CHashBundle *HashBundle;
83 virtual void ProcessWasFinished_GuiVirt(); 83 virtual void ProcessWasFinished_GuiVirt() Z7_override;
84 #endif 84 #endif
85 85
86 CMyComPtr<IExtractCallbackUI> ExtractCallback; 86 CMyComPtr<IFolderArchiveExtractCallback> FolderArchiveExtractCallback;
87 UString Title; 87 UString Title;
88 88
89 CPropNameValPairs Pairs; 89 CPropNameValPairs Pairs;
90}; 90};
91 91
92 92
93#ifndef _SFX 93#ifndef Z7_SFX
94void CThreadExtracting::ProcessWasFinished_GuiVirt() 94void CThreadExtracting::ProcessWasFinished_GuiVirt()
95{ 95{
96 if (HashBundle && !Pairs.IsEmpty()) 96 if (HashBundle && !Pairs.IsEmpty())
@@ -102,7 +102,7 @@ HRESULT CThreadExtracting::ProcessVirt()
102{ 102{
103 CDecompressStat Stat; 103 CDecompressStat Stat;
104 104
105 #ifndef _SFX 105 #ifndef Z7_SFX
106 /* 106 /*
107 if (HashBundle) 107 if (HashBundle)
108 HashBundle->Init(); 108 HashBundle->Init();
@@ -111,20 +111,21 @@ HRESULT CThreadExtracting::ProcessVirt()
111 111
112 HRESULT res = Extract( 112 HRESULT res = Extract(
113 /* 113 /*
114 #ifdef EXTERNAL_CODECS 114 #ifdef Z7_EXTERNAL_CODECS
115 externalCodecs, 115 externalCodecs,
116 #endif 116 #endif
117 */ 117 */
118 codecs, 118 codecs,
119 *FormatIndices, *ExcludedFormatIndices, 119 *FormatIndices, *ExcludedFormatIndices,
120 *ArchivePaths, *ArchivePathsFull, 120 *ArchivePaths, *ArchivePathsFull,
121 *WildcardCensor, *Options, ExtractCallbackSpec, ExtractCallback, 121 *WildcardCensor, *Options,
122 #ifndef _SFX 122 ExtractCallbackSpec, ExtractCallbackSpec, FolderArchiveExtractCallback,
123 #ifndef Z7_SFX
123 HashBundle, 124 HashBundle,
124 #endif 125 #endif
125 FinalMessage.ErrorMessage.Message, Stat); 126 FinalMessage.ErrorMessage.Message, Stat);
126 127
127 #ifndef _SFX 128 #ifndef Z7_SFX
128 if (res == S_OK && ExtractCallbackSpec->IsOK()) 129 if (res == S_OK && ExtractCallbackSpec->IsOK())
129 { 130 {
130 if (HashBundle) 131 if (HashBundle)
@@ -172,7 +173,7 @@ HRESULT ExtractGUI(
172 UStringVector &archivePathsFull, 173 UStringVector &archivePathsFull,
173 const NWildcard::CCensorNode &wildcardCensor, 174 const NWildcard::CCensorNode &wildcardCensor,
174 CExtractOptions &options, 175 CExtractOptions &options,
175 #ifndef _SFX 176 #ifndef Z7_SFX
176 CHashBundle *hb, 177 CHashBundle *hb,
177 #endif 178 #endif
178 bool showDialog, 179 bool showDialog,
@@ -184,8 +185,8 @@ HRESULT ExtractGUI(
184 185
185 CThreadExtracting extracter; 186 CThreadExtracting extracter;
186 /* 187 /*
187 #ifdef EXTERNAL_CODECS 188 #ifdef Z7_EXTERNAL_CODECS
188 extracter.externalCodecs = __externalCodecs; 189 extracter.externalCodecs = _externalCodecs;
189 #endif 190 #endif
190 */ 191 */
191 extracter.codecs = codecs; 192 extracter.codecs = codecs;
@@ -222,7 +223,7 @@ HRESULT ExtractGUI(
222 if (archivePathsFull.Size() == 1) 223 if (archivePathsFull.Size() == 1)
223 dialog.ArcPath = archivePathsFull[0]; 224 dialog.ArcPath = archivePathsFull[0];
224 225
225 #ifndef _SFX 226 #ifndef Z7_SFX
226 // dialog.AltStreams = options.NtOptions.AltStreams; 227 // dialog.AltStreams = options.NtOptions.AltStreams;
227 dialog.NtSecurity = options.NtOptions.NtSecurity; 228 dialog.NtSecurity = options.NtOptions.NtSecurity;
228 if (extractCallback->PasswordIsDefined) 229 if (extractCallback->PasswordIsDefined)
@@ -238,7 +239,7 @@ HRESULT ExtractGUI(
238 options.PathMode = dialog.PathMode; 239 options.PathMode = dialog.PathMode;
239 options.ElimDup = dialog.ElimDup; 240 options.ElimDup = dialog.ElimDup;
240 241
241 #ifndef _SFX 242 #ifndef Z7_SFX
242 // options.NtOptions.AltStreams = dialog.AltStreams; 243 // options.NtOptions.AltStreams = dialog.AltStreams;
243 options.NtOptions.NtSecurity = dialog.NtSecurity; 244 options.NtOptions.NtSecurity = dialog.NtSecurity;
244 extractCallback->Password = dialog.Password; 245 extractCallback->Password = dialog.Password;
@@ -258,7 +259,7 @@ HRESULT ExtractGUI(
258 { 259 {
259 UString s = GetUnicodeString(NError::MyFormatMessage(GetLastError())); 260 UString s = GetUnicodeString(NError::MyFormatMessage(GetLastError()));
260 UString s2 = MyFormatNew(IDS_CANNOT_CREATE_FOLDER, 261 UString s2 = MyFormatNew(IDS_CANNOT_CREATE_FOLDER,
261 #ifdef LANG 262 #ifdef Z7_LANG
262 0x02000603, 263 0x02000603,
263 #endif 264 #endif
264 options.OutputDir); 265 options.OutputDir);
@@ -275,7 +276,7 @@ HRESULT ExtractGUI(
275 extracter.Title = title; 276 extracter.Title = title;
276 extracter.ExtractCallbackSpec = extractCallback; 277 extracter.ExtractCallbackSpec = extractCallback;
277 extracter.ExtractCallbackSpec->ProgressDialog = &extracter; 278 extracter.ExtractCallbackSpec->ProgressDialog = &extracter;
278 extracter.ExtractCallback = extractCallback; 279 extracter.FolderArchiveExtractCallback = extractCallback;
279 extracter.ExtractCallbackSpec->Init(); 280 extracter.ExtractCallbackSpec->Init();
280 281
281 extracter.CompressingMode = false; 282 extracter.CompressingMode = false;
@@ -284,13 +285,13 @@ HRESULT ExtractGUI(
284 extracter.ArchivePathsFull = &archivePathsFull; 285 extracter.ArchivePathsFull = &archivePathsFull;
285 extracter.WildcardCensor = &wildcardCensor; 286 extracter.WildcardCensor = &wildcardCensor;
286 extracter.Options = &options; 287 extracter.Options = &options;
287 #ifndef _SFX 288 #ifndef Z7_SFX
288 extracter.HashBundle = hb; 289 extracter.HashBundle = hb;
289 #endif 290 #endif
290 291
291 extracter.IconID = IDI_ICON; 292 extracter.IconID = IDI_ICON;
292 293
293 RINOK(extracter.Create(title, hwndParent)); 294 RINOK(extracter.Create(title, hwndParent))
294 messageWasDisplayed = extracter.ThreadFinishedOK && extracter.MessagesDisplayed; 295 messageWasDisplayed = extracter.ThreadFinishedOK && extracter.MessagesDisplayed;
295 return extracter.Result; 296 return extracter.Result;
296} 297}
diff --git a/CPP/7zip/UI/GUI/ExtractGUI.h b/CPP/7zip/UI/GUI/ExtractGUI.h
index 3b41259..13ca6ab 100644
--- a/CPP/7zip/UI/GUI/ExtractGUI.h
+++ b/CPP/7zip/UI/GUI/ExtractGUI.h
@@ -1,7 +1,7 @@
1// GUI/ExtractGUI.h 1// GUI/ExtractGUI.h
2 2
3#ifndef __EXTRACT_GUI_H 3#ifndef ZIP7_INC_EXTRACT_GUI_H
4#define __EXTRACT_GUI_H 4#define ZIP7_INC_EXTRACT_GUI_H
5 5
6#include "../Common/Extract.h" 6#include "../Common/Extract.h"
7 7
@@ -28,7 +28,7 @@ HRESULT ExtractGUI(
28 UStringVector &archivePathsFull, 28 UStringVector &archivePathsFull,
29 const NWildcard::CCensorNode &wildcardCensor, 29 const NWildcard::CCensorNode &wildcardCensor,
30 CExtractOptions &options, 30 CExtractOptions &options,
31 #ifndef _SFX 31 #ifndef Z7_SFX
32 CHashBundle *hb, 32 CHashBundle *hb,
33 #endif 33 #endif
34 bool showDialog, 34 bool showDialog,
diff --git a/CPP/7zip/UI/GUI/GUI.cpp b/CPP/7zip/UI/GUI/GUI.cpp
index c977516..37e637b 100644
--- a/CPP/7zip/UI/GUI/GUI.cpp
+++ b/CPP/7zip/UI/GUI/GUI.cpp
@@ -7,8 +7,11 @@
7#endif 7#endif
8 8
9#include "../../../Common/MyWindows.h" 9#include "../../../Common/MyWindows.h"
10 10#if defined(__MINGW32__) || defined(__MINGW64__)
11#include <shlwapi.h>
12#else
11#include <Shlwapi.h> 13#include <Shlwapi.h>
14#endif
12 15
13#include "../../../Common/MyInitGuid.h" 16#include "../../../Common/MyInitGuid.h"
14 17
@@ -23,7 +26,7 @@
23#include "../Common/ExitCode.h" 26#include "../Common/ExitCode.h"
24 27
25#include "../FileManager/StringUtils.h" 28#include "../FileManager/StringUtils.h"
26#include "../FileManager/MyWindowsNew.h" 29#include "../FileManager/LangUtils.h"
27 30
28#include "BenchmarkDialog.h" 31#include "BenchmarkDialog.h"
29#include "ExtractGUI.h" 32#include "ExtractGUI.h"
@@ -34,7 +37,9 @@
34 37
35using namespace NWindows; 38using namespace NWindows;
36 39
37#ifdef EXTERNAL_CODECS 40#ifdef Z7_EXTERNAL_CODECS
41extern
42const CExternalCodecs *g_ExternalCodecs_Ptr;
38const CExternalCodecs *g_ExternalCodecs_Ptr; 43const CExternalCodecs *g_ExternalCodecs_Ptr;
39#endif 44#endif
40 45
@@ -51,20 +56,23 @@ DWORD g_ComCtl32Version;
51static DWORD GetDllVersion(LPCTSTR dllName) 56static DWORD GetDllVersion(LPCTSTR dllName)
52{ 57{
53 DWORD dwVersion = 0; 58 DWORD dwVersion = 0;
54 HINSTANCE hinstDll = LoadLibrary(dllName); 59 const HMODULE hmodule = LoadLibrary(dllName);
55 if (hinstDll) 60 if (hmodule)
56 { 61 {
57 DLLGETVERSIONPROC pDllGetVersion = (DLLGETVERSIONPROC)(void *)GetProcAddress(hinstDll, "DllGetVersion"); 62 const
58 if (pDllGetVersion) 63 DLLGETVERSIONPROC f_DllGetVersion = Z7_GET_PROC_ADDRESS(
64 DLLGETVERSIONPROC, hmodule,
65 "DllGetVersion");
66 if (f_DllGetVersion)
59 { 67 {
60 DLLVERSIONINFO dvi; 68 DLLVERSIONINFO dvi;
61 ZeroMemory(&dvi, sizeof(dvi)); 69 ZeroMemory(&dvi, sizeof(dvi));
62 dvi.cbSize = sizeof(dvi); 70 dvi.cbSize = sizeof(dvi);
63 HRESULT hr = (*pDllGetVersion)(&dvi); 71 const HRESULT hr = (*f_DllGetVersion)(&dvi);
64 if (SUCCEEDED(hr)) 72 if (SUCCEEDED(hr))
65 dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion); 73 dwVersion = (DWORD)MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion);
66 } 74 }
67 FreeLibrary(hinstDll); 75 FreeLibrary(hmodule);
68 } 76 }
69 return dwVersion; 77 return dwVersion;
70} 78}
@@ -100,9 +108,9 @@ static int ShowMemErrorMessage()
100 return NExitCode::kMemoryError; 108 return NExitCode::kMemoryError;
101} 109}
102 110
103static int ShowSysErrorMessage(DWORD errorCode) 111static int ShowSysErrorMessage(HRESULT errorCode)
104{ 112{
105 if ((HRESULT)errorCode == E_OUTOFMEMORY) 113 if (errorCode == E_OUTOFMEMORY)
106 return ShowMemErrorMessage(); 114 return ShowMemErrorMessage();
107 ErrorMessage(HResultToMessage(errorCode)); 115 ErrorMessage(HResultToMessage(errorCode));
108 return NExitCode::kFatalError; 116 return NExitCode::kFatalError;
@@ -125,7 +133,7 @@ static int Main2()
125 #endif 133 #endif
126 if (commandStrings.Size() == 0) 134 if (commandStrings.Size() == 0)
127 { 135 {
128 MessageBoxW(0, L"Specify command", L"7-Zip", 0); 136 MessageBoxW(NULL, L"Specify command", L"7-Zip", 0);
129 return 0; 137 return 0;
130 } 138 }
131 139
@@ -142,14 +150,14 @@ static int Main2()
142 ThrowException_if_Error(codecs->Load()); 150 ThrowException_if_Error(codecs->Load());
143 Codecs_AddHashArcHandler(codecs); 151 Codecs_AddHashArcHandler(codecs);
144 152
145 #ifdef EXTERNAL_CODECS 153 #ifdef Z7_EXTERNAL_CODECS
146 { 154 {
147 g_ExternalCodecs_Ptr = &__externalCodecs; 155 g_ExternalCodecs_Ptr = &_externalCodecs;
148 UString s; 156 UString s;
149 codecs->GetCodecsErrorMessage(s); 157 codecs->GetCodecsErrorMessage(s);
150 if (!s.IsEmpty()) 158 if (!s.IsEmpty())
151 { 159 {
152 MessageBoxW(0, s, L"7-Zip", MB_ICONERROR); 160 MessageBoxW(NULL, s, L"7-Zip", MB_ICONERROR);
153 } 161 }
154 162
155 } 163 }
@@ -162,7 +170,7 @@ static int Main2()
162 170
163 || options.Command.IsFromUpdateGroup())) 171 || options.Command.IsFromUpdateGroup()))
164 { 172 {
165 #ifdef EXTERNAL_CODECS 173 #ifdef Z7_EXTERNAL_CODECS
166 if (!codecs->MainDll_ErrorPath.IsEmpty()) 174 if (!codecs->MainDll_ErrorPath.IsEmpty())
167 { 175 {
168 UString s ("7-Zip cannot load module: "); 176 UString s ("7-Zip cannot load module: ");
@@ -194,12 +202,12 @@ static int Main2()
194 // excludedFormats.Sort(); 202 // excludedFormats.Sort();
195 } 203 }
196 204
197 #ifdef EXTERNAL_CODECS 205 #ifdef Z7_EXTERNAL_CODECS
198 if (isExtractGroupCommand 206 if (isExtractGroupCommand
199 || options.Command.IsFromUpdateGroup() 207 || options.Command.IsFromUpdateGroup()
200 || options.Command.CommandType == NCommandType::kHash 208 || options.Command.CommandType == NCommandType::kHash
201 || options.Command.CommandType == NCommandType::kBenchmark) 209 || options.Command.CommandType == NCommandType::kBenchmark)
202 ThrowException_if_Error(__externalCodecs.Load()); 210 ThrowException_if_Error(_externalCodecs.Load());
203 #endif 211 #endif
204 212
205 if (options.Command.CommandType == NCommandType::kBenchmark) 213 if (options.Command.CommandType == NCommandType::kBenchmark)
@@ -227,7 +235,7 @@ static int Main2()
227 CExtractCallbackImp *ecs = new CExtractCallbackImp; 235 CExtractCallbackImp *ecs = new CExtractCallbackImp;
228 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs; 236 CMyComPtr<IFolderArchiveExtractCallback> extractCallback = ecs;
229 237
230 #ifndef _NO_CRYPTO 238 #ifndef Z7_NO_CRYPTO
231 ecs->PasswordIsDefined = options.PasswordEnabled; 239 ecs->PasswordIsDefined = options.PasswordEnabled;
232 ecs->Password = options.Password; 240 ecs->Password = options.Password;
233 #endif 241 #endif
@@ -241,13 +249,13 @@ static int Main2()
241 eo.YesToAll = options.YesToAll; 249 eo.YesToAll = options.YesToAll;
242 eo.TestMode = options.Command.IsTestCommand(); 250 eo.TestMode = options.Command.IsTestCommand();
243 251
244 #ifndef _SFX 252 #ifndef Z7_SFX
245 eo.Properties = options.Properties; 253 eo.Properties = options.Properties;
246 #endif 254 #endif
247 255
248 bool messageWasDisplayed = false; 256 bool messageWasDisplayed = false;
249 257
250 #ifndef _SFX 258 #ifndef Z7_SFX
251 CHashBundle hb; 259 CHashBundle hb;
252 CHashBundle *hb_ptr = NULL; 260 CHashBundle *hb_ptr = NULL;
253 261
@@ -289,7 +297,7 @@ static int Main2()
289 ArchivePathsFullSorted, 297 ArchivePathsFullSorted,
290 options.Censor.Pairs.Front().Head, 298 options.Censor.Pairs.Front().Head,
291 eo, 299 eo,
292 #ifndef _SFX 300 #ifndef Z7_SFX
293 hb_ptr, 301 hb_ptr,
294 #endif 302 #endif
295 options.ShowDialog, messageWasDisplayed, ecs); 303 options.ShowDialog, messageWasDisplayed, ecs);
@@ -304,14 +312,14 @@ static int Main2()
304 } 312 }
305 else if (options.Command.IsFromUpdateGroup()) 313 else if (options.Command.IsFromUpdateGroup())
306 { 314 {
307 #ifndef _NO_CRYPTO 315 #ifndef Z7_NO_CRYPTO
308 bool passwordIsDefined = options.PasswordEnabled && !options.Password.IsEmpty(); 316 bool passwordIsDefined = options.PasswordEnabled && !options.Password.IsEmpty();
309 #endif 317 #endif
310 318
311 CUpdateCallbackGUI callback; 319 CUpdateCallbackGUI callback;
312 // callback.EnablePercents = options.EnablePercents; 320 // callback.EnablePercents = options.EnablePercents;
313 321
314 #ifndef _NO_CRYPTO 322 #ifndef Z7_NO_CRYPTO
315 callback.PasswordIsDefined = passwordIsDefined; 323 callback.PasswordIsDefined = passwordIsDefined;
316 callback.AskPassword = options.PasswordEnabled && options.Password.IsEmpty(); 324 callback.AskPassword = options.PasswordEnabled && options.Password.IsEmpty();
317 callback.Password = options.Password; 325 callback.Password = options.Password;
@@ -407,7 +415,9 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
407 OleInitialize(NULL); 415 OleInitialize(NULL);
408 #endif 416 #endif
409 417
418 #ifdef Z7_LANG
410 LoadLangOneTime(); 419 LoadLangOneTime();
420 #endif
411 421
412 // setlocale(LC_COLLATE, ".ACP"); 422 // setlocale(LC_COLLATE, ".ACP");
413 try 423 try
@@ -456,7 +466,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /* hPrevInstance */,
456 catch(int v) 466 catch(int v)
457 { 467 {
458 AString e ("Error: "); 468 AString e ("Error: ");
459 e.Add_UInt32(v); 469 e.Add_UInt32((unsigned)v);
460 ErrorMessage(e); 470 ErrorMessage(e);
461 return NExitCode::kFatalError; 471 return NExitCode::kFatalError;
462 } 472 }
diff --git a/CPP/7zip/UI/GUI/GUI.dsp b/CPP/7zip/UI/GUI/GUI.dsp
index b55a115..3a6b60f 100644
--- a/CPP/7zip/UI/GUI/GUI.dsp
+++ b/CPP/7zip/UI/GUI/GUI.dsp
@@ -45,7 +45,7 @@ RSC=rc.exe
45# PROP Ignore_Export_Lib 0 45# PROP Ignore_Export_Lib 0
46# PROP Target_Dir "" 46# PROP Target_Dir ""
47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c 47# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c
48# 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 48# 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
49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 49# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 50# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
51# ADD BASE RSC /l 0x419 /d "NDEBUG" 51# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -72,7 +72,7 @@ LINK32=link.exe
72# PROP Ignore_Export_Lib 0 72# PROP Ignore_Export_Lib 0
73# PROP Target_Dir "" 73# PROP Target_Dir ""
74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c 74# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c
75# 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 75# 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
76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 76# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 77# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
78# ADD BASE RSC /l 0x419 /d "_DEBUG" 78# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -99,7 +99,7 @@ LINK32=link.exe
99# PROP Ignore_Export_Lib 0 99# PROP Ignore_Export_Lib 0
100# PROP Target_Dir "" 100# PROP Target_Dir ""
101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c 101# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c
102# 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 102# 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
103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 103# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 104# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
105# ADD BASE RSC /l 0x419 /d "NDEBUG" 105# ADD BASE RSC /l 0x419 /d "NDEBUG"
@@ -127,7 +127,7 @@ LINK32=link.exe
127# PROP Ignore_Export_Lib 0 127# PROP Ignore_Export_Lib 0
128# PROP Target_Dir "" 128# PROP Target_Dir ""
129# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c 129# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c
130# 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 130# 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
131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 131# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 132# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
133# ADD BASE RSC /l 0x419 /d "_DEBUG" 133# ADD BASE RSC /l 0x419 /d "_DEBUG"
@@ -485,10 +485,6 @@ SOURCE=..\FileManager\ExtractCallback.h
485# End Source File 485# End Source File
486# Begin Source File 486# Begin Source File
487 487
488SOURCE=..\FileManager\FolderInterface.h
489# End Source File
490# Begin Source File
491
492SOURCE=..\FileManager\FormatUtils.cpp 488SOURCE=..\FileManager\FormatUtils.cpp
493# End Source File 489# End Source File
494# Begin Source File 490# Begin Source File
@@ -669,6 +665,14 @@ SOURCE=..\..\Common\MethodProps.h
669# End Source File 665# End Source File
670# Begin Source File 666# Begin Source File
671 667
668SOURCE=..\..\Common\MultiOutStream.cpp
669# End Source File
670# Begin Source File
671
672SOURCE=..\..\Common\MultiOutStream.h
673# End Source File
674# Begin Source File
675
672SOURCE=..\..\Common\ProgressUtils.cpp 676SOURCE=..\..\Common\ProgressUtils.cpp
673# End Source File 677# End Source File
674# Begin Source File 678# Begin Source File
@@ -777,6 +781,10 @@ SOURCE=..\..\..\..\C\7zTypes.h
777# End Source File 781# End Source File
778# Begin Source File 782# Begin Source File
779 783
784SOURCE=..\..\..\..\C\7zWindows.h
785# End Source File
786# Begin Source File
787
780SOURCE=..\..\..\..\C\Alloc.c 788SOURCE=..\..\..\..\C\Alloc.c
781# SUBTRACT CPP /YX /Yc /Yu 789# SUBTRACT CPP /YX /Yc /Yu
782# End Source File 790# End Source File
@@ -872,6 +880,14 @@ SOURCE=..\..\..\Common\CommandLineParser.h
872# End Source File 880# End Source File
873# Begin Source File 881# Begin Source File
874 882
883SOURCE=..\..\..\Common\Common.h
884# End Source File
885# Begin Source File
886
887SOURCE=..\..\..\..\C\Compiler.h
888# End Source File
889# Begin Source File
890
875SOURCE=..\..\..\Common\CRC.cpp 891SOURCE=..\..\..\Common\CRC.cpp
876# End Source File 892# End Source File
877# Begin Source File 893# Begin Source File
@@ -928,6 +944,10 @@ SOURCE=..\..\..\Common\MyVector.h
928# End Source File 944# End Source File
929# Begin Source File 945# Begin Source File
930 946
947SOURCE=..\..\..\Common\MyWindows.h
948# End Source File
949# Begin Source File
950
931SOURCE=..\..\..\Common\NewHandler.cpp 951SOURCE=..\..\..\Common\NewHandler.cpp
932# End Source File 952# End Source File
933# Begin Source File 953# Begin Source File
@@ -1226,6 +1246,14 @@ SOURCE=..\..\Archive\IArchive.h
1226 1246
1227SOURCE=..\..\ICoder.h 1247SOURCE=..\..\ICoder.h
1228# End Source File 1248# End Source File
1249# Begin Source File
1250
1251SOURCE=..\..\IDecl.h
1252# End Source File
1253# Begin Source File
1254
1255SOURCE=..\..\IStream.h
1256# End Source File
1229# End Group 1257# End Group
1230# End Target 1258# End Target
1231# End Project 1259# End Project
diff --git a/CPP/7zip/UI/GUI/HashGUI.cpp b/CPP/7zip/UI/GUI/HashGUI.cpp
index 5782f79..b96e413 100644
--- a/CPP/7zip/UI/GUI/HashGUI.cpp
+++ b/CPP/7zip/UI/GUI/HashGUI.cpp
@@ -22,7 +22,7 @@ using namespace NWindows;
22 22
23 23
24 24
25class CHashCallbackGUI: public CProgressThreadVirt, public IHashCallbackUI 25class CHashCallbackGUI Z7_final: public CProgressThreadVirt, public IHashCallbackUI
26{ 26{
27 UInt64 NumFiles; 27 UInt64 NumFiles;
28 bool _curIsFolder; 28 bool _curIsFolder;
@@ -31,24 +31,28 @@ class CHashCallbackGUI: public CProgressThreadVirt, public IHashCallbackUI
31 31
32 CPropNameValPairs PropNameValPairs; 32 CPropNameValPairs PropNameValPairs;
33 33
34 HRESULT ProcessVirt(); 34 HRESULT ProcessVirt() Z7_override;
35 virtual void ProcessWasFinished_GuiVirt(); 35 virtual void ProcessWasFinished_GuiVirt() Z7_override;
36 36
37public: 37public:
38 const NWildcard::CCensor *censor; 38 const NWildcard::CCensor *censor;
39 const CHashOptions *options; 39 const CHashOptions *options;
40 40
41 DECL_EXTERNAL_CODECS_LOC_VARS2; 41 DECL_EXTERNAL_CODECS_LOC_VARS_DECL
42 42
43 CHashCallbackGUI() {} 43 Z7_IFACE_IMP(IDirItemsCallback)
44 ~CHashCallbackGUI() { } 44 Z7_IFACE_IMP(IHashCallbackUI)
45
46 INTERFACE_IHashCallbackUI(;)
47 45
46 /*
48 void AddErrorMessage(DWORD systemError, const wchar_t *name) 47 void AddErrorMessage(DWORD systemError, const wchar_t *name)
49 { 48 {
50 Sync.AddError_Code_Name(systemError, name); 49 Sync.AddError_Code_Name(systemError, name);
51 } 50 }
51 */
52 void AddErrorMessage(HRESULT systemError, const wchar_t *name)
53 {
54 Sync.AddError_Code_Name(systemError, name);
55 }
52}; 56};
53 57
54 58
@@ -106,13 +110,13 @@ HRESULT CHashCallbackGUI::ScanProgress(const CDirItemsStat &st, const FString &p
106 110
107HRESULT CHashCallbackGUI::ScanError(const FString &path, DWORD systemError) 111HRESULT CHashCallbackGUI::ScanError(const FString &path, DWORD systemError)
108{ 112{
109 AddErrorMessage(systemError, fs2us(path)); 113 AddErrorMessage(HRESULT_FROM_WIN32(systemError), fs2us(path));
110 return CheckBreak(); 114 return CheckBreak();
111} 115}
112 116
113HRESULT CHashCallbackGUI::FinishScanning(const CDirItemsStat &st) 117HRESULT CHashCallbackGUI::FinishScanning(const CDirItemsStat &st)
114{ 118{
115 return ScanProgress(st, FString(), false); 119 return ScanProgress(st, FString(), false); // isDir
116} 120}
117 121
118HRESULT CHashCallbackGUI::CheckBreak() 122HRESULT CHashCallbackGUI::CheckBreak()
@@ -158,7 +162,7 @@ HRESULT CHashCallbackGUI::OpenFileError(const FString &path, DWORD systemError)
158{ 162{
159 // if (systemError == ERROR_SHARING_VIOLATION) 163 // if (systemError == ERROR_SHARING_VIOLATION)
160 { 164 {
161 AddErrorMessage(systemError, fs2us(path)); 165 AddErrorMessage(HRESULT_FROM_WIN32(systemError), fs2us(path));
162 return S_FALSE; 166 return S_FALSE;
163 } 167 }
164 // return systemError; 168 // return systemError;
@@ -305,8 +309,8 @@ HRESULT HashCalcGUI(
305 bool &messageWasDisplayed) 309 bool &messageWasDisplayed)
306{ 310{
307 CHashCallbackGUI t; 311 CHashCallbackGUI t;
308 #ifdef EXTERNAL_CODECS 312 #ifdef Z7_EXTERNAL_CODECS
309 t.__externalCodecs = __externalCodecs; 313 t._externalCodecs = _externalCodecs;
310 #endif 314 #endif
311 t.censor = &censor; 315 t.censor = &censor;
312 t.options = &options; 316 t.options = &options;
@@ -319,7 +323,7 @@ HRESULT HashCalcGUI(
319 t.MainAddTitle = title; 323 t.MainAddTitle = title;
320 t.MainAddTitle.Add_Space(); 324 t.MainAddTitle.Add_Space();
321 325
322 RINOK(t.Create(title)); 326 RINOK(t.Create(title))
323 messageWasDisplayed = t.ThreadFinishedOK && t.MessagesDisplayed; 327 messageWasDisplayed = t.ThreadFinishedOK && t.MessagesDisplayed;
324 return S_OK; 328 return S_OK;
325} 329}
@@ -352,8 +356,8 @@ void ShowHashResults(const CHashBundle &hb, HWND hwnd)
352 ShowHashResults(propPairs, hwnd); 356 ShowHashResults(propPairs, hwnd);
353} 357}
354 358
355
356void CHashCallbackGUI::ProcessWasFinished_GuiVirt() 359void CHashCallbackGUI::ProcessWasFinished_GuiVirt()
357{ 360{
358 ShowHashResults(PropNameValPairs, *this); 361 if (Result != E_ABORT)
362 ShowHashResults(PropNameValPairs, *this);
359} 363}
diff --git a/CPP/7zip/UI/GUI/HashGUI.h b/CPP/7zip/UI/GUI/HashGUI.h
index 8264453..1ec9c47 100644
--- a/CPP/7zip/UI/GUI/HashGUI.h
+++ b/CPP/7zip/UI/GUI/HashGUI.h
@@ -1,7 +1,7 @@
1// HashGUI.h 1// HashGUI.h
2 2
3#ifndef __HASH_GUI_H 3#ifndef ZIP7_INC_HASH_GUI_H
4#define __HASH_GUI_H 4#define ZIP7_INC_HASH_GUI_H
5 5
6#include "../Common/HashCalc.h" 6#include "../Common/HashCalc.h"
7#include "../Common/Property.h" 7#include "../Common/Property.h"
diff --git a/CPP/7zip/UI/GUI/StdAfx.h b/CPP/7zip/UI/GUI/StdAfx.h
index 1918c8c..130db8a 100644
--- a/CPP/7zip/UI/GUI/StdAfx.h
+++ b/CPP/7zip/UI/GUI/StdAfx.h
@@ -1,21 +1,6 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#if _MSC_VER >= 1800
4#define __STDAFX_H 4#pragma warning(disable : 4464) // relative include path contains '..'
5
6// #define _WIN32_WINNT 0x0400
7#define _WIN32_WINNT 0x0500
8#define WINVER _WIN32_WINNT
9
10#include "../../../Common/Common.h"
11
12// #include "../../../Common/MyWindows.h"
13
14// #include <CommCtrl.h>
15// #include <ShlObj.h>
16// #include <Shlwapi.h>
17
18// #define printf(x) NO_PRINTF_(x)
19// #define sprintf(x) NO_SPRINTF_(x)
20
21#endif 5#endif
6#include "../FileManager/StdAfx.h"
diff --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp b/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp
index 1f272cd..26057a7 100644
--- a/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp
+++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI.cpp
@@ -51,7 +51,7 @@ HRESULT CUpdateCallbackGUI::StartScanning()
51HRESULT CUpdateCallbackGUI::ScanError(const FString &path, DWORD systemError) 51HRESULT CUpdateCallbackGUI::ScanError(const FString &path, DWORD systemError)
52{ 52{
53 FailedFiles.Add(path); 53 FailedFiles.Add(path);
54 ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); 54 ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path));
55 return S_OK; 55 return S_OK;
56} 56}
57 57
@@ -59,7 +59,7 @@ HRESULT CUpdateCallbackGUI::FinishScanning(const CDirItemsStat &st)
59{ 59{
60 CProgressSync &sync = ProgressDialog->Sync; 60 CProgressSync &sync = ProgressDialog->Sync;
61 RINOK(ProgressDialog->Sync.ScanProgress(st.NumFiles + st.NumAltStreams, 61 RINOK(ProgressDialog->Sync.ScanProgress(st.NumFiles + st.NumAltStreams,
62 st.GetTotalBytes(), FString(), true)); 62 st.GetTotalBytes(), FString(), true))
63 sync.Set_Status(L""); 63 sync.Set_Status(L"");
64 return S_OK; 64 return S_OK;
65} 65}
@@ -130,7 +130,7 @@ HRESULT CUpdateCallbackGUI::OpenFileError(const FString &path, DWORD systemError
130 FailedFiles.Add(path); 130 FailedFiles.Add(path);
131 // if (systemError == ERROR_SHARING_VIOLATION) 131 // if (systemError == ERROR_SHARING_VIOLATION)
132 { 132 {
133 ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); 133 ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path));
134 return S_FALSE; 134 return S_FALSE;
135 } 135 }
136 // return systemError; 136 // return systemError;
@@ -209,7 +209,7 @@ HRESULT CUpdateCallbackGUI::Open_SetCompleted(const UInt64 * /* numFiles */, con
209 return ProgressDialog->Sync.CheckStop(); 209 return ProgressDialog->Sync.CheckStop();
210} 210}
211 211
212#ifndef _NO_CRYPTO 212#ifndef Z7_NO_CRYPTO
213 213
214HRESULT CUpdateCallbackGUI::Open_CryptoGetTextPassword(BSTR *password) 214HRESULT CUpdateCallbackGUI::Open_CryptoGetTextPassword(BSTR *password)
215{ 215{
@@ -260,7 +260,7 @@ HRESULT CUpdateCallbackGUI::StartOpenArchive(const wchar_t * /* name */)
260HRESULT CUpdateCallbackGUI::ReadingFileError(const FString &path, DWORD systemError) 260HRESULT CUpdateCallbackGUI::ReadingFileError(const FString &path, DWORD systemError)
261{ 261{
262 FailedFiles.Add(path); 262 FailedFiles.Add(path);
263 ProgressDialog->Sync.AddError_Code_Name(systemError, fs2us(path)); 263 ProgressDialog->Sync.AddError_Code_Name(HRESULT_FROM_WIN32(systemError), fs2us(path));
264 return S_OK; 264 return S_OK;
265} 265}
266 266
diff --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI.h b/CPP/7zip/UI/GUI/UpdateCallbackGUI.h
index 2e0c111..998249a 100644
--- a/CPP/7zip/UI/GUI/UpdateCallbackGUI.h
+++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI.h
@@ -1,34 +1,31 @@
1// UpdateCallbackGUI.h 1// UpdateCallbackGUI.h
2 2
3#ifndef __UPDATE_CALLBACK_GUI_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_GUI_H
4#define __UPDATE_CALLBACK_GUI_H 4#define ZIP7_INC_UPDATE_CALLBACK_GUI_H
5 5
6#include "../Common/Update.h" 6#include "../Common/Update.h"
7#include "../Common/ArchiveOpenCallback.h" 7#include "../Common/ArchiveOpenCallback.h"
8 8
9#include "UpdateCallbackGUI2.h" 9#include "UpdateCallbackGUI2.h"
10 10
11class CUpdateCallbackGUI: 11class CUpdateCallbackGUI Z7_final:
12 public IOpenCallbackUI, 12 public IOpenCallbackUI,
13 public IUpdateCallbackUI2, 13 public IUpdateCallbackUI2,
14 public CUpdateCallbackGUI2 14 public CUpdateCallbackGUI2
15{ 15{
16public: 16 Z7_IFACE_IMP(IOpenCallbackUI)
17 // CUpdateCallbackGUI(); 17 Z7_IFACE_IMP(IUpdateCallbackUI)
18 // ~CUpdateCallbackGUI(); 18 Z7_IFACE_IMP(IDirItemsCallback)
19 Z7_IFACE_IMP(IUpdateCallbackUI2)
19 20
21public:
20 bool AskPassword; 22 bool AskPassword;
21 23 FStringVector FailedFiles;
22 void Init();
23 24
24 CUpdateCallbackGUI(): 25 CUpdateCallbackGUI():
25 AskPassword(false) 26 AskPassword(false)
26 {} 27 {}
27 28 void Init();
28 INTERFACE_IUpdateCallbackUI2(;)
29 INTERFACE_IOpenCallbackUI(;)
30
31 FStringVector FailedFiles;
32}; 29};
33 30
34#endif 31#endif
diff --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp
index 4eeead7..966f57e 100644
--- a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp
+++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.cpp
@@ -31,7 +31,7 @@ void CUpdateCallbackGUI2::Init()
31 31
32 _lang_Removing = LangString(IDS_PROGRESS_REMOVE); 32 _lang_Removing = LangString(IDS_PROGRESS_REMOVE);
33 _lang_Ops.Clear(); 33 _lang_Ops.Clear();
34 for (unsigned i = 0; i < ARRAY_SIZE(k_UpdNotifyLangs); i++) 34 for (unsigned i = 0; i < Z7_ARRAY_SIZE(k_UpdNotifyLangs); i++)
35 _lang_Ops.Add(LangString(k_UpdNotifyLangs[i])); 35 _lang_Ops.Add(LangString(k_UpdNotifyLangs[i]));
36} 36}
37 37
diff --git a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h
index 2b30ad2..e32b602 100644
--- a/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h
+++ b/CPP/7zip/UI/GUI/UpdateCallbackGUI2.h
@@ -1,7 +1,7 @@
1// UpdateCallbackGUI2.h 1// UpdateCallbackGUI2.h
2 2
3#ifndef __UPDATE_CALLBACK_GUI2_H 3#ifndef ZIP7_INC_UPDATE_CALLBACK_GUI2_H
4#define __UPDATE_CALLBACK_GUI2_H 4#define ZIP7_INC_UPDATE_CALLBACK_GUI2_H
5 5
6#include "../FileManager/ProgressDialog2.h" 6#include "../FileManager/ProgressDialog2.h"
7 7
@@ -23,7 +23,6 @@ public:
23 NumFiles(0) 23 NumFiles(0)
24 {} 24 {}
25 25
26 // ~CUpdateCallbackGUI2();
27 void Init(); 26 void Init();
28 27
29 CProgressDialog *ProgressDialog; 28 CProgressDialog *ProgressDialog;
diff --git a/CPP/7zip/UI/GUI/UpdateGUI.cpp b/CPP/7zip/UI/GUI/UpdateGUI.cpp
index 2d04143..aaf7ebd 100644
--- a/CPP/7zip/UI/GUI/UpdateGUI.cpp
+++ b/CPP/7zip/UI/GUI/UpdateGUI.cpp
@@ -37,7 +37,7 @@ UString HResultToMessage(HRESULT errorCode);
37 37
38class CThreadUpdating: public CProgressThreadVirt 38class CThreadUpdating: public CProgressThreadVirt
39{ 39{
40 HRESULT ProcessVirt(); 40 HRESULT ProcessVirt() Z7_override;
41public: 41public:
42 CCodecs *codecs; 42 CCodecs *codecs;
43 const CObjectVector<COpenType> *formatIndices; 43 const CObjectVector<COpenType> *formatIndices;
@@ -185,7 +185,7 @@ static void ParseAndAddPropertires(CObjectVector<CProperty> &properties,
185 property.Name = s; 185 property.Name = s;
186 else 186 else
187 { 187 {
188 property.Name.SetFrom(s, index); 188 property.Name.SetFrom(s, (unsigned)index);
189 property.Value = s.Ptr(index + 1); 189 property.Value = s.Ptr(index + 1);
190 } 190 }
191 properties.Add(property); 191 properties.Add(property);
@@ -222,6 +222,16 @@ static void SetOutProperties(
222 name += (di.OrderMode ? "mem" : "d"); 222 name += (di.OrderMode ? "mem" : "d");
223 AddProp_Size(properties, name, di.Dict64); 223 AddProp_Size(properties, name, di.Dict64);
224 } 224 }
225 /*
226 if (di.Dict64_Chain != (UInt64)(Int64)-1)
227 {
228 AString name;
229 if (is7z)
230 name = "0";
231 name += "dc";
232 AddProp_Size(properties, name, di.Dict64_Chain);
233 }
234 */
225 if (di.Order != (UInt32)(Int32)-1) 235 if (di.Order != (UInt32)(Int32)-1)
226 { 236 {
227 AString name; 237 AString name;
@@ -287,17 +297,17 @@ static const C_UpdateMode_ToAction_Pair g_UpdateMode_Pairs[] =
287 297
288static int FindActionSet(const NUpdateArchive::CActionSet &actionSet) 298static int FindActionSet(const NUpdateArchive::CActionSet &actionSet)
289{ 299{
290 for (unsigned i = 0; i < ARRAY_SIZE(g_UpdateMode_Pairs); i++) 300 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_UpdateMode_Pairs); i++)
291 if (actionSet.IsEqualTo(*g_UpdateMode_Pairs[i].ActionSet)) 301 if (actionSet.IsEqualTo(*g_UpdateMode_Pairs[i].ActionSet))
292 return i; 302 return (int)i;
293 return -1; 303 return -1;
294} 304}
295 305
296static int FindUpdateMode(NCompressDialog::NUpdateMode::EEnum mode) 306static int FindUpdateMode(NCompressDialog::NUpdateMode::EEnum mode)
297{ 307{
298 for (unsigned i = 0; i < ARRAY_SIZE(g_UpdateMode_Pairs); i++) 308 for (unsigned i = 0; i < Z7_ARRAY_SIZE(g_UpdateMode_Pairs); i++)
299 if (mode == g_UpdateMode_Pairs[i].UpdateMode) 309 if (mode == g_UpdateMode_Pairs[i].UpdateMode)
300 return i; 310 return (int)i;
301 return -1; 311 return -1;
302} 312}
303 313
@@ -365,10 +375,14 @@ static HRESULT ShowDialog(
365 } 375 }
366 } 376 }
367 377
368 378
379 /*
380 // v23: we restore current dir in dialog code
369 #if defined(_WIN32) && !defined(UNDER_CE) 381 #if defined(_WIN32) && !defined(UNDER_CE)
370 CCurrentDirRestorer curDirRestorer; 382 CCurrentDirRestorer curDirRestorer;
371 #endif 383 #endif
384 */
385
372 CCompressDialog dialog; 386 CCompressDialog dialog;
373 NCompressDialog::CInfo &di = dialog.Info; 387 NCompressDialog::CInfo &di = dialog.Info;
374 dialog.ArcFormats = &codecs->Formats; 388 dialog.ArcFormats = &codecs->Formats;
@@ -453,9 +467,11 @@ static HRESULT ShowDialog(
453 if (di.PreserveATime.Def) 467 if (di.PreserveATime.Def)
454 options.PreserveATime = di.PreserveATime.Val; 468 options.PreserveATime = di.PreserveATime.Val;
455 469
470 /*
456 #if defined(_WIN32) && !defined(UNDER_CE) 471 #if defined(_WIN32) && !defined(UNDER_CE)
457 curDirRestorer.NeedRestore = dialog.CurrentDirWasChanged; 472 curDirRestorer.NeedRestore = dialog.CurrentDirWasChanged;
458 #endif 473 #endif
474 */
459 475
460 options.VolumesSizes = di.VolumeSizes; 476 options.VolumesSizes = di.VolumeSizes;
461 /* 477 /*
@@ -539,7 +555,7 @@ HRESULT UpdateGUI(
539 bool needSetPath = true; 555 bool needSetPath = true;
540 if (showDialog) 556 if (showDialog)
541 { 557 {
542 RINOK(ShowDialog(codecs, censor.CensorPaths, options, callback, hwndParent)); 558 RINOK(ShowDialog(codecs, censor.CensorPaths, options, callback, hwndParent))
543 needSetPath = false; 559 needSetPath = false;
544 } 560 }
545 if (options.SfxMode && options.SfxModule.IsEmpty()) 561 if (options.SfxMode && options.SfxModule.IsEmpty())
@@ -582,7 +598,7 @@ HRESULT UpdateGUI(
582 tu.Options = &options; 598 tu.Options = &options;
583 tu.IconID = IDI_ICON; 599 tu.IconID = IDI_ICON;
584 600
585 RINOK(tu.Create(title, hwndParent)); 601 RINOK(tu.Create(title, hwndParent))
586 602
587 messageWasDisplayed = tu.ThreadFinishedOK && tu.MessagesDisplayed; 603 messageWasDisplayed = tu.ThreadFinishedOK && tu.MessagesDisplayed;
588 return tu.Result; 604 return tu.Result;
diff --git a/CPP/7zip/UI/GUI/UpdateGUI.h b/CPP/7zip/UI/GUI/UpdateGUI.h
index d1880de..0c43a01 100644
--- a/CPP/7zip/UI/GUI/UpdateGUI.h
+++ b/CPP/7zip/UI/GUI/UpdateGUI.h
@@ -1,7 +1,7 @@
1// GUI/UpdateGUI.h 1// GUI/UpdateGUI.h
2 2
3#ifndef __UPDATE_GUI_H 3#ifndef ZIP7_INC_UPDATE_GUI_H
4#define __UPDATE_GUI_H 4#define ZIP7_INC_UPDATE_GUI_H
5 5
6#include "../Common/Update.h" 6#include "../Common/Update.h"
7 7
diff --git a/CPP/7zip/UI/GUI/makefile b/CPP/7zip/UI/GUI/makefile
index 123410c..9e2a9b4 100644
--- a/CPP/7zip/UI/GUI/makefile
+++ b/CPP/7zip/UI/GUI/makefile
@@ -1,13 +1,13 @@
1PROG = 7zG.exe 1PROG = 7zG.exe
2CFLAGS = $(CFLAGS) \ 2CFLAGS = $(CFLAGS) \
3 -DLANG \ 3 -DZ7_LANG \
4 -DEXTERNAL_CODECS \ 4 -DZ7_EXTERNAL_CODECS \
5 5
6!IFDEF UNDER_CE 6!IFDEF UNDER_CE
7LIBS = $(LIBS) ceshell.lib Commctrl.lib 7LIBS = $(LIBS) ceshell.lib Commctrl.lib
8!ELSE 8!ELSE
9LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib gdi32.lib 9LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib gdi32.lib
10CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -DSUPPORT_DEVICE_FILE -D_7ZIP_LARGE_PAGES 10CFLAGS = $(CFLAGS) -DZ7_LONG_PATH -DZ7_LARGE_PAGES -DZ7_DEVICE_FILE
11!ENDIF 11!ENDIF
12 12
13GUI_OBJS = \ 13GUI_OBJS = \
@@ -72,6 +72,7 @@ WIN_CTRL_OBJS = \
72 $O\FilterCoder.obj \ 72 $O\FilterCoder.obj \
73 $O\LimitedStreams.obj \ 73 $O\LimitedStreams.obj \
74 $O\MethodProps.obj \ 74 $O\MethodProps.obj \
75 $O\MultiOutStream.obj \
75 $O\ProgressUtils.obj \ 76 $O\ProgressUtils.obj \
76 $O\PropId.obj \ 77 $O\PropId.obj \
77 $O\StreamObjects.obj \ 78 $O\StreamObjects.obj \
diff --git a/CPP/7zip/warn_clang.mak b/CPP/7zip/warn_clang.mak
index ed4f908..0d00730 100644
--- a/CPP/7zip/warn_clang.mak
+++ b/CPP/7zip/warn_clang.mak
@@ -1,37 +1,3 @@
1CFLAGS_WARN_CLANG_3_8_UNIQ = \ 1CFLAGS_WARN = -Weverything -Wfatal-errors
2 -Wno-reserved-id-macro \ 2# CXX_STD_FLAGS = -std=c++11
3 -Wno-old-style-cast \ 3# CXX_STD_FLAGS =
4 -Wno-c++11-long-long \
5 -Wno-unused-macros \
6
7CFLAGS_WARN_CLANG_3_8 = \
8 $(CFLAGS_WARN_CLANG_3_8_UNIQ) \
9 -Weverything \
10 -Wno-extra-semi \
11 -Wno-sign-conversion \
12 -Wno-language-extension-token \
13 -Wno-global-constructors \
14 -Wno-non-virtual-dtor \
15 -Wno-switch-enum \
16 -Wno-covered-switch-default \
17 -Wno-cast-qual \
18 -Wno-padded \
19 -Wno-exit-time-destructors \
20 -Wno-weak-vtables \
21
22CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \
23 -Wno-extra-semi-stmt \
24 -Wno-zero-as-null-pointer-constant \
25 -Wno-deprecated-dynamic-exception-spec \
26 -Wno-c++98-compat-pedantic \
27 -Wno-atomic-implicit-seq-cst \
28 -Wconversion \
29 -Wno-sign-conversion \
30
31CFLAGS_WARN_1 = \
32 -Wno-deprecated-copy-dtor \
33
34
35
36
37CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_1)
diff --git a/CPP/7zip/warn_clang_mac.mak b/CPP/7zip/warn_clang_mac.mak
index aadf14f..ed936c5 100644
--- a/CPP/7zip/warn_clang_mac.mak
+++ b/CPP/7zip/warn_clang_mac.mak
@@ -1,39 +1,9 @@
1CFLAGS_WARN_CLANG_3_8_UNIQ = \ 1CFLAGS_WARN = -Weverything -Wfatal-errors -Wno-poison-system-directories
2 -Wno-reserved-id-macro \ 2CXX_STD_FLAGS = -std=c++98
3 -Wno-old-style-cast \ 3CXX_STD_FLAGS = -std=c++11
4 -Wno-c++11-long-long \ 4CXX_STD_FLAGS = -std=c++14
5 -Wno-unused-macros \ 5CXX_STD_FLAGS = -std=c++17
6 6CXX_STD_FLAGS = -std=c++20
7CFLAGS_WARN_CLANG_3_8 = \ 7CXX_STD_FLAGS = -std=c++23
8 $(CFLAGS_WARN_CLANG_3_8_UNIQ) \ 8
9 -Weverything \ 9CXX_STD_FLAGS = -std=c++11
10 -Wno-extra-semi \
11 -Wno-sign-conversion \
12 -Wno-language-extension-token \
13 -Wno-global-constructors \
14 -Wno-non-virtual-dtor \
15 -Wno-switch-enum \
16 -Wno-covered-switch-default \
17 -Wno-cast-qual \
18 -Wno-padded \
19 -Wno-exit-time-destructors \
20 -Wno-weak-vtables \
21
22CFLAGS_WARN_CLANG_12= $(CFLAGS_WARN_CLANG_3_8) \
23 -Wno-extra-semi-stmt \
24 -Wno-zero-as-null-pointer-constant \
25 -Wno-deprecated-dynamic-exception-spec \
26 -Wno-c++98-compat-pedantic \
27 -Wno-atomic-implicit-seq-cst \
28 -Wconversion \
29 -Wno-sign-conversion \
30 -Wno-suggest-override \
31 -Wno-suggest-destructor-override \
32
33CFLAGS_WARN_MAC = \
34 -Wno-poison-system-directories \
35 -Wno-c++11-long-long \
36 -Wno-atomic-implicit-seq-cst \
37
38
39CFLAGS_WARN = $(CFLAGS_WARN_CLANG_12) $(CFLAGS_WARN_MAC)
diff --git a/CPP/7zip/warn_gcc.mak b/CPP/7zip/warn_gcc.mak
index 3185326..7eb1f57 100644
--- a/CPP/7zip/warn_gcc.mak
+++ b/CPP/7zip/warn_gcc.mak
@@ -1,57 +1,45 @@
1CFLAGS_WARN_GCC_4_5 = \ 1CFLAGS_WARN_GCC_4_8 = \
2
3CFLAGS_WARN_GCC_6 = \
4 -Waddress \ 2 -Waddress \
5 -Waggressive-loop-optimizations \ 3 -Waggressive-loop-optimizations \
6 -Wattributes \ 4 -Wattributes \
7 -Wbool-compare \
8 -Wcast-align \ 5 -Wcast-align \
9 -Wcomment \ 6 -Wcomment \
10 -Wdiv-by-zero \ 7 -Wdiv-by-zero \
11 -Wduplicated-cond \
12 -Wformat-contains-nul \ 8 -Wformat-contains-nul \
13 -Winit-self \ 9 -Winit-self \
14 -Wint-to-pointer-cast \ 10 -Wint-to-pointer-cast \
15 -Wunused \ 11 -Wunused \
16 -Wunused-macros \ 12 -Wunused-macros \
17 13
14CFLAGS_WARN_GCC_6 = $(CFLAGS_WARN_GCC_4_8)\
15 -Wbool-compare \
16 -Wduplicated-cond \
17
18# -Wno-strict-aliasing 18# -Wno-strict-aliasing
19 19
20CFLAGS_WARN_GCC_9 = \ 20CFLAGS_WARN_GCC_9 = $(CFLAGS_WARN_GCC_6)\
21 -Waddress \
22 -Waddress-of-packed-member \ 21 -Waddress-of-packed-member \
23 -Waggressive-loop-optimizations \
24 -Wattributes \
25 -Wbool-compare \
26 -Wbool-operation \ 22 -Wbool-operation \
27 -Wcast-align \
28 -Wcast-align=strict \ 23 -Wcast-align=strict \
29 -Wcomment \ 24 -Wconversion \
30 -Wdangling-else \ 25 -Wdangling-else \
31 -Wdiv-by-zero \
32 -Wduplicated-branches \ 26 -Wduplicated-branches \
33 -Wduplicated-cond \
34 -Wformat-contains-nul \
35 -Wimplicit-fallthrough=5 \ 27 -Wimplicit-fallthrough=5 \
36 -Winit-self \
37 -Wint-in-bool-context \ 28 -Wint-in-bool-context \
38 -Wint-to-pointer-cast \ 29 -Wmaybe-uninitialized \
39 -Wunused \ 30 -Wmisleading-indentation \
40 -Wunused-macros \ 31 -Wmissing-attributes
41 -Wconversion \
42 32
33# In C: -Wsign-conversion enabled also by -Wconversion
43# -Wno-sign-conversion \ 34# -Wno-sign-conversion \
44 35
45CFLAGS_WARN_GCC_10 = $(CFLAGS_WARN_GCC_9) \
46 -Wmaybe-uninitialized \
47 -Wmisleading-indentation \
48 36
49CFLAGS_WARN_GCC_PPMD_UNALIGNED = \ 37CFLAGS_WARN_GCC_PPMD_UNALIGNED = \
50 -Wno-strict-aliasing \ 38 -Wno-strict-aliasing \
51 39
52 40
53CFLAGS_WARN = $(CFLAGS_WARN_GCC_9) \ 41# CFLAGS_WARN = $(CFLAGS_WARN_GCC_4_8)
54 42CFLAGS_WARN = $(CFLAGS_WARN_GCC_9)
55# $(CFLAGS_WARN_GCC_PPMD_UNALIGNED)
56 43
57 \ No newline at end of file 44# CXX_STD_FLAGS = -std=c++11
45# CXX_STD_FLAGS =
diff --git a/CPP/Build.mak b/CPP/Build.mak
index 1ef676e..393fa2c 100644
--- a/CPP/Build.mak
+++ b/CPP/Build.mak
@@ -4,6 +4,11 @@ LIBS = $(LIBS) oleaut32.lib ole32.lib
4CFLAGS = $(CFLAGS) -DUNICODE -D_UNICODE 4CFLAGS = $(CFLAGS) -DUNICODE -D_UNICODE
5!ENDIF 5!ENDIF
6 6
7!IF "$(CC)" != "clang-cl"
8# for link time code generation:
9# CFLAGS = $(CFLAGS) -GL
10!ENDIF
11
7!IFNDEF O 12!IFNDEF O
8!IFDEF PLATFORM 13!IFDEF PLATFORM
9O=$(PLATFORM) 14O=$(PLATFORM)
@@ -51,33 +56,22 @@ COMPL_ASM = $(MY_ML) $** $O/$(*B).obj
51COMPL_ASM = $(MY_ML) -c -Fo$O/ $** 56COMPL_ASM = $(MY_ML) -c -Fo$O/ $**
52!ENDIF 57!ENDIF
53 58
54CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ -W4 -WX -EHsc -Gy -GR- -GF 59!IFDEF OLD_COMPILER
60CFLAGS_WARN_LEVEL = -W4
61!ELSE
62CFLAGS_WARN_LEVEL = -Wall
63!ENDIF
64
65CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ $(CFLAGS_WARN_LEVEL) -WX -EHsc -Gy -GR- -GF
55 66
56!IF "$(CC)" == "clang-cl" 67!IF "$(CC)" == "clang-cl"
57 68
58CFLAGS = $(CFLAGS) \ 69CFLAGS = $(CFLAGS) \
59 -Werror \ 70 -Werror \
60 -Wextra \
61 -Wall \ 71 -Wall \
72 -Wextra \
62 -Weverything \ 73 -Weverything \
63 -Wno-extra-semi-stmt \ 74 -Wfatal-errors \
64 -Wno-extra-semi \
65 -Wno-zero-as-null-pointer-constant \
66 -Wno-sign-conversion \
67 -Wno-old-style-cast \
68 -Wno-reserved-id-macro \
69 -Wno-deprecated-dynamic-exception-spec \
70 -Wno-language-extension-token \
71 -Wno-global-constructors \
72 -Wno-non-virtual-dtor \
73 -Wno-deprecated-copy-dtor \
74 -Wno-exit-time-destructors \
75 -Wno-switch-enum \
76 -Wno-covered-switch-default \
77 -Wno-nonportable-system-include-path \
78 -Wno-c++98-compat-pedantic \
79 -Wno-cast-qual \
80 -Wc++11-extensions \
81 75
82!ENDIF 76!ENDIF
83 77
@@ -92,8 +86,21 @@ CFLAGS = $(CFLAGS) -MT
92 86
93CFLAGS = $(CFLAGS_COMMON) $(CFLAGS) 87CFLAGS = $(CFLAGS_COMMON) $(CFLAGS)
94 88
89
95!IFNDEF OLD_COMPILER 90!IFNDEF OLD_COMPILER
96CFLAGS = $(CFLAGS) -GS- -Zc:forScope -Zc:wchar_t 91
92CFLAGS = $(CFLAGS) -GS- -Zc:wchar_t
93!IFDEF VCTOOLSVERSION
94!IF "$(VCTOOLSVERSION)" >= "14.00"
95!IF "$(CC)" != "clang-cl"
96CFLAGS = $(CFLAGS) -Zc:throwingNew
97!ENDIF
98!ENDIF
99!ELSE
100# -Zc:forScope is default in VS2010. so we need it only for older versions
101CFLAGS = $(CFLAGS) -Zc:forScope
102!ENDIF
103
97!IFNDEF UNDER_CE 104!IFNDEF UNDER_CE
98!IF "$(CC)" != "clang-cl" 105!IF "$(CC)" != "clang-cl"
99CFLAGS = $(CFLAGS) -MP4 106CFLAGS = $(CFLAGS) -MP4
@@ -102,10 +109,10 @@ CFLAGS = $(CFLAGS) -MP4
102# CFLAGS = $(CFLAGS) -arch:IA32 109# CFLAGS = $(CFLAGS) -arch:IA32
103!ENDIF 110!ENDIF
104!ENDIF 111!ENDIF
105!ELSE 112
106CFLAGS = $(CFLAGS)
107!ENDIF 113!ENDIF
108 114
115
109!IFDEF MY_CONSOLE 116!IFDEF MY_CONSOLE
110CFLAGS = $(CFLAGS) -D_CONSOLE 117CFLAGS = $(CFLAGS) -D_CONSOLE
111!ENDIF 118!ENDIF
@@ -123,7 +130,7 @@ CFLAGS_O1 = $(CFLAGS) -O1
123!ENDIF 130!ENDIF
124CFLAGS_O2 = $(CFLAGS) -O2 131CFLAGS_O2 = $(CFLAGS) -O2
125 132
126LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF 133LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF -INCREMENTAL:NO
127 134
128!IFNDEF UNDER_CE 135!IFNDEF UNDER_CE
129LFLAGS = $(LFLAGS) /LARGEADDRESSAWARE 136LFLAGS = $(LFLAGS) /LARGEADDRESSAWARE
@@ -140,6 +147,12 @@ LFLAGS = $(LFLAGS) /FIXED:NO
140# /BASE:0x400000 147# /BASE:0x400000
141!ENDIF 148!ENDIF
142 149
150!IF "$(PLATFORM)" == "arm64"
151# we can get better compression ratio with ARM64 filter if we change alignment to 4096
152# LFLAGS = $(LFLAGS) /FILEALIGN:4096
153!ENDIF
154
155
143 156
144# !IF "$(PLATFORM)" == "x64" 157# !IF "$(PLATFORM)" == "x64"
145 158
@@ -162,21 +175,23 @@ COMPL_O1 = $(CC) $(CFLAGS_O1) $**
162COMPL_O2 = $(CC) $(CFLAGS_O2) $** 175COMPL_O2 = $(CC) $(CFLAGS_O2) $**
163COMPL_PCH = $(CC) $(CFLAGS_O1) -Yc"StdAfx.h" -Fp$O/a.pch $** 176COMPL_PCH = $(CC) $(CFLAGS_O1) -Yc"StdAfx.h" -Fp$O/a.pch $**
164COMPL = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $** 177COMPL = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $**
165 178COMPLB = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $<
166COMPLB = $(CC) $(CFLAGS_O1) -Yu"StdAfx.h" -Fp$O/a.pch $< 179COMPLB_O2 = $(CC) $(CFLAGS_O2) $<
167# COMPLB_O2 = $(CC) $(CFLAGS_O2) -Yu"StdAfx.h" -Fp$O/a.pch $< 180# COMPLB_O2 = $(CC) $(CFLAGS_O2) -Yu"StdAfx.h" -Fp$O/a.pch $<
168COMPLB_O2 = $(CC) $(CFLAGS_O2) $<
169 181
170CFLAGS_C_ALL = $(CFLAGS_O2) $(CFLAGS_C_SPEC) 182CFLAGS_C_ALL = $(CFLAGS_O2) $(CFLAGS_C_SPEC)
183
171CCOMPL_PCH = $(CC) $(CFLAGS_C_ALL) -Yc"Precomp.h" -Fp$O/a.pch $** 184CCOMPL_PCH = $(CC) $(CFLAGS_C_ALL) -Yc"Precomp.h" -Fp$O/a.pch $**
172CCOMPL_USE = $(CC) $(CFLAGS_C_ALL) -Yu"Precomp.h" -Fp$O/a.pch $** 185CCOMPL_USE = $(CC) $(CFLAGS_C_ALL) -Yu"Precomp.h" -Fp$O/a.pch $**
186CCOMPLB_USE = $(CC) $(CFLAGS_C_ALL) -Yu"Precomp.h" -Fp$O/a.pch $<
173CCOMPL = $(CC) $(CFLAGS_C_ALL) $** 187CCOMPL = $(CC) $(CFLAGS_C_ALL) $**
174CCOMPLB = $(CC) $(CFLAGS_C_ALL) $< 188CCOMPLB = $(CC) $(CFLAGS_C_ALL) $<
175 189
176!IF "$(CC)" == "clang-cl" 190!IF "$(CC)" == "clang-cl"
177COMPL = $(COMPL) -FI StdAfx.h 191COMPL = $(COMPL) -FI StdAfx.h
178COMPLB = $(COMPLB) -FI StdAfx.h 192COMPLB = $(COMPLB) -FI StdAfx.h
179CCOMPL_USE = $(CCOMPL_USE) -FI Precomp.h 193CCOMPL_USE = $(CCOMPL_USE) -FI Precomp.h
194CCOMPLB_USE = $(CCOMPLB_USE) -FI Precomp.h
180!ENDIF 195!ENDIF
181 196
182all: $(PROGPATH) 197all: $(PROGPATH)
@@ -189,6 +204,11 @@ $O:
189$O/asm: 204$O/asm:
190 if not exist "$O/asm" mkdir "$O/asm" 205 if not exist "$O/asm" mkdir "$O/asm"
191 206
207!IF "$(CC)" != "clang-cl"
208# for link time code generation:
209# LFLAGS = $(LFLAGS) -LTCG
210!ENDIF
211
192$(PROGPATH): $O $O/asm $(OBJS) $(DEF_FILE) 212$(PROGPATH): $O $O/asm $(OBJS) $(DEF_FILE)
193 link $(LFLAGS) -out:$(PROGPATH) $(OBJS) $(LIBS) 213 link $(LFLAGS) -out:$(PROGPATH) $(OBJS) $(LIBS)
194 214
@@ -198,3 +218,12 @@ $O\resource.res: $(*B).rc
198!ENDIF 218!ENDIF
199$O\StdAfx.obj: $(*B).cpp 219$O\StdAfx.obj: $(*B).cpp
200 $(COMPL_PCH) 220 $(COMPL_PCH)
221
222predef: empty.c
223 $(CCOMPL) /EP /Zc:preprocessor /PD
224predef2: A.cpp
225 $(COMPL) -EP -Zc:preprocessor -PD
226predef3: A.cpp
227 $(COMPL) -E -dM
228predef4: A.cpp
229 $(COMPL_O2) -E
diff --git a/CPP/Common/AutoPtr.h b/CPP/Common/AutoPtr.h
index 006d315..0be8a7a 100644
--- a/CPP/Common/AutoPtr.h
+++ b/CPP/Common/AutoPtr.h
@@ -1,13 +1,13 @@
1// Common/AutoPtr.h 1// Common/AutoPtr.h
2 2
3#ifndef __COMMON_AUTOPTR_H 3#ifndef ZIP7_INC_COMMON_AUTOPTR_H
4#define __COMMON_AUTOPTR_H 4#define ZIP7_INC_COMMON_AUTOPTR_H
5 5
6template<class T> class CMyAutoPtr 6template<class T> class CMyAutoPtr
7{ 7{
8 T *_p; 8 T *_p;
9public: 9public:
10 CMyAutoPtr(T *p = 0) : _p(p) {} 10 CMyAutoPtr(T *p = NULL) : _p(p) {}
11 CMyAutoPtr(CMyAutoPtr<T>& p): _p(p.release()) {} 11 CMyAutoPtr(CMyAutoPtr<T>& p): _p(p.release()) {}
12 CMyAutoPtr<T>& operator=(CMyAutoPtr<T>& p) 12 CMyAutoPtr<T>& operator=(CMyAutoPtr<T>& p)
13 { 13 {
@@ -21,10 +21,10 @@ public:
21 T* release() 21 T* release()
22 { 22 {
23 T *tmp = _p; 23 T *tmp = _p;
24 _p = 0; 24 _p = NULL;
25 return tmp; 25 return tmp;
26 } 26 }
27 void reset(T* p = 0) 27 void reset(T* p = NULL)
28 { 28 {
29 if (p != _p) 29 if (p != _p)
30 delete _p; 30 delete _p;
diff --git a/CPP/Common/C_FileIO.h b/CPP/Common/C_FileIO.h
index 6818558..12d9439 100644
--- a/CPP/Common/C_FileIO.h
+++ b/CPP/Common/C_FileIO.h
@@ -1,6 +1,6 @@
1// Common/C_FileIO.h 1// Common/C_FileIO.h
2 2
3#ifndef __COMMON_C_FILEIO_H 3#ifndef ZIP7_INC_COMMON_C_FILEIO_H
4#define __COMMON_C_FILEIO_H 4#define ZIP7_INC_COMMON_C_FILEIO_H
5 5
6#endif 6#endif
diff --git a/CPP/Common/CksumReg.cpp b/CPP/Common/CksumReg.cpp
index 29d9f82..8c9c449 100644
--- a/CPP/Common/CksumReg.cpp
+++ b/CPP/Common/CksumReg.cpp
@@ -7,35 +7,30 @@
7#include "../Common/MyCom.h" 7#include "../Common/MyCom.h"
8 8
9#include "../7zip/Common/RegisterCodec.h" 9#include "../7zip/Common/RegisterCodec.h"
10
11#include "../7zip/Compress/BZip2Crc.h" 10#include "../7zip/Compress/BZip2Crc.h"
12 11
13class CCksumHasher: 12Z7_CLASS_IMP_COM_1(
14 public IHasher, 13 CCksumHasher
15 public CMyUnknownImp 14 , IHasher
16{ 15)
17 CBZip2Crc _crc; 16 CBZip2Crc _crc;
18 UInt64 _size; 17 UInt64 _size;
19 Byte mtDummy[1 << 7];
20
21public: 18public:
19 // Byte _mtDummy[1 << 7];
22 CCksumHasher() 20 CCksumHasher()
23 { 21 {
24 _crc.Init(0); 22 _crc.Init(0);
25 _size = 0; 23 _size = 0;
26 } 24 }
27
28 MY_UNKNOWN_IMP1(IHasher)
29 INTERFACE_IHasher(;)
30}; 25};
31 26
32STDMETHODIMP_(void) CCksumHasher::Init() throw() 27Z7_COM7F_IMF2(void, CCksumHasher::Init())
33{ 28{
34 _crc.Init(0); 29 _crc.Init(0);
35 _size = 0; 30 _size = 0;
36} 31}
37 32
38STDMETHODIMP_(void) CCksumHasher::Update(const void *data, UInt32 size) throw() 33Z7_COM7F_IMF2(void, CCksumHasher::Update(const void *data, UInt32 size))
39{ 34{
40 _size += size; 35 _size += size;
41 CBZip2Crc crc = _crc; 36 CBZip2Crc crc = _crc;
@@ -44,7 +39,7 @@ STDMETHODIMP_(void) CCksumHasher::Update(const void *data, UInt32 size) throw()
44 _crc = crc; 39 _crc = crc;
45} 40}
46 41
47STDMETHODIMP_(void) CCksumHasher::Final(Byte *digest) throw() 42Z7_COM7F_IMF2(void, CCksumHasher::Final(Byte *digest))
48{ 43{
49 UInt64 size = _size; 44 UInt64 size = _size;
50 CBZip2Crc crc = _crc; 45 CBZip2Crc crc = _crc;
@@ -54,7 +49,7 @@ STDMETHODIMP_(void) CCksumHasher::Final(Byte *digest) throw()
54 size >>= 8; 49 size >>= 8;
55 } 50 }
56 const UInt32 val = crc.GetDigest(); 51 const UInt32 val = crc.GetDigest();
57 SetUi32(digest, val); 52 SetUi32(digest, val)
58} 53}
59 54
60REGISTER_HASHER(CCksumHasher, 0x203, "CKSUM", 4) 55REGISTER_HASHER(CCksumHasher, 0x203, "CKSUM", 4)
diff --git a/CPP/Common/ComTry.h b/CPP/Common/ComTry.h
index 297c407..84746a7 100644
--- a/CPP/Common/ComTry.h
+++ b/CPP/Common/ComTry.h
@@ -1,7 +1,7 @@
1// ComTry.h 1// ComTry.h
2 2
3#ifndef __COM_TRY_H 3#ifndef ZIP7_INC_COM_TRY_H
4#define __COM_TRY_H 4#define ZIP7_INC_COM_TRY_H
5 5
6#include "MyWindows.h" 6#include "MyWindows.h"
7// #include "Exception.h" 7// #include "Exception.h"
diff --git a/CPP/Common/CommandLineParser.h b/CPP/Common/CommandLineParser.h
index fbd4fa5..fc6f028 100644
--- a/CPP/Common/CommandLineParser.h
+++ b/CPP/Common/CommandLineParser.h
@@ -1,7 +1,7 @@
1// Common/CommandLineParser.h 1// Common/CommandLineParser.h
2 2
3#ifndef __COMMON_COMMAND_LINE_PARSER_H 3#ifndef ZIP7_INC_COMMON_COMMAND_LINE_PARSER_H
4#define __COMMON_COMMAND_LINE_PARSER_H 4#define ZIP7_INC_COMMON_COMMAND_LINE_PARSER_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7 7
diff --git a/CPP/Common/Common.h b/CPP/Common/Common.h
index 72db7a8..0c77ab4 100644
--- a/CPP/Common/Common.h
+++ b/CPP/Common/Common.h
@@ -1,7 +1,13 @@
1// Common.h 1// Common.h
2 2
3#ifndef __COMMON_COMMON_H 3#if defined(_MSC_VER) && _MSC_VER >= 1800
4#define __COMMON_COMMON_H 4#pragma warning(disable : 4464) // relative include path contains '..'
5#endif
6
7#ifndef ZIP7_INC_COMMON_H
8#define ZIP7_INC_COMMON_H
9
10#include "../../C/Compiler.h"
5 11
6/* 12/*
7This file is included to all cpp files in 7-Zip. 13This 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,
16you can change this h file or h files included in this file. 22you can change this h file or h files included in this file.
17*/ 23*/
18 24
19// compiler pragmas to disable some warnings 25#ifdef _MSC_VER
20#include "../../C/Compiler.h" 26 #pragma warning(disable : 4710) // function not inlined
27 // 'CUncopyable::CUncopyable':
28 #pragma warning(disable : 4514) // unreferenced inline function has been removed
29 #if _MSC_VER < 1300
30 #pragma warning(disable : 4702) // unreachable code
31 #pragma warning(disable : 4714) // function marked as __forceinline not inlined
32 #pragma warning(disable : 4786) // identifier was truncated to '255' characters in the debug information
33 #endif
34 #if _MSC_VER < 1400
35 #pragma warning(disable : 4511) // copy constructor could not be generated // #pragma warning(disable : 4512) // assignment operator could not be generated
36 #pragma warning(disable : 4512) // assignment operator could not be generated
37 #endif
38 #if _MSC_VER > 1400 && _MSC_VER <= 1900
39 // #pragma warning(disable : 4996)
40 // strcat: This function or variable may be unsafe
41 // GetVersion was declared deprecated
42 #endif
21 43
22// it's <windows.h> or code that defines windows things, if it's not _WIN32 44#if _MSC_VER > 1200
23#include "MyWindows.h" 45// -Wall warnings
24 46
25// NewHandler.h and NewHandler.cpp redefine operator new() to throw exceptions, if compiled with old MSVC compilers 47#if _MSC_VER <= 1600
26#include "NewHandler.h" 48#pragma warning(disable : 4917) // 'OLE_HANDLE' : a GUID can only be associated with a class, interface or namespace
49#endif
27 50
51// #pragma warning(disable : 4061) // enumerator '' in switch of enum '' is not explicitly handled by a case label
52// #pragma warning(disable : 4266) // no override available for virtual member function from base ''; function is hidden
53#pragma warning(disable : 4625) // copy constructor was implicitly defined as deleted
54#pragma warning(disable : 4626) // assignment operator was implicitly defined as deleted
55#if _MSC_VER >= 1600 && _MSC_VER < 1920
56#pragma warning(disable : 4571) // Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught
57#endif
58#if _MSC_VER >= 1600
59#pragma warning(disable : 4365) // 'initializing' : conversion from 'int' to 'unsigned int', signed / unsigned mismatch
60#endif
61#if _MSC_VER < 1800
62// we disable the warning, if we don't use 'final' in class
63#pragma warning(disable : 4265) // class has virtual functions, but destructor is not virtual
64#endif
65
66#if _MSC_VER >= 1900
67#pragma warning(disable : 5026) // move constructor was implicitly defined as deleted
68#pragma warning(disable : 5027) // move assignment operator was implicitly defined as deleted
69#endif
70#if _MSC_VER >= 1912
71#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.
72#endif
73#if _MSC_VER >= 1925
74// #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
75#endif
76#if _MSC_VER >= 1934
77// #pragma warning(disable : 5264) // const variable is not used
78#endif
28 79
80#endif // _MSC_VER > 1200
81#endif // _MSC_VER
29 82
30#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 83
84#if defined(_MSC_VER) // && !defined(__clang__)
85#define Z7_DECLSPEC_NOTHROW __declspec(nothrow)
86#elif defined(__clang__) || defined(__GNUC__)
87#define Z7_DECLSPEC_NOTHROW __attribute__((nothrow))
88#else
89#define Z7_DECLSPEC_NOTHROW
90#endif
91
92/*
93#if defined (_MSC_VER) && _MSC_VER >= 1900 \
94 || defined(__clang__) && __clang_major__ >= 6 \
95 || defined(__GNUC__) && __GNUC__ >= 6
96 #define Z7_noexcept noexcept
97#else
98 #define Z7_noexcept throw()
99#endif
100*/
101
102
103#if defined(__clang__)
104
105// noexcept, final, = delete
106#pragma GCC diagnostic ignored "-Wc++98-compat"
107#if __clang_major__ >= 4
108// throw() dynamic exception specifications are deprecated
109#pragma GCC diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
110#endif
111#pragma GCC diagnostic ignored "-Wold-style-cast"
112#pragma GCC diagnostic ignored "-Wglobal-constructors"
113#pragma GCC diagnostic ignored "-Wexit-time-destructors"
114
115// #pragma GCC diagnostic ignored "-Wunused-private-field"
116// #pragma GCC diagnostic ignored "-Wnonportable-system-include-path"
117// #pragma GCC diagnostic ignored "-Wsuggest-override"
118// #pragma GCC diagnostic ignored "-Wsign-conversion"
119// #pragma GCC diagnostic ignored "-Winconsistent-missing-override"
120// #pragma GCC diagnostic ignored "-Wsuggest-destructor-override"
121// #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
122// #pragma GCC diagnostic ignored "-Wdeprecated-copy-with-user-provided-dtor"
123// #pragma GCC diagnostic ignored "-Wdeprecated-copy-dtor"
124// #ifndef _WIN32
125// #pragma GCC diagnostic ignored "-Wweak-vtables"
126// #endif
127/*
128#if defined(Z7_GCC_VERSION) && (Z7_GCC_VERSION >= 40400) \
129 || defined(Z7_CLANG_VERSION) && (Z7_CLANG_VERSION >= 30000)
130// enumeration values not explicitly handled in switch
131#pragma GCC diagnostic ignored "-Wswitch-enum"
132#endif
133*/
134#endif // __clang__
135
136
137#ifdef __GNUC__
138// #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
139#endif
31 140
32 141
33/* There is BUG in MSVC 6.0 compiler for operator new[]: 142/* There is BUG in MSVC 6.0 compiler for operator new[]:
34 It doesn't check overflow, when it calculates size in bytes for allocated array. 143 It doesn't check overflow, when it calculates size in bytes for allocated array.
35 So we can use MY_ARRAY_NEW macro instead of new[] operator. */ 144 So we can use Z7_ARRAY_NEW macro instead of new[] operator. */
36 145
37#if defined(_MSC_VER) && (_MSC_VER == 1200) && !defined(_WIN64) 146#if defined(_MSC_VER) && (_MSC_VER == 1200) && !defined(_WIN64)
38 #define MY_ARRAY_NEW(p, T, size) p = new T[((size) > (unsigned)0xFFFFFFFF / sizeof(T)) ? (unsigned)0xFFFFFFFF / sizeof(T) : (size)]; 147 #define Z7_ARRAY_NEW(p, T, size) p = new T[((size) > (unsigned)0xFFFFFFFF / sizeof(T)) ? (unsigned)0xFFFFFFFF / sizeof(T) : (size)];
39#else 148#else
40 #define MY_ARRAY_NEW(p, T, size) p = new T[size]; 149 #define Z7_ARRAY_NEW(p, T, size) p = new T[size];
41#endif 150#endif
42 151
43#if (defined(__GNUC__) && (__GNUC__ >= 8)) 152#if (defined(__GNUC__) && (__GNUC__ >= 8))
44 #define MY_ATTR_NORETURN __attribute__((noreturn)) 153 #define Z7_ATTR_NORETURN __attribute__((noreturn))
45#elif (defined(__clang__) && (__clang_major__ >= 3)) 154#elif (defined(__clang__) && (__clang_major__ >= 3))
46 #if __has_feature(cxx_attributes) 155 #if __has_feature(cxx_attributes)
47 #define MY_ATTR_NORETURN [[noreturn]] 156 #define Z7_ATTR_NORETURN [[noreturn]]
48 #else 157 #else
49 #define MY_ATTR_NORETURN __attribute__ ((noreturn)) 158 #define Z7_ATTR_NORETURN __attribute__((noreturn))
50 #endif 159 #endif
51#elif (defined(_MSC_VER) && (_MSC_VER >= 1900)) 160#elif (defined(_MSC_VER) && (_MSC_VER >= 1900))
52 #define MY_ATTR_NORETURN [[noreturn]] 161 #define Z7_ATTR_NORETURN [[noreturn]]
162#else
163 #define Z7_ATTR_NORETURN
164#endif
165
166
167// final in "GCC 4.7.0"
168// In C++98 and C++03 code the alternative spelling __final can be used instead (this is a GCC extension.)
169
170#if defined (__cplusplus) && __cplusplus >= 201103L \
171 || defined(_MSC_VER) && _MSC_VER >= 1800 \
172 || defined(__clang__) && __clang_major__ >= 4 \
173 /* || defined(__GNUC__) && __GNUC__ >= 9 */
174 #define Z7_final final
175 #if defined(__clang__) && __cplusplus < 201103L
176 #pragma GCC diagnostic ignored "-Wc++11-extensions"
177 #endif
178#elif defined (__cplusplus) && __cplusplus >= 199711L \
179 && defined(__GNUC__) && __GNUC__ >= 4 && !defined(__clang__)
180 #define Z7_final __final
53#else 181#else
54 #define MY_ATTR_NORETURN 182 #define Z7_final
183 #if defined(__clang__) && __clang_major__ >= 4 \
184 || defined(__GNUC__) && __GNUC__ >= 4
185 #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
186 #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
187 #endif
55#endif 188#endif
56 189
190#define Z7_class_final(c) class c Z7_final
191
192
193#if defined (__cplusplus) && __cplusplus >= 201103L \
194 || (defined(_MSC_VER) && _MSC_VER >= 1800)
195 #define Z7_CPP_IS_SUPPORTED_default
196 #define Z7_eq_delete = delete
197 // #define Z7_DECL_DEFAULT_COPY_CONSTRUCTOR_IF_SUPPORTED(c) c(const c& k) = default;
198#else
199 #define Z7_eq_delete
200 // #define Z7_DECL_DEFAULT_COPY_CONSTRUCTOR_IF_SUPPORTED(c)
57#endif 201#endif
202
203
204#if defined(__cplusplus) && (__cplusplus >= 201103L) \
205 || defined(_MSC_VER) && (_MSC_VER >= 1400) /* && (_MSC_VER != 1600) */ \
206 || defined(__clang__) && __clang_major__ >= 4
207 #if defined(_MSC_VER) && (_MSC_VER == 1600) /* && (_MSC_VER != 1600) */
208 #pragma warning(disable : 4481) // nonstandard extension used: override specifier 'override'
209 #define Z7_DESTRUCTOR_override
210 #else
211 #define Z7_DESTRUCTOR_override override
212 #endif
213 #define Z7_override override
214#else
215 #define Z7_override
216 #define Z7_DESTRUCTOR_override
217#endif
218
219
220
221#define Z7_CLASS_NO_COPY(cls) \
222 private: \
223 cls(const cls &) Z7_eq_delete; \
224 cls &operator=(const cls &) Z7_eq_delete;
225
226class CUncopyable
227{
228protected:
229 CUncopyable() {} // allow constructor
230 // ~CUncopyable() {}
231 Z7_CLASS_NO_COPY(CUncopyable)
232};
233
234#define MY_UNCOPYABLE :private CUncopyable
235// #define MY_UNCOPYABLE
236
237
238typedef void (*Z7_void_Function)(void);
239
240#if defined(__clang__) || defined(__GNUC__)
241#define Z7_CAST_FUNC(t, e) reinterpret_cast<t>(reinterpret_cast<Z7_void_Function>(e))
242#else
243#define Z7_CAST_FUNC(t, e) reinterpret_cast<t>(reinterpret_cast<void*>(e))
244// #define Z7_CAST_FUNC(t, e) reinterpret_cast<t>(e)
245#endif
246
247#define Z7_GET_PROC_ADDRESS(func_type, hmodule, func_name) \
248 Z7_CAST_FUNC(func_type, GetProcAddress(hmodule, func_name))
249
250// || defined(__clang__)
251// || defined(__GNUC__)
252
253#if defined(_MSC_VER) && (_MSC_VER >= 1400)
254#define Z7_DECLSPEC_NOVTABLE __declspec(novtable)
255#else
256#define Z7_DECLSPEC_NOVTABLE
257#endif
258
259#ifdef __clang__
260#define Z7_PURE_INTERFACES_BEGIN \
261_Pragma("GCC diagnostic push") \
262_Pragma("GCC diagnostic ignored \"-Wnon-virtual-dtor\"")
263_Pragma("GCC diagnostic ignored \"-Wweak-vtables\"")
264#define Z7_PURE_INTERFACES_END \
265_Pragma("GCC diagnostic pop")
266#else
267#define Z7_PURE_INTERFACES_BEGIN
268#define Z7_PURE_INTERFACES_END
269#endif
270
271// NewHandler.h and NewHandler.cpp redefine operator new() to throw exceptions, if compiled with old MSVC compilers
272#include "NewHandler.h"
273
274/*
275// #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
276#ifndef ARRAY_SIZE
277#define ARRAY_SIZE(a) Z7_ARRAY_SIZE(a)
278#endif
279*/
280
281#endif // ZIP7_INC_COMMON_H
282
283
284
285// #define Z7_REDEFINE_NULL
286
287#if defined(Z7_REDEFINE_NULL) /* && (!defined(__clang__) || defined(_MSC_VER)) */
288
289// NULL is defined in <stddef.h>
290#include <stddef.h>
291#undef NULL
292
293#ifdef __cplusplus
294 #if defined (__cplusplus) && __cplusplus >= 201103L \
295 || (defined(_MSC_VER) && _MSC_VER >= 1800)
296 #define NULL nullptr
297 #else
298 #define NULL 0
299 #endif
300#else
301 #define NULL ((void *)0)
302#endif
303
304#else // Z7_REDEFINE_NULL
305
306#if defined(__clang__) && __clang_major__ >= 5
307#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
308#endif
309
310#endif // Z7_REDEFINE_NULL
311
312// for precompiler:
313#include "MyWindows.h"
diff --git a/CPP/Common/CrcReg.cpp b/CPP/Common/CrcReg.cpp
index fdbba77..6cda892 100644
--- a/CPP/Common/CrcReg.cpp
+++ b/CPP/Common/CrcReg.cpp
@@ -11,42 +11,39 @@
11 11
12EXTERN_C_BEGIN 12EXTERN_C_BEGIN
13 13
14typedef UInt32 (MY_FAST_CALL *CRC_FUNC)(UInt32 v, const void *data, size_t size, const UInt32 *table); 14// UInt32 Z7_FASTCALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table);
15
16UInt32 MY_FAST_CALL CrcUpdateT1(UInt32 v, const void *data, size_t size, const UInt32 *table);
17 15
18extern CRC_FUNC g_CrcUpdate; 16extern CRC_FUNC g_CrcUpdate;
19extern CRC_FUNC g_CrcUpdateT4; 17// extern CRC_FUNC g_CrcUpdateT4;
20extern CRC_FUNC g_CrcUpdateT8; 18extern CRC_FUNC g_CrcUpdateT8;
21extern CRC_FUNC g_CrcUpdateT0_32; 19extern CRC_FUNC g_CrcUpdateT0_32;
22extern CRC_FUNC g_CrcUpdateT0_64; 20extern CRC_FUNC g_CrcUpdateT0_64;
23 21
24EXTERN_C_END 22EXTERN_C_END
25 23
26class CCrcHasher: 24Z7_CLASS_IMP_COM_2(
27 public IHasher, 25 CCrcHasher
28 public ICompressSetCoderProperties, 26 , IHasher
29 public CMyUnknownImp 27 , ICompressSetCoderProperties
30{ 28)
31 UInt32 _crc; 29 UInt32 _crc;
32 CRC_FUNC _updateFunc; 30 CRC_FUNC _updateFunc;
33 Byte mtDummy[1 << 7]; 31
34 32 Z7_CLASS_NO_COPY(CCrcHasher)
33
35 bool SetFunctions(UInt32 tSize); 34 bool SetFunctions(UInt32 tSize);
36public: 35public:
37 CCrcHasher(): _crc(CRC_INIT_VAL) { SetFunctions(0); } 36 Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field
38 37
39 MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties) 38 CCrcHasher(): _crc(CRC_INIT_VAL) { SetFunctions(0); }
40 INTERFACE_IHasher(;)
41 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
42}; 39};
43 40
44bool CCrcHasher::SetFunctions(UInt32 tSize) 41bool CCrcHasher::SetFunctions(UInt32 tSize)
45{ 42{
46 CRC_FUNC f = NULL; 43 CRC_FUNC f = NULL;
47 if (tSize == 0) f = g_CrcUpdate; 44 if (tSize == 0) f = g_CrcUpdate;
48 else if (tSize == 1) f = CrcUpdateT1; 45 // else if (tSize == 1) f = CrcUpdateT1;
49 else if (tSize == 4) f = g_CrcUpdateT4; 46 // else if (tSize == 4) f = g_CrcUpdateT4;
50 else if (tSize == 8) f = g_CrcUpdateT8; 47 else if (tSize == 8) f = g_CrcUpdateT8;
51 else if (tSize == 32) f = g_CrcUpdateT0_32; 48 else if (tSize == 32) f = g_CrcUpdateT0_32;
52 else if (tSize == 64) f = g_CrcUpdateT0_64; 49 else if (tSize == 64) f = g_CrcUpdateT0_64;
@@ -60,13 +57,13 @@ bool CCrcHasher::SetFunctions(UInt32 tSize)
60 return true; 57 return true;
61} 58}
62 59
63STDMETHODIMP CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 60Z7_COM7F_IMF(CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
64{ 61{
65 for (UInt32 i = 0; i < numProps; i++) 62 for (UInt32 i = 0; i < numProps; i++)
66 { 63 {
67 const PROPVARIANT &prop = coderProps[i];
68 if (propIDs[i] == NCoderPropID::kDefaultProp) 64 if (propIDs[i] == NCoderPropID::kDefaultProp)
69 { 65 {
66 const PROPVARIANT &prop = coderProps[i];
70 if (prop.vt != VT_UI4) 67 if (prop.vt != VT_UI4)
71 return E_INVALIDARG; 68 return E_INVALIDARG;
72 if (!SetFunctions(prop.ulVal)) 69 if (!SetFunctions(prop.ulVal))
@@ -76,20 +73,20 @@ STDMETHODIMP CCrcHasher::SetCoderProperties(const PROPID *propIDs, const PROPVAR
76 return S_OK; 73 return S_OK;
77} 74}
78 75
79STDMETHODIMP_(void) CCrcHasher::Init() throw() 76Z7_COM7F_IMF2(void, CCrcHasher::Init())
80{ 77{
81 _crc = CRC_INIT_VAL; 78 _crc = CRC_INIT_VAL;
82} 79}
83 80
84STDMETHODIMP_(void) CCrcHasher::Update(const void *data, UInt32 size) throw() 81Z7_COM7F_IMF2(void, CCrcHasher::Update(const void *data, UInt32 size))
85{ 82{
86 _crc = _updateFunc(_crc, data, size, g_CrcTable); 83 _crc = _updateFunc(_crc, data, size, g_CrcTable);
87} 84}
88 85
89STDMETHODIMP_(void) CCrcHasher::Final(Byte *digest) throw() 86Z7_COM7F_IMF2(void, CCrcHasher::Final(Byte *digest))
90{ 87{
91 UInt32 val = CRC_GET_DIGEST(_crc); 88 const UInt32 val = CRC_GET_DIGEST(_crc);
92 SetUi32(digest, val); 89 SetUi32(digest, val)
93} 90}
94 91
95REGISTER_HASHER(CCrcHasher, 0x1, "CRC32", 4) 92REGISTER_HASHER(CCrcHasher, 0x1, "CRC32", 4)
diff --git a/CPP/Common/Defs.h b/CPP/Common/Defs.h
index 9adb88c..e302f35 100644
--- a/CPP/Common/Defs.h
+++ b/CPP/Common/Defs.h
@@ -1,7 +1,7 @@
1// Common/Defs.h 1// Common/Defs.h
2 2
3#ifndef __COMMON_DEFS_H 3#ifndef ZIP7_INC_COMMON_DEFS_H
4#define __COMMON_DEFS_H 4#define ZIP7_INC_COMMON_DEFS_H
5 5
6template <class T> inline T MyMin(T a, T b) { return a < b ? a : b; } 6template <class T> inline T MyMin(T a, T b) { return a < b ? a : b; }
7template <class T> inline T MyMax(T a, T b) { return a > b ? a : b; } 7template <class T> inline T MyMax(T a, T b) { return a > b ? a : b; }
@@ -10,7 +10,7 @@ template <class T> inline int MyCompare(T a, T b)
10 { return a == b ? 0 : (a < b ? -1 : 1); } 10 { return a == b ? 0 : (a < b ? -1 : 1); }
11 11
12inline int BoolToInt(bool v) { return (v ? 1 : 0); } 12inline int BoolToInt(bool v) { return (v ? 1 : 0); }
13inline unsigned BoolToUInt(bool v) { return (v ? (unsigned)1 : (unsigned)0); } 13inline unsigned BoolToUInt(bool v) { return (v ? 1u : 0u); }
14inline bool IntToBool(int v) { return (v != 0); } 14inline bool IntToBool(int v) { return (v != 0); }
15 15
16#endif 16#endif
diff --git a/CPP/Common/DynLimBuf.cpp b/CPP/Common/DynLimBuf.cpp
index 7914104..1d92af3 100644
--- a/CPP/Common/DynLimBuf.cpp
+++ b/CPP/Common/DynLimBuf.cpp
@@ -7,7 +7,7 @@
7 7
8CDynLimBuf::CDynLimBuf(size_t limit) throw() 8CDynLimBuf::CDynLimBuf(size_t limit) throw()
9{ 9{
10 _chars = 0; 10 _chars = NULL;
11 _pos = 0; 11 _pos = 0;
12 _size = 0; 12 _size = 0;
13 _sizeLimit = limit; 13 _sizeLimit = limit;
diff --git a/CPP/Common/DynLimBuf.h b/CPP/Common/DynLimBuf.h
index e80a7e7..af22f07 100644
--- a/CPP/Common/DynLimBuf.h
+++ b/CPP/Common/DynLimBuf.h
@@ -1,7 +1,7 @@
1// Common/DynLimBuf.h 1// Common/DynLimBuf.h
2 2
3#ifndef __COMMON_DYN_LIM_BUF_H 3#ifndef ZIP7_INC_COMMON_DYN_LIM_BUF_H
4#define __COMMON_DYN_LIM_BUF_H 4#define ZIP7_INC_COMMON_DYN_LIM_BUF_H
5 5
6#include <string.h> 6#include <string.h>
7 7
diff --git a/CPP/Common/DynamicBuffer.h b/CPP/Common/DynamicBuffer.h
index f6f6b15..714be4a 100644
--- a/CPP/Common/DynamicBuffer.h
+++ b/CPP/Common/DynamicBuffer.h
@@ -1,7 +1,11 @@
1// Common/DynamicBuffer.h 1// Common/DynamicBuffer.h
2 2
3#ifndef __COMMON_DYNAMIC_BUFFER_H 3#ifndef ZIP7_INC_COMMON_DYNAMIC_BUFFER_H
4#define __COMMON_DYNAMIC_BUFFER_H 4#define ZIP7_INC_COMMON_DYNAMIC_BUFFER_H
5
6#include <string.h>
7
8#include "Common.h"
5 9
6template <class T> class CDynamicBuffer 10template <class T> class CDynamicBuffer
7{ 11{
@@ -34,7 +38,7 @@ template <class T> class CDynamicBuffer
34 } 38 }
35 39
36public: 40public:
37 CDynamicBuffer(): _items(0), _size(0), _pos(0) {} 41 CDynamicBuffer(): _items(NULL), _size(0), _pos(0) {}
38 // operator T *() { return _items; } 42 // operator T *() { return _items; }
39 operator const T *() const { return _items; } 43 operator const T *() const { return _items; }
40 ~CDynamicBuffer() { delete []_items; } 44 ~CDynamicBuffer() { delete []_items; }
diff --git a/CPP/Common/IntToString.cpp b/CPP/Common/IntToString.cpp
index c87643c..21b0680 100644
--- a/CPP/Common/IntToString.cpp
+++ b/CPP/Common/IntToString.cpp
@@ -16,7 +16,7 @@
16 16
17char * ConvertUInt32ToString(UInt32 val, char *s) throw() 17char * ConvertUInt32ToString(UInt32 val, char *s) throw()
18{ 18{
19 CONVERT_INT_TO_STR(char, 16); 19 CONVERT_INT_TO_STR(char, 16)
20} 20}
21 21
22char * ConvertUInt64ToString(UInt64 val, char *s) throw() 22char * ConvertUInt64ToString(UInt64 val, char *s) throw()
@@ -25,7 +25,7 @@ char * ConvertUInt64ToString(UInt64 val, char *s) throw()
25 { 25 {
26 return ConvertUInt32ToString((UInt32)val, s); 26 return ConvertUInt32ToString((UInt32)val, s);
27 } 27 }
28 CONVERT_INT_TO_STR(char, 24); 28 CONVERT_INT_TO_STR(char, 24)
29} 29}
30 30
31void ConvertUInt64ToOct(UInt64 val, char *s) throw() 31void ConvertUInt64ToOct(UInt64 val, char *s) throw()
@@ -102,7 +102,7 @@ void ConvertUInt32ToHex8Digits(UInt32 val, char *s) throw()
102 { 102 {
103 unsigned t = val & 0xF; 103 unsigned t = val & 0xF;
104 val >>= 4; 104 val >>= 4;
105 s[i] = GET_HEX_CHAR(t);; 105 s[i] = GET_HEX_CHAR(t);
106 } 106 }
107} 107}
108 108
@@ -121,7 +121,7 @@ void ConvertUInt32ToHex8Digits(UInt32 val, wchar_t *s)
121 121
122wchar_t * ConvertUInt32ToString(UInt32 val, wchar_t *s) throw() 122wchar_t * ConvertUInt32ToString(UInt32 val, wchar_t *s) throw()
123{ 123{
124 CONVERT_INT_TO_STR(wchar_t, 16); 124 CONVERT_INT_TO_STR(wchar_t, 16)
125} 125}
126 126
127wchar_t * ConvertUInt64ToString(UInt64 val, wchar_t *s) throw() 127wchar_t * ConvertUInt64ToString(UInt64 val, wchar_t *s) throw()
@@ -130,7 +130,7 @@ wchar_t * ConvertUInt64ToString(UInt64 val, wchar_t *s) throw()
130 { 130 {
131 return ConvertUInt32ToString((UInt32)val, s); 131 return ConvertUInt32ToString((UInt32)val, s);
132 } 132 }
133 CONVERT_INT_TO_STR(wchar_t, 24); 133 CONVERT_INT_TO_STR(wchar_t, 24)
134} 134}
135 135
136void ConvertInt64ToString(Int64 val, char *s) throw() 136void ConvertInt64ToString(Int64 val, char *s) throw()
diff --git a/CPP/Common/IntToString.h b/CPP/Common/IntToString.h
index d0a96ef..f4fc662 100644
--- a/CPP/Common/IntToString.h
+++ b/CPP/Common/IntToString.h
@@ -1,7 +1,7 @@
1// Common/IntToString.h 1// Common/IntToString.h
2 2
3#ifndef __COMMON_INT_TO_STRING_H 3#ifndef ZIP7_INC_COMMON_INT_TO_STRING_H
4#define __COMMON_INT_TO_STRING_H 4#define ZIP7_INC_COMMON_INT_TO_STRING_H
5 5
6#include "MyTypes.h" 6#include "MyTypes.h"
7 7
diff --git a/CPP/Common/Lang.cpp b/CPP/Common/Lang.cpp
index 35d3752..b0b4342 100644
--- a/CPP/Common/Lang.cpp
+++ b/CPP/Common/Lang.cpp
@@ -12,85 +12,95 @@ void CLang::Clear() throw()
12{ 12{
13 _ids.Clear(); 13 _ids.Clear();
14 _offsets.Clear(); 14 _offsets.Clear();
15 Comments.Clear();
15 delete []_text; 16 delete []_text;
16 _text = 0; 17 _text = NULL;
17} 18}
18 19
19static const char * const kLangSignature = ";!@Lang2@!UTF-8!"; 20static const char * const kLangSignature = ";!@Lang2@!UTF-8!\n";
20 21
21bool CLang::OpenFromString(const AString &s2) 22bool CLang::OpenFromString(const AString &s2)
22{ 23{
23 UString s; 24 UString su;
24 if (!ConvertUTF8ToUnicode(s2, s)) 25 if (!ConvertUTF8ToUnicode(s2, su))
25 return false; 26 return false;
26 unsigned i = 0; 27 if (su.IsEmpty())
27 if (s.IsEmpty())
28 return false; 28 return false;
29 if (s[0] == 0xFEFF) 29 const wchar_t *s = su;
30 i++; 30 const wchar_t *sLim = s + su.Len();
31 31 if (*s == 0xFEFF)
32 for (const char *p = kLangSignature;; i++) 32 s++;
33 for (const char *p = kLangSignature;; s++)
33 { 34 {
34 Byte c = (Byte)(*p++); 35 const Byte c = (Byte)(*p++);
35 if (c == 0) 36 if (c == 0)
36 break; 37 break;
37 if (s[i] != c) 38 if (*s != c)
38 return false; 39 return false;
39 } 40 }
40 41
41 _text = new wchar_t[s.Len() - i + 1]; 42 wchar_t *text = new wchar_t[(size_t)(sLim - s) + 1];
42 wchar_t *text = _text; 43 _text = text;
43 44
44 Int32 id = -100; 45 UString comment;
45 UInt32 pos = 0; 46 Int32 id = -1024;
47 unsigned pos = 0;
46 48
47 while (i < s.Len()) 49 while (s != sLim)
48 { 50 {
49 unsigned start = pos; 51 const unsigned start = pos;
50 do 52 do
51 { 53 {
52 wchar_t c = s[i++]; 54 wchar_t c = *s++;
53 if (c == '\n') 55 if (c == '\n')
54 break; 56 break;
55 if (c == '\\') 57 if (c == '\\')
56 { 58 {
57 if (i == s.Len()) 59 if (s == sLim)
58 return false; 60 return false;
59 c = s[i++]; 61 c = *s++;
60 switch (c) 62 switch (c)
61 { 63 {
62 case '\n': return false; 64 case '\n': return false;
63 case 'n': c = '\n'; break; 65 case 'n': c = '\n'; break;
64 case 't': c = '\t'; break; 66 case 't': c = '\t'; break;
65 case '\\': c = '\\'; break; 67 case '\\': /* c = '\\'; */ break;
66 default: text[pos++] = L'\\'; break; 68 default: text[pos++] = L'\\'; break;
67 } 69 }
68 } 70 }
69 text[pos++] = c; 71 text[pos++] = c;
70 } 72 }
71 while (i < s.Len()); 73 while (s != sLim);
72 74
73 { 75 {
74 unsigned j = start; 76 unsigned j = start;
75 for (; j < pos; j++) 77 for (; j < pos; j++)
76 if (text[j] != ' ') 78 if (text[j] != ' ' && text[j] != '\t')
77 break; 79 break;
78 if (j == pos) 80 if (j == pos)
79 { 81 {
80 id++; 82 id++;
83 pos = start;
81 continue; 84 continue;
82 } 85 }
83 } 86 }
87
88 // start != pos
89 text[pos++] = 0;
90
84 if (text[start] == ';') 91 if (text[start] == ';')
85 { 92 {
86 pos = start; 93 comment = text + start;
94 comment.TrimRight();
95 if (comment.Len() != 1)
96 Comments.Add(comment);
87 id++; 97 id++;
98 pos = start;
88 continue; 99 continue;
89 } 100 }
90 101
91 text[pos++] = 0;
92 const wchar_t *end; 102 const wchar_t *end;
93 UInt32 id32 = ConvertStringToUInt32(text + start, &end); 103 const UInt32 id32 = ConvertStringToUInt32(text + start, &end);
94 if (*end == 0) 104 if (*end == 0)
95 { 105 {
96 if (id32 > ((UInt32)1 << 30) || (Int32)id32 < id) 106 if (id32 > ((UInt32)1 << 30) || (Int32)id32 < id)
@@ -134,7 +144,7 @@ bool CLang::Open(CFSTR fileName, const char *id)
134 char *p2 = p; 144 char *p2 = p;
135 for (unsigned i = 0; i < len; i++) 145 for (unsigned i = 0; i < len; i++)
136 { 146 {
137 char c = p[i]; 147 const char c = p[i];
138 if (c == 0) 148 if (c == 0)
139 break; 149 break;
140 if (c != 0x0D) 150 if (c != 0x0D)
@@ -156,7 +166,7 @@ bool CLang::Open(CFSTR fileName, const char *id)
156 166
157const wchar_t *CLang::Get(UInt32 id) const throw() 167const wchar_t *CLang::Get(UInt32 id) const throw()
158{ 168{
159 int index = _ids.FindInSorted(id); 169 const int index = _ids.FindInSorted(id);
160 if (index < 0) 170 if (index < 0)
161 return NULL; 171 return NULL;
162 return _text + (size_t)_offsets[(unsigned)index]; 172 return _text + (size_t)_offsets[(unsigned)index];
diff --git a/CPP/Common/Lang.h b/CPP/Common/Lang.h
index cc66677..76d5418 100644
--- a/CPP/Common/Lang.h
+++ b/CPP/Common/Lang.h
@@ -1,23 +1,30 @@
1// Common/Lang.h 1// Common/Lang.h
2 2
3#ifndef __COMMON_LANG_H 3#ifndef ZIP7_INC_COMMON_LANG_H
4#define __COMMON_LANG_H 4#define ZIP7_INC_COMMON_LANG_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7 7
8class CLang 8class CLang
9{ 9{
10 wchar_t *_text; 10 wchar_t *_text;
11 CRecordVector<UInt32> _ids;
12 CRecordVector<UInt32> _offsets;
13 11
14 bool OpenFromString(const AString &s); 12 bool OpenFromString(const AString &s);
15public: 13public:
16 CLang(): _text(0) {} 14 CRecordVector<UInt32> _ids;
15 CRecordVector<UInt32> _offsets;
16 UStringVector Comments;
17
18 CLang(): _text(NULL) {}
17 ~CLang() { Clear(); } 19 ~CLang() { Clear(); }
18 bool Open(CFSTR fileName, const char *id); 20 bool Open(CFSTR fileName, const char *id);
19 void Clear() throw(); 21 void Clear() throw();
22 bool IsEmpty() const { return _ids.IsEmpty(); }
20 const wchar_t *Get(UInt32 id) const throw(); 23 const wchar_t *Get(UInt32 id) const throw();
24 const wchar_t *Get_by_index(unsigned index) const throw()
25 {
26 return _text + (size_t)_offsets[index];
27 }
21}; 28};
22 29
23#endif 30#endif
diff --git a/CPP/Common/ListFileUtils.cpp b/CPP/Common/ListFileUtils.cpp
index b361b37..e43dbc9 100644
--- a/CPP/Common/ListFileUtils.cpp
+++ b/CPP/Common/ListFileUtils.cpp
@@ -66,7 +66,7 @@ bool ReadNamesFromListFile2(CFSTR fileName, UStringVector &strings, UINT codePag
66 if (fileSize >= ((UInt32)1 << 31) - 32) 66 if (fileSize >= ((UInt32)1 << 31) - 32)
67 return false; 67 return false;
68 UString u; 68 UString u;
69 if (codePage == MY__CP_UTF16 || codePage == MY__CP_UTF16BE) 69 if (codePage == Z7_WIN_CP_UTF16 || codePage == Z7_WIN_CP_UTF16BE)
70 { 70 {
71 if ((fileSize & 1) != 0) 71 if ((fileSize & 1) != 0)
72 return false; 72 return false;
@@ -78,7 +78,7 @@ bool ReadNamesFromListFile2(CFSTR fileName, UStringVector &strings, UINT codePag
78 file.Close(); 78 file.Close();
79 const unsigned num = (unsigned)fileSize / 2; 79 const unsigned num = (unsigned)fileSize / 2;
80 wchar_t *p = u.GetBuf(num); 80 wchar_t *p = u.GetBuf(num);
81 if (codePage == MY__CP_UTF16) 81 if (codePage == Z7_WIN_CP_UTF16)
82 for (unsigned i = 0; i < num; i++) 82 for (unsigned i = 0; i < num; i++)
83 { 83 {
84 wchar_t c = GetUi16(buf + (size_t)i * 2); 84 wchar_t c = GetUi16(buf + (size_t)i * 2);
diff --git a/CPP/Common/ListFileUtils.h b/CPP/Common/ListFileUtils.h
index a91e4b1..d43cc37 100644
--- a/CPP/Common/ListFileUtils.h
+++ b/CPP/Common/ListFileUtils.h
@@ -1,13 +1,13 @@
1// Common/ListFileUtils.h 1// Common/ListFileUtils.h
2 2
3#ifndef __COMMON_LIST_FILE_UTILS_H 3#ifndef ZIP7_INC_COMMON_LIST_FILE_UTILS_H
4#define __COMMON_LIST_FILE_UTILS_H 4#define ZIP7_INC_COMMON_LIST_FILE_UTILS_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7#include "MyTypes.h" 7#include "MyTypes.h"
8 8
9#define MY__CP_UTF16 1200 9#define Z7_WIN_CP_UTF16 1200
10#define MY__CP_UTF16BE 1201 10#define Z7_WIN_CP_UTF16BE 1201
11 11
12// bool ReadNamesFromListFile(CFSTR fileName, UStringVector &strings, UINT codePage = CP_OEMCP); 12// bool ReadNamesFromListFile(CFSTR fileName, UStringVector &strings, UINT codePage = CP_OEMCP);
13 13
diff --git a/CPP/Common/MyBuffer.h b/CPP/Common/MyBuffer.h
index 18ab6fa..bc829f4 100644
--- a/CPP/Common/MyBuffer.h
+++ b/CPP/Common/MyBuffer.h
@@ -1,13 +1,15 @@
1// Common/MyBuffer.h 1// Common/MyBuffer.h
2 2
3#ifndef __COMMON_MY_BUFFER_H 3#ifndef ZIP7_INC_COMMON_MY_BUFFER_H
4#define __COMMON_MY_BUFFER_H 4#define ZIP7_INC_COMMON_MY_BUFFER_H
5
6#include <string.h>
5 7
6#include "Defs.h" 8#include "Defs.h"
7#include "MyTypes.h" 9#include "MyTypes.h"
8 10
9/* 7-Zip now uses CBuffer only as CByteBuffer. 11/* 7-Zip now uses CBuffer only as CByteBuffer.
10 So there is no need to use MY_ARRAY_NEW macro in CBuffer code. */ 12 So there is no need to use Z7_ARRAY_NEW macro in CBuffer code. */
11 13
12template <class T> class CBuffer 14template <class T> class CBuffer
13{ 15{
@@ -20,16 +22,23 @@ public:
20 if (_items) 22 if (_items)
21 { 23 {
22 delete []_items; 24 delete []_items;
23 _items = 0; 25 _items = NULL;
24 } 26 }
25 _size = 0; 27 _size = 0;
26 } 28 }
27 29
28 CBuffer(): _items(0), _size(0) {}; 30 CBuffer(): _items(NULL), _size(0) {}
29 CBuffer(size_t size): _items(0), _size(0) { _items = new T[size]; _size = size; } 31 CBuffer(size_t size): _items(NULL), _size(0)
30 CBuffer(const CBuffer &buffer): _items(0), _size(0) 32 {
33 if (size != 0)
34 {
35 _items = new T[size];
36 _size = size;
37 }
38 }
39 CBuffer(const CBuffer &buffer): _items(NULL), _size(0)
31 { 40 {
32 size_t size = buffer._size; 41 const size_t size = buffer._size;
33 if (size != 0) 42 if (size != 0)
34 { 43 {
35 _items = new T[size]; 44 _items = new T[size];
@@ -136,7 +145,7 @@ typedef CBuffer<unsigned char> CByteBuffer;
136 145
137class CByteBuffer_Wipe: public CByteBuffer 146class CByteBuffer_Wipe: public CByteBuffer
138{ 147{
139 CLASS_NO_COPY(CByteBuffer_Wipe) 148 Z7_CLASS_NO_COPY(CByteBuffer_Wipe)
140public: 149public:
141 // CByteBuffer_Wipe(): CBuffer<unsigned char>() {} 150 // CByteBuffer_Wipe(): CBuffer<unsigned char>() {}
142 CByteBuffer_Wipe(size_t size): CBuffer<unsigned char>(size) {} 151 CByteBuffer_Wipe(size_t size): CBuffer<unsigned char>(size) {}
@@ -157,17 +166,17 @@ public:
157 void Free() 166 void Free()
158 { 167 {
159 delete []_items; 168 delete []_items;
160 _items = 0; 169 _items = NULL;
161 } 170 }
162 CObjArray(size_t size): _items(0) 171 CObjArray(size_t size): _items(NULL)
163 { 172 {
164 if (size != 0) 173 if (size != 0)
165 { 174 {
166 MY_ARRAY_NEW(_items, T, size) 175 Z7_ARRAY_NEW(_items, T, size)
167 // _items = new T[size]; 176 // _items = new T[size];
168 } 177 }
169 } 178 }
170 CObjArray(): _items(0) {}; 179 CObjArray(): _items(NULL) {}
171 ~CObjArray() { delete []_items; } 180 ~CObjArray() { delete []_items; }
172 181
173 operator T *() { return _items; } 182 operator T *() { return _items; }
@@ -176,8 +185,8 @@ public:
176 void Alloc(size_t newSize) 185 void Alloc(size_t newSize)
177 { 186 {
178 delete []_items; 187 delete []_items;
179 _items = 0; 188 _items = NULL;
180 MY_ARRAY_NEW(_items, T, newSize) 189 Z7_ARRAY_NEW(_items, T, newSize)
181 // _items = new T[newSize]; 190 // _items = new T[newSize];
182 } 191 }
183}; 192};
@@ -201,12 +210,12 @@ public:
201 void Free() 210 void Free()
202 { 211 {
203 delete []_items; 212 delete []_items;
204 _items = 0; 213 _items = NULL;
205 _size = 0; 214 _size = 0;
206 } 215 }
207 CObjArray2(): _items(0), _size(0) {}; 216 CObjArray2(): _items(NULL), _size(0) {}
208 /* 217 /*
209 CObjArray2(const CObjArray2 &buffer): _items(0), _size(0) 218 CObjArray2(const CObjArray2 &buffer): _items(NULL), _size(0)
210 { 219 {
211 size_t newSize = buffer._size; 220 size_t newSize = buffer._size;
212 if (newSize != 0) 221 if (newSize != 0)
@@ -221,7 +230,7 @@ public:
221 } 230 }
222 */ 231 */
223 /* 232 /*
224 CObjArray2(size_t size): _items(0), _size(0) 233 CObjArray2(size_t size): _items(NULL), _size(0)
225 { 234 {
226 if (size != 0) 235 if (size != 0)
227 { 236 {
@@ -247,7 +256,7 @@ public:
247 T *newBuffer = NULL; 256 T *newBuffer = NULL;
248 if (size != 0) 257 if (size != 0)
249 { 258 {
250 MY_ARRAY_NEW(newBuffer, T, size) 259 Z7_ARRAY_NEW(newBuffer, T, size)
251 // newBuffer = new T[size]; 260 // newBuffer = new T[size];
252 } 261 }
253 delete []_items; 262 delete []_items;
diff --git a/CPP/Common/MyBuffer2.h b/CPP/Common/MyBuffer2.h
index 372d478..23394f8 100644
--- a/CPP/Common/MyBuffer2.h
+++ b/CPP/Common/MyBuffer2.h
@@ -1,7 +1,7 @@
1// Common/MyBuffer2.h 1// Common/MyBuffer2.h
2 2
3#ifndef __COMMON_MY_BUFFER2_H 3#ifndef ZIP7_INC_COMMON_MY_BUFFER2_H
4#define __COMMON_MY_BUFFER2_H 4#define ZIP7_INC_COMMON_MY_BUFFER2_H
5 5
6#include "../../C/Alloc.h" 6#include "../../C/Alloc.h"
7 7
@@ -12,7 +12,7 @@ class CMidBuffer
12 Byte *_data; 12 Byte *_data;
13 size_t _size; 13 size_t _size;
14 14
15 CLASS_NO_COPY(CMidBuffer) 15 Z7_CLASS_NO_COPY(CMidBuffer)
16 16
17public: 17public:
18 CMidBuffer(): _data(NULL), _size(0) {} 18 CMidBuffer(): _data(NULL), _size(0) {}
@@ -56,12 +56,37 @@ public:
56}; 56};
57 57
58 58
59class CAlignedBuffer1
60{
61 Byte *_data;
62
63 Z7_CLASS_NO_COPY(CAlignedBuffer1)
64
65public:
66 ~CAlignedBuffer1()
67 {
68 ISzAlloc_Free(&g_AlignedAlloc, _data);
69 }
70
71 CAlignedBuffer1(size_t size)
72 {
73 _data = NULL;
74 _data = (Byte *)ISzAlloc_Alloc(&g_AlignedAlloc, size);
75 if (!_data)
76 throw 1;
77 }
78
79 operator Byte *() { return _data; }
80 operator const Byte *() const { return _data; }
81};
82
83
59class CAlignedBuffer 84class CAlignedBuffer
60{ 85{
61 Byte *_data; 86 Byte *_data;
62 size_t _size; 87 size_t _size;
63 88
64 CLASS_NO_COPY(CAlignedBuffer) 89 Z7_CLASS_NO_COPY(CAlignedBuffer)
65 90
66public: 91public:
67 CAlignedBuffer(): _data(NULL), _size(0) {} 92 CAlignedBuffer(): _data(NULL), _size(0) {}
diff --git a/CPP/Common/MyCom.h b/CPP/Common/MyCom.h
index ff54278..65c4330 100644
--- a/CPP/Common/MyCom.h
+++ b/CPP/Common/MyCom.h
@@ -1,15 +1,11 @@
1// MyCom.h 1// MyCom.h
2 2
3#ifndef __MY_COM_H 3#ifndef ZIP7_INC_MY_COM_H
4#define __MY_COM_H 4#define ZIP7_INC_MY_COM_H
5 5
6#include "MyWindows.h" 6#include "MyWindows.h"
7#include "MyTypes.h" 7#include "MyTypes.h"
8 8
9#ifndef RINOK
10#define RINOK(x) { HRESULT __result_ = (x); if (__result_ != S_OK) return __result_; }
11#endif
12
13template <class T> 9template <class T>
14class CMyComPtr 10class CMyComPtr
15{ 11{
@@ -72,6 +68,10 @@ public:
72 } 68 }
73}; 69};
74 70
71#define Z7_DECL_CMyComPtr_QI_FROM(i, v, unk) \
72 CMyComPtr<i> v; (unk)->QueryInterface(IID_ ## i, (void **)&v);
73
74
75////////////////////////////////////////////////////////// 75//////////////////////////////////////////////////////////
76 76
77inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) 77inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr)
@@ -83,7 +83,7 @@ inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr)
83class CMyComBSTR 83class CMyComBSTR
84{ 84{
85 BSTR m_str; 85 BSTR m_str;
86 CLASS_NO_COPY(CMyComBSTR) 86 Z7_CLASS_NO_COPY(CMyComBSTR)
87public: 87public:
88 CMyComBSTR(): m_str(NULL) {} 88 CMyComBSTR(): m_str(NULL) {}
89 ~CMyComBSTR() { ::SysFreeString(m_str); } 89 ~CMyComBSTR() { ::SysFreeString(m_str); }
@@ -174,7 +174,7 @@ private:
174 174
175class CMyComBSTR_Wipe: public CMyComBSTR 175class CMyComBSTR_Wipe: public CMyComBSTR
176{ 176{
177 CLASS_NO_COPY(CMyComBSTR_Wipe) 177 Z7_CLASS_NO_COPY(CMyComBSTR_Wipe)
178public: 178public:
179 CMyComBSTR_Wipe(): CMyComBSTR() {} 179 CMyComBSTR_Wipe(): CMyComBSTR() {}
180 ~CMyComBSTR_Wipe() { Wipe_and_Free(); } 180 ~CMyComBSTR_Wipe() { Wipe_and_Free(); }
@@ -185,123 +185,325 @@ public:
185/* 185/*
186 If CMyUnknownImp doesn't use virtual destructor, the code size is smaller. 186 If CMyUnknownImp doesn't use virtual destructor, the code size is smaller.
187 But if some class_1 derived from CMyUnknownImp 187 But if some class_1 derived from CMyUnknownImp
188 uses MY_ADDREF_RELEASE and IUnknown::Release() 188 uses Z7_COM_ADDREF_RELEASE and IUnknown::Release()
189 and some another class_2 is derived from class_1, 189 and some another class_2 is derived from class_1,
190 then class_1 must use virtual destructor: 190 then class_1 must use virtual destructor:
191 virtual ~class_1(); 191 virtual ~class_1();
192 In that case, class_1::Release() calls correct destructor of class_2. 192 In that case, class_1::Release() calls correct destructor of class_2.
193 193 We can use virtual ~CMyUnknownImp() to disable warning
194 We use virtual ~CMyUnknownImp() to disable warning
195 "class has virtual functions, but destructor is not virtual". 194 "class has virtual functions, but destructor is not virtual".
196 195 Also we can use virtual ~IUnknown() {} in MyWindows.h
197 also we can use virtual ~IUnknown() {} in MyWindows.h
198*/ 196*/
199 197
200class CMyUnknownImp 198class CMyUnknownImp
201{ 199{
202 CLASS_NO_COPY(CMyUnknownImp) 200 Z7_CLASS_NO_COPY(CMyUnknownImp)
203public: 201protected:
204 ULONG __m_RefCount; 202 ULONG _m_RefCount;
205 CMyUnknownImp(): __m_RefCount(0) {} 203 CMyUnknownImp(): _m_RefCount(0) {}
206 204
207 #ifdef _WIN32 205 #ifdef _WIN32
208 #if defined(__GNUC__) || defined(__clang__) 206 #if defined(__GNUC__) || defined(__clang__)
209 virtual // to disable GCC/CLANG varnings 207 // virtual ~CMyUnknownImp() {} // to disable GCC/CLANG varnings
210 #endif 208 #endif
211 #endif 209 #endif
212 ~CMyUnknownImp() {}
213}; 210};
214 211
215 212
216 213
217#define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \ 214#define Z7_COM_QI_BEGIN \
218(REFGUID iid, void **outObject) throw() { *outObject = NULL; 215 private: STDMETHOD(QueryInterface) (REFGUID iid, void **outObject) throw() Z7_override Z7_final \
216 { *outObject = NULL;
217
218#define Z7_COM_QI_ENTRY(i) \
219 else if (iid == IID_ ## i) \
220 { i *ti = this; *outObject = ti; }
221// { *outObject = (void *)(i *)this; }
219 222
220#define MY_QUERYINTERFACE_ENTRY(i) else if (iid == IID_ ## i) \ 223#define Z7_COM_QI_ENTRY_UNKNOWN_0 \
221 { *outObject = (void *)(i *)this; } 224 if (iid == IID_IUnknown) \
225 { IUnknown *tu = this; *outObject = tu; }
222 226
223#define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ 227#define Z7_COM_QI_ENTRY_UNKNOWN(i) \
224 { *outObject = (void *)(IUnknown *)(i *)this; } 228 if (iid == IID_IUnknown) \
229 { i *ti = this; IUnknown *tu = ti; *outObject = tu; }
230// { *outObject = (void *)(IUnknown *)(i *)this; }
225 231
226#define MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ 232#define Z7_COM_QI_BEGIN2(i) \
227 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ 233 Z7_COM_QI_BEGIN \
228 MY_QUERYINTERFACE_ENTRY(i) 234 Z7_COM_QI_ENTRY_UNKNOWN(i) \
235 Z7_COM_QI_ENTRY(i)
229 236
230#define MY_QUERYINTERFACE_END else return E_NOINTERFACE; ++__m_RefCount; /* AddRef(); */ return S_OK; } 237#define Z7_COM_QI_END \
238 else return E_NOINTERFACE; \
239 ++_m_RefCount; /* AddRef(); */ return S_OK; }
231 240
232#define MY_ADDREF_RELEASE \ 241#define Z7_COM_ADDREF_RELEASE \
233STDMETHOD_(ULONG, AddRef)() throw() { return ++__m_RefCount; } \ 242 private: \
234STDMETHOD_(ULONG, Release)() { if (--__m_RefCount != 0) return __m_RefCount; \ 243 STDMETHOD_(ULONG, AddRef)() throw() Z7_override Z7_final \
235 delete this; return 0; } 244 { return ++_m_RefCount; } \
245 STDMETHOD_(ULONG, Release)() throw() Z7_override Z7_final \
246 { if (--_m_RefCount != 0) return _m_RefCount; delete this; return 0; } \
236 247
237#define MY_UNKNOWN_IMP_SPEC(i) \ 248#define Z7_COM_UNKNOWN_IMP_SPEC(i) \
238 MY_QUERYINTERFACE_BEGIN \ 249 Z7_COM_QI_BEGIN \
239 i \ 250 i \
240 MY_QUERYINTERFACE_END \ 251 Z7_COM_QI_END \
241 MY_ADDREF_RELEASE 252 Z7_COM_ADDREF_RELEASE
242 253
243 254
244#define MY_UNKNOWN_IMP MY_QUERYINTERFACE_BEGIN \ 255#define Z7_COM_UNKNOWN_IMP_0 \
245 MY_QUERYINTERFACE_ENTRY_UNKNOWN(IUnknown) \ 256 Z7_COM_QI_BEGIN \
246 MY_QUERYINTERFACE_END \ 257 Z7_COM_QI_ENTRY_UNKNOWN_0 \
247 MY_ADDREF_RELEASE 258 Z7_COM_QI_END \
259 Z7_COM_ADDREF_RELEASE
248 260
249#define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \ 261#define Z7_COM_UNKNOWN_IMP_1(i) \
250 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ 262 Z7_COM_UNKNOWN_IMP_SPEC( \
251 MY_QUERYINTERFACE_ENTRY(i) \ 263 Z7_COM_QI_ENTRY_UNKNOWN(i) \
264 Z7_COM_QI_ENTRY(i) \
252 ) 265 )
253 266
254#define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \ 267#define Z7_COM_UNKNOWN_IMP_2(i1, i2) \
255 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 268 Z7_COM_UNKNOWN_IMP_SPEC( \
256 MY_QUERYINTERFACE_ENTRY(i1) \ 269 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
257 MY_QUERYINTERFACE_ENTRY(i2) \ 270 Z7_COM_QI_ENTRY(i1) \
271 Z7_COM_QI_ENTRY(i2) \
258 ) 272 )
259 273
260#define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \ 274#define Z7_COM_UNKNOWN_IMP_3(i1, i2, i3) \
261 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 275 Z7_COM_UNKNOWN_IMP_SPEC( \
262 MY_QUERYINTERFACE_ENTRY(i1) \ 276 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
263 MY_QUERYINTERFACE_ENTRY(i2) \ 277 Z7_COM_QI_ENTRY(i1) \
264 MY_QUERYINTERFACE_ENTRY(i3) \ 278 Z7_COM_QI_ENTRY(i2) \
279 Z7_COM_QI_ENTRY(i3) \
265 ) 280 )
266 281
267#define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \ 282#define Z7_COM_UNKNOWN_IMP_4(i1, i2, i3, i4) \
268 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 283 Z7_COM_UNKNOWN_IMP_SPEC( \
269 MY_QUERYINTERFACE_ENTRY(i1) \ 284 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
270 MY_QUERYINTERFACE_ENTRY(i2) \ 285 Z7_COM_QI_ENTRY(i1) \
271 MY_QUERYINTERFACE_ENTRY(i3) \ 286 Z7_COM_QI_ENTRY(i2) \
272 MY_QUERYINTERFACE_ENTRY(i4) \ 287 Z7_COM_QI_ENTRY(i3) \
288 Z7_COM_QI_ENTRY(i4) \
273 ) 289 )
274 290
275#define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \ 291#define Z7_COM_UNKNOWN_IMP_5(i1, i2, i3, i4, i5) \
276 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 292 Z7_COM_UNKNOWN_IMP_SPEC( \
277 MY_QUERYINTERFACE_ENTRY(i1) \ 293 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
278 MY_QUERYINTERFACE_ENTRY(i2) \ 294 Z7_COM_QI_ENTRY(i1) \
279 MY_QUERYINTERFACE_ENTRY(i3) \ 295 Z7_COM_QI_ENTRY(i2) \
280 MY_QUERYINTERFACE_ENTRY(i4) \ 296 Z7_COM_QI_ENTRY(i3) \
281 MY_QUERYINTERFACE_ENTRY(i5) \ 297 Z7_COM_QI_ENTRY(i4) \
298 Z7_COM_QI_ENTRY(i5) \
282 ) 299 )
283 300
284#define MY_UNKNOWN_IMP6(i1, i2, i3, i4, i5, i6) MY_UNKNOWN_IMP_SPEC( \ 301#define Z7_COM_UNKNOWN_IMP_6(i1, i2, i3, i4, i5, i6) \
285 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 302 Z7_COM_UNKNOWN_IMP_SPEC( \
286 MY_QUERYINTERFACE_ENTRY(i1) \ 303 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
287 MY_QUERYINTERFACE_ENTRY(i2) \ 304 Z7_COM_QI_ENTRY(i1) \
288 MY_QUERYINTERFACE_ENTRY(i3) \ 305 Z7_COM_QI_ENTRY(i2) \
289 MY_QUERYINTERFACE_ENTRY(i4) \ 306 Z7_COM_QI_ENTRY(i3) \
290 MY_QUERYINTERFACE_ENTRY(i5) \ 307 Z7_COM_QI_ENTRY(i4) \
291 MY_QUERYINTERFACE_ENTRY(i6) \ 308 Z7_COM_QI_ENTRY(i5) \
309 Z7_COM_QI_ENTRY(i6) \
292 ) 310 )
293 311
294#define MY_UNKNOWN_IMP7(i1, i2, i3, i4, i5, i6, i7) MY_UNKNOWN_IMP_SPEC( \ 312#define Z7_COM_UNKNOWN_IMP_7(i1, i2, i3, i4, i5, i6, i7) \
295 MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ 313 Z7_COM_UNKNOWN_IMP_SPEC( \
296 MY_QUERYINTERFACE_ENTRY(i1) \ 314 Z7_COM_QI_ENTRY_UNKNOWN(i1) \
297 MY_QUERYINTERFACE_ENTRY(i2) \ 315 Z7_COM_QI_ENTRY(i1) \
298 MY_QUERYINTERFACE_ENTRY(i3) \ 316 Z7_COM_QI_ENTRY(i2) \
299 MY_QUERYINTERFACE_ENTRY(i4) \ 317 Z7_COM_QI_ENTRY(i3) \
300 MY_QUERYINTERFACE_ENTRY(i5) \ 318 Z7_COM_QI_ENTRY(i4) \
301 MY_QUERYINTERFACE_ENTRY(i6) \ 319 Z7_COM_QI_ENTRY(i5) \
302 MY_QUERYINTERFACE_ENTRY(i7) \ 320 Z7_COM_QI_ENTRY(i6) \
321 Z7_COM_QI_ENTRY(i7) \
303 ) 322 )
304 323
305const HRESULT k_My_HRESULT_WritingWasCut = 0x20000010; 324
325#define Z7_IFACES_IMP_UNK_1(i1) \
326 Z7_COM_UNKNOWN_IMP_1(i1) \
327 Z7_IFACE_COM7_IMP(i1) \
328
329#define Z7_IFACES_IMP_UNK_2(i1, i2) \
330 Z7_COM_UNKNOWN_IMP_2(i1, i2) \
331 Z7_IFACE_COM7_IMP(i1) \
332 Z7_IFACE_COM7_IMP(i2) \
333
334#define Z7_IFACES_IMP_UNK_3(i1, i2, i3) \
335 Z7_COM_UNKNOWN_IMP_3(i1, i2, i3) \
336 Z7_IFACE_COM7_IMP(i1) \
337 Z7_IFACE_COM7_IMP(i2) \
338 Z7_IFACE_COM7_IMP(i3) \
339
340#define Z7_IFACES_IMP_UNK_4(i1, i2, i3, i4) \
341 Z7_COM_UNKNOWN_IMP_4(i1, i2, i3, i4) \
342 Z7_IFACE_COM7_IMP(i1) \
343 Z7_IFACE_COM7_IMP(i2) \
344 Z7_IFACE_COM7_IMP(i3) \
345 Z7_IFACE_COM7_IMP(i4) \
346
347#define Z7_IFACES_IMP_UNK_5(i1, i2, i3, i4, i5) \
348 Z7_COM_UNKNOWN_IMP_5(i1, i2, i3, i4, i5) \
349 Z7_IFACE_COM7_IMP(i1) \
350 Z7_IFACE_COM7_IMP(i2) \
351 Z7_IFACE_COM7_IMP(i3) \
352 Z7_IFACE_COM7_IMP(i4) \
353 Z7_IFACE_COM7_IMP(i5) \
354
355#define Z7_IFACES_IMP_UNK_6(i1, i2, i3, i4, i5, i6) \
356 Z7_COM_UNKNOWN_IMP_6(i1, i2, i3, i4, i5, i6) \
357 Z7_IFACE_COM7_IMP(i1) \
358 Z7_IFACE_COM7_IMP(i2) \
359 Z7_IFACE_COM7_IMP(i3) \
360 Z7_IFACE_COM7_IMP(i4) \
361 Z7_IFACE_COM7_IMP(i5) \
362 Z7_IFACE_COM7_IMP(i6) \
363
364
365#define Z7_CLASS_IMP_COM_0(c) \
366 Z7_class_final(c) : \
367 public IUnknown, \
368 public CMyUnknownImp { \
369 Z7_COM_UNKNOWN_IMP_0 \
370 private:
371
372#define Z7_CLASS_IMP_COM_1(c, i1) \
373 Z7_class_final(c) : \
374 public i1, \
375 public CMyUnknownImp { \
376 Z7_IFACES_IMP_UNK_1(i1) \
377 private:
378
379#define Z7_CLASS_IMP_COM_2(c, i1, i2) \
380 Z7_class_final(c) : \
381 public i1, \
382 public i2, \
383 public CMyUnknownImp { \
384 Z7_IFACES_IMP_UNK_2(i1, i2) \
385 private:
386
387#define Z7_CLASS_IMP_COM_3(c, i1, i2, i3) \
388 Z7_class_final(c) : \
389 public i1, \
390 public i2, \
391 public i3, \
392 public CMyUnknownImp { \
393 Z7_IFACES_IMP_UNK_3(i1, i2, i3) \
394 private:
395
396#define Z7_CLASS_IMP_COM_4(c, i1, i2, i3, i4) \
397 Z7_class_final(c) : \
398 public i1, \
399 public i2, \
400 public i3, \
401 public i4, \
402 public CMyUnknownImp { \
403 Z7_IFACES_IMP_UNK_4(i1, i2, i3, i4) \
404 private:
405
406#define Z7_CLASS_IMP_COM_5(c, i1, i2, i3, i4, i5) \
407 Z7_class_final(c) : \
408 public i1, \
409 public i2, \
410 public i3, \
411 public i4, \
412 public i5, \
413 public CMyUnknownImp { \
414 Z7_IFACES_IMP_UNK_5(i1, i2, i3, i4, i5) \
415 private:
416
417#define Z7_CLASS_IMP_COM_6(c, i1, i2, i3, i4, i5, i6) \
418 Z7_class_final(c) : \
419 public i1, \
420 public i2, \
421 public i3, \
422 public i4, \
423 public i5, \
424 public i6, \
425 public CMyUnknownImp { \
426 Z7_IFACES_IMP_UNK_6(i1, i2, i3, i4, i5, i6) \
427 private:
428
429
430/*
431#define Z7_CLASS_IMP_NOQIB_0(c) \
432 Z7_class_final(c) : \
433 public IUnknown, \
434 public CMyUnknownImp { \
435 Z7_COM_UNKNOWN_IMP_0 \
436 private:
437*/
438
439#define Z7_CLASS_IMP_NOQIB_1(c, i1) \
440 Z7_class_final(c) : \
441 public i1, \
442 public CMyUnknownImp { \
443 Z7_COM_UNKNOWN_IMP_0 \
444 Z7_IFACE_COM7_IMP(i1) \
445 private:
446
447#define Z7_CLASS_IMP_NOQIB_2(c, i1, i2) \
448 Z7_class_final(c) : \
449 public i1, \
450 public i2, \
451 public CMyUnknownImp { \
452 Z7_COM_UNKNOWN_IMP_1(i2) \
453 Z7_IFACE_COM7_IMP(i1) \
454 Z7_IFACE_COM7_IMP(i2) \
455 private:
456
457#define Z7_CLASS_IMP_NOQIB_3(c, i1, i2, i3) \
458 Z7_class_final(c) : \
459 public i1, \
460 public i2, \
461 public i3, \
462 public CMyUnknownImp { \
463 Z7_COM_UNKNOWN_IMP_2(i2, i3) \
464 Z7_IFACE_COM7_IMP(i1) \
465 Z7_IFACE_COM7_IMP(i2) \
466 Z7_IFACE_COM7_IMP(i3) \
467 private:
468
469#define Z7_CLASS_IMP_NOQIB_4(c, i1, i2, i3, i4) \
470 Z7_class_final(c) : \
471 public i1, \
472 public i2, \
473 public i3, \
474 public i4, \
475 public CMyUnknownImp { \
476 Z7_COM_UNKNOWN_IMP_3(i2, i3, i4) \
477 Z7_IFACE_COM7_IMP(i1) \
478 Z7_IFACE_COM7_IMP(i2) \
479 Z7_IFACE_COM7_IMP(i3) \
480 Z7_IFACE_COM7_IMP(i4) \
481
482/*
483#define Z7_CLASS_IMP_NOQIB_5(c, i1, i2, i3, i4, i5) \
484 Z7_class_final(c) : \
485 public i1, \
486 public i2, \
487 public i3, \
488 public i4, \
489 public i5, \
490 public CMyUnknownImp { \
491 Z7_COM_UNKNOWN_IMP_4(i2, i3, i4, i5) \
492 Z7_IFACE_COM7_IMP(i1) \
493 Z7_IFACE_COM7_IMP(i2) \
494 Z7_IFACE_COM7_IMP(i3) \
495 Z7_IFACE_COM7_IMP(i4) \
496 Z7_IFACE_COM7_IMP(i5) \
497*/
498
499
500#define Z7_CLASS_IMP_IInStream(c) \
501 class c Z7_final : \
502 public IInStream, \
503 public CMyUnknownImp { \
504 Z7_IFACES_IMP_UNK_2(ISequentialInStream, IInStream) \
505
506
507#define k_My_HRESULT_WritingWasCut 0x20000010
306 508
307#endif 509#endif
diff --git a/CPP/Common/MyException.h b/CPP/Common/MyException.h
index f0ad111..06fbdea 100644
--- a/CPP/Common/MyException.h
+++ b/CPP/Common/MyException.h
@@ -1,7 +1,7 @@
1// Common/Exception.h 1// Common/Exception.h
2 2
3#ifndef __COMMON_EXCEPTION_H 3#ifndef ZIP7_INC_COMMON_EXCEPTION_H
4#define __COMMON_EXCEPTION_H 4#define ZIP7_INC_COMMON_EXCEPTION_H
5 5
6#include "MyWindows.h" 6#include "MyWindows.h"
7 7
diff --git a/CPP/Common/MyGuidDef.h b/CPP/Common/MyGuidDef.h
index 38aad6e..ab9993b 100644
--- a/CPP/Common/MyGuidDef.h
+++ b/CPP/Common/MyGuidDef.h
@@ -1,8 +1,12 @@
1// Common/MyGuidDef.h 1// Common/MyGuidDef.h
2 2
3// #pragma message "Common/MyGuidDef.h"
4
3#ifndef GUID_DEFINED 5#ifndef GUID_DEFINED
4#define GUID_DEFINED 6#define GUID_DEFINED
5 7
8// #pragma message "GUID_DEFINED"
9
6#include "MyTypes.h" 10#include "MyTypes.h"
7 11
8typedef struct { 12typedef struct {
@@ -27,31 +31,33 @@ typedef GUID CLSID;
27#ifdef __cplusplus 31#ifdef __cplusplus
28inline int operator==(REFGUID g1, REFGUID g2) 32inline int operator==(REFGUID g1, REFGUID g2)
29{ 33{
30 for (int i = 0; i < (int)sizeof(g1); i++) 34 for (unsigned i = 0; i < sizeof(g1); i++)
31 if (((unsigned char *)&g1)[i] != ((unsigned char *)&g2)[i]) 35 if (((const unsigned char *)&g1)[i] != ((const unsigned char *)&g2)[i])
32 return 0; 36 return 0;
33 return 1; 37 return 1;
34} 38}
35inline int operator!=(REFGUID g1, REFGUID g2) { return !(g1 == g2); } 39inline int operator!=(REFGUID g1, REFGUID g2) { return !(g1 == g2); }
36#endif 40#endif
37 41
42#endif // GUID_DEFINED
43
44#ifndef EXTERN_C
38#ifdef __cplusplus 45#ifdef __cplusplus
39 #define MY_EXTERN_C extern "C" 46 #define EXTERN_C extern "C"
40#else 47#else
41 #define MY_EXTERN_C extern 48 #define EXTERN_C extern
42#endif 49#endif
43
44#endif 50#endif
45 51
46
47#ifdef DEFINE_GUID 52#ifdef DEFINE_GUID
48#undef DEFINE_GUID 53#undef DEFINE_GUID
49#endif 54#endif
50 55
51#ifdef INITGUID 56#ifdef INITGUID
52 #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ 57 #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
53 MY_EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } 58 EXTERN_C const GUID name; \
59 EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
54#else 60#else
55 #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ 61 #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
56 MY_EXTERN_C const GUID name 62 EXTERN_C const GUID name
57#endif 63#endif
diff --git a/CPP/Common/MyInitGuid.h b/CPP/Common/MyInitGuid.h
index 04d77e2..3745c79 100644
--- a/CPP/Common/MyInitGuid.h
+++ b/CPP/Common/MyInitGuid.h
@@ -1,7 +1,7 @@
1// Common/MyInitGuid.h 1// Common/MyInitGuid.h
2 2
3#ifndef __COMMON_MY_INITGUID_H 3#ifndef ZIP7_INC_COMMON_MY_INITGUID_H
4#define __COMMON_MY_INITGUID_H 4#define ZIP7_INC_COMMON_MY_INITGUID_H
5 5
6/* 6/*
7This file must be included only to one C++ file in project before 7This 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:
19 Other: we define IID_IUnknown in this file 19 Other: we define IID_IUnknown in this file
20*/ 20*/
21 21
22#ifdef __clang__ 22// #include "Common.h"
23 #pragma clang diagnostic ignored "-Wmissing-variable-declarations" 23/* vc6 without sdk needs <objbase.h> before <initguid.h>,
24#endif 24 but it doesn't work in new msvc.
25 So we include full "MyWindows.h" instead of <objbase.h> */
26// #include <objbase.h>
27#include "MyWindows.h"
25 28
26#ifdef _WIN32 29#ifdef _WIN32
27 30
31#ifdef __clang__
32 // #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
33#endif
34
28#ifdef UNDER_CE 35#ifdef UNDER_CE
29#include <basetyps.h> 36#include <basetyps.h>
30#endif 37#endif
31 38
32#include <InitGuid.h> 39// for vc6 without sdk we must define INITGUID here
40#define INITGUID
41#include <initguid.h>
33 42
34#ifdef UNDER_CE 43#ifdef UNDER_CE
35DEFINE_GUID(IID_IUnknown, 44DEFINE_GUID(IID_IUnknown,
360x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); 450x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
37#endif 46#endif
38 47
39#else 48#else // _WIN32
40 49
41#define INITGUID 50#define INITGUID
42#include "MyGuidDef.h" 51#include "MyGuidDef.h"
43DEFINE_GUID(IID_IUnknown, 52DEFINE_GUID(IID_IUnknown,
440x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); 530x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
45 54
46#endif 55#endif // _WIN32
47
48 56
49#endif 57#endif
diff --git a/CPP/Common/MyLinux.h b/CPP/Common/MyLinux.h
index 98b453c..a8454d7 100644
--- a/CPP/Common/MyLinux.h
+++ b/CPP/Common/MyLinux.h
@@ -1,7 +1,7 @@
1// MyLinux.h 1// MyLinux.h
2 2
3#ifndef __MY_LIN_LINUX_H 3#ifndef ZIP7_INC_COMMON_MY_LINUX_H
4#define __MY_LIN_LINUX_H 4#define ZIP7_INC_COMMON_MY_LINUX_H
5 5
6// #include "../../C/7zTypes.h" 6// #include "../../C/7zTypes.h"
7 7
diff --git a/CPP/Common/MyMap.cpp b/CPP/Common/MyMap.cpp
index 923846a..0a200f0 100644
--- a/CPP/Common/MyMap.cpp
+++ b/CPP/Common/MyMap.cpp
@@ -76,7 +76,7 @@ bool CMap32::Set(UInt32 key, UInt32 value)
76 unsigned i = kNumBitsMax - 1; 76 unsigned i = kNumBitsMax - 1;
77 for (; GetSubBit(key, i) == GetSubBit(n.Key, i); i--); 77 for (; GetSubBit(key, i) == GetSubBit(n.Key, i); i--);
78 n.Len = (UInt16)(kNumBitsMax - (1 + i)); 78 n.Len = (UInt16)(kNumBitsMax - (1 + i));
79 unsigned newBit = GetSubBit(key, i); 79 const unsigned newBit = GetSubBit(key, i);
80 n.Values[newBit] = value; 80 n.Values[newBit] = value;
81 n.Keys[newBit] = key; 81 n.Keys[newBit] = key;
82 return false; 82 return false;
@@ -91,7 +91,7 @@ bool CMap32::Set(UInt32 key, UInt32 value)
91 bitPos -= n.Len; 91 bitPos -= n.Len;
92 if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) 92 if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len))
93 { 93 {
94 unsigned i = n.Len - 1; 94 unsigned i = (unsigned)n.Len - 1;
95 for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--); 95 for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--);
96 96
97 CNode e2(n); 97 CNode e2(n);
@@ -107,7 +107,7 @@ bool CMap32::Set(UInt32 key, UInt32 value)
107 Nodes.Add(e2); 107 Nodes.Add(e2);
108 return false; 108 return false;
109 } 109 }
110 unsigned bit = GetSubBit(key, --bitPos); 110 const unsigned bit = GetSubBit(key, --bitPos);
111 111
112 if (n.IsLeaf[bit]) 112 if (n.IsLeaf[bit])
113 { 113 {
@@ -121,7 +121,7 @@ bool CMap32::Set(UInt32 key, UInt32 value)
121 121
122 CNode e2; 122 CNode e2;
123 123
124 unsigned newBit = GetSubBit(key, i); 124 const unsigned newBit = GetSubBit(key, i);
125 e2.Values[newBit] = value; 125 e2.Values[newBit] = value;
126 e2.Values[1 - newBit] = n.Values[bit]; 126 e2.Values[1 - newBit] = n.Values[bit];
127 e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1; 127 e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1;
diff --git a/CPP/Common/MyMap.h b/CPP/Common/MyMap.h
index cbcbadd..9ca5566 100644
--- a/CPP/Common/MyMap.h
+++ b/CPP/Common/MyMap.h
@@ -1,7 +1,7 @@
1// MyMap.h 1// MyMap.h
2 2
3#ifndef __COMMON_MYMAP_H 3#ifndef ZIP7_INC_COMMON_MY_MAP_H
4#define __COMMON_MYMAP_H 4#define ZIP7_INC_COMMON_MY_MAP_H
5 5
6#include "MyTypes.h" 6#include "MyTypes.h"
7#include "MyVector.h" 7#include "MyVector.h"
diff --git a/CPP/Common/MyString.cpp b/CPP/Common/MyString.cpp
index bf1638e..51c1c3b 100644
--- a/CPP/Common/MyString.cpp
+++ b/CPP/Common/MyString.cpp
@@ -408,7 +408,7 @@ void AString::ReAlloc(unsigned newLimit)
408 // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, (size_t)_len + 1); 408 // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, (size_t)_len + 1);
409 char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1); 409 char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1);
410 memcpy(newBuf, _chars, (size_t)_len + 1); 410 memcpy(newBuf, _chars, (size_t)_len + 1);
411 MY_STRING_DELETE(_chars); 411 MY_STRING_DELETE(_chars)
412 _chars = newBuf; 412 _chars = newBuf;
413 _limit = newLimit; 413 _limit = newLimit;
414} 414}
@@ -419,9 +419,10 @@ void AString::ReAlloc2(unsigned newLimit)
419 // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, 0); 419 // MY_STRING_REALLOC(_chars, char, (size_t)newLimit + 1, 0);
420 char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1); 420 char *newBuf = MY_STRING_NEW_char((size_t)newLimit + 1);
421 newBuf[0] = 0; 421 newBuf[0] = 0;
422 MY_STRING_DELETE(_chars); 422 MY_STRING_DELETE(_chars)
423 _chars = newBuf; 423 _chars = newBuf;
424 _limit = newLimit; 424 _limit = newLimit;
425 _len = 0;
425} 426}
426 427
427void AString::SetStartLen(unsigned len) 428void AString::SetStartLen(unsigned len)
@@ -541,7 +542,7 @@ AString &AString::operator=(char c)
541 if (1 > _limit) 542 if (1 > _limit)
542 { 543 {
543 char *newBuf = MY_STRING_NEW_char(1 + 1); 544 char *newBuf = MY_STRING_NEW_char(1 + 1);
544 MY_STRING_DELETE(_chars); 545 MY_STRING_DELETE(_chars)
545 _chars = newBuf; 546 _chars = newBuf;
546 _limit = 1; 547 _limit = 1;
547 } 548 }
@@ -558,7 +559,7 @@ AString &AString::operator=(const char *s)
558 if (len > _limit) 559 if (len > _limit)
559 { 560 {
560 char *newBuf = MY_STRING_NEW_char((size_t)len + 1); 561 char *newBuf = MY_STRING_NEW_char((size_t)len + 1);
561 MY_STRING_DELETE(_chars); 562 MY_STRING_DELETE(_chars)
562 _chars = newBuf; 563 _chars = newBuf;
563 _limit = len; 564 _limit = len;
564 } 565 }
@@ -575,7 +576,7 @@ AString &AString::operator=(const AString &s)
575 if (len > _limit) 576 if (len > _limit)
576 { 577 {
577 char *newBuf = MY_STRING_NEW_char((size_t)len + 1); 578 char *newBuf = MY_STRING_NEW_char((size_t)len + 1);
578 MY_STRING_DELETE(_chars); 579 MY_STRING_DELETE(_chars)
579 _chars = newBuf; 580 _chars = newBuf;
580 _limit = len; 581 _limit = len;
581 } 582 }
@@ -600,7 +601,7 @@ void AString::SetFromWStr_if_Ascii(const wchar_t *s)
600 if (len > _limit) 601 if (len > _limit)
601 { 602 {
602 char *newBuf = MY_STRING_NEW_char((size_t)len + 1); 603 char *newBuf = MY_STRING_NEW_char((size_t)len + 1);
603 MY_STRING_DELETE(_chars); 604 MY_STRING_DELETE(_chars)
604 _chars = newBuf; 605 _chars = newBuf;
605 _limit = len; 606 _limit = len;
606 } 607 }
@@ -624,7 +625,7 @@ void AString::SetFromBstr_if_Ascii(BSTR s)
624 if (len > _limit) 625 if (len > _limit)
625 { 626 {
626 char *newBuf = MY_STRING_NEW_char((size_t)len + 1); 627 char *newBuf = MY_STRING_NEW_char((size_t)len + 1);
627 MY_STRING_DELETE(_chars); 628 MY_STRING_DELETE(_chars)
628 _chars = newBuf; 629 _chars = newBuf;
629 _limit = len; 630 _limit = len;
630 } 631 }
@@ -641,6 +642,8 @@ void AString::Add_Space() { operator+=(' '); }
641void AString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); } 642void AString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); }
642void AString::Add_LF() { operator+=('\n'); } 643void AString::Add_LF() { operator+=('\n'); }
643void AString::Add_Slash() { operator+=('/'); } 644void AString::Add_Slash() { operator+=('/'); }
645void AString::Add_Dot() { operator+=('.'); }
646void AString::Add_Minus() { operator+=('-'); }
644 647
645AString &AString::operator+=(const char *s) 648AString &AString::operator+=(const char *s)
646{ 649{
@@ -694,7 +697,7 @@ void AString::SetFrom(const char *s, unsigned len) // no check
694 if (len > _limit) 697 if (len > _limit)
695 { 698 {
696 char *newBuf = MY_STRING_NEW_char((size_t)len + 1); 699 char *newBuf = MY_STRING_NEW_char((size_t)len + 1);
697 MY_STRING_DELETE(_chars); 700 MY_STRING_DELETE(_chars)
698 _chars = newBuf; 701 _chars = newBuf;
699 _limit = len; 702 _limit = len;
700 } 703 }
@@ -766,7 +769,7 @@ int AString::ReverseFind_PathSepar() const throw()
766 const char *p = _chars + _len - 1; 769 const char *p = _chars + _len - 1;
767 for (;;) 770 for (;;)
768 { 771 {
769 char c = *p; 772 const char c = *p;
770 if (IS_PATH_SEPAR(c)) 773 if (IS_PATH_SEPAR(c))
771 return (int)(p - _chars); 774 return (int)(p - _chars);
772 if (p == _chars) 775 if (p == _chars)
@@ -1001,7 +1004,7 @@ void UString::ReAlloc(unsigned newLimit)
1001 // MY_STRING_REALLOC(_chars, wchar_t, (size_t)newLimit + 1, (size_t)_len + 1); 1004 // MY_STRING_REALLOC(_chars, wchar_t, (size_t)newLimit + 1, (size_t)_len + 1);
1002 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1); 1005 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1);
1003 wmemcpy(newBuf, _chars, _len + 1); 1006 wmemcpy(newBuf, _chars, _len + 1);
1004 MY_STRING_DELETE(_chars); 1007 MY_STRING_DELETE(_chars)
1005 _chars = newBuf; 1008 _chars = newBuf;
1006 _limit = newLimit; 1009 _limit = newLimit;
1007} 1010}
@@ -1012,14 +1015,15 @@ void UString::ReAlloc2(unsigned newLimit)
1012 // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0); 1015 // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0);
1013 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1); 1016 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)newLimit + 1);
1014 newBuf[0] = 0; 1017 newBuf[0] = 0;
1015 MY_STRING_DELETE(_chars); 1018 MY_STRING_DELETE(_chars)
1016 _chars = newBuf; 1019 _chars = newBuf;
1017 _limit = newLimit; 1020 _limit = newLimit;
1021 _len = 0;
1018} 1022}
1019 1023
1020void UString::SetStartLen(unsigned len) 1024void UString::SetStartLen(unsigned len)
1021{ 1025{
1022 _chars = 0; 1026 _chars = NULL;
1023 _chars = MY_STRING_NEW_wchar_t((size_t)len + 1); 1027 _chars = MY_STRING_NEW_wchar_t((size_t)len + 1);
1024 _len = len; 1028 _len = len;
1025 _limit = len; 1029 _limit = len;
@@ -1101,7 +1105,7 @@ UString operator+(const wchar_t *s1, const UString &s2) { return UString(s1, MyS
1101 1105
1102UString::UString() 1106UString::UString()
1103{ 1107{
1104 _chars = 0; 1108 _chars = NULL;
1105 _chars = MY_STRING_NEW_wchar_t(kStartStringCapacity); 1109 _chars = MY_STRING_NEW_wchar_t(kStartStringCapacity);
1106 _len = 0; 1110 _len = 0;
1107 _limit = kStartStringCapacity - 1; 1111 _limit = kStartStringCapacity - 1;
@@ -1163,7 +1167,7 @@ UString &UString::operator=(wchar_t c)
1163 if (1 > _limit) 1167 if (1 > _limit)
1164 { 1168 {
1165 wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1); 1169 wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1);
1166 MY_STRING_DELETE(_chars); 1170 MY_STRING_DELETE(_chars)
1167 _chars = newBuf; 1171 _chars = newBuf;
1168 _limit = 1; 1172 _limit = 1;
1169 } 1173 }
@@ -1180,7 +1184,7 @@ UString &UString::operator=(const wchar_t *s)
1180 if (len > _limit) 1184 if (len > _limit)
1181 { 1185 {
1182 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1186 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1183 MY_STRING_DELETE(_chars); 1187 MY_STRING_DELETE(_chars)
1184 _chars = newBuf; 1188 _chars = newBuf;
1185 _limit = len; 1189 _limit = len;
1186 } 1190 }
@@ -1197,7 +1201,7 @@ UString &UString::operator=(const UString &s)
1197 if (len > _limit) 1201 if (len > _limit)
1198 { 1202 {
1199 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1203 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1200 MY_STRING_DELETE(_chars); 1204 MY_STRING_DELETE(_chars)
1201 _chars = newBuf; 1205 _chars = newBuf;
1202 _limit = len; 1206 _limit = len;
1203 } 1207 }
@@ -1211,7 +1215,7 @@ void UString::SetFrom(const wchar_t *s, unsigned len) // no check
1211 if (len > _limit) 1215 if (len > _limit)
1212 { 1216 {
1213 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1217 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1214 MY_STRING_DELETE(_chars); 1218 MY_STRING_DELETE(_chars)
1215 _chars = newBuf; 1219 _chars = newBuf;
1216 _limit = len; 1220 _limit = len;
1217 } 1221 }
@@ -1249,7 +1253,7 @@ void UString::SetFromBstr(LPCOLESTR s)
1249 if (len > _limit) 1253 if (len > _limit)
1250 { 1254 {
1251 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1255 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1252 MY_STRING_DELETE(_chars); 1256 MY_STRING_DELETE(_chars)
1253 _chars = newBuf; 1257 _chars = newBuf;
1254 _limit = len; 1258 _limit = len;
1255 } 1259 }
@@ -1289,7 +1293,7 @@ UString &UString::operator=(const char *s)
1289 if (len > _limit) 1293 if (len > _limit)
1290 { 1294 {
1291 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1295 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1292 MY_STRING_DELETE(_chars); 1296 MY_STRING_DELETE(_chars)
1293 _chars = newBuf; 1297 _chars = newBuf;
1294 _limit = len; 1298 _limit = len;
1295 } 1299 }
@@ -1301,6 +1305,7 @@ UString &UString::operator=(const char *s)
1301 return *this; 1305 return *this;
1302} 1306}
1303 1307
1308void UString::Add_Dot() { operator+=(L'.'); }
1304void UString::Add_Space() { operator+=(L' '); } 1309void UString::Add_Space() { operator+=(L' '); }
1305void UString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); } 1310void UString::Add_Space_if_NotEmpty() { if (!IsEmpty()) Add_Space(); }
1306 1311
@@ -1393,31 +1398,26 @@ int UString::ReverseFind(wchar_t c) const throw()
1393{ 1398{
1394 if (_len == 0) 1399 if (_len == 0)
1395 return -1; 1400 return -1;
1396 const wchar_t *p = _chars + _len - 1; 1401 const wchar_t *p = _chars + _len;
1397 for (;;) 1402 do
1398 { 1403 {
1399 if (*p == c) 1404 if (*(--p) == c)
1400 return (int)(p - _chars); 1405 return (int)(p - _chars);
1401 if (p == _chars)
1402 return -1;
1403 p--;
1404 } 1406 }
1407 while (p != _chars);
1408 return -1;
1405} 1409}
1406 1410
1407int UString::ReverseFind_PathSepar() const throw() 1411int UString::ReverseFind_PathSepar() const throw()
1408{ 1412{
1409 if (_len == 0) 1413 const wchar_t *p = _chars + _len;
1410 return -1; 1414 while (p != _chars)
1411 const wchar_t *p = _chars + _len - 1;
1412 for (;;)
1413 { 1415 {
1414 wchar_t c = *p; 1416 const wchar_t c = *(--p);
1415 if (IS_PATH_SEPAR(c)) 1417 if (IS_PATH_SEPAR(c))
1416 return (int)(p - _chars); 1418 return (int)(p - _chars);
1417 if (p == _chars)
1418 return -1;
1419 p--;
1420 } 1419 }
1420 return -1;
1421} 1421}
1422 1422
1423void UString::TrimLeft() throw() 1423void UString::TrimLeft() throw()
@@ -1601,7 +1601,7 @@ void UString2::ReAlloc2(unsigned newLimit)
1601 // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0); 1601 // MY_STRING_REALLOC(_chars, wchar_t, newLimit + 1, 0);
1602 if (_chars) 1602 if (_chars)
1603 { 1603 {
1604 MY_STRING_DELETE(_chars); 1604 MY_STRING_DELETE(_chars)
1605 _chars = NULL; 1605 _chars = NULL;
1606 // _len = 0; 1606 // _len = 0;
1607 } 1607 }
@@ -1651,7 +1651,7 @@ UString2 &UString2::operator=(wchar_t c)
1651 { 1651 {
1652 wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1); 1652 wchar_t *newBuf = MY_STRING_NEW_wchar_t(1 + 1);
1653 if (_chars) 1653 if (_chars)
1654 MY_STRING_DELETE(_chars); 1654 MY_STRING_DELETE(_chars)
1655 _chars = newBuf; 1655 _chars = newBuf;
1656 } 1656 }
1657 _len = 1; 1657 _len = 1;
@@ -1669,7 +1669,7 @@ UString2 &UString2::operator=(const wchar_t *s)
1669 { 1669 {
1670 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1670 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1671 if (_chars) 1671 if (_chars)
1672 MY_STRING_DELETE(_chars); 1672 MY_STRING_DELETE(_chars)
1673 _chars = newBuf; 1673 _chars = newBuf;
1674 } 1674 }
1675 _len = len; 1675 _len = len;
@@ -1684,7 +1684,7 @@ void UString2::SetFromAscii(const char *s)
1684 { 1684 {
1685 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1685 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1686 if (_chars) 1686 if (_chars)
1687 MY_STRING_DELETE(_chars); 1687 MY_STRING_DELETE(_chars)
1688 _chars = newBuf; 1688 _chars = newBuf;
1689 } 1689 }
1690 wchar_t *chars = _chars; 1690 wchar_t *chars = _chars;
@@ -1703,7 +1703,7 @@ UString2 &UString2::operator=(const UString2 &s)
1703 { 1703 {
1704 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1); 1704 wchar_t *newBuf = MY_STRING_NEW_wchar_t((size_t)len + 1);
1705 if (_chars) 1705 if (_chars)
1706 MY_STRING_DELETE(_chars); 1706 MY_STRING_DELETE(_chars)
1707 _chars = newBuf; 1707 _chars = newBuf;
1708 } 1708 }
1709 _len = len; 1709 _len = len;
@@ -1793,3 +1793,67 @@ FString us2fs(const wchar_t *s)
1793} 1793}
1794 1794
1795#endif // USE_UNICODE_FSTRING 1795#endif // USE_UNICODE_FSTRING
1796
1797
1798bool CStringFinder::FindWord_In_LowCaseAsciiList_NoCase(const char *p, const wchar_t *str)
1799{
1800 _temp.Empty();
1801 for (;;)
1802 {
1803 const wchar_t c = *str++;
1804 if (c == 0)
1805 break;
1806 if (c <= 0x20 || c > 0x7f)
1807 return false;
1808 _temp += (char)MyCharLower_Ascii((char)c);
1809 }
1810
1811 while (*p != 0)
1812 {
1813 const char *s2 = _temp.Ptr();
1814 char c, c2;
1815 do
1816 {
1817 c = *p++;
1818 c2 = *s2++;
1819 }
1820 while (c == c2);
1821
1822 if (c == ' ')
1823 {
1824 if (c2 == 0)
1825 return true;
1826 continue;
1827 }
1828
1829 while (*p++ != ' ');
1830 }
1831
1832 return false;
1833}
1834
1835
1836void SplitString(const UString &srcString, UStringVector &destStrings)
1837{
1838 destStrings.Clear();
1839 unsigned len = srcString.Len();
1840 if (len == 0)
1841 return;
1842 UString s;
1843 for (unsigned i = 0; i < len; i++)
1844 {
1845 const wchar_t c = srcString[i];
1846 if (c == ' ')
1847 {
1848 if (!s.IsEmpty())
1849 {
1850 destStrings.Add(s);
1851 s.Empty();
1852 }
1853 }
1854 else
1855 s += c;
1856 }
1857 if (!s.IsEmpty())
1858 destStrings.Add(s);
1859}
diff --git a/CPP/Common/MyString.h b/CPP/Common/MyString.h
index c777c8c..e5ce18a 100644
--- a/CPP/Common/MyString.h
+++ b/CPP/Common/MyString.h
@@ -1,7 +1,7 @@
1// Common/MyString.h 1// Common/MyString.h
2 2
3#ifndef __COMMON_MY_STRING_H 3#ifndef ZIP7_INC_COMMON_MY_STRING_H
4#define __COMMON_MY_STRING_H 4#define ZIP7_INC_COMMON_MY_STRING_H
5 5
6#include <string.h> 6#include <string.h>
7 7
@@ -10,6 +10,7 @@
10#include <wchar.h> 10#include <wchar.h>
11#endif 11#endif
12 12
13#include "Common.h"
13#include "MyWindows.h" 14#include "MyWindows.h"
14#include "MyTypes.h" 15#include "MyTypes.h"
15#include "MyVector.h" 16#include "MyVector.h"
@@ -70,7 +71,7 @@ inline char *MyStpCpy(char *dest, const char *src)
70{ 71{
71 for (;;) 72 for (;;)
72 { 73 {
73 char c = *src; 74 const char c = *src;
74 *dest = c; 75 *dest = c;
75 if (c == 0) 76 if (c == 0)
76 return dest; 77 return dest;
@@ -79,6 +80,13 @@ inline char *MyStpCpy(char *dest, const char *src)
79 } 80 }
80} 81}
81 82
83inline void MyStringCat(char *dest, const char *src)
84{
85 for (; *dest != 0; dest++);
86 while ((*dest++ = *src++) != 0);
87 // MyStringCopy(dest + MyStringLen(dest), src);
88}
89
82inline unsigned MyStringLen(const wchar_t *s) 90inline unsigned MyStringLen(const wchar_t *s)
83{ 91{
84 unsigned i; 92 unsigned i;
@@ -93,7 +101,9 @@ inline void MyStringCopy(wchar_t *dest, const wchar_t *src)
93 101
94inline void MyStringCat(wchar_t *dest, const wchar_t *src) 102inline void MyStringCat(wchar_t *dest, const wchar_t *src)
95{ 103{
96 MyStringCopy(dest + MyStringLen(dest), src); 104 for (; *dest != 0; dest++);
105 while ((*dest++ = *src++) != 0);
106 // MyStringCopy(dest + MyStringLen(dest), src);
97} 107}
98 108
99 109
@@ -102,7 +112,7 @@ inline wchar_t *MyWcpCpy(wchar_t *dest, const wchar_t *src)
102{ 112{
103 for (;;) 113 for (;;)
104 { 114 {
105 wchar_t c = *src; 115 const wchar_t c = *src;
106 *dest = c; 116 *dest = c;
107 if (c == 0) 117 if (c == 0)
108 return dest; 118 return dest;
@@ -225,7 +235,7 @@ bool StringsAreEqualNoCase_Ascii(const char *s1, const char *s2) throw();
225bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const char *s2) throw(); 235bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const char *s2) throw();
226bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const wchar_t *s2) throw(); 236bool StringsAreEqualNoCase_Ascii(const wchar_t *s1, const wchar_t *s2) throw();
227 237
228#define MY_STRING_DELETE(_p_) delete []_p_; 238#define MY_STRING_DELETE(_p_) { delete [](_p_); }
229// #define MY_STRING_DELETE(_p_) my_delete(_p_); 239// #define MY_STRING_DELETE(_p_) my_delete(_p_);
230 240
231 241
@@ -312,7 +322,7 @@ public:
312 explicit AString(char c); 322 explicit AString(char c);
313 explicit AString(const char *s); 323 explicit AString(const char *s);
314 AString(const AString &s); 324 AString(const AString &s);
315 ~AString() { MY_STRING_DELETE(_chars); } 325 ~AString() { MY_STRING_DELETE(_chars) }
316 326
317 unsigned Len() const { return _len; } 327 unsigned Len() const { return _len; }
318 bool IsEmpty() const { return _len == 0; } 328 bool IsEmpty() const { return _len == 0; }
@@ -322,6 +332,7 @@ public:
322 char *Ptr_non_const() const { return _chars; } 332 char *Ptr_non_const() const { return _chars; }
323 const char *Ptr() const { return _chars; } 333 const char *Ptr() const { return _chars; }
324 const char *Ptr(unsigned pos) const { return _chars + pos; } 334 const char *Ptr(unsigned pos) const { return _chars + pos; }
335 const char *Ptr(int pos) const { return _chars + (unsigned)pos; }
325 const char *RightPtr(unsigned num) const { return _chars + _len - num; } 336 const char *RightPtr(unsigned num) const { return _chars + _len - num; }
326 char Back() const { return _chars[(size_t)_len - 1]; } 337 char Back() const { return _chars[(size_t)_len - 1]; }
327 338
@@ -379,6 +390,8 @@ public:
379 void Add_OptSpaced(const char *s); 390 void Add_OptSpaced(const char *s);
380 void Add_LF(); 391 void Add_LF();
381 void Add_Slash(); 392 void Add_Slash();
393 void Add_Dot();
394 void Add_Minus();
382 void Add_PathSepar() { operator+=(CHAR_PATH_SEPARATOR); } 395 void Add_PathSepar() { operator+=(CHAR_PATH_SEPARATOR); }
383 396
384 AString &operator+=(const char *s); 397 AString &operator+=(const char *s);
@@ -389,6 +402,10 @@ public:
389 402
390 void AddFrom(const char *s, unsigned len); // no check 403 void AddFrom(const char *s, unsigned len); // no check
391 void SetFrom(const char *s, unsigned len); // no check 404 void SetFrom(const char *s, unsigned len); // no check
405 void SetFrom(const char* s, int len) // no check
406 {
407 SetFrom(s, (unsigned)len); // no check
408 }
392 void SetFrom_CalcLen(const char *s, unsigned len); 409 void SetFrom_CalcLen(const char *s, unsigned len);
393 410
394 AString Mid(unsigned startIndex, unsigned count) const { return AString(count, _chars + startIndex); } 411 AString Mid(unsigned startIndex, unsigned count) const { return AString(count, _chars + startIndex); }
@@ -419,9 +436,13 @@ public:
419 int Find(char c) const { return FindCharPosInString(_chars, c); } 436 int Find(char c) const { return FindCharPosInString(_chars, c); }
420 int Find(char c, unsigned startIndex) const 437 int Find(char c, unsigned startIndex) const
421 { 438 {
422 int pos = FindCharPosInString(_chars + startIndex, c); 439 const int pos = FindCharPosInString(_chars + startIndex, c);
423 return pos < 0 ? -1 : (int)startIndex + pos; 440 return pos < 0 ? -1 : (int)startIndex + pos;
424 } 441 }
442 int Find(char c, int startIndex) const
443 {
444 return Find(c, (unsigned)startIndex);
445 }
425 446
426 int ReverseFind(char c) const throw(); 447 int ReverseFind(char c) const throw();
427 int ReverseFind_Dot() const throw() { return ReverseFind('.'); } 448 int ReverseFind_Dot() const throw() { return ReverseFind('.'); }
@@ -460,6 +481,11 @@ public:
460 _chars[index] = 0; 481 _chars[index] = 0;
461 } 482 }
462 } 483 }
484 void DeleteFrom(int index)
485 {
486 DeleteFrom((unsigned)index);
487 }
488
463 489
464 void Wipe_and_Empty() 490 void Wipe_and_Empty()
465 { 491 {
@@ -474,7 +500,7 @@ public:
474 500
475class AString_Wipe: public AString 501class AString_Wipe: public AString
476{ 502{
477 CLASS_NO_COPY(AString_Wipe) 503 Z7_CLASS_NO_COPY(AString_Wipe)
478public: 504public:
479 AString_Wipe(): AString() {} 505 AString_Wipe(): AString() {}
480 // AString_Wipe(const AString &s): AString(s) {} 506 // AString_Wipe(const AString &s): AString(s) {}
@@ -582,7 +608,7 @@ public:
582 explicit UString(const AString &s); 608 explicit UString(const AString &s);
583 UString(const wchar_t *s); 609 UString(const wchar_t *s);
584 UString(const UString &s); 610 UString(const UString &s);
585 ~UString() { MY_STRING_DELETE(_chars); } 611 ~UString() { MY_STRING_DELETE(_chars) }
586 612
587 unsigned Len() const { return _len; } 613 unsigned Len() const { return _len; }
588 bool IsEmpty() const { return _len == 0; } 614 bool IsEmpty() const { return _len == 0; }
@@ -591,6 +617,7 @@ public:
591 operator const wchar_t *() const { return _chars; } 617 operator const wchar_t *() const { return _chars; }
592 wchar_t *Ptr_non_const() const { return _chars; } 618 wchar_t *Ptr_non_const() const { return _chars; }
593 const wchar_t *Ptr() const { return _chars; } 619 const wchar_t *Ptr() const { return _chars; }
620 const wchar_t *Ptr(int pos) const { return _chars + (unsigned)pos; }
594 const wchar_t *Ptr(unsigned pos) const { return _chars + pos; } 621 const wchar_t *Ptr(unsigned pos) const { return _chars + pos; }
595 const wchar_t *RightPtr(unsigned num) const { return _chars + _len - num; } 622 const wchar_t *RightPtr(unsigned num) const { return _chars + _len - num; }
596 wchar_t Back() const { return _chars[(size_t)_len - 1]; } 623 wchar_t Back() const { return _chars[(size_t)_len - 1]; }
@@ -599,6 +626,14 @@ public:
599 626
600 wchar_t *GetBuf() { return _chars; } 627 wchar_t *GetBuf() { return _chars; }
601 628
629 /*
630 wchar_t *GetBuf_GetMaxAvail(unsigned &availBufLen)
631 {
632 availBufLen = _limit;
633 return _chars;
634 }
635 */
636
602 wchar_t *GetBuf(unsigned minLen) 637 wchar_t *GetBuf(unsigned minLen)
603 { 638 {
604 if (minLen > _limit) 639 if (minLen > _limit)
@@ -650,6 +685,7 @@ public:
650 void Add_Space(); 685 void Add_Space();
651 void Add_Space_if_NotEmpty(); 686 void Add_Space_if_NotEmpty();
652 void Add_LF(); 687 void Add_LF();
688 void Add_Dot();
653 void Add_PathSepar() { operator+=(WCHAR_PATH_SEPARATOR); } 689 void Add_PathSepar() { operator+=(WCHAR_PATH_SEPARATOR); }
654 690
655 UString &operator+=(const wchar_t *s); 691 UString &operator+=(const wchar_t *s);
@@ -662,6 +698,7 @@ public:
662 698
663 UString Mid(unsigned startIndex, unsigned count) const { return UString(count, _chars + startIndex); } 699 UString Mid(unsigned startIndex, unsigned count) const { return UString(count, _chars + startIndex); }
664 UString Left(unsigned count) const { return UString(count, *this); } 700 UString Left(unsigned count) const { return UString(count, *this); }
701 UString Left(int count) const { return Left((unsigned)count); }
665 702
666 // void MakeUpper() { MyStringUpper(_chars); } 703 // void MakeUpper() { MyStringUpper(_chars); }
667 // void MakeUpper() { MyStringUpper_Ascii(_chars); } 704 // void MakeUpper() { MyStringUpper_Ascii(_chars); }
@@ -720,10 +757,12 @@ public:
720 void Replace(wchar_t oldChar, wchar_t newChar) throw(); 757 void Replace(wchar_t oldChar, wchar_t newChar) throw();
721 void Replace(const UString &oldString, const UString &newString); 758 void Replace(const UString &oldString, const UString &newString);
722 759
760 void Delete(int index) throw() { Delete((unsigned)index); }
723 void Delete(unsigned index) throw(); 761 void Delete(unsigned index) throw();
724 void Delete(unsigned index, unsigned count) throw(); 762 void Delete(unsigned index, unsigned count) throw();
725 void DeleteFrontal(unsigned num) throw(); 763 void DeleteFrontal(unsigned num) throw();
726 void DeleteBack() { _chars[--_len] = 0; } 764 void DeleteBack() { _chars[--_len] = 0; }
765 void DeleteFrom(int index) { DeleteFrom((unsigned)index); }
727 void DeleteFrom(unsigned index) 766 void DeleteFrom(unsigned index)
728 { 767 {
729 if (index < _len) 768 if (index < _len)
@@ -746,7 +785,7 @@ public:
746 785
747class UString_Wipe: public UString 786class UString_Wipe: public UString
748{ 787{
749 CLASS_NO_COPY(UString_Wipe) 788 Z7_CLASS_NO_COPY(UString_Wipe)
750public: 789public:
751 UString_Wipe(): UString() {} 790 UString_Wipe(): UString() {}
752 // UString_Wipe(const UString &s): UString(s) {} 791 // UString_Wipe(const UString &s): UString(s) {}
@@ -834,7 +873,7 @@ public:
834 UString2(): _chars(NULL), _len(0) {} 873 UString2(): _chars(NULL), _len(0) {}
835 UString2(const wchar_t *s); 874 UString2(const wchar_t *s);
836 UString2(const UString2 &s); 875 UString2(const UString2 &s);
837 ~UString2() { if (_chars) MY_STRING_DELETE(_chars); } 876 ~UString2() { if (_chars) { MY_STRING_DELETE(_chars) } }
838 877
839 unsigned Len() const { return _len; } 878 unsigned Len() const { return _len; }
840 bool IsEmpty() const { return _len == 0; } 879 bool IsEmpty() const { return _len == 0; }
@@ -912,7 +951,7 @@ typedef CObjectVector<CSysString> CSysStringVector;
912 951
913#ifdef USE_UNICODE_FSTRING 952#ifdef USE_UNICODE_FSTRING
914 953
915 #define __FTEXT(quote) L##quote 954 #define MY_FTEXT(quote) L##quote
916 955
917 typedef wchar_t FChar; 956 typedef wchar_t FChar;
918 typedef UString FString; 957 typedef UString FString;
@@ -923,9 +962,9 @@ typedef CObjectVector<CSysString> CSysStringVector;
923 FString fas2fs(const AString &s); 962 FString fas2fs(const AString &s);
924 AString fs2fas(const FChar *s); 963 AString fs2fas(const FChar *s);
925 964
926#else 965#else // USE_UNICODE_FSTRING
927 966
928 #define __FTEXT(quote) quote 967 #define MY_FTEXT(quote) quote
929 968
930 typedef char FChar; 969 typedef char FChar;
931 970
@@ -979,9 +1018,9 @@ typedef CObjectVector<CSysString> CSysStringVector;
979 FString us2fs(const wchar_t *s); 1018 FString us2fs(const wchar_t *s);
980 #define fs2fas(_x_) (_x_) 1019 #define fs2fas(_x_) (_x_)
981 1020
982#endif 1021#endif // USE_UNICODE_FSTRING
983 1022
984#define FTEXT(quote) __FTEXT(quote) 1023#define FTEXT(quote) MY_FTEXT(quote)
985 1024
986#define FCHAR_PATH_SEPARATOR FTEXT(CHAR_PATH_SEPARATOR) 1025#define FCHAR_PATH_SEPARATOR FTEXT(CHAR_PATH_SEPARATOR)
987#define FSTRING_PATH_SEPARATOR FTEXT(STRING_PATH_SEPARATOR) 1026#define FSTRING_PATH_SEPARATOR FTEXT(STRING_PATH_SEPARATOR)
@@ -993,6 +1032,18 @@ typedef const FChar *CFSTR;
993 1032
994typedef CObjectVector<FString> FStringVector; 1033typedef CObjectVector<FString> FStringVector;
995 1034
1035
1036class CStringFinder
1037{
1038 AString _temp;
1039public:
1040 // list - is list of low case Ascii strings separated by space " ".
1041 // the function returns true, if it can find exact word (str) in (list).
1042 bool FindWord_In_LowCaseAsciiList_NoCase(const char *list, const wchar_t *str);
1043};
1044
1045void SplitString(const UString &srcString, UStringVector &destStrings);
1046
996#endif 1047#endif
997 1048
998 1049
@@ -1000,10 +1051,10 @@ typedef CObjectVector<FString> FStringVector;
1000#if defined(_WIN32) 1051#if defined(_WIN32)
1001 // #include <wchar.h> 1052 // #include <wchar.h>
1002 // WCHAR_MAX is defined as ((wchar_t)-1) 1053 // WCHAR_MAX is defined as ((wchar_t)-1)
1003 #define _WCHART_IS_16BIT 1 1054 #define Z7_WCHART_IS_16BIT 1
1004#elif (defined(WCHAR_MAX) && (WCHAR_MAX <= 0xffff)) \ 1055#elif (defined(WCHAR_MAX) && (WCHAR_MAX <= 0xffff)) \
1005 || (defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ == 2)) 1056 || (defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ == 2))
1006 #define _WCHART_IS_16BIT 1 1057 #define Z7_WCHART_IS_16BIT 1
1007#endif 1058#endif
1008 1059
1009#if WCHAR_PATH_SEPARATOR == L'\\' 1060#if WCHAR_PATH_SEPARATOR == L'\\'
diff --git a/CPP/Common/MyTypes.h b/CPP/Common/MyTypes.h
index 71b8e7f..8f44f67 100644
--- a/CPP/Common/MyTypes.h
+++ b/CPP/Common/MyTypes.h
@@ -1,9 +1,10 @@
1// Common/MyTypes.h 1// Common/MyTypes.h
2 2
3#ifndef __COMMON_MY_TYPES_H 3#ifndef ZIP7_INC_COMMON_MY_TYPES_H
4#define __COMMON_MY_TYPES_H 4#define ZIP7_INC_COMMON_MY_TYPES_H
5 5
6#include "../../C/7zTypes.h" 6#include "../../C/7zTypes.h"
7#include "Common.h"
7 8
8typedef int HRes; 9typedef int HRes;
9 10
@@ -33,20 +34,4 @@ struct CBoolPair
33 } 34 }
34}; 35};
35 36
36#define CLASS_NO_COPY(cls) \
37 private: \
38 cls(const cls &); \
39 cls &operator=(const cls &);
40
41class CUncopyable
42{
43protected:
44 CUncopyable() {} // allow constructor
45 // ~CUncopyable() {}
46CLASS_NO_COPY(CUncopyable)
47};
48
49#define MY_UNCOPYABLE :private CUncopyable
50// #define MY_UNCOPYABLE
51
52#endif 37#endif
diff --git a/CPP/Common/MyUnknown.h b/CPP/Common/MyUnknown.h
index ff025cb..75ee96f 100644
--- a/CPP/Common/MyUnknown.h
+++ b/CPP/Common/MyUnknown.h
@@ -1,17 +1,8 @@
1// MyUnknown.h 1// MyUnknown.h
2 2
3#ifndef __MY_UNKNOWN_H 3#ifndef ZIP7_INC_MY_UNKNOWN_H
4#define __MY_UNKNOWN_H 4#define ZIP7_INC_MY_UNKNOWN_H
5 5
6#include "MyWindows.h" 6#include "MyWindows.h"
7 7
8/*
9#ifdef _WIN32
10#include <basetyps.h>
11#include <unknwn.h>
12#else
13#include "MyWindows.h"
14#endif
15*/
16
17#endif 8#endif
diff --git a/CPP/Common/MyVector.h b/CPP/Common/MyVector.h
index 3417a17..9ee7105 100644
--- a/CPP/Common/MyVector.h
+++ b/CPP/Common/MyVector.h
@@ -1,10 +1,12 @@
1// Common/MyVector.h 1// Common/MyVector.h
2 2
3#ifndef __COMMON_MY_VECTOR_H 3#ifndef ZIP7_INC_COMMON_MY_VECTOR_H
4#define __COMMON_MY_VECTOR_H 4#define ZIP7_INC_COMMON_MY_VECTOR_H
5 5
6#include <string.h> 6#include <string.h>
7 7
8#include "Common.h"
9
8const unsigned k_VectorSizeMax = ((unsigned)1 << 31) - 1; 10const unsigned k_VectorSizeMax = ((unsigned)1 << 31) - 1;
9 11
10template <class T> 12template <class T>
@@ -22,7 +24,7 @@ class CRecordVector
22 void ReAllocForNewCapacity(const unsigned newCapacity) 24 void ReAllocForNewCapacity(const unsigned newCapacity)
23 { 25 {
24 T *p; 26 T *p;
25 MY_ARRAY_NEW(p, T, newCapacity); 27 Z7_ARRAY_NEW(p, T, newCapacity)
26 // p = new T[newCapacity]; 28 // p = new T[newCapacity];
27 if (_size != 0) 29 if (_size != 0)
28 memcpy(p, _items, (size_t)_size * sizeof(T)); 30 memcpy(p, _items, (size_t)_size * sizeof(T));
@@ -53,7 +55,7 @@ public:
53 const unsigned size = v.Size(); 55 const unsigned size = v.Size();
54 if (size != 0) 56 if (size != 0)
55 { 57 {
56 // MY_ARRAY_NEW(_items, T, size) 58 // Z7_ARRAY_NEW(_items, T, size)
57 _items = new T[size]; 59 _items = new T[size];
58 _size = size; 60 _size = size;
59 _capacity = size; 61 _capacity = size;
@@ -68,7 +70,7 @@ public:
68 { 70 {
69 if (size != 0) 71 if (size != 0)
70 { 72 {
71 MY_ARRAY_NEW(_items, T, size) 73 Z7_ARRAY_NEW(_items, T, size)
72 // _items = new T[size]; 74 // _items = new T[size];
73 _capacity = size; 75 _capacity = size;
74 } 76 }
@@ -100,7 +102,7 @@ public:
100 delete []_items; 102 delete []_items;
101 _items = NULL; 103 _items = NULL;
102 _capacity = 0; 104 _capacity = 0;
103 MY_ARRAY_NEW(_items, T, newCapacity) 105 Z7_ARRAY_NEW(_items, T, newCapacity)
104 // _items = new T[newCapacity]; 106 // _items = new T[newCapacity];
105 _capacity = newCapacity; 107 _capacity = newCapacity;
106 } 108 }
@@ -119,7 +121,7 @@ public:
119 T *p = NULL; 121 T *p = NULL;
120 if (_size != 0) 122 if (_size != 0)
121 { 123 {
122 // MY_ARRAY_NEW(p, T, _size) 124 // Z7_ARRAY_NEW(p, T, _size)
123 p = new T[_size]; 125 p = new T[_size];
124 memcpy(p, _items, (size_t)_size * sizeof(T)); 126 memcpy(p, _items, (size_t)_size * sizeof(T));
125 } 127 }
@@ -264,6 +266,8 @@ public:
264 266
265 const T& operator[](unsigned index) const { return _items[index]; } 267 const T& operator[](unsigned index) const { return _items[index]; }
266 T& operator[](unsigned index) { return _items[index]; } 268 T& operator[](unsigned index) { return _items[index]; }
269 const T& operator[](int index) const { return _items[(unsigned)index]; }
270 T& operator[](int index) { return _items[(unsigned)index]; }
267 const T& Front() const { return _items[0]; } 271 const T& Front() const { return _items[0]; }
268 T& Front() { return _items[0]; } 272 T& Front() { return _items[0]; }
269 const T& Back() const { return _items[(size_t)_size - 1]; } 273 const T& Back() const { return _items[(size_t)_size - 1]; }
@@ -497,6 +501,8 @@ public:
497 501
498 const T& operator[](unsigned index) const { return *((T *)_v[index]); } 502 const T& operator[](unsigned index) const { return *((T *)_v[index]); }
499 T& operator[](unsigned index) { return *((T *)_v[index]); } 503 T& operator[](unsigned index) { return *((T *)_v[index]); }
504 const T& operator[](int index) const { return *((T *)_v[(unsigned)index]); }
505 T& operator[](int index) { return *((T *)_v[(unsigned)index]); }
500 const T& Front() const { return operator[](0); } 506 const T& Front() const { return operator[](0); }
501 T& Front() { return operator[](0); } 507 T& Front() { return operator[](0); }
502 const T& Back() const { return *(T *)_v.Back(); } 508 const T& Back() const { return *(T *)_v.Back(); }
@@ -604,6 +610,7 @@ public:
604 delete (T *)_v[index]; 610 delete (T *)_v[index];
605 _v.Delete(index); 611 _v.Delete(index);
606 } 612 }
613 // void Delete(int index) { Delete((unsigned)index); }
607 614
608 /* 615 /*
609 void Delete(unsigned index, unsigned num) 616 void Delete(unsigned index, unsigned num)
diff --git a/CPP/Common/MyWindows.cpp b/CPP/Common/MyWindows.cpp
index 88f312f..ae284eb 100644
--- a/CPP/Common/MyWindows.cpp
+++ b/CPP/Common/MyWindows.cpp
@@ -78,7 +78,7 @@ BSTR SysAllocStringLen(const OLECHAR *s, UINT len)
78BSTR SysAllocString(const OLECHAR *s) 78BSTR SysAllocString(const OLECHAR *s)
79{ 79{
80 if (!s) 80 if (!s)
81 return 0; 81 return NULL;
82 const OLECHAR *s2 = s; 82 const OLECHAR *s2 = s;
83 while (*s2 != 0) 83 while (*s2 != 0)
84 s2++; 84 s2++;
@@ -181,7 +181,7 @@ BOOL WINAPI FileTimeToLocalFileTime(const FILETIME *fileTime, FILETIME *localFil
181{ 181{
182 UInt64 v = GET_TIME_64(fileTime); 182 UInt64 v = GET_TIME_64(fileTime);
183 v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC); 183 v = (UInt64)((Int64)v - (Int64)TIME_GetBias() * TICKS_PER_SEC);
184 SET_FILETIME(localFileTime, v); 184 SET_FILETIME(localFileTime, v)
185 return TRUE; 185 return TRUE;
186} 186}
187 187
@@ -189,7 +189,7 @@ BOOL WINAPI LocalFileTimeToFileTime(const FILETIME *localFileTime, FILETIME *fil
189{ 189{
190 UInt64 v = GET_TIME_64(localFileTime); 190 UInt64 v = GET_TIME_64(localFileTime);
191 v = (UInt64)((Int64)v + (Int64)TIME_GetBias() * TICKS_PER_SEC); 191 v = (UInt64)((Int64)v + (Int64)TIME_GetBias() * TICKS_PER_SEC);
192 SET_FILETIME(fileTime, v); 192 SET_FILETIME(fileTime, v)
193 return TRUE; 193 return TRUE;
194} 194}
195 195
@@ -203,7 +203,7 @@ VOID WINAPI GetSystemTimeAsFileTime(FILETIME *ft)
203 t = tv.tv_sec * (UInt64)TICKS_PER_SEC + TICKS_1601_TO_1970; 203 t = tv.tv_sec * (UInt64)TICKS_PER_SEC + TICKS_1601_TO_1970;
204 t += tv.tv_usec * 10; 204 t += tv.tv_usec * 10;
205 } 205 }
206 SET_FILETIME(ft, t); 206 SET_FILETIME(ft, t)
207} 207}
208*/ 208*/
209 209
diff --git a/CPP/Common/MyWindows.h b/CPP/Common/MyWindows.h
index 15db524..a76e14b 100644
--- a/CPP/Common/MyWindows.h
+++ b/CPP/Common/MyWindows.h
@@ -1,16 +1,25 @@
1// MyWindows.h 1// MyWindows.h
2 2
3#ifndef __MY_WINDOWS_H 3#ifdef Z7_DEFINE_GUID
4#define __MY_WINDOWS_H 4#undef Z7_DEFINE_GUID
5#endif
5 6
6#ifdef _WIN32 7#ifdef INITGUID
8 #define Z7_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
9 EXTERN_C const GUID name; \
10 EXTERN_C const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
11#else
12 #define Z7_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
13 EXTERN_C const GUID name
14#endif
7 15
8#include <Windows.h>
9 16
10#ifdef UNDER_CE 17#ifndef ZIP7_INC_MY_WINDOWS_H
11 #undef VARIANT_TRUE 18#define ZIP7_INC_MY_WINDOWS_H
12 #define VARIANT_TRUE ((VARIANT_BOOL)-1) 19
13#endif 20#ifdef _WIN32
21
22#include "../../C/7zWindows.h"
14 23
15#else // _WIN32 24#else // _WIN32
16 25
@@ -18,11 +27,11 @@
18#include <string.h> 27#include <string.h>
19// #include <stdint.h> // for uintptr_t 28// #include <stdint.h> // for uintptr_t
20 29
30#include "../../C/7zTypes.h"
21#include "MyGuidDef.h" 31#include "MyGuidDef.h"
22 32
23// WINAPI is __stdcall in Windows-MSVC in windef.h 33// WINAPI is __stdcall in Windows-MSVC in windef.h
24#define WINAPI 34#define WINAPI
25#define EXTERN_C MY_EXTERN_C
26 35
27typedef char CHAR; 36typedef char CHAR;
28typedef unsigned char UCHAR; 37typedef unsigned char UCHAR;
@@ -103,31 +112,78 @@ typedef LONG SCODE;
103 112
104#define STDAPI EXTERN_C HRESULT STDAPICALLTYPE 113#define STDAPI EXTERN_C HRESULT STDAPICALLTYPE
105 114
106#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f 115#ifndef DECLSPEC_NOTHROW
107#define STDMETHOD(f) STDMETHOD_(HRESULT, f) 116#define DECLSPEC_NOTHROW Z7_DECLSPEC_NOTHROW
108#define STDMETHODIMP_(type) type STDMETHODCALLTYPE 117#endif
109#define STDMETHODIMP STDMETHODIMP_(HRESULT) 118
119#ifndef DECLSPEC_NOVTABLE
120#define DECLSPEC_NOVTABLE Z7_DECLSPEC_NOVTABLE
121#endif
122
123#ifndef COM_DECLSPEC_NOTHROW
124#ifdef COM_STDMETHOD_CAN_THROW
125 #define COM_DECLSPEC_NOTHROW
126#else
127 #define COM_DECLSPEC_NOTHROW DECLSPEC_NOTHROW
128#endif
129#endif
130
131#define DECLARE_INTERFACE(iface) struct DECLSPEC_NOVTABLE iface
132#define DECLARE_INTERFACE_(iface, baseiface) struct DECLSPEC_NOVTABLE iface : public baseiface
133
134#define STDMETHOD_(t, f) virtual COM_DECLSPEC_NOTHROW t STDMETHODCALLTYPE f
135#define STDMETHOD(f) STDMETHOD_(HRESULT, f)
136#define STDMETHODIMP_(t) COM_DECLSPEC_NOTHROW t STDMETHODCALLTYPE
137#define STDMETHODIMP STDMETHODIMP_(HRESULT)
138
110 139
111#define PURE = 0 140#define PURE = 0
112 141
113#define MIDL_INTERFACE(x) struct 142// #define MIDL_INTERFACE(x) struct
143
114 144
115#ifdef __cplusplus 145#ifdef __cplusplus
116 146
147/*
148 p7zip and 7-Zip before v23 used virtual destructor in IUnknown,
149 if _WIN32 is not defined.
150 It used virtual destructor, because some compilers don't like virtual
151 interfaces without virtual destructor.
152 IUnknown in Windows (_WIN32) doesn't use virtual destructor in IUnknown.
153 We still can define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN here,
154 if we want to be compatible with old plugin interface of p7zip and 7-Zip before v23.
155
156v23:
157 In new 7-Zip v23 we try to be more compatible with original IUnknown from _WIN32.
158 So we do not define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN here,
159*/
160// #define Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN
161
162#ifdef Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN
163#if defined(__clang__)
164#pragma GCC diagnostic ignored "-Winconsistent-missing-destructor-override"
165#endif
166#endif
167
168Z7_PURE_INTERFACES_BEGIN
169
117DEFINE_GUID(IID_IUnknown, 170DEFINE_GUID(IID_IUnknown,
1180x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); 1710x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
119struct IUnknown 172struct IUnknown
120{ 173{
121 STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE; 174 STDMETHOD(QueryInterface) (REFIID iid, void **outObject) =0;
122 STDMETHOD_(ULONG, AddRef)() PURE; 175 STDMETHOD_(ULONG, AddRef)() =0;
123 STDMETHOD_(ULONG, Release)() PURE; 176 STDMETHOD_(ULONG, Release)() =0;
177 #ifdef Z7_USE_VIRTUAL_DESTRUCTOR_IN_IUNKNOWN
124 virtual ~IUnknown() {} 178 virtual ~IUnknown() {}
125 // We use virtual ~IUnknown() here for binary compatibility with 7z.so from p7zip 179 #endif
126}; 180};
127 181
128typedef IUnknown *LPUNKNOWN; 182typedef IUnknown *LPUNKNOWN;
129 183
130#endif 184Z7_PURE_INTERFACES_END
185
186#endif // __cplusplus
131 187
132#define VARIANT_TRUE ((VARIANT_BOOL)-1) 188#define VARIANT_TRUE ((VARIANT_BOOL)-1)
133#define VARIANT_FALSE ((VARIANT_BOOL)0) 189#define VARIANT_FALSE ((VARIANT_BOOL)0)
@@ -197,8 +253,8 @@ typedef PROPVARIANT tagVARIANT;
197typedef tagVARIANT VARIANT; 253typedef tagVARIANT VARIANT;
198typedef VARIANT VARIANTARG; 254typedef VARIANT VARIANTARG;
199 255
200MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop); 256EXTERN_C HRESULT VariantClear(VARIANTARG *prop);
201MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, const VARIANTARG *src); 257EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, const VARIANTARG *src);
202 258
203typedef struct tagSTATPROPSTG 259typedef struct tagSTATPROPSTG
204{ 260{
@@ -207,19 +263,19 @@ typedef struct tagSTATPROPSTG
207 VARTYPE vt; 263 VARTYPE vt;
208} STATPROPSTG; 264} STATPROPSTG;
209 265
210MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len); 266EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len);
211MY_EXTERN_C BSTR SysAllocStringLen(const OLECHAR *sz, UINT len); 267EXTERN_C BSTR SysAllocStringLen(const OLECHAR *sz, UINT len);
212MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz); 268EXTERN_C BSTR SysAllocString(const OLECHAR *sz);
213MY_EXTERN_C void SysFreeString(BSTR bstr); 269EXTERN_C void SysFreeString(BSTR bstr);
214MY_EXTERN_C UINT SysStringByteLen(BSTR bstr); 270EXTERN_C UINT SysStringByteLen(BSTR bstr);
215MY_EXTERN_C UINT SysStringLen(BSTR bstr); 271EXTERN_C UINT SysStringLen(BSTR bstr);
216 272
217MY_EXTERN_C DWORD GetLastError(); 273EXTERN_C DWORD GetLastError();
218MY_EXTERN_C void SetLastError(DWORD dwCode); 274EXTERN_C void SetLastError(DWORD dwCode);
219MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2); 275EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2);
220 276
221MY_EXTERN_C DWORD GetCurrentThreadId(); 277EXTERN_C DWORD GetCurrentThreadId();
222MY_EXTERN_C DWORD GetCurrentProcessId(); 278EXTERN_C DWORD GetCurrentProcessId();
223 279
224#define MAX_PATH 1024 280#define MAX_PATH 1024
225 281
diff --git a/CPP/Common/MyXml.cpp b/CPP/Common/MyXml.cpp
index e014518..a879d34 100644
--- a/CPP/Common/MyXml.cpp
+++ b/CPP/Common/MyXml.cpp
@@ -81,7 +81,7 @@ AString CXmlItem::GetSubStringForTag(const char *tag) const
81 81
82const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels) 82const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
83{ 83{
84 SKIP_SPACES(s); 84 SKIP_SPACES(s)
85 85
86 const char *beg = s; 86 const char *beg = s;
87 for (;;) 87 for (;;)
@@ -102,7 +102,7 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
102 IsTag = true; 102 IsTag = true;
103 103
104 s++; 104 s++;
105 SKIP_SPACES(s); 105 SKIP_SPACES(s)
106 106
107 beg = s; 107 beg = s;
108 for (;; s++) 108 for (;; s++)
@@ -115,11 +115,11 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
115 for (;;) 115 for (;;)
116 { 116 {
117 beg = s; 117 beg = s;
118 SKIP_SPACES(s); 118 SKIP_SPACES(s)
119 if (*s == '/') 119 if (*s == '/')
120 { 120 {
121 s++; 121 s++;
122 // SKIP_SPACES(s); 122 // SKIP_SPACES(s)
123 if (*s != '>') 123 if (*s != '>')
124 return NULL; 124 return NULL;
125 return s + 1; 125 return s + 1;
@@ -132,7 +132,7 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
132 SubItems.Clear(); 132 SubItems.Clear();
133 for (;;) 133 for (;;)
134 { 134 {
135 SKIP_SPACES(s); 135 SKIP_SPACES(s)
136 if (s[0] == '<' && s[1] == '/') 136 if (s[0] == '<' && s[1] == '/')
137 break; 137 break;
138 CXmlItem &item = SubItems.AddNew(); 138 CXmlItem &item = SubItems.AddNew();
@@ -168,11 +168,11 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
168 return NULL; 168 return NULL;
169 prop.Name.SetFrom(beg, (unsigned)(s - beg)); 169 prop.Name.SetFrom(beg, (unsigned)(s - beg));
170 170
171 SKIP_SPACES(s); 171 SKIP_SPACES(s)
172 if (*s != '=') 172 if (*s != '=')
173 return NULL; 173 return NULL;
174 s++; 174 s++;
175 SKIP_SPACES(s); 175 SKIP_SPACES(s)
176 if (*s != '\"') 176 if (*s != '\"')
177 return NULL; 177 return NULL;
178 s++; 178 s++;
@@ -194,7 +194,7 @@ const char * CXmlItem::ParseItem(const char *s, int numAllowedLevels)
194 194
195static const char * SkipHeader(const char *s, const char *startString, const char *endString) 195static const char * SkipHeader(const char *s, const char *startString, const char *endString)
196{ 196{
197 SKIP_SPACES(s); 197 SKIP_SPACES(s)
198 if (IsString1PrefixedByString2(s, startString)) 198 if (IsString1PrefixedByString2(s, startString))
199 { 199 {
200 s = strstr(s, endString); 200 s = strstr(s, endString);
@@ -215,7 +215,7 @@ void CXmlItem::AppendTo(AString &s) const
215 FOR_VECTOR (i, Props) 215 FOR_VECTOR (i, Props)
216 { 216 {
217 const CXmlProp &prop = Props[i]; 217 const CXmlProp &prop = Props[i];
218 s += ' '; 218 s.Add_Space();
219 s += prop.Name; 219 s += prop.Name;
220 s += '='; 220 s += '=';
221 s += '\"'; 221 s += '\"';
@@ -228,7 +228,7 @@ void CXmlItem::AppendTo(AString &s) const
228 { 228 {
229 const CXmlItem &item = SubItems[i]; 229 const CXmlItem &item = SubItems[i];
230 if (i != 0 && !SubItems[i - 1].IsTag) 230 if (i != 0 && !SubItems[i - 1].IsTag)
231 s += ' '; 231 s.Add_Space();
232 item.AppendTo(s); 232 item.AppendTo(s);
233 } 233 }
234 if (IsTag) 234 if (IsTag)
@@ -248,7 +248,7 @@ bool CXml::Parse(const char *s)
248 s = Root.ParseItem(s, 1000); 248 s = Root.ParseItem(s, 1000);
249 if (!s || !Root.IsTag) 249 if (!s || !Root.IsTag)
250 return false; 250 return false;
251 SKIP_SPACES(s); 251 SKIP_SPACES(s)
252 return *s == 0; 252 return *s == 0;
253} 253}
254 254
diff --git a/CPP/Common/MyXml.h b/CPP/Common/MyXml.h
index 00b7113..5362602 100644
--- a/CPP/Common/MyXml.h
+++ b/CPP/Common/MyXml.h
@@ -1,7 +1,7 @@
1// MyXml.h 1// MyXml.h
2 2
3#ifndef __MY_XML_H 3#ifndef ZIP7_INC_MY_XML_H
4#define __MY_XML_H 4#define ZIP7_INC_MY_XML_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7 7
diff --git a/CPP/Common/NewHandler.cpp b/CPP/Common/NewHandler.cpp
index 65ef41d..c95833e 100644
--- a/CPP/Common/NewHandler.cpp
+++ b/CPP/Common/NewHandler.cpp
@@ -10,21 +10,23 @@
10 10
11#ifndef DEBUG_MEMORY_LEAK 11#ifndef DEBUG_MEMORY_LEAK
12 12
13#ifdef _7ZIP_REDEFINE_OPERATOR_NEW 13#ifdef Z7_REDEFINE_OPERATOR_NEW
14 14
15/* 15/*
16void * my_new(size_t size) 16void * my_new(size_t size)
17{ 17{
18 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); 18 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
19 if (size == 0)
20 size = 1;
19 void *p = ::malloc(size); 21 void *p = ::malloc(size);
20 if (p == 0) 22 if (!p)
21 throw CNewException(); 23 throw CNewException();
22 return p; 24 return p;
23} 25}
24 26
25void my_delete(void *p) throw() 27void my_delete(void *p) throw()
26{ 28{
27 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); 29 // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p);
28 ::free(p); 30 ::free(p);
29} 31}
30 32
@@ -44,9 +46,21 @@ __cdecl
44#endif 46#endif
45operator new(size_t size) 47operator new(size_t size)
46{ 48{
49 /* by C++ specification:
50 if (size == 0), operator new(size) returns non_NULL pointer.
51 If (operator new(0) returns NULL), it's out of specification.
52 but some calling code can work correctly even in this case too. */
53 // if (size == 0) return NULL; // for debug only. don't use it
54
55 /* malloc(0) returns non_NULL in main compilers, as we need here.
56 But specification also allows malloc(0) to return NULL.
57 So we change (size=0) to (size=1) here to get real non_NULL pointer */
58 if (size == 0)
59 size = 1;
47 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); 60 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
61 // void *p = ::MyAlloc(size); // note: MyAlloc(0) returns NULL
48 void *p = ::malloc(size); 62 void *p = ::malloc(size);
49 if (p == 0) 63 if (!p)
50 throw CNewException(); 64 throw CNewException();
51 return p; 65 return p;
52} 66}
@@ -57,7 +71,8 @@ __cdecl
57#endif 71#endif
58operator delete(void *p) throw() 72operator delete(void *p) throw()
59{ 73{
60 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); 74 // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p);
75 // MyFree(p);
61 ::free(p); 76 ::free(p);
62} 77}
63 78
@@ -69,8 +84,10 @@ __cdecl
69operator new[](size_t size) 84operator new[](size_t size)
70{ 85{
71 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); 86 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
87 if (size == 0)
88 size = 1;
72 void *p = ::malloc(size); 89 void *p = ::malloc(size);
73 if (p == 0) 90 if (!p)
74 throw CNewException(); 91 throw CNewException();
75 return p; 92 return p;
76} 93}
@@ -81,7 +98,7 @@ __cdecl
81#endif 98#endif
82operator delete[](void *p) throw() 99operator delete[](void *p) throw()
83{ 100{
84 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p); 101 // if (!p) return; ::HeapFree(::GetProcessHeap(), 0, p);
85 ::free(p); 102 ::free(p);
86} 103}
87*/ 104*/
@@ -93,16 +110,43 @@ operator delete[](void *p) throw()
93#include <stdio.h> 110#include <stdio.h>
94 111
95// #pragma init_seg(lib) 112// #pragma init_seg(lib)
113/*
96const int kDebugSize = 1000000; 114const int kDebugSize = 1000000;
97static void *a[kDebugSize]; 115static void *a[kDebugSize];
98static int index = 0; 116static int g_index = 0;
117
118class CC
119{
120public:
121 CC()
122 {
123 for (int i = 0; i < kDebugSize; i++)
124 a[i] = 0;
125 }
126 ~CC()
127 {
128 printf("\nDestructor: %d\n", numAllocs);
129 for (int i = 0; i < kDebugSize; i++)
130 if (a[i] != 0)
131 return;
132 }
133} g_CC;
134*/
99 135
136#ifdef _WIN32
100static bool wasInit = false; 137static bool wasInit = false;
101static CRITICAL_SECTION cs; 138static CRITICAL_SECTION cs;
139#endif
102 140
103static int numAllocs = 0; 141static int numAllocs = 0;
104void * __cdecl operator new(size_t size) 142
143void *
144#ifdef _MSC_VER
145__cdecl
146#endif
147operator new(size_t size)
105{ 148{
149 #ifdef _WIN32
106 if (!wasInit) 150 if (!wasInit)
107 { 151 {
108 InitializeCriticalSection(&cs); 152 InitializeCriticalSection(&cs);
@@ -114,52 +158,126 @@ void * __cdecl operator new(size_t size)
114 int loc = numAllocs; 158 int loc = numAllocs;
115 void *p = HeapAlloc(GetProcessHeap(), 0, size); 159 void *p = HeapAlloc(GetProcessHeap(), 0, size);
116 /* 160 /*
117 if (index < kDebugSize) 161 if (g_index < kDebugSize)
118 { 162 {
119 a[index] = p; 163 a[g_index] = p;
120 index++; 164 g_index++;
121 } 165 }
122 */ 166 */
123 printf("Alloc %6d, size = %8u\n", loc, (unsigned)size); 167 printf("Alloc %6d, size = %8u\n", loc, (unsigned)size);
124 LeaveCriticalSection(&cs); 168 LeaveCriticalSection(&cs);
125 if (p == 0) 169 if (!p)
126 throw CNewException(); 170 throw CNewException();
127 return p; 171 return p;
128} 172 #else
129 173 numAllocs++;
130class CC 174 int loc = numAllocs;
131{ 175 if (size == 0)
132public: 176 size = 1;
133 CC() 177 void *p = malloc(size);
134 { 178 /*
135 for (int i = 0; i < kDebugSize; i++) 179 if (g_index < kDebugSize)
136 a[i] = 0;
137 }
138 ~CC()
139 { 180 {
140 printf("\nDestructor: %d\n", numAllocs); 181 a[g_index] = p;
141 for (int i = 0; i < kDebugSize; i++) 182 g_index++;
142 if (a[i] != 0)
143 return;
144 } 183 }
145} g_CC; 184 */
146 185 printf("Alloc %6d, size = %8u\n", loc, (unsigned)size);
186 if (!p)
187 throw CNewException();
188 return p;
189 #endif
190}
147 191
148void __cdecl operator delete(void *p) 192void
193#ifdef _MSC_VER
194__cdecl
195#endif
196operator delete(void *p) throw()
149{ 197{
150 if (p == 0) 198 if (!p)
151 return; 199 return;
200 #ifdef _WIN32
152 EnterCriticalSection(&cs); 201 EnterCriticalSection(&cs);
153 /* 202 /*
154 for (int i = 0; i < index; i++) 203 for (int i = 0; i < g_index; i++)
155 if (a[i] == p) 204 if (a[i] == p)
156 a[i] = 0; 205 a[i] = 0;
157 */ 206 */
158 HeapFree(GetProcessHeap(), 0, p); 207 HeapFree(GetProcessHeap(), 0, p);
208 if (numAllocs == 0)
209 numAllocs = numAllocs; // ERROR
159 numAllocs--; 210 numAllocs--;
211 if (numAllocs == 0)
212 numAllocs = numAllocs; // OK: all objects were deleted
160 printf("Free %d\n", numAllocs); 213 printf("Free %d\n", numAllocs);
161 LeaveCriticalSection(&cs); 214 LeaveCriticalSection(&cs);
215 #else
216 free(p);
217 numAllocs--;
218 printf("Free %d\n", numAllocs);
219 #endif
220}
221
222/*
223void *
224#ifdef _MSC_VER
225__cdecl
226#endif
227operator new[](size_t size)
228{
229 printf("operator_new[] : ");
230 return operator new(size);
231}
232
233void
234#ifdef _MSC_VER
235__cdecl
236#endif
237operator delete(void *p, size_t sz) throw();
238
239void
240#ifdef _MSC_VER
241__cdecl
242#endif
243operator delete(void *p, size_t sz) throw()
244{
245 if (!p)
246 return;
247 printf("operator_delete_size : size=%d : ", (unsigned)sz);
248 operator delete(p);
249}
250
251void
252#ifdef _MSC_VER
253__cdecl
254#endif
255operator delete[](void *p) throw()
256{
257 if (!p)
258 return;
259 printf("operator_delete[] : ");
260 operator delete(p);
261}
262
263void
264#ifdef _MSC_VER
265__cdecl
266#endif
267operator delete[](void *p, size_t sz) throw();
268
269void
270#ifdef _MSC_VER
271__cdecl
272#endif
273operator delete[](void *p, size_t sz) throw()
274{
275 if (!p)
276 return;
277 printf("operator_delete_size[] : size=%d : ", (unsigned)sz);
278 operator delete(p);
162} 279}
280*/
163 281
164#endif 282#endif
165 283
diff --git a/CPP/Common/NewHandler.h b/CPP/Common/NewHandler.h
index aedeca6..50f6d0a 100644
--- a/CPP/Common/NewHandler.h
+++ b/CPP/Common/NewHandler.h
@@ -1,7 +1,7 @@
1// Common/NewHandler.h 1// Common/NewHandler.h
2 2
3#ifndef __COMMON_NEW_HANDLER_H 3#ifndef ZIP7_INC_COMMON_NEW_HANDLER_H
4#define __COMMON_NEW_HANDLER_H 4#define ZIP7_INC_COMMON_NEW_HANDLER_H
5 5
6/* 6/*
7NewHandler.h and NewHandler.cpp allows to solve problem with compilers that 7NewHandler.h and NewHandler.cpp allows to solve problem with compilers that
@@ -10,6 +10,16 @@ don't throw exception in operator new().
10This file must be included before any code that uses operators new() or delete() 10This file must be included before any code that uses operators new() or delete()
11and you must compile and link "NewHandler.cpp", if you use some old MSVC compiler. 11and you must compile and link "NewHandler.cpp", if you use some old MSVC compiler.
12 12
13DOCs:
14 Since ISO C++98, operator new throws std::bad_alloc when memory allocation fails.
15 MSVC 6.0 returned a null pointer on an allocation failure.
16 Beginning in VS2002, operator new conforms to the standard and throws on failure.
17
18 By default, the compiler also generates defensive null checks to prevent
19 these older-style allocators from causing an immediate crash on failure.
20 The /Zc:throwingNew option tells the compiler to leave out these null checks,
21 on the assumption that all linked memory allocators conform to the standard.
22
13The operator new() in some MSVC versions doesn't throw exception std::bad_alloc. 23The operator new() in some MSVC versions doesn't throw exception std::bad_alloc.
14MSVC 6.0 (_MSC_VER == 1200) doesn't throw exception. 24MSVC 6.0 (_MSC_VER == 1200) doesn't throw exception.
15The code produced by some another MSVC compilers also can be linked 25The code produced by some another MSVC compilers also can be linked
@@ -36,13 +46,13 @@ void my_delete(void *p) throw();
36#endif 46#endif
37 47
38 48
39#if defined(_MSC_VER) && (_MSC_VER < 1900) 49#if defined(_MSC_VER) && (_MSC_VER < 1600)
40 // If you want to use default operator new(), you can disable the following line 50 // If you want to use default operator new(), you can disable the following line
41 #define _7ZIP_REDEFINE_OPERATOR_NEW 51 #define Z7_REDEFINE_OPERATOR_NEW
42#endif 52#endif
43 53
44 54
45#ifdef _7ZIP_REDEFINE_OPERATOR_NEW 55#ifdef Z7_REDEFINE_OPERATOR_NEW
46 56
47// std::bad_alloc can require additional DLL dependency. 57// std::bad_alloc can require additional DLL dependency.
48// So we don't define CNewException as std::bad_alloc here. 58// So we don't define CNewException as std::bad_alloc here.
diff --git a/CPP/Common/Random.h b/CPP/Common/Random.h
index e784e98..283869e 100644
--- a/CPP/Common/Random.h
+++ b/CPP/Common/Random.h
@@ -1,7 +1,7 @@
1// Common/Random.h 1// Common/Random.h
2 2
3#ifndef __COMMON_RANDOM_H 3#ifndef ZIP7_INC_COMMON_RANDOM_H
4#define __COMMON_RANDOM_H 4#define ZIP7_INC_COMMON_RANDOM_H
5 5
6class CRandom 6class CRandom
7{ 7{
diff --git a/CPP/Common/Sha1Reg.cpp b/CPP/Common/Sha1Reg.cpp
index 0cb2baf..64eef34 100644
--- a/CPP/Common/Sha1Reg.cpp
+++ b/CPP/Common/Sha1Reg.cpp
@@ -9,13 +9,14 @@
9 9
10#include "../7zip/Common/RegisterCodec.h" 10#include "../7zip/Common/RegisterCodec.h"
11 11
12class CSha1Hasher: 12Z7_CLASS_IMP_COM_2(
13 public IHasher, 13 CSha1Hasher
14 public ICompressSetCoderProperties, 14 , IHasher
15 public CMyUnknownImp 15 , ICompressSetCoderProperties
16{ 16)
17 CAlignedBuffer _buf; 17 CAlignedBuffer1 _buf;
18 Byte mtDummy[1 << 7]; 18public:
19 Byte _mtDummy[1 << 7];
19 20
20 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_buf; } 21 CSha1 *Sha() { return (CSha1 *)(void *)(Byte *)_buf; }
21public: 22public:
@@ -25,36 +26,32 @@ public:
25 Sha1_SetFunction(Sha(), 0); 26 Sha1_SetFunction(Sha(), 0);
26 Sha1_InitState(Sha()); 27 Sha1_InitState(Sha());
27 } 28 }
28
29 MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties)
30 INTERFACE_IHasher(;)
31 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
32}; 29};
33 30
34STDMETHODIMP_(void) CSha1Hasher::Init() throw() 31Z7_COM7F_IMF2(void, CSha1Hasher::Init())
35{ 32{
36 Sha1_InitState(Sha()); 33 Sha1_InitState(Sha());
37} 34}
38 35
39STDMETHODIMP_(void) CSha1Hasher::Update(const void *data, UInt32 size) throw() 36Z7_COM7F_IMF2(void, CSha1Hasher::Update(const void *data, UInt32 size))
40{ 37{
41 Sha1_Update(Sha(), (const Byte *)data, size); 38 Sha1_Update(Sha(), (const Byte *)data, size);
42} 39}
43 40
44STDMETHODIMP_(void) CSha1Hasher::Final(Byte *digest) throw() 41Z7_COM7F_IMF2(void, CSha1Hasher::Final(Byte *digest))
45{ 42{
46 Sha1_Final(Sha(), digest); 43 Sha1_Final(Sha(), digest);
47} 44}
48 45
49 46
50STDMETHODIMP CSha1Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 47Z7_COM7F_IMF(CSha1Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
51{ 48{
52 unsigned algo = 0; 49 unsigned algo = 0;
53 for (UInt32 i = 0; i < numProps; i++) 50 for (UInt32 i = 0; i < numProps; i++)
54 { 51 {
55 const PROPVARIANT &prop = coderProps[i];
56 if (propIDs[i] == NCoderPropID::kDefaultProp) 52 if (propIDs[i] == NCoderPropID::kDefaultProp)
57 { 53 {
54 const PROPVARIANT &prop = coderProps[i];
58 if (prop.vt != VT_UI4) 55 if (prop.vt != VT_UI4)
59 return E_INVALIDARG; 56 return E_INVALIDARG;
60 if (prop.ulVal > 2) 57 if (prop.ulVal > 2)
diff --git a/CPP/Common/Sha256Reg.cpp b/CPP/Common/Sha256Reg.cpp
index 5f3a35b..b5689c4 100644
--- a/CPP/Common/Sha256Reg.cpp
+++ b/CPP/Common/Sha256Reg.cpp
@@ -9,13 +9,14 @@
9 9
10#include "../7zip/Common/RegisterCodec.h" 10#include "../7zip/Common/RegisterCodec.h"
11 11
12class CSha256Hasher: 12Z7_CLASS_IMP_COM_2(
13 public IHasher, 13 CSha256Hasher
14 public ICompressSetCoderProperties, 14 , IHasher
15 public CMyUnknownImp 15 , ICompressSetCoderProperties
16{ 16)
17 CAlignedBuffer _buf; 17 CAlignedBuffer1 _buf;
18 Byte mtDummy[1 << 7]; 18public:
19 Byte _mtDummy[1 << 7];
19 20
20 CSha256 *Sha() { return (CSha256 *)(void *)(Byte *)_buf; } 21 CSha256 *Sha() { return (CSha256 *)(void *)(Byte *)_buf; }
21public: 22public:
@@ -25,36 +26,32 @@ public:
25 Sha256_SetFunction(Sha(), 0); 26 Sha256_SetFunction(Sha(), 0);
26 Sha256_InitState(Sha()); 27 Sha256_InitState(Sha());
27 } 28 }
28
29 MY_UNKNOWN_IMP2(IHasher, ICompressSetCoderProperties)
30 INTERFACE_IHasher(;)
31 STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
32}; 29};
33 30
34STDMETHODIMP_(void) CSha256Hasher::Init() throw() 31Z7_COM7F_IMF2(void, CSha256Hasher::Init())
35{ 32{
36 Sha256_InitState(Sha()); 33 Sha256_InitState(Sha());
37} 34}
38 35
39STDMETHODIMP_(void) CSha256Hasher::Update(const void *data, UInt32 size) throw() 36Z7_COM7F_IMF2(void, CSha256Hasher::Update(const void *data, UInt32 size))
40{ 37{
41 Sha256_Update(Sha(), (const Byte *)data, size); 38 Sha256_Update(Sha(), (const Byte *)data, size);
42} 39}
43 40
44STDMETHODIMP_(void) CSha256Hasher::Final(Byte *digest) throw() 41Z7_COM7F_IMF2(void, CSha256Hasher::Final(Byte *digest))
45{ 42{
46 Sha256_Final(Sha(), digest); 43 Sha256_Final(Sha(), digest);
47} 44}
48 45
49 46
50STDMETHODIMP CSha256Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps) 47Z7_COM7F_IMF(CSha256Hasher::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps))
51{ 48{
52 unsigned algo = 0; 49 unsigned algo = 0;
53 for (UInt32 i = 0; i < numProps; i++) 50 for (UInt32 i = 0; i < numProps; i++)
54 { 51 {
55 const PROPVARIANT &prop = coderProps[i];
56 if (propIDs[i] == NCoderPropID::kDefaultProp) 52 if (propIDs[i] == NCoderPropID::kDefaultProp)
57 { 53 {
54 const PROPVARIANT &prop = coderProps[i];
58 if (prop.vt != VT_UI4) 55 if (prop.vt != VT_UI4)
59 return E_INVALIDARG; 56 return E_INVALIDARG;
60 if (prop.ulVal > 2) 57 if (prop.ulVal > 2)
diff --git a/CPP/Common/StdAfx.h b/CPP/Common/StdAfx.h
index 420f5c3..a5228b0 100644
--- a/CPP/Common/StdAfx.h
+++ b/CPP/Common/StdAfx.h
@@ -1,7 +1,7 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#include "Common.h" 6#include "Common.h"
7 7
diff --git a/CPP/Common/StdInStream.cpp b/CPP/Common/StdInStream.cpp
index abad34b..7b209f1 100644
--- a/CPP/Common/StdInStream.cpp
+++ b/CPP/Common/StdInStream.cpp
@@ -14,10 +14,12 @@
14// #define kReadErrorMessage "Error reading input stream" 14// #define kReadErrorMessage "Error reading input stream"
15// #define kIllegalCharMessage "Illegal zero character in input stream" 15// #define kIllegalCharMessage "Illegal zero character in input stream"
16 16
17#define kFileOpenMode TEXT("r")
18 17
19CStdInStream g_StdIn(stdin); 18CStdInStream g_StdIn(stdin);
20 19
20/*
21#define kFileOpenMode TEXT("r")
22
21bool CStdInStream::Open(LPCTSTR fileName) throw() 23bool CStdInStream::Open(LPCTSTR fileName) throw()
22{ 24{
23 Close(); 25 Close();
@@ -39,6 +41,7 @@ bool CStdInStream::Close() throw()
39 _streamIsOpen = (fclose(_stream) != 0); 41 _streamIsOpen = (fclose(_stream) != 0);
40 return !_streamIsOpen; 42 return !_streamIsOpen;
41} 43}
44*/
42 45
43bool CStdInStream::ScanAStringUntilNewLine(AString &s) 46bool CStdInStream::ScanAStringUntilNewLine(AString &s)
44{ 47{
diff --git a/CPP/Common/StdInStream.h b/CPP/Common/StdInStream.h
index 71578eb..81ca3bf 100644
--- a/CPP/Common/StdInStream.h
+++ b/CPP/Common/StdInStream.h
@@ -1,7 +1,7 @@
1// Common/StdInStream.h 1// Common/StdInStream.h
2 2
3#ifndef __COMMON_STD_IN_STREAM_H 3#ifndef ZIP7_INC_COMMON_STD_IN_STREAM_H
4#define __COMMON_STD_IN_STREAM_H 4#define ZIP7_INC_COMMON_STD_IN_STREAM_H
5 5
6#include <stdio.h> 6#include <stdio.h>
7 7
@@ -11,20 +11,22 @@
11class CStdInStream 11class CStdInStream
12{ 12{
13 FILE *_stream; 13 FILE *_stream;
14 bool _streamIsOpen; 14 // bool _streamIsOpen;
15public: 15public:
16 int CodePage; 16 int CodePage;
17 17
18 CStdInStream(FILE *stream = NULL): 18 CStdInStream(FILE *stream = NULL):
19 _stream(stream), 19 _stream(stream),
20 _streamIsOpen(false), 20 // _streamIsOpen(false),
21 CodePage(-1) 21 CodePage(-1)
22 {}; 22 {}
23 23
24 /*
24 ~CStdInStream() { Close(); } 25 ~CStdInStream() { Close(); }
25 26
26 bool Open(LPCTSTR fileName) throw(); 27 bool Open(LPCTSTR fileName) throw();
27 bool Close() throw(); 28 bool Close() throw();
29 */
28 30
29 // returns: 31 // returns:
30 // false, if ZERO character in stream 32 // false, if ZERO character in stream
diff --git a/CPP/Common/StdOutStream.cpp b/CPP/Common/StdOutStream.cpp
index 40799e2..cfa5fde 100644
--- a/CPP/Common/StdOutStream.cpp
+++ b/CPP/Common/StdOutStream.cpp
@@ -11,11 +11,12 @@
11#include "StringConvert.h" 11#include "StringConvert.h"
12#include "UTFConvert.h" 12#include "UTFConvert.h"
13 13
14#define kFileOpenMode "wt"
15
16CStdOutStream g_StdOut(stdout); 14CStdOutStream g_StdOut(stdout);
17CStdOutStream g_StdErr(stderr); 15CStdOutStream g_StdErr(stderr);
18 16
17/*
18// #define kFileOpenMode "wt"
19
19bool CStdOutStream::Open(const char *fileName) throw() 20bool CStdOutStream::Open(const char *fileName) throw()
20{ 21{
21 Close(); 22 Close();
@@ -34,6 +35,7 @@ bool CStdOutStream::Close() throw()
34 _streamIsOpen = false; 35 _streamIsOpen = false;
35 return true; 36 return true;
36} 37}
38*/
37 39
38bool CStdOutStream::Flush() throw() 40bool CStdOutStream::Flush() throw()
39{ 41{
@@ -73,7 +75,7 @@ void CStdOutStream::Convert_UString_to_AString(const UString &src, AString &dest
73 75
74static const wchar_t kReplaceChar = '_'; 76static const wchar_t kReplaceChar = '_';
75 77
76void CStdOutStream::Normalize_UString__LF_Allowed(UString &s) 78void CStdOutStream::Normalize_UString_LF_Allowed(UString &s)
77{ 79{
78 unsigned len = s.Len(); 80 unsigned len = s.Len();
79 wchar_t *d = s.GetBuf(); 81 wchar_t *d = s.GetBuf();
diff --git a/CPP/Common/StdOutStream.h b/CPP/Common/StdOutStream.h
index 93f1dfa..bd15d7c 100644
--- a/CPP/Common/StdOutStream.h
+++ b/CPP/Common/StdOutStream.h
@@ -1,7 +1,7 @@
1// Common/StdOutStream.h 1// Common/StdOutStream.h
2 2
3#ifndef __COMMON_STD_OUT_STREAM_H 3#ifndef ZIP7_INC_COMMON_STD_OUT_STREAM_H
4#define __COMMON_STD_OUT_STREAM_H 4#define ZIP7_INC_COMMON_STD_OUT_STREAM_H
5 5
6#include <stdio.h> 6#include <stdio.h>
7 7
@@ -11,26 +11,28 @@
11class CStdOutStream 11class CStdOutStream
12{ 12{
13 FILE *_stream; 13 FILE *_stream;
14 bool _streamIsOpen; 14 // bool _streamIsOpen;
15public: 15public:
16 bool IsTerminalMode; 16 bool IsTerminalMode;
17 int CodePage; 17 int CodePage;
18 18
19 CStdOutStream(FILE *stream = 0): 19 CStdOutStream(FILE *stream = NULL):
20 _stream(stream), 20 _stream(stream),
21 _streamIsOpen(false), 21 // _streamIsOpen(false),
22 IsTerminalMode(false), 22 IsTerminalMode(false),
23 CodePage(-1) 23 CodePage(-1)
24 {}; 24 {}
25 25
26 ~CStdOutStream() { Close(); } 26 // ~CStdOutStream() { Close(); }
27 27
28 // void AttachStdStream(FILE *stream) { _stream = stream; _streamIsOpen = false; } 28 // void AttachStdStream(FILE *stream) { _stream = stream; _streamIsOpen = false; }
29 // bool IsDefined() const { return _stream != NULL; } 29 // bool IsDefined() const { return _stream != NULL; }
30 30
31 operator FILE *() { return _stream; } 31 operator FILE *() { return _stream; }
32 /*
32 bool Open(const char *fileName) throw(); 33 bool Open(const char *fileName) throw();
33 bool Close() throw(); 34 bool Close() throw();
35 */
34 bool Flush() throw(); 36 bool Flush() throw();
35 37
36 CStdOutStream & operator<<(CStdOutStream & (* func)(CStdOutStream &)) 38 CStdOutStream & operator<<(CStdOutStream & (* func)(CStdOutStream &))
@@ -60,7 +62,7 @@ public:
60 void PrintUString(const UString &s, AString &temp); 62 void PrintUString(const UString &s, AString &temp);
61 void Convert_UString_to_AString(const UString &src, AString &dest); 63 void Convert_UString_to_AString(const UString &src, AString &dest);
62 64
63 void Normalize_UString__LF_Allowed(UString &s); 65 void Normalize_UString_LF_Allowed(UString &s);
64 void Normalize_UString(UString &s); 66 void Normalize_UString(UString &s);
65 67
66 void NormalizePrint_UString(const UString &s, UString &tempU, AString &tempA); 68 void NormalizePrint_UString(const UString &s, UString &tempU, AString &tempA);
diff --git a/CPP/Common/StringConvert.cpp b/CPP/Common/StringConvert.cpp
index c0bde0f..f25396a 100644
--- a/CPP/Common/StringConvert.cpp
+++ b/CPP/Common/StringConvert.cpp
@@ -534,6 +534,7 @@ AString UnicodeStringToMultiByte(const UString &src, UINT codePage)
534 534
535 535
536 536
537#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE)
537 538
538#ifdef _WIN32 539#ifdef _WIN32
539#define U_to_A(a, b, c) UnicodeStringToMultiByte2 540#define U_to_A(a, b, c) UnicodeStringToMultiByte2
@@ -544,8 +545,6 @@ AString UnicodeStringToMultiByte(const UString &src, UINT codePage)
544// #define A_to_U(a, b, c) MultiByteToUnicodeString2_Native(a, b) 545// #define A_to_U(a, b, c) MultiByteToUnicodeString2_Native(a, b)
545#endif 546#endif
546 547
547#if !defined(_WIN32) || defined(ENV_HAVE_LOCALE)
548
549bool IsNativeUTF8() 548bool IsNativeUTF8()
550{ 549{
551 UString u; 550 UString u;
diff --git a/CPP/Common/StringConvert.h b/CPP/Common/StringConvert.h
index 865c025..2092a2d 100644
--- a/CPP/Common/StringConvert.h
+++ b/CPP/Common/StringConvert.h
@@ -1,7 +1,7 @@
1// Common/StringConvert.h 1// Common/StringConvert.h
2 2
3#ifndef __COMMON_STRING_CONVERT_H 3#ifndef ZIP7_INC_COMMON_STRING_CONVERT_H
4#define __COMMON_STRING_CONVERT_H 4#define ZIP7_INC_COMMON_STRING_CONVERT_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7#include "MyWindows.h" 7#include "MyWindows.h"
diff --git a/CPP/Common/StringToInt.h b/CPP/Common/StringToInt.h
index 4057e49..c9dce7d 100644
--- a/CPP/Common/StringToInt.h
+++ b/CPP/Common/StringToInt.h
@@ -1,7 +1,7 @@
1// Common/StringToInt.h 1// Common/StringToInt.h
2 2
3#ifndef __COMMON_STRING_TO_INT_H 3#ifndef ZIP7_INC_COMMON_STRING_TO_INT_H
4#define __COMMON_STRING_TO_INT_H 4#define ZIP7_INC_COMMON_STRING_TO_INT_H
5 5
6#include "MyTypes.h" 6#include "MyTypes.h"
7 7
diff --git a/CPP/Common/TextConfig.cpp b/CPP/Common/TextConfig.cpp
index 1428aab..d3e561c 100644
--- a/CPP/Common/TextConfig.cpp
+++ b/CPP/Common/TextConfig.cpp
@@ -15,7 +15,7 @@ static AString GetIDString(const char *s, unsigned &finishPos)
15 AString result; 15 AString result;
16 for (finishPos = 0; ; finishPos++) 16 for (finishPos = 0; ; finishPos++)
17 { 17 {
18 char c = s[finishPos]; 18 const char c = s[finishPos];
19 if (IsDelimitChar(c) || c == '=') 19 if (IsDelimitChar(c) || c == '=')
20 break; 20 break;
21 result += c; 21 result += c;
@@ -35,7 +35,7 @@ static bool SkipSpaces(const AString &s, unsigned &pos)
35{ 35{
36 for (; pos < s.Len(); pos++) 36 for (; pos < s.Len(); pos++)
37 { 37 {
38 char c = s[pos]; 38 const char c = s[pos];
39 if (!IsDelimitChar(c)) 39 if (!IsDelimitChar(c))
40 { 40 {
41 if (c != ';') 41 if (c != ';')
@@ -111,13 +111,13 @@ int FindTextConfigItem(const CObjectVector<CTextConfigPair> &pairs, const char *
111{ 111{
112 FOR_VECTOR (i, pairs) 112 FOR_VECTOR (i, pairs)
113 if (pairs[i].ID.IsEqualTo(id)) 113 if (pairs[i].ID.IsEqualTo(id))
114 return i; 114 return (int)i;
115 return -1; 115 return -1;
116} 116}
117 117
118UString GetTextConfigValue(const CObjectVector<CTextConfigPair> &pairs, const char *id) 118UString GetTextConfigValue(const CObjectVector<CTextConfigPair> &pairs, const char *id)
119{ 119{
120 int index = FindTextConfigItem(pairs, id); 120 const int index = FindTextConfigItem(pairs, id);
121 if (index < 0) 121 if (index < 0)
122 return UString(); 122 return UString();
123 return pairs[index].String; 123 return pairs[index].String;
diff --git a/CPP/Common/TextConfig.h b/CPP/Common/TextConfig.h
index cc7ce41..2263a44 100644
--- a/CPP/Common/TextConfig.h
+++ b/CPP/Common/TextConfig.h
@@ -1,7 +1,7 @@
1// Common/TextConfig.h 1// Common/TextConfig.h
2 2
3#ifndef __COMMON_TEXT_CONFIG_H 3#ifndef ZIP7_INC_COMMON_TEXT_CONFIG_H
4#define __COMMON_TEXT_CONFIG_H 4#define ZIP7_INC_COMMON_TEXT_CONFIG_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7 7
diff --git a/CPP/Common/UTFConvert.cpp b/CPP/Common/UTFConvert.cpp
index ac069db..fb166b7 100644
--- a/CPP/Common/UTFConvert.cpp
+++ b/CPP/Common/UTFConvert.cpp
@@ -8,17 +8,17 @@
8#include "UTFConvert.h" 8#include "UTFConvert.h"
9 9
10 10
11#ifndef _WCHART_IS_16BIT 11#ifndef Z7_WCHART_IS_16BIT
12#ifndef __APPLE__ 12#ifndef __APPLE__
13 // we define it if the system supports files with non-utf8 symbols: 13 // we define it if the system supports files with non-utf8 symbols:
14 #define _UTF8_RAW_NON_UTF8_SUPPORTED 14 #define MY_UTF8_RAW_NON_UTF8_SUPPORTED
15#endif 15#endif
16#endif 16#endif
17 17
18/* 18/*
19 _UTF8_START(n) - is a base value for start byte (head), if there are (n) additional bytes after start byte 19 MY_UTF8_START(n) - is a base value for start byte (head), if there are (n) additional bytes after start byte
20 20
21 n : _UTF8_START(n) : Bits of code point 21 n : MY_UTF8_START(n) : Bits of code point
22 22
23 0 : 0x80 : : unused 23 0 : 0x80 : : unused
24 1 : 0xC0 : 11 : 24 1 : 0xC0 : 11 :
@@ -30,13 +30,13 @@
30 7 : 0xFF : 30 7 : 0xFF :
31*/ 31*/
32 32
33#define _UTF8_START(n) (0x100 - (1 << (7 - (n)))) 33#define MY_UTF8_START(n) (0x100 - (1 << (7 - (n))))
34 34
35#define _UTF8_HEAD_PARSE2(n) \ 35#define MY_UTF8_HEAD_PARSE2(n) \
36 if (c < _UTF8_START((n) + 1)) \ 36 if (c < MY_UTF8_START((n) + 1)) \
37 { numBytes = (n); val -= _UTF8_START(n); } 37 { numBytes = (n); val -= MY_UTF8_START(n); }
38 38
39#ifndef _WCHART_IS_16BIT 39#ifndef Z7_WCHART_IS_16BIT
40 40
41/* 41/*
42 if (wchar_t is 32-bit), we can support large points in long UTF-8 sequence, 42 if (wchar_t is 32-bit), we can support large points in long UTF-8 sequence,
@@ -46,30 +46,30 @@
46 (_UTF8_NUM_TAIL_BYTES_MAX == 6) : (36-bit hack) 46 (_UTF8_NUM_TAIL_BYTES_MAX == 6) : (36-bit hack)
47*/ 47*/
48 48
49#define _UTF8_NUM_TAIL_BYTES_MAX 5 49#define MY_UTF8_NUM_TAIL_BYTES_MAX 5
50#endif 50#endif
51 51
52/* 52/*
53#define _UTF8_HEAD_PARSE \ 53#define MY_UTF8_HEAD_PARSE \
54 UInt32 val = c; \ 54 UInt32 val = c; \
55 _UTF8_HEAD_PARSE2(1) \ 55 MY_UTF8_HEAD_PARSE2(1) \
56 else _UTF8_HEAD_PARSE2(2) \ 56 else MY_UTF8_HEAD_PARSE2(2) \
57 else _UTF8_HEAD_PARSE2(3) \ 57 else MY_UTF8_HEAD_PARSE2(3) \
58 else _UTF8_HEAD_PARSE2(4) \ 58 else MY_UTF8_HEAD_PARSE2(4) \
59 else _UTF8_HEAD_PARSE2(5) \ 59 else MY_UTF8_HEAD_PARSE2(5) \
60 #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 60 #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6
61 else _UTF8_HEAD_PARSE2(6) 61 else MY_UTF8_HEAD_PARSE2(6)
62 #endif 62 #endif
63*/ 63*/
64 64
65#define _UTF8_HEAD_PARSE_MAX_3_BYTES \ 65#define MY_UTF8_HEAD_PARSE_MAX_3_BYTES \
66 UInt32 val = c; \ 66 UInt32 val = c; \
67 _UTF8_HEAD_PARSE2(1) \ 67 MY_UTF8_HEAD_PARSE2(1) \
68 else _UTF8_HEAD_PARSE2(2) \ 68 else MY_UTF8_HEAD_PARSE2(2) \
69 else { numBytes = 3; val -= _UTF8_START(3); } 69 else { numBytes = 3; val -= MY_UTF8_START(3); }
70 70
71 71
72#define _UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6)) 72#define MY_UTF8_RANGE(n) (((UInt32)1) << ((n) * 5 + 6))
73 73
74 74
75#define START_POINT_FOR_SURROGATE 0x10000 75#define START_POINT_FOR_SURROGATE 0x10000
@@ -82,7 +82,7 @@
82*/ 82*/
83 83
84 84
85#if defined(_WCHART_IS_16BIT) 85#if defined(Z7_WCHART_IS_16BIT)
86 86
87#define UTF_ESCAPE_PLANE 0 87#define UTF_ESCAPE_PLANE 0
88 88
@@ -102,7 +102,7 @@ we can place 128 ESCAPE chars to
102#define UTF_ESCAPE_PLANE 0 102#define UTF_ESCAPE_PLANE 0
103 103
104/* 104/*
105 if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is set) 105 if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is set)
106 { 106 {
107 if (UTF_ESCAPE_PLANE is UTF_ESCAPE_PLANE_HIGH) 107 if (UTF_ESCAPE_PLANE is UTF_ESCAPE_PLANE_HIGH)
108 { 108 {
@@ -111,13 +111,13 @@ we can place 128 ESCAPE chars to
111 So we still need a way to extract 8-bit Escapes and BMP-Escapes-8 111 So we still need a way to extract 8-bit Escapes and BMP-Escapes-8
112 from same BMP-Escapes-16 stored in 7z. 112 from same BMP-Escapes-16 stored in 7z.
113 And if we want to restore any 8-bit from 7z archive, 113 And if we want to restore any 8-bit from 7z archive,
114 we still must use UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT for (utf-8 -> utf-16) 114 we still must use Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT for (utf-8 -> utf-16)
115 Also we need additional Conversions to tranform from utf-16 to utf-16-With-Escapes-21 115 Also we need additional Conversions to tranform from utf-16 to utf-16-With-Escapes-21
116 } 116 }
117 else (UTF_ESCAPE_PLANE == 0) 117 else (UTF_ESCAPE_PLANE == 0)
118 { 118 {
119 we must convert original 3-bytes utf-8 BMP-Escape point to sequence 119 we must convert original 3-bytes utf-8 BMP-Escape point to sequence
120 of 3 BMP-Escape-16 points with UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT 120 of 3 BMP-Escape-16 points with Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT
121 so we can extract original RAW-UTF-8 from UTFD-16 later. 121 so we can extract original RAW-UTF-8 from UTFD-16 later.
122 } 122 }
123 } 123 }
@@ -138,7 +138,7 @@ we can place 128 ESCAPE chars to
138#define IS_LOW_SURROGATE_POINT(v) (((v) & (UInt32)0xfffffC00) == 0xdc00) 138#define IS_LOW_SURROGATE_POINT(v) (((v) & (UInt32)0xfffffC00) == 0xdc00)
139 139
140 140
141#define _ERROR_UTF8_CHECK \ 141#define UTF_ERROR_UTF8_CHECK \
142 { NonUtf = true; continue; } 142 { NonUtf = true; continue; }
143 143
144void CUtf8Check::Check_Buf(const char *src, size_t size) throw() 144void 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()
168 if (c < 0x80) 168 if (c < 0x80)
169 continue; 169 continue;
170 170
171 if (c < 0xc0 + 2)// it's limit for 0x140000 unicode codes : win32 compatibility 171 if (c < 0xc0 + 2) // it's limit for 0x140000 unicode codes : win32 compatibility
172 _ERROR_UTF8_CHECK 172 UTF_ERROR_UTF8_CHECK
173 173
174 unsigned numBytes; 174 unsigned numBytes;
175 175
176 UInt32 val = c; 176 UInt32 val = c;
177 _UTF8_HEAD_PARSE2(1) 177 MY_UTF8_HEAD_PARSE2(1)
178 else _UTF8_HEAD_PARSE2(2) 178 else MY_UTF8_HEAD_PARSE2(2)
179 else _UTF8_HEAD_PARSE2(4) 179 else MY_UTF8_HEAD_PARSE2(4)
180 else _UTF8_HEAD_PARSE2(5) 180 else MY_UTF8_HEAD_PARSE2(5)
181 else 181 else
182 { 182 {
183 _ERROR_UTF8_CHECK 183 UTF_ERROR_UTF8_CHECK
184 } 184 }
185 185
186 unsigned pos = 0; 186 unsigned pos = 0;
@@ -206,7 +206,7 @@ void CUtf8Check::Check_Buf(const char *src, size_t size) throw()
206 if (pos == size) 206 if (pos == size)
207 Truncated = true; 207 Truncated = true;
208 else 208 else
209 _ERROR_UTF8_CHECK 209 UTF_ERROR_UTF8_CHECK
210 } 210 }
211 211
212 #ifdef UTF_ESCAPE_BASE 212 #ifdef UTF_ESCAPE_BASE
@@ -268,7 +268,7 @@ bool CheckUTF8(const char *src, bool allowReduced) throw()
268 return false; 268 return false;
269 269
270 unsigned numBytes; 270 unsigned numBytes;
271 _UTF8_HEAD_PARSE 271 MY_UTF8_HEAD_PARSE
272 else 272 else
273 return false; 273 return false;
274 274
@@ -285,7 +285,7 @@ bool CheckUTF8(const char *src, bool allowReduced) throw()
285 } 285 }
286 while (--numBytes); 286 while (--numBytes);
287 287
288 if (val < _UTF8_RANGE(pos - 1)) 288 if (val < MY_UTF8_RANGE(pos - 1))
289 return false; 289 return false;
290 290
291 if (val >= 0x110000) 291 if (val >= 0x110000)
@@ -303,18 +303,18 @@ bool CheckUTF8(const char *src, bool allowReduced) throw()
303 303
304 304
305#define UTF_ESCAPE(c) \ 305#define UTF_ESCAPE(c) \
306 ((flags & UTF_FLAG__FROM_UTF8__USE_ESCAPE) ? \ 306 ((flags & Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE) ? \
307 UTF_ESCAPE_PLANE + UTF_ESCAPE_BASE + (c) : UTF_REPLACEMENT_CHAR) 307 UTF_ESCAPE_PLANE + UTF_ESCAPE_BASE + (c) : UTF_REPLACEMENT_CHAR)
308 308
309/* 309/*
310#define _HARD_ERROR_UTF8 310#define UTF_HARD_ERROR_UTF8
311 { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \ 311 { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \
312 destPos++; ok = false; continue; } 312 destPos++; ok = false; continue; }
313*/ 313*/
314 314
315// we ignore utf errors, and don't change (ok) variable! 315// we ignore utf errors, and don't change (ok) variable!
316 316
317#define _ERROR_UTF8 \ 317#define UTF_ERROR_UTF8 \
318 { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \ 318 { if (dest) dest[destPos] = (wchar_t)UTF_ESCAPE(c); \
319 destPos++; continue; } 319 destPos++; continue; }
320 320
@@ -362,12 +362,12 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
362 if (c < 0xc0 + 2 362 if (c < 0xc0 + 2
363 || c >= 0xf5) // it's limit for 0x140000 unicode codes : win32 compatibility 363 || c >= 0xf5) // it's limit for 0x140000 unicode codes : win32 compatibility
364 { 364 {
365 _ERROR_UTF8 365 UTF_ERROR_UTF8
366 } 366 }
367 367
368 unsigned numBytes; 368 unsigned numBytes;
369 369
370 _UTF8_HEAD_PARSE_MAX_3_BYTES 370 MY_UTF8_HEAD_PARSE_MAX_3_BYTES
371 371
372 unsigned pos = 0; 372 unsigned pos = 0;
373 do 373 do
@@ -387,7 +387,7 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
387 break; 387 break;
388 if (numBytes == 2) 388 if (numBytes == 2)
389 { 389 {
390 if (flags & UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) 390 if (flags & Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR)
391 if ((val & (0xF800 >> 6)) == (0xd800 >> 6)) 391 if ((val & (0xF800 >> 6)) == (0xd800 >> 6))
392 break; 392 break;
393 } 393 }
@@ -399,27 +399,27 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
399 399
400 if (numBytes != 0) 400 if (numBytes != 0)
401 { 401 {
402 if ((flags & UTF_FLAG__FROM_UTF8__USE_ESCAPE) == 0) 402 if ((flags & Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE) == 0)
403 { 403 {
404 // the following code to emit the 0xfffd chars as win32 Utf8 function. 404 // the following code to emit the 0xfffd chars as win32 Utf8 function.
405 // disable the folling line, if you need 0xfffd for each incorrect byte as in Escape mode 405 // disable the folling line, if you need 0xfffd for each incorrect byte as in Escape mode
406 src += pos; 406 src += pos;
407 } 407 }
408 _ERROR_UTF8 408 UTF_ERROR_UTF8
409 } 409 }
410 410
411 /* 411 /*
412 if (val < _UTF8_RANGE(pos - 1)) 412 if (val < MY_UTF8_RANGE(pos - 1))
413 _ERROR_UTF8 413 UTF_ERROR_UTF8
414 */ 414 */
415 415
416 #ifdef UTF_ESCAPE_BASE 416 #ifdef UTF_ESCAPE_BASE
417 417
418 if ((flags & UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT) 418 if ((flags & Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT)
419 && IS_ESCAPE_POINT(val, 0)) 419 && IS_ESCAPE_POINT(val, 0))
420 { 420 {
421 // We will emit 3 utf16-Escape-16-21 points from one Escape-16 point (3 bytes) 421 // We will emit 3 utf16-Escape-16-21 points from one Escape-16 point (3 bytes)
422 _ERROR_UTF8 422 UTF_ERROR_UTF8
423 } 423 }
424 424
425 #endif 425 #endif
@@ -434,11 +434,11 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
434 if (val < START_POINT_FOR_SURROGATE) 434 if (val < START_POINT_FOR_SURROGATE)
435 { 435 {
436 /* 436 /*
437 if ((flags & UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) 437 if ((flags & Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR)
438 && IS_SURROGATE_POINT(val)) 438 && IS_SURROGATE_POINT(val))
439 { 439 {
440 // We will emit 3 utf16-Escape-16-21 points from one Surrogate-16 point (3 bytes) 440 // We will emit 3 utf16-Escape-16-21 points from one Surrogate-16 point (3 bytes)
441 _ERROR_UTF8 441 UTF_ERROR_UTF8
442 } 442 }
443 */ 443 */
444 if (dest) 444 if (dest)
@@ -451,7 +451,7 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
451 if (val >= 0x110000) 451 if (val >= 0x110000)
452 { 452 {
453 // We will emit utf16-Escape-16-21 point from each source byte 453 // We will emit utf16-Escape-16-21 point from each source byte
454 _ERROR_UTF8 454 UTF_ERROR_UTF8
455 } 455 }
456 */ 456 */
457 if (dest) 457 if (dest)
@@ -467,8 +467,8 @@ static bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, const
467 467
468 468
469 469
470#define _UTF8_HEAD(n, val) ((char)(_UTF8_START(n) + (val >> (6 * (n))))) 470#define MY_UTF8_HEAD(n, val) ((char)(MY_UTF8_START(n) + (val >> (6 * (n)))))
471#define _UTF8_CHAR(n, val) ((char)(0x80 + (((val) >> (6 * (n))) & 0x3F))) 471#define MY_UTF8_CHAR(n, val) ((char)(0x80 + (((val) >> (6 * (n))) & 0x3F)))
472 472
473static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsigned flags) 473static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsigned flags)
474{ 474{
@@ -483,7 +483,7 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi
483 if (val < 0x80) 483 if (val < 0x80)
484 continue; 484 continue;
485 485
486 if (val < _UTF8_RANGE(1)) 486 if (val < MY_UTF8_RANGE(1))
487 { 487 {
488 size++; 488 size++;
489 continue; 489 continue;
@@ -492,12 +492,12 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi
492 #ifdef UTF_ESCAPE_BASE 492 #ifdef UTF_ESCAPE_BASE
493 493
494 #if UTF_ESCAPE_PLANE != 0 494 #if UTF_ESCAPE_PLANE != 0
495 if (flags & UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE) 495 if (flags & Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE)
496 if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE)) 496 if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE))
497 continue; 497 continue;
498 #endif 498 #endif
499 499
500 if (flags & UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE) 500 if (flags & Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE)
501 if (IS_ESCAPE_POINT(val, 0)) 501 if (IS_ESCAPE_POINT(val, 0))
502 continue; 502 continue;
503 503
@@ -517,18 +517,18 @@ static size_t Utf16_To_Utf8_Calc(const wchar_t *src, const wchar_t *srcLim, unsi
517 continue; 517 continue;
518 } 518 }
519 519
520 #ifdef _WCHART_IS_16BIT 520 #ifdef Z7_WCHART_IS_16BIT
521 521
522 size += 2; 522 size += 2;
523 523
524 #else 524 #else
525 525
526 if (val < _UTF8_RANGE(2)) size += 2; 526 if (val < MY_UTF8_RANGE(2)) size += 2;
527 else if (val < _UTF8_RANGE(3)) size += 3; 527 else if (val < MY_UTF8_RANGE(3)) size += 3;
528 else if (val < _UTF8_RANGE(4)) size += 4; 528 else if (val < MY_UTF8_RANGE(4)) size += 4;
529 else if (val < _UTF8_RANGE(5)) size += 5; 529 else if (val < MY_UTF8_RANGE(5)) size += 5;
530 else 530 else
531 #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 531 #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6
532 size += 6; 532 size += 6;
533 #else 533 #else
534 size += 3; 534 size += 3;
@@ -554,10 +554,10 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim
554 continue; 554 continue;
555 } 555 }
556 556
557 if (val < _UTF8_RANGE(1)) 557 if (val < MY_UTF8_RANGE(1))
558 { 558 {
559 dest[0] = _UTF8_HEAD(1, val); 559 dest[0] = MY_UTF8_HEAD(1, val);
560 dest[1] = _UTF8_CHAR(0, val); 560 dest[1] = MY_UTF8_CHAR(0, val);
561 dest += 2; 561 dest += 2;
562 continue; 562 continue;
563 } 563 }
@@ -567,11 +567,11 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim
567 #if UTF_ESCAPE_PLANE != 0 567 #if UTF_ESCAPE_PLANE != 0
568 /* 568 /*
569 if (wchar_t is 32-bit) 569 if (wchar_t is 32-bit)
570 && (UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE is set) 570 && (Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE is set)
571 && (point is virtual escape plane) 571 && (point is virtual escape plane)
572 we extract 8-bit byte from virtual HIGH-ESCAPE PLANE. 572 we extract 8-bit byte from virtual HIGH-ESCAPE PLANE.
573 */ 573 */
574 if (flags & UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE) 574 if (flags & Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE)
575 if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE)) 575 if (IS_ESCAPE_POINT(val, UTF_ESCAPE_PLANE))
576 { 576 {
577 *dest++ = (char)(val); 577 *dest++ = (char)(val);
@@ -579,10 +579,10 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim
579 } 579 }
580 #endif // UTF_ESCAPE_PLANE != 0 580 #endif // UTF_ESCAPE_PLANE != 0
581 581
582 /* if (UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE is defined) 582 /* if (Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE is defined)
583 we extract 8-bit byte from BMP-ESCAPE PLANE. */ 583 we extract 8-bit byte from BMP-ESCAPE PLANE. */
584 584
585 if (flags & UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE) 585 if (flags & Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE)
586 if (IS_ESCAPE_POINT(val, 0)) 586 if (IS_ESCAPE_POINT(val, 0))
587 { 587 {
588 *dest++ = (char)(val); 588 *dest++ = (char)(val);
@@ -601,46 +601,46 @@ static char *Utf16_To_Utf8(char *dest, const wchar_t *src, const wchar_t *srcLim
601 { 601 {
602 src++; 602 src++;
603 val = (((val - 0xd800) << 10) | (c2 - 0xdc00)) + 0x10000; 603 val = (((val - 0xd800) << 10) | (c2 - 0xdc00)) + 0x10000;
604 dest[0] = _UTF8_HEAD(3, val); 604 dest[0] = MY_UTF8_HEAD(3, val);
605 dest[1] = _UTF8_CHAR(2, val); 605 dest[1] = MY_UTF8_CHAR(2, val);
606 dest[2] = _UTF8_CHAR(1, val); 606 dest[2] = MY_UTF8_CHAR(1, val);
607 dest[3] = _UTF8_CHAR(0, val); 607 dest[3] = MY_UTF8_CHAR(0, val);
608 dest += 4; 608 dest += 4;
609 continue; 609 continue;
610 } 610 }
611 } 611 }
612 if (flags & UTF_FLAG__TO_UTF8__SURROGATE_ERROR) 612 if (flags & Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR)
613 val = UTF_REPLACEMENT_CHAR; // WIN32 function does it 613 val = UTF_REPLACEMENT_CHAR; // WIN32 function does it
614 } 614 }
615 615
616 #ifndef _WCHART_IS_16BIT 616 #ifndef Z7_WCHART_IS_16BIT
617 if (val < _UTF8_RANGE(2)) 617 if (val < MY_UTF8_RANGE(2))
618 #endif 618 #endif
619 { 619 {
620 dest[0] = _UTF8_HEAD(2, val); 620 dest[0] = MY_UTF8_HEAD(2, val);
621 dest[1] = _UTF8_CHAR(1, val); 621 dest[1] = MY_UTF8_CHAR(1, val);
622 dest[2] = _UTF8_CHAR(0, val); 622 dest[2] = MY_UTF8_CHAR(0, val);
623 dest += 3; 623 dest += 3;
624 continue; 624 continue;
625 } 625 }
626 626
627 #ifndef _WCHART_IS_16BIT 627 #ifndef Z7_WCHART_IS_16BIT
628 628
629 // we don't expect this case. so we can throw exception 629 // we don't expect this case. so we can throw exception
630 // throw 20210407; 630 // throw 20210407;
631 631
632 char b; 632 char b;
633 unsigned numBits; 633 unsigned numBits;
634 if (val < _UTF8_RANGE(3)) { numBits = 6 * 3; b = _UTF8_HEAD(3, val); } 634 if (val < MY_UTF8_RANGE(3)) { numBits = 6 * 3; b = MY_UTF8_HEAD(3, val); }
635 else if (val < _UTF8_RANGE(4)) { numBits = 6 * 4; b = _UTF8_HEAD(4, val); } 635 else if (val < MY_UTF8_RANGE(4)) { numBits = 6 * 4; b = MY_UTF8_HEAD(4, val); }
636 else if (val < _UTF8_RANGE(5)) { numBits = 6 * 5; b = _UTF8_HEAD(5, val); } 636 else if (val < MY_UTF8_RANGE(5)) { numBits = 6 * 5; b = MY_UTF8_HEAD(5, val); }
637 #if _UTF8_NUM_TAIL_BYTES_MAX >= 6 637 #if MY_UTF8_NUM_TAIL_BYTES_MAX >= 6
638 else { numBits = 6 * 6; b = (char)_UTF8_START(6); } 638 else { numBits = 6 * 6; b = (char)MY_UTF8_START(6); }
639 #else 639 #else
640 else 640 else
641 { 641 {
642 val = UTF_REPLACEMENT_CHAR; 642 val = UTF_REPLACEMENT_CHAR;
643 { numBits = 6 * 3; b = _UTF8_HEAD(3, val); } 643 { numBits = 6 * 3; b = MY_UTF8_HEAD(3, val); }
644 } 644 }
645 #endif 645 #endif
646 646
@@ -675,11 +675,11 @@ bool ConvertUTF8ToUnicode_Flags(const AString &src, UString &dest, unsigned flag
675 675
676static 676static
677unsigned g_UTF8_To_Unicode_Flags = 677unsigned g_UTF8_To_Unicode_Flags =
678 UTF_FLAG__FROM_UTF8__USE_ESCAPE 678 Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE
679 #ifndef _WCHART_IS_16BIT 679 #ifndef Z7_WCHART_IS_16BIT
680 | UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 680 | Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR
681 #ifdef _UTF8_RAW_NON_UTF8_SUPPORTED 681 #ifdef MY_UTF8_RAW_NON_UTF8_SUPPORTED
682 | UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT 682 | Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT
683 #endif 683 #endif
684 #endif 684 #endif
685 ; 685 ;
@@ -729,13 +729,13 @@ void ConvertUnicodeToUTF8_Flags(const UString &src, AString &dest, unsigned flag
729 729
730 730
731unsigned g_Unicode_To_UTF8_Flags = 731unsigned g_Unicode_To_UTF8_Flags =
732 // UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE 732 // Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE
733 0 733 0
734 #ifndef _WIN32 734 #ifndef _WIN32
735 #ifdef _UTF8_RAW_NON_UTF8_SUPPORTED 735 #ifdef MY_UTF8_RAW_NON_UTF8_SUPPORTED
736 | UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE 736 | Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE
737 #else 737 #else
738 | UTF_FLAG__TO_UTF8__SURROGATE_ERROR; 738 | Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR
739 #endif 739 #endif
740 #endif 740 #endif
741 ; 741 ;
@@ -840,7 +840,7 @@ bool Unicode_IsThere_Utf16SurrogateError(const UString &src)
840} 840}
841*/ 841*/
842 842
843#ifndef _WCHART_IS_16BIT 843#ifndef Z7_WCHART_IS_16BIT
844 844
845void Convert_UnicodeEsc16_To_UnicodeEscHigh 845void Convert_UnicodeEsc16_To_UnicodeEscHigh
846#if UTF_ESCAPE_PLANE == 0 846#if UTF_ESCAPE_PLANE == 0
diff --git a/CPP/Common/UTFConvert.h b/CPP/Common/UTFConvert.h
index 37c4975..94a8024 100644
--- a/CPP/Common/UTFConvert.h
+++ b/CPP/Common/UTFConvert.h
@@ -1,7 +1,7 @@
1// Common/UTFConvert.h 1// Common/UTFConvert.h
2 2
3#ifndef __COMMON_UTF_CONVERT_H 3#ifndef ZIP7_INC_COMMON_UTF_CONVERT_H
4#define __COMMON_UTF_CONVERT_H 4#define ZIP7_INC_COMMON_UTF_CONVERT_H
5 5
6#include "MyBuffer.h" 6#include "MyBuffer.h"
7#include "MyString.h" 7#include "MyString.h"
@@ -88,12 +88,12 @@ if (allowReduced == true) - it allows truncated last character-Utf8-sequence
88bool Check_UTF8_Buf(const char *src, size_t size, bool allowReduced) throw(); 88bool Check_UTF8_Buf(const char *src, size_t size, bool allowReduced) throw();
89bool CheckUTF8_AString(const AString &s) throw(); 89bool CheckUTF8_AString(const AString &s) throw();
90 90
91#define UTF_FLAG__FROM_UTF8__SURROGATE_ERROR (1 << 0) 91#define Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR (1 << 0)
92#define UTF_FLAG__FROM_UTF8__USE_ESCAPE (1 << 1) 92#define Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE (1 << 1)
93#define UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT (1 << 2) 93#define Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT (1 << 2)
94 94
95/* 95/*
96UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 96Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR
97 97
98 if (flag is NOT set) 98 if (flag is NOT set)
99 { 99 {
@@ -108,14 +108,14 @@ UTF_FLAG__FROM_UTF8__SURROGATE_ERROR
108 108
109 if (flag is set) 109 if (flag is set)
110 { 110 {
111 if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is defined) 111 if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is defined)
112 it generates ESCAPE for SINGLE-SURROGATE-8, 112 it generates ESCAPE for SINGLE-SURROGATE-8,
113 if (UTF_FLAG__FROM_UTF8__USE_ESCAPE is not defined) 113 if (Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE is not defined)
114 it generates U+fffd for SINGLE-SURROGATE-8, 114 it generates U+fffd for SINGLE-SURROGATE-8,
115 } 115 }
116 116
117 117
118UTF_FLAG__FROM_UTF8__USE_ESCAPE 118Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE
119 119
120 if (flag is NOT set) 120 if (flag is NOT set)
121 it generates (U+fffd) code for non-UTF-8 (invalid) characters 121 it generates (U+fffd) code for non-UTF-8 (invalid) characters
@@ -126,7 +126,7 @@ UTF_FLAG__FROM_UTF8__USE_ESCAPE
126 And later we can restore original UTF-8-RAW characters from (ESCAPE-16-21) codes. 126 And later we can restore original UTF-8-RAW characters from (ESCAPE-16-21) codes.
127 } 127 }
128 128
129UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT 129Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT
130 130
131 if (flag is NOT set) 131 if (flag is NOT set)
132 { 132 {
@@ -146,9 +146,9 @@ Main USE CASES with UTF-8 <-> UTF-16 conversions:
146 146
147 WIN32: UTF-16-RAW -> UTF-8 (Archive) -> UTF-16-RAW 147 WIN32: UTF-16-RAW -> UTF-8 (Archive) -> UTF-16-RAW
148 { 148 {
149 set UTF_FLAG__FROM_UTF8__USE_ESCAPE 149 set Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE
150 Do NOT set UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 150 Do NOT set Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR
151 Do NOT set UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT 151 Do NOT set Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT
152 152
153 So we restore original SINGLE-SURROGATE-16 from single SINGLE-SURROGATE-8. 153 So we restore original SINGLE-SURROGATE-16 from single SINGLE-SURROGATE-8.
154 } 154 }
@@ -157,17 +157,17 @@ Main USE CASES with UTF-8 <-> UTF-16 conversions:
157 { 157 {
158 we want restore original UTF-8-RAW sequence later from that ESCAPE-16. 158 we want restore original UTF-8-RAW sequence later from that ESCAPE-16.
159 Set the flags: 159 Set the flags:
160 UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 160 Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR
161 UTF_FLAG__FROM_UTF8__USE_ESCAPE 161 Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE
162 UTF_FLAG__FROM_UTF8__BMP_ESCAPE_CONVERT 162 Z7_UTF_FLAG_FROM_UTF8_BMP_ESCAPE_CONVERT
163 } 163 }
164 164
165 MacOS: UTF-8-RAW -> UTF-16 (Intermediate / Archive) -> UTF-8-RAW 165 MacOS: UTF-8-RAW -> UTF-16 (Intermediate / Archive) -> UTF-8-RAW
166 { 166 {
167 we want to restore correct UTF-8 without any BMP processing: 167 we want to restore correct UTF-8 without any BMP processing:
168 Set the flags: 168 Set the flags:
169 UTF_FLAG__FROM_UTF8__SURROGATE_ERROR 169 Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR
170 UTF_FLAG__FROM_UTF8__USE_ESCAPE 170 Z7_UTF_FLAG_FROM_UTF8_USE_ESCAPE
171 } 171 }
172 172
173*/ 173*/
@@ -178,12 +178,12 @@ bool Convert_UTF8_Buf_To_Unicode(const char *src, size_t srcSize, UString &dest,
178bool ConvertUTF8ToUnicode_Flags(const AString &src, UString &dest, unsigned flags = 0); 178bool ConvertUTF8ToUnicode_Flags(const AString &src, UString &dest, unsigned flags = 0);
179bool ConvertUTF8ToUnicode(const AString &src, UString &dest); 179bool ConvertUTF8ToUnicode(const AString &src, UString &dest);
180 180
181#define UTF_FLAG__TO_UTF8__SURROGATE_ERROR (1 << 8) 181#define Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR (1 << 8)
182#define UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE (1 << 9) 182#define Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE (1 << 9)
183// #define UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE (1 << 10) 183// #define Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE (1 << 10)
184 184
185/* 185/*
186UTF_FLAG__TO_UTF8__SURROGATE_ERROR 186Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR
187 187
188 if (flag is NOT set) 188 if (flag is NOT set)
189 { 189 {
@@ -193,7 +193,7 @@ UTF_FLAG__TO_UTF8__SURROGATE_ERROR
193 193
194 In Linux : 194 In Linux :
195 use-case-1: UTF-8 -> UTF-16 -> UTF-8 doesn't generate UTF-16 SINGLE-SURROGATE, 195 use-case-1: UTF-8 -> UTF-16 -> UTF-8 doesn't generate UTF-16 SINGLE-SURROGATE,
196 if (UTF_FLAG__FROM_UTF8__SURROGATE_ERROR) is used. 196 if (Z7_UTF_FLAG_FROM_UTF8_SURROGATE_ERROR) is used.
197 use-case 2: UTF-16-7z (with SINGLE-SURROGATE from Windows) -> UTF-8 (Linux) 197 use-case 2: UTF-16-7z (with SINGLE-SURROGATE from Windows) -> UTF-8 (Linux)
198 will generate SINGLE-SURROGATE-UTF-8 here. 198 will generate SINGLE-SURROGATE-UTF-8 here.
199 } 199 }
@@ -206,17 +206,17 @@ UTF_FLAG__TO_UTF8__SURROGATE_ERROR
206 } 206 }
207 207
208 208
209UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE 209Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE
210 210
211 if (flag is NOT set) it doesn't extract raw 8-bit symbol from Escape-Plane-16 211 if (flag is NOT set) it doesn't extract raw 8-bit symbol from Escape-Plane-16
212 if (flag is set) it extracts raw 8-bit symbol from Escape-Plane-16 212 if (flag is set) it extracts raw 8-bit symbol from Escape-Plane-16
213 213
214 in Linux we need some way to extract NON-UTF8 RAW 8-bits from BMP (UTF-16 7z archive): 214 in Linux we need some way to extract NON-UTF8 RAW 8-bits from BMP (UTF-16 7z archive):
215 if (we use High-Escape-Plane), we can transfer BMP escapes to High-Escape-Plane. 215 if (we use High-Escape-Plane), we can transfer BMP escapes to High-Escape-Plane.
216 if (we don't use High-Escape-Plane), we must use UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE. 216 if (we don't use High-Escape-Plane), we must use Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE.
217 217
218 218
219UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE 219Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE
220 // that flag affects the code only if (wchar_t is 32-bit) 220 // that flag affects the code only if (wchar_t is 32-bit)
221 // that mode with high-escape can be disabled now in UTFConvert.cpp 221 // that mode with high-escape can be disabled now in UTFConvert.cpp
222 if (flag is NOT set) 222 if (flag is NOT set)
@@ -228,19 +228,19 @@ Main use cases:
228 228
229WIN32 : UTF-16-RAW -> UTF-8 (archive) -> UTF-16-RAW 229WIN32 : UTF-16-RAW -> UTF-8 (archive) -> UTF-16-RAW
230 { 230 {
231 Do NOT set UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE. 231 Do NOT set Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE.
232 Do NOT set UTF_FLAG__TO_UTF8__SURROGATE_ERROR. 232 Do NOT set Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR.
233 So we restore original UTF-16-RAW. 233 So we restore original UTF-16-RAW.
234 } 234 }
235 235
236Linix : UTF-8 with Escapes -> UTF-16 (7z archive) -> UTF-8 with Escapes 236Linix : UTF-8 with Escapes -> UTF-16 (7z archive) -> UTF-8 with Escapes
237 set UTF_FLAG__TO_UTF8__EXTRACT_BMP_ESCAPE to extract non-UTF from 7z archive 237 set Z7_UTF_FLAG_TO_UTF8_EXTRACT_BMP_ESCAPE to extract non-UTF from 7z archive
238 set UTF_FLAG__TO_UTF8__PARSE_HIGH_ESCAPE for intermediate UTF-16. 238 set Z7_UTF_FLAG_TO_UTF8_PARSE_HIGH_ESCAPE for intermediate UTF-16.
239 Note: high esacape mode can be ignored now in UTFConvert.cpp 239 Note: high esacape mode can be ignored now in UTFConvert.cpp
240 240
241macOS: 241macOS:
242 the system doesn't support incorrect UTF-8 in file names. 242 the system doesn't support incorrect UTF-8 in file names.
243 set UTF_FLAG__TO_UTF8__SURROGATE_ERROR 243 set Z7_UTF_FLAG_TO_UTF8_SURROGATE_ERROR
244*/ 244*/
245 245
246extern unsigned g_Unicode_To_UTF8_Flags; 246extern unsigned g_Unicode_To_UTF8_Flags;
@@ -261,7 +261,7 @@ bool Unicode_IsThere_BmpEscape(const UString &src);
261bool Unicode_IsThere_Utf16SurrogateError(const UString &src); 261bool Unicode_IsThere_Utf16SurrogateError(const UString &src);
262*/ 262*/
263 263
264#ifdef _WCHART_IS_16BIT 264#ifdef Z7_WCHART_IS_16BIT
265#define Convert_UnicodeEsc16_To_UnicodeEscHigh(s) 265#define Convert_UnicodeEsc16_To_UnicodeEscHigh(s)
266#else 266#else
267void Convert_UnicodeEsc16_To_UnicodeEscHigh(UString &s); 267void Convert_UnicodeEsc16_To_UnicodeEscHigh(UString &s);
diff --git a/CPP/Common/Wildcard.cpp b/CPP/Common/Wildcard.cpp
index 861f3f7..798cbd9 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)
125{ 125{
126 for (;;) 126 for (;;)
127 { 127 {
128 wchar_t m = *mask; 128 const wchar_t m = *mask;
129 wchar_t c = *name; 129 const wchar_t c = *name;
130 if (m == 0) 130 if (m == 0)
131 return (c == 0); 131 return (c == 0);
132 if (m == '*') 132 if (m == '*')
@@ -526,12 +526,10 @@ int CCensor::FindPairForPrefix(const UString &prefix) const
526 526
527bool IsDriveColonName(const wchar_t *s) 527bool IsDriveColonName(const wchar_t *s)
528{ 528{
529 wchar_t c = s[0]; 529 unsigned c = s[0];
530 return c != 0 530 c |= 0x20;
531 && s[1] == ':' 531 c -= 'a';
532 && s[2] == 0 532 return c <= (unsigned)('z' - 'a') && s[1] == ':' && s[2] == 0;
533 && ((c >= 'a' && c <= 'z')
534 || (c >= 'A' && c <= 'Z'));
535} 533}
536 534
537unsigned GetNumPrefixParts_if_DrivePath(UStringVector &pathParts) 535unsigned GetNumPrefixParts_if_DrivePath(UStringVector &pathParts)
diff --git a/CPP/Common/Wildcard.h b/CPP/Common/Wildcard.h
index 0fa4887..4f81da9 100644
--- a/CPP/Common/Wildcard.h
+++ b/CPP/Common/Wildcard.h
@@ -1,7 +1,7 @@
1// Common/Wildcard.h 1// Common/Wildcard.h
2 2
3#ifndef __COMMON_WILDCARD_H 3#ifndef ZIP7_INC_COMMON_WILDCARD_H
4#define __COMMON_WILDCARD_H 4#define ZIP7_INC_COMMON_WILDCARD_H
5 5
6#include "MyString.h" 6#include "MyString.h"
7 7
@@ -83,7 +83,7 @@ public:
83 CCensorNode(): 83 CCensorNode():
84 Parent(NULL) 84 Parent(NULL)
85 // , ExcludeDirItems(false) 85 // , ExcludeDirItems(false)
86 {}; 86 {}
87 87
88 CCensorNode(const UString &name, CCensorNode *parent): 88 CCensorNode(const UString &name, CCensorNode *parent):
89 Parent(parent) 89 Parent(parent)
diff --git a/CPP/Common/XzCrc64Reg.cpp b/CPP/Common/XzCrc64Reg.cpp
index 33b5249..e9e67ef 100644
--- a/CPP/Common/XzCrc64Reg.cpp
+++ b/CPP/Common/XzCrc64Reg.cpp
@@ -9,34 +9,31 @@
9 9
10#include "../7zip/Common/RegisterCodec.h" 10#include "../7zip/Common/RegisterCodec.h"
11 11
12class CXzCrc64Hasher: 12Z7_CLASS_IMP_COM_1(
13 public IHasher, 13 CXzCrc64Hasher
14 public CMyUnknownImp 14 , IHasher
15{ 15)
16 UInt64 _crc; 16 UInt64 _crc;
17 Byte mtDummy[1 << 7];
18
19public: 17public:
20 CXzCrc64Hasher(): _crc(CRC64_INIT_VAL) {} 18 Byte _mtDummy[1 << 7]; // it's public to eliminate clang warning: unused private field
21 19
22 MY_UNKNOWN_IMP1(IHasher) 20 CXzCrc64Hasher(): _crc(CRC64_INIT_VAL) {}
23 INTERFACE_IHasher(;)
24}; 21};
25 22
26STDMETHODIMP_(void) CXzCrc64Hasher::Init() throw() 23Z7_COM7F_IMF2(void, CXzCrc64Hasher::Init())
27{ 24{
28 _crc = CRC64_INIT_VAL; 25 _crc = CRC64_INIT_VAL;
29} 26}
30 27
31STDMETHODIMP_(void) CXzCrc64Hasher::Update(const void *data, UInt32 size) throw() 28Z7_COM7F_IMF2(void, CXzCrc64Hasher::Update(const void *data, UInt32 size))
32{ 29{
33 _crc = Crc64Update(_crc, data, size); 30 _crc = Crc64Update(_crc, data, size);
34} 31}
35 32
36STDMETHODIMP_(void) CXzCrc64Hasher::Final(Byte *digest) throw() 33Z7_COM7F_IMF2(void, CXzCrc64Hasher::Final(Byte *digest))
37{ 34{
38 UInt64 val = CRC64_GET_DIGEST(_crc); 35 const UInt64 val = CRC64_GET_DIGEST(_crc);
39 SetUi64(digest, val); 36 SetUi64(digest, val)
40} 37}
41 38
42REGISTER_HASHER(CXzCrc64Hasher, 0x4, "CRC64", 8) 39REGISTER_HASHER(CXzCrc64Hasher, 0x4, "CRC64", 8)
diff --git a/CPP/Windows/COM.h b/CPP/Windows/COM.h
index cee7f70..a8780ca 100644
--- a/CPP/Windows/COM.h
+++ b/CPP/Windows/COM.h
@@ -1,9 +1,9 @@
1// Windows/COM.h 1// Windows/COM.h
2 2
3#ifndef __WINDOWS_COM_H 3#ifndef ZIP7_INC_WINDOWS_COM_H
4#define __WINDOWS_COM_H 4#define ZIP7_INC_WINDOWS_COM_H
5 5
6#include "../Common/MyString.h" 6// #include "../Common/MyString.h"
7 7
8namespace NWindows { 8namespace NWindows {
9namespace NCOM { 9namespace NCOM {
@@ -21,17 +21,18 @@ public:
21 // it's single thread. Do we need multithread? 21 // it's single thread. Do we need multithread?
22 CoInitialize(NULL); 22 CoInitialize(NULL);
23 #endif 23 #endif
24 }; 24 }
25 ~CComInitializer() { CoUninitialize(); } 25 ~CComInitializer() { CoUninitialize(); }
26}; 26};
27 27
28class CStgMedium 28/*
29class CStgMedium2
29{ 30{
30 STGMEDIUM _object; 31 STGMEDIUM _object;
31public:
32 bool _mustBeReleased; 32 bool _mustBeReleased;
33 CStgMedium(): _mustBeReleased(false) {} 33public:
34 ~CStgMedium() { Free(); } 34 CStgMedium2(): _mustBeReleased(false) {}
35 ~CStgMedium2() { Free(); }
35 void Free() 36 void Free()
36 { 37 {
37 if (_mustBeReleased) 38 if (_mustBeReleased)
@@ -42,6 +43,21 @@ public:
42 STGMEDIUM* operator->() { return &_object;} 43 STGMEDIUM* operator->() { return &_object;}
43 STGMEDIUM* operator&() { return &_object; } 44 STGMEDIUM* operator&() { return &_object; }
44}; 45};
46*/
47
48struct CStgMedium: public STGMEDIUM
49{
50 CStgMedium()
51 {
52 tymed = TYMED_NULL; // 0
53 hGlobal = NULL;
54 pUnkForRelease = NULL;
55 }
56 ~CStgMedium()
57 {
58 ReleaseStgMedium(this);
59 }
60};
45 61
46#endif 62#endif
47 63
diff --git a/CPP/Windows/Clipboard.h b/CPP/Windows/Clipboard.h
index 60fedc1..3b4f2fe 100644
--- a/CPP/Windows/Clipboard.h
+++ b/CPP/Windows/Clipboard.h
@@ -1,7 +1,7 @@
1// Windows/Clipboard.h 1// Windows/Clipboard.h
2 2
3#ifndef __CLIPBOARD_H 3#ifndef ZIP7_INC_CLIPBOARD_H
4#define __CLIPBOARD_H 4#define ZIP7_INC_CLIPBOARD_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
@@ -11,7 +11,7 @@ class CClipboard
11{ 11{
12 bool m_Open; 12 bool m_Open;
13public: 13public:
14 CClipboard(): m_Open(false) {}; 14 CClipboard(): m_Open(false) {}
15 ~CClipboard() { Close(); } 15 ~CClipboard() { Close(); }
16 bool Open(HWND wndNewOwner) throw(); 16 bool Open(HWND wndNewOwner) throw();
17 bool Close() throw(); 17 bool Close() throw();
diff --git a/CPP/Windows/CommonDialog.cpp b/CPP/Windows/CommonDialog.cpp
index eaaecad..7a92d5f 100644
--- a/CPP/Windows/CommonDialog.cpp
+++ b/CPP/Windows/CommonDialog.cpp
@@ -2,7 +2,7 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#include "../Common/MyWindows.h" 5#include "../Common/MyBuffer.h"
6 6
7#ifdef UNDER_CE 7#ifdef UNDER_CE
8#include <commdlg.h> 8#include <commdlg.h>
@@ -14,6 +14,7 @@
14 14
15#include "CommonDialog.h" 15#include "CommonDialog.h"
16#include "Defs.h" 16#include "Defs.h"
17// #include "FileDir.h"
17 18
18#ifndef _UNICODE 19#ifndef _UNICODE
19extern bool g_IsNT; 20extern bool g_IsNT;
@@ -21,61 +22,46 @@ extern bool g_IsNT;
21 22
22namespace NWindows { 23namespace NWindows {
23 24
24#ifndef _UNICODE 25/*
26 GetSaveFileName()
27 GetOpenFileName()
28 OPENFILENAME
25 29
26class CDoubleZeroStringListA 30(lpstrInitialDir) : the initial directory.
27{ 31DOCs: the algorithm for selecting the initial directory varies on different platforms:
28 LPTSTR Buf;
29 unsigned Size;
30public:
31 CDoubleZeroStringListA(LPSTR buf, unsigned size): Buf(buf), Size(size) {}
32 bool Add(LPCSTR s) throw();
33 void Finish() { *Buf = 0; }
34};
35
36bool CDoubleZeroStringListA::Add(LPCSTR s) throw()
37{ 32{
38 unsigned len = MyStringLen(s) + 1; 33 Win2000/XP/Vista:
39 if (len >= Size) 34 1. If lpstrFile contains a path, that path is the initial directory.
40 return false; 35 2. Otherwise, lpstrInitialDir specifies the initial directory.
41 MyStringCopy(Buf, s); 36
42 Buf += len; 37 Win7:
43 Size -= len; 38 If lpstrInitialDir has the same value as was passed the first time
44 return true; 39 the application used an Open or Save As dialog box, the path
40 most recently selected by the user is used as the initial directory.
45} 41}
46 42
47#endif 43Win10:
44 in:
45 function supports (lpstrInitialDir) path with super prefix "\\\\?\\"
46 function supports (lpstrInitialDir) path with long path
47 function doesn't support absolute (lpstrFile) path with super prefix "\\\\?\\"
48 function doesn't support absolute (lpstrFile) path with long path
49 out: the path with super prefix "\\\\?\\" will be returned, if selected path is long
48 50
49class CDoubleZeroStringListW 51WinXP-64 and Win10: if no filters, the system shows all files.
50{ 52 but DOCs say: If all three members are zero or NULL,
51 LPWSTR Buf; 53 the system does not use any filters and does not
52 unsigned Size; 54 show any files in the file list control of the dialog box.
53public:
54 CDoubleZeroStringListW(LPWSTR buf, unsigned size): Buf(buf), Size(size) {}
55 bool Add(LPCWSTR s) throw();
56 void Finish() { *Buf = 0; }
57};
58
59bool CDoubleZeroStringListW::Add(LPCWSTR s) throw()
60{
61 unsigned len = MyStringLen(s) + 1;
62 if (len >= Size)
63 return false;
64 MyStringCopy(Buf, s);
65 Buf += len;
66 Size -= len;
67 return true;
68}
69 55
56in Win7+: GetOpenFileName() and GetSaveFileName()
57 do not support pstrCustomFilter feature anymore
58*/
70 59
71#ifdef UNDER_CE 60#ifdef UNDER_CE
72#define MY__OFN_PROJECT 0x00400000 61#define MY_OFN_PROJECT 0x00400000
73#define MY__OFN_SHOW_ALL 0x01000000 62#define MY_OFN_SHOW_ALL 0x01000000
74#endif 63#endif
75 64
76/* if (lpstrFilter == NULL && nFilterIndex == 0)
77 MSDN : "the system doesn't show any files",
78 but WinXP-64 shows all files. Why ??? */
79 65
80/* 66/*
81structures 67structures
@@ -89,16 +75,16 @@ contain additional members:
89#endif 75#endif
90 76
91If we compile the source code with (_WIN32_WINNT >= 0x0500), some functions 77If we compile the source code with (_WIN32_WINNT >= 0x0500), some functions
92will not work at NT 4.0, if we use sizeof(OPENFILENAME*). 78will not work at NT 4.0, if we use sizeof(OPENFILENAME).
93So we use size of old version of structure. */ 79We try to use reduced structure OPENFILENAME_NT4.
80*/
94 81
95#if defined(UNDER_CE) || defined(_WIN64) || (_WIN32_WINNT < 0x0500) 82// #if defined(_WIN64) || (defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0500)
96// || !defined(WINVER) 83#if defined(__GNUC__) && (__GNUC__ <= 9) || defined(Z7_OLD_WIN_SDK)
97 #ifndef _UNICODE 84 #ifndef _UNICODE
98 #define my_compatib_OPENFILENAMEA_size sizeof(OPENFILENAMEA) 85 #define my_compatib_OPENFILENAMEA OPENFILENAMEA
99 #endif 86 #endif
100 #define my_compatib_OPENFILENAMEW_size sizeof(OPENFILENAMEW) 87 #define my_compatib_OPENFILENAMEW OPENFILENAMEW
101#else
102 88
103 // MinGW doesn't support some required macros. So we define them here: 89 // MinGW doesn't support some required macros. So we define them here:
104 #ifndef CDSIZEOF_STRUCT 90 #ifndef CDSIZEOF_STRUCT
@@ -117,91 +103,166 @@ So we use size of old version of structure. */
117 #define my_compatib_OPENFILENAMEA_size OPENFILENAME_SIZE_VERSION_400A 103 #define my_compatib_OPENFILENAMEA_size OPENFILENAME_SIZE_VERSION_400A
118 #endif 104 #endif
119 #define my_compatib_OPENFILENAMEW_size OPENFILENAME_SIZE_VERSION_400W 105 #define my_compatib_OPENFILENAMEW_size OPENFILENAME_SIZE_VERSION_400W
106#else
107 #ifndef _UNICODE
108 #define my_compatib_OPENFILENAMEA OPENFILENAME_NT4A
109 #define my_compatib_OPENFILENAMEA_size sizeof(my_compatib_OPENFILENAMEA)
110 #endif
111 #define my_compatib_OPENFILENAMEW OPENFILENAME_NT4W
112 #define my_compatib_OPENFILENAMEW_size sizeof(my_compatib_OPENFILENAMEW)
113#endif
114/*
115#elif defined(UNDER_CE) || defined(_WIN64) || (_WIN32_WINNT < 0x0500)
116// || !defined(WINVER)
117 #ifndef _UNICODE
118 #define my_compatib_OPENFILENAMEA OPENFILENAMEA
119 #define my_compatib_OPENFILENAMEA_size sizeof(OPENFILENAMEA)
120 #endif
121 #define my_compatib_OPENFILENAMEW OPENFILENAMEW
122 #define my_compatib_OPENFILENAMEW_size sizeof(OPENFILENAMEW)
123#else
124
120#endif 125#endif
126*/
121 127
122#ifndef _UNICODE 128#ifndef _UNICODE
123#define CONV_U_To_A(dest, src, temp) AString temp; if (src) { temp = GetSystemString(src); dest = temp; } 129#define CONV_U_To_A(dest, src, temp) AString temp; if (src) { temp = GetSystemString(src); dest = temp; }
124#endif 130#endif
125 131
126bool MyGetOpenFileName(HWND hwnd, LPCWSTR title, 132bool CCommonDialogInfo::CommonDlg_BrowseForFile(LPCWSTR lpstrInitialDir, const UStringVector &filters)
127 LPCWSTR initialDir,
128 LPCWSTR filePath,
129 LPCWSTR filterDescription,
130 LPCWSTR filter,
131 UString &resPath
132 #ifdef UNDER_CE
133 , bool openFolder
134 #endif
135 )
136{ 133{
137 const unsigned kBufSize = MAX_PATH * 2; 134 /* GetSaveFileName() and GetOpenFileName() could change current dir,
138 const unsigned kFilterBufSize = MAX_PATH; 135 if OFN_NOCHANGEDIR is not used.
139 if (!filter) 136 We can restore current dir manually, if it's required.
140 filter = L"*.*"; 137 22.02: we use OFN_NOCHANGEDIR. So we don't need to restore current dir manually. */
141 #ifndef _UNICODE 138 // NFile::NDir::CCurrentDirRestorer curDirRestorer;
139
140#ifndef _UNICODE
142 if (!g_IsNT) 141 if (!g_IsNT)
143 { 142 {
144 CHAR buf[kBufSize]; 143 AString tempPath;
145 MyStringCopy(buf, (const char *)GetSystemString(filePath)); 144 AStringVector f;
146 // OPENFILENAME_NT4A 145 unsigned i;
147 OPENFILENAMEA p; 146 for (i = 0; i < filters.Size(); i++)
147 f.Add(GetSystemString(filters[i]));
148 unsigned size = f.Size() + 1;
149 for (i = 0; i < f.Size(); i++)
150 size += f[i].Len();
151 CObjArray<char> filterBuf(size);
152 // memset(filterBuf, 0, size * sizeof(char));
153 {
154 char *dest = filterBuf;
155 for (i = 0; i < f.Size(); i++)
156 {
157 const AString &s = f[i];
158 MyStringCopy(dest, s);
159 dest += s.Len() + 1;
160 }
161 *dest = 0;
162 }
163 my_compatib_OPENFILENAMEA p;
148 memset(&p, 0, sizeof(p)); 164 memset(&p, 0, sizeof(p));
149 p.lStructSize = my_compatib_OPENFILENAMEA_size; 165 p.lStructSize = my_compatib_OPENFILENAMEA_size;
150 p.hwndOwner = hwnd; 166 p.hwndOwner = hwndOwner;
151 CHAR filterBuf[kFilterBufSize]; 167 if (size > 1)
152 { 168 {
153 CDoubleZeroStringListA dz(filterBuf, kFilterBufSize);
154 dz.Add(GetSystemString(filterDescription ? filterDescription : filter));
155 dz.Add(GetSystemString(filter));
156 dz.Finish();
157 p.lpstrFilter = filterBuf; 169 p.lpstrFilter = filterBuf;
158 p.nFilterIndex = 1; 170 p.nFilterIndex = (DWORD)(FilterIndex + 1);
171 }
172
173 CONV_U_To_A(p.lpstrInitialDir, lpstrInitialDir, initialDir_a)
174 CONV_U_To_A(p.lpstrTitle, lpstrTitle, title_a)
175
176 const AString filePath_a = GetSystemString(FilePath);
177 const unsigned bufSize = MAX_PATH * 8
178 + filePath_a.Len()
179 + initialDir_a.Len();
180 p.nMaxFile = bufSize;
181 p.lpstrFile = tempPath.GetBuf(bufSize);
182 MyStringCopy(p.lpstrFile, filePath_a);
183 p.Flags =
184 OFN_EXPLORER
185 | OFN_HIDEREADONLY
186 | OFN_NOCHANGEDIR;
187 const BOOL b = SaveMode ?
188 ::GetSaveFileNameA((LPOPENFILENAMEA)(void *)&p) :
189 ::GetOpenFileNameA((LPOPENFILENAMEA)(void *)&p);
190 if (!b)
191 return false;
192 {
193 tempPath.ReleaseBuf_CalcLen(bufSize);
194 FilePath = GetUnicodeString(tempPath);
195 FilterIndex = (int)p.nFilterIndex - 1;
196 return true;
159 } 197 }
160
161 p.lpstrFile = buf;
162 p.nMaxFile = kBufSize;
163 CONV_U_To_A(p.lpstrInitialDir, initialDir, initialDirA);
164 CONV_U_To_A(p.lpstrTitle, title, titleA);
165 p.Flags = OFN_EXPLORER | OFN_HIDEREADONLY;
166
167 bool res = BOOLToBool(::GetOpenFileNameA(&p));
168 resPath = GetUnicodeString(buf);
169 return res;
170 } 198 }
171 else 199 else
172 #endif 200#endif
173 { 201 {
174 WCHAR buf[kBufSize]; 202 UString tempPath;
175 MyStringCopy(buf, filePath); 203 unsigned size = filters.Size() + 1;
176 // OPENFILENAME_NT4W 204 unsigned i;
177 OPENFILENAMEW p; 205 for (i = 0; i < filters.Size(); i++)
206 size += filters[i].Len();
207 CObjArray<wchar_t> filterBuf(size);
208 // memset(filterBuf, 0, size * sizeof(wchar_t));
209 {
210 wchar_t *dest = filterBuf;
211 for (i = 0; i < filters.Size(); i++)
212 {
213 const UString &s = filters[i];
214 MyStringCopy(dest, s);
215 dest += s.Len() + 1;
216 }
217 *dest = 0;
218 // if ((unsigned)(dest + 1 - filterBuf) != size) return false;
219 }
220 my_compatib_OPENFILENAMEW p;
178 memset(&p, 0, sizeof(p)); 221 memset(&p, 0, sizeof(p));
179 p.lStructSize = my_compatib_OPENFILENAMEW_size; 222 p.lStructSize = my_compatib_OPENFILENAMEW_size;
180 p.hwndOwner = hwnd; 223 p.hwndOwner = hwndOwner;
181 224 if (size > 1)
182 WCHAR filterBuf[kFilterBufSize];
183 { 225 {
184 CDoubleZeroStringListW dz(filterBuf, kFilterBufSize);
185 dz.Add(filterDescription ? filterDescription : filter);
186 dz.Add(filter);
187 dz.Finish();
188 p.lpstrFilter = filterBuf; 226 p.lpstrFilter = filterBuf;
189 p.nFilterIndex = 1; 227 p.nFilterIndex = (DWORD)(FilterIndex + 1);
190 } 228 }
191 229 unsigned bufSize = MAX_PATH * 8 + FilePath.Len();
192 p.lpstrFile = buf; 230 if (lpstrInitialDir)
193 p.nMaxFile = kBufSize; 231 {
194 p.lpstrInitialDir = initialDir; 232 p.lpstrInitialDir = lpstrInitialDir;
195 p.lpstrTitle = title; 233 bufSize += MyStringLen(lpstrInitialDir);
196 p.Flags = OFN_EXPLORER | OFN_HIDEREADONLY 234 }
197 #ifdef UNDER_CE 235 p.nMaxFile = bufSize;
198 | (openFolder ? (MY__OFN_PROJECT | MY__OFN_SHOW_ALL) : 0) 236 p.lpstrFile = tempPath.GetBuf(bufSize);
199 #endif 237 MyStringCopy(p.lpstrFile, FilePath);
238 p.lpstrTitle = lpstrTitle;
239 p.Flags =
240 OFN_EXPLORER
241 | OFN_HIDEREADONLY
242 | OFN_NOCHANGEDIR
243 // | OFN_FORCESHOWHIDDEN // Win10 shows hidden items even without this flag
244 // | OFN_PATHMUSTEXIST
245 #ifdef UNDER_CE
246 | (OpenFolderMode ? (MY_OFN_PROJECT | MY_OFN_SHOW_ALL) : 0)
247 #endif
200 ; 248 ;
201 249 const BOOL b = SaveMode ?
202 bool res = BOOLToBool(::GetOpenFileNameW(&p)); 250 ::GetSaveFileNameW((LPOPENFILENAMEW)(void *)&p) :
203 resPath = buf; 251 ::GetOpenFileNameW((LPOPENFILENAMEW)(void *)&p);
204 return res; 252 /* DOCs: lpstrFile :
253 if the buffer is too small, then:
254 - the function returns FALSE
255 - the CommDlgExtendedError() returns FNERR_BUFFERTOOSMALL
256 - the first two bytes of the lpstrFile buffer contain the
257 required size, in bytes or characters. */
258 if (!b)
259 return false;
260 {
261 tempPath.ReleaseBuf_CalcLen(bufSize);
262 FilePath = tempPath;
263 FilterIndex = (int)p.nFilterIndex - 1;
264 return true;
265 }
205 } 266 }
206} 267}
207 268
diff --git a/CPP/Windows/CommonDialog.h b/CPP/Windows/CommonDialog.h
index aaf17ac..85b071f 100644
--- a/CPP/Windows/CommonDialog.h
+++ b/CPP/Windows/CommonDialog.h
@@ -1,22 +1,42 @@
1// Windows/CommonDialog.h 1// Windows/CommonDialog.h
2 2
3#ifndef __WINDOWS_COMMON_DIALOG_H 3#ifndef ZIP7_INC_WINDOWS_COMMON_DIALOG_H
4#define __WINDOWS_COMMON_DIALOG_H 4#define ZIP7_INC_WINDOWS_COMMON_DIALOG_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
8namespace NWindows { 8namespace NWindows {
9 9
10bool MyGetOpenFileName(HWND hwnd, LPCWSTR title, 10struct CCommonDialogInfo
11 LPCWSTR initialDir, // can be NULL, so dir prefix in filePath will be used 11{
12 LPCWSTR filePath, // full path 12 /* (FilterIndex == -1) means no selected filter.
13 LPCWSTR filterDescription, // like "All files (*.*)" 13 and (-1) also is reserved for unsupported custom filter.
14 LPCWSTR filter, // like "*.exe" 14 if (FilterIndex >= 0), then FilterIndex is index of filter */
15 UString &resPath 15 int FilterIndex; // [in / out]
16 #ifdef UNDER_CE 16 bool SaveMode;
17 , bool openFolder = false 17 #ifdef UNDER_CE
18 #endif 18 bool OpenFolderMode;
19); 19 #endif
20 HWND hwndOwner;
21 // LPCWSTR lpstrInitialDir;
22 LPCWSTR lpstrTitle;
23 UString FilePath; // [in / out]
24
25 CCommonDialogInfo()
26 {
27 FilterIndex = -1;
28 SaveMode = false;
29 #ifdef UNDER_CE
30 OpenFolderMode = false;
31 #endif
32 hwndOwner = NULL;
33 // lpstrInitialDir = NULL;
34 lpstrTitle = NULL;
35 }
36
37 /* (filters) : 2 sequential vector strings (Description, Masks) represent each filter */
38 bool CommonDlg_BrowseForFile(LPCWSTR lpstrInitialDir, const UStringVector &filters);
39};
20 40
21} 41}
22 42
diff --git a/CPP/Windows/Console.h b/CPP/Windows/Console.h
index 43e02fa..818b8d4 100644
--- a/CPP/Windows/Console.h
+++ b/CPP/Windows/Console.h
@@ -1,7 +1,7 @@
1// Windows/Console.h 1// Windows/Console.h
2 2
3#ifndef __WINDOWS_CONSOLE_H 3#ifndef ZIP7_INC_WINDOWS_CONSOLE_H
4#define __WINDOWS_CONSOLE_H 4#define ZIP7_INC_WINDOWS_CONSOLE_H
5 5
6#include "Defs.h" 6#include "Defs.h"
7 7
diff --git a/CPP/Windows/Control/ComboBox.cpp b/CPP/Windows/Control/ComboBox.cpp
index f6ed8d3..8da487d 100644
--- a/CPP/Windows/Control/ComboBox.cpp
+++ b/CPP/Windows/Control/ComboBox.cpp
@@ -43,10 +43,10 @@ LRESULT CComboBox::GetLBText(int index, UString &s)
43 s.Empty(); 43 s.Empty();
44 if (g_IsNT) 44 if (g_IsNT)
45 { 45 {
46 LRESULT len = SendMsgW(CB_GETLBTEXTLEN, MY__int_TO_WPARAM(index), 0); 46 LRESULT len = SendMsgW(CB_GETLBTEXTLEN, MY_int_TO_WPARAM(index), 0);
47 if (len == CB_ERR) 47 if (len == CB_ERR)
48 return len; 48 return len;
49 LRESULT len2 = SendMsgW(CB_GETLBTEXT, MY__int_TO_WPARAM(index), (LPARAM)s.GetBuf((unsigned)len)); 49 LRESULT len2 = SendMsgW(CB_GETLBTEXT, MY_int_TO_WPARAM(index), (LPARAM)s.GetBuf((unsigned)len));
50 if (len2 == CB_ERR) 50 if (len2 == CB_ERR)
51 return len; 51 return len;
52 if (len > len2) 52 if (len > len2)
@@ -55,11 +55,11 @@ LRESULT CComboBox::GetLBText(int index, UString &s)
55 return len; 55 return len;
56 } 56 }
57 AString sa; 57 AString sa;
58 LRESULT len = GetLBText(index, sa); 58 const LRESULT len = GetLBText(index, sa);
59 if (len == CB_ERR) 59 if (len == CB_ERR)
60 return len; 60 return len;
61 s = GetUnicodeString(sa); 61 s = GetUnicodeString(sa);
62 return s.Len(); 62 return (LRESULT)s.Len();
63} 63}
64#endif 64#endif
65 65
diff --git a/CPP/Windows/Control/ComboBox.h b/CPP/Windows/Control/ComboBox.h
index f08b1f7..2a60b8a 100644
--- a/CPP/Windows/Control/ComboBox.h
+++ b/CPP/Windows/Control/ComboBox.h
@@ -1,7 +1,7 @@
1// Windows/Control/ComboBox.h 1// Windows/Control/ComboBox.h
2 2
3#ifndef __WINDOWS_CONTROL_COMBOBOX_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_COMBOBOX_H
4#define __WINDOWS_CONTROL_COMBOBOX_H 4#define ZIP7_INC_WINDOWS_CONTROL_COMBOBOX_H
5 5
6#include "../../Common/MyWindows.h" 6#include "../../Common/MyWindows.h"
7 7
@@ -12,8 +12,6 @@
12namespace NWindows { 12namespace NWindows {
13namespace NControl { 13namespace NControl {
14 14
15#define MY__int_TO_WPARAM(i) ((WPARAM)(INT_PTR)(i))
16
17class CComboBox: public CWindow 15class CComboBox: public CWindow
18{ 16{
19public: 17public:
@@ -24,7 +22,8 @@ public:
24 #endif 22 #endif
25 23
26 /* If this parameter is -1, any current selection in the list is removed and the edit control is cleared.*/ 24 /* If this parameter is -1, any current selection in the list is removed and the edit control is cleared.*/
27 LRESULT SetCurSel(int index) { return SendMsg(CB_SETCURSEL, MY__int_TO_WPARAM(index), 0); } 25 LRESULT SetCurSel(int index) { return SendMsg(CB_SETCURSEL, MY_int_TO_WPARAM(index), 0); }
26 LRESULT SetCurSel(unsigned index) { return SendMsg(CB_SETCURSEL, index, 0); }
28 27
29 /* If no item is selected, it returns CB_ERR (-1) */ 28 /* If no item is selected, it returns CB_ERR (-1) */
30 int GetCurSel() { return (int)SendMsg(CB_GETCURSEL, 0, 0); } 29 int GetCurSel() { return (int)SendMsg(CB_GETCURSEL, 0, 0); }
@@ -32,15 +31,16 @@ public:
32 /* If an error occurs, it is CB_ERR (-1) */ 31 /* If an error occurs, it is CB_ERR (-1) */
33 int GetCount() { return (int)SendMsg(CB_GETCOUNT, 0, 0); } 32 int GetCount() { return (int)SendMsg(CB_GETCOUNT, 0, 0); }
34 33
35 LRESULT GetLBTextLen(int index) { return SendMsg(CB_GETLBTEXTLEN, MY__int_TO_WPARAM(index), 0); } 34 LRESULT GetLBTextLen(int index) { return SendMsg(CB_GETLBTEXTLEN, MY_int_TO_WPARAM(index), 0); }
36 LRESULT GetLBText(int index, LPTSTR s) { return SendMsg(CB_GETLBTEXT, MY__int_TO_WPARAM(index), (LPARAM)s); } 35 LRESULT GetLBText(int index, LPTSTR s) { return SendMsg(CB_GETLBTEXT, MY_int_TO_WPARAM(index), (LPARAM)s); }
37 LRESULT GetLBText(int index, CSysString &s); 36 LRESULT GetLBText(int index, CSysString &s);
38 #ifndef _UNICODE 37 #ifndef _UNICODE
39 LRESULT GetLBText(int index, UString &s); 38 LRESULT GetLBText(int index, UString &s);
40 #endif 39 #endif
41 40
42 LRESULT SetItemData(int index, LPARAM lParam) { return SendMsg(CB_SETITEMDATA, MY__int_TO_WPARAM(index), lParam); } 41 LRESULT SetItemData(int index, LPARAM lParam) { return SendMsg(CB_SETITEMDATA, MY_int_TO_WPARAM(index), lParam); }
43 LRESULT GetItemData(int index) { return SendMsg(CB_GETITEMDATA, MY__int_TO_WPARAM(index), 0); } 42 LRESULT GetItemData(int index) { return SendMsg(CB_GETITEMDATA, MY_int_TO_WPARAM(index), 0); }
43 LRESULT GetItemData(unsigned index) { return SendMsg(CB_GETITEMDATA, index, 0); }
44 44
45 LRESULT GetItemData_of_CurSel() { return GetItemData(GetCurSel()); } 45 LRESULT GetItemData_of_CurSel() { return GetItemData(GetCurSel()); }
46 46
@@ -57,7 +57,7 @@ public:
57 /* Returns: 57 /* Returns:
58 an INT value that represents the number of items remaining in the control. 58 an INT value that represents the number of items remaining in the control.
59 If (index) is invalid, the message returns CB_ERR. */ 59 If (index) is invalid, the message returns CB_ERR. */
60 LRESULT DeleteItem(int index) { return SendMsg(CBEM_DELETEITEM, MY__int_TO_WPARAM(index), 0); } 60 LRESULT DeleteItem(int index) { return SendMsg(CBEM_DELETEITEM, MY_int_TO_WPARAM(index), 0); }
61 61
62 LRESULT InsertItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_INSERTITEM, 0, (LPARAM)item); } 62 LRESULT InsertItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_INSERTITEM, 0, (LPARAM)item); }
63 #ifndef _UNICODE 63 #ifndef _UNICODE
@@ -65,7 +65,7 @@ public:
65 #endif 65 #endif
66 66
67 LRESULT SetItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_SETITEM, 0, (LPARAM)item); } 67 LRESULT SetItem(COMBOBOXEXITEM *item) { return SendMsg(CBEM_SETITEM, 0, (LPARAM)item); }
68 DWORD SetExtendedStyle(DWORD exMask, DWORD exStyle) { return (DWORD)SendMsg(CBEM_SETEXTENDEDSTYLE, exMask, exStyle); } 68 DWORD SetExtendedStyle(DWORD exMask, DWORD exStyle) { return (DWORD)SendMsg(CBEM_SETEXTENDEDSTYLE, exMask, (LPARAM)exStyle); }
69 HWND GetEditControl() { return (HWND)SendMsg(CBEM_GETEDITCONTROL, 0, 0); } 69 HWND GetEditControl() { return (HWND)SendMsg(CBEM_GETEDITCONTROL, 0, 0); }
70 HIMAGELIST SetImageList(HIMAGELIST imageList) { return (HIMAGELIST)SendMsg(CBEM_SETIMAGELIST, 0, (LPARAM)imageList); } 70 HIMAGELIST SetImageList(HIMAGELIST imageList) { return (HIMAGELIST)SendMsg(CBEM_SETIMAGELIST, 0, (LPARAM)imageList); }
71}; 71};
diff --git a/CPP/Windows/Control/CommandBar.h b/CPP/Windows/Control/CommandBar.h
index a619744..d1b2f17 100644
--- a/CPP/Windows/Control/CommandBar.h
+++ b/CPP/Windows/Control/CommandBar.h
@@ -1,7 +1,7 @@
1// Windows/Control/CommandBar.h 1// Windows/Control/CommandBar.h
2 2
3#ifndef __WINDOWS_CONTROL_COMMANDBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_COMMANDBAR_H
4#define __WINDOWS_CONTROL_COMMANDBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_COMMANDBAR_H
5 5
6#ifdef UNDER_CE 6#ifdef UNDER_CE
7 7
@@ -26,12 +26,12 @@ public:
26 // Macros 26 // Macros
27 // void Destroy() { CommandBar_Destroy(_window); } 27 // void Destroy() { CommandBar_Destroy(_window); }
28 // bool AddButtons(UINT numButtons, LPTBBUTTON buttons) { return BOOLToBool(SendMsg(TB_ADDBUTTONS, (WPARAM)numButtons, (LPARAM)buttons)); } 28 // bool AddButtons(UINT numButtons, LPTBBUTTON buttons) { return BOOLToBool(SendMsg(TB_ADDBUTTONS, (WPARAM)numButtons, (LPARAM)buttons)); }
29 bool InsertButton(int iButton, LPTBBUTTON button) { return BOOLToBool(SendMsg(TB_INSERTBUTTON, (WPARAM)iButton, (LPARAM)button)); } 29 // bool InsertButton(unsigned iButton, LPTBBUTTON button) { return BOOLToBool(SendMsg(TB_INSERTBUTTON, (WPARAM)iButton, (LPARAM)button)); }
30 BOOL AddToolTips(UINT numToolTips, LPTSTR toolTips) { return BOOLToBool(SendMsg(TB_SETTOOLTIPS, (WPARAM)numToolTips, (LPARAM)toolTips)); } 30 // BOOL AddToolTips(UINT numToolTips, LPTSTR toolTips) { return BOOLToBool(SendMsg(TB_SETTOOLTIPS, (WPARAM)numToolTips, (LPARAM)toolTips)); }
31 void AutoSize() { SendMsg(TB_AUTOSIZE, 0, 0); } 31 void AutoSize() { SendMsg(TB_AUTOSIZE, 0, 0); }
32 32
33 bool AddAdornments(DWORD dwFlags) { return BOOLToBool(::CommandBar_AddAdornments(_window, dwFlags, 0)); } 33 // bool AddAdornments(DWORD dwFlags) { return BOOLToBool(::CommandBar_AddAdornments(_window, dwFlags, 0)); }
34 int AddBitmap(HINSTANCE hInst, int idBitmap, int iNumImages, int iImageWidth, int iImageHeight) { return ::CommandBar_AddBitmap(_window, hInst, idBitmap, iNumImages, iImageWidth, iImageHeight); } 34 // int AddBitmap(HINSTANCE hInst, int idBitmap, int iNumImages, int iImageWidth, int iImageHeight) { return ::CommandBar_AddBitmap(_window, hInst, idBitmap, iNumImages, iImageWidth, iImageHeight); }
35 bool DrawMenuBar(WORD iButton) { return BOOLToBool(::CommandBar_DrawMenuBar(_window, iButton)); } 35 bool DrawMenuBar(WORD iButton) { return BOOLToBool(::CommandBar_DrawMenuBar(_window, iButton)); }
36 HMENU GetMenu(WORD iButton) { return ::CommandBar_GetMenu(_window, iButton); } 36 HMENU GetMenu(WORD iButton) { return ::CommandBar_GetMenu(_window, iButton); }
37 int Height() { return CommandBar_Height(_window); } 37 int Height() { return CommandBar_Height(_window); }
diff --git a/CPP/Windows/Control/Dialog.cpp b/CPP/Windows/Control/Dialog.cpp
index 9ddd234..c8f1bd2 100644
--- a/CPP/Windows/Control/Dialog.cpp
+++ b/CPP/Windows/Control/Dialog.cpp
@@ -18,7 +18,14 @@ extern bool g_IsNT;
18namespace NWindows { 18namespace NWindows {
19namespace NControl { 19namespace NControl {
20 20
21static INT_PTR APIENTRY DialogProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) 21static
22#ifdef Z7_OLD_WIN_SDK
23 BOOL
24#else
25 INT_PTR
26#endif
27APIENTRY
28DialogProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam)
22{ 29{
23 CWindow tempDialog(dialogHWND); 30 CWindow tempDialog(dialogHWND);
24 if (message == WM_INITDIALOG) 31 if (message == WM_INITDIALOG)
@@ -45,7 +52,7 @@ bool CDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
45 switch (message) 52 switch (message)
46 { 53 {
47 case WM_INITDIALOG: return OnInit(); 54 case WM_INITDIALOG: return OnInit();
48 case WM_COMMAND: return OnCommand(wParam, lParam); 55 case WM_COMMAND: return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam);
49 case WM_NOTIFY: return OnNotify((UINT)wParam, (LPNMHDR) lParam); 56 case WM_NOTIFY: return OnNotify((UINT)wParam, (LPNMHDR) lParam);
50 case WM_TIMER: return OnTimer(wParam, lParam); 57 case WM_TIMER: return OnTimer(wParam, lParam);
51 case WM_SIZE: return OnSize(wParam, LOWORD(lParam), HIWORD(lParam)); 58 case WM_SIZE: return OnSize(wParam, LOWORD(lParam), HIWORD(lParam));
@@ -65,19 +72,21 @@ bool CDialog::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
65 } 72 }
66} 73}
67 74
68bool CDialog::OnCommand(WPARAM wParam, LPARAM lParam) 75/*
76bool CDialog::OnCommand2(WPARAM wParam, LPARAM lParam)
69{ 77{
70 return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam); 78 return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam);
71} 79}
80*/
72 81
73bool CDialog::OnCommand(int code, int itemID, LPARAM lParam) 82bool CDialog::OnCommand(unsigned code, unsigned itemID, LPARAM lParam)
74{ 83{
75 if (code == BN_CLICKED) 84 if (code == BN_CLICKED)
76 return OnButtonClicked(itemID, (HWND)lParam); 85 return OnButtonClicked(itemID, (HWND)lParam);
77 return false; 86 return false;
78} 87}
79 88
80bool CDialog::OnButtonClicked(int buttonID, HWND /* buttonHWND */) 89bool CDialog::OnButtonClicked(unsigned buttonID, HWND /* buttonHWND */)
81{ 90{
82 switch (buttonID) 91 switch (buttonID)
83 { 92 {
@@ -90,6 +99,28 @@ bool CDialog::OnButtonClicked(int buttonID, HWND /* buttonHWND */)
90 return true; 99 return true;
91} 100}
92 101
102#ifndef UNDER_CE
103/* in win2000/win98 : monitor functions are supported.
104 We need dynamic linking, if we want nt4/win95 support in program.
105 Even if we compile the code with low (WINVER) value, we still
106 want to use monitor functions. So we declare missing functions here */
107// #if (WINVER < 0x0500)
108#ifndef MONITOR_DEFAULTTOPRIMARY
109extern "C" {
110DECLARE_HANDLE(HMONITOR);
111#define MONITOR_DEFAULTTOPRIMARY 0x00000001
112typedef struct tagMONITORINFO
113{
114 DWORD cbSize;
115 RECT rcMonitor;
116 RECT rcWork;
117 DWORD dwFlags;
118} MONITORINFO, *LPMONITORINFO;
119WINUSERAPI HMONITOR WINAPI MonitorFromWindow(HWND hwnd, DWORD dwFlags);
120WINUSERAPI BOOL WINAPI GetMonitorInfoA(HMONITOR hMonitor, LPMONITORINFO lpmi);
121}
122#endif
123#endif
93 124
94static bool GetWorkAreaRect(RECT *rect, HWND hwnd) 125static bool GetWorkAreaRect(RECT *rect, HWND hwnd)
95{ 126{
@@ -172,7 +203,7 @@ int CDialog::Units_To_Pixels_X(int units)
172 return rect.right - rect.left; 203 return rect.right - rect.left;
173} 204}
174 205
175bool CDialog::GetItemSizes(int id, int &x, int &y) 206bool CDialog::GetItemSizes(unsigned id, int &x, int &y)
176{ 207{
177 RECT rect; 208 RECT rect;
178 if (!::GetWindowRect(GetItem(id), &rect)) 209 if (!::GetWindowRect(GetItem(id), &rect))
@@ -182,13 +213,13 @@ bool CDialog::GetItemSizes(int id, int &x, int &y)
182 return true; 213 return true;
183} 214}
184 215
185void CDialog::GetClientRectOfItem(int id, RECT &rect) 216void CDialog::GetClientRectOfItem(unsigned id, RECT &rect)
186{ 217{
187 ::GetWindowRect(GetItem(id), &rect); 218 ::GetWindowRect(GetItem(id), &rect);
188 ScreenToClient(&rect); 219 ScreenToClient(&rect);
189} 220}
190 221
191bool CDialog::MoveItem(int id, int x, int y, int width, int height, bool repaint) 222bool CDialog::MoveItem(unsigned id, int x, int y, int width, int height, bool repaint)
192{ 223{
193 return BOOLToBool(::MoveWindow(GetItem(id), x, y, width, height, BoolToBOOL(repaint))); 224 return BOOLToBool(::MoveWindow(GetItem(id), x, y, width, height, BoolToBOOL(repaint)));
194} 225}
@@ -356,8 +387,8 @@ void CDialog::NormalizePosition()
356 387
357bool CModelessDialog::Create(LPCTSTR templateName, HWND parentWindow) 388bool CModelessDialog::Create(LPCTSTR templateName, HWND parentWindow)
358{ 389{
359 HWND aHWND = CreateDialogParam(g_hInstance, templateName, parentWindow, DialogProcedure, (LPARAM)this); 390 const HWND aHWND = CreateDialogParam(g_hInstance, templateName, parentWindow, DialogProcedure, (LPARAM)this);
360 if (aHWND == 0) 391 if (!aHWND)
361 return false; 392 return false;
362 Attach(aHWND); 393 Attach(aHWND);
363 return true; 394 return true;
diff --git a/CPP/Windows/Control/Dialog.h b/CPP/Windows/Control/Dialog.h
index 8a39e99..06be4bf 100644
--- a/CPP/Windows/Control/Dialog.h
+++ b/CPP/Windows/Control/Dialog.h
@@ -1,7 +1,7 @@
1// Windows/Control/Dialog.h 1// Windows/Control/Dialog.h
2 2
3#ifndef __WINDOWS_CONTROL_DIALOG_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_DIALOG_H
4#define __WINDOWS_CONTROL_DIALOG_H 4#define ZIP7_INC_WINDOWS_CONTROL_DIALOG_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
@@ -10,65 +10,66 @@ namespace NControl {
10 10
11class CDialog: public CWindow 11class CDialog: public CWindow
12{ 12{
13 // Z7_CLASS_NO_COPY(CDialog)
13public: 14public:
14 CDialog(HWND wnd = NULL): CWindow(wnd){}; 15 CDialog(HWND wnd = NULL): CWindow(wnd) {}
15 virtual ~CDialog() {}; 16 virtual ~CDialog() {}
16 17
17 HWND GetItem(int itemID) const 18 HWND GetItem(unsigned itemID) const
18 { return GetDlgItem(_window, itemID); } 19 { return GetDlgItem(_window, (int)itemID); }
19 20
20 bool EnableItem(int itemID, bool enable) const 21 bool EnableItem(unsigned itemID, bool enable) const
21 { return BOOLToBool(::EnableWindow(GetItem(itemID), BoolToBOOL(enable))); } 22 { return BOOLToBool(::EnableWindow(GetItem(itemID), BoolToBOOL(enable))); }
22 23
23 bool ShowItem(int itemID, int cmdShow) const 24 bool ShowItem(unsigned itemID, int cmdShow) const
24 { return BOOLToBool(::ShowWindow(GetItem(itemID), cmdShow)); } 25 { return BOOLToBool(::ShowWindow(GetItem(itemID), cmdShow)); }
25 26
26 bool ShowItem_Bool(int itemID, bool show) const 27 bool ShowItem_Bool(unsigned itemID, bool show) const
27 { return ShowItem(itemID, show ? SW_SHOW: SW_HIDE); } 28 { return ShowItem(itemID, show ? SW_SHOW: SW_HIDE); }
28 29
29 bool HideItem(int itemID) const { return ShowItem(itemID, SW_HIDE); } 30 bool HideItem(unsigned itemID) const { return ShowItem(itemID, SW_HIDE); }
30 31
31 bool SetItemText(int itemID, LPCTSTR s) 32 bool SetItemText(unsigned itemID, LPCTSTR s)
32 { return BOOLToBool(SetDlgItemText(_window, itemID, s)); } 33 { return BOOLToBool(SetDlgItemText(_window, (int)itemID, s)); }
33 34
34 bool SetItemTextA(int itemID, LPCSTR s) 35 bool SetItemTextA(unsigned itemID, LPCSTR s)
35 { return BOOLToBool(SetDlgItemTextA(_window, itemID, s)); } 36 { return BOOLToBool(SetDlgItemTextA(_window, (int)itemID, s)); }
36 37
37 bool SetItemText_Empty(int itemID) 38 bool SetItemText_Empty(unsigned itemID)
38 { return SetItemText(itemID, TEXT("")); } 39 { return SetItemText(itemID, TEXT("")); }
39 40
40 #ifndef _UNICODE 41 #ifndef _UNICODE
41 bool SetItemText(int itemID, LPCWSTR s) 42 bool SetItemText(unsigned itemID, LPCWSTR s)
42 { 43 {
43 CWindow window(GetItem(itemID)); 44 CWindow window(GetItem(itemID));
44 return window.SetText(s); 45 return window.SetText(s);
45 } 46 }
46 #endif 47 #endif
47 48
48 UINT GetItemText(int itemID, LPTSTR string, int maxCount) 49 UINT GetItemText(unsigned itemID, LPTSTR string, unsigned maxCount)
49 { return GetDlgItemText(_window, itemID, string, maxCount); } 50 { return GetDlgItemText(_window, (int)itemID, string, (int)maxCount); }
50 #ifndef _UNICODE 51 #ifndef _UNICODE
51 /* 52 /*
52 bool GetItemText(int itemID, LPWSTR string, int maxCount) 53 bool GetItemText(unsigned itemID, LPWSTR string, int maxCount)
53 { 54 {
54 CWindow window(GetItem(itemID)); 55 CWindow window(GetItem(unsigned));
55 return window.GetText(string, maxCount); 56 return window.GetText(string, maxCount);
56 } 57 }
57 */ 58 */
58 #endif 59 #endif
59 60
60 bool GetItemText(int itemID, UString &s) 61 bool GetItemText(unsigned itemID, UString &s)
61 { 62 {
62 CWindow window(GetItem(itemID)); 63 CWindow window(GetItem(itemID));
63 return window.GetText(s); 64 return window.GetText(s);
64 } 65 }
65 66
66 bool SetItemInt(int itemID, UINT value, bool isSigned) 67 bool SetItemInt(unsigned itemID, UINT value, bool isSigned)
67 { return BOOLToBool(SetDlgItemInt(_window, itemID, value, BoolToBOOL(isSigned))); } 68 { return BOOLToBool(SetDlgItemInt(_window, (int)itemID, value, BoolToBOOL(isSigned))); }
68 bool GetItemInt(int itemID, bool isSigned, UINT &value) 69 bool GetItemInt(unsigned itemID, bool isSigned, UINT &value)
69 { 70 {
70 BOOL result; 71 BOOL result;
71 value = GetDlgItemInt(_window, itemID, &result, BoolToBOOL(isSigned)); 72 value = GetDlgItemInt(_window, (int)itemID, &result, BoolToBOOL(isSigned));
72 return BOOLToBool(result); 73 return BOOLToBool(result);
73 } 74 }
74 75
@@ -80,7 +81,7 @@ public:
80 LRESULT SendMsg_NextDlgCtl(WPARAM wParam, LPARAM lParam) 81 LRESULT SendMsg_NextDlgCtl(WPARAM wParam, LPARAM lParam)
81 { return SendMsg(WM_NEXTDLGCTL, wParam, lParam); } 82 { return SendMsg(WM_NEXTDLGCTL, wParam, lParam); }
82 LRESULT SendMsg_NextDlgCtl_HWND(HWND hwnd) { return SendMsg_NextDlgCtl((WPARAM)hwnd, TRUE); } 83 LRESULT SendMsg_NextDlgCtl_HWND(HWND hwnd) { return SendMsg_NextDlgCtl((WPARAM)hwnd, TRUE); }
83 LRESULT SendMsg_NextDlgCtl_CtlId(int id) { return SendMsg_NextDlgCtl_HWND(GetItem(id)); } 84 LRESULT SendMsg_NextDlgCtl_CtlId(unsigned id) { return SendMsg_NextDlgCtl_HWND(GetItem(id)); }
84 LRESULT SendMsg_NextDlgCtl_Next() { return SendMsg_NextDlgCtl(0, FALSE); } 85 LRESULT SendMsg_NextDlgCtl_Next() { return SendMsg_NextDlgCtl(0, FALSE); }
85 LRESULT SendMsg_NextDlgCtl_Prev() { return SendMsg_NextDlgCtl(1, FALSE); } 86 LRESULT SendMsg_NextDlgCtl_Prev() { return SendMsg_NextDlgCtl(1, FALSE); }
86 87
@@ -90,26 +91,27 @@ public:
90 bool IsMessage(LPMSG message) 91 bool IsMessage(LPMSG message)
91 { return BOOLToBool(IsDialogMessage(_window, message)); } 92 { return BOOLToBool(IsDialogMessage(_window, message)); }
92 93
93 LRESULT SendItemMessage(int itemID, UINT message, WPARAM wParam, LPARAM lParam) 94 LRESULT SendItemMessage(unsigned itemID, UINT message, WPARAM wParam, LPARAM lParam)
94 { return SendDlgItemMessage(_window, itemID, message, wParam, lParam); } 95 { return SendDlgItemMessage(_window, (int)itemID, message, wParam, lParam); }
95 96
96 bool CheckButton(int buttonID, UINT checkState) 97 bool CheckButton(unsigned buttonID, UINT checkState)
97 { return BOOLToBool(CheckDlgButton(_window, buttonID, checkState)); } 98 { return BOOLToBool(CheckDlgButton(_window, (int)buttonID, checkState)); }
98 bool CheckButton(int buttonID, bool checkState) 99 bool CheckButton(unsigned buttonID, bool checkState)
99 { return CheckButton(buttonID, UINT(checkState ? BST_CHECKED : BST_UNCHECKED)); } 100 { return CheckButton(buttonID, UINT(checkState ? BST_CHECKED : BST_UNCHECKED)); }
100 101
101 UINT IsButtonChecked(int buttonID) const 102 UINT IsButtonChecked_BST(unsigned buttonID) const
102 { return IsDlgButtonChecked(_window, buttonID); } 103 { return IsDlgButtonChecked(_window, (int)buttonID); }
103 bool IsButtonCheckedBool(int buttonID) const 104 bool IsButtonCheckedBool(unsigned buttonID) const
104 { return (IsButtonChecked(buttonID) == BST_CHECKED); } 105 { return (IsButtonChecked_BST(buttonID) == BST_CHECKED); }
105 106
106 bool CheckRadioButton(int firstButtonID, int lastButtonID, int checkButtonID) 107 bool CheckRadioButton(unsigned firstButtonID, unsigned lastButtonID, unsigned checkButtonID)
107 { return BOOLToBool(::CheckRadioButton(_window, firstButtonID, lastButtonID, checkButtonID)); } 108 { return BOOLToBool(::CheckRadioButton(_window,
109 (int)firstButtonID, (int)lastButtonID, (int)checkButtonID)); }
108 110
109 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 111 virtual bool OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
110 virtual bool OnInit() { return true; } 112 virtual bool OnInit() { return true; }
111 virtual bool OnCommand(WPARAM wParam, LPARAM lParam); 113 // virtual bool OnCommand2(WPARAM wParam, LPARAM lParam);
112 virtual bool OnCommand(int code, int itemID, LPARAM lParam); 114 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam);
113 virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; } 115 virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; }
114 virtual bool OnDestroy() { return false; } 116 virtual bool OnDestroy() { return false; }
115 117
@@ -120,11 +122,11 @@ public:
120 virtual void OnHelp(LPHELPINFO) { OnHelp(); } 122 virtual void OnHelp(LPHELPINFO) { OnHelp(); }
121 #endif 123 #endif
122 */ 124 */
123 virtual void OnHelp() {}; 125 virtual void OnHelp() {}
124 126
125 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 127 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND);
126 virtual void OnOK() {}; 128 virtual void OnOK() {}
127 virtual void OnCancel() {}; 129 virtual void OnCancel() {}
128 virtual void OnClose() {} 130 virtual void OnClose() {}
129 virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */) { return false; } 131 virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */) { return false; }
130 virtual bool OnTimer(WPARAM /* timerID */, LPARAM /* callback */) { return false; } 132 virtual bool OnTimer(WPARAM /* timerID */, LPARAM /* callback */) { return false; }
@@ -136,9 +138,11 @@ public:
136 138
137 bool GetMargins(int margin, int &x, int &y); 139 bool GetMargins(int margin, int &x, int &y);
138 int Units_To_Pixels_X(int units); 140 int Units_To_Pixels_X(int units);
139 bool GetItemSizes(int id, int &x, int &y); 141 bool GetItemSizes(unsigned id, int &x, int &y);
140 void GetClientRectOfItem(int id, RECT &rect); 142 void GetClientRectOfItem(unsigned id, RECT &rect);
141 bool MoveItem(int id, int x, int y, int width, int height, bool repaint = true); 143 bool MoveItem(unsigned id, int x, int y, int width, int height, bool repaint = true);
144 bool MoveItem_RECT(unsigned id, const RECT &r, bool repaint = true)
145 { return MoveItem(id, r.left, r.top, RECT_SIZE_X(r), RECT_SIZE_Y(r), repaint); }
142 146
143 void NormalizeSize(bool fullNormalize = false); 147 void NormalizeSize(bool fullNormalize = false);
144 void NormalizePosition(); 148 void NormalizePosition();
@@ -152,9 +156,9 @@ public:
152 #ifndef _UNICODE 156 #ifndef _UNICODE
153 bool Create(LPCWSTR templateName, HWND parentWindow); 157 bool Create(LPCWSTR templateName, HWND parentWindow);
154 #endif 158 #endif
155 virtual void OnOK() { Destroy(); } 159 virtual void OnOK() Z7_override { Destroy(); }
156 virtual void OnCancel() { Destroy(); } 160 virtual void OnCancel() Z7_override { Destroy(); }
157 virtual void OnClose() { Destroy(); } 161 virtual void OnClose() Z7_override { Destroy(); }
158}; 162};
159 163
160class CModalDialog: public CDialog 164class CModalDialog: public CDialog
@@ -167,18 +171,18 @@ public:
167 #endif 171 #endif
168 172
169 bool End(INT_PTR result) { return BOOLToBool(::EndDialog(_window, result)); } 173 bool End(INT_PTR result) { return BOOLToBool(::EndDialog(_window, result)); }
170 virtual void OnOK() { End(IDOK); } 174 virtual void OnOK() Z7_override { End(IDOK); }
171 virtual void OnCancel() { End(IDCANCEL); } 175 virtual void OnCancel() Z7_override { End(IDCANCEL); }
172 virtual void OnClose() { End(IDCLOSE); } 176 virtual void OnClose() Z7_override { End(IDCLOSE); }
173}; 177};
174 178
175class CDialogChildControl: public NWindows::CWindow 179class CDialogChildControl: public NWindows::CWindow
176{ 180{
177 int m_ID; 181 // unsigned m_ID;
178public: 182public:
179 void Init(const NWindows::NControl::CDialog &parentDialog, int id) 183 void Init(const NWindows::NControl::CDialog &parentDialog, unsigned id)
180 { 184 {
181 m_ID = id; 185 // m_ID = id;
182 Attach(parentDialog.GetItem(id)); 186 Attach(parentDialog.GetItem(id));
183 } 187 }
184}; 188};
diff --git a/CPP/Windows/Control/Edit.h b/CPP/Windows/Control/Edit.h
index 51a22c5..963470d 100644
--- a/CPP/Windows/Control/Edit.h
+++ b/CPP/Windows/Control/Edit.h
@@ -1,7 +1,7 @@
1// Windows/Control/Edit.h 1// Windows/Control/Edit.h
2 2
3#ifndef __WINDOWS_CONTROL_EDIT_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_EDIT_H
4#define __WINDOWS_CONTROL_EDIT_H 4#define ZIP7_INC_WINDOWS_CONTROL_EDIT_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
diff --git a/CPP/Windows/Control/ImageList.h b/CPP/Windows/Control/ImageList.h
index 19feb11..688f177 100644
--- a/CPP/Windows/Control/ImageList.h
+++ b/CPP/Windows/Control/ImageList.h
@@ -1,7 +1,7 @@
1// Windows/Control/ImageList.h 1// Windows/Control/ImageList.h
2 2
3#ifndef __WINDOWS_CONTROL_IMAGE_LIST_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_IMAGE_LIST_H
4#define __WINDOWS_CONTROL_IMAGE_LIST_H 4#define ZIP7_INC_WINDOWS_CONTROL_IMAGE_LIST_H
5 5
6#include <CommCtrl.h> 6#include <CommCtrl.h>
7 7
@@ -56,7 +56,7 @@ public:
56 bool GetImageInfo(int index, IMAGEINFO* imageInfo) const 56 bool GetImageInfo(int index, IMAGEINFO* imageInfo) const
57 { return BOOLToBool(ImageList_GetImageInfo(m_Object, index, imageInfo)); } 57 { return BOOLToBool(ImageList_GetImageInfo(m_Object, index, imageInfo)); }
58 58
59 int Add(HBITMAP hbmImage, HBITMAP hbmMask = 0) 59 int Add(HBITMAP hbmImage, HBITMAP hbmMask = NULL)
60 { return ImageList_Add(m_Object, hbmImage, hbmMask); } 60 { return ImageList_Add(m_Object, hbmImage, hbmMask); }
61 int AddMasked(HBITMAP hbmImage, COLORREF mask) 61 int AddMasked(HBITMAP hbmImage, COLORREF mask)
62 { return ImageList_AddMasked(m_Object, hbmImage, mask); } 62 { return ImageList_AddMasked(m_Object, hbmImage, mask); }
diff --git a/CPP/Windows/Control/ListView.cpp b/CPP/Windows/Control/ListView.cpp
index 16cfd39..3e8786a 100644
--- a/CPP/Windows/Control/ListView.cpp
+++ b/CPP/Windows/Control/ListView.cpp
@@ -20,78 +20,85 @@ bool CListView::CreateEx(DWORD exStyle, DWORD style,
20 height, parentWindow, idOrHMenu, instance, createParam); 20 height, parentWindow, idOrHMenu, instance, createParam);
21} 21}
22 22
23bool CListView::GetItemParam(int index, LPARAM &param) const 23/* note: LVITEM and LVCOLUMN structures contain optional fields
24 depending from preprocessor macros:
25 #if (_WIN32_IE >= 0x0300)
26 #if (_WIN32_WINNT >= 0x0501)
27 #if (_WIN32_WINNT >= 0x0600)
28*/
29
30bool CListView::GetItemParam(unsigned index, LPARAM &param) const
24{ 31{
25 LVITEM item; 32 LVITEM item;
26 item.iItem = index; 33 item.iItem = (int)index;
27 item.iSubItem = 0; 34 item.iSubItem = 0;
28 item.mask = LVIF_PARAM; 35 item.mask = LVIF_PARAM;
29 bool aResult = GetItem(&item); 36 const bool res = GetItem(&item);
30 param = item.lParam; 37 param = item.lParam;
31 return aResult; 38 return res;
32} 39}
33 40
34int CListView::InsertColumn(int columnIndex, LPCTSTR text, int width) 41int CListView::InsertColumn(unsigned columnIndex, LPCTSTR text, int width)
35{ 42{
36 LVCOLUMN ci; 43 LVCOLUMN ci;
37 ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; 44 ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;
38 ci.pszText = (LPTSTR)(void *)text; 45 ci.pszText = (LPTSTR)(void *)text;
39 ci.iSubItem = columnIndex; 46 ci.iSubItem = (int)columnIndex;
40 ci.cx = width; 47 ci.cx = width;
41 return InsertColumn(columnIndex, &ci); 48 return InsertColumn(columnIndex, &ci);
42} 49}
43 50
44int CListView::InsertItem(int index, LPCTSTR text) 51int CListView::InsertItem(unsigned index, LPCTSTR text)
45{ 52{
46 LVITEM item; 53 LVITEM item;
47 item.mask = LVIF_TEXT | LVIF_PARAM; 54 item.mask = LVIF_TEXT | LVIF_PARAM;
48 item.iItem = index; 55 item.iItem = (int)index;
49 item.lParam = index; 56 item.lParam = (LPARAM)index;
50 item.pszText = (LPTSTR)(void *)text; 57 item.pszText = (LPTSTR)(void *)text;
51 item.iSubItem = 0; 58 item.iSubItem = 0;
52 return InsertItem(&item); 59 return InsertItem(&item);
53} 60}
54 61
55int CListView::SetSubItem(int index, int subIndex, LPCTSTR text) 62int CListView::SetSubItem(unsigned index, unsigned subIndex, LPCTSTR text)
56{ 63{
57 LVITEM item; 64 LVITEM item;
58 item.mask = LVIF_TEXT; 65 item.mask = LVIF_TEXT;
59 item.iItem = index; 66 item.iItem = (int)index;
60 item.pszText = (LPTSTR)(void *)text; 67 item.pszText = (LPTSTR)(void *)text;
61 item.iSubItem = subIndex; 68 item.iSubItem = (int)subIndex;
62 return SetItem(&item); 69 return SetItem(&item);
63} 70}
64 71
65#ifndef _UNICODE 72#ifndef _UNICODE
66 73
67int CListView::InsertColumn(int columnIndex, LPCWSTR text, int width) 74int CListView::InsertColumn(unsigned columnIndex, LPCWSTR text, int width)
68{ 75{
69 LVCOLUMNW ci; 76 LVCOLUMNW ci;
70 ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; 77 ci.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;
71 ci.pszText = (LPWSTR)(void *)text; 78 ci.pszText = (LPWSTR)(void *)text;
72 ci.iSubItem = columnIndex; 79 ci.iSubItem = (int)columnIndex;
73 ci.cx = width; 80 ci.cx = width;
74 return InsertColumn(columnIndex, &ci); 81 return InsertColumn(columnIndex, &ci);
75} 82}
76 83
77int CListView::InsertItem(int index, LPCWSTR text) 84int CListView::InsertItem(unsigned index, LPCWSTR text)
78{ 85{
79 LVITEMW item; 86 LVITEMW item;
80 item.mask = LVIF_TEXT | LVIF_PARAM; 87 item.mask = LVIF_TEXT | LVIF_PARAM;
81 item.iItem = index; 88 item.iItem = (int)index;
82 item.lParam = index; 89 item.lParam = (LPARAM)index;
83 item.pszText = (LPWSTR)(void *)text; 90 item.pszText = (LPWSTR)(void *)text;
84 item.iSubItem = 0; 91 item.iSubItem = 0;
85 return InsertItem(&item); 92 return InsertItem(&item);
86} 93}
87 94
88int CListView::SetSubItem(int index, int subIndex, LPCWSTR text) 95int CListView::SetSubItem(unsigned index, unsigned subIndex, LPCWSTR text)
89{ 96{
90 LVITEMW item; 97 LVITEMW item;
91 item.mask = LVIF_TEXT; 98 item.mask = LVIF_TEXT;
92 item.iItem = index; 99 item.iItem = (int)index;
93 item.pszText = (LPWSTR)(void *)text; 100 item.pszText = (LPWSTR)(void *)text;
94 item.iSubItem = subIndex; 101 item.iSubItem = (int)subIndex;
95 return SetItem(&item); 102 return SetItem(&item);
96} 103}
97 104
diff --git a/CPP/Windows/Control/ListView.h b/CPP/Windows/Control/ListView.h
index a13b104..11a33a0 100644
--- a/CPP/Windows/Control/ListView.h
+++ b/CPP/Windows/Control/ListView.h
@@ -1,7 +1,7 @@
1// Windows/Control/ListView.h 1// Windows/Control/ListView.h
2 2
3#ifndef __WINDOWS_CONTROL_LISTVIEW_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_LISTVIEW_H
4#define __WINDOWS_CONTROL_LISTVIEW_H 4#define ZIP7_INC_WINDOWS_CONTROL_LISTVIEW_H
5 5
6#include "../../Common/MyWindows.h" 6#include "../../Common/MyWindows.h"
7 7
@@ -28,11 +28,11 @@ public:
28 } 28 }
29 29
30 bool DeleteAllItems() { return BOOLToBool(ListView_DeleteAllItems(_window)); } 30 bool DeleteAllItems() { return BOOLToBool(ListView_DeleteAllItems(_window)); }
31 bool DeleteColumn(int columnIndex) { return BOOLToBool(ListView_DeleteColumn(_window, columnIndex)); } 31 bool DeleteColumn(unsigned columnIndex) { return BOOLToBool(ListView_DeleteColumn(_window, columnIndex)); }
32 32
33 int InsertColumn(int columnIndex, const LVCOLUMN *columnInfo) { return ListView_InsertColumn(_window, columnIndex, columnInfo); } 33 int InsertColumn(unsigned columnIndex, const LVCOLUMN *columnInfo) { return ListView_InsertColumn(_window, columnIndex, columnInfo); }
34 int InsertColumn(int columnIndex, LPCTSTR text, int width); 34 int InsertColumn(unsigned columnIndex, LPCTSTR text, int width);
35 bool SetColumnOrderArray(int count, const int *columns) 35 bool SetColumnOrderArray(unsigned count, const int *columns)
36 { return BOOLToBool(ListView_SetColumnOrderArray(_window, count, (int *)(void *)columns)); } 36 { return BOOLToBool(ListView_SetColumnOrderArray(_window, count, (int *)(void *)columns)); }
37 37
38 /* 38 /*
@@ -46,43 +46,49 @@ public:
46 */ 46 */
47 47
48 int InsertItem(const LVITEM* item) { return ListView_InsertItem(_window, item); } 48 int InsertItem(const LVITEM* item) { return ListView_InsertItem(_window, item); }
49 int InsertItem(int index, LPCTSTR text); 49 int InsertItem(unsigned index, LPCTSTR text);
50 bool SetItem(const LVITEM* item) { return BOOLToBool(ListView_SetItem(_window, item)); } 50 bool SetItem(const LVITEM* item) { return BOOLToBool(ListView_SetItem(_window, item)); }
51 int SetSubItem(int index, int subIndex, LPCTSTR text); 51 int SetSubItem(unsigned index, unsigned subIndex, LPCTSTR text);
52 52
53 #ifndef _UNICODE 53 #ifndef _UNICODE
54 54
55 int InsertColumn(int columnIndex, const LVCOLUMNW *columnInfo) { return (int)SendMsg(LVM_INSERTCOLUMNW, (WPARAM)columnIndex, (LPARAM)columnInfo); } 55 int InsertColumn(unsigned columnIndex, const LVCOLUMNW *columnInfo) { return (int)SendMsg(LVM_INSERTCOLUMNW, (WPARAM)columnIndex, (LPARAM)columnInfo); }
56 int InsertColumn(int columnIndex, LPCWSTR text, int width); 56 int InsertColumn(unsigned columnIndex, LPCWSTR text, int width);
57 int InsertItem(const LV_ITEMW* item) { return (int)SendMsg(LVM_INSERTITEMW, 0, (LPARAM)item); } 57 int InsertItem(const LV_ITEMW* item) { return (int)SendMsg(LVM_INSERTITEMW, 0, (LPARAM)item); }
58 int InsertItem(int index, LPCWSTR text); 58 int InsertItem(unsigned index, LPCWSTR text);
59 bool SetItem(const LV_ITEMW* item) { return BOOLToBool((BOOL)SendMsg(LVM_SETITEMW, 0, (LPARAM)item)); } 59 bool SetItem(const LV_ITEMW* item) { return BOOLToBool((BOOL)SendMsg(LVM_SETITEMW, 0, (LPARAM)item)); }
60 int SetSubItem(int index, int subIndex, LPCWSTR text); 60 int SetSubItem(unsigned index, unsigned subIndex, LPCWSTR text);
61 61
62 #endif 62 #endif
63 63
64 bool DeleteItem(int itemIndex) { return BOOLToBool(ListView_DeleteItem(_window, itemIndex)); } 64 bool DeleteItem(unsigned itemIndex) { return BOOLToBool(ListView_DeleteItem(_window, itemIndex)); }
65 65
66 UINT GetSelectedCount() const { return ListView_GetSelectedCount(_window); } 66 UINT GetSelectedCount() const { return ListView_GetSelectedCount(_window); }
67 int GetItemCount() const { return ListView_GetItemCount(_window); } 67 int GetItemCount() const { return ListView_GetItemCount(_window); }
68 68
69 INT GetSelectionMark() const { return ListView_GetSelectionMark(_window); } 69 INT GetSelectionMark() const { return ListView_GetSelectionMark(_window); }
70 70
71 void SetItemCount(int numItems) { ListView_SetItemCount(_window, numItems); } 71 void SetItemCount(unsigned numItems) { ListView_SetItemCount(_window, numItems); }
72 void SetItemCountEx(int numItems, DWORD flags) { ListView_SetItemCountEx(_window, numItems, flags); } 72 void SetItemCountEx(unsigned numItems, DWORD flags) { ListView_SetItemCountEx(_window, numItems, flags); }
73 73
74 /* startIndex : The index of the item with which to begin the search,
75 or -1 to find the first item that matches the specified flags.
76 The specified item itself is excluded from the search. */
74 int GetNextItem(int startIndex, UINT flags) const { return ListView_GetNextItem(_window, startIndex, flags); } 77 int GetNextItem(int startIndex, UINT flags) const { return ListView_GetNextItem(_window, startIndex, flags); }
75 int GetNextSelectedItem(int startIndex) const { return GetNextItem(startIndex, LVNI_SELECTED); } 78 int GetNextSelectedItem(int startIndex) const { return GetNextItem(startIndex, LVNI_SELECTED); }
76 int GetFocusedItem() const { return GetNextItem(-1, LVNI_FOCUSED); } 79 int GetFocusedItem() const { return GetNextItem(-1, LVNI_FOCUSED); }
77 80
78 bool GetItem(LVITEM* item) const { return BOOLToBool(ListView_GetItem(_window, item)); } 81 bool GetItem(LVITEM* item) const { return BOOLToBool(ListView_GetItem(_window, item)); }
79 bool GetItemParam(int itemIndex, LPARAM &param) const; 82 bool GetItemParam(unsigned itemIndex, LPARAM &param) const;
80 void GetItemText(int itemIndex, int subItemIndex, LPTSTR text, int textSizeMax) const 83 /*
81 { ListView_GetItemText(_window, itemIndex, subItemIndex, text, textSizeMax); } 84 void GetItemText(unsigned itemIndex, unsigned subItemIndex, LPTSTR text, unsigned textSizeMax) const
85 { ListView_GetItemText(_window, itemIndex, subItemIndex, text, textSizeMax) }
86 */
82 bool SortItems(PFNLVCOMPARE compareFunction, LPARAM dataParam) 87 bool SortItems(PFNLVCOMPARE compareFunction, LPARAM dataParam)
83 { return BOOLToBool(ListView_SortItems(_window, compareFunction, dataParam)); } 88 { return BOOLToBool(ListView_SortItems(_window, compareFunction, dataParam)); }
84 89
85 void SetItemState(int index, UINT state, UINT mask) { ListView_SetItemState(_window, index, state, mask); } 90 // If (index == -1), then the state change is applied to all items.
91 void SetItemState(int index, UINT state, UINT mask) { ListView_SetItemState(_window, index, state, mask) }
86 void SetItemState_Selected(int index, bool select) { SetItemState(index, select ? LVIS_SELECTED : 0, LVIS_SELECTED); } 92 void SetItemState_Selected(int index, bool select) { SetItemState(index, select ? LVIS_SELECTED : 0, LVIS_SELECTED); }
87 void SetItemState_Selected(int index) { SetItemState(index, LVIS_SELECTED, LVIS_SELECTED); } 93 void SetItemState_Selected(int index) { SetItemState(index, LVIS_SELECTED, LVIS_SELECTED); }
88 void SelectAll() { SetItemState_Selected(-1); } 94 void SelectAll() { SetItemState_Selected(-1); }
@@ -90,7 +96,7 @@ public:
90 UINT GetItemState(int index, UINT mask) const { return ListView_GetItemState(_window, index, mask); } 96 UINT GetItemState(int index, UINT mask) const { return ListView_GetItemState(_window, index, mask); }
91 bool IsItemSelected(int index) const { return GetItemState(index, LVIS_SELECTED) == LVIS_SELECTED; } 97 bool IsItemSelected(int index) const { return GetItemState(index, LVIS_SELECTED) == LVIS_SELECTED; }
92 98
93 bool GetColumn(int columnIndex, LVCOLUMN* columnInfo) const 99 bool GetColumn(unsigned columnIndex, LVCOLUMN* columnInfo) const
94 { return BOOLToBool(ListView_GetColumn(_window, columnIndex, columnInfo)); } 100 { return BOOLToBool(ListView_GetColumn(_window, columnIndex, columnInfo)); }
95 101
96 HIMAGELIST SetImageList(HIMAGELIST imageList, int imageListType) 102 HIMAGELIST SetImageList(HIMAGELIST imageList, int imageListType)
@@ -101,7 +107,7 @@ public:
101 void SetExtendedListViewStyle(DWORD exStyle) { ListView_SetExtendedListViewStyle(_window, exStyle); } 107 void SetExtendedListViewStyle(DWORD exStyle) { ListView_SetExtendedListViewStyle(_window, exStyle); }
102 void SetExtendedListViewStyle(DWORD exMask, DWORD exStyle) { ListView_SetExtendedListViewStyleEx(_window, exMask, exStyle); } 108 void SetExtendedListViewStyle(DWORD exMask, DWORD exStyle) { ListView_SetExtendedListViewStyleEx(_window, exMask, exStyle); }
103 109
104 void SetCheckState(UINT index, bool checkState) { ListView_SetCheckState(_window, index, BoolToBOOL(checkState)); } 110 void SetCheckState(UINT index, bool checkState) { ListView_SetCheckState(_window, index, BoolToBOOL(checkState)) }
105 bool GetCheckState(UINT index) { return BOOLToBool(ListView_GetCheckState(_window, index)); } 111 bool GetCheckState(UINT index) { return BOOLToBool(ListView_GetCheckState(_window, index)); }
106 112
107 bool EnsureVisible(int index, bool partialOK) { return BOOLToBool(ListView_EnsureVisible(_window, index, BoolToBOOL(partialOK))); } 113 bool EnsureVisible(int index, bool partialOK) { return BOOLToBool(ListView_EnsureVisible(_window, index, BoolToBOOL(partialOK))); }
@@ -129,7 +135,10 @@ public:
129class CListView2: public CListView 135class CListView2: public CListView
130{ 136{
131 WNDPROC _origWindowProc; 137 WNDPROC _origWindowProc;
138 // ~CListView2() ZIP7_eq_delete;
132public: 139public:
140 virtual ~CListView2() {}
141 CListView2() {}
133 void SetWindowProc(); 142 void SetWindowProc();
134 virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 143 virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
135}; 144};
diff --git a/CPP/Windows/Control/ProgressBar.h b/CPP/Windows/Control/ProgressBar.h
index 0374306..2256aa9 100644
--- a/CPP/Windows/Control/ProgressBar.h
+++ b/CPP/Windows/Control/ProgressBar.h
@@ -1,7 +1,7 @@
1// Windows/Control/ProgressBar.h 1// Windows/Control/ProgressBar.h
2 2
3#ifndef __WINDOWS_CONTROL_PROGRESSBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_PROGRESSBAR_H
4#define __WINDOWS_CONTROL_PROGRESSBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_PROGRESSBAR_H
5 5
6#include "../../Common/MyWindows.h" 6#include "../../Common/MyWindows.h"
7 7
@@ -15,18 +15,18 @@ namespace NControl {
15class CProgressBar: public CWindow 15class CProgressBar: public CWindow
16{ 16{
17public: 17public:
18 LRESULT SetPos(int pos) { return SendMsg(PBM_SETPOS, pos, 0); } 18 LRESULT SetPos(int pos) { return SendMsg(PBM_SETPOS, (unsigned)pos, 0); }
19 LRESULT DeltaPos(int increment) { return SendMsg(PBM_DELTAPOS, increment, 0); } 19 // LRESULT DeltaPos(int increment) { return SendMsg(PBM_DELTAPOS, increment, 0); }
20 UINT GetPos() { return (UINT)SendMsg(PBM_GETPOS, 0, 0); } 20 // UINT GetPos() { return (UINT)SendMsg(PBM_GETPOS, 0, 0); }
21 LRESULT SetRange(unsigned short minValue, unsigned short maxValue) { return SendMsg(PBM_SETRANGE, 0, MAKELPARAM(minValue, maxValue)); } 21 // LRESULT SetRange(unsigned short minValue, unsigned short maxValue) { return SendMsg(PBM_SETRANGE, 0, MAKELPARAM(minValue, maxValue)); }
22 DWORD SetRange32(int minValue, int maxValue) { return (DWORD)SendMsg(PBM_SETRANGE32, minValue, maxValue); } 22 DWORD SetRange32(int minValue, int maxValue) { return (DWORD)SendMsg(PBM_SETRANGE32, (unsigned)minValue, (LPARAM)(unsigned)maxValue); }
23 int SetStep(int step) { return (int)SendMsg(PBM_SETSTEP, step, 0); } 23 // int SetStep(int step) { return (int)SendMsg(PBM_SETSTEP, step, 0); }
24 LRESULT StepIt() { return SendMsg(PBM_STEPIT, 0, 0); } 24 // LRESULT StepIt() { return SendMsg(PBM_STEPIT, 0, 0); }
25 INT GetRange(bool minValue, PPBRANGE range) { return (INT)SendMsg(PBM_GETRANGE, BoolToBOOL(minValue), (LPARAM)range); } 25 // INT GetRange(bool minValue, PPBRANGE range) { return (INT)SendMsg(PBM_GETRANGE, BoolToBOOL(minValue), (LPARAM)range); }
26 26
27 #ifndef UNDER_CE 27 #ifndef UNDER_CE
28 COLORREF SetBarColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBARCOLOR, 0, color); } 28 COLORREF SetBarColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBARCOLOR, 0, (LPARAM)color); }
29 COLORREF SetBackgroundColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBKCOLOR, 0, color); } 29 COLORREF SetBackgroundColor(COLORREF color) { return (COLORREF)SendMsg(PBM_SETBKCOLOR, 0, (LPARAM)color); }
30 #endif 30 #endif
31}; 31};
32 32
diff --git a/CPP/Windows/Control/PropertyPage.cpp b/CPP/Windows/Control/PropertyPage.cpp
index ce8696d..f8effe6 100644
--- a/CPP/Windows/Control/PropertyPage.cpp
+++ b/CPP/Windows/Control/PropertyPage.cpp
@@ -16,7 +16,13 @@ extern bool g_IsNT;
16namespace NWindows { 16namespace NWindows {
17namespace NControl { 17namespace NControl {
18 18
19static INT_PTR APIENTRY MyProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam) 19static
20#ifdef Z7_OLD_WIN_SDK
21 BOOL
22#else
23 INT_PTR
24#endif
25APIENTRY MyProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wParam, LPARAM lParam)
20{ 26{
21 CWindow tempDialog(dialogHWND); 27 CWindow tempDialog(dialogHWND);
22 if (message == WM_INITDIALOG) 28 if (message == WM_INITDIALOG)
@@ -34,75 +40,91 @@ bool CPropertyPage::OnNotify(UINT /* controlID */, LPNMHDR lParam)
34{ 40{
35 switch (lParam->code) 41 switch (lParam->code)
36 { 42 {
37 case PSN_APPLY: SetMsgResult(OnApply(LPPSHNOTIFY(lParam))); break; 43 case PSN_APPLY: SetMsgResult(OnApply2(LPPSHNOTIFY(lParam))); break;
38 case PSN_KILLACTIVE: SetMsgResult(BoolToBOOL(OnKillActive(LPPSHNOTIFY(lParam)))); break; 44 case PSN_KILLACTIVE: SetMsgResult(BoolToBOOL(OnKillActive2(LPPSHNOTIFY(lParam)))); break;
39 case PSN_SETACTIVE: SetMsgResult(OnSetActive(LPPSHNOTIFY(lParam))); break; 45 case PSN_SETACTIVE: SetMsgResult(OnSetActive2(LPPSHNOTIFY(lParam))); break;
40 case PSN_RESET: OnReset(LPPSHNOTIFY(lParam)); break; 46 case PSN_RESET: OnReset2(LPPSHNOTIFY(lParam)); break;
41 case PSN_HELP: OnNotifyHelp(LPPSHNOTIFY(lParam)); break; 47 case PSN_HELP: OnNotifyHelp2(LPPSHNOTIFY(lParam)); break;
42 default: return false; 48 default: return false;
43 } 49 }
44 return true; 50 return true;
45} 51}
46 52
53/*
54PROPSHEETPAGE fields depend from
55#if (_WIN32_WINNT >= 0x0600)
56#elif (_WIN32_WINNT >= 0x0501)
57#elif (_WIN32_IE >= 0x0400)
58PROPSHEETHEADER fields depend from
59#if (_WIN32_IE >= 0x0400)
60*/
61#if defined(PROPSHEETPAGEA_V1_SIZE) && !defined(Z7_OLD_WIN_SDK)
62#ifndef _UNICODE
63#define my_compatib_PROPSHEETPAGEA PROPSHEETPAGEA_V1
64#endif
65#define my_compatib_PROPSHEETPAGEW PROPSHEETPAGEW_V1
66#else
67// for old mingw:
68#ifndef _UNICODE
69#define my_compatib_PROPSHEETPAGEA PROPSHEETPAGEA
70#endif
71#define my_compatib_PROPSHEETPAGEW PROPSHEETPAGEW
72#endif
73
47INT_PTR MyPropertySheet(const CObjectVector<CPageInfo> &pagesInfo, HWND hwndParent, const UString &title) 74INT_PTR MyPropertySheet(const CObjectVector<CPageInfo> &pagesInfo, HWND hwndParent, const UString &title)
48{ 75{
49 #ifndef _UNICODE
50 AStringVector titles;
51 #endif
52 #ifndef _UNICODE
53 CRecordVector<PROPSHEETPAGEA> pagesA;
54 #endif
55 CRecordVector<PROPSHEETPAGEW> pagesW;
56
57 unsigned i; 76 unsigned i;
58 #ifndef _UNICODE 77 #ifndef _UNICODE
78 AStringVector titles;
59 for (i = 0; i < pagesInfo.Size(); i++) 79 for (i = 0; i < pagesInfo.Size(); i++)
60 titles.Add(GetSystemString(pagesInfo[i].Title)); 80 titles.Add(GetSystemString(pagesInfo[i].Title));
81 CRecordVector<my_compatib_PROPSHEETPAGEA> pagesA;
61 #endif 82 #endif
83 CRecordVector<my_compatib_PROPSHEETPAGEW> pagesW;
62 84
63 for (i = 0; i < pagesInfo.Size(); i++) 85 for (i = 0; i < pagesInfo.Size(); i++)
64 { 86 {
65 const CPageInfo &pageInfo = pagesInfo[i]; 87 const CPageInfo &pageInfo = pagesInfo[i];
66 #ifndef _UNICODE 88 #ifndef _UNICODE
67 { 89 {
68 PROPSHEETPAGE page; 90 my_compatib_PROPSHEETPAGEA page;
91 memset(&page, 0, sizeof(page));
69 page.dwSize = sizeof(page); 92 page.dwSize = sizeof(page);
70 page.dwFlags = PSP_HASHELP; 93 page.dwFlags = PSP_HASHELP;
71 page.hInstance = g_hInstance; 94 page.hInstance = g_hInstance;
72 page.pszTemplate = MAKEINTRESOURCE(pageInfo.ID); 95 page.pszTemplate = MAKEINTRESOURCEA(pageInfo.ID);
73 page.pszIcon = NULL; 96 // page.pszIcon = NULL;
74 page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure; 97 page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure;
75 98
76 if (titles[i].IsEmpty()) 99 if (!titles[i].IsEmpty())
77 page.pszTitle = NULL;
78 else
79 { 100 {
80 page.dwFlags |= PSP_USETITLE;
81 page.pszTitle = titles[i]; 101 page.pszTitle = titles[i];
102 page.dwFlags |= PSP_USETITLE;
82 } 103 }
104 // else page.pszTitle = NULL;
83 page.lParam = (LPARAM)pageInfo.Page; 105 page.lParam = (LPARAM)pageInfo.Page;
84 page.pfnCallback = NULL; 106 // page.pfnCallback = NULL;
85 pagesA.Add(page); 107 pagesA.Add(page);
86 } 108 }
87 #endif 109 #endif
88 { 110 {
89 PROPSHEETPAGEW page; 111 my_compatib_PROPSHEETPAGEW page;
112 memset(&page, 0, sizeof(page));
90 page.dwSize = sizeof(page); 113 page.dwSize = sizeof(page);
91 page.dwFlags = PSP_HASHELP; 114 page.dwFlags = PSP_HASHELP;
92 page.hInstance = g_hInstance; 115 page.hInstance = g_hInstance;
93 page.pszTemplate = MAKEINTRESOURCEW(pageInfo.ID); 116 page.pszTemplate = MAKEINTRESOURCEW(pageInfo.ID);
94 page.pszIcon = NULL; 117 // page.pszIcon = NULL;
95 page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure; 118 page.pfnDlgProc = NWindows::NControl::MyProperyPageProcedure;
96 119
97 if (pageInfo.Title.IsEmpty()) 120 if (!pageInfo.Title.IsEmpty())
98 page.pszTitle = NULL;
99 else
100 { 121 {
101 page.dwFlags |= PSP_USETITLE;
102 page.pszTitle = pageInfo.Title; 122 page.pszTitle = pageInfo.Title;
123 page.dwFlags |= PSP_USETITLE;
103 } 124 }
125 // else page.pszTitle = NULL;
104 page.lParam = (LPARAM)pageInfo.Page; 126 page.lParam = (LPARAM)pageInfo.Page;
105 page.pfnCallback = NULL; 127 // page.pfnCallback = NULL;
106 pagesW.Add(page); 128 pagesW.Add(page);
107 } 129 }
108 } 130 }
@@ -110,16 +132,16 @@ INT_PTR MyPropertySheet(const CObjectVector<CPageInfo> &pagesInfo, HWND hwndPare
110 #ifndef _UNICODE 132 #ifndef _UNICODE
111 if (!g_IsNT) 133 if (!g_IsNT)
112 { 134 {
113 PROPSHEETHEADER sheet; 135 PROPSHEETHEADERA sheet;
114 sheet.dwSize = sizeof(sheet); 136 sheet.dwSize = sizeof(sheet);
115 sheet.dwFlags = PSH_PROPSHEETPAGE; 137 sheet.dwFlags = PSH_PROPSHEETPAGE;
116 sheet.hwndParent = hwndParent; 138 sheet.hwndParent = hwndParent;
117 sheet.hInstance = g_hInstance; 139 sheet.hInstance = g_hInstance;
118 AString titleA (GetSystemString(title)); 140 AString titleA (GetSystemString(title));
119 sheet.pszCaption = titleA; 141 sheet.pszCaption = titleA;
120 sheet.nPages = pagesInfo.Size(); 142 sheet.nPages = pagesA.Size();
121 sheet.nStartPage = 0; 143 sheet.nStartPage = 0;
122 sheet.ppsp = &pagesA.Front(); 144 sheet.ppsp = (LPCPROPSHEETPAGEA)(const void *)&pagesA.Front();
123 sheet.pfnCallback = NULL; 145 sheet.pfnCallback = NULL;
124 return ::PropertySheetA(&sheet); 146 return ::PropertySheetA(&sheet);
125 } 147 }
@@ -132,9 +154,9 @@ INT_PTR MyPropertySheet(const CObjectVector<CPageInfo> &pagesInfo, HWND hwndPare
132 sheet.hwndParent = hwndParent; 154 sheet.hwndParent = hwndParent;
133 sheet.hInstance = g_hInstance; 155 sheet.hInstance = g_hInstance;
134 sheet.pszCaption = title; 156 sheet.pszCaption = title;
135 sheet.nPages = pagesInfo.Size(); 157 sheet.nPages = pagesW.Size();
136 sheet.nStartPage = 0; 158 sheet.nStartPage = 0;
137 sheet.ppsp = &pagesW.Front(); 159 sheet.ppsp = (LPCPROPSHEETPAGEW)(const void *)&pagesW.Front();
138 sheet.pfnCallback = NULL; 160 sheet.pfnCallback = NULL;
139 return ::PropertySheetW(&sheet); 161 return ::PropertySheetW(&sheet);
140 } 162 }
diff --git a/CPP/Windows/Control/PropertyPage.h b/CPP/Windows/Control/PropertyPage.h
index b68fd8f..264a5d2 100644
--- a/CPP/Windows/Control/PropertyPage.h
+++ b/CPP/Windows/Control/PropertyPage.h
@@ -1,11 +1,11 @@
1// Windows/Control/PropertyPage.h 1// Windows/Control/PropertyPage.h
2 2
3#ifndef __WINDOWS_CONTROL_PROPERTYPAGE_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_PROPERTYPAGE_H
4#define __WINDOWS_CONTROL_PROPERTYPAGE_H 4#define ZIP7_INC_WINDOWS_CONTROL_PROPERTYPAGE_H
5 5
6#include "../../Common/MyWindows.h" 6#include "../../Common/MyWindows.h"
7 7
8#include <PrSht.h> 8#include <prsht.h>
9 9
10#include "Dialog.h" 10#include "Dialog.h"
11 11
@@ -17,23 +17,23 @@ INT_PTR APIENTRY ProperyPageProcedure(HWND dialogHWND, UINT message, WPARAM wPar
17class CPropertyPage: public CDialog 17class CPropertyPage: public CDialog
18{ 18{
19public: 19public:
20 CPropertyPage(HWND window = NULL): CDialog(window){}; 20 CPropertyPage(HWND window = NULL): CDialog(window) {}
21 21
22 void Changed() { PropSheet_Changed(GetParent(), (HWND)*this); } 22 void Changed() { PropSheet_Changed(GetParent(), (HWND)*this); }
23 void UnChanged() { PropSheet_UnChanged(GetParent(), (HWND)*this); } 23 void UnChanged() { PropSheet_UnChanged(GetParent(), (HWND)*this); }
24 24
25 virtual bool OnNotify(UINT controlID, LPNMHDR lParam); 25 virtual bool OnNotify(UINT controlID, LPNMHDR lParam) Z7_override;
26 26
27 virtual bool OnKillActive() { return false; } // false = OK 27 virtual bool OnKillActive() { return false; } // false = OK
28 virtual bool OnKillActive(const PSHNOTIFY *) { return OnKillActive(); } 28 virtual bool OnKillActive2(const PSHNOTIFY *) { return OnKillActive(); }
29 virtual LONG OnSetActive() { return false; } // false = OK 29 virtual LONG OnSetActive() { return false; } // false = OK
30 virtual LONG OnSetActive(const PSHNOTIFY *) { return OnSetActive(); } 30 virtual LONG OnSetActive2(const PSHNOTIFY *) { return OnSetActive(); }
31 virtual LONG OnApply() { return PSNRET_NOERROR; } 31 virtual LONG OnApply() { return PSNRET_NOERROR; }
32 virtual LONG OnApply(const PSHNOTIFY *) { return OnApply(); } 32 virtual LONG OnApply2(const PSHNOTIFY *) { return OnApply(); }
33 virtual void OnNotifyHelp() {} 33 virtual void OnNotifyHelp() {}
34 virtual void OnNotifyHelp(const PSHNOTIFY *) { OnNotifyHelp(); } 34 virtual void OnNotifyHelp2(const PSHNOTIFY *) { OnNotifyHelp(); }
35 virtual void OnReset() {} 35 virtual void OnReset() {}
36 virtual void OnReset(const PSHNOTIFY *) { OnReset(); } 36 virtual void OnReset2(const PSHNOTIFY *) { OnReset(); }
37}; 37};
38 38
39struct CPageInfo 39struct CPageInfo
diff --git a/CPP/Windows/Control/ReBar.h b/CPP/Windows/Control/ReBar.h
index c2d58db..b56f018 100644
--- a/CPP/Windows/Control/ReBar.h
+++ b/CPP/Windows/Control/ReBar.h
@@ -1,7 +1,7 @@
1// Windows/Control/ReBar.h 1// Windows/Control/ReBar.h
2 2
3#ifndef __WINDOWS_CONTROL_REBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_REBAR_H
4#define __WINDOWS_CONTROL_REBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_REBAR_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
@@ -14,7 +14,7 @@ public:
14 bool SetBarInfo(LPREBARINFO barInfo) 14 bool SetBarInfo(LPREBARINFO barInfo)
15 { return LRESULTToBool(SendMsg(RB_SETBARINFO, 0, (LPARAM)barInfo)); } 15 { return LRESULTToBool(SendMsg(RB_SETBARINFO, 0, (LPARAM)barInfo)); }
16 bool InsertBand(int index, LPREBARBANDINFO bandInfo) 16 bool InsertBand(int index, LPREBARBANDINFO bandInfo)
17 { return LRESULTToBool(SendMsg(RB_INSERTBAND, index, (LPARAM)bandInfo)); } 17 { return LRESULTToBool(SendMsg(RB_INSERTBAND, MY_int_TO_WPARAM(index), (LPARAM)bandInfo)); }
18 bool SetBandInfo(unsigned index, LPREBARBANDINFO bandInfo) 18 bool SetBandInfo(unsigned index, LPREBARBANDINFO bandInfo)
19 { return LRESULTToBool(SendMsg(RB_SETBANDINFO, index, (LPARAM)bandInfo)); } 19 { return LRESULTToBool(SendMsg(RB_SETBANDINFO, index, (LPARAM)bandInfo)); }
20 void MaximizeBand(unsigned index, bool ideal) 20 void MaximizeBand(unsigned index, bool ideal)
diff --git a/CPP/Windows/Control/Static.h b/CPP/Windows/Control/Static.h
index 5523b2e..ceeedf9 100644
--- a/CPP/Windows/Control/Static.h
+++ b/CPP/Windows/Control/Static.h
@@ -1,7 +1,7 @@
1// Windows/Control/Static.h 1// Windows/Control/Static.h
2 2
3#ifndef __WINDOWS_CONTROL_STATIC_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_STATIC_H
4#define __WINDOWS_CONTROL_STATIC_H 4#define ZIP7_INC_WINDOWS_CONTROL_STATIC_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
diff --git a/CPP/Windows/Control/StatusBar.h b/CPP/Windows/Control/StatusBar.h
index 988b847..38aca47 100644
--- a/CPP/Windows/Control/StatusBar.h
+++ b/CPP/Windows/Control/StatusBar.h
@@ -1,7 +1,7 @@
1// Windows/Control/StatusBar.h 1// Windows/Control/StatusBar.h
2 2
3#ifndef __WINDOWS_CONTROL_STATUSBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_STATUSBAR_H
4#define __WINDOWS_CONTROL_STATUSBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_STATUSBAR_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
@@ -12,7 +12,7 @@ class CStatusBar: public NWindows::CWindow
12{ 12{
13public: 13public:
14 bool Create(LONG style, LPCTSTR text, HWND hwndParent, UINT id) 14 bool Create(LONG style, LPCTSTR text, HWND hwndParent, UINT id)
15 { return (_window = ::CreateStatusWindow(style, text, hwndParent, id)) != 0; } 15 { return (_window = ::CreateStatusWindow(style, text, hwndParent, id)) != NULL; }
16 bool SetText(LPCTSTR text) 16 bool SetText(LPCTSTR text)
17 { return CWindow::SetText(text); } 17 { return CWindow::SetText(text); }
18 bool SetText(unsigned index, LPCTSTR text, UINT type) 18 bool SetText(unsigned index, LPCTSTR text, UINT type)
@@ -22,7 +22,7 @@ public:
22 22
23 #ifndef _UNICODE 23 #ifndef _UNICODE
24 bool Create(LONG style, LPCWSTR text, HWND hwndParent, UINT id) 24 bool Create(LONG style, LPCWSTR text, HWND hwndParent, UINT id)
25 { return (_window = ::CreateStatusWindowW(style, text, hwndParent, id)) != 0; } 25 { return (_window = ::CreateStatusWindowW(style, text, hwndParent, id)) != NULL; }
26 bool SetText(LPCWSTR text) 26 bool SetText(LPCWSTR text)
27 { return CWindow::SetText(text); } 27 { return CWindow::SetText(text); }
28 bool SetText(unsigned index, LPCWSTR text, UINT type) 28 bool SetText(unsigned index, LPCWSTR text, UINT type)
@@ -34,7 +34,7 @@ public:
34 bool SetParts(unsigned numParts, const int *edgePostions) 34 bool SetParts(unsigned numParts, const int *edgePostions)
35 { return LRESULTToBool(SendMsg(SB_SETPARTS, numParts, (LPARAM)edgePostions)); } 35 { return LRESULTToBool(SendMsg(SB_SETPARTS, numParts, (LPARAM)edgePostions)); }
36 void Simple(bool simple) 36 void Simple(bool simple)
37 { SendMsg(SB_SIMPLE, BoolToBOOL(simple), 0); } 37 { SendMsg(SB_SIMPLE, (WPARAM)BoolToBOOL(simple), 0); }
38}; 38};
39 39
40}} 40}}
diff --git a/CPP/Windows/Control/StdAfx.h b/CPP/Windows/Control/StdAfx.h
index 1cbd7fe..8086655 100644
--- a/CPP/Windows/Control/StdAfx.h
+++ b/CPP/Windows/Control/StdAfx.h
@@ -1,8 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5 5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
6#include "../../Common/Common.h" 9#include "../../Common/Common.h"
7 10
8#endif 11#endif
diff --git a/CPP/Windows/Control/ToolBar.h b/CPP/Windows/Control/ToolBar.h
index 7bc93a2..2bf20a5 100644
--- a/CPP/Windows/Control/ToolBar.h
+++ b/CPP/Windows/Control/ToolBar.h
@@ -1,7 +1,7 @@
1// Windows/Control/ToolBar.h 1// Windows/Control/ToolBar.h
2 2
3#ifndef __WINDOWS_CONTROL_TOOLBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_TOOLBAR_H
4#define __WINDOWS_CONTROL_TOOLBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_TOOLBAR_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
@@ -18,7 +18,7 @@ public:
18 #ifdef UNDER_CE 18 #ifdef UNDER_CE
19 { 19 {
20 // maybe it must be fixed for more than 1 buttons 20 // maybe it must be fixed for more than 1 buttons
21 DWORD val = GetButtonSize(); 21 const DWORD val = GetButtonSize();
22 size->cx = LOWORD(val); 22 size->cx = LOWORD(val);
23 size->cy = HIWORD(val); 23 size->cy = HIWORD(val);
24 return true; 24 return true;
diff --git a/CPP/Windows/Control/Trackbar.h b/CPP/Windows/Control/Trackbar.h
index 313e0c8..18d1b29 100644
--- a/CPP/Windows/Control/Trackbar.h
+++ b/CPP/Windows/Control/Trackbar.h
@@ -1,7 +1,7 @@
1// Windows/Control/Trackbar.h 1// Windows/Control/Trackbar.h
2 2
3#ifndef __WINDOWS_CONTROL_TRACKBAR_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_TRACKBAR_H
4#define __WINDOWS_CONTROL_TRACKBAR_H 4#define ZIP7_INC_WINDOWS_CONTROL_TRACKBAR_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
diff --git a/CPP/Windows/Control/Window2.cpp b/CPP/Windows/Control/Window2.cpp
index 994d96e..8fe908e 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,
32 if (message == MY_START_WM_CREATE) 32 if (message == MY_START_WM_CREATE)
33 tempWindow.SetUserDataLongPtr((LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); 33 tempWindow.SetUserDataLongPtr((LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams));
34 CWindow2 *window = (CWindow2 *)(tempWindow.GetUserDataLongPtr()); 34 CWindow2 *window = (CWindow2 *)(tempWindow.GetUserDataLongPtr());
35 if (window != NULL && message == MY_START_WM_CREATE) 35 if (window && message == MY_START_WM_CREATE)
36 window->Attach(aHWND); 36 window->Attach(aHWND);
37 if (window == 0) 37 if (!window)
38 { 38 {
39 #ifndef _UNICODE 39 #ifndef _UNICODE
40 if (g_IsNT) 40 if (g_IsNT)
@@ -140,7 +140,7 @@ LRESULT CWindow2::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
140 return -1; 140 return -1;
141 break; 141 break;
142 case WM_COMMAND: 142 case WM_COMMAND:
143 if (OnCommand(wParam, lParam, result)) 143 if (OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result))
144 return result; 144 return result;
145 break; 145 break;
146 case WM_NOTIFY: 146 case WM_NOTIFY:
@@ -160,12 +160,14 @@ LRESULT CWindow2::OnMessage(UINT message, WPARAM wParam, LPARAM lParam)
160 return DefProc(message, wParam, lParam); 160 return DefProc(message, wParam, lParam);
161} 161}
162 162
163bool CWindow2::OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result) 163/*
164bool CWindow2::OnCommand2(WPARAM wParam, LPARAM lParam, LRESULT &result)
164{ 165{
165 return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result); 166 return OnCommand(HIWORD(wParam), LOWORD(wParam), lParam, result);
166} 167}
168*/
167 169
168bool CWindow2::OnCommand(int /* code */, int /* itemID */, LPARAM /* lParam */, LRESULT & /* result */) 170bool CWindow2::OnCommand(unsigned /* code */, unsigned /* itemID */, LPARAM /* lParam */, LRESULT & /* result */)
169{ 171{
170 return false; 172 return false;
171 // return DefProc(message, wParam, lParam); 173 // return DefProc(message, wParam, lParam);
@@ -176,7 +178,7 @@ bool CWindow2::OnCommand(int /* code */, int /* itemID */, LPARAM /* lParam */,
176} 178}
177 179
178/* 180/*
179bool CDialog::OnButtonClicked(int buttonID, HWND buttonHWND) 181bool CDialog::OnButtonClicked(unsigned buttonID, HWND buttonHWND)
180{ 182{
181 switch (buttonID) 183 switch (buttonID)
182 { 184 {
diff --git a/CPP/Windows/Control/Window2.h b/CPP/Windows/Control/Window2.h
index 7ac580c..ebb5979 100644
--- a/CPP/Windows/Control/Window2.h
+++ b/CPP/Windows/Control/Window2.h
@@ -1,7 +1,7 @@
1// Windows/Control/Window2.h 1// Windows/Control/Window2.h
2 2
3#ifndef __WINDOWS_CONTROL_WINDOW2_H 3#ifndef ZIP7_INC_WINDOWS_CONTROL_WINDOW2_H
4#define __WINDOWS_CONTROL_WINDOW2_H 4#define ZIP7_INC_WINDOWS_CONTROL_WINDOW2_H
5 5
6#include "../Window.h" 6#include "../Window.h"
7 7
@@ -10,10 +10,12 @@ namespace NControl {
10 10
11class CWindow2: public CWindow 11class CWindow2: public CWindow
12{ 12{
13 // Z7_CLASS_NO_COPY(CWindow2)
14
13 LRESULT DefProc(UINT message, WPARAM wParam, LPARAM lParam); 15 LRESULT DefProc(UINT message, WPARAM wParam, LPARAM lParam);
14public: 16public:
15 CWindow2(HWND newWindow = NULL): CWindow(newWindow){}; 17 CWindow2(HWND newWindow = NULL): CWindow(newWindow) {}
16 virtual ~CWindow2() {}; 18 virtual ~CWindow2() {}
17 19
18 bool CreateEx(DWORD exStyle, LPCTSTR className, LPCTSTR windowName, 20 bool CreateEx(DWORD exStyle, LPCTSTR className, LPCTSTR windowName,
19 DWORD style, int x, int y, int width, int height, 21 DWORD style, int x, int y, int width, int height,
@@ -28,8 +30,8 @@ public:
28 virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam); 30 virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
29 virtual bool OnCreate(CREATESTRUCT * /* createStruct */) { return true; } 31 virtual bool OnCreate(CREATESTRUCT * /* createStruct */) { return true; }
30 // virtual LRESULT OnCommand(WPARAM wParam, LPARAM lParam); 32 // virtual LRESULT OnCommand(WPARAM wParam, LPARAM lParam);
31 virtual bool OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result); 33 // bool OnCommand2(WPARAM wParam, LPARAM lParam, LRESULT &result);
32 virtual bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result); 34 virtual bool OnCommand(unsigned code, unsigned itemID, LPARAM lParam, LRESULT &result);
33 virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; } 35 virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; }
34 virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */, LRESULT & /* result */) { return false; } 36 virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */, LRESULT & /* result */) { return false; }
35 virtual void OnDestroy() { PostQuitMessage(0); } 37 virtual void OnDestroy() { PostQuitMessage(0); }
@@ -37,7 +39,7 @@ public:
37 /* 39 /*
38 virtual LRESULT OnHelp(LPHELPINFO helpInfo) { OnHelp(); } 40 virtual LRESULT OnHelp(LPHELPINFO helpInfo) { OnHelp(); }
39 virtual LRESULT OnHelp() {}; 41 virtual LRESULT OnHelp() {};
40 virtual bool OnButtonClicked(int buttonID, HWND buttonHWND); 42 virtual bool OnButtonClicked(unsigned buttonID, HWND buttonHWND);
41 virtual void OnOK() {}; 43 virtual void OnOK() {};
42 virtual void OnCancel() {}; 44 virtual void OnCancel() {};
43 */ 45 */
diff --git a/CPP/Windows/DLL.cpp b/CPP/Windows/DLL.cpp
index cf5d01a..b2499ec 100644
--- a/CPP/Windows/DLL.cpp
+++ b/CPP/Windows/DLL.cpp
@@ -17,11 +17,11 @@ namespace NDLL {
17 17
18bool CLibrary::Free() throw() 18bool CLibrary::Free() throw()
19{ 19{
20 if (_module == 0) 20 if (_module == NULL)
21 return true; 21 return true;
22 if (!::FreeLibrary(_module)) 22 if (!::FreeLibrary(_module))
23 return false; 23 return false;
24 _module = 0; 24 _module = NULL;
25 return true; 25 return true;
26} 26}
27 27
@@ -90,7 +90,7 @@ bool MyGetModuleFileName(FString &path)
90 return false; 90 return false;
91} 91}
92 92
93#ifndef _SFX 93#ifndef Z7_SFX
94 94
95FString GetModuleDirPrefix() 95FString GetModuleDirPrefix()
96{ 96{
@@ -110,38 +110,35 @@ FString GetModuleDirPrefix()
110 110
111}} 111}}
112 112
113#else 113#else // _WIN32
114 114
115#include <dlfcn.h> 115#include <dlfcn.h>
116#include <stdlib.h> 116#include <stdlib.h>
117#include "../Common/Common.h"
118
119// FARPROC
120void *GetProcAddress(HMODULE module, LPCSTR procName)
121{
122 void *ptr = NULL;
123 if (module)
124 ptr = dlsym(module, procName);
125 return ptr;
126}
117 127
118namespace NWindows { 128namespace NWindows {
119namespace NDLL { 129namespace NDLL {
120 130
121bool CLibrary::Free() throw() 131bool CLibrary::Free() throw()
122{ 132{
123 if (_module == NULL) 133 if (!_module)
124 return true; 134 return true;
125 int ret = dlclose(_module); 135 const int ret = dlclose(_module);
126 if (ret != 0) 136 if (ret != 0)
127 return false; 137 return false;
128 _module = NULL; 138 _module = NULL;
129 return true; 139 return true;
130} 140}
131 141
132static
133// FARPROC
134void *
135local_GetProcAddress(HMODULE module, LPCSTR procName)
136{
137 void *ptr = NULL;
138 if (module)
139 {
140 ptr = dlsym(module, procName);
141 }
142 return ptr;
143}
144
145bool CLibrary::Load(CFSTR path) throw() 142bool CLibrary::Load(CFSTR path) throw()
146{ 143{
147 if (!Free()) 144 if (!Free())
@@ -163,21 +160,11 @@ bool CLibrary::Load(CFSTR path) throw()
163 #endif 160 #endif
164 #endif 161 #endif
165 162
166 void *handler = dlopen(path, options); 163 _module = dlopen(path, options);
167
168 if (handler)
169 {
170 // here we can transfer some settings to DLL
171 }
172 else
173 {
174 }
175
176 _module = handler;
177
178 return (_module != NULL); 164 return (_module != NULL);
179} 165}
180 166
167/*
181// FARPROC 168// FARPROC
182void * CLibrary::GetProc(LPCSTR procName) const 169void * CLibrary::GetProc(LPCSTR procName) const
183{ 170{
@@ -185,6 +172,7 @@ void * CLibrary::GetProc(LPCSTR procName) const
185 return local_GetProcAddress(_module, procName); 172 return local_GetProcAddress(_module, procName);
186 // return NULL; 173 // return NULL;
187} 174}
175*/
188 176
189}} 177}}
190 178
diff --git a/CPP/Windows/DLL.h b/CPP/Windows/DLL.h
index 0c093ee..19a82b3 100644
--- a/CPP/Windows/DLL.h
+++ b/CPP/Windows/DLL.h
@@ -1,20 +1,29 @@
1// Windows/DLL.h 1// Windows/DLL.h
2 2
3#ifndef __WINDOWS_DLL_H 3#ifndef ZIP7_INC_WINDOWS_DLL_H
4#define __WINDOWS_DLL_H 4#define ZIP7_INC_WINDOWS_DLL_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
8#ifndef _WIN32
9typedef void * HMODULE;
10// typedef int (*FARPROC)();
11// typedef void *FARPROC;
12void *GetProcAddress(HMODULE module, LPCSTR procName);
13#endif
14
8namespace NWindows { 15namespace NWindows {
9namespace NDLL { 16namespace NDLL {
10 17
11#ifdef _WIN32 18#ifdef _WIN32
12 19
20/*
13#ifdef UNDER_CE 21#ifdef UNDER_CE
14#define My_GetProcAddress(module, procName) (void *)::GetProcAddressA(module, procName) 22#define My_GetProcAddress(module, procName) (void *)::GetProcAddressA(module, procName)
15#else 23#else
16#define My_GetProcAddress(module, procName) (void *)::GetProcAddress(module, procName) 24#define My_GetProcAddress(module, procName) (void *)::GetProcAddress(module, procName)
17#endif 25#endif
26*/
18 27
19/* Win32: Don't call CLibrary::Free() and FreeLibrary() from another 28/* Win32: Don't call CLibrary::Free() and FreeLibrary() from another
20 FreeLibrary() code: detaching code in DLL entry-point or in 29 FreeLibrary() code: detaching code in DLL entry-point or in
@@ -24,13 +33,25 @@ class CLibrary
24{ 33{
25 HMODULE _module; 34 HMODULE _module;
26 35
27 // CLASS_NO_COPY(CLibrary); 36 // Z7_CLASS_NO_COPY(CLibrary);
37 // copy constructor is required here
28public: 38public:
29 CLibrary(): _module(NULL) {}; 39 CLibrary(): _module(NULL) {}
30 ~CLibrary() { Free(); } 40 ~CLibrary() { Free(); }
31 41
32 operator HMODULE() const { return _module; } 42 CLibrary(const CLibrary &c): _module(NULL)
33 HMODULE* operator&() { return &_module; } 43 {
44 if (c._module)
45 {
46 // we need non const to reference from original item
47 // c._module = NULL;
48 throw 20230102;
49 }
50 }
51
52 HMODULE Get_HMODULE() const { return _module; }
53 // operator HMODULE() const { return _module; }
54 // HMODULE* operator&() { return &_module; }
34 bool IsLoaded() const { return (_module != NULL); } 55 bool IsLoaded() const { return (_module != NULL); }
35 56
36 void Attach(HMODULE m) 57 void Attach(HMODULE m)
@@ -40,7 +61,7 @@ public:
40 } 61 }
41 HMODULE Detach() 62 HMODULE Detach()
42 { 63 {
43 HMODULE m = _module; 64 const HMODULE m = _module;
44 _module = NULL; 65 _module = NULL;
45 return m; 66 return m;
46 } 67 }
@@ -49,28 +70,26 @@ public:
49 bool LoadEx(CFSTR path, DWORD flags = LOAD_LIBRARY_AS_DATAFILE) throw(); 70 bool LoadEx(CFSTR path, DWORD flags = LOAD_LIBRARY_AS_DATAFILE) throw();
50 bool Load(CFSTR path) throw(); 71 bool Load(CFSTR path) throw();
51 // FARPROC 72 // FARPROC
52 void *GetProc(LPCSTR procName) const { return My_GetProcAddress(_module, procName); } 73 // void *GetProc(LPCSTR procName) const { return My_GetProcAddress(_module, procName); }
53}; 74};
54 75
55#else 76#else
56 77
57typedef void * HMODULE;
58// typedef int (*FARPROC)();
59// typedef void *FARPROC;
60
61class CLibrary 78class CLibrary
62{ 79{
63 HMODULE _module; 80 HMODULE _module;
64 81
65 // CLASS_NO_COPY(CLibrary); 82 // Z7_CLASS_NO_COPY(CLibrary);
66public: 83public:
67 CLibrary(): _module(NULL) {}; 84 CLibrary(): _module(NULL) {}
68 ~CLibrary() { Free(); } 85 ~CLibrary() { Free(); }
69 86
87 HMODULE Get_HMODULE() const { return _module; }
88
70 bool Free() throw(); 89 bool Free() throw();
71 bool Load(CFSTR path) throw(); 90 bool Load(CFSTR path) throw();
72 // FARPROC 91 // FARPROC
73 void *GetProc(LPCSTR procName) const; // { return My_GetProcAddress(_module, procName); } 92 // void *GetProc(LPCSTR procName) const; // { return My_GetProcAddress(_module, procName); }
74}; 93};
75 94
76#endif 95#endif
diff --git a/CPP/Windows/Defs.h b/CPP/Windows/Defs.h
index 1d96078..8ab9cf5 100644
--- a/CPP/Windows/Defs.h
+++ b/CPP/Windows/Defs.h
@@ -1,12 +1,11 @@
1// Windows/Defs.h 1// Windows/Defs.h
2 2
3#ifndef __WINDOWS_DEFS_H 3#ifndef ZIP7_INC_WINDOWS_DEFS_H
4#define __WINDOWS_DEFS_H 4#define ZIP7_INC_WINDOWS_DEFS_H
5 5
6#include "../Common/MyWindows.h" 6#include "../Common/MyWindows.h"
7 7
8#ifdef _WIN32 8#ifdef _WIN32
9inline bool LRESULTToBool(LRESULT v) { return (v != FALSE); }
10inline BOOL BoolToBOOL(bool v) { return (v ? TRUE: FALSE); } 9inline BOOL BoolToBOOL(bool v) { return (v ? TRUE: FALSE); }
11#endif 10#endif
12 11
diff --git a/CPP/Windows/ErrorMsg.cpp b/CPP/Windows/ErrorMsg.cpp
index f6343a5..5acf3ad 100644
--- a/CPP/Windows/ErrorMsg.cpp
+++ b/CPP/Windows/ErrorMsg.cpp
@@ -19,8 +19,8 @@ namespace NError {
19 19
20static bool MyFormatMessage(DWORD errorCode, UString &message) 20static bool MyFormatMessage(DWORD errorCode, UString &message)
21{ 21{
22 #ifndef _SFX 22 #ifndef Z7_SFX
23 if ((HRESULT)errorCode == MY_HRES_ERROR__INTERNAL_ERROR) 23 if ((HRESULT)errorCode == MY_HRES_ERROR_INTERNAL_ERROR)
24 { 24 {
25 message = "Internal Error: The failure in hardware (RAM or CPU), OS or program"; 25 message = "Internal Error: The failure in hardware (RAM or CPU), OS or program";
26 return true; 26 return true;
@@ -72,7 +72,7 @@ static bool MyFormatMessage(DWORD errorCode, UString &message)
72 case E_OUTOFMEMORY : s = "E_OUTOFMEMORY : Can't allocate required memory"; break; 72 case E_OUTOFMEMORY : s = "E_OUTOFMEMORY : Can't allocate required memory"; break;
73 case E_INVALIDARG : s = "E_INVALIDARG : One or more arguments are invalid"; break; 73 case E_INVALIDARG : s = "E_INVALIDARG : One or more arguments are invalid"; break;
74 74
75 // case MY__E_ERROR_NEGATIVE_SEEK : s = "MY__E_ERROR_NEGATIVE_SEEK"; break; 75 // case MY_E_ERROR_NEGATIVE_SEEK : s = "MY_E_ERROR_NEGATIVE_SEEK"; break;
76 default: 76 default:
77 break; 77 break;
78 } 78 }
@@ -81,7 +81,7 @@ static bool MyFormatMessage(DWORD errorCode, UString &message)
81 So we must transfer error codes before strerror() */ 81 So we must transfer error codes before strerror() */
82 if (!s) 82 if (!s)
83 { 83 {
84 if ((errorCode & 0xFFFF0000) == (UInt32)((MY__FACILITY__WRes << 16) | 0x80000000)) 84 if ((errorCode & 0xFFFF0000) == (UInt32)((MY_FACILITY_WRes << 16) | 0x80000000))
85 errorCode &= 0xFFFF; 85 errorCode &= 0xFFFF;
86 else if ((errorCode & ((UInt32)1 << 31))) 86 else if ((errorCode & ((UInt32)1 << 31)))
87 return false; // we will show hex error later for that case 87 return false; // we will show hex error later for that case
diff --git a/CPP/Windows/ErrorMsg.h b/CPP/Windows/ErrorMsg.h
index 01204eb..6142b4e 100644
--- a/CPP/Windows/ErrorMsg.h
+++ b/CPP/Windows/ErrorMsg.h
@@ -1,7 +1,7 @@
1// Windows/ErrorMsg.h 1// Windows/ErrorMsg.h
2 2
3#ifndef __WINDOWS_ERROR_MSG_H 3#ifndef ZIP7_INC_WINDOWS_ERROR_MSG_H
4#define __WINDOWS_ERROR_MSG_H 4#define ZIP7_INC_WINDOWS_ERROR_MSG_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
diff --git a/CPP/Windows/FileDir.cpp b/CPP/Windows/FileDir.cpp
index cce2638..5b1f340 100644
--- a/CPP/Windows/FileDir.cpp
+++ b/CPP/Windows/FileDir.cpp
@@ -65,46 +65,55 @@ namespace NDir {
65 65
66bool GetWindowsDir(FString &path) 66bool GetWindowsDir(FString &path)
67{ 67{
68 UINT needLength; 68 const unsigned kBufSize = MAX_PATH + 16;
69 UINT len;
69 #ifndef _UNICODE 70 #ifndef _UNICODE
70 if (!g_IsNT) 71 if (!g_IsNT)
71 { 72 {
72 TCHAR s[MAX_PATH + 2]; 73 TCHAR s[kBufSize + 1];
73 s[0] = 0; 74 s[0] = 0;
74 needLength = ::GetWindowsDirectory(s, MAX_PATH + 1); 75 len = ::GetWindowsDirectory(s, kBufSize);
75 path = fas2fs(s); 76 path = fas2fs(s);
76 } 77 }
77 else 78 else
78 #endif 79 #endif
79 { 80 {
80 WCHAR s[MAX_PATH + 2]; 81 WCHAR s[kBufSize + 1];
81 s[0] = 0; 82 s[0] = 0;
82 needLength = ::GetWindowsDirectoryW(s, MAX_PATH + 1); 83 len = ::GetWindowsDirectoryW(s, kBufSize);
83 path = us2fs(s); 84 path = us2fs(s);
84 } 85 }
85 return (needLength > 0 && needLength <= MAX_PATH); 86 return (len != 0 && len < kBufSize);
86} 87}
87 88
89
90/*
91new DOCs for GetSystemDirectory:
92 returned path does not end with a backslash unless the
93 system directory is the root directory.
94*/
95
88bool GetSystemDir(FString &path) 96bool GetSystemDir(FString &path)
89{ 97{
90 UINT needLength; 98 const unsigned kBufSize = MAX_PATH + 16;
99 UINT len;
91 #ifndef _UNICODE 100 #ifndef _UNICODE
92 if (!g_IsNT) 101 if (!g_IsNT)
93 { 102 {
94 TCHAR s[MAX_PATH + 2]; 103 TCHAR s[kBufSize + 1];
95 s[0] = 0; 104 s[0] = 0;
96 needLength = ::GetSystemDirectory(s, MAX_PATH + 1); 105 len = ::GetSystemDirectory(s, kBufSize);
97 path = fas2fs(s); 106 path = fas2fs(s);
98 } 107 }
99 else 108 else
100 #endif 109 #endif
101 { 110 {
102 WCHAR s[MAX_PATH + 2]; 111 WCHAR s[kBufSize + 1];
103 s[0] = 0; 112 s[0] = 0;
104 needLength = ::GetSystemDirectoryW(s, MAX_PATH + 1); 113 len = ::GetSystemDirectoryW(s, kBufSize);
105 path = us2fs(s); 114 path = us2fs(s);
106 } 115 }
107 return (needLength > 0 && needLength <= MAX_PATH); 116 return (len != 0 && len < kBufSize);
108} 117}
109#endif // UNDER_CE 118#endif // UNDER_CE
110 119
@@ -123,7 +132,7 @@ bool SetDirTime(CFSTR path, const CFiTime *cTime, const CFiTime *aTime, const CF
123 IF_USE_MAIN_PATH 132 IF_USE_MAIN_PATH
124 hDir = ::CreateFileW(fs2us(path), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 133 hDir = ::CreateFileW(fs2us(path), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
125 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 134 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
126 #ifdef WIN_LONG_PATH 135 #ifdef Z7_LONG_PATH
127 if (hDir == INVALID_HANDLE_VALUE && USE_SUPER_PATH) 136 if (hDir == INVALID_HANDLE_VALUE && USE_SUPER_PATH)
128 { 137 {
129 UString superPath; 138 UString superPath;
@@ -158,7 +167,7 @@ bool SetFileAttrib(CFSTR path, DWORD attrib)
158 IF_USE_MAIN_PATH 167 IF_USE_MAIN_PATH
159 if (::SetFileAttributesW(fs2us(path), attrib)) 168 if (::SetFileAttributesW(fs2us(path), attrib))
160 return true; 169 return true;
161 #ifdef WIN_LONG_PATH 170 #ifdef Z7_LONG_PATH
162 if (USE_SUPER_PATH) 171 if (USE_SUPER_PATH)
163 { 172 {
164 UString superPath; 173 UString superPath;
@@ -195,7 +204,7 @@ bool RemoveDir(CFSTR path)
195 IF_USE_MAIN_PATH 204 IF_USE_MAIN_PATH
196 if (::RemoveDirectoryW(fs2us(path))) 205 if (::RemoveDirectoryW(fs2us(path)))
197 return true; 206 return true;
198 #ifdef WIN_LONG_PATH 207 #ifdef Z7_LONG_PATH
199 if (USE_SUPER_PATH) 208 if (USE_SUPER_PATH)
200 { 209 {
201 UString superPath; 210 UString superPath;
@@ -224,7 +233,7 @@ bool MyMoveFile(CFSTR oldFile, CFSTR newFile)
224 if (::MoveFileW(fs2us(oldFile), fs2us(newFile))) 233 if (::MoveFileW(fs2us(oldFile), fs2us(newFile)))
225 return true; 234 return true;
226 } 235 }
227 #ifdef WIN_LONG_PATH 236 #ifdef Z7_LONG_PATH
228 if (USE_SUPER_PATH_2) 237 if (USE_SUPER_PATH_2)
229 { 238 {
230 UString d1, d2; 239 UString d1, d2;
@@ -261,8 +270,11 @@ bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName)
261 else 270 else
262 #endif 271 #endif
263 { 272 {
264 Func_CreateHardLinkW my_CreateHardLinkW = (Func_CreateHardLinkW) 273 const
265 (void *)::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "CreateHardLinkW"); 274 Func_CreateHardLinkW
275 my_CreateHardLinkW = Z7_GET_PROC_ADDRESS(
276 Func_CreateHardLinkW, ::GetModuleHandleW(L"kernel32.dll"),
277 "CreateHardLinkW");
266 if (!my_CreateHardLinkW) 278 if (!my_CreateHardLinkW)
267 return false; 279 return false;
268 IF_USE_MAIN_PATH_2(newFileName, existFileName) 280 IF_USE_MAIN_PATH_2(newFileName, existFileName)
@@ -270,7 +282,7 @@ bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName)
270 if (my_CreateHardLinkW(fs2us(newFileName), fs2us(existFileName), NULL)) 282 if (my_CreateHardLinkW(fs2us(newFileName), fs2us(existFileName), NULL))
271 return true; 283 return true;
272 } 284 }
273 #ifdef WIN_LONG_PATH 285 #ifdef Z7_LONG_PATH
274 if (USE_SUPER_PATH_2) 286 if (USE_SUPER_PATH_2)
275 { 287 {
276 UString d1, d2; 288 UString d1, d2;
@@ -320,7 +332,7 @@ bool CreateDir(CFSTR path)
320 IF_USE_MAIN_PATH 332 IF_USE_MAIN_PATH
321 if (::CreateDirectoryW(fs2us(path), NULL)) 333 if (::CreateDirectoryW(fs2us(path), NULL))
322 return true; 334 return true;
323 #ifdef WIN_LONG_PATH 335 #ifdef Z7_LONG_PATH
324 if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH) 336 if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH)
325 { 337 {
326 UString superPath; 338 UString superPath;
@@ -355,7 +367,7 @@ static bool CreateDir2(CFSTR path)
355 IF_USE_MAIN_PATH 367 IF_USE_MAIN_PATH
356 if (::CreateDirectoryW(fs2us(path), NULL)) 368 if (::CreateDirectoryW(fs2us(path), NULL))
357 return true; 369 return true;
358 #ifdef WIN_LONG_PATH 370 #ifdef Z7_LONG_PATH
359 if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH) 371 if ((!USE_MAIN_PATH || ::GetLastError() != ERROR_ALREADY_EXISTS) && USE_SUPER_PATH)
360 { 372 {
361 UString superPath; 373 UString superPath;
@@ -390,7 +402,7 @@ bool CreateComplexDir(CFSTR _path)
390 #ifdef _WIN32 402 #ifdef _WIN32
391 403
392 { 404 {
393 DWORD attrib = NFind::GetFileAttrib(_path); 405 const DWORD attrib = NFind::GetFileAttrib(_path);
394 if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0) 406 if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0)
395 return true; 407 return true;
396 } 408 }
@@ -496,7 +508,7 @@ bool DeleteFileAlways(CFSTR path)
496 IF_USE_MAIN_PATH 508 IF_USE_MAIN_PATH
497 if (::DeleteFileW(fs2us(path))) 509 if (::DeleteFileW(fs2us(path)))
498 return true; 510 return true;
499 #ifdef WIN_LONG_PATH 511 #ifdef Z7_LONG_PATH
500 if (USE_SUPER_PATH) 512 if (USE_SUPER_PATH)
501 { 513 {
502 UString superPath; 514 UString superPath;
@@ -586,9 +598,12 @@ bool MyGetFullPathName(CFSTR path, FString &resFullPath)
586 598
587#ifdef _WIN32 599#ifdef _WIN32
588 600
601/* Win10: SetCurrentDirectory() doesn't support long paths and
602 doesn't support super prefix "\\?\", if long path behavior is not
603 enabled in registry (LongPathsEnabled) and in manifest (longPathAware). */
604
589bool SetCurrentDir(CFSTR path) 605bool SetCurrentDir(CFSTR path)
590{ 606{
591 // SetCurrentDirectory doesn't support \\?\ prefix
592 #ifndef _UNICODE 607 #ifndef _UNICODE
593 if (!g_IsNT) 608 if (!g_IsNT)
594 { 609 {
@@ -602,28 +617,74 @@ bool SetCurrentDir(CFSTR path)
602} 617}
603 618
604 619
620/*
621we use system function GetCurrentDirectory()
622new GetCurrentDirectory() DOCs:
623 - If the function fails, the return value is zero.
624 - If the function succeeds, the return value specifies
625 the number of characters that are written to the buffer,
626 not including the terminating null character.
627 - If the buffer is not large enough, the return value specifies
628 the required size of the buffer, in characters,
629 including the null-terminating character.
630
631GetCurrentDir() calls GetCurrentDirectory().
632GetCurrentDirectory() in win10 in tests:
633 the returned (path) does not end with a backslash, if
634 current directory is not root directory of drive.
635 But that behavior is not guarantied in specification docs.
636*/
637
605bool GetCurrentDir(FString &path) 638bool GetCurrentDir(FString &path)
606{ 639{
640 const unsigned kBufSize = MAX_PATH + 16;
607 path.Empty(); 641 path.Empty();
608 642
609 DWORD needLength;
610 #ifndef _UNICODE 643 #ifndef _UNICODE
611 if (!g_IsNT) 644 if (!g_IsNT)
612 { 645 {
613 TCHAR s[MAX_PATH + 2]; 646 TCHAR s[kBufSize + 1];
614 s[0] = 0; 647 s[0] = 0;
615 needLength = ::GetCurrentDirectory(MAX_PATH + 1, s); 648 const DWORD len = ::GetCurrentDirectory(kBufSize, s);
649 if (len == 0 || len >= kBufSize)
650 return false;
651 s[kBufSize] = 0; // optional guard
616 path = fas2fs(s); 652 path = fas2fs(s);
653 return true;
617 } 654 }
618 else 655 else
619 #endif 656 #endif
620 { 657 {
621 WCHAR s[MAX_PATH + 2]; 658 DWORD len;
622 s[0] = 0; 659 {
623 needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, s); 660 WCHAR s[kBufSize + 1];
624 path = us2fs(s); 661 s[0] = 0;
662 len = ::GetCurrentDirectoryW(kBufSize, s);
663 if (len == 0)
664 return false;
665 if (len < kBufSize)
666 {
667 s[kBufSize] = 0; // optional guard
668 path = us2fs(s);
669 return true;
670 }
671 }
672 UString temp;
673 const DWORD len2 = ::GetCurrentDirectoryW(len, temp.GetBuf(len));
674 if (len2 == 0)
675 return false;
676 temp.ReleaseBuf_CalcLen(len);
677 if (temp.Len() != len2 || len - 1 != len2)
678 {
679 /* it's unexpected case, if current dir of process
680 was changed between two function calls,
681 or some unexpected function implementation */
682 // SetLastError((DWORD)E_FAIL); // we can set some error code
683 return false;
684 }
685 path = us2fs(temp);
686 return true;
625 } 687 }
626 return (needLength > 0 && needLength <= MAX_PATH);
627} 688}
628 689
629#endif // _WIN32 690#endif // _WIN32
@@ -648,41 +709,59 @@ bool GetOnlyDirPrefix(CFSTR path, FString &resDirPrefix)
648 return GetFullPathAndSplit(path, resDirPrefix, resFileName); 709 return GetFullPathAndSplit(path, resDirPrefix, resFileName);
649} 710}
650 711
712
713
651bool MyGetTempPath(FString &path) 714bool MyGetTempPath(FString &path)
652{ 715{
653 #ifdef _WIN32 716 #ifdef _WIN32
654 path.Empty(); 717
655 DWORD needLength; 718 /*
719 new DOCs for GetTempPathW():
720 - The returned string ends with a backslash.
721 - The maximum possible return value is MAX_PATH+1 (261).
722 */
723
724 const unsigned kBufSize = MAX_PATH + 16;
725 DWORD len;
656 #ifndef _UNICODE 726 #ifndef _UNICODE
657 if (!g_IsNT) 727 if (!g_IsNT)
658 { 728 {
659 TCHAR s[MAX_PATH + 2]; 729 TCHAR s[kBufSize + 1];
660 s[0] = 0; 730 s[0] = 0;
661 needLength = ::GetTempPath(MAX_PATH + 1, s); 731 len = ::GetTempPath(kBufSize, s);
662 path = fas2fs(s); 732 path = fas2fs(s);
663 } 733 }
664 else 734 else
665 #endif 735 #endif
666 { 736 {
667 WCHAR s[MAX_PATH + 2]; 737 WCHAR s[kBufSize + 1];
668 s[0] = 0; 738 s[0] = 0;
669 needLength = ::GetTempPathW(MAX_PATH + 1, s);; 739 len = ::GetTempPathW(kBufSize, s);
670 path = us2fs(s); 740 path = us2fs(s);
671 } 741 }
672 return (needLength > 0 && needLength <= MAX_PATH); 742 /* win10: GetTempPathW() doesn't set backslash at the end of path,
743 if (buffer_size == len_of(path_with_backslash)).
744 So we normalize path here: */
745 NormalizeDirPathPrefix(path);
746 return (len != 0 && len < kBufSize);
673 747
674 #else 748 #else // !_WIN32
675 749
676 // FIXME: improve that code 750 // FIXME: improve that code
677 path = "/tmp/"; 751 path = STRING_PATH_SEPARATOR "tmp";
678 if (!NFind::DoesDirExist_FollowLink(path)) 752 const char *s;
679 path = "./"; 753 if (NFind::DoesDirExist_FollowLink(path))
754 s = STRING_PATH_SEPARATOR "tmp" STRING_PATH_SEPARATOR;
755 else
756 s = "." STRING_PATH_SEPARATOR;
757 path = s;
680 return true; 758 return true;
759
681 #endif 760 #endif
682} 761}
683 762
684 763
685static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COutFile *outFile) 764bool CreateTempFile2(CFSTR prefix, bool addRandom, AString &postfix, NIO::COutFile *outFile)
686{ 765{
687 UInt32 d = 766 UInt32 d =
688 #ifdef _WIN32 767 #ifdef _WIN32
@@ -693,7 +772,7 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu
693 772
694 for (unsigned i = 0; i < 100; i++) 773 for (unsigned i = 0; i < 100; i++)
695 { 774 {
696 path = prefix; 775 postfix.Empty();
697 if (addRandom) 776 if (addRandom)
698 { 777 {
699 char s[16]; 778 char s[16];
@@ -701,14 +780,14 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu
701 unsigned k; 780 unsigned k;
702 for (k = 0; k < 8; k++) 781 for (k = 0; k < 8; k++)
703 { 782 {
704 unsigned t = val & 0xF; 783 const unsigned t = val & 0xF;
705 val >>= 4; 784 val >>= 4;
706 s[k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10))); 785 s[k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
707 } 786 }
708 s[k] = '\0'; 787 s[k] = '\0';
709 if (outFile) 788 if (outFile)
710 path += '.'; 789 postfix.Add_Dot();
711 path += s; 790 postfix += s;
712 UInt32 step = GetTickCount() + 2; 791 UInt32 step = GetTickCount() + 2;
713 if (step == 0) 792 if (step == 0)
714 step = 1; 793 step = 1;
@@ -716,7 +795,9 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu
716 } 795 }
717 addRandom = true; 796 addRandom = true;
718 if (outFile) 797 if (outFile)
719 path += ".tmp"; 798 postfix += ".tmp";
799 FString path (prefix);
800 path += postfix;
720 if (NFind::DoesFileOrDirExist(path)) 801 if (NFind::DoesFileOrDirExist(path))
721 { 802 {
722 SetLastError(ERROR_ALREADY_EXISTS); 803 SetLastError(ERROR_ALREADY_EXISTS);
@@ -732,12 +813,12 @@ static bool CreateTempFile(CFSTR prefix, bool addRandom, FString &path, NIO::COu
732 if (CreateDir(path)) 813 if (CreateDir(path))
733 return true; 814 return true;
734 } 815 }
735 DWORD error = GetLastError(); 816 const DWORD error = GetLastError();
736 if (error != ERROR_FILE_EXISTS && 817 if (error != ERROR_FILE_EXISTS &&
737 error != ERROR_ALREADY_EXISTS) 818 error != ERROR_ALREADY_EXISTS)
738 break; 819 break;
739 } 820 }
740 path.Empty(); 821 postfix.Empty();
741 return false; 822 return false;
742} 823}
743 824
@@ -745,8 +826,12 @@ bool CTempFile::Create(CFSTR prefix, NIO::COutFile *outFile)
745{ 826{
746 if (!Remove()) 827 if (!Remove())
747 return false; 828 return false;
748 if (!CreateTempFile(prefix, false, _path, outFile)) 829 _path.Empty();
830 AString postfix;
831 if (!CreateTempFile2(prefix, false, postfix, outFile))
749 return false; 832 return false;
833 _path = prefix;
834 _path += postfix;
750 _mustBeDeleted = true; 835 _mustBeDeleted = true;
751 return true; 836 return true;
752} 837}
@@ -755,11 +840,16 @@ bool CTempFile::CreateRandomInTempFolder(CFSTR namePrefix, NIO::COutFile *outFil
755{ 840{
756 if (!Remove()) 841 if (!Remove())
757 return false; 842 return false;
843 _path.Empty();
758 FString tempPath; 844 FString tempPath;
759 if (!MyGetTempPath(tempPath)) 845 if (!MyGetTempPath(tempPath))
760 return false; 846 return false;
761 if (!CreateTempFile(tempPath + namePrefix, true, _path, outFile)) 847 AString postfix;
848 tempPath += namePrefix;
849 if (!CreateTempFile2(tempPath, true, postfix, outFile))
762 return false; 850 return false;
851 _path = tempPath;
852 _path += postfix;
763 _mustBeDeleted = true; 853 _mustBeDeleted = true;
764 return true; 854 return true;
765} 855}
@@ -802,11 +892,16 @@ bool CTempDir::Create(CFSTR prefix)
802{ 892{
803 if (!Remove()) 893 if (!Remove())
804 return false; 894 return false;
895 _path.Empty();
805 FString tempPath; 896 FString tempPath;
806 if (!MyGetTempPath(tempPath)) 897 if (!MyGetTempPath(tempPath))
807 return false; 898 return false;
808 if (!CreateTempFile(tempPath + prefix, true, _path, NULL)) 899 tempPath += prefix;
900 AString postfix;
901 if (!CreateTempFile2(tempPath, true, postfix, NULL))
809 return false; 902 return false;
903 _path = tempPath;
904 _path += postfix;
810 _mustBeDeleted = true; 905 _mustBeDeleted = true;
811 return true; 906 return true;
812} 907}
@@ -830,7 +925,7 @@ bool RemoveDir(CFSTR path)
830} 925}
831 926
832 927
833static BOOL My__CopyFile(CFSTR oldFile, CFSTR newFile) 928static BOOL My_CopyFile(CFSTR oldFile, CFSTR newFile)
834{ 929{
835 NWindows::NFile::NIO::COutFile outFile; 930 NWindows::NFile::NIO::COutFile outFile;
836 if (!outFile.Create(newFile, false)) 931 if (!outFile.Create(newFile, false))
@@ -865,7 +960,7 @@ bool MyMoveFile(CFSTR oldFile, CFSTR newFile)
865 if (errno != EXDEV) // (oldFile and newFile are not on the same mounted filesystem) 960 if (errno != EXDEV) // (oldFile and newFile are not on the same mounted filesystem)
866 return false; 961 return false;
867 962
868 if (My__CopyFile(oldFile, newFile) == FALSE) 963 if (My_CopyFile(oldFile, newFile) == FALSE)
869 return false; 964 return false;
870 965
871 struct stat info_file; 966 struct stat info_file;
@@ -906,11 +1001,11 @@ bool GetCurrentDir(FString &path)
906{ 1001{
907 path.Empty(); 1002 path.Empty();
908 1003
909 #define MY__PATH_MAX PATH_MAX 1004 #define MY_PATH_MAX PATH_MAX
910 // #define MY__PATH_MAX 1024 1005 // #define MY_PATH_MAX 1024
911 1006
912 char s[MY__PATH_MAX + 1]; 1007 char s[MY_PATH_MAX + 1];
913 char *res = getcwd(s, MY__PATH_MAX); 1008 char *res = getcwd(s, MY_PATH_MAX);
914 if (res) 1009 if (res)
915 { 1010 {
916 path = fas2fs(s); 1011 path = fas2fs(s);
@@ -1035,10 +1130,10 @@ static C_umask g_umask;
1035#define PRF(x) 1130#define PRF(x)
1036 1131
1037#define TRACE_SetFileAttrib(msg) \ 1132#define TRACE_SetFileAttrib(msg) \
1038 PRF(printf("\nSetFileAttrib(%s, %x) : %s\n", (const char *)path, attrib, msg)); 1133 PRF(printf("\nSetFileAttrib(%s, %x) : %s\n", (const char *)path, attrib, msg);)
1039 1134
1040#define TRACE_chmod(s, mode) \ 1135#define TRACE_chmod(s, mode) \
1041 PRF(printf("\n chmod(%s, %o)\n", (const char *)path, (unsigned)(mode))); 1136 PRF(printf("\n chmod(%s, %o)\n", (const char *)path, (unsigned)(mode));)
1042 1137
1043int my_chown(CFSTR path, uid_t owner, gid_t group) 1138int my_chown(CFSTR path, uid_t owner, gid_t group)
1044{ 1139{
@@ -1047,7 +1142,7 @@ int my_chown(CFSTR path, uid_t owner, gid_t group)
1047 1142
1048bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib) 1143bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1049{ 1144{
1050 TRACE_SetFileAttrib(""); 1145 TRACE_SetFileAttrib("")
1051 1146
1052 struct stat st; 1147 struct stat st;
1053 1148
@@ -1056,7 +1151,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1056 { 1151 {
1057 if (lstat(path, &st) != 0) 1152 if (lstat(path, &st) != 0)
1058 { 1153 {
1059 TRACE_SetFileAttrib("bad lstat()"); 1154 TRACE_SetFileAttrib("bad lstat()")
1060 return false; 1155 return false;
1061 } 1156 }
1062 // TRACE_chmod("lstat", st.st_mode); 1157 // TRACE_chmod("lstat", st.st_mode);
@@ -1065,14 +1160,14 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1065 { 1160 {
1066 if (stat(path, &st) != 0) 1161 if (stat(path, &st) != 0)
1067 { 1162 {
1068 TRACE_SetFileAttrib("bad stat()"); 1163 TRACE_SetFileAttrib("bad stat()")
1069 return false; 1164 return false;
1070 } 1165 }
1071 } 1166 }
1072 1167
1073 if (attrib & FILE_ATTRIBUTE_UNIX_EXTENSION) 1168 if (attrib & FILE_ATTRIBUTE_UNIX_EXTENSION)
1074 { 1169 {
1075 TRACE_SetFileAttrib("attrib & FILE_ATTRIBUTE_UNIX_EXTENSION"); 1170 TRACE_SetFileAttrib("attrib & FILE_ATTRIBUTE_UNIX_EXTENSION")
1076 st.st_mode = attrib >> 16; 1171 st.st_mode = attrib >> 16;
1077 if (S_ISDIR(st.st_mode)) 1172 if (S_ISDIR(st.st_mode))
1078 { 1173 {
@@ -1092,7 +1187,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1092 } 1187 }
1093 else 1188 else
1094 { 1189 {
1095 TRACE_SetFileAttrib("Only Windows Attributes"); 1190 TRACE_SetFileAttrib("Only Windows Attributes")
1096 // Only Windows Attributes 1191 // Only Windows Attributes
1097 if (S_ISDIR(st.st_mode) 1192 if (S_ISDIR(st.st_mode)
1098 || (attrib & FILE_ATTRIBUTE_READONLY) == 0) 1193 || (attrib & FILE_ATTRIBUTE_READONLY) == 0)
@@ -1105,7 +1200,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1105 if (S_ISLNK(st.st_mode)) 1200 if (S_ISLNK(st.st_mode))
1106 { 1201 {
1107 printf("\nfchmodat()\n"); 1202 printf("\nfchmodat()\n");
1108 TRACE_chmod(path, (st.st_mode) & g_umask.mask); 1203 TRACE_chmod(path, (st.st_mode) & g_umask.mask)
1109 // AT_SYMLINK_NOFOLLOW is not implemted still in Linux. 1204 // AT_SYMLINK_NOFOLLOW is not implemted still in Linux.
1110 res = fchmodat(AT_FDCWD, path, (st.st_mode) & g_umask.mask, 1205 res = fchmodat(AT_FDCWD, path, (st.st_mode) & g_umask.mask,
1111 S_ISLNK(st.st_mode) ? AT_SYMLINK_NOFOLLOW : 0); 1206 S_ISLNK(st.st_mode) ? AT_SYMLINK_NOFOLLOW : 0);
@@ -1113,7 +1208,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1113 else 1208 else
1114 */ 1209 */
1115 { 1210 {
1116 TRACE_chmod(path, (st.st_mode) & g_umask.mask); 1211 TRACE_chmod(path, (st.st_mode) & g_umask.mask)
1117 res = chmod(path, (st.st_mode) & g_umask.mask); 1212 res = chmod(path, (st.st_mode) & g_umask.mask);
1118 } 1213 }
1119 // TRACE_SetFileAttrib("End") 1214 // TRACE_SetFileAttrib("End")
@@ -1123,7 +1218,7 @@ bool SetFileAttrib_PosixHighDetect(CFSTR path, DWORD attrib)
1123 1218
1124bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName) 1219bool MyCreateHardLink(CFSTR newFileName, CFSTR existFileName)
1125{ 1220{
1126 PRF(printf("\nhard link() %s -> %s\n", newFileName, existFileName)); 1221 PRF(printf("\nhard link() %s -> %s\n", newFileName, existFileName);)
1127 return (link(existFileName, newFileName) == 0); 1222 return (link(existFileName, newFileName) == 0);
1128} 1223}
1129 1224
diff --git a/CPP/Windows/FileDir.h b/CPP/Windows/FileDir.h
index 08281aa..573ffa2 100644
--- a/CPP/Windows/FileDir.h
+++ b/CPP/Windows/FileDir.h
@@ -1,7 +1,7 @@
1// Windows/FileDir.h 1// Windows/FileDir.h
2 2
3#ifndef __WINDOWS_FILE_DIR_H 3#ifndef ZIP7_INC_WINDOWS_FILE_DIR_H
4#define __WINDOWS_FILE_DIR_H 4#define ZIP7_INC_WINDOWS_FILE_DIR_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
@@ -73,6 +73,8 @@ bool GetCurrentDir(FString &resultPath);
73 73
74bool MyGetTempPath(FString &resultPath); 74bool MyGetTempPath(FString &resultPath);
75 75
76bool CreateTempFile2(CFSTR prefix, bool addRandom, AString &postfix, NIO::COutFile *outFile);
77
76class CTempFile MY_UNCOPYABLE 78class CTempFile MY_UNCOPYABLE
77{ 79{
78 bool _mustBeDeleted; 80 bool _mustBeDeleted;
diff --git a/CPP/Windows/FileFind.cpp b/CPP/Windows/FileFind.cpp
index c655759..c562a90 100644
--- a/CPP/Windows/FileFind.cpp
+++ b/CPP/Windows/FileFind.cpp
@@ -39,10 +39,10 @@ typedef struct
39 WCHAR cStreamName[MAX_PATH + 36]; 39 WCHAR cStreamName[MAX_PATH + 36];
40} MY_WIN32_FIND_STREAM_DATA, *MY_PWIN32_FIND_STREAM_DATA; 40} MY_WIN32_FIND_STREAM_DATA, *MY_PWIN32_FIND_STREAM_DATA;
41 41
42typedef HANDLE (WINAPI *FindFirstStreamW_Ptr)(LPCWSTR fileName, MY_STREAM_INFO_LEVELS infoLevel, 42typedef HANDLE (WINAPI *Func_FindFirstStreamW)(LPCWSTR fileName, MY_STREAM_INFO_LEVELS infoLevel,
43 LPVOID findStreamData, DWORD flags); 43 LPVOID findStreamData, DWORD flags);
44 44
45typedef BOOL (APIENTRY *FindNextStreamW_Ptr)(HANDLE findStream, LPVOID findStreamData); 45typedef BOOL (APIENTRY *Func_FindNextStreamW)(HANDLE findStream, LPVOID findStreamData);
46 46
47EXTERN_C_END 47EXTERN_C_END
48 48
@@ -54,7 +54,7 @@ namespace NFile {
54 54
55 55
56#ifdef _WIN32 56#ifdef _WIN32
57#ifdef SUPPORT_DEVICE_FILE 57#ifdef Z7_DEVICE_FILE
58namespace NSystem 58namespace NSystem
59{ 59{
60bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize); 60bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize);
@@ -128,7 +128,7 @@ bool CFileInfo::IsDots() const throw()
128 128
129static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfo &fi) 129static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfo &fi)
130{ 130{
131 WIN_FD_TO_MY_FI(fi, fd); 131 WIN_FD_TO_MY_FI(fi, fd)
132 fi.Name = us2fs(fd.cFileName); 132 fi.Name = us2fs(fd.cFileName);
133 #if defined(_WIN32) && !defined(UNDER_CE) 133 #if defined(_WIN32) && !defined(UNDER_CE)
134 // fi.ShortName = us2fs(fd.cAlternateFileName); 134 // fi.ShortName = us2fs(fd.cAlternateFileName);
@@ -138,7 +138,7 @@ static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATAW &fd, CFil
138#ifndef _UNICODE 138#ifndef _UNICODE
139static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi) 139static void Convert_WIN32_FIND_DATA_to_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi)
140{ 140{
141 WIN_FD_TO_MY_FI(fi, fd); 141 WIN_FD_TO_MY_FI(fi, fd)
142 fi.Name = fas2fs(fd.cFileName); 142 fi.Name = fas2fs(fd.cFileName);
143 #if defined(_WIN32) && !defined(UNDER_CE) 143 #if defined(_WIN32) && !defined(UNDER_CE)
144 // fi.ShortName = fas2fs(fd.cAlternateFileName); 144 // fi.ShortName = fas2fs(fd.cAlternateFileName);
@@ -211,7 +211,7 @@ bool CFindFile::FindFirst(CFSTR path, CFileInfo &fi)
211 211
212 IF_USE_MAIN_PATH 212 IF_USE_MAIN_PATH
213 _handle = ::FindFirstFileW(fs2us(path), &fd); 213 _handle = ::FindFirstFileW(fs2us(path), &fd);
214 #ifdef WIN_LONG_PATH 214 #ifdef Z7_LONG_PATH
215 if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH) 215 if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH)
216 { 216 {
217 UString superPath; 217 UString superPath;
@@ -252,23 +252,27 @@ bool CFindFile::FindNext(CFileInfo &fi)
252//////////////////////////////// 252////////////////////////////////
253// AltStreams 253// AltStreams
254 254
255static FindFirstStreamW_Ptr g_FindFirstStreamW; 255static Func_FindFirstStreamW g_FindFirstStreamW;
256static FindNextStreamW_Ptr g_FindNextStreamW; 256static Func_FindNextStreamW g_FindNextStreamW;
257 257
258static struct CFindStreamLoader 258static struct CFindStreamLoader
259{ 259{
260 CFindStreamLoader() 260 CFindStreamLoader()
261 { 261 {
262 HMODULE hm = ::GetModuleHandleA("kernel32.dll"); 262 const HMODULE hm = ::GetModuleHandleA("kernel32.dll");
263 g_FindFirstStreamW = (FindFirstStreamW_Ptr)(void *)::GetProcAddress(hm, "FindFirstStreamW"); 263 g_FindFirstStreamW = Z7_GET_PROC_ADDRESS(
264 g_FindNextStreamW = (FindNextStreamW_Ptr)(void *)::GetProcAddress(hm, "FindNextStreamW"); 264 Func_FindFirstStreamW, hm,
265 "FindFirstStreamW");
266 g_FindNextStreamW = Z7_GET_PROC_ADDRESS(
267 Func_FindNextStreamW, hm,
268 "FindNextStreamW");
265 } 269 }
266} g_FindStreamLoader; 270} g_FindStreamLoader;
267 271
268bool CStreamInfo::IsMainStream() const throw() 272bool CStreamInfo::IsMainStream() const throw()
269{ 273{
270 return StringsAreEqualNoCase_Ascii(Name, "::$DATA"); 274 return StringsAreEqualNoCase_Ascii(Name, "::$DATA");
271}; 275}
272 276
273UString CStreamInfo::GetReducedName() const 277UString CStreamInfo::GetReducedName() const
274{ 278{
@@ -331,7 +335,7 @@ bool CFindStream::FindFirst(CFSTR path, CStreamInfo &si)
331 if (::GetLastError() == ERROR_HANDLE_EOF) 335 if (::GetLastError() == ERROR_HANDLE_EOF)
332 return false; 336 return false;
333 // long name can be tricky for path like ".\dirName". 337 // long name can be tricky for path like ".\dirName".
334 #ifdef WIN_LONG_PATH 338 #ifdef Z7_LONG_PATH
335 if (USE_SUPER_PATH) 339 if (USE_SUPER_PATH)
336 { 340 {
337 UString superPath; 341 UString superPath;
@@ -414,7 +418,7 @@ DWORD GetFileAttrib(CFSTR path)
414 if (dw != INVALID_FILE_ATTRIBUTES) 418 if (dw != INVALID_FILE_ATTRIBUTES)
415 return dw; 419 return dw;
416 } 420 }
417 #ifdef WIN_LONG_PATH 421 #ifdef Z7_LONG_PATH
418 if (USE_SUPER_PATH) 422 if (USE_SUPER_PATH)
419 { 423 {
420 UString superPath; 424 UString superPath;
@@ -451,7 +455,7 @@ also we support paths that are not supported by FindFirstFile:
451 455
452bool CFileInfo::Find(CFSTR path, bool followLink) 456bool CFileInfo::Find(CFSTR path, bool followLink)
453{ 457{
454 #ifdef SUPPORT_DEVICE_FILE 458 #ifdef Z7_DEVICE_FILE
455 459
456 if (IS_PATH_SEPAR(path[0]) && 460 if (IS_PATH_SEPAR(path[0]) &&
457 IS_PATH_SEPAR(path[1]) && 461 IS_PATH_SEPAR(path[1]) &&
@@ -847,7 +851,7 @@ HANDLE CFindChangeNotification::FindFirst(CFSTR path, bool watchSubtree, DWORD n
847 { 851 {
848 IF_USE_MAIN_PATH 852 IF_USE_MAIN_PATH
849 _handle = ::FindFirstChangeNotificationW(fs2us(path), BoolToBOOL(watchSubtree), notifyFilter); 853 _handle = ::FindFirstChangeNotificationW(fs2us(path), BoolToBOOL(watchSubtree), notifyFilter);
850 #ifdef WIN_LONG_PATH 854 #ifdef Z7_LONG_PATH
851 if (!IsHandleAllocated()) 855 if (!IsHandleAllocated())
852 { 856 {
853 UString superPath; 857 UString superPath;
diff --git a/CPP/Windows/FileFind.h b/CPP/Windows/FileFind.h
index fcfe02c..11408d0 100644
--- a/CPP/Windows/FileFind.h
+++ b/CPP/Windows/FileFind.h
@@ -1,7 +1,7 @@
1// Windows/FileFind.h 1// Windows/FileFind.h
2 2
3#ifndef __WINDOWS_FILE_FIND_H 3#ifndef ZIP7_INC_WINDOWS_FILE_FIND_H
4#define __WINDOWS_FILE_FIND_H 4#define ZIP7_INC_WINDOWS_FILE_FIND_H
5 5
6#ifndef _WIN32 6#ifndef _WIN32
7#include <sys/stat.h> 7#include <sys/stat.h>
@@ -249,7 +249,15 @@ class CFindChangeNotification MY_UNCOPYABLE
249 HANDLE _handle; 249 HANDLE _handle;
250public: 250public:
251 operator HANDLE () { return _handle; } 251 operator HANDLE () { return _handle; }
252 bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE && _handle != 0; } 252 bool IsHandleAllocated() const
253 {
254 /* at least on win2000/XP (undocumented):
255 if pathName is "" or NULL,
256 FindFirstChangeNotification() could return NULL.
257 So we check for INVALID_HANDLE_VALUE and NULL.
258 */
259 return _handle != INVALID_HANDLE_VALUE && _handle != NULL;
260 }
253 CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {} 261 CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {}
254 ~CFindChangeNotification() { Close(); } 262 ~CFindChangeNotification() { Close(); }
255 bool Close() throw(); 263 bool Close() throw();
diff --git a/CPP/Windows/FileIO.cpp b/CPP/Windows/FileIO.cpp
index e51b0eb..4ecbb7e 100644
--- a/CPP/Windows/FileIO.cpp
+++ b/CPP/Windows/FileIO.cpp
@@ -2,7 +2,7 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5#ifdef SUPPORT_DEVICE_FILE 5#ifdef Z7_DEVICE_FILE
6#include "../../C/Alloc.h" 6#include "../../C/Alloc.h"
7#endif 7#endif
8 8
@@ -21,7 +21,7 @@
21 21
22HRESULT GetLastError_noZero_HRESULT() 22HRESULT GetLastError_noZero_HRESULT()
23{ 23{
24 DWORD res = ::GetLastError(); 24 const DWORD res = ::GetLastError();
25 if (res == 0) 25 if (res == 0)
26 return E_FAIL; 26 return E_FAIL;
27 return HRESULT_FROM_WIN32(res); 27 return HRESULT_FROM_WIN32(res);
@@ -40,7 +40,7 @@ using namespace NName;
40namespace NWindows { 40namespace NWindows {
41namespace NFile { 41namespace NFile {
42 42
43#ifdef SUPPORT_DEVICE_FILE 43#ifdef Z7_DEVICE_FILE
44 44
45namespace NSystem 45namespace NSystem
46{ 46{
@@ -72,7 +72,7 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess,
72 if (!Close()) 72 if (!Close())
73 return false; 73 return false;
74 74
75 #ifdef SUPPORT_DEVICE_FILE 75 #ifdef Z7_DEVICE_FILE
76 IsDeviceFile = false; 76 IsDeviceFile = false;
77 #endif 77 #endif
78 78
@@ -88,7 +88,7 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess,
88 IF_USE_MAIN_PATH 88 IF_USE_MAIN_PATH
89 _handle = ::CreateFileW(fs2us(path), desiredAccess, shareMode, 89 _handle = ::CreateFileW(fs2us(path), desiredAccess, shareMode,
90 (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL); 90 (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, flagsAndAttributes, (HANDLE)NULL);
91 #ifdef WIN_LONG_PATH 91 #ifdef Z7_LONG_PATH
92 if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH) 92 if (_handle == INVALID_HANDLE_VALUE && USE_SUPER_PATH)
93 { 93 {
94 UString superPath; 94 UString superPath;
@@ -101,7 +101,7 @@ bool CFileBase::Create(CFSTR path, DWORD desiredAccess,
101 101
102 /* 102 /*
103 #ifndef UNDER_CE 103 #ifndef UNDER_CE
104 #ifndef _SFX 104 #ifndef Z7_SFX
105 if (_handle == INVALID_HANDLE_VALUE) 105 if (_handle == INVALID_HANDLE_VALUE)
106 { 106 {
107 // it's debug hack to open symbolic links in Windows XP and WSL links in Windows 10 107 // 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()
149 149
150bool CFileBase::GetLength(UInt64 &length) const throw() 150bool CFileBase::GetLength(UInt64 &length) const throw()
151{ 151{
152 #ifdef SUPPORT_DEVICE_FILE 152 #ifdef Z7_DEVICE_FILE
153 if (IsDeviceFile && SizeDefined) 153 if (IsDeviceFile && SizeDefined)
154 { 154 {
155 length = Size; 155 length = Size;
@@ -219,7 +219,7 @@ bool CFileBase::GetPosition(UInt64 &position) const throw()
219 219
220bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const throw() 220bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const throw()
221{ 221{
222 #ifdef SUPPORT_DEVICE_FILE 222 #ifdef Z7_DEVICE_FILE
223 if (IsDeviceFile && SizeDefined && moveMethod == FILE_END) 223 if (IsDeviceFile && SizeDefined && moveMethod == FILE_END)
224 { 224 {
225 distanceToMove += Size; 225 distanceToMove += Size;
@@ -262,12 +262,12 @@ bool CFileBase::SeekToEnd(UInt64 &newPosition) const throw()
262 262
263// ---------- CInFile --------- 263// ---------- CInFile ---------
264 264
265#ifdef SUPPORT_DEVICE_FILE 265#ifdef Z7_DEVICE_FILE
266 266
267void CInFile::CorrectDeviceSize() 267void CInFile::CorrectDeviceSize()
268{ 268{
269 // maybe we must decrease kClusterSize to 1 << 12, if we want correct size at tail 269 // maybe we must decrease kClusterSize to 1 << 12, if we want correct size at tail
270 static const UInt32 kClusterSize = 1 << 14; 270 const UInt32 kClusterSize = 1 << 14;
271 UInt64 pos = Size & ~(UInt64)(kClusterSize - 1); 271 UInt64 pos = Size & ~(UInt64)(kClusterSize - 1);
272 UInt64 realNewPosition; 272 UInt64 realNewPosition;
273 if (!Seek(pos, realNewPosition)) 273 if (!Seek(pos, realNewPosition))
@@ -462,7 +462,7 @@ static const UInt32 kChunkSizeMax = (1 << 22);
462bool CInFile::Read1(void *data, UInt32 size, UInt32 &processedSize) throw() 462bool CInFile::Read1(void *data, UInt32 size, UInt32 &processedSize) throw()
463{ 463{
464 DWORD processedLoc = 0; 464 DWORD processedLoc = 0;
465 bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL)); 465 const bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL));
466 processedSize = (UInt32)processedLoc; 466 processedSize = (UInt32)processedLoc;
467 return res; 467 return res;
468} 468}
@@ -480,7 +480,7 @@ bool CInFile::Read(void *data, UInt32 size, UInt32 &processedSize) throw()
480 do 480 do
481 { 481 {
482 UInt32 processedLoc = 0; 482 UInt32 processedLoc = 0;
483 bool res = ReadPart(data, size, processedLoc); 483 const bool res = ReadPart(data, size, processedLoc);
484 processedSize += processedLoc; 484 processedSize += processedLoc;
485 if (!res) 485 if (!res)
486 return false; 486 return false;
@@ -551,7 +551,7 @@ bool COutFile::Write(const void *data, UInt32 size, UInt32 &processedSize) throw
551 do 551 do
552 { 552 {
553 UInt32 processedLoc = 0; 553 UInt32 processedLoc = 0;
554 bool res = WritePart(data, size, processedLoc); 554 const bool res = WritePart(data, size, processedLoc);
555 processedSize += processedLoc; 555 processedSize += processedLoc;
556 if (!res) 556 if (!res)
557 return false; 557 return false;
@@ -628,14 +628,14 @@ bool SetDirTime(CFSTR path, const CFiTime *cTime, const CFiTime *aTime, const CF
628 628
629namespace NIO { 629namespace NIO {
630 630
631bool CFileBase::OpenBinary(const char *name, int flags) 631bool CFileBase::OpenBinary(const char *name, int flags, mode_t mode)
632{ 632{
633 #ifdef O_BINARY 633 #ifdef O_BINARY
634 flags |= O_BINARY; 634 flags |= O_BINARY;
635 #endif 635 #endif
636 636
637 Close(); 637 Close();
638 _handle = ::open(name, flags, 0666); 638 _handle = ::open(name, flags, mode);
639 return _handle != -1; 639 return _handle != -1;
640 640
641 /* 641 /*
@@ -804,10 +804,10 @@ bool COutFile::Create(const char *name, bool createAlways)
804 if (createAlways) 804 if (createAlways)
805 { 805 {
806 Close(); 806 Close();
807 _handle = ::creat(name, 0666); 807 _handle = ::creat(name, mode_for_Create);
808 return _handle != -1; 808 return _handle != -1;
809 } 809 }
810 return OpenBinary(name, O_CREAT | O_EXCL | O_WRONLY); 810 return OpenBinary(name, O_CREAT | O_EXCL | O_WRONLY, mode_for_Create);
811} 811}
812 812
813bool COutFile::Open(const char *name, DWORD creationDisposition) 813bool COutFile::Open(const char *name, DWORD creationDisposition)
@@ -850,13 +850,13 @@ bool COutFile::SetLength(UInt64 length) throw()
850 return false; 850 return false;
851 } 851 }
852 // The value of the seek pointer shall not be modified by a call to ftruncate(). 852 // The value of the seek pointer shall not be modified by a call to ftruncate().
853 int iret = ftruncate(_handle, len2); 853 const int iret = ftruncate(_handle, len2);
854 return (iret == 0); 854 return (iret == 0);
855} 855}
856 856
857bool COutFile::Close() 857bool COutFile::Close()
858{ 858{
859 bool res = CFileBase::Close(); 859 const bool res = CFileBase::Close();
860 if (!res) 860 if (!res)
861 return res; 861 return res;
862 if (CTime_defined || ATime_defined || MTime_defined) 862 if (CTime_defined || ATime_defined || MTime_defined)
diff --git a/CPP/Windows/FileIO.h b/CPP/Windows/FileIO.h
index 8050965..03e061a 100644
--- a/CPP/Windows/FileIO.h
+++ b/CPP/Windows/FileIO.h
@@ -1,23 +1,23 @@
1// Windows/FileIO.h 1// Windows/FileIO.h
2 2
3#ifndef __WINDOWS_FILE_IO_H 3#ifndef ZIP7_INC_WINDOWS_FILE_IO_H
4#define __WINDOWS_FILE_IO_H 4#define ZIP7_INC_WINDOWS_FILE_IO_H
5 5
6#include "../Common/MyWindows.h" 6#include "../Common/MyWindows.h"
7 7
8#define _my_IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L) 8#define Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
9#define _my_IO_REPARSE_TAG_SYMLINK (0xA000000CL) 9#define Z7_WIN_IO_REPARSE_TAG_SYMLINK (0xA000000CL)
10#define _my_IO_REPARSE_TAG_LX_SYMLINK (0xA000001DL) 10#define Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK (0xA000001DL)
11 11
12#define _my_SYMLINK_FLAG_RELATIVE 1 12#define Z7_WIN_SYMLINK_FLAG_RELATIVE 1
13 13
14// what the meaning of that FLAG or field (2)? 14// what the meaning of that FLAG or field (2)?
15#define _my_LX_SYMLINK_FLAG 2 15#define Z7_WIN_LX_SYMLINK_FLAG 2
16 16
17#ifdef _WIN32 17#ifdef _WIN32
18 18
19#if defined(_WIN32) && !defined(UNDER_CE) 19#if defined(_WIN32) && !defined(UNDER_CE)
20#include <WinIoCtl.h> 20#include <winioctl.h>
21#endif 21#endif
22 22
23#else 23#else
@@ -76,11 +76,11 @@ struct CReparseAttr
76 // returns (false) and (ErrorCode = ERROR_REPARSE_TAG_INVALID), if unknown tag 76 // returns (false) and (ErrorCode = ERROR_REPARSE_TAG_INVALID), if unknown tag
77 bool Parse(const Byte *p, size_t size); 77 bool Parse(const Byte *p, size_t size);
78 78
79 bool IsMountPoint() const { return Tag == _my_IO_REPARSE_TAG_MOUNT_POINT; } // it's Junction 79 bool IsMountPoint() const { return Tag == Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT; } // it's Junction
80 bool IsSymLink_Win() const { return Tag == _my_IO_REPARSE_TAG_SYMLINK; } 80 bool IsSymLink_Win() const { return Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK; }
81 bool IsSymLink_WSL() const { return Tag == _my_IO_REPARSE_TAG_LX_SYMLINK; } 81 bool IsSymLink_WSL() const { return Tag == Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK; }
82 82
83 bool IsRelative_Win() const { return Flags == _my_SYMLINK_FLAG_RELATIVE; } 83 bool IsRelative_Win() const { return Flags == Z7_WIN_SYMLINK_FLAG_RELATIVE; }
84 84
85 bool IsRelative_WSL() const 85 bool IsRelative_WSL() const
86 { 86 {
@@ -141,17 +141,19 @@ public:
141 141
142public: 142public:
143 bool PreserveATime; 143 bool PreserveATime;
144 #ifdef SUPPORT_DEVICE_FILE 144 #ifdef Z7_DEVICE_FILE
145 bool IsDeviceFile; 145 bool IsDeviceFile;
146 bool SizeDefined; 146 bool SizeDefined;
147 UInt64 Size; // it can be larger than real available size 147 UInt64 Size; // it can be larger than real available size
148 #endif 148 #endif
149 149
150 CFileBase(): _handle(INVALID_HANDLE_VALUE), PreserveATime(false) {}; 150 CFileBase(): _handle(INVALID_HANDLE_VALUE), PreserveATime(false) {}
151 ~CFileBase() { Close(); } 151 ~CFileBase() { Close(); }
152 152
153 HANDLE GetHandle() const { return _handle; } 153 HANDLE GetHandle() const { return _handle; }
154 154
155 // void Detach() { _handle = INVALID_HANDLE_VALUE; }
156
155 bool Close() throw(); 157 bool Close() throw();
156 158
157 bool GetPosition(UInt64 &position) const throw(); 159 bool GetPosition(UInt64 &position) const throw();
@@ -193,7 +195,7 @@ struct my_DISK_GEOMETRY_EX
193 195
194class CInFile: public CFileBase 196class CInFile: public CFileBase
195{ 197{
196 #ifdef SUPPORT_DEVICE_FILE 198 #ifdef Z7_DEVICE_FILE
197 199
198 #ifndef UNDER_CE 200 #ifndef UNDER_CE
199 201
@@ -232,6 +234,14 @@ public:
232 // we must use (FILE_FLAG_BACKUP_SEMANTICS) to open handle of directory. 234 // we must use (FILE_FLAG_BACKUP_SEMANTICS) to open handle of directory.
233 } 235 }
234 236
237 bool Open_for_FileRenameInformation(CFSTR fileName)
238 {
239 return Create(fileName, DELETE | SYNCHRONIZE | GENERIC_READ,
240 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
241 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
242 // we must use (FILE_FLAG_BACKUP_SEMANTICS) to open handle of directory.
243 }
244
235 bool OpenReparse(CFSTR fileName) 245 bool OpenReparse(CFSTR fileName)
236 { 246 {
237 // 17.02 fix: to support Windows XP compatibility junctions: 247 // 17.02 fix: to support Windows XP compatibility junctions:
@@ -295,12 +305,13 @@ protected:
295 UInt64 Size; // it can be larger than real available size 305 UInt64 Size; // it can be larger than real available size
296 */ 306 */
297 307
298 bool OpenBinary(const char *name, int flags); 308 bool OpenBinary(const char *name, int flags, mode_t mode = 0666);
299public: 309public:
300 bool PreserveATime; 310 bool PreserveATime;
301 311
302 CFileBase(): _handle(-1), PreserveATime(false) {}; 312 CFileBase(): _handle(-1), PreserveATime(false) {}
303 ~CFileBase() { Close(); } 313 ~CFileBase() { Close(); }
314 // void Detach() { _handle = -1; }
304 bool Close(); 315 bool Close();
305 bool GetLength(UInt64 &length) const; 316 bool GetLength(UInt64 &length) const;
306 off_t seek(off_t distanceToMove, int moveMethod) const; 317 off_t seek(off_t distanceToMove, int moveMethod) const;
@@ -330,7 +341,6 @@ class COutFile: public CFileBase
330 bool CTime_defined; 341 bool CTime_defined;
331 bool ATime_defined; 342 bool ATime_defined;
332 bool MTime_defined; 343 bool MTime_defined;
333
334 CFiTime CTime; 344 CFiTime CTime;
335 CFiTime ATime; 345 CFiTime ATime;
336 CFiTime MTime; 346 CFiTime MTime;
@@ -338,10 +348,13 @@ class COutFile: public CFileBase
338 AString Path; 348 AString Path;
339 ssize_t write_part(const void *data, size_t size) throw(); 349 ssize_t write_part(const void *data, size_t size) throw();
340public: 350public:
351 mode_t mode_for_Create;
352
341 COutFile(): 353 COutFile():
342 CTime_defined(false), 354 CTime_defined(false),
343 ATime_defined(false), 355 ATime_defined(false),
344 MTime_defined(false) 356 MTime_defined(false),
357 mode_for_Create(0666)
345 {} 358 {}
346 359
347 bool Close(); 360 bool Close();
diff --git a/CPP/Windows/FileLink.cpp b/CPP/Windows/FileLink.cpp
index 8ce634f..2b9fa1a 100644
--- a/CPP/Windows/FileLink.cpp
+++ b/CPP/Windows/FileLink.cpp
@@ -8,7 +8,7 @@
8#include <unistd.h> 8#include <unistd.h>
9#endif 9#endif
10 10
11#ifdef SUPPORT_DEVICE_FILE 11#ifdef Z7_DEVICE_FILE
12#include "../../C/Alloc.h" 12#include "../../C/Alloc.h"
13#endif 13#endif
14 14
@@ -20,6 +20,15 @@
20#include "FileIO.h" 20#include "FileIO.h"
21#include "FileName.h" 21#include "FileName.h"
22 22
23#ifdef Z7_OLD_WIN_SDK
24#ifndef ERROR_INVALID_REPARSE_DATA
25#define ERROR_INVALID_REPARSE_DATA 4392L
26#endif
27#ifndef ERROR_REPARSE_TAG_INVALID
28#define ERROR_REPARSE_TAG_INVALID 4393L
29#endif
30#endif
31
23#ifndef _UNICODE 32#ifndef _UNICODE
24extern bool g_IsNT; 33extern bool g_IsNT;
25#endif 34#endif
@@ -72,13 +81,13 @@ static const UInt32 kReparseFlags_Alias = (1 << 29);
72static const UInt32 kReparseFlags_HighLatency = (1 << 30); 81static const UInt32 kReparseFlags_HighLatency = (1 << 30);
73static const UInt32 kReparseFlags_Microsoft = ((UInt32)1 << 31); 82static const UInt32 kReparseFlags_Microsoft = ((UInt32)1 << 31);
74 83
75#define _my_IO_REPARSE_TAG_HSM (0xC0000004L) 84#define Z7_WIN_IO_REPARSE_TAG_HSM (0xC0000004L)
76#define _my_IO_REPARSE_TAG_HSM2 (0x80000006L) 85#define Z7_WIN_IO_REPARSE_TAG_HSM2 (0x80000006L)
77#define _my_IO_REPARSE_TAG_SIS (0x80000007L) 86#define Z7_WIN_IO_REPARSE_TAG_SIS (0x80000007L)
78#define _my_IO_REPARSE_TAG_WIM (0x80000008L) 87#define Z7_WIN_IO_REPARSE_TAG_WIM (0x80000008L)
79#define _my_IO_REPARSE_TAG_CSV (0x80000009L) 88#define Z7_WIN_IO_REPARSE_TAG_CSV (0x80000009L)
80#define _my_IO_REPARSE_TAG_DFS (0x8000000AL) 89#define Z7_WIN_IO_REPARSE_TAG_DFS (0x8000000AL)
81#define _my_IO_REPARSE_TAG_DFSR (0x80000012L) 90#define Z7_WIN_IO_REPARSE_TAG_DFSR (0x80000012L)
82*/ 91*/
83 92
84#define Get16(p) GetUi16(p) 93#define Get16(p) GetUi16(p)
@@ -112,7 +121,7 @@ static void WriteString(Byte *dest, const wchar_t *path)
112 wchar_t c = *path++; 121 wchar_t c = *path++;
113 if (c == 0) 122 if (c == 0)
114 return; 123 return;
115 Set16(dest, (UInt16)c); 124 Set16(dest, (UInt16)c)
116 dest += 2; 125 dest += 2;
117 } 126 }
118} 127}
@@ -133,10 +142,10 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i
133 return false; 142 return false;
134 dest.Alloc(8 + size); 143 dest.Alloc(8 + size);
135 Byte *p = dest; 144 Byte *p = dest;
136 Set32(p, _my_IO_REPARSE_TAG_LX_SYMLINK); 145 Set32(p, Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK)
137 Set16(p + 4, (UInt16)(size)); 146 Set16(p + 4, (UInt16)(size))
138 Set16(p + 6, 0); 147 Set16(p + 6, 0)
139 Set32(p + 8, _my_LX_SYMLINK_FLAG); 148 Set32(p + 8, Z7_WIN_LX_SYMLINK_FLAG)
140 memcpy(p + 12, utf.Ptr(), utf.Len()); 149 memcpy(p + 12, utf.Ptr(), utf.Len());
141 return true; 150 return true;
142 } 151 }
@@ -176,12 +185,12 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i
176 dest.Alloc(size); 185 dest.Alloc(size);
177 memset(dest, 0, size); 186 memset(dest, 0, size);
178 const UInt32 tag = isSymLink ? 187 const UInt32 tag = isSymLink ?
179 _my_IO_REPARSE_TAG_SYMLINK : 188 Z7_WIN_IO_REPARSE_TAG_SYMLINK :
180 _my_IO_REPARSE_TAG_MOUNT_POINT; 189 Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT;
181 Byte *p = dest; 190 Byte *p = dest;
182 Set32(p, tag); 191 Set32(p, tag)
183 Set16(p + 4, (UInt16)(size - 8)); 192 Set16(p + 4, (UInt16)(size - 8))
184 Set16(p + 6, 0); 193 Set16(p + 6, 0)
185 p += 8; 194 p += 8;
186 195
187 unsigned subOffs = 0; 196 unsigned subOffs = 0;
@@ -191,16 +200,16 @@ bool FillLinkData(CByteBuffer &dest, const wchar_t *path, bool isSymLink, bool i
191 else 200 else
192 printOffs = (unsigned)len1 + 2; 201 printOffs = (unsigned)len1 + 2;
193 202
194 Set16(p + 0, (UInt16)subOffs); 203 Set16(p + 0, (UInt16)subOffs)
195 Set16(p + 2, (UInt16)len1); 204 Set16(p + 2, (UInt16)len1)
196 Set16(p + 4, (UInt16)printOffs); 205 Set16(p + 4, (UInt16)printOffs)
197 Set16(p + 6, (UInt16)len2); 206 Set16(p + 6, (UInt16)len2)
198 207
199 p += 8; 208 p += 8;
200 if (isSymLink) 209 if (isSymLink)
201 { 210 {
202 UInt32 flags = isAbs ? 0 : _my_SYMLINK_FLAG_RELATIVE; 211 UInt32 flags = isAbs ? 0 : Z7_WIN_SYMLINK_FLAG_RELATIVE;
203 Set32(p, flags); 212 Set32(p, flags)
204 p += 4; 213 p += 4;
205 } 214 }
206 215
@@ -255,9 +264,9 @@ bool CReparseAttr::Parse(const Byte *p, size_t size)
255 264
256 HeaderError = false; 265 HeaderError = false;
257 266
258 if ( Tag != _my_IO_REPARSE_TAG_MOUNT_POINT 267 if ( Tag != Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT
259 && Tag != _my_IO_REPARSE_TAG_SYMLINK 268 && Tag != Z7_WIN_IO_REPARSE_TAG_SYMLINK
260 && Tag != _my_IO_REPARSE_TAG_LX_SYMLINK) 269 && Tag != Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK)
261 { 270 {
262 // for unsupported reparse points 271 // for unsupported reparse points
263 ErrorCode = (DWORD)ERROR_REPARSE_TAG_INVALID; // ERROR_REPARSE_TAG_MISMATCH 272 ErrorCode = (DWORD)ERROR_REPARSE_TAG_INVALID; // ERROR_REPARSE_TAG_MISMATCH
@@ -270,12 +279,12 @@ bool CReparseAttr::Parse(const Byte *p, size_t size)
270 p += 8; 279 p += 8;
271 size -= 8; 280 size -= 8;
272 281
273 if (Tag == _my_IO_REPARSE_TAG_LX_SYMLINK) 282 if (Tag == Z7_WIN_IO_REPARSE_TAG_LX_SYMLINK)
274 { 283 {
275 if (len < 4) 284 if (len < 4)
276 return false; 285 return false;
277 Flags = Get32(p); // maybe it's not Flags 286 Flags = Get32(p); // maybe it's not Flags
278 if (Flags != _my_LX_SYMLINK_FLAG) 287 if (Flags != Z7_WIN_LX_SYMLINK_FLAG)
279 return false; 288 return false;
280 len -= 4; 289 len -= 4;
281 p += 4; 290 p += 4;
@@ -304,7 +313,7 @@ bool CReparseAttr::Parse(const Byte *p, size_t size)
304 p += 8; 313 p += 8;
305 314
306 Flags = 0; 315 Flags = 0;
307 if (Tag == _my_IO_REPARSE_TAG_SYMLINK) 316 if (Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK)
308 { 317 {
309 if (len < 4) 318 if (len < 4)
310 return false; 319 return false;
@@ -341,8 +350,8 @@ bool CReparseShortInfo::Parse(const Byte *p, size_t size)
341 (type & kReparseFlags_Microsoft) == 0 || 350 (type & kReparseFlags_Microsoft) == 0 ||
342 (type & 0xFFFF) != 3) 351 (type & 0xFFFF) != 3)
343 */ 352 */
344 if (Tag != _my_IO_REPARSE_TAG_MOUNT_POINT && 353 if (Tag != Z7_WIN_IO_REPARSE_TAG_MOUNT_POINT &&
345 Tag != _my_IO_REPARSE_TAG_SYMLINK) 354 Tag != Z7_WIN_IO_REPARSE_TAG_SYMLINK)
346 // return true; 355 // return true;
347 return false; 356 return false;
348 357
@@ -365,7 +374,7 @@ bool CReparseShortInfo::Parse(const Byte *p, size_t size)
365 p += 8; 374 p += 8;
366 375
367 // UInt32 Flags = 0; 376 // UInt32 Flags = 0;
368 if (Tag == _my_IO_REPARSE_TAG_SYMLINK) 377 if (Tag == Z7_WIN_IO_REPARSE_TAG_SYMLINK)
369 { 378 {
370 if (len < 4) 379 if (len < 4)
371 return false; 380 return false;
@@ -426,13 +435,13 @@ UString CReparseAttr::GetPath() const
426 return s; 435 return s;
427} 436}
428 437
429#ifdef SUPPORT_DEVICE_FILE 438#ifdef Z7_DEVICE_FILE
430 439
431namespace NSystem 440namespace NSystem
432{ 441{
433bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize); 442bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize, UInt64 &freeSize);
434} 443}
435#endif // SUPPORT_DEVICE_FILE 444#endif // Z7_DEVICE_FILE
436 445
437#if defined(_WIN32) && !defined(UNDER_CE) 446#if defined(_WIN32) && !defined(UNDER_CE)
438 447
diff --git a/CPP/Windows/FileMapping.h b/CPP/Windows/FileMapping.h
index f90c429..caa7ea3 100644
--- a/CPP/Windows/FileMapping.h
+++ b/CPP/Windows/FileMapping.h
@@ -1,7 +1,7 @@
1// Windows/FileMapping.h 1// Windows/FileMapping.h
2 2
3#ifndef __WINDOWS_FILEMAPPING_H 3#ifndef ZIP7_INC_WINDOWS_FILE_MAPPING_H
4#define __WINDOWS_FILEMAPPING_H 4#define ZIP7_INC_WINDOWS_FILE_MAPPING_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7 7
@@ -34,7 +34,7 @@ public:
34 return res; 34 return res;
35 #else 35 #else
36 _handle = ::OpenFileMapping(desiredAccess, FALSE, name); 36 _handle = ::OpenFileMapping(desiredAccess, FALSE, name);
37 if (_handle != 0) 37 if (_handle != NULL)
38 return 0; 38 return 0;
39 return ::GetLastError(); 39 return ::GetLastError();
40 #endif 40 #endif
diff --git a/CPP/Windows/FileName.cpp b/CPP/Windows/FileName.cpp
index d61ff7e..c9c4f8b 100644
--- a/CPP/Windows/FileName.cpp
+++ b/CPP/Windows/FileName.cpp
@@ -6,9 +6,9 @@
6#include <limits.h> 6#include <limits.h>
7#include <unistd.h> 7#include <unistd.h>
8#include "../Common/StringConvert.h" 8#include "../Common/StringConvert.h"
9#include "FileDir.h"
10#endif 9#endif
11 10
11#include "FileDir.h"
12#include "FileName.h" 12#include "FileName.h"
13 13
14#ifndef _UNICODE 14#ifndef _UNICODE
@@ -68,7 +68,7 @@ void NormalizeDirPathPrefix(UString &dirPath)
68#ifdef _WIN32 68#ifdef _WIN32
69 69
70#ifndef USE_UNICODE_FSTRING 70#ifndef USE_UNICODE_FSTRING
71#ifdef WIN_LONG_PATH 71#ifdef Z7_LONG_PATH
72static void NormalizeDirSeparators(UString &s) 72static void NormalizeDirSeparators(UString &s)
73{ 73{
74 const unsigned len = s.Len(); 74 const unsigned len = s.Len();
@@ -90,7 +90,7 @@ void NormalizeDirSeparators(FString &s)
90#endif 90#endif
91 91
92 92
93#define IS_LETTER_CHAR(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) 93#define IS_LETTER_CHAR(c) ((((unsigned)(int)(c) | 0x20) - (unsigned)'a' <= (unsigned)('z' - 'a')))
94 94
95bool IsDrivePath(const wchar_t *s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':' && IS_SEPAR(s[2]); } 95bool IsDrivePath(const wchar_t *s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':' && IS_SEPAR(s[2]); }
96 96
@@ -120,7 +120,7 @@ bool IsAltPathPrefix(CFSTR s) throw()
120#if defined(_WIN32) && !defined(UNDER_CE) 120#if defined(_WIN32) && !defined(UNDER_CE)
121 121
122const char * const kSuperPathPrefix = "\\\\?\\"; 122const char * const kSuperPathPrefix = "\\\\?\\";
123#ifdef WIN_LONG_PATH 123#ifdef Z7_LONG_PATH
124static const char * const kSuperUncPrefix = "\\\\?\\UNC\\"; 124static const char * const kSuperUncPrefix = "\\\\?\\UNC\\";
125#endif 125#endif
126 126
@@ -191,7 +191,7 @@ unsigned GetNetworkServerPrefixSize(CFSTR s) throw()
191 if (c == '.' || c == '?') 191 if (c == '.' || c == '?')
192 return 0; 192 return 0;
193 } 193 }
194 int pos = FindSepar(s + prefixSize); 194 const int pos = FindSepar(s + prefixSize);
195 if (pos < 0) 195 if (pos < 0)
196 return 0; 196 return 0;
197 return prefixSize + (unsigned)(pos + 1); 197 return prefixSize + (unsigned)(pos + 1);
@@ -199,11 +199,11 @@ unsigned GetNetworkServerPrefixSize(CFSTR s) throw()
199 199
200bool IsNetworkShareRootPath(CFSTR s) throw() 200bool IsNetworkShareRootPath(CFSTR s) throw()
201{ 201{
202 unsigned prefixSize = GetNetworkServerPrefixSize(s); 202 const unsigned prefixSize = GetNetworkServerPrefixSize(s);
203 if (prefixSize == 0) 203 if (prefixSize == 0)
204 return false; 204 return false;
205 s += prefixSize; 205 s += prefixSize;
206 int pos = FindSepar(s); 206 const int pos = FindSepar(s);
207 if (pos < 0) 207 if (pos < 0)
208 return true; 208 return true;
209 return s[(unsigned)pos + 1] == 0; 209 return s[(unsigned)pos + 1] == 0;
@@ -217,6 +217,37 @@ bool IsSuperPath(const wchar_t *s) throw() { return IS_SUPER_PREFIX(s); }
217bool IsSuperOrDevicePath(const wchar_t *s) throw() { return IS_SUPER_OR_DEVICE_PATH(s); } 217bool IsSuperOrDevicePath(const wchar_t *s) throw() { return IS_SUPER_OR_DEVICE_PATH(s); }
218// bool IsSuperUncPath(const wchar_t *s) throw() { return (IS_SUPER_PREFIX(s) && IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize)); } 218// bool IsSuperUncPath(const wchar_t *s) throw() { return (IS_SUPER_PREFIX(s) && IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize)); }
219 219
220bool IsAltStreamPrefixWithColon(const UString &s) throw()
221{
222 if (s.IsEmpty())
223 return false;
224 if (s.Back() != ':')
225 return false;
226 unsigned pos = 0;
227 if (IsSuperPath(s))
228 pos = kSuperPathPrefixSize;
229 if (s.Len() - pos == 2 && IsDrivePath2(s.Ptr(pos)))
230 return false;
231 return true;
232}
233
234bool If_IsSuperPath_RemoveSuperPrefix(UString &s)
235{
236 if (!IsSuperPath(s))
237 return false;
238 unsigned start = 0;
239 unsigned count = kSuperPathPrefixSize;
240 const wchar_t *s2 = s.Ptr(kSuperPathPrefixSize);
241 if (IS_UNC_WITH_SLASH(s2))
242 {
243 start = 2;
244 count = kSuperUncPathPrefixSize - 2;
245 }
246 s.Delete(start, count);
247 return true;
248}
249
250
220#ifndef USE_UNICODE_FSTRING 251#ifndef USE_UNICODE_FSTRING
221bool IsDrivePath2(CFSTR s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':'; } 252bool IsDrivePath2(CFSTR s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':'; }
222// bool IsDriveName2(CFSTR s) throw() { return IS_LETTER_CHAR(s[0]) && s[1] == ':' && s[2] == 0; } 253// 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)
288 return 0; 319 return 0;
289 if (s[1] == 0 || !IS_SEPAR(s[1])) 320 if (s[1] == 0 || !IS_SEPAR(s[1]))
290 return 1; 321 return 1;
291 unsigned size = GetRootPrefixSize_Of_NetworkPath(s + 2); 322 const unsigned size = GetRootPrefixSize_Of_NetworkPath(s + 2);
292 return (size == 0) ? 0 : 2 + size; 323 return (size == 0) ? 0 : 2 + size;
293} 324}
294 325
@@ -296,11 +327,11 @@ static unsigned GetRootPrefixSize_Of_SuperPath(CFSTR s)
296{ 327{
297 if (IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize)) 328 if (IS_UNC_WITH_SLASH(s + kSuperPathPrefixSize))
298 { 329 {
299 unsigned size = GetRootPrefixSize_Of_NetworkPath(s + kSuperUncPathPrefixSize); 330 const unsigned size = GetRootPrefixSize_Of_NetworkPath(s + kSuperUncPathPrefixSize);
300 return (size == 0) ? 0 : kSuperUncPathPrefixSize + size; 331 return (size == 0) ? 0 : kSuperUncPathPrefixSize + size;
301 } 332 }
302 // we support \\?\c:\ paths and volume GUID paths \\?\Volume{GUID}\" 333 // we support \\?\c:\ paths and volume GUID paths \\?\Volume{GUID}\"
303 int pos = FindSepar(s + kSuperPathPrefixSize); 334 const int pos = FindSepar(s + kSuperPathPrefixSize);
304 if (pos < 0) 335 if (pos < 0)
305 return 0; 336 return 0;
306 return kSuperPathPrefixSize + pos + 1; 337 return kSuperPathPrefixSize + pos + 1;
@@ -379,42 +410,26 @@ unsigned GetRootPrefixSize(const wchar_t *s) throw() { return IS_SEPAR(s[0]) ? 1
379 410
380#ifndef UNDER_CE 411#ifndef UNDER_CE
381 412
382static bool GetCurDir(UString &path)
383{
384 path.Empty();
385 413
386 #ifdef _WIN32 414#ifdef USE_UNICODE_FSTRING
387 415
388 DWORD needLength; 416#define GetCurDir NDir::GetCurrentDir
389 #ifndef _UNICODE
390 if (!g_IsNT)
391 {
392 TCHAR s[MAX_PATH + 2];
393 s[0] = 0;
394 needLength = ::GetCurrentDirectory(MAX_PATH + 1, s);
395 path = fs2us(fas2fs(s));
396 }
397 else
398 #endif
399 {
400 WCHAR s[MAX_PATH + 2];
401 s[0] = 0;
402 needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, s);
403 path = s;
404 }
405 return (needLength > 0 && needLength <= MAX_PATH);
406 417
407 #else 418#else
408 419
420static bool GetCurDir(UString &path)
421{
422 path.Empty();
409 FString s; 423 FString s;
410 if (!NDir::GetCurrentDir(s)) 424 if (!NDir::GetCurrentDir(s))
411 return false; 425 return false;
412 path = GetUnicodeString(s); 426 path = fs2us(s);
413 return true; 427 return true;
414
415 #endif
416} 428}
417 429
430#endif
431
432
418static bool ResolveDotsFolders(UString &s) 433static bool ResolveDotsFolders(UString &s)
419{ 434{
420 #ifdef _WIN32 435 #ifdef _WIN32
@@ -516,7 +531,7 @@ static bool AreThereDotsFolders(CFSTR s)
516#endif 531#endif
517#endif // LONG_PATH_DOTS_FOLDERS_PARSING 532#endif // LONG_PATH_DOTS_FOLDERS_PARSING
518 533
519#ifdef WIN_LONG_PATH 534#ifdef Z7_LONG_PATH
520 535
521/* 536/*
522Most of Windows versions have problems, if some file or dir name 537Most of Windows versions have problems, if some file or dir name
@@ -610,11 +625,11 @@ static bool GetSuperPathBase(CFSTR s, UString &res)
610 return true; 625 return true;
611 626
612 UString temp = fs2us(s); 627 UString temp = fs2us(s);
613 unsigned fixedSize = GetRootPrefixSize_Of_SuperPath(temp); 628 const unsigned fixedSize = GetRootPrefixSize_Of_SuperPath(temp);
614 if (fixedSize == 0) 629 if (fixedSize == 0)
615 return true; 630 return true;
616 631
617 UString rem = &temp[fixedSize]; 632 UString rem = temp.Ptr(fixedSize);
618 if (!ResolveDotsFolders(rem)) 633 if (!ResolveDotsFolders(rem))
619 return true; 634 return true;
620 635
@@ -632,13 +647,13 @@ static bool GetSuperPathBase(CFSTR s, UString &res)
632 if (IS_SEPAR(s[1])) 647 if (IS_SEPAR(s[1]))
633 { 648 {
634 UString temp = fs2us(s + 2); 649 UString temp = fs2us(s + 2);
635 unsigned fixedSize = GetRootPrefixSize_Of_NetworkPath(temp); 650 const unsigned fixedSize = GetRootPrefixSize_Of_NetworkPath(temp);
636 // we ignore that error to allow short network paths server\share? 651 // we ignore that error to allow short network paths server\share?
637 /* 652 /*
638 if (fixedSize == 0) 653 if (fixedSize == 0)
639 return false; 654 return false;
640 */ 655 */
641 UString rem = &temp[fixedSize]; 656 UString rem = temp.Ptr(fixedSize);
642 if (!ResolveDotsFolders(rem)) 657 if (!ResolveDotsFolders(rem))
643 return false; 658 return false;
644 res += kSuperUncPrefix; 659 res += kSuperUncPrefix;
@@ -783,7 +798,7 @@ bool GetSuperPath(CFSTR path, UString &superPath)
783 return false; 798 return false;
784} 799}
785*/ 800*/
786#endif // WIN_LONG_PATH 801#endif // Z7_LONG_PATH
787 802
788bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res) 803bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res)
789{ 804{
@@ -801,8 +816,11 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res)
801 816
802 #else 817 #else
803 818
804 unsigned prefixSize = GetRootPrefixSize(s); 819 const unsigned prefixSize = GetRootPrefixSize(s);
805 if (prefixSize != 0) 820 if (prefixSize != 0)
821#ifdef _WIN32
822 if (prefixSize != 1)
823#endif
806 { 824 {
807 if (!AreThereDotsFolders(s + prefixSize)) 825 if (!AreThereDotsFolders(s + prefixSize))
808 return true; 826 return true;
@@ -815,21 +833,9 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res)
815 return true; 833 return true;
816 } 834 }
817 835
818 /*
819 FChar c = s[0];
820 if (c == 0)
821 return true;
822 if (c == '.' && (s[1] == 0 || (s[1] == '.' && s[2] == 0)))
823 return true;
824 if (IS_SEPAR(c) && IS_SEPAR(s[1]))
825 return true;
826 if (IsDrivePath(s))
827 return true;
828 */
829
830 UString curDir; 836 UString curDir;
831 if (dirPrefix) 837 if (dirPrefix && prefixSize == 0)
832 curDir = fs2us(dirPrefix); 838 curDir = fs2us(dirPrefix); // we use (dirPrefix), only if (s) path is relative
833 else 839 else
834 { 840 {
835 if (!GetCurDir(curDir)) 841 if (!GetCurDir(curDir))
@@ -837,46 +843,40 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res)
837 } 843 }
838 NormalizeDirPathPrefix(curDir); 844 NormalizeDirPathPrefix(curDir);
839 845
840 unsigned fixedSize = 0; 846 unsigned fixedSize = GetRootPrefixSize(curDir);
841 847
842 #ifdef _WIN32 848 UString temp;
843 849#ifdef _WIN32
844 if (IsSuperPath(curDir)) 850 if (prefixSize != 0)
845 { 851 {
846 fixedSize = GetRootPrefixSize_Of_SuperPath(curDir); 852 /* (s) is absolute path, but only (prefixSize == 1) is possible here.
853 So for full resolving we need root of current folder and
854 relative part of (s). */
855 s += prefixSize;
856 // (s) is relative part now
847 if (fixedSize == 0) 857 if (fixedSize == 0)
848 return false;
849 }
850 else
851 {
852 if (IsDrivePath(curDir))
853 fixedSize = kDrivePrefixSize;
854 else
855 { 858 {
856 if (!IsPathSepar(curDir[0]) || !IsPathSepar(curDir[1])) 859 // (curDir) is not absolute.
857 return false; 860 // That case is unexpected, but we support it too.
858 fixedSize = GetRootPrefixSize_Of_NetworkPath(curDir.Ptr(2)); 861 curDir.Empty();
859 if (fixedSize == 0) 862 curDir.Add_PathSepar();
860 return false; 863 fixedSize = 1;
861 fixedSize += 2; 864 // (curDir) now is just Separ character.
865 // So final (res) path later also will have Separ prefix.
862 } 866 }
863 } 867 }
864
865 #endif // _WIN32
866
867 UString temp;
868 if (IS_SEPAR(s[0]))
869 {
870 temp = fs2us(s + 1);
871 }
872 else 868 else
869#endif // _WIN32
873 { 870 {
874 temp += curDir.Ptr(fixedSize); 871 // (s) is relative path
875 temp += fs2us(s); 872 temp = curDir.Ptr(fixedSize);
873 // (temp) is relative_part_of(curDir)
876 } 874 }
875 temp += fs2us(s);
877 if (!ResolveDotsFolders(temp)) 876 if (!ResolveDotsFolders(temp))
878 return false; 877 return false;
879 curDir.DeleteFrom(fixedSize); 878 curDir.DeleteFrom(fixedSize);
879 // (curDir) now contains only absolute prefix part
880 res = us2fs(curDir); 880 res = us2fs(curDir);
881 res += us2fs(temp); 881 res += us2fs(temp);
882 882
@@ -885,6 +885,7 @@ bool GetFullPath(CFSTR dirPrefix, CFSTR s, FString &res)
885 return true; 885 return true;
886} 886}
887 887
888
888bool GetFullPath(CFSTR path, FString &fullPath) 889bool GetFullPath(CFSTR path, FString &fullPath)
889{ 890{
890 return GetFullPath(NULL, path, fullPath); 891 return GetFullPath(NULL, path, fullPath);
diff --git a/CPP/Windows/FileName.h b/CPP/Windows/FileName.h
index de8bd13..219b656 100644
--- a/CPP/Windows/FileName.h
+++ b/CPP/Windows/FileName.h
@@ -1,7 +1,7 @@
1// Windows/FileName.h 1// Windows/FileName.h
2 2
3#ifndef __WINDOWS_FILE_NAME_H 3#ifndef ZIP7_INC_WINDOWS_FILE_NAME_H
4#define __WINDOWS_FILE_NAME_H 4#define ZIP7_INC_WINDOWS_FILE_NAME_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
@@ -54,6 +54,10 @@ bool IsDrivePath2(const wchar_t *s) throw(); // first 2 chars are drive chars li
54bool IsSuperPath(const wchar_t *s) throw(); 54bool IsSuperPath(const wchar_t *s) throw();
55bool IsSuperOrDevicePath(const wchar_t *s) throw(); 55bool IsSuperOrDevicePath(const wchar_t *s) throw();
56 56
57bool IsAltStreamPrefixWithColon(const UString &s) throw();
58// returns true, if super prefix was removed
59bool If_IsSuperPath_RemoveSuperPrefix(UString &s);
60
57#ifndef USE_UNICODE_FSTRING 61#ifndef USE_UNICODE_FSTRING
58bool IsDrivePath2(CFSTR s) throw(); // first 2 chars are drive chars like "a:" 62bool IsDrivePath2(CFSTR s) throw(); // first 2 chars are drive chars like "a:"
59// bool IsDriveName2(CFSTR s) throw(); // is drive name like "a:" 63// bool IsDriveName2(CFSTR s) throw(); // is drive name like "a:"
@@ -82,7 +86,7 @@ int FindAltStreamColon(CFSTR path) throw();
82bool IsAbsolutePath(const wchar_t *s) throw(); 86bool IsAbsolutePath(const wchar_t *s) throw();
83unsigned GetRootPrefixSize(const wchar_t *s) throw(); 87unsigned GetRootPrefixSize(const wchar_t *s) throw();
84 88
85#ifdef WIN_LONG_PATH 89#ifdef Z7_LONG_PATH
86 90
87const int kSuperPathType_UseOnlyMain = 0; 91const int kSuperPathType_UseOnlyMain = 0;
88const int kSuperPathType_UseOnlySuper = 1; 92const int kSuperPathType_UseOnlySuper = 1;
@@ -92,16 +96,16 @@ int GetUseSuperPathType(CFSTR s) throw();
92bool GetSuperPath(CFSTR path, UString &superPath, bool onlyIfNew); 96bool GetSuperPath(CFSTR path, UString &superPath, bool onlyIfNew);
93bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew); 97bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew);
94 98
95#define USE_MAIN_PATH (__useSuperPathType != kSuperPathType_UseOnlySuper) 99#define USE_MAIN_PATH (_useSuperPathType != kSuperPathType_UseOnlySuper)
96#define USE_MAIN_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlySuper && __useSuperPathType2 != kSuperPathType_UseOnlySuper) 100#define USE_MAIN_PATH_2 (_useSuperPathType1 != kSuperPathType_UseOnlySuper && _useSuperPathType2 != kSuperPathType_UseOnlySuper)
97 101
98#define USE_SUPER_PATH (__useSuperPathType != kSuperPathType_UseOnlyMain) 102#define USE_SUPER_PATH (_useSuperPathType != kSuperPathType_UseOnlyMain)
99#define USE_SUPER_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlyMain || __useSuperPathType2 != kSuperPathType_UseOnlyMain) 103#define USE_SUPER_PATH_2 (_useSuperPathType1 != kSuperPathType_UseOnlyMain || _useSuperPathType2 != kSuperPathType_UseOnlyMain)
100 104
101#define IF_USE_MAIN_PATH int __useSuperPathType = GetUseSuperPathType(path); if (USE_MAIN_PATH) 105#define IF_USE_MAIN_PATH int _useSuperPathType = GetUseSuperPathType(path); if (USE_MAIN_PATH)
102#define IF_USE_MAIN_PATH_2(x1, x2) \ 106#define IF_USE_MAIN_PATH_2(x1, x2) \
103 int __useSuperPathType1 = GetUseSuperPathType(x1); \ 107 int _useSuperPathType1 = GetUseSuperPathType(x1); \
104 int __useSuperPathType2 = GetUseSuperPathType(x2); \ 108 int _useSuperPathType2 = GetUseSuperPathType(x2); \
105 if (USE_MAIN_PATH_2) 109 if (USE_MAIN_PATH_2)
106 110
107#else 111#else
@@ -109,8 +113,18 @@ bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew)
109#define IF_USE_MAIN_PATH 113#define IF_USE_MAIN_PATH
110#define IF_USE_MAIN_PATH_2(x1, x2) 114#define IF_USE_MAIN_PATH_2(x1, x2)
111 115
112#endif // WIN_LONG_PATH 116#endif // Z7_LONG_PATH
113 117
118/*
119 if (dirPrefix != NULL && (path) is relative)
120 {
121 (dirPrefix) will be used
122 result (fullPath) will contain prefix part of (dirPrefix).
123 }
124 Current_Dir path can be used in 2 cases:
125 1) if (path) is relative && dirPrefix == NULL
126 2) for _WIN32: if (path) is absolute starting wuth "\"
127*/
114bool GetFullPath(CFSTR dirPrefix, CFSTR path, FString &fullPath); 128bool GetFullPath(CFSTR dirPrefix, CFSTR path, FString &fullPath);
115bool GetFullPath(CFSTR path, FString &fullPath); 129bool GetFullPath(CFSTR path, FString &fullPath);
116 130
diff --git a/CPP/Windows/FileSystem.cpp b/CPP/Windows/FileSystem.cpp
index 6259453..6a262d9 100644
--- a/CPP/Windows/FileSystem.cpp
+++ b/CPP/Windows/FileSystem.cpp
@@ -71,14 +71,14 @@ UINT MyGetDriveType(CFSTR pathName)
71 } 71 }
72} 72}
73 73
74typedef BOOL (WINAPI * GetDiskFreeSpaceExA_Pointer)( 74typedef BOOL (WINAPI * Func_GetDiskFreeSpaceExA)(
75 LPCSTR lpDirectoryName, // directory name 75 LPCSTR lpDirectoryName, // directory name
76 PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller 76 PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller
77 PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk 77 PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk
78 PULARGE_INTEGER lpTotalNumberOfFreeBytes // free bytes on disk 78 PULARGE_INTEGER lpTotalNumberOfFreeBytes // free bytes on disk
79); 79);
80 80
81typedef BOOL (WINAPI * GetDiskFreeSpaceExW_Pointer)( 81typedef BOOL (WINAPI * Func_GetDiskFreeSpaceExW)(
82 LPCWSTR lpDirectoryName, // directory name 82 LPCWSTR lpDirectoryName, // directory name
83 PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller 83 PULARGE_INTEGER lpFreeBytesAvailable, // bytes available to caller
84 PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk 84 PULARGE_INTEGER lpTotalNumberOfBytes, // bytes on disk
@@ -92,12 +92,14 @@ bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize,
92 #ifndef _UNICODE 92 #ifndef _UNICODE
93 if (!g_IsNT) 93 if (!g_IsNT)
94 { 94 {
95 GetDiskFreeSpaceExA_Pointer pGetDiskFreeSpaceEx = (GetDiskFreeSpaceExA_Pointer)(void *)GetProcAddress( 95 const
96 GetModuleHandle(TEXT("kernel32.dll")), "GetDiskFreeSpaceExA"); 96 Func_GetDiskFreeSpaceExA f = Z7_GET_PROC_ADDRESS(
97 if (pGetDiskFreeSpaceEx) 97 Func_GetDiskFreeSpaceExA, GetModuleHandle(TEXT("kernel32.dll")),
98 "GetDiskFreeSpaceExA");
99 if (f)
98 { 100 {
99 ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2; 101 ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2;
100 sizeIsDetected = BOOLToBool(pGetDiskFreeSpaceEx(fs2fas(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); 102 sizeIsDetected = BOOLToBool(f(fs2fas(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2));
101 totalSize = totalSize2.QuadPart; 103 totalSize = totalSize2.QuadPart;
102 freeSize = freeSize2.QuadPart; 104 freeSize = freeSize2.QuadPart;
103 } 105 }
@@ -107,12 +109,14 @@ bool MyGetDiskFreeSpace(CFSTR rootPath, UInt64 &clusterSize, UInt64 &totalSize,
107 else 109 else
108 #endif 110 #endif
109 { 111 {
110 GetDiskFreeSpaceExW_Pointer pGetDiskFreeSpaceEx = (GetDiskFreeSpaceExW_Pointer)(void *)GetProcAddress( 112 const
111 GetModuleHandle(TEXT("kernel32.dll")), "GetDiskFreeSpaceExW"); 113 Func_GetDiskFreeSpaceExW f = Z7_GET_PROC_ADDRESS(
112 if (pGetDiskFreeSpaceEx) 114 Func_GetDiskFreeSpaceExW, GetModuleHandle(TEXT("kernel32.dll")),
115 "GetDiskFreeSpaceExW");
116 if (f)
113 { 117 {
114 ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2; 118 ULARGE_INTEGER freeBytesToCaller2, totalSize2, freeSize2;
115 sizeIsDetected = BOOLToBool(pGetDiskFreeSpaceEx(fs2us(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2)); 119 sizeIsDetected = BOOLToBool(f(fs2us(rootPath), &freeBytesToCaller2, &totalSize2, &freeSize2));
116 totalSize = totalSize2.QuadPart; 120 totalSize = totalSize2.QuadPart;
117 freeSize = freeSize2.QuadPart; 121 freeSize = freeSize2.QuadPart;
118 } 122 }
diff --git a/CPP/Windows/FileSystem.h b/CPP/Windows/FileSystem.h
index 9b49a02..9f9e399 100644
--- a/CPP/Windows/FileSystem.h
+++ b/CPP/Windows/FileSystem.h
@@ -1,7 +1,7 @@
1// Windows/FileSystem.h 1// Windows/FileSystem.h
2 2
3#ifndef __WINDOWS_FILE_SYSTEM_H 3#ifndef ZIP7_INC_WINDOWS_FILE_SYSTEM_H
4#define __WINDOWS_FILE_SYSTEM_H 4#define ZIP7_INC_WINDOWS_FILE_SYSTEM_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7#include "../Common/MyTypes.h" 7#include "../Common/MyTypes.h"
diff --git a/CPP/Windows/Handle.h b/CPP/Windows/Handle.h
index 5878c83..6ae09ec 100644
--- a/CPP/Windows/Handle.h
+++ b/CPP/Windows/Handle.h
@@ -1,9 +1,9 @@
1// Windows/Handle.h 1// Windows/Handle.h
2 2
3#ifndef __WINDOWS_HANDLE_H 3#ifndef ZIP7_INC_WINDOWS_HANDLE_H
4#define __WINDOWS_HANDLE_H 4#define ZIP7_INC_WINDOWS_HANDLE_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyWindows.h"
7 7
8namespace NWindows { 8namespace NWindows {
9 9
@@ -28,7 +28,7 @@ public:
28 void Attach(HANDLE handle) { _handle = handle; } 28 void Attach(HANDLE handle) { _handle = handle; }
29 HANDLE Detach() 29 HANDLE Detach()
30 { 30 {
31 HANDLE handle = _handle; 31 const HANDLE handle = _handle;
32 _handle = NULL; 32 _handle = NULL;
33 return handle; 33 return handle;
34 } 34 }
diff --git a/CPP/Windows/MemoryGlobal.h b/CPP/Windows/MemoryGlobal.h
index c217510..6852591 100644
--- a/CPP/Windows/MemoryGlobal.h
+++ b/CPP/Windows/MemoryGlobal.h
@@ -1,7 +1,7 @@
1// Windows/MemoryGlobal.h 1// Windows/MemoryGlobal.h
2 2
3#ifndef __WINDOWS_MEMORY_GLOBAL_H 3#ifndef ZIP7_INC_WINDOWS_MEMORY_GLOBAL_H
4#define __WINDOWS_MEMORY_GLOBAL_H 4#define ZIP7_INC_WINDOWS_MEMORY_GLOBAL_H
5 5
6#include "../Common/MyWindows.h" 6#include "../Common/MyWindows.h"
7 7
@@ -12,7 +12,7 @@ class CGlobal
12{ 12{
13 HGLOBAL _global; 13 HGLOBAL _global;
14public: 14public:
15 CGlobal(): _global(NULL){}; 15 CGlobal(): _global(NULL) {}
16 ~CGlobal() { Free(); } 16 ~CGlobal() { Free(); }
17 operator HGLOBAL() const { return _global; } 17 operator HGLOBAL() const { return _global; }
18 void Attach(HGLOBAL hGlobal) 18 void Attach(HGLOBAL hGlobal)
@@ -22,7 +22,7 @@ public:
22 } 22 }
23 HGLOBAL Detach() 23 HGLOBAL Detach()
24 { 24 {
25 HGLOBAL h = _global; 25 const HGLOBAL h = _global;
26 _global = NULL; 26 _global = NULL;
27 return h; 27 return h;
28 } 28 }
@@ -42,10 +42,10 @@ public:
42 CGlobalLock(HGLOBAL hGlobal): _global(hGlobal) 42 CGlobalLock(HGLOBAL hGlobal): _global(hGlobal)
43 { 43 {
44 _ptr = GlobalLock(hGlobal); 44 _ptr = GlobalLock(hGlobal);
45 }; 45 }
46 ~CGlobalLock() 46 ~CGlobalLock()
47 { 47 {
48 if (_ptr != NULL) 48 if (_ptr)
49 GlobalUnlock(_global); 49 GlobalUnlock(_global);
50 } 50 }
51}; 51};
diff --git a/CPP/Windows/MemoryLock.cpp b/CPP/Windows/MemoryLock.cpp
index 24866b1..0bd7504 100644
--- a/CPP/Windows/MemoryLock.cpp
+++ b/CPP/Windows/MemoryLock.cpp
@@ -21,7 +21,10 @@ typedef BOOL (WINAPI * Func_LookupPrivilegeValue)(LPCTSTR lpSystemName, LPCTSTR
21typedef BOOL (WINAPI * Func_AdjustTokenPrivileges)(HANDLE TokenHandle, BOOL DisableAllPrivileges, 21typedef BOOL (WINAPI * Func_AdjustTokenPrivileges)(HANDLE TokenHandle, BOOL DisableAllPrivileges,
22 PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); 22 PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength);
23} 23}
24#define GET_PROC_ADDR(fff, name) Func_ ## fff my_ ## fff = (Func_ ## fff) (void(*)()) GetProcAddress(hModule, name) 24
25#define GET_PROC_ADDR(fff, name) \
26 const Func_ ## fff my_ ## fff = Z7_GET_PROC_ADDRESS( \
27 Func_ ## fff, hModule, name);
25#endif 28#endif
26 29
27bool EnablePrivilege(LPCTSTR privilegeName, bool enable) 30bool EnablePrivilege(LPCTSTR privilegeName, bool enable)
@@ -30,13 +33,19 @@ bool EnablePrivilege(LPCTSTR privilegeName, bool enable)
30 33
31 #ifndef _UNICODE 34 #ifndef _UNICODE
32 35
33 HMODULE hModule = ::LoadLibrary(TEXT("Advapi32.dll")); 36 const HMODULE hModule = ::LoadLibrary(TEXT("advapi32.dll"));
34 if (hModule == NULL) 37 if (!hModule)
35 return false; 38 return false;
36 39
37 GET_PROC_ADDR(OpenProcessToken, "OpenProcessToken"); 40 GET_PROC_ADDR(
38 GET_PROC_ADDR(LookupPrivilegeValue, "LookupPrivilegeValueA"); 41 OpenProcessToken,
39 GET_PROC_ADDR(AdjustTokenPrivileges, "AdjustTokenPrivileges"); 42 "OpenProcessToken")
43 GET_PROC_ADDR(
44 LookupPrivilegeValue,
45 "LookupPrivilegeValueA")
46 GET_PROC_ADDR(
47 AdjustTokenPrivileges,
48 "AdjustTokenPrivileges")
40 49
41 if (my_OpenProcessToken && 50 if (my_OpenProcessToken &&
42 my_AdjustTokenPrivileges && 51 my_AdjustTokenPrivileges &&
@@ -85,10 +94,13 @@ typedef void (WINAPI * Func_RtlGetVersion) (OSVERSIONINFOEXW *);
85unsigned Get_LargePages_RiskLevel() 94unsigned Get_LargePages_RiskLevel()
86{ 95{
87 OSVERSIONINFOEXW vi; 96 OSVERSIONINFOEXW vi;
88 HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); 97 const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll");
89 if (!ntdll) 98 if (!ntdll)
90 return 0; 99 return 0;
91 Func_RtlGetVersion func = (Func_RtlGetVersion)(void *)GetProcAddress(ntdll, "RtlGetVersion"); 100 const
101 Func_RtlGetVersion func = Z7_GET_PROC_ADDRESS(
102 Func_RtlGetVersion, ntdll,
103 "RtlGetVersion");
92 if (!func) 104 if (!func)
93 return 0; 105 return 0;
94 func(&vi); 106 func(&vi);
diff --git a/CPP/Windows/MemoryLock.h b/CPP/Windows/MemoryLock.h
index dcaf182..2b85002 100644
--- a/CPP/Windows/MemoryLock.h
+++ b/CPP/Windows/MemoryLock.h
@@ -1,7 +1,7 @@
1// Windows/MemoryLock.h 1// Windows/MemoryLock.h
2 2
3#ifndef __WINDOWS_MEMORY_LOCK_H 3#ifndef ZIP7_INC_WINDOWS_MEMORY_LOCK_H
4#define __WINDOWS_MEMORY_LOCK_H 4#define ZIP7_INC_WINDOWS_MEMORY_LOCK_H
5 5
6#include "../Common/MyWindows.h" 6#include "../Common/MyWindows.h"
7 7
diff --git a/CPP/Windows/Menu.cpp b/CPP/Windows/Menu.cpp
index 3ad6953..af54c66 100644
--- a/CPP/Windows/Menu.cpp
+++ b/CPP/Windows/Menu.cpp
@@ -22,8 +22,23 @@ contain additional member:
22 HBITMAP hbmpItem; 22 HBITMAP hbmpItem;
23 #endif 23 #endif
24If we compile the source code with (WINVER >= 0x0500), some functions 24If we compile the source code with (WINVER >= 0x0500), some functions
25will not work at NT 4.0, if cbSize is set as sizeof(MENUITEMINFO*). 25will not work at NT4, if cbSize is set as sizeof(MENUITEMINFO).
26So we use size of old version of structure. */ 26So we use size of old version of structure in some conditions.
27Win98 probably supports full structure including hbmpItem.
28
29We have 2 ways to get/set string in menu item:
30win95/NT4: we must use MIIM_TYPE only.
31 MIIM_TYPE : Retrieves or sets the fType and dwTypeData members.
32win98/win2000: there are new flags that can be used instead of MIIM_TYPE:
33 MIIM_FTYPE : Retrieves or sets the fType member.
34 MIIM_STRING : Retrieves or sets the dwTypeData member.
35
36Windows versions probably support MIIM_TYPE flag, if we set MENUITEMINFO::cbSize
37as sizeof of old (small) MENUITEMINFO that doesn't include (hbmpItem) field.
38But do all Windows versions support old MIIM_TYPE flag, if we use
39MENUITEMINFO::cbSize as sizeof of new (big) MENUITEMINFO including (hbmpItem) field ?
40win10 probably supports any combination of small/big (cbSize) and old/new MIIM_TYPE/MIIM_STRING.
41*/
27 42
28#if defined(UNDER_CE) || defined(_WIN64) || (WINVER < 0x0500) 43#if defined(UNDER_CE) || defined(_WIN64) || (WINVER < 0x0500)
29 #ifndef _UNICODE 44 #ifndef _UNICODE
@@ -36,20 +51,31 @@ So we use size of old version of structure. */
36 #define my_compatib_MENUITEMINFOA_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOA, hbmpItem) 51 #define my_compatib_MENUITEMINFOA_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOA, hbmpItem)
37 #endif 52 #endif
38 #define my_compatib_MENUITEMINFOW_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOW, hbmpItem) 53 #define my_compatib_MENUITEMINFOW_size MY_STRUCT_SIZE_BEFORE(MENUITEMINFOW, hbmpItem)
54#if defined(__clang__) && __clang_major__ >= 13
55// error : performing pointer subtraction with a null pointer may have undefined behavior
56#pragma GCC diagnostic ignored "-Wnull-pointer-subtraction"
39#endif 57#endif
58#endif
59
60
61#define COPY_MENUITEM_field(d, s, name) \
62 d.name = s.name;
63
64#define COPY_MENUITEM_fields(d, s) \
65 COPY_MENUITEM_field(d, s, fMask) \
66 COPY_MENUITEM_field(d, s, fType) \
67 COPY_MENUITEM_field(d, s, fState) \
68 COPY_MENUITEM_field(d, s, wID) \
69 COPY_MENUITEM_field(d, s, hSubMenu) \
70 COPY_MENUITEM_field(d, s, hbmpChecked) \
71 COPY_MENUITEM_field(d, s, hbmpUnchecked) \
72 COPY_MENUITEM_field(d, s, dwItemData) \
40 73
41static void ConvertItemToSysForm(const CMenuItem &item, MENUITEMINFOW &si) 74static void ConvertItemToSysForm(const CMenuItem &item, MENUITEMINFOW &si)
42{ 75{
43 ZeroMemory(&si, sizeof(si)); 76 ZeroMemory(&si, sizeof(si));
44 si.cbSize = my_compatib_MENUITEMINFOW_size; // sizeof(si); 77 si.cbSize = my_compatib_MENUITEMINFOW_size; // sizeof(si);
45 si.fMask = item.fMask; 78 COPY_MENUITEM_fields(si, item)
46 si.fType = item.fType;
47 si.fState = item.fState;
48 si.wID = item.wID;
49 si.hSubMenu = item.hSubMenu;
50 si.hbmpChecked = item.hbmpChecked;
51 si.hbmpUnchecked = item.hbmpUnchecked;
52 si.dwItemData = item.dwItemData;
53} 79}
54 80
55#ifndef _UNICODE 81#ifndef _UNICODE
@@ -57,62 +83,63 @@ static void ConvertItemToSysForm(const CMenuItem &item, MENUITEMINFOA &si)
57{ 83{
58 ZeroMemory(&si, sizeof(si)); 84 ZeroMemory(&si, sizeof(si));
59 si.cbSize = my_compatib_MENUITEMINFOA_size; // sizeof(si); 85 si.cbSize = my_compatib_MENUITEMINFOA_size; // sizeof(si);
60 si.fMask = item.fMask; 86 COPY_MENUITEM_fields(si, item)
61 si.fType = item.fType;
62 si.fState = item.fState;
63 si.wID = item.wID;
64 si.hSubMenu = item.hSubMenu;
65 si.hbmpChecked = item.hbmpChecked;
66 si.hbmpUnchecked = item.hbmpUnchecked;
67 si.dwItemData = item.dwItemData;
68} 87}
69#endif 88#endif
70 89
71static void ConvertItemToMyForm(const MENUITEMINFOW &si, CMenuItem &item) 90static void ConvertItemToMyForm(const MENUITEMINFOW &si, CMenuItem &item)
72{ 91{
73 item.fMask = si.fMask; 92 COPY_MENUITEM_fields(item, si)
74 item.fType = si.fType;
75 item.fState = si.fState;
76 item.wID = si.wID;
77 item.hSubMenu = si.hSubMenu;
78 item.hbmpChecked = si.hbmpChecked;
79 item.hbmpUnchecked = si.hbmpUnchecked;
80 item.dwItemData = si.dwItemData;
81} 93}
82 94
83#ifndef _UNICODE 95#ifndef _UNICODE
84static void ConvertItemToMyForm(const MENUITEMINFOA &si, CMenuItem &item) 96static void ConvertItemToMyForm(const MENUITEMINFOA &si, CMenuItem &item)
85{ 97{
86 item.fMask = si.fMask; 98 COPY_MENUITEM_fields(item, si)
87 item.fType = si.fType;
88 item.fState = si.fState;
89 item.wID = si.wID;
90 item.hSubMenu = si.hSubMenu;
91 item.hbmpChecked = si.hbmpChecked;
92 item.hbmpUnchecked = si.hbmpUnchecked;
93 item.dwItemData = si.dwItemData;
94} 99}
95#endif 100#endif
96 101
97bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) 102
103bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) const
98{ 104{
99 const UINT kMaxSize = 512; 105 item.StringValue.Empty();
106 const unsigned kMaxSize = 512;
100 #ifndef _UNICODE 107 #ifndef _UNICODE
101 if (!g_IsNT) 108 if (!g_IsNT)
102 { 109 {
103 CHAR s[kMaxSize + 1];
104 MENUITEMINFOA si; 110 MENUITEMINFOA si;
105 ConvertItemToSysForm(item, si); 111 ConvertItemToSysForm(item, si);
106 if (item.IsString()) 112 const bool isString = item.IsString();
113 unsigned bufSize = kMaxSize;
114 AString a;
115 if (isString)
107 { 116 {
108 si.cch = kMaxSize; 117 si.cch = bufSize;
109 si.dwTypeData = s; 118 si.dwTypeData = a.GetBuf(bufSize);
110 } 119 }
111 if (GetItemInfo(itemIndex, byPosition, &si)) 120 bool res = GetItemInfo(itemIndex, byPosition, &si);
121 if (isString)
122 a.ReleaseBuf_CalcLen(bufSize);
123 if (!res)
124 return false;
112 { 125 {
126 if (isString && si.cch >= bufSize - 1)
127 {
128 si.dwTypeData = NULL;
129 res = GetItemInfo(itemIndex, byPosition, &si);
130 if (!res)
131 return false;
132 si.cch++;
133 bufSize = si.cch;
134 si.dwTypeData = a.GetBuf(bufSize);
135 res = GetItemInfo(itemIndex, byPosition, &si);
136 a.ReleaseBuf_CalcLen(bufSize);
137 if (!res)
138 return false;
139 }
113 ConvertItemToMyForm(si, item); 140 ConvertItemToMyForm(si, item);
114 if (item.IsString()) 141 if (isString)
115 item.StringValue = GetUnicodeString(s); 142 item.StringValue = GetUnicodeString(a);
116 return true; 143 return true;
117 } 144 }
118 } 145 }
@@ -120,24 +147,45 @@ bool CMenu::GetItem(UINT itemIndex, bool byPosition, CMenuItem &item)
120 #endif 147 #endif
121 { 148 {
122 wchar_t s[kMaxSize + 1]; 149 wchar_t s[kMaxSize + 1];
150 s[0] = 0;
123 MENUITEMINFOW si; 151 MENUITEMINFOW si;
124 ConvertItemToSysForm(item, si); 152 ConvertItemToSysForm(item, si);
125 if (item.IsString()) 153 const bool isString = item.IsString();
154 unsigned bufSize = kMaxSize;
155 if (isString)
126 { 156 {
127 si.cch = kMaxSize; 157 si.cch = bufSize;
128 si.dwTypeData = s; 158 si.dwTypeData = s;
129 } 159 }
130 if (GetItemInfo(itemIndex, byPosition, &si)) 160 bool res = GetItemInfo(itemIndex, byPosition, &si);
161 if (!res)
162 return false;
163 if (isString)
131 { 164 {
132 ConvertItemToMyForm(si, item); 165 s[Z7_ARRAY_SIZE(s) - 1] = 0;
133 if (item.IsString()) 166 item.StringValue = s;
134 item.StringValue = s; 167 if (si.cch >= bufSize - 1)
135 return true; 168 {
169 si.dwTypeData = NULL;
170 res = GetItemInfo(itemIndex, byPosition, &si);
171 if (!res)
172 return false;
173 si.cch++;
174 bufSize = si.cch;
175 si.dwTypeData = item.StringValue.GetBuf(bufSize);
176 res = GetItemInfo(itemIndex, byPosition, &si);
177 item.StringValue.ReleaseBuf_CalcLen(bufSize);
178 if (!res)
179 return false;
180 }
181 // if (item.StringValue.Len() != si.cch) throw 123; // for debug
136 } 182 }
183 ConvertItemToMyForm(si, item);
184 return true;
137 } 185 }
138 return false;
139} 186}
140 187
188
141bool CMenu::SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item) 189bool CMenu::SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item)
142{ 190{
143 #ifndef _UNICODE 191 #ifndef _UNICODE
@@ -164,6 +212,7 @@ bool CMenu::SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item)
164 } 212 }
165} 213}
166 214
215
167bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item) 216bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item)
168{ 217{
169 #ifndef _UNICODE 218 #ifndef _UNICODE
@@ -188,11 +237,11 @@ bool CMenu::InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item)
188 si.dwTypeData = item.StringValue.Ptr_non_const(); 237 si.dwTypeData = item.StringValue.Ptr_non_const();
189 #ifdef UNDER_CE 238 #ifdef UNDER_CE
190 UINT flags = (item.fType & MFT_SEPARATOR) ? MF_SEPARATOR : MF_STRING; 239 UINT flags = (item.fType & MFT_SEPARATOR) ? MF_SEPARATOR : MF_STRING;
191 UINT id = item.wID; 240 UINT_PTR id = item.wID;
192 if ((item.fMask & MIIM_SUBMENU) != 0) 241 if ((item.fMask & MIIM_SUBMENU) != 0)
193 { 242 {
194 flags |= MF_POPUP; 243 flags |= MF_POPUP;
195 id = (UINT)item.hSubMenu; 244 id = (UINT_PTR)item.hSubMenu;
196 } 245 }
197 if (!Insert(itemIndex, flags | (byPosition ? MF_BYPOSITION : MF_BYCOMMAND), id, item.StringValue)) 246 if (!Insert(itemIndex, flags | (byPosition ? MF_BYPOSITION : MF_BYCOMMAND), id, item.StringValue))
198 return false; 247 return false;
diff --git a/CPP/Windows/Menu.h b/CPP/Windows/Menu.h
index aacdc7c..e1de4c4 100644
--- a/CPP/Windows/Menu.h
+++ b/CPP/Windows/Menu.h
@@ -1,14 +1,27 @@
1// Windows/Menu.h 1// Windows/Menu.h
2 2
3#ifndef __WINDOWS_MENU_H 3#ifndef ZIP7_INC_WINDOWS_MENU_H
4#define __WINDOWS_MENU_H 4#define ZIP7_INC_WINDOWS_MENU_H
5 5
6#include "../Common/MyWindows.h"
6#include "../Common/MyString.h" 7#include "../Common/MyString.h"
7 8
8#include "Defs.h" 9#include "Defs.h"
9 10
10namespace NWindows { 11namespace NWindows {
11 12
13#ifndef MIIM_STRING
14#define MIIM_STRING 0x00000040
15#endif
16/*
17#ifndef MIIM_BITMAP
18#define MIIM_BITMAP 0x00000080
19#endif
20*/
21#ifndef MIIM_FTYPE
22#define MIIM_FTYPE 0x00000100
23#endif
24
12struct CMenuItem 25struct CMenuItem
13{ 26{
14 UString StringValue; 27 UString StringValue;
@@ -23,24 +36,23 @@ struct CMenuItem
23 // LPTSTR dwTypeData; 36 // LPTSTR dwTypeData;
24 // UINT cch; 37 // UINT cch;
25 // HBITMAP hbmpItem; 38 // HBITMAP hbmpItem;
26 bool IsString() const // change it MIIM_STRING 39 bool IsString() const { return (fMask & (MIIM_TYPE | MIIM_STRING)) != 0; }
27 { return ((fMask & MIIM_TYPE) != 0 && (fType == MFT_STRING)); }
28 bool IsSeparator() const { return (fType == MFT_SEPARATOR); } 40 bool IsSeparator() const { return (fType == MFT_SEPARATOR); }
29 CMenuItem(): fMask(0), fType(0), fState(0), wID(0), hSubMenu(0), hbmpChecked(0), 41 CMenuItem(): fMask(0), fType(0), fState(0), wID(0),
30 hbmpUnchecked(0), dwItemData(0) {} 42 hSubMenu(NULL), hbmpChecked(NULL), hbmpUnchecked(NULL), dwItemData(0) {}
31}; 43};
32 44
33class CMenu 45class CMenu
34{ 46{
35 HMENU _menu; 47 HMENU _menu;
36public: 48public:
37 CMenu(): _menu(NULL) {}; 49 CMenu(): _menu(NULL) {}
38 operator HMENU() const { return _menu; } 50 operator HMENU() const { return _menu; }
39 void Attach(HMENU menu) { _menu = menu; } 51 void Attach(HMENU menu) { _menu = menu; }
40 52
41 HMENU Detach() 53 HMENU Detach()
42 { 54 {
43 HMENU menu = _menu; 55 const HMENU menu = _menu;
44 _menu = NULL; 56 _menu = NULL;
45 return menu; 57 return menu;
46 } 58 }
@@ -59,27 +71,27 @@ public:
59 71
60 bool Destroy() 72 bool Destroy()
61 { 73 {
62 if (_menu == NULL) 74 if (!_menu)
63 return false; 75 return false;
64 return BOOLToBool(::DestroyMenu(Detach())); 76 return BOOLToBool(::DestroyMenu(Detach()));
65 } 77 }
66 78
67 int GetItemCount() 79 int GetItemCount() const
68 { 80 {
69 #ifdef UNDER_CE 81 #ifdef UNDER_CE
70 for (int i = 0;; i++) 82 for (unsigned i = 0;; i++)
71 { 83 {
72 CMenuItem item; 84 CMenuItem item;
73 item.fMask = MIIM_STATE; 85 item.fMask = MIIM_STATE;
74 if (!GetItem(i, true, item)) 86 if (!GetItem(i, true, item))
75 return i; 87 return (int)i;
76 } 88 }
77 #else 89 #else
78 return GetMenuItemCount(_menu); 90 return GetMenuItemCount(_menu);
79 #endif 91 #endif
80 } 92 }
81 93
82 HMENU GetSubMenu(int pos) { return ::GetSubMenu(_menu, pos); } 94 HMENU GetSubMenu(int pos) const { return ::GetSubMenu(_menu, pos); }
83 #ifndef UNDER_CE 95 #ifndef UNDER_CE
84 /* 96 /*
85 bool GetItemString(UINT idItem, UINT flag, CSysString &result) 97 bool GetItemString(UINT idItem, UINT flag, CSysString &result)
@@ -93,11 +105,11 @@ public:
93 return (len != 0); 105 return (len != 0);
94 } 106 }
95 */ 107 */
96 UINT GetItemID(int pos) { return ::GetMenuItemID(_menu, pos); } 108 UINT GetItemID(int pos) const { return ::GetMenuItemID(_menu, pos); }
97 UINT GetItemState(UINT id, UINT flags) { return ::GetMenuState(_menu, id, flags); } 109 UINT GetItemState(UINT id, UINT flags) const { return ::GetMenuState(_menu, id, flags); }
98 #endif 110 #endif
99 111
100 bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) 112 bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) const
101 { return BOOLToBool(::GetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } 113 { return BOOLToBool(::GetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
102 bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo) 114 bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo)
103 { return BOOLToBool(::SetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } 115 { return BOOLToBool(::SetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
@@ -118,7 +130,7 @@ public:
118 void RemoveAllItems() { RemoveAllItemsFrom(0); } 130 void RemoveAllItems() { RemoveAllItemsFrom(0); }
119 131
120 #ifndef _UNICODE 132 #ifndef _UNICODE
121 bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) 133 bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) const
122 { return BOOLToBool(::GetMenuItemInfoW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } 134 { return BOOLToBool(::GetMenuItemInfoW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
123 bool InsertItem(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo) 135 bool InsertItem(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo)
124 { return BOOLToBool(::InsertMenuItemW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); } 136 { return BOOLToBool(::InsertMenuItemW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
@@ -127,7 +139,7 @@ public:
127 bool AppendItem(UINT flags, UINT_PTR newItemID, LPCWSTR newItem); 139 bool AppendItem(UINT flags, UINT_PTR newItemID, LPCWSTR newItem);
128 #endif 140 #endif
129 141
130 bool GetItem(UINT itemIndex, bool byPosition, CMenuItem &item); 142 bool GetItem(UINT itemIndex, bool byPosition, CMenuItem &item) const;
131 bool SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item); 143 bool SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item);
132 bool InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item); 144 bool InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item);
133 145
@@ -147,10 +159,10 @@ class CMenuDestroyer
147 CMenu *_menu; 159 CMenu *_menu;
148public: 160public:
149 CMenuDestroyer(CMenu &menu): _menu(&menu) {} 161 CMenuDestroyer(CMenu &menu): _menu(&menu) {}
150 CMenuDestroyer(): _menu(0) {} 162 CMenuDestroyer(): _menu(NULL) {}
151 ~CMenuDestroyer() { if (_menu) _menu->Destroy(); } 163 ~CMenuDestroyer() { if (_menu) _menu->Destroy(); }
152 void Attach(CMenu &menu) { _menu = &menu; } 164 void Attach(CMenu &menu) { _menu = &menu; }
153 void Disable() { _menu = 0; } 165 void Disable() { _menu = NULL; }
154}; 166};
155 167
156} 168}
diff --git a/CPP/Windows/NationalTime.cpp b/CPP/Windows/NationalTime.cpp
index 0dcd31e..d3c38de 100644
--- a/CPP/Windows/NationalTime.cpp
+++ b/CPP/Windows/NationalTime.cpp
@@ -16,8 +16,8 @@ bool MyGetTimeFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
16 if (numChars == 0) 16 if (numChars == 0)
17 return false; 17 return false;
18 numChars = ::GetTimeFormat(locale, flags, time, format, 18 numChars = ::GetTimeFormat(locale, flags, time, format,
19 resultString.GetBuf(numChars), numChars + 1); 19 resultString.GetBuf((unsigned)numChars), numChars + 1);
20 resultString.ReleaseBuf_CalcLen(numChars); 20 resultString.ReleaseBuf_CalcLen((unsigned)numChars);
21 return (numChars != 0); 21 return (numChars != 0);
22} 22}
23 23
@@ -29,8 +29,8 @@ bool MyGetDateFormat(LCID locale, DWORD flags, CONST SYSTEMTIME *time,
29 if (numChars == 0) 29 if (numChars == 0)
30 return false; 30 return false;
31 numChars = ::GetDateFormat(locale, flags, time, format, 31 numChars = ::GetDateFormat(locale, flags, time, format,
32 resultString.GetBuf(numChars), numChars + 1); 32 resultString.GetBuf((unsigned)numChars), numChars + 1);
33 resultString.ReleaseBuf_CalcLen(numChars); 33 resultString.ReleaseBuf_CalcLen((unsigned)numChars);
34 return (numChars != 0); 34 return (numChars != 0);
35} 35}
36 36
diff --git a/CPP/Windows/NationalTime.h b/CPP/Windows/NationalTime.h
index 49b0e5e..32ba479 100644
--- a/CPP/Windows/NationalTime.h
+++ b/CPP/Windows/NationalTime.h
@@ -1,7 +1,7 @@
1// Windows/NationalTime.h 1// Windows/NationalTime.h
2 2
3#ifndef __WINDOWS_NATIONAL_TIME_H 3#ifndef ZIP7_INC_WINDOWS_NATIONAL_TIME_H
4#define __WINDOWS_NATIONAL_TIME_H 4#define ZIP7_INC_WINDOWS_NATIONAL_TIME_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
diff --git a/CPP/Windows/Net.cpp b/CPP/Windows/Net.cpp
index 2a3952a..0ac82d4 100644
--- a/CPP/Windows/Net.cpp
+++ b/CPP/Windows/Net.cpp
@@ -14,13 +14,41 @@
14extern bool g_IsNT; 14extern bool g_IsNT;
15#endif 15#endif
16 16
17extern "C"
18{
19#if !defined(WNetGetResourceParent)
20// #if defined(Z7_OLD_WIN_SDK)
21// #if (WINVER >= 0x0400)
22DWORD APIENTRY WNetGetResourceParentA(IN LPNETRESOURCEA lpNetResource,
23 OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer);
24DWORD APIENTRY WNetGetResourceParentW(IN LPNETRESOURCEW lpNetResource,
25 OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer);
26#ifdef UNICODE
27#define WNetGetResourceParent WNetGetResourceParentW
28#else
29#define WNetGetResourceParent WNetGetResourceParentA
30#endif
31
32DWORD APIENTRY WNetGetResourceInformationA(IN LPNETRESOURCEA lpNetResource,
33 OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer, OUT LPSTR *lplpSystem);
34DWORD APIENTRY WNetGetResourceInformationW(IN LPNETRESOURCEW lpNetResource,
35 OUT LPVOID lpBuffer, IN OUT LPDWORD lpcbBuffer, OUT LPWSTR *lplpSystem);
36#ifdef UNICODE
37#define WNetGetResourceInformation WNetGetResourceInformationW
38#else
39#define WNetGetResourceInformation WNetGetResourceInformationA
40#endif
41// #endif // (WINVER >= 0x0400)
42#endif
43}
44
17namespace NWindows { 45namespace NWindows {
18namespace NNet { 46namespace NNet {
19 47
20DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResource) 48DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResource)
21{ 49{
22 Close(); 50 Close();
23 DWORD result = ::WNetOpenEnum(scope, type, usage, netResource, &_handle); 51 const DWORD result = ::WNetOpenEnum(scope, type, usage, netResource, &_handle);
24 _handleAllocated = (result == NO_ERROR); 52 _handleAllocated = (result == NO_ERROR);
25 return result; 53 return result;
26} 54}
@@ -29,7 +57,7 @@ DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCE netResourc
29DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCEW netResource) 57DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCEW netResource)
30{ 58{
31 Close(); 59 Close();
32 DWORD result = ::WNetOpenEnumW(scope, type, usage, netResource, &_handle); 60 const DWORD result = ::WNetOpenEnumW(scope, type, usage, netResource, &_handle);
33 _handleAllocated = (result == NO_ERROR); 61 _handleAllocated = (result == NO_ERROR);
34 return result; 62 return result;
35} 63}
@@ -37,7 +65,7 @@ DWORD CEnum::Open(DWORD scope, DWORD type, DWORD usage, LPNETRESOURCEW netResour
37 65
38static void SetComplexString(bool &defined, CSysString &destString, LPCTSTR srcString) 66static void SetComplexString(bool &defined, CSysString &destString, LPCTSTR srcString)
39{ 67{
40 defined = (srcString != 0); 68 defined = (srcString != NULL);
41 if (defined) 69 if (defined)
42 destString = srcString; 70 destString = srcString;
43 else 71 else
@@ -179,7 +207,7 @@ DWORD CEnum::Close()
179{ 207{
180 if (!_handleAllocated) 208 if (!_handleAllocated)
181 return NO_ERROR; 209 return NO_ERROR;
182 DWORD result = ::WNetCloseEnum(_handle); 210 const DWORD result = ::WNetCloseEnum(_handle);
183 _handleAllocated = (result != NO_ERROR); 211 _handleAllocated = (result != NO_ERROR);
184 return result; 212 return result;
185} 213}
@@ -204,7 +232,7 @@ DWORD CEnum::Next(CResource &resource)
204 ZeroMemory(lpnrLocal, kBufferSize); 232 ZeroMemory(lpnrLocal, kBufferSize);
205 DWORD bufferSize = kBufferSize; 233 DWORD bufferSize = kBufferSize;
206 DWORD numEntries = 1; 234 DWORD numEntries = 1;
207 DWORD result = Next(&numEntries, lpnrLocal, &bufferSize); 235 const DWORD result = Next(&numEntries, lpnrLocal, &bufferSize);
208 if (result != NO_ERROR) 236 if (result != NO_ERROR)
209 return result; 237 return result;
210 if (numEntries != 1) 238 if (numEntries != 1)
@@ -224,7 +252,7 @@ DWORD CEnum::Next(CResourceW &resource)
224 ZeroMemory(lpnrLocal, kBufferSize); 252 ZeroMemory(lpnrLocal, kBufferSize);
225 DWORD bufferSize = kBufferSize; 253 DWORD bufferSize = kBufferSize;
226 DWORD numEntries = 1; 254 DWORD numEntries = 1;
227 DWORD result = NextW(&numEntries, lpnrLocal, &bufferSize); 255 const DWORD result = NextW(&numEntries, lpnrLocal, &bufferSize);
228 if (result != NO_ERROR) 256 if (result != NO_ERROR)
229 return result; 257 return result;
230 if (numEntries != 1) 258 if (numEntries != 1)
@@ -233,7 +261,7 @@ DWORD CEnum::Next(CResourceW &resource)
233 return result; 261 return result;
234 } 262 }
235 CResource resourceA; 263 CResource resourceA;
236 DWORD result = Next(resourceA); 264 const DWORD result = Next(resourceA);
237 ConvertResourceToResourceW(resourceA, resource); 265 ConvertResourceToResourceW(resourceA, resource);
238 return result; 266 return result;
239} 267}
@@ -249,7 +277,7 @@ DWORD GetResourceParent(const CResource &resource, CResource &parentResource)
249 DWORD bufferSize = kBufferSize; 277 DWORD bufferSize = kBufferSize;
250 NETRESOURCE netResource; 278 NETRESOURCE netResource;
251 ConvertCResourceToNETRESOURCE(resource, netResource); 279 ConvertCResourceToNETRESOURCE(resource, netResource);
252 DWORD result = ::WNetGetResourceParent(&netResource, lpnrLocal, &bufferSize); 280 const DWORD result = ::WNetGetResourceParent(&netResource, lpnrLocal, &bufferSize);
253 if (result != NO_ERROR) 281 if (result != NO_ERROR)
254 return result; 282 return result;
255 ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource); 283 ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource);
@@ -268,7 +296,7 @@ DWORD GetResourceParent(const CResourceW &resource, CResourceW &parentResource)
268 DWORD bufferSize = kBufferSize; 296 DWORD bufferSize = kBufferSize;
269 NETRESOURCEW netResource; 297 NETRESOURCEW netResource;
270 ConvertCResourceToNETRESOURCE(resource, netResource); 298 ConvertCResourceToNETRESOURCE(resource, netResource);
271 DWORD result = ::WNetGetResourceParentW(&netResource, lpnrLocal, &bufferSize); 299 const DWORD result = ::WNetGetResourceParentW(&netResource, lpnrLocal, &bufferSize);
272 if (result != NO_ERROR) 300 if (result != NO_ERROR)
273 return result; 301 return result;
274 ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource); 302 ConvertNETRESOURCEToCResource(lpnrLocal[0], parentResource);
@@ -276,7 +304,7 @@ DWORD GetResourceParent(const CResourceW &resource, CResourceW &parentResource)
276 } 304 }
277 CResource resourceA, parentResourceA; 305 CResource resourceA, parentResourceA;
278 ConvertResourceWToResource(resource, resourceA); 306 ConvertResourceWToResource(resource, resourceA);
279 DWORD result = GetResourceParent(resourceA, parentResourceA); 307 const DWORD result = GetResourceParent(resourceA, parentResourceA);
280 ConvertResourceToResourceW(parentResourceA, parentResource); 308 ConvertResourceToResourceW(parentResourceA, parentResource);
281 return result; 309 return result;
282} 310}
@@ -293,11 +321,11 @@ DWORD GetResourceInformation(const CResource &resource,
293 NETRESOURCE netResource; 321 NETRESOURCE netResource;
294 ConvertCResourceToNETRESOURCE(resource, netResource); 322 ConvertCResourceToNETRESOURCE(resource, netResource);
295 LPTSTR lplpSystem; 323 LPTSTR lplpSystem;
296 DWORD result = ::WNetGetResourceInformation(&netResource, 324 const DWORD result = ::WNetGetResourceInformation(&netResource,
297 lpnrLocal, &bufferSize, &lplpSystem); 325 lpnrLocal, &bufferSize, &lplpSystem);
298 if (result != NO_ERROR) 326 if (result != NO_ERROR)
299 return result; 327 return result;
300 if (lplpSystem != 0) 328 if (lplpSystem != NULL)
301 systemPathPart = lplpSystem; 329 systemPathPart = lplpSystem;
302 ConvertNETRESOURCEToCResource(lpnrLocal[0], destResource); 330 ConvertNETRESOURCEToCResource(lpnrLocal[0], destResource);
303 return result; 331 return result;
@@ -317,7 +345,7 @@ DWORD GetResourceInformation(const CResourceW &resource,
317 NETRESOURCEW netResource; 345 NETRESOURCEW netResource;
318 ConvertCResourceToNETRESOURCE(resource, netResource); 346 ConvertCResourceToNETRESOURCE(resource, netResource);
319 LPWSTR lplpSystem; 347 LPWSTR lplpSystem;
320 DWORD result = ::WNetGetResourceInformationW(&netResource, 348 const DWORD result = ::WNetGetResourceInformationW(&netResource,
321 lpnrLocal, &bufferSize, &lplpSystem); 349 lpnrLocal, &bufferSize, &lplpSystem);
322 if (result != NO_ERROR) 350 if (result != NO_ERROR)
323 return result; 351 return result;
@@ -329,7 +357,7 @@ DWORD GetResourceInformation(const CResourceW &resource,
329 CResource resourceA, destResourceA; 357 CResource resourceA, destResourceA;
330 ConvertResourceWToResource(resource, resourceA); 358 ConvertResourceWToResource(resource, resourceA);
331 AString systemPathPartA; 359 AString systemPathPartA;
332 DWORD result = GetResourceInformation(resourceA, destResourceA, systemPathPartA); 360 const DWORD result = GetResourceInformation(resourceA, destResourceA, systemPathPartA);
333 ConvertResourceToResourceW(destResourceA, destResource); 361 ConvertResourceToResourceW(destResourceA, destResource);
334 systemPathPart = GetUnicodeString(systemPathPartA); 362 systemPathPart = GetUnicodeString(systemPathPartA);
335 return result; 363 return result;
diff --git a/CPP/Windows/Net.h b/CPP/Windows/Net.h
index 7b60b1b..a954bdb 100644
--- a/CPP/Windows/Net.h
+++ b/CPP/Windows/Net.h
@@ -1,9 +1,10 @@
1// Windows/Net.h 1// Windows/Net.h
2 2
3#ifndef __WINDOWS_NET_H 3#ifndef ZIP7_INC_WINDOWS_NET_H
4#define __WINDOWS_NET_H 4#define ZIP7_INC_WINDOWS_NET_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7#include "../Common/MyWindows.h"
7 8
8namespace NWindows { 9namespace NWindows {
9namespace NNet { 10namespace NNet {
diff --git a/CPP/Windows/NtCheck.h b/CPP/Windows/NtCheck.h
index 0af3291..362a05a 100644
--- a/CPP/Windows/NtCheck.h
+++ b/CPP/Windows/NtCheck.h
@@ -1,19 +1,29 @@
1// Windows/NtCheck.h 1// Windows/NtCheck.h
2 2
3#ifndef __WINDOWS_NT_CHECK_H 3#ifndef ZIP7_INC_WINDOWS_NT_CHECK_H
4#define __WINDOWS_NT_CHECK_H 4#define ZIP7_INC_WINDOWS_NT_CHECK_H
5 5
6#ifdef _WIN32 6#ifdef _WIN32
7 7
8#include "../Common/MyWindows.h" 8#include "../Common/MyWindows.h"
9 9
10#if !defined(_WIN64) && !defined(UNDER_CE) 10#if !defined(_WIN64) && !defined(UNDER_CE)
11
12#if defined(_MSC_VER) && _MSC_VER >= 1900
13#pragma warning(push)
14// GetVersionExW was declared deprecated
15#pragma warning(disable : 4996)
16#endif
11static inline bool IsItWindowsNT() 17static inline bool IsItWindowsNT()
12{ 18{
13 OSVERSIONINFO vi; 19 OSVERSIONINFO vi;
14 vi.dwOSVersionInfoSize = sizeof(vi); 20 vi.dwOSVersionInfoSize = sizeof(vi);
15 return (::GetVersionEx(&vi) && vi.dwPlatformId == VER_PLATFORM_WIN32_NT); 21 return (::GetVersionEx(&vi) && vi.dwPlatformId == VER_PLATFORM_WIN32_NT);
16} 22}
23#if defined(_MSC_VER) && _MSC_VER >= 1900
24#pragma warning(pop)
25#endif
26
17#endif 27#endif
18 28
19#ifndef _UNICODE 29#ifndef _UNICODE
diff --git a/CPP/Windows/ProcessMessages.h b/CPP/Windows/ProcessMessages.h
index b2558a0..aa98bbb 100644
--- a/CPP/Windows/ProcessMessages.h
+++ b/CPP/Windows/ProcessMessages.h
@@ -1,7 +1,7 @@
1// Windows/ProcessMessages.h 1// Windows/ProcessMessages.h
2 2
3#ifndef __WINDOWS_PROCESSMESSAGES_H 3#ifndef ZIP7_INC_WINDOWS_PROCESS_MESSAGES_H
4#define __WINDOWS_PROCESSMESSAGES_H 4#define ZIP7_INC_WINDOWS_PROCESS_MESSAGES_H
5 5
6namespace NWindows { 6namespace NWindows {
7 7
diff --git a/CPP/Windows/ProcessUtils.cpp b/CPP/Windows/ProcessUtils.cpp
index 9bf0538..607b4bb 100644
--- a/CPP/Windows/ProcessUtils.cpp
+++ b/CPP/Windows/ProcessUtils.cpp
@@ -46,9 +46,9 @@ WRes CProcess::Create(LPCWSTR imageName, const UString &params, LPCWSTR curDir)
46 #endif 46 #endif
47 params; 47 params;
48 #ifdef UNDER_CE 48 #ifdef UNDER_CE
49 curDir = 0; 49 curDir = NULL;
50 #else 50 #else
51 imageName = 0; 51 imageName = NULL;
52 #endif 52 #endif
53 PROCESS_INFORMATION pi; 53 PROCESS_INFORMATION pi;
54 BOOL result; 54 BOOL result;
@@ -57,12 +57,12 @@ WRes CProcess::Create(LPCWSTR imageName, const UString &params, LPCWSTR curDir)
57 { 57 {
58 STARTUPINFOA si; 58 STARTUPINFOA si;
59 si.cb = sizeof(si); 59 si.cb = sizeof(si);
60 si.lpReserved = 0; 60 si.lpReserved = NULL;
61 si.lpDesktop = 0; 61 si.lpDesktop = NULL;
62 si.lpTitle = 0; 62 si.lpTitle = NULL;
63 si.dwFlags = 0; 63 si.dwFlags = 0;
64 si.cbReserved2 = 0; 64 si.cbReserved2 = 0;
65 si.lpReserved2 = 0; 65 si.lpReserved2 = NULL;
66 66
67 CSysString curDirA; 67 CSysString curDirA;
68 if (curDir != 0) 68 if (curDir != 0)
@@ -76,12 +76,12 @@ WRes CProcess::Create(LPCWSTR imageName, const UString &params, LPCWSTR curDir)
76 { 76 {
77 STARTUPINFOW si; 77 STARTUPINFOW si;
78 si.cb = sizeof(si); 78 si.cb = sizeof(si);
79 si.lpReserved = 0; 79 si.lpReserved = NULL;
80 si.lpDesktop = 0; 80 si.lpDesktop = NULL;
81 si.lpTitle = 0; 81 si.lpTitle = NULL;
82 si.dwFlags = 0; 82 si.dwFlags = 0;
83 si.cbReserved2 = 0; 83 si.cbReserved2 = 0;
84 si.lpReserved2 = 0; 84 si.lpReserved2 = NULL;
85 85
86 result = CreateProcessW(imageName, params2.Ptr_non_const(), 86 result = CreateProcessW(imageName, params2.Ptr_non_const(),
87 NULL, NULL, FALSE, 0, NULL, curDir, &si, &pi); 87 NULL, NULL, FALSE, 0, NULL, curDir, &si, &pi);
@@ -96,7 +96,7 @@ WRes CProcess::Create(LPCWSTR imageName, const UString &params, LPCWSTR curDir)
96WRes MyCreateProcess(LPCWSTR imageName, const UString &params) 96WRes MyCreateProcess(LPCWSTR imageName, const UString &params)
97{ 97{
98 CProcess process; 98 CProcess process;
99 return process.Create(imageName, params, 0); 99 return process.Create(imageName, params, NULL);
100} 100}
101 101
102} 102}
diff --git a/CPP/Windows/ProcessUtils.h b/CPP/Windows/ProcessUtils.h
index e46f9ab..b1fce3a 100644
--- a/CPP/Windows/ProcessUtils.h
+++ b/CPP/Windows/ProcessUtils.h
@@ -1,9 +1,41 @@
1// Windows/ProcessUtils.h 1// Windows/ProcessUtils.h
2 2
3#ifndef __WINDOWS_PROCESS_UTILS_H 3#ifndef ZIP7_INC_WINDOWS_PROCESS_UTILS_H
4#define __WINDOWS_PROCESS_UTILS_H 4#define ZIP7_INC_WINDOWS_PROCESS_UTILS_H
5 5
6#include "../Common/MyWindows.h"
7
8#ifndef Z7_OLD_WIN_SDK
9
10#if defined(__MINGW32__) || defined(__MINGW64__)
11#include <psapi.h>
12#else
6#include <Psapi.h> 13#include <Psapi.h>
14#endif
15
16#else // Z7_OLD_WIN_SDK
17
18typedef struct _MODULEINFO {
19 LPVOID lpBaseOfDll;
20 DWORD SizeOfImage;
21 LPVOID EntryPoint;
22} MODULEINFO, *LPMODULEINFO;
23
24typedef struct _PROCESS_MEMORY_COUNTERS {
25 DWORD cb;
26 DWORD PageFaultCount;
27 SIZE_T PeakWorkingSetSize;
28 SIZE_T WorkingSetSize;
29 SIZE_T QuotaPeakPagedPoolUsage;
30 SIZE_T QuotaPagedPoolUsage;
31 SIZE_T QuotaPeakNonPagedPoolUsage;
32 SIZE_T QuotaNonPagedPoolUsage;
33 SIZE_T PagefileUsage;
34 SIZE_T PeakPagefileUsage;
35} PROCESS_MEMORY_COUNTERS;
36typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS;
37
38#endif // Z7_OLD_WIN_SDK
7 39
8#include "../Common/MyString.h" 40#include "../Common/MyString.h"
9 41
@@ -18,7 +50,7 @@ public:
18 bool Open(DWORD desiredAccess, bool inheritHandle, DWORD processId) 50 bool Open(DWORD desiredAccess, bool inheritHandle, DWORD processId)
19 { 51 {
20 _handle = ::OpenProcess(desiredAccess, inheritHandle, processId); 52 _handle = ::OpenProcess(desiredAccess, inheritHandle, processId);
21 return (_handle != 0); 53 return (_handle != NULL);
22 } 54 }
23 55
24 #ifndef UNDER_CE 56 #ifndef UNDER_CE
@@ -43,9 +75,14 @@ public:
43 { return BOOLToBool(::ReadProcessMemory(_handle, baseAddress, buffer, size, numberOfBytesRead)); } 75 { return BOOLToBool(::ReadProcessMemory(_handle, baseAddress, buffer, size, numberOfBytesRead)); }
44 76
45 bool WriteMemory(LPVOID baseAddress, LPCVOID buffer, SIZE_T size, SIZE_T* numberOfBytesWritten) 77 bool WriteMemory(LPVOID baseAddress, LPCVOID buffer, SIZE_T size, SIZE_T* numberOfBytesWritten)
46 { return BOOLToBool(::WriteProcessMemory(_handle, baseAddress, buffer, size, numberOfBytesWritten)); } 78 { return BOOLToBool(::WriteProcessMemory(_handle, baseAddress,
47 79 #ifdef Z7_OLD_WIN_SDK
48 bool FlushInstructionCache(LPCVOID baseAddress = 0, SIZE_T size = 0) 80 (LPVOID)
81 #endif
82 buffer,
83 size, numberOfBytesWritten)); }
84
85 bool FlushInstructionCache(LPCVOID baseAddress = NULL, SIZE_T size = 0)
49 { return BOOLToBool(::FlushInstructionCache(_handle, baseAddress, size)); } 86 { return BOOLToBool(::FlushInstructionCache(_handle, baseAddress, size)); }
50 87
51 LPVOID VirtualAlloc(LPVOID address, SIZE_T size, DWORD allocationType, DWORD protect) 88 LPVOID VirtualAlloc(LPVOID address, SIZE_T size, DWORD allocationType, DWORD protect)
@@ -56,17 +93,17 @@ public:
56 93
57 // Process Status API (PSAPI) 94 // Process Status API (PSAPI)
58 95
96 /*
59 bool EmptyWorkingSet() 97 bool EmptyWorkingSet()
60 { return BOOLToBool(::EmptyWorkingSet(_handle)); } 98 { return BOOLToBool(::EmptyWorkingSet(_handle)); }
61 bool EnumModules(HMODULE *hModules, DWORD arraySizeInBytes, LPDWORD receivedBytes) 99 bool EnumModules(HMODULE *hModules, DWORD arraySizeInBytes, LPDWORD receivedBytes)
62 { return BOOLToBool(::EnumProcessModules(_handle, hModules, arraySizeInBytes, receivedBytes)); } 100 { return BOOLToBool(::EnumProcessModules(_handle, hModules, arraySizeInBytes, receivedBytes)); }
63
64 DWORD MyGetModuleBaseName(HMODULE hModule, LPTSTR baseName, DWORD size) 101 DWORD MyGetModuleBaseName(HMODULE hModule, LPTSTR baseName, DWORD size)
65 { return ::GetModuleBaseName(_handle, hModule, baseName, size); } 102 { return ::GetModuleBaseName(_handle, hModule, baseName, size); }
66 bool MyGetModuleBaseName(HMODULE hModule, CSysString &name) 103 bool MyGetModuleBaseName(HMODULE hModule, CSysString &name)
67 { 104 {
68 const unsigned len = MAX_PATH + 100; 105 const unsigned len = MAX_PATH + 100;
69 DWORD resultLen = MyGetModuleBaseName(hModule, name.GetBuf(len), len); 106 const DWORD resultLen = MyGetModuleBaseName(hModule, name.GetBuf(len), len);
70 name.ReleaseBuf_CalcLen(len); 107 name.ReleaseBuf_CalcLen(len);
71 return (resultLen != 0); 108 return (resultLen != 0);
72 } 109 }
@@ -76,7 +113,7 @@ public:
76 bool MyGetModuleFileNameEx(HMODULE hModule, CSysString &name) 113 bool MyGetModuleFileNameEx(HMODULE hModule, CSysString &name)
77 { 114 {
78 const unsigned len = MAX_PATH + 100; 115 const unsigned len = MAX_PATH + 100;
79 DWORD resultLen = MyGetModuleFileNameEx(hModule, name.GetBuf(len), len); 116 const DWORD resultLen = MyGetModuleFileNameEx(hModule, name.GetBuf(len), len);
80 name.ReleaseBuf_CalcLen(len); 117 name.ReleaseBuf_CalcLen(len);
81 return (resultLen != 0); 118 return (resultLen != 0);
82 } 119 }
@@ -85,6 +122,7 @@ public:
85 { return BOOLToBool(::GetModuleInformation(_handle, hModule, moduleInfo, sizeof(MODULEINFO))); } 122 { return BOOLToBool(::GetModuleInformation(_handle, hModule, moduleInfo, sizeof(MODULEINFO))); }
86 bool GetMemoryInfo(PPROCESS_MEMORY_COUNTERS memCounters) 123 bool GetMemoryInfo(PPROCESS_MEMORY_COUNTERS memCounters)
87 { return BOOLToBool(::GetProcessMemoryInfo(_handle, memCounters, sizeof(PROCESS_MEMORY_COUNTERS))); } 124 { return BOOLToBool(::GetProcessMemoryInfo(_handle, memCounters, sizeof(PROCESS_MEMORY_COUNTERS))); }
125 */
88 126
89 #endif 127 #endif
90 128
diff --git a/CPP/Windows/PropVariant.cpp b/CPP/Windows/PropVariant.cpp
index 2b17950..457b1dc 100644
--- a/CPP/Windows/PropVariant.cpp
+++ b/CPP/Windows/PropVariant.cpp
@@ -197,17 +197,17 @@ BSTR CPropVariant::AllocBstr(unsigned numChars)
197 197
198void CPropVariant::Set_Int32(Int32 value) throw() 198void CPropVariant::Set_Int32(Int32 value) throw()
199{ 199{
200 SET_PROP_id_dest(VT_I4, lVal); 200 SET_PROP_id_dest(VT_I4, lVal)
201} 201}
202 202
203void CPropVariant::Set_Int64(Int64 value) throw() 203void CPropVariant::Set_Int64(Int64 value) throw()
204{ 204{
205 SET_PROP_id_dest(VT_I8, hVal.QuadPart); 205 SET_PROP_id_dest(VT_I8, hVal.QuadPart)
206} 206}
207 207
208#define SET_PROP_FUNC(type, id, dest) \ 208#define SET_PROP_FUNC(type, id, dest) \
209 CPropVariant& CPropVariant::operator=(type value) throw() \ 209 CPropVariant& CPropVariant::operator=(type value) throw() \
210 { SET_PROP_id_dest(id, dest); return *this; } 210 { SET_PROP_id_dest(id, dest) return *this; }
211 211
212SET_PROP_FUNC(Byte, VT_UI1, bVal) 212SET_PROP_FUNC(Byte, VT_UI1, bVal)
213// SET_PROP_FUNC(Int16, VT_I2, iVal) 213// SET_PROP_FUNC(Int16, VT_I2, iVal)
@@ -245,7 +245,7 @@ SET_PROP_FUNC(const FILETIME &, VT_FILETIME, filetime)
245 we call system functions for VT_BSTR and for unknown typed 245 we call system functions for VT_BSTR and for unknown typed
246*/ 246*/
247 247
248CPropVariant::~CPropVariant() 248CPropVariant::~CPropVariant() throw()
249{ 249{
250 switch ((unsigned)vt) 250 switch ((unsigned)vt)
251 { 251 {
diff --git a/CPP/Windows/PropVariant.h b/CPP/Windows/PropVariant.h
index 171402f..f358fde 100644
--- a/CPP/Windows/PropVariant.h
+++ b/CPP/Windows/PropVariant.h
@@ -1,7 +1,7 @@
1// Windows/PropVariant.h 1// Windows/PropVariant.h
2 2
3#ifndef __WINDOWS_PROP_VARIANT_H 3#ifndef ZIP7_INC_WINDOWS_PROP_VARIANT_H
4#define __WINDOWS_PROP_VARIANT_H 4#define ZIP7_INC_WINDOWS_PROP_VARIANT_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7#include "../Common/MyWindows.h" 7#include "../Common/MyWindows.h"
@@ -64,7 +64,7 @@ public:
64 // wReserved2 = 0; 64 // wReserved2 = 0;
65 // wReserved3 = 0; 65 // wReserved3 = 0;
66 // uhVal.QuadPart = 0; 66 // uhVal.QuadPart = 0;
67 bstrVal = 0; 67 bstrVal = NULL;
68 } 68 }
69 69
70 70
@@ -104,13 +104,13 @@ public:
104 const unsigned ns100 = wReserved2; 104 const unsigned ns100 = wReserved2;
105 if (prec == 0 105 if (prec == 0
106 && prec <= k_PropVar_TimePrec_1ns 106 && prec <= k_PropVar_TimePrec_1ns
107 && ns100 < 100 107 && ns100 < 100
108 && wReserved3 == 0) 108 && wReserved3 == 0)
109 return ns100; 109 return ns100;
110 return 0; 110 return 0;
111 } 111 }
112 112
113 ~CPropVariant(); 113 ~CPropVariant() throw();
114 CPropVariant(const PROPVARIANT &varSrc); 114 CPropVariant(const PROPVARIANT &varSrc);
115 CPropVariant(const CPropVariant &varSrc); 115 CPropVariant(const CPropVariant &varSrc);
116 CPropVariant(BSTR bstrSrc); 116 CPropVariant(BSTR bstrSrc);
diff --git a/CPP/Windows/PropVariantConv.cpp b/CPP/Windows/PropVariantConv.cpp
index 3c9bbd1..5fb96a7 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
36 s[0] = (char)('0' + val / 10); 36 s[0] = (char)('0' + val / 10);
37 s += 4; 37 s += 4;
38 } 38 }
39 UINT_TO_STR_2('-', st.wMonth); 39 UINT_TO_STR_2('-', st.wMonth)
40 UINT_TO_STR_2('-', st.wDay); 40 UINT_TO_STR_2('-', st.wDay)
41 41
42 if (level > kTimestampPrintLevel_DAY) 42 if (level > kTimestampPrintLevel_DAY)
43 { 43 {
44 UINT_TO_STR_2(' ', st.wHour); 44 UINT_TO_STR_2(' ', st.wHour)
45 UINT_TO_STR_2(':', st.wMinute); 45 UINT_TO_STR_2(':', st.wMinute)
46 46
47 if (level >= kTimestampPrintLevel_SEC) 47 if (level >= kTimestampPrintLevel_SEC)
48 { 48 {
49 UINT_TO_STR_2(':', st.wSecond); 49 UINT_TO_STR_2(':', st.wSecond)
50 50
51 if (level > kTimestampPrintLevel_SEC) 51 if (level > kTimestampPrintLevel_SEC)
52 { 52 {
diff --git a/CPP/Windows/PropVariantConv.h b/CPP/Windows/PropVariantConv.h
index 6067784..ec5223b 100644
--- a/CPP/Windows/PropVariantConv.h
+++ b/CPP/Windows/PropVariantConv.h
@@ -1,7 +1,7 @@
1// Windows/PropVariantConv.h 1// Windows/PropVariantConv.h
2 2
3#ifndef __PROP_VARIANT_CONV_H 3#ifndef ZIP7_INC_PROP_VARIANT_CONV_H
4#define __PROP_VARIANT_CONV_H 4#define ZIP7_INC_PROP_VARIANT_CONV_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7 7
diff --git a/CPP/Windows/PropVariantUtils.h b/CPP/Windows/PropVariantUtils.h
index 3dd8295..78adb50 100644
--- a/CPP/Windows/PropVariantUtils.h
+++ b/CPP/Windows/PropVariantUtils.h
@@ -1,7 +1,7 @@
1// Windows/PropVariantUtils.h 1// Windows/PropVariantUtils.h
2 2
3#ifndef __PROP_VARIANT_UTILS_H 3#ifndef ZIP7_INC_PROP_VARIANT_UTILS_H
4#define __PROP_VARIANT_UTILS_H 4#define ZIP7_INC_PROP_VARIANT_UTILS_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
@@ -24,11 +24,11 @@ void FlagsToProp(const CUInt32PCharPair *pairs, unsigned num, UInt32 flags, NWin
24AString TypeToString(const char * const table[], unsigned num, UInt32 value); 24AString TypeToString(const char * const table[], unsigned num, UInt32 value);
25void TypeToProp(const char * const table[], unsigned num, UInt32 value, NWindows::NCOM::CPropVariant &prop); 25void TypeToProp(const char * const table[], unsigned num, UInt32 value, NWindows::NCOM::CPropVariant &prop);
26 26
27#define PAIR_TO_PROP(pairs, value, prop) PairToProp(pairs, ARRAY_SIZE(pairs), value, prop) 27#define PAIR_TO_PROP(pairs, value, prop) PairToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop)
28#define FLAGS_TO_PROP(pairs, value, prop) FlagsToProp(pairs, ARRAY_SIZE(pairs), value, prop) 28#define FLAGS_TO_PROP(pairs, value, prop) FlagsToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop)
29#define TYPE_TO_PROP(table, value, prop) TypeToProp(table, ARRAY_SIZE(table), value, prop) 29#define TYPE_TO_PROP(table, value, prop) TypeToProp(table, Z7_ARRAY_SIZE(table), value, prop)
30 30
31void Flags64ToProp(const CUInt32PCharPair *pairs, unsigned num, UInt64 flags, NWindows::NCOM::CPropVariant &prop); 31void Flags64ToProp(const CUInt32PCharPair *pairs, unsigned num, UInt64 flags, NWindows::NCOM::CPropVariant &prop);
32#define FLAGS64_TO_PROP(pairs, value, prop) Flags64ToProp(pairs, ARRAY_SIZE(pairs), value, prop) 32#define FLAGS64_TO_PROP(pairs, value, prop) Flags64ToProp(pairs, Z7_ARRAY_SIZE(pairs), value, prop)
33 33
34#endif 34#endif
diff --git a/CPP/Windows/Registry.h b/CPP/Windows/Registry.h
index ca79dfe..0d3b4fc 100644
--- a/CPP/Windows/Registry.h
+++ b/CPP/Windows/Registry.h
@@ -1,7 +1,7 @@
1// Windows/Registry.h 1// Windows/Registry.h
2 2
3#ifndef __WINDOWS_REGISTRY_H 3#ifndef ZIP7_INC_WINDOWS_REGISTRY_H
4#define __WINDOWS_REGISTRY_H 4#define ZIP7_INC_WINDOWS_REGISTRY_H
5 5
6#include "../Common/MyBuffer.h" 6#include "../Common/MyBuffer.h"
7#include "../Common/MyString.h" 7#include "../Common/MyString.h"
diff --git a/CPP/Windows/ResourceString.h b/CPP/Windows/ResourceString.h
index f0bdabf..773307b 100644
--- a/CPP/Windows/ResourceString.h
+++ b/CPP/Windows/ResourceString.h
@@ -1,9 +1,10 @@
1// Windows/ResourceString.h 1// Windows/ResourceString.h
2 2
3#ifndef __WINDOWS_RESOURCE_STRING_H 3#ifndef ZIP7_INC_WINDOWS_RESOURCE_STRING_H
4#define __WINDOWS_RESOURCE_STRING_H 4#define ZIP7_INC_WINDOWS_RESOURCE_STRING_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7#include "../Common/MyWindows.h"
7 8
8namespace NWindows { 9namespace NWindows {
9 10
diff --git a/CPP/Windows/SecurityUtils.cpp b/CPP/Windows/SecurityUtils.cpp
index ede83fa..d4282d0 100644
--- a/CPP/Windows/SecurityUtils.cpp
+++ b/CPP/Windows/SecurityUtils.cpp
@@ -4,9 +4,6 @@
4 4
5#include "SecurityUtils.h" 5#include "SecurityUtils.h"
6 6
7#define MY_CAST_FUNC (void(*)())
8// #define MY_CAST_FUNC
9
10namespace NWindows { 7namespace NWindows {
11namespace NSecurity { 8namespace NSecurity {
12 9
@@ -35,7 +32,7 @@ bool MyLookupAccountSid(LPCTSTR systemName, PSID sid,
35 32
36static void SetLsaString(LPWSTR src, PLSA_UNICODE_STRING dest) 33static void SetLsaString(LPWSTR src, PLSA_UNICODE_STRING dest)
37{ 34{
38 size_t len = (size_t)wcslen(src); 35 const size_t len = (size_t)wcslen(src);
39 dest->Length = (USHORT)(len * sizeof(WCHAR)); 36 dest->Length = (USHORT)(len * sizeof(WCHAR));
40 dest->MaximumLength = (USHORT)((len + 1) * sizeof(WCHAR)); 37 dest->MaximumLength = (USHORT)((len + 1) * sizeof(WCHAR));
41 dest->Buffer = src; 38 dest->Buffer = src;
@@ -72,13 +69,14 @@ typedef BOOL (WINAPI * Func_LookupAccountNameW)(
72static PSID GetSid(LPWSTR accountName) 69static PSID GetSid(LPWSTR accountName)
73{ 70{
74 #ifndef _UNICODE 71 #ifndef _UNICODE
75 HMODULE hModule = GetModuleHandle(TEXT("Advapi32.dll")); 72 const HMODULE hModule = GetModuleHandle(TEXT("advapi32.dll"));
76 if (hModule == NULL) 73 if (!hModule)
77 return NULL; 74 return NULL;
78 Func_LookupAccountNameW lookupAccountNameW = (Func_LookupAccountNameW) 75 const
79 MY_CAST_FUNC 76 Func_LookupAccountNameW lookupAccountNameW = Z7_GET_PROC_ADDRESS(
80 GetProcAddress(hModule, "LookupAccountNameW"); 77 Func_LookupAccountNameW, hModule,
81 if (lookupAccountNameW == NULL) 78 "LookupAccountNameW");
79 if (!lookupAccountNameW)
82 return NULL; 80 return NULL;
83 #endif 81 #endif
84 82
@@ -88,21 +86,21 @@ static PSID GetSid(LPWSTR accountName)
88 #ifdef _UNICODE 86 #ifdef _UNICODE
89 ::LookupAccountNameW 87 ::LookupAccountNameW
90 #else 88 #else
91 lookupAccountNameW 89 lookupAccountNameW
92 #endif 90 #endif
93 (NULL, accountName, NULL, &sidLen, NULL, &domainLen, &sidNameUse)) 91 (NULL, accountName, NULL, &sidLen, NULL, &domainLen, &sidNameUse))
94 { 92 {
95 if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) 93 if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
96 { 94 {
97 PSID pSid = ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidLen); 95 const PSID pSid = ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidLen);
98 LPWSTR domainName = (LPWSTR)::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (domainLen + 1) * sizeof(WCHAR)); 96 LPWSTR domainName = (LPWSTR)::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (domainLen + 1) * sizeof(WCHAR));
99 BOOL res = 97 const BOOL res =
100 #ifdef _UNICODE 98 #ifdef _UNICODE
101 ::LookupAccountNameW 99 ::LookupAccountNameW
102 #else 100 #else
103 lookupAccountNameW 101 lookupAccountNameW
104 #endif 102 #endif
105 (NULL, accountName, pSid, &sidLen, domainName, &domainLen, &sidNameUse); 103 (NULL, accountName, pSid, &sidLen, domainName, &domainLen, &sidNameUse);
106 ::HeapFree(GetProcessHeap(), 0, domainName); 104 ::HeapFree(GetProcessHeap(), 0, domainName);
107 if (res) 105 if (res)
108 return pSid; 106 return pSid;
@@ -111,7 +109,7 @@ static PSID GetSid(LPWSTR accountName)
111 return NULL; 109 return NULL;
112} 110}
113 111
114#define MY__SE_LOCK_MEMORY_NAME L"SeLockMemoryPrivilege" 112#define Z7_WIN_SE_LOCK_MEMORY_NAME L"SeLockMemoryPrivilege"
115 113
116bool AddLockMemoryPrivilege() 114bool AddLockMemoryPrivilege()
117{ 115{
@@ -131,13 +129,13 @@ bool AddLockMemoryPrivilege()
131 != 0) 129 != 0)
132 return false; 130 return false;
133 LSA_UNICODE_STRING userRights; 131 LSA_UNICODE_STRING userRights;
134 wchar_t s[128] = MY__SE_LOCK_MEMORY_NAME; 132 wchar_t s[128] = Z7_WIN_SE_LOCK_MEMORY_NAME;
135 SetLsaString(s, &userRights); 133 SetLsaString(s, &userRights);
136 WCHAR userName[256 + 2]; 134 WCHAR userName[256 + 2];
137 DWORD size = 256; 135 DWORD size = 256;
138 if (!GetUserNameW(userName, &size)) 136 if (!GetUserNameW(userName, &size))
139 return false; 137 return false;
140 PSID psid = GetSid(userName); 138 const PSID psid = GetSid(userName);
141 if (psid == NULL) 139 if (psid == NULL)
142 return false; 140 return false;
143 bool res = false; 141 bool res = false;
@@ -176,7 +174,7 @@ bool AddLockMemoryPrivilege()
176 res = true; 174 res = true;
177 } 175 }
178 */ 176 */
179 NTSTATUS status = policy.AddAccountRights(psid, &userRights); 177 const NTSTATUS status = policy.AddAccountRights(psid, &userRights);
180 if (status == 0) 178 if (status == 0)
181 res = true; 179 res = true;
182 // ULONG res = LsaNtStatusToWinError(status); 180 // ULONG res = LsaNtStatusToWinError(status);
diff --git a/CPP/Windows/SecurityUtils.h b/CPP/Windows/SecurityUtils.h
index c0d7b12..4ef3939 100644
--- a/CPP/Windows/SecurityUtils.h
+++ b/CPP/Windows/SecurityUtils.h
@@ -1,7 +1,7 @@
1// Windows/SecurityUtils.h 1// Windows/SecurityUtils.h
2 2
3#ifndef __WINDOWS_SECURITY_UTILS_H 3#ifndef ZIP7_INC_WINDOWS_SECURITY_UTILS_H
4#define __WINDOWS_SECURITY_UTILS_H 4#define ZIP7_INC_WINDOWS_SECURITY_UTILS_H
5 5
6#include <NTSecAPI.h> 6#include <NTSecAPI.h>
7 7
@@ -20,7 +20,7 @@ typedef NTSTATUS (NTAPI *Func_LsaAddAccountRights)(LSA_HANDLE PolicyHandle,
20 20
21#define POLICY_FUNC_CALL(fff, str) \ 21#define POLICY_FUNC_CALL(fff, str) \
22 if (hModule == NULL) return MY_STATUS_NOT_IMPLEMENTED; \ 22 if (hModule == NULL) return MY_STATUS_NOT_IMPLEMENTED; \
23 Func_ ## fff v = (Func_ ## fff) (void(*)()) GetProcAddress(hModule, str); \ 23 const Func_ ## fff v = Z7_GET_PROC_ADDRESS(Func_ ## fff, hModule, str); \
24 if (!v) return MY_STATUS_NOT_IMPLEMENTED; \ 24 if (!v) return MY_STATUS_NOT_IMPLEMENTED; \
25 const NTSTATUS res = v 25 const NTSTATUS res = v
26 26
@@ -39,7 +39,7 @@ class CAccessToken
39{ 39{
40 HANDLE _handle; 40 HANDLE _handle;
41public: 41public:
42 CAccessToken(): _handle(NULL) {}; 42 CAccessToken(): _handle(NULL) {}
43 ~CAccessToken() { Close(); } 43 ~CAccessToken() { Close(); }
44 bool Close() 44 bool Close()
45 { 45 {
@@ -93,9 +93,9 @@ public:
93 CPolicy(): _handle(NULL) 93 CPolicy(): _handle(NULL)
94 { 94 {
95 #ifndef _UNICODE 95 #ifndef _UNICODE
96 hModule = GetModuleHandle(TEXT("Advapi32.dll")); 96 hModule = GetModuleHandle(TEXT("advapi32.dll"));
97 #endif 97 #endif
98 }; 98 }
99 ~CPolicy() { Close(); } 99 ~CPolicy() { Close(); }
100 100
101 NTSTATUS Open(PLSA_UNICODE_STRING systemName, PLSA_OBJECT_ATTRIBUTES objectAttributes, 101 NTSTATUS Open(PLSA_UNICODE_STRING systemName, PLSA_OBJECT_ATTRIBUTES objectAttributes,
diff --git a/CPP/Windows/Shell.cpp b/CPP/Windows/Shell.cpp
index 071833c..b2a3489 100644
--- a/CPP/Windows/Shell.cpp
+++ b/CPP/Windows/Shell.cpp
@@ -2,23 +2,50 @@
2 2
3#include "StdAfx.h" 3#include "StdAfx.h"
4 4
5/*
6#include <stdio.h>
7#include <string.h>
8*/
9
10#include "../Common/MyCom.h" 5#include "../Common/MyCom.h"
11#ifndef _UNICODE
12#include "../Common/StringConvert.h" 6#include "../Common/StringConvert.h"
13#endif
14 7
15#include "COM.h" 8#include "COM.h"
9#include "FileName.h"
10#include "MemoryGlobal.h"
16#include "Shell.h" 11#include "Shell.h"
17 12
18#ifndef _UNICODE 13#ifndef _UNICODE
19extern bool g_IsNT; 14extern bool g_IsNT;
20#endif 15#endif
21 16
17// MSVC6 and old SDK don't support this function:
18// #define LWSTDAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE
19// LWSTDAPI StrRetToStrW(STRRET *pstr, LPCITEMIDLIST pidl, LPWSTR *ppsz);
20
21// #define SHOW_DEBUG_SHELL
22
23#ifdef SHOW_DEBUG_SHELL
24
25#include "../Common/IntToString.h"
26
27static void Print_Number(UInt32 number, const char *s)
28{
29 AString s2;
30 s2.Add_UInt32(number);
31 s2.Add_Space();
32 s2 += s;
33 OutputDebugStringA(s2);
34}
35
36#define ODS(sz) { OutputDebugStringA(sz); }
37#define ODS_U(s) { OutputDebugStringW(s); }
38#define ODS_(op) { op; }
39
40#else
41
42#define ODS(sz)
43#define ODS_U(s)
44#define ODS_(op)
45
46#endif
47
48
22namespace NWindows { 49namespace NWindows {
23namespace NShell { 50namespace NShell {
24 51
@@ -28,12 +55,24 @@ namespace NShell {
28 55
29void CItemIDList::Free() 56void CItemIDList::Free()
30{ 57{
31 if (m_Object == NULL) 58 if (!m_Object)
32 return; 59 return;
60 /* DOCs:
61 SHGetMalloc was introduced in Windows 95 and Microsoft Windows NT 4.0,
62 but as of Windows 2000 it is no longer necessary.
63 In its place, programs can call the equivalent (and easier to use) CoTaskMemAlloc and CoTaskMemFree.
64 Description from oldnewthings:
65 shell functions could work without COM (if OLE32.DLL is not loaded),
66 but now if OLE32.DLL is loaded, then shell functions and com functions do same things.
67 22.02: so we use OLE32.DLL function to free memory:
68 */
69 /*
33 CMyComPtr<IMalloc> shellMalloc; 70 CMyComPtr<IMalloc> shellMalloc;
34 if (::SHGetMalloc(&shellMalloc) != NOERROR) 71 if (::SHGetMalloc(&shellMalloc) != NOERROR)
35 throw 41099; 72 throw 41099;
36 shellMalloc->Free(m_Object); 73 shellMalloc->Free(m_Object);
74 */
75 CoTaskMemFree(m_Object);
37 m_Object = NULL; 76 m_Object = NULL;
38} 77}
39 78
@@ -70,9 +109,354 @@ CItemIDList& CItemIDList::operator=(const CItemIDList &object)
70} 109}
71*/ 110*/
72 111
112
113static HRESULT ReadUnicodeStrings(const wchar_t *p, size_t size, UStringVector &names)
114{
115 names.Clear();
116 const wchar_t *lim = p + size;
117 UString s;
118 /*
119 if (size == 0 || p[size - 1] != 0)
120 return E_INVALIDARG;
121 if (size == 1)
122 return S_OK;
123 if (p[size - 2] != 0)
124 return E_INVALIDARG;
125 */
126 for (;;)
127 {
128 const wchar_t *start = p;
129 for (;;)
130 {
131 if (p == lim) return E_INVALIDARG; // S_FALSE
132 if (*p++ == 0)
133 break;
134 }
135 const size_t num = (size_t)(p - start);
136 if (num == 1)
137 {
138 if (p != lim) return E_INVALIDARG; // S_FALSE
139 return S_OK;
140 }
141 s.SetFrom(start, (unsigned)(num - 1));
142 ODS_U(s)
143 names.Add(s);
144 // names.ReserveOnePosition();
145 // names.AddInReserved_Ptr_of_new(new UString((unsigned)num - 1, start));
146 }
147}
148
149
150static HRESULT ReadAnsiStrings(const char *p, size_t size, UStringVector &names)
151{
152 names.Clear();
153 AString name;
154 for (; size != 0; size--)
155 {
156 const char c = *p++;
157 if (c == 0)
158 {
159 if (name.IsEmpty())
160 return S_OK;
161 names.Add(GetUnicodeString(name));
162 name.Empty();
163 }
164 else
165 name += c;
166 }
167 return E_INVALIDARG;
168}
169
170
171#define INIT_FORMATETC_HGLOBAL(type) { (type), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }
172
173static HRESULT DataObject_GetData_HGLOBAL(IDataObject *dataObject, CLIPFORMAT cf, NCOM::CStgMedium &medium)
174{
175 FORMATETC etc = INIT_FORMATETC_HGLOBAL(cf);
176 RINOK(dataObject->GetData(&etc, &medium))
177 if (medium.tymed != TYMED_HGLOBAL)
178 return E_INVALIDARG;
179 return S_OK;
180}
181
182static HRESULT DataObject_GetData_HDROP_Names(IDataObject *dataObject, UStringVector &names)
183{
184 names.Clear();
185 NCOM::CStgMedium medium;
186
187 /* Win10 : if (dataObject) is from IContextMenu::Initialize() and
188 if (len_of_path >= MAX_PATH (260) for some file in data object)
189 {
190 GetData() returns HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)
191 "The data area passed to a system call is too small",
192 Is there a way to fix this code for long paths?
193 } */
194
195 RINOK(DataObject_GetData_HGLOBAL(dataObject, CF_HDROP, medium))
196 const size_t blockSize = GlobalSize(medium.hGlobal);
197 if (blockSize < sizeof(DROPFILES))
198 return E_INVALIDARG;
199 NMemory::CGlobalLock dropLock(medium.hGlobal);
200 const DROPFILES *dropFiles = (const DROPFILES *)dropLock.GetPointer();
201 if (!dropFiles)
202 return E_INVALIDARG;
203 if (blockSize < dropFiles->pFiles
204 || dropFiles->pFiles < sizeof(DROPFILES)
205 // || dropFiles->pFiles != sizeof(DROPFILES)
206 )
207 return E_INVALIDARG;
208 const size_t size = blockSize - dropFiles->pFiles;
209 const void *namesData = (const Byte *)(const void *)dropFiles + dropFiles->pFiles;
210 HRESULT hres;
211 if (dropFiles->fWide)
212 {
213 if (size % sizeof(wchar_t) != 0)
214 return E_INVALIDARG;
215 hres = ReadUnicodeStrings((const wchar_t *)namesData, size / sizeof(wchar_t), names);
216 }
217 else
218 hres = ReadAnsiStrings((const char *)namesData, size, names);
219
220 ODS_(Print_Number(names.Size(), "DataObject_GetData_HDROP_Names"))
221 return hres;
222}
223
224
225
226// CF_IDLIST:
227#define MYWIN_CFSTR_SHELLIDLIST TEXT("Shell IDList Array")
228
229typedef struct
230{
231 UINT cidl;
232 UINT aoffset[1];
233} MYWIN_CIDA;
234/*
235 cidl : number of PIDLs that are being transferred, not including the parent folder.
236 aoffset : An array of offsets, relative to the beginning of this structure.
237 aoffset[0] - fully qualified PIDL of a parent folder.
238 If this PIDL is empty, the parent folder is the desktop.
239 aoffset[1] ... aoffset[cidl] : offset to one of the PIDLs to be transferred.
240 All of these PIDLs are relative to the PIDL of the parent folder.
241*/
242
243static HRESULT DataObject_GetData_IDLIST(IDataObject *dataObject, UStringVector &names)
244{
245 names.Clear();
246 NCOM::CStgMedium medium;
247 RINOK(DataObject_GetData_HGLOBAL(dataObject, (CLIPFORMAT)
248 RegisterClipboardFormat(MYWIN_CFSTR_SHELLIDLIST), medium))
249 const size_t blockSize = GlobalSize(medium.hGlobal);
250 if (blockSize < sizeof(MYWIN_CIDA) || blockSize >= (UInt32)((UInt32)0 - 1))
251 return E_INVALIDARG;
252 NMemory::CGlobalLock dropLock(medium.hGlobal);
253 const MYWIN_CIDA *cida = (const MYWIN_CIDA *)dropLock.GetPointer();
254 if (!cida)
255 return E_INVALIDARG;
256 if (cida->cidl == 0)
257 {
258 // is it posssible to have no selected items?
259 // it's unexpected case.
260 return E_INVALIDARG;
261 }
262 if (cida->cidl >= (blockSize - (UInt32)sizeof(MYWIN_CIDA)) / sizeof(UINT))
263 return E_INVALIDARG;
264 const UInt32 start = cida->cidl * (UInt32)sizeof(UINT) + (UInt32)sizeof(MYWIN_CIDA);
265
266 STRRET strret;
267 CMyComPtr<IShellFolder> parentFolder;
268 {
269 const UINT offset = cida->aoffset[0];
270 if (offset < start || offset >= blockSize
271 // || offset != start
272 )
273 return E_INVALIDARG;
274
275 CMyComPtr<IShellFolder> desktopFolder;
276 RINOK(::SHGetDesktopFolder(&desktopFolder))
277 if (!desktopFolder)
278 return E_FAIL;
279
280 LPCITEMIDLIST const lpcItem = (LPCITEMIDLIST)(const void *)((const Byte *)cida + offset);
281
282 #ifdef SHOW_DEBUG_SHELL
283 {
284 const HRESULT res = desktopFolder->GetDisplayNameOf(
285 lpcItem, SHGDN_FORPARSING, &strret);
286 if (res == S_OK && strret.uType == STRRET_WSTR)
287 {
288 ODS_U(strret.pOleStr)
289 /* if lpcItem is empty, the path will be
290 "C:\Users\user_name\Desktop"
291 if lpcItem is "My Computer" folder, the path will be
292 "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" */
293 CoTaskMemFree(strret.pOleStr);
294 }
295 }
296 #endif
297
298 RINOK(desktopFolder->BindToObject(lpcItem,
299 NULL, IID_IShellFolder, (void **)&parentFolder))
300 if (!parentFolder)
301 return E_FAIL;
302 }
303
304 names.ClearAndReserve(cida->cidl);
305 UString path;
306
307 // for (int y = 0; y < 1; y++) // for debug
308 for (unsigned i = 1; i <= cida->cidl; i++)
309 {
310 const UINT offset = cida->aoffset[i];
311 if (offset < start || offset >= blockSize)
312 return E_INVALIDARG;
313 const void *p = (const Byte *)(const void *)cida + offset;
314 /* ITEMIDLIST of file can contain more than one SHITEMID item.
315 In win10 only SHGDN_FORPARSING returns path that contains
316 all path parts related to parts of ITEMIDLIST.
317 So we can use only SHGDN_FORPARSING here.
318 Don't use (SHGDN_INFOLDER)
319 Don't use (SHGDN_INFOLDER | SHGDN_FORPARSING)
320 */
321 RINOK(parentFolder->GetDisplayNameOf((LPCITEMIDLIST)p, SHGDN_FORPARSING, &strret))
322
323 /*
324 // MSVC6 and old SDK do not support StrRetToStrW().
325 LPWSTR lpstr;
326 RINOK (StrRetToStrW(&strret, NULL, &lpstr))
327 ODS_U(lpstr)
328 path = lpstr;
329 CoTaskMemFree(lpstr);
330 */
331 if (strret.uType != STRRET_WSTR)
332 return E_INVALIDARG;
333 ODS_U(strret.pOleStr)
334 path = strret.pOleStr;
335 // the path could have super path prefix "\\\\?\\"
336 // we can remove super path prefix here, if we don't need that prefix
337 #ifdef Z7_LONG_PATH
338 // we remove super prefix, if we can work without that prefix
339 NFile::NName::If_IsSuperPath_RemoveSuperPrefix(path);
340 #endif
341 names.AddInReserved(path);
342 CoTaskMemFree(strret.pOleStr);
343 }
344
345 ODS_(Print_Number(cida->cidl, "CFSTR_SHELLIDLIST END"))
346 return S_OK;
347}
348
349
350HRESULT DataObject_GetData_HDROP_or_IDLIST_Names(IDataObject *dataObject, UStringVector &paths)
351{
352 ODS("-- DataObject_GetData_HDROP_or_IDLIST_Names START")
353 HRESULT hres = NShell::DataObject_GetData_HDROP_Names(dataObject, paths);
354 // if (hres == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
355 if (hres != S_OK)
356 {
357 ODS("-- DataObject_GetData_IDLIST START")
358 // for (int y = 0; y < 10000; y++) // for debug
359 hres = NShell::DataObject_GetData_IDLIST(dataObject, paths);
360 }
361 ODS("-- DataObject_GetData_HDROP_or_IDLIST_Names END")
362 return hres;
363}
364
365
366
367// #if (NTDDI_VERSION >= NTDDI_VISTA)
368typedef struct
369{
370 UINT cItems; // number of items in rgdwFileAttributes array
371 DWORD dwSumFileAttributes; // all of the attributes ORed together
372 DWORD dwProductFileAttributes; // all of the attributes ANDed together
373 DWORD rgdwFileAttributes[1]; // array
374} MYWIN_FILE_ATTRIBUTES_ARRAY;
375
376#define MYWIN_CFSTR_FILE_ATTRIBUTES_ARRAY TEXT("File Attributes Array")
377
378HRESULT DataObject_GetData_FILE_ATTRS(IDataObject *dataObject, CFileAttribs &attribs)
379{
380 attribs.Clear();
381 NCOM::CStgMedium medium;
382 RINOK(DataObject_GetData_HGLOBAL(dataObject, (CLIPFORMAT)
383 RegisterClipboardFormat(MYWIN_CFSTR_FILE_ATTRIBUTES_ARRAY), medium))
384 const size_t blockSize = GlobalSize(medium.hGlobal);
385 if (blockSize < sizeof(MYWIN_FILE_ATTRIBUTES_ARRAY))
386 return E_INVALIDARG;
387 NMemory::CGlobalLock dropLock(medium.hGlobal);
388 const MYWIN_FILE_ATTRIBUTES_ARRAY *faa = (const MYWIN_FILE_ATTRIBUTES_ARRAY *)dropLock.GetPointer();
389 if (!faa)
390 return E_INVALIDARG;
391 const unsigned numFiles = faa->cItems;
392 if (numFiles == 0)
393 {
394 // is it posssible to have empty array here?
395 return E_INVALIDARG;
396 }
397 if ((blockSize - (sizeof(MYWIN_FILE_ATTRIBUTES_ARRAY) - sizeof(DWORD)))
398 / sizeof(DWORD) != numFiles)
399 return E_INVALIDARG;
400 // attribs.Sum = faa->dwSumFileAttributes;
401 // attribs.Product = faa->dwProductFileAttributes;
402 // attribs.Vals.SetFromArray(faa->rgdwFileAttributes, numFiles);
403 // attribs.IsDirVector.ClearAndSetSize(numFiles);
404
405 if ((faa->dwSumFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
406 {
407 /* in win10: if selected items are volumes (c:\, d:\ ..) in My Compter,
408 all items have FILE_ATTRIBUTE_DIRECTORY attribute
409 ntfs volume also have FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM
410 udf volume: FILE_ATTRIBUTE_READONLY
411 dvd-rom device: (-1) : all bits are set
412 */
413 const DWORD *attr = faa->rgdwFileAttributes;
414 // DWORD product = (UInt32)0 - 1, sum = 0;
415 for (unsigned i = 0; i < numFiles; i++)
416 {
417 if (attr[i] & FILE_ATTRIBUTE_DIRECTORY)
418 {
419 // attribs.ThereAreDirs = true;
420 attribs.FirstDirIndex = (int)i;
421 break;
422 }
423 // attribs.IsDirVector[i] = (attr[i] & FILE_ATTRIBUTE_DIRECTORY) != 0;
424 // product &= v;
425 // sum |= v;
426 }
427 // ODS_(Print_Number(product, "Product calc FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names"))
428 // ODS_(Print_Number(sum, "Sum calc FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names"))
429 }
430 // ODS_(Print_Number(attribs.Product, "Product FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names"))
431 // ODS_(Print_Number(attribs.Sum, "Sum FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names"))
432 ODS_(Print_Number(numFiles, "FILE_ATTRIBUTES_ARRAY ==== DataObject_GetData_HDROP_Names"))
433 return S_OK;
434}
435
436
73///////////////////////////// 437/////////////////////////////
74// CDrop 438// CDrop
75 439
440/*
441 win10:
442 DragQueryFile() implementation code is not effective because
443 there is no pointer inside DROP internal file list, so
444 DragQueryFile(fileIndex) runs all names in range [0, fileIndex].
445 DragQueryFile(,, buf, bufSize)
446 if (buf == NULL) by spec
447 {
448 returns value is the required size
449 in characters, of the buffer, not including the terminating null character
450 tests show that if (bufSize == 0), then it also returns required size.
451 }
452 if (bufSize != NULL)
453 {
454 returns: the count of the characters copied, not including null character.
455 win10: null character is also copied at position buf[ret_count];
456 }
457*/
458
459/*
76void CDrop::Attach(HDROP object) 460void CDrop::Attach(HDROP object)
77{ 461{
78 Free(); 462 Free();
@@ -92,56 +476,133 @@ UINT CDrop::QueryCountOfFiles()
92 return QueryFile(0xFFFFFFFF, (LPTSTR)NULL, 0); 476 return QueryFile(0xFFFFFFFF, (LPTSTR)NULL, 0);
93} 477}
94 478
95UString CDrop::QueryFileName(UINT fileIndex) 479void CDrop::QueryFileName(UINT fileIndex, UString &fileName)
96{ 480{
97 UString fileName;
98 #ifndef _UNICODE 481 #ifndef _UNICODE
99 if (!g_IsNT) 482 if (!g_IsNT)
100 { 483 {
101 AString fileNameA; 484 AString fileNameA;
102 UINT bufferSize = QueryFile(fileIndex, (LPTSTR)NULL, 0); 485 const UINT len = QueryFile(fileIndex, (LPTSTR)NULL, 0);
103 const unsigned len = bufferSize + 2; 486 const UINT numCopied = QueryFile(fileIndex, fileNameA.GetBuf(len + 2), len + 2);
104 QueryFile(fileIndex, fileNameA.GetBuf(len), bufferSize + 1);
105 fileNameA.ReleaseBuf_CalcLen(len); 487 fileNameA.ReleaseBuf_CalcLen(len);
488 if (numCopied != len)
489 throw 20221223;
106 fileName = GetUnicodeString(fileNameA); 490 fileName = GetUnicodeString(fileNameA);
107 } 491 }
108 else 492 else
109 #endif 493 #endif
110 { 494 {
111 UINT bufferSize = QueryFile(fileIndex, (LPWSTR)NULL, 0); 495 // kReserve must be >= 3 for additional buffer size
112 const unsigned len = bufferSize + 2; 496 // safety and for optimal performance
113 QueryFile(fileIndex, fileName.GetBuf(len), bufferSize + 1); 497 const unsigned kReserve = 3;
498 {
499 unsigned len = 0;
500 wchar_t *buf = fileName.GetBuf_GetMaxAvail(len);
501 if (len >= kReserve)
502 {
503 const UINT numCopied = QueryFile(fileIndex, buf, len);
504 if (numCopied < len - 1)
505 {
506 // (numCopied < len - 1) case means that it have copied full string.
507 fileName.ReleaseBuf_CalcLen(numCopied);
508 return;
509 }
510 }
511 }
512 const UINT len = QueryFile(fileIndex, (LPWSTR)NULL, 0);
513 const UINT numCopied = QueryFile(fileIndex,
514 fileName.GetBuf(len + kReserve), len + kReserve);
114 fileName.ReleaseBuf_CalcLen(len); 515 fileName.ReleaseBuf_CalcLen(len);
516 if (numCopied != len)
517 throw 20221223;
115 } 518 }
116 return fileName;
117} 519}
118 520
521
119void CDrop::QueryFileNames(UStringVector &fileNames) 522void CDrop::QueryFileNames(UStringVector &fileNames)
120{ 523{
121 UINT numFiles = QueryCountOfFiles(); 524 UINT numFiles = QueryCountOfFiles();
122 /* 525
123 char s[100]; 526 Print_Number(numFiles, "\n====== CDrop::QueryFileNames START ===== \n");
124 sprintf(s, "QueryFileNames: %d files", numFiles); 527
125 OutputDebugStringA(s);
126 */
127 fileNames.ClearAndReserve(numFiles); 528 fileNames.ClearAndReserve(numFiles);
529 UString s;
128 for (UINT i = 0; i < numFiles; i++) 530 for (UINT i = 0; i < numFiles; i++)
129 { 531 {
130 const UString s2 = QueryFileName(i); 532 QueryFileName(i, s);
131 if (!s2.IsEmpty()) 533 if (!s.IsEmpty())
132 fileNames.AddInReserved(s2); 534 fileNames.AddInReserved(s);
133 /*
134 OutputDebugStringW(L"file ---");
135 OutputDebugStringW(s2);
136 */
137 } 535 }
536 Print_Number(numFiles, "\n====== CDrop::QueryFileNames END ===== \n");
537}
538*/
539
540
541// #if (NTDDI_VERSION >= NTDDI_VISTA)
542// SHGetPathFromIDListEx returns a win32 file system path for the item in the name space.
543typedef int Z7_WIN_GPFIDL_FLAGS;
544
545extern "C" {
546typedef BOOL (WINAPI * Func_SHGetPathFromIDListW)(LPCITEMIDLIST pidl, LPWSTR pszPath);
547typedef BOOL (WINAPI * Func_SHGetPathFromIDListEx)(LPCITEMIDLIST pidl, PWSTR pszPath, DWORD cchPath, Z7_WIN_GPFIDL_FLAGS uOpts);
138} 548}
139 549
550#ifndef _UNICODE
140 551
141bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path) 552bool GetPathFromIDList(LPCITEMIDLIST itemIDList, AString &path)
553{
554 path.Empty();
555 const unsigned len = MAX_PATH + 16;
556 const bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList, path.GetBuf(len)));
557 path.ReleaseBuf_CalcLen(len);
558 return result;
559}
560
561#endif
562
563bool GetPathFromIDList(LPCITEMIDLIST itemIDList, UString &path)
142{ 564{
143 const unsigned len = MAX_PATH * 2; 565 path.Empty();
566 unsigned len = MAX_PATH + 16;
567
568#ifdef _UNICODE
144 bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList, path.GetBuf(len))); 569 bool result = BOOLToBool(::SHGetPathFromIDList(itemIDList, path.GetBuf(len)));
570#else
571 const
572 Func_SHGetPathFromIDListW
573 shGetPathFromIDListW = Z7_GET_PROC_ADDRESS(
574 Func_SHGetPathFromIDListW, ::GetModuleHandleW(L"shell32.dll"),
575 "SHGetPathFromIDListW");
576 if (!shGetPathFromIDListW)
577 return false;
578 bool result = BOOLToBool(shGetPathFromIDListW(itemIDList, path.GetBuf(len)));
579#endif
580
581 if (!result)
582 {
583 ODS("==== GetPathFromIDList() SHGetPathFromIDList() returned false")
584 /* for long path we need SHGetPathFromIDListEx().
585 win10: SHGetPathFromIDListEx() for long path returns path with
586 with super path prefix "\\\\?\\". */
587 const
588 Func_SHGetPathFromIDListEx
589 func_SHGetPathFromIDListEx = Z7_GET_PROC_ADDRESS(
590 Func_SHGetPathFromIDListEx, ::GetModuleHandleW(L"shell32.dll"),
591 "SHGetPathFromIDListEx");
592 if (func_SHGetPathFromIDListEx)
593 {
594 ODS("==== GetPathFromIDList() (SHGetPathFromIDListEx)")
595 do
596 {
597 len *= 4;
598 result = BOOLToBool(func_SHGetPathFromIDListEx(itemIDList, path.GetBuf(len), len, 0));
599 if (result)
600 break;
601 }
602 while (len <= (1 << 16));
603 }
604 }
605
145 path.ReleaseBuf_CalcLen(len); 606 path.ReleaseBuf_CalcLen(len);
146 return result; 607 return result;
147} 608}
@@ -180,11 +641,16 @@ bool BrowseForFolder(HWND /* owner */, LPCTSTR /* title */,
180 641
181#else 642#else
182 643
644/* win10: SHBrowseForFolder() doesn't support long paths,
645 even if long path suppport is enabled in registry and in manifest.
646 and SHBrowseForFolder() doesn't support super path prefix "\\\\?\\". */
647
183bool BrowseForFolder(LPBROWSEINFO browseInfo, CSysString &resultPath) 648bool BrowseForFolder(LPBROWSEINFO browseInfo, CSysString &resultPath)
184{ 649{
650 resultPath.Empty();
185 NWindows::NCOM::CComInitializer comInitializer; 651 NWindows::NCOM::CComInitializer comInitializer;
186 LPITEMIDLIST itemIDList = ::SHBrowseForFolder(browseInfo); 652 LPITEMIDLIST itemIDList = ::SHBrowseForFolder(browseInfo);
187 if (itemIDList == NULL) 653 if (!itemIDList)
188 return false; 654 return false;
189 CItemIDList itemIDListHolder; 655 CItemIDList itemIDListHolder;
190 itemIDListHolder.Attach(itemIDList); 656 itemIDListHolder.Attach(itemIDList);
@@ -240,11 +706,18 @@ static bool BrowseForFolder(HWND owner, LPCTSTR title, UINT ulFlags,
240 browseInfo.lpszTitle = title; 706 browseInfo.lpszTitle = title;
241 // #endif 707 // #endif
242 browseInfo.ulFlags = ulFlags; 708 browseInfo.ulFlags = ulFlags;
243 browseInfo.lpfn = (initialFolder != NULL) ? BrowseCallbackProc : NULL; 709 browseInfo.lpfn = initialFolder ? BrowseCallbackProc : NULL;
244 browseInfo.lParam = (LPARAM)initialFolder; 710 browseInfo.lParam = (LPARAM)initialFolder;
245 return BrowseForFolder(&browseInfo, resultPath); 711 return BrowseForFolder(&browseInfo, resultPath);
246} 712}
247 713
714#ifdef Z7_OLD_WIN_SDK
715// ShlObj.h:
716#ifndef BIF_NEWDIALOGSTYLE
717#define BIF_NEWDIALOGSTYLE 0x0040
718#endif
719#endif
720
248bool BrowseForFolder(HWND owner, LPCTSTR title, 721bool BrowseForFolder(HWND owner, LPCTSTR title,
249 LPCTSTR initialFolder, CSysString &resultPath) 722 LPCTSTR initialFolder, CSysString &resultPath)
250{ 723{
@@ -259,38 +732,21 @@ bool BrowseForFolder(HWND owner, LPCTSTR title,
259#ifndef _UNICODE 732#ifndef _UNICODE
260 733
261extern "C" { 734extern "C" {
262typedef BOOL (WINAPI * Func_SHGetPathFromIDListW)(LPCITEMIDLIST pidl, LPWSTR pszPath);
263typedef LPITEMIDLIST (WINAPI * Func_SHBrowseForFolderW)(LPBROWSEINFOW lpbi); 735typedef LPITEMIDLIST (WINAPI * Func_SHBrowseForFolderW)(LPBROWSEINFOW lpbi);
264} 736}
265 737
266#define MY_CAST_FUNC (void(*)())
267// #define MY_CAST_FUNC
268
269bool GetPathFromIDList(LPCITEMIDLIST itemIDList, UString &path)
270{
271 path.Empty();
272 Func_SHGetPathFromIDListW shGetPathFromIDListW = (Func_SHGetPathFromIDListW)
273 MY_CAST_FUNC
274 ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHGetPathFromIDListW");
275 if (!shGetPathFromIDListW)
276 return false;
277 const unsigned len = MAX_PATH * 2;
278 bool result = BOOLToBool(shGetPathFromIDListW(itemIDList, path.GetBuf(len)));
279 path.ReleaseBuf_CalcLen(len);
280 return result;
281}
282
283
284static bool BrowseForFolder(LPBROWSEINFOW browseInfo, UString &resultPath) 738static bool BrowseForFolder(LPBROWSEINFOW browseInfo, UString &resultPath)
285{ 739{
286 NWindows::NCOM::CComInitializer comInitializer; 740 NWindows::NCOM::CComInitializer comInitializer;
287 Func_SHBrowseForFolderW shBrowseForFolderW = (Func_SHBrowseForFolderW) 741 const
288 MY_CAST_FUNC 742 Func_SHBrowseForFolderW
289 ::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHBrowseForFolderW"); 743 f_SHBrowseForFolderW = Z7_GET_PROC_ADDRESS(
290 if (!shBrowseForFolderW) 744 Func_SHBrowseForFolderW, ::GetModuleHandleW(L"shell32.dll"),
745 "SHBrowseForFolderW");
746 if (!f_SHBrowseForFolderW)
291 return false; 747 return false;
292 LPITEMIDLIST itemIDList = shBrowseForFolderW(browseInfo); 748 LPITEMIDLIST itemIDList = f_SHBrowseForFolderW(browseInfo);
293 if (itemIDList == NULL) 749 if (!itemIDList)
294 return false; 750 return false;
295 CItemIDList itemIDListHolder; 751 CItemIDList itemIDListHolder;
296 itemIDListHolder.Attach(itemIDList); 752 itemIDListHolder.Attach(itemIDList);
@@ -336,7 +792,7 @@ static bool BrowseForFolder(HWND owner, LPCWSTR title, UINT ulFlags,
336 browseInfo.pszDisplayName = displayName.GetBuf(MAX_PATH); 792 browseInfo.pszDisplayName = displayName.GetBuf(MAX_PATH);
337 browseInfo.lpszTitle = title; 793 browseInfo.lpszTitle = title;
338 browseInfo.ulFlags = ulFlags; 794 browseInfo.ulFlags = ulFlags;
339 browseInfo.lpfn = (initialFolder != NULL) ? BrowseCallbackProc2 : NULL; 795 browseInfo.lpfn = initialFolder ? BrowseCallbackProc2 : NULL;
340 browseInfo.lParam = (LPARAM)initialFolder; 796 browseInfo.lParam = (LPARAM)initialFolder;
341 return BrowseForFolder(&browseInfo, resultPath); 797 return BrowseForFolder(&browseInfo, resultPath);
342} 798}
diff --git a/CPP/Windows/Shell.h b/CPP/Windows/Shell.h
index de91d3f..b4cdb30 100644
--- a/CPP/Windows/Shell.h
+++ b/CPP/Windows/Shell.h
@@ -1,17 +1,22 @@
1// Windows/Shell.h 1// Windows/Shell.h
2 2
3#ifndef __WINDOWS_SHELL_H 3#ifndef ZIP7_WINDOWS_SHELL_H
4#define __WINDOWS_SHELL_H 4#define ZIP7_WINDOWS_SHELL_H
5 5
6#include "../Common/Common.h"
6#include "../Common/MyWindows.h" 7#include "../Common/MyWindows.h"
8#if defined(__MINGW32__) || defined(__MINGW64__)
9#include <shlobj.h>
10#else
7#include <ShlObj.h> 11#include <ShlObj.h>
12#endif
8 13
9#include "../Common/MyString.h" 14#include "../Common/MyString.h"
10 15
11#include "Defs.h" 16#include "Defs.h"
12 17
13namespace NWindows{ 18namespace NWindows {
14namespace NShell{ 19namespace NShell {
15 20
16///////////////////////// 21/////////////////////////
17// CItemIDList 22// CItemIDList
@@ -20,6 +25,7 @@ namespace NShell{
20class CItemIDList 25class CItemIDList
21{ 26{
22 LPITEMIDLIST m_Object; 27 LPITEMIDLIST m_Object;
28 Z7_CLASS_NO_COPY(CItemIDList)
23public: 29public:
24 CItemIDList(): m_Object(NULL) {} 30 CItemIDList(): m_Object(NULL) {}
25 // CItemIDList(LPCITEMIDLIST itemIDList); 31 // CItemIDList(LPCITEMIDLIST itemIDList);
@@ -49,6 +55,7 @@ public:
49///////////////////////////// 55/////////////////////////////
50// CDrop 56// CDrop
51 57
58/*
52class CDrop 59class CDrop
53{ 60{
54 HDROP m_Object; 61 HDROP m_Object;
@@ -63,22 +70,51 @@ public:
63 operator HDROP() { return m_Object;} 70 operator HDROP() { return m_Object;}
64 bool QueryPoint(LPPOINT point) 71 bool QueryPoint(LPPOINT point)
65 { return BOOLToBool(::DragQueryPoint(m_Object, point)); } 72 { return BOOLToBool(::DragQueryPoint(m_Object, point)); }
66 void Finish() { ::DragFinish(m_Object); } 73 void Finish()
67 UINT QueryFile(UINT fileIndex, LPTSTR fileName, UINT fileNameSize) 74 {
68 { return ::DragQueryFile(m_Object, fileIndex, fileName, fileNameSize); } 75 ::DragFinish(m_Object);
76 }
77 UINT QueryFile(UINT fileIndex, LPTSTR fileName, UINT bufSize)
78 { return ::DragQueryFile(m_Object, fileIndex, fileName, bufSize); }
69 #ifndef _UNICODE 79 #ifndef _UNICODE
70 UINT QueryFile(UINT fileIndex, LPWSTR fileName, UINT fileNameSize) 80 UINT QueryFile(UINT fileIndex, LPWSTR fileName, UINT bufSize)
71 { return ::DragQueryFileW(m_Object, fileIndex, fileName, fileNameSize); } 81 { return ::DragQueryFileW(m_Object, fileIndex, fileName, bufSize); }
72 #endif 82 #endif
73 UINT QueryCountOfFiles(); 83 UINT QueryCountOfFiles();
74 UString QueryFileName(UINT fileIndex); 84 void QueryFileName(UINT fileIndex, UString &fileName);
75 void QueryFileNames(UStringVector &fileNames); 85 void QueryFileNames(UStringVector &fileNames);
76}; 86};
77 87*/
78#endif 88#endif
79 89
80///////////////////////////// 90struct CFileAttribs
81// Functions 91{
92 int FirstDirIndex;
93 // DWORD Sum;
94 // DWORD Product;
95 // CRecordVector<DWORD> Vals;
96 // CRecordVector<bool> IsDirVector;
97
98 CFileAttribs()
99 {
100 Clear();
101 }
102
103 void Clear()
104 {
105 FirstDirIndex = -1;
106 // Sum = 0;
107 // Product = 0;
108 // IsDirVector.Clear();
109 }
110};
111
112
113/* read pathnames from HDROP or SHELLIDLIST.
114 The parser can return E_INVALIDARG, if there is some unexpected data in dataObject */
115HRESULT DataObject_GetData_HDROP_or_IDLIST_Names(IDataObject *dataObject, UStringVector &names);
116
117HRESULT DataObject_GetData_FILE_ATTRS(IDataObject *dataObject, CFileAttribs &attribs);
82 118
83bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path); 119bool GetPathFromIDList(LPCITEMIDLIST itemIDList, CSysString &path);
84bool BrowseForFolder(LPBROWSEINFO lpbi, CSysString &resultPath); 120bool BrowseForFolder(LPBROWSEINFO lpbi, CSysString &resultPath);
diff --git a/CPP/Windows/StdAfx.h b/CPP/Windows/StdAfx.h
index 1766dfa..bd5084f 100644
--- a/CPP/Windows/StdAfx.h
+++ b/CPP/Windows/StdAfx.h
@@ -1,7 +1,11 @@
1// StdAfx.h 1// StdAfx.h
2 2
3#ifndef __STDAFX_H 3#ifndef ZIP7_INC_STDAFX_H
4#define __STDAFX_H 4#define ZIP7_INC_STDAFX_H
5
6#if defined(_MSC_VER) && _MSC_VER >= 1800
7#pragma warning(disable : 4464) // relative include path contains '..'
8#endif
5 9
6#include "../Common/Common.h" 10#include "../Common/Common.h"
7 11
diff --git a/CPP/Windows/Synchronization.cpp b/CPP/Windows/Synchronization.cpp
index fbf919d..d5542af 100644
--- a/CPP/Windows/Synchronization.cpp
+++ b/CPP/Windows/Synchronization.cpp
@@ -19,6 +19,30 @@ namespace NSynchronization {
19DWORD WaitForMultipleObjects(DWORD count, const HANDLE *handles, BOOL wait_all, DWORD timeout); 19DWORD WaitForMultipleObjects(DWORD count, const HANDLE *handles, BOOL wait_all, DWORD timeout);
20*/ 20*/
21 21
22/* clang: we need to place some virtual functions in cpp file to rid off the warning:
23 'CBaseHandle_WFMO' has no out-of-line virtual method definitions;
24 its vtable will be emitted in every translation unit */
25CBaseHandle_WFMO::~CBaseHandle_WFMO()
26{
27}
28
29bool CBaseEvent_WFMO::IsSignaledAndUpdate()
30{
31 if (this->_state == false)
32 return false;
33 if (this->_manual_reset == false)
34 this->_state = false;
35 return true;
36}
37
38bool CSemaphore_WFMO::IsSignaledAndUpdate()
39{
40 if (this->_count == 0)
41 return false;
42 this->_count--;
43 return true;
44}
45
22DWORD WINAPI WaitForMultiObj_Any_Infinite(DWORD count, const CHandle_WFMO *handles) 46DWORD WINAPI WaitForMultiObj_Any_Infinite(DWORD count, const CHandle_WFMO *handles)
23{ 47{
24 if (count < 1) 48 if (count < 1)
diff --git a/CPP/Windows/Synchronization.h b/CPP/Windows/Synchronization.h
index 7d2e8d2..afd03d2 100644
--- a/CPP/Windows/Synchronization.h
+++ b/CPP/Windows/Synchronization.h
@@ -1,7 +1,7 @@
1// Windows/Synchronization.h 1// Windows/Synchronization.h
2 2
3#ifndef __WINDOWS_SYNCHRONIZATION_H 3#ifndef ZIP7_INC_WINDOWS_SYNCHRONIZATION_H
4#define __WINDOWS_SYNCHRONIZATION_H 4#define ZIP7_INC_WINDOWS_SYNCHRONIZATION_H
5 5
6#include "../../C/Threads.h" 6#include "../../C/Threads.h"
7 7
@@ -32,14 +32,14 @@ public:
32 WRes Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES sa = NULL) 32 WRes Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES sa = NULL)
33 { 33 {
34 _object = ::CreateEvent(sa, BoolToBOOL(manualReset), BoolToBOOL(initiallyOwn), name); 34 _object = ::CreateEvent(sa, BoolToBOOL(manualReset), BoolToBOOL(initiallyOwn), name);
35 if (name == NULL && _object != 0) 35 if (name == NULL && _object != NULL)
36 return 0; 36 return 0;
37 return ::GetLastError(); 37 return ::GetLastError();
38 } 38 }
39 WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) 39 WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
40 { 40 {
41 _object = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name); 41 _object = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name);
42 if (_object != 0) 42 if (_object != NULL)
43 return 0; 43 return 0;
44 return ::GetLastError(); 44 return ::GetLastError();
45 } 45 }
@@ -227,8 +227,8 @@ public:
227 } 227 }
228 WRes Create() 228 WRes Create()
229 { 229 {
230 RINOK(::pthread_mutex_init(&_mutex, 0)); 230 RINOK(::pthread_mutex_init(&_mutex, NULL))
231 WRes ret = ::pthread_cond_init(&_cond, 0); 231 const WRes ret = ::pthread_cond_init(&_cond, NULL);
232 _isValid = 1; 232 _isValid = 1;
233 return ret; 233 return ret;
234 } 234 }
@@ -246,8 +246,8 @@ public:
246 } 246 }
247 WRes LeaveAndSignal() 247 WRes LeaveAndSignal()
248 { 248 {
249 WRes res1 = ::pthread_cond_broadcast(&_cond); 249 const WRes res1 = ::pthread_cond_broadcast(&_cond);
250 WRes res2 = ::pthread_mutex_unlock(&_mutex); 250 const WRes res2 = ::pthread_mutex_unlock(&_mutex);
251 return (res2 ? res2 : res1); 251 return (res2 ? res2 : res1);
252 } 252 }
253}; 253};
@@ -268,6 +268,7 @@ struct CBaseHandle_WFMO MY_UNCOPYABLE
268 CSynchro *_sync; 268 CSynchro *_sync;
269 269
270 CBaseHandle_WFMO(): _sync(NULL) {} 270 CBaseHandle_WFMO(): _sync(NULL) {}
271 virtual ~CBaseHandle_WFMO();
271 272
272 operator CHandle_WFMO() { return this; } 273 operator CHandle_WFMO() { return this; }
273 virtual bool IsSignaledAndUpdate() = 0; 274 virtual bool IsSignaledAndUpdate() = 0;
@@ -283,7 +284,7 @@ public:
283 284
284 // bool IsCreated() { return (this->_sync != NULL); } 285 // bool IsCreated() { return (this->_sync != NULL); }
285 // CBaseEvent_WFMO() { ; } 286 // CBaseEvent_WFMO() { ; }
286 ~CBaseEvent_WFMO() { Close(); } 287 // ~CBaseEvent_WFMO() Z7_override { Close(); }
287 288
288 WRes Close() { this->_sync = NULL; return 0; } 289 WRes Close() { this->_sync = NULL; return 0; }
289 290
@@ -299,37 +300,30 @@ public:
299 300
300 WRes Set() 301 WRes Set()
301 { 302 {
302 RINOK(this->_sync->Enter()); 303 RINOK(this->_sync->Enter())
303 this->_state = true; 304 this->_state = true;
304 return this->_sync->LeaveAndSignal(); 305 return this->_sync->LeaveAndSignal();
305 } 306 }
306 307
307 WRes Reset() 308 WRes Reset()
308 { 309 {
309 RINOK(this->_sync->Enter()); 310 RINOK(this->_sync->Enter())
310 this->_state = false; 311 this->_state = false;
311 return this->_sync->Leave(); 312 return this->_sync->Leave();
312 } 313 }
313 314
314 virtual bool IsSignaledAndUpdate() 315 virtual bool IsSignaledAndUpdate() Z7_override;
315 {
316 if (this->_state == false)
317 return false;
318 if (this->_manual_reset == false)
319 this->_state = false;
320 return true;
321 }
322}; 316};
323 317
324 318
325class CManualResetEvent_WFMO: public CBaseEvent_WFMO 319class CManualResetEvent_WFMO Z7_final: public CBaseEvent_WFMO
326{ 320{
327public: 321public:
328 WRes Create(CSynchro *sync, bool initiallyOwn = false) { return CBaseEvent_WFMO::Create(sync, true, initiallyOwn); } 322 WRes Create(CSynchro *sync, bool initiallyOwn = false) { return CBaseEvent_WFMO::Create(sync, true, initiallyOwn); }
329}; 323};
330 324
331 325
332class CAutoResetEvent_WFMO: public CBaseEvent_WFMO 326class CAutoResetEvent_WFMO Z7_final: public CBaseEvent_WFMO
333{ 327{
334public: 328public:
335 WRes Create(CSynchro *sync) { return CBaseEvent_WFMO::Create(sync, false, false); } 329 WRes Create(CSynchro *sync) { return CBaseEvent_WFMO::Create(sync, false, false); }
@@ -340,7 +334,7 @@ public:
340}; 334};
341 335
342 336
343class CSemaphore_WFMO : public CBaseHandle_WFMO 337class CSemaphore_WFMO Z7_final: public CBaseHandle_WFMO
344{ 338{
345 UInt32 _count; 339 UInt32 _count;
346 UInt32 _maxCount; 340 UInt32 _maxCount;
@@ -365,11 +359,11 @@ public:
365 if (releaseCount < 1) 359 if (releaseCount < 1)
366 return EINVAL; 360 return EINVAL;
367 361
368 RINOK(this->_sync->Enter()); 362 RINOK(this->_sync->Enter())
369 UInt32 newCount = this->_count + releaseCount; 363 UInt32 newCount = this->_count + releaseCount;
370 if (newCount > this->_maxCount) 364 if (newCount > this->_maxCount)
371 { 365 {
372 RINOK(this->_sync->Leave()); 366 RINOK(this->_sync->Leave())
373 return ERROR_TOO_MANY_POSTS; // EINVAL 367 return ERROR_TOO_MANY_POSTS; // EINVAL
374 } 368 }
375 this->_count = newCount; 369 this->_count = newCount;
@@ -377,13 +371,7 @@ public:
377 return this->_sync->LeaveAndSignal(); 371 return this->_sync->LeaveAndSignal();
378 } 372 }
379 373
380 virtual bool IsSignaledAndUpdate() 374 virtual bool IsSignaledAndUpdate() Z7_override;
381 {
382 if (this->_count == 0)
383 return false;
384 this->_count--;
385 return true;
386 }
387}; 375};
388 376
389#endif // _WIN32 377#endif // _WIN32
diff --git a/CPP/Windows/System.cpp b/CPP/Windows/System.cpp
index 3a14b77..dbe287a 100644
--- a/CPP/Windows/System.cpp
+++ b/CPP/Windows/System.cpp
@@ -4,6 +4,7 @@
4 4
5#ifndef _WIN32 5#ifndef _WIN32
6#include <unistd.h> 6#include <unistd.h>
7#include <limits.h>
7#ifdef __APPLE__ 8#ifdef __APPLE__
8#include <sys/sysctl.h> 9#include <sys/sysctl.h>
9#else 10#else
@@ -74,7 +75,7 @@ BOOL CProcessAffinity::Get()
74 return TRUE; 75 return TRUE;
75 */ 76 */
76 77
77 #ifdef _7ZIP_AFFINITY_SUPPORTED 78 #ifdef Z7_AFFINITY_SUPPORTED
78 79
79 // numSysThreads = sysconf(_SC_NPROCESSORS_ONLN); // The number of processors currently online 80 // numSysThreads = sysconf(_SC_NPROCESSORS_ONLN); // The number of processors currently online
80 if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) != 0) 81 if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) != 0)
@@ -93,7 +94,7 @@ BOOL CProcessAffinity::Get()
93 94
94UInt32 GetNumberOfProcessors() 95UInt32 GetNumberOfProcessors()
95{ 96{
96 #ifndef _7ZIP_ST 97 #ifndef Z7_ST
97 long n = sysconf(_SC_NPROCESSORS_CONF); // The number of processors configured 98 long n = sysconf(_SC_NPROCESSORS_CONF); // The number of processors configured
98 if (n < 1) 99 if (n < 1)
99 n = 1; 100 n = 1;
@@ -110,7 +111,8 @@ UInt32 GetNumberOfProcessors()
110 111
111#ifndef UNDER_CE 112#ifndef UNDER_CE
112 113
113#if !defined(_WIN64) && defined(__GNUC__) 114#if !defined(_WIN64) && \
115 (defined(__MINGW32_VERSION) || defined(Z7_OLD_WIN_SDK))
114 116
115typedef struct _MY_MEMORYSTATUSEX { 117typedef struct _MY_MEMORYSTATUSEX {
116 DWORD dwLength; 118 DWORD dwLength;
@@ -131,7 +133,7 @@ typedef struct _MY_MEMORYSTATUSEX {
131 133
132#endif 134#endif
133 135
134typedef BOOL (WINAPI *GlobalMemoryStatusExP)(MY_LPMEMORYSTATUSEX lpBuffer); 136typedef BOOL (WINAPI *Func_GlobalMemoryStatusEx)(MY_LPMEMORYSTATUSEX lpBuffer);
135 137
136#endif // !UNDER_CE 138#endif // !UNDER_CE
137 139
@@ -155,9 +157,11 @@ bool GetRamSize(UInt64 &size)
155 #else 157 #else
156 158
157 #ifndef UNDER_CE 159 #ifndef UNDER_CE
158 GlobalMemoryStatusExP globalMemoryStatusEx = (GlobalMemoryStatusExP) 160 const
159 (void *)::GetProcAddress(::GetModuleHandleA("kernel32.dll"), "GlobalMemoryStatusEx"); 161 Func_GlobalMemoryStatusEx fn = Z7_GET_PROC_ADDRESS(
160 if (globalMemoryStatusEx && globalMemoryStatusEx(&stat)) 162 Func_GlobalMemoryStatusEx, ::GetModuleHandleA("kernel32.dll"),
163 "GlobalMemoryStatusEx");
164 if (fn && fn(&stat))
161 { 165 {
162 size = MyMin(stat.ullTotalVirtual, stat.ullTotalPhys); 166 size = MyMin(stat.ullTotalVirtual, stat.ullTotalPhys);
163 return true; 167 return true;
@@ -231,4 +235,44 @@ bool GetRamSize(UInt64 &size)
231 235
232#endif 236#endif
233 237
238
239unsigned long Get_File_OPEN_MAX()
240{
241 #ifdef _WIN32
242 return (1 << 24) - (1 << 16); // ~16M handles
243 #else
244 // some linux versions have default open file limit for user process of 1024 files.
245 long n = sysconf(_SC_OPEN_MAX);
246 // n = -1; // for debug
247 // n = 9; // for debug
248 if (n < 1)
249 {
250 // n = OPEN_MAX; // ???
251 // n = FOPEN_MAX; // = 16 : <stdio.h>
252 #ifdef _POSIX_OPEN_MAX
253 n = _POSIX_OPEN_MAX; // = 20 : <limits.h>
254 #else
255 n = 30; // our limit
256 #endif
257 }
258 return (unsigned long)n;
259 #endif
260}
261
262unsigned Get_File_OPEN_MAX_Reduced_for_3_tasks()
263{
264 unsigned long numFiles_OPEN_MAX = NSystem::Get_File_OPEN_MAX();
265 const unsigned delta = 10; // the reserve for another internal needs of process
266 if (numFiles_OPEN_MAX > delta)
267 numFiles_OPEN_MAX -= delta;
268 else
269 numFiles_OPEN_MAX = 1;
270 numFiles_OPEN_MAX /= 3; // we suppose that we have up to 3 tasks in total for multiple file processing
271 numFiles_OPEN_MAX = MyMax(numFiles_OPEN_MAX, (unsigned long)3);
272 unsigned n = (UInt32)(UInt32)-1;
273 if (n > numFiles_OPEN_MAX)
274 n = (unsigned)numFiles_OPEN_MAX;
275 return n;
276}
277
234}} 278}}
diff --git a/CPP/Windows/System.h b/CPP/Windows/System.h
index 23cb0da..0650007 100644
--- a/CPP/Windows/System.h
+++ b/CPP/Windows/System.h
@@ -1,7 +1,7 @@
1// Windows/System.h 1// Windows/System.h
2 2
3#ifndef __WINDOWS_SYSTEM_H 3#ifndef ZIP7_INC_WINDOWS_SYSTEM_H
4#define __WINDOWS_SYSTEM_H 4#define ZIP7_INC_WINDOWS_SYSTEM_H
5 5
6#ifndef _WIN32 6#ifndef _WIN32
7// #include <sched.h> 7// #include <sched.h>
@@ -9,11 +9,11 @@
9#endif 9#endif
10 10
11#include "../Common/MyTypes.h" 11#include "../Common/MyTypes.h"
12#include "../Common/MyWindows.h"
12 13
13namespace NWindows { 14namespace NWindows {
14namespace NSystem { 15namespace NSystem {
15 16
16
17#ifdef _WIN32 17#ifdef _WIN32
18 18
19UInt32 CountAffinity(DWORD_PTR mask); 19UInt32 CountAffinity(DWORD_PTR mask);
@@ -64,7 +64,7 @@ struct CProcessAffinity
64 UInt32 GetNumSystemThreads() const { return (UInt32)numSysThreads; } 64 UInt32 GetNumSystemThreads() const { return (UInt32)numSysThreads; }
65 BOOL Get(); 65 BOOL Get();
66 66
67 #ifdef _7ZIP_AFFINITY_SUPPORTED 67 #ifdef Z7_AFFINITY_SUPPORTED
68 68
69 CCpuSet cpu_set; 69 CCpuSet cpu_set;
70 70
@@ -86,7 +86,7 @@ struct CProcessAffinity
86 return sched_setaffinity(0, sizeof(cpu_set), &cpu_set) == 0; 86 return sched_setaffinity(0, sizeof(cpu_set), &cpu_set) == 0;
87 } 87 }
88 88
89 #else 89 #else // Z7_AFFINITY_SUPPORTED
90 90
91 void InitST() 91 void InitST()
92 { 92 {
@@ -114,16 +114,19 @@ struct CProcessAffinity
114 return FALSE; 114 return FALSE;
115 } 115 }
116 116
117 #endif 117 #endif // Z7_AFFINITY_SUPPORTED
118}; 118};
119 119
120#endif 120#endif // _WIN32
121 121
122 122
123UInt32 GetNumberOfProcessors(); 123UInt32 GetNumberOfProcessors();
124 124
125bool GetRamSize(UInt64 &size); // returns false, if unknown ram size 125bool GetRamSize(UInt64 &size); // returns false, if unknown ram size
126 126
127unsigned long Get_File_OPEN_MAX();
128unsigned Get_File_OPEN_MAX_Reduced_for_3_tasks();
129
127}} 130}}
128 131
129#endif 132#endif
diff --git a/CPP/Windows/SystemInfo.cpp b/CPP/Windows/SystemInfo.cpp
index d882a8e..6bafc80 100644
--- a/CPP/Windows/SystemInfo.cpp
+++ b/CPP/Windows/SystemInfo.cpp
@@ -102,38 +102,44 @@ static void PrintHex(AString &s, UInt64 v)
102 102
103#ifdef MY_CPU_X86_OR_AMD64 103#ifdef MY_CPU_X86_OR_AMD64
104 104
105Z7_NO_INLINE
105static void PrintCpuChars(AString &s, UInt32 v) 106static void PrintCpuChars(AString &s, UInt32 v)
106{ 107{
107 for (int j = 0; j < 4; j++) 108 for (unsigned j = 0; j < 4; j++)
108 { 109 {
109 Byte b = (Byte)(v & 0xFF); 110 Byte b = (Byte)(v & 0xFF);
110 v >>= 8; 111 v >>= 8;
111 if (b == 0) 112 if (b == 0)
112 break; 113 break;
113 s += (char)b; 114 if (b >= 0x20 && b <= 0x7f)
115 s += (char)b;
116 else
117 {
118 s += '[';
119 char temp[16];
120 ConvertUInt32ToHex(b, temp);
121 s += temp;
122 s += ']';
123 }
114 } 124 }
115} 125}
116 126
117 127
118static void x86cpuid_to_String(const Cx86cpuid &c, AString &s, AString &ver) 128static void x86cpuid_to_String(AString &s)
119{ 129{
120 s.Empty(); 130 s.Empty();
121 131
122 UInt32 maxFunc2 = 0; 132 UInt32 a[4];
123 UInt32 t[3]; 133 // cpuid was called already. So we don't check for cpuid availability here
134 z7_x86_cpuid(a, 0x80000000);
124 135
125 MyCPUID(0x80000000, &maxFunc2, &t[0], &t[1], &t[2]); 136 if (a[0] >= 0x80000004) // if (maxFunc2 >= hi+4) the full name is available
126
127 bool fullNameIsAvail = (maxFunc2 >= 0x80000004);
128
129 if (fullNameIsAvail)
130 { 137 {
131 for (unsigned i = 0; i < 3; i++) 138 for (unsigned i = 0; i < 3; i++)
132 { 139 {
133 UInt32 d[4] = { 0 }; 140 z7_x86_cpuid(a, 0x80000002 + i);
134 MyCPUID(0x80000002 + i, &d[0], &d[1], &d[2], &d[3]);
135 for (unsigned j = 0; j < 4; j++) 141 for (unsigned j = 0; j < 4; j++)
136 PrintCpuChars(s, d[j]); 142 PrintCpuChars(s, a[j]);
137 } 143 }
138 } 144 }
139 145
@@ -141,16 +147,14 @@ static void x86cpuid_to_String(const Cx86cpuid &c, AString &s, AString &ver)
141 147
142 if (s.IsEmpty()) 148 if (s.IsEmpty())
143 { 149 {
144 for (int i = 0; i < 3; i++) 150 z7_x86_cpuid(a, 0);
145 PrintCpuChars(s, c.vendor[i]); 151 for (unsigned i = 1; i < 4; i++)
152 {
153 const unsigned j = (i ^ (i >> 1));
154 PrintCpuChars(s, a[j]);
155 }
146 s.Trim(); 156 s.Trim();
147 } 157 }
148
149 {
150 char temp[32];
151 ConvertUInt32ToHex(c.ver, temp);
152 ver += temp;
153 }
154} 158}
155 159
156/* 160/*
@@ -184,7 +188,7 @@ static void x86cpuid_all_to_String(AString &s)
184 { 188 {
185 char temp[32]; 189 char temp[32];
186 ConvertUInt32ToHex8Digits(d[i], temp); 190 ConvertUInt32ToHex8Digits(d[i], temp);
187 s += " "; 191 s.Add_Space();
188 s += temp; 192 s += temp;
189 } 193 }
190 } 194 }
@@ -215,12 +219,12 @@ static const char * const k_PROCESSOR_ARCHITECTURE[] =
215 , "ARM32_ON_WIN64" 219 , "ARM32_ON_WIN64"
216}; 220};
217 221
218#define MY__PROCESSOR_ARCHITECTURE_INTEL 0 222#define Z7_WIN_PROCESSOR_ARCHITECTURE_INTEL 0
219#define MY__PROCESSOR_ARCHITECTURE_AMD64 9 223#define Z7_WIN_PROCESSOR_ARCHITECTURE_AMD64 9
220 224
221 225
222#define MY__PROCESSOR_INTEL_PENTIUM 586 226#define Z7_WIN_PROCESSOR_INTEL_PENTIUM 586
223#define MY__PROCESSOR_AMD_X8664 8664 227#define Z7_WIN_PROCESSOR_AMD_X8664 8664
224 228
225/* 229/*
226static const CUInt32PCharPair k_PROCESSOR[] = 230static const CUInt32PCharPair k_PROCESSOR[] =
@@ -303,19 +307,20 @@ static const char * const k_PF[] =
303#endif 307#endif
304 308
305 309
306#ifdef _WIN32 310static void PrintPage(AString &s, UInt64 v)
307
308static void PrintPage(AString &s, UInt32 v)
309{ 311{
310 if ((v & 0x3FF) == 0) 312 const char *t = "B";
313 if ((v & 0x3ff) == 0)
311 { 314 {
312 s.Add_UInt32(v >> 10); 315 v >>= 10;
313 s += "K"; 316 t = "KB";
314 } 317 }
315 else 318 s.Add_UInt64(v);
316 s.Add_UInt32(v >> 10); 319 s += t;
317} 320}
318 321
322#ifdef _WIN32
323
319static AString TypeToString2(const char * const table[], unsigned num, UInt32 value) 324static AString TypeToString2(const char * const table[], unsigned num, UInt32 value)
320{ 325{
321 char sz[16]; 326 char sz[16];
@@ -330,7 +335,7 @@ static AString TypeToString2(const char * const table[], unsigned num, UInt32 va
330 return (AString)p; 335 return (AString)p;
331} 336}
332 337
333// #if defined(_7ZIP_LARGE_PAGES) || defined(_WIN32) 338// #if defined(Z7_LARGE_PAGES) || defined(_WIN32)
334// #ifdef _WIN32 339// #ifdef _WIN32
335void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v) 340void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v)
336{ 341{
@@ -342,32 +347,32 @@ void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v)
342 }}}} 347 }}}}
343 else 348 else
344 { 349 {
350 // s += "0x";
345 PrintHex(s, v); 351 PrintHex(s, v);
346 return; 352 return;
347 } 353 }
348 char temp[32]; 354 s.Add_UInt64(v);
349 ConvertUInt64ToString(v, temp);
350 s += temp;
351 if (c) 355 if (c)
352 s += c; 356 s += c;
357 s += 'B';
353} 358}
354// #endif 359// #endif
355// #endif 360// #endif
356 361
357static void SysInfo_To_String(AString &s, const SYSTEM_INFO &si) 362static void SysInfo_To_String(AString &s, const SYSTEM_INFO &si)
358{ 363{
359 s += TypeToString2(k_PROCESSOR_ARCHITECTURE, ARRAY_SIZE(k_PROCESSOR_ARCHITECTURE), si.wProcessorArchitecture); 364 s += TypeToString2(k_PROCESSOR_ARCHITECTURE, Z7_ARRAY_SIZE(k_PROCESSOR_ARCHITECTURE), si.wProcessorArchitecture);
360 365
361 if (!( (si.wProcessorArchitecture == MY__PROCESSOR_ARCHITECTURE_INTEL && si.dwProcessorType == MY__PROCESSOR_INTEL_PENTIUM) 366 if (!( (si.wProcessorArchitecture == Z7_WIN_PROCESSOR_ARCHITECTURE_INTEL && si.dwProcessorType == Z7_WIN_PROCESSOR_INTEL_PENTIUM)
362 || (si.wProcessorArchitecture == MY__PROCESSOR_ARCHITECTURE_AMD64 && si.dwProcessorType == MY__PROCESSOR_AMD_X8664))) 367 || (si.wProcessorArchitecture == Z7_WIN_PROCESSOR_ARCHITECTURE_AMD64 && si.dwProcessorType == Z7_WIN_PROCESSOR_AMD_X8664)))
363 { 368 {
364 s += " "; 369 s.Add_Space();
365 // s += TypePairToString(k_PROCESSOR, ARRAY_SIZE(k_PROCESSOR), si.dwProcessorType); 370 // s += TypePairToString(k_PROCESSOR, Z7_ARRAY_SIZE(k_PROCESSOR), si.dwProcessorType);
366 s.Add_UInt32(si.dwProcessorType); 371 s.Add_UInt32(si.dwProcessorType);
367 } 372 }
368 s += " "; 373 s.Add_Space();
369 PrintHex(s, si.wProcessorLevel); 374 PrintHex(s, si.wProcessorLevel);
370 s += "."; 375 s.Add_Dot();
371 PrintHex(s, si.wProcessorRevision); 376 PrintHex(s, si.wProcessorRevision);
372 if ((UInt64)si.dwActiveProcessorMask + 1 != ((UInt64)1 << si.dwNumberOfProcessors)) 377 if ((UInt64)si.dwActiveProcessorMask + 1 != ((UInt64)1 << si.dwNumberOfProcessors))
373 if ((UInt64)si.dwActiveProcessorMask + 1 != 0 || si.dwNumberOfProcessors != sizeof(UInt64) * 8) 378 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)
387 s += " gran:"; 392 s += " gran:";
388 PrintPage(s, si.dwAllocationGranularity); 393 PrintPage(s, si.dwAllocationGranularity);
389 } 394 }
390 s += " "; 395 s.Add_Space();
391 396
392 DWORD_PTR minAdd = (DWORD_PTR)si.lpMinimumApplicationAddress; 397 const DWORD_PTR minAdd = (DWORD_PTR)si.lpMinimumApplicationAddress;
393 UInt64 maxSize = (UInt64)(DWORD_PTR)si.lpMaximumApplicationAddress + 1; 398 UInt64 maxSize = (UInt64)(DWORD_PTR)si.lpMaximumApplicationAddress + 1;
394 const UInt32 kReserveSize = ((UInt32)1 << 16); 399 const UInt32 kReserveSize = ((UInt32)1 << 16);
395 if (minAdd != kReserveSize) 400 if (minAdd != kReserveSize)
@@ -419,7 +424,7 @@ static void Add_sysctlbyname_to_String(const char *name, AString &s)
419{ 424{
420 size_t bufSize = 256; 425 size_t bufSize = 256;
421 char buf[256]; 426 char buf[256];
422 if (My_sysctlbyname_Get(name, &buf, &bufSize) == 0) 427 if (z7_sysctlbyname_Get(name, &buf, &bufSize) == 0)
423 s += buf; 428 s += buf;
424} 429}
425#endif 430#endif
@@ -440,12 +445,14 @@ void GetSysInfo(AString &s1, AString &s2)
440 } 445 }
441 446
442 #if !defined(_WIN64) && !defined(UNDER_CE) 447 #if !defined(_WIN64) && !defined(UNDER_CE)
443 Func_GetNativeSystemInfo fn_GetNativeSystemInfo = (Func_GetNativeSystemInfo)(void *)GetProcAddress( 448 const
444 GetModuleHandleA("kernel32.dll"), "GetNativeSystemInfo"); 449 Func_GetNativeSystemInfo fn = Z7_GET_PROC_ADDRESS(
445 if (fn_GetNativeSystemInfo) 450 Func_GetNativeSystemInfo, GetModuleHandleA("kernel32.dll"),
451 "GetNativeSystemInfo");
452 if (fn)
446 { 453 {
447 SYSTEM_INFO si2; 454 SYSTEM_INFO si2;
448 fn_GetNativeSystemInfo(&si2); 455 fn(&si2);
449 // if (memcmp(&si, &si2, sizeof(si)) != 0) 456 // if (memcmp(&si, &si2, sizeof(si)) != 0)
450 { 457 {
451 // s += " - "; 458 // s += " - ";
@@ -500,18 +507,20 @@ void CCpuName::Fill()
500 507
501 #ifdef MY_CPU_X86_OR_AMD64 508 #ifdef MY_CPU_X86_OR_AMD64
502 { 509 {
503 Cx86cpuid cpuid; 510 #if !defined(MY_CPU_AMD64)
504 if (x86cpuid_CheckAndRead(&cpuid)) 511 if (!z7_x86_cpuid_GetMaxFunc())
505 { 512 s += "x86";
506 x86cpuid_to_String(cpuid, s, Revision);
507 }
508 else 513 else
509 {
510 #ifdef MY_CPU_AMD64
511 s += "x64";
512 #else
513 s += "x86";
514 #endif 514 #endif
515 {
516 x86cpuid_to_String(s);
517 {
518 UInt32 a[4];
519 z7_x86_cpuid(a, 1);
520 char temp[16];
521 ConvertUInt32ToHex(a[0], temp);
522 Revision += temp;
523 }
515 } 524 }
516 } 525 }
517 #elif defined(__APPLE__) 526 #elif defined(__APPLE__)
@@ -534,12 +543,12 @@ void CCpuName::Fill()
534 { 543 {
535 AString s2; 544 AString s2;
536 UInt32 v = 0; 545 UInt32 v = 0;
537 if (My_sysctlbyname_Get_UInt32("machdep.cpu.core_count", &v) == 0) 546 if (z7_sysctlbyname_Get_UInt32("machdep.cpu.core_count", &v) == 0)
538 { 547 {
539 s2.Add_UInt32(v); 548 s2.Add_UInt32(v);
540 s2 += 'C'; 549 s2 += 'C';
541 } 550 }
542 if (My_sysctlbyname_Get_UInt32("machdep.cpu.thread_count", &v) == 0) 551 if (z7_sysctlbyname_Get_UInt32("machdep.cpu.thread_count", &v) == 0)
543 { 552 {
544 s2.Add_UInt32(v); 553 s2.Add_UInt32(v);
545 s2 += 'T'; 554 s2 += 'T';
@@ -561,7 +570,7 @@ void CCpuName::Fill()
561 LONG res[2]; 570 LONG res[2];
562 CByteBuffer bufs[2]; 571 CByteBuffer bufs[2];
563 { 572 {
564 for (int i = 0; i < 2; i++) 573 for (unsigned i = 0; i < 2; i++)
565 { 574 {
566 UInt32 size = 0; 575 UInt32 size = 0;
567 res[i] = key.QueryValue(i == 0 ? 576 res[i] = key.QueryValue(i == 0 ?
@@ -574,7 +583,7 @@ void CCpuName::Fill()
574 } 583 }
575 if (res[0] == ERROR_SUCCESS || res[1] == ERROR_SUCCESS) 584 if (res[0] == ERROR_SUCCESS || res[1] == ERROR_SUCCESS)
576 { 585 {
577 for (int i = 0; i < 2; i++) 586 for (unsigned i = 0; i < 2; i++)
578 { 587 {
579 if (i == 1) 588 if (i == 1)
580 Microcode += "->"; 589 Microcode += "->";
@@ -598,7 +607,7 @@ void CCpuName::Fill()
598 #endif 607 #endif
599 608
600 609
601 #ifdef _7ZIP_LARGE_PAGES 610 #ifdef Z7_LARGE_PAGES
602 Add_LargePages_String(LargePages); 611 Add_LargePages_String(LargePages);
603 #endif 612 #endif
604} 613}
@@ -608,7 +617,7 @@ void AddCpuFeatures(AString &s)
608{ 617{
609 #ifdef _WIN32 618 #ifdef _WIN32
610 // const unsigned kNumFeatures_Extra = 32; // we check also for unknown features 619 // const unsigned kNumFeatures_Extra = 32; // we check also for unknown features
611 // const unsigned kNumFeatures = ARRAY_SIZE(k_PF) + kNumFeatures_Extra; 620 // const unsigned kNumFeatures = Z7_ARRAY_SIZE(k_PF) + kNumFeatures_Extra;
612 const unsigned kNumFeatures = 64; 621 const unsigned kNumFeatures = 64;
613 UInt64 flags = 0; 622 UInt64 flags = 0;
614 for (unsigned i = 0; i < kNumFeatures; i++) 623 for (unsigned i = 0; i < kNumFeatures; i++)
@@ -617,7 +626,7 @@ void AddCpuFeatures(AString &s)
617 { 626 {
618 flags += (UInt64)1 << i; 627 flags += (UInt64)1 << i;
619 // s.Add_Space_if_NotEmpty(); 628 // s.Add_Space_if_NotEmpty();
620 // s += TypeToString2(k_PF, ARRAY_SIZE(k_PF), i); 629 // s += TypeToString2(k_PF, Z7_ARRAY_SIZE(k_PF), i);
621 } 630 }
622 } 631 }
623 s.Add_OptSpaced("f:"); 632 s.Add_OptSpaced("f:");
@@ -626,11 +635,10 @@ void AddCpuFeatures(AString &s)
626 #elif defined(__APPLE__) 635 #elif defined(__APPLE__)
627 { 636 {
628 UInt32 v = 0; 637 UInt32 v = 0;
629 if (My_sysctlbyname_Get_UInt32("hw.pagesize", &v) == 0) 638 if (z7_sysctlbyname_Get_UInt32("hw.pagesize", &v) == 0)
630 { 639 {
631 s += "PageSize:"; 640 s.Add_OptSpaced("PageSize:");
632 s.Add_UInt32(v >> 10); 641 PrintPage(s, v);
633 s += "KB";
634 } 642 }
635 } 643 }
636 644
@@ -639,10 +647,8 @@ void AddCpuFeatures(AString &s)
639 const long v = sysconf(_SC_PAGESIZE); 647 const long v = sysconf(_SC_PAGESIZE);
640 if (v != -1) 648 if (v != -1)
641 { 649 {
642 s.Add_Space_if_NotEmpty(); 650 s.Add_OptSpaced("PageSize:");
643 s += "PageSize:"; 651 PrintPage(s, (unsigned long)v);
644 s.Add_UInt32((UInt32)(v >> 10));
645 s += "KB";
646 } 652 }
647 653
648 #if !defined(_AIX) 654 #if !defined(_AIX)
@@ -659,11 +665,11 @@ void AddCpuFeatures(AString &s)
659 const int pos = s2.Find('['); 665 const int pos = s2.Find('[');
660 if (pos >= 0) 666 if (pos >= 0)
661 { 667 {
662 const int pos2 = s2.Find(']', pos + 1); 668 const int pos2 = s2.Find(']', (unsigned)pos + 1);
663 if (pos2 >= 0) 669 if (pos2 >= 0)
664 { 670 {
665 s2.DeleteFrom(pos2); 671 s2.DeleteFrom((unsigned)pos2);
666 s2.DeleteFrontal(pos + 1); 672 s2.DeleteFrontal((unsigned)pos + 1);
667 } 673 }
668 } 674 }
669 s += s2; 675 s += s2;
@@ -722,10 +728,13 @@ EXTERN_C_END
722 728
723static BOOL My_RtlGetVersion(OSVERSIONINFOEXW *vi) 729static BOOL My_RtlGetVersion(OSVERSIONINFOEXW *vi)
724{ 730{
725 HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); 731 const HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll");
726 if (!ntdll) 732 if (!ntdll)
727 return FALSE; 733 return FALSE;
728 Func_RtlGetVersion func = (Func_RtlGetVersion)(void *)GetProcAddress(ntdll, "RtlGetVersion"); 734 const
735 Func_RtlGetVersion func = Z7_GET_PROC_ADDRESS(
736 Func_RtlGetVersion, ntdll,
737 "RtlGetVersion");
729 if (!func) 738 if (!func)
730 return FALSE; 739 return FALSE;
731 func(vi); 740 func(vi);
@@ -752,18 +761,18 @@ void GetOsInfoText(AString &sRes)
752 s += "Windows"; 761 s += "Windows";
753 if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT) 762 if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT)
754 s.Add_UInt32(vi.dwPlatformId); 763 s.Add_UInt32(vi.dwPlatformId);
755 s += " "; s.Add_UInt32(vi.dwMajorVersion); 764 s.Add_Space(); s.Add_UInt32(vi.dwMajorVersion);
756 s += "."; s.Add_UInt32(vi.dwMinorVersion); 765 s.Add_Dot(); s.Add_UInt32(vi.dwMinorVersion);
757 s += " "; s.Add_UInt32(vi.dwBuildNumber); 766 s.Add_Space(); s.Add_UInt32(vi.dwBuildNumber);
758 767
759 if (vi.wServicePackMajor != 0 || vi.wServicePackMinor != 0) 768 if (vi.wServicePackMajor != 0 || vi.wServicePackMinor != 0)
760 { 769 {
761 s += " SP:"; s.Add_UInt32(vi.wServicePackMajor); 770 s += " SP:"; s.Add_UInt32(vi.wServicePackMajor);
762 s += "."; s.Add_UInt32(vi.wServicePackMinor); 771 s.Add_Dot(); s.Add_UInt32(vi.wServicePackMinor);
763 } 772 }
764 // s += " Suite:"; PrintHex(s, vi.wSuiteMask); 773 // s += " Suite:"; PrintHex(s, vi.wSuiteMask);
765 // s += " Type:"; s.Add_UInt32(vi.wProductType); 774 // s += " Type:"; s.Add_UInt32(vi.wProductType);
766 // s += " "; s += GetOemString(vi.szCSDVersion); 775 // s.Add_Space(); s += GetOemString(vi.szCSDVersion);
767 } 776 }
768 /* 777 /*
769 { 778 {
@@ -793,6 +802,17 @@ void GetOsInfoText(AString &sRes)
793 #endif // _WIN32 802 #endif // _WIN32
794 803
795 sRes += s; 804 sRes += s;
805 #ifdef MY_CPU_X86_OR_AMD64
806 {
807 AString s2;
808 GetVirtCpuid(s2);
809 if (!s2.IsEmpty())
810 {
811 sRes += " : ";
812 sRes += s2;
813 }
814 }
815 #endif
796} 816}
797 817
798 818
@@ -875,6 +895,61 @@ void GetCpuName_MultiLine(AString &s)
875 } 895 }
876} 896}
877 897
898
899#ifdef MY_CPU_X86_OR_AMD64
900
901void GetVirtCpuid(AString &s)
902{
903 const UInt32 kHv = 0x40000000;
904
905 Z7_IF_X86_CPUID_SUPPORTED
906 {
907 UInt32 a[4];
908 z7_x86_cpuid(a, kHv);
909
910 if (a[0] < kHv || a[0] >= kHv + (1 << 16))
911 return;
912 {
913 {
914 for (unsigned j = 1; j < 4; j++)
915 PrintCpuChars(s, a[j]);
916 }
917 }
918 if (a[0] >= kHv + 1)
919 {
920 UInt32 d[4];
921 z7_x86_cpuid(d, kHv + 1);
922 s += " : ";
923 PrintCpuChars(s, d[0]);
924 if (a[0] >= kHv + 2)
925 {
926 z7_x86_cpuid(d, kHv + 2);
927 s += " : ";
928 s.Add_UInt32(d[1] >> 16);
929 s.Add_Dot(); s.Add_UInt32(d[1] & 0xffff);
930 s.Add_Dot(); s.Add_UInt32(d[0]);
931 s.Add_Dot(); s.Add_UInt32(d[2]);
932 s.Add_Dot(); s.Add_UInt32(d[3] >> 24);
933 s.Add_Dot(); s.Add_UInt32(d[3] & 0xffffff);
934 }
935 /*
936 if (a[0] >= kHv + 5)
937 {
938 z7_x86_cpuid(d, kHv + 5);
939 s += " : ";
940 s.Add_UInt32(d[0]);
941 s += "p";
942 s.Add_UInt32(d[1]);
943 s += "t";
944 }
945 */
946 }
947 }
948}
949
950#endif
951
952
878void GetCompiler(AString &s) 953void GetCompiler(AString &s)
879{ 954{
880 #ifdef __VERSION__ 955 #ifdef __VERSION__
@@ -884,28 +959,28 @@ void GetCompiler(AString &s)
884 #ifdef __GNUC__ 959 #ifdef __GNUC__
885 s += " GCC "; 960 s += " GCC ";
886 s.Add_UInt32(__GNUC__); 961 s.Add_UInt32(__GNUC__);
887 s += '.'; 962 s.Add_Dot();
888 s.Add_UInt32(__GNUC_MINOR__); 963 s.Add_UInt32(__GNUC_MINOR__);
889 s += '.'; 964 s.Add_Dot();
890 s.Add_UInt32(__GNUC_PATCHLEVEL__); 965 s.Add_UInt32(__GNUC_PATCHLEVEL__);
891 #endif 966 #endif
892 967
893 #ifdef __clang__ 968 #ifdef __clang__
894 s += " CLANG "; 969 s += " CLANG ";
895 s.Add_UInt32(__clang_major__); 970 s.Add_UInt32(__clang_major__);
896 s += '.'; 971 s.Add_Dot();
897 s.Add_UInt32(__clang_minor__); 972 s.Add_UInt32(__clang_minor__);
898 #endif 973 #endif
899 974
900 #ifdef __xlC__ 975 #ifdef __xlC__
901 s += " XLC "; 976 s += " XLC ";
902 s.Add_UInt32(__xlC__ >> 8); 977 s.Add_UInt32(__xlC__ >> 8);
903 s += '.'; 978 s.Add_Dot();
904 s.Add_UInt32(__xlC__ & 0xFF); 979 s.Add_UInt32(__xlC__ & 0xFF);
905 #ifdef __xlC_ver__ 980 #ifdef __xlC_ver__
906 s += '.'; 981 s.Add_Dot();
907 s.Add_UInt32(__xlC_ver__ >> 8); 982 s.Add_UInt32(__xlC_ver__ >> 8);
908 s += '.'; 983 s.Add_Dot();
909 s.Add_UInt32(__xlC_ver__ & 0xFF); 984 s.Add_UInt32(__xlC_ver__ & 0xFF);
910 #endif 985 #endif
911 #endif 986 #endif
@@ -914,4 +989,34 @@ void GetCompiler(AString &s)
914 s += " MSC "; 989 s += " MSC ";
915 s.Add_UInt32(_MSC_VER); 990 s.Add_UInt32(_MSC_VER);
916 #endif 991 #endif
992
993 #if defined(__AVX2__)
994 #define MY_CPU_COMPILE_ISA "AVX2"
995 #elif defined(__AVX__)
996 #define MY_CPU_COMPILE_ISA "AVX"
997 #elif defined(__SSE2__)
998 #define MY_CPU_COMPILE_ISA "SSE2"
999 #elif defined(_M_IX86_FP) && (_M_IX86_FP >= 2)
1000 #define MY_CPU_COMPILE_ISA "SSE2"
1001 #elif defined(__SSE__)
1002 #define MY_CPU_COMPILE_ISA "SSE"
1003 #elif defined(_M_IX86_FP) && (_M_IX86_FP >= 1)
1004 #define MY_CPU_COMPILE_ISA "SSE"
1005 #elif defined(__i686__)
1006 #define MY_CPU_COMPILE_ISA "i686"
1007 #elif defined(__i586__)
1008 #define MY_CPU_COMPILE_ISA "i586"
1009 #elif defined(__i486__)
1010 #define MY_CPU_COMPILE_ISA "i486"
1011 #elif defined(__i386__)
1012 #define MY_CPU_COMPILE_ISA "i386"
1013 #elif defined(_M_IX86_FP)
1014 #define MY_CPU_COMPILE_ISA "IA32"
1015 #endif
1016
1017
1018 #ifdef MY_CPU_COMPILE_ISA
1019 s += ':';
1020 s.Add_OptSpaced(MY_CPU_COMPILE_ISA);
1021 #endif
917} 1022}
diff --git a/CPP/Windows/SystemInfo.h b/CPP/Windows/SystemInfo.h
index e941d0a..c2e2e3b 100644
--- a/CPP/Windows/SystemInfo.h
+++ b/CPP/Windows/SystemInfo.h
@@ -1,7 +1,7 @@
1// Windows/SystemInfo.h 1// Windows/SystemInfo.h
2 2
3#ifndef __WINDOWS_SYSTEM_INFO_H 3#ifndef ZIP7_INC_WINDOWS_SYSTEM_INFO_H
4#define __WINDOWS_SYSTEM_INFO_H 4#define ZIP7_INC_WINDOWS_SYSTEM_INFO_H
5 5
6#include "../Common/MyString.h" 6#include "../Common/MyString.h"
7 7
@@ -14,5 +14,6 @@ void PrintSize_KMGT_Or_Hex(AString &s, UInt64 v);
14void Add_LargePages_String(AString &s); 14void Add_LargePages_String(AString &s);
15 15
16void GetCompiler(AString &s); 16void GetCompiler(AString &s);
17void GetVirtCpuid(AString &s);
17 18
18#endif 19#endif
diff --git a/CPP/Windows/Thread.h b/CPP/Windows/Thread.h
index 5fca173..d72f64c 100644
--- a/CPP/Windows/Thread.h
+++ b/CPP/Windows/Thread.h
@@ -1,7 +1,7 @@
1// Windows/Thread.h 1// Windows/Thread.h
2 2
3#ifndef __WINDOWS_THREAD_H 3#ifndef ZIP7_INC_WINDOWS_THREAD_H
4#define __WINDOWS_THREAD_H 4#define ZIP7_INC_WINDOWS_THREAD_H
5 5
6#include "../../C/Threads.h" 6#include "../../C/Threads.h"
7 7
@@ -13,7 +13,7 @@ class CThread MY_UNCOPYABLE
13{ 13{
14 ::CThread thread; 14 ::CThread thread;
15public: 15public:
16 CThread() { Thread_Construct(&thread); } 16 CThread() { Thread_CONSTRUCT(&thread) }
17 ~CThread() { Close(); } 17 ~CThread() { Close(); }
18 bool IsCreated() { return Thread_WasCreated(&thread) != 0; } 18 bool IsCreated() { return Thread_WasCreated(&thread) != 0; }
19 WRes Close() { return Thread_Close(&thread); } 19 WRes Close() { return Thread_Close(&thread); }
diff --git a/CPP/Windows/TimeUtils.cpp b/CPP/Windows/TimeUtils.cpp
index 77d2c51..e80ae13 100644
--- a/CPP/Windows/TimeUtils.cpp
+++ b/CPP/Windows/TimeUtils.cpp
@@ -258,7 +258,7 @@ void GetCurUtc_FiTime(CFiTime &ft) throw()
258 258
259 FiTime_Clear(ft); 259 FiTime_Clear(ft);
260 struct timeval now; 260 struct timeval now;
261 if (gettimeofday(&now, 0 ) == 0) 261 if (gettimeofday(&now, NULL) == 0)
262 { 262 {
263 ft.tv_sec = now.tv_sec; 263 ft.tv_sec = now.tv_sec;
264 ft.tv_nsec = now.tv_usec * 1000; 264 ft.tv_nsec = now.tv_usec * 1000;
@@ -272,7 +272,7 @@ void GetCurUtcFileTime(FILETIME &ft) throw()
272{ 272{
273 UInt64 v = 0; 273 UInt64 v = 0;
274 struct timeval now; 274 struct timeval now;
275 if (gettimeofday(&now, 0 ) == 0) 275 if (gettimeofday(&now, NULL) == 0)
276 { 276 {
277 v = ((UInt64)now.tv_sec + kUnixTimeOffset) * 277 v = ((UInt64)now.tv_sec + kUnixTimeOffset) *
278 kNumTimeQuantumsInSecond + (UInt64)now.tv_usec * 10; 278 kNumTimeQuantumsInSecond + (UInt64)now.tv_usec * 10;
diff --git a/CPP/Windows/TimeUtils.h b/CPP/Windows/TimeUtils.h
index 60ee739..4a9d0f2 100644
--- a/CPP/Windows/TimeUtils.h
+++ b/CPP/Windows/TimeUtils.h
@@ -1,7 +1,7 @@
1// Windows/TimeUtils.h 1// Windows/TimeUtils.h
2 2
3#ifndef __WINDOWS_TIME_UTILS_H 3#ifndef ZIP7_INC_WINDOWS_TIME_UTILS_H
4#define __WINDOWS_TIME_UTILS_H 4#define ZIP7_INC_WINDOWS_TIME_UTILS_H
5 5
6#include "../Common/MyTypes.h" 6#include "../Common/MyTypes.h"
7#include "../Common/MyWindows.h" 7#include "../Common/MyWindows.h"
diff --git a/CPP/Windows/Window.cpp b/CPP/Windows/Window.cpp
index 32af4aa..102c503 100644
--- a/CPP/Windows/Window.cpp
+++ b/CPP/Windows/Window.cpp
@@ -111,7 +111,7 @@ bool MySetWindowText(HWND wnd, LPCWSTR s)
111} 111}
112#endif 112#endif
113 113
114bool CWindow::GetText(CSysString &s) 114bool CWindow::GetText(CSysString &s) const
115{ 115{
116 s.Empty(); 116 s.Empty();
117 unsigned len = (unsigned)GetTextLength(); 117 unsigned len = (unsigned)GetTextLength();
@@ -119,7 +119,7 @@ bool CWindow::GetText(CSysString &s)
119 return (::GetLastError() == ERROR_SUCCESS); 119 return (::GetLastError() == ERROR_SUCCESS);
120 TCHAR *p = s.GetBuf(len); 120 TCHAR *p = s.GetBuf(len);
121 { 121 {
122 unsigned len2 = (unsigned)GetText(p, (int)(len + 1)); 122 const unsigned len2 = (unsigned)GetText(p, (int)(len + 1));
123 if (len > len2) 123 if (len > len2)
124 len = len2; 124 len = len2;
125 } 125 }
@@ -130,7 +130,7 @@ bool CWindow::GetText(CSysString &s)
130} 130}
131 131
132#ifndef _UNICODE 132#ifndef _UNICODE
133bool CWindow::GetText(UString &s) 133bool CWindow::GetText(UString &s) const
134{ 134{
135 if (g_IsNT) 135 if (g_IsNT)
136 { 136 {
@@ -140,7 +140,7 @@ bool CWindow::GetText(UString &s)
140 return (::GetLastError() == ERROR_SUCCESS); 140 return (::GetLastError() == ERROR_SUCCESS);
141 wchar_t *p = s.GetBuf(len); 141 wchar_t *p = s.GetBuf(len);
142 { 142 {
143 unsigned len2 = (unsigned)GetWindowTextW(_window, p, (int)(len + 1)); 143 const unsigned len2 = (unsigned)GetWindowTextW(_window, p, (int)(len + 1));
144 if (len > len2) 144 if (len > len2)
145 len = len2; 145 len = len2;
146 } 146 }
@@ -150,7 +150,7 @@ bool CWindow::GetText(UString &s)
150 return true; 150 return true;
151 } 151 }
152 CSysString sysString; 152 CSysString sysString;
153 bool result = GetText(sysString); 153 const bool result = GetText(sysString);
154 MultiByteToUnicodeString2(s, sysString); 154 MultiByteToUnicodeString2(s, sysString);
155 return result; 155 return result;
156} 156}
diff --git a/CPP/Windows/Window.h b/CPP/Windows/Window.h
index 83726c7..a99143b 100644
--- a/CPP/Windows/Window.h
+++ b/CPP/Windows/Window.h
@@ -1,7 +1,7 @@
1// Windows/Window.h 1// Windows/Window.h
2 2
3#ifndef __WINDOWS_WINDOW_H 3#ifndef ZIP7_INC_WINDOWS_WINDOW_H
4#define __WINDOWS_WINDOW_H 4#define ZIP7_INC_WINDOWS_WINDOW_H
5 5
6#include "../Common/MyWindows.h" 6#include "../Common/MyWindows.h"
7#include "../Common/MyString.h" 7#include "../Common/MyString.h"
@@ -9,23 +9,100 @@
9#include "Defs.h" 9#include "Defs.h"
10 10
11#ifndef UNDER_CE 11#ifndef UNDER_CE
12#ifdef WM_CHANGEUISTATE
13#define Z7_WIN_WM_CHANGEUISTATE WM_CHANGEUISTATE
14#define Z7_WIN_WM_UPDATEUISTATE WM_UPDATEUISTATE
15#define Z7_WIN_WM_QUERYUISTATE WM_QUERYUISTATE
16#else
17// these are defined for (_WIN32_WINNT >= 0x0500):
18#define Z7_WIN_WM_CHANGEUISTATE 0x0127
19#define Z7_WIN_WM_UPDATEUISTATE 0x0128
20#define Z7_WIN_WM_QUERYUISTATE 0x0129
21#endif
22
23#ifdef UIS_SET
12 24
13#define MY__WM_CHANGEUISTATE 0x0127 25#define Z7_WIN_UIS_SET UIS_SET
14#define MY__WM_UPDATEUISTATE 0x0128 26#define Z7_WIN_UIS_CLEAR UIS_CLEAR
15#define MY__WM_QUERYUISTATE 0x0129 27#define Z7_WIN_UIS_INITIALIZE UIS_INITIALIZE
16 28
29#define Z7_WIN_UISF_HIDEFOCUS UISF_HIDEFOCUS
30#define Z7_WIN_UISF_HIDEACCEL UISF_HIDEACCEL
31
32#else
33// these are defined for (_WIN32_WINNT >= 0x0500):
17// LOWORD(wParam) values in WM_*UISTATE 34// LOWORD(wParam) values in WM_*UISTATE
18#define MY__UIS_SET 1 35#define Z7_WIN_UIS_SET 1
19#define MY__UIS_CLEAR 2 36#define Z7_WIN_UIS_CLEAR 2
20#define MY__UIS_INITIALIZE 3 37#define Z7_WIN_UIS_INITIALIZE 3
21 38
22// HIWORD(wParam) values in WM_*UISTATE 39// HIWORD(wParam) values in WM_*UISTATE
23#define MY__UISF_HIDEFOCUS 0x1 40#define Z7_WIN_UISF_HIDEFOCUS 0x1
24#define MY__UISF_HIDEACCEL 0x2 41#define Z7_WIN_UISF_HIDEACCEL 0x2
25#define MY__UISF_ACTIVE 0x4 42// defined for for (_WIN32_WINNT >= 0x0501):
43// #define Z7_WIN_UISF_ACTIVE 0x4
26 44
27#endif 45#endif
28 46
47#endif // UNDER_CE
48
49
50#ifdef Z7_OLD_WIN_SDK
51
52// #define VK_OEM_1 0xBA // ';:' for US
53#define VK_OEM_PLUS 0xBB // '+' any country
54// #define VK_OEM_COMMA 0xBC // ',' any country
55#define VK_OEM_MINUS 0xBD // '-' any country
56// #define VK_OEM_PERIOD 0xBE // '.' any country
57// #define VK_OEM_2 0xBF // '/?' for US
58// #define VK_OEM_3 0xC0 // '`~' for US
59
60// #ifndef GWLP_USERDATA
61#define GWLP_WNDPROC (-4)
62#define GWLP_USERDATA (-21)
63// #endif
64#define DWLP_MSGRESULT 0
65// #define DWLP_DLGPROC DWLP_MSGRESULT + sizeof(LRESULT)
66// #define DWLP_USER DWLP_DLGPROC + sizeof(DLGPROC)
67
68#define BTNS_BUTTON TBSTYLE_BUTTON // 0x0000
69
70/*
71vc6 defines INT_PTR via long:
72 typedef long INT_PTR, *PINT_PTR;
73 typedef unsigned long UINT_PTR, *PUINT_PTR;
74but newer sdk (sdk2003+) defines INT_PTR via int:
75 typedef _W64 int INT_PTR, *PINT_PTR;
76 typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;
77*/
78
79#define IS_INTRESOURCE(_r) (((ULONG_PTR)(_r) >> 16) == 0)
80
81#define GetWindowLongPtrA GetWindowLongA
82#define GetWindowLongPtrW GetWindowLongW
83#ifdef UNICODE
84#define GetWindowLongPtr GetWindowLongPtrW
85#else
86#define GetWindowLongPtr GetWindowLongPtrA
87#endif // !UNICODE
88
89#define SetWindowLongPtrA SetWindowLongA
90#define SetWindowLongPtrW SetWindowLongW
91#ifdef UNICODE
92#define SetWindowLongPtr SetWindowLongPtrW
93#else
94#define SetWindowLongPtr SetWindowLongPtrA
95#endif // !UNICODE
96
97#define ListView_SetCheckState(hwndLV, i, fCheck) \
98 ListView_SetItemState(hwndLV, i, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), LVIS_STATEIMAGEMASK)
99
100#endif // Z7_OLD_WIN_SDK
101
102inline bool LRESULTToBool(LRESULT v) { return (v != FALSE); }
103
104#define MY_int_TO_WPARAM(i) ((WPARAM)(INT_PTR)(i))
105
29namespace NWindows { 106namespace NWindows {
30 107
31inline ATOM MyRegisterClass(CONST WNDCLASS *wndClass) 108inline ATOM MyRegisterClass(CONST WNDCLASS *wndClass)
@@ -52,12 +129,13 @@ bool MySetWindowText(HWND wnd, LPCWSTR s);
52 129
53class CWindow 130class CWindow
54{ 131{
132 Z7_CLASS_NO_COPY(CWindow)
55private: 133private:
56 // bool ModifyStyleBase(int styleOffset, DWORD remove, DWORD add, UINT flags); 134 // bool ModifyStyleBase(int styleOffset, DWORD remove, DWORD add, UINT flags);
57protected: 135protected:
58 HWND _window; 136 HWND _window;
59public: 137public:
60 CWindow(HWND newWindow = NULL): _window(newWindow){}; 138 CWindow(HWND newWindow = NULL): _window(newWindow) {}
61 CWindow& operator=(HWND newWindow) 139 CWindow& operator=(HWND newWindow)
62 { 140 {
63 _window = newWindow; 141 _window = newWindow;
@@ -174,6 +252,7 @@ public:
174 void SetRedraw(bool redraw = true) { SendMsg(WM_SETREDRAW, (WPARAM)BoolToBOOL(redraw), 0); } 252 void SetRedraw(bool redraw = true) { SendMsg(WM_SETREDRAW, (WPARAM)BoolToBOOL(redraw), 0); }
175 253
176 LONG_PTR SetStyle(LONG_PTR style) { return SetLongPtr(GWL_STYLE, style); } 254 LONG_PTR SetStyle(LONG_PTR style) { return SetLongPtr(GWL_STYLE, style); }
255 // LONG_PTR SetStyle(DWORD style) { return SetLongPtr(GWL_STYLE, (LONG_PTR)style); }
177 LONG_PTR GetStyle() const { return GetLongPtr(GWL_STYLE); } 256 LONG_PTR GetStyle() const { return GetLongPtr(GWL_STYLE); }
178 // bool MyIsMaximized() const { return ((GetStyle() & WS_MAXIMIZE) != 0); } 257 // bool MyIsMaximized() const { return ((GetStyle() & WS_MAXIMIZE) != 0); }
179 258
@@ -246,19 +325,19 @@ public:
246 { return GetWindowTextLength(_window); } 325 { return GetWindowTextLength(_window); }
247 int GetText(LPTSTR string, int maxCount) const 326 int GetText(LPTSTR string, int maxCount) const
248 { return GetWindowText(_window, string, maxCount); } 327 { return GetWindowText(_window, string, maxCount); }
249 bool GetText(CSysString &s); 328 bool GetText(CSysString &s) const;
250 #ifndef _UNICODE 329 #ifndef _UNICODE
251 /* 330 /*
252 UINT GetText(LPWSTR string, int maxCount) const 331 UINT GetText(LPWSTR string, int maxCount) const
253 { return GetWindowTextW(_window, string, maxCount); } 332 { return GetWindowTextW(_window, string, maxCount); }
254 */ 333 */
255 bool GetText(UString &s); 334 bool GetText(UString &s) const;
256 #endif 335 #endif
257 336
258 bool Enable(bool enable) 337 bool Enable(bool enable)
259 { return BOOLToBool(::EnableWindow(_window, BoolToBOOL(enable))); } 338 { return BOOLToBool(::EnableWindow(_window, BoolToBOOL(enable))); }
260 339
261 bool IsEnabled() 340 bool IsEnabled() const
262 { return BOOLToBool(::IsWindowEnabled(_window)); } 341 { return BOOLToBool(::IsWindowEnabled(_window)); }
263 342
264 #ifndef UNDER_CE 343 #ifndef UNDER_CE
@@ -266,7 +345,7 @@ public:
266 { return ::GetSystemMenu(_window, BoolToBOOL(revert)); } 345 { return ::GetSystemMenu(_window, BoolToBOOL(revert)); }
267 #endif 346 #endif
268 347
269 UINT_PTR SetTimer(UINT_PTR idEvent, UINT elapse, TIMERPROC timerFunc = 0) 348 UINT_PTR SetTimer(UINT_PTR idEvent, UINT elapse, TIMERPROC timerFunc = NULL)
270 { return ::SetTimer(_window, idEvent, elapse, timerFunc); } 349 { return ::SetTimer(_window, idEvent, elapse, timerFunc); }
271 bool KillTimer(UINT_PTR idEvent) 350 bool KillTimer(UINT_PTR idEvent)
272 {return BOOLToBool(::KillTimer(_window, idEvent)); } 351 {return BOOLToBool(::KillTimer(_window, idEvent)); }
diff --git a/DOC/7zip.wxs b/DOC/7zip.wxs
index 123182e..df1d320 100644
--- a/DOC/7zip.wxs
+++ b/DOC/7zip.wxs
@@ -1,6 +1,6 @@
1<?xml version="1.0"?> 1<?xml version="1.0"?>
2 2
3<?define VerMajor = "22" ?> 3<?define VerMajor = "23" ?>
4<?define VerMinor = "01" ?> 4<?define VerMinor = "01" ?>
5<?define VerBuild = "00" ?> 5<?define VerBuild = "00" ?>
6<?define MmVer = "$(var.VerMajor).$(var.VerMinor)" ?> 6<?define MmVer = "$(var.VerMajor).$(var.VerMinor)" ?>
diff --git a/DOC/Methods.txt b/DOC/Methods.txt
index d4a1b1d..541f1c1 100644
--- a/DOC/Methods.txt
+++ b/DOC/Methods.txt
@@ -1,8 +1,8 @@
17-Zip method IDs for 7z and xz archives 17-Zip method IDs for 7z and xz archives
2--------------------------------------- 2---------------------------------------
3 3
4Version: 18.06 4Version: 23.01
5Date: 2018-06-30 5Date: 2023-06-30
6 6
7Each compression or crypto method in 7z is associated with unique binary value (ID). 7Each compression or crypto method in 7z is associated with unique binary value (ID).
8The length of ID in bytes is arbitrary but it can not exceed 63 bits (8 bytes). 8The length of ID in bytes is arbitrary but it can not exceed 63 bits (8 bytes).
@@ -37,6 +37,7 @@ List of defined IDs
3707 - ARM (little-endian) 3707 - ARM (little-endian)
3808 - ARMT (little-endian) 3808 - ARMT (little-endian)
3909 - SPARC 3909 - SPARC
400A - ARM64
40 41
4121 - LZMA2 4221 - LZMA2
42 43
@@ -88,6 +89,8 @@ List of defined IDs
88 0A - Imploding 89 0A - Imploding
89 0C - BZip2 (not used. Use {040202} instead) 90 0C - BZip2 (not used. Use {040202} instead)
90 0E - LZMA (LZMA-zip) 91 0E - LZMA (LZMA-zip)
92
93 5D - ZSTD
91 5F - xz 94 5F - xz
92 60 - Jpeg 95 60 - Jpeg
93 61 - WavPack 96 61 - WavPack
diff --git a/DOC/lzma.txt b/DOC/lzma.txt
index a65988f..142feb1 100644
--- a/DOC/lzma.txt
+++ b/DOC/lzma.txt
@@ -1,6 +1,6 @@
1LZMA compression 1LZMA compression
2---------------- 2----------------
3Version: 9.35 3Version: 23.01
4 4
5This file describes LZMA encoding and decoding functions written in C language. 5This file describes LZMA encoding and decoding functions written in C language.
6 6
@@ -169,12 +169,14 @@ How To compress data
169Compile files: 169Compile files:
170 7zTypes.h 170 7zTypes.h
171 Threads.h 171 Threads.h
172 Threads.c
172 LzmaEnc.h 173 LzmaEnc.h
173 LzmaEnc.c 174 LzmaEnc.c
174 LzFind.h 175 LzFind.h
175 LzFind.c 176 LzFind.c
176 LzFindMt.h 177 LzFindMt.h
177 LzFindMt.c 178 LzFindMt.c
179 LzFindOpt.c
178 LzHash.h 180 LzHash.h
179 181
180Memory Requirements: 182Memory Requirements:
@@ -283,17 +285,26 @@ Return code:
283Defines 285Defines
284------- 286-------
285 287
286_LZMA_SIZE_OPT - Enable some optimizations in LZMA Decoder to get smaller executable code. 288Z7_LZMA_SIZE_OPT - Enable some code size optimizations in LZMA Decoder to get smaller executable code.
287 289
288_LZMA_PROB32 - It can increase the speed on some 32-bit CPUs, but memory usage for 290Z7_LZMA_PROB32 - It can increase the speed on some 32-bit CPUs, but memory usage for
289 some structures will be doubled in that case. 291 some structures will be doubled in that case.
290 292
291_LZMA_UINT32_IS_ULONG - Define it if int is 16-bit on your compiler and long is 32-bit. 293Z7_DECL_Int32_AS_long - Define it if int is 16-bit on your compiler and long is 32-bit.
292 294
293_LZMA_NO_SYSTEM_SIZE_T - Define it if you don't want to use size_t type. 295Z7_DECL_SizeT_AS_unsigned_int - Define it if you don't want to use size_t type.
294 296
295 297
296_7ZIP_PPMD_SUPPPORT - Define it if you don't want to support PPMD method in AMSI-C .7z decoder. 298Defines for 7z decoder written in C
299-----------------------------------
300These defines are for 7zDec.c only (the decoder in C).
301C++ 7z decoder doesn't uses these macros.
302
303Z7_PPMD_SUPPORT - define it if you need PPMD method support.
304Z7_NO_METHODS_FILTERS - do not use filters (except of BCJ2 filter).
305Z7_USE_NATIVE_BRANCH_FILTER - use filter for native ISA:
306 use x86 filter, if compiled to x86 executable,
307 use arm64 filter, if compiled to arm64 executable.
297 308
298 309
299C++ LZMA Encoder/Decoder 310C++ LZMA Encoder/Decoder
@@ -305,20 +316,26 @@ C++ LZMA code is just wrapper over ANSI-C code.
305 316
306C++ Notes 317C++ Notes
307~~~~~~~~~~~~~~~~~~~~~~~~ 318~~~~~~~~~~~~~~~~~~~~~~~~
308If you use some C++ code folders in 7-Zip (for example, C++ code for .7z handling), 319If you use some C++ code folders in 7-Zip (for example, C++ code for 7z archive handling),
309you must check that you correctly work with "new" operator. 320you must check that you correctly work with "new" operator.
3107-Zip can be compiled with MSVC 6.0 that doesn't throw "exception" from "new" operator. 3217-Zip can be compiled with MSVC 6.0 that doesn't throw "exception" from "new" operator.
311So 7-Zip uses "CPP\Common\NewHandler.cpp" that redefines "new" operator: 322So 7-Zip uses "CPP\Common\NewHandler.cpp" that redefines "new" operator,
323if compiled by old MSVC compilers (MSVC before version VS 2010):
324
312operator new(size_t size) 325operator new(size_t size)
313{ 326{
314 void *p = ::malloc(size); 327 void *p = ::malloc(size);
315 if (p == 0) 328 if (!p)
316 throw CNewException(); 329 throw CNewException();
317 return p; 330 return p;
318} 331}
319If you use MSCV that throws exception for "new" operator, you can compile without 332
320"NewHandler.cpp". So standard exception will be used. Actually some code of 333If the compiler is VS 2010 or newer, NewHandler.cpp doesn't redefine "new" operator.
3217-Zip catches any exception in internal code and converts it to HRESULT code. 334Sp if you use new compiler (VS 2010 or newer), you still can include "NewHandler.cpp"
335to compilation, and it will not redefine operator new.
336Also you can compile without "NewHandler.cpp" with new compilers.
337If 7-zip doesn't redefine operator "new", standard exception will be used instead of CNewException.
338Some code of 7-Zip catches any exception in internal code and converts it to HRESULT code.
322So you don't need to catch CNewException, if you call COM interfaces of 7-Zip. 339So you don't need to catch CNewException, if you call COM interfaces of 7-Zip.
323 340
324--- 341---
diff --git a/DOC/readme.txt b/DOC/readme.txt
index faec8dc..5cd90c5 100644
--- a/DOC/readme.txt
+++ b/DOC/readme.txt
@@ -1,17 +1,18 @@
17-Zip 22.01 Sources 17-Zip 23.01 Sources
2------------------- 2-------------------
3 3
47-Zip is a file archiver for Windows. 47-Zip is a file archiver for Windows.
5 5
67-Zip Copyright (C) 1999-2022 Igor Pavlov. 67-Zip Copyright (C) 1999-2023 Igor Pavlov.
7 7
8 8
9License Info 9License Info
10------------ 10------------
11 11
127-Zip is free software distributed under the GNU LGPL 127-Zip is free software distributed under the GNU LGPL
13(except for unRar code). 13(except for unRar code). Also some code
14read License.txt for more infomation about license. 14is licensed under the "BSD 3-clause License".
15Read "License.txt" for more infomation about license.
15 16
16Notes about unRAR license: 17Notes about unRAR license:
17 18
@@ -46,13 +47,11 @@ How to compile in Windows
46------------------------- 47-------------------------
47 48
48To compile the sources to Windows binaries you need Visual Studio compiler and/or Windows SDK. 49To compile the sources to Windows binaries you need Visual Studio compiler and/or Windows SDK.
49You can use latest Windows Studio 2017/2019 to compile binaries for x86, x64 and arm64 platforms. 50You can use latest Windows Studio 2017/2019/2022 to compile binaries for x86, x64, arm64 and arm platforms.
50Also you can use old compilers for some platforms: 51Also you can use old compilers for some platforms:
51 x86 : Visual C++ 6.0 with Platform SDK 52 x86 : Visual C++ 6.0 with Platform SDK
52 x64 : Windows Server 2003 R2 Platform SDK 53 x64 : Windows Server 2003 R2 Platform SDK
53 arm64 : Windows Studio 2017 54 ia64 (itanium) : Windows Server 2003 R2 Platform SDK
54 arm : Windows Studio 2017
55 ia64 (itanium) : Windows Server 2003 R2 Platform SDK
56 arm for Windows CE : Standard SDK for Windows CE 5.0 55 arm for Windows CE : Standard SDK for Windows CE 5.0
57 56
58If you use MSVC6, specify also Platform SDK directories at top of directories lists: 57If 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:
702) via dsp file in Visual Studio. 692) via dsp file in Visual Studio.
71 70
72The dsp file compiling can be used for development and debug purposes. 71The dsp file compiling can be used for development and debug purposes.
73The final 7-Zip binaries are compiled via makefiles, that provide best 72All final 7-Zip binaries are compiled via makefiles, that provide best
74optimization options. 73optimization options.
75 74
76 75
@@ -94,8 +93,8 @@ MY_DYNAMIC_LINK
94Compiling 7-Zip for Unix/Linux 93Compiling 7-Zip for Unix/Linux
95------------------------------ 94------------------------------
96 95
97There are several otpions to compile 7-Zip with different compilers: gcc and clang. 96There are several options to compile 7-Zip with different compilers: gcc and clang.
98Also 7-Zip code contains two versions for some critical parts of code: in C and in Assembeler. 97Also 7-Zip code contains two versions for some parts of code: in C and in Assembeler.
99So if you compile the version with Assembeler code, you will get faster 7-Zip binary. 98So if you compile the version with Assembeler code, you will get faster 7-Zip binary.
100 99
1017-Zip's assembler code uses the following syntax for different platforms: 1007-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
109 https://github.com/nidud/asmc 108 https://github.com/nidud/asmc
110 109
1112) arm64: GNU assembler for ARM64 with preprocessor. 1102) arm64: GNU assembler for ARM64 with preprocessor.
112 That systax of that arm64 assembler code in 7-Zip is supported by GCC and CLANG for ARM64. 111 That systax is supported by GCC and CLANG for ARM64.
113 112
114There are different binaries that can be compiled from 7-Zip source. 113There are different binaries that can be compiled from 7-Zip source.
115There are 2 main files in folder for compiling: 114There are 2 main files in folder for compiling:
116 makefile - that can be used for compiling Windows version of 7-Zip with nmake command 115 makefile - that can be used for compiling Windows version of 7-Zip with nmake command
117 makefile.gcc - that can be used for compiling Linux/macOS versions of 7-Zip with make command 116 makefile.gcc - that can be used for compiling Linux/macOS versions of 7-Zip or Windows version
118 117 with MINGW (GCC) with make command.
118
119At first you must change the current folder to folder that contains `makefile.gcc`: 119At first you must change the current folder to folder that contains `makefile.gcc`:
120 120
121 cd CPP/7zip/Bundles/Alone2 121 cd CPP/7zip/Bundles/Alone2
@@ -143,7 +143,7 @@ To compile 7-Zip for arm64 with assembler:
143To compile 7-Zip for arm64 for macOS: 143To compile 7-Zip for arm64 for macOS:
144 make -j -f ../../cmpl_mac_arm64.mak 144 make -j -f ../../cmpl_mac_arm64.mak
145 145
146Also you can change some compiler options in the mak files: 146Also you can change some compiler options in the "mak" files:
147 cmpl_gcc.mak 147 cmpl_gcc.mak
148 var_gcc.mak 148 var_gcc.mak
149 warn_gcc.mak 149 warn_gcc.mak
@@ -207,16 +207,17 @@ Description of 7-Zip sources package
207 207
208DOC Documentation 208DOC Documentation
209--- 209---
210 7zFormat.txt - 7z format description 210 readme.txt - Readme file
211 copying.txt - GNU LGPL license
212 unRarLicense.txt - License for unRAR part of source code
213 src-history.txt - Sources history 211 src-history.txt - Sources history
212 7zC.txt - 7z ANSI-C Decoder description
213 7zFormat.txt - 7z format description
214 Methods.txt - Compression method IDs 214 Methods.txt - Compression method IDs
215 readme.txt - Readme file
216 lzma.txt - LZMA compression description 215 lzma.txt - LZMA compression description
217 7zip.nsi - installer script for NSIS 216 License.txt - license information
218 7zip.wix - installer script for WIX 217 copying.txt - GNU LGPL license
219 218 unRarLicense.txt - License for unRAR part of source code
219 7zip.wxs - installer script for WIX
220 7zip.hhp - html help project file
220 221
221Asm - Source code in Assembler : optimized code for CRC, SHA, AES, LZMA decoding. 222Asm - Source code in Assembler : optimized code for CRC, SHA, AES, LZMA decoding.
222 223
@@ -250,9 +251,9 @@ Windows common files for Windows related code
250 SFXWin 7z.sfx: Windows 7z SFX module 251 SFXWin 7z.sfx: Windows 7z SFX module
251 SFXSetup 7zS.sfx: Windows 7z SFX module for Installers 252 SFXSetup 7zS.sfx: Windows 7z SFX module for Installers
252 253
253 Compress files for compression/decompression 254 Compress files for compression / decompression
254 255
255 Crypto files for encryption / decompression 256 Crypto files for encryption / decryption
256 257
257 UI 258 UI
258 259
diff --git a/DOC/src-history.txt b/DOC/src-history.txt
index f546c4e..c1c1b71 100644
--- a/DOC/src-history.txt
+++ b/DOC/src-history.txt
@@ -1,6 +1,28 @@
1HISTORY of the 7-Zip source code 1HISTORY of the 7-Zip source code
2-------------------------------- 2--------------------------------
3 3
423.01 2023-06-20
5-------------------------
6- All external macros for compiling C/C++ code of 7-Zip now have Z7_ prefix.
7- 7-Zip COM interfaces now use new macros that allow to declare and implement COM interface.
8- The code has been modified to compile with the maximum diagnostic warning level:
9 -Wall in MSVC and -Weverything in CLANG.
10 And some warning types are disabled in 2 files:
11 - C/Compiler.h for C/C++ code warnings.
12 - CPP/Common/Common.h for C++ code warnings.
13- Linux/macOS versions of 7-Zip: IUnknown interface in new code doesn't use
14 virtual destructor that was used in previous 7-Zip and p7zip:
15 // virtual ~IUnknown() {}
16 So 7-Zip's dynamically linked shared libraries (codecs) are not compatible
17 between new 7-Zip for Linux/macOS and old 7-Zip (and p7zip).
18- Some optimizations in filters code: BCJ, BCJ2, Swap* and opthers.
19- If 7-Zip uses BCJ2 filter for big datasets compressing, it can use additional temp
20 files in system's TEMP folder. 7-Zip uses temp file for additional compressed
21 data stream, if size of such compressed stream is larger than predefined limit:
22 16 MiB in 32-bit version, 4 GiB in 64-bit version.
23- Some bugs were fixed.
24
25
422.00 2022-06-16 2622.00 2022-06-16
5------------------------- 27-------------------------
6- 7-Zip interfaces now support high precision (1 ns) timestamps with reserved 28- 7-Zip interfaces now support high precision (1 ns) timestamps with reserved