forked from jrsoftware/issrc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstall.pas
3651 lines (3386 loc) · 150 KB
/
Install.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit Install;
{
Inno Setup
Copyright (C) 1997-2020 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Installation procedures
}
interface
{$I VERSION.INC}
procedure PerformInstall(var Succeeded: Boolean; const ChangesEnvironment,
ChangesAssociations: Boolean);
type
TOnDownloadProgress = function(const Url, BaseName: string; const Progress, ProgressMax: Int64): Boolean of object;
procedure ExtractTemporaryFile(const BaseName: String);
function ExtractTemporaryFiles(const Pattern: String): Integer;
function DownloadTemporaryFile(const Url, BaseName, RequiredSHA256OfFile: String; const OnDownloadProgress: TOnDownloadProgress): Int64;
function DownloadTemporaryFileSize(const Url: String): Int64;
implementation
uses
Windows, SysUtils, Messages, Classes, Forms, ShlObj, Struct, Undo, SetupTypes,
InstFunc, InstFnc2, SecurityFunc, Msgs, Main, Logging, Extract, FileClass,
Compress, SHA1, PathFunc, CmnFunc, CmnFunc2, RedirFunc, Int64Em, MsgIDs,
Wizard, DebugStruct, DebugClient, VerInfo, ScriptRunner, RegDLL, Helper,
ResUpdate, DotNet, TaskbarProgressFunc, NewProgressBar, RestartManager, Net.HTTPClient;
type
TSetupUninstallLog = class(TUninstallLog)
protected
procedure HandleException; override;
end;
var
CurProgress: Integer64;
ProgressShiftCount: Cardinal;
{ TSetupUninstallLog }
procedure TSetupUninstallLog.HandleException;
begin
Application.HandleException(Self);
end;
procedure SetFilenameLabelText(const S: String; const CallUpdate: Boolean);
begin
WizardForm.FilenameLabel.Caption := MinimizePathName(S, WizardForm.FilenameLabel.Font, WizardForm.FileNameLabel.Width);
if CallUpdate then
WizardForm.FilenameLabel.Update;
end;
procedure SetStatusLabelText(const S: String);
begin
WizardForm.StatusLabel.Caption := S;
WizardForm.StatusLabel.Update;
SetFilenameLabelText('', True);
end;
procedure InstallMessageBoxCallback(const Flags: LongInt; const After: Boolean;
const Param: LongInt);
const
States: array [TNewProgressBarState] of TTaskbarProgressState =
(tpsNormal, tpsError, tpsPaused);
var
NewState: TNewProgressBarState;
begin
if After then
NewState := npbsNormal
else if (Flags and MB_ICONSTOP) <> 0 then
NewState := npbsError
else
NewState := npbsPaused;
with WizardForm.ProgressGauge do begin
State := NewState;
Invalidate;
end;
SetAppTaskbarProgressState(States[NewState]);
end;
procedure CalcFilesSize(var InstallFilesSize, AfterInstallFilesSize: Integer64);
var
N: Integer;
CurFile: PSetupFileEntry;
FileSize: Integer64;
begin
InstallFilesSize.Hi := 0;
InstallFilesSize.Lo := 0;
AfterInstallFilesSize := InstallFilesSize;
for N := 0 to Entries[seFile].Count-1 do begin
CurFile := PSetupFileEntry(Entries[seFile][N]);
if ShouldProcessFileEntry(WizardComponents, WizardTasks, CurFile, False) then begin
with CurFile^ do begin
if LocationEntry <> -1 then { not an "external" file }
FileSize := PSetupFileLocationEntry(Entries[seFileLocation][
LocationEntry])^.OriginalSize
else
FileSize := ExternalSize;
Inc6464(InstallFilesSize, FileSize);
if not (foDeleteAfterInstall in Options) then
Inc6464(AfterInstallFilesSize, FileSize);
end;
end;
end;
end;
procedure InitProgressGauge(const InstallFilesSize: Integer64);
var
NewMaxValue: Integer64;
begin
{ Calculate the MaxValue for the progress meter }
NewMaxValue.Hi := 0;
NewMaxValue.Lo := 1000 * Entries[seIcon].Count;
if Entries[seIni].Count <> 0 then Inc(NewMaxValue.Lo, 1000);
if Entries[seRegistry].Count <> 0 then Inc(NewMaxValue.Lo, 1000);
Inc6464(NewMaxValue, InstallFilesSize);
{ To avoid progress updates that are too small to result in any visible
change, divide the Max value by 2 until it's under 1500 }
ProgressShiftCount := 0;
while (NewMaxValue.Hi <> 0) or (NewMaxValue.Lo >= Cardinal(1500)) do begin
Shr64(NewMaxValue, 1);
Inc(ProgressShiftCount);
end;
WizardForm.ProgressGauge.Max := NewMaxValue.Lo;
SetMessageBoxCallbackFunc(InstallMessageBoxCallback, 0);
end;
procedure UpdateProgressGauge;
var
NewPosition: Integer64;
begin
NewPosition := CurProgress;
Shr64(NewPosition, ProgressShiftCount);
if WizardForm.ProgressGauge.Position <> Longint(NewPosition.Lo) then begin
WizardForm.ProgressGauge.Position := NewPosition.Lo;
WizardForm.ProgressGauge.Update;
end;
SetAppTaskbarProgressValue(NewPosition.Lo, WizardForm.ProgressGauge.Max);
if (CodeRunner <> nil) and CodeRunner.FunctionExists('CurInstallProgressChanged', True) then begin
try
CodeRunner.RunProcedures('CurInstallProgressChanged', [NewPosition.Lo,
WizardForm.ProgressGauge.Max], False);
except
Log('CurInstallProgressChanged raised an exception.');
Application.HandleException(nil);
end;
end;
end;
procedure FinishProgressGauge(const HideGauge: Boolean);
begin
SetMessageBoxCallbackFunc(nil, 0);
if HideGauge then
WizardForm.ProgressGauge.Visible := False;
SetAppTaskbarProgressState(tpsNoProgress);
end;
procedure SetProgress(const AProgress: Integer64);
begin
CurProgress := AProgress;
UpdateProgressGauge;
end;
procedure IncProgress(const N: Cardinal);
begin
Inc64(CurProgress, N);
UpdateProgressGauge;
end;
procedure IncProgress64(const N: Integer64);
begin
Inc6464(CurProgress, N);
UpdateProgressGauge;
end;
procedure ProcessEvents;
{ Processes any waiting events. Must call this this periodically or else
events like clicking the Cancel button won't be processed.
Calls Abort if NeedToAbortInstall is True, which is usually the result of
the user clicking Cancel and the form closing. }
begin
if NeedToAbortInstall then Abort;
Application.ProcessMessages;
if NeedToAbortInstall then Abort;
end;
procedure ExtractorProgressProc(Bytes: Cardinal);
begin
IncProgress(Bytes);
ProcessEvents;
end;
function AbortRetryIgnoreTaskDialogMsgBox(const Text: String;
const RetryIgnoreAbortButtonLabels: array of String): Boolean;
{ Returns True if Ignore was selected, False if Retry was selected, or
calls Abort if Abort was selected. }
begin
Result := False;
case LoggedTaskDialogMsgBox('', SetupMessages[msgAbortRetryIgnoreSelectAction], Text, '',
mbError, MB_ABORTRETRYIGNORE, RetryIgnoreAbortButtonLabels, 0, True, IDABORT) of
IDABORT: Abort;
IDRETRY: ;
IDIGNORE: Result := True;
else
Log('LoggedTaskDialogMsgBox returned an unexpected value. Assuming Abort.');
Abort;
end;
end;
function FileTimeToStr(const AFileTime: TFileTime): String;
{ Converts a TFileTime into a string for log purposes. }
var
FT: TFileTime;
ST: TSystemTime;
begin
FileTimeToLocalFileTime(AFileTime, FT);
if FileTimeToSystemTime(FT, ST) then
Result := Format('%.4u-%.2u-%.2u %.2u:%.2u:%.2u.%.3u',
[ST.wYear, ST.wMonth, ST.wDay, ST.wHour, ST.wMinute, ST.wSecond,
ST.wMilliseconds])
else
Result := '(invalid)';
end;
function TryToGetSHA1OfFile(const DisableFsRedir: Boolean; const Filename: String;
var Sum: TSHA1Digest): Boolean;
{ Like GetSHA1OfFile but traps exceptions locally. Returns True if successful. }
begin
try
Sum := GetSHA1OfFile(DisableFsRedir, Filename);
Result := True;
except
Result := False;
end;
end;
procedure CopySourceFileToDestFile(const SourceF, DestF: TFile;
AMaxProgress: Integer64);
{ Copies all bytes from SourceF to DestF, incrementing process meter as it
goes. Assumes file pointers of both are 0. }
var
BytesLeft: Integer64;
NewProgress: Integer64;
BufSize: Cardinal;
Buf: array[0..16383] of Byte;
begin
Inc6464(AMaxProgress, CurProgress);
BytesLeft := SourceF.Size;
{ To avoid file system fragmentation, preallocate all of the bytes in the
destination file }
DestF.Seek64(BytesLeft);
DestF.Truncate;
DestF.Seek(0);
while True do begin
BufSize := SizeOf(Buf);
if (BytesLeft.Hi = 0) and (BytesLeft.Lo < BufSize) then
BufSize := BytesLeft.Lo;
if BufSize = 0 then
Break;
SourceF.ReadBuffer(Buf, BufSize);
DestF.WriteBuffer(Buf, BufSize);
Dec64(BytesLeft, BufSize);
NewProgress := CurProgress;
Inc64(NewProgress, BufSize);
if Compare64(NewProgress, AMaxProgress) > 0 then
NewProgress := AMaxProgress;
SetProgress(NewProgress);
ProcessEvents;
end;
{ In case the source file was shorter than we thought it was, bump the
progress bar to the maximum amount }
SetProgress(AMaxProgress);
end;
procedure AddAttributesToFile(const DisableFsRedir: Boolean;
const Filename: String; Attribs: Integer);
var
ExistingAttr: DWORD;
begin
if Attribs <> 0 then begin
ExistingAttr := GetFileAttributesRedir(DisableFsRedir, Filename);
if ExistingAttr <> $FFFFFFFF then
SetFileAttributesRedir(DisableFsRedir, Filename,
(ExistingAttr and not FILE_ATTRIBUTE_NORMAL) or DWORD(Attribs));
end;
end;
function ShortenOrExpandFontFilename(const Filename: String): String;
{ Expands Filename, except if it's in the Fonts directory, in which case it
removes the path }
var
FontDir: String;
begin
Result := PathExpand(Filename);
FontDir := GetShellFolder(False, sfFonts, False);
if FontDir <> '' then
if PathCompare(PathExtractDir(Result), FontDir) = 0 then
Result := PathExtractName(Result);
end;
function LastErrorIndicatesPossiblyInUse(const LastError: DWORD; const CheckAlreadyExists: Boolean): Boolean;
begin
Result := (LastError = ERROR_ACCESS_DENIED) or
(LastError = ERROR_SHARING_VIOLATION) or
(CheckAlreadyExists and (LastError = ERROR_ALREADY_EXISTS));
end;
procedure PerformInstall(var Succeeded: Boolean; const ChangesEnvironment,
ChangesAssociations: Boolean);
type
PRegisterFilesListRec = ^TRegisterFilesListRec;
TRegisterFilesListRec = record
Filename: String;
Is64Bit, TypeLib, NoErrorMessages: Boolean;
end;
var
UninstLog: TSetupUninstallLog;
UninstallTempExeFilename, UninstallDataFilename, UninstallMsgFilename: String;
UninstallExeCreated: (ueNone, ueNew, ueReplaced);
UninstallDataCreated, UninstallMsgCreated, AppendUninstallData: Boolean;
RegisterFilesList: TList;
ExpandedAppId: String;
function GetLocalTimeAsStr: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
SetString(Result, PChar(@SysTime), SizeOf(SysTime) div SizeOf(Char));
end;
procedure RecordStartInstall;
var
AppDir: String;
begin
if shCreateAppDir in SetupHeader.Options then
AppDir := WizardDirValue
else
AppDir := '';
UninstLog.Add(utStartInstall, [GetComputerNameString, GetUserNameString,
AppDir, GetLocalTimeAsStr], 0);
end;
procedure PackCustomMessagesIntoString(var S: String);
var
M: TMemoryStream;
Count, I, N: Integer;
begin
M := TMemoryStream.Create;
try
Count := 0;
M.WriteBuffer(Count, SizeOf(Count)); { overwritten later }
for I := 0 to Entries[seCustomMessage].Count-1 do begin
with PSetupCustomMessageEntry(Entries[seCustomMessage][I])^ do begin
if (LangIndex = -1) or (LangIndex = ActiveLanguage) then begin
N := Length(Name);
M.WriteBuffer(N, SizeOf(N));
M.WriteBuffer(Name[1], N*SizeOf(Name[1]));
N := Length(Value);
M.WriteBuffer(N, SizeOf(N));
M.WriteBuffer(Value[1], N*SizeOf(Value[1]));
Inc(Count);
end;
end;
end;
M.Seek(0, soFromBeginning);
M.WriteBuffer(Count, SizeOf(Count));
SetString(S, PChar(M.Memory), M.Size div SizeOf(Char));
finally
M.Free;
end;
end;
function PackCompiledCodeTextIntoString(const CompiledCodeText: AnsiString): String;
{$IFDEF UNICODE}
var
N: Integer;
begin
N := Length(CompiledCodeText);
if N mod 2 = 1 then
Inc(N); { This will lead to 1 extra byte being moved but that's ok since it is the #0 }
N := N div 2;
SetString(Result, PChar(Pointer(CompiledCodeText)), N);
{$ELSE}
begin
Result := CompiledCodeText;
{$ENDIF}
end;
procedure RecordCompiledCode;
var
LeadBytesStr, ExpandedApp, ExpandedGroup, CustomMessagesStr: String;
begin
{$IFNDEF UNICODE}
SetString(LeadBytesStr, PChar(@SetupHeader.LeadBytes),
SizeOf(SetupHeader.LeadBytes));
{$ENDIF}
{ Only use app if Setup creates one }
if shCreateAppDir in SetupHeader.Options then
ExpandedApp := ExpandConst('{app}')
else
ExpandedApp := '';
try
ExpandedGroup := ExpandConst('{group}');
except
{ Yep, expanding "group" might fail with an exception }
ExpandedGroup := '';
end;
if SetupHeader.CompiledCodeText <> '' then
PackCustomMessagesIntoString(CustomMessagesStr);
{ Record [Code] even if empty to 'overwrite' old versions }
UninstLog.Add(utCompiledCode, [PackCompiledCodeTextIntoString(SetupHeader.CompiledCodeText),
LeadBytesStr, ExpandedApp, ExpandedGroup, WizardGroupValue,
ExpandConst('{language}'), CustomMessagesStr], SetupBinVersion {$IFDEF UNICODE} or Longint($80000000) {$ENDIF});
end;
type
TRegErrorFunc = (reRegSetValueEx, reRegCreateKeyEx, reRegOpenKeyEx);
procedure RegError(const Func: TRegErrorFunc; const RootKey: HKEY;
const KeyName: String; const ErrorCode: Longint);
const
ErrorMsgs: array[TRegErrorFunc] of TSetupMessageID =
(msgErrorRegWriteKey, msgErrorRegCreateKey, msgErrorRegOpenKey);
FuncNames: array[TRegErrorFunc] of String =
('RegSetValueEx', 'RegCreateKeyEx', 'RegOpenKeyEx');
begin
raise Exception.Create(FmtSetupMessage(ErrorMsgs[Func],
[GetRegRootKeyName(RootKey), KeyName]) + SNewLine2 +
FmtSetupMessage(msgErrorFunctionFailedWithMessage,
[FuncNames[Func], IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
end;
procedure RegisterUninstallInfo(const UninstallRegKeyBaseName: String; const AfterInstallFilesSize: Integer64);
{ Stores uninstall information in the Registry so that the program can be
uninstalled through the Control Panel Add/Remove Programs applet. }
const
AdminInstallModeNames: array [Boolean] of String =
('non administrative', 'administrative');
BitInstallModeNames: array [Boolean] of String =
('32-bit', '64-bit');
var
RegView, OppositeRegView: TRegView;
RegViewIs64Bit, OppositeRegViewIs64Bit: Boolean;
RootKey, OppositeRootKey: HKEY;
RootKeyIsHKLM, OppositeRootKeyIsHKLM: Boolean;
SubkeyName: String;
procedure SetStringValue(const K: HKEY; const ValueName: PChar;
const Data: String);
var
ErrorCode: Longint;
begin
ErrorCode := RegSetValueEx(K, ValueName, 0, REG_SZ, PChar(Data),
(Length(Data)+1)*SizeOf(Data[1]));
if ErrorCode <> ERROR_SUCCESS then
RegError(reRegSetValueEx, RootKey, SubkeyName, ErrorCode);
end;
procedure SetStringValueUnlessEmpty(const K: HKEY; const ValueName: PChar;
const Data: String);
begin
if Data <> '' then
SetStringValue(K, ValueName, Data);
end;
procedure SetDWordValue(const K: HKEY; const ValueName: PChar;
const Data: DWord);
var
ErrorCode: Longint;
begin
ErrorCode := RegSetValueEx(K, ValueName, 0, REG_DWORD, @Data,
SizeOf(Data));
if ErrorCode <> ERROR_SUCCESS then
RegError(reRegSetValueEx, RootKey, SubkeyName, ErrorCode);
end;
function GetInstallDateString: String;
var
ST: TSystemTime;
begin
GetLocalTime(ST);
Result := Format('%.4u%.2u%.2u', [ST.wYear, ST.wMonth, ST.wDay]);
end;
function ExtractMajorMinorVersion(Version: String; var Major, Minor: Integer): Boolean;
var
P, I: Integer;
begin
P := Pos('.', Version);
if P <> 0 then begin
Val(Copy(Version, 1, P-1), Major, I);
if I = 0 then begin
Delete(Version, 1, P);
P := Pos('.', Version);
if P <> 0 then
Val(Copy(Version, 1, P-1), Minor, I)
else
Val(Version, Minor, I);
end;
end else begin
Val(Version, Major, I);
Minor := 0;
end;
Result := I = 0;
end;
{ Also see Main.pas }
function ExistingInstallationAt(const RegView: TRegView; const RootKey: HKEY): Boolean;
var
K: HKEY;
begin
if RegOpenKeyExView(RegView, RootKey, PChar(SubkeyName), 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
Result := True;
RegCloseKey(K);
end else
Result := False;
end;
procedure HandleDuplicateDisplayNames(var DisplayName: String);
const
UninstallDisplayNameMarksUser: array [Boolean] of TSetupMessageId =
(msgUninstallDisplayNameMarkCurrentUser, msgUninstallDisplayNameMarkAllUsers);
UninstallDisplayNameMarksBits: array [Boolean] of TSetupMessageId =
(msgUninstallDisplayNameMark32Bit, msgUninstallDisplayNameMark64Bit);
var
ExistingAtOppositeAdminInstallMode, ExistingAtOpposite64BitInstallMode: Boolean;
begin
{ Check opposite administrative install mode. }
ExistingAtOppositeAdminInstallMode := ExistingInstallationAt(RegView, OppositeRootKey);
if RootKeyIsHKLM or not IsWin64 then begin
{ Opposite (HKCU) is shared for 32-bit and 64-bit so don't log bitness. Also don't log bitness on a 32-bit system. }
LogFmt('Detected previous %s install? %s',
[AdminInstallModeNames[OppositeRootKeyIsHKLM {always False}], SYesNo[ExistingAtOppositeAdminInstallMode]])
end else begin
{ Opposite (HKLM) is not shared for 32-bit and 64-bit so log bitness. }
LogFmt('Detected previous %s %s install? %s',
[AdminInstallModeNames[OppositeRootKeyIsHKLM {always True}], BitInstallModeNames[RegViewIs64Bit], SYesNo[ExistingAtOppositeAdminInstallMode]]);
end;
if IsWin64 then begin
{ Check opposite 32-bit or 64-bit install mode. }
if RootKeyIsHKLM then begin
{ HKLM is not shared for 32-bit and 64-bit so check it for opposite 32-bit or 64-bit install mode. Not checking HKCU
since HKCU is shared for 32-bit and 64-bit mode and we already checked HKCU above. }
ExistingAtOpposite64BitInstallMode := ExistingInstallationAt(OppositeRegView, RootKey {always HKLM});
LogFmt('Detected previous %s %s install? %s',
[AdminInstallModeNames[RootKeyIsHKLM {always True}], BitInstallModeNames[OppositeRegViewIs64Bit], SYesNo[ExistingAtOpposite64BitInstallMode]]);
end else begin
{ HKCU is shared for 32-bit and 64-bit so not checking it but we do still need to check HKLM for opposite 32-bit or
64-bit install mode since we haven't already done that. }
ExistingAtOpposite64BitInstallMode := ExistingInstallationAt(OppositeRegView, OppositeRootKey {always HKLM});
if ExistingAtOpposite64BitInstallMode then
ExistingAtOppositeAdminInstallMode := True;
LogFmt('Detected previous %s %s install? %s',
[AdminInstallModeNames[OppositeRootKeyIsHKLM {always True}], BitInstallModeNames[OppositeRegViewIs64Bit], SYesNo[ExistingAtOpposite64BitInstallMode]]);
end;
end else
ExistingAtOpposite64BitInstallMode := False;
{ Mark new display name if needed. Note: currently we don't attempt to mark existing display names as well. }
if ExistingAtOppositeAdminInstallMode or ExistingAtOpposite64BitInstallMode then begin
if ExistingAtOppositeAdminInstallMode and ExistingAtOpposite64BitInstallMode then
DisplayName := FmtSetupMessage(msgUninstallDisplayNameMarks,
[DisplayName, SetupMessages[UninstallDisplayNameMarksUser[RootKeyIsHKLM]],
SetupMessages[UninstallDisplayNameMarksBits[RegViewIs64Bit]]])
else if ExistingAtOppositeAdminInstallMode then
DisplayName := FmtSetupMessage(msgUninstallDisplayNameMark,
[DisplayName, SetupMessages[UninstallDisplayNameMarksUser[RootKeyIsHKLM]]])
else
DisplayName := FmtSetupMessage(msgUninstallDisplayNameMark,
[DisplayName, SetupMessages[UninstallDisplayNameMarksBits[RegViewIs64Bit]]]);
LogFmt('Marked uninstall display name to avoid duplicate entries. New display name: %s', [DisplayName]);
end;
end;
var
H2: HKEY;
ErrorCode: Longint;
Z: String;
MajorVersion, MinorVersion, I: Integer;
EstimatedSize: Integer64;
begin
RegView := InstallDefaultRegView;
RegViewIs64Bit := RegView = rv64Bit;
if RegViewIs64Bit then
OppositeRegView := rv32Bit
else
OppositeRegView := rv64Bit;
OppositeRegViewIs64Bit := not RegViewIs64Bit;
RootKey := InstallModeRootKey;
RootKeyIsHKLM := RootKey = HKEY_LOCAL_MACHINE;
if RootKeyIsHKLM then
OppositeRootKey := HKEY_CURRENT_USER
else
OppositeRootKey := HKEY_LOCAL_MACHINE;
OppositeRootKeyIsHKLM := not RootKeyIsHKLM;
SubkeyName := GetUninstallRegSubkeyName(UninstallRegKeyBaseName);
if ExistingInstallationAt(RegView, RootKey) then begin
if RootKeyIsHKLM then begin
{ HKLM is not shared for 32-bit and 64-bit so log bitness. }
LogFmt('Deleting uninstall key left over from previous %s %s install.',
[AdminInstallModeNames[RootKeyIsHKLM {always True}], BitInstallModeNames[RegViewIs64Bit]]);
end else begin
{ HKCU is shared for 32-bit and 64-bit so don't log bitness. }
LogFmt('Deleting uninstall key left over from previous %s install.',
[AdminInstallModeNames[RootKeyIsHKLM {always False}]])
end;
RegDeleteKeyIncludingSubkeys(RegView, RootKey, PChar(SubkeyName));
end;
LogFmt('Creating new uninstall key: %s\%s', [GetRegRootKeyName(RootKey), SubkeyName]);
{ Create uninstall key }
ErrorCode := RegCreateKeyExView(RegView, RootKey, PChar(SubkeyName),
0, nil, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nil, H2, nil);
if ErrorCode <> ERROR_SUCCESS then
RegError(reRegCreateKeyEx, RootKey, SubkeyName, ErrorCode);
try
Log('Writing uninstall key values.');
{ do not localize or change any of the following strings }
SetStringValue(H2, 'Inno Setup: Setup Version', SetupVersion);
if shCreateAppDir in SetupHeader.Options then
Z := WizardDirValue
else
Z := '';
SetStringValue(H2, 'Inno Setup: App Path', Z);
SetStringValueUnlessEmpty(H2, 'InstallLocation', AddBackslash(Z));
SetStringValue(H2, 'Inno Setup: Icon Group', WizardGroupValue);
if WizardNoIcons then
SetDWordValue(H2, 'Inno Setup: No Icons', 1);
SetStringValue(H2, 'Inno Setup: User', GetUserNameString);
if WizardSetupType <> nil then begin
SetStringValue(H2, 'Inno Setup: Setup Type', WizardSetupType.Name);
SetStringValue(H2, 'Inno Setup: Selected Components', StringsToCommaString(WizardComponents));
SetStringValue(H2, 'Inno Setup: Deselected Components', StringsToCommaString(WizardDeselectedComponents));
end;
if HasTasks then begin
SetStringValue(H2, 'Inno Setup: Selected Tasks', StringsToCommaString(WizardTasks));
SetStringValue(H2, 'Inno Setup: Deselected Tasks', StringsToCommaString(WizardDeselectedTasks));
end;
if shUserInfoPage in SetupHeader.Options then begin
SetStringValue(H2, 'Inno Setup: User Info: Name', WizardUserInfoName);
SetStringValue(H2, 'Inno Setup: User Info: Organization', WizardUserInfoOrg);
SetStringValue(H2, 'Inno Setup: User Info: Serial', WizardUserInfoSerial);
end;
SetStringValue(H2, 'Inno Setup: Language', PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name);
if SetupHeader.UninstallDisplayName <> '' then
Z := ExpandConst(SetupHeader.UninstallDisplayName)
else
Z := ExpandedAppVerName;
HandleDuplicateDisplayNames(Z);
{ For the entry to appear in ARP, DisplayName cannot exceed 63 characters
on Windows 9x/NT 4.0, or 259 characters on Windows 2000 and later. }
if WindowsVersionAtLeast(5, 0) then
I := 259
else
I := 63;
SetStringValue(H2, 'DisplayName', Copy(Z, 1, I));
SetStringValueUnlessEmpty(H2, 'DisplayIcon', ExpandConst(SetupHeader.UninstallDisplayIcon));
SetStringValue(H2, 'UninstallString', '"' + UninstallExeFilename + '"');
SetStringValue(H2, 'QuietUninstallString', '"' + UninstallExeFilename + '" /SILENT');
SetStringValueUnlessEmpty(H2, 'DisplayVersion', ExpandConst(SetupHeader.AppVersion));
SetStringValueUnlessEmpty(H2, 'Publisher', ExpandConst(SetupHeader.AppPublisher));
SetStringValueUnlessEmpty(H2, 'URLInfoAbout', ExpandConst(SetupHeader.AppPublisherURL));
SetStringValueUnlessEmpty(H2, 'HelpTelephone', ExpandConst(SetupHeader.AppSupportPhone));
SetStringValueUnlessEmpty(H2, 'HelpLink', ExpandConst(SetupHeader.AppSupportURL));
SetStringValueUnlessEmpty(H2, 'URLUpdateInfo', ExpandConst(SetupHeader.AppUpdatesURL));
SetStringValueUnlessEmpty(H2, 'Readme', ExpandConst(SetupHeader.AppReadmeFile));
SetStringValueUnlessEmpty(H2, 'Contact', ExpandConst(SetupHeader.AppContact));
SetStringValueUnlessEmpty(H2, 'Comments', ExpandConst(SetupHeader.AppComments));
Z := ExpandConst(SetupHeader.AppModifyPath);
if Z <> '' then
SetStringValue(H2, 'ModifyPath', Z)
else
SetDWordValue(H2, 'NoModify', 1);
SetDWordValue(H2, 'NoRepair', 1);
SetStringValue(H2, 'InstallDate', GetInstallDateString);
if ExtractMajorMinorVersion(ExpandConst(SetupHeader.AppVersion), MajorVersion, MinorVersion) then begin
{ Originally MSDN said to write to Major/MinorVersion, now it says to write to VersionMajor/Minor. So write to both. }
SetDWordValue(H2, 'MajorVersion', MajorVersion);
SetDWordValue(H2, 'MinorVersion', MinorVersion);
SetDWordValue(H2, 'VersionMajor', MajorVersion);
SetDWordValue(H2, 'VersionMinor', MinorVersion);
end;
{ Note: Windows 7 doesn't automatically calculate sizes so set EstimatedSize ourselves. Do not set it
on earlier Windows versions since calculated sizes are cached and clearing the cache would require
updating an undocumented key at HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Management\ARPCache\<id>. }
if WindowsVersion shr 16 >= $0601 then begin
if (SetupHeader.UninstallDisplaySize.Hi = 0) and (SetupHeader.UninstallDisplaySize.Lo = 0) then begin
{ Estimate the size by taking the size of all files and adding any ExtraDiskSpaceRequired. }
EstimatedSize := AfterInstallFilesSize;
Inc6464(EstimatedSize, SetupHeader.ExtraDiskSpaceRequired);
for I := 0 to Entries[seComponent].Count-1 do begin
with PSetupComponentEntry(Entries[seComponent][I])^ do begin
if ShouldProcessEntry(WizardComponents, nil, Name, '', Languages, '') then
Inc6464(EstimatedSize, ExtraDiskSpaceRequired);
end;
end;
end else
EstimatedSize := SetupHeader.UninstallDisplaySize;
{ ARP on Windows 7 without SP1 only pays attention to the lower 6 bytes of EstimatedSize and
throws away the rest. For example putting in $4000001 (=4GB + 1KB) displays as 1 KB.
So we need to check for this. Already checked this is Windows 7 or newer above. }
if (Hi(NTServicePackLevel) > 0) or (WindowsVersion shr 16 > $0601) or (EstimatedSize.Hi = 0) then begin
Div64(EstimatedSize, 1024);
SetDWordValue(H2, 'EstimatedSize', EstimatedSize.Lo)
end;
end;
{ Also see SetPreviousData in ScriptFunc.pas }
if CodeRunner <> nil then begin
try
CodeRunner.RunProcedures('RegisterPreviousData', [Integer(H2)], False);
except
Log('RegisterPreviousData raised an exception.');
Application.HandleException(nil);
end;
end;
finally
RegCloseKey(H2);
end;
UninstLog.AddReg(utRegDeleteEntireKey, RegView, RootKey,
[SubkeyName]);
end;
type
TMakeDirFlags = set of (mdNoUninstall, mdAlwaysUninstall, mdDeleteAfterInstall,
mdNotifyChange);
function MakeDir(const DisableFsRedir: Boolean; Dir: String;
const Flags: TMakeDirFlags): Boolean;
{ Returns True if a new directory was created.
Note: If DisableFsRedir is True, the mdNotifyChange flag should not be
specified; it won't work properly. }
var
ErrorCode: DWORD;
UninstFlags: Longint;
begin
Result := False;
Dir := RemoveBackslashUnlessRoot(PathExpand(Dir));
if PathExtractName(Dir) = '' then { reached root? }
Exit;
if DirExistsRedir(DisableFsRedir, Dir) then begin
if not(mdAlwaysUninstall in Flags) then
Exit;
end
else begin
MakeDir(DisableFsRedir, PathExtractDir(Dir), Flags - [mdAlwaysUninstall]);
LogFmt('Creating directory: %s', [Dir]);
if not CreateDirectoryRedir(DisableFsRedir, Dir) then begin
ErrorCode := GetLastError;
raise Exception.Create(FmtSetupMessage(msgLastErrorMessage,
[FmtSetupMessage1(msgErrorCreatingDir, Dir), IntToStr(ErrorCode),
Win32ErrorString(ErrorCode)]));
end;
Result := True;
if mdNotifyChange in Flags then begin
SHChangeNotify(SHCNE_MKDIR, SHCNF_PATH, PChar(Dir), nil);
SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH or SHCNF_FLUSH,
PChar(PathExtractDir(Dir)), nil);
end;
end;
if mdDeleteAfterInstall in Flags then
DeleteDirsAfterInstallList.AddObject(Dir, Pointer(Ord(DisableFsRedir)))
else begin
if not(mdNoUninstall in Flags) then begin
UninstFlags := utDeleteDirOrFiles_IsDir;
if DisableFsRedir then
UninstFlags := UninstFlags or utDeleteDirOrFiles_DisableFsRedir;
if mdNotifyChange in Flags then
UninstFlags := UninstFlags or utDeleteDirOrFiles_CallChangeNotify;
UninstLog.Add(utDeleteDirOrFiles, [Dir], UninstFlags);
end;
end;
end;
procedure CreateDirs;
{ Creates the application's directories }
procedure ApplyPermissions(const DisableFsRedir: Boolean;
const Filename: String; const PermsEntry: Integer);
var
P: PSetupPermissionEntry;
begin
if PermsEntry <> -1 then begin
LogFmt('Setting permissions on directory: %s', [Filename]);
P := Entries[sePermission][PermsEntry];
if not GrantPermissionOnFile(DisableFsRedir, Filename,
TGrantPermissionEntry(Pointer(P.Permissions)^),
Length(P.Permissions) div SizeOf(TGrantPermissionEntry)) then
LogFmt('Failed to set permissions on directory (%d).', [GetLastError]);
end;
end;
procedure ApplyNTFSCompression(const DisableFsRedir: Boolean;
const Filename: String; const Compress: Boolean);
begin
if Compress then
LogFmt('Setting NTFS compression on directory: %s', [Filename])
else
LogFmt('Unsetting NTFS compression on directory: %s', [Filename]);
if not SetNTFSCompressionRedir(DisableFsRedir, Filename, Compress) then
LogFmt('Failed to set NTFS compression state (%d).', [GetLastError]);
end;
var
CurDirNumber: Integer;
Flags: TMakeDirFlags;
N: String;
begin
{ Create main application directory }
MakeDir(InstallDefaultDisableFsRedir, WizardDirValue, []);
{ Create the rest of the directories, if any }
for CurDirNumber := 0 to Entries[seDir].Count-1 do
with PSetupDirEntry(Entries[seDir][CurDirNumber])^ do begin
if ShouldProcessEntry(WizardComponents, WizardTasks, Components, Tasks, Languages, Check) then begin
DebugNotifyEntry(seDir, CurDirNumber);
NotifyBeforeInstallEntry(BeforeInstall);
Flags := [];
if doUninsNeverUninstall in Options then Include(Flags, mdNoUninstall);
if doDeleteAfterInstall in Options then Include(Flags, mdDeleteAfterInstall);
if doUninsAlwaysUninstall in Options then Include(Flags, mdAlwaysUninstall);
N := RemoveBackslashUnlessRoot(PathExpand(ExpandConst(DirName)));
MakeDir(InstallDefaultDisableFsRedir, N, Flags);
AddAttributesToFile(InstallDefaultDisableFsRedir, N, Attribs);
ApplyPermissions(InstallDefaultDisableFsRedir, N, PermissionsEntry);
if (doSetNTFSCompression in Options) or (doUnsetNTFSCompression in Options) then
ApplyNTFSCompression(InstallDefaultDisableFsRedir, N, doSetNTFSCompression in Options);
NotifyAfterInstallEntry(AfterInstall);
end;
end;
end;
procedure WriteMsgData(const F: TFile);
var
MsgLangOpts: TMessagesLangOptions;
LangEntry: PSetupLanguageEntry;
begin
FillChar(MsgLangOpts, SizeOf(MsgLangOpts), 0);
MsgLangOpts.ID := MessagesLangOptionsID;
StrPLCopy(MsgLangOpts.DialogFontName, LangOptions.DialogFontName,
(SizeOf(MsgLangOpts.DialogFontName) div SizeOf(MsgLangOpts.DialogFontName[0])) - 1);
MsgLangOpts.DialogFontSize := LangOptions.DialogFontSize;
if LangOptions.RightToLeft then
Include(MsgLangOpts.Flags, lfRightToLeft);
LangEntry := Entries[seLanguage][ActiveLanguage];
F.WriteBuffer(LangEntry.Data[1], Length(LangEntry.Data));
F.WriteBuffer(MsgLangOpts, SizeOf(MsgLangOpts));
end;
procedure MarkExeHeader(const F: TFile; const ModeID: Longint);
begin
F.Seek(SetupExeModeOffset);
F.WriteBuffer(ModeID, SizeOf(ModeID));
end;
procedure BindUninstallMsgDataToExe(const F: TFile);
var
UniqueValue: TSHA1Digest;
UninstallerMsgTail: TUninstallerMsgTail;
begin
F.SeekToEnd;
{ First append the hash of AppId so that unins*.exe files from different
applications won't have the same MD5 sum. This is done to combat broken
anti-spyware programs that catch all unins*.exe files with certain MD5
sums just because some piece of spyware was deployed with Inno Setup and
had the unins*.exe file in its directory. }
{$IFDEF UNICODE}
UniqueValue := GetSHA1OfUnicodeString(ExpandedAppId);
{$ELSE}
UniqueValue := GetSHA1OfAnsiString(ExpandedAppId);
{$ENDIF}
F.WriteBuffer(UniqueValue, SizeOf(UniqueValue));
UninstallerMsgTail.ID := UninstallerMsgTailID;
UninstallerMsgTail.Offset := F.Position.Lo;
WriteMsgData(F);
F.WriteBuffer(UninstallerMsgTail, SizeOf(UninstallerMsgTail));
end;
type
TOverwriteAll = (oaUnknown, oaOverwrite, oaKeep);
procedure ProcessFileEntry(const CurFile: PSetupFileEntry;
const DisableFsRedir: Boolean; ASourceFile, ADestName: String;
const FileLocationFilenames: TStringList; const AExternalSize: Integer64;
var ConfirmOverwriteOverwriteAll, PromptIfOlderOverwriteAll: TOverwriteAll;
var WarnedPerUserFonts: Boolean);
procedure InstallFont(const Filename, FontName: String;
const PerUserFont, AddToFontTableNow: Boolean; var WarnedPerUserFonts: Boolean);
const
FontsKeys: array[Boolean] of PChar =
(NEWREGSTR_PATH_SETUP + '\Fonts',
'Software\Microsoft\Windows NT\CurrentVersion\Fonts');
var
RootKey, K: HKEY;
begin
if PerUserFont and (WindowsVersion < Cardinal($0A0042EE)) then begin
{ Per-user fonts require Windows 10 Version 1803 (10.0.17134) or newer. }
if not WarnedPerUserFonts then begin
Log('Failed to set value in Fonts registry key: per-user fonts are not supported by this version of Windows.');
WarnedPerUserFonts := True;
end;
end else begin
{ 64-bit Windows note: The Fonts key is evidently exempt from registry
redirection. When a 32-bit app writes to the Fonts key, it's the main
64-bit key that is modified. (There is actually a Fonts key under
Wow6432Node but it appears it's never used or updated.)
Also: We don't bother with any FS redirection stuff here. I'm not sure
it's safe to disable FS redirection when calling AddFontResource, or
if it would even work. Users should be installing their fonts to the
Fonts directory instead of the System directory anyway. }
if PerUserFont then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
if RegOpenKeyExView(rvDefault, RootKey, FontsKeys[IsNT], 0,
KEY_SET_VALUE, K) = ERROR_SUCCESS then begin
if RegSetValueEx(K, PChar(FontName), 0, REG_SZ, PChar(Filename),
(Length(Filename)+1)*SizeOf(Filename[1])) <> ERROR_SUCCESS then
Log('Failed to set value in Fonts registry key.');
RegCloseKey(K);
end
else
Log('Failed to open Fonts registry key.');
end;
if AddToFontTableNow then begin
repeat
{ Note: AddFontResource doesn't set the thread's last error code }
if AddFontResource(PChar(Filename)) <> 0 then begin
SendNotifyMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
Break;
end;
until AbortRetryIgnoreTaskDialogMsgBox(
AddPeriod(FmtSetupMessage1(msgErrorFunctionFailedNoCode, 'AddFontResource')),
[SetupMessages[msgAbortRetryIgnoreRetry], SetupMessages[msgAbortRetryIgnoreIgnore], SetupMessages[msgAbortRetryIgnoreCancel]]);
end;
end;
procedure SetFileLocationFilename(const LocationEntry: Integer;
Filename: String);
var
LowercaseFilename: String;
Hash: Longint;
I: Integer;
begin
Filename := PathExpand(Filename);
LowercaseFilename := PathLowercase(Filename);
Hash := GetCRC32(LowercaseFilename[1], Length(LowercaseFilename)*SizeOf(LowercaseFilename[1]));
{ If Filename was already associated with another LocationEntry,
disassociate it. If we *don't* do this, then this script won't
produce the expected result:
[Files]
Source: "fileA"; DestName: "file2"
Source: "fileB"; DestName: "file2"
Source: "fileA"; DestName: "file1"
1. It extracts fileA under the name "file2"
2. It extracts fileB under the name "file2"
3. It copies file2 to file1, thinking a copy of fileA was still
stored in file2.
}
for I := 0 to FileLocationFilenames.Count-1 do
if (Longint(FileLocationFilenames.Objects[I]) = Hash) and
(PathLowercase(FileLocationFilenames[I]) = LowercaseFilename) then begin
FileLocationFilenames[I] := '';
FileLocationFilenames.Objects[I] := nil;