-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathPosixShim.java
More file actions
707 lines (602 loc) · 23.5 KB
/
PosixShim.java
File metadata and controls
707 lines (602 loc) · 23.5 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
package org.jruby.util.io;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileLock;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.OverlappingFileLockException;
import java.nio.channels.Pipe;
import jnr.constants.platform.Errno;
import jnr.constants.platform.Fcntl;
import jnr.posix.FileStat;
import jnr.posix.POSIX;
import org.jruby.Ruby;
import org.jruby.ext.fcntl.FcntlLibrary;
import org.jruby.platform.Platform;
import org.jruby.runtime.Helpers;
import org.jruby.util.JRubyFile;
import org.jruby.util.ResourceException;
/**
* Representations of as many native posix functions as possible applied to an NIO channel
*/
public class PosixShim {
public static final int LOCK_SH = 1;
public static final int LOCK_EX = 2;
public static final int LOCK_NB = 4;
public static final int LOCK_UN = 8;
public static final int SEEK_SET = 0;
public static final int SEEK_CUR = 1;
public static final int SEEK_END = 2;
public PosixShim(Ruby runtime) {
this.runtime = runtime;
this.posix = runtime.getPosix();
}
// pseudo lseek(2)
public long lseek(ChannelFD fd, long offset, int type) {
clear();
if (fd.chSeek != null) {
int adj = 0;
try {
switch (type) {
case SEEK_SET:
return fd.chSeek.position(offset).position();
case SEEK_CUR:
return fd.chSeek.position(fd.chSeek.position() - adj + offset).position();
case SEEK_END:
return fd.chSeek.position(fd.chSeek.size() + offset).position();
default:
setErrno(Errno.EINVAL);
return -1;
}
} catch (IllegalArgumentException e) {
setErrno(Errno.EINVAL);
return -1;
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
}
} else if (fd.chNative != null) {
// native channel, use native lseek
long ret = posix.lseekLong(fd.chNative.getFD(), offset, type);
if (ret == -1) setErrno(Errno.valueOf(posix.errno()));
return ret;
}
if (fd.chSelect != null) {
// For other channel types, we can't get at a native descriptor to lseek, and we can't use FileChannel
// .position, so we have to treat them as unseekable and raise EPIPE
//
// TODO: It's perhaps just a coincidence that all the channels for
// which we should raise are instanceof SelectableChannel, since
// stdio is not...so this bothers me slightly. -CON
//
// Original change made in 66b024fedbb2ee32316ccd9de8387931d07993ec
setErrno(Errno.EPIPE);
return -1;
}
return 0;
}
public int write(ChannelFD fd, byte[] bytes, int offset, int length, boolean nonblock) {
// FIXME: don't allocate every time
ByteBuffer tmp = ByteBuffer.wrap(bytes, offset, length);
return write(fd, tmp, offset, length, nonblock);
}
public int write(ChannelFD fd, ByteBuffer buffer, int offset, int length, boolean nonblock) {
clear();
try {
if (nonblock) {
// TODO: figure out what nonblocking writes against atypical streams (files?) actually do
// If we can't set the channel nonblocking, I'm not sure what we can do to
// pretend the channel is nonblocking.
}
if (fd.chWrite == null) {
setErrno(Errno.EACCES);
return -1;
}
int written = fd.chWrite.write(buffer);
if (written == 0 && length > 0) {
// if it's a nonblocking write against a file and we've hit EOF, do EAGAIN
if (nonblock) {
setErrno(Errno.EAGAIN);
return -1;
}
}
return written;
} catch (Exception e) {
setErrno(Helpers.errnoFromException(e));
error = e;
return -1;
}
}
private static final int NATIVE_EOF = 0;
private static final int JAVA_EOF = -1;
public int read(ChannelFD fd, byte[] target, int offset, int length, boolean nonblock) {
clear();
try {
if (checkForBlocking(fd, nonblock)) return -1;
// FIXME: inefficient to recreate ByteBuffer every time
ByteBuffer buffer = ByteBuffer.wrap(target, offset, length);
return performRead(fd, buffer, nonblock);
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
}
}
public int read(ChannelFD fd, ByteBuffer buffer, int offset, int length, boolean nonblock) {
clear();
try {
if (checkForBlocking(fd, nonblock)) return -1;
buffer.position(offset);
buffer.limit(offset + length);
return performRead(fd, buffer, nonblock);
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
}
}
private int performRead(ChannelFD fd, ByteBuffer buffer, boolean nonblock) throws IOException {
int read = fd.chRead.read(buffer);
if (nonblock) {
if (read == JAVA_EOF) {
read = NATIVE_EOF; // still treat EOF as EOF
} else if (read == 0) {
setErrno(Errno.EAGAIN);
return -1;
} else {
return read;
}
} else {
// NIO channels will always raise for errors, so -1 only means EOF.
if (read == JAVA_EOF) read = NATIVE_EOF;
}
return read;
}
private boolean checkForBlocking(ChannelFD fd, boolean nonblock) throws IOException {
if (nonblock) {
// need to ensure channels that don't support nonblocking IO at least
// appear to be nonblocking
if (fd.chSelect != null) {
// ok...we should have set it nonblocking already in setNonblock
} else {
if (fd.chFile != null) {
long position = fd.chFile.position();
long size = fd.chFile.size();
if (position != -1 && size != -1 && position < size) {
// there should be bytes available...proceed
} else {
setErrno(Errno.EAGAIN);
return true;
}
} else if (fd.chNative != null && fd.isNativeFile) {
// it's a native file, so we don't do selection or nonblock
} else {
setErrno(Errno.EAGAIN);
return true;
}
}
}
return false;
}
// rb_thread_flock
public int flock(ChannelFD fd, int lockMode) {
// TODO: null channel always succeeds for all locking operations
// if (descriptor.isNull()) return RubyFixnum.zero(runtime);
clear();
int real_fd = fd.realFileno;
if (!Platform.IS_SOLARIS && !Platform.IS_WINDOWS &&
posix.isNative() && real_fd != -1 && real_fd < FilenoUtil.FIRST_FAKE_FD) {
// we have a real fd and not on Solaris...try native flocking
// see jruby/jruby#3254 and jnr/jnr-posix#60
int result = posix.flock(real_fd, lockMode);
if (result < 0) {
setErrno(Errno.valueOf(posix.errno()));
return -1;
}
return 0;
}
if (fd.chFile != null) {
int ret = checkSharedExclusive(fd, lockMode);
if (ret < 0) return ret;
if (!lockStateChanges(fd.currentLock.get(), lockMode)) return 0;
try {
synchronized (fd.chFile) {
// check again, to avoid unnecessary overhead
if (!lockStateChanges(fd.currentLock.get(), lockMode)) return 0;
switch (lockMode) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
return unlock(fd);
case LOCK_EX:
return lock(fd, true);
case LOCK_EX | LOCK_NB:
return tryLock(fd, true);
case LOCK_SH:
return lock(fd, false);
case LOCK_SH | LOCK_NB:
return tryLock(fd, false);
}
}
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
} catch (OverlappingFileLockException ioe) {
setErrno(Errno.EINVAL);
errmsg = "overlapping file locks";
}
return lockFailedReturn(lockMode);
} else {
// We're not actually a real file, so we can't flock
// FIXME: This needs to be ENOTSUP
setErrno(Errno.EINVAL);
errmsg = "stream is not a file";
return -1;
}
}
public int dup2(ChannelFD filedes, ChannelFD filedes2) {
return filedes2.dup2From(posix, filedes);
}
public int close(ChannelFD fd) {
return close((Closeable)fd);
}
public int close(Closeable closeable) {
clear();
try {
closeable.close();
return 0;
} catch (IOException ioe) {
Errno errno = Helpers.errnoFromException(ioe);
if (errno == null) {
throw new RuntimeException("unknown IOException: " + ioe);
}
this.setErrno(errno);
return -1;
}
}
public Channel[] pipe() {
clear();
try {
Pipe pipe = Pipe.open();
Channel source = pipe.source(), sink = pipe.sink();
if (posix.isNative() && !Platform.IS_WINDOWS) {
// set cloexec if possible
int read = FilenoUtil.filenoFrom(source);
int write = FilenoUtil.filenoFrom(sink);
setCloexec(read, true);
setCloexec(write, true);
}
return new Channel[]{source, sink};
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return null;
}
}
/**
* The appropriate errno value for the last thrown error, if any.
*/
public Errno getErrno() {
return errno.get();
}
public void setErrno(Errno errno) {
this.errno.set(errno);
}
public interface WaitMacros {
public abstract boolean WIFEXITED(long status);
public abstract boolean WIFSIGNALED(long status);
public abstract int WTERMSIG(long status);
public abstract int WEXITSTATUS(long status);
public abstract int WSTOPSIG(long status);
public abstract boolean WIFSTOPPED(long status);
public abstract boolean WCOREDUMP(long status);
}
public static class BSDWaitMacros implements WaitMacros {
public final long _WSTOPPED = 0177;
// Only confirmed on Darwin
public final long WCOREFLAG = 0200;
public long _WSTATUS(long status) {
return status & _WSTOPPED;
}
public boolean WIFEXITED(long status) {
return _WSTATUS(status) == 0;
}
public boolean WIFSIGNALED(long status) {
return _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0;
}
public int WTERMSIG(long status) {
return (int)_WSTATUS(status);
}
public int WEXITSTATUS(long status) {
// not confirmed on all platforms
return (int)((status >>> 8) & 0xFF);
}
public int WSTOPSIG(long status) {
return (int)(status >>> 8);
}
public boolean WIFSTOPPED(long status) {
return _WSTATUS(status) == _WSTOPPED && WSTOPSIG(status) != 0x13;
}
public boolean WCOREDUMP(long status) {
return (status & WCOREFLAG) != 0;
}
}
public static class LinuxWaitMacros implements WaitMacros {
private int __WAIT_INT(long status) { return (int)status; }
private int __W_EXITCODE(int ret, int sig) { return (ret << 8) | sig; }
private int __W_STOPCODE(int sig) { return (sig << 8) | 0x7f; }
private static int __W_CONTINUED = 0xffff;
private static final int __WCOREFLAG = 0x80;
/* If WIFEXITED(STATUS), the low-order 8 bits of the status. */
private int __WEXITSTATUS(long status) { return (int)((status & 0xff00) >> 8); }
/* If WIFSIGNALED(STATUS), the terminating signal. */
private int __WTERMSIG(long status) { return (int)(status & 0x7f); }
/* If WIFSTOPPED(STATUS), the signal that stopped the child. */
private int __WSTOPSIG(long status) { return __WEXITSTATUS(status); }
/* Nonzero if STATUS indicates normal termination. */
private boolean __WIFEXITED(long status) { return __WTERMSIG(status) == 0; }
/* Nonzero if STATUS indicates termination by a signal. */
private boolean __WIFSIGNALED(long status) {
return ((status & 0x7f) + 1) >> 1 > 0;
}
/* Nonzero if STATUS indicates the child is stopped. */
private boolean __WIFSTOPPED(long status) { return (status & 0xff) == 0x7f; }
/* Nonzero if STATUS indicates the child dumped core. */
private boolean __WCOREDUMP(long status) { return (status & __WCOREFLAG) != 0; }
/* Macros for constructing status values. */
public int WEXITSTATUS(long status) { return __WEXITSTATUS (__WAIT_INT (status)); }
public int WTERMSIG(long status) { return __WTERMSIG(__WAIT_INT(status)); }
public int WSTOPSIG(long status) { return __WSTOPSIG(__WAIT_INT(status)); }
public boolean WIFEXITED(long status) { return __WIFEXITED(__WAIT_INT(status)); }
public boolean WIFSIGNALED(long status) { return __WIFSIGNALED(__WAIT_INT(status)); }
public boolean WIFSTOPPED(long status) { return __WIFSTOPPED(__WAIT_INT(status)); }
public boolean WCOREDUMP(long status) { return __WCOREDUMP(__WAIT_INT(status)); }
}
public static final WaitMacros WAIT_MACROS;
static {
if (Platform.IS_BSD) {
WAIT_MACROS = new BSDWaitMacros();
} else {
// need other platforms
WAIT_MACROS = new LinuxWaitMacros();
}
}
public int setCloexec(int fd, boolean cloexec) {
int ret = posix.fcntl(fd, Fcntl.F_GETFD);
if (ret == -1) {
setErrno(Errno.valueOf(posix.errno()));
return -1;
}
if (
(cloexec && (ret & FcntlLibrary.FD_CLOEXEC) == FcntlLibrary.FD_CLOEXEC)
|| (!cloexec && (ret & FcntlLibrary.FD_CLOEXEC) == 0)) {
return 0;
}
ret = cloexec ?
ret | FcntlLibrary.FD_CLOEXEC :
ret & ~FcntlLibrary.FD_CLOEXEC;
ret = posix.fcntlInt(fd, Fcntl.F_SETFD, ret);
if (ret == -1) setErrno(Errno.valueOf(posix.errno()));
return ret;
}
public int fcntlSetFD(int fd, int flags) {
int ret = posix.fcntlInt(fd, Fcntl.F_SETFD, flags);
if (ret == -1) setErrno(Errno.valueOf(posix.errno()));
return ret;
}
public int fcntlGetFD(int fd) {
int ret = posix.fcntl(fd, Fcntl.F_GETFD);
if (ret == -1) {
setErrno(Errno.valueOf(posix.errno()));
}
return ret;
}
public Channel open(String cwd, String path, int flags, int perm) {
if (Platform.IS_WINDOWS && (path.equals("/dev/null") || path.equalsIgnoreCase("nul"))) {
path = "NUL:";
}
try {
return JRubyFile.createResource(runtime, cwd, path).openChannel(flags, perm);
} catch (ResourceException.FileExists e) {
setErrno(Errno.EEXIST);
} catch (ResourceException.FileIsDirectory e) {
setErrno(Errno.EISDIR);
} catch (ResourceException.FileIsNotDirectory e) {
setErrno(Errno.ENOTDIR);
} catch (ResourceException.NotFound e) {
setErrno(Errno.ENOENT);
} catch (ResourceException.PermissionDenied e) {
setErrno(Errno.EACCES);
} catch (ResourceException.TooManySymlinks e) {
setErrno(Errno.ELOOP);
} catch (ResourceException.ErrnoException e) {
setErrno(e.getErrno());
} catch (ResourceException ex) {
throw ex.newRaiseException(runtime);
} catch (Exception ex) {
Helpers.throwErrorFromException(runtime, ex);
// not reached
}
return null;
}
// no longer used
public Channel open(String cwd, String path, ModeFlags flags, int perm) {
return open(cwd, path, flags.getFlags(), perm);
}
/**
* Joy of POSIX, only way to get the umask is to set the umask,
* then set it back. That's unsafe in a threaded program. We
* minimize but may not totally remove this race by caching the
* obtained or previously set (see umask() above) umask and using
* that as the initial set value which, cross fingers, is a
* no-op. The cache access is then synchronized. TODO: Better?
*/
public static int umask(POSIX posix) {
synchronized (_umaskLock) {
final int umask = posix.umask(_cachedUmask);
if (_cachedUmask != umask ) {
posix.umask(umask);
_cachedUmask = umask;
}
return umask;
}
}
public static int umask(POSIX posix, int newMask) {
int oldMask;
synchronized (_umaskLock) {
oldMask = posix.umask(newMask);
_cachedUmask = newMask;
}
return oldMask;
}
public int ftruncate(ChannelFD fd, long pos) {
if (fd.chNative != null) {
int ret = posix.ftruncate(fd.chNative.getFD(), pos);
if (ret == -1) setErrno(Errno.valueOf(posix.errno()));
return ret;
} else if (fd.chFile != null) {
try {
fd.chFile.truncate(pos);
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
}
} else {
setErrno(Errno.EINVAL);
return -1;
}
return 0;
}
public long size(ChannelFD fd) {
if (fd.chNative != null) { // native fd, use fstat
FileStat stat = posix.allocateStat();
int ret = posix.fstat(fd.chNative.getFD(), stat);
if (ret == -1) {
setErrno(Errno.valueOf(posix.errno()));
return -1;
}
return stat.st_size();
} else if (fd.chSeek != null) { // if it is seekable, get size directly
try {
return fd.chSeek.size();
} catch (IOException ioe) {
setErrno(Helpers.errnoFromException(ioe));
return -1;
}
} else {
// otherwise just return -1 (should be rare, since size is only defined on File
setErrno(Errno.EINVAL);
return -1;
}
}
private void clear() {
setErrno(null);
errmsg = null;
}
private int checkSharedExclusive(ChannelFD fd, int lockMode) {
// This logic used to attempt a shared lock instead of an exclusive
// lock, because LOCK_EX on some systems (as reported in JRUBY-1214)
// allow exclusively locking a read-only file. However, the JDK
// APIs do not allow acquiring an exclusive lock on files that are
// not open for read, and there are other platforms (such as Solaris,
// see JRUBY-5627) that refuse at an *OS* level to exclusively lock
// files opened only for read. As a result, this behavior is platform-
// dependent, and so we will obey the JDK's policy of disallowing
// exclusive locks on files opened only for read.
if (fd.chWrite == null && (lockMode & LOCK_EX) > 0) {
setErrno(Errno.EINVAL);
errmsg = "cannot acquire exclusive lock on File not opened for write";
return -1;
}
// Likewise, JDK does not allow acquiring a shared lock on files
// that have not been opened for read. We comply here.
if (fd.chRead == null && (lockMode & LOCK_SH) > 0) {
setErrno(Errno.EINVAL);
errmsg = "cannot acquire shared lock on File not opened for read";
return -1;
}
return 0;
}
private static int lockFailedReturn(int lockMode) {
return (lockMode & LOCK_EX) == 0 ? 0 : -1;
}
private static boolean lockStateChanges(FileLock lock, int lockMode) {
if (lock == null) {
// no lock, only proceed if we are acquiring
switch (lockMode & 0xF) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
return false;
default:
return true;
}
} else {
// existing lock, only proceed if we are unlocking or changing
switch (lockMode & 0xF) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
return true;
case LOCK_EX:
case LOCK_EX | LOCK_NB:
return lock.isShared();
case LOCK_SH:
case LOCK_SH | LOCK_NB:
return !lock.isShared();
default:
return false;
}
}
}
private int unlock(ChannelFD fd) throws IOException {
FileLock fileLock = fd.currentLock.get();
if (fileLock != null) {
fileLock.release();
fd.currentLock.remove();
return 0;
}
return -1;
}
private int lock(ChannelFD fd, boolean exclusive) throws IOException {
FileLock fileLock = fd.currentLock.get();
if (fileLock != null) fileLock.release();
fileLock = fd.chFile.lock(0L, Long.MAX_VALUE, !exclusive);
fd.currentLock.set(fileLock);
if (fileLock != null) {
return 0;
}
return lockFailedReturn(exclusive ? LOCK_EX : LOCK_SH);
}
private int tryLock(ChannelFD fd, boolean exclusive) throws IOException {
FileLock fileLock = fd.currentLock.get();
if (fileLock != null) fileLock.release();
fileLock = fd.chFile.tryLock(0L, Long.MAX_VALUE, !exclusive);
fd.currentLock.set(fileLock);
if (fileLock != null) {
return 0;
}
return lockFailedReturn(exclusive ? LOCK_EX : LOCK_SH);
}
/**
* The last Throwable exception raised by a call.
*/
public Throwable error;
private final ThreadLocal<Errno> errno = new ThreadLocal<>();
/**
* The recommended error message, if any.
*/
public String errmsg;
/**
* The POSIX instance to use for native calls
*/
private final POSIX posix;
/**
* The current runtime
*/
private final Ruby runtime;
/**
* An object to synchronize calls to umask
*/
private static final Object _umaskLock = new Object();
/**
* The last umask we set
*/
private static int _cachedUmask = 0;
}