forked from rubinius/rubinius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.rb
3591 lines (2966 loc) · 88.6 KB
/
io.rb
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
class IO
include Enumerable
def self.fnmatch(pattern, path, flags)
Rubinius.primitive :io_fnmatch
raise PrimitiveFailure, "IO#fnmatch primitive failed"
end
def socket_recv(bytes, flags, type)
Rubinius.primitive :io_socket_read
raise PrimitiveFailure, "io_socket_read failed"
end
module TransferIO
def send_io(io)
Rubinius.primitive :io_send_io
raise PrimitiveFailure, "IO#send_io failed"
end
def recv_fd
Rubinius.primitive :io_recv_fd
raise PrimitiveFailure, "IO#recv_fd failed"
end
end
module WaitReadable; end
module WaitWritable; end
class EAGAINWaitReadable < Errno::EAGAIN
include ::IO::WaitReadable
end
class EAGAINWaitWritable < Errno::EAGAIN
include ::IO::WaitWritable
end
class EWOULDBLOCKWaitReadable < Errno::EAGAIN
include WaitReadable
end
class EWOULDBLOCKWaitWritable < Errno::EAGAIN
include WaitWritable
end
class EINPROGRESSWaitReadable < Errno::EINPROGRESS
include WaitReadable
end
class EINPROGRESSWaitWritable < Errno::EINPROGRESS
include WaitWritable
end
class FileDescriptor
class RIOStream
def self.close(io, allow_exception)
Rubinius.primitive :rio_close
raise PrimitiveFailure, "IO::FileDescriptor::RIOStream.close primitive failed"
end
end
attr_reader :offset
def self.choose_type(fd, io)
stat = File::Stat.fstat(fd)
case stat.ftype
when "file"
BufferedFileDescriptor.new(fd, stat, io)
when "fifo", "characterSpecial"
FIFOFileDescriptor.new(fd, stat, io)
when "socket"
SocketFileDescriptor.new(fd, stat, io)
when "directory"
DirectoryFileDescriptor.new(fd, stat, io)
when "blockSpecial"
raise "cannot make block special"
when "link"
raise "cannot make link"
else
new(fd, stat, io)
end
end
def self.open_with_mode(path, mode, perm)
fd = open_with_cloexec(path, mode, perm)
if fd < 0
Errno.handle("failed to open file")
end
return fd
end
def self.open_with_cloexec(path, mode, perm)
if O_CLOEXEC
fd = FFI::Platform::POSIX.open(path, mode | O_CLOEXEC, perm)
update_max_fd(fd)
else
fd = FFI::Platform::POSIX.open(path, mode, perm)
new_open_fd(fd)
end
return fd
end
def self.new_open_fd(new_fd)
if new_fd > 2
flags = FFI::Platform::POSIX.fcntl(new_fd, F_GETFD, 0)
Errno.handle("fcntl(2) failed") if FFI.call_failed?(flags)
flags = FFI::Platform::POSIX.fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC)
Errno.handle("fcntl(2) failed") if FFI.call_failed?(flags)
end
update_max_fd(new_fd)
end
def self.pagesize
@pagesize ||= FFI::Platform::POSIX.getpagesize
end
def self.truncate(name, offset)
raise RangeError, "bignum too big to convert into `long'" if offset.kind_of?(Bignum)
status = FFI::Platform::POSIX.truncate(name, offset)
Errno.handle("truncate(2) failed") if FFI.call_failed?(status)
return status
end
def self.update_max_fd(new_fd)
@@max_descriptors.get_and_set(new_fd)
end
def self.max_fd
@@max_descriptors.get
end
def self.get_flags(fd)
if IO::F_GETFL
if FFI.call_failed?(flags = FFI::Platform::POSIX.fcntl(fd, IO::F_GETFL, 0))
Errno.handle("fcntl(2) failed")
end
else
flags = 0
end
flags
end
def self.clear_flag(flag, fd)
flags = get_flags(fd)
if (flags & flag) == 0
flags &= ~flag
if FFI.call_failed?(flags = FFI::Platform::POSIX.fcntl(fd, IO::F_SETFL, flags))
Errno.handle("fcntl(2) failed")
end
end
end
def self.set_flag(flag, fd)
flags = get_flags(fd)
if (flags & flag) == 0
flags |= flag
if FFI.call_failed?(flags = FFI::Platform::POSIX.fcntl(fd, IO::F_SETFL, flags))
Errno.handle("fcntl(2) failed")
end
end
end
def initialize(fd, stat, io)
@descriptor, @stat, @io = fd, stat, io
acc_mode = FileDescriptor.get_flags(@descriptor)
if acc_mode < 0
# Assume it's closed.
if Errno.eql?(Errno::EBADF::Errno)
@descriptor = -1
end
@mode = nil
else
@mode = acc_mode
end
@sync = true
@autoclose = false
reset_positioning(@stat)
# Don't bother to add finalization for stdio
if @descriptor >= 3
# Sometimes a FileDescriptor class is replaced (see IO#reopen) so we need to be
# careful we don't finalize that descriptor. Probably need a way to cancel
# the finalization when we are transferring an FD from one instance to another.
ObjectSpace.define_finalizer(self)
end
end
def autoclose=(bool)
@autoclose = bool
end
def descriptor
@descriptor
end
def descriptor=(value)
@descriptor = value
end
def mode
@mode
end
def mode=(value)
@mode = value
end
def sync
@sync
end
def sync=(value)
@sync = value
end
CLONG_OVERFLOW = 1 << 64
def lseek(offset, whence=SEEK_SET)
ensure_open
# FIXME: check +amount+ to make sure it isn't too large
raise RangeError if offset > CLONG_OVERFLOW
position = FFI::Platform::POSIX.lseek(descriptor, offset, whence)
Errno.handle("seek failed") if FFI.call_failed?(position)
@offset = position
determine_eof
return position
end
def read(length, output_string=nil)
length ||= FileDescriptor.pagesize
while true
ensure_open
storage = FFI::MemoryPointer.new(length)
raise IOError, "read(2) failed to malloc a buffer for read length #{length}" if storage.null?
bytes_read = read_into_storage(length, storage)
if bytes_read == 0
@eof = true if length > 0
return nil
else
break
end
end
if output_string
output_string.replace(storage.read_string(bytes_read))
else
output_string = storage.read_string(bytes_read).force_encoding(Encoding::ASCII_8BIT)
end
@offset += bytes_read
determine_eof
return output_string
end
def read_into_storage(count, storage)
while true
Thread.current.instance_variable_set(:@sleep, true)
bytes_read = FFI::Platform::POSIX.read(descriptor, storage, count)
Thread.current.instance_variable_set(:@sleep, false)
if FFI.call_failed?(bytes_read)
errno = Errno.errno
if errno == Errno::EAGAIN::Errno || errno == Errno::EINTR::Errno
ensure_open
next
else
Errno.handle "read(2) failed"
end
else
break
end
end
# before returning verify file hasn't been closed in another thread
ensure_open
return bytes_read
end
private :read_into_storage
def write(str)
buf_size = str.bytesize
left = buf_size
buffer = FFI::MemoryPointer.new(left)
buffer.write_string(str)
error = false
while left > 0
bytes_written = FFI::Platform::POSIX.write(@descriptor, buffer, left)
if FFI.call_failed?(bytes_written)
errno = Errno.errno
if errno == Errno::EINTR::Errno || errno == Errno::EAGAIN::Errno
# do a #select and wait for descriptor to become writable
if blocking?
Select.wait_for_writable(@descriptor)
next
else
break
end
end
error = true
break
end
break if error
left -= bytes_written
buffer += bytes_written
@offset += bytes_written
if @offset > @total_size
@total_size = @offset
@eof = false # only a failed read can set EOF!
end
end
Errno.handle("write failed") if error
return(buf_size - left)
end
def close
ensure_open
fd = @descriptor
if fd != -1
# return early if this handle was promoted to a stream by a C-ext
return if RIOStream.close(@io, true)
ret_code = FFI::Platform::POSIX.close(fd)
if FFI.call_failed?(ret_code)
Errno.handle("close failed")
elsif ret_code == 0
# no op
else
raise IOError, "::close(): Unknown error on fd #{fd}"
end
end
@descriptor = -1
return nil
end
def determine_eof
if @offset >= @total_size
@eof = true
@total_size += (@total_size - @offset)
@total_size = @offset if @offset > @total_size
else
@eof = false
end
end
private :determine_eof
def eof?
@eof
end
# This is NOT the same as close().
def shutdown(how)
ensure_open
fd = descriptor
if how != IO::SHUT_RD && how != IO::SHUT_WR && how != IO::SHUT_RDWR
raise ArgumentError, "::shutdown(): Invalid `how` #{how} for fd #{fd}"
end
ret_code = FFI::Platform::POSIX.shutdown(fd, how)
if FFI.call_failed?(ret_code)
Errno.handle("shutdown(2) failed")
elsif ret_code == 0
if how == IO::SHUT_RDWR
close
self.descriptor = -2
end
else
Errno.handle("::shutdown(): Unknown error on fd #{fd}")
end
return how
end
def ensure_open(fd=nil)
fd ||= descriptor
if fd.nil?
raise IOError, "uninitialized stream"
elsif fd == -1
raise IOError, "closed stream"
elsif fd == -2
raise IOError, "shutdown stream"
end
return nil
end
def force_read_only
@mode = (@mode & ~IO::O_ACCMODE ) | O_RDONLY
end
def force_write_only
@mode = (@mode & ~IO::O_ACCMODE) | O_WRONLY
end
def read_only?
(@mode & O_ACCMODE) == O_RDONLY
end
def write_only?
(@mode & O_ACCMODE) == O_WRONLY
end
def read_write?
(@mode & O_ACCMODE) == O_RDWR
end
def reopen(other_fd)
current_fd = @descriptor
if FFI.call_failed?(FFI::Platform::POSIX.dup2(other_fd, current_fd))
Errno.handle("reopen")
end
set_mode
reset_positioning
return true
end
def reopen_path(path, mode)
current_fd = @descriptor
other_fd = FileDescriptor.open_with_cloexec(path, mode, 0666)
Errno.handle("could not reopen path \"#{path}\"") if other_fd < 0
if FFI.call_failed?(FFI::Platform::POSIX.dup2(other_fd, current_fd))
if Errno.eql?(Errno::EBADF::Errno)
# means current_fd is closed, so set ourselves to use the new fd and continue
@descriptor = other_fd
else
FFI::Platform::POSIX.close(other_fd) if other_fd > 0
Errno.handle("could not reopen path \"#{path}\"")
end
else
FFI::Platform::POSIX.close(other_fd)
end
set_mode
reset_positioning
return true
end
def reset_positioning(stat=nil)
# Discover final size of file so we can set EOF properly
stat = File::Stat.fstat(@descriptor) unless stat
@total_size = stat.size
# We may have reopened a file descriptor that went from "file" to a different
# ftype which doesn't allow seeking, so catch it here.
if stat.ftype == "file"
seek_positioning
else
@offset = 0
end
determine_eof
end
def seek_positioning
@offset = lseek(0, SEEK_CUR) # find current position if we are reopening!
end
private :seek_positioning
def set_mode
@mode = FileDescriptor.get_flags(@descriptor)
end
def blocking?
(FileDescriptor.get_flags(@descriptor) & O_NONBLOCK) == 0
end
def clear_nonblock
flags = FileDescriptor.get_flags(@descriptor)
FileDescriptor.clear_flag(O_NONBLOCK, @descriptor)
end
def set_nonblock
flags = FileDescriptor.get_flags(@descriptor)
FileDescriptor.set_flag(O_NONBLOCK, @descriptor)
end
def ftruncate(offset)
ensure_open
# FIXME: fail if +offset+ is too large, see C++ code
status = FFI::Platform::POSIX.ftruncate(descriptor, offset)
Errno.handle("ftruncate(2) failed") if FFI.call_failed?(status)
return status
end
##
# Returns true if ios is associated with a terminal device (tty), false otherwise.
#
# File.new("testfile").isatty #=> false
# File.new("/dev/tty").isatty #=> true
def tty?
ensure_open
FFI::Platform::POSIX.isatty(@descriptor) == 1
end
def ttyname
# Need to protect this call with a lock since the OS copies this string information
# to an internal static object and returns a pointer to that object. Future calls
# to #ttyname modify that same object. Therefore, we need to protect this from
# race conditions.
Rubinius.lock(self)
name = FFI::Platform::POSIX.ttyname(descriptor)
if name
name
else
Errno.handle("ttyname(3) failed")
nil
end
ensure
Rubinius.unlock(self)
end
def inspect
stat = File::Stat.fstat(@descriptor)
"fd [#{descriptor}], mode [#{@mode}], total_size [#{@total_size}], offset [#{@offset}], eof [#{@eof}], stat.size [#{stat.size}], written? [#{@written}]"
end
def cancel_finalizer
ObjectSpace.undefine_finalizer(self)
end
def __finalize__
return if @descriptor.nil? || @descriptor == -1
fd = @descriptor
# Should flush a write buffer here if one exists. Current
# implementation does not buffer writes internally, so this
# is a no-op.
# Do not close stdin/out/err (0, 1, and 2)
if @descriptor > 3
@descriptor = -1
# Take care of any IO cleanup for the C API here. An IO may
# have been promoted to a low-level RIO struct using #fdopen,
# so we MUST use #fclose to clost it.
return if RIOStream.close(@io, false)
# Ignore any return code... don't care if it fails
FFI::Platform::POSIX.close(fd) if @autoclose
end
end
end # class FileDescriptor
class BufferedFileDescriptor < FileDescriptor
def buffer_reset
@unget_buffer.clear
end
private :buffer_reset
def read(length, output_string=nil)
length ||= FileDescriptor.pagesize
# Preferentially read from the buffer and then from the underlying
# FileDescriptor.
# FIXME: make this logic clearer.
if length > @unget_buffer.size
@offset += @unget_buffer.size
length -= @unget_buffer.size
str = @unget_buffer.inject("".force_encoding(Encoding::ASCII_8BIT)) { |sum, val| val.chr + sum }
str2 = super(length, output_string)
if str.size == 0 && str2.nil?
determine_eof
return nil
elsif str2
str += str2
end
buffer_reset
elsif length == @unget_buffer.size
@offset += length
length -= @unget_buffer.size
str = @unget_buffer.inject("".force_encoding(Encoding::ASCII_8BIT)) { |sum, val| val.chr + sum }
buffer_reset
else
@offset += @unget_buffer.size
str = "".force_encoding(Encoding::ASCII_8BIT)
length.times do
str << @unget_buffer.pop
end
end
if output_string
output_string.replace(str)
else
output_string = str.force_encoding(Encoding::ASCII_8BIT)
end
determine_eof
return output_string
end
def read_only_buffer(length)
unless @unget_buffer.empty?
if length >= @unget_buffer.size
@offset += @unget_buffer.size
length -= @unget_buffer.size
str = @unget_buffer.inject("".force_encoding(Encoding::ASCII_8BIT)) { |sum, val| val.chr + sum }
buffer_reset
[str, length]
else
@offset += @unget_buffer.size
str = "".force_encoding(Encoding::ASCII_8BIT)
length.times do
str << @unget_buffer.pop
end
[str, 0]
end
else
[nil, length]
end
end
def seek(bytes, whence)
# @offset may not match actual file pointer if there were calls to #unget.
if whence == SEEK_CUR
# adjust the number of bytes to seek based on how far ahead we are with the buffer
bytes -= @unget_buffer.size
end
buffer_reset
lseek(bytes, whence)
end
def sysread(byte_count)
raise_if_buffering
read(byte_count)
end
def sysseek(bytes, whence)
raise_if_buffering
lseek(bytes, whence)
end
def eof?
super && @unget_buffer.empty?
end
def flush
#@unget_buffer.clear
end
def raise_if_buffering
raise IOError unless @unget_buffer.empty?
end
def reset_positioning(*args)
@unget_buffer = []
super
end
def write_nonblock(str)
buffer_reset
set_nonblock
buf_size = str.bytesize
left = buf_size
if left > 0
buffer = FFI::MemoryPointer.new(left)
buffer.write_string(str)
if FFI.call_failed?(bytes_written = FFI::Platform::POSIX.write(@descriptor, buffer, left))
clear_nonblock
Errno.raise_waitwritable("write_nonblock")
end
left -= bytes_written
buffer += bytes_written
@offset += bytes_written
end
return(buf_size - left)
end
def unget(byte)
@offset -= 1
@unget_buffer << byte
end
end # class BufferedFileDescriptor
class FIFOFileDescriptor < BufferedFileDescriptor
def self.connect_pipe_fds
fds = FFI::MemoryPointer.new(:int, 2)
Errno.handle("creating pipe failed") if FFI.call_failed?(FFI::Platform::POSIX.pipe(fds))
fd0, fd1 = fds.read_array_of_int(2)
FileDescriptor.new_open_fd(fd0)
FileDescriptor.new_open_fd(fd1)
return [fd0, fd1]
end
def initialize(fd, stat, io, mode=nil)
super(fd, stat, self)
@mode = mode if mode
@eof = false # force to false
end
def determine_eof
if @offset >= @total_size
@eof = true
# No seeking allowed on a pipe, so its size is always its offset
@total_size = @offset
end
end
def eof?
# The only way to confirm we are EOF with a pipe is to try to read from
# it. If we fail, then we are EOF. If we succeed, then unget the byte
# so that EOF is false (i.e. more to read).
str = read(1)
unget(str) if str
super
end
def seek_positioning
# no seeking allowed for pipes
@offset = 0
end
def sysseek(offset, whence=SEEK_SET)
# lseek does not work with pipes.
raise Errno::ESPIPE
end
end # class FIFOFileDescriptor
class DirectoryFileDescriptor < BufferedFileDescriptor
end # class DirectoryFileDescriptor
class SocketFileDescriptor < FIFOFileDescriptor
def initialize(fd, stat, io)
super
@mode &= O_ACCMODE
@sync = true
end
def force_read_write
@mode &= ~(O_RDONLY | O_WRONLY)
@mode |= O_RDWR
end
end # class SocketFileDescriptor
# Encapsulates all of the logic necessary for handling #select.
class Select
#eval(Rubinius::Config['rbx.platform.timeval.class'])
class FDSet
def self.new
Rubinius.primitive :fdset_allocate
raise PrimitiveFailure, "FDSet.allocate failed"
end
def zero
Rubinius.primitive :fdset_zero
raise PrimitiveFailure, "FDSet.zero failed"
end
def set(descriptor)
Rubinius.primitive :fdset_set
raise PrimitiveFailure, "FDSet.set failed"
end
def set?(descriptor)
Rubinius.primitive :fdset_is_set
raise PrimitiveFailure, "FDSet.set? failed"
end
def to_set
Rubinius.primitive :fdset_to_set
raise PrimitiveFailure, "FDSet.to_set failed"
end
end
def self.fd_set_from_array(array)
highest = -1
fd_set = FDSet.new
fd_set.zero
array.each do |io|
io = io[1] if io.is_a?(Array)
descriptor = io.descriptor
if descriptor >= FD_SETSIZE
raise IOError
end
if descriptor >= 0
highest = descriptor > highest ? descriptor : highest
fd_set.set(descriptor)
end
end
return [fd_set, highest]
end
def self.collect_set_fds(array, fd_set)
return [] unless fd_set
array.map do |io|
key, io = if io.is_a?(Array)
[io[0], io[1]]
else
[io, io]
end
if fd_set.set?(io.descriptor) || io.descriptor < 0
key
else
nil
end
end.compact
end
def self.timer_add(time1, time2, result)
result[:tv_sec] = time1[:tv_sec] + time2[:tv_sec]
result[:tv_usec] = time1[:tv_usec] + time2[:tv_usec]
if result[:tv_usec] >= 1_000_000
result[:tv_sec] += 1
result[:tv_usec] -= 1_000_000
end
end
def self.timer_sub(time1, time2, result)
result[:tv_sec] = time1[:tv_sec] - time2[:tv_sec]
result[:tv_usec] = time1[:tv_usec] - time2[:tv_usec]
if result[:tv_usec] < 0
result[:tv_sec] -= 1
result[:tv_usec] += 1_000_000
end
end
def self.make_timeval_timeout(timeout)
if timeout
limit = Timeval_t.new
future = Timeval_t.new
limit[:tv_sec] = (timeout / 1_000_000.0).to_i
limit[:tv_usec] = (timeout % 1_000_000.0).to_i
# Get current time to be used if select is interrupted and we have to recalculate the sleep time
if FFI.call_failed?(FFI::Platform::POSIX.gettimeofday(future, nil))
Errno.handle("gettimeofday(2) failed")
end
timer_add(future, limit, future)
end
[limit, future]
end
def self.reset_timeval_timeout(time_limit, future)
now = Timeval_t.new
if FFI.call_failed?(FFI::Platform::POSIX.gettimeofday(now, nil))
Errno.handle("gettimeofday(2) failed")
end
timer_sub(future, now, time_limit)
end
def self.readable_events(read_fd)
fd_set = FDSet.new
fd_set.zero
fd_set.set(read_fd)
unless const_defined?(:Timeval_t)
# This is a complete hack.
Select.class_eval(Rubinius::Config['rbx.platform.timeval.class'])
end
timer = Timeval_t.new # sets fields to zero by default
FFI::Platform::POSIX.select(read_fd + 1, fd_set.to_set, nil, nil, timer)
end
def self.wait_for_writable(fd)
fd_set = FDSet.new
fd_set.zero
fd_set.set(fd)
FFI::Platform::POSIX.select(fd + 1, nil, fd_set.to_set, nil, nil)
end
def self.select(readables, writables, errorables, timeout)
read_set, highest_read_fd = readables.nil? ? [nil, nil] : fd_set_from_array(readables)
write_set, highest_write_fd = writables.nil? ? [nil, nil] : fd_set_from_array(writables)
error_set, highest_err_fd = errorables.nil? ? [nil, nil] : fd_set_from_array(errorables)
max_fd = [highest_read_fd, highest_write_fd, highest_err_fd].compact.max || -1
unless const_defined?(:Timeval_t)
# This is a complete hack.
Select.class_eval(Rubinius::Config['rbx.platform.timeval.class'])
end
time_limit, future = make_timeval_timeout(timeout)
events = 0
loop do
Thread.current.instance_variable_set(:@sleep, true)
events = FFI::Platform::POSIX.select(max_fd + 1,
(read_set ? read_set.to_set : nil),
(write_set ? write_set.to_set : nil),
(error_set ? error_set.to_set : nil),
time_limit)
Thread.current.instance_variable_set(:@sleep, false)
if FFI.call_failed?(events)
if Errno::EAGAIN::Errno == Errno.errno || Errno::EINTR::Errno == Errno.errno
# return nil if async_interruption?
time_limit = reset_timeval_timeout(time_limit, future)
continue
end
Errno.handle("select(2) failed")
end
break
end
return nil if events.zero?
output_fds = []
output_fds << collect_set_fds(readables, read_set)
output_fds << collect_set_fds(writables, write_set)
output_fds << collect_set_fds(errorables, error_set)
return output_fds
end
def self.validate_and_convert_argument(objects)
if objects
raise TypeError, "Argument must be an Array" unless objects.respond_to?(:to_ary)
objects =
objects.to_ary.map do |obj|
if obj.kind_of? IO
raise IOError, "closed stream" if obj.closed?
obj
else
raise TypeError unless obj.respond_to?(:to_io)
io = obj.to_io
raise TypeError unless io
raise IOError, "closed stream" if io.closed?
[obj, io]
end
end