Repository navigation
Expand file tree
/
Copy pathPathFunc.pas
More file actions
1053 lines (959 loc) · 40.2 KB
/
Copy pathPathFunc.pas
File metadata and controls
1053 lines (959 loc) · 40.2 KB
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 PathFunc;
{
Inno Setup
Copyright (C) 1997-2026 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
This unit provides some path-related functions.
The string comparison functions (including PathCompare, PathEndsWith, PathHasSubstringAt,
PathSame, PathStartsWith, PathStrCompare, PathStrFind) all ignore case by
default, and use a locale-independent "ordinal" comparison, which is important
when comparing filenames/paths. Despite the "Path" prefix, however, the
functions can be used to compare any kind of text, not just filenames/paths.
About super paths (extended-length paths):
PathHasInvalidCharacters considers all super paths as invalid.
PathSame and Path(Str)Compare do not consider a super path and its normal
version to be the same.
}
interface
uses
Windows, SysUtils;
type
EPathFuncError = class(Exception);
function AddBackslash(const S: String): String;
function PathChangeExt(const Filename, Extension: String): String;
function PathCharIsDriveLetter(const C: Char): Boolean;
function PathCharIsSlash(const C: Char): Boolean;
function PathCombine(const Dir, Filename: String): String;
function PathCompare(const S1, S2: String; const IgnoreCase: Boolean = True): Integer;
function PathComponentIsReservedName(const Filename: String): Boolean;
function PathConvertNormalToSuper(const Filename: String): String; overload;
function PathConvertNormalToSuper(const Filename: String;
out SuperFilename: String): Boolean; overload;
function PathConvertSuperToNormal(const Filename: String): String; overload;
function PathConvertSuperToNormal(const Filename: String;
out NormalFilename: String): Boolean; overload;
function PathDrivePartLength(const Filename: String): Integer;
function PathDrivePartLengthEx(const Filename: String;
const IncludeSignificantSlash: Boolean): Integer;
function PathEndsWith(const S, AEndsWith: String;
const IgnoreCase: Boolean = True): Boolean;
function PathExpand(const Filename: String): String; overload;
function PathExpand(const Filename: String; out ExpandedFilename: String): Boolean; overload;
function PathExtensionPos(const Filename: String): Integer;
function PathExtractDir(const Filename: String): String;
function PathExtractDrive(const Filename: String): String;
function PathExtractExt(const Filename: String): String;
function PathExtractName(const Filename: String): String;
function PathExtractPath(const Filename: String): String;
function PathHasInvalidCharacters(const S: String;
const AllowDriveLetterColon: Boolean): Boolean;
function PathHasSubstringAt(const S, Substring: String; const Offset: Integer;
const IgnoreCase: Boolean = True): Boolean;
function PathIsRooted(const Filename: String): Boolean;
function PathLastChar(const S: String): PChar;
function PathLastDelimiter(const Delimiters, S: string): Integer;
function PathLowercase(const S: String): String;
function PathNormalizeSlashes(S: String): String;
function PathPathPartLength(const Filename: String;
const IncludeSlashesAfterPath: Boolean): Integer;
function PathPos(const C: Char; const S: String;
const Offset: Integer = 1): Integer;
function PathSame(const S1, S2: String): Boolean;
function PathStartsWith(const S, AStartsWith: String;
const IgnoreCase: Boolean = True): Boolean;
function PathStrCompare(const S1: PChar; const S1Length: Integer;
const S2: PChar; const S2Length: Integer;
const IgnoreCase: Boolean = True): Integer;
function PathStrFind(const SSource: PChar; const SSourceLength: Integer;
const SValue: PChar; const SValueLength: Integer;
const IgnoreCase: Boolean = True): Integer;
function PathStrNextChar(const S: PChar): PChar;
function PathStrScan(const S: PChar; const C: Char): PChar;
function RemoveBackslash(const S: String): String;
function RemoveBackslashUnlessRoot(const S: String): String;
function ValidateAndCombinePath(const ADestDir, AFilename: String;
out AResultingPath: String): Boolean; overload;
function ValidateAndCombinePath(const ADestDir, AFilename: String): Boolean; overload;
implementation
{$ZEROBASEDSTRINGS OFF}
function AddBackslash(const S: String): String;
{ Returns S plus a trailing backslash, unless S is an empty string or already
ends in a backslash/slash. }
begin
if (S <> '') and not PathCharIsSlash(PathLastChar(S)^) then
Result := S + '\'
else
Result := S;
end;
function PathCharIsDriveLetter(const C: Char): Boolean;
begin
Result := CharInSet(C, ['A'..'Z', 'a'..'z']);
end;
function PathCharIsSlash(const C: Char): Boolean;
{ Returns True if C is a backslash or slash. }
begin
Result := (C = '\') or (C = '/');
end;
function PathChangeExt(const Filename, Extension: String): String;
{ Takes Filename, removes any existing extension, then adds the extension
specified by Extension and returns the resulting string. }
var
I: Integer;
begin
I := PathExtensionPos(Filename);
if I = 0 then
Result := Filename + Extension
else
Result := Copy(Filename, 1, I - 1) + Extension;
end;
function PathCombine(const Dir, Filename: String): String;
{ Combines a directory and filename into a path.
If Dir is empty, it just returns Filename.
If Filename is empty, it returns an empty string (ignoring Dir).
If Filename begins with a drive letter or slash, it returns Filename
(ignoring Dir).
If Dir specifies only a drive letter and colon ('c:'), it returns
Dir + Filename.
Otherwise, it returns the equivalent of AddBackslash(Dir) + Filename. }
begin
if (Dir = '') or (Filename = '') or PathIsRooted(Filename) then
Result := Filename
else begin
if ((Length(Dir) = 2) and not PathCharIsSlash(Dir[1]) and (Dir[2] = ':')) or
PathCharIsSlash(Dir[High(Dir)]) then
Result := Dir + Filename
else
Result := Dir + '\' + Filename;
end;
end;
function PathCompare(const S1, S2: String; const IgnoreCase: Boolean = True): Integer;
{ Compares two strings (typically filenames, but they don't have to be) and
returns 0 for "equal", <0 for "less than", or >0 for "greater than".
An ordinal comparison is used, ignoring case by default. }
begin
Result := PathStrCompare(PChar(S1), Length(S1), PChar(S2), Length(S2),
IgnoreCase);
end;
function PathComponentIsReservedName(const Filename: String): Boolean;
{ Returns True if the specified path component is one of the "reserved" device
names listed here:
https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
or CONIN$ or CONOUT$, which are also reserved.
Certain parts of the component are ignored when comparing against device
names, consistent with how GetFullPathName works on Windows 10 (22H2):
1. Dots/colons and all characters after them are removed.
Per docs: "NUL.txt and NUL.tar.gz are both equivalent to NUL."
Testing shows 'NUL:' and 'NUL:xxx' are also equivalent to NUL.
2. Any remaining trailing spaces are removed.
Testing shows 'NUL ', 'NUL .txt', and 'NUL :' are also equivalent to
NUL.
("equivalent to NUL" means "GetFullPathName returns \\.\NUL")
============================================================================
Different behavior on Windows 11 -- NOT IMPLEMENTED BY THIS FUNCTION:
On Windows 11's GetFullPathName, fewer parts of the component are ignored
when comparing against device names. From testing on 25H2, it appears that
the component is modified as follows:
1. If the last character is a colon, it is removed. (Just one.)
2. Any number of spaces/dots at the end are removed.
3. If the last character is a colon, it is removed. (Just one.)
4. Any number of spaces at the end are removed.
So these are all equivalent to NUL:
'NUL.'
'NUL::'
'NUL :'
'NUL . :'
'NUL : . :'
But these are not:
'NUL.txt'
'NUL:xxx'
'NUL:::'
'NUL : . : '
'NUL . : . :'
Another difference from Windows 10: with the sole exception of NUL, paths
with multiple components are not treated as devices.
'C:\PRN' is no longer equivalent to PRN. (Same for COM1, etc.)
'C:\NUL' is still equivalent to NUL.
}
const
Sup1 = #$00B9;
Sup2 = #$00B2;
Sup3 = #$00B3;
DeviceNames: array[0..5] of String =
('CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$');
begin
var NewLength := 0;
for var I := 1 to Length(Filename) do
case Filename[I] of
' ': ;
'.', ':': Break;
else
NewLength := I;
end;
case NewLength of
3, 6, 7:
begin
for var J := Low(DeviceNames) to High(DeviceNames) do
if (NewLength = Length(DeviceNames[J])) and
PathStartsWith(Filename, DeviceNames[J]) then
Exit(True);
end;
4: begin
if PathStartsWith(Filename, 'COM') or
PathStartsWith(Filename, 'LPT') then
case Filename[4] of
'1'..'9', Sup1, Sup2, Sup3: Exit(True);
end;
end;
end;
Result := False;
end;
function PathInternalConvertNormalToSuper(var Filename: String): Boolean;
{ For internal use. PathExpand must have already been called on Filename. }
begin
if (Length(Filename) >= 3) and not PathCharIsSlash(Filename[1]) and
(Filename[2] = ':') and (Filename[3] = '\') then begin
Insert('\\?\', Filename, 1);
Exit(True);
end;
if PathStartsWith(Filename, '\\') then begin
if PathStartsWith(Filename, '\\?\') then
Exit(True);
if PathStartsWith(Filename, '\\.\') then begin
Filename[3] := '?';
Exit(True);
end;
{ No validation is done on anything after '\\'. Even '\\' by itself is
"successfully" converted. This is consistent with Windows'
RtlDosPathNameToNtPathName_U function. }
Insert('?\UNC\', Filename, 3);
Exit(True);
end;
{ Shouldn't be possible to get here; PathExpand is only known to return
'X:\' and '\\' paths }
Result := False;
end;
function PathConvertNormalToSuper(const Filename: String;
out SuperFilename: String): Boolean;
{ Does not fail if the specified path already is an extended-length path. }
begin
var NewFilename: String;
if not PathExpand(Filename, NewFilename) then
Exit(False);
if not PathInternalConvertNormalToSuper(NewFilename) then
Exit(False);
SuperFilename := NewFilename;
Result := True;
end;
function PathConvertNormalToSuper(const Filename: String): String;
{ Does not fail if the specified path already is an extended-length path. }
begin
var NewFilename := PathExpand(Filename); { may raise exception }
if NewFilename <> '' then begin
{ There is no known case in which PathInternalConvertNormalToSuper
actually can return False when passed a non-empty path returned by
PathExpand. So it shouldn't be possible to see this exception. }
if not PathInternalConvertNormalToSuper(NewFilename) then
raise EPathFuncError.Create('PathConvertNormalToSuper: Unsupported syntax');
end;
Result := NewFilename;
end;
function PathConvertSuperToNormal(const Filename: String): String;
{ Attempts to convert a "\\?\"-prefixed path to normal form, and returns the
new path. If the path cannot be converted, then Filename is returned
unchanged.
Note that the main purpose of this function is to reverse the effect of a
previous call to PathConvertNormalToSuper. Paths obtained from other sources
are not guaranteed to be convertible. Paths are assumed to be well-formed;
if passed a path that is malformed in some way, the result may also be
malformed (garbage in, garbage out).
Reasons why a path may not be convertible include:
- The path doesn't start with "\\?\" (i.e., it's already in normal form)
- The prefix isn't followed by "x:" (where "x" is a non-slash character
specifying a drive) or "UNC\".
("\\?\GLOBALROOT\" isn't supported.)
- The path contains forward slashes or repeated backslashes (not counting
the leading "\\"). These are not permitted in super paths, so this
function does not make a special effort to support them. However, this
function may still convert such paths if the characters come after
"\\?\x:\" or "\\?\UNC\". But don't rely on that.
Examples of conversions:
\\?\C: -> C:\
\\?\C:\ -> C:\
\\?\C:\xxx -> C:\xxx
\\?\UNC\server\share -> \\server\share
}
begin
if PathStartsWith(Filename, '\\?\UNC\') then
Exit('\\' + Copy(Filename, 9, Maxint));
const Len = Length(Filename);
if (Len >= 6) and PathStartsWith(Filename, '\\?\') and
not PathCharIsSlash(Filename[5]) and
(Filename[6] = ':') then begin
{ "\\?\C:\" or "\\?\C:\xxx" }
if (Len >= 7) and (Filename[7] = '\') then
Exit(Copy(Filename, 5, Maxint));
{ "\\?\C:" -- in this case we need to append "\" so the result is "C:\" }
if Len = 6 then
Exit(Copy(Filename, 5, Maxint) + '\');
{ "\\?\C:xxx" -- not valid, can't convert }
end;
Result := Filename;
end;
function PathConvertSuperToNormal(const Filename: String;
out NormalFilename: String): Boolean;
{ Like the other overload, but returns False if the normal form can't be used
in place of Filename by code that doesn't support super paths: when Filename
is a super path that can't be converted, when the normal form is MAX_PATH or
longer, or when it doesn't convert back to Filename. The latter happens with
trailing dots or spaces and with reserved device names, which only super
paths can access because they skip Win32 path normalization.
If False is returned, NormalFilename is empty. }
begin
const NewNormalFilename = PathConvertSuperToNormal(Filename);
if PathStartsWith(NewNormalFilename, '\\?\') or
(Length(NewNormalFilename) >= MAX_PATH) then
Exit(False);
{ If Filename was already a normal path, there is nothing to check }
if NewNormalFilename <> Filename then begin
var SuperFilename: String;
if not PathConvertNormalToSuper(NewNormalFilename, SuperFilename) or
not PathSame(SuperFilename, Filename) then
Exit(False);
end;
NormalFilename := NewNormalFilename;
Result := True;
end;
function PathDrivePartLength(const Filename: String): Integer;
begin
Result := PathDrivePartLengthEx(Filename, False);
end;
function PathDrivePartLengthEx(const Filename: String;
const IncludeSignificantSlash: Boolean): Integer;
{ Returns length of the drive portion of Filename, or 0 if there is no drive
portion.
If IncludeSignificantSlash is True, the drive portion can include a trailing
slash if it is significant to the meaning of the path (i.e. 'x:' and 'x:\'
are not equivalent, nor are '\' and '').
If IncludeSignificantSlash is False, the function works as follows:
'x:file' -> 2 ('x:')
'x:\file' -> 2 ('x:')
'\\server\share\file' -> 14 ('\\server\share')
'\file' -> 0 ('')
If IncludeSignificantSlash is True, the function works as follows:
'x:file' -> 2 ('x:')
'x:\file' -> 3 ('x:\')
'\\server\share\file' -> 14 ('\\server\share')
'\file' -> 1 ('\')
}
var
Len, I: Integer;
begin
Len := Length(Filename);
{ Standard UNC path:
\\server\share
Super/device-namespace drives:
\\?\C:
\\.\C:
\\?\C:\ (trailing slash kept when IncludeSignificantSlash is True)
\\.\C:\
Super/device-namespace UNC paths (4 components):
\\?\UNC\server\share
\\.\UNC\server\share }
if (Len >= 2) and PathCharIsSlash(Filename[1]) and PathCharIsSlash(Filename[2]) then begin
{ For consistency with the behavior of Windows' GetFullPathName function,
we don't collapse 3 leading slashes into 2. Instead, a leading "\\\" is
treated like "\\<empty computer name>\".
PathNormalizeSlashes works the same way. }
var FirstComponentIsNamespace := False;
var SecondComponentIsDrive := False;
var MaxComponents := 2;
var CurComponent := 0;
var ComponentStartIndex := 3;
I := ComponentStartIndex;
while I <= Len do begin
if PathCharIsSlash(Filename[I]) then begin
const ComponentLen = I - ComponentStartIndex;
case CurComponent of
0: begin
if (ComponentLen = 1) and
CharInSet(Filename[ComponentStartIndex], ['?', '.']) then
FirstComponentIsNamespace := True;
end;
1: if FirstComponentIsNamespace then begin
if ComponentLen = 2 then begin
if Filename[ComponentStartIndex+1] = ':' then
SecondComponentIsDrive := True;
end
else if ComponentLen = 3 then begin
if PathHasSubstringAt(Filename, 'UNC', ComponentStartIndex - Low(Filename)) then
Inc(MaxComponents, 2);
end;
end;
end;
Inc(CurComponent);
if CurComponent >= MaxComponents then begin
if SecondComponentIsDrive and IncludeSignificantSlash then
Inc(I);
Break;
end;
repeat
Inc(I);
{ And skip any additional consecutive slashes: }
until (I > Len) or not PathCharIsSlash(Filename[I]);
ComponentStartIndex := I;
end
else
Inc(I);
end;
Result := I - 1;
Exit;
end;
{ \ }
{ Note: Test this before 'x:' since '\:stream' means access stream 'stream'
on the root directory of the current drive, not access drive '\:' }
if (Len >= 1) and PathCharIsSlash(Filename[1]) then begin
if IncludeSignificantSlash then
Result := 1
else
Result := 0;
Exit;
end;
{ x: }
if (Len >= 2) and (Filename[2] = ':') then begin
{ We intentionally omit an A-Z check here because Windows doesn't have
one. For example, you can define a drive '@:' using DefineDosDevice, and
then successfully pass '@:\file' to APIs like GetFileAttributes. }
if IncludeSignificantSlash and (Len >= 3) and PathCharIsSlash(Filename[3]) then
Result := 3
else
Result := 2;
Exit;
end;
Result := 0;
end;
function PathIsRooted(const Filename: String): Boolean;
{ Returns True if Filename begins with a slash or drive ('x:').
Equivalent to: PathDrivePartLengthEx(Filename, True) <> 0 }
begin
const Len = Length(Filename);
Result :=
((Len >= 1) and PathCharIsSlash(Filename[1])) or
((Len >= 2) and (Filename[2] = ':'));
end;
function PathPathPartLength(const Filename: String;
const IncludeSlashesAfterPath: Boolean): Integer;
{ Returns length of the path portion of Filename, or 0 if there is no path
portion.
Note these differences from Delphi's ExtractFilePath function:
- The result will never be less than what PathDrivePartLength returns.
If you pass a UNC root path, e.g. '\\server\share', it will return the
length of the entire string, NOT the length of '\\server\'.
- If you pass in a filename with a reference to an NTFS alternate data
stream, e.g. 'abc:def', it will return 0, NOT the length of 'abc:'. }
begin
const DrivePartLen = PathDrivePartLengthEx(Filename, True);
var FoundSlash := False;
Result := Length(Filename);
while Result > DrivePartLen do begin
if PathCharIsSlash(Filename[Result]) then begin
if IncludeSlashesAfterPath then
Break;
FoundSlash := True;
end else begin
if FoundSlash then
Break;
end;
Dec(Result);
end;
end;
function PathEndsWith(const S, AEndsWith: String;
const IgnoreCase: Boolean = True): Boolean;
{ Returns True if S ends with (or is equal to) AEndsWith.
An ordinal comparison is used, ignoring case by default. }
begin
Result := PathHasSubstringAt(S, AEndsWith, Length(S) - Length(AEndsWith),
IgnoreCase);
end;
function PathIsEmptyOrOnlySpaces(const S: String): Boolean;
{ Internally used by the PathExpand functions. }
begin
for var I := Low(S) to High(S) do
if S[I] <> ' ' then
Exit(False);
Result := True;
end;
function PathExpand(const Filename: String; out ExpandedFilename: String): Boolean;
{ This is a wrapper around Windows' GetFullPathName function, which takes a
possibly relative path and returns a fully qualified path. Other changes,
not documented but believed to be consistent across Windows versions, are
made as well:
- Forward slashes are changed to backslashes
- Repeated slashes are collapsed into one, except for a leading '\\'.
(But there's a quirk: see comments in PathNormalizeSlashes.)
- Unless the last (or only) component is '.' or '..' exactly, any number of
dots and spaces at the end of the path are removed. Also, a single dot at
the end of preceding components may be removed.
(See comments in PathHasInvalidCharacters for details.)
- Paths with certain device names as the only component, or in some cases
as the last component, are changed to '\\.\<device name>', except when the
path has the '\\?\' prefix.
For example, if the last component is 'NUL', the whole path is changed to
'\\.\NUL'.
- '\\.' is changed to '\\.\' and '\\?' is changed to '\\?\'
(but '\\X' is *not* changed to '\\X\')
Returns True if successful, or False on failure.
Failure is known to occur in these cases (there could be more):
- Filename is an empty string or contains only spaces
- Filename or the resulting path exceeds 32K characters
Super paths are supposed to be in canonical form already, absolute with no
forward slashes or repeated backslashes. Although they can be passed to
GetFullPathName anyway, there's a downside: GetFullPathName removes all
trailing dots and spaces from the path. Files should never be *created* with
trailing dots or spaces (because they can only be accessed with super
paths), but removing them may interfere with opening or deleting such
files. }
var
Buf: array[0..$7FFF] of Char;
begin
{ Length limits observed on Windows 11 25H2:
- GetFullPathName fails with ERROR_FILENAME_EXCED_RANGE [sic] if lpFileName
is more than $7FFE characters long (not counting null terminator).
- GetFullPathName fails with ERROR_INVALID_NAME if the resulting path
would be more than $7FFE characters long (not counting null terminator),
even if the buffer is much larger than that. }
{ GetFullPathName fails if passed an empty string or a string with only
spaces. Just in case that behavior were to change in the future, we avoid
relying on it and do our own check for these cases here.
(GetFullPathName does not fail if passed invalid dots like '...' or dots
and spaces like '.. '; the result is as if '.\' was passed.) }
if PathIsEmptyOrOnlySpaces(Filename) then
Exit(False);
var FilePart: PChar;
const Res = GetFullPathName(PChar(Filename), SizeOf(Buf) div SizeOf(Buf[0]),
Buf, FilePart);
Result := (Res > 0) and (Res < SizeOf(Buf) div SizeOf(Buf[0]));
if Result then begin
SetString(ExpandedFilename, Buf, Res);
{ Memory usage optimization: Most of the time, no changes are made to the
path. When that is the case, return a reference to the passed-in string
so that there aren't two identical strings on the heap. }
if ExpandedFilename = Filename then
ExpandedFilename := Filename;
end;
end;
function PathExpand(const Filename: String): String;
{ Like the other PathExpand overload, but handles failures internally by
either returning an empty string (when Filename is empty or only spaces) or
raising an exception (currently the only known case is when Filename or the
resulting path exceeds 32K characters). }
begin
{ GetFullPathName fails if passed an empty string or a string with only
spaces. For backward compatibility with callers that may not be expecting
an exception in these cases, we handle both by returning an empty string
instead of raising an exception.
Delphi's ExpandFileName returns an empty string for any failure.
Prior to IS 7, PathExpand returned the original Filename for any failure. }
if PathIsEmptyOrOnlySpaces(Filename) then
Exit('');
if not PathExpand(Filename, Result) then
raise EPathFuncError.CreateFmt('PathExpand: GetFullPathName failed (length: %d)',
[Length(Filename)]);
end;
function PathExtensionPos(const Filename: String): Integer;
{ Returns index of the last '.' character in the filename portion of Filename,
or 0 if there is no '.' in the filename portion.
Note: Filename is assumed to NOT include an NTFS alternate data stream name
(i.e. 'filename:stream'). }
begin
const NamePartStartIndex = PathPathPartLength(Filename, True) + 1;
for var I := Length(Filename) downto NamePartStartIndex do
if Filename[I] = '.' then
Exit(I);
Result := 0;
end;
function PathExtractDir(const Filename: String): String;
{ Like PathExtractPath, but strips any trailing slashes, unless the resulting
path is the root directory of a drive (i.e. 'C:\' or '\'). }
var
I: Integer;
begin
I := PathPathPartLength(Filename, False);
Result := Copy(Filename, 1, I);
end;
function PathExtractDrive(const Filename: String): String;
{ Returns the drive portion of Filename (either 'x:' or '\\server\share'),
or an empty string if there is no drive portion. }
var
L: Integer;
begin
L := PathDrivePartLength(Filename);
if L = 0 then
Result := ''
else
Result := Copy(Filename, 1, L);
end;
function PathExtractExt(const Filename: String): String;
{ Returns the extension portion of the last component of Filename (e.g. '.txt')
or an empty string if there is no extension. }
var
I: Integer;
begin
I := PathExtensionPos(Filename);
if I = 0 then
Result := ''
else
Result := Copy(Filename, I, Maxint);
end;
function PathExtractName(const Filename: String): String;
{ Returns the filename portion of Filename (e.g. 'filename.txt'). If Filename
ends in a slash or consists only of a drive part or is empty, the result will
be an empty string.
This function is essentially the opposite of PathExtractPath. }
var
I: Integer;
begin
I := PathPathPartLength(Filename, True);
Result := Copy(Filename, I + 1, Maxint);
end;
function PathExtractPath(const Filename: String): String;
{ Returns the path portion of Filename (e.g. 'c:\dir\'). If Filename contains
no drive part or slash, the result will be an empty string.
This function is essentially the opposite of PathExtractName. }
var
I: Integer;
begin
I := PathPathPartLength(Filename, True);
Result := Copy(Filename, 1, I);
end;
function PathHasInvalidCharacters(const S: String;
const AllowDriveLetterColon: Boolean): Boolean;
{ Checks the specified path for characters that are never allowed in paths,
or characters and path components that are accepted by the system but might
present a security problem (such as '..' and sometimes ':').
Specifically, True is returned if S includes any of the following:
- Control characters (0-31)
- One of these characters: /*?"<>|
(This means forward slashes and the prefixes '\\?\' and '\??\' are never
allowed.)
- Colons (':'), except when AllowDriveLetterColon=True and the string's
first character is a letter and the second character is the only colon.
(This blocks NTFS alternate data stream names.)
- A component with a trailing dot or space
Due to the last rule above, '.' and '..' components are never allowed, nor
are components like these:
'file '
'file.'
'file. . .'
'file . . '
When expanding paths (with no '\\?\' prefix used), Windows 11 23H2 silently
removes all trailing dots and spaces from the end of the string. Therefore,
if used at the end of a path, all of the above cases yield just 'file'.
On preceding components of the path, nothing is done with spaces; if there
is exactly one dot at the end, it is removed (e.g., 'dir.\file' becomes
'dir\file'), while multiple dots are left untouched ('dir..\file' doesn't
change).
By rejecting trailing dots and spaces up front, we avoid all that weirdness
and the problems that could arise from it.
Since ':' is considered invalid (except in the one case noted above), it's
not possible to sneak in disallowed dots/spaces by including an NTFS
alternate data stream name. The function will return True in these cases:
'..:streamname'
'file :streamname'
}
begin
Result := True;
for var I := Low(S) to High(S) do begin
var C := S[I];
if Ord(C) < 32 then
Exit;
case C of
#32, '.':
begin
if (I = High(S)) or PathCharIsSlash(S[I+1]) then
Exit;
end;
':':
begin
{ The A-Z check ensures that '.:streamname', ' :streamname', and
'\:streamname' are disallowed. }
if not AllowDriveLetterColon or (I <> Low(S)+1) or
not PathCharIsDriveLetter(S[Low(S)]) then
Exit;
end;
'/', '*', '?', '"', '<', '>', '|': Exit;
end;
end;
Result := False;
end;
function PathHasSubstringAt(const S, Substring: String; const Offset: Integer;
const IgnoreCase: Boolean = True): Boolean;
{ Returns True if Substring exists in S at the specified zero-based offset
from the beginning of S.
An ordinal comparison is used, ignoring case by default.
Passing an out-of-range Offset value is allowed/safe. False is returned if
Offset is negative or if checking for Substring at Offset would go beyond
the end of S (partially or fully).
If Substring is empty and Offset = Length(S), then True is returned because
that is not considered going *beyond* the end of S. }
begin
if Offset < 0 then
Exit(False);
const SubstringLen = Length(Substring);
if Offset > Length(S) - SubstringLen then
Exit(False);
Result := (PathStrCompare(PChar(S) + Offset, SubstringLen, PChar(Substring),
SubstringLen, IgnoreCase) = 0);
end;
function PathLastChar(const S: String): PChar;
{ Returns pointer to last character in the string. Returns nil if the string is
empty. }
begin
if S = '' then
Result := nil
else
Result := @S[High(S)];
end;
function PathLastDelimiter(const Delimiters, S: string): Integer;
{ Returns the index of the last occurrence in S of one of the characters in
Delimiters, or 0 if none were found.
Both strings are allowed to contain #0 characters; they are treated the same
as any other character. (Delphi's LastDelimiter function doesn't allow #0
in Delimiters.) }
begin
for var I := Length(S) downto 1 do
if PathPos(S[I], Delimiters) <> 0 then
Exit(I);
Result := 0;
end;
function PathLowercase(const S: String): String;
{ Converts the specified path name to lowercase }
begin
Result := AnsiLowerCase(S);
end;
function PathPos(const C: Char; const S: String;
const Offset: Integer = 1): Integer;
{ Like Delphi's Pos function, but searches for a single character instead of a
string, making it somewhat faster.
Returns 1-based index of the first occurrence of C in S, or 0 if not found.
The optional Offset parameter (1-based) specifies where the search should
start. If Offset is less than 1, then 0 is returned (same as Delphi's Pos
function). }
begin
if Offset >= 1 then
for var I := Offset to Length(S) do
if S[I] = C then
Exit(I);
Result := 0;
end;
function PathNormalizeSlashes(S: String): String;
{ Returns S minus any superfluous slashes, and with any forward slashes
converted to backslashes. For example, if S is 'C:\\\some//path', it returns
'C:\some\path'.
If the string starts with two slashes ('\\') then those two characters are
ignored when collapsing repeated slashes. So:
\\server\share -> \\server\share (unchanged)
\\\server\share -> \\\server\share (unchanged)
\\\\server\share -> \\\server\share (one backslash removed)
Note that paths with 3+ leading slashes don't actually work. But Windows'
GetFullPathName function, used by PathExpand, collapses slashes the same
way. Best to be consistent. }
begin
const Len = Length(S);
var I: Integer;
for I := 1 to Len do
if S[I] = '/' then
S[I] := '\';
var EndIndex := 2;
if (Len >= 2) and (S[1] = '\') and (S[2] = '\') then
Inc(EndIndex, 2);
for I := Len downto EndIndex do
if (S[I] = '\') and (S[I-1] = '\') then
Delete(S, I, 1);
Result := S;
end;
function PathSame(const S1, S2: String): Boolean;
{ Returns True if the specified strings (typically filenames) are equal.
An ordinal comparison is used, ignoring case.
Like PathCompare, but faster for checking equality as it returns False
immediately if the strings are different lengths. }
begin
Result := (Length(S1) = Length(S2)) and (PathCompare(S1, S2) = 0);
end;
function PathStartsWith(const S, AStartsWith: String;
const IgnoreCase: Boolean = True): Boolean;
{ Returns True if S starts with (or is equal to) AStartsWith.
An ordinal comparison is used, ignoring case by default. }
begin
Result := PathHasSubstringAt(S, AStartsWith, 0, IgnoreCase);
end;
{ Use our own CompareStringOrdinal declaration. The one in the Windows unit is
"delayload" (yuck), and the bIgnoreCase parameter type differs between
Delphi 11 and 12 (BOOL vs. DWORD). }
function CompareStringOrdinal_static(lpString1: LPCWSTR; cchCount1: Integer;
lpString2: LPCWSTR; cchCount2: Integer; bIgnoreCase: BOOL): Integer; stdcall;
external kernel32 name 'CompareStringOrdinal';
function PathStrCompare(const S1: PChar; const S1Length: Integer;
const S2: PChar; const S2Length: Integer;
const IgnoreCase: Boolean = True): Integer;
{ Compares two strings and returns 0 for "equal", <0 for "less than", or
>0 for "greater than".
An ordinal comparison is used, ignoring case by default.
A length of -1 may be passed if a string is null-terminated; in that case,
the length is determined automatically. }
begin
{ As documented, CompareStringOrdinal only allows 1 for TRUE in the
bIgnoreCase parameter. "BOOL(Byte(IgnoreCase))" ensures we pass 1, not the
usual -1 Delphi passes when a Boolean is implicitly converted to BOOL. }
const CompareResult = CompareStringOrdinal_static(S1, S1Length, S2, S2Length,
BOOL(Byte(IgnoreCase)));
case CompareResult of
0: raise EPathFuncError.CreateFmt('PathStrCompare: CompareStringOrdinal failed (%u)',
[GetLastError]);
1..3: ;
else
raise EPathFuncError.CreateFmt('PathStrCompare: CompareStringOrdinal result invalid (%d)',
[CompareResult]);
end;
Result := CompareResult - 2;
end;
{ Use our own FindStringOrdinal declaration. The one in the Windows unit is
"delayload" (yuck). }
function FindStringOrdinal_static(dwFindStringOrdinalFlags: DWORD;
lpStringSource: LPCWSTR; cchSource: Integer;
lpStringValue: LPCWSTR; cchValue: Integer; bIgnoreCase: BOOL): Integer; stdcall;
external kernel32 name 'FindStringOrdinal';
function PathStrFind(const SSource: PChar; const SSourceLength: Integer;
const SValue: PChar; const SValueLength: Integer;
const IgnoreCase: Boolean = True): Integer;
{ Locates a value in a string, starting with the first character of the string.
Returns a 0-based index if found, and -1 otherwise.
An ordinal comparison is used, ignoring case by default.
A length of -1 may be passed if a string is null-terminated; in that case,
the length is determined automatically. }
begin
{ This is not documented for FindStringOrdinal, but like CompareStringOrdinal
it only allows 1 for TRUE in the bIgnoreCase parameter. See above. }
const CompareResult = FindStringOrdinal_static(FIND_FROMSTART, SSource, SSourceLength,
SValue, SValueLength, BOOL(Byte(IgnoreCase)));
if CompareResult = -1 then begin
const LastError = GetLastError;
if LastError <> ERROR_SUCCESS then
raise EPathFuncError.CreateFmt('PathStrFind: FindStringOrdinal failed (%u)',
[LastError]);
end else if not ((CompareResult >= 0) and ((SSourceLength = -1) or (CompareResult < SSourceLength))) then
raise EPathFuncError.CreateFmt('PathStrFind: FindStringOrdinal result invalid (%d)',
[CompareResult]);
Result := CompareResult;
end;
function PathStrNextChar(const S: PChar): PChar;
{ Returns pointer to the character after S, unless S points to a null (#0). }
begin
Result := S;
if Result^ <> #0 then
Inc(Result);
end;
function PathStrScan(const S: PChar; const C: Char): PChar;
{ Returns pointer to first occurrence of C in S, or nil if there are no
occurrences. As with StrScan, specifying #0 for the search character is legal. }
begin
Result := S;
while Result^ <> C do begin
if Result^ = #0 then begin
Result := nil;
Break;
end;
Result := PathStrNextChar(Result);
end;
end;
function RemoveBackslash(const S: String): String;
{ Returns S minus any trailing slashes. Use of this function is discouraged;
use RemoveBackslashUnlessRoot instead when working with file system paths. }
var
I: Integer;
begin
I := Length(S);
while (I > 0) and PathCharIsSlash(S[I]) do
Dec(I);
if I = Length(S) then
Result := S
else
Result := Copy(S, 1, I);
end;
function RemoveBackslashUnlessRoot(const S: String): String;
{ Returns S minus any trailing slashes, unless S specifies the root directory
of a drive (i.e. 'C:\' or '\'), in which case it leaves 1 slash. }
var
DrivePartLen, I: Integer;
begin
DrivePartLen := PathDrivePartLengthEx(S, True);
I := Length(S);
while (I > DrivePartLen) and PathCharIsSlash(S[I]) do
Dec(I);
if I = Length(S) then
Result := S
else
Result := Copy(S, 1, I);
end;
function ValidateAndCombinePath(const ADestDir, AFilename: String;
out AResultingPath: String): Boolean;
{ Combines ADestDir and AFilename without allowing a result outside of
ADestDir and without allowing other security problems.
Returns True if all security checks pass, with the combination of ADestDir
and AFilename in AResultingPath.
ADestDir is assumed to be normalized already and have a trailing backslash.
AFilename may be a file or directory name. }
function IsAnyComponentReservedName(S: String): Boolean;
begin
{ GetFullPathName doesn't treat 'NUL\file.txt' as a device name, but the
caller might access 'NUL' if it tries to create parent directories. So