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
1716 lines (1444 loc) · 71.8 KB
/
nt.cs
File metadata and controls
1716 lines (1444 loc) · 71.8 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.
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#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...";
#if FEATURE_PROCESS
private static Dictionary<int, Process> _processToIdMapping = new Dictionary<int, Process>();
private static 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";
[SpecialName]
public static void PerformModuleReload(PythonContext context, 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
[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);
[PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static string _getfinalpathname(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();
}
#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>
public static bool access(CodeContext/*!*/ context, string path, int mode) {
if (path == null) throw PythonOps.TypeError("expected string, got None");
#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
}
#if FEATURE_FILESYSTEM
public static void chdir([NotNull]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);
}
}
// Isolate Mono.Unix from the rest of the method so that we don't try to load the Mono.Posix 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);
}
public static void chmod(string path, int mode, [ParamDictionary]IDictionary<string, object> dict) {
if (dict != null) {
foreach (var key in dict.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();
}
}
#endif
public static void close(CodeContext/*!*/ context, int fd) {
PythonContext pythonContext = context.LanguageContext;
PythonFileManager fileManager = pythonContext.FileManager;
if (fileManager.TryGetFileFromId(pythonContext, fd, out PythonIOModule.FileIO file)) {
fileManager.CloseIfLast(context, fd, file);
} else {
Stream stream = fileManager.GetObjectFromId(fd) as Stream;
if (stream == null) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
fileManager.CloseIfLast(fd, stream);
}
}
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
}
}
}
private static bool IsValidFd(CodeContext/*!*/ context, int fd) {
PythonContext pythonContext = context.LanguageContext;
if (pythonContext.FileManager.TryGetFileFromId(pythonContext, fd, out PythonIOModule.FileIO _)) {
return true;
}
if (pythonContext.FileManager.TryGetObjectFromId(pythonContext, fd, out object o)) {
if (o is Stream) {
return true;
}
}
return false;
}
public static int dup(CodeContext/*!*/ context, int fd) {
PythonContext pythonContext = context.LanguageContext;
if (pythonContext.FileManager.TryGetFileFromId(pythonContext, fd, out PythonIOModule.FileIO file)) {
return pythonContext.FileManager.AddToStrongMapping(file);
} else {
Stream stream = pythonContext.FileManager.GetObjectFromId(fd) as Stream;
if (stream == null) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
return pythonContext.FileManager.AddToStrongMapping(stream);
}
}
public static int dup2(CodeContext/*!*/ context, int fd, int fd2) {
PythonContext pythonContext = context.LanguageContext;
if (!IsValidFd(context, fd)) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
if (!pythonContext.FileManager.ValidateFdRange(fd2)) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
bool fd2Valid = IsValidFd(context, fd2);
if (fd == fd2) {
if (fd2Valid) {
return fd2;
}
throw PythonOps.OSError(9, "Bad file descriptor");
}
if (fd2Valid) {
close(context, fd2);
}
if (pythonContext.FileManager.TryGetFileFromId(pythonContext, fd, out PythonIOModule.FileIO file)) {
return pythonContext.FileManager.AddToStrongMapping(file, fd2);
}
var stream = pythonContext.FileManager.GetObjectFromId(fd) as Stream;
if (stream == null) {
throw PythonOps.OSError(9, "Bad file descriptor");
}
return pythonContext.FileManager.AddToStrongMapping(stream, fd2);
}
#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 code) {
context.LanguageContext.DomainManager.Platform.TerminateScriptExecution(code);
}
[LightThrowing]
public static object fstat(CodeContext/*!*/ context, int fd) {
PythonContext pythonContext = context.LanguageContext;
if (pythonContext.FileManager.TryGetFileFromId(pythonContext, fd, out PythonIOModule.FileIO file) && file.name is string strName) {
return file.IsConsole ? new stat_result(8192) : lstat(strName);
}
throw PythonOps.OSError(9, "Bad file descriptor");
}
public static void fsync(CodeContext context, int fd) {
PythonContext pythonContext = context.LanguageContext;
var pf = pythonContext.FileManager.GetFileFromId(pythonContext, fd);
try {
pf.flush(context);
} catch (Exception ex) when (ex is ValueErrorException || ex is 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) {
var encoding = SysModule.getfilesystemencoding() as string;
return StringOps.encode(context, context.LanguageContext.DomainManager.Platform.CurrentDirectory, encoding);
}
#if NETCOREAPP || NETSTANDARD
private static readonly char[] invalidPathChars = new char[] { '\"', '<', '>' };
#endif
public static string _getfullpathname(CodeContext/*!*/ context, [NotNull]string/*!*/ dir) {
PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform;
try {
return pal.GetFullPath(dir);
} 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 = dir;
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 = dir.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) + dir[curDir] + res.Substring(curRes + 1);
break;
}
}
}
}
return res;
}
}
private static bool IsWindows() {
return Environment.OSVersion.Platform == PlatformID.Win32NT ||
Environment.OSVersion.Platform == PlatformID.Win32S ||
Environment.OSVersion.Platform == PlatformID.Win32Windows;
}
#if FEATURE_PROCESS
public static int getpid() {
return System.Diagnostics.Process.GetCurrentProcess().Id;
}
#endif
public static PythonList listdir(CodeContext/*!*/ context, [BytesConversion][NotNull]IList<byte> path)
=> listdir(context, PythonOps.MakeString(path));
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);
}
PythonList ret = PythonOps.MakeList();
try {
addBase(context.LanguageContext.DomainManager.Platform.GetFileSystemEntries(path, "*"), ret);
return ret;
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
public static BigInteger lseek(CodeContext context, int filedes, long offset, int whence) {
var file = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, filedes);
return file.seek(context, offset, whence);
}
/// <summary>
/// lstat(path) -> stat result
/// Like stat(path), but do not follow symbolic links.
/// </summary>
[LightThrowing]
public static object lstat(string path) {
// TODO: detect links
return stat(path, null);
}
[LightThrowing]
public static object lstat([BytesConversion]IList<byte> path)
=> lstat(PythonOps.MakeString(path));
#if FEATURE_NATIVE
[PythonHidden(PlatformsAttribute.PlatformFamily.Windows)]
public static void symlink(string source, string link_name) {
if (Mono.Unix.Native.Syscall.symlink(source, link_name) == 0) return;
throw GetLastUnixError(source, link_name);
}
[PythonType("uname_result"), PythonHidden(PlatformsAttribute.PlatformFamily.Windows)]
public class uname_result : PythonTuple {
public uname_result(string sysname, string nodename, string release, string version, string machine) :
base(new object[] { sysname, nodename, release, version, machine }) { }
public string sysname => (string)this[0];
public string nodename => (string)this[1];
public string release => (string)this[2];
public string version => (string)this[3];
public string machine => (string)this[4];
public override string ToString() {
return $"posix.uname_result(sysname='{sysname}', nodename='{nodename}', release='{release}', version='{version}', machine='{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
public static void mkdir(string path) {
if (Directory.Exists(path))
throw DirectoryExists();
try {
Directory.CreateDirectory(path);
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
public static void mkdir(string path, int mode) {
if (Directory.Exists(path)) throw DirectoryExists();
// we ignore mode
try {
Directory.CreateDirectory(path);
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
public static object open(CodeContext/*!*/ context, string filename, int flag) {
return open(context, filename, flag, 0777);
}
private const int DefaultBufferSize = 4096;
public static object open(CodeContext/*!*/ context, string filename, int flag, int mode) {
try {
FileMode fileMode = FileModeFromFlags(flag);
FileAccess access = FileAccessFromFlags(flag);
FileOptions options = FileOptionsFromFlags(flag);
Stream fs;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && string.Equals(filename, "nul", StringComparison.OrdinalIgnoreCase)
|| (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) && filename == "/dev/null") {
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(filename, fileMode, FileAccess.Write, FileShare.None);
fs.Close();
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, DefaultBufferSize, options);
} else if (access == FileAccess.ReadWrite && fileMode == FileMode.Append) {
fs = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, DefaultBufferSize, options);
} else {
fs = new FileStream(filename, fileMode, access, FileShare.ReadWrite, DefaultBufferSize, options);
}
string mode2;
if (fs.CanRead && fs.CanWrite) mode2 = "w+";
else if (fs.CanWrite) mode2 = "w";
else mode2 = "r";
if ((flag & O_BINARY) != 0) {
mode2 += "b";
}
return context.LanguageContext.FileManager.AddToStrongMapping(new PythonIOModule.FileIO(context, fs) { name = filename });
} catch (Exception e) {
throw ToPythonException(e, filename);
}
}
private static FileOptions FileOptionsFromFlags(int flag) {
FileOptions res = FileOptions.None;
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> CreatePipeStreamsUnix() {
Mono.Unix.UnixPipes pipes = Mono.Unix.UnixPipes.CreatePipes();
return Tuple.Create<Stream, Stream>(pipes.Reading, pipes.Writing);
}
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);
}
}
public static PythonTuple pipe(CodeContext context) {
var pipeStreams = CreatePipeStreams();
var inFile = new PythonIOModule.FileIO(context, pipeStreams.Item1);
var outFile = new PythonIOModule.FileIO(context, pipeStreams.Item2);
return PythonTuple.MakeTuple(
context.LanguageContext.FileManager.AddToStrongMapping(inFile),
context.LanguageContext.FileManager.AddToStrongMapping(outFile)
);
}
#endif
#if FEATURE_PROCESS
public static void putenv(string varname, string value) {
try {
System.Environment.SetEnvironmentVariable(varname, 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 pf = pythonContext.FileManager.GetFileFromId(pythonContext, fd);
return (Bytes)pf.read(context, buffersize);
} catch (Exception e) {
throw ToPythonException(e);
}
}
public static void rename(string src, string dst) {
try {
Directory.Move(src, dst);
} catch (Exception e) {
throw ToPythonException(e);
}
}
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 replaceUnix(string src, string dst) {
if (Mono.Unix.Native.Syscall.rename(src, dst) == 0) return;
throw GetLastUnixError(src, dst);
}
public static void replace(string src, string dst) {
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)) {
replaceUnix(src, dst);
} else {
throw new NotImplementedException();
}
}
public static void rmdir(string path) {
try {
Directory.Delete(path);
} catch (Exception e) {
throw ToPythonException(e, path);
}
}
#if FEATURE_PROCESS
/// <summary>
/// spawns a new process.
///
/// If mode is nt.P_WAIT then then the call blocks until the process exits and the return value
/// is the exit code.
///
/// Otherwise the call returns a handle to the process. The caller must then call nt.waitpid(pid, options)
/// to free the handle and get the exit code of the process. Failure to call nt.waitpid will result
/// in a handle leak.
/// </summary>
public static object spawnv(CodeContext/*!*/ context, int mode, string path, object args) {
return SpawnProcessImpl(context, MakeProcess(), mode, path, args);
}
/// <summary>
/// spawns a new process.
///
/// If mode is nt.P_WAIT then then the call blocks until the process exits and the return value
/// is the exit code.
///
/// Otherwise the call returns a handle to the process. The caller must then call nt.waitpid(pid, options)
/// to free the handle and get the exit code of the process. Failure to call nt.waitpid will result
/// in a handle leak.
/// </summary>
public static object spawnve(CodeContext/*!*/ context, int mode, string path, object args, object env) {
Process process = MakeProcess();
SetEnvironment(process.StartInfo.EnvironmentVariables, env);
return SpawnProcessImpl(context, process, mode, path, args);
}
private static Process MakeProcess() {
try {
return new Process();
} catch (Exception e) {
throw ToPythonException(e);
}
}
private static object SpawnProcessImpl(CodeContext/*!*/ context, Process process, int mode, string path, object args) {
try {
process.StartInfo.Arguments = ArgumentsToString(context, args);
process.StartInfo.FileName = path;
process.StartInfo.UseShellExecute = false;
} catch (Exception e) {
throw ToPythonException(e, path);
}
if (!process.Start()) {
throw PythonOps.OSError("Cannot start process: {0}", path);
}
if (mode == P_WAIT) {
process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();
return exitCode;
}
lock (_processToIdMapping) {
int id;
if (_freeProcessIds.Count > 0) {
id = _freeProcessIds[_freeProcessIds.Count - 1];
_freeProcessIds.RemoveAt(_freeProcessIds.Count - 1);
} else {
// process IDs are handles on CPython/Win32 so we match
// that behavior and return something that is handle like. Handles
// on NT are guaranteed to have the low 2 bits not set and users
// could use these for their own purposes. We therefore match that
// behavior here.
_processCount += 4;
id = _processCount;
}
_processToIdMapping[id] = process;
return ScriptingRuntimeHelpers.Int32ToObject(id);
}
}
/// <summary>
/// Copy elements from a Python mapping of dict environment variables to a StringDictionary.
/// </summary>
private static void SetEnvironment(System.Collections.Specialized.StringDictionary currentEnvironment, object newEnvironment) {
PythonDictionary env = newEnvironment as PythonDictionary;
if (env == null) {
throw PythonOps.TypeError("env argument must be a dict");
}
currentEnvironment.Clear();
string strKey, strValue;
foreach (object key in env.keys()) {
if (!Converter.TryConvertToString(key, out strKey)) {
throw PythonOps.TypeError("env dict contains a non-string key");
}
if (!Converter.TryConvertToString(env[key], out strValue)) {
throw PythonOps.TypeError("env dict contains a non-string value");
}
currentEnvironment[strKey] = strValue;
}
}
#endif
/// <summary>
/// Convert a sequence of args to a string suitable for using to spawn a process.
/// </summary>
private static string ArgumentsToString(CodeContext/*!*/ context, object args) {
IEnumerator argsEnumerator;
System.Text.StringBuilder sb = null;
if (!PythonOps.TryGetEnumerator(context, args, out argsEnumerator)) {
throw PythonOps.TypeError("args parameter must be sequence, not {0}", DynamicHelpers.GetPythonType(args));
}
bool space = false;
try {
// skip the first element, which is the name of the command being run
argsEnumerator.MoveNext();
while (argsEnumerator.MoveNext()) {
if (sb == null) sb = new System.Text.StringBuilder(); // lazy creation
string strarg = PythonOps.ToString(argsEnumerator.Current);
if (space) {
sb.Append(' ');
}
if (strarg.IndexOf(' ') != -1) {
sb.Append('"');
// double quote any existing quotes
sb.Append(strarg.Replace("\"", "\"\""));
sb.Append('"');
} else {
sb.Append(strarg);
}
space = true;
}
} finally {
IDisposable disposable = argsEnumerator as IDisposable;
if (disposable != null) disposable.Dispose();
}
if (sb == null) return "";
return sb.ToString();
}
#if FEATURE_PROCESS
[PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static void startfile(string filename, string operation = "open") {
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = filename;
process.StartInfo.UseShellExecute = true;
process.StartInfo.Verb = operation;
try {
process.Start();
} catch (Exception e) {
throw ToPythonException(e, filename);
}
}
#endif
[PythonType]
public sealed class stat_result : PythonTuple {
public const int n_fields = 16;
public const int n_sequence_fields = 10;
public const int n_unnamed_fields = 3;
private const long nanosecondsPerSeconds = 1_000_000_000;
internal stat_result(int mode) : this(new object[10] { mode, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, null) { }
internal stat_result(Mono.Unix.Native.Stat stat)
: this(new object[16] {(int)stat.st_mode, stat.st_ino, stat.st_dev, stat.st_nlink, stat.st_uid, stat.st_gid, stat.st_size, stat.st_atime, stat.st_mtime, stat.st_ctime,
stat.st_atime + stat.st_atime_nsec / (double)nanosecondsPerSeconds, stat.st_mtime + stat.st_mtime_nsec / (double)nanosecondsPerSeconds, stat.st_ctime + stat.st_ctime_nsec / (double)nanosecondsPerSeconds,
stat.st_atime * nanosecondsPerSeconds + stat.st_atime_nsec, stat.st_mtime * nanosecondsPerSeconds + stat.st_mtime_nsec, stat.st_ctime * nanosecondsPerSeconds + stat.st_ctime_nsec }, null) { }
internal stat_result(int mode, ulong fileidx, long size, long st_atime_ns, long st_mtime_ns, long st_ctime_ns)
: this(new object[16] { mode, fileidx, 0, 0, 0, 0, size, st_atime_ns / nanosecondsPerSeconds, st_mtime_ns / nanosecondsPerSeconds, st_ctime_ns / nanosecondsPerSeconds,
st_atime_ns / (double)nanosecondsPerSeconds, st_mtime_ns / (double)nanosecondsPerSeconds, st_ctime_ns / (double)nanosecondsPerSeconds,
st_atime_ns, st_mtime_ns, st_ctime_ns }, null) { }
private stat_result(object[] statResult, PythonDictionary dict) : base(statResult.Take(n_sequence_fields).ToArray()) {
if (statResult.Length < n_sequence_fields) {
throw PythonOps.TypeError($"os.stat_result() takes an at least {n_sequence_fields}-sequence ({statResult.Length}-sequence given)");
} else if (statResult.Length > n_fields) {
throw PythonOps.TypeError($"os.stat_result() takes an at least {n_sequence_fields}-sequence ({statResult.Length}-sequence given)");
}
object obj;
if (statResult.Length >= 11) {
_atime = statResult[10];
} else if (TryGetDictValue(dict, "st_atime", out obj)) {
_atime = obj;
}
if (statResult.Length >= 12) {
_mtime = statResult[11];
} else if (TryGetDictValue(dict, "st_mtime", out obj)) {
_mtime = obj;
}
if (statResult.Length >= 13) {
_ctime = statResult[12];
} else if (TryGetDictValue(dict, "st_ctime", out obj)) {
_ctime = obj;
}
if (statResult.Length >= 14) {
st_atime_ns = statResult[13];
} else if (TryGetDictValue(dict, "st_atime_ns", out obj)) {
st_atime_ns = obj;
}
if (statResult.Length >= 15) {
st_mtime_ns = statResult[14];
} else if (TryGetDictValue(dict, "st_mtime_ns", out obj)) {
st_mtime_ns = obj;
}
if (statResult.Length >= 16) {
st_ctime_ns = statResult[15];
} else if (TryGetDictValue(dict, "st_ctime_ns", out obj)) {
st_ctime_ns = obj;
}
}
public static stat_result __new__(CodeContext context, PythonType cls, IEnumerable<object> sequence, PythonDictionary dict = null) {
return new stat_result(sequence, dict);
}
public stat_result(IEnumerable<object> sequence, PythonDictionary dict = null)
: this(sequence.ToArray(), dict) { }
private static bool TryGetDictValue(PythonDictionary dict, string name, out object value) {
value = null;
return dict != null && dict.TryGetValue(name, out value);
}
private readonly object _atime;
private readonly object _mtime;
private readonly object _ctime;
public object st_mode => this[0];
public object st_ino => this[1];
public object st_dev => this[2];
public object st_nlink => this[3];
public object st_uid => this[4];
public object st_gid => this[5];
public object st_size => this[6];
public object st_atime => _atime ?? this[7];
public object st_mtime => _mtime ?? this[8];
public object st_ctime => _ctime ?? this[9];
public object st_atime_ns { get; }
public object st_mtime_ns { get; }
public object st_ctime_ns { get; }
public override string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format("os.stat_result("
+ "st_mode={0}, "
+ "st_ino={1}, "
+ "st_dev={2}, "
+ "st_nlink={3}, "
+ "st_uid={4}, "
+ "st_gid={5}, "
+ "st_size={6}, "
+ "st_atime={7}, "
+ "st_mtime={8}, "
+ "st_ctime={9})", ToArray());
}
public PythonTuple __reduce__() {
PythonDictionary timeDict = new PythonDictionary(3);
timeDict["st_atime"] = _atime;
timeDict["st_mtime"] = _mtime;
timeDict["st_ctime"] = _ctime;
timeDict["st_atime_ns"] = st_atime_ns;
timeDict["st_mtime_ns"] = st_mtime_ns;
timeDict["st_ctime_ns"] = st_ctime_ns;
return MakeTuple(
DynamicHelpers.GetPythonTypeFromType(typeof(stat_result)),
MakeTuple(MakeTuple(this), timeDict)
);
}
}
private static bool HasExecutableExtension(string path) {
string extension = Path.GetExtension(path).ToLower(CultureInfo.InvariantCulture);
return (extension == ".exe" || extension == ".dll" || extension == ".com" || extension == ".bat");
}
// Isolate Mono.Unix from the rest of the method so that we don't try to load the Mono.Posix assembly on Windows.
private static object statUnix(string path) {
if (Mono.Unix.Native.Syscall.stat(path, out Mono.Unix.Native.Stat buf) == 0) {
return new stat_result(buf);
}
return LightExceptions.Throw(GetLastUnixError(path));
}
private const int OPEN_EXISTING = 3;
private const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
private const int FILE_READ_ATTRIBUTES = 0x0080;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
private const int FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
private static extern SafeFileHandle CreateFile(
string lpFileName,
int dwDesiredAccess,
int dwShareMode,
IntPtr securityAttrs,
int dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetFileInformationByHandle(SafeFileHandle hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct BY_HANDLE_FILE_INFORMATION {
public uint FileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
}
[Documentation("stat(path) -> stat result\nGathers statistics about the specified file or directory")]
[LightThrowing]
public static object stat(string path, [ParamDictionary]IDictionary<string, object> dict) {
if (path == null) {
return LightExceptions.Throw(PythonOps.TypeError("expected string, got NoneType"));
}
if (dict != null) {
foreach (var key in dict.Keys) {
switch (key) {
case "dir_fd":
case "follow_symlinks":
// TODO: implement these!
break;
default:
return LightExceptions.Throw(PythonOps.TypeError("'{0}' is an invalid keyword argument for this function", key));
}
}
}