forked from jrsoftware/issrc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCmnFunc2.pas
1847 lines (1698 loc) · 61.5 KB
/
CmnFunc2.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 CmnFunc2;
{
Inno Setup
Copyright (C) 1997-2024 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Common non-VCL functions
}
{$B-,R-}
interface
uses
Windows, SysUtils, Classes;
const
KEY_WOW64_64KEY = $0100;
type
TOneShotTimer = record
private
FLastElapsed: Cardinal;
FStartTick: DWORD;
FTimeout: Cardinal;
public
function Expired: Boolean;
procedure SleepUntilExpired;
procedure Start(const Timeout: Cardinal);
function TimeElapsed: Cardinal;
function TimeRemaining: Cardinal;
end;
TLogProc = procedure(const S: String; const Error, FirstLine: Boolean; const Data: NativeInt);
TOutputMode = (omLog, omCapture);
TCreateProcessOutputReaderPipe = record
OKToRead: Boolean;
PipeRead, PipeWrite: THandle;
Buffer: AnsiString;
CaptureList: TStringList;
end;
TCreateProcessOutputReader = class
private
FMaxTotalBytesToRead: Cardinal;
FMaxTotalLinesToRead: Cardinal;
FTotalBytesRead: Cardinal;
FTotalLinesRead: Cardinal;
FStdInNulDevice: THandle;
FStdOut: TCreateProcessOutputReaderPipe;
FStdErr: TCreateProcessOutputReaderPipe;
FLogProc: TLogProc;
FLogProcData: NativeInt;
FNextLineIsFirstLine: Boolean;
FMode: TOutputMode;
FCaptureOutList: TStringList;
FCaptureErrList: TStringList;
FCaptureError: Boolean;
procedure CloseAndClearHandle(var Handle: THandle);
procedure HandleAndLogErrorFmt(const S: String; const Args: array of const);
public
constructor Create(const ALogProc: TLogProc; const ALogProcData: NativeInt; AMode: TOutputMode = omLog);
destructor Destroy; override;
procedure UpdateStartupInfo(var StartupInfo: TStartupInfo);
procedure NotifyCreateProcessDone;
procedure Read(const LastRead: Boolean);
property CaptureOutList: TStringList read FCaptureOutList;
property CaptureErrList: TStringList read FCaptureErrList;
property CaptureError: Boolean read FCaptureError;
end;
TRegView = (rvDefault, rv32Bit, rv64Bit);
const
RegViews64Bit = [rv64Bit];
function NewFileExists(const Name: String): Boolean;
function DirExists(const Name: String): Boolean;
function FileOrDirExists(const Name: String): Boolean;
function IsDirectoryAndNotReparsePoint(const Name: String): Boolean;
function GetIniString(const Section, Key: String; Default: String; const Filename: String): String;
function GetIniInt(const Section, Key: String; const Default, Min, Max: Longint; const Filename: String): Longint;
function GetIniBool(const Section, Key: String; const Default: Boolean; const Filename: String): Boolean;
function IniKeyExists(const Section, Key, Filename: String): Boolean;
function IsIniSectionEmpty(const Section, Filename: String): Boolean;
function SetIniString(const Section, Key, Value, Filename: String): Boolean;
function SetIniInt(const Section, Key: String; const Value: Longint; const Filename: String): Boolean;
function SetIniBool(const Section, Key: String; const Value: Boolean; const Filename: String): Boolean;
procedure DeleteIniEntry(const Section, Key, Filename: String);
procedure DeleteIniSection(const Section, Filename: String);
function GetEnv(const EnvVar: String): String;
function GetCmdTail: String;
function GetCmdTailEx(StartIndex: Integer): String;
function NewParamCount: Integer;
function NewParamStr(Index: Integer): string;
function AddQuotes(const S: String): String;
function RemoveQuotes(const S: String): String;
function GetShortName(const LongName: String): String;
function GetWinDir: String;
function GetSystemWinDir: String;
function GetSystemDir: String;
function GetSysWow64Dir: String;
function GetSysNativeDir(const IsWin64: Boolean): String;
function GetTempDir: String;
function StringChange(var S: String; const FromStr, ToStr: String): Integer;
function StringChangeEx(var S: String; const FromStr, ToStr: String;
const SupportDBCS: Boolean): Integer;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
function ConvertConstPercentStr(var S: String): Boolean;
function ConvertPercentStr(var S: String): Boolean;
function ConstPos(const Ch: Char; const S: String): Integer;
function SkipPastConst(const S: String; const Start: Integer): Integer;
function RegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
function RegQueryMultiStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
function RegValueExists(H: HKEY; Name: PChar): Boolean;
function RegCreateKeyExView(const RegView: TRegView; hKey: HKEY; lpSubKey: PChar;
Reserved: DWORD; lpClass: PChar; dwOptions: DWORD; samDesired: REGSAM;
lpSecurityAttributes: PSecurityAttributes; var phkResult: HKEY;
lpdwDisposition: PDWORD): Longint;
function RegOpenKeyExView(const RegView: TRegView; hKey: HKEY; lpSubKey: PChar;
ulOptions: DWORD; samDesired: REGSAM; var phkResult: HKEY): Longint;
function RegDeleteKeyView(const RegView: TRegView; const Key: HKEY; const Name: PChar): Longint;
function RegDeleteKeyIncludingSubkeys(const RegView: TRegView; const Key: HKEY; const Name: PChar): Longint;
function RegDeleteKeyIfEmpty(const RegView: TRegView; const RootKey: HKEY; const SubkeyName: PChar): Longint;
function GetShellFolderPath(const FolderID: Integer): String;
function GetCurrentUserSid: String;
function IsAdminLoggedOn: Boolean;
function IsPowerUserLoggedOn: Boolean;
function IsMultiByteString(const S: AnsiString): Boolean;
function FontExists(const FaceName: String): Boolean;
function GetUILanguage: LANGID;
function RemoveAccelChar(const S: String): String;
function GetTextWidth(const DC: HDC; S: String; const Prefix: Boolean): Integer;
function AddPeriod(const S: String): String;
function GetExceptMessage: String;
function GetPreferredUIFont: String;
function IsWildcard(const Pattern: String): Boolean;
function WildcardMatch(const Text, Pattern: PChar): Boolean;
function IntMax(const A, B: Integer): Integer;
function Win32ErrorString(ErrorCode: Integer): String;
function DeleteDirTree(const Dir: String): Boolean;
function SetNTFSCompression(const FileOrDir: String; Compress: Boolean): Boolean;
procedure AddToWindowMessageFilterEx(const Wnd: HWND; const Msg: UINT);
function ShutdownBlockReasonCreate(Wnd: HWND; const Reason: String): Boolean;
function ShutdownBlockReasonDestroy(Wnd: HWND): Boolean;
function TryStrToBoolean(const S: String; var BoolResult: Boolean): Boolean;
procedure WaitMessageWithTimeout(const Milliseconds: DWORD);
function MoveFileReplace(const ExistingFileName, NewFileName: String): Boolean;
procedure TryEnableAutoCompleteFileSystem(Wnd: HWND);
procedure CreateMutex(const MutexName: String);
implementation
uses
PathFunc;
{ Avoid including Variants (via ActiveX and ShlObj) in SetupLdr (SetupLdr uses CmnFunc2), saving 26 KB. }
const
shell32 = 'shell32.dll';
type
PSHItemID = ^TSHItemID;
_SHITEMID = record
cb: Word; { Size of the ID (including cb itself) }
abID: array[0..0] of Byte; { The item ID (variable length) }
end;
TSHItemID = _SHITEMID;
SHITEMID = _SHITEMID;
PItemIDList = ^TItemIDList;
_ITEMIDLIST = record
mkid: TSHItemID;
end;
TItemIDList = _ITEMIDLIST;
ITEMIDLIST = _ITEMIDLIST;
IMalloc = interface(IUnknown)
['{00000002-0000-0000-C000-000000000046}']
function Alloc(cb: Longint): Pointer; stdcall;
function Realloc(pv: Pointer; cb: Longint): Pointer; stdcall;
procedure Free(pv: Pointer); stdcall;
function GetSize(pv: Pointer): Longint; stdcall;
function DidAlloc(pv: Pointer): Integer; stdcall;
procedure HeapMinimize; stdcall;
end;
function SHGetMalloc(var ppMalloc: IMalloc): HResult; stdcall; external shell32 name 'SHGetMalloc';
function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer;
var ppidl: PItemIDList): HResult; stdcall; external shell32 name 'SHGetSpecialFolderLocation';
function SHGetPathFromIDList(pidl: PItemIDList; pszPath: PChar): BOOL; stdcall;
external shell32 name 'SHGetPathFromIDListW';
function InternalGetFileAttr(const Name: String): Integer;
begin
Result := GetFileAttributes(PChar(RemoveBackslashUnlessRoot(Name)));
end;
function NewFileExists(const Name: String): Boolean;
{ Returns True if the specified file exists.
This function is better than Delphi's FileExists function because it works
on files in directories that don't have "list" permission. There is, however,
one other difference: FileExists allows wildcards, but this function does
not. }
var
Attr: Integer;
begin
Attr := GetFileAttributes(PChar(Name));
Result := (Attr <> -1) and (Attr and faDirectory = 0);
end;
function DirExists(const Name: String): Boolean;
{ Returns True if the specified directory name exists. The specified name
may include a trailing backslash.
NOTE: Delphi's FileCtrl unit has a similar function called DirectoryExists.
However, the implementation is different between Delphi 1 and 2. (Delphi 1
does not count hidden or system directories as existing.) }
var
Attr: Integer;
begin
Attr := InternalGetFileAttr(Name);
Result := (Attr <> -1) and (Attr and faDirectory <> 0);
end;
function FileOrDirExists(const Name: String): Boolean;
{ Returns True if the specified directory or file name exists. The specified
name may include a trailing backslash. }
begin
Result := InternalGetFileAttr(Name) <> -1;
end;
function IsDirectoryAndNotReparsePoint(const Name: String): Boolean;
{ Returns True if the specified directory exists and is NOT a reparse point. }
const
FILE_ATTRIBUTE_REPARSE_POINT = $00000400;
var
Attr: DWORD;
begin
Attr := GetFileAttributes(PChar(Name));
Result := (Attr <> $FFFFFFFF) and
(Attr and FILE_ATTRIBUTE_DIRECTORY <> 0) and
(Attr and FILE_ATTRIBUTE_REPARSE_POINT = 0);
end;
function GetIniString(const Section, Key: String; Default: String;
const Filename: String): String;
var
BufSize, Len: Integer;
begin
{ On Windows 9x, Get*ProfileString can modify the lpDefault parameter, so
make sure it's unique and not read-only }
UniqueString(Default);
BufSize := 256;
while True do begin
SetString(Result, nil, BufSize);
if Filename <> '' then
Len := GetPrivateProfileString(PChar(Section), PChar(Key), PChar(Default),
@Result[1], BufSize, PChar(Filename))
else
Len := GetProfileString(PChar(Section), PChar(Key), PChar(Default),
@Result[1], BufSize);
{ Work around bug present on Windows NT/2000 (not 95): When lpDefault is
too long to fit in the buffer, nSize is returned (null terminator
counted) instead of nSize-1 (what it's supposed to return). So don't
trust the returned length; calculate it ourself.
Note: This also ensures the string can never include embedded nulls. }
if Len <> 0 then
Len := StrLen(PChar(Result));
{ Break if the string fits, or if it's apparently 64 KB or longer.
No point in increasing buffer size past 64 KB because the length
returned by Windows 2000 seems to be mod 65536. And Windows 95 returns
0 on values longer than ~32 KB.
Note: The docs say the function returns "nSize minus one" if the buffer
is too small, but I'm willing to bet it can be "minus two" if the last
character is double-byte. Let's just be extremely paranoid and check for
BufSize-8. }
if (Len < BufSize-8) or (BufSize >= 65536) then begin
SetLength(Result, Len);
Break;
end;
{ Otherwise double the buffer size and try again }
BufSize := BufSize * 2;
end;
end;
function GetIniInt(const Section, Key: String;
const Default, Min, Max: Longint; const Filename: String): Longint;
{ Reads a Longint from an INI file. If the Longint read is not between Min/Max
then it returns Default. If Min=Max then Min/Max are ignored }
var
S: String;
E: Integer;
begin
S := GetIniString(Section, Key, '', Filename);
if S = '' then
Result := Default
else begin
Val(S, Result, E);
if (E <> 0) or ((Min <> Max) and ((Result < Min) or (Result > Max))) then
Result := Default;
end;
end;
function GetIniBool(const Section, Key: String; const Default: Boolean;
const Filename: String): Boolean;
begin
Result := GetIniInt(Section, Key, Ord(Default), 0, 0, Filename) <> 0;
end;
function IniKeyExists(const Section, Key, Filename: String): Boolean;
function Equals(const Default: PChar): Boolean;
var
Test: array[0..7] of Char;
begin
Test[0] := #0;
if Filename <> '' then
GetPrivateProfileString(PChar(Section), PChar(Key), Default,
Test, SizeOf(Test) div SizeOf(Test[0]), PChar(Filename))
else
GetProfileString(PChar(Section), PChar(Key), Default,
Test, SizeOf(Test) div SizeOf(Test[0]));
Result := lstrcmp(Test, Default) = 0;
end;
begin
{ If the key does not exist, a default string is returned both times. }
Result := not Equals('x1234x') or not Equals('x5678x'); { <- don't change }
end;
function IsIniSectionEmpty(const Section, Filename: String): Boolean;
var
Test: array[0..255] of Char;
begin
Test[0] := #0;
if Filename <> '' then
GetPrivateProfileString(PChar(Section), nil, '', Test,
SizeOf(Test) div SizeOf(Test[0]), PChar(Filename))
else
GetProfileString(PChar(Section), nil, '', Test,
SizeOf(Test) div SizeOf(Test[0]));
Result := Test[0] = #0;
end;
function SetIniString(const Section, Key, Value, Filename: String): Boolean;
begin
if Filename <> '' then
Result := WritePrivateProfileString(PChar(Section), PChar(Key),
PChar(Value), PChar(Filename))
else
Result := WriteProfileString(PChar(Section), PChar(Key),
PChar(Value));
end;
function SetIniInt(const Section, Key: String; const Value: Longint;
const Filename: String): Boolean;
begin
Result := SetIniString(Section, Key, IntToStr(Value), Filename);
end;
function SetIniBool(const Section, Key: String; const Value: Boolean;
const Filename: String): Boolean;
begin
Result := SetIniInt(Section, Key, Ord(Value), Filename);
end;
procedure DeleteIniEntry(const Section, Key, Filename: String);
begin
if Filename <> '' then
WritePrivateProfileString(PChar(Section), PChar(Key),
nil, PChar(Filename))
else
WriteProfileString(PChar(Section), PChar(Key),
nil);
end;
procedure DeleteIniSection(const Section, Filename: String);
begin
if Filename <> '' then
WritePrivateProfileString(PChar(Section), nil, nil,
PChar(Filename))
else
WriteProfileString(PChar(Section), nil, nil);
end;
function GetEnv(const EnvVar: String): String;
{ Gets the value of the specified environment variable. (Just like TP's GetEnv) }
var
Res: DWORD;
begin
SetLength(Result, 255);
repeat
Res := GetEnvironmentVariable(PChar(EnvVar), PChar(Result), Length(Result));
if Res = 0 then begin
Result := '';
Break;
end;
until AdjustLength(Result, Res);
end;
function GetParamStr(const P: PChar; var Param: String): PChar;
function Extract(P: PChar; const Buffer: PChar; var Len: Integer): PChar;
var
InQuote: Boolean;
begin
Len := 0;
InQuote := False;
while (P^ <> #0) and ((P^ > ' ') or InQuote) do begin
if P^ = '"' then
InQuote := not InQuote
else begin
if Assigned(Buffer) then
Buffer[Len] := P^;
Inc(Len);
end;
Inc(P);
end;
Result := P;
end;
var
Len: Integer;
Buffer: String;
begin
Extract(P, nil, Len);
SetString(Buffer, nil, Len);
Result := Extract(P, @Buffer[1], Len);
Param := Buffer;
while (Result^ <> #0) and (Result^ <= ' ') do
Inc(Result);
end;
function GetCmdTail: String;
{ Returns all command line parameters passed to the process as a single
string. }
var
S: String;
begin
Result := GetParamStr(GetCommandLine, S);
end;
function GetCmdTailEx(StartIndex: Integer): String;
{ Returns all command line parameters passed to the process as a single
string, starting with StartIndex (one-based). }
var
P: PChar;
S: String;
begin
P := GetParamStr(GetCommandLine, S);
while (StartIndex > 1) and (P^ <> #0) do begin
P := GetParamStr(P, S);
Dec(StartIndex);
end;
Result := P;
end;
function NewParamCount: Integer;
var
P: PChar;
S: String;
begin
P := GetParamStr(GetCommandLine, S);
Result := 0;
while P^ <> #0 do begin
Inc(Result);
P := GetParamStr(P, S);
end;
end;
function NewParamStr(Index: Integer): string;
{ Returns the Indexth command line parameter, or an empty string if Index is
out of range.
Differences from Delphi's ParamStr:
- No limits on parameter length
- Doesn't ignore empty parameters ("")
- Handles the empty argv[0] case like MSVC: if GetCommandLine() returns
" a b" then NewParamStr(1) should return "a", not "b" }
var
Buffer: array[0..MAX_PATH-1] of Char;
S: String;
P: PChar;
begin
if Index = 0 then begin
SetString(Result, Buffer, GetModuleFileName(0, Buffer, SizeOf(Buffer) div SizeOf(Buffer[0])));
end
else begin
P := GetCommandLine;
while True do begin
if P^ = #0 then begin
S := '';
Break;
end;
P := GetParamStr(P, S);
if Index = 0 then Break;
Dec(Index);
end;
Result := S;
end;
end;
function AddQuotes(const S: String): String;
{ Adds a quote (") character to the left and right sides of the string if
the string contains a space and it didn't have quotes already. This is
primarily used when spawning another process with a long filename as one of
the parameters. }
begin
Result := Trim(S);
if (PathPos(' ', Result) <> 0) and
((Result[1] <> '"') or (PathLastChar(Result)^ <> '"')) then
Result := '"' + Result + '"';
end;
function RemoveQuotes(const S: String): String;
{ Opposite of AddQuotes; removes any quotes around the string. }
begin
Result := S;
while (Result <> '') and (Result[1] = '"') do
Delete(Result, 1, 1);
while (Result <> '') and (PathLastChar(Result)^ = '"') do
SetLength(Result, Length(Result)-1);
end;
function ConvertPercentStr(var S: String): Boolean;
{ Expands all %-encoded characters in the string (see RFC 2396). Returns True
if all were successfully expanded. }
var
I, C, E: Integer;
N: String;
begin
Result := True;
I := 1;
while I <= Length(S) do begin
if S[I] = '%' then begin
N := Copy(S, I, 3);
if Length(N) <> 3 then begin
Result := False;
Break;
end;
N[1] := '$';
Val(N, C, E);
if E <> 0 then begin
Result := False;
Break;
end;
{ delete the two numbers following '%', and replace '%' with the character }
Delete(S, I+1, 2);
S[I] := Chr(C);
end;
Inc(I);
end;
end;
function SkipPastConst(const S: String; const Start: Integer): Integer;
{ Returns the character index following the Inno Setup constant embedded
into the string S at index Start.
If the constant is not closed (missing a closing brace), it returns zero. }
var
L, BraceLevel, LastOpenBrace: Integer;
begin
Result := Start;
L := Length(S);
if Result < L then begin
Inc(Result);
if S[Result] = '{' then begin
Inc(Result);
Exit;
end
else begin
BraceLevel := 1;
LastOpenBrace := -1;
while Result <= L do begin
case S[Result] of
'{': begin
if LastOpenBrace <> Result-1 then begin
Inc(BraceLevel);
LastOpenBrace := Result;
end
else
{ Skip over '{{' when in an embedded constant }
Dec(BraceLevel);
end;
'}': begin
Dec(BraceLevel);
if BraceLevel = 0 then begin
Inc(Result);
Exit;
end;
end;
end;
Inc(Result);
end;
end;
end;
Result := 0;
end;
function ConvertConstPercentStr(var S: String): Boolean;
{ Same as ConvertPercentStr, but is designed to ignore embedded Inno Setup
constants. Any '%' characters between braces are not translated. Two
consecutive braces are ignored. }
var
I, C, E: Integer;
N: String;
begin
Result := True;
I := 1;
while I <= Length(S) do begin
case S[I] of
'{': begin
I := SkipPastConst(S, I);
if I = 0 then begin
Result := False;
Break;
end;
Dec(I); { ...since there's an Inc below }
end;
'%': begin
N := Copy(S, I, 3);
if Length(N) <> 3 then begin
Result := False;
Break;
end;
N[1] := '$';
Val(N, C, E);
if E <> 0 then begin
Result := False;
Break;
end;
{ delete the two numbers following '%', and replace '%' with the character }
Delete(S, I+1, 2);
S[I] := Chr(C);
end;
end;
Inc(I);
end;
end;
function ConstPos(const Ch: Char; const S: String): Integer;
{ Like the standard Pos function, but skips over any Inno Setup constants
embedded in S }
var
I, L: Integer;
begin
Result := 0;
I := 1;
L := Length(S);
while I <= L do begin
if S[I] = Ch then begin
Result := I;
Break;
end
else if S[I] = '{' then begin
I := SkipPastConst(S, I);
if I = 0 then
Break;
end
else
Inc(I);
end;
end;
function GetShortName(const LongName: String): String;
{ Gets the short version of the specified long filename. If the file does not
exist, or some other error occurs, it returns LongName. }
var
Res: DWORD;
begin
SetLength(Result, MAX_PATH);
repeat
Res := GetShortPathName(PChar(LongName), PChar(Result), Length(Result));
if Res = 0 then begin
Result := LongName;
Break;
end;
until AdjustLength(Result, Res);
end;
function GetWinDir: String;
{ Returns fully qualified path of the Windows directory. Only includes a
trailing backslash if the Windows directory is the root directory. }
var
Buf: array[0..MAX_PATH-1] of Char;
begin
GetWindowsDirectory(Buf, SizeOf(Buf) div SizeOf(Buf[0]));
Result := StrPas(Buf);
end;
function GetSystemWindowsDirectoryW(lpBuffer: LPWSTR; uSize: UINT): UINT; stdcall; external kernel32;
function GetSystemWinDir: String;
{ Like get GetWinDir but uses GetSystemWindowsDirectory instead of
GetWindowsDirectory: With Terminal Services, the GetSystemWindowsDirectory
function retrieves the path of the system Windows directory, while the
GetWindowsDirectory function retrieves the path of a Windows directory that is
private for each user. On a single-user system, GetSystemWindowsDirectory is
the same as GetWindowsDirectory. }
var
Buf: array[0..MAX_PATH-1] of Char;
begin
GetSystemWindowsDirectoryW(Buf, SizeOf(Buf) div SizeOf(Buf[0]));
Result := StrPas(Buf);
end;
function GetSystemDir: String;
{ Returns fully qualified path of the Windows System directory. Only includes a
trailing backslash if the Windows System directory is the root directory. }
var
Buf: array[0..MAX_PATH-1] of Char;
begin
GetSystemDirectory(Buf, SizeOf(Buf) div SizeOf(Buf[0]));
Result := StrPas(Buf);
end;
function GetSysWow64Dir: String;
{ Returns fully qualified path of the SysWow64 directory on 64-bit Windows.
Returns '' if there is no SysWow64 directory (e.g. running 32-bit Windows). }
var
GetSystemWow64DirectoryFunc: function(
lpBuffer: PWideChar; uSize: UINT): UINT; stdcall;
Res: Integer;
Buf: array[0..MAX_PATH] of Char;
begin
Result := '';
GetSystemWow64DirectoryFunc := GetProcAddress(GetModuleHandle(kernel32),
'GetSystemWow64DirectoryW');
if Assigned(GetSystemWow64DirectoryFunc) then begin
Res := GetSystemWow64DirectoryFunc(Buf, SizeOf(Buf) div SizeOf(Buf[0]));
if (Res > 0) and (Res < SizeOf(Buf) div SizeOf(Buf[0])) then
Result := Buf;
end;
end;
function GetSysNativeDir(const IsWin64: Boolean): String;
{ Returns the special Sysnative alias, without trailing backslash.
Returns '' if there is no Sysnative alias. }
begin
{ From MSDN: 32-bit applications can access the native system directory by
substituting %windir%\Sysnative for %windir%\System32. WOW64 recognizes
Sysnative as a special alias used to indicate that the file system should
not redirect the access. }
if IsWin64 then
{ Note: Avoiding GetWinDir here as that might not return the real Windows
directory under Terminal Services }
Result := PathExpand(AddBackslash(GetSystemDir) + '..\Sysnative') { Do not localize }
else
Result := '';
end;
function GetTempDir: String;
{ Returns fully qualified path of the temporary directory, with trailing
backslash. This does not use the Win32 function GetTempPath, due to platform
differences. }
label 1;
begin
Result := GetEnv('TMP');
if (Result <> '') and DirExists(Result) then
goto 1;
Result := GetEnv('TEMP');
if (Result <> '') and DirExists(Result) then
goto 1;
{ Like Windows 2000's GetTempPath, return USERPROFILE when TMP and TEMP
are not set }
Result := GetEnv('USERPROFILE');
if (Result <> '') and DirExists(Result) then
goto 1;
Result := GetWinDir;
1:Result := AddBackslash(PathExpand(Result));
end;
function StringChangeEx(var S: String; const FromStr, ToStr: String;
const SupportDBCS: Boolean): Integer;
{ Changes all occurrences in S of FromStr to ToStr. If SupportDBCS is True
(recommended), double-byte character sequences in S are recognized and
handled properly. Otherwise, the function behaves in a binary-safe manner.
Returns the number of times FromStr was matched and changed. }
var
FromStrLen, I, EndPos, J: Integer;
IsMatch: Boolean;
label 1;
begin
Result := 0;
if FromStr = '' then Exit;
FromStrLen := Length(FromStr);
I := 1;
1:EndPos := Length(S) - FromStrLen + 1;
while I <= EndPos do begin
IsMatch := True;
J := 0;
while J < FromStrLen do begin
if S[J+I] <> FromStr[J+1] then begin
IsMatch := False;
Break;
end;
Inc(J);
end;
if IsMatch then begin
Inc(Result);
Delete(S, I, FromStrLen);
Insert(ToStr, S, I);
Inc(I, Length(ToStr));
goto 1;
end;
if SupportDBCS then
Inc(I, PathCharLength(S, I))
else
Inc(I);
end;
end;
function StringChange(var S: String; const FromStr, ToStr: String): Integer;
{ Same as calling StringChangeEx with SupportDBCS=False }
begin
Result := StringChangeEx(S, FromStr, ToStr, False);
end;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
{ Returns True if successful. Returns False if buffer wasn't large enough,
and called AdjustLength to resize it. }
begin
Result := Integer(Res) < Length(S);
SetLength(S, Res);
end;
function InternalRegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String;
Type1, Type2: DWORD): Boolean;
var
Typ, Size: DWORD;
Len: Integer;
S: String;
ErrorCode: Longint;
label 1;
begin
Result := False;
1:Size := 0;
if (RegQueryValueEx(H, Name, nil, @Typ, nil, @Size) = ERROR_SUCCESS) and
((Typ = Type1) or (Typ = Type2)) then begin
if Size = 0 then begin
{ It's an empty string with no null terminator.
(Must handle those here since we can't pass a nil lpData pointer on
the second RegQueryValueEx call.) }
ResultStr := '';
Result := True;
end
else begin
{ Paranoia: Impose reasonable upper limit on Size to avoid potential
integer overflows below }
if Cardinal(Size) >= Cardinal($70000000) then
OutOfMemoryError;
{ Note: If Size isn't a multiple of SizeOf(S[1]), we have to round up
here so that RegQueryValueEx doesn't overflow the buffer }
Len := (Size + (SizeOf(S[1]) - 1)) div SizeOf(S[1]);
SetString(S, nil, Len);
ErrorCode := RegQueryValueEx(H, Name, nil, @Typ, @S[1], @Size);
if ErrorCode = ERROR_MORE_DATA then begin
{ The data must've increased in size since the first RegQueryValueEx
call. Start over. }
goto 1;
end;
if (ErrorCode = ERROR_SUCCESS) and
((Typ = Type1) or (Typ = Type2)) then begin
{ If Size isn't a multiple of SizeOf(S[1]), we disregard the partial
character, like RegGetValue }
Len := Size div SizeOf(S[1]);
{ Remove any null terminators from the end and trim the string to the
returned length.
Note: We *should* find 1 null terminator, but it's possible for
there to be more or none if the value was written that way. }
while (Len <> 0) and (S[Len] = #0) do
Dec(Len);
{ In a REG_MULTI_SZ value, each individual string is null-terminated,
so add 1 null (back) to the end, unless there are no strings (Len=0) }
if (Typ = REG_MULTI_SZ) and (Len <> 0) then
Inc(Len);
SetLength(S, Len);
if (Typ = REG_MULTI_SZ) and (Len <> 0) then
S[Len] := #0;
ResultStr := S;
Result := True;
end;
end;
end;
end;
function RegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
{ Queries the specified REG_SZ or REG_EXPAND_SZ registry key/value, and returns
the value in ResultStr. Returns True if successful. When False is returned,
ResultStr is unmodified. }
begin
Result := InternalRegQueryStringValue(H, Name, ResultStr, REG_SZ,
REG_EXPAND_SZ);
end;
function RegQueryMultiStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
{ Queries the specified REG_MULTI_SZ registry key/value, and returns the value
in ResultStr. Returns True if successful. When False is returned, ResultStr
is unmodified. }
begin
Result := InternalRegQueryStringValue(H, Name, ResultStr, REG_MULTI_SZ,
REG_MULTI_SZ);
end;
function RegValueExists(H: HKEY; Name: PChar): Boolean;
{ Returns True if the specified value exists. Requires KEY_QUERY_VALUE access
to the key. }
begin
Result := RegQueryValueEx(H, Name, nil, nil, nil, nil) = ERROR_SUCCESS;
end;
function RegCreateKeyExView(const RegView: TRegView; hKey: HKEY; lpSubKey: PChar;
Reserved: DWORD; lpClass: PChar; dwOptions: DWORD; samDesired: REGSAM;
lpSecurityAttributes: PSecurityAttributes; var phkResult: HKEY;
lpdwDisposition: PDWORD): Longint;
begin
if RegView = rv64Bit then
samDesired := samDesired or KEY_WOW64_64KEY;
Result := RegCreateKeyEx(hKey, lpSubKey, Reserved, lpClass, dwOptions,
samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
end;
function RegOpenKeyExView(const RegView: TRegView; hKey: HKEY; lpSubKey: PChar;
ulOptions: DWORD; samDesired: REGSAM; var phkResult: HKEY): Longint;
begin
if RegView = rv64Bit then
samDesired := samDesired or KEY_WOW64_64KEY;
Result := RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, phkResult);
end;
var
RegDeleteKeyExFunc: function(hKey: HKEY;
lpSubKey: PWideChar; samDesired: REGSAM; Reserved: DWORD): Longint; stdcall;
function RegDeleteKeyView(const RegView: TRegView; const Key: HKEY;
const Name: PChar): Longint;
begin
if RegView <> rv64Bit then
Result := RegDeleteKey(Key, Name)
else begin
if @RegDeleteKeyExFunc = nil then
RegDeleteKeyExFunc := GetProcAddress(GetModuleHandle(advapi32),
'RegDeleteKeyExW');
if Assigned(RegDeleteKeyExFunc) then
Result := RegDeleteKeyExFunc(Key, Name, KEY_WOW64_64KEY, 0)
else
Result := ERROR_PROC_NOT_FOUND;
end;
end;
function RegDeleteKeyIncludingSubkeys(const RegView: TRegView; const Key: HKEY;
const Name: PChar): Longint;
{ Deletes the specified key and all subkeys.
Returns ERROR_SUCCESS if the key was successful deleted. }
var
H: HKEY;
KeyName: String;
I, KeyNameCount: DWORD;
ErrorCode: Longint;
begin
if (Name = nil) or (Name[0] = #0) then begin
Result := ERROR_INVALID_PARAMETER;
Exit;
end;
if RegOpenKeyExView(RegView, Key, Name, 0, KEY_ENUMERATE_SUB_KEYS, H) = ERROR_SUCCESS then begin
try
SetString(KeyName, nil, 256);
I := 0;
while True do begin
KeyNameCount := Length(KeyName);
ErrorCode := RegEnumKeyEx(H, I, @KeyName[1], KeyNameCount, nil, nil, nil, nil);
if ErrorCode = ERROR_MORE_DATA then begin
{ Double the size of the buffer and try again }
if Length(KeyName) >= 65536 then begin
{ Sanity check: If we tried a 64 KB buffer and it's still saying
there's more data, something must be seriously wrong. Bail. }
Break;
end;
SetString(KeyName, nil, Length(KeyName) * 2);
Continue;
end;
if ErrorCode <> ERROR_SUCCESS then
Break;
if RegDeleteKeyIncludingSubkeys(RegView, H, PChar(KeyName)) <> ERROR_SUCCESS then
Inc(I);
end;
finally
RegCloseKey(H);
end;
end;
Result := RegDeleteKeyView(RegView, Key, Name);
end;
function RegDeleteKeyIfEmpty(const RegView: TRegView; const RootKey: HKEY;
const SubkeyName: PChar): Longint;
{ Deletes the specified subkey if it has no subkeys or values.
Returns ERROR_SUCCESS if the key was successful deleted, ERROR_DIR_NOT_EMPTY
if it was not deleted because it contained subkeys or values, or possibly
some other Win32 error code. }
var
K: HKEY;