-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathPosixModule.java
More file actions
1497 lines (1362 loc) · 53.8 KB
/
Copy pathPosixModule.java
File metadata and controls
1497 lines (1362 loc) · 53.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
/* Copyright (c) Jython Developers */
package org.python.modules.posix;
import com.kenai.jffi.Library;
import jnr.constants.Constant;
import jnr.constants.platform.Errno;
import jnr.constants.platform.Sysconf;
import jnr.posix.FileStat;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;
import jnr.posix.Times;
import jnr.posix.util.FieldAccess;
import jnr.posix.util.Platform;
import org.python.core.ArgParser;
import org.python.core.BufferProtocol;
import org.python.core.BuiltinDocs;
import org.python.core.Py;
import org.python.core.PyBUF;
import org.python.core.PyBuffer;
import org.python.core.PyBuiltinFunctionNarrow;
import org.python.core.PyBytes;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyFloat;
import org.python.core.PyList;
import org.python.core.PyLong;
import org.python.core.PyObject;
import org.python.core.PyStringMap;
import org.python.core.PySystemState;
import org.python.core.PyTuple;
import org.python.core.PyUnicode;
import org.python.core.Untraversable;
import org.python.core.io.FileIO;
import org.python.core.io.IOBase;
import org.python.core.io.RawIOBase;
import org.python.core.util.StringUtil;
import org.python.expose.ExposedConst;
import org.python.expose.ExposedFunction;
import org.python.expose.ExposedModule;
import org.python.expose.ModuleInit;
import org.python.modules._io.OpenMode;
import org.python.modules._io.PyFileIO;
import org.python.util.FilenoUtil;
import org.python.util.PosixShim;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.nio.file.NotLinkException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* The posix/nt module, depending on the platform.
*/
@ExposedModule(name = "posix", doc = BuiltinDocs.posix_doc)
public class PosixModule {
/** Current OS information. */
private static final OS os = OS.getOS();
/** Platform specific POSIX services. */
private static final POSIX posix = POSIXFactory.getPOSIX(new PythonPOSIXHandler(), true);
/** os.open flags. */
@ExposedConst
public static final int O_RDONLY = 0x0;
@ExposedConst
public static final int O_WRONLY = 0x1;
@ExposedConst
public static final int O_RDWR = 0x2;
@ExposedConst
public static final int O_APPEND = 0x8;
@ExposedConst
public static final int O_SYNC = 0x80;
@ExposedConst
public static final int O_CREAT = 0x200;
@ExposedConst
public static final int O_TRUNC = 0x400;
@ExposedConst
public static final int O_EXCL = 0x800;
/** os.access constants. */
@ExposedConst
public static final int F_OK = 0;
@ExposedConst
public static final int X_OK = 1 << 0;
@ExposedConst
public static final int W_OK = 1 << 1;
@ExposedConst
public static final int R_OK = 1 << 2;
/** RTLD_* constants */
@ExposedConst
public static final int RTLD_LAZY = Library.LAZY;
@ExposedConst
public static final int RTLD_NOW = Library.NOW;
@ExposedConst
public static final int RTLD_GLOBAL = Library.GLOBAL;
@ExposedConst
public static final int RTLD_LOCAL = Library.LOCAL;
@ExposedConst
public static final int WNOHANG = 0x00000001;
/** Lazily initialized singleton source for urandom. */
private static class UrandomSource {
static final SecureRandom INSTANCE = new SecureRandom();
}
/** Lazily initialised singleton representing some Unix-only features. */
private static class UnixSystem {
/*
* The reason for this rather elaborate device is that simply importing
* com.sun.security.auth.module.UnixSystem will prevent Jython compiling on Windows, where
* it is not supplied. We therefore take a reflective approach where creation of a singleton
* instance is allowed to fail, and looks like the non-availability of the function sought.
* This shouldn't arise if we've used the @Hide(OS.NT) annotation to avoid exposure of
* functions we don't have.
*/
private static Class<?> UNIX_SYSTEM = null;
private static Object INSTANCE = null;
private static Method GET_GROUPS = null;
static {
try {
UNIX_SYSTEM = Class.forName("com.sun.security.auth.module.UnixSystem");
INSTANCE = UNIX_SYSTEM.newInstance();
// long[] com.sun.security.auth.module.UnixSystem.getGroups()
GET_GROUPS = UNIX_SYSTEM.getMethod("getGroups");
} catch (Exception e) {}
}
/** Core of the function <code>os.getgroups</code>. */
static long[] getgroups() {
if (GET_GROUPS != null) {
try {
return (long[])GET_GROUPS.invoke(INSTANCE);
} catch (ReflectiveOperationException | IllegalArgumentException e) {
// and throw ...
}
}
throw notAvailable("getgroups");
}
/** Create an exception to report that the desired function is not available. */
private static PyException notAvailable(String name) {
String msg = String.format("module 'os' has no attribute '%s'", name);
return Py.AttributeError(msg);
}
}
@ModuleInit
public static void init(PyObject dict) {
// SecurityManager may restrict access to native implementation,
// so use Java-only implementation as necessary
boolean nativePosix = false;
try {
nativePosix = posix.isNative();
dict.__setitem__("_native_posix", Py.newBoolean(nativePosix));
dict.__setitem__("_posix_impl", Py.java2py(posix));
} catch (SecurityException ex) {}
dict.__setitem__("environ", getEnviron());
dict.__setitem__("error", Py.OSError);
dict.__setitem__("stat_result", PyStatResult.TYPE);
// Faster call paths, because __call__ is defined
dict.__setitem__("fstat", new FstatFunction());
if (os == OS.NT) {
WindowsStatFunction stat = new WindowsStatFunction();
dict.__setitem__("lstat", stat);
dict.__setitem__("stat", stat);
} else {
dict.__setitem__("lstat", new LstatFunction());
dict.__setitem__("stat", new StatFunction());
}
// Hide from Python
Hider.hideFunctions(PosixModule.class, dict, os, nativePosix);
String[] haveFunctions = new String[]{
"HAVE_FCHDIR", "HAVE_FCHMOD", "HAVE_FCHOWN",
"HAVE_FEXECVE", "HAVE_FDOPENDIR", "HAVE_FPATHCONF", "HAVE_FSTATVFS", "HAVE_FTRUNCATE",
"HAVE_LCHOWN", "HAVE_LUTIMES"
};
List<PyObject> haveFuncs = new ArrayList<PyObject>();
for (String haveFunc : haveFunctions) {
haveFuncs.add(PyUnicode.fromInterned(haveFunc));
}
dict.__setitem__("_have_functions", PyList.fromList(haveFuncs));
// Hide __doc__s
PyList keys;
if (dict instanceof PyStringMap) {
keys = (PyList) ((PyStringMap) dict).keys();
} else {
keys = (PyList) dict.invoke("keys");
}
for (Iterator<?> it = keys.listIterator(); it.hasNext();) {
String key = (String)it.next();
}
dict.__setitem__("__all__", keys);
}
// Combine Java FileDescriptor objects with Posix int file descriptors in one representation.
// Unfortunate ugliness!
public static class FDUnion {
volatile int intFD;
final FileDescriptor javaFD;
FDUnion(int fd) {
intFD = fd;
javaFD = null;
}
FDUnion(FileDescriptor fd) {
intFD = -1;
javaFD = fd;
}
boolean isIntFD() {
return intFD != -1;
}
public int getIntFD() {
return getIntFD(true);
}
int getIntFD(boolean checkFD) {
if (intFD == -1) {
if (!(javaFD instanceof FileDescriptor)) {
throw Py.OSError(Errno.EBADF);
}
try {
Field fdField = FieldAccess.getProtectedField(FileDescriptor.class, "fd");
intFD = fdField.getInt(javaFD);
} catch (SecurityException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (NullPointerException e) {}
}
if (checkFD) {
if (intFD == -1) {
throw Py.OSError(Errno.EBADF);
} else {
posix.fstat(intFD); // side effect of checking if this a good FD or not
}
}
return intFD;
}
@Override
public String toString() {
return "FDUnion(int=" + intFD + ", java=" + javaFD + ")";
}
}
public static FDUnion getFD(PyObject fdObj) {
if (fdObj.isInteger()) {
int intFd = fdObj.asInt();
switch (intFd) {
case 0:
return new FDUnion(FileDescriptor.in);
case 1:
return new FDUnion(FileDescriptor.out);
case 2:
return new FDUnion(FileDescriptor.err);
default:
return new FDUnion(intFd);
}
}
Object tojava = fdObj.__tojava__(FileDescriptor.class);
if (tojava != Py.NoConversion) {
return new FDUnion((FileDescriptor) tojava);
}
tojava = fdObj.__tojava__(FileIO.class);
if (tojava != Py.NoConversion) {
return new FDUnion(((FileIO)tojava).getFD());
}
if (fdObj instanceof PyFileIO) {
return new FDUnion(FilenoUtil.filenoFrom(fdObj));
}
tojava = fdObj.__tojava__(RawIOBase.class);
if (tojava != Py.NoConversion) {
return new FDUnion(FilenoUtil.filenoFrom(((RawIOBase) tojava).getChannel()));
}
throw Py.TypeError("an integer or Java/Jython file descriptor is required");
}
@ExposedFunction(doc = BuiltinDocs.posix__exit_doc, defaults = {"0"})
public static void _exit(int status) {
System.exit(status);
}
@ExposedFunction(doc = BuiltinDocs.posix_access_doc)
public static boolean access(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("access", args, keywords, "path", "mode", "*",
"dir_fd", "effective_ids", "follow_symlinks");
PyObject path = ap.getPyObject(0);
int mode = ap.getInt(1);
File file = absolutePath(path).toFile();
boolean result = true;
if (!file.exists()) {
result = false;
}
if ((mode & R_OK) != 0 && !file.canRead()) {
result = false;
}
if ((mode & W_OK) != 0 && !file.canWrite()) {
result = false;
}
if ((mode & X_OK) != 0 && !file.canExecute()) {
// Previously Jython used JNR Posix, but this is unnecessary -
// File#canExecute uses the same code path
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6379654
result = false;
}
return result;
}
@ExposedFunction(doc = BuiltinDocs.posix_chdir_doc)
public static void chdir(PyObject path) {
PySystemState sys = Py.getSystemState();
Path absolutePath = absolutePath(path);
// stat raises ENOENT for us if path doesn't exist
if (!basicstat(path, absolutePath).isDirectory()) {
throw Py.OSError(Errno.ENOTDIR, path);
}
if (os == OS.NT) {
// No symbolic links and preserve dos-like names (e.g. PROGRA~1)
sys.setCurrentWorkingDir(absolutePath.toString());
} else {
// Resolve symbolic links
try {
sys.setCurrentWorkingDir(absolutePath.toRealPath().toString());
} catch (IOException ioe) {
throw Py.OSError(ioe);
}
}
}
@ExposedFunction(doc = BuiltinDocs.posix_chmod_doc)
public static void chmod(PyObject path, int mode) {
if (os == OS.NT) {
try {
// We can only allow/deny write access (not read & execute)
boolean writable = (mode & FileStat.S_IWUSR) != 0;
File f = absolutePath(path).toFile();
if (!f.exists()) {
throw Py.OSError(Errno.ENOENT, path);
} else if (!f.setWritable(writable)) {
throw Py.OSError(Errno.EPERM, path);
}
} catch (SecurityException ex) {
throw Py.OSError(Errno.EACCES, path);
}
} else if (posix.chmod(absolutePath(path).toString(), mode) < 0) {
throw errorFromErrno(path);
}
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_chown_doc)
public static void chown(PyObject path, int uid, int gid) {
if (posix.chown(absolutePath(path).toString(), uid, gid) < 0) {
throw errorFromErrno(path);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_close_doc)
public static void close(PyObject fd) {
Object obj = fd.__tojava__(RawIOBase.class);
if (obj != Py.NoConversion) {
((RawIOBase)obj).close();
} else {
posix.close(getFD(fd).getIntFD());
}
}
@ExposedFunction(doc = BuiltinDocs.posix_closerange_doc)
public static void closerange(PyObject fd_lowObj, PyObject fd_highObj) {
int fd_low = getFD(fd_lowObj).getIntFD(false);
int fd_high = getFD(fd_highObj).getIntFD(false);
for (int i = fd_low; i < fd_high; i++) {
try {
posix.close(i);
} catch (Exception e) {}
}
}
// Disable dup support until it fully works with fdopen;
// this incomplete support currently breaks py.test
// public static PyObject dup(PyObject fd1) {
// return Py.newLong(posix.dup(getFD(fd1).getIntFD()));
// }
//
// public static PyObject dup2(PyObject fd1, PyObject fd2) {
// return Py.newLong(posix.dup2(getFD(fd1).getIntFD(), getFD(fd2).getIntFD()));
// }
// public static PyBytes __doc__fdopen = new PyBytes(
// "fdopen(fd [, mode='r' [, bufsize]]) -> file_object\n\n" +
// "Return an open file object connected to a file descriptor.");
// public static PyObject fdopen(PyObject fd) {
// return fdopen(fd, "r");
//
// }
//
// public static PyObject fdopen(PyObject fd, String mode) {
// return fdopen(fd, mode, -1);
//
// }
// public static PyObject fdopen(PyObject fd, String mode, int bufsize) {
// if (mode.length() == 0 || !"rwa".contains("" + mode.charAt(0))) {
// throw Py.ValueError(String.format("invalid file mode '%s'", mode));
// }
// Object javaobj = fd.__tojava__(RawIOBase.class);
// if (javaobj == Py.NoConversion) {
// getFD(fd).getIntFD();
// throw Py.NotImplementedError("Integer file descriptors not currently supported for fdopen");
// }
// RawIOBase rawIO = (RawIOBase)javaobj;
// if (rawIO.closed()) {
// throw badFD();
// }
//
// try {
// return new PyFile(rawIO, "<fdopen>", mode, bufsize);
// } catch (PyException pye) {
// if (!pye.match(Py.IOError)) {
// throw pye;
// }
// throw Py.OSError(Errno.EINVAL);
// }
// }
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_fdatasync_doc)
public static void fdatasync(PyObject fd) {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
fsync((RawIOBase)javaobj, false);
} else {
posix.fdatasync(getFD(fd).getIntFD());
}
}
@ExposedFunction(doc = BuiltinDocs.posix_fsync_doc)
public static void fsync(PyObject fd) {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
fsync((RawIOBase)javaobj, true);
} else {
posix.fsync(getFD(fd).getIntFD());
}
}
/**
* Internal fsync implementation.
*/
private static void fsync(RawIOBase rawIO, boolean metadata) {
rawIO.checkClosed();
Channel channel = rawIO.getChannel();
if (!(channel instanceof FileChannel)) {
throw Py.OSError(Errno.EINVAL);
}
try {
((FileChannel)channel).force(metadata);
} catch (ClosedChannelException cce) {
// In the rare case it's closed but the rawIO wasn't
throw Py.ValueError("I/O operation on closed file");
} catch (IOException ioe) {
throw Py.OSError(ioe);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_ftruncate_doc)
public static void ftruncate(PyObject fd, long length) {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
try {
((RawIOBase) javaobj).truncate(length);
} catch (PyException pye) {
throw Py.OSError(Errno.EBADF);
}
} else {
posix.ftruncate(getFD(fd).getIntFD(), length);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_getcwd_doc)
public static PyObject getcwd() {
return Py.newUnicode(Py.getSystemState().getCurrentWorkingDir());
}
@ExposedFunction(doc = BuiltinDocs.posix_getcwdb_doc)
public static PyObject getcwdb() {
return new PyBytes(Py.getSystemState().getCurrentWorkingDir());
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_getegid_doc)
public static int getegid() {
return posix.getegid();
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_geteuid_doc)
public static int geteuid() {
return posix.geteuid();
}
@ExposedFunction(doc = BuiltinDocs.posix_getgid_doc)
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
public static int getgid() {
return posix.getgid();
}
@ExposedFunction(doc = BuiltinDocs.posix_getgroups_doc)
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
public static PyObject getgroups() {
long[] groups = UnixSystem.getgroups();
PyObject[] list = new PyObject[groups.length];
for (int i = 0; i < groups.length; i++) {
list[i] = new PyLong(groups[i]);
}
return new PyList(list);
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_getlogin_doc)
public static PyObject getlogin() {
return new PyBytes(posix.getlogin());
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_getppid_doc)
public static int getppid() {
return posix.getppid();
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_getuid_doc)
public static int getuid() {
return posix.getuid();
}
@Hide(posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_getpid_doc)
public static int getpid() {
return posix.getpid();
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_getpgrp_doc)
public static int getpgrp() {
return posix.getpgrp();
}
@Hide(posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_isatty_doc)
public static boolean isatty(PyObject fdObj) {
Object tojava = fdObj.__tojava__(IOBase.class);
if (tojava != Py.NoConversion) {
try {
return ((IOBase) tojava).isatty();
} catch (PyException pye) {
if (pye.match(Py.ValueError)) {
return false;
}
throw pye;
}
}
FDUnion fd = getFD(fdObj);
if (fd.javaFD != null) {
return posix.isatty(fd.javaFD);
}
try {
fd.getIntFD(); // evaluate for side effect of checking EBADF or raising TypeError
} catch (PyException pye) {
if (pye.match(Py.OSError)) {
return false;
}
throw pye;
}
throw Py.NotImplementedError(
"Integer file descriptor compatibility only "
+ "available for stdin, stdout and stderr (0-2)");
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction(doc = BuiltinDocs.posix_kill_doc)
public static void kill(PyObject pidObj, int sig) {
Object ret = pidObj.__tojava__(Process.class);
if (ret == Py.NoConversion) {
int pid = pidObj.asInt();
if (posix.kill(pid, sig) < 0) {
throw errorFromErrno();
}
} else {
((Process) ret).destroy();
}
}
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
@ExposedFunction
public static void lchmod(PyObject path, int mode) {
if (posix.lchmod(absolutePath(path).toString(), mode) < 0) {
throw errorFromErrno(path);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_lchown_doc)
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
public static void lchown(PyObject path, int uid, int gid) {
if (posix.lchown(absolutePath(path).toString(), uid, gid) < 0) {
throw errorFromErrno(path);
}
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_link_doc)
public static void link(PyObject src, PyObject dst) {
try {
Files.createLink(Paths.get(asPath(dst)), Paths.get(asPath(src)));
} catch (FileAlreadyExistsException ex) {
throw Py.OSError(Errno.EEXIST);
} catch (NoSuchFileException ex) {
throw Py.OSError(Errno.ENOENT);
} catch (IOException ioe) {
System.err.println("Got this exception " + ioe);
throw Py.OSError(ioe);
} catch (SecurityException ex) {
throw Py.OSError(Errno.EACCES);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_listdir_doc)
public static PyList listdir(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("listdir", args, keywords, "path");
String path = ap.getString(0, System.getProperty("user.home"));
File file = absolutePath(path).toFile();
String[] names = file.list();
if (names == null) {
if (!file.exists()) {
throw Py.OSError(Errno.ENOENT, path);
}
if (!file.isDirectory()) {
throw Py.OSError(Errno.ENOTDIR, path);
}
if (!file.canRead()) {
throw Py.OSError(Errno.EACCES, path);
}
throw Py.OSError("listdir(): an unknown error occurred: " + path);
}
PyList list = new PyList();
for (String name : names) {
list.append(Py.newUnicode(name));
}
return list;
}
@ExposedFunction(doc = BuiltinDocs.posix_scandir_doc)
public static PyObject scandir(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("listdir", args, keywords, "path");
String path = ap.getString(0, System.getProperty("user.home"));
Path p = absolutePath(path);
List<Path> paths = new ArrayList<Path>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {
for (Path f: stream) {
paths.add(f);
}
} catch (NotDirectoryException e) {
throw Py.OSError(Errno.ENOENT, path);
} catch (IOException e) {
throw Py.OSError(Errno.ENOTDIR, path);
} catch (SecurityException e) {
throw Py.OSError(Errno.EACCES, path);
}
return new PyScandirIterator(paths.iterator());
}
@ExposedFunction(doc = BuiltinDocs.posix_lseek_doc)
public static long lseek(PyObject fd, long pos, int how) {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
try {
return ((RawIOBase) javaobj).seek(pos, how);
} catch (PyException pye) {
throw badFD();
}
} else {
return posix.lseek(getFD(fd).getIntFD(), pos, how);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_mkfifo_doc)
public static void mkfifo(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("mkfifo", args, keywords, "path", "mode", "*", "dir_fd");
PyObject dir_fd = ap.getPyObject(3, Py.None);
if (dir_fd != Py.None) {
throw Py.NotImplementedError("dir_fd is not supported");
}
String path = ap.getString(0);
int mode = ap.getInt(1, 438);
posix.mkfifo(path, mode);
}
@ExposedFunction(doc = BuiltinDocs.posix_mknod_doc)
public static void mknod(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("mknod", args, keywords, "path", "mode", "device", "*", "dir_fd");
PyObject dir_fd = ap.getPyObject(4, Py.None);
if (dir_fd != Py.None) {
throw Py.NotImplementedError("dir_fd is not supported");
}
}
@ExposedFunction(doc = BuiltinDocs.posix_mkdir_doc, defaults = {"0777"})
public static void mkdir(PyObject path, int mode) {
if (os == OS.NT) {
try {
Path nioPath = absolutePath(path);
// Windows does not use any mode attributes in creating a directory;
// see the corresponding function in posixmodule.c, posix_mkdir;
Files.createDirectory(nioPath);
} catch (FileAlreadyExistsException ex) {
throw Py.OSError(Errno.EEXIST, path);
} catch (IOException ioe) {
throw Py.OSError(ioe);
} catch (SecurityException ex) {
throw Py.OSError(Errno.EACCES, path);
}
// Further work on mapping mode to PosixAttributes would have to be done
// for non Windows platforms. In addition, posix.mkdir would still be necessary
// for mode bits like stat.S_ISGID
} else if (posix.mkdir(absolutePath(path).toString(), mode) < 0) {
throw errorFromErrno(path);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_open_doc, defaults = {"0777"})
public static PyObject open(PyObject path, int flag, int mode) {
Path p = absolutePath(path);
File file = p.toFile();
boolean reading = (flag & O_RDONLY) != 0;
boolean writing = (flag & O_WRONLY) != 0;
boolean updating = (flag & O_RDWR) != 0;
boolean creating = (flag & O_CREAT) != 0;
boolean appending = (flag & O_APPEND) != 0;
boolean truncating = (flag & O_TRUNC) != 0;
boolean exclusive = (flag & O_EXCL) != 0;
boolean sync = (flag & O_SYNC) != 0;
if (updating && writing) {
throw Py.OSError(Errno.EINVAL, path);
}
if (!creating && !file.exists()) {
throw Py.OSError(Errno.ENOENT, path);
}
if (!writing) {
if (updating) {
writing = true;
} else {
reading = true;
}
}
if (truncating && !writing) {
// Explicitly truncate, writing will truncate anyway
new FileIO((PyUnicode) path, "w").close();
}
if (exclusive && creating) {
try {
if (!file.createNewFile()) {
throw Py.OSError(Errno.EEXIST, path);
}
} catch (IOException ioe) {
throw Py.OSError(ioe);
}
}
String fileIOMode = (reading ? "r" : "") + (!appending && writing ? "w" : "")
+ (appending && (writing || updating) ? "a" : "") + (updating ? "+" : "");
FileIO res;
if (sync && (writing || updating)) {
try {
res = new FileIO(new RandomAccessFile(file, "rws").getChannel(), fileIOMode);
} catch (IOException e) {
throw Py.IOError(e);
}
} else {
res = new FileIO((PyUnicode) path, fileIOMode);
}
return new PyFileIO(res, new OpenMode(fileIOMode));
}
// XXX handle IOException
@ExposedFunction(doc = BuiltinDocs.posix_pipe_doc)
public static PyObject pipe() throws IOException {
// This is ideal solution, but we need a wrapper in java to read and write into,
// or else when this file descriptor is passed back to java, we cannot handle it
// int[] fds = new int[2];
// int rc = posix.pipe(fds); // XXX check rc
// return new PyTuple(new PyLong(fds[0]), new PyLong(fds[1]));
final Pipe pipe = Pipe.open();
final ReadableByteChannel readChan = pipe.source();
RawIOBase read = new RawIOBase() {
@Override
public Channel getChannel() {
return readChan;
}
@Override
public boolean readable() {
return true;
}
@Override
public long seek(long pos, int whence) {
return -1;
}
@Override
public int readinto(ByteBuffer buf) {
try {
return readChan.read(buf);
} catch (IOException e) {
return -1;
}
}
};
RawIOBase write = new RawIOBase() {
@Override
public Channel getChannel() {
return pipe.sink();
}
@Override
public boolean writable() {
return true;
}
};
return new PyTuple(new PyFileIO(read, OpenMode.R_ONLY), new PyFileIO(write, OpenMode.W_ONLY));
}
@ExposedFunction(doc = BuiltinDocs.posix_putenv_doc)
public static void putenv(String key, String value) {
posix.setenv(key, value, 1);
}
@ExposedFunction(doc = BuiltinDocs.posix_read_doc)
public static PyObject read(PyObject fd, int buffersize) {
if (fd instanceof PyFileIO) {
RawIOBase readable = ((PyFileIO) fd).getRawIO();
return new PyBytes(readable.read(buffersize));
} else {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
try {
return new PyBytes(((RawIOBase) javaobj).read(buffersize));
} catch (PyException pye) {
throw badFD();
}
} else {
// FIXME: this is broken
ByteBuffer buffer = ByteBuffer.allocate(buffersize);
posix.read(getFD(fd).getIntFD(), buffer, buffersize);
return new PyBytes(buffer);
}
}
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_readlink_doc)
public static PyUnicode readlink(PyObject path) {
try {
return Py.newUnicode(Files.readSymbolicLink(absolutePath(path)).toString());
} catch (NotLinkException ex) {
throw Py.OSError(Errno.EINVAL, path);
} catch (NoSuchFileException ex) {
throw Py.OSError(Errno.ENOENT, path);
} catch (IOException ioe) {
throw Py.OSError(ioe);
} catch (SecurityException ex) {
throw Py.OSError(Errno.EACCES, path);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_remove_doc)
public static void remove(PyObject path) {
unlink(path);
}
@ExposedFunction(doc = BuiltinDocs.posix_rename_doc)
public static void rename(PyObject oldpath, PyObject newpath) {
if (!(absolutePath(oldpath).toFile().renameTo(absolutePath(newpath).toFile()))) {
PyObject args = new PyTuple(Py.Zero, new PyBytes("Couldn't rename file"));
throw new PyException(Py.OSError, args);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_rmdir_doc)
public static void rmdir(PyObject path) {
File file = absolutePath(path).toFile();
if (!file.exists()) {
throw Py.OSError(Errno.ENOENT, path);
} else if (!file.isDirectory()) {
throw Py.OSError(Errno.ENOTDIR, path);
} else if (!file.delete()) {
PyObject args = new PyTuple(Py.Zero, new PyBytes("Couldn't delete directory"),
path);
throw new PyException(Py.OSError, args);
}
}
@ExposedFunction(doc = BuiltinDocs.posix_setpgrp_doc)
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
public static void setpgrp() {
if (posix.setpgrp(0, 0) < 0) {
throw errorFromErrno();
}
}
@ExposedFunction(doc = BuiltinDocs.posix_setsid_doc)
@Hide(value=OS.NT, posixImpl = PosixImpl.JAVA)
public static void setsid() {
if (posix.setsid() < 0) {
throw errorFromErrno();
}
}
@ExposedFunction(doc = BuiltinDocs.posix_strerror_doc)
public static PyObject strerror(int code) {
Constant errno = Errno.valueOf(code);
if (errno == Errno.__UNKNOWN_CONSTANT__) {
return new PyBytes("Unknown error: " + code);
}
if (errno.name() == errno.toString()) {
// Fake constant or just lacks a description, fallback to Linux's
// XXX: have jnr-constants handle this fallback
errno = Enum.valueOf(jnr.constants.platform.linux.Errno.class,
errno.name());
}
return new PyBytes(errno.toString());
}
@Hide(OS.NT)
@ExposedFunction(doc = BuiltinDocs.posix_symlink_doc)
public static void symlink(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("symlink", args, keywords, "src", "dst", "target_is_directory", "*", "dir_fd");
String src = ap.getString(0);
String dst = ap.getString(1);
boolean isDirectory = ap.getPyObject(2, Py.False).__bool__();
PyObject dir_fd = ap.getPyObject(4, Py.None);
if (dir_fd != Py.None) {
throw Py.NotImplementedError("dir_fd is not supported");
}
try {
Files.createSymbolicLink(Paths.get(dst), Paths.get(src));
} catch (FileAlreadyExistsException ex) {
throw Py.OSError(Errno.EEXIST);
} catch (IOException ioe) {
throw Py.OSError(ioe);