Compression.SevenZipDecoder.pas 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. unit Compression.SevenZipDecoder;
  2. {
  3. Inno Setup
  4. Copyright (C) 1997-2025 Jordan Russell
  5. Portions by Martijn Laan
  6. For conditions of distribution and use, see LICENSE.TXT.
  7. Interface to the 7-Zip Decoder OBJ in Compression.SevenZipDecoder\7ZipDecode,
  8. used by Setup.
  9. }
  10. interface
  11. type
  12. TOnExtractionProgress = function(const ArchiveName, FileName: string; const Progress, ProgressMax: Int64): Boolean of object;
  13. procedure Extract7ZipArchiveRedir(const DisableFsRedir: Boolean;
  14. const ArchiveFileName, DestDir: String; const FullPaths: Boolean;
  15. const OnExtractionProgress: TOnExtractionProgress);
  16. implementation
  17. uses
  18. Windows, SysUtils, Forms,
  19. PathFunc,
  20. Shared.SetupMessageIDs, SetupLdrAndSetup.Messages, SetupLdrAndSetup.RedirFunc,
  21. Setup.LoggingFunc, Setup.MainFunc, Setup.InstFunc;
  22. type
  23. TSevenZipDecodeState = record
  24. DisableFsRedir: Boolean;
  25. ExpandedArchiveFileName, ExpandedDestDir: String;
  26. LogBuffer: AnsiString;
  27. ExtractedArchiveName: String;
  28. OnExtractionProgress: TOnExtractionProgress;
  29. LastReportedProgress, LastReportedProgressMax: UInt64;
  30. Aborted: Boolean;
  31. end;
  32. var
  33. State: TSevenZipDecodeState;
  34. { Compiled by Visual Studio 2022 using compile.bat
  35. To enable source debugging recompile using compile-bcc32c.bat and turn off the VISUALSTUDIO define below
  36. Note that in a speed test the code produced by bcc32c was about 33% slower }
  37. {$L Src\Compression.SevenZipDecoder\7zDecode\IS7zDec.obj}
  38. {$DEFINE VISUALSTUDIO}
  39. function IS_7zDec(const fileName: PChar; const fullPaths: Bool): Integer; cdecl; external name '_IS_7zDec';
  40. function __CreateDirectoryW(lpPathName: LPCWSTR;
  41. lpSecurityAttributes: PSecurityAttributes): BOOL; cdecl;
  42. begin
  43. var ExpandedDir: String;
  44. if ValidateAndCombinePath(State.ExpandedDestDir, lpPathName, ExpandedDir) then
  45. Result := CreateDirectoryRedir(State.DisableFsRedir, ExpandedDir, lpSecurityAttributes)
  46. else begin
  47. Result := False;
  48. SetLastError(ERROR_ACCESS_DENIED);
  49. end;
  50. end;
  51. { Never actually called but still required by the linker }
  52. function __CreateFileA(lpFileName: LPCSTR; dwDesiredAccess, dwShareMode: DWORD;
  53. lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
  54. hTemplateFile: THandle): THandle; cdecl;
  55. begin
  56. { Return an error if we do ever get called which is unwanted because it should
  57. use CreateFileW and not CreateFileA }
  58. Result := INVALID_HANDLE_VALUE;
  59. SetLastError(ERROR_INVALID_FUNCTION);
  60. end;
  61. function __CreateFileW(lpFileName: LPCWSTR; dwDesiredAccess, dwShareMode: DWORD;
  62. lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
  63. hTemplateFile: THandle): THandle; cdecl;
  64. begin
  65. { Filenames read from archives aren't validated at all by the SDK's 7zMain.c,
  66. so we have to handle that ourself. Most importantly, we need to make sure a
  67. malicious archive cannot create files outside of the destination directory. }
  68. var ExpandedFileName: String;
  69. if ((dwDesiredAccess = GENERIC_READ) and
  70. PathExpand(lpFileName, ExpandedFileName) and
  71. (PathCompare(ExpandedFileName, State.ExpandedArchiveFileName) = 0)) or
  72. ((dwDesiredAccess = GENERIC_WRITE) and
  73. ValidateAndCombinePath(State.ExpandedDestDir, lpFileName, ExpandedFileName)) then
  74. Result := CreateFileRedir(State.DisableFsRedir, ExpandedFileName,
  75. dwDesiredAccess, dwShareMode, lpSecurityAttributes,
  76. dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile)
  77. else begin
  78. Result := INVALID_HANDLE_VALUE;
  79. SetLastError(ERROR_ACCESS_DENIED);
  80. end;
  81. end;
  82. {$IFDEF VISUALSTUDIO}
  83. function __FileTimeToLocalFileTime(lpFileTime: PFileTime; var lpLocalFileTime: TFileTime): BOOL; cdecl;
  84. begin
  85. Result := FileTimeToLocalFileTime(lpFileTime, lpLocalFileTime);
  86. end;
  87. { Never actually called but still required by the linker }
  88. function __GetFileSize(hFile: THandle; lpFileSizeHigh: Pointer): DWORD; cdecl;
  89. begin
  90. Result := GetFileSize(hFile, lpFileSizeHigh);
  91. end;
  92. function __ReadFile(hFile: THandle; var Buffer; nNumberOfBytesToRead: DWORD;
  93. var lpNumberOfBytesRead: DWORD; lpOverlapped: POverlapped): BOOL; cdecl;
  94. begin
  95. Result := ReadFile(hFile, Buffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
  96. end;
  97. function __SetFileAttributesW(lpFileName: LPCWSTR; dwFileAttributes: DWORD): BOOL; cdecl;
  98. begin
  99. { See above }
  100. var ExpandedFileName: String;
  101. if ValidateAndCombinePath(State.ExpandedDestDir, lpFileName, ExpandedFileName) then
  102. Result := SetFileAttributesRedir(State.DisableFsRedir, ExpandedFileName, dwFileAttributes)
  103. else begin
  104. Result := False;
  105. SetLastError(ERROR_ACCESS_DENIED);
  106. end;
  107. end;
  108. function __SetFilePointer(hFile: THandle; lDistanceToMove: Longint;
  109. lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD): DWORD; cdecl;
  110. begin
  111. Result := SetFilePointer(hFile, lDistanceToMove, lpDistanceToMoveHigh, dwMoveMethod);
  112. end;
  113. function __SetFileTime(hFile: THandle;
  114. lpCreationTime, lpLastAccessTime, lpLastWriteTime: PFileTime): BOOL; cdecl;
  115. begin
  116. Result := SetFileTime(hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime);
  117. end;
  118. function __WriteFile(hFile: THandle; const Buffer; nNumberOfBytesToWrite: DWORD;
  119. var lpNumberOfBytesWritten: DWORD; lpOverlapped: POverlapped): BOOL; cdecl;
  120. begin
  121. Result := WriteFile(hFile, Buffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped);
  122. end;
  123. function __CloseHandle(hObject: THandle): BOOL; cdecl;
  124. begin
  125. Result := CloseHandle(hObject);
  126. end;
  127. function __GetLastError: DWORD; cdecl;
  128. begin
  129. Result := GetLastError;
  130. end;
  131. function __LocalFree(hMem: HLOCAL): HLOCAL; cdecl;
  132. begin
  133. Result := LocalFree(hMem);
  134. end;
  135. function __FormatMessageA(dwFlags: DWORD; lpSource: Pointer; dwMessageId: DWORD; dwLanguageId: DWORD;
  136. lpBuffer: LPSTR; nSize: DWORD; Arguments: Pointer): DWORD; cdecl;
  137. begin
  138. Result := FormatMessageA(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments);
  139. end;
  140. function __WideCharToMultiByte(CodePage: UINT; dwFlags: DWORD;
  141. lpWideCharStr: LPWSTR; cchWideChar: Integer; lpMultiByteStr: LPSTR;
  142. cchMultiByte: Integer; lpDefaultChar: LPCSTR; lpUsedDefaultChar: PBOOL): Integer; cdecl;
  143. begin
  144. Result := WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cchMultiByte, lpDefaultChar, lpUsedDefaultChar);
  145. end;
  146. //https://github.com/rust-lang/compiler-builtins/issues/403
  147. procedure __allshl; register; external 'ntdll.dll' name '_allshl';
  148. procedure __aullshr; register; external 'ntdll.dll' name '_aullshr';
  149. {$ELSE}
  150. procedure __aullrem; stdcall; external 'ntdll.dll' name '_aullrem';
  151. procedure __aulldiv; stdcall; external 'ntdll.dll' name '_aulldiv';
  152. {$ENDIF}
  153. function _memcpy(dest, src: Pointer; n: Cardinal): Pointer; cdecl;
  154. begin
  155. Move(src^, dest^, n);
  156. Result := dest;
  157. end;
  158. function _memset(dest: Pointer; c: Integer; n: Cardinal): Pointer; cdecl;
  159. begin
  160. FillChar(dest^, n, c);
  161. Result := dest;
  162. end;
  163. function _malloc(size: NativeUInt): Pointer; cdecl;
  164. begin
  165. if size > NativeUInt(High(NativeInt)) then
  166. Result := nil
  167. else begin
  168. try
  169. GetMem(Result, NativeInt(size));
  170. except
  171. on EOutOfMemory do
  172. Result := nil;
  173. end;
  174. end;
  175. end;
  176. procedure _free(address: Pointer); cdecl;
  177. begin
  178. FreeMem(address);
  179. end;
  180. function _wcscmp(string1, string2: PChar): Integer; cdecl;
  181. begin
  182. Result := StrComp(string1, string2);
  183. end;
  184. procedure Log(const S: AnsiString);
  185. begin
  186. if S <> '' then
  187. Setup.LoggingFunc.Log(UTF8ToString(S));
  188. end;
  189. function __fputs(str: PAnsiChar; unused: Pointer): Integer; cdecl;
  190. function FindNewLine(const S: AnsiString): Integer;
  191. begin
  192. { 7zMain.c always sends #10 as newline but its call to FormatMessage can cause #13#10 anyway }
  193. var N := Length(S);
  194. for var I := 1 to N do
  195. if CharInSet(S[I], [#13, #10]) then
  196. Exit(I);
  197. Result := 0;
  198. end;
  199. begin
  200. try
  201. State.LogBuffer := State.LogBuffer + str;
  202. var P := FindNewLine(State.LogBuffer);
  203. while P <> 0 do begin
  204. Log(Copy(State.LogBuffer, 1, P-1));
  205. if (State.LogBuffer[P] = #13) and (P < Length(State.LogBuffer)) and (State.LogBuffer[P+1] = #10) then
  206. Inc(P);
  207. Delete(State.LogBuffer, 1, P);
  208. P := FindNewLine(State.LogBuffer);
  209. end;
  210. Result := 0;
  211. except
  212. Result := -1; { EOF }
  213. end;
  214. end;
  215. procedure _ReportProgress(const FileName: PChar; const Progress, ProgressMax: UInt64; var Abort: Bool); cdecl;
  216. begin
  217. if Assigned(State.OnExtractionProgress) then begin
  218. { Make sure script isn't called crazy often because that would slow the extraction significantly. Only report:
  219. -At start or finish
  220. -Or if somehow Progress decreased or Max changed
  221. -Or if at least 512 KB progress was made since last report
  222. }
  223. if (Progress = 0) or (Progress = ProgressMax) or
  224. (Progress < State.LastReportedProgress) or (ProgressMax <> State.LastReportedProgressMax) or
  225. ((Progress - State.LastReportedProgress) > 524288) then begin
  226. try
  227. if not State.OnExtractionProgress(State.ExtractedArchiveName, FileName, Progress, ProgressMax) then
  228. Abort := True;
  229. finally
  230. State.LastReportedProgress := Progress;
  231. State.LastReportedProgressMax := ProgressMax;
  232. end;
  233. end;
  234. end;
  235. if not Abort and DownloadTemporaryFileOrExtract7ZipArchiveProcessMessages then
  236. Application.ProcessMessages;
  237. if Abort then
  238. State.Aborted := True;
  239. end;
  240. procedure Extract7ZipArchiveRedir(const DisableFsRedir: Boolean;
  241. const ArchiveFileName, DestDir: String; const FullPaths: Boolean;
  242. const OnExtractionProgress: TOnExtractionProgress);
  243. begin
  244. if ArchiveFileName = '' then
  245. InternalError('Extract7ZipArchive: Invalid ArchiveFileName value');
  246. if DestDir = '' then
  247. InternalError('Extract7ZipArchive: Invalid DestDir value');
  248. LogFmt('Extracting 7-Zip archive %s to %s. Full paths? %s', [ArchiveFileName, DestDir, SYesNo[FullPaths]]);
  249. if not ForceDirectories(DisableFsRedir, DestDir) then
  250. raise Exception.Create(FmtSetupMessage(msgErrorExtractionFailed, ['-1']));
  251. State.DisableFsRedir := DisableFsRedir;
  252. State.ExpandedArchiveFileName := PathExpand(ArchiveFileName);
  253. State.ExpandedDestDir := AddBackslash(PathExpand(DestDir));
  254. State.LogBuffer := '';
  255. State.ExtractedArchiveName := PathExtractName(ArchiveFileName);
  256. State.OnExtractionProgress := OnExtractionProgress;
  257. State.LastReportedProgress := 0;
  258. State.LastReportedProgressMax := 0;
  259. State.Aborted := False;
  260. var Res := IS_7zDec(PChar(ArchiveFileName), FullPaths);
  261. if State.LogBuffer <> '' then
  262. Log(State.LogBuffer);
  263. if State.Aborted then
  264. raise Exception.Create(SetupMessages[msgErrorExtractionAborted])
  265. else if Res <> 0 then
  266. raise Exception.Create(FmtSetupMessage(msgErrorExtractionFailed, [Res.ToString]));
  267. end;
  268. end.