/
RubyIO.java
4961 lines (4185 loc) · 176 KB
/
RubyIO.java
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
/*
**** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2006 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Evan Buswell <ebuswell@gmail.com>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import jnr.constants.platform.Errno;
import jnr.constants.platform.OpenFlags;
import jnr.enxio.channels.NativeDeviceChannel;
import jnr.enxio.channels.NativeSelectableChannel;
import org.jcodings.transcode.EConvFlags;
import org.jruby.runtime.Helpers;
import org.jruby.util.StringSupport;
import org.jruby.util.io.ChannelFD;
import org.jruby.util.io.EncodingUtils;
import static org.jruby.util.io.EncodingUtils.vmodeVperm;
import static org.jruby.util.io.EncodingUtils.vperm;
import org.jruby.util.io.FilenoUtil;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.io.POSIXProcess;
import org.jruby.util.io.PopenExecutor;
import org.jruby.util.io.PosixShim;
import jnr.constants.platform.Fcntl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jcodings.Encoding;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.fcntl.FcntlLibrary;
import org.jruby.platform.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import static org.jruby.runtime.Visibility.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.io.SelectExecutor;
import org.jruby.util.io.IOOptions;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.ShellLauncher;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.STDIO;
import org.jruby.util.io.OpenFile;
import org.jruby.runtime.Arity;
import static org.jruby.RubyEnumerator.enumeratorize;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.internal.runtime.ThreadedRunnable;
import org.jruby.runtime.encoding.EncodingService;
import org.jruby.util.ShellLauncher.POpenProcess;
import org.jruby.util.io.IOEncodable;
/**
*
* @author jpetersen
*/
@JRubyClass(name="IO", include="Enumerable")
public class RubyIO extends RubyObject implements IOEncodable {
// We use a highly uncommon string to represent the paragraph delimiter (100% soln not worth it)
public static final ByteList PARAGRAPH_DELIMETER = ByteList.create("PARAGRPH_DELIM_MRK_ER");
public static final ByteList PARAGRAPH_SEPARATOR = ByteList.create("\n\n");
public static final String CLOSED_STREAM_MSG = "closed stream";
// This should only be called by this and RubyFile.
// It allows this object to be created without a IOHandler.
public RubyIO(Ruby runtime, RubyClass type) {
super(runtime, type);
}
public RubyIO(Ruby runtime, OutputStream outputStream) {
this(runtime, outputStream, true);
}
public RubyIO(Ruby runtime, OutputStream outputStream, boolean autoclose) {
super(runtime, runtime.getIO());
// We only want IO objects with valid streams (better to error now).
if (outputStream == null) {
throw runtime.newRuntimeError("Opening null stream");
}
openFile = MakeOpenFile();
openFile.setFD(new ChannelFD(Channels.newChannel(outputStream), runtime.getPosix(), runtime.getFilenoUtil()));
openFile.setMode(OpenFile.WRITABLE | OpenFile.APPEND);
openFile.setAutoclose(autoclose);
}
public RubyIO(Ruby runtime, InputStream inputStream) {
super(runtime, runtime.getIO());
if (inputStream == null) {
throw runtime.newRuntimeError("Opening null stream");
}
openFile = MakeOpenFile();
openFile.setFD(new ChannelFD(Channels.newChannel(inputStream), runtime.getPosix(), runtime.getFilenoUtil()));
openFile.setMode(OpenFile.READABLE);
}
public RubyIO(Ruby runtime, Channel channel) {
this(runtime, runtime.getIO(), channel);
}
public RubyIO(Ruby runtime, RubyClass klass, Channel channel) {
super(runtime, klass);
// We only want IO objects with valid streams (better to error now).
if (channel == null) {
throw runtime.newRuntimeError("Opening null channel");
}
ThreadContext context = runtime.getCurrentContext();
initializeCommon(context, new ChannelFD(channel, runtime.getPosix(), runtime.getFilenoUtil()), runtime.newFixnum(ModeFlags.oflagsFrom(runtime.getPosix(), channel)), context.nil);
}
public RubyIO(Ruby runtime, ShellLauncher.POpenProcess process, IOOptions ioOptions) {
super(runtime, runtime.getIO());
ioOptions = updateIOOptionsFromOptions(runtime.getCurrentContext(), null, ioOptions);
openFile = MakeOpenFile();
setupPopen(ioOptions.getModeFlags(), process);
}
// MRI: prep_stdio
public static RubyIO prepStdio(Ruby runtime, InputStream f, Channel c, int fmode, RubyClass klass, String path) {
OpenFile fptr;
RubyIO io = prepIO(runtime, c, fmode | OpenFile.PREP | EncodingUtils.DEFAULT_TEXTMODE, klass, path);
fptr = io.getOpenFileChecked();
prepStdioEcflags(fptr, fmode);
fptr.stdio_file = f;
// We checkTTY again here because we're using stdout/stdin to indicate this is stdio
return recheckTTY(runtime, fptr, io);
}
// MRI: prep_stdio
public static RubyIO prepStdio(Ruby runtime, OutputStream f, Channel c, int fmode, RubyClass klass, String path) {
OpenFile fptr;
RubyIO io = prepIO(runtime, c, fmode | OpenFile.PREP | EncodingUtils.DEFAULT_TEXTMODE, klass, path);
fptr = io.getOpenFileChecked();
prepStdioEcflags(fptr, fmode);
fptr.stdio_file = f;
return recheckTTY(runtime, fptr, io);
}
private static RubyIO recheckTTY(Ruby runtime, OpenFile fptr, RubyIO io) {
// We checkTTY again here because we're using stdout/stdin to indicate this is stdio
fptr.checkTTY();
return io;
}
// MRI: part of prep_stdio
private static void prepStdioEcflags(OpenFile fptr, int fmode) {
boolean locked = fptr.lock();
try {
fptr.encs.ecflags |= EncodingUtils.ECONV_DEFAULT_NEWLINE_DECORATOR;
if (EncodingUtils.TEXTMODE_NEWLINE_DECORATOR_ON_WRITE != 0) {
fptr.encs.ecflags |= EncodingUtils.TEXTMODE_NEWLINE_DECORATOR_ON_WRITE;
if ((fmode & OpenFile.READABLE) != 0) {
fptr.encs.ecflags |= EConvFlags.UNIVERSAL_NEWLINE_DECORATOR;
}
}
} finally {
if (locked) fptr.unlock();
}
}
// MRI: prep_io
private static RubyIO prepIO(Ruby runtime, Channel fd, int fmode, RubyClass klass, String path) {
OpenFile fp;
RubyIO io = (RubyIO)klass.allocate();
fp = io.MakeOpenFile();
fp.setChannel(fd);
// Can we determine this?
// if (Platform.IS_CYGWIN) {
// if (!runtime.getPosix().isatty(fd)) {
// fmode |= OpenFile.BINMODE;
// TODO: setmode O_BINARY means what via NIO?
// setmode(fd, OpenFlags.O_BINARY);
// }
// }
fp.setMode(fmode);
fp.checkTTY();
if (path != null) fp.setPath(path);
// rb_update_max_fd(fd);
return io;
}
public static RubyIO newIO(Ruby runtime, Channel channel) {
return new RubyIO(runtime, channel);
}
public OpenFile getOpenFile() {
return openFile;
}
public OpenFile getOpenFileChecked() {
openFile.checkClosed();
return openFile;
}
private static ObjectAllocator IO_ALLOCATOR = new ObjectAllocator() {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyIO(runtime, klass);
}
};
/*
* We use FILE versus IO to match T_FILE in MRI.
*/
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.FILE;
}
public static RubyClass createIOClass(Ruby runtime) {
RubyClass ioClass = runtime.defineClass("IO", runtime.getObject(), IO_ALLOCATOR);
ioClass.setClassIndex(ClassIndex.IO);
ioClass.setReifiedClass(RubyIO.class);
ioClass.kindOf = new RubyModule.JavaClassKindOf(RubyIO.class);
ioClass.includeModule(runtime.getEnumerable());
ioClass.defineAnnotatedMethods(RubyIO.class);
// Constants for seek
ioClass.setConstant("SEEK_SET", runtime.newFixnum(PosixShim.SEEK_SET));
ioClass.setConstant("SEEK_CUR", runtime.newFixnum(PosixShim.SEEK_CUR));
ioClass.setConstant("SEEK_END", runtime.newFixnum(PosixShim.SEEK_END));
ioClass.defineModuleUnder("WaitReadable");
ioClass.defineModuleUnder("WaitWritable");
return ioClass;
}
public OutputStream getOutStream() {
// FIXME: Could be faster by caching bytelist or string rather than creating for every call
return new OutputStream() {
final Ruby runtime = getRuntime();
@Override
public void write(int b) throws IOException {
putc(runtime.getCurrentContext(), runtime.newFixnum(b));
}
@Override
public void write(byte[] b) throws IOException {
RubyIO.this.write(runtime.getCurrentContext(), RubyString.newStringNoCopy(runtime, b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
RubyIO.this.write(runtime.getCurrentContext(), RubyString.newStringNoCopy(runtime, b, off, len));
}
@Override
public void flush() throws IOException {
RubyIO.this.flush(runtime.getCurrentContext());
}
@Override
public void close() throws IOException {
RubyIO.this.close();
}
};
}
public InputStream getInStream() {
// FIXME: Could be faster by caching bytelist or string rather than creating for every call
return new InputStream() {
final Ruby runtime = getRuntime();
@Override
public int read() throws IOException {
return getByte(runtime.getCurrentContext());
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
RubyFixnum c = runtime.newFixnum(len);
RubyString s = RubyString.newStringNoCopy(runtime, b, off, len);
IRubyObject i = RubyIO.this.read(runtime.getCurrentContext(), c, s);
if (i.isNil()) return -1;
return s.size();
}
@Override
public long skip(long n) throws IOException {
return seek(runtime.getCurrentContext(), runtime.newFixnum(PosixShim.SEEK_CUR), runtime.newFixnum(n)).getLongValue();
}
@Override
public int available() throws IOException {
if (RubyIO.this instanceof RubyFile) {
long size = ((RubyFixnum)((RubyFile)RubyIO.this).size(runtime.getCurrentContext())).getLongValue();
if (size == 0) return 0;
if (size >= 0) return (int)(size - pos(runtime.getCurrentContext()).getLongValue());
}
return 0;
}
@Override
public void close() throws IOException {
RubyIO.this.close();
}
};
}
/**
* Get the underlying channel from this IO object. Note that IO buffers data internally, so the channel returned
* here may have been read into those buffers. If the channel and the IO are both being used at the same time, the
* stream will get out of sync.
*
* @return the underlying channel for this IO
*/
public Channel getChannel() {
// FIXME: Do we want to make a faux channel that is backed by IO's buffering? Or turn buffering off?
return openFile.channel();
}
// io_reopen
protected RubyIO reopenIO(ThreadContext context, RubyIO nfile) {
Ruby runtime = context.runtime;
OpenFile fptr, orig;
ChannelFD fd, fd2;
long pos = 0;
nfile = TypeConverter.ioGetIO(runtime, nfile);
fptr = getOpenFileChecked();
orig = nfile.getOpenFileChecked();
if (fptr == orig) return this;
if (fptr.IS_PREP_STDIO()) {
if ((fptr.stdio_file == System.in && !orig.isReadable()) ||
(fptr.stdio_file == System.out && !orig.isWritable()) ||
(fptr.stdio_file == System.err && !orig.isWritable())) {
throw runtime.newArgumentError(fptr.PREP_STDIO_NAME() + " can't change access mode from \"" + fptr.getModeAsString(runtime) + "\" to \"" + orig.getModeAsString(runtime) + "\"");
}
}
// FIXME: three lock acquires...trying to reduce risk of deadlock, but not sure it's possible.
boolean locked = fptr.lock();
try {
if (fptr.isWritable()) {
if (fptr.io_fflush(context) < 0)
throw runtime.newErrnoFromErrno(fptr.errno(), fptr.getPath());
} else {
fptr.tell(context);
}
} finally {
if (locked) fptr.unlock();
}
locked = orig.lock();
try {
if (orig.isReadable()) {
pos = orig.tell(context);
}
if (orig.isWritable()) {
if (orig.io_fflush(context) < 0)
throw runtime.newErrnoFromErrno(orig.errno(), fptr.getPath());
}
} finally {
if (locked) orig.unlock();
}
/* copy rb_io_t structure */
// NOTE: MRI does not copy sync here, but I can find no way to make stdout/stderr stay sync through a reopen
locked = fptr.lock();
boolean locked2 = orig.lock(); // TODO: This WILL deadlock if two threads try to reopen the same IOs in opposite directions. Fix?
try {
fptr.setMode(orig.getMode() | (fptr.getMode() & (OpenFile.PREP | OpenFile.SYNC)));
fptr.setProcess(orig.getProcess());
fptr.setLineNumber(orig.getLineNumber());
if (orig.getPath() != null) fptr.setPath(orig.getPath());
else if (!fptr.IS_PREP_STDIO()) fptr.setPath(null);
fptr.setFinalizer(orig.getFinalizer());
// TODO: unsure what to do here
// #if defined (__CYGWIN__) || !defined(HAVE_FORK)
// if (fptr->finalize == pipe_finalize)
// pipe_add_fptr(fptr);
// #endif
fd = fptr.fd();
fd2 = orig.fd();
if (fd != fd2) {
if (fptr.IS_PREP_STDIO() || fd.bestFileno() <= 2 || fptr.stdio_file == null) {
/* need to keep FILE objects of stdin, stdout and stderr */
checkReopenCloexecDup2(runtime, orig, fd2, fd);
// rb_update_max_fd(fd);
fptr.setFD(fd);
// // MRI does not do this, but we seem to need to set some types of channels to sync if they
// // are reopened as stdout/stderr.
// if (fptr.stdio_file == System.out || fptr.stdio_file == System.err) {
// fd.chFile.force();
// }
} else {
if (fptr.stdio_file != null) try {
fptr.stdio_file.close();
} catch (IOException ioe) {
}
fptr.clearStdio();
fptr.setFD(null);
checkReopenCloexecDup2(runtime, orig, fd2, fd);
// rb_update_max_fd(fd);
fptr.setFD(fd);
}
// TODO: clear interrupts waiting on this IO?
// rb_thread_fd_close(fd);
if (orig.isReadable() && pos >= 0) {
fptr.checkReopenSeek(context, runtime, pos);
orig.checkReopenSeek(context, runtime, pos);
}
}
if (fptr.isBinmode()) {
setBinmode();
}
} finally {
if (locked2) orig.unlock();
if (locked) fptr.unlock();
}
// We simply can't do this and still have real concrete types under RubyIO
// setMetaClass(nfile.getMetaClass());
return this;
}
private void checkReopenCloexecDup2(Ruby runtime, OpenFile orig, ChannelFD oldfd, ChannelFD newfd) {
OpenFile.cloexecDup2(new PosixShim(runtime.getPosix()), oldfd, newfd);
}
// rb_io_binmode
private void setBinmode() {
OpenFile fptr;
fptr = getOpenFileChecked();
boolean locked = fptr.lock();
try {
if (fptr.readconv != null)
fptr.readconv.binmode();
if (fptr.writeconv != null)
fptr.writeconv.binmode();
fptr.setBinmode();
fptr.clearTextMode();
fptr.writeconvPreEcflags &= ~EConvFlags.NEWLINE_DECORATOR_MASK;
if (OpenFlags.O_BINARY.defined()) {
// TODO: Windows
// if (fptr.readconv == null) {
// SET_BINARY_MODE_WITH_SEEK_CUR(fptr);
// }
// else {
// TODO: setmode O_BINARY means what via NIO?
// setmode(fptr->fd, O_BINARY);
// }
}
} finally {
if (locked) fptr.unlock();
}
return;
}
// MRI: rb_io_reopen
@JRubyMethod(name = "reopen", required = 1, optional = 1)
public IRubyObject reopen(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.runtime;
RubyIO file = this;
IRubyObject fname = context.nil, nmode = context.nil, opt = context.nil;
int[] oflags_p = {0};
OpenFile fptr;
switch (args.length) {
case 3:
opt = TypeConverter.checkHashType(runtime, args[2]);
if (opt.isNil()) throw getRuntime().newArgumentError(3, 2);
case 2:
if (opt.isNil()) {
opt = TypeConverter.checkHashType(runtime, args[1]);
if (opt.isNil()) {
nmode = args[1];
opt = context.nil;
}
} else {
nmode = args[1];
}
case 1:
fname = args[0];
}
if (args.length == 1) {
IRubyObject tmp = TypeConverter.ioCheckIO(runtime, fname);
if (!tmp.isNil()) {
return file.reopenIO(context, (RubyIO)tmp);
}
}
fname = RubyFile.get_path(context, fname);
// Not implemented
// fname.checkTaint();
fptr = file.openFile;
if (fptr == null) {
fptr = file.openFile = MakeOpenFile();
}
boolean locked = fptr.lock();
try {
if (!nmode.isNil() || !opt.isNil()) {
ConvConfig convconfig = new ConvConfig();
Object vmode_vperm = vmodeVperm(nmode, null);
int[] fmode_p = {0};
EncodingUtils.extractModeEncoding(context, convconfig, vmode_vperm, opt, oflags_p, fmode_p);
if (fptr.IS_PREP_STDIO() &&
((fptr.getMode() & OpenFile.READWRITE) & (fmode_p[0] & OpenFile.READWRITE)) !=
(fptr.getMode() & OpenFile.READWRITE)) {
throw runtime.newArgumentError(fptr.PREP_STDIO_NAME() + " can't change access mode from \"" + fptr.getModeAsString(runtime) + "\" to \"" + OpenFile.getStringFromMode(fmode_p[0]));
}
fptr.setMode(fmode_p[0]);
fptr.encs = convconfig;
} else {
oflags_p[0] = OpenFile.getModeFlagsAsIntFrom(fptr.getMode());
}
fptr.setPath(fname.toString());
if (fptr.fd() == null) {
fptr.setFD(sysopen(runtime, fptr.getPath(), oflags_p[0], 0666));
fptr.clearStdio();
return file;
}
if (fptr.isWritable()) {
if (fptr.io_fflush(context) < 0)
throw runtime.newErrnoFromErrno(fptr.errno(), fptr.getPath());
}
fptr.rbuf.off = fptr.rbuf.len = 0;
if (fptr.isStdio()) {
// Logic here reopens the stdio FILE* with a new path and mode. For our purposes, we skip this
// since we do not want to damage the stdio streams
// if (freopen(RSTRING_PTR(fptr.pathv), rb_io_oflags_modestr(oflags), fptr.stdio_file) == 0) {
// rb_sys_fail_path(fptr.pathv);
// }
fptr.setFD(sysopen(runtime, fptr.getPath(), oflags_p[0], 0666));
// This logic fixes the original stdio file descriptor by clearing any CLOEXEC that might have
// come across with the newly opened file. Since we do not yet support CLOEXEC, we skip this.
// fptr.fd = fileno(fptr.stdio_file);
// rb_fd_fix_cloexec(fptr.fd);
// This logic configures buffering (none, line, full) and buffer size to match the original stdio
// stream associated with this IO. I don't believe we can do this.
// #ifdef USE_SETVBUF
// if (setvbuf(fptr.stdio_file, NULL, _IOFBF, 0) != 0)
// rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr.pathv);
// #endif
// if (fptr.stdio_file == stderr) {
// if (setvbuf(fptr.stdio_file, NULL, _IONBF, BUFSIZ) != 0)
// rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr.pathv);
// }
// else if (fptr.stdio_file == stdout && isatty(fptr.fd)) {
// if (setvbuf(fptr.stdio_file, NULL, _IOLBF, BUFSIZ) != 0)
// rb_warn("setvbuf() can't be honoured for %"PRIsVALUE, fptr.pathv);
// }
} else {
ChannelFD tmpfd = sysopen(runtime, fptr.getPath(), oflags_p[0], 0666);
Errno err = null;
if (fptr.cloexecDup2(fptr.posix, tmpfd, fptr.fd()) < 0)
err = fptr.errno();
if (err != null) {
throw runtime.newErrnoFromErrno(err, fptr.getPath());
}
fptr.setFD(tmpfd);
}
} finally {
if (locked) fptr.unlock();
}
return file;
}
public IRubyObject getline(ThreadContext context, IRubyObject separator) {
return getline(context, separator, -1, null);
}
/**
* getline using logic of gets. If limit is -1 then read unlimited amount.
*
*/
public IRubyObject getline(ThreadContext context, IRubyObject separator, long limit) {
return getline(context, separator, limit, null);
}
private IRubyObject getline(ThreadContext context, IRubyObject separator, long limit, ByteListCache cache) {
return getlineInner(context, separator, (int)limit, cache);
}
/**
* getline using logic of gets. If limit is -1 then read unlimited amount.
* mri: rb_io_getline_1 (mostly)
*/
private IRubyObject getlineInner(ThreadContext context, IRubyObject rs, int _limit, ByteListCache cache) {
Ruby runtime = context.runtime;
IRubyObject str = context.nil;
boolean noLimit = false;
Encoding enc;
OpenFile fptr = getOpenFileChecked();
boolean locked = fptr.lock();
try {
fptr.checkCharReadable(context);
if (rs.isNil() && _limit < 0) {
str = fptr.readAll(context, 0, context.nil);
if (((RubyString) str).size() == 0) return context.nil;
} else if (_limit == 0) {
return RubyString.newEmptyString(runtime, fptr.readEncoding(runtime));
} else if (
rs == runtime.getGlobalVariables().getDefaultSeparator()
&& _limit < 0
&& !fptr.needsReadConversion()
&& (enc = fptr.readEncoding(runtime)).isAsciiCompatible()) {
fptr.NEED_NEWLINE_DECORATOR_ON_READ_CHECK();
return fptr.getlineFast(context, enc, this);
}
// slow path logic
int c, newline = -1;
byte[] rsptrBytes = null;
int rsptr = 0;
int rslen = 0;
boolean rspara = false;
int extraLimit = 16;
fptr.SET_BINARY_MODE();
enc = getReadEncoding();
if (!rs.isNil()) {
RubyString rsStr = (RubyString) rs;
ByteList rsByteList = rsStr.getByteList();
rslen = rsByteList.getRealSize();
if (rslen == 0) {
rsptrBytes = PARAGRAPH_SEPARATOR.unsafeBytes();
rsptr = PARAGRAPH_SEPARATOR.getBegin();
rslen = 2;
rspara = true;
fptr.swallow(context, '\n');
rs = null;
if (!enc.isAsciiCompatible()) {
rs = RubyString.newUsAsciiStringShared(runtime, rsptrBytes, rsptr, rslen);
rs = EncodingUtils.rbStrEncode(context, rs, runtime.getEncodingService().convertEncodingToRubyEncoding(enc), 0, context.nil);
rs.setFrozen(true);
rsStr = (RubyString) rs;
rsByteList = rsStr.getByteList();
rsptrBytes = rsByteList.getUnsafeBytes();
rsptr = rsByteList.getBegin();
rslen = rsByteList.getRealSize();
}
} else {
rsptrBytes = rsByteList.unsafeBytes();
rsptr = rsByteList.getBegin();
}
newline = rsptrBytes[rsptr + rslen - 1] & 0xFF;
}
ByteList buf = cache != null ? cache.allocate(0) : new ByteList(0);
try {
boolean bufferString = str instanceof RubyString;
ByteList[] strPtr = {bufferString ? ((RubyString) str).getByteList() : null};
int[] limit_p = {_limit};
while ((c = fptr.appendline(context, newline, strPtr, limit_p)) != OpenFile.EOF) {
int s, p, pp, e;
if (c == newline) {
if (strPtr[0].getRealSize() < rslen) continue;
s = strPtr[0].getBegin();
e = s + strPtr[0].getRealSize();
p = e - rslen;
pp = enc.leftAdjustCharHead(strPtr[0].getUnsafeBytes(), s, p, e);
if (pp != p) continue;
if (ByteList.memcmp(strPtr[0].getUnsafeBytes(), p, rsptrBytes, rsptr, rslen) == 0) break;
}
if (limit_p[0] == 0) {
s = strPtr[0].getBegin();
p = s + strPtr[0].getRealSize();
pp = enc.leftAdjustCharHead(strPtr[0].getUnsafeBytes(), s, p - 1, p);
if (extraLimit != 0 &&
StringSupport.MBCLEN_NEEDMORE_P(StringSupport.preciseLength(enc, strPtr[0].getUnsafeBytes(), pp, p))) {
limit_p[0] = 1;
extraLimit--;
} else {
noLimit = true;
break;
}
}
}
_limit = limit_p[0];
if (strPtr[0] != null) {
if (bufferString) {
if (strPtr[0] != ((RubyString) str).getByteList()) {
((RubyString) str).setValue(strPtr[0]);
} else {
// same BL as before
}
} else {
// create string
str = runtime.newString(strPtr[0]);
}
}
if (rspara && c != OpenFile.EOF) {
// FIXME: This may block more often than it should, to clean up extraneous newlines
fptr.swallow(context, '\n');
}
if (!str.isNil()) {
str = EncodingUtils.ioEncStr(runtime, str, fptr);
}
} finally {
if (cache != null) cache.release(buf);
}
if (!str.isNil() && !noLimit) {
fptr.incrementLineno(runtime);
}
} finally {
if (locked) fptr.unlock();
}
return str;
}
// fptr->enc and codeconv->enc
public Encoding getEnc() {
return openFile.encs.enc;
}
// mri: io_read_encoding
public Encoding getReadEncoding() {
return openFile.readEncoding(getRuntime());
}
// fptr->enc2 and codeconv->enc2
public Encoding getEnc2() {
return openFile.encs.enc2;
}
// mri: io_input_encoding
public Encoding getInputEncoding() {
return openFile.inputEncoding(getRuntime());
}
private static final String VENDOR;
static { String v = SafePropertyAccessor.getProperty("java.VENDOR") ; VENDOR = (v == null) ? "" : v; };
private static final String msgEINTR = "Interrupted system call";
// FIXME: We needed to use this to raise an appropriate error somewhere...find where...I think IRB related when suspending process?
public static boolean restartSystemCall(Exception e) {
return VENDOR.startsWith("Apple") && e.getMessage().equals(msgEINTR);
}
// IO class methods.
@JRubyMethod(name = "new", rest = true, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass)recv;
if (block.isGiven()) {
String className = klass.getName();
context.runtime.getWarnings().warn(
ID.BLOCK_NOT_ACCEPTED,
className + "::new() does not take block; use " + className + "::open() instead");
}
return klass.newInstance(context, args, block);
}
@JRubyMethod(rest = true, meta = true)
public static IRubyObject for_fd(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass)recv;
return klass.newInstance(context, args, block);
}
private IRubyObject initializeCommon(ThreadContext context, int fileno, IRubyObject vmodeArg, IRubyObject opt) {
Ruby runtime = context.runtime;
ChannelFD fd;
if (!FilenoUtil.isFake(fileno)) {
// try using existing ChannelFD, then fall back on creating a new one
fd = runtime.getFilenoUtil().getWrapperFromFileno(fileno);
if (fd == null) {
fd = new ChannelFD(new NativeDeviceChannel(fileno), runtime.getPosix(), runtime.getFilenoUtil());
}
} else {
ChannelFD descriptor = runtime.getFilenoUtil().getWrapperFromFileno(fileno);
if (descriptor == null) throw runtime.newErrnoEBADFError();
fd = descriptor;
}
if (!fd.ch.isOpen()) {
throw runtime.newErrnoEBADFError();
}
return initializeCommon(context, fd, vmodeArg, opt);
}
private IRubyObject initializeCommon(ThreadContext context, ChannelFD fd, IRubyObject vmodeArg, IRubyObject opt) {
Ruby runtime = context.runtime;
int ofmode;
int[] oflags_p = {ModeFlags.RDONLY};
if(opt != null && !opt.isNil() && !(opt instanceof RubyHash) && !(opt.respondsTo("to_hash"))) {
throw runtime.newArgumentError("last argument must be a hash!");
}
if (opt != null && !opt.isNil()) {
opt = opt.convertToHash();
}
if (!fd.ch.isOpen()) {
throw runtime.newErrnoEBADFError();
}
Object pm = EncodingUtils.vmodeVperm(vmodeArg, runtime.newFixnum(0));
int[] fmode_p = {0};
ConvConfig convconfig = new ConvConfig();
EncodingUtils.extractModeEncoding(context, convconfig, pm, opt, oflags_p, fmode_p);
{ // normally done with fcntl...which we *could* do too...but this is just checking read/write
oflags_p[0] = ModeFlags.oflagsFrom(runtime.getPosix(), fd.ch);
ofmode = ModeFlags.getOpenFileFlagsFor(oflags_p[0]);
if (EncodingUtils.vmode(pm) == null || EncodingUtils.vmode(pm).isNil()) {
fmode_p[0] = ofmode;
} else if (((~ofmode & fmode_p[0]) & OpenFile.READWRITE) != 0) {
throw runtime.newErrnoEINVALError();
}
}
if (opt != null && !opt.isNil() && ((RubyHash)opt).op_aref(context, runtime.newSymbol("autoclose")) == runtime.getFalse()) {
fmode_p[0] |= OpenFile.PREP;
}
// JRUBY-4650: Make sure we clean up the old data, if it's present.
MakeOpenFile();
openFile.setFD(fd);
openFile.setMode(fmode_p[0]);
openFile.encs = convconfig;
openFile.clearCodeConversion();
openFile.checkTTY();
switch (fd.bestFileno()) {
case 0:
openFile.stdio_file = System.in;
break;
case 1:
openFile.stdio_file = System.out;
break;
case 2:
openFile.stdio_file = System.err;
break;
}
if (openFile.isBOM()) {
EncodingUtils.ioSetEncodingByBOM(context, this);
}
return this;
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject fileNumber, Block unused) {
return initializeCommon(context, RubyNumeric.fix2int(fileNumber), null, context.nil);
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject fileNumber, IRubyObject second, Block unused) {
int fileno = RubyNumeric.fix2int(fileNumber);
IRubyObject vmode = null;
IRubyObject options;
IRubyObject hashTest = TypeConverter.checkHashType(context.runtime, second);
if (hashTest instanceof RubyHash) {
options = hashTest;
} else {
options = context.nil;
vmode = second;
}
return initializeCommon(context, fileno, vmode, options);
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject fileNumber, IRubyObject modeValue, IRubyObject options, Block unused) {
int fileno = RubyNumeric.fix2int(fileNumber);
return initializeCommon(context, fileno, modeValue, options);
}
// Encoding processing
protected IOOptions parseIOOptions(IRubyObject arg) {
Ruby runtime = getRuntime();
if (arg instanceof RubyFixnum) return newIOOptions(runtime, (int) RubyFixnum.fix2long(arg));
String modeString = arg.convertToString().toString();
try {
return new IOOptions(runtime, modeString);
} catch (InvalidValueException ive) {
throw runtime.newArgumentError("invalid access mode " + modeString);
}
}
@JRubyMethod
public IRubyObject external_encoding(ThreadContext context) {
EncodingService encodingService = context.runtime.getEncodingService();
if (openFile.encs.enc2 != null) return encodingService.getEncoding(openFile.encs.enc2);
if (openFile.isWritable()) {
return openFile.encs.enc == null ? context.runtime.getNil() : encodingService.getEncoding(openFile.encs.enc);
}