Compiler.ExeUpdateFunc.pas 17 KB

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