CompExeUpdate.pas 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. unit CompExeUpdate;
  2. {
  3. Inno Setup
  4. Copyright (C) 1997-2024 Jordan Russell
  5. Portions by Martijn Laan
  6. For conditions of distribution and use, see LICENSE.TXT.
  7. PE header and resource update functions used by the compiler only
  8. }
  9. interface
  10. uses
  11. Windows, SysUtils, FileClass, VerInfo;
  12. {$I VERSION.INC}
  13. procedure UpdateSetupPEHeaderFields(const F: TCustomFile;
  14. const IsTSAware, IsDEPCompatible, IsASLRCompatible: Boolean);
  15. procedure UpdateIcons(const FileName, IcoFileName: String; const DeleteUninstallIcon: Boolean);
  16. procedure UpdateVersionInfo(const F: TCustomFile;
  17. const NewBinaryFileVersion, NewBinaryProductVersion: TFileVersionNumbers;
  18. const NewCompanyName, NewFileDescription, NewTextFileVersion, NewLegalCopyright,
  19. NewProductName, NewTextProductVersion, NewOriginalFileName: String;
  20. const SetFileVersionAndDescription: Boolean);
  21. procedure PreventCOMCTL32Sideloading(const F: TCustomFile);
  22. implementation
  23. uses
  24. ResUpdate, Math, Int64Em;
  25. procedure UpdateSetupPEHeaderFields(const F: TCustomFile;
  26. const IsTSAware, IsDEPCompatible, IsASLRCompatible: Boolean);
  27. function SeekToPEHeader(const F: TCustomFile): Boolean;
  28. var
  29. DosHeader: packed record
  30. Sig: array[0..1] of AnsiChar;
  31. Other: array[0..57] of Byte;
  32. PEHeaderOffset: LongWord;
  33. end;
  34. Sig: DWORD;
  35. begin
  36. Result := False;
  37. F.Seek(0);
  38. if F.Read(DosHeader, SizeOf(DosHeader)) = SizeOf(DosHeader) then begin
  39. if (DosHeader.Sig[0] = 'M') and (DosHeader.Sig[1] = 'Z') and
  40. (DosHeader.PEHeaderOffset <> 0) then begin
  41. F.Seek(DosHeader.PEHeaderOffset);
  42. if F.Read(Sig, SizeOf(Sig)) = SizeOf(Sig) then
  43. if Sig = IMAGE_NT_SIGNATURE then
  44. Result := True;
  45. end;
  46. end;
  47. end;
  48. const
  49. IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = $0040;
  50. IMAGE_DLLCHARACTERISTICS_NX_COMPAT = $0100;
  51. IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = $8000;
  52. OffsetOfOperatingSystemVersion = $28;
  53. OffsetOfImageVersion = $2C;
  54. OffsetOfSubsystemVersion = $30;
  55. OffsetOfDllCharacteristics = $46;
  56. var
  57. Header: TImageFileHeader;
  58. Ofs: Cardinal;
  59. OptMagic, DllChars, OrigDllChars: Word;
  60. begin
  61. if SeekToPEHeader(F) then begin
  62. if (F.Read(Header, SizeOf(Header)) = SizeOf(Header)) and
  63. (Header.SizeOfOptionalHeader = 224) then begin
  64. Ofs := F.Position.Lo;
  65. if (F.Read(OptMagic, SizeOf(OptMagic)) = SizeOf(OptMagic)) and
  66. (OptMagic = IMAGE_NT_OPTIONAL_HDR32_MAGIC) then begin
  67. { Update DllCharacteristics }
  68. F.Seek(Ofs + OffsetOfDllCharacteristics);
  69. if F.Read(DllChars, SizeOf(DllChars)) = SizeOf(DllChars) then begin
  70. OrigDllChars := DllChars;
  71. if IsTSAware then
  72. DllChars := DllChars or IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE
  73. else
  74. DllChars := DllChars and not IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
  75. if IsDEPCompatible then
  76. DllChars := DllChars or IMAGE_DLLCHARACTERISTICS_NX_COMPAT
  77. else
  78. DllChars := DllChars and not IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
  79. { Note: because we stripped relocations from Setup(Ldr).e32 during
  80. compilation IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE won't actually
  81. enable ASLR, but allow setting it anyway to make checkers happy. }
  82. if IsASLRCompatible then
  83. DllChars := DllChars or IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
  84. else
  85. DllChars := DllChars and not IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
  86. if DllChars <> OrigDllChars then begin
  87. F.Seek(Ofs + OffsetOfDllCharacteristics);
  88. F.WriteBuffer(DllChars, SizeOf(DllChars));
  89. end;
  90. Exit;
  91. end;
  92. end;
  93. end;
  94. end;
  95. raise Exception.Create('UpdateSetupPEHeaderFields failed');
  96. end;
  97. procedure ResUpdateError(const Msg: String);
  98. begin
  99. raise Exception.Create('Resource update error: ' + Msg);
  100. end;
  101. procedure ResUpdateErrorWithLastError(const Msg: String);
  102. begin
  103. ResUpdateError(Msg + ' (' + IntToStr(GetLastError) + ')');
  104. end;
  105. procedure UpdateVersionInfo(const F: TCustomFile;
  106. const NewBinaryFileVersion, NewBinaryProductVersion: TFileVersionNumbers;
  107. const NewCompanyName, NewFileDescription, NewTextFileVersion, NewLegalCopyright,
  108. NewProductName, NewTextProductVersion, NewOriginalFileName: String;
  109. const SetFileVersionAndDescription: Boolean);
  110. function WideStrsEqual(P1, P2: PWideChar): Boolean;
  111. function WideUpCase(C: WideChar): WideChar;
  112. begin
  113. Result := C;
  114. if (Result >= 'a') and (Result <= 'z') then
  115. Dec(Result, Ord('a') - Ord('A'));
  116. end;
  117. begin
  118. while True do begin
  119. if WideUpCase(P1^) <> WideUpCase(P2^) then begin
  120. Result := False;
  121. Exit;
  122. end;
  123. if P1^ = #0 then
  124. Break;
  125. Inc(P1);
  126. Inc(P2);
  127. end;
  128. Result := True;
  129. end;
  130. procedure BumpToDWordBoundary(var P: Pointer);
  131. begin
  132. if Cardinal(P) and 3 <> 0 then
  133. Cardinal(P) := (Cardinal(P) or 3) + 1;
  134. end;
  135. function QueryValue(P: Pointer; Path: PWideChar; var Buf: Pointer;
  136. var BufLen: Cardinal): Boolean;
  137. var
  138. EndP: Pointer;
  139. ValueLength: Cardinal;
  140. begin
  141. Result := False;
  142. Cardinal(EndP) := Cardinal(P) + PWord(P)^;
  143. Inc(PWord(P));
  144. ValueLength := PWord(P)^;
  145. Inc(PWord(P));
  146. Inc(PWord(P));
  147. if WideStrsEqual(PWideChar(P), Path) then begin
  148. Inc(PWideChar(P), lstrlenW(P) + 1);
  149. BumpToDWordBoundary(P);
  150. Inc(Path, lstrlenW(Path) + 1);
  151. if Path^ = #0 then begin
  152. { Found the requested value }
  153. Buf := P;
  154. BufLen := ValueLength;
  155. Result := True;
  156. end
  157. else begin
  158. { Handle children.
  159. Note: Like VerQueryValue, we always treat ValueLength as a byte count
  160. when looking for child nodes. Many resource compilers, including
  161. Borland's, wrongly set ValueLength to a *character* count on string
  162. nodes. But since we never try to query for a child of a string node,
  163. that doesn't matter here. }
  164. Inc(Cardinal(P), ValueLength);
  165. BumpToDWordBoundary(P);
  166. while Cardinal(P) < Cardinal(EndP) do begin
  167. Result := QueryValue(P, Path, Buf, BufLen);
  168. if Result then
  169. Exit;
  170. Inc(Cardinal(P), PWord(P)^);
  171. BumpToDWordBoundary(P);
  172. end;
  173. end;
  174. end;
  175. end;
  176. procedure ReplaceWithRealCopyrightSymbols(const Value: PWideChar);
  177. var
  178. Len, I, J: Integer;
  179. begin
  180. Len := lstrlenW(Value);
  181. for I := 0 to Len-3 do begin
  182. if (Value[I] = '(') and (Value[I+1] = 'C') and (Value[I+2] = ')') then begin
  183. Value[I] := WideChar($00A9);
  184. { Shift back two characters }
  185. for J := I+1 to Len-3 do
  186. Value[J] := Value[J+2];
  187. Value[Len-2] := ' ';
  188. Value[Len-1] := ' ';
  189. end;
  190. end;
  191. end;
  192. procedure UpdateStringValue(P: Pointer; const Path: PWideChar; NewValue: String);
  193. var
  194. Value: PWideChar;
  195. ValueLen: Cardinal;
  196. begin
  197. if not QueryValue(P, Path, Pointer(Value), ValueLen) then
  198. ResUpdateError('Unexpected version resource format (1)');
  199. Move(Pointer(NewValue)^, Value^, (Min(Length(NewValue), lstrlenW(Value)))*SizeOf(Char));
  200. ReplaceWithRealCopyrightSymbols(Value);
  201. end;
  202. procedure UpdateFixedFileInfo(P: Pointer; const Path: PWideChar;
  203. const NewFileVersion, NewProductVersion: TFileVersionNumbers;
  204. const SetFileVersion: Boolean);
  205. var
  206. FixedFileInfo: PVSFixedFileInfo;
  207. ValueLen: Cardinal;
  208. begin
  209. if not QueryValue(P, Path, Pointer(FixedFileInfo), ValueLen) then
  210. ResUpdateError('Unexpected version resource format (2)');
  211. if FixedFileInfo.dwSignature <> $FEEF04BD then
  212. ResUpdateError('Unexpected version resource format (3)');
  213. if SetFileVersion then begin
  214. FixedFileInfo.dwFileVersionLS := NewFileVersion.LS;
  215. FixedFileInfo.dwFileVersionMS := NewFileVersion.MS;
  216. end;
  217. FixedFileInfo.dwProductVersionLS := NewProductVersion.LS;
  218. FixedFileInfo.dwProductVersionMS := NewProductVersion.MS;
  219. end;
  220. var
  221. ResOffset, ResSize: Cardinal;
  222. VersRes: Pointer;
  223. begin
  224. { Locate the resource }
  225. ResSize := SeekToResourceData(F, Cardinal(RT_VERSION), 1);
  226. ResOffset := F.Position.Lo;
  227. GetMem(VersRes, ResSize);
  228. try
  229. { Read the resource }
  230. F.ReadBuffer(VersRes^, ResSize);
  231. { Update the resource }
  232. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'CompanyName'#0, NewCompanyName);
  233. if SetFileVersionAndDescription then begin
  234. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'FileDescription'#0, NewFileDescription);
  235. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'FileVersion'#0, NewTextFileVersion);
  236. end;
  237. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'LegalCopyright'#0, NewLegalCopyright);
  238. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'ProductName'#0, NewProductName);
  239. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'OriginalFileName'#0, NewOriginalFileName);
  240. UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'ProductVersion'#0, NewTextProductVersion);
  241. UpdateFixedFileInfo(VersRes, 'VS_VERSION_INFO'#0, NewBinaryFileVersion, NewBinaryProductVersion, SetFileVersionAndDescription);
  242. { Write the updated resource }
  243. F.Seek(ResOffset);
  244. F.WriteBuffer(VersRes^, ResSize);
  245. finally
  246. FreeMem(VersRes);
  247. end;
  248. end;
  249. function EnumLangsFunc(hModule: Cardinal; lpType, lpName: PAnsiChar; wLanguage: Word; lParam: Integer): BOOL; stdcall;
  250. begin
  251. PWord(lParam)^ := wLanguage;
  252. Result := False;
  253. end;
  254. function GetResourceLanguage(hModule: Cardinal; lpType, lpName: PChar; var wLanguage: Word): Boolean;
  255. begin
  256. wLanguage := 0;
  257. EnumResourceLanguages(hModule, lpType, lpName, @EnumLangsFunc, Integer(@wLanguage));
  258. Result := True;
  259. end;
  260. procedure UpdateIcons(const FileName, IcoFileName: String; const DeleteUninstallIcon: Boolean);
  261. type
  262. PIcoItemHeader = ^TIcoItemHeader;
  263. TIcoItemHeader = packed record
  264. Width: Byte;
  265. Height: Byte;
  266. Colors: Byte;
  267. Reserved: Byte;
  268. Planes: Word;
  269. BitCount: Word;
  270. ImageSize: DWORD;
  271. end;
  272. PIcoItem = ^TIcoItem;
  273. TIcoItem = packed record
  274. Header: TIcoItemHeader;
  275. Offset: DWORD;
  276. end;
  277. PIcoHeader = ^TIcoHeader;
  278. TIcoHeader = packed record
  279. Reserved: Word;
  280. Typ: Word;
  281. ItemCount: Word;
  282. Items: array [0..MaxInt shr 4 - 1] of TIcoItem;
  283. end;
  284. PGroupIconDirItem = ^TGroupIconDirItem;
  285. TGroupIconDirItem = packed record
  286. Header: TIcoItemHeader;
  287. Id: Word;
  288. end;
  289. PGroupIconDir = ^TGroupIconDir;
  290. TGroupIconDir = packed record
  291. Reserved: Word;
  292. Typ: Word;
  293. ItemCount: Word;
  294. Items: array [0..MaxInt shr 4 - 1] of TGroupIconDirItem;
  295. end;
  296. function IsValidIcon(P: Pointer; Size: Cardinal): Boolean;
  297. var
  298. ItemCount: Cardinal;
  299. begin
  300. Result := False;
  301. if Size < Cardinal(SizeOf(Word) * 3) then
  302. Exit;
  303. if (PChar(P)[0] = 'M') and (PChar(P)[1] = 'Z') then
  304. Exit;
  305. ItemCount := PIcoHeader(P).ItemCount;
  306. if Size < Cardinal((SizeOf(Word) * 3) + (ItemCount * SizeOf(TIcoItem))) then
  307. Exit;
  308. P := @PIcoHeader(P).Items;
  309. while ItemCount > Cardinal(0) do begin
  310. if (Cardinal(PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize) < Cardinal(PIcoItem(P).Offset)) or
  311. (Cardinal(PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize) > Cardinal(Size)) then
  312. Exit;
  313. Inc(PIcoItem(P));
  314. Dec(ItemCount);
  315. end;
  316. Result := True;
  317. end;
  318. function DeleteIcon(const H: THandle; const M: HMODULE; const ResourceName: PChar): PGroupIconDir;
  319. var
  320. R: HRSRC;
  321. Res: HGLOBAL;
  322. GroupIconDir: PGroupIconDir;
  323. I: Integer;
  324. wLanguage: Word;
  325. begin
  326. { Load the group icon resource }
  327. R := FindResource(M, ResourceName, RT_GROUP_ICON);
  328. if R = 0 then
  329. ResUpdateErrorWithLastError('FindResource failed (1)');
  330. Res := LoadResource(M, R);
  331. if Res = 0 then
  332. ResUpdateErrorWithLastError('LoadResource failed (1)');
  333. GroupIconDir := LockResource(Res);
  334. if GroupIconDir = nil then
  335. ResUpdateErrorWithLastError('LockResource failed (1)');
  336. { Delete the group icon resource }
  337. if not GetResourceLanguage(M, RT_GROUP_ICON, ResourceName, wLanguage) then
  338. ResUpdateError('GetResourceLanguage failed (1)');
  339. if not UpdateResource(H, RT_GROUP_ICON, ResourceName, wLanguage, nil, 0) then
  340. ResUpdateErrorWithLastError('UpdateResource failed (1)');
  341. { Delete the icon resources that belonged to the group }
  342. for I := 0 to GroupIconDir.ItemCount-1 do begin
  343. if not GetResourceLanguage(M, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage) then
  344. ResUpdateError('GetResourceLanguage failed (2)');
  345. if not UpdateResource(H, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage, nil, 0) then
  346. ResUpdateErrorWithLastError('UpdateResource failed (2)');
  347. end;
  348. Result := GroupIconDir;
  349. end;
  350. var
  351. H: THandle;
  352. M: HMODULE;
  353. OldGroupIconDir, NewGroupIconDir: PGroupIconDir;
  354. I: Integer;
  355. F: TFile;
  356. Ico: PIcoHeader;
  357. N: Cardinal;
  358. NewGroupIconDirSize: LongInt;
  359. begin
  360. Ico := nil;
  361. try
  362. { Load the icons }
  363. F := TFile.Create(IcoFileName, fdOpenExisting, faRead, fsRead);
  364. try
  365. N := F.CappedSize;
  366. if Cardinal(N) > Cardinal($100000) then { sanity check }
  367. ResUpdateError('Icon file is too large');
  368. GetMem(Ico, N);
  369. F.ReadBuffer(Ico^, N);
  370. finally
  371. F.Free;
  372. end;
  373. { Ensure the icon is valid }
  374. if not IsValidIcon(Ico, N) then
  375. ResUpdateError('Icon file is invalid');
  376. { Update the resources }
  377. H := BeginUpdateResource(PChar(FileName), False);
  378. if H = 0 then
  379. ResUpdateErrorWithLastError('BeginUpdateResource failed (1)');
  380. try
  381. M := LoadLibraryEx(PChar(FileName), 0, LOAD_LIBRARY_AS_DATAFILE);
  382. if M = 0 then
  383. ResUpdateErrorWithLastError('LoadLibraryEx failed (1)');
  384. try
  385. { Delete default icons }
  386. OldGroupIconDir := DeleteIcon(H, M, 'MAINICON');
  387. if DeleteUninstallIcon then
  388. DeleteIcon(H, M, 'Z_UNINSTALLICON');
  389. { Build the new group icon resource }
  390. NewGroupIconDirSize := 3*SizeOf(Word)+Ico.ItemCount*SizeOf(TGroupIconDirItem);
  391. GetMem(NewGroupIconDir, NewGroupIconDirSize);
  392. try
  393. { Build the new group icon resource }
  394. NewGroupIconDir.Reserved := OldGroupIconDir.Reserved;
  395. NewGroupIconDir.Typ := OldGroupIconDir.Typ;
  396. NewGroupIconDir.ItemCount := Ico.ItemCount;
  397. for I := 0 to NewGroupIconDir.ItemCount-1 do begin
  398. NewGroupIconDir.Items[I].Header := Ico.Items[I].Header;
  399. NewGroupIconDir.Items[I].Id := I+100; //start at 100 to avoid overwriting other icons that may exist
  400. end;
  401. { Update 'MAINICON' }
  402. for I := 0 to NewGroupIconDir.ItemCount-1 do
  403. if not UpdateResource(H, RT_ICON, MakeIntResource(NewGroupIconDir.Items[I].Id), 1033, Pointer(DWORD(Ico) + Ico.Items[I].Offset), Ico.Items[I].Header.ImageSize) then
  404. ResUpdateErrorWithLastError('UpdateResource failed (3)');
  405. { Update the icons }
  406. if not UpdateResource(H, RT_GROUP_ICON, 'MAINICON', 1033, NewGroupIconDir, NewGroupIconDirSize) then
  407. ResUpdateErrorWithLastError('UpdateResource failed (4)');
  408. finally
  409. FreeMem(NewGroupIconDir);
  410. end;
  411. finally
  412. FreeLibrary(M);
  413. end;
  414. except
  415. EndUpdateResource(H, True); { discard changes }
  416. raise;
  417. end;
  418. if not EndUpdateResource(H, False) then
  419. ResUpdateErrorWithLastError('EndUpdateResource failed');
  420. finally
  421. FreeMem(Ico);
  422. end;
  423. end;
  424. procedure PreventCOMCTL32Sideloading(const F: TCustomFile);
  425. const
  426. DependencyStartTag: AnsiString = '<dependency>';
  427. DependencyEndTag: AnsiString = '</dependency>';
  428. FileStartTag: AnsiString = '<file name="';
  429. COMCTL32Entry: AnsiString = '<file name="comctl32.dll" loadFrom="%SystemRoot%\system32\" />'#13#10;
  430. var
  431. S: AnsiString;
  432. Offset: Integer64;
  433. P,Q,R: Integer;
  434. begin
  435. { Read the manifest resource into a string }
  436. SetString(S, nil, SeekToResourceData(F, 24, 1));
  437. Offset := F.Position;
  438. F.ReadBuffer(S[1], Length(S));
  439. { Locate and update the <dependency> tag }
  440. P := Pos(DependencyStartTag, S);
  441. if P = 0 then
  442. ResUpdateError('<dependency> tag not found');
  443. Q := Pos(DependencyEndTag, S);
  444. if Q <= P then
  445. ResUpdateError('<dependency> end tag not found');
  446. Q := Q+Length(DependencyEndTag);
  447. if Length(COMCTL32Entry) > Q-P then
  448. ResUpdateError('<dependency> tag shorter than replacement');
  449. R := Pos(FileStartTag, S);
  450. if R <= Q then
  451. ResUpdateError('<dependency> end tag after <file>?');
  452. Inc64(Offset, P-1);
  453. F.Seek64(Offset);
  454. F.WriteAnsiString(AnsiString(Format('%*s', [Q-P-Length(COMCTL32Entry), ' '])));
  455. F.WriteAnsiString(AnsiString(Copy(S, Q, R-Q)));
  456. F.WriteAnsiString(COMCTL32Entry);
  457. end;
  458. end.