Compiler.ExeUpdateFunc.pas 17 KB

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