-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathPosixModule.java
More file actions
1590 lines (1438 loc) · 59.3 KB
/
PosixModule.java
File metadata and controls
1590 lines (1438 loc) · 59.3 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 java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
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.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotLinkException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
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.POSIXHandler;
import jnr.posix.Times;
import jnr.posix.WindowsRawFileStat;
import jnr.posix.util.FieldAccess;
import jnr.posix.windows.CommonFileInformation;
import org.python.core.BufferProtocol;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyBUF;
import org.python.core.PyBuffer;
import org.python.core.PyBuiltinFunctionNarrow;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyFile;
import org.python.core.PyFloat;
import org.python.core.PyJavaType;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.core.PyTuple;
import org.python.core.PyUnicode;
import org.python.core.Untraversable;
import org.python.core.imp;
import org.python.core.io.FileIO;
import org.python.core.io.IOBase;
import org.python.core.io.RawIOBase;
import org.python.core.io.StreamIO;
import org.python.core.util.StringUtil;
/**
* The posix/nt module, depending on the platform.
*/
public class PosixModule implements ClassDictInit {
public static final PyString __doc__ = new PyString(
"This module provides access to operating system functionality that is\n" +
"standardized by the C Standard and the POSIX standard (a thinly\n" +
"disguised Unix interface). Refer to the library manual and\n" +
"corresponding Unix manual entries for more information on calls.");
/** Current OS information. */
private static final OS os = OS.getOS();
/** Platform specific POSIX services. */
private static final POSIXHandler posixHandler = new PythonPOSIXHandler();
private static final POSIX posix = POSIXFactory.getPOSIX(posixHandler, true);
/** os.open flags. */
private static final int O_RDONLY = 0x0;
private static final int O_WRONLY = 0x1;
private static final int O_RDWR = 0x2;
private static final int O_APPEND = 0x8;
private static final int O_SYNC = 0x80;
private static final int O_CREAT = 0x200;
private static final int O_TRUNC = 0x400;
private static final int O_EXCL = 0x800;
/** os.access constants. */
private static final int F_OK = 0;
private static final int X_OK = 1 << 0;
private static final int W_OK = 1 << 1;
private static final int R_OK = 1 << 2;
/** Lazily initialized singleton source for urandom. */
private static class UrandomSource {
static final SecureRandom INSTANCE = new SecureRandom();
}
public static void classDictInit(PyObject dict) {
// only expose the open flags we support
dict.__setitem__("O_RDONLY", Py.newInteger(O_RDONLY));
dict.__setitem__("O_WRONLY", Py.newInteger(O_WRONLY));
dict.__setitem__("O_RDWR", Py.newInteger(O_RDWR));
dict.__setitem__("O_APPEND", Py.newInteger(O_APPEND));
dict.__setitem__("O_SYNC", Py.newInteger(O_SYNC));
dict.__setitem__("O_CREAT", Py.newInteger(O_CREAT));
dict.__setitem__("O_TRUNC", Py.newInteger(O_TRUNC));
dict.__setitem__("O_EXCL", Py.newInteger(O_EXCL));
// os.access flags
dict.__setitem__("F_OK", Py.newInteger(F_OK));
dict.__setitem__("X_OK", Py.newInteger(X_OK));
dict.__setitem__("W_OK", Py.newInteger(W_OK));
dict.__setitem__("R_OK", Py.newInteger(R_OK));
// Successful termination
dict.__setitem__("EX_OK", Py.Zero);
// 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);
dict.__setitem__("classDictInit", null);
dict.__setitem__("__init__", null);
dict.__setitem__("getPOSIX", null);
dict.__setitem__("getOSName", null);
dict.__setitem__("badFD", null);
// Hide __doc__s
PyList keys = (PyList)dict.invoke("keys");
for (Iterator<?> it = keys.listIterator(); it.hasNext();) {
String key = (String)it.next();
if (key.startsWith("__doc__")) {
it.remove();
dict.__setitem__(key, null);
}
}
dict.__setitem__("__all__", keys);
dict.__setitem__("__name__", new PyString(os.getModuleName()));
dict.__setitem__("__doc__", __doc__);
}
// Combine Java FileDescriptor objects with Posix int file descriptors in one representation.
// Unfortunate ugliness!
private 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;
}
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 + ")";
}
}
private static FDUnion getFD(PyObject fdObj) {
if (fdObj.isInteger()) {
int intFd = fdObj.asInt();
switch (intFd) {
case -1:
break;
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());
}
throw Py.TypeError("an integer or Java/Jython file descriptor is required");
}
public static PyString __doc___exit = new PyString(
"_exit(status)\n\n" +
"Exit to the system with specified status, without normal exit processing.");
public static void _exit() {
_exit(0);
}
public static void _exit(int status) {
System.exit(status);
}
public static PyString __doc__access = new PyString(
"access(path, mode) -> True if granted, False otherwise\n\n" +
"Use the real uid/gid to test for access to a path. Note that most\n" +
"operations will use the effective uid/gid, therefore this routine can\n" +
"be used in a suid/sgid environment to test if the invoking user has the\n" +
"specified access to the path. The mode argument can be F_OK to test\n" +
"existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
public static boolean access(PyObject path, int mode) {
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;
}
public static PyString __doc__chdir = new PyString(
"chdir(path)\n\n" +
"Change the current working directory to the specified path.");
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);
}
}
}
public static PyString __doc__chmod = new PyString(
"chmod(path, mode)\n\n" +
"Change the access permissions of a file.");
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.isDirectory() && !f.setWritable(writable)) {
// The read-only flag of directories means "don't delete" not "you can't write"
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);
}
}
public static PyString __doc__chown = new PyString(
"chown(path, uid, gid)\n\n" +
"Change the owner and group id of path to the numeric uid and gid.");
@Hider.Hide(OS.NT)
public static void chown(PyObject path, int uid, int gid) {
if (posix.chown(absolutePath(path).toString(), uid, gid) < 0) {
throw errorFromErrno(path);
}
}
public static PyString __doc__close = new PyString(
"close(fd)\n\n" +
"Close a file descriptor (for low level IO).");
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());
}
}
@Hider.Hide(OS.NT)
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.newInteger(posix.dup(getFD(fd1).getIntFD()));
// }
//
// public static PyObject dup2(PyObject fd1, PyObject fd2) {
// return Py.newInteger(posix.dup2(getFD(fd1).getIntFD(), getFD(fd2).getIntFD()));
// }
public static PyString __doc__fdopen = new PyString(
"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);
}
}
public static PyString __doc__fdatasync = new PyString(
"fdatasync(fildes)\n\n" +
"force write of file with filedescriptor to disk.\n" +
"does not force update of metadata.");
@Hider.Hide(OS.NT)
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());
}
}
public static PyString __doc__fsync = new PyString(
"fsync(fildes)\n\n" +
"force write of file with filedescriptor to disk.");
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);
}
}
public static PyString __doc__ftruncate = new PyString(
"ftruncate(fd, length)\n\n" +
"Truncate a file to a specified length.");
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);
}
}
public static PyString __doc__getcwd = new PyString(
"getcwd() -> path\n\n" +
"Return a string representing the current working directory.");
public static PyObject getcwd() {
// The return value is bytes in the file system encoding
return Py.fileSystemEncode(Py.getSystemState().getCurrentWorkingDir());
}
public static PyString __doc__getcwdu = new PyString(
"getcwd() -> path\n\n" +
"Return a unicode string representing the current working directory.");
public static PyObject getcwdu() {
return Py.newUnicode(Py.getSystemState().getCurrentWorkingDir());
}
public static PyString __doc__getegid = new PyString(
"getegid() -> egid\n\n" +
"Return the current process's effective group id.");
@Hider.Hide(OS.NT)
public static int getegid() {
return posix.getegid();
}
public static PyString __doc__geteuid = new PyString(
"geteuid() -> euid\n\n" +
"Return the current process's effective user id.");
@Hider.Hide(OS.NT)
public static int geteuid() {
return posix.geteuid();
}
public static PyString __doc__getgid = new PyString(
"getgid() -> gid\n\n" +
"Return the current process's group id.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static int getgid() {
return posix.getgid();
}
public static PyString __doc__getlogin = new PyString(
"getlogin() -> string\n\n" +
"Return the actual login name.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static PyObject getlogin() {
String login = posix.getlogin();
if (login == null) {
// recommend according to https://docs.python.org/2/library/os.html#os.getlogin
throw Py.OSError(
"getlogin OS call failed. Preferentially use os.getenv('LOGNAME') instead.");
}
return new PyString(login);
}
public static PyString __doc__getppid = new PyString(
"getppid() -> ppid\n\n" +
"Return the parent's process id.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static int getppid() {
return posix.getppid();
}
public static PyString __doc__getuid = new PyString(
"getuid() -> uid\n\n" +
"Return the current process's user id.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static int getuid() {
return posix.getuid();
}
public static PyString __doc__getpid = new PyString(
"getpid() -> pid\n\n" +
"Return the current process id");
@Hider.Hide(posixImpl = Hider.PosixImpl.JAVA)
public static int getpid() {
return posix.getpid();
}
public static PyString __doc__getpgrp = new PyString(
"getpgrp() -> pgrp\n\n" +
"Return the current process group id.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static int getpgrp() {
return posix.getpgrp();
}
public static PyString __doc__isatty = new PyString(
"isatty(fd) -> bool\n\n" +
"Return True if the file descriptor 'fd' is an open file descriptor\n" +
"connected to the slave end of a terminal.");
@Hider.Hide(posixImpl = Hider.PosixImpl.JAVA)
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)");
}
public static PyString __doc__kill = new PyString(
"kill(pid, sig)\n\n" +
"Kill a process with a signal.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static void kill(int pid, int sig) {
if (posix.kill(pid, sig) < 0) {
throw errorFromErrno();
}
}
public static PyString __doc__lchmod = new PyString(
"lchmod(path, mode)\n\n" +
"Change the access permissions of a file. If path is a symlink, this\n" +
"affects the link itself rather than the target.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static void lchmod(PyObject path, int mode) {
if (posix.lchmod(absolutePath(path).toString(), mode) < 0) {
throw errorFromErrno(path);
}
}
public static PyString __doc__lchown = new PyString(
"lchown(path, uid, gid)\n\n" +
"Change the owner and group id of path to the numeric uid and gid.\n" +
"This function will not follow symbolic links.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static void lchown(PyObject path, int uid, int gid) {
if (posix.lchown(absolutePath(path).toString(), uid, gid) < 0) {
throw errorFromErrno(path);
}
}
public static PyString __doc__link = new PyString(
"link(src, dst)\n\n" +
"Create a hard link to a file.");
@Hider.Hide(OS.NT)
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);
}
}
public static PyString __doc__listdir = new PyString(
"listdir(path) -> list_of_strings\n\n" +
"Return a list containing the names of the entries in the directory.\n\n" +
"path: path of directory to list\n\n" +
"The list is in arbitrary order. It does not include the special\n" +
"entries '.' and '..' even if they are present in the directory.");
public static PyList listdir(PyObject path) {
File file = absolutePath(path).toFile();
String[] names = file.list();
if (names == null) {
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);
}
// Return names as bytes or unicode according to the type of the original argument
PyList list = new PyList();
if (path instanceof PyUnicode) {
for (String name : names) {
list.append(Py.newUnicode(name));
}
} else {
for (String name : names) {
list.append(Py.fileSystemEncode(name));
}
}
return list;
}
public static PyString __doc__lseek = new PyString(
"lseek(fd, pos, how) -> newpos\n\n" +
"Set the current position of a file descriptor.");
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);
}
}
public static PyString __doc__mkdir = new PyString(
"mkdir(path [, mode=0777])\n\n" +
"Create a directory.");
public static void mkdir(PyObject path) {
mkdir(path, 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);
}
}
public static PyString __doc__open = new PyString(
"open(filename, flag [, mode=0777]) -> fd\n\n" +
"Open a file (for low level IO).\n\n" +
"Note that the mode argument is not currently supported on Jython.");
public static FileIO open(PyObject path, int flag) {
return open(path, flag, 0777);
}
public static FileIO open(PyObject path, int flag, int mode) {
File file = absolutePath(path).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((PyString) 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 ? "+" : "");
if (sync && (writing || updating)) {
try {
return new FileIO(new RandomAccessFile(file, "rws").getChannel(), fileIOMode);
} catch (FileNotFoundException fnfe) {
throw Py.OSError(file.isDirectory() ? Errno.EISDIR : Errno.ENOENT, path);
}
}
return new FileIO((PyString) path, fileIOMode);
}
public static PyString __doc__pipe = new PyString(
"pipe() -> (read_end, write_end)\n\n" +
"Create a pipe.");
public static PyTuple pipe() {
try {
Pipe pipe = Pipe.open();
StreamIO pipe_read = new StreamIO(pipe.source());
StreamIO pipe_write = new StreamIO(pipe.sink());
return new PyTuple(
PyJavaType.wrapJavaObject(pipe_read.fileno()),
PyJavaType.wrapJavaObject(pipe_write.fileno()));
} catch (IOException ioe) {
throw Py.OSError(ioe);
}
}
public static PyString __doc__popen = new PyString(
"popen(command [, mode='r' [, bufsize]]) -> pipe\n\n" +
"Open a pipe to/from a command returning a file object.");
public static PyObject popen(PyObject[] args, String[] kwds) {
// XXX: popen lives in posix in 2.x, but moves to os in 3.x. It's easier for us to
// keep it in os
// import os; return os.popen(*args, **kwargs)
return imp.load("os").__getattr__("popen").__call__(args, kwds);
}
public static PyString __doc__putenv = new PyString(
"putenv(key, value)\n\n" +
"Change or add an environment variable.");
public static void putenv(String key, String value) {
// XXX: Consider deprecating putenv/unsetenv
// import os; os.environ[key] = value
PyObject environ = imp.load("os").__getattr__("environ");
environ.__setitem__(key, new PyString(value));
}
public static PyString __doc__read = new PyString(
"read(fd, buffersize) -> string\n\n" +
"Read a file descriptor.");
public static PyObject read(PyObject fd, int buffersize) {
Object javaobj = fd.__tojava__(RawIOBase.class);
if (javaobj != Py.NoConversion) {
try {
return new PyString(StringUtil.fromBytes(((RawIOBase) javaobj).read(buffersize)));
} catch (PyException pye) {
throw badFD();
}
} else {
ByteBuffer buffer = ByteBuffer.allocate(buffersize);
posix.read(getFD(fd).getIntFD(), buffer, buffersize);
return new PyString(StringUtil.fromBytes(buffer));
}
}
public static PyString __doc__readlink = new PyString(
"readlink(path) -> path\n\n" +
"Return a string representing the path to which the symbolic link points.");
@Hider.Hide(OS.NT)
public static PyString readlink(PyObject path) {
try {
return Py.newStringOrUnicode(path, 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);
}
}
public static PyString __doc__remove = new PyString(
"remove(path)\n\n" +
"Remove a file (same as unlink(path)).");
public static void remove(PyObject path) {
unlink(path);
}
public static PyString __doc__rename = new PyString(
"rename(old, new)\n\n" +
"Rename a file or directory.");
public static void rename(PyObject oldpath, PyObject newpath) {
if (!(absolutePath(oldpath).toFile().renameTo(absolutePath(newpath).toFile()))) {
PyObject args = new PyTuple(Py.Zero, new PyString("Couldn't rename file"));
throw new PyException(Py.OSError, args);
}
}
public static PyString __doc__rmdir = new PyString(
"rmdir(path)\n\n" +
"Remove a directory.");
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 PyString("Couldn't delete directory"),
path);
throw new PyException(Py.OSError, args);
}
}
public static PyString __doc__setpgrp = new PyString(
"setpgrp()\n\n" +
"Make this process a session leader.");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static void setpgrp() {
if (posix.setpgrp(0, 0) < 0) {
throw errorFromErrno();
}
}
public static PyString __doc__setsid = new PyString(
"setsid()\n\n" +
"Call the system call setsid().");
@Hider.Hide(value=OS.NT, posixImpl = Hider.PosixImpl.JAVA)
public static void setsid() {
if (posix.setsid() < 0) {
throw errorFromErrno();
}
}
public static PyString __doc__strerror = new PyString(
"strerror(code) -> string\n\n" +
"Translate an error code to a message string.");
public static PyObject strerror(int code) {
Constant errno = Errno.valueOf(code);
if (errno == Errno.__UNKNOWN_CONSTANT__) {
return new PyString("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 PyString(errno.toString());
}
public static PyString __doc__symlink = new PyString(
"symlink(src, dst)\n\n" +
"Create a symbolic link pointing to src named dst.");
@Hider.Hide(OS.NT)
public static void symlink(PyObject src, PyObject dst) {
try {
Files.createSymbolicLink(Paths.get(asPath(dst)), Paths.get(asPath(src)));
} catch (FileAlreadyExistsException ex) {
throw Py.OSError(Errno.EEXIST);
} catch (IOException ioe) {
throw Py.OSError(ioe);
} catch (SecurityException ex) {
throw Py.OSError(Errno.EACCES);
}
}
private static PyFloat ratio(long num, long div) {
return Py.newFloat(((double)num)/((double)div));
}
public static PyString __doc__times = new PyString(
"times() -> (utime, stime, cutime, cstime, elapsed_time)\n\n" +
"Return a tuple of floating point numbers indicating process times.");
@Hider.Hide(posixImpl = Hider.PosixImpl.JAVA)
public static PyTuple times() {
Times times = posix.times();
long CLK_TCK = Sysconf._SC_CLK_TCK.longValue();
return new PyTuple(
ratio(times.utime(), CLK_TCK),
ratio(times.stime(), CLK_TCK),
ratio(times.cutime(), CLK_TCK),
ratio(times.cstime(), CLK_TCK),
ratio(ManagementFactory.getRuntimeMXBean().getUptime(), 1000)
);
}
public static PyString __doc__umask = new PyString(
"umask(new_mask) -> old_mask\n\n" +
"Set the current numeric umask and return the previous umask.");
@Hider.Hide(posixImpl = Hider.PosixImpl.JAVA)
public static int umask(int mask) {
return posix.umask(mask);
}
public static PyString __doc__uname = new PyString(
"uname() -> (sysname, nodename, release, version, machine)\n\n" +
"Return a tuple identifying the current operating system.");
/* Obtaining uname values via exec is expensive, so we cache here.
* Cache is placed here near uname, because it is needed exclusively by uname.
*/
private static PyTuple uname_cache = null;
/**