forked from jrsoftware/issrc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstFunc.pas
1535 lines (1439 loc) · 52 KB
/
InstFunc.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 InstFunc;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Misc. installation functions
}
interface
uses
Windows, SysUtils, Struct, Int64Em, MD5, SHA1, CmnFunc2;
{$I VERSION.INC}
type
PSimpleStringListArray = ^TSimpleStringListArray;
TSimpleStringListArray = array[0..$1FFFFFFE] of String;
TSimpleStringList = class
private
FList: PSimpleStringListArray;
FCount, FCapacity: Integer;
function Get(Index: Integer): String;
procedure SetCapacity(NewCapacity: Integer);
public
destructor Destroy; override;
procedure Add(const S: String);
procedure AddIfDoesntExist(const S: String);
procedure Clear;
function IndexOf(const S: String): Integer;
property Count: Integer read FCount;
property Items[Index: Integer]: String read Get; default;
end;
TDeleteDirProc = function(const DisableFsRedir: Boolean; const DirName: String;
const Param: Pointer): Boolean;
TDeleteFileProc = function(const DisableFsRedir: Boolean; const FileName: String;
const Param: Pointer): Boolean;
TEnumFROFilenamesProc = procedure(const Filename: String; Param: Pointer);
{ Must keep this in synch with ScriptFunc_C: }
TExecWait = (ewNoWait, ewWaitUntilTerminated, ewWaitUntilIdle);
TDetermineDefaultLanguageResult = (ddNoMatch, ddMatch, ddMatchLangParameter);
TGetLanguageEntryProc = function(Index: Integer; var Entry: PSetupLanguageEntry): Boolean;
function CheckForMutexes(const Mutexes: String): Boolean;
procedure CreateMutexes(const Mutexes: String);
function CreateTempDir: String;
function DecrementSharedCount(const RegView: TRegView; const Filename: String): Boolean;
procedure DelayDeleteFile(const DisableFsRedir: Boolean; const Filename: String;
const MaxTries, FirstRetryDelayMS, SubsequentRetryDelayMS: Integer);
function DelTree(const DisableFsRedir: Boolean; const Path: String;
const IsDir, DeleteFiles, DeleteSubdirsAlso, BreakOnError: Boolean;
const DeleteDirProc: TDeleteDirProc; const DeleteFileProc: TDeleteFileProc;
const Param: Pointer): Boolean;
function DetermineDefaultLanguage(const GetLanguageEntryProc: TGetLanguageEntryProc;
const Method: TSetupLanguageDetectionMethod; const LangParameter: String;
var ResultIndex: Integer): TDetermineDefaultLanguageResult;
procedure EnumFileReplaceOperationsFilenames(const EnumFunc: TEnumFROFilenamesProc;
Param: Pointer);
function GenerateNonRandomUniqueFilename(Path: String; var Filename: String): Boolean;
function GenerateUniqueName(const DisableFsRedir: Boolean; Path: String;
const Extension: String): String;
function GetComputerNameString: String;
function GetFileDateTime(const DisableFsRedir: Boolean; const Filename: String;
var DateTime: TFileTime): Boolean;
function GetMD5OfFile(const DisableFsRedir: Boolean; const Filename: String): TMD5Digest;
function GetMD5OfAnsiString(const S: AnsiString): TMD5Digest;
{$IFDEF UNICODE}
function GetMD5OfUnicodeString(const S: UnicodeString): TMD5Digest;
{$ENDIF}
function GetSHA1OfFile(const DisableFsRedir: Boolean; const Filename: String): TSHA1Digest;
function GetSHA1OfAnsiString(const S: AnsiString): TSHA1Digest;
{$IFDEF UNICODE}
function GetSHA1OfUnicodeString(const S: UnicodeString): TSHA1Digest;
{$ENDIF}
function GetRegRootKeyName(const RootKey: HKEY): String;
function GetSpaceOnDisk(const DisableFsRedir: Boolean; const DriveRoot: String;
var FreeBytes, TotalBytes: Integer64): Boolean;
function GetSpaceOnNearestMountPoint(const DisableFsRedir: Boolean;
const StartDir: String; var FreeBytes, TotalBytes: Integer64): Boolean;
function GetUserNameString: String;
procedure IncrementSharedCount(const RegView: TRegView; const Filename: String;
const AlreadyExisted: Boolean);
function InstExec(const DisableFsRedir: Boolean; const Filename, Params: String;
WorkingDir: String; const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
function InstShellExec(const Verb, Filename, Params: String; WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
procedure InternalError(const Id: String);
procedure InternalErrorFmt(const S: String; const Args: array of const);
function IsDirEmpty(const DisableFsRedir: Boolean; const Dir: String): Boolean;
function IsProtectedSystemFile(const DisableFsRedir: Boolean;
const Filename: String): Boolean;
function MakePendingFileRenameOperationsChecksum: TMD5Digest;
function ModifyPifFile(const Filename: String; const CloseOnExit: Boolean): Boolean;
procedure RaiseFunctionFailedError(const FunctionName: String);
procedure RaiseOleError(const FunctionName: String; const ResultCode: HRESULT);
procedure RefreshEnvironment;
function ReplaceSystemDirWithSysWow64(const Path: String): String;
function ReplaceSystemDirWithSysNative(Path: String; const IsWin64: Boolean): String;
procedure UnregisterFont(const FontName, FontFilename: String);
function RestartComputer: Boolean;
procedure RestartReplace(const DisableFsRedir: Boolean; TempFile, DestFile: String);
procedure SplitNewParamStr(const Index: Integer; var AName, AValue: String);
procedure Win32ErrorMsg(const FunctionName: String);
procedure Win32ErrorMsgEx(const FunctionName: String; const ErrorCode: DWORD);
function ForceDirectories(const DisableFsRedir: Boolean; Dir: String): Boolean;
implementation
uses
Messages, ShellApi, PathFunc, Msgs, MsgIDs, FileClass, RedirFunc;
procedure InternalError(const Id: String);
begin
raise Exception.Create(FmtSetupMessage1(msgErrorInternal2, Id));
end;
procedure InternalErrorFmt(const S: String; const Args: array of const);
begin
InternalError(Format(S, Args));
end;
procedure Win32ErrorMsgEx(const FunctionName: String; const ErrorCode: DWORD);
begin
raise Exception.Create(FmtSetupMessage(msgErrorFunctionFailedWithMessage,
[FunctionName, IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
end;
procedure Win32ErrorMsg(const FunctionName: String);
begin
Win32ErrorMsgEx(FunctionName, GetLastError);
end;
procedure RaiseOleError(const FunctionName: String; const ResultCode: HRESULT);
begin
raise Exception.Create(FmtSetupMessage(msgErrorFunctionFailedWithMessage,
[FunctionName, IntToHexStr8(ResultCode), Win32ErrorString(ResultCode)]));
end;
procedure RaiseFunctionFailedError(const FunctionName: String);
begin
raise Exception.Create(FmtSetupMessage1(msgErrorFunctionFailedNoCode,
FunctionName));
end;
function GetRegRootKeyName(const RootKey: HKEY): String;
begin
case RootKey of
HKEY_CLASSES_ROOT: Result := 'HKEY_CLASSES_ROOT';
HKEY_CURRENT_USER: Result := 'HKEY_CURRENT_USER';
HKEY_LOCAL_MACHINE: Result := 'HKEY_LOCAL_MACHINE';
HKEY_USERS: Result := 'HKEY_USERS';
HKEY_PERFORMANCE_DATA: Result := 'HKEY_PERFORMANCE_DATA';
HKEY_CURRENT_CONFIG: Result := 'HKEY_CURRENT_CONFIG';
HKEY_DYN_DATA: Result := 'HKEY_DYN_DATA';
else
{ unknown - shouldn't get here }
Result := Format('[%x]', [Cardinal(RootKey)]);
end;
end;
function IntToBase32(Number: Longint): String;
const
Table: array[0..31] of Char = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
var
I: Integer;
begin
Result := '';
for I := 0 to 4 do begin
Insert(Table[Number and 31], Result, 1);
Number := Number shr 5;
end;
end;
function GenerateUniqueName(const DisableFsRedir: Boolean; Path: String;
const Extension: String): String;
var
Rand, RandOrig: Longint;
Filename: String;
begin
Path := AddBackslash(Path);
RandOrig := Random($2000000);
Rand := RandOrig;
repeat
Inc(Rand);
if Rand > $1FFFFFF then Rand := 0;
if Rand = RandOrig then
{ practically impossible to go through 33 million possibilities,
but check "just in case"... }
raise Exception.Create(FmtSetupMessage1(msgErrorTooManyFilesInDir,
RemoveBackslashUnlessRoot(Path)));
{ Generate a random name }
Filename := Path + 'is-' + IntToBase32(Rand) + Extension;
until not FileOrDirExistsRedir(DisableFsRedir, Filename);
Result := Filename;
end;
function GenerateNonRandomUniqueFilename(Path: String; var Filename: String): Boolean;
{ Returns True if it overwrote an existing file. }
var
Rand, RandOrig: Longint;
F: THandle;
Success: Boolean;
FN: String;
begin
Path := AddBackslash(Path);
RandOrig := $123456;
Rand := RandOrig;
Success := False;
Result := False;
repeat
Inc(Rand);
if Rand > $1FFFFFF then Rand := 0;
if Rand = RandOrig then
{ practically impossible to go through 33 million possibilities,
but check "just in case"... }
raise Exception.Create(FmtSetupMessage1(msgErrorTooManyFilesInDir,
RemoveBackslashUnlessRoot(Path)));
{ Generate a random name }
FN := Path + '_iu' + IntToBase32(Rand) + '.tmp';
if DirExists(FN) then Continue;
Success := True;
Result := NewFileExists(FN);
if Result then begin
F := CreateFile(PChar(FN), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
Success := F <> INVALID_HANDLE_VALUE;
if Success then CloseHandle(F);
end;
until Success;
Filename := FN;
end;
function CreateTempDir: String;
var
Dir: String;
ErrorCode: DWORD;
begin
while True do begin
Dir := GenerateUniqueName(False, GetTempDir, '.tmp');
if CreateDirectory(PChar(Dir), nil) then
Break;
ErrorCode := GetLastError;
if ErrorCode <> ERROR_ALREADY_EXISTS then
raise Exception.Create(FmtSetupMessage(msgLastErrorMessage,
[FmtSetupMessage1(msgErrorCreatingDir, Dir), IntToStr(ErrorCode),
Win32ErrorString(ErrorCode)]));
end;
Result := Dir;
end;
function ReplaceSystemDirWithSysWow64(const Path: String): String;
{ If the user is running 64-bit Windows and Path begins with
'x:\windows\system32' it replaces it with 'x:\windows\syswow64', like the
file system redirector would do. Otherwise, Path is returned unchanged. }
var
SysWow64Dir, SysDir: String;
L: Integer;
begin
SysWow64Dir := GetSysWow64Dir;
if SysWow64Dir <> '' then begin
SysDir := GetSystemDir;
{ x:\windows\system32 -> x:\windows\syswow64
x:\windows\system32\ -> x:\windows\syswow64\
x:\windows\system32\filename -> x:\windows\syswow64\filename
x:\windows\system32x -> x:\windows\syswow64x <- yes, like Windows! }
L := Length(SysDir);
if (Length(Path) = L) or
((Length(Path) > L) and not PathCharIsTrailByte(Path, L+1)) then begin
{ ^ avoid splitting a double-byte character }
if PathCompare(Copy(Path, 1, L), SysDir) = 0 then begin
Result := SysWow64Dir + Copy(Path, L+1, Maxint);
Exit;
end;
end;
end;
Result := Path;
end;
function ReplaceSystemDirWithSysNative(Path: String; const IsWin64: Boolean): String;
{ If the user is running 64-bit Windows Vista or newer and Path
begins with 'x:\windows\system32\' it replaces it with
'x:\windows\sysnative\' and if Path equals 'x:\windows\system32'
it replaces it with 'x:\windows\sysnative'. Otherwise, Path is
returned unchanged. }
var
SysNativeDir, SysDir: String;
L: Integer;
begin
SysNativeDir := GetSysNativeDir(IsWin64);
if SysNativeDir <> '' then begin
SysDir := GetSystemDir;
if PathCompare(Path, SysDir) = 0 then begin
{ x:\windows\system32 -> x:\windows\sysnative }
Result := SysNativeDir;
Exit;
end else begin
{ x:\windows\system32\ -> x:\windows\sysnative\
x:\windows\system32\filename -> x:\windows\sysnative\filename }
SysDir := AddBackslash(SysDir);
L := Length(SysDir);
if (Length(Path) = L) or
((Length(Path) > L) and not PathCharIsTrailByte(Path, L+1)) then begin
{ ^ avoid splitting a double-byte character }
if PathCompare(Copy(Path, 1, L), SysDir) = 0 then begin
Result := SysNativeDir + Copy(Path, L, Maxint);
Exit;
end;
end;
end;
end;
Result := Path;
end;
procedure RestartReplace(const DisableFsRedir: Boolean; TempFile, DestFile: String);
{ Renames TempFile to DestFile the next time Windows is started. If DestFile
already existed, it will be overwritten. If DestFile is '' then TempFile
will be deleted, however this is only supported by 95/98 and NT, not
Windows 3.1x. }
var
WinDir, WinInitFile, TempWinInitFile: String;
OldF: TTextFileReader;
NewF: TTextFileWriter;
L, L2: String;
RenameSectionFound, WriteLastLine: Boolean;
begin
TempFile := PathExpand(TempFile);
if DestFile <> '' then
DestFile := PathExpand(DestFile);
if not UsingWinNT then begin
{ Because WININIT.INI allows multiple entries with the same name,
it must manually parse the file instead of using
WritePrivateProfileString }
WinDir := GetWinDir;
WinInitFile := AddBackslash(WinDir) + 'WININIT.INI';
TempWinInitFile := GenerateUniqueName(False, WinDir, '.tmp');
try
OldF := nil;
NewF := nil;
try
{ Flush Windows' cache for the file first }
WritePrivateProfileString(nil, nil, nil, PChar(WinInitFile));
OldF := TTextFileReader.Create(WinInitFile, fdOpenAlways, faRead,
fsRead);
NewF := TTextFileWriter.Create(TempWinInitFile, fdCreateAlways,
faWrite, fsNone);
RenameSectionFound := False;
WriteLastLine := False;
while not OldF.Eof do begin
L := OldF.ReadLine;
WriteLastLine := True;
L2 := Trim(L);
if (L2 <> '') and (L2[1] = '[') then begin
if CompareText(L2, '[rename]') = 0 then
RenameSectionFound := True
else
if RenameSectionFound then
Break;
end;
NewF.WriteLine(L);
WriteLastLine := False;
end;
if not RenameSectionFound then
NewF.WriteLine('[rename]');
if DestFile <> '' then
L2 := GetShortName(DestFile)
else
L2 := 'NUL';
NewF.WriteLine(L2 + '=' + GetShortName(TempFile));
if WriteLastLine then
NewF.WriteLine(L);
while not OldF.Eof do begin
L := OldF.ReadLine;
NewF.WriteLine(L);
end;
finally
NewF.Free;
OldF.Free;
end;
{ Strip any read-only attribute }
SetFileAttributes(PChar(WinInitFile), FILE_ATTRIBUTE_ARCHIVE);
if not DeleteFile(WinInitFile) then
Win32ErrorMsg('DeleteFile');
if not MoveFile(PChar(TempWinInitFile), PChar(WinInitFile)) then
Win32ErrorMsg('MoveFile');
except
DeleteFile(TempWinInitFile);
raise;
end;
end
else begin
if not DisableFsRedir then begin
{ Work around WOW64 bug present in the IA64 and x64 editions of Windows
XP (3790) and Server 2003 prior to SP1 RC2: MoveFileEx writes filenames
to the registry verbatim without mapping system32->syswow64. }
TempFile := ReplaceSystemDirWithSysWow64(TempFile);
if DestFile <> '' then
DestFile := ReplaceSystemDirWithSysWow64(DestFile);
end;
if not MoveFileExRedir(DisableFsRedir, TempFile, DestFile,
MOVEFILE_DELAY_UNTIL_REBOOT or MOVEFILE_REPLACE_EXISTING) then
Win32ErrorMsg('MoveFileEx');
end;
end;
function DelTree(const DisableFsRedir: Boolean; const Path: String;
const IsDir, DeleteFiles, DeleteSubdirsAlso, BreakOnError: Boolean;
const DeleteDirProc: TDeleteDirProc; const DeleteFileProc: TDeleteFileProc;
const Param: Pointer): Boolean;
{ Deletes the specified directory including all files and subdirectories in
it (including those with hidden, system, and read-only attributes). Returns
True if it was able to successfully remove everything. If BreakOnError is
set to True it will stop and return False the first time a delete failed or
DeleteDirProc/DeleteFileProc returned False. }
var
BasePath, FindSpec: String;
H: THandle;
FindData: TWin32FindData;
S: String;
begin
Result := True;
if DeleteFiles and
(not IsDir or IsDirectoryAndNotReparsePointRedir(DisableFsRedir, Path)) then begin
if IsDir then begin
BasePath := AddBackslash(Path);
FindSpec := BasePath + '*';
end
else begin
BasePath := PathExtractPath(Path);
FindSpec := Path;
end;
H := FindFirstFileRedir(DisableFsRedir, FindSpec, FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
S := FindData.cFileName;
if (S <> '.') and (S <> '..') then begin
if FindData.dwFileAttributes and FILE_ATTRIBUTE_READONLY <> 0 then begin
{ Strip the read-only attribute if this is a file, or if it's a
directory and we're deleting subdirectories also }
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0) or DeleteSubdirsAlso then
SetFileAttributesRedir(DisableFsRedir, BasePath + S,
FindData.dwFileAttributes and not FILE_ATTRIBUTE_READONLY);
end;
if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
if Assigned(DeleteFileProc) then begin
if not DeleteFileProc(DisableFsRedir, BasePath + S, Param) then
Result := False;
end
else begin
if not DeleteFileRedir(DisableFsRedir, BasePath + S) then
Result := False;
end;
end
else begin
if DeleteSubdirsAlso then
if not DelTree(DisableFsRedir, BasePath + S, True, True, True, BreakOnError,
DeleteDirProc, DeleteFileProc, Param) then
Result := False;
end;
end;
until (BreakOnError and not Result) or not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
end;
if (not BreakOnError or Result) and IsDir then begin
if Assigned(DeleteDirProc) then begin
if not DeleteDirProc(DisableFsRedir, Path, Param) then
Result := False;
end
else begin
if not RemoveDirectoryRedir(DisableFsRedir, Path) then
Result := False;
end;
end;
end;
function IsDirEmpty(const DisableFsRedir: Boolean; const Dir: String): Boolean;
{ Returns True if Dir contains no files or subdirectories.
Note: If Dir does not exist or lacks list permission, False will be
returned. }
var
H: THandle;
FindData: TWin32FindData;
begin
H := FindFirstFileRedir(DisableFsRedir, AddBackslash(Dir) + '*', FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
Result := True;
while True do begin
if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
{ Found a file }
Result := False;
Break;
end;
if (StrComp(FindData.cFileName, '.') <> 0) and
(StrComp(FindData.cFileName, '..') <> 0) then begin
{ Found a subdirectory }
Result := False;
Break;
end;
if not FindNextFile(H, FindData) then begin
if GetLastError <> ERROR_NO_MORE_FILES then begin
{ Exited the loop early due to some unexpected error. The directory
might not be empty, so return False }
Result := False;
end;
Break;
end;
end;
finally
Windows.FindClose(H);
end;
end
else begin
{ The directory may not exist, or it may lack list permission }
Result := False;
end;
end;
procedure IncrementSharedCount(const RegView: TRegView; const Filename: String;
const AlreadyExisted: Boolean);
const
SharedDLLsKey = NEWREGSTR_PATH_SETUP + '\SharedDLLs'; {don't localize}
var
ErrorCode: Longint;
K: HKEY;
Disp, Size, Count, CurType, NewType: DWORD;
CountStr: String;
FilenameP: PChar;
begin
ErrorCode := RegCreateKeyExView(RegView, HKEY_LOCAL_MACHINE, SharedDLLsKey, 0, nil,
REG_OPTION_NON_VOLATILE, KEY_QUERY_VALUE or KEY_SET_VALUE, nil, K, @Disp);
if ErrorCode <> ERROR_SUCCESS then
raise Exception.Create(FmtSetupMessage(msgErrorRegOpenKey,
[GetRegRootKeyName(HKEY_LOCAL_MACHINE), SharedDLLsKey]) + SNewLine2 +
FmtSetupMessage(msgErrorFunctionFailedWithMessage,
['RegCreateKeyEx', IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
FilenameP := PChar(Filename);
Count := 0;
NewType := REG_DWORD;
try
if RegQueryValueEx(K, FilenameP, nil, @CurType, nil, @Size) = ERROR_SUCCESS then
case CurType of
REG_SZ:
if RegQueryStringValue(K, FilenameP, CountStr) then begin
Count := StrToInt(CountStr);
NewType := REG_SZ;
end;
REG_BINARY: begin
if (Size >= 1) and (Size <= 4) then begin
if RegQueryValueEx(K, FilenameP, nil, nil, @Count, @Size) <> ERROR_SUCCESS then
{ ^ relies on the high 3 bytes of Count being initialized to 0 }
Abort;
NewType := REG_BINARY;
end;
end;
REG_DWORD: begin
Size := SizeOf(DWORD);
if RegQueryValueEx(K, FilenameP, nil, nil, @Count, @Size) <> ERROR_SUCCESS then
Abort;
end;
end;
except
Count := 0;
end;
if Integer(Count) < 0 then Count := 0; { just in case... }
if (Count = 0) and AlreadyExisted then
Inc(Count);
Inc(Count);
case NewType of
REG_SZ: begin
CountStr := IntToStr(Count);
RegSetValueEx(K, FilenameP, 0, NewType, PChar(CountStr), (Length(CountStr)+1)*SizeOf(CountStr[1]));
end;
REG_BINARY, REG_DWORD:
RegSetValueEx(K, FilenameP, 0, NewType, @Count, SizeOf(Count));
end;
RegCloseKey(K);
end;
function DecrementSharedCount(const RegView: TRegView;
const Filename: String): Boolean;
{ Attempts to decrement the shared file reference count of Filename. Returns
True if the count reached zero (meaning it's OK to delete the file). }
const
SharedDLLsKey = NEWREGSTR_PATH_SETUP + '\SharedDLLs'; {don't localize}
var
ErrorCode: Longint;
K: HKEY;
CountRead: Boolean;
Count, CurType, Size: DWORD;
CountStr: String;
begin
Result := False;
ErrorCode := RegOpenKeyExView(RegView, HKEY_LOCAL_MACHINE, SharedDLLsKey, 0,
KEY_QUERY_VALUE or KEY_SET_VALUE, K);
if ErrorCode = ERROR_FILE_NOT_FOUND then
Exit;
if ErrorCode <> ERROR_SUCCESS then
raise Exception.Create(FmtSetupMessage(msgErrorRegOpenKey,
[GetRegRootKeyName(HKEY_LOCAL_MACHINE), SharedDLLsKey]) + SNewLine2 +
FmtSetupMessage(msgErrorFunctionFailedWithMessage,
['RegOpenKeyEx', IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
try
if RegQueryValueEx(K, PChar(Filename), nil, @CurType, nil, @Size) <> ERROR_SUCCESS then
Exit;
CountRead := False;
Count := 0;
try
case CurType of
REG_SZ:
if RegQueryStringValue(K, PChar(Filename), CountStr) then begin
Count := StrToInt(CountStr);
CountRead := True;
end;
REG_BINARY: begin
if (Size >= 1) and (Size <= 4) then begin
if RegQueryValueEx(K, PChar(Filename), nil, nil, @Count, @Size) = ERROR_SUCCESS then
{ ^ relies on the high 3 bytes of Count being initialized to 0 }
CountRead := True;
end;
end;
REG_DWORD: begin
Size := SizeOf(DWORD);
if RegQueryValueEx(K, PChar(Filename), nil, nil, @Count, @Size) = ERROR_SUCCESS then
CountRead := True;
end;
end;
except
{ don't propogate exceptions (e.g. from StrToInt) }
end;
{ If we failed to read the count, or it's in some type we don't recognize,
don't touch it }
if not CountRead then
Exit;
Dec(Count);
if Integer(Count) <= 0 then begin
Result := True;
RegDeleteValue(K, PChar(Filename));
end
else begin
case CurType of
REG_SZ: begin
CountStr := IntToStr(Count);
RegSetValueEx(K, PChar(Filename), 0, REG_SZ, PChar(CountStr), (Length(CountStr)+1)*SizeOf(Char));
end;
REG_BINARY, REG_DWORD:
RegSetValueEx(K, PChar(Filename), 0, CurType, @Count, SizeOf(Count));
end;
end;
finally
RegCloseKey(K);
end;
end;
function GetFileDateTime(const DisableFsRedir: Boolean; const Filename: String;
var DateTime: TFileTime): Boolean;
var
Handle: THandle;
FindData: TWin32FindData;
begin
Handle := FindFirstFileRedir(DisableFsRedir, Filename, FindData);
if Handle <> INVALID_HANDLE_VALUE then begin
Windows.FindClose(Handle);
if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
DateTime := FindData.ftLastWriteTime;
Result := True;
Exit;
end;
end;
Result := False;
DateTime.dwLowDateTime := 0;
DateTime.dwHighDateTime := 0;
end;
function GetMD5OfFile(const DisableFsRedir: Boolean; const Filename: String): TMD5Digest;
{ Gets MD5 sum of the file Filename. An exception will be raised upon
failure. }
var
F: TFile;
NumRead: Cardinal;
Context: TMD5Context;
Buf: array[0..65535] of Byte;
begin
MD5Init(Context);
F := TFileRedir.Create(DisableFsRedir, Filename, fdOpenExisting, faRead, fsReadWrite);
try
while True do begin
NumRead := F.Read(Buf, SizeOf(Buf));
if NumRead = 0 then Break;
MD5Update(Context, Buf, NumRead);
end;
finally
F.Free;
end;
Result := MD5Final(Context);
end;
function GetSHA1OfFile(const DisableFsRedir: Boolean; const Filename: String): TSHA1Digest;
{ Gets SHA-1 sum of the file Filename. An exception will be raised upon
failure. }
var
F: TFile;
NumRead: Cardinal;
Context: TSHA1Context;
Buf: array[0..65535] of Byte;
begin
SHA1Init(Context);
F := TFileRedir.Create(DisableFsRedir, Filename, fdOpenExisting, faRead, fsReadWrite);
try
while True do begin
NumRead := F.Read(Buf, SizeOf(Buf));
if NumRead = 0 then Break;
SHA1Update(Context, Buf, NumRead);
end;
finally
F.Free;
end;
Result := SHA1Final(Context);
end;
function GetMD5OfAnsiString(const S: AnsiString): TMD5Digest;
begin
Result := MD5Buf(Pointer(S)^, Length(S)*SizeOf(S[1]));
end;
{$IFDEF UNICODE}
function GetMD5OfUnicodeString(const S: UnicodeString): TMD5Digest;
begin
Result := MD5Buf(Pointer(S)^, Length(S)*SizeOf(S[1]));
end;
{$ENDIF}
function GetSHA1OfAnsiString(const S: AnsiString): TSHA1Digest;
begin
Result := SHA1Buf(Pointer(S)^, Length(S)*SizeOf(S[1]));
end;
{$IFDEF UNICODE}
function GetSHA1OfUnicodeString(const S: UnicodeString): TSHA1Digest;
begin
Result := SHA1Buf(Pointer(S)^, Length(S)*SizeOf(S[1]));
end;
{$ENDIF}
var
SFCInitialized: Boolean;
SfcIsFileProtectedFunc: function(RpcHandle: THandle; ProtFileName: PWideChar): BOOL; stdcall;
function IsProtectedSystemFile(const DisableFsRedir: Boolean;
const Filename: String): Boolean;
{ Returns True if the specified file is protected by Windows File Protection
(and therefore can't be replaced). }
var
M: HMODULE;
FN: String;
{$IFNDEF UNICODE}
Buf: array[0..4095] of WideChar;
{$ENDIF}
begin
if not SFCInitialized then begin
M := SafeLoadLibrary(PChar(AddBackslash(GetSystemDir) + 'sfc.dll'),
SEM_NOOPENFILEERRORBOX);
if M <> 0 then
SfcIsFileProtectedFunc := GetProcAddress(M, 'SfcIsFileProtected');
SFCInitialized := True;
end;
if Assigned(SfcIsFileProtectedFunc) then begin
{ The function only accepts fully qualified paths. Also, as of
IA-64 2003 SP1 and x64 XP, it does not respect file system redirection,
so a call to ReplaceSystemDirWithSysWow64 is needed. }
FN := PathExpand(Filename);
if not DisableFsRedir then
FN := ReplaceSystemDirWithSysWow64(FN);
{$IFDEF UNICODE}
Result := SfcIsFileProtectedFunc(0, PChar(FN));
{$ELSE}
Buf[MultiByteToWideChar(CP_ACP, 0, PChar(FN), Length(FN), Buf,
(SizeOf(Buf) div SizeOf(Buf[0])) - 1)] := #0;
Result := (Buf[0] <> #0) and SfcIsFileProtectedFunc(0, Buf);
{$ENDIF}
end
else begin
{ Windows File Protection doesn't exist on Windows 95/98/NT4 }
Result := False;
end;
end;
procedure HandleProcessWait(ProcessHandle: THandle; const Wait: TExecWait;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer);
begin
try
if Wait = ewWaitUntilIdle then begin
repeat
ProcessMessagesProc;
until WaitForInputIdle(ProcessHandle, 50) <> WAIT_TIMEOUT;
end;
if Wait = ewWaitUntilTerminated then begin
{ Wait until the process returns, but still process any messages that
arrive. }
repeat
{ Process any pending messages first because MsgWaitForMultipleObjects
(called below) only returns when *new* messages arrive }
ProcessMessagesProc;
until MsgWaitForMultipleObjects(1, ProcessHandle, False, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0+1;
{ Process messages once more in case MsgWaitForMultipleObjects saw the
process terminate and new messages arrive simultaneously. (Can't leave
unprocessed messages waiting, or a subsequent call to WaitMessage
won't see them.) }
ProcessMessagesProc;
end;
{ Get the exit code. Will be set to STILL_ACTIVE if not yet available }
if not GetExitCodeProcess(ProcessHandle, DWORD(ResultCode)) then
ResultCode := -1; { just in case }
finally
CloseHandle(ProcessHandle);
end;
end;
function InstExec(const DisableFsRedir: Boolean; const Filename, Params: String;
WorkingDir: String; const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
CmdLine: String;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
if Filename = '>' then
CmdLine := Params
else begin
CmdLine := '"' + Filename + '"';
if Params <> '' then
CmdLine := CmdLine + ' ' + Params;
if (CompareText(PathExtractExt(Filename), '.bat') = 0) or
(CompareText(PathExtractExt(Filename), '.cmd') = 0) then begin
{ Use our own handling for .bat and .cmd files since passing them straight
to CreateProcess on Windows NT 4.0 has problems: it doesn't properly
quote the command line it passes to cmd.exe. This didn't work before:
Filename: "c:\batch.bat"; Parameters: """abc"""
And other Windows versions might have unknown quirks too, since
CreateProcess isn't documented to accept .bat files in the first place. }
if UsingWinNT then
{ With cmd.exe, the whole command line must be quoted for quoted
parameters to work. For example, this fails:
cmd.exe /c "z:\blah.bat" "test"
But this works:
cmd.exe /c ""z:\blah.bat" "test""
}
CmdLine := '"' + AddBackslash(GetSystemDir) + 'cmd.exe" /C "' + CmdLine + '"'
else
CmdLine := '"' + AddBackslash(GetWinDir) + 'COMMAND.COM" /C ' + CmdLine;
end;
if WorkingDir = '' then
WorkingDir := PathExtractDir(Filename);
end;
FillChar(StartupInfo, SizeOf(StartupInfo), 0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := ShowCmd;
if WorkingDir = '' then
WorkingDir := GetSystemDir;
Result := CreateProcessRedir(DisableFsRedir, nil, PChar(CmdLine), nil, nil, False,
CREATE_DEFAULT_ERROR_MODE, nil, PChar(WorkingDir), StartupInfo, ProcessInfo);
if not Result then begin
ResultCode := GetLastError;
Exit;
end;
{ Don't need the thread handle, so close it now }
CloseHandle(ProcessInfo.hThread);
HandleProcessWait(ProcessInfo.hProcess, Wait, ProcessMessagesProc, ResultCode);
end;
function InstShellExec(const Verb, Filename, Params: String; WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
Info: TShellExecuteInfo;
begin
if WorkingDir = '' then begin
WorkingDir := PathExtractDir(Filename);
if WorkingDir = '' then
WorkingDir := GetSystemDir;
end;
FillChar(Info, SizeOf(Info), 0);
Info.cbSize := SizeOf(Info);
Info.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_FLAG_DDEWAIT or
SEE_MASK_NOCLOSEPROCESS;
if Verb <> '' then
Info.lpVerb := PChar(Verb);
Info.lpFile := PChar(Filename);
Info.lpParameters := PChar(Params);
Info.lpDirectory := PChar(WorkingDir);
Info.nShow := ShowCmd;
Result := ShellExecuteEx(@Info);
if not Result then begin
ResultCode := GetLastError;
Exit;
end;
ResultCode := STILL_ACTIVE;
{ A process handle won't always be returned, e.g. if DDE was used }
if Info.hProcess <> 0 then
HandleProcessWait(Info.hProcess, Wait, ProcessMessagesProc, ResultCode);
end;
function CheckForOrCreateMutexes(Mutexes: String; const Create: Boolean): Boolean;
function MutexPos(const S: String): Integer;
var
I: Integer;
begin
for I := 1 to Length(S) do begin
if (S[I] = ',') and ((I = 1) or (S[I-1] <> '\')) then begin
Result := I;
Exit;
end;
end;
Result := 0;
end;
{ Returns True if any of the mutexes in the comma-separated Mutexes string
exist and Create is False }
var
I: Integer;
M: String;
H: THandle;
begin
Result := False;
repeat
I := MutexPos(Mutexes);
if I = 0 then I := Maxint;
M := Trim(Copy(Mutexes, 1, I-1));
if M <> '' then begin
StringChange(M, '\,', ',');
if Create then begin
CreateMutex(M)
end else begin
H := OpenMutex(SYNCHRONIZE, False, PChar(M));
if H <> 0 then begin
CloseHandle(H);
Result := True;
Break;
end;
end;
end;
Delete(Mutexes, 1, I);
until Mutexes = '';
end;
function CheckForMutexes(const Mutexes: String): Boolean;
begin
Result := CheckForOrCreateMutexes(Mutexes, False);
end;
procedure CreateMutexes(const Mutexes: String);
begin
CheckForOrCreateMutexes(Mutexes, True);
end;
function ModifyPifFile(const Filename: String; const CloseOnExit: Boolean): Boolean;
{ Changes the "Close on exit" setting of a .pif file. Returns True if it was
able to make the change. }
var
F: TFile;
B: Byte;
begin
{ Note: Specs on the .pif format were taken from
http://smsoft.chat.ru/en/pifdoc.htm }
Result := False;
F := TFile.Create(Filename, fdOpenExisting, faReadWrite, fsNone);
try
{ Is it a valid .pif file? }
if F.Size.Lo >= $171 then begin
F.Seek($63);
F.ReadBuffer(B, SizeOf(B));
{ Toggle the "Close on exit" bit }
if (B and $10 <> 0) <> CloseOnExit then begin
B := B xor $10;
F.Seek($63);
F.WriteBuffer(B, SizeOf(B));
end;