forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnt.cs
More file actions
2338 lines (1916 loc) · 104 KB
/
nt.cs
File metadata and controls
2338 lines (1916 loc) · 104 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using NotNullWhenAttribute = System.Diagnostics.CodeAnalysis.NotNullWhenAttribute;
using NotNullAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute;
#if FEATURE_PIPES
using System.IO.Pipes;
#endif
[assembly: PythonModule("nt", typeof(IronPython.Modules.PythonNT))]
namespace IronPython.Modules {
public static class PythonNT {
public const string __doc__ = "Provides low-level operating system access for files, the environment, etc...";
/* TODO: missing functions/classes:
* Windows:
* {'execve', '_isdir', 'getlogin', 'get_inheritable', 'statvfs_result', 'readlink', 'stat_float_times', 'getppid',
* '_getdiskusage', 'execv', 'set_inheritable', 'device_encoding', 'isatty', '_getvolumepathname',
* 'times_result', 'cpu_count', 'get_handle_inheritable', 'set_handle_inheritable'}
*/
#if FEATURE_PROCESS
private static readonly Dictionary<int, Process> _processToIdMapping = new Dictionary<int, Process>();
private static readonly List<int> _freeProcessIds = new List<int>();
private static int _processCount;
#endif
private static readonly object _keyFields = new object();
private static readonly string _keyHaveFunctions = "_have_functions";
private static readonly Encoding _utf8Encoding;
private static readonly Encoding _mbcsEncoding;
static PythonNT() {
// TODO: Python 3.6: use sys.getfilesystemencodeerrors()
_mbcsEncoding = Encoding.GetEncoding(0); // on errors does diacritics stripping if possible else replace
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
_utf8Encoding = new PythonSurrogatePassEncoding(Encoding.UTF8);
} else {
// TODO: Verify: CPython uses surrogateescape, but .NET will handle using replace
// so paths produced as output will never have surrogates, but have errors replaced by U+FFFD
// and paths provided as input will have any surrogates replaced by U+FFFD or ?
// Using surrogateescape here properly validates bytes input but does not guarantee safe roundtrip
_utf8Encoding = new PythonSurrogateEscapeEncoding(Encoding.UTF8);
}
}
[SpecialName]
public static void PerformModuleReload([NotNone] PythonContext context, [NotNone] PythonDictionary dict) {
var have_functions = new PythonList();
if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
have_functions.Add("MS_WINDOWS");
}
context.GetOrCreateModuleState(_keyFields, () => {
dict.Add(_keyHaveFunctions, have_functions);
return dict;
});
}
#region Public API Surface
[PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static PythonTuple _getdiskusage([NotNone] string path) {
var driveInfo = new DriveInfo(path);
return PythonTuple.MakeTuple((BigInteger)driveInfo.TotalSize, (BigInteger)driveInfo.AvailableFreeSpace);
}
[DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetFinalPathNameByHandle([In] SafeFileHandle hFile, [Out] StringBuilder lpszFilePath, [In] int cchFilePath, [In] int dwFlags);
[SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static string _getfinalpathname([NotNone] string path) {
var hFile = CreateFile(path, 0, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
if (hFile.IsInvalid) {
throw GetLastWin32Error(path);
}
const int MAX_PATH_LEN = 10000;
StringBuilder sb = new StringBuilder(MAX_PATH_LEN);
if (GetFinalPathNameByHandle(hFile, sb, MAX_PATH_LEN, 0) == 0) {
throw GetLastWin32Error(path);
}
return sb.ToString();
}
public static string _getfullpathname(CodeContext/*!*/ context, [NotNone] string/*!*/ path) {
PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform;
try {
return pal.GetFullPath(path);
} catch (ArgumentException) {
// .NET validates the path, CPython doesn't... so we replace invalid chars with
// Char.Maxvalue, get the full path, and then replace the Char.Maxvalue's back w/
// their original value.
string newdir = path;
if (IsWindows()) {
if (newdir.Length >= 2 && newdir[1] == ':' &&
(newdir[0] < 'a' || newdir[0] > 'z') && (newdir[0] < 'A' || newdir[0] > 'Z')) {
// invalid drive, .NET will reject this
if (newdir.Length == 2) {
return newdir + Path.DirectorySeparatorChar;
} else if (newdir[2] == Path.DirectorySeparatorChar) {
return newdir;
} else {
return newdir.Substring(0, 2) + Path.DirectorySeparatorChar + newdir.Substring(2);
}
}
if (newdir.Length > 2 && newdir.IndexOf(':', 2) != -1) {
// : is an invalid char if it's not in the 2nd position
newdir = newdir.Substring(0, 2) + newdir.Substring(2).Replace(':', Char.MaxValue);
}
if (newdir.Length > 0 && newdir[0] == ':') {
newdir = Char.MaxValue + newdir.Substring(1);
}
}
foreach (char c in Path.GetInvalidPathChars()) {
newdir = newdir.Replace(c, Char.MaxValue);
}
#if NETCOREAPP || NETSTANDARD
foreach (char c in invalidPathChars) {
newdir = newdir.Replace(c, Char.MaxValue);
}
#endif
foreach (char c in Path.GetInvalidFileNameChars()) {
// don't replace the volume or directory separators
if (c == Path.VolumeSeparatorChar || c == Path.DirectorySeparatorChar) continue;
newdir = newdir.Replace(c, Char.MaxValue);
}
// walk backwards through the path replacing the same characters. We should have
// only updated the directory leaving the filename which we're fixing.
string res = pal.GetFullPath(newdir);
int curDir = path.Length;
for (int curRes = res.Length - 1; curRes >= 0; curRes--) {
if (res[curRes] == Char.MaxValue) {
for (curDir--; curDir >= 0; curDir--) {
if (newdir[curDir] == Char.MaxValue) {
res = res.Substring(0, curRes) + path[curDir] + res.Substring(curRes + 1);
break;
}
}
}
}
return res;
}
static bool IsWindows() {
return Environment.OSVersion.Platform == PlatformID.Win32NT ||
Environment.OSVersion.Platform == PlatformID.Win32S ||
Environment.OSVersion.Platform == PlatformID.Win32Windows;
}
}
public static Bytes _getfullpathname(CodeContext/*!*/ context, [NotNone] Bytes path)
=> _getfullpathname(context, path.ToFsString(context)).ToFsBytes(context);
public static Bytes _getfullpathname(CodeContext/*!*/ context, object? path)
=> _getfullpathname(context, ConvertToFsString(context, path, nameof(path))).ToFsBytes(context);
#if FEATURE_PROCESS
public static void abort() {
System.Environment.FailFast("IronPython os.abort");
}
#endif
/// <summary>
/// Checks for the specific permissions, provided by the mode parameter, are available for the provided path. Permissions can be:
///
/// F_OK: Check to see if the file exists
/// R_OK | W_OK | X_OK: Check for the specific permissions. Only W_OK is respected.
/// </summary>
[Documentation("access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)")]
public static bool access(CodeContext/*!*/ context, [NotNone] string path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
if (path == null) throw PythonOps.TypeError("expected string, got None");
foreach (var pair in kwargs) {
switch (pair.Key) {
case "dir_fd":
case "follow_symlinks":
// TODO: implement these!
break;
case "effective_ids":
if (PythonOps.IsTrue(pair.Value))
throw PythonOps.NotImplementedError("access: effective_ids unavailable on this platform");
break;
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", pair.Key);
}
}
#if FEATURE_FILESYSTEM
try {
FileAttributes fa = File.GetAttributes(path);
if (mode == F_OK) {
return true;
}
// match the behavior of the VC C Runtime
if ((fa & FileAttributes.Directory) != 0) {
// directories have read & write access
return true;
}
if ((fa & FileAttributes.ReadOnly) != 0 && (mode & W_OK) != 0) {
// want to write but file is read-only
return false;
}
return true;
} catch (ArgumentException) {
} catch (PathTooLongException) {
} catch (NotSupportedException) {
} catch (FileNotFoundException) {
} catch (DirectoryNotFoundException) {
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
return false;
#else
throw new NotImplementedException();
#endif
}
[Documentation("")]
public static bool access(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> access(context, path.ToFsString(context), mode, kwargs);
[Documentation("")]
public static bool access(CodeContext context, object? path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> access(context, ConvertToFsString(context, path, nameof(path)), mode, kwargs);
#if FEATURE_FILESYSTEM
public static void chdir([NotNone] string path) {
if (String.IsNullOrEmpty(path)) {
throw PythonOps.OSError(PythonExceptions._OSError.ERROR_INVALID_NAME, "Path cannot be an empty string", path, PythonExceptions._OSError.ERROR_INVALID_NAME);
}
try {
Directory.SetCurrentDirectory(path);
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
public static void chdir(CodeContext context, [NotNone] Bytes path)
=> chdir(path.ToFsString(context));
public static void chdir(CodeContext context, object? path)
=> chdir(ConvertToFsString(context, path, nameof(path)));
// Isolate Mono.Unix from the rest of the method so that we don't try to load the Mono.Unix assembly on Windows.
private static void chmodUnix(string path, int mode) {
if (Mono.Unix.Native.Syscall.chmod(path, Mono.Unix.Native.NativeConvert.ToFilePermissions((uint)mode)) == 0) return;
throw GetLastUnixError(path);
}
[Documentation("chmod(path, mode, *, dir_fd=None, follow_symlinks=True)")]
public static void chmod([NotNone] string path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
foreach (var key in kwargs.Keys) {
switch (key) {
case "dir_fd":
case "follow_symlinks":
// TODO: implement these!
break;
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", key);
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
try {
FileInfo fi = new FileInfo(path);
if ((mode & S_IWRITE) != 0) {
fi.Attributes &= ~(FileAttributes.ReadOnly);
} else {
fi.Attributes |= FileAttributes.ReadOnly;
}
} catch (Exception e) {
throw ToPythonException(e, path);
}
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
chmodUnix(path, mode);
} else {
throw new PlatformNotSupportedException();
}
}
[Documentation("")]
public static void chmod(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> chmod(path.ToFsString(context), mode, kwargs);
[Documentation("")]
public static void chmod(CodeContext context, object? path, int mode, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> chmod(ConvertToFsString(context, path, nameof(path)), mode, kwargs);
#endif
public static void close(CodeContext/*!*/ context, int fd) {
PythonFileManager fileManager = context.LanguageContext.FileManager;
StreamBox streams = fileManager.GetStreams(fd);
streams.CloseStreams(fileManager);
}
public static void closerange(CodeContext/*!*/ context, int fd_low, int fd_high) {
for (var fd = fd_low; fd <= fd_high; fd++) {
try {
close(context, fd);
} catch (OSException) {
// ignore errors on close
}
}
}
public static int dup(CodeContext/*!*/ context, int fd) {
PythonFileManager fileManager = context.LanguageContext.FileManager;
StreamBox streams = fileManager.GetStreams(fd); // OSError if fd not valid
fileManager.EnsureRefStreams(streams);
fileManager.AddRefStreams(streams);
return fileManager.Add(new(streams));
}
public static int dup2(CodeContext/*!*/ context, int fd, int fd2) {
PythonFileManager fileManager = context.LanguageContext.FileManager;
StreamBox streams = fileManager.GetStreams(fd); // OSError if fd not valid
if (fd == fd2) {
return fd2;
}
if (!fileManager.ValidateFdRange(fd2)) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
if (fileManager.TryGetStreams(fd2, out _)) {
close(context, fd2);
}
// TODO: race condition: `open` or `dup` on another thread may occupy fd2
fileManager.EnsureRefStreams(streams);
fileManager.AddRefStreams(streams);
return fileManager.Add(fd2, new(streams));
}
#if FEATURE_PROCESS
/// <summary>
/// single instance of environment dictionary is shared between multiple runtimes because the environment
/// is shared by multiple runtimes.
/// </summary>
public static readonly object environ = new PythonDictionary(new EnvironmentDictionaryStorage());
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType error = Builtin.OSError;
public static void _exit(CodeContext/*!*/ context, int status) {
context.LanguageContext.DomainManager.Platform.TerminateScriptExecution(status);
}
public static object fspath(CodeContext context, [AllowNull] object path)
=> PythonOps.FsPath(path);
[LightThrowing]
public static object fstat(CodeContext/*!*/ context, int fd) {
PythonFileManager fileManager = context.LanguageContext.FileManager;
if (fileManager.TryGetStreams(fd, out StreamBox? streams)) {
if (streams.IsConsoleStream()) return new stat_result(0x2000);
if (streams.IsStandardIOStream()) return new stat_result(0x1000);
if (StatStream(streams.ReadStream) is not null and var res) return res;
}
return LightExceptions.Throw(PythonOps.OSError(9, "Bad file descriptor"));
static object? StatStream(Stream stream) {
if (stream is FileStream fs) return lstat(fs.Name, new Dictionary<string, object>(1));
#if FEATURE_PIPES
if (stream is PipeStream) return new stat_result(0x1000);
#endif
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
if (ReferenceEquals(stream, Stream.Null)) return new stat_result(0x2000);
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
if (IsUnixStream(stream)) return new stat_result(0x1000);
}
return null;
}
static bool IsUnixStream(Stream stream) {
return stream is Mono.Unix.UnixStream;
}
}
public static void fsync(CodeContext context, int fd) {
PythonFileManager fileManager = context.LanguageContext.FileManager;
StreamBox streams = fileManager.GetStreams(fd);
try {
streams.Flush();
} catch (IOException) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
}
public static string getcwd(CodeContext/*!*/ context) {
return context.LanguageContext.DomainManager.Platform.CurrentDirectory;
}
public static Bytes getcwdb(CodeContext/*!*/ context)
=> getcwd(context).ToFsBytes(context);
#if NETCOREAPP || NETSTANDARD
private static readonly char[] invalidPathChars = new char[] { '\"', '<', '>' };
#endif
#if FEATURE_PROCESS
public static int getpid() {
return System.Diagnostics.Process.GetCurrentProcess().Id;
}
#endif
[Documentation("link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)")]
public static void link([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
foreach (var key in kwargs.Keys) {
switch (key) {
case "src_dir_fd":
case "dst_dir_fd":
case "follow_symlinks":
// TODO: implement these!
break;
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", key);
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
linkWindows(src, dst);
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
linkUnix(src, dst);
} else {
throw new NotImplementedException();
}
static void linkWindows(string src, string dst) {
if (!CreateHardLink(dst, src, IntPtr.Zero))
throw GetLastWin32Error(src, dst);
}
static void linkUnix(string src, string dst) {
if (Mono.Unix.Native.Syscall.link(src, dst) == 0) return;
throw GetLastUnixError(src, dst);
}
}
public static bool isatty(CodeContext context, int fd) {
if (context.LanguageContext.FileManager.TryGetStreams(fd, out var streams))
return streams.IsConsoleStream();
return false;
}
[Documentation("")]
public static void link(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> link(src.ToFsString(context), dst.ToFsString(context), kwargs);
[Documentation("")]
public static void link(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> link(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs);
[DllImport("kernel32.dll", EntryPoint = "CreateHardLinkW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
public static PythonList listdir(CodeContext/*!*/ context, string? path = null) {
if (path == null) {
path = getcwd(context);
}
if (path == string.Empty) {
throw PythonOps.OSError(PythonExceptions._OSError.ERROR_PATH_NOT_FOUND, "The system cannot find the path specified", path, PythonExceptions._OSError.ERROR_PATH_NOT_FOUND);
}
#if !NETFRAMEWORK
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
// .NET Core throws an unhelpful "The parameter is incorrect" error when trying to listdir a file
if (File.Exists(path)) {
throw GetWin32Error(PythonExceptions._OSError.ERROR_DIRECTORY, path);
}
}
#endif
PythonList ret = new PythonList();
try {
addBase(context.LanguageContext.DomainManager.Platform.GetFileSystemEntries(path, "*"), ret);
return ret;
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
public static PythonList listdir(CodeContext context, [NotNone] Bytes path) {
PythonList ret = new PythonList();
foreach (object? item in listdir(context, path.ToFsString(context))) {
ret.AddNoLock(((string)item!).ToFsBytes(context));
}
return ret;
}
public static PythonList listdir(CodeContext context, object? path)
=> listdir(context, ConvertToFsString(context, path, nameof(path)));
public static BigInteger lseek(CodeContext context, int fd, long offset, int whence) {
var streams = context.LanguageContext.FileManager.GetStreams(fd);
return streams.ReadStream.Seek(offset, (SeekOrigin)whence);
}
[Documentation("lstat(path, *, dir_fd=None) -> stat_result\n\n" +
"Like stat(), but do not follow symbolic links.\n" +
"Equivalent to calling stat(...) with follow_symlinks=False.")]
[LightThrowing]
public static object lstat([NotNone] string path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
if (kwargs.ContainsKey("follow_symlinks"))
throw PythonOps.TypeError("'follow_symlinks' is an invalid keyword argument for lstat(...)");
kwargs["follow_symlinks"] = false;
return stat(path, kwargs);
}
[LightThrowing, Documentation("")]
public static object lstat(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> lstat(path.ToFsString(context), kwargs);
[LightThrowing, Documentation("")]
public static object lstat(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> lstat(ConvertToFsString(context, path, nameof(path)), kwargs);
[PythonType]
public sealed class DirEntry {
private readonly CodeContext context;
private readonly FileSystemInfo info;
private readonly bool asBytes;
internal DirEntry(CodeContext context, FileSystemInfo info, bool asBytes) {
this.context = context;
this.info = info;
this.asBytes = asBytes;
}
public object path => asBytes ? info.FullName.ToFsBytes(context) : info.FullName;
public object name => asBytes ? info.Name.ToFsBytes(context) : info.Name;
[LightThrowing]
public object? inode() {
var obj = stat(follow_symlinks: false);
if (obj is stat_result res) return res.st_ino;
return obj;
}
public bool is_dir(bool follow_symlinks = true) => info.Attributes.HasFlag(FileAttributes.Directory);
public bool is_file(bool follow_symlinks = true) => !is_dir();
public bool is_symlink() => throw new NotImplementedException();
[LightThrowing]
public object? stat(bool follow_symlinks = true) => PythonNT.stat(info.FullName, new Dictionary<string, object>());
public string __repr__(CodeContext context) => $"<DirEntry {PythonOps.Repr(context, name)}>";
}
[PythonType, PythonHidden]
public sealed class ScandirIterator : IEnumerable<DirEntry>, IEnumerator<DirEntry> {
private readonly CodeContext context;
private readonly IEnumerator<FileSystemInfo> enumerator;
private readonly bool asBytes;
internal ScandirIterator(CodeContext context, IEnumerable<FileSystemInfo> list, bool asBytes) {
this.context = context;
enumerator = list.GetEnumerator();
this.asBytes = asBytes;
}
[PythonHidden]
public DirEntry Current => new DirEntry(context, enumerator.Current, asBytes);
object IEnumerator.Current => Current;
[PythonHidden]
public void Dispose() => enumerator.Dispose();
[PythonHidden]
public IEnumerator<DirEntry> GetEnumerator() => this;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
[PythonHidden]
public bool MoveNext() => enumerator.MoveNext();
[PythonHidden]
public void Reset() => enumerator.Reset();
}
public static ScandirIterator scandir(CodeContext context, string? path = null)
=> new ScandirIterator(context, ScandirHelper(context, path), asBytes: false);
public static ScandirIterator scandir(CodeContext context, [NotNone] IBufferProtocol path)
=> new ScandirIterator(context, ScandirHelper(context, ConvertToFsString(context, path, nameof(path))), asBytes: true);
private static IEnumerable<FileSystemInfo> ScandirHelper(CodeContext context, string? path) {
if (path == null) {
path = getcwd(context);
}
if (path == string.Empty) {
throw PythonOps.OSError(PythonExceptions._OSError.ERROR_PATH_NOT_FOUND, "The system cannot find the path specified", path, PythonExceptions._OSError.ERROR_PATH_NOT_FOUND);
}
#if !NETFRAMEWORK
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
// .NET Core throws an unhelpful "The parameter is incorrect" error when trying to listdir a file
if (File.Exists(path)) {
throw GetWin32Error(PythonExceptions._OSError.ERROR_DIRECTORY, path);
}
}
#endif
try {
return new DirectoryInfo(path).EnumerateFileSystemInfos();
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
#if FEATURE_NATIVE
[Documentation("symlink(src, dst, target_is_directory=False, *, dir_fd=None)")]
public static void symlink([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args) {
var numArgs = args.Length;
CheckOptionalArgsCount(numRegParms: 2, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count);
bool target_is_directory = numArgs > 0 ? Converter.ConvertToBoolean(args[0]) : false;
foreach (var kvp in kwargs) {
switch (kvp.Key) {
case nameof(target_is_directory):
if (numArgs > 0) throw PythonOps.TypeError("argument for {0}() given by name ('{1}') and position ({2})", nameof(symlink), nameof(target_is_directory), 3);
target_is_directory = Converter.ConvertToBoolean(kvp.Value);
break;
case "dir_fd":
throw PythonOps.NotImplementedError("{0} unavailable on this platform", kvp.Key);
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for {1}()", kvp.Key, nameof(symlink));
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
// TODO: implement this
throw new NotImplementedException();
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
symlinkUnix(src, dst);
} else {
throw new NotImplementedException();
}
static void symlinkUnix(string src, string dst) {
if (Mono.Unix.Native.Syscall.symlink(src, dst) == 0) return;
throw GetLastUnixError(src, dst);
}
}
[Documentation("")]
public static void symlink(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> symlink(src.ToFsString(context), dst.ToFsString(context), kwargs, args);
[Documentation("")]
public static void symlink(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> symlink(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs, args);
[PythonType]
public sealed class uname_result : PythonTuple {
public const int n_fields = 5;
public const int n_sequence_fields = 5;
public const int n_unnamed_fields = 0;
internal uname_result(object?[] sequence) : base(sequence) {
if (_data.Length != n_sequence_fields) {
// TODO: CPython shows nt/posix instead of os...
throw PythonOps.ValueError($"os.{nameof(uname_result)}() takes a 5-sequence ({_data.Length}-sequence given)");
}
}
internal uname_result(string? sysname, string? nodename, string? release, string? version, string? machine) :
base(new object?[] { sysname, nodename, release, version, machine }) { }
public static uname_result __new__(CodeContext context, [NotNone] PythonType cls, [NotNone] IEnumerable<object?> sequence) {
return new uname_result(sequence.ToArray());
}
public object? sysname => this[0];
public object? nodename => this[1];
public object? release => this[2];
public object? version => this[3];
public object? machine => this[4];
public override string __repr__(CodeContext context) {
return $"os.{nameof(uname_result)}sysname={PythonOps.Repr(context, sysname)}, nodename={PythonOps.Repr(context, nodename)}, release={PythonOps.Repr(context, release)}, version={PythonOps.Repr(context, version)}, machine={PythonOps.Repr(context, machine)})";
}
}
[PythonHidden(PlatformsAttribute.PlatformFamily.Windows)]
public static uname_result uname() {
Mono.Unix.Native.Utsname info;
Mono.Unix.Native.Syscall.uname(out info);
return new uname_result(info.sysname, info.nodename, info.release, info.version, info.machine);
}
[PythonHidden(PlatformsAttribute.PlatformFamily.Windows)]
public static BigInteger getuid() {
return Mono.Unix.Native.Syscall.getuid();
}
[PythonHidden(PlatformsAttribute.PlatformFamily.Windows)]
public static BigInteger geteuid() {
return Mono.Unix.Native.Syscall.geteuid();
}
#endif
#if FEATURE_FILESYSTEM
[Documentation("mkdir(path, mode=511, *, dir_fd=None)")]
public static void mkdir([NotNone] string path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args) {
var numArgs = args.Length;
CheckOptionalArgsCount(numRegParms: 1, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count);
int mode = numArgs > 0 ? Converter.ConvertToIndex(args[0], throwOverflowError: true) : 511; // 0o777
foreach (var kvp in kwargs) {
switch (kvp.Key) {
case nameof(mode):
if (numArgs > 0) throw PythonOps.TypeError("argument for {0}() given by name ('{1}') and position ({2})", nameof(mkdir), nameof(mode), 2);
mode = Converter.ConvertToIndex(kvp.Value, throwOverflowError: true);
break;
case "dir_fd":
throw PythonOps.NotImplementedError("{0} unavailable on this platform", kvp.Key);
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for {1}()", kvp.Key, nameof(mkdir));
}
}
if (Directory.Exists(path)) throw DirectoryExists();
// we ignore mode
try {
Directory.CreateDirectory(path);
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
[Documentation("")]
public static void mkdir(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> mkdir(path.ToFsString(context), kwargs, args);
[Documentation("")]
public static void mkdir(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> mkdir(ConvertToFsString(context, path, nameof(path)), kwargs, args);
private const int DefaultBufferSize = 4096;
[Documentation("open(path, flags, mode=511, *, dir_fd=None)")]
public static object open(CodeContext/*!*/ context, [NotNone] string path, int flags, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args) {
var numArgs = args.Length;
CheckOptionalArgsCount(numRegParms: 2, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count);
int mode = numArgs > 0 ? Converter.ConvertToIndex(args[0], throwOverflowError: true) : 511; // 0o777
foreach (var kvp in kwargs) {
switch (kvp.Key) {
case nameof(mode):
if (numArgs > 0) throw PythonOps.TypeError("argument for {0}() given by name ('{1}') and position ({2})", nameof(open), nameof(mode), 3);
mode = Converter.ConvertToIndex(kvp.Value, throwOverflowError: true);
break;
case "dir_fd":
throw PythonOps.NotImplementedError("{0} unavailable on this platform", kvp.Key);
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for {1}()", kvp.Key, nameof(open));
}
}
try {
FileMode fileMode = FileModeFromFlags(flags);
FileAccess access = FileAccessFromFlags(flags);
FileOptions options = FileOptionsFromFlags(flags);
Stream fs;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && IsNulFile(path)) {
fs = Stream.Null;
} else if (access == FileAccess.Read && (fileMode == FileMode.CreateNew || fileMode == FileMode.Create || fileMode == FileMode.Append)) {
// .NET doesn't allow Create/CreateNew w/ access == Read, so create the file, then close it, then
// open it again w/ just read access.
fs = new FileStream(path, fileMode, FileAccess.Write, FileShare.None);
fs.Close();
fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, DefaultBufferSize, options);
} else if (access == FileAccess.ReadWrite && fileMode == FileMode.Append) {
fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, DefaultBufferSize, options);
} else {
fs = new FileStream(path, fileMode, access, FileShare.ReadWrite, DefaultBufferSize, options);
}
return context.LanguageContext.FileManager.Add(new(fs));
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
[Documentation("")]
public static object open(CodeContext context, [NotNone] Bytes path, int flags, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> open(context, path.ToFsString(context), flags, kwargs, args);
[Documentation("")]
public static object open(CodeContext context, object? path, int flags, [ParamDictionary, NotNone] IDictionary<string, object> kwargs, [NotNone] params object[] args)
=> open(context, ConvertToFsString(context, path, nameof(path)), flags, kwargs, args);
private static FileOptions FileOptionsFromFlags(int flag) {
FileOptions res = FileOptions.None;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
if ((flag & O_TEMPORARY) != 0) {
res |= FileOptions.DeleteOnClose;
}
if ((flag & O_RANDOM) != 0) {
res |= FileOptions.RandomAccess;
}
if ((flag & O_SEQUENTIAL) != 0) {
res |= FileOptions.SequentialScan;
}
}
return res;
}
#endif
#if FEATURE_PIPES
private static Tuple<Stream, Stream> CreatePipeStreams() {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
return CreatePipeStreamsUnix();
} else {
var inPipe = new AnonymousPipeServerStream(PipeDirection.In);
var outPipe = new AnonymousPipeClientStream(PipeDirection.Out, inPipe.ClientSafePipeHandle);
return Tuple.Create<Stream, Stream>(inPipe, outPipe);
}
static Tuple<Stream, Stream> CreatePipeStreamsUnix() {
Mono.Unix.UnixPipes pipes = Mono.Unix.UnixPipes.CreatePipes();
return Tuple.Create<Stream, Stream>(pipes.Reading, pipes.Writing);
}
}
public static PythonTuple pipe(CodeContext context) {
var pipeStreams = CreatePipeStreams();
var manager = context.LanguageContext.FileManager;
return PythonTuple.MakeTuple(
manager.Add(new(pipeStreams.Item1)),
manager.Add(new(pipeStreams.Item2))
);
}
#endif
#if FEATURE_PROCESS
public static void putenv([NotNone] string name, [NotNone] string value) {
try {
System.Environment.SetEnvironmentVariable(name, value);
} catch (Exception e) {
throw ToPythonException(e);
}
}
#endif
public static Bytes read(CodeContext/*!*/ context, int fd, int buffersize) {
if (buffersize < 0) {
throw PythonOps.OSError(PythonErrorNumber.EINVAL, "Invalid argument");
}
try {
PythonContext pythonContext = context.LanguageContext;
var streams = pythonContext.FileManager.GetStreams(fd);
if (!streams.ReadStream.CanRead) throw PythonOps.OSError(9, "Bad file descriptor");
return Bytes.Make(streams.Read(buffersize));
} catch (Exception e) {
throw ToPythonException(e);
}
}
[Documentation("rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)")]
public static void rename([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
foreach (var key in kwargs.Keys) {
switch (key) {
case "src_dir_fd":
case "dst_dir_fd":
// TODO: posix: implement these!
break;
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", key);
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
if (!MoveFileEx(src, dst, 0)) {
throw GetLastWin32Error(src, dst);
}
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
renameUnix(src, dst);
} else {
try {
Directory.Move(src, dst);
} catch (Exception e) {
throw ToPythonException(e);
}
}
}
[Documentation("")]
public static void rename(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> rename(src.ToFsString(context), dst.ToFsString(context), kwargs);
[Documentation("")]
public static void rename(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs)
=> rename(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs);
private const uint MOVEFILE_REPLACE_EXISTING = 0x01;
[DllImport("kernel32.dll", EntryPoint = "MoveFileExW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
private static extern bool MoveFileEx(string src, string dst, uint flags);
private static void renameUnix(string src, string dst) {
if (Mono.Unix.Native.Syscall.rename(src, dst) == 0) return;
throw GetLastUnixError(src, dst);
}
[Documentation("replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)")]
public static void replace([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary<string, object> kwargs) {
foreach (var key in kwargs.Keys) {
switch (key) {
case "src_dir_fd":
case "dst_dir_fd":
// TODO: posix: implement these!
break;
default:
throw PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", key);
}
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
if (!MoveFileEx(src, dst, MOVEFILE_REPLACE_EXISTING)) {
throw GetLastWin32Error(src, dst);
}
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
renameUnix(src, dst);
} else {
throw new NotImplementedException();
}
}